-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproject-resources.js
1147 lines (1067 loc) · 45.2 KB
/
project-resources.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { tiny } from "./tiny-graphics.js";
// Pull these names into this module's scope for convenience:
const {
Vec,
Mat,
Mat4,
Color,
Light,
Shape,
Material,
Shader,
Texture,
Scene
} = tiny;
import { widgets } from "./tiny-graphics-widgets.js";
Object.assign(tiny, widgets);
const defs = {};
export { tiny, defs };
const Triangle = (defs.Triangle = class Triangle extends Shape {
// **Triangle** The simplest possible 2D Shape – one triangle. It stores 3 vertices, each
// having their own 3D position, normal vector, and texture-space coordinate.
constructor() {
// Name the values we'll define per each vertex:
super("position", "normal", "texture_coord");
// First, specify the vertex positions -- the three point locations of an imaginary triangle:
this.arrays.position = [Vec.of(0, 0, 0), Vec.of(1, 0, 0), Vec.of(0, 1, 0)];
// Next, supply vectors that point away from the triangle face. They should match up with
// the points in the above list. Normal vectors are needed so the graphics engine can
// know if the shape is pointed at light or not, and color it accordingly.
this.arrays.normal = [Vec.of(0, 0, 1), Vec.of(0, 0, 1), Vec.of(0, 0, 1)];
// lastly, put each point somewhere in texture space too:
this.arrays.texture_coord = [Vec.of(0, 0), Vec.of(1, 0), Vec.of(0, 1)];
// Index into our vertices to connect them into a whole triangle:
this.indices = [0, 1, 2];
// A position, normal, and texture coord fully describes one "vertex". What's the "i"th vertex? Simply
// the combined data you get if you look up index "i" of those lists above -- a position, normal vector,
// and texture coordinate together. Lastly we told it how to connect vertex entries into triangles.
// Every three indices in "this.indices" traces out one triangle.
}
});
const Square = (defs.Square = class Square extends Shape {
// **Square** demonstrates two triangles that share vertices. On any planar surface, the
// interior edges don't make any important seams. In these cases there's no reason not
// to re-use data of the common vertices between triangles. This makes all the vertex
// arrays (position, normals, etc) smaller and more cache friendly.
constructor() {
super("position", "normal", "texture_coord");
// Specify the 4 square corner locations, and match those up with normal vectors:
this.arrays.position = Vec.cast(
[-1, -1, 0],
[1, -1, 0],
[-1, 1, 0],
[1, 1, 0]
);
this.arrays.normal = Vec.cast([0, 0, 1], [0, 0, 1], [0, 0, 1], [0, 0, 1]);
// Arrange the vertices into a square shape in texture space too:
this.arrays.texture_coord = Vec.cast([0, 0], [1, 0], [0, 1], [1, 1]);
// Use two triangles this time, indexing into four distinct vertices:
this.indices.push(0, 1, 2, 1, 3, 2);
}
});
const Tetrahedron = (defs.Tetrahedron = class Tetrahedron extends Shape {
// **Tetrahedron** demonstrates flat vs smooth shading (a boolean argument selects
// which one). It is also our first 3D, non-planar shape. Four triangles share
// corners with each other. Unless we store duplicate points at each corner
// (storing the same position at each, but different normal vectors), the lighting
// will look "off". To get crisp seams at the edges we need the repeats.
constructor(using_flat_shading) {
super("position", "normal", "texture_coord");
var a = 1 / Math.sqrt(3);
if (!using_flat_shading) {
// Method 1: A tetrahedron with shared vertices. Compact, performs better,
// but can't produce flat shading or discontinuous seams in textures.
this.arrays.position = Vec.cast(
[0, 0, 0],
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]
);
this.arrays.normal = Vec.cast(
[-a, -a, -a],
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]
);
this.arrays.texture_coord = Vec.cast([0, 0], [1, 0], [0, 1], [1, 1]);
// Notice the repeats in the index list. Vertices are shared
// and appear in multiple triangles with this method.
this.indices.push(0, 1, 2, 0, 1, 3, 0, 2, 3, 1, 2, 3);
} else {
// Method 2: A tetrahedron with four independent triangles.
this.arrays.position = Vec.cast(
[0, 0, 0],
[1, 0, 0],
[0, 1, 0],
[0, 0, 0],
[1, 0, 0],
[0, 0, 1],
[0, 0, 0],
[0, 1, 0],
[0, 0, 1],
[0, 0, 1],
[1, 0, 0],
[0, 1, 0]
);
// The essence of flat shading: This time, values of normal vectors can
// be constant per whole triangle. Repeat them for all three vertices.
this.arrays.normal = Vec.cast(
[0, 0, -1],
[0, 0, -1],
[0, 0, -1],
[0, -1, 0],
[0, -1, 0],
[0, -1, 0],
[-1, 0, 0],
[-1, 0, 0],
[-1, 0, 0],
[a, a, a],
[a, a, a],
[a, a, a]
);
// Each face in Method 2 also gets its own set of texture coords (half the
// image is mapped onto each face). We couldn't do this with shared
// vertices since this features abrupt transitions when approaching the
// same point from different directions.
this.arrays.texture_coord = Vec.cast(
[0, 0],
[1, 0],
[1, 1],
[0, 0],
[1, 0],
[1, 1],
[0, 0],
[1, 0],
[1, 1],
[0, 0],
[1, 0],
[1, 1]
);
// Notice all vertices are unique this time.
this.indices.push(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
}
}
});
const Windmill = (defs.Windmill = class Windmill extends Shape {
// **Windmill** As our shapes get more complicated, we begin using matrices and flow
// control (including loops) to generate non-trivial point clouds and connect them.
constructor(num_blades) {
super("position", "normal", "texture_coord");
// A for loop to automatically generate the triangles:
for (let i = 0; i < num_blades; i++) {
// Rotate around a few degrees in the XZ plane to place each new point:
const spin = Mat4.rotation(
(i * 2 * Math.PI) / num_blades,
Vec.of(0, 1, 0)
);
// Apply that XZ rotation matrix to point (1,0,0) of the base triangle.
const newPoint = spin.times(Vec.of(1, 0, 0, 1)).to3();
const triangle = [
newPoint, // Store that XZ position as point 1.
newPoint.plus([0, 1, 0]), // Store it again but with higher y coord as point 2.
Vec.of(0, 0, 0)
]; // All triangles touch this location -- point 3.
this.arrays.position.push(...triangle);
// Rotate our base triangle's normal (0,0,1) to get the new one. Careful! Normal vectors are not
// points; their perpendicularity constraint gives them a mathematical quirk that when applying
// matrices you have to apply the transposed inverse of that matrix instead. But right now we've
// got a pure rotation matrix, where the inverse and transpose operations cancel out, so it's ok.
var newNormal = spin.times(Vec.of(0, 0, 1).to4(0)).to3();
// Propagate the same normal to all three vertices:
this.arrays.normal.push(newNormal, newNormal, newNormal);
this.arrays.texture_coord.push(...Vec.cast([0, 0], [0, 1], [1, 0]));
// Procedurally connect the 3 new vertices into triangles:
this.indices.push(3 * i, 3 * i + 1, 3 * i + 2);
}
}
});
const Cube = (defs.Cube = class Cube extends Shape {
// **Cube** A closed 3D shape, and the first example of a compound shape (a Shape constructed
// out of other Shapes). A cube inserts six Square strips into its own arrays, using six
// different matrices as offsets for each square.
constructor() {
super("position", "normal", "texture_coord");
// Loop 3 times (for each axis), and inside loop twice (for opposing cube sides):
for (var i = 0; i < 3; i++)
for (var j = 0; j < 2; j++) {
var square_transform = Mat4.rotation(
i == 0 ? Math.PI / 2 : 0,
Vec.of(1, 0, 0)
)
.times(
Mat4.rotation(
Math.PI * j - (i == 1 ? Math.PI / 2 : 0),
Vec.of(0, 1, 0)
)
)
.times(Mat4.translation([0, 0, 1]));
// Calling this function of a Square (or any Shape) copies it into the specified
// Shape (this one) at the specified matrix offset (square_transform):
Square.insert_transformed_copy_into(this, [], square_transform);
}
}
});
const Subdivision_Sphere = (defs.Subdivision_Sphere = class Subdivision_Sphere extends Shape {
// **Subdivision_Sphere** defines a Sphere surface, with nice uniform triangles. A subdivision surface
// (see Wikipedia article on those) is initially simple, then builds itself into a more and more
// detailed shape of the same layout. Each act of subdivision makes it a better approximation of
// some desired mathematical surface by projecting each new point onto that surface's known
// implicit equation. For a sphere, we begin with a closed 3-simplex (a tetrahedron). For each
// face, connect the midpoints of each edge together to make more faces. Repeat recursively until
// the desired level of detail is obtained. Project all new vertices to unit vectors (onto the
// unit sphere) and group them into triangles by following the predictable pattern of the recursion.
constructor(max_subdivisions) {
super("position", "normal", "texture_coord");
// Start from the following equilateral tetrahedron:
const tetrahedron = [
[0, 0, -1],
[0, 0.9428, 0.3333],
[-0.8165, -0.4714, 0.3333],
[0.8165, -0.4714, 0.3333]
];
this.arrays.position = Vec.cast(...tetrahedron);
// Begin recursion:
this.subdivide_triangle(0, 1, 2, max_subdivisions);
this.subdivide_triangle(3, 2, 1, max_subdivisions);
this.subdivide_triangle(1, 0, 3, max_subdivisions);
this.subdivide_triangle(0, 2, 3, max_subdivisions);
// With positions calculated, fill in normals and texture_coords of the finished Sphere:
for (let p of this.arrays.position) {
// Each point has a normal vector that simply goes to the point from the origin:
this.arrays.normal.push(p.copy());
// Textures are tricky. A Subdivision sphere has no straight seams to which image
// edges in UV space can be mapped. The only way to avoid artifacts is to smoothly
// wrap & unwrap the image in reverse - displaying the texture twice on the sphere.
// this.arrays.texture_coord.push( Vec.of( Math.asin( p[0]/Math.PI ) + .5, Math.asin( p[1]/Math.PI ) + .5 ) );
this.arrays.texture_coord.push(
Vec.of(
0.5 - Math.atan2(p[2], p[0]) / (2 * Math.PI),
0.5 + Math.asin(p[1]) / Math.PI
)
);
}
// Fix the UV seam by duplicating vertices with offset UV:
const tex = this.arrays.texture_coord;
for (let i = 0; i < this.indices.length; i += 3) {
const a = this.indices[i],
b = this.indices[i + 1],
c = this.indices[i + 2];
if (
[[a, b], [a, c], [b, c]].some(
x => Math.abs(tex[x[0]][0] - tex[x[1]][0]) > 0.5
) &&
[a, b, c].some(x => tex[x][0] < 0.5)
) {
for (let q of [[a, i], [b, i + 1], [c, i + 2]]) {
if (tex[q[0]][0] < 0.5) {
this.indices[q[1]] = this.arrays.position.length;
this.arrays.position.push(this.arrays.position[q[0]].copy());
this.arrays.normal.push(this.arrays.normal[q[0]].copy());
tex.push(tex[q[0]].plus(Vec.of(1, 0)));
}
}
}
}
}
subdivide_triangle(a, b, c, count) {
// subdivide_triangle(): Recurse through each level of detail
// by splitting triangle (a,b,c) into four smaller ones.
if (count <= 0) {
// Base case of recursion - we've hit the finest level of detail we want.
this.indices.push(a, b, c);
return;
}
// So we're not at the base case. So, build 3 new vertices at midpoints,
// and extrude them out to touch the unit sphere (length 1).
var ab_vert = this.arrays.position[a]
.mix(this.arrays.position[b], 0.5)
.normalized(),
ac_vert = this.arrays.position[a]
.mix(this.arrays.position[c], 0.5)
.normalized(),
bc_vert = this.arrays.position[b]
.mix(this.arrays.position[c], 0.5)
.normalized();
// Here, push() returns the indices of the three new vertices (plus one).
var ab = this.arrays.position.push(ab_vert) - 1,
ac = this.arrays.position.push(ac_vert) - 1,
bc = this.arrays.position.push(bc_vert) - 1;
// Recurse on four smaller triangles, and we're done. Skipping every fourth vertex index in
// our list takes you down one level of detail, and so on, due to the way we're building it.
this.subdivide_triangle(a, ab, ac, count - 1);
this.subdivide_triangle(ab, b, bc, count - 1);
this.subdivide_triangle(ac, bc, c, count - 1);
this.subdivide_triangle(ab, bc, ac, count - 1);
}
});
const Shape_From_File = (defs.Shape_From_File = class Shape_From_File extends Shape {
// **Shape_From_File** is a versatile standalone Shape that imports
// all its arrays' data from an .obj 3D model file.
constructor(filename) {
super("position", "normal", "texture_coord");
// Begin downloading the mesh. Once that completes, return
// control to our parse_into_mesh function.
this.load_file(filename);
}
load_file(filename) {
// Request the external file and wait for it to load.
// Failure mode: Loads an empty shape.
return fetch(filename)
.then(response => {
if (response.ok) return Promise.resolve(response.text());
else return Promise.reject(response.status);
})
.then(obj_file_contents => this.parse_into_mesh(obj_file_contents))
.catch(error => {
this.copy_onto_graphics_card(this.gl);
});
}
parse_into_mesh(data) {
// Adapted from the "webgl-obj-loader.js" library found online:
var verts = [],
vertNormals = [],
textures = [],
unpacked = {};
unpacked.verts = [];
unpacked.norms = [];
unpacked.textures = [];
unpacked.hashindices = {};
unpacked.indices = [];
unpacked.index = 0;
var lines = data.split("\n");
var VERTEX_RE = /^v\s/;
var NORMAL_RE = /^vn\s/;
var TEXTURE_RE = /^vt\s/;
var FACE_RE = /^f\s/;
var WHITESPACE_RE = /\s+/;
for (var i = 0; i < lines.length; i++) {
var line = lines[i].trim();
var elements = line.split(WHITESPACE_RE);
elements.shift();
if (VERTEX_RE.test(line)) verts.push.apply(verts, elements);
else if (NORMAL_RE.test(line))
vertNormals.push.apply(vertNormals, elements);
else if (TEXTURE_RE.test(line)) textures.push.apply(textures, elements);
else if (FACE_RE.test(line)) {
var quad = false;
for (var j = 0, eleLen = elements.length; j < eleLen; j++) {
if (j === 3 && !quad) {
j = 2;
quad = true;
}
if (elements[j] in unpacked.hashindices)
unpacked.indices.push(unpacked.hashindices[elements[j]]);
else {
var vertex = elements[j].split("/");
unpacked.verts.push(+verts[(vertex[0] - 1) * 3 + 0]);
unpacked.verts.push(+verts[(vertex[0] - 1) * 3 + 1]);
unpacked.verts.push(+verts[(vertex[0] - 1) * 3 + 2]);
if (textures.length) {
unpacked.textures.push(
+textures[(vertex[1] - 1 || vertex[0]) * 2 + 0]
);
unpacked.textures.push(
+textures[(vertex[1] - 1 || vertex[0]) * 2 + 1]
);
}
unpacked.norms.push(
+vertNormals[(vertex[2] - 1 || vertex[0]) * 3 + 0]
);
unpacked.norms.push(
+vertNormals[(vertex[2] - 1 || vertex[0]) * 3 + 1]
);
unpacked.norms.push(
+vertNormals[(vertex[2] - 1 || vertex[0]) * 3 + 2]
);
unpacked.hashindices[elements[j]] = unpacked.index;
unpacked.indices.push(unpacked.index);
unpacked.index += 1;
}
if (j === 3 && quad)
unpacked.indices.push(unpacked.hashindices[elements[0]]);
}
}
}
{
const { verts, norms, textures } = unpacked;
for (var j = 0; j < verts.length / 3; j++) {
this.arrays.position.push(
Vec.of(verts[3 * j], verts[3 * j + 1], verts[3 * j + 2])
);
this.arrays.normal.push(
Vec.of(norms[3 * j], norms[3 * j + 1], norms[3 * j + 2])
);
this.arrays.texture_coord.push(
Vec.of(textures[2 * j], textures[2 * j + 1])
);
}
this.indices = unpacked.indices;
}
this.normalize_positions(false);
this.ready = true;
}
draw(context, program_state, model_transform, material) {
// draw(): Same as always for shapes, but cancel all
// attempts to draw the shape before it loads:
if (this.ready)
super.draw(context, program_state, model_transform, material);
}
});
const Grid_Patch = (defs.Grid_Patch = class Grid_Patch extends Shape {
// A grid of rows and columns you can distort. A tesselation of triangles connects the
// points, generated with a certain predictable pattern of indices. Two callbacks
// allow you to dynamically define how to reach the next row or column.
constructor(
rows,
columns,
next_row_function,
next_column_function,
texture_coord_range = [[0, rows], [0, columns]]
) {
super("position", "normal", "texture_coord");
let points = [];
for (let r = 0; r <= rows; r++) {
points.push(new Array(columns + 1)); // Allocate a 2D array.
// Use next_row_function to generate the start point of each row. Pass in the progress ratio,
points[r][0] = next_row_function(
r / rows,
points[r - 1] && points[r - 1][0]
); // and the previous point if it existed.
}
for (
let r = 0;
r <= rows;
r++ // From those, use next_column function to generate the remaining points:
)
for (let c = 0; c <= columns; c++) {
if (c > 0)
points[r][c] = next_column_function(
c / columns,
points[r][c - 1],
r / rows
);
this.arrays.position.push(points[r][c]);
// Interpolate texture coords from a provided range.
const a1 = c / columns,
a2 = r / rows,
x_range = texture_coord_range[0],
y_range = texture_coord_range[1];
this.arrays.texture_coord.push(
Vec.of(
a1 * x_range[1] + (1 - a1) * x_range[0],
a2 * y_range[1] + (1 - a2) * y_range[0]
)
);
}
for (
let r = 0;
r <= rows;
r++ // Generate normals by averaging the cross products of all defined neighbor pairs.
)
for (let c = 0; c <= columns; c++) {
let curr = points[r][c],
neighbors = new Array(4),
normal = Vec.of(0, 0, 0);
for (let [i, dir] of [[-1, 0], [0, 1], [1, 0], [0, -1]].entries()) // Store each neighbor by rotational order.
neighbors[i] = points[r + dir[1]] && points[r + dir[1]][c + dir[0]]; // Leave "undefined" in the array wherever
// we hit a boundary.
for (
let i = 0;
i < 4;
i++ // Take cross-products of pairs of neighbors, proceeding
)
if (neighbors[i] && neighbors[(i + 1) % 4])
// a consistent rotational direction through the pairs:
normal = normal.plus(
neighbors[i].minus(curr).cross(neighbors[(i + 1) % 4].minus(curr))
);
normal.normalize(); // Normalize the sum to get the average vector.
// Store the normal if it's valid (not NaN or zero length), otherwise use a default:
if (normal.every(x => x == x) && normal.norm() > 0.01)
this.arrays.normal.push(Vec.from(normal));
else this.arrays.normal.push(Vec.of(0, 0, 1));
}
for (
var h = 0;
h < rows;
h++ // Generate a sequence like this (if #columns is 10):
)
for (
var i = 0;
i < 2 * columns;
i++ // "1 11 0 11 1 12 2 12 1 12 2 13 3 13 2 13 3 14 4 14 3..."
)
for (var j = 0; j < 3; j++)
this.indices.push(
h * (columns + 1) +
columns * ((i + (j % 2)) % 2) +
(~~((j % 3) / 2) ? ~~(i / 2) + 2 * (i % 2) : ~~(i / 2) + 1)
);
}
static sample_array(
array,
ratio // Optional but sometimes useful as a next row or column operation. In a given array
) {
// of points, intepolate the pair of points that our progress ratio falls between.
const frac = ratio * (array.length - 1),
alpha = frac - Math.floor(frac);
return array[Math.floor(frac)].mix(array[Math.ceil(frac)], alpha);
}
});
const Surface_Of_Revolution = (defs.Surface_Of_Revolution = class Surface_Of_Revolution extends Grid_Patch {
// SURFACE OF REVOLUTION: Produce a curved "sheet" of triangles with rows and columns.
// Begin with an input array of points, defining a 1D path curving through 3D space --
// now let each such point be a row. Sweep that whole curve around the Z axis in equal
// steps, stopping and storing new points along the way; let each step be a column. Now
// we have a flexible "generalized cylinder" spanning an area until total_curvature_angle.
constructor(
rows,
columns,
points,
texture_coord_range,
total_curvature_angle = 2 * Math.PI
) {
const row_operation = i => Grid_Patch.sample_array(points, i),
column_operation = (j, p) =>
Mat4.rotation(total_curvature_angle / columns, Vec.of(0, 0, 1))
.times(p.to4(1))
.to3();
super(rows, columns, row_operation, column_operation, texture_coord_range);
}
});
const Regular_2D_Polygon = (defs.Regular_2D_Polygon = class Regular_2D_Polygon extends Surface_Of_Revolution {
// Approximates a flat disk / circle
constructor(rows, columns) {
super(rows, columns, Vec.cast([0, 0, 0], [1, 0, 0]));
this.arrays.normal = this.arrays.normal.map(x => Vec.of(0, 0, 1));
this.arrays.texture_coord.forEach(
(x, i, a) =>
(a[i] = this.arrays.position[i].map(x => x / 2 + 0.5).slice(0, 2))
);
}
});
const Cylindrical_Tube = (defs.Cylindrical_Tube = class Cylindrical_Tube extends Surface_Of_Revolution {
// An open tube shape with equally sized sections, pointing down Z locally.
constructor(rows, columns, texture_range) {
super(rows, columns, Vec.cast([1, 0, 0.5], [1, 0, -0.5]), texture_range);
}
});
const Cone_Tip = (defs.Cone_Tip = class Cone_Tip extends Surface_Of_Revolution {
// Note: Touches the Z axis; squares degenerate into triangles as they sweep around.
constructor(rows, columns, texture_range) {
super(rows, columns, Vec.cast([0, 0, 1], [1, 0, -1]), texture_range);
}
});
const Torus = (defs.Torus = class Torus extends Shape {
// Build a donut shape. An example of a surface of revolution.
constructor(rows, columns, texture_range) {
super("position", "normal", "texture_coord");
const circle_points = Array(rows)
.fill(Vec.of(1 / 3, 0, 0))
.map((p, i, a) =>
Mat4.translation([-2 / 3, 0, 0])
.times(
Mat4.rotation((i / (a.length - 1)) * 2 * Math.PI, Vec.of(0, -1, 0))
)
.times(Mat4.scale([1, 1, 3]))
.times(p.to4(1))
.to3()
);
Surface_Of_Revolution.insert_transformed_copy_into(this, [
rows,
columns,
circle_points,
texture_range
]);
}
});
const Grid_Sphere = (defs.Grid_Sphere = class Grid_Sphere extends Shape {
// With lattitude / longitude divisions; this means singularities are at
constructor(
rows,
columns,
texture_range // the mesh's top and bottom. Subdivision_Sphere is a better alternative.
) {
super("position", "normal", "texture_coord");
const semi_circle_points = Array(rows)
.fill(Vec.of(0, 0, 1))
.map((x, i, a) =>
Mat4.rotation((i / (a.length - 1)) * Math.PI, Vec.of(0, 1, 0))
.times(x.to4(1))
.to3()
);
Surface_Of_Revolution.insert_transformed_copy_into(this, [
rows,
columns,
semi_circle_points,
texture_range
]);
}
});
const Closed_Cone = (defs.Closed_Cone = class Closed_Cone extends Shape {
// Combine a cone tip and a regular polygon to make a closed cone.
constructor(rows, columns, texture_range) {
super("position", "normal", "texture_coord");
Cone_Tip.insert_transformed_copy_into(this, [rows, columns, texture_range]);
Regular_2D_Polygon.insert_transformed_copy_into(
this,
[1, columns],
Mat4.rotation(Math.PI, Vec.of(0, 1, 0)).times(Mat4.translation([0, 0, 1]))
);
}
});
const Rounded_Closed_Cone = (defs.Rounded_Closed_Cone = class Rounded_Closed_Cone extends Surface_Of_Revolution {
// An alternative without two separate sections
constructor(rows, columns, texture_range) {
super(
rows,
columns,
Vec.cast([0, 0, 1], [1, 0, -1], [0, 0, -1]),
texture_range
);
}
});
const Capped_Cylinder = (defs.Capped_Cylinder = class Capped_Cylinder extends Shape {
// Combine a tube and two regular polygons to make a closed cylinder.
constructor(
rows,
columns,
texture_range // Flat shade this to make a prism, where #columns = #sides.
) {
super("position", "normal", "texture_coord");
Cylindrical_Tube.insert_transformed_copy_into(this, [
rows,
columns,
texture_range
]);
Regular_2D_Polygon.insert_transformed_copy_into(
this,
[1, columns],
Mat4.translation([0, 0, 0.5])
);
Regular_2D_Polygon.insert_transformed_copy_into(
this,
[1, columns],
Mat4.rotation(Math.PI, Vec.of(0, 1, 0)).times(
Mat4.translation([0, 0, 0.5])
)
);
}
});
const Rounded_Capped_Cylinder = (defs.Rounded_Capped_Cylinder = class Rounded_Capped_Cylinder extends Surface_Of_Revolution {
// An alternative without three separate sections
constructor(rows, columns, texture_range) {
super(
rows,
columns,
Vec.cast([0, 0, 0.5], [1, 0, 0.5], [1, 0, -0.5], [0, 0, -0.5]),
texture_range
);
}
});
const Minimal_Shape = (defs.Minimal_Shape = class Minimal_Shape extends tiny.Vertex_Buffer {
// **Minimal_Shape** an even more minimal triangle, with three
// vertices each holding a 3D position and a color.
constructor() {
super("position", "color");
// Describe the where the points of a triangle are in space, and also describe their colors:
this.arrays.position = [Vec.of(0, 0, 0), Vec.of(1, 0, 0), Vec.of(0, 1, 0)];
this.arrays.color = [
Color.of(1, 0, 0, 1),
Color.of(0, 1, 0, 1),
Color.of(0, 0, 1, 1)
];
}
});
const Minimal_Webgl_Demo = (defs.Minimal_Webgl_Demo = class Minimal_Webgl_Demo extends Scene {
// **Minimal_Webgl_Demo** is an extremely simple example of a Scene class.
constructor(webgl_manager, control_panel) {
super(webgl_manager, control_panel);
// Send a Triangle's vertices to the GPU's buffers:
this.shapes = { triangle: new Minimal_Shape() };
this.shader = new Basic_Shader();
}
display(context, graphics_state) {
// Every frame, simply draw the Triangle at its default location.
this.shapes.triangle.draw(
context,
graphics_state,
Mat4.identity(),
this.shader.material()
);
}
make_control_panel() {
this.control_panel.innerHTML += "(This one has no controls)";
}
});
const Basic_Shader = (defs.Basic_Shader = class Basic_Shader extends Shader {
// **Basic_Shader** is nearly the simplest example of a subclass of Shader, which stores and
// maanges a GPU program. Basic_Shader is a trivial pass-through shader that applies a
// shape's matrices and then simply samples literal colors stored at each vertex.
update_GPU(
context,
gpu_addresses,
graphics_state,
model_transform,
material
) {
// update_GPU(): Define how to synchronize our JavaScript's variables to the GPU's:
const [P, C, M] = [
graphics_state.projection_transform,
graphics_state.camera_inverse,
model_transform
],
PCM = P.times(C).times(M);
context.uniformMatrix4fv(
gpu_addresses.projection_camera_model_transform,
false,
Mat.flatten_2D_to_1D(PCM.transposed())
);
}
shared_glsl_code() {
// ********* SHARED CODE, INCLUDED IN BOTH SHADERS *********
return `precision mediump float;
varying vec4 VERTEX_COLOR;
`;
}
vertex_glsl_code() {
// ********* VERTEX SHADER *********
return `
attribute vec4 color;
attribute vec3 position; // Position is expressed in object coordinates.
uniform mat4 projection_camera_model_transform;
void main()
{ // Compute the vertex's final resting place (in NDCS), and use the hard-coded color of the vertex:
gl_Position = projection_camera_model_transform * vec4( position, 1.0 );
VERTEX_COLOR = color;
}`;
}
fragment_glsl_code() {
// ********* FRAGMENT SHADER *********
return `
void main()
{ // The interpolation gets done directly on the per-vertex colors:
gl_FragColor = VERTEX_COLOR;
}`;
}
});
const Funny_Shader = (defs.Funny_Shader = class Funny_Shader extends Shader {
// **Funny_Shader**: A simple "procedural" texture shader, with
// texture coordinates but without an input image.
update_GPU(context, gpu_addresses, program_state, model_transform, material) {
// update_GPU(): Define how to synchronize our JavaScript's variables to the GPU's:
const [P, C, M] = [
program_state.projection_transform,
program_state.camera_inverse,
model_transform
],
PCM = P.times(C).times(M);
context.uniformMatrix4fv(
gpu_addresses.projection_camera_model_transform,
false,
Mat.flatten_2D_to_1D(PCM.transposed())
);
context.uniform1f(
gpu_addresses.animation_time,
program_state.animation_time / 1000
);
}
shared_glsl_code() {
// ********* SHARED CODE, INCLUDED IN BOTH SHADERS *********
return `precision mediump float;
varying vec2 f_tex_coord;
`;
}
vertex_glsl_code() {
// ********* VERTEX SHADER *********
return (
this.shared_glsl_code() +
`
attribute vec3 position; // Position is expressed in object coordinates.
attribute vec2 texture_coord;
uniform mat4 projection_camera_model_transform;
void main()
{ gl_Position = projection_camera_model_transform * vec4( position, 1.0 ); // The vertex's final resting place (in NDCS).
f_tex_coord = texture_coord; // Directly use original texture coords and interpolate between.
}`
);
}
fragment_glsl_code() {
// ********* FRAGMENT SHADER *********
return (
this.shared_glsl_code() +
`
uniform float animation_time;
void main()
{ float a = animation_time, u = f_tex_coord.x, v = f_tex_coord.y;
// Use an arbitrary math function to color in all pixels as a complex
gl_FragColor = vec4( // function of the UV texture coordintaes of the pixel and of time.
2.0 * u * sin(17.0 * u ) + 3.0 * v * sin(11.0 * v ) + 1.0 * sin(13.0 * a),
3.0 * u * sin(18.0 * u ) + 4.0 * v * sin(12.0 * v ) + 2.0 * sin(14.0 * a),
4.0 * u * sin(19.0 * u ) + 5.0 * v * sin(13.0 * v ) + 3.0 * sin(15.0 * a),
5.0 * u * sin(20.0 * u ) + 6.0 * v * sin(14.0 * v ) + 4.0 * sin(16.0 * a));
}`
);
}
});
const Phong_Shader = (defs.Phong_Shader = class Phong_Shader extends Shader {
// **Phong_Shader** is a subclass of Shader, which stores and maanges a GPU program.
// Graphic cards prior to year 2000 had shaders like this one hard-coded into them
// instead of customizable shaders. "Phong-Blinn" Shading here is a process of
// determining brightness of pixels via vector math. It compares the normal vector
// at that pixel with the vectors toward the camera and light sources.
constructor(num_lights = 2) {
super();
this.num_lights = num_lights;
}
shared_glsl_code() {
// ********* SHARED CODE, INCLUDED IN BOTH SHADERS *********
return (
` precision mediump float;
const int N_LIGHTS = ` +
this.num_lights +
`;
uniform float ambient, diffusivity, specularity, smoothness;
uniform vec4 light_positions_or_vectors[N_LIGHTS], light_colors[N_LIGHTS];
uniform float light_attenuation_factors[N_LIGHTS];
uniform vec4 shape_color;
uniform vec3 squared_scale, camera_center;
// Specifier "varying" means a variable's final value will be passed from the vertex shader
// on to the next phase (fragment shader), then interpolated per-fragment, weighted by the
// pixel fragment's proximity to each of the 3 vertices (barycentric interpolation).
varying vec3 N, vertex_worldspace;
varying vec4 eyespace_pos;
uniform vec4 clip_plane;
// ***** PHONG SHADING HAPPENS HERE: *****
vec3 phong_model_lights( vec3 N, vec3 vertex_worldspace, vec4 tex_color )
{ // phong_model_lights(): Add up the lights' contributions.
vec3 E = normalize( camera_center - vertex_worldspace );
vec3 result = vec3( 0.0 );
for(int i = 0; i < N_LIGHTS; i++)
{
// Lights store homogeneous coords - either a position or vector. If w is 0, the
// light will appear directional (uniform direction from all points), and we
// simply obtain a vector towards the light by directly using the stored value.
// Otherwise if w is 1 it will appear as a point light -- compute the vector to
// the point light's location from the current surface point. In either case,
// fade (attenuate) the light as the vector needed to reach it gets longer.
vec3 surface_to_light_vector = light_positions_or_vectors[i].xyz -
light_positions_or_vectors[i].w * vertex_worldspace;
float distance_to_light = length( surface_to_light_vector );
vec3 L = normalize( surface_to_light_vector );
vec3 H = normalize( L + E );
// Compute the diffuse and specular components from the Phong
// Reflection Model, using Blinn's "halfway vector" method:
float diffuse = max( dot( N, L ), 0.0 );
float specular = pow( max( dot( N, H ), 0.0 ), smoothness );
float attenuation = 1.0 / (1.0 + light_attenuation_factors[i] * distance_to_light * distance_to_light );
vec3 light_contribution = (shape_color.xyz + tex_color.xyz) * light_colors[i].xyz * diffusivity * diffuse
+ light_colors[i].xyz * specularity * specular;
result += attenuation * light_contribution;
}
return result;
} `
);
}
vertex_glsl_code() {
// ********* VERTEX SHADER *********
return (
this.shared_glsl_code() +
`
attribute vec3 position, normal; // Position is expressed in object coordinates.
uniform mat4 model_transform;
uniform mat4 projection_camera_model_transform;
void main()
{ // The vertex's final resting place (in NDCS):
gl_Position = projection_camera_model_transform * vec4( position, 1.0 );
// The final normal vector in screen space.
N = normalize( mat3( model_transform ) * normal / squared_scale);
vertex_worldspace = ( model_transform * vec4( position, 1.0 ) ).xyz;
eyespace_pos = model_transform * vec4(position, 1.0);
} `
);
}
fragment_glsl_code() {
// ********* FRAGMENT SHADER *********
// A fragment is a pixel that's overlapped by the current triangle.
// Fragments affect the final image or get discarded due to depth.
return (
this.shared_glsl_code() +
`
void main()
{
if (dot(eyespace_pos, clip_plane) < 0.0) discard;
// Compute an initial (ambient) color:
gl_FragColor = vec4( shape_color.xyz * ambient, shape_color.w );
// Compute the final color with contributions from lights:
gl_FragColor.xyz += phong_model_lights( normalize( N ), vertex_worldspace, vec4(0, 0, 0, 0) );
} `
);
}
send_material(gl, gpu, material) {
// send_material(): Send the desired shape-wide material qualities to the
// graphics card, where they will tweak the Phong lighting formula.
gl.uniform4fv(gpu.shape_color, material.color);
gl.uniform1f(gpu.ambient, material.ambient);
gl.uniform1f(gpu.diffusivity, material.diffusivity);
gl.uniform1f(gpu.specularity, material.specularity);
gl.uniform1f(gpu.smoothness, material.smoothness);
}
send_gpu_state(gl, gpu, gpu_state, model_transform) {
// send_gpu_state(): Send the state of our whole drawing context to the GPU.
const O = Vec.of(0, 0, 0, 1),
camera_center = gpu_state.camera_transform.times(O).to3();
gl.uniform3fv(gpu.camera_center, camera_center);
// Use the squared scale trick from "Eric's blog" instead of inverse transpose matrix:
const squared_scale = model_transform
.reduce((acc, r) => {
return acc.plus(Vec.from(r).mult_pairs(r));
}, Vec.of(0, 0, 0, 0))
.to3();
gl.uniform3fv(gpu.squared_scale, squared_scale);
// Send the current matrices to the shader. Go ahead and pre-compute
// the products we'll need of the of the three special matrices and just
// cache and send those. They will be the same throughout this draw
// call, and thus across each instance of the vertex shader.
// Transpose them since the GPU expects matrices as column-major arrays.
const PCM = gpu_state.projection_transform
.times(gpu_state.camera_inverse)
.times(model_transform);
gl.uniformMatrix4fv(
gpu.model_transform,
false,
Mat.flatten_2D_to_1D(model_transform.transposed())
);
gl.uniformMatrix4fv(