@sequent-org/ifc-viewer 1.2.4-ci.52.0 → 1.2.4-ci.54.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1071 @@
1
+ import * as THREE from "three";
2
+
3
+ class LabelMarker {
4
+ /**
5
+ * @param {object} deps
6
+ * @param {number|string} deps.id
7
+ * @param {THREE.Vector3} deps.localPoint
8
+ * @param {HTMLElement} deps.el
9
+ * @param {object|null} deps.sceneState
10
+ */
11
+ constructor(deps) {
12
+ this.id = deps.id;
13
+ this.localPoint = deps.localPoint;
14
+ this.el = deps.el;
15
+ this.sceneState = deps.sceneState || null;
16
+ }
17
+ }
18
+
19
+ /**
20
+ * UI-контроллер: "+ Добавить метку" → призрак у курсора → установка метки кликом по модели.
21
+ *
22
+ * Важно:
23
+ * - метка хранит координату в ЛОКАЛЬНЫХ координатах activeModel, чтобы "ехать" вместе с моделью при её перемещении.
24
+ * - во время режима постановки блокируем обработку LMB у OrbitControls/других контроллеров (capture-phase).
25
+ */
26
+ export class LabelPlacementController {
27
+ /**
28
+ * @param {object} deps
29
+ * @param {import('../viewer/Viewer.js').Viewer} deps.viewer
30
+ * @param {HTMLElement} deps.container Контейнер viewer (обычно #app)
31
+ * @param {object} [deps.logger]
32
+ */
33
+ constructor(deps) {
34
+ this.viewer = deps.viewer;
35
+ this.container = deps.container;
36
+ this.logger = deps.logger || null;
37
+
38
+ this._placing = false;
39
+ this._nextId = 1;
40
+ /** @type {LabelMarker[]} */
41
+ this._markers = [];
42
+ this._selectedId = null;
43
+
44
+ this._raycaster = new THREE.Raycaster();
45
+ this._ndc = new THREE.Vector2();
46
+ this._tmpV = new THREE.Vector3();
47
+ this._tmpLocal = new THREE.Vector3();
48
+
49
+ this._lastPointer = { x: 0, y: 0 };
50
+ this._ghostPos = { x: 0, y: 0 };
51
+ this._raf = 0;
52
+
53
+ this._controlsWasEnabled = null;
54
+
55
+ this._containerOffset = { left: 0, top: 0 };
56
+ this._containerOffsetValid = false;
57
+
58
+ this._contextMenu = {
59
+ open: false,
60
+ marker: null,
61
+ };
62
+
63
+ this._fly = {
64
+ raf: 0,
65
+ active: false,
66
+ prevControlsEnabled: null,
67
+ startTs: 0,
68
+ durationMs: 550,
69
+ // start/end snapshots
70
+ from: null,
71
+ to: null,
72
+ // tmp vectors
73
+ v0: new THREE.Vector3(),
74
+ v1: new THREE.Vector3(),
75
+ v2: new THREE.Vector3(),
76
+ };
77
+
78
+ this._ui = this.#createUi();
79
+ this.#attachUi();
80
+ this.#bindEvents();
81
+ this.#startRaf();
82
+ }
83
+
84
+ dispose() {
85
+ try { this.cancelPlacement(); } catch (_) {}
86
+ try { this.#cancelFly(); } catch (_) {}
87
+ try { this.#closeContextMenu(); } catch (_) {}
88
+
89
+ const dom = this.viewer?.renderer?.domElement;
90
+ try { dom?.removeEventListener("pointermove", this._onPointerMove); } catch (_) {}
91
+ try { dom?.removeEventListener("pointerrawupdate", this._onPointerRawUpdate); } catch (_) {}
92
+ try { dom?.removeEventListener("pointerdown", this._onPointerDownCapture, { capture: true }); } catch (_) {
93
+ try { dom?.removeEventListener("pointerdown", this._onPointerDownCapture); } catch (_) {}
94
+ }
95
+ try { window.removeEventListener("keydown", this._onKeyDown); } catch (_) {}
96
+ try { window.removeEventListener("resize", this._onWindowResize); } catch (_) {}
97
+ try { window.removeEventListener("scroll", this._onWindowScroll, true); } catch (_) {}
98
+ try { window.removeEventListener("pointerdown", this._onWindowPointerDown, true); } catch (_) {}
99
+ try { this._ui?.btn?.removeEventListener("click", this._onBtnClick); } catch (_) {}
100
+ try { this._ui?.menu?.removeEventListener("pointerdown", this._onMenuPointerDown); } catch (_) {}
101
+ try { this._ui?.menu?.removeEventListener("click", this._onMenuClick); } catch (_) {}
102
+
103
+ if (this._raf) cancelAnimationFrame(this._raf);
104
+ this._raf = 0;
105
+
106
+ try { this._markers.forEach((m) => m?.el?.remove?.()); } catch (_) {}
107
+ this._markers.length = 0;
108
+
109
+ try { this._ui?.ghost?.remove?.(); } catch (_) {}
110
+ try { this._ui?.btn?.remove?.(); } catch (_) {}
111
+ try { this._ui?.menu?.remove?.(); } catch (_) {}
112
+ }
113
+
114
+ startPlacement() {
115
+ if (this._placing) return;
116
+ this._placing = true;
117
+
118
+ const controls = this.viewer?.controls;
119
+ if (controls) {
120
+ // Запоминаем и временно выключаем OrbitControls целиком
121
+ this._controlsWasEnabled = !!controls.enabled;
122
+ controls.enabled = false;
123
+ }
124
+
125
+ this.#refreshContainerOffset();
126
+ this.#syncGhost();
127
+ this.#setGhostVisible(true);
128
+ this.#log("startPlacement", { nextId: this._nextId });
129
+ }
130
+
131
+ cancelPlacement() {
132
+ if (!this._placing) return;
133
+ this._placing = false;
134
+ this.#setGhostVisible(false);
135
+
136
+ const controls = this.viewer?.controls;
137
+ if (controls && this._controlsWasEnabled != null) {
138
+ controls.enabled = !!this._controlsWasEnabled;
139
+ this._controlsWasEnabled = null;
140
+ }
141
+
142
+ this.#log("cancelPlacement", {});
143
+ }
144
+
145
+ #log(event, payload) {
146
+ try {
147
+ this.logger?.log?.("[LabelPlacement]", event, payload);
148
+ } catch (_) {}
149
+ }
150
+
151
+ #dispatchLabelEvent(name, detail, legacyName = null) {
152
+ try {
153
+ const ev = new CustomEvent(name, { detail, bubbles: true });
154
+ this.container?.dispatchEvent?.(ev);
155
+ } catch (_) {}
156
+ if (!legacyName) return;
157
+ try {
158
+ const ev = new CustomEvent(legacyName, { detail, bubbles: true });
159
+ this.container?.dispatchEvent?.(ev);
160
+ } catch (_) {}
161
+ }
162
+
163
+ #easeOutCubic(t) {
164
+ const x = Math.min(1, Math.max(0, Number(t) || 0));
165
+ const inv = 1 - x;
166
+ return 1 - inv * inv * inv; // быстрый старт, плавный конец
167
+ }
168
+
169
+ #cancelFly() {
170
+ if (this._fly.raf) cancelAnimationFrame(this._fly.raf);
171
+ this._fly.raf = 0;
172
+ this._fly.active = false;
173
+ this._fly.startTs = 0;
174
+ this._fly.from = null;
175
+ this._fly.to = null;
176
+
177
+ // Вернём OrbitControls, если отключали
178
+ try {
179
+ const controls = this.viewer?.controls;
180
+ if (controls && this._fly.prevControlsEnabled != null) controls.enabled = this._fly.prevControlsEnabled;
181
+ } catch (_) {}
182
+ this._fly.prevControlsEnabled = null;
183
+ }
184
+
185
+ #getCurrentCameraSnapshot() {
186
+ const viewer = this.viewer;
187
+ if (!viewer) return null;
188
+ const camera = viewer.camera;
189
+ const controls = viewer.controls;
190
+ if (!camera || !controls) return null;
191
+
192
+ const snap = {
193
+ projectionMode: (typeof viewer.getProjectionMode === "function")
194
+ ? viewer.getProjectionMode()
195
+ : (camera.isOrthographicCamera ? "ortho" : "perspective"),
196
+ camPos: camera.position.clone(),
197
+ target: controls.target.clone(),
198
+ fov: camera.isPerspectiveCamera ? Number(camera.fov) : null,
199
+ zoom: camera.isOrthographicCamera ? Number(camera.zoom || 1) : null,
200
+ viewOffset: (camera.view && camera.view.enabled)
201
+ ? { enabled: true, offsetX: camera.view.offsetX || 0, offsetY: camera.view.offsetY || 0 }
202
+ : { enabled: false, offsetX: 0, offsetY: 0 },
203
+ };
204
+ return snap;
205
+ }
206
+
207
+ #captureSceneState() {
208
+ const viewer = this.viewer;
209
+ if (!viewer) return null;
210
+
211
+ const camera = viewer.camera;
212
+ const controls = viewer.controls;
213
+ const model = viewer.activeModel;
214
+
215
+ const projectionMode = (typeof viewer.getProjectionMode === "function")
216
+ ? viewer.getProjectionMode()
217
+ : (camera?.isOrthographicCamera ? "ortho" : "perspective");
218
+
219
+ const camPos = camera?.position ? { x: camera.position.x, y: camera.position.y, z: camera.position.z } : null;
220
+ const target = controls?.target ? { x: controls.target.x, y: controls.target.y, z: controls.target.z } : null;
221
+
222
+ const cam = {
223
+ projectionMode,
224
+ position: camPos,
225
+ target,
226
+ fov: (camera && camera.isPerspectiveCamera) ? Number(camera.fov) : null,
227
+ zoom: (camera && camera.isOrthographicCamera) ? Number(camera.zoom || 1) : null,
228
+ // MMB-pan (camera.viewOffset) — сохраняем как есть, в пикселях
229
+ viewOffset: (camera && camera.view && camera.view.enabled)
230
+ ? { enabled: true, offsetX: camera.view.offsetX || 0, offsetY: camera.view.offsetY || 0 }
231
+ : { enabled: false, offsetX: 0, offsetY: 0 },
232
+ };
233
+
234
+ const modelTransform = model ? {
235
+ position: { x: model.position.x, y: model.position.y, z: model.position.z },
236
+ quaternion: { x: model.quaternion.x, y: model.quaternion.y, z: model.quaternion.z, w: model.quaternion.w },
237
+ scale: { x: model.scale.x, y: model.scale.y, z: model.scale.z },
238
+ } : null;
239
+
240
+ const planes = viewer.clipping?.planes || [];
241
+ const clipConstants = [
242
+ planes?.[0]?.constant,
243
+ planes?.[1]?.constant,
244
+ planes?.[2]?.constant,
245
+ ];
246
+
247
+ return {
248
+ camera: cam,
249
+ modelTransform,
250
+ clipping: { constants: clipConstants },
251
+ };
252
+ }
253
+
254
+ #restoreSceneState(sceneState) {
255
+ const viewer = this.viewer;
256
+ if (!viewer || !sceneState) return;
257
+
258
+ // 1) Проекция (может заменить ссылку viewer.camera)
259
+ try {
260
+ const pm = sceneState?.camera?.projectionMode;
261
+ if (pm && typeof viewer.setProjectionMode === "function") viewer.setProjectionMode(pm);
262
+ } catch (_) {}
263
+
264
+ const camera = viewer.camera;
265
+ const controls = viewer.controls;
266
+ const model = viewer.activeModel;
267
+
268
+ // 2) Камера + target + zoom/fov
269
+ try {
270
+ const t = sceneState?.camera?.target;
271
+ if (controls && t) controls.target.set(Number(t.x) || 0, Number(t.y) || 0, Number(t.z) || 0);
272
+ } catch (_) {}
273
+ try {
274
+ const p = sceneState?.camera?.position;
275
+ if (camera && p) camera.position.set(Number(p.x) || 0, Number(p.y) || 0, Number(p.z) || 0);
276
+ } catch (_) {}
277
+ try {
278
+ if (camera?.isPerspectiveCamera && sceneState?.camera?.fov != null) {
279
+ const fov = Number(sceneState.camera.fov);
280
+ if (Number.isFinite(fov) && fov > 1e-3 && fov < 179) camera.fov = fov;
281
+ }
282
+ } catch (_) {}
283
+ try {
284
+ if (camera?.isOrthographicCamera && sceneState?.camera?.zoom != null) {
285
+ const z = Number(sceneState.camera.zoom);
286
+ if (Number.isFinite(z) && z > 1e-6) camera.zoom = z;
287
+ }
288
+ } catch (_) {}
289
+
290
+ // 3) Трансформ модели (позиция/поворот/масштаб)
291
+ try {
292
+ const mt = sceneState?.modelTransform;
293
+ if (model && mt?.position && mt?.quaternion && mt?.scale) {
294
+ model.position.set(Number(mt.position.x) || 0, Number(mt.position.y) || 0, Number(mt.position.z) || 0);
295
+ model.quaternion.set(
296
+ Number(mt.quaternion.x) || 0,
297
+ Number(mt.quaternion.y) || 0,
298
+ Number(mt.quaternion.z) || 0,
299
+ Number(mt.quaternion.w) || 1
300
+ );
301
+ model.scale.set(Number(mt.scale.x) || 1, Number(mt.scale.y) || 1, Number(mt.scale.z) || 1);
302
+ model.updateMatrixWorld?.(true);
303
+ }
304
+ } catch (_) {}
305
+
306
+ // 4) ViewOffset (MMB-pan) — применяем после смены камеры/проекции
307
+ try {
308
+ const vo = sceneState?.camera?.viewOffset;
309
+ if (camera && vo && typeof camera.setViewOffset === "function") {
310
+ const dom = viewer?.renderer?.domElement;
311
+ const rect = dom?.getBoundingClientRect?.();
312
+ const w = Math.max(1, Math.floor(rect?.width || 1));
313
+ const h = Math.max(1, Math.floor(rect?.height || 1));
314
+ if (vo.enabled) {
315
+ camera.setViewOffset(w, h, Math.round(Number(vo.offsetX) || 0), Math.round(Number(vo.offsetY) || 0), w, h);
316
+ } else if (typeof camera.clearViewOffset === "function") {
317
+ camera.clearViewOffset();
318
+ } else {
319
+ camera.setViewOffset(w, h, 0, 0, w, h);
320
+ }
321
+ }
322
+ } catch (_) {}
323
+
324
+ // 5) Клиппинг (как Home: сначала восстановили камеру+модель, затем planes)
325
+ try {
326
+ const constants = sceneState?.clipping?.constants || [];
327
+ if (typeof viewer.setSection === "function") {
328
+ ["x", "y", "z"].forEach((axis, i) => {
329
+ const c = constants[i];
330
+ const enabled = Number.isFinite(c);
331
+ const dist = -Number(c);
332
+ viewer.setSection(axis, enabled, enabled ? dist : 0);
333
+ });
334
+ }
335
+ } catch (_) {}
336
+
337
+ try { camera?.updateProjectionMatrix?.(); } catch (_) {}
338
+ try { controls?.update?.(); } catch (_) {}
339
+ }
340
+
341
+ #applyModelTransformFromState(sceneState) {
342
+ const viewer = this.viewer;
343
+ if (!viewer || !sceneState) return;
344
+ const model = viewer.activeModel;
345
+ if (!model) return;
346
+ const mt = sceneState?.modelTransform;
347
+ if (!mt?.position || !mt?.quaternion || !mt?.scale) return;
348
+ try {
349
+ model.position.set(Number(mt.position.x) || 0, Number(mt.position.y) || 0, Number(mt.position.z) || 0);
350
+ model.quaternion.set(
351
+ Number(mt.quaternion.x) || 0,
352
+ Number(mt.quaternion.y) || 0,
353
+ Number(mt.quaternion.z) || 0,
354
+ Number(mt.quaternion.w) || 1
355
+ );
356
+ model.scale.set(Number(mt.scale.x) || 1, Number(mt.scale.y) || 1, Number(mt.scale.z) || 1);
357
+ model.updateMatrixWorld?.(true);
358
+ } catch (_) {}
359
+ }
360
+
361
+ #applyClippingFromState(sceneState) {
362
+ const viewer = this.viewer;
363
+ if (!viewer || !sceneState) return;
364
+ try {
365
+ const constants = sceneState?.clipping?.constants || [];
366
+ if (typeof viewer.setSection === "function") {
367
+ ["x", "y", "z"].forEach((axis, i) => {
368
+ const c = constants[i];
369
+ const enabled = Number.isFinite(c);
370
+ const dist = -Number(c);
371
+ viewer.setSection(axis, enabled, enabled ? dist : 0);
372
+ });
373
+ }
374
+ } catch (_) {}
375
+ }
376
+
377
+ #applyViewOffset(camera, viewOffset) {
378
+ if (!camera || !viewOffset) return;
379
+ try {
380
+ const viewer = this.viewer;
381
+ const dom = viewer?.renderer?.domElement;
382
+ const rect = dom?.getBoundingClientRect?.();
383
+ const w = Math.max(1, Math.floor(rect?.width || 1));
384
+ const h = Math.max(1, Math.floor(rect?.height || 1));
385
+
386
+ if (viewOffset.enabled) {
387
+ camera.setViewOffset(w, h, Math.round(Number(viewOffset.offsetX) || 0), Math.round(Number(viewOffset.offsetY) || 0), w, h);
388
+ } else if (typeof camera.clearViewOffset === "function") {
389
+ camera.clearViewOffset();
390
+ } else {
391
+ camera.setViewOffset(w, h, 0, 0, w, h);
392
+ }
393
+ } catch (_) {}
394
+ }
395
+
396
+ #animateToSceneState(sceneState, durationMs = 550) {
397
+ const viewer = this.viewer;
398
+ if (!viewer || !sceneState) return;
399
+
400
+ // Если уже летим — отменим предыдущую анимацию
401
+ this.#cancelFly();
402
+
403
+ // 1) Сразу применяем проекцию (может сменить viewer.camera)
404
+ try {
405
+ const pm = sceneState?.camera?.projectionMode;
406
+ if (pm && typeof viewer.setProjectionMode === "function") viewer.setProjectionMode(pm);
407
+ } catch (_) {}
408
+
409
+ // 2) Сразу применяем трансформ модели (если нужен) — камера полетит уже к нужной сцене
410
+ this.#applyModelTransformFromState(sceneState);
411
+
412
+ const camera = viewer.camera;
413
+ const controls = viewer.controls;
414
+ if (!camera || !controls) return;
415
+
416
+ const from = this.#getCurrentCameraSnapshot();
417
+ if (!from) return;
418
+
419
+ // Целевые значения (камера/target/zoom/fov/offset)
420
+ const to = {
421
+ projectionMode: sceneState?.camera?.projectionMode || from.projectionMode,
422
+ camPos: sceneState?.camera?.position
423
+ ? new THREE.Vector3(Number(sceneState.camera.position.x) || 0, Number(sceneState.camera.position.y) || 0, Number(sceneState.camera.position.z) || 0)
424
+ : from.camPos.clone(),
425
+ target: sceneState?.camera?.target
426
+ ? new THREE.Vector3(Number(sceneState.camera.target.x) || 0, Number(sceneState.camera.target.y) || 0, Number(sceneState.camera.target.z) || 0)
427
+ : from.target.clone(),
428
+ fov: (camera.isPerspectiveCamera && sceneState?.camera?.fov != null) ? Number(sceneState.camera.fov) : from.fov,
429
+ zoom: (camera.isOrthographicCamera && sceneState?.camera?.zoom != null) ? Number(sceneState.camera.zoom) : from.zoom,
430
+ viewOffset: sceneState?.camera?.viewOffset || from.viewOffset,
431
+ };
432
+
433
+ // На время "долеталки" отключаем controls
434
+ try {
435
+ this._fly.prevControlsEnabled = !!controls.enabled;
436
+ controls.enabled = false;
437
+ } catch (_) {
438
+ this._fly.prevControlsEnabled = null;
439
+ }
440
+
441
+ this._fly.active = true;
442
+ this._fly.startTs = performance.now();
443
+ this._fly.durationMs = Math.max(50, Number(durationMs) || 550);
444
+ this._fly.from = from;
445
+ this._fly.to = to;
446
+
447
+ const tick = () => {
448
+ if (!this._fly.active) return;
449
+ const now = performance.now();
450
+ const t = (now - this._fly.startTs) / this._fly.durationMs;
451
+ const k = this.#easeOutCubic(t);
452
+
453
+ // position lerp
454
+ this._fly.v0.copy(from.camPos).lerp(to.camPos, k);
455
+ camera.position.copy(this._fly.v0);
456
+
457
+ // target lerp
458
+ this._fly.v1.copy(from.target).lerp(to.target, k);
459
+ controls.target.copy(this._fly.v1);
460
+
461
+ // fov/zoom
462
+ try {
463
+ if (camera.isPerspectiveCamera && to.fov != null && from.fov != null) {
464
+ const f = Number(from.fov) + (Number(to.fov) - Number(from.fov)) * k;
465
+ if (Number.isFinite(f) && f > 1e-3 && f < 179) camera.fov = f;
466
+ }
467
+ } catch (_) {}
468
+ try {
469
+ if (camera.isOrthographicCamera && to.zoom != null && from.zoom != null) {
470
+ const z = Number(from.zoom) + (Number(to.zoom) - Number(from.zoom)) * k;
471
+ if (Number.isFinite(z) && z > 1e-6) camera.zoom = z;
472
+ }
473
+ } catch (_) {}
474
+
475
+ // viewOffset lerp
476
+ try {
477
+ const vo0 = from.viewOffset || { enabled: false, offsetX: 0, offsetY: 0 };
478
+ const vo1 = to.viewOffset || { enabled: false, offsetX: 0, offsetY: 0 };
479
+ const enabled = !!(vo0.enabled || vo1.enabled);
480
+ const ox = Number(vo0.offsetX) + (Number(vo1.offsetX) - Number(vo0.offsetX)) * k;
481
+ const oy = Number(vo0.offsetY) + (Number(vo1.offsetY) - Number(vo0.offsetY)) * k;
482
+ this.#applyViewOffset(camera, { enabled, offsetX: ox, offsetY: oy });
483
+ } catch (_) {}
484
+
485
+ try { camera.updateProjectionMatrix?.(); } catch (_) {}
486
+ try { controls.update?.(); } catch (_) {}
487
+
488
+ if (t >= 1) {
489
+ // Финал: зафиксируем точные значения
490
+ try { camera.position.copy(to.camPos); } catch (_) {}
491
+ try { controls.target.copy(to.target); } catch (_) {}
492
+ try {
493
+ if (camera.isPerspectiveCamera && to.fov != null) camera.fov = to.fov;
494
+ if (camera.isOrthographicCamera && to.zoom != null) camera.zoom = to.zoom;
495
+ } catch (_) {}
496
+ try { this.#applyViewOffset(camera, to.viewOffset); } catch (_) {}
497
+
498
+ // В конце применяем clipping (чтобы ориентация плоскостей считалась по финальной камере)
499
+ this.#applyClippingFromState(sceneState);
500
+
501
+ try { camera.updateProjectionMatrix?.(); } catch (_) {}
502
+ try { controls.update?.(); } catch (_) {}
503
+
504
+ this.#cancelFly();
505
+ return;
506
+ }
507
+
508
+ this._fly.raf = requestAnimationFrame(tick);
509
+ };
510
+
511
+ this._fly.raf = requestAnimationFrame(tick);
512
+ }
513
+
514
+ #createUi() {
515
+ const btn = document.createElement("button");
516
+ btn.type = "button";
517
+ btn.className = "ifc-label-add-btn";
518
+ btn.textContent = "+ Добавить метку";
519
+
520
+ const ghost = document.createElement("div");
521
+ ghost.className = "ifc-label-ghost";
522
+ ghost.setAttribute("aria-hidden", "true");
523
+ ghost.style.display = "none";
524
+ // Базовая позиция: двигаем transform'ом, поэтому left/top держим в 0
525
+ ghost.style.left = "0px";
526
+ ghost.style.top = "0px";
527
+
528
+ const dot = document.createElement("div");
529
+ dot.className = "ifc-label-dot";
530
+ const num = document.createElement("div");
531
+ num.className = "ifc-label-num";
532
+
533
+ ghost.appendChild(dot);
534
+ ghost.appendChild(num);
535
+
536
+ const menu = document.createElement("div");
537
+ menu.className = "ifc-label-menu";
538
+ menu.style.display = "none";
539
+ menu.setAttribute("role", "menu");
540
+
541
+ const menuCopy = document.createElement("button");
542
+ menuCopy.type = "button";
543
+ menuCopy.className = "ifc-label-menu-item";
544
+ menuCopy.textContent = "Копировать";
545
+ menuCopy.setAttribute("data-action", "copy");
546
+
547
+ const menuMove = document.createElement("button");
548
+ menuMove.type = "button";
549
+ menuMove.className = "ifc-label-menu-item";
550
+ menuMove.textContent = "Переместить";
551
+ menuMove.setAttribute("data-action", "move");
552
+
553
+ const menuDelete = document.createElement("button");
554
+ menuDelete.type = "button";
555
+ menuDelete.className = "ifc-label-menu-item";
556
+ menuDelete.textContent = "Удалить";
557
+ menuDelete.setAttribute("data-action", "delete");
558
+
559
+ menu.appendChild(menuCopy);
560
+ menu.appendChild(menuMove);
561
+ menu.appendChild(menuDelete);
562
+
563
+ return { btn, ghost, dot, num, menu };
564
+ }
565
+
566
+ #attachUi() {
567
+ // Важно: container должен быть position:relative (в index.html уже так).
568
+ this.container.appendChild(this._ui.btn);
569
+ this.container.appendChild(this._ui.ghost);
570
+ this.container.appendChild(this._ui.menu);
571
+ }
572
+
573
+ #bindEvents() {
574
+ this._onBtnClick = (e) => {
575
+ // Не даём событию уйти в canvas/OrbitControls и не ставим метку "тем же кликом".
576
+ try { e.preventDefault(); } catch (_) {}
577
+ try { e.stopPropagation(); } catch (_) {}
578
+ try { e.stopImmediatePropagation?.(); } catch (_) {}
579
+ this.startPlacement();
580
+ };
581
+ this._ui.btn.addEventListener("click", this._onBtnClick, { passive: false });
582
+
583
+ this._onMenuPointerDown = (e) => {
584
+ // Не даём клику меню попасть в canvas/OrbitControls
585
+ try { e.preventDefault(); } catch (_) {}
586
+ try { e.stopPropagation(); } catch (_) {}
587
+ try { e.stopImmediatePropagation?.(); } catch (_) {}
588
+ };
589
+ this._ui.menu.addEventListener("pointerdown", this._onMenuPointerDown, { passive: false });
590
+
591
+ this._onMenuClick = (e) => {
592
+ const target = e.target;
593
+ const action = target?.getAttribute?.("data-action");
594
+ if (!action) return;
595
+ try { e.preventDefault(); } catch (_) {}
596
+ try { e.stopPropagation(); } catch (_) {}
597
+ const marker = this._contextMenu?.marker || null;
598
+ this.#emitLabelAction(action, marker);
599
+ this.#closeContextMenu();
600
+ };
601
+ this._ui.menu.addEventListener("click", this._onMenuClick);
602
+
603
+ this._onKeyDown = (e) => {
604
+ if (this._placing) {
605
+ if (e.key === "Escape") this.cancelPlacement();
606
+ return;
607
+ }
608
+
609
+ const target = e.target;
610
+ const tag = (target && target.tagName) ? String(target.tagName).toLowerCase() : "";
611
+ if (tag === "input" || tag === "textarea" || target?.isContentEditable) return;
612
+
613
+ const hasSelection = this.#getSelectedMarker() != null;
614
+ if (!hasSelection) return;
615
+
616
+ const key = String(e.key || "").toLowerCase();
617
+ const withCmd = !!(e.ctrlKey || e.metaKey);
618
+
619
+ if (withCmd && key === "c") {
620
+ try { e.preventDefault(); } catch (_) {}
621
+ this.#emitLabelAction("copy");
622
+ return;
623
+ }
624
+ if (key === "delete" || key === "backspace") {
625
+ try { e.preventDefault(); } catch (_) {}
626
+ this.#emitLabelAction("delete");
627
+ return;
628
+ }
629
+ if (key === "m" || (withCmd && key === "m")) {
630
+ try { e.preventDefault(); } catch (_) {}
631
+ this.#emitLabelAction("move");
632
+ }
633
+ };
634
+ window.addEventListener("keydown", this._onKeyDown);
635
+
636
+ this._onWindowPointerDown = (e) => {
637
+ if (!this._contextMenu.open) return;
638
+ const menu = this._ui?.menu;
639
+ if (menu && menu.contains(e.target)) return;
640
+ this.#closeContextMenu();
641
+ };
642
+ window.addEventListener("pointerdown", this._onWindowPointerDown, true);
643
+
644
+ // Смещение контейнера (#app) относительно viewport может меняться при resize/scroll.
645
+ // Обновляем кэш, чтобы призрак/метки не "плыли".
646
+ this._onWindowResize = () => {
647
+ this.#refreshContainerOffset();
648
+ if (this._placing) this.#syncGhost();
649
+ this.#closeContextMenu();
650
+ };
651
+ this._onWindowScroll = () => {
652
+ this.#refreshContainerOffset();
653
+ if (this._placing) this.#syncGhost();
654
+ this.#closeContextMenu();
655
+ };
656
+ window.addEventListener("resize", this._onWindowResize, { passive: true });
657
+ // scroll слушаем в capture, чтобы ловить скролл вложенных контейнеров
658
+ window.addEventListener("scroll", this._onWindowScroll, true);
659
+
660
+ const dom = this.viewer?.renderer?.domElement;
661
+ if (!dom) return;
662
+
663
+ this._onPointerMove = (e) => {
664
+ if (!this._placing) return;
665
+ this.#updateGhostFromClient(e.clientX, e.clientY);
666
+ };
667
+ dom.addEventListener("pointermove", this._onPointerMove, { passive: true });
668
+
669
+ // Best-effort: более частые координаты, чем pointermove (Chrome).
670
+ this._onPointerRawUpdate = (e) => {
671
+ if (!this._placing) return;
672
+ this.#updateGhostFromClient(e.clientX, e.clientY);
673
+ };
674
+ try { dom.addEventListener("pointerrawupdate", this._onPointerRawUpdate, { passive: true }); } catch (_) {}
675
+
676
+ this._onPointerDownCapture = (e) => {
677
+ if (!this._placing) return;
678
+ // Только ЛКМ ставит метку. Остальные кнопки не блокируем (например, колесо/ПКМ).
679
+ if (e.button !== 0) return;
680
+
681
+ // Блокируем другие контроллеры (OrbitControls/MMB/RMB) на время постановки.
682
+ try { e.preventDefault(); } catch (_) {}
683
+ try { e.stopPropagation(); } catch (_) {}
684
+ try { e.stopImmediatePropagation?.(); } catch (_) {}
685
+
686
+ const hit = this.#pickModelPoint(e.clientX, e.clientY);
687
+ if (!hit) {
688
+ this.#log("placeAttempt:no-hit", {});
689
+ return; // остаёмся в режиме, пользователь может кликнуть ещё раз
690
+ }
691
+ this.#createMarkerAtHit(hit);
692
+ this.cancelPlacement(); // по ТЗ: “вторым кликом устанавливаем”
693
+ };
694
+ dom.addEventListener("pointerdown", this._onPointerDownCapture, { capture: true, passive: false });
695
+ }
696
+
697
+ #setGhostVisible(visible) {
698
+ if (!this._ui?.ghost) return;
699
+ this._ui.ghost.style.display = visible ? "block" : "none";
700
+ }
701
+
702
+ #refreshContainerOffset() {
703
+ const cr = this.container?.getBoundingClientRect?.();
704
+ if (!cr) {
705
+ this._containerOffset.left = 0;
706
+ this._containerOffset.top = 0;
707
+ this._containerOffsetValid = false;
708
+ return;
709
+ }
710
+ this._containerOffset.left = cr.left || 0;
711
+ this._containerOffset.top = cr.top || 0;
712
+ this._containerOffsetValid = true;
713
+ }
714
+
715
+ #applyGhostTransform() {
716
+ const g = this._ui?.ghost;
717
+ if (!g) return;
718
+ g.style.transform = `translate3d(${this._ghostPos.x}px, ${this._ghostPos.y}px, 0) translate(-50%, -50%)`;
719
+ }
720
+
721
+ #updateGhostFromClient(clientX, clientY) {
722
+ this._lastPointer = { x: clientX, y: clientY };
723
+ if (!this._containerOffsetValid) this.#refreshContainerOffset();
724
+ const x = (clientX - this._containerOffset.left);
725
+ const y = (clientY - this._containerOffset.top);
726
+ this._ghostPos.x = x;
727
+ this._ghostPos.y = y;
728
+ // Обновляем transform сразу в обработчике — без ожидания RAF.
729
+ this.#applyGhostTransform();
730
+ }
731
+
732
+ #syncGhost() {
733
+ const g = this._ui?.ghost;
734
+ if (!g) return;
735
+ this._ui.num.textContent = String(this._nextId);
736
+ // Число может меняться (id), позиция — из последних координат курсора.
737
+ this.#updateGhostFromClient(this._lastPointer.x, this._lastPointer.y);
738
+ }
739
+
740
+ #pickModelPoint(clientX, clientY) {
741
+ const model = this.viewer?.activeModel;
742
+ const camera = this.viewer?.camera;
743
+ const dom = this.viewer?.renderer?.domElement;
744
+ if (!model || !camera || !dom) return null;
745
+
746
+ const rect = dom.getBoundingClientRect?.();
747
+ if (!rect || rect.width <= 0 || rect.height <= 0) return null;
748
+
749
+ const x = ((clientX - rect.left) / rect.width) * 2 - 1;
750
+ const y = -(((clientY - rect.top) / rect.height) * 2 - 1);
751
+ this._ndc.set(x, y);
752
+
753
+ this._raycaster.setFromCamera(this._ndc, camera);
754
+ const hits = this._raycaster.intersectObject(model, true);
755
+ if (!hits || hits.length <= 0) return null;
756
+
757
+ // ВАЖНО: у модели могут быть контурные линии/оверлеи (LineSegments),
758
+ // которые перехватывают hit раньше "реального" Mesh фасада.
759
+ // Для постановки метки выбираем первый hit именно по Mesh.
760
+ let best = null;
761
+ for (const h of hits) {
762
+ if (!h || !h.point) continue;
763
+ const obj = h.object;
764
+ if (obj && obj.isMesh) { best = h; break; }
765
+ }
766
+ // fallback: если Mesh не найден (редко), берём первый валидный hit
767
+ if (!best) {
768
+ for (const h of hits) {
769
+ if (h && h.point) { best = h; break; }
770
+ }
771
+ }
772
+
773
+ if (!best || !best.point) return null;
774
+ return best;
775
+ }
776
+
777
+ #createMarkerAtHit(hit) {
778
+ const model = this.viewer?.activeModel;
779
+ if (!model) return;
780
+
781
+ const id = this._nextId++;
782
+
783
+ // Храним локальную координату модели, чтобы метка оставалась “приклеенной” к модели
784
+ this._tmpLocal.copy(hit.point);
785
+ model.worldToLocal(this._tmpLocal);
786
+
787
+ const sceneState = this.#captureSceneState();
788
+ const marker = this.#createMarkerFromData({
789
+ id,
790
+ localPoint: { x: this._tmpLocal.x, y: this._tmpLocal.y, z: this._tmpLocal.z },
791
+ sceneState,
792
+ }, true);
793
+
794
+ this.#log("placed", {
795
+ id,
796
+ local: { x: +marker.localPoint.x.toFixed(4), y: +marker.localPoint.y.toFixed(4), z: +marker.localPoint.z.toFixed(4) },
797
+ sceneState: sceneState ? { hasCamera: !!sceneState.camera, hasModel: !!sceneState.modelTransform, hasClip: !!sceneState.clipping } : null,
798
+ });
799
+ }
800
+
801
+ #createMarkerElement(id) {
802
+ const el = document.createElement("div");
803
+ el.className = "ifc-label-marker";
804
+ el.setAttribute("data-id", String(id));
805
+ el.innerHTML = `<div class="ifc-label-dot"></div><div class="ifc-label-num">${id}</div>`;
806
+ // Базовая позиция: двигаем transform'ом, поэтому left/top держим в 0
807
+ el.style.left = "0px";
808
+ el.style.top = "0px";
809
+ this.container.appendChild(el);
810
+ return el;
811
+ }
812
+
813
+ #setSelectedMarker(marker) {
814
+ if (!marker) {
815
+ this.#clearSelection();
816
+ return;
817
+ }
818
+ if (this._selectedId === marker.id) return;
819
+ this.#clearSelection();
820
+ this._selectedId = marker.id;
821
+ try { marker.el?.classList?.add?.("ifc-label-marker--active"); } catch (_) {}
822
+ }
823
+
824
+ #clearSelection() {
825
+ if (this._selectedId == null) return;
826
+ const marker = this._markers.find((m) => String(m?.id) === String(this._selectedId));
827
+ try { marker?.el?.classList?.remove?.("ifc-label-marker--active"); } catch (_) {}
828
+ this._selectedId = null;
829
+ }
830
+
831
+ #getSelectedMarker() {
832
+ if (this._selectedId == null) return null;
833
+ return this._markers.find((m) => String(m?.id) === String(this._selectedId)) || null;
834
+ }
835
+
836
+ #buildActionPayload(marker) {
837
+ if (!marker) return null;
838
+ return {
839
+ id: marker.id,
840
+ localPoint: { x: marker.localPoint.x, y: marker.localPoint.y, z: marker.localPoint.z },
841
+ sceneState: marker.sceneState || null,
842
+ };
843
+ }
844
+
845
+ #emitLabelAction(action, marker = null) {
846
+ const target = marker || this.#getSelectedMarker();
847
+ if (!target) return;
848
+ const detail = this.#buildActionPayload(target);
849
+ if (!detail) return;
850
+ this.#dispatchLabelEvent(`ifcviewer:label-${action}`, detail, null);
851
+ }
852
+
853
+ #openContextMenu(marker, clientX, clientY) {
854
+ const menu = this._ui?.menu;
855
+ if (!menu || !marker) return;
856
+
857
+ this.#closeContextMenu();
858
+
859
+ this._contextMenu.open = true;
860
+ this._contextMenu.marker = marker;
861
+
862
+ if (!this._containerOffsetValid) this.#refreshContainerOffset();
863
+ const x = clientX - this._containerOffset.left;
864
+ const y = clientY - this._containerOffset.top;
865
+
866
+ menu.style.display = "block";
867
+ // Зафиксируем базовую точку, чтобы transform не смещался от offsetTop/Left
868
+ menu.style.left = "0px";
869
+ menu.style.top = "0px";
870
+ menu.style.transform = `translate3d(${x}px, ${y}px, 0) translate(8px, 8px)`;
871
+
872
+ // Корректируем позицию, чтобы не выходить за контейнер
873
+ try {
874
+ const rect = this.container?.getBoundingClientRect?.();
875
+ const mw = menu.offsetWidth || 0;
876
+ const mh = menu.offsetHeight || 0;
877
+ if (rect && mw && mh) {
878
+ let px = x + 8;
879
+ let py = y + 8;
880
+ if (px + mw > rect.width) px = Math.max(0, rect.width - mw - 4);
881
+ if (py + mh > rect.height) py = Math.max(0, rect.height - mh - 4);
882
+ menu.style.transform = `translate3d(${px}px, ${py}px, 0)`;
883
+ }
884
+ } catch (_) {}
885
+ }
886
+
887
+ #closeContextMenu() {
888
+ const menu = this._ui?.menu;
889
+ if (!menu) return;
890
+ this._contextMenu.open = false;
891
+ this._contextMenu.marker = null;
892
+ menu.style.display = "none";
893
+ }
894
+
895
+ #createMarkerFromData(data, emitPlacedEvent) {
896
+ if (!data) return null;
897
+ const localPoint = data.localPoint || {};
898
+ const marker = new LabelMarker({
899
+ id: data.id,
900
+ localPoint: new THREE.Vector3(
901
+ Number(localPoint.x) || 0,
902
+ Number(localPoint.y) || 0,
903
+ Number(localPoint.z) || 0
904
+ ),
905
+ el: this.#createMarkerElement(data.id),
906
+ sceneState: data.sceneState || null,
907
+ });
908
+ this._markers.push(marker);
909
+
910
+ const onMarkerPointerDown = (e) => {
911
+ // Важно: не даём клику попасть в canvas/OrbitControls
912
+ try { e.preventDefault(); } catch (_) {}
913
+ try { e.stopPropagation(); } catch (_) {}
914
+ try { e.stopImmediatePropagation?.(); } catch (_) {}
915
+ // если были в режиме постановки — выходим
916
+ try { this.cancelPlacement(); } catch (_) {}
917
+
918
+ if (e.button === 0) {
919
+ this.#closeContextMenu();
920
+ this.#setSelectedMarker(marker);
921
+ this.#dispatchLabelEvent("ifcviewer:label-click", {
922
+ id: marker.id,
923
+ sceneState: marker.sceneState || null,
924
+ }, "ifcviewer:card-click");
925
+ // "Долеталка" камеры: быстрый старт + мягкий конец
926
+ this.#animateToSceneState(marker.sceneState, 550);
927
+ }
928
+ };
929
+ // capture-phase, чтобы обогнать любые handlers на canvas
930
+ try { marker.el.addEventListener("pointerdown", onMarkerPointerDown, { capture: true, passive: false }); } catch (_) {
931
+ try { marker.el.addEventListener("pointerdown", onMarkerPointerDown); } catch (_) {}
932
+ }
933
+
934
+ const onMarkerContextMenu = (e) => {
935
+ try { e.preventDefault(); } catch (_) {}
936
+ try { e.stopPropagation(); } catch (_) {}
937
+ try { e.stopImmediatePropagation?.(); } catch (_) {}
938
+ try { this.cancelPlacement(); } catch (_) {}
939
+
940
+ this.#setSelectedMarker(marker);
941
+ this.#openContextMenu(marker, e.clientX, e.clientY);
942
+ };
943
+ try { marker.el.addEventListener("contextmenu", onMarkerContextMenu, { capture: true, passive: false }); } catch (_) {
944
+ try { marker.el.addEventListener("contextmenu", onMarkerContextMenu); } catch (_) {}
945
+ }
946
+
947
+ if (emitPlacedEvent) {
948
+ this.#dispatchLabelEvent("ifcviewer:label-placed", {
949
+ id: marker.id,
950
+ localPoint: { x: marker.localPoint.x, y: marker.localPoint.y, z: marker.localPoint.z },
951
+ sceneState: marker.sceneState || null,
952
+ }, "ifcviewer:card-placed");
953
+ }
954
+
955
+ return marker;
956
+ }
957
+
958
+ #clearMarkers() {
959
+ try { this._markers.forEach((m) => m?.el?.remove?.()); } catch (_) {}
960
+ this._markers.length = 0;
961
+ this.#clearSelection();
962
+ }
963
+
964
+ setLabelMarkers(items) {
965
+ if (!Array.isArray(items)) return;
966
+ const prevSelectedId = this._selectedId;
967
+ this.#clearMarkers();
968
+
969
+ let maxNumericId = null;
970
+ for (const item of items) {
971
+ const marker = this.#createMarkerFromData(item, false);
972
+ if (marker && typeof marker.id === "number" && Number.isFinite(marker.id)) {
973
+ maxNumericId = (maxNumericId == null) ? marker.id : Math.max(maxNumericId, marker.id);
974
+ }
975
+ }
976
+ if (maxNumericId != null) this._nextId = Math.max(1, Math.floor(maxNumericId) + 1);
977
+ if (prevSelectedId != null) this.selectLabel(prevSelectedId);
978
+ }
979
+
980
+ getLabelMarkers() {
981
+ return this._markers.map((m) => ({
982
+ id: m.id,
983
+ localPoint: { x: m.localPoint.x, y: m.localPoint.y, z: m.localPoint.z },
984
+ sceneState: m.sceneState || null,
985
+ }));
986
+ }
987
+
988
+ /**
989
+ * @deprecated используйте setLabelMarkers
990
+ */
991
+ setCardMarkers(items) {
992
+ try { this.logger?.warn?.("[LabelPlacement] setCardMarkers is deprecated, use setLabelMarkers"); } catch (_) {}
993
+ this.setLabelMarkers(items);
994
+ }
995
+
996
+ /**
997
+ * @deprecated используйте getLabelMarkers
998
+ */
999
+ getCardMarkers() {
1000
+ try { this.logger?.warn?.("[LabelPlacement] getCardMarkers is deprecated, use getLabelMarkers"); } catch (_) {}
1001
+ return this.getLabelMarkers();
1002
+ }
1003
+
1004
+ selectLabel(id) {
1005
+ if (id == null) {
1006
+ this.#clearSelection();
1007
+ return;
1008
+ }
1009
+ const marker = this._markers.find((m) => String(m?.id) === String(id)) || null;
1010
+ if (!marker) {
1011
+ this.#clearSelection();
1012
+ return;
1013
+ }
1014
+ this.#setSelectedMarker(marker);
1015
+ }
1016
+
1017
+ #startRaf() {
1018
+ const tick = () => {
1019
+ this._raf = requestAnimationFrame(tick);
1020
+ this.#updateMarkerScreenspace();
1021
+ };
1022
+ this._raf = requestAnimationFrame(tick);
1023
+ }
1024
+
1025
+ #updateMarkerScreenspace() {
1026
+ const model = this.viewer?.activeModel;
1027
+ const camera = this.viewer?.camera;
1028
+ const dom = this.viewer?.renderer?.domElement;
1029
+ if (!camera || !dom) return;
1030
+
1031
+ const rect = dom.getBoundingClientRect?.();
1032
+ if (!rect || rect.width <= 0 || rect.height <= 0) return;
1033
+
1034
+ const w = rect.width;
1035
+ const h = rect.height;
1036
+
1037
+ for (const m of this._markers) {
1038
+ if (!m || !m.el) continue;
1039
+
1040
+ if (!model) {
1041
+ m.el.style.display = "none";
1042
+ continue;
1043
+ }
1044
+
1045
+ // local -> world (учитывает позицию/поворот/scale модели)
1046
+ this._tmpV.copy(m.localPoint);
1047
+ model.localToWorld(this._tmpV);
1048
+
1049
+ const ndc = this._tmpV.project(camera);
1050
+
1051
+ // Если точка за камерой или далеко за пределами — скрываем
1052
+ const inFront = Number.isFinite(ndc.z) && ndc.z >= -1 && ndc.z <= 1;
1053
+ if (!inFront) {
1054
+ m.el.style.display = "none";
1055
+ continue;
1056
+ }
1057
+
1058
+ const x = (ndc.x * 0.5 + 0.5) * w;
1059
+ const y = (-ndc.y * 0.5 + 0.5) * h;
1060
+
1061
+ if (!Number.isFinite(x) || !Number.isFinite(y)) {
1062
+ m.el.style.display = "none";
1063
+ continue;
1064
+ }
1065
+
1066
+ m.el.style.display = "block";
1067
+ m.el.style.transform = `translate3d(${x}px, ${y}px, 0) translate(-50%, -50%)`;
1068
+ }
1069
+ }
1070
+ }
1071
+