-
Notifications
You must be signed in to change notification settings - Fork 1
/
three-vr-viewer.js
1873 lines (1350 loc) · 50.9 KB
/
three-vr-viewer.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
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.VRViewer = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
'use strict';
/**
* @author mflux / http://minmax.design
* Based on @mattdesl three-orbit-viewer
*/
var Emitter = require('events');
var WEBVR = require('./thirdparty/webvr');
module.exports = function create() {
var _ref = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var _ref$emptyRoom = _ref.emptyRoom;
var emptyRoom = _ref$emptyRoom === undefined ? true : _ref$emptyRoom;
var _ref$standing = _ref.standing;
var standing = _ref$standing === undefined ? true : _ref$standing;
var _ref$loadControllers = _ref.loadControllers;
var loadControllers = _ref$loadControllers === undefined ? true : _ref$loadControllers;
var _ref$vrButton = _ref.vrButton;
var vrButton = _ref$vrButton === undefined ? true : _ref$vrButton;
var _ref$antiAlias = _ref.antiAlias;
var antiAlias = _ref$antiAlias === undefined ? true : _ref$antiAlias;
var _ref$clearColor = _ref.clearColor;
var clearColor = _ref$clearColor === undefined ? 0x505050 : _ref$clearColor;
var _ref$pathToController = _ref.pathToControllers;
var pathToControllers = _ref$pathToController === undefined ? 'models/obj/vive-controller/' : _ref$pathToController;
var _ref$controllerModelN = _ref.controllerModelName;
var controllerModelName = _ref$controllerModelN === undefined ? 'vr_controller_vive_1_5.obj' : _ref$controllerModelN;
var _ref$controllerTextur = _ref.controllerTextureMap;
var controllerTextureMap = _ref$controllerTextur === undefined ? 'onepointfive_texture.png' : _ref$controllerTextur;
var _ref$controllerSpecMa = _ref.controllerSpecMap;
var controllerSpecMap = _ref$controllerSpecMa === undefined ? 'onepointfive_spec.png' : _ref$controllerSpecMa;
var THREE = _ref.THREE;
var VREffect = require('./thirdparty/vreffect')(THREE);
var VRControls = require('./thirdparty/vrcontrols')(THREE);
var ViveController = require('./thirdparty/vivecontroller')(THREE);
var OBJLoader = require('./thirdparty/objloader')(THREE);
if (WEBVR.isLatestAvailable() === false) {
document.body.appendChild(WEBVR.getMessage());
}
var events = new Emitter();
var container = document.createElement('div');
document.body.appendChild(container);
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 0.1, 10);
scene.add(camera);
if (emptyRoom) {
var room = new THREE.Mesh(new THREE.BoxGeometry(6, 6, 6, 8, 8, 8), new THREE.MeshBasicMaterial({ color: 0x404040, wireframe: true }));
room.position.y = 3;
scene.add(room);
scene.add(new THREE.HemisphereLight(0x606060, 0x404040));
var light = new THREE.DirectionalLight(0xffffff);
light.position.set(1, 1, 1).normalize();
scene.add(light);
}
var renderer = new THREE.WebGLRenderer({ antialias: antiAlias });
renderer.setClearColor(clearColor);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.sortObjects = false;
container.appendChild(renderer.domElement);
var controls = new THREE.VRControls(camera);
controls.standing = standing;
var controller1 = new THREE.ViveController(0);
var controller2 = new THREE.ViveController(1);
scene.add(controller1, controller2);
if (loadControllers) {
controller1.standingMatrix = controls.getStandingMatrix();
controller2.standingMatrix = controls.getStandingMatrix();
var loader = new THREE.OBJLoader();
loader.setPath(pathToControllers);
loader.load(controllerModelName, function (object) {
var textureLoader = new THREE.TextureLoader();
textureLoader.setPath(pathToControllers);
var controller = object.children[0];
controller.material.map = textureLoader.load(controllerTextureMap);
controller.material.specularMap = textureLoader.load(controllerSpecMap);
controller1.add(object.clone());
controller2.add(object.clone());
});
}
var effect = new THREE.VREffect(renderer);
if (WEBVR.isAvailable() === true) {
if (vrButton) {
document.body.appendChild(WEBVR.getButton(effect));
}
/*
Sigh.
Some day, when the world is a more trustworthy place, you can be back.
if( autoEnter ){
setTimeout( ()=>effect.requestPresent(), 1000 );
}
*/
}
window.addEventListener('resize', function () {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
effect.setSize(window.innerWidth, window.innerHeight);
events.emit('resize', window.innerWidth, window.innerHeight);
}, false);
var clock = new THREE.Clock();
clock.start();
function animate() {
var dt = clock.getDelta();
effect.requestAnimationFrame(animate);
controller1.update();
controller2.update();
controls.update();
events.emit('tick', dt);
render();
events.emit('render', dt);
}
function render() {
effect.render(scene, camera);
}
function toggleVR() {
effect.isPresenting ? effect.exitPresent() : effect.requestPresent();
}
animate();
return {
scene: scene, camera: camera, controls: controls, renderer: renderer, vrEffect: effect,
controllers: [controller1, controller2],
events: events,
toggleVR: toggleVR
};
};
if (window) {
window.VRViewer = module.exports;
}
},{"./thirdparty/objloader":3,"./thirdparty/vivecontroller":4,"./thirdparty/vrcontrols":5,"./thirdparty/vreffect":6,"./thirdparty/webvr":7,"events":2}],2:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
} else {
// At least give some kind of context to the user
var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
err.context = er;
throw err;
}
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
args = Array.prototype.slice.call(arguments, 1);
handler.apply(this, args);
}
} else if (isObject(handler)) {
args = Array.prototype.slice.call(arguments, 1);
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject(this._events[type]) && !this._events[type].warned) {
if (!isUndefined(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
if (typeof console.trace === 'function') {
// not supported in IE 10
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else if (listeners) {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.prototype.listenerCount = function(type) {
if (this._events) {
var evlistener = this._events[type];
if (isFunction(evlistener))
return 1;
else if (evlistener)
return evlistener.length;
}
return 0;
};
EventEmitter.listenerCount = function(emitter, type) {
return emitter.listenerCount(type);
};
function isFunction(arg) {
return typeof arg === 'function';
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined(arg) {
return arg === void 0;
}
},{}],3:[function(require,module,exports){
'use strict';
/**
* @author mrdoob / http://mrdoob.com/
*/
module.exports = function (THREE) {
THREE.OBJLoader = function (manager) {
this.manager = manager !== undefined ? manager : THREE.DefaultLoadingManager;
this.materials = null;
this.regexp = {
// v float float float
vertex_pattern: /^v\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)/,
// vn float float float
normal_pattern: /^vn\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)/,
// vt float float
uv_pattern: /^vt\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)/,
// f vertex vertex vertex
face_vertex: /^f\s+(-?\d+)\s+(-?\d+)\s+(-?\d+)(?:\s+(-?\d+))?/,
// f vertex/uv vertex/uv vertex/uv
face_vertex_uv: /^f\s+(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)(?:\s+(-?\d+)\/(-?\d+))?/,
// f vertex/uv/normal vertex/uv/normal vertex/uv/normal
face_vertex_uv_normal: /^f\s+(-?\d+)\/(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)\/(-?\d+)(?:\s+(-?\d+)\/(-?\d+)\/(-?\d+))?/,
// f vertex//normal vertex//normal vertex//normal
face_vertex_normal: /^f\s+(-?\d+)\/\/(-?\d+)\s+(-?\d+)\/\/(-?\d+)\s+(-?\d+)\/\/(-?\d+)(?:\s+(-?\d+)\/\/(-?\d+))?/,
// o object_name | g group_name
object_pattern: /^[og]\s*(.+)?/,
// s boolean
smoothing_pattern: /^s\s+(\d+|on|off)/,
// mtllib file_reference
material_library_pattern: /^mtllib /,
// usemtl material_name
material_use_pattern: /^usemtl /
};
};
THREE.OBJLoader.prototype = {
constructor: THREE.OBJLoader,
load: function load(url, onLoad, onProgress, onError) {
var scope = this;
var loader = new THREE.XHRLoader(scope.manager);
loader.setPath(this.path);
loader.load(url, function (text) {
onLoad(scope.parse(text));
}, onProgress, onError);
},
setPath: function setPath(value) {
this.path = value;
},
setMaterials: function setMaterials(materials) {
this.materials = materials;
},
_createParserState: function _createParserState() {
var state = {
objects: [],
object: {},
vertices: [],
normals: [],
uvs: [],
materialLibraries: [],
startObject: function startObject(name, fromDeclaration) {
// If the current object (initial from reset) is not from a g/o declaration in the parsed
// file. We need to use it for the first parsed g/o to keep things in sync.
if (this.object && this.object.fromDeclaration === false) {
this.object.name = name;
this.object.fromDeclaration = fromDeclaration !== false;
return;
}
if (this.object && typeof this.object._finalize === 'function') {
this.object._finalize();
}
var previousMaterial = this.object && typeof this.object.currentMaterial === 'function' ? this.object.currentMaterial() : undefined;
this.object = {
name: name || '',
fromDeclaration: fromDeclaration !== false,
geometry: {
vertices: [],
normals: [],
uvs: []
},
materials: [],
smooth: true,
startMaterial: function startMaterial(name, libraries) {
var previous = this._finalize(false);
// New usemtl declaration overwrites an inherited material, except if faces were declared
// after the material, then it must be preserved for proper MultiMaterial continuation.
if (previous && (previous.inherited || previous.groupCount <= 0)) {
this.materials.splice(previous.index, 1);
}
var material = {
index: this.materials.length,
name: name || '',
mtllib: Array.isArray(libraries) && libraries.length > 0 ? libraries[libraries.length - 1] : '',
smooth: previous !== undefined ? previous.smooth : this.smooth,
groupStart: previous !== undefined ? previous.groupEnd : 0,
groupEnd: -1,
groupCount: -1,
inherited: false,
clone: function clone(index) {
return {
index: typeof index === 'number' ? index : this.index,
name: this.name,
mtllib: this.mtllib,
smooth: this.smooth,
groupStart: this.groupEnd,
groupEnd: -1,
groupCount: -1,
inherited: false
};
}
};
this.materials.push(material);
return material;
},
currentMaterial: function currentMaterial() {
if (this.materials.length > 0) {
return this.materials[this.materials.length - 1];
}
return undefined;
},
_finalize: function _finalize(end) {
var lastMultiMaterial = this.currentMaterial();
if (lastMultiMaterial && lastMultiMaterial.groupEnd === -1) {
lastMultiMaterial.groupEnd = this.geometry.vertices.length / 3;
lastMultiMaterial.groupCount = lastMultiMaterial.groupEnd - lastMultiMaterial.groupStart;
lastMultiMaterial.inherited = false;
}
// Guarantee at least one empty material, this makes the creation later more straight forward.
if (end !== false && this.materials.length === 0) {
this.materials.push({
name: '',
smooth: this.smooth
});
}
return lastMultiMaterial;
}
};
// Inherit previous objects material.
// Spec tells us that a declared material must be set to all objects until a new material is declared.
// If a usemtl declaration is encountered while this new object is being parsed, it will
// overwrite the inherited material. Exception being that there was already face declarations
// to the inherited material, then it will be preserved for proper MultiMaterial continuation.
if (previousMaterial && previousMaterial.name && typeof previousMaterial.clone === "function") {
var declared = previousMaterial.clone(0);
declared.inherited = true;
this.object.materials.push(declared);
}
this.objects.push(this.object);
},
finalize: function finalize() {
if (this.object && typeof this.object._finalize === 'function') {
this.object._finalize();
}
},
parseVertexIndex: function parseVertexIndex(value, len) {
var index = parseInt(value, 10);
return (index >= 0 ? index - 1 : index + len / 3) * 3;
},
parseNormalIndex: function parseNormalIndex(value, len) {
var index = parseInt(value, 10);
return (index >= 0 ? index - 1 : index + len / 3) * 3;
},
parseUVIndex: function parseUVIndex(value, len) {
var index = parseInt(value, 10);
return (index >= 0 ? index - 1 : index + len / 2) * 2;
},
addVertex: function addVertex(a, b, c) {
var src = this.vertices;
var dst = this.object.geometry.vertices;
dst.push(src[a + 0]);
dst.push(src[a + 1]);
dst.push(src[a + 2]);
dst.push(src[b + 0]);
dst.push(src[b + 1]);
dst.push(src[b + 2]);
dst.push(src[c + 0]);
dst.push(src[c + 1]);
dst.push(src[c + 2]);
},
addVertexLine: function addVertexLine(a) {
var src = this.vertices;
var dst = this.object.geometry.vertices;
dst.push(src[a + 0]);
dst.push(src[a + 1]);
dst.push(src[a + 2]);
},
addNormal: function addNormal(a, b, c) {
var src = this.normals;
var dst = this.object.geometry.normals;
dst.push(src[a + 0]);
dst.push(src[a + 1]);
dst.push(src[a + 2]);
dst.push(src[b + 0]);
dst.push(src[b + 1]);
dst.push(src[b + 2]);
dst.push(src[c + 0]);
dst.push(src[c + 1]);
dst.push(src[c + 2]);
},
addUV: function addUV(a, b, c) {
var src = this.uvs;
var dst = this.object.geometry.uvs;
dst.push(src[a + 0]);
dst.push(src[a + 1]);
dst.push(src[b + 0]);
dst.push(src[b + 1]);
dst.push(src[c + 0]);
dst.push(src[c + 1]);
},
addUVLine: function addUVLine(a) {
var src = this.uvs;
var dst = this.object.geometry.uvs;
dst.push(src[a + 0]);
dst.push(src[a + 1]);
},
addFace: function addFace(a, b, c, d, ua, ub, uc, ud, na, nb, nc, nd) {
var vLen = this.vertices.length;
var ia = this.parseVertexIndex(a, vLen);
var ib = this.parseVertexIndex(b, vLen);
var ic = this.parseVertexIndex(c, vLen);
var id;
if (d === undefined) {
this.addVertex(ia, ib, ic);
} else {
id = this.parseVertexIndex(d, vLen);
this.addVertex(ia, ib, id);
this.addVertex(ib, ic, id);
}
if (ua !== undefined) {
var uvLen = this.uvs.length;
ia = this.parseUVIndex(ua, uvLen);
ib = this.parseUVIndex(ub, uvLen);
ic = this.parseUVIndex(uc, uvLen);
if (d === undefined) {
this.addUV(ia, ib, ic);
} else {
id = this.parseUVIndex(ud, uvLen);
this.addUV(ia, ib, id);
this.addUV(ib, ic, id);
}
}
if (na !== undefined) {
// Normals are many times the same. If so, skip function call and parseInt.
var nLen = this.normals.length;
ia = this.parseNormalIndex(na, nLen);
ib = na === nb ? ia : this.parseNormalIndex(nb, nLen);
ic = na === nc ? ia : this.parseNormalIndex(nc, nLen);
if (d === undefined) {
this.addNormal(ia, ib, ic);
} else {
id = this.parseNormalIndex(nd, nLen);
this.addNormal(ia, ib, id);
this.addNormal(ib, ic, id);
}
}
},
addLineGeometry: function addLineGeometry(vertices, uvs) {
this.object.geometry.type = 'Line';
var vLen = this.vertices.length;
var uvLen = this.uvs.length;
for (var vi = 0, l = vertices.length; vi < l; vi++) {
this.addVertexLine(this.parseVertexIndex(vertices[vi], vLen));
}
for (var uvi = 0, l = uvs.length; uvi < l; uvi++) {
this.addUVLine(this.parseUVIndex(uvs[uvi], uvLen));
}
}
};
state.startObject('', false);
return state;
},
parse: function parse(text) {
console.time('OBJLoader');
var state = this._createParserState();
if (text.indexOf('\r\n') !== -1) {
// This is faster than String.split with regex that splits on both
text = text.replace('\r\n', '\n');
}
var lines = text.split('\n');
var line = '',
lineFirstChar = '',
lineSecondChar = '';
var lineLength = 0;
var result = [];
// Faster to just trim left side of the line. Use if available.
var trimLeft = typeof ''.trimLeft === 'function';
for (var i = 0, l = lines.length; i < l; i++) {
line = lines[i];
line = trimLeft ? line.trimLeft() : line.trim();
lineLength = line.length;
if (lineLength === 0) continue;
lineFirstChar = line.charAt(0);
// @todo invoke passed in handler if any
if (lineFirstChar === '#') continue;
if (lineFirstChar === 'v') {
lineSecondChar = line.charAt(1);
if (lineSecondChar === ' ' && (result = this.regexp.vertex_pattern.exec(line)) !== null) {
// 0 1 2 3
// ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
state.vertices.push(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3]));
} else if (lineSecondChar === 'n' && (result = this.regexp.normal_pattern.exec(line)) !== null) {
// 0 1 2 3
// ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
state.normals.push(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3]));
} else if (lineSecondChar === 't' && (result = this.regexp.uv_pattern.exec(line)) !== null) {
// 0 1 2
// ["vt 0.1 0.2", "0.1", "0.2"]
state.uvs.push(parseFloat(result[1]), parseFloat(result[2]));
} else {
throw new Error("Unexpected vertex/normal/uv line: '" + line + "'");
}
} else if (lineFirstChar === "f") {
if ((result = this.regexp.face_vertex_uv_normal.exec(line)) !== null) {
// f vertex/uv/normal vertex/uv/normal vertex/uv/normal
// 0 1 2 3 4 5 6 7 8 9 10 11 12
// ["f 1/1/1 2/2/2 3/3/3", "1", "1", "1", "2", "2", "2", "3", "3", "3", undefined, undefined, undefined]
state.addFace(result[1], result[4], result[7], result[10], result[2], result[5], result[8], result[11], result[3], result[6], result[9], result[12]);
} else if ((result = this.regexp.face_vertex_uv.exec(line)) !== null) {
// f vertex/uv vertex/uv vertex/uv
// 0 1 2 3 4 5 6 7 8
// ["f 1/1 2/2 3/3", "1", "1", "2", "2", "3", "3", undefined, undefined]
state.addFace(result[1], result[3], result[5], result[7], result[2], result[4], result[6], result[8]);
} else if ((result = this.regexp.face_vertex_normal.exec(line)) !== null) {
// f vertex//normal vertex//normal vertex//normal
// 0 1 2 3 4 5 6 7 8
// ["f 1//1 2//2 3//3", "1", "1", "2", "2", "3", "3", undefined, undefined]
state.addFace(result[1], result[3], result[5], result[7], undefined, undefined, undefined, undefined, result[2], result[4], result[6], result[8]);
} else if ((result = this.regexp.face_vertex.exec(line)) !== null) {
// f vertex vertex vertex
// 0 1 2 3 4
// ["f 1 2 3", "1", "2", "3", undefined]
state.addFace(result[1], result[2], result[3], result[4]);
} else {
throw new Error("Unexpected face line: '" + line + "'");
}
} else if (lineFirstChar === "l") {
var lineParts = line.substring(1).trim().split(" ");
var lineVertices = [],
lineUVs = [];
if (line.indexOf("/") === -1) {
lineVertices = lineParts;
} else {
for (var li = 0, llen = lineParts.length; li < llen; li++) {
var parts = lineParts[li].split("/");
if (parts[0] !== "") lineVertices.push(parts[0]);
if (parts[1] !== "") lineUVs.push(parts[1]);
}
}
state.addLineGeometry(lineVertices, lineUVs);
} else if ((result = this.regexp.object_pattern.exec(line)) !== null) {
// o object_name
// or
// g group_name
var name = result[0].substr(1).trim();
state.startObject(name);
} else if (this.regexp.material_use_pattern.test(line)) {
// material
state.object.startMaterial(line.substring(7).trim(), state.materialLibraries);
} else if (this.regexp.material_library_pattern.test(line)) {
// mtl file
state.materialLibraries.push(line.substring(7).trim());
} else if ((result = this.regexp.smoothing_pattern.exec(line)) !== null) {
// smooth shading
// @todo Handle files that have varying smooth values for a set of faces inside one geometry,
// but does not define a usemtl for each face set.
// This should be detected and a dummy material created (later MultiMaterial and geometry groups).
// This requires some care to not create extra material on each smooth value for "normal" obj files.
// where explicit usemtl defines geometry groups.
// Example asset: examples/models/obj/cerberus/Cerberus.obj
var value = result[1].trim().toLowerCase();
state.object.smooth = value === '1' || value === 'on';
var material = state.object.currentMaterial();
if (material) {
material.smooth = state.object.smooth;
}
} else {