forked from va3c/viewer
-
Notifications
You must be signed in to change notification settings - Fork 32
/
SPECTACLES.js
1779 lines (1407 loc) · 69.3 KB
/
SPECTACLES.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
//The MIT License (MIT)
//
//Copyright (c) 2015 Thornton Tomasetti, Inc.
//
//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.
//base application object containing Spectacles functions and properties
var SPECTACLES = function (divToBind, jsonFileData, callback) {
var SPECT = this; //a local app object we can work with inside of the constructor to avoid 'this' confusion.
SPECT.viewerDiv = divToBind; //a reference to the div for use throughout the app
SPECT.scene = {}; //the THREE.js scene object
SPECT.jsonLoader = {}; //the object that will take care of loading a THREE.js scene from a json file
SPECT.boundingSphere = undefined; //a sphere that encompasses everything in the scene
SPECT.lightingRig = {}; //a parent object to hold our lights. We'll be setting properties with UI
SPECT.orbitControls = {}; //the THREE.js orbit controls object
SPECT.camera = {}; //the THREE.js camera object
SPECT.renderer = {}; //the THREE.js renderer object
SPECT.clock = {}; //the THREE.js clock
SPECT.stats = undefined; //the Stats object
SPECT.backgroundColor = 0xFFFFFF;
//*********************
//*********************
//*** THREE.js setup
//function that sets up the initial THREE.js scene, renderer, camera, orbit controls, etc.
//also creates loading and blackout divs which are shown/hidden as json files are loaded
SPECT.initViewer = function (viewerDiv) {
//append the blackout div and let it respond to the parent div resizing
SPECT.viewerDiv.append("<div class='Spectacles_blackout'></div>");
//function to position and size the blackout div
var setBlackout = function () {
//set the position of the UI relative to the viewer div
var targetDiv = $('.Spectacles_blackout');
//get upper left coordinates of the viewer div - we'll use these for positioning
var win = $(window);
var x = SPECT.viewerDiv.offset().left - win.scrollLeft();
var y = SPECT.viewerDiv.offset().top - win.scrollTop();
//set the position and size
targetDiv.css('left', x.toString() + "px");
targetDiv.css('top', y.toString() + "px");
targetDiv.css('width', SPECT.viewerDiv.width().toString() + "px");
targetDiv.css('height', SPECT.viewerDiv.height().toString() + "px");
};
//call this the first time through
setBlackout();
//respond to resize of the parent div
SPECT.viewerDiv.resize(function () {
setBlackout();
});
//append the loading div and let it respond to the parent div resizing
SPECT.viewerDiv.append("<div class='Spectacles_loading'><h1>Loading Spectacles .json file...</h1></div>");
//function to position the loading div
var setLoading = function () {
//set the position of the UI relative to the viewer div
var targetDiv = $('.Spectacles_loading');
//get upper left coordinates of the viewer div - we'll use these for positioning
var win = $(window);
var x = ((SPECT.viewerDiv.offset().left + SPECT.viewerDiv.outerWidth()) - win.scrollLeft()) / 2;
var y = ((SPECT.viewerDiv.offset().top + SPECT.viewerDiv.outerHeight()) - win.scrollTop()) / 2;
//set the position and size
targetDiv.css('left', x.toString() + "px");
targetDiv.css('top', y.toString() + "px");
};
//call this the first time through
setLoading();
//respond to resize of the parent div
SPECT.viewerDiv.resize(function () {
setLoading();
});
//append a footer. Feel free to strip this out if you'd like to! ;]
SPECT.viewerDiv.append(
"<div class='Spectacles_Footer'>" +
"<img src='https://raw.githubusercontent.com/tt-acm/Spectacles.WebViewer/gh-pages/docs/SPECTACLES_20px.png'> " +
"Spectacles is developed by the <a href='http://core.thorntontomasetti.com/' target='blank'>CORE studio</a>. " +
"Copyright <a href='http://thorntontomasetti.com/' target='blank'>Thornton Tomasetti</a> 2015." +
"</div>");
//function to position footer
var setFooter = function(){
//set the position of the UI relative to the viewer div
var targetDiv = $('.Spectacles_Footer');
//get lower right coordinates of the viewer div - we'll use these for positioning
var win = $(window);
var x = SPECT.viewerDiv.offset().left - win.scrollLeft();
var y = (SPECT.viewerDiv.offset().top - win.scrollTop()) + SPECT.viewerDiv.height();
//set the position
targetDiv.css('left', x.toString() + "px");
targetDiv.css('top', (y - 25).toString() + "px");
};
//call the first time through
setFooter();
//respond to resize of the parent div
SPECT.viewerDiv.resize(function () {
setFooter();
});
//empty scene
SPECT.scene = new THREE.Scene();
//set up the THREE.js div and renderer
SPECT.container = viewerDiv;
SPECT.renderer = new THREE.WebGLRenderer(
{
maxLights: 10,
antialias: true
}
);
SPECT.renderer.setClearColor(SPECT.backgroundColor, 1.0);
SPECT.renderer.setSize(viewerDiv.innerWidth(), viewerDiv.innerHeight());
SPECT.renderer.shadowMapEnabled = true;
SPECT.container.append(SPECT.renderer.domElement);
//set up the camera and orbit controls
SPECT.camera = new THREE.PerspectiveCamera(45, viewerDiv.innerWidth() / viewerDiv.innerHeight(), 1, 1000000);
SPECT.camera.position.set(1000, 1000, 1000);
SPECT.orbitControls = new THREE.OrbitControls(SPECT.camera, SPECT.renderer.domElement);
SPECT.orbitControls.target.set(0, 100, 0);
//a clock. the camera uses this
SPECT.clock = new THREE.Clock();
//respond to resize
viewerDiv.resize(function () {
var WIDTH = viewerDiv.innerWidth(),
HEIGHT = viewerDiv.innerHeight();
SPECT.renderer.setSize(WIDTH, HEIGHT);
SPECT.orbitControls.object.aspect = WIDTH / HEIGHT;
SPECT.orbitControls.object.updateProjectionMatrix();
});
//respond to window resize and scrolling. when the window resizes, sometimes it moves our parent div ... and all of our
//children need to be repositioned (maybe I'm just horrible with CSS?). On a resize, trigger the resize
//event on our parent DIV, which should reposition all of the children.
window.addEventListener('resize', function () {
SPECT.viewerDiv.resize();
});
window.addEventListener('scroll', function () {
SPECT.viewerDiv.resize();
});
//call the render function - this starts the webgl render loop
SPECT.render();
};
//function that starts the THREE.js renderer
SPECT.render = function () {
if (SPECT.stats !== undefined) {
SPECT.stats.update();
}
var delta = SPECT.clock.getDelta();
SPECT.orbitControls.update(delta); //getting a warning here - look into it
requestAnimationFrame(SPECT.render); // same here - look into this warning
SPECT.renderer.render(SPECT.scene, SPECT.orbitControls.object);
};
//*********************
//*********************
//*** TOP LEVEL FUNCTION CALLS
//these are called from outside and enable / disable chunks of application functionality and UI
//**********************TOP LEVEL METHOD!!!**********************************
//this is the method that is called to initialize the dat.GUI user interface.
SPECT.userInterface = function () {
//append a child div to our parent and use the child to host the dat.GUI controller
$('body').append('<div class="Spectacles_uiTarget"></div>');
//function to position the target div relative to the parent
var positionGuiDiv = function () {
//set the position of the UI relative to the viwer div
var targetDiv = $('.Spectacles_uiTarget');
//get upper right coordinates of the viewer div - we'll use these for positioning
var win = $(window);
var x = (SPECT.viewerDiv.offset().left - win.scrollLeft()) + SPECT.viewerDiv.width();
var y = SPECT.viewerDiv.offset().top - win.scrollTop();
//set the position
targetDiv.css('left', (x - 310).toString() + "px");
targetDiv.css('top', y.toString() + "px");
}
positionGuiDiv();
//respond to resize of Parent div
SPECT.viewerDiv.resize(function () {
positionGuiDiv();
});
//initialize the Dat.GUI object, and bind it to our target div
SPECT.uiVariables = new SPECT.UiConstructor();
SPECT.datGui = new dat.GUI({ autoPlace: false });
SPECT.datGui.width = 300;
$('.Spectacles_uiTarget').append(SPECT.datGui.domElement);
//hide the dat.gui close controls button
//$(".close-button").css('visibility', 'hidden');
//Jquery UI stuff - make divs draggable, resizable, etc.
//make the attributes div draggable and resizeable
//$('.Spectacles_attributeList').draggable({ containment: "parent" });
//$('.attributeList').resizable();
};
//**********************TOP LEVEL METHOD!!!**********************************
//call this method to enable the file open UI.
SPECT.openLocalFiles = function () {
//function to position the loading div
var setFileOpen = function () {
//set the position of the UI relative to the viewer div
var targetDiv = $('.Spectacles_openFile');
//get upper left coordinates of the viewer div - we'll use these for positioning
var x = (SPECT.viewerDiv.position().left + SPECT.viewerDiv.width()) / 2;
var y = (SPECT.viewerDiv.position().top + SPECT.viewerDiv.height()) / 2;
//set the position and size
targetDiv.css('left', x.toString() + "px");
targetDiv.css('top', y.toString() + "px");
};
//call this the first time through
setFileOpen();
//respond to resize of the parent div
SPECT.viewerDiv.resize(function () {
setFileOpen();
});
//add a file folder containing the file open button
var fileFolder = SPECT.datGui.addFolder('File');
SPECT.UIfolders.File = fileFolder;
fileFolder.add(SPECT.uiVariables, 'openLocalFile').name("Open Spectacles Files");
//fileFolder.add(SPECT.uiVariables, 'openUrl'); //not working yet - commenting out for now
//make the file open divs draggable
//$(".Spectacles_openFile").draggable({ containment: "parent" });
};
//**********************TOP LEVEL METHOD!!!**********************************
//call this method to enable the Scene UI
SPECT.sceneUI = function () {
//add scene folder
var sceneFolder = SPECT.datGui.addFolder('Scene');
SPECT.UIfolders.Scene = sceneFolder;
//background color control
sceneFolder.addColor(SPECT.uiVariables, 'backgroundColor')
.listen()
.onChange(function (e) {
//set background color
SPECT.renderer.setClearColor(e);
});
//scene fog
//sceneFolder.add(SPECT.uiVariables, 'fog').onChange(function(e){
// Spectacles.lightingRig.setFog(e);
// });
//append a new div to the parent to use for stats visualization
SPECT.viewerDiv.append("<div id='Spectacles_stats' style= 'position: fixed;'></div>");
//set up the stats window
SPECT.stats = new Stats();
SPECT.stats.domElement.style.cssText = 'opacity: 0.5; position: fixed; ';
$('#Spectacles_stats').append(SPECT.stats.domElement);
//position the stats relative to the parent
var positionStats = function () {
//set the position of the UI relative to the viewer div
var targetDiv = $('#Spectacles_stats');
//get lower right coordinates of the viewer div - we'll use these for positioning
//get upper left coordinates of the viewer div - we'll use these for positioning
var win = $(window);
var x = (SPECT.viewerDiv.offset().left - win.scrollLeft()) + SPECT.viewerDiv.width();
var y = (SPECT.viewerDiv.offset().top - win.scrollTop()) + SPECT.viewerDiv.height();
//set the position
targetDiv.css('left', (x - 77).toString() + "px");
targetDiv.css('top', (y - 48).toString() + "px");
};
positionStats();
//hide the stats the first time through.
$('#Spectacles_stats').hide();
//respond to resize
SPECT.viewerDiv.resize(function () {
positionStats();
});
//create the controller in the UI
SPECT.UIfolders.Scene.add(SPECT.uiVariables, 'showStats').onChange(function (e) {
if (e) {
$('#Spectacles_stats').show();
}
else {
$('#Spectacles_stats').hide();
}
});
};
//**********************TOP LEVEL METHOD!!!**********************************
//call this method to enable the Lighting UI
SPECT.lightingUI = function () {
//add a lighting folder
var lightsFolder = SPECT.datGui.addFolder('Lighting');
SPECT.UIfolders.Lighting = lightsFolder;
//light colors
lightsFolder.addColor(SPECT.uiVariables, 'ambientLightColor').onChange(function (e) {
SPECT.lightingRig.setAmbientLightColor(e);
});
lightsFolder.addColor(SPECT.uiVariables, 'pointLightsColor').onChange(function (e) {
SPECT.lightingRig.setPointLightsColor(e);
});
lightsFolder.add(SPECT.uiVariables, 'shadows').onChange(function (e) {
SPECT.lightingRig.shadowsOnOff(e);
});
/*//solar az and alt
lightsFolder.add(SPECT.uiVariables, 'solarAzimuth')
.min(0)
.max(359)
.step(1);
lightsFolder.add(SPECT.uiVariables, 'solarAltitude')
.min(0)
.max(90)
.step(0.1);*/
};
//**********************TOP LEVEL METHOD!!!**********************************
//call this method to enable view and selection UI
SPECT.viewAndSelectionUI = function () {
//add view folder
var viewFolder = SPECT.datGui.addFolder('View_and_Selection');
SPECT.UIfolders.View_and_Selection = viewFolder;
//zoom extents and selected
viewFolder.add(SPECT.uiVariables, 'zoomExtents');
viewFolder.add(SPECT.uiVariables, 'zoomSelected');
//change color of selected object's material
viewFolder.addColor(SPECT.uiVariables, 'selectedObjectColor').onChange(function (e) {
SPECT.attributes.setSelectedObjectColor(e);
});
//initialize object selection and attributes display
SPECT.attributes.init();
};
//**********************TOP LEVEL METHOD!!!**********************************
//call this method to enable the view dropdown UI
SPECT.viewsUI = function () {
SPECT.views.viewsEnabled = true;
if (SPECT.views.viewList.length !== 0) {
SPECT.views.purge();
}
SPECT.views.getViews();
SPECT.views.CreateViewUI();
};
//**********************TOP LEVEL METHOD!!!**********************************
//call this method to enable the view dropdown UI
SPECT.layersUI = function () {
SPECT.layers.layersEnabled = true;
if (SPECT.layers.layerList.length !== 0) {
SPECT.layers.purge();
}
SPECT.layers.getLayers();
SPECT.layers.CreateLayerUI();
};
//*********************
//*********************
//*** JSON Model Loader
//a function to open a file from disk
//found this method here: http://www.javascripture.com/FileReader
SPECT.jsonLoader.openLocalFile = function (event) {
//the input object
var input = event.target;
//a new filereader object and onload callback
var reader = new FileReader();
reader.onload = function () {
//data variable to populate
var data = null;
try { //get the json data
data = $.parseJSON(reader.result);
} catch (e) {
console.log("something went wrong while trying to parse the json data.");
console.log(e);
return;
}
try { //load the json data into the scene
if (data !== null) {
SPECT.jsonLoader.loadSceneFromJson(data);
SPECT.zoomExtents();
SPECT.views.storeDefaultView();
}
} catch (e) {
console.log("something went wrong while trying to load the json data.");
console.log(e);
}
};
//read the file as text - this will fire the onload function above when a user selects a file
reader.readAsText(input.files[0]);
//hide the input form and blackout
$("#OpenLocalFile").css("visibility", "hidden");
$(".Spectacles_loading").show();
};
SPECT.jsonLoader.clearFile = function (event) {
//the input object
var input = event.target;
input.value = "";
};
//function to open a file from url
SPECT.jsonLoader.openUrl = function (url) {
//hide form, show loading
$("#OpenLocalFile").css("visibility", "hidden");
$(".Spectacles_loading").show();
//try to parse the json and load the scene
try {
$.getJSON(url, function (data) {
try {
//call our load scene function
SPECT.jsonLoader.loadSceneFromJson(data);
SPECT.zoomExtents();
SPECT.views.storeDefaultView();
} catch (e) {
$(".Spectacles_loading").hide();
$(".Spectacles_blackout").hide();
console.log("Spectacles load a scene using the json data from the URL you provided! Here's the error:");
console.log(e);
}
})
//some ajax errors don't throw. this catches those errors (i think)
.fail(function(){
$(".Spectacles_loading").hide();
$(".Spectacles_blackout").hide();
console.log("Spectacles could not get a json file from the URL you provided - this is probably a security thing on the json file host's end.");
});
} catch (e) {
$(".Spectacles_loading").hide();
$(".Spectacles_blackout").hide();
console.log("Spectacles could not get a json file from the URL you provided! Here's the error:");
console.log(e);
}
};
//function to hide the 'open file' dialogs.
SPECT.jsonLoader.hideOpenDialog = function () {
//hide the input form
$(".Spectacles_openFile").css("visibility", "hidden");
};
//a function to populate our scene object from a json file
SPECT.jsonLoader.loadSceneFromJson = function (jsonToLoad) {
//show the blackout and loading message
$(".Spectacles_blackout").show();
$(".Spectacles_loading").show();
//restore the initial state of the top level application objects
if (SPECT.attributes.elementList.length > 0) {
SPECT.attributes.purge();
}
if (SPECT.lightingRig.pointLights.length > 0) {
SPECT.lightingRig.purge();
}
if (SPECT.views.viewList.length > 0) {
SPECT.views.purge();
}
if (SPECT.layers.layerList.length > 0) {
SPECT.layers.purge();
}
//parse the JSON into a THREE scene
var loader = new THREE.ObjectLoader();
SPECT.scene = new THREE.Scene();
SPECT.scene = loader.parse(jsonToLoad);
//SPECT.scene.fog = new THREE.FogExp2(0x000000, 0.025);
//call helper functions
SPECT.jsonLoader.makeFaceMaterialsWork();
SPECT.jsonLoader.processSceneGeometry();
SPECT.jsonLoader.computeBoundingSphere();
//SPECT.zoomExtents();
//SPECT.views.storeDefaultView();
//set up the lighting rig
SPECT.lightingRig.createLights();//note - i think we should check to see if there is an active lighting UI and use those colors to init lights if so...
//if those chunks have been enabled by the outside caller, call getViews and getLayers on the scene.
if (SPECT.views.viewsEnabled) {
//TO DO --- if a view with the same name as the open view exists in the incoming file, set that view
SPECT.views.getViews();
SPECT.views.CreateViewUI();
}
if (SPECT.layers.layersEnabled) {
SPECT.layers.getLayers();
SPECT.layers.CreateLayerUI();
}
//hide the blackout
$(".Spectacles_blackout").hide();
$(".Spectacles_loading").hide();
};
//a function to add a textured obj/mtl pair to a scene
SPECT.jsonLoader.addObjMtlToScene = function (objPath, mtlPath, zoomExtentsAfterLoad){
//hide the blackout
$(".Spectacles_blackout").show();
$(".Spectacles_loading").show();
//new objmtl loader object
var loader = new THREE.OBJMTLLoader();
//try to load the pair
loader.load(objPath, mtlPath,
function(loadedObj){
//we need to mirror the objects coming in around the X axis and the Z
var mat = (new THREE.Matrix4()).identity();
mat.elements[0] = -1;
mat.elements[10] = -1;
//process the loaded geometry - make sure faces are 2 sided, merge vertices and compute, etc
for(var i=0; i<loadedObj.children.length; i++){
if(loadedObj.children[i] instanceof THREE.Mesh){
//apply the matrix to accurately position the mesh
loadedObj.children[i].geometry.applyMatrix(mat);
//replace phong material with Lambert. Phonga don't play so nice with our lighting setup
var lambert = new THREE.MeshLambertMaterial();
lambert.map = loadedObj.children[i].material.map;
loadedObj.children[i].material = lambert;
//set up for transparency
loadedObj.children[i].material.side = 2;
loadedObj.children[i].material.transparent = true;
loadedObj.children[i].material.opacity = 1;
}
if(loadedObj.children[i] instanceof THREE.Object3D){
//loop over the children of the object
for(var j=0; j<loadedObj.children[i].children.length; j++){
//apply the matrix to accurately position the mesh
loadedObj.children[i].children[j].geometry.applyMatrix(mat);
//replace phong material with Lambert. Phonga don't play so nice with our lighting setup
var lambert = new THREE.MeshLambertMaterial();
lambert.map = loadedObj.children[i].children[j].material.map;
loadedObj.children[i].children[j].material = lambert;
//set up for transparency
loadedObj.children[i].children[j].material.side = 2;
loadedObj.children[i].children[j].transparent = true;
loadedObj.children[i].children[j].opacity = 1;
}
}
}
//add our loaded object to the scene
SPECT.scene.add(loadedObj);
//update lights
SPECT.jsonLoader.computeBoundingSphere();
SPECT.lightingRig.updateLights();
//zoom extents?
if(zoomExtentsAfterLoad) { SPECT.zoomExtents(); }
//hide the blackout
$(".Spectacles_blackout").hide();
$(".Spectacles_loading").hide();
},
// Function called when downloads progress
function ( xhr ) {
//console.log( (xhr.loaded / xhr.total * 100) + '% loaded' );
},
// Function called when downloads error
function ( er ) {
//console.log( 'An error happened' );
}
);
};
//call this function to set a geometry's face material index to the same index as the face number
//this lets meshfacematerials work - the json loader only gets us part of the way there (I think we are missing something when we create mesh faces...)
SPECT.jsonLoader.makeFaceMaterialsWork = function () {
for (var i = 0, iLen = SPECT.scene.children.length, items; i < iLen; i++) {
items = SPECT.scene.children;
if (items[i].hasOwnProperty("geometry")) {
//the object to revise
var geo = items[i].geometry;
var currentMat = items[i].material;
var userData = items[i].userData;
//if this is a face materials object, make all of the mesh faces point to the correct material
if (currentMat.hasOwnProperty("materials") && userData.hasOwnProperty("Spectacles_FaceColorIndexes")) {
//get the 'Spectacles_FaceColorIndexes' string out of the mesh's user data object,
//and break it into an array of face material indexes
var faceColors = userData.Spectacles_FaceColorIndexes.split(",");
//loop over the faces in the geometry and make the face.materialIndex reference the face's index
for (var j in geo.faces) {
geo.faces[j].materialIndex = faceColors[j];
}
//tell three.js to update the element in the render loop
geo.elementsNeedUpdate = true;
//remove the Spectacles_FaceColorIndexes property from the userdata object
delete userData['Spectacles_FaceColorIndexes'];
}
}
}
};
//function that loops over the geometry in the scene and makes sure everything
//renders correctly and can be selected
SPECT.jsonLoader.processSceneGeometry = function () {
//get all of the items in the scene
items = SPECT.scene.children;
//loop over all of the elements and process any geometry objects
for (var i = 0, iLen = SPECT.scene.children.length, items; i < iLen; i++) {
//if this is a single mesh (like ones that come from grasshopper), process the geometry and add the
//element to the attributes elements list so selection works.
if (items[i].hasOwnProperty("geometry")) {
//three.js stuff
items[i].geometry.mergeVertices();
items[i].geometry.computeFaceNormals();
items[i].geometry.computeVertexNormals();
items[i].castShadow = true;
items[i].receiveShadow = true;
//add element to our list of elements that can be selected
//items[i].material.transparent = true;
//items[i].material.opacity = 1.0;
SPECT.attributes.elementList.push(items[i]);
}
//if this is an object that contains multiple meshes (like the objects that come from Revit), process the
//children meshes so they render correctly, and add the child to the attributes.elementList
else if (items[i].children.length > 0) {
//let the objects cast and receive shadows
items[i].castShadow = true;
items[i].receiveShadow = true;
//the children to loop over
var itemsChildren = items[i].children;
for (var k = 0, kLen = itemsChildren.length; k < kLen; k++) {
if (itemsChildren[k].hasOwnProperty("geometry")) {
itemsChildren[k].geometry.mergeVertices();
itemsChildren[k].geometry.computeFaceNormals();
itemsChildren[k].geometry.computeVertexNormals();
itemsChildren[k].material.side = 2;
itemsChildren[k].castShadow = true;
itemsChildren[k].receiveShadow = true;
//itemsChildren[k].material.transparent = true;
//itemsChildren[k].material.opacity = 1.0;
SPECT.attributes.elementList.push(itemsChildren[k]);
}
}
}
}
};
//function to compute the bounding sphere of the model
//we use this for the zoomExtents function and in the createLights function below
SPECT.jsonLoader.computeBoundingSphere = function () {
//loop over the children of the THREE scene, merge them into a mesh,
//and compute a bounding sphere for the scene
var geo = new THREE.Geometry();
SPECT.scene.traverse(function (child) {
if (child instanceof THREE.Mesh) {
geo.merge(child.geometry);
}
});
geo.computeBoundingSphere();
//expand the scope of the bounding sphere
SPECT.boundingSphere = geo.boundingSphere;
//for debugging - show the sphere in the scene
//var sphereGeo = new THREE.SphereGeometry(geo.boundingSphere.radius);
//var sphereMesh = new THREE.Mesh(sphereGeo, new THREE.MeshLambertMaterial({color: 0xffffff, transparent: true, opacity: 0.25}));
//sphereMesh.position.set(geo.boundingSphere.center.x,geo.boundingSphere.center.y,geo.boundingSphere.center.z);
//SPECT.scene.add(sphereMesh);
};
//zoom extents function. we call this when we load a file (and from the UI), so it shouldn't be in the UI constructor
SPECT.zoomExtents = function () {
if (SPECT.boundingSphere === undefined) SPECT.computeBoundingSphere();
//get the radius of the sphere and use it to compute an offset. This is a mashup of theo's method
//and the one we use in platypus
var r = SPECT.boundingSphere.radius;
var offset = r / Math.tan(Math.PI / 180.0 * SPECT.orbitControls.object.fov * 0.5);
var vector = new THREE.Vector3(0, 0, 1);
var dir = vector.applyQuaternion(SPECT.orbitControls.object.quaternion);
var newPos = new THREE.Vector3();
dir.multiplyScalar(offset * 1.25);
newPos.addVectors(SPECT.boundingSphere.center, dir);
SPECT.orbitControls.object.position.set(newPos.x, newPos.y, newPos.z);
SPECT.orbitControls.target = new THREE.Vector3(SPECT.boundingSphere.center.x, SPECT.boundingSphere.center.y, SPECT.boundingSphere.center.z);
};
//set background color function. we need this at the top level so a user can set the color of her (embedded) viewer without
//editing our library or using our UI.
SPECT.setBackgroundColor = function (hexColor) {
//set top level app variable
SPECT.backgroundColor = hexColor;
//update renderer
SPECT.renderer.setClearColor(SPECT.backgroundColor);
//update internal variable
SPECT.uiVariables.backgroundColor = SPECT.backgroundColor;
};
//Top level function to open a json file - As requested by Mostapha. Essentially a wrapper for Spectacles.jsonLoader.loadSceneFromJson
SPECT.loadNewModel = function (jsonData) {
SPECT.jsonLoader.loadSceneFromJson(jsonData);
};
//*********************
//*********************
//*** Lighting
//ambient light for the scene
SPECT.lightingRig.ambientLight = {};
//a spotlight representing the sun
SPECT.lightingRig.sunLight = {};
//an array of point lights to provide even coverage of the scene
SPECT.lightingRig.pointLights = [];
//function that creates lights in the scene
SPECT.lightingRig.createLights = function () {
// create ambient light
SPECT.lightingRig.ambientLight = new THREE.AmbientLight(0x696969);
SPECT.scene.add(SPECT.lightingRig.ambientLight);
//using the bounding sphere calculated above, get a numeric value to position the lights away from the center
var offset = SPECT.boundingSphere.radius * 2;
//get the center of the bounding sphere. we'll use this to center the rig
var center = SPECT.boundingSphere.center;
//create a series of pointlights
//directly above
var pointA = new THREE.PointLight(0x666666, 1, 0);
pointA.position.set(center.x, center.y + offset, center.z);
pointA.castShadow = false;
SPECT.scene.add(pointA);
SPECT.lightingRig.pointLights.push(pointA);
//directly below
var pointB = new THREE.PointLight(0x666666, 0.66, 0);
pointB.position.set(center.x, center.y - offset, center.z);
pointB.castShadow = false;
SPECT.scene.add(pointB);
SPECT.lightingRig.pointLights.push(pointB);
//4 from the cardinal directions, at roughly 45deg
var pointC = new THREE.PointLight(0x666666, 0.33, 0);
pointC.position.set(center.x + offset, center.y, center.z);
pointC.castShadow = false;
SPECT.scene.add(pointC);
SPECT.lightingRig.pointLights.push(pointC);
var pointD = new THREE.PointLight(0x666666, 0.33, 0);
pointD.position.set(center.x, center.y, center.z + offset);
pointD.castShadow = false;
SPECT.scene.add(pointD);
SPECT.lightingRig.pointLights.push(pointD);
var pointE = new THREE.PointLight(0x666666, 0.33, 0);
pointE.position.set(center.x - offset, center.y, center.z);
pointE.castShadow = false;
SPECT.scene.add(pointE);
SPECT.lightingRig.pointLights.push(pointE);
var pointF = new THREE.PointLight(0x666666, 0.33, 0);
pointF.position.set(center.x, center.y, center.z - offset);
pointF.castShadow = false;
SPECT.scene.add(pointF);
SPECT.lightingRig.pointLights.push(pointF);
//directional light - the sun
var light = new THREE.DirectionalLight(0xffffff, 1);
light.position.set(center.x + offset, center.y + offset, center.z + offset);
light.target.position.set(center.x, center.y, center.z);
//light.castShadow = true;
light.shadowCameraNear = 1;
light.shadowCameraFar = offset * 2.5;
light.shadowCameraTop = offset * 1.2;
light.shadowCameraRight = offset * 1.2;
light.shadowCameraBottom = offset * -1.2;
light.shadowCameraLeft = offset * -1.2;
light.distance = 0;
light.intensity = 0;
light.shadowBias = 0.001;
light.shadowMapHeight = SPECT.viewerDiv.innerHeight();
light.shadowMapWidth = SPECT.viewerDiv.innerWidth();
light.shadowDarkness = 0.65;
//light.shadowCameraVisible = true;
//add the light to our scene and to our app object
SPECT.lightingRig.sunLight = light;
SPECT.scene.add(light);
};
//function to update lights in the scene.
//should be called when new geometry is added to a running scene (.obj for instance)
SPECT.lightingRig.updateLights = function () {
//remove lights from scene
SPECT.scene.remove(this.ambientLight);
SPECT.scene.remove(this.sunLight);
for(var i=0; i<this.pointLights.length; i++){
SPECT.scene.remove(this.pointLights[i]);
}
//call purge and create
this.purge();
this.createLights();
//call update materials - this counts as a deep update for sure!
this.updateSceneMaterials();
};
//function that adjusts the point lights' color
//this is a handler for a UI variable
SPECT.lightingRig.setPointLightsColor = function (col) {
for (var i in SPECT.lightingRig.pointLights) {
SPECT.lightingRig.pointLights[i].color = new THREE.Color(col);
}
};
//function that adjusts the ambient light color
//another handler for a UI element
SPECT.lightingRig.setAmbientLightColor = function (col) {
//console.log(col);
//remove the old ambient light
SPECT.scene.remove(SPECT.lightingRig.ambientLight);
//replace the ambient light with a new one, and add it to the scene
SPECT.lightingRig.ambientLight = new THREE.AmbientLight(new THREE.Color(col));
SPECT.scene.add(SPECT.lightingRig.ambientLight);
};
//function that sets the position of the directional light (the sun)
SPECT.lightingRig.setSunPosition = function (az, alt) {
};
//function to turn the sun on and off
SPECT.lightingRig.shadowsOnOff = function (shad) {
if (shad) {
SPECT.lightingRig.sunLight.castShadow = true;
SPECT.lightingRig.sunLight.intensity = 1;
SPECT.lightingRig.updateSceneMaterials();
}
else {
SPECT.lightingRig.sunLight.castShadow = false;
SPECT.lightingRig.sunLight.intensity = 0;
SPECT.lightingRig.updateSceneMaterials();
}
};
//function that sets the fog amount in the scene
//doesn't seem like this should live in the lighting rig ... if we get more scene variables we may need a sceneFunctions
//object or something.
SPECT.lightingRig.setFog = function (n) {
//if false, set fog to null and return
if (!n) {
SPECT.scene.fog = null;
}
//if true, set up some fog in the scene using the backgound color and the bounding sphere's radius
else {
SPECT.scene.fog = new THREE.FogExp2(new THREE.Color(SPECT.uiVariables.backgroundColor), 0.00025);
}
};
//function to traverse materials in the scene when deep updates are needed - fog on off/ shadows on / off, etc
SPECT.lightingRig.updateSceneMaterials = function () {
SPECT.scene.traverse(function (child) {
if (child instanceof THREE.Mesh) {
child.material.needsUpdate = true;
}
else if (child.type === 'Object3D') {
try {
for (var i = 0; i < child.children.length; i++) {
for (var j = 0; j < child.children[i].children.length; j++) {
child.children[i].children[j].material.needsUpdate = true;
}
}
} catch (e) { }
}
});
};
//function to purge lighting variables. called when we load a new scene
SPECT.lightingRig.purge = function () {
this.ambientLight = {};
this.sunLight = {};
this.pointLights = [];
};