-
Notifications
You must be signed in to change notification settings - Fork 3
/
primitives.js
2016 lines (1853 loc) · 74.5 KB
/
primitives.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
/*
* Copyright 2009, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @fileoverview This file contains functions to create geometric primitives for
* o3d. It puts them in the "primitives" module on the o3djs object.
*
* For more information about o3d see http://code.google.com/p/o3d
*
*
* Requires base.js
*/
o3djs.provide('o3djs.primitives');
o3djs.require('o3djs.math');
/**
* A Module for creating primitives.
* @namespace
*/
o3djs.primitives = o3djs.primitives || {};
/**
* Sets the bounding box and zSortPoint for a primitive based on its vertices
*
* @param {!o3d.Primitive} primitive Primitive to set culling info for.
*/
o3djs.primitives.setCullingInfo = function(primitive) {
var box = primitive.getBoundingBox(0);
primitive.boundingBox = box;
var minExtent = box.minExtent;
var maxExtent = box.maxExtent;
primitive.zSortPoint = o3djs.math.divVectorScalar(
o3djs.math.addVector(minExtent, maxExtent), 2);
};
/**
* Used to store the elements of a stream.
* @param {number} numComponents The number of numerical components per
* element.
* @param {!o3d.Stream.Semantic} semantic The semantic of the stream.
* @param {number} opt_semanticIndex The semantic index of the stream.
* Defaults to zero.
* @constructor
*/
o3djs.primitives.VertexStreamInfo = function(numComponents,
semantic,
opt_semanticIndex) {
/**
* The number of numerical components per element.
* @type {number}
*/
this.numComponents = numComponents;
/**
* The semantic of the stream.
* @type {!o3d.Stream.Semantic}
*/
this.semantic = semantic;
/**
* The semantic index of the stream.
* @type {number}
*/
this.semanticIndex = opt_semanticIndex || 0;
/**
* The elements of the stream.
* @type {!Array.<number>}
*/
this.elements = [];
/**
* Adds an element to this VertexStreamInfo. The number of values passed must
* match the number of components for this VertexStreamInfo.
* @param {number} value1 First value.
* @param {number} opt_value2 Second value.
* @param {number} opt_value3 Third value.
* @param {number} opt_value4 Fourth value.
*/
this.addElement = function(value1, opt_value2, opt_value3, opt_value4) { };
/**
* Sets an element on this VertexStreamInfo. The number of values passed must
* match the number of components for this VertexStreamInfo.
* @param {number} index Index of element to set.
* @param {number} value1 First value.
* @param {number} opt_value2 Second value.
* @param {number} opt_value3 Third value.
* @param {number} opt_value4 Fourth value.
*/
this.setElement = function(
index, value1, opt_value2, opt_value3, opt_value4) { };
/**
* Adds an element to this VertexStreamInfo. The number of values in the
* vector must match the number of components for this VertexStreamInfo.
* @param {!Array.<number>} vector Array of values for element.
*/
this.addElementVector = function(vector) { }; // replaced below.
/**
* Sets an element on this VertexStreamInfo. The number of values in the
* vector must match the number of components for this VertexStreamInfo.
* @param {number} index Index of element to set.
* @param {!Array.<number>} vector Array of values for element.
*/
this.setElementVector = function(index, vector) { }; // replaced below.
/**
* Sets an element on this VertexStreamInfo. The number of values in the
* vector will match the number of components for this VertexStreamInfo.
* @param {number} index Index of element to set.
* @return {!Array.<number>} Array of values for element.
*/
this.getElementVector = function(index) { return []; }; // replaced below.
switch (numComponents) {
case 1:
this.addElement = function(value) {
this.elements.push(value);
}
this.getElement = function(index) {
return this.elements[index];
}
this.setElement = function(index, value) {
this.elements[index] = value;
}
break;
case 2:
this.addElement = function(value0, value1) {
this.elements.push(value0, value1);
}
this.addElementVector = function(vector) {
this.elements.push(vector[0], vector[1]);
}
this.getElementVector = function(index) {
return this.elements.slice(index * numComponents,
(index + 1) * numComponents);
}
this.setElement = function(index, value0, value1) {
this.elements[index * numComponents + 0] = value0;
this.elements[index * numComponents + 1] = value1;
}
this.setElementVector = function(index, vector) {
this.elements[index * numComponents + 0] = vector[0];
this.elements[index * numComponents + 1] = vector[1];
}
break;
case 3:
this.addElement = function(value0, value1, value2) {
this.elements.push(value0, value1, value2);
}
this.addElementVector = function(vector) {
this.elements.push(vector[0], vector[1], vector[2]);
}
this.getElementVector = function(index) {
return this.elements.slice(index * numComponents,
(index + 1) * numComponents);
}
this.setElement = function(index, value0, value1, value2) {
this.elements[index * numComponents + 0] = value0;
this.elements[index * numComponents + 1] = value1;
this.elements[index * numComponents + 2] = value2;
}
this.setElementVector = function(index, vector) {
this.elements[index * numComponents + 0] = vector[0];
this.elements[index * numComponents + 1] = vector[1];
this.elements[index * numComponents + 2] = vector[2];
}
break;
case 4:
this.addElement = function(value0, value1, value2, value3) {
this.elements.push(value0, value1, value2, value3);
}
this.addElementVector = function(vector) {
this.elements.push(vector[0], vector[1], vector[2], vector[3]);
}
this.getElementVector = function(index) {
return this.elements.slice(index * numComponents,
(index + 1) * numComponents);
}
this.setElement = function(index, value0, value1, value2, value3) {
this.elements[index * numComponents + 0] = value0;
this.elements[index * numComponents + 1] = value1;
this.elements[index * numComponents + 2] = value2;
this.elements[index * numComponents + 3] = value3;
}
this.setElementVector = function(index, vector) {
this.elements[index * numComponents + 0] = vector[0];
this.elements[index * numComponents + 1] = vector[1];
this.elements[index * numComponents + 2] = vector[2];
this.elements[index * numComponents + 3] = vector[3];
}
break;
default:
throw 'A stream must contain between 1 and 4 components';
}
};
/**
* Get the number of elements in the stream.
* @return {number} The number of elements in the stream.
*/
o3djs.primitives.VertexStreamInfo.prototype.numElements = function() {
return this.elements.length / this.numComponents;
};
/**
* Create a VertexStreamInfo.
* @param {number} numComponents The number of numerical components per
* element.
* @param {!o3d.Stream.Semantic} semantic The semantic of the stream.
* @param {number} opt_semanticIndex The semantic index of the stream.
* Defaults to zero.
* @return {!o3djs.primitives.VertexStreamInfo} The new stream.
*/
o3djs.primitives.createVertexStreamInfo = function(numComponents,
semantic,
opt_semanticIndex) {
return new o3djs.primitives.VertexStreamInfo(numComponents,
semantic,
opt_semanticIndex);
};
/**
* VertexInfoBase. Used to store vertices and indices.
* @constructor
*/
o3djs.primitives.VertexInfoBase = function() {
this.streams = [];
this.indices = [];
};
/**
* Add a new stream to the VertexInfo, replacing it with a new empty one
* if it already exists.
* @param {number} numComponents The number of components per vector.
* @param {!o3d.Stream.Semantic} semantic The semantic of the stream.
* @param {number} opt_semanticIndex The semantic index of the stream.
* Defaults to zero.
* @return {!o3djs.primitives.VertexStreamInfo} The new stream.
*/
o3djs.primitives.VertexInfoBase.prototype.addStream = function(
numComponents,
semantic,
opt_semanticIndex) {
this.removeStream(semantic, opt_semanticIndex);
var stream = o3djs.primitives.createVertexStreamInfo(
numComponents,
semantic,
opt_semanticIndex);
this.streams.push(stream);
return stream;
};
/**
* Find a stream in the VertexInfo.
* @param {!o3d.Stream.Semantic} semantic The semantic of the stream.
* @param {number} opt_semanticIndex The semantic index of the stream.
* Defaults to zero.
* @return {o3djs.primitives.VertexStreamInfo} The stream or null if it
* is not present.
*/
o3djs.primitives.VertexInfoBase.prototype.findStream = function(
semantic,
opt_semanticIndex) {
opt_semanticIndex = opt_semanticIndex || 0;
for (var i = 0; i < this.streams.length; ++i) {
if (this.streams[i].semantic === semantic &&
this.streams[i].semanticIndex == opt_semanticIndex) {
return this.streams[i];
}
}
return null;
};
/**
* Remove a stream from the VertexInfo. Does nothing if a matching stream
* does not exist.
* @param {!o3d.Stream.Semantic} semantic The semantic of the stream.
* @param {number} opt_semanticIndex The semantic index of the stream.
* Defaults to zero.
*/
o3djs.primitives.VertexInfoBase.prototype.removeStream = function(
semantic,
opt_semanticIndex) {
opt_semanticIndex = opt_semanticIndex || 0;
for (var i = 0; i < this.streams.length; ++i) {
if (this.streams[i].semantic === semantic &&
this.streams[i].semanticIndex == opt_semanticIndex) {
this.streams.splice(i, 1);
return;
}
}
};
/**
* Appends all of the information in the passed VertexInfo on to the
* end of this one. This is useful for putting multiple primitives'
* vertices, appropriately transformed, into a single Shape. Both
* VertexInfo objects must contain the same number of streams, with
* the same semantics and number of components.
* @param {!o3djs.primitives.VertexInfoBase} info The VertexInfo whose
* information should be appended to this one.
*/
o3djs.primitives.VertexInfoBase.prototype.append = function(info) {
if (this.streams.length == 0 && info.streams.length != 0) {
// Special case
for (var i = 0; i < info.streams.length; i++) {
var srcStream = info.streams[i];
var stream = this.addStream(srcStream.numComponents,
srcStream.semantic,
srcStream.semanticIndex);
stream.elements = stream.elements.concat(srcStream.elements);
}
this.indices = this.indices.concat(info.indices);
return;
}
// First verify that both have the same streams
if (this.streams.length != info.streams.length) {
throw 'Number of VertexInfoStreams did not match';
}
for (var i = 0; i < this.streams.length; i++) {
var found = false;
var semantic = this.streams[i].semantic;
var numComponents = this.streams[i].numComponents;
var semanticIndex = this.streams[i].semanticIndex;
for (var j = 0; j < info.streams.length; j++) {
var otherStream = info.streams[j];
if (otherStream.semantic === semantic &&
otherStream.numComponents == numComponents &&
otherStream.semanticIndex == semanticIndex) {
found = true;
break;
}
}
if (!found) {
throw 'Did not find stream with semantic=' + semantic +
', numComponents=' + numComponents +
', and semantic index=' + semanticIndex +
' in given VertexInfo';
}
}
// Compute the number of vertices currently in the shape
var positionStream = this.findStream(o3djs.base.o3d.Stream.POSITION);
if (!positionStream)
throw 'POSITION stream is missing';
var numVertices = positionStream.numElements();
// Concatenate all VertexStreamInfos' data
for (var i = 0; i < this.streams.length; i++) {
var stream = this.streams[i];
var srcStream = info.findStream(stream.semantic, stream.semanticIndex);
stream.elements = stream.elements.concat(srcStream.elements);
}
// Concatenate and adjust indices
for (var i = 0; i < info.indices.length; i++) {
this.indices.push(info.indices[i] + numVertices);
}
};
/**
* Validates that all the streams contain the same number of elements, that
* all the indices are within range and that a position stream is present.
*/
o3djs.primitives.VertexInfoBase.prototype.validate = function() {
// Check the position stream is present.
var positionStream = this.findStream(o3djs.base.o3d.Stream.POSITION);
if (!positionStream)
throw 'POSITION stream is missing';
// Check all the streams have the same number of elements.
var numElements = positionStream.numElements();
for (var s = 0; s < this.streams.length; ++s) {
if (this.streams[s].numElements() !== numElements) {
throw 'Stream ' + s + ' contains ' + this.streams[s].numElements() +
' elements whereas the POSITION stream contains ' + numElements;
}
}
// Check all the indices are in range.
for (var i = 0; i < this.indices.length; ++i) {
if (this.indices[i] < 0 || this.indices[i] >= numElements) {
throw 'The index ' + this.indices[i] + ' is out of range [0, ' +
numElements + ']';
}
}
};
/**
* Reorients the vertices, positions and normals, of this vertexInfo by the
* given matrix. In other words, it multiplies each vertex by the given matrix
* and each normal by the inverse-transpose of the given matrix.
* @param {!o3djs.math.Matrix4} matrix Matrix by which to multiply.
*/
o3djs.primitives.VertexInfoBase.prototype.reorient = function(matrix) {
var math = o3djs.math;
var matrixInverse = math.inverse(math.matrix4.getUpper3x3(matrix));
for (var s = 0; s < this.streams.length; ++s) {
var stream = this.streams[s];
if (stream.numComponents == 3) {
var numElements = stream.numElements();
switch (stream.semantic) {
case o3djs.base.o3d.Stream.POSITION:
for (var i = 0; i < numElements; ++i) {
stream.setElementVector(i,
math.matrix4.transformPoint(matrix,
stream.getElementVector(i)));
}
break;
case o3djs.base.o3d.Stream.NORMAL:
for (var i = 0; i < numElements; ++i) {
stream.setElementVector(i,
math.matrix4.transformNormal(matrix,
stream.getElementVector(i)));
}
break;
case o3djs.base.o3d.Stream.TANGENT:
case o3djs.base.o3d.Stream.BINORMAL:
for (var i = 0; i < numElements; ++i) {
stream.setElementVector(i,
math.matrix4.transformDirection(matrix,
stream.getElementVector(i)));
}
break;
}
}
}
};
/**
* Creates a shape from a VertexInfoBase
* @param {!o3d.Pack} pack Pack to create objects in.
* @param {!o3d.Material} material to use.
* @param {!o3d.Primitive.PrimitiveType} primitiveType The type of primitive.
* @return {!o3d.Shape} The created shape.
*/
o3djs.primitives.VertexInfoBase.prototype.createShapeByType = function(
pack,
material,
primitiveType) {
this.validate();
var numIndices = this.indices.length;
var numPrimitives;
switch (primitiveType) {
case o3djs.base.o3d.Primitive.POINTLIST:
numPrimitives = numIndices / 1;
break;
case o3djs.base.o3d.Primitive.LINELIST:
numPrimitives = numIndices / 2;
break;
case o3djs.base.o3d.Primitive.LINESTRIP:
numPrimitives = numIndices - 1;
break;
case o3djs.base.o3d.Primitive.TRIANGLELIST:
numPrimitives = numIndices / 3;
break;
case o3djs.base.o3d.Primitive.TRIANGLESTRIP:
case o3djs.base.o3d.Primitive.TRIANGLEFAN:
numPrimitives = numIndices - 2;
break;
default:
throw 'unknown primitive type';
}
var positionStream = this.findStream(o3djs.base.o3d.Stream.POSITION);
var numVertices = positionStream.numElements();
// create a shape and primitive for the vertices.
var shape = pack.createObject('Shape');
var primitive = pack.createObject('Primitive');
var streamBank = pack.createObject('StreamBank');
primitive.owner = shape;
primitive.streamBank = streamBank;
primitive.material = material;
primitive.numberPrimitives = numPrimitives;
primitive.primitiveType = primitiveType;
primitive.numberVertices = numVertices;
primitive.createDrawElement(pack, null);
// Calculate the tangent and binormal or provide defaults or fail if the
// effect requires either and they are not present.
var streamInfos = material.effect.getStreamInfo();
for (var s = 0; s < streamInfos.length; ++s) {
var semantic = streamInfos[s].semantic;
var semanticIndex = streamInfos[s].semanticIndex;
var requiredStream = this.findStream(semantic, semanticIndex);
if (!requiredStream) {
switch (semantic) {
case o3djs.base.o3d.Stream.TANGENT:
case o3djs.base.o3d.Stream.BINORMAL:
if (primitiveType == o3djs.base.o3d.Primitive.TRIANGLELIST) {
this.addTangentStreams(semanticIndex);
} else {
throw 'Can not create tangents and binormals for primitive type' +
primitiveType;
}
break;
case o3djs.base.o3d.Stream.COLOR:
requiredStream = this.addStream(4, semantic, semanticIndex);
for (var i = 0; i < numVertices; ++i) {
requiredStream.addElement(1, 1, 1, 1);
}
break;
case o3djs.base.o3d.Stream.INFLUENCE_WEIGHTS:
case o3djs.base.o3d.Stream.INFLUENCE_INDICES:
break;
default:
throw 'Missing stream for semantic ' + semantic +
' with semantic index ' + semanticIndex;
}
}
}
// These next few lines take our javascript streams and load them into a
// 'buffer' where the 3D hardware can find them. We have to do this
// because the 3D hardware can't 'see' javascript data until we copy it to
// a buffer.
var vertexBuffer = pack.createObject('VertexBuffer');
var fields = [];
for (var s = 0; s < this.streams.length; ++s) {
var stream = this.streams[s];
var fieldType = (stream.semantic == o3djs.base.o3d.Stream.COLOR &&
stream.numComponents == 4) ? 'UByteNField' : 'FloatField';
fields[s] = vertexBuffer.createField(fieldType, stream.numComponents);
streamBank.setVertexStream(stream.semantic,
stream.semanticIndex,
fields[s],
0);
}
vertexBuffer.allocateElements(numVertices);
for (var s = 0; s < this.streams.length; ++s) {
fields[s].setAt(0, this.streams[s].elements);
}
var indexBuffer = pack.createObject('IndexBuffer');
indexBuffer.set(this.indices);
primitive.indexBuffer = indexBuffer;
o3djs.primitives.setCullingInfo(primitive);
return shape;
};
/**
* A VertexInfo is a specialization of VertexInfoBase for triangle based
* geometry.
* @constructor
* @extends {o3djs.primitives.VertexInfoBase}
*/
o3djs.primitives.VertexInfo = function() {
o3djs.primitives.VertexInfoBase.call(this);
}
o3djs.base.inherit(o3djs.primitives.VertexInfo,
o3djs.primitives.VertexInfoBase);
/**
* Returns the number of triangles represented by the VertexInfo.
* @return {number} The number of triangles represented by VertexInfo.
*/
o3djs.primitives.VertexInfo.prototype.numTriangles = function() {
return this.indices.length / 3;
};
/**
* Adds a triangle.
* @param {number} index1 The index of the first vertex of the triangle.
* @param {number} index2 The index of the second vertex of the triangle.
* @param {number} index3 The index of the third vertex of the triangle.
*/
o3djs.primitives.VertexInfo.prototype.addTriangle = function(
index1, index2, index3) {
this.indices.push(index1, index2, index3);
};
/**
* Gets the vertex indices of the triangle at the given triangle index.
* @param {number} triangleIndex The index of the triangle.
* @return {!Array.<number>} An array of three triangle indices.
*/
o3djs.primitives.VertexInfo.prototype.getTriangle = function(
triangleIndex) {
var indexIndex = triangleIndex * 3;
return [this.indices[indexIndex + 0],
this.indices[indexIndex + 1],
this.indices[indexIndex + 2]];
};
/**
* Sets the vertex indices of the triangle at the given triangle index.
* @param {number} triangleIndex The index of the triangle.
* @param {number} index1 The index of the first vertex of the triangle.
* @param {number} index2 The index of the second vertex of the triangle.
* @param {number} index3 The index of the third vertex of the triangle.
*/
o3djs.primitives.VertexInfo.prototype.setTriangle = function(
triangleIndex, index1, index2, index3) {
var indexIndex = triangleIndex * 3;
this.indices[indexIndex + 0] = index1;
this.indices[indexIndex + 1] = index2;
this.indices[indexIndex + 2] = index3;
};
/**
* Creates a shape from a VertexInfo
* @param {!o3d.Pack} pack Pack to create objects in.
* @param {!o3d.Material} material to use.
* @return {!o3d.Shape} The created shape.
*/
o3djs.primitives.VertexInfo.prototype.createShape = function(
pack,
material) {
return this.createShapeByType(
pack, material, o3djs.base.o3d.Primitive.TRIANGLELIST);
};
/**
* Calculate tangents and binormals based on the positions, normals and
* texture coordinates found in existing streams.
* @param {number} opt_semanticIndex The semantic index of the texture
* coordinate to use and the tangent and binormal streams to add. Defaults
* to zero.
*/
o3djs.primitives.VertexInfo.prototype.addTangentStreams =
function(opt_semanticIndex) {
opt_semanticIndex = opt_semanticIndex || 0;
var math = o3djs.math;
this.validate();
// Find and validate the position, normal and texture coordinate frames.
var positionStream = this.findStream(o3djs.base.o3d.Stream.POSITION);
if (!positionStream)
throw 'Cannot calculate tangent frame because POSITION stream is missing';
if (positionStream.numComponents != 3)
throw 'Cannot calculate tangent frame because POSITION stream is not 3D';
var normalStream = this.findStream(o3djs.base.o3d.Stream.NORMAL);
if (!normalStream)
throw 'Cannot calculate tangent frame because NORMAL stream is missing';
if (normalStream.numComponents != 3)
throw 'Cannot calculate tangent frame because NORMAL stream is not 3D';
var texCoordStream = this.findStream(o3djs.base.o3d.Stream.TEXCOORD,
opt_semanticIndex);
if (!texCoordStream)
throw 'Cannot calculate tangent frame because TEXCOORD stream ' +
opt_semanticIndex + ' is missing';
// Maps from position, normal key to tangent and binormal matrix.
var tangentFrames = {};
// Rounds a vector to integer components.
function roundVector(v) {
return [Math.round(v[0]), Math.round(v[1]), Math.round(v[2])];
}
// Generates a key for the tangentFrames map from a position and normal
// vector. Rounds position and normal to allow some tolerance.
function tangentFrameKey(position, normal) {
return roundVector(math.mulVectorScalar(position, 100)) + ',' +
roundVector(math.mulVectorScalar(normal, 100));
}
// Accumulates into the tangent and binormal matrix at the approximate
// position and normal.
function addTangentFrame(position, normal, tangent, binormal) {
var key = tangentFrameKey(position, normal);
var frame = tangentFrames[key];
if (!frame) {
frame = [[0, 0, 0], [0, 0, 0]];
}
math.addVector3To(frame[0], tangent, frame[0]);
math.addVector3To(frame[1], binormal, frame[1]);
tangentFrames[key] = frame;
}
// Get the tangent and binormal matrix at the approximate position and
// normal.
function getTangentFrame(position, normal) {
var key = tangentFrameKey(position, normal);
return tangentFrames[key];
}
var numTriangles = this.numTriangles();
for (var triangleIndex = 0; triangleIndex < numTriangles; ++triangleIndex) {
// Get the vertex indices, uvs and positions for the triangle.
var vertexIndices = this.getTriangle(triangleIndex);
var uvs = [];
var positions = [];
var normals = [];
for (var i = 0; i < 3; ++i) {
var vertexIndex = vertexIndices[i];
uvs[i] = texCoordStream.getElementVector(vertexIndex);
positions[i] = positionStream.getElementVector(vertexIndex);
normals[i] = normalStream.getElementVector(vertexIndex);
}
// Calculate the tangent and binormal for the triangle using method
// described in Maya documentation appendix A: tangent and binormal
// vectors.
var tangent = [0, 0, 0];
var binormal = [0, 0, 0];
for (var axis = 0; axis < 3; ++axis) {
var edge1 = [positions[1][axis] - positions[0][axis],
uvs[1][0] - uvs[0][0], uvs[1][1] - uvs[0][1]];
var edge2 = [positions[2][axis] - positions[0][axis],
uvs[2][0] - uvs[0][0], uvs[2][1] - uvs[0][1]];
var edgeCross = math.normalize(math.cross(edge1, edge2));
if (edgeCross[0] == 0) {
edgeCross[0] = 1;
}
tangent[axis] = -edgeCross[1] / edgeCross[0];
binormal[axis] = -edgeCross[2] / edgeCross[0];
}
// Normalize the tangent and binornmal.
var tangentLength = math.length(tangent);
if (tangentLength > 0.001) {
tangent = math.mulVectorScalar(tangent, 1 / tangentLength);
}
var binormalLength = math.length(binormal);
if (binormalLength > 0.001) {
binormal = math.mulVectorScalar(binormal, 1 / binormalLength);
}
// Accumulate the tangent and binormal into the tangent frame map.
for (var i = 0; i < 3; ++i) {
addTangentFrame(positions[i], normals[i], tangent, binormal);
}
}
// Add the tangent and binormal streams.
var tangentStream = this.addStream(3,
o3djs.base.o3d.Stream.TANGENT,
opt_semanticIndex);
var binormalStream = this.addStream(3,
o3djs.base.o3d.Stream.BINORMAL,
opt_semanticIndex);
// Extract the tangent and binormal for each vertex.
var numVertices = positionStream.numElements();
for (var vertexIndex = 0; vertexIndex < numVertices; ++vertexIndex) {
var position = positionStream.getElementVector(vertexIndex);
var normal = normalStream.getElementVector(vertexIndex);
var frame = getTangentFrame(position, normal);
// Orthonormalize the tangent with respect to the normal.
var tangent = frame[0];
tangent = math.subVector(
tangent, math.mulVectorScalar(normal, math.dot(normal, tangent)));
var tangentLength = math.length(tangent);
if (tangentLength > 0.001) {
tangent = math.mulVectorScalar(tangent, 1 / tangentLength);
}
// Orthonormalize the binormal with respect to the normal and the tangent.
var binormal = frame[1];
binormal = math.subVector(
binormal, math.mulVectorScalar(tangent, math.dot(tangent, binormal)));
binormal = math.subVector(
binormal, math.mulVectorScalar(normal, math.dot(normal, binormal)));
var binormalLength = math.length(binormal);
if (binormalLength > 0.001) {
binormal = math.mulVectorScalar(binormal, 1 / binormalLength);
}
tangentStream.setElementVector(vertexIndex, tangent);
binormalStream.setElementVector(vertexIndex, binormal);
}
};
/**
* Creates a new VertexInfo.
* @return {!o3djs.primitives.VertexInfo} The new VertexInfo.
*/
o3djs.primitives.createVertexInfo = function() {
return new o3djs.primitives.VertexInfo();
};
/**
* Creates sphere vertices.
* The created sphere has position, normal and uv streams.
*
* @param {number} radius radius of the sphere.
* @param {number} subdivisionsAxis number of steps around the sphere.
* @param {number} subdivisionsHeight number of vertically on the sphere.
* @param {!o3djs.math.Matrix4} opt_matrix A matrix by which to multiply
* all the vertices.
* @return {!o3djs.primitives.VertexInfo} The created sphere vertices.
*/
o3djs.primitives.createSphereVertices = function(radius,
subdivisionsAxis,
subdivisionsHeight,
opt_matrix) {
if (subdivisionsAxis <= 0 || subdivisionsHeight <= 0) {
throw Error('subdivisionAxis and subdivisionHeight must be > 0');
}
// We are going to generate our sphere by iterating through its
// spherical coordinates and generating 2 triangles for each quad on a
// ring of the sphere.
var vertexInfo = o3djs.primitives.createVertexInfo();
var positionStream = vertexInfo.addStream(
3, o3djs.base.o3d.Stream.POSITION);
var normalStream = vertexInfo.addStream(
3, o3djs.base.o3d.Stream.NORMAL);
var texCoordStream = vertexInfo.addStream(
2, o3djs.base.o3d.Stream.TEXCOORD, 0);
// Generate the individual vertices in our vertex buffer.
for (var y = 0; y <= subdivisionsHeight; y++) {
for (var x = 0; x <= subdivisionsAxis; x++) {
// Generate a vertex based on its spherical coordinates
var u = x / subdivisionsAxis;
var v = y / subdivisionsHeight;
var theta = 2 * Math.PI * u;
var phi = Math.PI * v;
var sinTheta = Math.sin(theta);
var cosTheta = Math.cos(theta);
var sinPhi = Math.sin(phi);
var cosPhi = Math.cos(phi);
var ux = cosTheta * sinPhi;
var uy = cosPhi;
var uz = sinTheta * sinPhi;
positionStream.addElement(radius * ux, radius * uy, radius * uz);
normalStream.addElement(ux, uy, uz);
texCoordStream.addElement(1 - u, 1 - v);
}
}
var numVertsAround = subdivisionsAxis + 1;
for (var x = 0; x < subdivisionsAxis; x++) {
for (var y = 0; y < subdivisionsHeight; y++) {
// Make triangle 1 of quad.
vertexInfo.addTriangle(
(y + 0) * numVertsAround + x,
(y + 0) * numVertsAround + x + 1,
(y + 1) * numVertsAround + x);
// Make triangle 2 of quad.
vertexInfo.addTriangle(
(y + 1) * numVertsAround + x,
(y + 0) * numVertsAround + x + 1,
(y + 1) * numVertsAround + x + 1);
}
}
if (opt_matrix) {
vertexInfo.reorient(opt_matrix);
}
return vertexInfo;
};
/**
* Creates a sphere.
* The created sphere has position, normal and uv streams.
*
* @param {!o3d.Pack} pack Pack to create sphere elements in.
* @param {!o3d.Material} material to use.
* @param {number} radius radius of the sphere.
* @param {number} subdivisionsAxis number of steps around the sphere.
* @param {number} subdivisionsHeight number of vertically on the sphere.
* @param {!o3djs.math.Matrix4} opt_matrix A matrix by which to multiply
* all the vertices.
* @return {!o3d.Shape} The created sphere.
*
* @see o3d.Pack
* @see o3d.Shape
*/
o3djs.primitives.createSphere = function(pack,
material,
radius,
subdivisionsAxis,
subdivisionsHeight,
opt_matrix) {
var vertexInfo = o3djs.primitives.createSphereVertices(
radius,
subdivisionsAxis,
subdivisionsHeight,
opt_matrix);
return vertexInfo.createShape(pack, material);
};
/**
* Array of the indices of corners of each face of a cube.
* @private
* @type {!Array.<!Array.<number>>}
*/
o3djs.primitives.CUBE_FACE_INDICES_ = [
[3, 7, 5, 1],
[0, 4, 6, 2],
[6, 7, 3, 2],
[0, 1, 5, 4],
[5, 7, 6, 4],
[2, 3, 1, 0]
];
/**
* Creates the vertices and indices for a cube. The
* cube will be created around the origin. (-size / 2, size / 2)
* The created cube has position, normal and uv streams.
*
* @param {number} size Width, height and depth of the cube.
* @param {!o3djs.math.Matrix4} opt_matrix A matrix by which to multiply
* all the vertices.
* @return {!o3djs.primitives.VertexInfo} The created cube vertices.
*/
o3djs.primitives.createCubeVertices = function(size, opt_matrix) {
var k = size / 2;
var cornerVertices = [
[-k, -k, -k],
[+k, -k, -k],
[-k, +k, -k],
[+k, +k, -k],
[-k, -k, +k],
[+k, -k, +k],
[-k, +k, +k],
[+k, +k, +k]
];
var faceNormals = [
[+1, +0, +0],
[-1, +0, +0],
[+0, +1, +0],
[+0, -1, +0],
[+0, +0, +1],
[+0, +0, -1]
];
var uvCoords = [
[0, 0],
[1, 0],
[1, 1],
[0, 1]
];
var vertexInfo = o3djs.primitives.createVertexInfo();
var positionStream = vertexInfo.addStream(
3, o3djs.base.o3d.Stream.POSITION);
var normalStream = vertexInfo.addStream(
3, o3djs.base.o3d.Stream.NORMAL);
var texCoordStream = vertexInfo.addStream(
2, o3djs.base.o3d.Stream.TEXCOORD, 0);
for (var f = 0; f < 6; ++f) {
var faceIndices = o3djs.primitives.CUBE_FACE_INDICES_[f];
for (var v = 0; v < 4; ++v) {
var position = cornerVertices[faceIndices[v]];
var normal = faceNormals[f];
var uv = uvCoords[v];
// Each face needs all four vertices because the normals and texture
// coordinates are not all the same.
positionStream.addElementVector(position);
normalStream.addElementVector(normal);
texCoordStream.addElementVector(uv);
// Two triangles make a square face.
var offset = 4 * f;