-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathengine.js
1368 lines (1011 loc) · 41.7 KB
/
engine.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as THREE from './three.js/build/three.module.js';
import { STLLoader } from './three.js/examples/jsm/loaders/STLLoader.js';
import { OBJLoader2 } from "./three.js/examples/jsm/loaders/OBJLoader2.js";
import { OrbitControls } from './three.js/examples/jsm/controls/OrbitControls.js';
import Stats from './stats.js/build/stats.module.js';
// This part of the code defines setters and getters and listeners
// Setters and getters were nessecary to make sure that changes to properties
// such as model rotation or wavelength are reflected in the ui and the
// materials.
// Change this if you want the routines (rotationTS and testForA2mRadiusSphere) to calculate faster
// This allows maximal performance, with no rendering to ui in between
// the different calculations
const DEMO_MODE = true;
// Helper function to get a linspaced array between two numbers.
const linspace = (min, max, num) => {
const output = new Array(num);
const delta = (max - min) / (num-1);
for (let i = 0; i < num; i++) {
output[i] = min + delta*i;
}
return output;
};
const waveLengthListeners = new Array();
const [getWaveLength, setWaveLength2] = (function(){
let wavelength = 1;
const getter = function(){
return wavelength;
};
const setter = function(val){
for ( let func of waveLengthListeners ) func(val);
wavelength = val;
};
return [getter, setter];
})();
const phaseChangeListeners = new Array();
const [getPhase, setPhase] = (function(){
let phase = 0;
const getter = function(){
return phase;
};
const setter = function(val){
for (let func of phaseChangeListeners) func(val);
phase = val;
};
return [getter, setter];
})();
const cameraViewChangeListeners = new Array();
const [getPixelArea, setPixelArea] = (function(){
let pixelArea = 1;
const getter = function(){
return pixelArea;
};
const setter = function(val){
for (let func of cameraViewChangeListeners) func(val);
pixelArea = val;
};
return [getter, setter];
})();
const modelRotationListeners = new Array();
const modelPositionListeners = new Array();
// Get the aspect ratio of the canvas.
const getAspectRatio = (canvas) => canvas.clientWidth / canvas.clientHeight
// Helper function to get the camera.
// Can redifine some of the camera properies here.
const getPerspectiveCamera = canvas => {
const fov = 75;
const aspect = getAspectRatio(canvas);
const near = 0.1;
const far = 100;
const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
camera.position.x = 50;
camera.up.set(0,0,1);
return camera;
};
// Helper function to get a Orthographic camera.
const getOrthographicCamera = canvas => {
const width = canvas.clientWidth/10;
const height = canvas.clientHeight/10;
const near = 0.01;
const far = 100;
const camera = new THREE.OrthographicCamera(
width / - 2, width / 2,
height / 2, height / - 2);
camera.position.x = 50;
camera.up.set(0,0,1);
// Calculate new pixel area
const num_pixels = canvas.clientWidth*canvas.clientHeight;
const pixelarea = (width*height)/num_pixels;
// Notifies all pixel area change listeners
// setPixelArea(pixelarea);
return camera;
};
const getCamera = canvas => getOrthographicCamera(canvas);
// This function makes sure that the renderer have the same size as the camera.
// The "false" here makes sure that three.js does not override the size of the canvas itself.
// if the boolean is set to true, it will override the css-style for the canvas.
// This function is also used when we rescale our browser window, as will be seen furter down in the code.
const setRendererSize = (renderer, canvas) => renderer.setSize(canvas.clientWidth, canvas.clientHeight, false);
// Set up all the master elements, such as the scene, renderer and more
// This is the html element in which we draw in. This element can be
// resized and shift aspect ratio.
const canvas = document.getElementById("c");
// The scene is where we have all of our object and lights.
// Since we are working with our own shaders in this demo, no lights will be added
// since the "lights" (the audio source) is defined inside of the shaders.
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x000000); // Set the shader background to black.
// Add a model. There is nothing in it yet,
// it needs to be loaded. This is done asynchronously.
let model;
// The renderer is the element that draws our 3D objects to our canvas.
const renderer = new THREE.WebGLRenderer({canvas});
// This "constant" tells us how many pixels we want the output buffer to consist of. Higher number => higher resolution.
// When rendering we get slightly less than the target number of pixels.
// This value might be changed by the user.
let OUTPUT_TARGET_RESOLUTION = 2000*2000;
const outputBuffer = new THREE.WebGLRenderTarget(canvas.clientWidth, canvas.clientHeight, { minFilter: THREE.LinearFilter, magFilter: THREE.NearestFilter, format: THREE.RGBAFormat, type: THREE.FloatType });
setRendererSize(renderer, canvas); // We want the renderer to have the same size as our canvas
// to get maximal resolution.
setRendererSize(outputBuffer, canvas);
// Get the camera.
const camera = getCamera(canvas);
// Get outputBuffer camera
const outputBufferCamera = new THREE.OrthographicCamera(-1, 1, 1, -1);
outputBufferCamera.up.set(0,0,1);
outputBufferCamera.position.x = 50;
outputBufferCamera.lookAt(0,0,0);
outputBufferCamera.updateMatrixWorld();
outputBufferCamera.updateProjectionMatrix();
const outputBufferCameraHelper = new THREE.CameraHelper(outputBufferCamera);
scene.add(outputBufferCameraHelper);
outputBufferCameraHelper.update();
// Add orbit controls to the camera
const controls = new OrbitControls( camera, renderer.domElement );
controls.autoRotate = false;
controls.update();
// If we change the controls by mouse or arrows, make sure to rerender.
controls.addEventListener("change", () => renderer.render(scene, camera));
// Add stats. Shows framerate.
const stats = new Stats();
stats.showPanel(0);
document.body.appendChild(stats.dom);
stats.dom.style.cssText = 'position:fixed;bottom:0;left:0;cursor:pointer;opacity:0.9;z-index:10000'
// Boolean that is able to be set by user. Toggles animation of the phase.
let animatePhase = false;
// Animation loop for the orbit controls, and pretty much everything
const animate = (time) => {
stats.begin();
if (controls.autoRotate || animatePhase) {
if (model && animatePhase) setPhase(time/1000);
if ( controls.autoRotate ) controls.update();
renderer.render(scene, camera);
}
stats.end();
requestAnimationFrame(animate);
};
animate();
// If a model changes material we need to repaint the scene.
const replaceMaterial = (model, material) => {
model.material = material;
renderer.render(scene, camera);
};
// Function to give the model a phase material. This material is
// "sensitive" to changes in the aucustic phase.
const phaseMaterial = (function(){
// Playground for the different shaders
// Mostly taken from
// https://dev.to/maniflames/creating-a-custom-shader-in-threejs-3bhi
// https://aerotwist.com/tutorials/an-introduction-to-shaders-part-2/
const vertexShader = `
varying vec3 vNormal;
varying vec3 vUv;
void main() {
// set the vNormal value with
// the attribute value passed
// in by Three.js
vNormal = normal;
vUv = position;
gl_Position = projectionMatrix *
modelViewMatrix *
vec4(position, 1.0);
}
`;
const fragmentShader = `
varying vec3 vNormal;
varying vec3 vUv;
uniform mat4 inverseRotationMatrix;
uniform float lambda;
uniform float phase;
void main() {
// calc the dot product and clamp
// 0 -> 1 rather than -1 -> 1
vec4 light4 = vec4(1.0, 0.0, 0.0, 1.0);
// Rotate
light4 = inverseRotationMatrix * light4;
vec3 light = vec3(light4);
// ensure it's normalized
light = normalize(light);
// Dot between vUv and the "light" gives the z-distance into the model
// Multiply by 2 to get the phase after reflection
float prod = mod(2.0 * (dot(vUv, light) / lambda) + phase, 1.0);
gl_FragColor = vec4(prod, // R
prod, // G
prod, // B
1.0); // A
}
`;
let inverseRotationMatrix = new THREE.Matrix4();
const customMaterial = new THREE.ShaderMaterial({
uniforms: {
lambda: {type: 'float', value: 1.0},
phase: {type: 'float', value: 0.0},
inverseRotationMatrix: {type: 'mat4', value: inverseRotationMatrix}
},
fragmentShader: fragmentShader,
vertexShader: vertexShader
});
// This material is intrested in knowing about changes to
// + model rotation
// + Wavelength
// + Changes to the phase
waveLengthListeners.push((newWaveLength) => {
customMaterial.uniforms.lambda.value = newWaveLength;
});
phaseChangeListeners.push((newPhase) => {
customMaterial.uniforms.phase.value = newPhase;
});
modelRotationListeners.push((x,y,z) => {
const rotation = new THREE.Euler(-x,-y,-z, 'ZYX');
inverseRotationMatrix.makeRotationFromEuler(rotation);
});
return customMaterial;
})();
const intensityMaterial = (function(){
const vertexShader = `
varying vec3 vNormal;
varying vec3 vUv;
void main() {
// set the vNormal value with
// the attribute value passed
// in by Three.js
vNormal = normal;
vUv = position;
gl_Position = projectionMatrix *
modelViewMatrix *
vec4(position, 1.0);
}
`;
const fragmentShader = `
varying vec3 vNormal;
varying vec3 vUv;
uniform mat4 inverseRotationMatrix;
void main() {
// calc the dot product and clamp
// 0 -> 1 rather than -1 -> 1
vec4 light4 = vec4(1.0, 0.0, 0.0, 1.0);
// Rotate
light4 = inverseRotationMatrix * light4;
vec3 light = vec3(light4);
// ensure it's normalized
light = normalize(light);
// calculate the dot product of
// the light to the vertex normal
// Since they are both normalized, this will equal
// cos(theta), where theta is the angle between the
// light and the vertex normal
float prod = dot(normalize(vNormal), light);
gl_FragColor = vec4(prod, // R
prod, // G
prod, // B
1.0); // A
}
`;
let inverseRotationMatrix = new THREE.Matrix4();
const customMaterial = new THREE.ShaderMaterial({
uniforms: {
inverseRotationMatrix: {type: 'mat4', value: inverseRotationMatrix}
},
fragmentShader: fragmentShader,
vertexShader: vertexShader
});
// This material needs to know about changes in model rotation.
modelRotationListeners.push((x,y,z) => {
const rotation = new THREE.Euler(-x,-y,-z, 'ZYX');
inverseRotationMatrix.makeRotationFromEuler(rotation);
});
return customMaterial;
})();
const mixMaterial = (function() {
const vertexShader = `
varying vec3 vNormal;
varying vec3 vUv;
void main() {
// set the vNormal value with
// the attribute value passed
// in by Three.js
vNormal = normal;
vUv = position;
gl_Position = projectionMatrix *
modelViewMatrix *
vec4(position, 1.0);
}
`;
const fragmentShader = `
varying vec3 vNormal;
varying vec3 vUv;
uniform mat4 inverseRotationMatrix;
uniform float lambda;
uniform float phase;
void main() {
// calc the dot product and clamp
// 0 -> 1 rather than -1 -> 1
vec4 light4 = vec4(1.0, 0.0, 0.0, 1.0);
// Rotate
light4 = inverseRotationMatrix * light4;
vec3 light = vec3(light4);
// ensure it's normalized
light = normalize(light);
// Intensity is the cos(theta) between the "light" and the normal
// The phase is the z distance traveled by the "light" times 2 modulo 1.
float intensity = dot(normalize(vNormal), light);
float phase = mod(2.0 * (dot(vUv, light) / lambda) + phase, 1.0);
gl_FragColor = vec4(intensity, // R
phase, // G
0.0, // dot(vUv, light), // B
1.0); // A
}`;
const inverseRotationMatrix = new THREE.Matrix4();
const customMaterial = new THREE.ShaderMaterial({
uniforms: {
lambda: {type: 'float', value: getWaveLength()},
inverseRotationMatrix: {type: 'mat4', value: inverseRotationMatrix},
phase: {type: 'float', value: getPhase()}
},
fragmentShader: fragmentShader,
vertexShader: vertexShader
});
// Bind some functions that change the material when the model changes
// The material needs to know about changes in wavelength,
// phase and model rotation.
waveLengthListeners.push((newWaveLength) => {
customMaterial.uniforms.lambda.value = newWaveLength;
});
phaseChangeListeners.push((newPhase) => {
customMaterial.uniforms.phase.value = newPhase;
});
modelRotationListeners.push((x,y,z) => {
const rotation = new THREE.Euler(-x,-y,-z, 'ZYX');
inverseRotationMatrix.makeRotationFromEuler(rotation);
});
return customMaterial;
}
)();
const complexMaterial = (function() {
const vertexShader = `
varying vec3 vNormal;
varying vec3 vUv;
void main() {
// set the vNormal value with
// the attribute value passed
// in by Three.js
vNormal = normal;
vUv = position;
gl_Position = projectionMatrix *
modelViewMatrix *
vec4(position, 1.0);
}
`;
const fragmentShader = `
#define M_PI 3.1415926535897932384626433832795
varying vec3 vNormal;
varying vec3 vUv;
uniform mat4 inverseRotationMatrix;
uniform float lambda;
uniform float phase;
void main() {
// calc the dot product and clamp
// 0 -> 1 rather than -1 -> 1
vec4 light4 = vec4(1.0, 0.0, 0.0, 1.0);
// Rotate
light4 = inverseRotationMatrix * light4;
vec3 light = vec3(light4);
// ensure it's normalized
light = normalize(light);
// Intensity is the cos(theta) between the "light" and the normal
// float intensity = max(0.0, dot(normalize(vNormal), light));
// but in the monostatic case this is already "handled" by the projection
float intensity = 1.0;
// if you want to emphasize which areas that are actually lighted in the moving view
// you can uncomment the following lines. Note that this does not affect the result
/*
if (dot(vNormal, light) >= 0.0) {
intensity = 1.0;
}
else {
intensity = 0.0;
}
*/
// The angle is the distance the sound travels, times 2 pi divided by wavelength
float angle = 4. * M_PI * dot(vUv, light) / lambda + phase;
gl_FragColor = vec4(intensity * cos(angle), // R
intensity * sin(angle), // G
0.0, // dot(vUv, light), // B
1.0); // A
}`;
const inverseRotationMatrix = new THREE.Matrix4();
const customMaterial = new THREE.ShaderMaterial({
uniforms: {
lambda: {type: 'float', value: getWaveLength()},
inverseRotationMatrix: {type: 'mat4', value: inverseRotationMatrix},
phase: {type: 'float', value: getPhase()}
},
fragmentShader: fragmentShader,
vertexShader: vertexShader
});
// Bind some functions that change the material when the model changes
// The material needs to know about changes in wavelength,
// phase and model rotation.
waveLengthListeners.push((newWaveLength) => {
customMaterial.uniforms.lambda.value = newWaveLength;
});
phaseChangeListeners.push((newPhase) => {
customMaterial.uniforms.phase.value = newPhase;
});
modelRotationListeners.push((x,y,z) => {
const rotation = new THREE.Euler(-x,-y,-z, 'ZYX');
inverseRotationMatrix.makeRotationFromEuler(rotation);
});
return customMaterial;
}
)();
// If we switch model, set the material to the current material
// current material changes based on UI input.
// set default to phase material.
let currentMaterial = complexMaterial;
// Set camera view based on width and height.
const setCameraView = (camera, width, height) => {
camera.left = width / -2;
camera.right = width / 2;
camera.top = height / 2;
camera.bottom = height / -2;
camera.zoom = 1;
camera.updateProjectionMatrix();
};
// Update the camera to fit model
const fitCameraToModelFunction = (camera, canvas) => {
// Reset model position
setModelPosition(0,0,0);
// Make sure camera looks at the model
setCameraLookAt(camera, 0,0,0);
// Find the boundingbox
let bbh = new THREE.BoxHelper(model, 0xffff00);
// Get the dimensions of the bounding box
bbh.geometry.computeBoundingBox();
let boundingBox = bbh.geometry.boundingBox;
let width = boundingBox.max.y - boundingBox.min.y;
let height = boundingBox.max.z - boundingBox.min.z;
// Compare aspect ratios.
// If the model aspect ratio (w/h) is greater than the camera aspect ratio
// set the camera height to be equal to the bounding box height.
if (canvas !== undefined) {
const aspectRatio = canvas.clientWidth/canvas.clientHeight;
const objAspectRatio = width/height;
if (objAspectRatio < aspectRatio) {
// Keep the height
width = aspectRatio * height;
}
else height = width / aspectRatio;
}
// Since I couldnt get the bounding box to not translate while
// rotating the object, the object moves out of camera view by a little bit.
// This scaling ensures that the whole model is in view.
// Sorry for the ugly hack. Please change if (this whole function) if
// you ever figure out how to do this correctly.
const scale = 1.1;
width = width * scale;
height = height * scale;
setCameraView(camera, width, height);
camera.position.set(boundingBox.max.x*scale,0, 0);
};
const renderToBuffer = (camera) => {
// Documentiation on how to read pixels.
// https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/readPixels
// Ultimately, this is done the same way as have been done in following threejs example
// https://threejs.org/examples/?q=read#webgl_read_float_buffer
// There are two places from the example that I have copied shamelessly that
// was key to make this work
// Line 104: https://github.com/mrdoob/three.js/blob/master/examples/webgl_read_float_buffer.html#L104
// Line(s) 202-216: https://github.com/mrdoob/three.js/blob/master/examples/webgl_read_float_buffer.html#L202
resizeOutputBuffer(camera);
// Make sure outputBufferCameraHelper is not visible
const b = outputBufferCameraHelper.visible;
outputBufferCameraHelper.visible = false;
// Render to the rendertarget.
renderer.setRenderTarget(outputBuffer);
renderer.clear(); // Do not know what this line does.
renderer.render(scene, outputBufferCamera);
renderer.setRenderTarget(null);
// Create array for the storing the output of the GPU
let read = new Float32Array(4 * outputBuffer.width * outputBuffer.height);
// Read to the array
renderer.readRenderTargetPixels(outputBuffer, 0, 0, outputBuffer.width, outputBuffer.height, read);
// Reset outputBufferCameraHelper visibility
outputBufferCameraHelper.visible = b;
return read;
};
// Make it possible for the ui to respond to event when someone
// moves the camera. This is useful to update the coordinates for
// a camera controller when someone changes the camera position with mouse.
const addCameraChangeListener = handler => {
controls.addEventListener('change', handler);
}
// Start (or stop) OrbitControls auto rotation around the
// target.
const setAutoRotation = bool => controls.autoRotate = bool;
// Move camera in space. It will still though focus on the same target after
// the move.
const setCameraPosition = (x,y,z) => {
camera.position.set(x,y,z);
controls.update();
}
// Change camera focus and what to orbit around when autorotate.
const setCameraLookAt = (camera, x,y,z) => {
camera.lookAt(x,y,z);
controls.update();
};
// Move the model in the world.
const setModelPosition = (x,y,z) => {
// Update position if the position is changed
if (model.position.x !== x || model.position.y !== y || model.position.z !== z) {
model.position.set(x,y,z);
renderer.render(scene, camera);
}
};
// Rotate the model in the world.
const setModelRotation = (x,y,z) => {
model.rotation.set(x,y,z);
// Let everyone intrested in this change know about it
for (let func of modelRotationListeners) func(x,y,z);
renderer.render(scene, camera);
};
// Set to true if you want to autofit camera to model when rotation is applied.
let autoFitCameraToModel = false;
// Subscribe to changes in rotation of the model if we want to autofit.
modelRotationListeners.push(() => {
if ( autoFitCameraToModel ) fitCameraToModelFunction(camera, canvas);
});
// Sets the target resolution for the outputBuffer.
const setTargetResolution = (val) => {
OUTPUT_TARGET_RESOLUTION = val;
renderOutputBufferCameraInTinyWindow();
}
// Toggle autofit to model for the UI
// Could probably be named better so that the above function can
// have a better name
const autoFitCameraToModelUI = (bool) => {
autoFitCameraToModel = bool;
if (autoFitCameraToModel) {
fitCameraToModelFunction(camera, canvas);
renderer.render(scene, camera);
}
}
// These couple of lines defines a function to execute when the browser
// window is resized.
// If the browser window is resized, our canvas will have a height and width in
// px where we are able to draw. This means that both resolution and aspect
// ratio can change.
window.addEventListener('resize', () => {
// Update camera aspect ratio
const aspectRatio = getAspectRatio(canvas);
// Keep the height
const height = camera.top - camera.bottom;
const width = height * aspectRatio;
// If we have enabled autoFitCameraToModel then we let the fitCameraToModelFunction take
// take over.
// Else we only update the camera
if ( autoFitCameraToModel ) fitCameraToModelFunction(camera, canvas);
else setCameraView(camera, width, height);
// Get the new resolution of the view and give that to the renderer
setRendererSize(renderer, canvas);
// Update the buffer
outputBuffer.setSize(canvas.clientWidth, canvas.clientHeight);
// Repaint
renderer.render(scene, camera);
});
const replaceModel = imported_model => {
scene.remove( model );
scene.add(imported_model);
// Repaint
renderer.render(scene, camera);
// Make sure that the model points to our new model.
model = imported_model;
model.geometry.center();
model.position.set(0,0,0);
replaceMaterial(model, currentMaterial);
};
// Upload obj.
const replaceModelOBJ = (uri) => {
const loader = new OBJLoader2();
loader.load(uri, replaceModel);
};
// Upload STL.
const replaceModelSTL = (uri, callback) => {
const loader = new STLLoader();
loader.load(uri, geometry => {
geometry.computeFaceNormals();
geometry.computeVertexNormals();
const material = new THREE.MeshLambertMaterial({color: 0xff5533});
const imported_model = new THREE.Mesh(geometry, material);
replaceModel(imported_model);
callback();
});
};
// Quite uneccessary function. Might delete later
const setWaveLength = wavelength => {
setWaveLength2(wavelength);
renderer.render(scene, camera);
};
// Quite uneccessary function. Might delete later
const setPhaseShift = phase => {
setPhase(phase);
renderer.render(scene, camera);
};
const setPhaseAnimation = bool => animatePhase = bool;
const setMaterialUI = (materialString) => {
switch (materialString) {
case 'phase':
currentMaterial = phaseMaterial;
break;
case 'intensity':
currentMaterial = intensityMaterial;
break;
case 'mix':
currentMaterial = mixMaterial;
break;
case 'complex':
currentMaterial = complexMaterial;
break;
default:
alert('Invalid material');
}
replaceMaterial(model, currentMaterial);
renderOutputBufferCameraInTinyWindow();
renderer.render(scene, camera);
};
/*
This function assumes that the model has the complexMaterial selected.
This function does the following:
1. Make sure that the outputBufferCameraHelper is not visible
2. reads a Float32Array from GPU.
3. Extracts the the four channels from the Float32Array
4. The channel r and g contain I*cos(theta) and I*sin(theta) for
the real and imaginary part of the integrand
5. Sums the real and imaginary parts.
6. Scale the sums with dS/wavelength
7. Gets the norm of the complex number and apply 20*log of the norm.
*/
const getTS = () => {
const helperVisibilityState = outputBufferCameraHelper.visible
outputBufferCameraHelper.visible = false;
// Calculate pixelArea
const cameraWidth = outputBufferCamera.right - outputBufferCamera.left;
const cameraHeight = outputBufferCamera.top - outputBufferCamera.bottom;
const num_pixels = outputBuffer.height * outputBuffer.width;
setPixelArea(cameraWidth * cameraHeight / num_pixels);
const extractFourChannels = (arr) => {
const num_elements = arr.length;
const ch_elements = num_elements/4;
let ch1 = new Float32Array(ch_elements);
let ch2 = new Float32Array(ch_elements);
let ch3 = new Float32Array(ch_elements);
let ch4 = new Float32Array(ch_elements);
for (let i = 0; i < ch_elements; i++) {
const j = i * 4;
ch1[i] = arr[j];
ch2[i] = arr[j+1];
ch3[i] = arr[j+2];
ch4[i] = arr[j+3];
}
return [ch1, ch2, ch3, ch4];
};
// Steps to perform
// Make sure that model is in view
// Make sure that the model has the right material
// Get the output
let read = renderToBuffer(outputBufferCamera);
const [r,g,b,a] = extractFourChannels(read);
// Assume that complexMaterial is selected
let real_part = r;
let imag_part = g;
let sum = (x,y) => x + y;
let real_sum = real_part.reduce(sum, 0);
let imag_sum = imag_part.reduce(sum, 0);
// Multiply with scaling
real_sum *= getPixelArea()/getWaveLength();
imag_sum *= getPixelArea()/getWaveLength();
// Finally, get the absolute value
let TS = 10 * Math.log10(real_sum**2 + imag_sum**2);
outputBufferCameraHelper.visible = helperVisibilityState;
return TS
};
// Add a default model to our scene.
replaceModelSTL('./Russian_fine.stl', () => {
console.log("Default model added to scene");
renderOutputBufferCameraInTinyWindow();
displayOutputBufferCamera(false);
});
// https://stackoverflow.com/a/30800715/1939970
/*
Input: Any javascript object
Creates a JSON file and prompts the user to download the
file.
*/
const downloadObjectAsJson = (exportObj, exportName) => {
var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(exportObj));
var downloadAnchorNode = document.createElement('a');
downloadAnchorNode.setAttribute("href", dataStr);
downloadAnchorNode.setAttribute("download", exportName + ".json");
document.body.appendChild(downloadAnchorNode); // required for firefox
downloadAnchorNode.click();
downloadAnchorNode.remove();
};
// Test for a sphere
const testForA2mRadiusSphere = () => {
// Stuff common to the two modes
// Create the sphere
const geometry = new THREE.SphereGeometry(2, 128, 128);
const material = new THREE.MeshLambertMaterial({color: 0xff5533});
const sphere = new THREE.Mesh(geometry, material);
// Place the model and material to our super cool material
replaceModel(sphere);
// Set model rotation to 0,0,0
setModelRotation(0,0,0);
// Set the material to our cool material
setMaterialUI('complex');
// Make sure that the model fits optimally in the camera
fitCameraToModelFunction(outputBufferCamera);
// Reize outputbuffer
resizeOutputBuffer(outputBufferCamera);
// Set pixel area
const cameraWidth = outputBufferCamera.right - outputBufferCamera.left;
const cameraHeight = outputBufferCamera.top - outputBufferCamera.bottom;
const num_pixels = outputBuffer.height * outputBuffer.width;
setPixelArea(cameraWidth * cameraHeight / num_pixels);
renderer.render(scene, camera);