-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLowRank_approx_3D.html
More file actions
1239 lines (1055 loc) · 66.3 KB
/
LowRank_approx_3D.html
File metadata and controls
1239 lines (1055 loc) · 66.3 KB
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
<!DOCTYPE html>
<html lang="uk">
<head>
<meta charset="UTF-8">
<title>3D Візуалізація матричних перетворень з Low-Rank Апроксимацією</title>
<script type="importmap">
{
"imports": {
"three": "https://unpkg.com/three@0.160.0/build/three.module.js",
"three/addons/": "https://unpkg.com/three@0.160.0/examples/jsm/",
"three-mesh-bvh": "https://unpkg.com/three-mesh-bvh@0.7.3/build/index.module.js",
"three-bvh-csg": "https://esm.sh/three-bvh-csg@0.0.16?external=three,three-mesh-bvh"
}
}
</script>
<script>
window.MathJax = {
tex: {
inlineMath: [['$', '$'], ['\\(', '\\)']],
displayMath: [['$$', '$$'], ['\\[', '\\]']]
}
};
</script>
<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js" id="MathJax-script" async></script>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
margin: 0;
background-color: #f0f0f0;
color: #333;
overflow: auto;
min-height: 100vh;
}
#main-container {
display: flex;
flex-direction: column;
min-height: 100vh;
}
#scenes-container {
flex-grow: 1;
display: flex;
height: 65vh; /* Трохи зменшив висоту, щоб помістився спойлер */
}
.scene-wrapper {
flex: 1;
position: relative;
}
.scene-wrapper canvas {
display: block;
width: 100% !important;
height: 100% !important;
}
.scene-label {
position: absolute;
top: 10px;
left: 10px;
color: white;
background-color: rgba(0, 0, 0, 0.5);
padding: 5px 10px;
border-radius: 5px;
font-size: 1.2em;
}
#controls-panel {
padding: 20px;
background-color: #fff;
}
h2, h3 {
margin-top: 0;
color: #2c3e50;
border-bottom: 2px solid #3498db;
padding-bottom: 10px;
}
.matrix-controls {
display: flex;
gap: 30px;
margin: 20px 0;
}
.matrix-section {
flex: 1;
}
.matrix-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
margin: 10px 0;
}
.input-group {
display: flex;
align-items: center;
justify-content: center;
}
.input-group input {
width: 50px;
text-align: center;
font-size: 1em;
border: 1px solid #ccc;
border-radius: 4px;
margin: 0 5px;
}
.input-group button {
min-width: 25px;
height: 30px;
font-size: 1.2em;
line-height: 0;
padding: 0;
background-color: #ecf0f1;
color: #2c3e50;
border: 1px solid #bdc3c7;
cursor: pointer;
}
.options-group {
margin-top: 20px;
}
.options-group label, .options-group select {
font-size: 1.1em;
}
.options-group select {
width: 100%;
padding: 8px;
margin-top: 5px;
border-radius: 4px;
border: 1px solid #ccc;
}
#webgl-error {
display: none;
padding: 40px;
text-align: center;
color: #c0392b;
background-color: #fbe9e7;
border: 2px solid #c0392b;
margin: 50px;
border-radius: 8px;
}
.rank-controls {
display: flex;
align-items: center;
margin-top: 15px;
flex-wrap: wrap;
gap: 10px;
}
.rank-controls label {
margin-right: 5px;
}
.rank-controls select {
width: auto;
margin-right: 10px;
}
#eigen-message {
color: #c0392b;
font-weight: bold;
margin-left: 10px;
}
#determinant-display {
font-weight: bold;
font-size: 1.1em;
margin-left: 15px;
padding: 5px 8px;
border-radius: 4px;
}
.explanation {
margin-top: 20px;
padding: 15px;
background-color: #f8f9fa;
border-radius: 5px;
border-left: 4px solid #3498db;
}
.explanation summary {
cursor: pointer;
font-weight: bold;
}
.explanation summary h3 {
display: inline;
border: none;
padding: 0;
}
.explanation p, .explanation ul {
margin-top: 10px;
line-height: 1.6;
}
.matrix-display {
margin-top: 15px;
padding: 10px;
background-color: #f5f5f5;
border-radius: 5px;
font-family: monospace;
}
.matrix-row {
display: flex;
justify-content: center;
margin: 5px 0;
}
.matrix-cell {
width: 60px;
text-align: center;
padding: 5px;
}
.matrix-title {
text-align: center;
font-weight: bold;
margin-bottom: 10px;
color: #2c3e50;
}
</style>
</head>
<body>
<div id="webgl-error">
<h2>Помилка ініціалізації WebGL</h2>
<p>На жаль, ваш браузер або пристрій не зміг запустити 3D-графіку. Будь ласка, увімкніть "Апаратне прискорення" в налаштуваннях вашого браузера та перезапустіть його.</p>
</div>
<div id="main-container">
<div id="scenes-container">
<div class="scene-wrapper">
<div id="original-scene"></div>
<div class="scene-label">Оригінал</div>
</div>
<div class="scene-wrapper">
<div id="transformed-scene"></div>
<div class="scene-label">Трансформація</div>
</div>
<div class="scene-wrapper">
<div id="lowrank-scene"></div>
<div class="scene-label">Low-Rank Апроксимація</div>
</div>
</div>
<div id="controls-panel">
<h2>Матриця перетворення 3x3</h2>
<p>Змінюйте значення матриці, щоб побачити, як трансформується фігура. Обертайте сцени мишею, масштабуйте коліщатком.</p>
<div class="matrix-controls">
<div class="matrix-section">
<div class="matrix-title">Оригінальна матриця</div>
<div class="matrix-grid">
<div class="input-group"><button onclick="stepValue('m00', -0.1)">-</button><input type="number" id="m00" step="0.1" onchange="updateTransformation()"><button onclick="stepValue('m00', 0.1)">+</button></div>
<div class="input-group"><button onclick="stepValue('m01', -0.1)">-</button><input type="number" id="m01" step="0.1" onchange="updateTransformation()"><button onclick="stepValue('m01', 0.1)">+</button></div>
<div class="input-group"><button onclick="stepValue('m02', -0.1)">-</button><input type="number" id="m02" step="0.1" onchange="updateTransformation()"><button onclick="stepValue('m02', 0.1)">+</button></div>
<div class="input-group"><button onclick="stepValue('m10', -0.1)">-</button><input type="number" id="m10" step="0.1" onchange="updateTransformation()"><button onclick="stepValue('m10', 0.1)">+</button></div>
<div class="input-group"><button onclick="stepValue('m11', -0.1)">-</button><input type="number" id="m11" step="0.1" onchange="updateTransformation()"><button onclick="stepValue('m11', 0.1)">+</button></div>
<div class="input-group"><button onclick="stepValue('m12', -0.1)">-</button><input type="number" id="m12" step="0.1" onchange="updateTransformation()"><button onclick="stepValue('m12', 0.1)">+</button></div>
<div class="input-group"><button onclick="stepValue('m20', -0.1)">-</button><input type="number" id="m20" step="0.1" onchange="updateTransformation()"><button onclick="stepValue('m20', 0.1)">+</button></div>
<div class="input-group"><button onclick="stepValue('m21', -0.1)">-</button><input type="number" id="m21" step="0.1" onchange="updateTransformation()"><button onclick="stepValue('m21', 0.1)">+</button></div>
<div class="input-group"><button onclick="stepValue('m22', -0.1)">-</button><input type="number" id="m22" step="0.1" onchange="updateTransformation()"><button onclick="stepValue('m22', 0.1)">+</button></div>
</div>
</div>
<div class="matrix-section">
<div class="matrix-title">Апроксимована матриця</div>
<div class="matrix-display">
<div id="lowrank-matrix">
<div class="matrix-row">
<div class="matrix-cell" id="lr00">0.00</div>
<div class="matrix-cell" id="lr01">0.00</div>
<div class="matrix-cell" id="lr02">0.00</div>
</div>
<div class="matrix-row">
<div class="matrix-cell" id="lr10">0.00</div>
<div class="matrix-cell" id="lr11">0.00</div>
<div class="matrix-cell" id="lr12">0.00</div>
</div>
<div class="matrix-row">
<div class="matrix-cell" id="lr20">0.00</div>
<div class="matrix-cell" id="lr21">0.00</div>
<div class="matrix-cell" id="lr22">0.00</div>
</div>
</div>
</div>
</div>
</div>
<div class="options-group" style="display: flex; gap: 30px;">
<div style="flex: 1;">
<label for="presets">Готові пресети:</label>
<select id="presets" onchange="applyPreset()">
<option value="identity">Одинична матриця (без змін)</option>
<option value="scaleX">Розтягнення по X</option>
<option value="scaleUniform">Рівномірне збільшення</option>
<option value="rotateY">Поворот навколо Y</option>
<option value="rotateZ">Поворот навколо Z</option>
<option value="shear">Скошення (зсув)</option>
<option value="reflection">Дзеркальне відображення</option>
<option value="degenerate">Вироджена матриця</option>
</select>
</div>
<div style="flex: 1;">
<label for="model-select">Вибір 3D моделі:</label>
<select id="model-select" onchange="changeModel()">
<option value="snowman">Сніговик</option>
<option value="hatHead">Студент</option>
<option value="skull">Колишній студент</option>
<option value="box">Куб</option>
<option value="torus">Тор (пончик)</option>
<option value="torusKnot">Вузол</option>
<option value="octahedron">Октаедр</option>
<option value="teapot">Чайник</option>
<option value="mouse">Миша</option>
</select>
</div>
</div>
<div class="rank-controls">
<label for="rank-select">Ранг апроксимації:</label>
<select id="rank-select" onchange="updateTransformation()">
<option value="2">2 (плоске зображення)</option>
<option value="1">1 (лінійне зображення)</option>
</select>
<label><input type="checkbox" id="showBasis" onchange="toggleBasisVisibility()"> Базис</label>
<label><input type="checkbox" id="showEigen" onchange="toggleEigenVisibility()"> Власні вектори</label>
<label><input type="checkbox" id="showSVD" onchange="toggleSVDVisibility()"> Сингулярні вектори</label>
<span id="eigen-message"></span>
<span id="determinant-display">Det: 1.000</span>
</div>
<details class="explanation">
<summary><h3>Теоретична довідка (натисніть, щоб розгорнути)</h3></summary>
<p><strong>Матриця перетворення (A):</strong> Це таблиця 3x3, яка описує лінійне перетворення у 3D-просторі. Кожен <strong>стовпець</strong> матриці показує, куди перейде відповідний базисний вектор (i, j, k або X, Y, Z) після трансформації. Наприклад, перший стовпець $(m_{00}, m_{10}, m_{20})$ — це нова позиція вектора $(1, 0, 0)$.</p>
<p><strong>Детермінант (det(A)):</strong> Це одне число, яке описує, як перетворення впливає на <strong>об'єм</strong> (площу для 2D, гіпер-об'єм для просторів вищої розмірності).</p>
<ul>
<li>$det(A) = 1$: Об'єм не змінився (наприклад, чистий поворот).</li>
<li>$det(A) = 0.7$: Об'єм змінився на фактор 0.7 (зменшився на 30%).</li>
<li>$det(A) = 0$: Об'єм "схлопнувся" до площини (ранг 2) або лінії (ранг 1). Матриця є <strong>виродженою</strong>.</li>
<li>$det(A) < 0$ (від'ємний): Відбулося <strong>віддзеркалення</strong> (інверсія). Простір "вивернувся навиворіт".</li>
</ul>
<p><strong>Власні вектори (Eigenvectors)</strong> (жовті): Це особливі напрямки у просторі, які <strong>не змінюють своєї орієнтації</strong> під дією матриці. Вони лише розтягуються або стискаються на певне значення (власне число, $\lambda$), можуть розвернутися в протилежному напрямку (якщо $\lambda$ від'ємне). Вони існують не для всіх матриць (наприклад, матриця повороту може мати комплекснозначні вектори, які ми не показуємо).</p>
<p><strong>Сингулярний розклад (SVD):</strong> Це фундаментальний інструмент, який каже, що <strong>будь-яку</strong> матрицю $A$ можна розкласти на три окремі операції:
$$ A = U \Sigma V^T $$
Де:</p>
<ul>
<li>$V^T$ — (<strong>Праві</strong> вектори, <span style="color:#00ffff;">блакитні</span>). Це матриця <strong>повороту</strong> вхідного простору.</li>
<li>$\Sigma$ — (Сигма). Це <strong>діагональна</strong> матриця, яка виконує <strong>масштабування</strong> вздовж осей. Її значення $\sigma_1, \sigma_2, \sigma_3$ називаються <strong>сингулярними числами</strong>.</li>
<li>$U$ — (<strong>Ліві</strong> вектори, <span style="color:#ff00ff;">пурпурові</span>). Це матриця <strong>повороту</strong> вихідного простору.</li>
</ul>
<p>SVD показує, що будь-яке, навіть найскладніше, лінійне перетворення — це просто: 1. Поворот, 2. Масштабування, 3. Інший поворот.</p>
<p><strong>Low-Rank Апроксимація (Ранг $k$):</strong> Це серце стиснення інформації. Сингулярні числа в $\Sigma$ завжди відсортовані за важливістю ($\sigma_1 \ge \sigma_2 \ge \sigma_3 \ge 0$). Найбільше число $\sigma_1$ відповідає найважливішому "напрямку" в даних.</p>
<p>Щоб отримати апроксимацію з рангом $k$, ми просто "обрізаємо" матриці, взявши лише $k$ найбільших сингулярних чисел та відповідні їм вектори:
$$ A_k = U_k \Sigma_k V_k^T $$
</P>
<ul>
<li><strong>Ранг 2 ($k=2$):</strong> Ми беремо 2 найважливіші напрямки. Це дає нам <strong>найкращу можливу 2D-площину</strong>, яка представляє вихідну 3D-фігуру, зберігаючи максимум її варіативності (інформації).</li>
<li><strong>Ранг 1 ($k=1$):</strong> Ми беремо лише 1, найважливіший напрямок. Це дає <strong>найкращу можливу 1D-лінію</strong>.</li>
</ul>
<p><strong>Виявлення "прихованих факторів":</strong> Чому SVD такий потужний? Бо він автоматично знаходить "головні компоненти" (principal components) даних. Ці компоненти (напрямки, задані векторами $V$) часто є "прихованими факторами" або "латентними ознаками", які керують даними, але не є очевидними.</p>
<ul>
<li><strong>Рекомендаційні системи:</strong> Маємо гігантську матрицю [Користувачі] x [Фільми]. SVD може знайти приховані фактори, наприклад, "наскільки цей фільм є 'романтичною комедією'" або "наскільки цей користувач любить 'наукову фантастику'". Апроксимація $A_k$ (де $k \approx 50$) дозволяє передбачити рейтинги.</li>
<li><strong>Тематизація текстів (NLP):</strong> Матриця [Слова] x [Документи]. SVD знаходить "теми" (наприклад, "політика", "спорт") як приховані фактори.</li>
<li><strong>Біоінформатика:</strong> Матриця [Пацієнти] x [Гени]. SVD може виявити групи генів (головні компоненти), які найкраще пояснюють різницю між хворими та здоровими пацієнтами.</li>
</ul>
</details>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/numeric/1.2.6/numeric.min.js"></script>
<script type="module">
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { TeapotGeometry } from 'three/addons/geometries/TeapotGeometry.js'; // Імпорт "чайника"
import { Brush, Evaluator, SUBTRACTION } from 'three-bvh-csg';
let originalScene, transformedScene, lowrankScene, camera, originalRenderer, transformedRenderer, lowrankRenderer, controls1, controls2, controls3;
let originalModel, transformedModel, lowrankModel;
let originalWrapper, transformedWrapper, lowrankWrapper; // Обгортки для моделей
let newBasis, lowrankBasis;
let eigenVectors, originalEigenVectors;
let rightSingularVectors, leftSingularVectors, lowRankLeftSingularVectors;
let lastSVD = null;
let eigenMessageDiv;
const presets = {
identity: [1,0,0, 0,1,0, 0,0,1],
scaleX: [2,0,0, 0,1,0, 0,0,1],
scaleUniform: [1.5,0,0, 0,1.5,0, 0,0,1.5],
rotateY: [Math.cos(0.5), 0, Math.sin(0.5), 0,1,0, -Math.sin(0.5), 0, Math.cos(0.5)],
rotateZ: [Math.cos(0.5), -Math.sin(0.5), 0, Math.sin(0.5), Math.cos(0.5), 0, 0,0,1],
shear: [1,1,0, 0,1,0, 0,0,1],
reflection: [-1,0,0, 0,1,0, 0,0,1],
degenerate: [1,0,0, 1,0,0, 0,0,1]
};
function init() {
try {
eigenMessageDiv = document.getElementById('eigen-message');
originalScene = new THREE.Scene();
transformedScene = new THREE.Scene();
lowrankScene = new THREE.Scene();
originalScene.background = new THREE.Color(0x2c3e50);
transformedScene.background = new THREE.Color(0x2c3e50);
lowrankScene.background = new THREE.Color(0x2c3e50);
const aspect = window.innerWidth / 3 / (window.innerHeight * 0.65);
camera = new THREE.PerspectiveCamera(50, aspect, 0.1, 1000);
camera.position.set(2, 2.5, 4.5);
camera.lookAt(0, 0, 0);
const ambientLight = new THREE.AmbientLight(0xffffff, 0.7);
const directionalLight = new THREE.DirectionalLight(0xffffff, 1.8);
directionalLight.position.set(5, 7, 8);
originalScene.add(ambientLight.clone());
originalScene.add(directionalLight.clone());
transformedScene.add(ambientLight.clone());
transformedScene.add(directionalLight.clone());
lowrankScene.add(ambientLight.clone());
lowrankScene.add(directionalLight.clone());
const originalContainer = document.getElementById('original-scene');
const transformedContainer = document.getElementById('transformed-scene');
const lowrankContainer = document.getElementById('lowrank-scene');
originalRenderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
transformedRenderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
lowrankRenderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
originalContainer.appendChild(originalRenderer.domElement);
transformedContainer.appendChild(transformedRenderer.domElement);
lowrankContainer.appendChild(lowrankRenderer.domElement);
controls1 = new OrbitControls(camera, originalRenderer.domElement);
controls2 = new OrbitControls(camera, transformedRenderer.domElement);
controls3 = new OrbitControls(camera, lowrankRenderer.domElement);
// Створюємо обгортки (wrappers) для моделей
originalWrapper = new THREE.Group();
originalWrapper.position.y = -0.5;
originalScene.add(originalWrapper);
transformedWrapper = new THREE.Group();
transformedWrapper.position.y = -0.5;
transformedScene.add(transformedWrapper);
lowrankWrapper = new THREE.Group();
lowrankWrapper.position.y = -0.5;
lowrankScene.add(lowrankWrapper);
createHelpers(); // Створюємо всі стрілки та осі
changeModel(); // Завантажуємо модель за замовчуванням
applyPreset();
animate();
window.addEventListener('resize', onWindowResize);
onWindowResize();
} catch (e) {
console.error(e);
document.getElementById('main-container').style.display = 'none';
document.getElementById('webgl-error').style.display = 'block';
}
}
// Ця функція створює лише стрілки (базис, вектори)
function createHelpers() {
const axesHelper = new THREE.AxesHelper(2.5);
originalScene.add(axesHelper.clone());
// --- Базис для Трансформації ---
newBasis = new THREE.Group();
newBasis.add(new THREE.ArrowHelper(new THREE.Vector3(1,0,0), new THREE.Vector3(0,0,0), 2.5, 0xff0000, 0.3));
newBasis.add(new THREE.ArrowHelper(new THREE.Vector3(0,1,0), new THREE.Vector3(0,0,0), 2.5, 0x00ff00, 0.3));
newBasis.add(new THREE.ArrowHelper(new THREE.Vector3(0,0,1), new THREE.Vector3(0,0,0), 2.5, 0x0000ff, 0.3));
newBasis.visible = false;
// --- Власні вектори (Eigenvectors) для Трансформації ---
eigenVectors = new THREE.Group();
eigenVectors.add(new THREE.ArrowHelper(new THREE.Vector3(1,0,0), new THREE.Vector3(0,0,0), 2.5, 0xffff00, 0.3));
eigenVectors.add(new THREE.ArrowHelper(new THREE.Vector3(0,1,0), new THREE.Vector3(0,0,0), 2.5, 0xffff00, 0.3));
eigenVectors.add(new THREE.ArrowHelper(new THREE.Vector3(0,0,1), new THREE.Vector3(0,0,0), 2.5, 0xffff00, 0.3));
eigenVectors.visible = false;
// --- Сингулярні вектори (SVD Left) для Трансформації ---
leftSingularVectors = new THREE.Group();
leftSingularVectors.add(new THREE.ArrowHelper(new THREE.Vector3(1,0,0), new THREE.Vector3(0,0,0), 2.5, 0xff00ff, 0.3)); // Пурпуровий
leftSingularVectors.add(new THREE.ArrowHelper(new THREE.Vector3(0,1,0), new THREE.Vector3(0,0,0), 2.5, 0xff00ff, 0.3));
leftSingularVectors.add(new THREE.ArrowHelper(new THREE.Vector3(0,0,1), new THREE.Vector3(0,0,0), 2.5, 0xff00ff, 0.3));
leftSingularVectors.visible = false;
const transformedBasisWrapper = new THREE.Group();
transformedBasisWrapper.position.y = -0.5;
transformedBasisWrapper.add(newBasis, eigenVectors, leftSingularVectors);
transformedScene.add(transformedBasisWrapper);
// --- Власні вектори (Eigenvectors) для Оригіналу ---
originalEigenVectors = new THREE.Group();
originalEigenVectors.add(new THREE.ArrowHelper(new THREE.Vector3(1,0,0), new THREE.Vector3(0,0,0), 2.5, 0xffff00, 0.3)); // Жовтий
originalEigenVectors.add(new THREE.ArrowHelper(new THREE.Vector3(0,1,0), new THREE.Vector3(0,0,0), 2.5, 0xffff00, 0.3));
originalEigenVectors.add(new THREE.ArrowHelper(new THREE.Vector3(0,0,1), new THREE.Vector3(0,0,0), 2.5, 0xffff00, 0.3));
originalEigenVectors.visible = false;
// --- Сингулярні вектори (SVD Right) для Оригіналу ---
rightSingularVectors = new THREE.Group();
rightSingularVectors.add(new THREE.ArrowHelper(new THREE.Vector3(1,0,0), new THREE.Vector3(0,0,0), 2.5, 0x00ffff, 0.3)); // Блакитний
rightSingularVectors.add(new THREE.ArrowHelper(new THREE.Vector3(0,1,0), new THREE.Vector3(0,0,0), 2.5, 0x00ffff, 0.3));
rightSingularVectors.add(new THREE.ArrowHelper(new THREE.Vector3(0,0,1), new THREE.Vector3(0,0,0), 2.5, 0x00ffff, 0.3));
rightSingularVectors.visible = false;
const originalBasisWrapper = new THREE.Group();
originalBasisWrapper.position.y = -0.5;
originalBasisWrapper.add(originalEigenVectors, rightSingularVectors);
originalScene.add(originalBasisWrapper);
// --- Базис для Low-Rank ---
lowrankBasis = new THREE.Group();
lowrankBasis.add(new THREE.ArrowHelper(new THREE.Vector3(1,0,0), new THREE.Vector3(0,0,0), 2.5, 0xff0000, 0.3));
lowrankBasis.add(new THREE.ArrowHelper(new THREE.Vector3(0,1,0), new THREE.Vector3(0,0,0), 2.5, 0x00ff00, 0.3));
lowrankBasis.add(new THREE.ArrowHelper(new THREE.Vector3(0,0,1), new THREE.Vector3(0,0,0), 2.5, 0x0000ff, 0.3));
lowrankBasis.visible = false;
// --- Сингулярні вектори (SVD Left) для Low-Rank ---
lowRankLeftSingularVectors = new THREE.Group();
lowRankLeftSingularVectors.add(new THREE.ArrowHelper(new THREE.Vector3(1,0,0), new THREE.Vector3(0,0,0), 2.5, 0xff00ff, 0.3)); // Пурпуровий
lowRankLeftSingularVectors.add(new THREE.ArrowHelper(new THREE.Vector3(0,1,0), new THREE.Vector3(0,0,0), 2.5, 0xff00ff, 0.3));
lowRankLeftSingularVectors.add(new THREE.ArrowHelper(new THREE.Vector3(0,0,1), new THREE.Vector3(0,0,0), 2.5, 0xff00ff, 0.3));
lowRankLeftSingularVectors.visible = false;
const lowrankBasisWrapper = new THREE.Group();
lowrankBasisWrapper.position.y = -0.5;
lowrankBasisWrapper.add(lowrankBasis, lowRankLeftSingularVectors);
lowrankScene.add(lowrankBasisWrapper);
}
// Ця функція створює та повертає ОДНУ модель на основі імені
function createSelectedModel(modelName) {
const modelGroup = new THREE.Group();
const commonProps = {
side: THREE.DoubleSide,
transparent: true,
opacity: 0.9,
depthWrite: true,
depthTest: true
};
///////
// --- Функція створення Черепа (з skull.html) ---
function createSkullModel() {
const evaluator = new Evaluator();
// Матеріали
const boneMaterial = new THREE.MeshPhysicalMaterial({
color: 0xE3DAC9, roughness: 0.5, metalness: 0.1,
transparent: true, opacity: 0.8, side: THREE.FrontSide, depthWrite: false
});
const toothMaterial = new THREE.MeshStandardMaterial({
color: 0xEEEEEE, roughness: 0.2, metalness: 0.0
});
// 1. Черепна коробка
const outerGeo = new THREE.SphereGeometry(2.9, 64, 64);
const outerBrush = new Brush(outerGeo, boneMaterial);
outerBrush.scale.set(0.92, 0.9, 1);
outerBrush.updateMatrixWorld();
const innerGeo = new THREE.SphereGeometry(2.6, 64, 64);
const innerBrush = new Brush(innerGeo, boneMaterial);
innerBrush.scale.set(0.92, 0.9, 1);
innerBrush.updateMatrixWorld();
let result = evaluator.evaluate(outerBrush, innerBrush, SUBTRACTION);
// 2. Очі
const eyeGeo = new THREE.CylinderGeometry(0.55, 0.55, 5, 32);
const eyeBrush = new Brush(eyeGeo, boneMaterial);
eyeBrush.rotation.x = Math.PI / 2;
eyeBrush.position.set(-0.9, 0.3, 2.5);
eyeBrush.updateMatrixWorld();
result = evaluator.evaluate(result, eyeBrush, SUBTRACTION); // Ліве око
eyeBrush.position.set(0.9, 0.3, 2.5);
eyeBrush.updateMatrixWorld();
result = evaluator.evaluate(result, eyeBrush, SUBTRACTION); // Праве око
// 3. Ніс
const noseGeo = new THREE.CylinderGeometry(0.0, 0.6, 3, 3);
const noseBrush = new Brush(noseGeo, boneMaterial);
noseBrush.rotation.x = Math.PI / 2;
noseBrush.rotation.y = Math.PI;
noseBrush.position.set(0, -0.6, 2.0);
noseBrush.scale.set(2, 3, 3.0);
noseBrush.updateMatrixWorld();
result = evaluator.evaluate(result, noseBrush, SUBTRACTION);
// 4. Зріз знизу
const cutBoxGeo = new THREE.BoxGeometry(6, 6, 6);
const cutBrush = new Brush(cutBoxGeo, boneMaterial);
cutBrush.position.set(0, -4.8, 0);
cutBrush.updateMatrixWorld();
result = evaluator.evaluate(result, cutBrush, SUBTRACTION);
// Формуємо основний меш
const skullMesh = result;
skullMesh.material = boneMaterial; // Перестраховка
// 5. Зуби
const teethGroup = new THREE.Group();
const addRow = (isUpper) => {
const rowGroup = new THREE.Group();
const count = 10;
const radius = 1.3;
const startAngle = -Math.PI / 3;
const endAngle = Math.PI / 3;
for (let i = 0; i < count; i++) {
const t = i / (count - 1);
const angle = startAngle + t * (endAngle - startAngle);
// Визначення форми зуба
const distFromCenter = Math.abs(i - (count - 1) / 2);
let w = 0.26, h = 0.45, d = 0.2; // Різці
if (distFromCenter >= 2.5) { w = 0.35; h = 0.4; d = 0.35; } // Корінні
const geo = new THREE.BoxGeometry(w, h, d);
// Заокруглення зубів (Subdivision modifier тут немає, тому просто бокс)
const tooth = new THREE.Mesh(geo, toothMaterial);
// Позиціонування по дузі
tooth.position.x = radius * Math.sin(angle);
tooth.position.z = radius * Math.cos(angle);
tooth.rotation.y = angle;
rowGroup.add(tooth);
}
if (isUpper) {
rowGroup.position.set(0, -1.8, 0.7);
} else {
rowGroup.position.set(0, -2.45, 0.7);
rowGroup.rotation.x = 0.2;
}
teethGroup.add(rowGroup);
};
addRow(true);
addRow(false);
// Збираємо все в одну групу
const masterGroup = new THREE.Group();
masterGroup.add(skullMesh);
masterGroup.add(teethGroup);
// Масштабування для сцени LowRank (щоб влізло в екран)
masterGroup.scale.set(0.4, 0.4, 0.4);
return masterGroup;
}
// Універсальний матеріал для простих фігур
const defaultMaterial = new THREE.MeshStandardMaterial({ color: 0x00ff00, metalness: 0.2, roughness: 0.6, ...commonProps, opacity: 0.95 });
switch(modelName) {
case 'box':
modelGroup.add(new THREE.Mesh(new THREE.BoxGeometry(1.5, 1.5, 1.5), defaultMaterial));
break;
case 'skull': return createSkullModel();
case 'torus':
// Створимо окремий матеріал для пончика
const torusMaterial = new THREE.MeshStandardMaterial({
color: 0xff69b4, // Яскраво-рожевий колір
metalness: 0.2,
roughness: 0.6,
...commonProps, // ...commonProps успадковує прозорість та інші налаштування
opacity: 0.95
});
// TorusGeometry(radius, tube_radius, radialSegments, tubularSegments)
modelGroup.add(new THREE.Mesh(new THREE.TorusGeometry(1, 0.4, 32, 32), torusMaterial));
break;
case 'torusKnot':
modelGroup.add(new THREE.Mesh(new THREE.TorusKnotGeometry(0.8, 0.3, 100, 16), defaultMaterial));
break;
case 'octahedron':
modelGroup.add(new THREE.Mesh(new THREE.OctahedronGeometry(1.2), defaultMaterial));
break;
case 'teapot':
const teapotMaterial = new THREE.MeshStandardMaterial({ color: 0x00c0ff, metalness: 0.5, roughness: 0.4, ...commonProps });
const teapotMesh = new THREE.Mesh(new TeapotGeometry(1, 10), teapotMaterial);
teapotMesh.geometry.computeVertexNormals(); // Важливо для коректного освітлення
modelGroup.add(teapotMesh);
break;
case 'snowman': {
// Матеріали для сніговика
const snowMaterial = new THREE.MeshStandardMaterial({ color: 0xffffff, metalness: 0.1, roughness: 0.8, ...commonProps });
const eyeMaterial = new THREE.MeshStandardMaterial({ color: 0x111111, metalness: 0.0, roughness: 0.5, ...commonProps, opacity: 1.0 });
const noseMaterial = new THREE.MeshStandardMaterial({ color: 0xff8c00, metalness: 0.2, roughness: 0.6, ...commonProps });
const bucketMaterial = new THREE.MeshStandardMaterial({ color: 0x777777, metalness: 0.4, roughness: 0.3, ...commonProps }); // Сіре відро
// Геометрії та їх позиції
const body = new THREE.Mesh(new THREE.SphereGeometry(1), snowMaterial);
body.position.y = -0.3; // Центр тулуба трохи нижче
const head = new THREE.Mesh(new THREE.SphereGeometry(0.7), snowMaterial);
head.position.y = 1.1; // Голова (0.7) на тулубі (1) зі зміщенням (-0.3)
const armL = new THREE.Mesh(new THREE.SphereGeometry(0.3), snowMaterial);
armL.position.set(-1.1, -0.1, 0.1);
const armR = new THREE.Mesh(new THREE.SphereGeometry(0.2), snowMaterial);
armR.position.set(1.1, -0.1, -0.1);
const eyeL = new THREE.Mesh(new THREE.SphereGeometry(0.1), eyeMaterial);
eyeL.position.set(-0.25, 1.3, 0.6);
const eyeR = new THREE.Mesh(new THREE.SphereGeometry(0.1), eyeMaterial);
eyeR.position.set(0.25, 1.3, 0.6);
const nose = new THREE.Mesh(new THREE.ConeGeometry(0.1, 0.5, 16), noseMaterial);
nose.position.set(0, 1.1, 0.95); // (0.7 + 0.5/2)
nose.rotation.x = Math.PI / 2; // Повертаємо моркву горизонтально
// CylinderGeometry(radiusTop, radiusBottom, height)
const bucket = new THREE.Mesh(new THREE.CylinderGeometry(0.3, 0.5, 0.65, 32), bucketMaterial);
// --- ВИПРАВЛЕНО ---
bucket.position.y = 1.9; // На голові (1.1 + 0.7) + половина висоти відра (0.35)
// Збираємо всі частини в масив, як у 'hatHead'
const parts = [body, head, armL, armR, eyeL, eyeR, nose, bucket];
parts.forEach(mesh => {
mesh.updateMatrix(); // Зафіксувати позицію/поворот
mesh.geometry.applyMatrix4(mesh.matrix); // "Запекти" трансформацію в геометрію
// Скинути позицію, щоб вона не застосовувалась двічі
mesh.position.set(0,0,0);
mesh.rotation.set(0,0,0);
mesh.scale.set(1,1,1);
modelGroup.add(mesh); // Додати до групи
});
break;
}
case 'mouse': {
// Матеріали для миші
const mouseBodyMaterial = new THREE.MeshStandardMaterial({ color: 0xf0f0f0, metalness: 0.1, roughness: 0.8, ...commonProps }); // Майже білий
const eyeMaterial = new THREE.MeshStandardMaterial({ color: 0xaa3333, metalness: 0.0, roughness: 0.5, ...commonProps, opacity: 1.0 });
const noseMaterial = new THREE.MeshStandardMaterial({ color: 0xffb6c1, metalness: 0.2, roughness: 0.6, ...commonProps }); // Світло-рожевий
const whiskerMaterial = new THREE.MeshStandardMaterial({ color: 0x222222, metalness: 0.0, roughness: 0.5, ...commonProps, opacity: 1.0 });
const parts = [];
// --- Тулуб: Півсфера, площиною вниз ---
const body = new THREE.Mesh(new THREE.SphereGeometry(1, 32, 16, 0, Math.PI * 2, 0, Math.PI / 2), mouseBodyMaterial);
body.position.y = 0.4; // Плоске дно тулуба знаходиться на Y = 0.4
parts.push(body);
// --- Ноги: 4 маленькі півсфери під тулубом ---
// --- ВИПРАВЛЕНО: Створюємо НОВУ геометрію для КОЖНОЇ лапи ---
// І повернуто орієнтацію (0, Math.PI / 2) - "купол вниз", як ви і просили
const legFL = new THREE.Mesh(new THREE.SphereGeometry(0.3, 16, 8, 0, Math.PI * 2, 0, Math.PI / 2), mouseBodyMaterial);
legFL.position.set(-0.7, 0.4, 0.5); // Передня ліва (кріпиться до Y = 0.4)
const legFR = new THREE.Mesh(new THREE.SphereGeometry(0.3, 16, 8, 0, Math.PI * 2, 0, Math.PI / 2), mouseBodyMaterial);
legFR.position.set(0.7, 0.4, 0.5); // Передня права
const legBL = new THREE.Mesh(new THREE.SphereGeometry(0.3, 16, 8, 0, Math.PI * 2, 0, Math.PI / 2), mouseBodyMaterial);
legBL.position.set(-0.7, 0.4, -0.5); // Задня ліва
const legBR = new THREE.Mesh(new THREE.SphereGeometry(0.3, 16, 8, 0, Math.PI * 2, 0, Math.PI / 2), mouseBodyMaterial);
legBR.position.set(0.7, 0.4, -0.5); // Задня права
parts.push(legFL, legFR, legBL, legBR);
// --- Голова: Сфера + Конус ---
const headSphere = new THREE.Mesh(new THREE.SphereGeometry(0.6, 32, 16), mouseBodyMaterial);
headSphere.position.set(0, 0.7, 0.8);
const headCone = new THREE.Mesh(new THREE.ConeGeometry(0.4, 0.7, 32), mouseBodyMaterial);
headCone.position.set(0, 0.7, 1.45);
headCone.rotation.x = Math.PI / 2;
parts.push(headSphere, headCone);
// --- Ніс, Очі та ВУХА ---
const nose = new THREE.Mesh(new THREE.SphereGeometry(0.1, 16, 8), noseMaterial);
nose.position.set(0, 0.7, 1.8);
const eyeL = new THREE.Mesh(new THREE.SphereGeometry(0.1, 16, 8), eyeMaterial);
eyeL.position.set(-0.3, 1.0, 1.1);
const eyeR = new THREE.Mesh(new THREE.SphereGeometry(0.1, 16, 8), whiskerMaterial);
eyeR.position.set(0.3, 1.0, 1.1);
// --- ВИПРАВЛЕНО: НОВА геометрія для КОЖНОГО вуха ---
const earL = new THREE.Mesh(new THREE.CylinderGeometry(0.3, 0.3, 0.05, 20), noseMaterial);
earL.position.set(-0.5, 1.2, 0.8);
earL.rotation.set(Math.PI / 2.2, 0, -Math.PI / 10);
const earR = new THREE.Mesh(new THREE.CylinderGeometry(0.3, 0.3, 0.05, 20), noseMaterial);
earR.position.set(0.5, 1.2, 0.8);
earR.rotation.set(Math.PI / 2.3, 0, Math.PI / 10);
parts.push(nose, eyeL, eyeR, earL, earR);
// --- Вуса: 6 тонких циліндрів ---
// --- ВИПРАВЛЕНО: Збільшено товщину і НОВА геометрія для КОЖНОГО вуса ---
const whiskerPos = { x: 0, y: 0.7, z: 1.7 };
const whiskerRadius = 0.007; // Зроблено товстішими
const whiskerLength = 1.2; // Зроблено довшими
const wL1 = new THREE.Mesh(new THREE.CylinderGeometry(whiskerRadius, whiskerRadius, whiskerLength, 8), whiskerMaterial);
wL1.position.set(whiskerPos.x - 0.5, whiskerPos.y + 0.1, whiskerPos.z);
wL1.rotation.set(Math.PI / 20, 0.4, Math.PI / 2.3);
const wL2 = new THREE.Mesh(new THREE.CylinderGeometry(whiskerRadius, whiskerRadius, whiskerLength, 8), whiskerMaterial);
wL2.position.set(whiskerPos.x - 0.5, whiskerPos.y, whiskerPos.z);
wL2.rotation.set(0, 0.4, Math.PI / 2);
const wL3 = new THREE.Mesh(new THREE.CylinderGeometry(whiskerRadius, whiskerRadius, whiskerLength, 8), whiskerMaterial);
wL3.position.set(whiskerPos.x - 0.5, whiskerPos.y - 0.1, whiskerPos.z);
wL3.rotation.set(-Math.PI / 20, 0.4, Math.PI / 1.9);
const wR1 = new THREE.Mesh(new THREE.CylinderGeometry(whiskerRadius, whiskerRadius, whiskerLength, 8), whiskerMaterial);
wR1.position.set(whiskerPos.x + 0.5, whiskerPos.y + 0.1, whiskerPos.z);
wR1.rotation.set(Math.PI / 20, -0.4, -Math.PI / 2.3);
const wR2 = new THREE.Mesh(new THREE.CylinderGeometry(whiskerRadius, whiskerRadius, whiskerLength, 8), whiskerMaterial);
wR2.position.set(whiskerPos.x + 0.5, whiskerPos.y, whiskerPos.z);
wR2.rotation.set(0, -0.4, -Math.PI / 2);
const wR3 = new THREE.Mesh(new THREE.CylinderGeometry(whiskerRadius, whiskerRadius, whiskerLength, 8), whiskerMaterial);
wR3.position.set(whiskerPos.x + 0.5, whiskerPos.y - 0.1, whiskerPos.z);
wR3.rotation.set(-Math.PI / 20, -0.4, -Math.PI / 1.9);
parts.push(wL1, wL2, wL3, wR1, wR2, wR3);
// --- Хвіст: Вигнута труба + Конус на кінчику ---
// 1. Створюємо 3D-шлях (криву) для хвоста
const tailPath = new THREE.CatmullRomCurve3([
new THREE.Vector3(0, 0.6, -1.0), // 1. Початок: кріпиться до тулуба
new THREE.Vector3(0, 1.0, -2.5), // 2. Середина: вигинається вгору і назад
new THREE.Vector3(-0.9, 0.8, -3.5) // 3. Кінець: трохи вбік
]);
// 2. Створюємо геометрію труби (БЕЗ звуження)
const tailGeom = new THREE.TubeGeometry(
tailPath, // 3D-шлях
30, // Сегменти вздовж шляху
0.05, // Радіус труби
8, // Сегменти навколо
false // Не замкнений
);
const tail = new THREE.Mesh(tailGeom, noseMaterial); // Рожевий
parts.push(tail); // Додаємо трубу до "запікання"
// --- 3. Додаємо конус на кінчик ---
// Отримуємо останню точку шляху (де кінець труби)
const endPoint = tailPath.getPointAt(1.0);
// Отримуємо напрямок (тангенту) в цій точці
const tangent = tailPath.getTangentAt(1.0).normalize();
// Створюємо геометрію конуса (основа, висота)
const coneGeom = new THREE.ConeGeometry(0.05, 0.6, 8); // Основа = радіус труби
// "Запікаємо" зсув, щоб конус обертався навколо своєї основи
coneGeom.translate(0, 0.3, 0); //
const coneTip = new THREE.Mesh(coneGeom, noseMaterial);
// Ставимо основу конуса точно в кінець труби
coneTip.position.copy(endPoint);
// Орієнтуємо конус так, щоб він "ріс" у тому ж напрямку,
// в якому закінчилася труба
coneTip.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), tangent);
parts.push(coneTip); // Додаємо конус до "запікання"
// "Запікаємо" позиції та об'єднуємо
parts.forEach(mesh => {
mesh.updateMatrix();
mesh.geometry.applyMatrix4(mesh.matrix);
mesh.position.set(0,0,0);
mesh.rotation.set(0,0,0);
mesh.scale.set(1,1,1);
modelGroup.add(mesh);
});
break;
}
case 'hatHead':
default:
const headMaterial = new THREE.MeshStandardMaterial({ color: 0xffddaa, metalness: 0.2, roughness: 0.6, ...commonProps });
const hatMaterial = new THREE.MeshStandardMaterial({ color: 0x222222, metalness: 0.1, roughness: 0.4, ...commonProps });
const noseMaterial = new THREE.MeshStandardMaterial({ color: 0xff8c00, metalness: 0.2, roughness: 0.6, ...commonProps });
const eye1Material = new THREE.MeshStandardMaterial({ color: 0x00ff00, ...commonProps, opacity: 0.95 });
const eye2Material = new THREE.MeshStandardMaterial({ color: 0x0000ff, ...commonProps, opacity: 0.95 });
const head = new THREE.Mesh(new THREE.SphereGeometry(1, 32, 32), headMaterial);
const capBase = new THREE.Mesh(new THREE.CylinderGeometry(0.7, 0.7, 0.4, 32), hatMaterial);
capBase.position.y = 0.8;
const mortarboard = new THREE.Mesh(new THREE.BoxGeometry(1.4, 0.1, 1.4), hatMaterial);
mortarboard.position.y = 1.05;
const nose = new THREE.Mesh(new THREE.BoxGeometry(0.3, 0.3, 0.45), noseMaterial);
nose.position.z = 1.0;
const eye1 = new THREE.Mesh(new THREE.SphereGeometry(0.1, 16, 16), eye1Material);
eye1.position.set(-0.3, 0.3, 0.85);
const eye2 = new THREE.Mesh(new THREE.SphereGeometry(0.12, 16, 16), eye2Material);
eye2.position.set(0.3, 0.3, 0.85);
[capBase, mortarboard, nose, eye1, eye2].forEach(mesh => {
mesh.updateMatrix();
mesh.geometry.applyMatrix4(mesh.matrix);
mesh.position.set(0,0,0);
mesh.rotation.set(0,0,0);
mesh.scale.set(1,1,1);
});
modelGroup.add(head, capBase, mortarboard, nose, eye1, eye2);
break;
}
return modelGroup;
}
// Функція для зміни моделі
window.changeModel = function() {
const modelName = document.getElementById('model-select').value;
// 1. Видаляємо старі моделі з обгорток
if (originalModel) originalWrapper.remove(originalModel);
if (transformedModel) transformedWrapper.remove(transformedModel);
if (lowrankModel) lowrankWrapper.remove(lowrankModel);
// 2. Створюємо нову оригінальну модель
originalModel = createSelectedModel(modelName);
originalWrapper.add(originalModel);
// 3. Клонуємо для трансформованої
transformedModel = originalModel.clone(true);
transformedWrapper.add(transformedModel);
// 4. Клонуємо та налаштовуємо для Low-Rank
lowrankModel = originalModel.clone(true);
let order = 0;
lowrankModel.traverse(obj => { if (obj.isMesh) obj.renderOrder = order++; });
lowrankModel.traverse((child) => {
if (child.isMesh) {
child.material = child.material.clone();
child.material.transparent = true;
child.material.opacity = 0.6;
child.material.metalness = 0;
child.material.roughness = 1;
child.material.depthWrite = false;
child.material.blending = THREE.NormalBlending;
if (child.material.color) { // Перевірка, чи існує колір
child.material.emissive = new THREE.Color(child.material.color);
child.material.emissiveIntensity = 0.3;
}
}
});
lowrankWrapper.add(lowrankModel);
// 5. Оновлюємо трансформацію для нових моделей
updateTransformation();
}
function toNestedArray(flat) {
return [[flat[0], flat[1], flat[2]], [flat[3], flat[4], flat[5]], [flat[6], flat[7], flat[8]]];
}
function toFlatArray(nested) {
return [].concat.apply([], nested);
}
function computeLowRankApproximationSVD(matrix, rank) {
try {
const M = toNestedArray(matrix);
const svd = numeric.svd(M);
lastSVD = svd; // Зберігаємо SVD для показу векторів
const S_prime = svd.S.map((val, i) => (i < rank) ? val : 0);
const S_matrix = numeric.diag(S_prime);
const US = numeric.dot(svd.U, S_matrix);
const A_prime = numeric.dot(US, numeric.transpose(svd.V));
return toFlatArray(A_prime);
} catch (e) {
console.error("SVD calculation failed:", e);
lastSVD = null;
return [1,0,0, 0,1,0, 0,0,1]; // Return identity on error
}
}