-
Notifications
You must be signed in to change notification settings - Fork 482
Expand file tree
/
Copy pathpreview.ts
More file actions
2801 lines (2590 loc) · 92.7 KB
/
Copy pathpreview.ts
File metadata and controls
2801 lines (2590 loc) · 92.7 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
import { THREE } from '../lib/libs';
import OrbitControls from './OrbitControls';
import StateMemory from "../util/state_memory";
import { ConfigDialog } from '../interface/dialog';
import { toSnakeCase } from '../util/util';
import { electron, ipcRenderer } from '../native_apis';
import { Pressing } from '../misc';
import { CSS3DRenderer } from '../lib/CSS3DRenderer';
import { PointerTarget } from '../interface/pointer_target';
import { unselectInterface } from '../interface/interface';
import { sameMeshEdge } from '../modeling/mesh/util';
interface AnglePreset {
name?: string
id?: string
color?: string
condition?: ConditionResolvable
default?: true
position: ArrayVector3
target?: ArrayVector3
rotation?: ArrayVector3
projection: 'unset' | 'orthographic' | 'perspective'
zoom?: number
focal_length?: number
fov?: number
aspect_ratio?: number
locked_angle?: number
}
type PreviewAnnotation = {
node: HTMLElement
object: THREE.Object3D
}
export type RaycastResult = {
type: 'element' | 'keyframe' | 'vertex' | 'cube' | 'line' | 'none'
event: PointerEvent | MouseEvent | TouchEvent
cube?: Cube
intersects?: THREE.Intersection[]
intersect?: THREE.Intersection
face?: string
vertex?: any
vertices?: [string, string]
keyframe?: _Keyframe
vertex_index?: number
element?: OutlinerElement
}
type SplitScreenMode = 'single'|'double_horizontal'|'double_vertical'|'quad'|'triple_left'|'triple_right'|'triple_top'|'triple_bottom'
let main_preview: Preview = null;
let MediaPreview: Preview = null;
const NormalY = new THREE.Vector3(0, 1, 0);
var framespersecond = 0;
const canvas_scenes: Record<string, ReferenceImage> = {};
export const three_grid = new THREE.Object3D();
export const gizmo_colors = {
r: new THREE.Color(),
g: new THREE.Color(),
b: new THREE.Color(),
grid: new THREE.Color(),
solid: new THREE.Color(),
outline: new THREE.Color(),
gizmo_hover: new THREE.Color(),
spline_handle_aligned: new THREE.Color(),
spline_handle_mirrored: new THREE.Color(),
spline_handle_free: new THREE.Color(),
// used by spline sliders, to make it clear that they
// operate in a different space than the scene XYZ
u: new THREE.Color(),
v: new THREE.Color(),
w: new THREE.Color(),
}
export const DefaultCameraPresets = [
{
name: 'menu.preview.angle.initial',
id: 'initial',
projection: 'perspective',
get position() {
let base;
switch (Format.forward_direction) {
case '+x': base = [40, 32, -40]; break;
case '-x': base = [-40, 32, 40]; break;
case '+z': base = [40, 32, 40]; break;
case '-z': default: base = [-40, 32, -40]; break;
}
if (!Format) return base;
return base.map(v => v * (Format.block_size / 16));
},
get target() {
let block_size = Format.block_size ?? 16;
return [0, block_size * 0.75, 0]
},
default: true
},
{
name: 'direction.top',
id: 'top',
projection: 'orthographic',
color: 'y',
position: [0, 512, 0],
target: [0, 0, 0],
zoom: 0.5,
locked_angle: 'top',
default: true
},
{
name: 'direction.bottom',
id: 'bottom',
projection: 'orthographic',
color: 'y',
position: [0, -512, 0],
target: [0, 0, 0],
zoom: 0.5,
locked_angle: 'bottom',
default: true
},
{
name: 'direction.south',
id: 'south',
projection: 'orthographic',
color: 'z',
position: [0, 0, 512],
target: [0, 0, 0],
zoom: 0.5,
locked_angle: 'south',
default: true
},
{
name: 'direction.north',
id: 'north',
projection: 'orthographic',
color: 'z',
position: [0, 0, -512],
target: [0, 0, 0],
zoom: 0.5,
locked_angle: 'north',
default: true
},
{
name: 'direction.east',
id: 'east',
projection: 'orthographic',
color: 'x',
position: [512, 0, 0],
target: [0, 0, 0],
zoom: 0.5,
locked_angle: 'east',
default: true
},
{
name: 'direction.west',
id: 'west',
projection: 'orthographic',
color: 'x',
position: [-512, 0, 0],
target: [0, 0, 0],
zoom: 0.5,
locked_angle: 'west',
default: true
},
{
name: 'camera_angle.common_isometric_right',
id: 'isometric_right',
projection: 'orthographic',
position: [-512, 512*0.8165+8, -512],
target: [0, 8, 0],
zoom: 0.5,
default: true
},
{
name: 'camera_angle.common_isometric_left',
id: 'isometric_left',
projection: 'orthographic',
position: [512, 512*0.8165+8, -512],
target: [0, 8, 0],
zoom: 0.5,
default: true
},
{
name: 'camera_angle.true_isometric_right',
id: 'true_isometric_right',
projection: 'orthographic',
position: [-512, 512+8, -512],
target: [0, 8, 0],
zoom: 0.5,
default: true
},
{
name: 'camera_angle.true_isometric_left',
id: 'true_isometric_left',
projection: 'orthographic',
position: [512, 512+8, -512],
target: [0, 8, 0],
zoom: 0.5,
default: true
}
] as AnglePreset[]
interface PreviewOptions {
id: string
antialias?: boolean
offscreen?: boolean
}
/**
* Previews are 3D viewports, that can either be used as a viewport for the user, or as an offscreen view to record media.
*/
export class Preview {
id: string
canvas: HTMLCanvasElement
height: number
width: number
aspect_ratio?: number
node: HTMLElement
label: HTMLLabelElement
/**
* True if the preview is in orthographic camera mode
*/
isOrtho: boolean
/**
* Angle, when in a specific side view
*/
angle: null | string
default_angle: AnglePreset
camPers: THREE.PerspectiveCamera
camOrtho: THREE.OrthographicCamera & {axis: string, backgroundHandle: any}
controls: any
annotations: Record<string, PreviewAnnotation>
offscreen?: boolean
renderer: THREE.WebGLRenderer
css_renderer?: CSS3DRenderer
background: {
name: string
image: any
size: number
x: number
y: number
lock: boolean
}
side_view_target: THREE.Vector3
raycaster: THREE.Raycaster
orbit_gizmo?: OrbitGizmo
selection: {
box: HTMLElement,
frustum: THREE.Frustum
activated: boolean
start_x: number
start_y: number
client_x: number
client_y: number
sr_move_f?: any
sr_stop_f?: any
click_target?: RaycastResult
old_selected?: OutlinerElement[]
old_mesh_selection?: any
old_spline_selection?: any
deferred_event?: PointerEvent
}
static_rclick: boolean
rclick_cooldown: any
event_start?: ArrayVector2
mouse: THREE.Vector2
constructor(options: PreviewOptions) {
var scope = this;
if (options && options.id) {
this.id = options.id
}
//Node
this.canvas = document.createElement('canvas');
// @ts-expect-error
this.canvas.preview = this;
this.height = 0;
this.width = 0;
this.node = document.createElement('div')
this.node.className = 'preview';
this.node.appendChild(this.canvas);
let menu = $(`
<div class="preview_menu">
<div class="tool preview_fullscreen_button quad_view_only"><i class="material-icons">fullscreen</i></div>
<div class="tool preview_view_mode_menu one_is_enough"><i class="material-icons">image</i></div>
<div class="tool preview_view_options one_is_enough"><i class="material-icons">discover_tune</i></div>
<div class="tool preview_main_menu"><i class="material-icons">menu</i></div>
</div>`)[0];
/*menu.querySelector('.preview_reference_menu').onclick = (event) => {
BarItems.edit_reference_images.trigger();
}*/
(menu.querySelector('.preview_main_menu') as HTMLElement).onclick = (event) => {
this.menu.open(menu, this);
}
(menu.querySelector('.preview_view_options') as HTMLElement).onclick = (event) => {
ViewOptionsDialog.show(menu);
let preview_rect = Interface.preview.getBoundingClientRect();
ViewOptionsDialog.object.style.left = 'auto';
ViewOptionsDialog.object.style.right = (window.innerWidth-preview_rect.right) + 'px';
}
(menu.querySelector('.preview_fullscreen_button') as HTMLElement).onclick = (event) => {
this.fullscreen();
}
(menu.querySelector('.preview_view_mode_menu') as HTMLElement).onclick = (event) => {
BarItems.view_mode.open(event);
}
BarItem.prototype.addLabel(false, {
name: tl('menu.preview.maximize'),
node: menu.querySelector('.preview_fullscreen_button')
})
BarItem.prototype.addLabel(false, {
name: tl('action.view_mode'),
node: menu.querySelector('.preview_view_mode_menu')
})
/*BarItem.prototype.addLabel(false, {
name: tl('action.edit_reference_images'),
node: menu.querySelector('.preview_reference_menu')
})*/
BarItem.prototype.addLabel(false, {
name: tl('dialog.preview_options.title'),
node: menu.querySelector('.preview_view_options')
})
BarItem.prototype.addLabel(false, {
name: tl('data.preview'),
node: menu.querySelector('.preview_main_menu')
})
this.node.appendChild(menu)
//Cameras
this.offscreen = !!options.offscreen;
this.isOrtho = false;
this.angle = null;
this.camPers = new THREE.PerspectiveCamera(settings.fov.value as number, 16 / 9, settings.camera_near_plane.value as number||1, 30000);
// @ts-expect-error
this.camOrtho = new THREE.OrthographicCamera(-600, 600, -400, 400, -200, 20000);
this.camOrtho.backgroundHandle = [{n: false, a: 'x'}, {n: false, a: 'y'}]
this.camOrtho.axis = null
this.camOrtho.zoom = 0.5
// @ts-expect-error
this.camPers.preview = this.camOrtho.preview = this;
for (var i = 4; i <= 6; i++) {
this.camPers.layers.enable(i);
}
this.side_view_target = new THREE.Vector3();
//Controls
this.controls = new OrbitControls(this.camPers, this);
this.controls.minDistance = 1;
this.controls.maxDistance = 3960;
this.controls.enableKeys = false;
this.controls.zoomSpeed = (settings.viewport_zoom_speed.value as number) / 100 * 1.5;
this.controls.rotateSpeed = (settings.viewport_rotate_speed.value as number) / 100;
this.controls.onUpdate(() => {
if (this.angle != null) {
if (this.camOrtho.axis != 'x') this.side_view_target.x = this.controls.target.x;
if (this.camOrtho.axis != 'y') this.side_view_target.y = this.controls.target.y;
if (this.camOrtho.axis != 'z') this.side_view_target.z = this.controls.target.z;
}
})
//Annotations
this.annotations = {};
this.controls.onUpdate(() => setTimeout(() => {
scope.updateAnnotations();
}, 6))
this.default_angle = DefaultCameraPresets[0];
this.camPers.position.fromArray(this.default_angle.position);
this.controls.target.fromArray(this.default_angle.target);
if (!Blockbench.isMobile && !this.offscreen) {
this.orbit_gizmo = new OrbitGizmo(this);
this.node.append(this.orbit_gizmo.node);
}
//Keybinds
this.controls.mouseButtons.ZOOM = undefined;
//Renderer
try {
this.renderer = new THREE.WebGLRenderer({
canvas: this.canvas,
antialias: typeof options.antialias == 'boolean' ? options.antialias : Settings.get('antialiasing') as boolean,
alpha: true,
preserveDrawingBuffer: true
});
} catch (err) {
let error_element = document.querySelector('#loading_error_detail')
error_element.innerHTML = `Error creating WebGL context. Try to update your ${isApp ? 'graphics drivers' : 'web browser'}.`
if (isApp) {
// @ts-expect-error
window.restartWithoutHardwareAcceleration = function() {
ipcRenderer.send('edit-launch-setting', {key: 'hardware_acceleration', value: false});
settings.hardware_acceleration.value = false;
Settings.saveLocalStorages();
electron.app.relaunch()
electron.app.quit()
}
error_element.innerHTML = error_element.innerHTML +
'\nAlternatively, try to <a href onclick="restartWithoutHardwareAcceleration()">Restart without Hardware Acceleration.</a>'
var {BrowserWindow} = electron;
new BrowserWindow({
icon:'icon.ico',
backgroundColor: '#ffffff',
title: 'Blockbench GPU Information',
webPreferences: {
webgl: true,
webSecurity: true,
nodeIntegration: true
}
}).loadURL('chrome://gpu')
}
throw err;
}
this.renderer.setClearColor( 0x000000, 0 )
this.renderer.setSize(500, 400);
this.updateToneMapping();
if (!options.offscreen) {
this.css_renderer = new CSS3DRenderer({domElement: this.node});
this.css_renderer.setSize(500, 400);
this.node.append(this.css_renderer.domElement);
this.css_renderer.domElement.classList.add('preview_css_renderer_canvas')
}
this.selection = {
box: Interface.createElement('div', {id: 'selection_box', class: 'selection_rectangle'}),
frustum: new THREE.Frustum(),
activated: false,
start_x: 0,
start_y: 0,
client_x: 0,
client_y: 0,
}
this.label = Interface.createElement('label', {class: 'preview_perspective_label'}) as HTMLLabelElement;
this.node.append(this.label);
this.raycaster = new THREE.Raycaster();
this.mouse = new THREE.Vector2();
addEventListeners(this.canvas, 'pointerdown', (event: PointerEvent) => {
// Self-healing: on every genuine pointerdown, clean up any leftover
// state from a previous interaction that wasn't properly finalized.
if (this.selection.deferred_event || this.selection.sr_stop_f) {
if (this.selection.sr_move_f) {
removeEventListeners(document, 'mousemove touchmove', this.selection.sr_move_f);
delete this.selection.sr_move_f;
}
if (this.selection.sr_stop_f) {
removeEventListeners(document, 'mouseup touchend', this.selection.sr_stop_f);
delete this.selection.sr_stop_f;
}
this.selection.box.remove();
this.selection.deferred_event = null;
this.selection.activated = false;
}
this.click(event)
}, { passive: false });
addEventListeners(this.canvas, 'mousemove touchmove', (event: MouseEvent) => {
if (!this.static_rclick) return;
convertTouchEvent(event);
let threshold = 7;
if (!this.event_start || !Math.epsilon(this.event_start[0], event.clientX, threshold) || !Math.epsilon(this.event_start[1], event.clientY, threshold)) {
this.static_rclick = false;
}
}, false);
addEventListeners(this.canvas, 'mousemove touchmove', (event: MouseEvent) => {
if (PointerTarget.active == PointerTarget.types.global_drag_slider) return;
this.mousemove(event)
}, false);
addEventListeners(this.canvas, 'mouseup touchend', (event: MouseEvent) => {
this.mouseup(event)
}, false);
addEventListeners(this.canvas, 'dblclick', (event: MouseEvent) => {
if (settings.double_click_switch_tools.value) {
Toolbox.toggleTransforms(event);
}
}, false);
addEventListeners(this.canvas, 'mouseenter touchstart', (event: MouseEvent) => {
this.occupyTransformer(event)
}, false);
addEventListeners(this.canvas, 'mouseenter', (event: MouseEvent) => {
this.controls.hasMoved = true
}, false);
Preview.all.push(this);
}
// MARK: Render
/**
* Set a size of the preview in pixels. With no arguments, and if the preview node is connected to the DOM, it will adjust to the size of the parent element
*/
resize(width?: number, height?: number) {
if (this.canvas.isConnected && this !== MediaPreview) {
this.height = this.node.parentElement.clientHeight;
this.width = this.node.parentElement.clientWidth;
if (this.aspect_ratio) {
let natural_ratio = this.width/this.height;
if (Math.abs(natural_ratio-this.aspect_ratio) > 0.02) {
if (natural_ratio < this.aspect_ratio) {
this.height = this.width / this.aspect_ratio;
} else {
this.width = this.height * this.aspect_ratio;
}
}
this.node.classList.add('fixed_ratio');
} else {
this.node.classList.remove('fixed_ratio');
}
} else if (height && width) {
this.height = height;
this.width = width;
} else {
return this;
}
if (this.isOrtho === false) {
this.camPers.aspect = this.width / this.height
this.camPers.updateProjectionMatrix();
} else {
this.camOrtho.right = this.width / 80
this.camOrtho.left = this.camOrtho.right*-1
this.camOrtho.top = this.height / 80
this.camOrtho.bottom = this.camOrtho.top*-1
this.camOrtho.updateProjectionMatrix();
}
this.renderer.setSize(this.width, this.height);
if (this.css_renderer) this.css_renderer.setSize(this.width, this.height);
if (this.canvas.isConnected) {
this.renderer.setPixelRatio(window.devicePixelRatio);
if ("Transformer" in window) {
Transformer.update()
}
}
return this;
}
updateToneMapping() {
switch (settings.tone_mapping.value) {
case 'none': this.renderer.toneMapping = THREE.NoToneMapping; break;
case 'linear': this.renderer.toneMapping = THREE.LinearToneMapping; break;
case 'reinhard': this.renderer.toneMapping = THREE.ReinhardToneMapping; break;
case 'cineon': this.renderer.toneMapping = THREE.CineonToneMapping; break;
case 'aces_filmic': this.renderer.toneMapping = THREE.ACESFilmicToneMapping; break;
//case 'agx': this.renderer.toneMapping = THREE.AgXToneMapping; break;
//case 'neutral': this.renderer.toneMapping = THREE.NeutralToneMapping; break;
}
}
raycast(event: MouseEvent, options = Toolbox.selected.raycast_options || {}): false | RaycastResult {
convertTouchEvent(event);
var canvas_offset = $(this.canvas).offset()
this.mouse.x = ((event.clientX - canvas_offset.left) / this.width) * 2 - 1;
this.mouse.y = - ((event.clientY - canvas_offset.top) / this.height) * 2 + 1;
this.raycaster.setFromCamera( this.mouse, this.camera );
var objects = []
Outliner.elements.forEach(element => {
if (element.visibility === false || element.locked === true || (element.mesh && element.mesh.visible == false)) return;
if (element.mesh && 'geometry' in element.mesh) {
objects.push(element.mesh);
if (Modes.edit && element.selected) {
// @ts-expect-error
if (element.mesh.vertex_points && (element.mesh.vertex_points.visible || options.vertices)) {
// @ts-expect-error
objects.push(element.mesh.vertex_points);
}
if (element instanceof Mesh && ((element.mesh.outline.visible && BarItems.selection_mode.value == 'edge') || options.edges)) {
objects.push(element.mesh.outline);
}
} else if (element instanceof SplineMesh && 'render_mode' in element && element.render_mode !== "mesh") {
// @ts-expect-error
objects.push(element.mesh.pathLine);
}
} else if (element instanceof Locator) {
// @ts-expect-error
objects.push(element.mesh.sprite);
} else if (element instanceof ArmatureBone) {
if (Toolbox.selected.id == 'weight_brush' && !(event.altKey || Pressing.overrides.alt)) return;
objects.push(element.mesh.children[0]);
}
})
for (let group of Group.multi_selected) {
// @ts-expect-error
if (group.mesh.vertex_points) objects.push(group.mesh.vertex_points);
}
if (Animator.open && settings.motion_trails.value && Group.first_selected) {
Animator.motion_trail.children.forEach(object => {
// @ts-expect-error
if (object.isKeyframe === true) {
objects.push(object)
}
})
}
let intersects = this.raycaster.intersectObjects(objects, false);
if (intersects.length == 0) return false;
let depth_offset = Preview.selected.calculateControlScale(intersects[0].point);
for (let intersect of intersects) {
// @ts-expect-error
if (intersect.object.isLine) {
intersect.distance -= depth_offset;
// @ts-expect-error
} else if (intersect.object.isPoints) {
intersect.distance -= depth_offset * 1.4;
}
}
if (Toolbox.selected.id == 'vertex_snap_tool') {
intersects.sort((a, b) => {
// @ts-expect-error
if (a.object.isPoints != b.object.isPoints) return a.object.isPoints ? -100 : 100;
return a.distance - b.distance;
});
} else {
intersects.sort((a, b) => {
if (a.object.renderOrder > 10 || b.object.renderOrder > 10) {
return b.object.renderOrder - a.object.renderOrder;
}
return a.distance - b.distance;
});
}
if ((settings.seethrough_outline.value && BarItems.selection_mode.value == 'edge')) {
let all_intersects = intersects;
// @ts-expect-error
intersects = intersects.filter(a => a.object.isLine);
if (intersects.length == 0) intersects = all_intersects;
}
let intersect = intersects[0];
let intersect_object = intersect.object;
if (intersect_object.isElement) {
let element, face;
while (true) {
element = OutlinerNode.uuids[intersect_object.name];
if (element.getTypeBehavior('cube_faces')) {
if (element.getTypeBehavior('select_faces')) {
// @ts-expect-error
face = intersect_object.geometry.faces[Math.floor(intersects[0].faceIndex / 2)];
} else {
face = Object.keys(element.faces)[0];
}
} else if (element instanceof Mesh) {
let index = intersects[0].faceIndex;
for (let key in element.faces) {
let {vertices} = element.faces[key];
if (vertices.length < 3) continue;
if (index == 0 || (index == 1 && vertices.length == 4)) {
face = key;
break;
}
if (vertices.length == 3) index -= 1;
if (vertices.length == 4) index -= 2;
}
} else if (element instanceof SplineMesh) {
let index = intersects[0].faceIndex;
for (let key in element.faces) {
let {vertices} = element.faces[key];
if (index == 0 || (index == 1 && vertices.length == 4)) {
face = key;
break;
}
index -= 2;
}
}
if (Modes.paint && (Toolbox.selected.id == 'color_picker' || (Painter.lock_alpha && Settings.get('paint_through_transparency')))) {
let texture = element.faces[face].getTexture();
if (texture) {
let [x, y] = Painter.getCanvasToolPixelCoords(intersects[0].uv, texture);
let ctx = Painter.getCanvas(texture).getContext('2d');
let color = Painter.getPixelColor(ctx, x, y);
if (color.getAlpha() < 0.004) {
intersects.shift();
while (intersects.length && !intersects[0].object.isElement) {
intersects.shift();
}
if (!intersects[0]) return false;
intersect_object = intersects[0].object;
continue;
}
}
}
break;
}
return {
type: 'element',
event,
intersects,
face,
element
}
// @ts-expect-error
} else if (intersect_object.isKeyframe) {
// @ts-expect-error
let uuid = intersect_object.keyframeUUIDs[intersect.index];
let keyframe = Timeline.keyframes.find(kf => kf.uuid == uuid);
return {
event,
type: 'keyframe',
intersects,
keyframe: keyframe
}
} else if (intersect_object.type == 'Points') {
// @ts-expect-error
var element = OutlinerNode.uuids[intersect_object.element_uuid] as OutlinerElement;
let vertex = element instanceof Mesh
? Object.keys(element.vertices)[intersect.index]
// @ts-expect-error
: intersect_object.vertices[intersect.index];
return {
event,
type: 'vertex',
element,
intersects,
intersect,
vertex,
vertex_index: intersect.index,
}
} else if (intersect_object.type == 'LineSegments') {
let element = OutlinerNode.uuids[intersect_object.parent.name] as OutlinerElement;
let vertices;
// @ts-expect-error
if (!(element instanceof SplineMesh)) vertices = intersect_object.vertex_order.slice(intersect.index, intersect.index+2);
return {
event,
type: 'line',
element,
intersects,
intersect,
vertices
}
}
}
render() {
this.controls.update();
this.renderer.render(Canvas.scene, this.camera);
if (this.css_renderer) {
this.css_renderer.render(Canvas.scene, this.camera, this == Preview.selected);
}
}
// MARK: Camera
get camera(): THREE.PerspectiveCamera | THREE.OrthographicCamera {
return this.isOrtho ? this.camOrtho : this.camPers;
}
setProjectionMode(orthographic: boolean, toggle?: boolean): this {
let position = this.camera.position;
this.isOrtho = !!orthographic;
this.resize()
this.controls.object = this.camera;
this.camera.position.copy(position);
if (toggle) {
let perspective_distance = this.camPers.position.distanceTo(this.controls.target);
let factor = 0.64 * devicePixelRatio * this.camPers.getFocalLength();
if (this.isOrtho) {
this.camera.zoom = factor / perspective_distance;
} else {
let target_distance = factor / this.camOrtho.zoom;
let cam_offset = new THREE.Vector3().copy(this.camPers.position).sub(this.controls.target);
cam_offset.multiplyScalar(target_distance / perspective_distance);
this.camPers.position.copy(cam_offset).add(this.controls.target);
}
}
if (!this.offscreen) {
this.setLockedAngle();
this.controls.updateSceneScale();
}
if (this == Preview.selected) {
this.occupyTransformer();
}
return this;
}
setFOV(fov: number): void {
this.camPers.fov = fov;
this.camPers.updateProjectionMatrix();
}
setNormalCamera() {
//Deprecated
this.setProjectionMode(false)
return this;
}
setLockedAngle(angle?: number): this {
if (typeof angle === 'string' && this.isOrtho) {
this.angle = angle
this.controls.enableRotate = false;
switch (angle) {
case 'top':
this.camOrtho.axis = 'y'
this.camOrtho.backgroundHandle = [{n: false, a: 'x'}, {n: false, a: 'z'}]
break;
case 'bottom':
this.camOrtho.axis = 'y'
this.camOrtho.backgroundHandle = [{n: false, a: 'x'}, {n: true, a: 'z'}]
break;
case 'south':
this.camOrtho.axis = 'z'
this.camOrtho.backgroundHandle = [{n: false, a: 'x'}, {n: true, a: 'y'}]
break;
case 'north':
this.camOrtho.axis = 'z'
this.camOrtho.backgroundHandle = [{n: true, a: 'x'}, {n: true, a: 'y'}]
break;
case 'east':
this.camOrtho.axis = 'x'
this.camOrtho.backgroundHandle = [{n: true, a: 'z'}, {n: true, a: 'y'}]
break;
case 'west':
this.camOrtho.axis = 'x'
this.camOrtho.backgroundHandle = [{n: false, a: 'z'}, {n: true, a: 'y'}]
break;
}
var layer = getAxisNumber(this.camOrtho.axis)+1;
this.camOrtho.layers.set(0);
this.camOrtho.layers.enable(layer);
for (var i = 1; i <= 3; i++) {
if (i != layer) {
this.camOrtho.layers.enable(i+3);
}
}
if (this.camOrtho.axis != 'x') {
this.controls.target.x = this.camOrtho.position.x = this.side_view_target.x;
}
if (this.camOrtho.axis != 'y') {
this.controls.target.y = this.camOrtho.position.y = this.side_view_target.y;
}
if (this.camOrtho.axis != 'z') {
this.controls.target.z = this.camOrtho.position.z = this.side_view_target.z;
}
this.label.textContent = tl(`direction.${angle}`);
} else {
this.angle = null;
this.camOrtho.axis = null
this.camOrtho.layers.set(0);
this.camOrtho.layers.enable(4);
this.camOrtho.layers.enable(5);
this.camOrtho.layers.enable(6);
this.resize()
this.controls.enableRotate = true;
this.label.textContent = '';
}
Transformer.update();
ReferenceImage.updateAll();
return this;
}
setDefaultAnglePreset(preset: AnglePreset) {
this.default_angle = preset;
this.loadAnglePreset(preset);
return this;
}
loadAnglePreset(preset: AnglePreset): this {
if (!preset) return;
this.camera.position.fromArray(preset.position);
if (preset.target) {
this.controls.target.fromArray(preset.target);
} else if (preset.rotation) {
this.controls.target.set(0, 0, 16).applyEuler(new THREE.Euler(
Math.degToRad(preset.rotation[0]),
Math.degToRad(preset.rotation[1]),
Math.degToRad(preset.rotation[2]),
'ZYX'
));
this.controls.target.add(this.camera.position);
}
if (this.aspect_ratio != preset.aspect_ratio) {
this.aspect_ratio = preset.aspect_ratio;
}
if (preset.projection !== 'unset') {
this.setProjectionMode(preset.projection == 'orthographic')
}
if (this.isOrtho && preset.zoom && !preset.locked_angle) {
this.camera.zoom = preset.zoom;
this.camera.updateProjectionMatrix()
}
if (!this.isOrtho) {
if (typeof preset.focal_length == 'number') {
// Only used for display mode and similar presets
this.camPers.setFocalLength(preset.focal_length);
} else {
this.setFOV(preset.fov ?? Settings.get('fov') as number);
}
}
this.setLockedAngle(preset.locked_angle)
return this;
}
/**
* Opens a dialog to create and save a new angle preset
*/
newAnglePreset(): this {
let scope = this;
let position = scope.camera.position.toArray();
let target = scope.controls.target.toArray();
position.forEach((v, i) => {
position[i] = Math.round(v*100)/100
})
target.forEach((v, i) => {
target[i] = Math.round(v*100)/100
})
let rotation_mode = 'target';
let dialog = new Dialog({
id: 'save_angle',
title: 'menu.preview.save_angle',
width: 540,
form: {
name: {label: 'generic.name'},
projection: {label: 'dialog.save_angle.projection', type: 'select', default: 'unset', options: {
unset: 'generic.unset',
perspective: 'dialog.save_angle.projection.perspective',
orthographic: 'dialog.save_angle.projection.orthographic'
}},
divider1: '_',
rotation_mode: {label: 'dialog.save_angle.rotation_mode', type: 'inline_select', value: rotation_mode, options: {
target: 'dialog.save_angle.target',
rotation: 'dialog.save_angle.rotation'
}},
position: {label: 'dialog.save_angle.position', type: 'vector', dimensions: 3, value: position},
target: {label: 'dialog.save_angle.target', type: 'vector', dimensions: 3, value: target, condition: ({rotation_mode}) => rotation_mode == 'target'},
rotation: {label: 'dialog.save_angle.rotation', type: 'vector', dimensions: 2, condition: ({rotation_mode}) => rotation_mode == 'rotation'},
zoom: {label: 'dialog.save_angle.zoom', type: 'number', value: Math.roundTo(scope.camOrtho.zoom || 1, 4), condition: result => scope.isOrtho},
},
onFormChange(form) {
if (form.rotation_mode !== rotation_mode) {
rotation_mode = form.rotation_mode as string;
if (form.rotation_mode == 'rotation') {
this.setFormValues({rotation: cameraTargetToRotation(form.position, form.target).map(trimFloatNumber)});
} else {
this.setFormValues({target: cameraRotationToTarget(form.position, form.rotation).map(trimFloatNumber)});
}
}
},
onConfirm: function(formResult) {
if (!formResult.name) return;
let preset: AnglePreset = {
name: formResult.name,
projection: formResult.projection,
position: formResult.position,
target: formResult.target,
}
if (scope.isOrtho) preset.zoom = scope.camOrtho.zoom;
let presets: AnglePreset[];
try {
presets = JSON.parse(localStorage.getItem('camera_presets'))||[]
} catch (err) {
presets = [];
}
presets.push(preset);
localStorage.setItem('camera_presets', JSON.stringify(presets))
dialog.hide()
}
})
dialog.show()
return this;
}
//Orientation
getFacingDirection(): 'north' | 'south' | 'east' | 'west' {
var vec = new THREE.Vector3()
this.controls.object.getWorldDirection(vec)
vec.applyAxisAngle(new THREE.Vector3(0, 1, 0), Math.PI / 4).ceil()
switch (vec.x+'_'+vec.z) {
case '1_1':
return 'south'
break;
case '0_0':
return 'north'
break;
case '1_0':
return 'east'
break;
case '0_1':
return 'west'
break;
}
}
getFacingHeight(): 'up' | 'middle' | 'down' {
var y = this.controls.object.getWorldDirection(new THREE.Vector3()).y
if (y > 0.5) {
return 'up'
} else if (y < -0.5) {
return 'down';
} else {
return 'middle'
}