-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathraytracing.js
1684 lines (1430 loc) · 54.5 KB
/
raytracing.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
/*
* FYO 2020 - Light dispersion project
* Author: Ondřej Pavela (xpavel34@stud.fit.vutbr.cz)
*/
/*
* wavelengthToColor() function was taken from
* http://scienceprimer.com/javascript-code-convert-light-wavelength-color
*/
function wavelengthToColor(wl) {
let rgb;
if (wl >= 380 && wl < 440) {
rgb = [-1 * (wl - 440) / (440 - 380), 0, 1];
} else if (wl >= 440 && wl < 490) {
rgb = [0, (wl - 440) / (490 - 440), 1];
} else if (wl >= 490 && wl < 510) {
rgb = [0, 1, -1 * (wl - 510) / (510 - 490)];
} else if (wl >= 510 && wl < 580) {
rgb = [(wl - 510) / (580 - 510), 1, 0];
} else if (wl >= 580 && wl < 645) {
rgb = [1, -1 * (wl - 645) / (645 - 580), 0];
} else if (wl >= 645 && wl <= 780) {
rgb = [1, 0, 0];
} else {
rgb = [0, 0, 0];
}
// intensty is lower at the edges of the visible spectrum.
let alpha;
if (wl > 780 || wl < 380) {
alpha = 0;
} else if (wl > 700) {
alpha = (780 - wl) / (780 - 700);
} else if (wl < 420) {
alpha = (wl - 380) / (420 - 380);
} else {
alpha = 1;
}
return rgb;
}
function degToRad(deg) { return math.multiply(math.divide(deg, 180), Math.PI); }
function radToDeg(rad) { return math.divide(math.multiply(rad, 180), Math.PI); }
function normalize(vect) { return math.multiply(vect, (1.0 / math.norm(vect))); }
function crossProduct(point1, point2) { return point1[0] * point2[1] - point1[1] * point2[0]; }
function raySegmentIntersection(ray, start, end) {
var s = math.subtract(end, start);
var uNumerator = crossProduct(math.subtract(start, ray.origin), ray.dir);
var denominator = crossProduct(ray.dir, s);
if (uNumerator == 0 && denominator == 0) {
// They are colinear
// Do they touch? (Are any of the points equal?)
return ray.origin === start || ray.origin === end;
}
if (denominator == 0) {
// lines are paralell
return undefined;
}
var u = uNumerator / denominator;
var t = crossProduct(math.subtract(start, ray.origin), s) / denominator;
if (t >= 0 && (u >= 0) && (u <= 1)) {
return t;
}
return undefined;
}
/*
* Calculate a resulting vector of refraction at surface with 'normal'
* and refractive indices n1 and n2
* Algorithm taken from article:
* https://graphics.stanford.edu/courses/cs148-10-summer/docs/2006--degreve--reflection_refraction.pdf
*/
function refractRay(ray, normal, point, material1, material2) {
let rays = [];
const cosI = -math.dot(normal, ray.dir);
let reflectDir = undefined;
if (math.abs(cosI) == 1.0) {
// Ray is perpendicular, no refraction
rays.push({
ray: new LightRay(point, ray.dir, ray.waves),
TIR: false
});
}
else {
for (const wave of ray.waves) {
const n1 = material1.refractiveIndex(wave.lambda);
const n2 = material2.refractiveIndex(wave.lambda);
const mu = math.divide(n1, n2);
const sin2Phi = math.pow(mu, 2) * (1 - math.pow(cosI, 2));
if (sin2Phi > 1.0) {
if (!reflectDir) reflectDir = math.add(ray.dir, math.multiply(math.multiply(2.0, cosI), normal));
rays.push({
ray: new LightRay(point, reflectDir, [wave]),
TIR: true
});
}
const refractDir = math.add(math.multiply(mu, ray.dir),
math.multiply((math.subtract(mu * cosI, math.sqrt(1 - sin2Phi))), normal));
rays.push({
ray: new LightRay(point, refractDir, [wave]),
TIR: false
});
}
}
return rays;
}
class LightRay {
constructor(origin, dir, waves) {
this.origin = origin;
this.dir = dir;
this.normal = getNormal(this.dir);
this.waves = waves;
this.inside = false;
this.lastEdgeIdx = undefined;
this.lastGeometry = undefined;
this.hovered = false;
this.selected = false;
this.endPointHovered = false;
this.arrowLenght = 50;
this.arrowEndPoint = math.add(this.origin, math.multiply(this.dir, this.arrowLenght));
this.arrowOffset = math.add(this.origin, math.multiply(this.dir, this.arrowLenght - 15));
}
getAngle() {
let angle = math.acos(math.dot(this.dir, [1.0, 0.0]));
if (this.dir[1] < 0) {
angle = -angle;
}
return angle;
}
setAngle(angle) {
this.dir = [Math.cos(angle), Math.sin(angle)];
this.normal = getNormal(this.dir);
this.arrowEndPoint = math.add(this.origin, math.multiply(this.dir, this.arrowLenght));
this.arrowOffset = math.add(this.origin, math.multiply(this.dir, this.arrowLenght - 15));
}
setWavelength(wl) {
this.waves = [{
lambda: wl,
color: PIXI.utils.rgb2hex(wavelengthToColor(wl))
}];
}
setWavelengthRange(min, max, count) {
const stepSize = (max - min) / count;
this.waves = Array(count).fill().map(function (_, idx) {
const wl = min + (idx * stepSize);
return {
lambda: wl,
color: PIXI.utils.rgb2hex(wavelengthToColor(wl))
};
});
}
color() {
return this.waves.length > 1 ? 0xffffff : this.waves[0].color;
}
translate(delta, mousePos) {
if (this.endPointHovered) {
this.dir = normalize(math.subtract(mousePos, this.origin));
this.normal = getNormal(this.dir);
this.arrowEndPoint = math.add(this.origin, math.multiply(this.dir, this.arrowLenght));
this.arrowOffset = math.add(this.origin, math.multiply(this.dir, this.arrowLenght - 15));
$("#ray-angle").val(-radToDeg(this.getAngle()).toFixed(2));
}
else {
this.origin = math.add(this.origin, delta);
this.arrowEndPoint = math.add(this.arrowEndPoint, delta);
this.arrowOffset = math.add(this.arrowOffset, delta);
}
}
pointCheck(point) {
const d1 = math.distance(this.origin, point);
const d2 = math.distance(this.arrowEndPoint, point);
this.endPointHovered = d2 < 25;
return d1 < 25 || this.endPointHovered;
}
draw(gfx) {
drawLine(gfx, 0x00ff00, this.origin, this.arrowEndPoint);
drawPoint(this.origin, gfx, 6, this.selected ? 0x0000ff : 0xffffff, 0xffffff);
const arrowWingsLength = 7;
const p1 = math.add(this.arrowOffset, math.multiply(this.normal, arrowWingsLength));
const p2 = math.subtract(this.arrowOffset, math.multiply(this.normal, arrowWingsLength));
drawLine(gfx, 0x00ff00, this.arrowEndPoint, p1);
drawLine(gfx, 0x00ff00, this.arrowEndPoint, p2);
}
getSegment(length) {
let endPoint = math.add(this.origin, math.multiply(this.dir, length));
return new Line(0x91CF46, this.origin, endPoint);
}
tracePath(geometries) {
const ray = this;
let intersection = undefined;
for (let i = 0; i < geometries.length; i++) {
// Ignore last solved geometry
if (ray.lastGeometry != geometries[i]) {
const result = geometries[i].rayIntersection(ray);
if (intersection != undefined) {
if (result != undefined && result.t < intersection.t) {
intersection = result;
}
} else {
intersection = result;
}
}
}
if (intersection) {
const result = intersection.geometry.solveRay(ray, intersection);
let lineSegments = result.lineSegments;
//Recursively trace emergent rays
for (const emergentRay of result.emergentRays) {
lineSegments = lineSegments.concat(emergentRay.tracePath(geometries));
}
return lineSegments;
}
else {
// No intersection found, TODO: maybe fix this and find intersection with canvas boundaries
const rayColor = this.waves.length > 1 ? 0xffffff : this.waves[0].color;
const endPoint = math.add(this.origin, math.multiply(this.dir, 1000.0));
return [new Line(rayColor, this.origin, endPoint)];
}
}
}
function drawPoint(point, gfx, size = 5, color = 0xe74c3c, edgeColor = 0xffff00) {
gfx.lineStyle(2, edgeColor, 1);
gfx.beginFill(color); // Red
gfx.drawCircle(point[0], point[1], size);
gfx.endFill();
}
function drawLine(gfx, color, p1, p2) {
gfx.lineStyle(2, color, 1);
gfx.moveTo(...p1);
gfx.lineTo(...p2);
}
function drawPolyline(gfx, color, points) {
gfx.lineStyle(2, color, 1);
gfx.moveTo(...points[0]);
for (let i = 1; i < points.length; i++) {
gfx.lineTo(...points[i]);
gfx.moveTo(...points[i]);
}
}
function getNormal(vec2D) {
return normalize([-vec2D[1], vec2D[0]]);
}
function getSegmentVector(p1, p2) { return normalize(math.subtract(p2, p1)); }
class Material {
static defaultCurvePoints = [
[380, 1.9],
[400, 1.7],
[500, 1.5],
[600, 1.45],
[700, 1.41],
[740, 1.39]
];
constructor(curvePoints = undefined) {
this.curvePoints = curvePoints ? new Map(curvePoints) : new Map(Material.defaultCurvePoints);
this.modifiable = true;
}
refractiveIndex(wavelength) {
// Dispersion curve is just a spline based on selected curve points
// Find interval
const curvePoints = this.curvePoints.entries();
let p1 = undefined;
for (const p2 of curvePoints) {
if (p1 && wavelength >= p1[0] && wavelength <= p2[0]) {
const wavelengthDelta = p2[0] - p1[0];
const indexDelta = p2[1] - p1[1];
let index = (indexDelta / wavelengthDelta) * (wavelength - p1[0]) + p1[1];
if (this !== environmentMaterial) {
index = index * settings["multiplier"];
}
return index;
}
p1 = p2;
}
console.log(`Undefined refraction index for ${wavelength} nm wavelength, defaulting to 1.0`);
return 1.0;
}
}
// Fluorite crown FK51A optical glass material
class FK51A extends Material {
constructor() {
super();
this.modifiable = false;
}
refractiveIndex(lambda) {
lambda = lambda / 1000;
const lambda2 = lambda * lambda;
const A = (0.971247817 * lambda2) / (lambda2 - 0.00472301995);
const B = (0.216901417 * lambda2) / (lambda2 - 0.0153575612);
const C = (0.904651666 * lambda2) / (lambda2 - 168.68133);
return Math.sqrt(A + B + C + 1);
}
}
// Dense flint SF10 optical glass material
class DenseFlintSF10 extends Material {
constructor() {
super();
this.modifiable = false;
}
refractiveIndex(lambda) {
lambda = lambda / 1000;
const lambda2 = lambda * lambda;
const A = (1.62153902 * lambda2) / (lambda2 - 0.0122241457);
const B = (0.256287842 * lambda2) / (lambda2 - 0.0595736775);
const C = (1.64447552 * lambda2) / (lambda2 - 147.468793);
return Math.sqrt(A + B + C + 1);
}
}
// Borosilicate crown BK7 optical glass material
class BorosilicateBK7 extends Material {
constructor() {
super();
this.modifiable = false;
}
refractiveIndex(lambda) {
lambda = lambda / 1000;
const lambda2 = lambda * lambda;
const A = (1.03961212 * lambda2) / (lambda2 - 0.00600069867);
const B = (0.231792344 * lambda2) / (lambda2 - 0.0200179144);
const C = (1.01046945 * lambda2) / (lambda2 - 103.560653);
return Math.sqrt(A + B + C + 1);
}
}
// Lanthanum dense flint LaSF9 optical glass material
class LanthanumDenseFlintLASF9 extends Material {
constructor() {
super();
this.modifiable = false;
}
refractiveIndex(lambda) {
lambda = lambda / 1000;
const lambda2 = lambda * lambda;
const A = (2.00029547 * lambda2) / (lambda2 - 0.0121426017);
const B = (0.298926886 * lambda2) / (lambda2 - 0.0538736236);
const C = (1.80691843 * lambda2) / (lambda2 - 156.530829);
return Math.sqrt(A + B + C + 1);
}
}
class Water extends Material {
constructor() {
super([
[380, 1.3406],
[400, 1.3390],
[500, 1.3350],
[600, 1.3320],
[700, 1.3310],
[740, 1.3300]
]);
this.modifiable = false;
}
}
class Ice extends Material {
constructor() {
super([
[380, 1.3215],
[400, 1.3194],
[500, 1.3130],
[600, 1.3094],
[700, 1.3069],
[740, 1.3060]
]);
this.modifiable = false;
}
}
class Geometry {
constructor(drawColor) {
this.color = drawColor;
this.hovered = false;
this.selected = false;
this.material = undefined;
this.rotation = 0.0;
this.colliding = new Set();
this.customMaterial = new Material();
this.material = this.customMaterial;
}
rayIntersection(ray, gfx) { }
getProjectionRange(axis) {
let min = math.dot(this.vertices[0], axis);
let max = min;
for (let i = 1; i < this.vertices.length; i++) {
let dot = math.dot(this.vertices[i], axis);
if (dot > max) {
max = dot
}
else if (dot < min) {
min = dot;
}
}
return { min, max };
}
updateCollisions(geometries) {
const thisGeometry = this;
// Check for all colliding geometries
this.colliding = new Set(geometries.filter(function (g) {
if (thisGeometry !== g) {
if (thisGeometry.isColliding(g)) {
if (!thisGeometry.colliding.has(g)) {
// New colliding geometry
g.colliding.add(thisGeometry);
}
return true;
} else {
if (thisGeometry.colliding.has(g)) {
// Not colliding anymore
g.colliding.delete(thisGeometry);
}
return false;
}
}
}));
}
// 2D SAT collision detection for convex polygons
isColliding(geometry) {
const axes = this.getAxes().concat(geometry.getAxes());
for (const separatingAxis of axes) {
// Project all vertices of both geometries to the axis
const firstRange = this.getProjectionRange(separatingAxis);
const secondRange = geometry.getProjectionRange(separatingAxis);
// Check for overlay of projection ranges
if (secondRange.min > firstRange.max || secondRange.max < firstRange.min) {
return false;
}
}
// Could not find separating axis, geometries are colliding
return true;
}
translate(delta, _mousePos) {
this.vertices = this.vertices.map(x => math.add(x, delta));
}
rotate(angle) {
const angleDelta = angle - this.rotation;
this.rotation = angle;
let vertices = this.vertices;
const center = this.getCenter();
const vertexCount = this.vertices.length;
for (let i = 0; i < vertexCount; i++) {
// Translate to rotate around center of the triangle
let vertex = math.subtract(vertices[i], center);
vertex = [
vertex[0] * Math.cos(angleDelta) - vertex[1] * Math.sin(angleDelta),
vertex[0] * Math.sin(angleDelta) + vertex[1] * Math.cos(angleDelta)
]
vertices[i] = math.add(vertex, center);
}
for (let i = 0; i < vertexCount; i++) {
this.normals[i] = getNormal(math.subtract(vertices[(i + 1) % vertexCount], vertices[i]));
}
this.updateCollisions(tracedGeometries);
}
getRotation() { return this.rotation; }
draw(gfx) {
if (settings["debugOn"]) {
this.debugDraw(gfx);
}
let color;
let lineWidth = 2;
if (this.colliding.size > 0) {
color = 0xff0000;
lineWidth = 4;
}
else if (this.hovered && this.selected) {
color = 0x0f0fff;
lineWidth = 3;
}
else if (this.hovered) {
color = hoverColor;
lineWidth = 3;
}
else if (this.selected) {
color = selectColor;
}
else {
color = this.color;
}
gfx.lineStyle(lineWidth, color, 1);
if (this.vertices.length > 2) {
gfx.drawPolygon(...this.vertices.flat());
} else {
drawLine(gfx, this.color, this.vertices[0], this.vertices[1]);
}
}
debugDraw(gfx) {
if (this.vertices.length > 2) {
for (let i = 0; i < this.vertices.length; i++) {
const v1 = this.vertices[i];
const v2 = this.vertices[(i + 1) % this.vertices.length];
const edgeCenter = math.divide(math.add(v1, v2), 2.0);
const endPoint = math.add(edgeCenter, math.multiply(this.normals[i], 50.0));
drawLine(gfx, 0xff00ff, edgeCenter, endPoint);
}
}
}
/* Checks if specified point is inside the geometry */
pointCheck(point) {
const vertexCount = this.vertices.length;
for (let i = 0; i < vertexCount; i++) {
const v1 = this.vertices[i];
const v2 = this.vertices[(i + 1) % vertexCount];
const edgeVector = math.subtract(v2, v1);
const pointVector = math.subtract(point, v1);
if (math.dot(edgeVector, pointVector) < 0) {
return false;
}
}
return true;
}
rayIntersection(ray) {
let result = undefined;
for (let i = 0; i < this.vertices.length; i++) {
let p1 = this.vertices[i];
let p2 = this.vertices[(i + 1) % this.vertices.length];
let param = raySegmentIntersection(ray, p1, p2);
if (param != undefined) {
if (result != undefined) {
if (param < result.t) {
result = {
t: param,
edgeIdx: i,
edgeVector: getSegmentVector(p1, p2),
edgeNormal: this.normals[i],
geometry: this
};
}
}
else {
result = {
t: param,
edgeIdx: i,
edgeVector: getSegmentVector(p1, p2),
edgeNormal: this.normals[i],
geometry: this
};
}
}
}
return result;
}
solveRay(ray, intersection) {
let lineSegments = [];
let emergentRays = [];
const vertexCount = this.vertices.length;
if (this.pointCheck(ray.origin)) {
//TODO
}
else {
// Ray origin is outside the geometry
const enterPoint = math.add(ray.origin, math.multiply(ray.dir, intersection.t));
lineSegments.push(new Line(ray.color(), ray.origin, enterPoint));
let rays = refractRay(ray, intersection.edgeNormal, enterPoint, environmentMaterial, this.material);
rays = rays.map(function (x) {
x.ray.lastEdgeIdx = intersection.edgeIdx;
x.ray.inside = !x.TIR;
return x;
});
while (rays.length > 0) {
let rayData = rays.pop();
let currentRay = rayData.ray;
if (!currentRay.inside) {
currentRay.lastEdgeIdx = undefined;
currentRay.inside = false;
currentRay.lastGeometry = this;
emergentRays.push(currentRay);
continue;
}
// Find next incidence edge
let nextEdgeIdx;
let t = undefined;
for (let i = 0; i < vertexCount; i++) {
if (i == currentRay.lastEdgeIdx) {
continue;
}
let p1 = this.vertices[i];
let p2 = this.vertices[(i + 1) % vertexCount];
t = raySegmentIntersection(currentRay, p1, p2);
if (t != undefined) {
nextEdgeIdx = i;
break;
}
}
// Calculate incidence point
if (t != undefined) {
const nextPoint = math.add(currentRay.origin, math.multiply(currentRay.dir, t));
lineSegments.push(new Line(currentRay.color(), currentRay.origin, nextPoint));
const invertedNormal = math.multiply(-1, this.normals[nextEdgeIdx]);
let newRays = refractRay(currentRay, invertedNormal, nextPoint, this.material, environmentMaterial);
rays = rays.concat(newRays.map(x => {
x.ray.lastEdgeIdx = nextEdgeIdx;
x.ray.inside = x.TIR;
return x;
}));
}
else {
// TODO?
}
}
}
return {
lineSegments,
emergentRays
};
}
}
class Line extends Geometry {
constructor(drawColor, v1, v2) {
super(drawColor);
this.vertices = [v1, v2];
}
}
class Rectangle extends Geometry {
static idCounter = 0;
constructor(drawColor, v, width, height) {
super(drawColor);
this.id = (Rectangle.idCounter++);
this.height = height;
this.width = width;
this.vertices = [
math.add(v, [0, height]),
math.add(v, [width, height]),
math.add(v, [width, 0]),
v,
];
this.normals = [
getNormal(math.subtract(this.vertices[1], this.vertices[0])),
getNormal(math.subtract(this.vertices[2], this.vertices[1])),
getNormal(math.subtract(this.vertices[3], this.vertices[2])),
getNormal(math.subtract(this.vertices[0], this.vertices[3])),
];
}
getAxes() { return this.normals.slice(0, 2); }
getCenter() { return math.divide(math.add(this.vertices[0], this.vertices[2]), 2.0); }
getWidth() { return this.width; }
getHeight() { return this.height; }
setWidth(value) {
this.width = value;
const dir = normalize(math.subtract(this.vertices[1], this.vertices[0]));
this.vertices[1] = math.add(this.vertices[0], math.multiply(this.width, dir));
this.vertices[2] = math.add(this.vertices[3], math.multiply(this.width, dir));
this.updateCollisions(tracedGeometries);
}
setHeight(value) {
this.height = value;
const dir = normalize(math.subtract(this.vertices[3], this.vertices[0]));
this.vertices[2] = math.add(this.vertices[1], math.multiply(this.height, dir));
this.vertices[3] = math.add(this.vertices[0], math.multiply(this.height, dir));
this.updateCollisions(tracedGeometries);
}
}
class Triangle extends Geometry {
static idCounter = 0;
constructor(drawColor, v1, v2, v3) {
super(drawColor);
this.id = (Triangle.idCounter++);
this.vertices = [v1, v2, v3];
this.normals = [
getNormal(math.subtract(v2, v1)),
getNormal(math.subtract(v3, v2)),
getNormal(math.subtract(v1, v3))
];
this.apexAngle = Math.PI - math.acos(math.dot(this.normals[1], this.normals[2]));
this.height = (math.distance(v1, v2) / 2.0) / Math.tan(this.apexAngle / 2.0);
}
getAxes() { return this.normals; }
getCenter() { return math.divide(math.add(math.add(this.vertices[0], this.vertices[1]), this.vertices[2]), 3.0); }
getAngle() {
return this.apexAngle;
}
getHeight() {
return this.height;
}
setAngle(angle) {
this.apexAngle = angle;
const halfAngle = this.apexAngle / 2.0;
let baseMidpoint = math.divide(math.add(this.vertices[0], this.vertices[1]), 2.0);
let baseDir = normalize(math.subtract(this.vertices[1], this.vertices[0]));
let baseHalfLength = this.height * Math.tan(halfAngle);
this.vertices[0] = math.add(baseMidpoint, math.multiply(-baseHalfLength, baseDir));
this.vertices[1] = math.add(baseMidpoint, math.multiply(baseHalfLength, baseDir));
this.normals[1] = getNormal(math.subtract(this.vertices[2], this.vertices[1]));
this.normals[2] = getNormal(math.subtract(this.vertices[0], this.vertices[2]));
this.updateCollisions(tracedGeometries);
}
setHeight(height) {
this.height = height;
const halfAngle = this.apexAngle / 2.0;
let hypotenuseLenght = this.height / Math.cos(halfAngle);
let rightDir = normalize(math.subtract(this.vertices[1], this.vertices[2]));
let leftDir = normalize(math.subtract(this.vertices[0], this.vertices[2]));
this.vertices[0] = math.add(this.vertices[2], math.multiply(hypotenuseLenght, leftDir));
this.vertices[1] = math.add(this.vertices[2], math.multiply(hypotenuseLenght, rightDir));
this.updateCollisions(tracedGeometries);
}
pointCheck(point) {
function sign(p1, p2, p3) {
return (p1[0] - p3[0]) * (p2[1] - p3[1]) - (p2[0] - p3[0]) * (p1[1] - p3[1]);
}
const d1 = sign(point, this.vertices[0], this.vertices[1]);
const d2 = sign(point, this.vertices[1], this.vertices[2]);
const d3 = sign(point, this.vertices[2], this.vertices[0]);
const has_neg = (d1 < 0) || (d2 < 0) || (d3 < 0);
const has_pos = (d1 > 0) || (d2 > 0) || (d3 > 0);
return !(has_neg && has_pos);
}
}
function selectObject(key, object) {
if (selection[key]) {
if (selection[key] != object) {
selection[key].selected = false;
selection[key] = object;
if (object) {
selection[key].selected = true;
}
}
else {
selection[key].selected = false;
selection[key] = undefined;
}
} else {
selection[key] = object;
if (object) {
selection[key].selected = true;
}
}
}
function selectGeometry(geometry) {
selectObject("geometry", geometry);
if (selection.geometry) {
setNumberInputs(geometry.material);
selection.material = geometry.material;
$('#geometryType').text("Dispersion curve: " + geometry.constructor.name + "#" + geometry.id);
// $('#unselected-div').hide();
$('#rotate-div').show();
$('#selected-div').show();
$('#geometry-rotation').val(radToDeg(-geometry.getRotation()).toFixed(3));
switch (geometry.constructor) {
case Rectangle:
$('#triangle-div').hide();
$('#rectangle-div').show();
$('#rect-width').val(geometry.getWidth().toFixed(3));
$('#rect-height').val(geometry.getHeight().toFixed(3));
break;
case Triangle:
$('#rectangle-div').hide();
$('#triangle-div').show();
$('#triangle-angle').val(radToDeg(geometry.getAngle()).toFixed(3));
$('#triangle-height').val(geometry.getHeight().toFixed(3));
break;
}
} else {
setNumberInputs(environmentMaterial);
selection.material = environmentMaterial;
$('#geometryType').text("Dispersion curve: environment");
$('#rectangle-div').hide();
$('#triangle-div').hide();
$('#rotate-div').hide();
$('#selected-div').hide();
// $('#unselected-div').show();
}
computeCurvePoints();
renderSettings();
renderScene();
}
function selectRay(ray) {
selectObject("ray", ray);
if (selection.ray) {
$("#ray-inputs").show();
$("#ray-angle").val(-radToDeg(ray.getAngle()).toFixed(2));
const waves = selection.ray.waves;
if (waves.length > 1) {
$("#ray-count").val(waves.length);
$("#wavelength-min").val(waves[0].lambda);
$("#wavelength-max").val(waves[waves.length - 1].lambda);
}
else {
$("#ray-wavelength").val(waves[0].lambda);
}
}
else {
$("#ray-inputs").hide();
}
// renderSettings();
renderScene();
}
let settings = {
"refraction": 1.5,
"debugOn": false,
"multiplier": 1.0,
"multiplier-min": 1.0,
"multiplier-max": 3.0,
"wavelength-min": 380,
"wavelength-max": 740,
"ray-min": 2,
"ray-max": 25,
"ray-count": 25
}
let leftMouseDown = false;
let lastMousePos = [0, 0];
let activeRays = [];
let tracedGeometries = [];
let renderLines = [];
let rayCanvasDiv = null;
let rayCanvas = null;
let rayApp = null;
let rayGfx = new PIXI.Graphics();
let curveCanvas = null;
let curveCanvasDiv = null;
let settingsApp = null;
let settingsGfx = new PIXI.Graphics();
const basicCurvePoints = [
[380, 1.0],
[400, 1.0],
[500, 1.0],
[600, 1.0],
[700, 1.0],
[740, 1.0]
];
const basicMaterial = new Material(basicCurvePoints);
let environmentMaterial = basicMaterial;
const materialFK51A = new FK51A();
const materialDenseFlintSF10 = new DenseFlintSF10();
const materialBK7 = new BorosilicateBK7();
const materialLASF9 = new LanthanumDenseFlintLASF9();
const materialWater = new Water();
const materialIce = new Ice();
const hoverColor = 0xff00ff;
const selectColor = 0x00ffff;
let hoveredObject = undefined;
let selection = {
"geometry": undefined,
"ray": undefined,
"material": environmentMaterial
}
//TODO: simulate more precisely, implement refractive index curves somehow
// function dispersionCurve(wavelength) {
// return refractiveIndexBase + ((740 - wavelength) / (740 * 4));
// }
// const whitelightWavelengths = [380.0, 400.0, 500.0, 600.0, 700.0, 740.0];
const lightWaves = [380.0, 400.0, 500.0, 600.0, 700.0, 740.0].map(x => {
return {
lambda: x,
color: PIXI.utils.rgb2hex(wavelengthToColor(x))
}
});
function renderScene() {
rayGfx.clear();
for (const geometry of tracedGeometries) {
geometry.draw(rayGfx);
}
for (const line of renderLines) {
line.draw(rayGfx);
}