@sequent-org/ifc-viewer 1.2.4-ci.49.0 → 1.2.4-ci.51.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,774 @@
1
+ import * as THREE from "three";
2
+
3
+ class CardMarker {
4
+ /**
5
+ * @param {object} deps
6
+ * @param {number} 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 CardPlacementController {
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 {CardMarker[]} */
41
+ this._markers = [];
42
+
43
+ this._raycaster = new THREE.Raycaster();
44
+ this._ndc = new THREE.Vector2();
45
+ this._tmpV = new THREE.Vector3();
46
+ this._tmpLocal = new THREE.Vector3();
47
+
48
+ this._lastPointer = { x: 0, y: 0 };
49
+ this._ghostPos = { x: 0, y: 0 };
50
+ this._raf = 0;
51
+
52
+ this._controlsWasEnabled = null;
53
+
54
+ this._containerOffset = { left: 0, top: 0 };
55
+ this._containerOffsetValid = false;
56
+
57
+ this._fly = {
58
+ raf: 0,
59
+ active: false,
60
+ prevControlsEnabled: null,
61
+ startTs: 0,
62
+ durationMs: 550,
63
+ // start/end snapshots
64
+ from: null,
65
+ to: null,
66
+ // tmp vectors
67
+ v0: new THREE.Vector3(),
68
+ v1: new THREE.Vector3(),
69
+ v2: new THREE.Vector3(),
70
+ };
71
+
72
+ this._ui = this.#createUi();
73
+ this.#attachUi();
74
+ this.#bindEvents();
75
+ this.#startRaf();
76
+ }
77
+
78
+ dispose() {
79
+ try { this.cancelPlacement(); } catch (_) {}
80
+ try { this.#cancelFly(); } catch (_) {}
81
+
82
+ const dom = this.viewer?.renderer?.domElement;
83
+ try { dom?.removeEventListener("pointermove", this._onPointerMove); } catch (_) {}
84
+ try { dom?.removeEventListener("pointerrawupdate", this._onPointerRawUpdate); } catch (_) {}
85
+ try { dom?.removeEventListener("pointerdown", this._onPointerDownCapture, { capture: true }); } catch (_) {
86
+ try { dom?.removeEventListener("pointerdown", this._onPointerDownCapture); } catch (_) {}
87
+ }
88
+ try { window.removeEventListener("keydown", this._onKeyDown); } catch (_) {}
89
+ try { window.removeEventListener("resize", this._onWindowResize); } catch (_) {}
90
+ try { window.removeEventListener("scroll", this._onWindowScroll, true); } catch (_) {}
91
+ try { this._ui?.btn?.removeEventListener("click", this._onBtnClick); } catch (_) {}
92
+
93
+ if (this._raf) cancelAnimationFrame(this._raf);
94
+ this._raf = 0;
95
+
96
+ try { this._markers.forEach((m) => m?.el?.remove?.()); } catch (_) {}
97
+ this._markers.length = 0;
98
+
99
+ try { this._ui?.ghost?.remove?.(); } catch (_) {}
100
+ try { this._ui?.btn?.remove?.(); } catch (_) {}
101
+ }
102
+
103
+ startPlacement() {
104
+ if (this._placing) return;
105
+ this._placing = true;
106
+
107
+ const controls = this.viewer?.controls;
108
+ if (controls) {
109
+ // Запоминаем и временно выключаем OrbitControls целиком
110
+ this._controlsWasEnabled = !!controls.enabled;
111
+ controls.enabled = false;
112
+ }
113
+
114
+ this.#refreshContainerOffset();
115
+ this.#syncGhost();
116
+ this.#setGhostVisible(true);
117
+ this.#log("startPlacement", { nextId: this._nextId });
118
+ }
119
+
120
+ cancelPlacement() {
121
+ if (!this._placing) return;
122
+ this._placing = false;
123
+ this.#setGhostVisible(false);
124
+
125
+ const controls = this.viewer?.controls;
126
+ if (controls && this._controlsWasEnabled != null) {
127
+ controls.enabled = !!this._controlsWasEnabled;
128
+ this._controlsWasEnabled = null;
129
+ }
130
+
131
+ this.#log("cancelPlacement", {});
132
+ }
133
+
134
+ #log(event, payload) {
135
+ try {
136
+ this.logger?.log?.("[CardPlacement]", event, payload);
137
+ } catch (_) {}
138
+ }
139
+
140
+ #easeOutCubic(t) {
141
+ const x = Math.min(1, Math.max(0, Number(t) || 0));
142
+ const inv = 1 - x;
143
+ return 1 - inv * inv * inv; // быстрый старт, плавный конец
144
+ }
145
+
146
+ #cancelFly() {
147
+ if (this._fly.raf) cancelAnimationFrame(this._fly.raf);
148
+ this._fly.raf = 0;
149
+ this._fly.active = false;
150
+ this._fly.startTs = 0;
151
+ this._fly.from = null;
152
+ this._fly.to = null;
153
+
154
+ // Вернём OrbitControls, если отключали
155
+ try {
156
+ const controls = this.viewer?.controls;
157
+ if (controls && this._fly.prevControlsEnabled != null) controls.enabled = this._fly.prevControlsEnabled;
158
+ } catch (_) {}
159
+ this._fly.prevControlsEnabled = null;
160
+ }
161
+
162
+ #getCurrentCameraSnapshot() {
163
+ const viewer = this.viewer;
164
+ if (!viewer) return null;
165
+ const camera = viewer.camera;
166
+ const controls = viewer.controls;
167
+ if (!camera || !controls) return null;
168
+
169
+ const snap = {
170
+ projectionMode: (typeof viewer.getProjectionMode === "function")
171
+ ? viewer.getProjectionMode()
172
+ : (camera.isOrthographicCamera ? "ortho" : "perspective"),
173
+ camPos: camera.position.clone(),
174
+ target: controls.target.clone(),
175
+ fov: camera.isPerspectiveCamera ? Number(camera.fov) : null,
176
+ zoom: camera.isOrthographicCamera ? Number(camera.zoom || 1) : null,
177
+ viewOffset: (camera.view && camera.view.enabled)
178
+ ? { enabled: true, offsetX: camera.view.offsetX || 0, offsetY: camera.view.offsetY || 0 }
179
+ : { enabled: false, offsetX: 0, offsetY: 0 },
180
+ };
181
+ return snap;
182
+ }
183
+
184
+ #captureSceneState() {
185
+ const viewer = this.viewer;
186
+ if (!viewer) return null;
187
+
188
+ const camera = viewer.camera;
189
+ const controls = viewer.controls;
190
+ const model = viewer.activeModel;
191
+
192
+ const projectionMode = (typeof viewer.getProjectionMode === "function")
193
+ ? viewer.getProjectionMode()
194
+ : (camera?.isOrthographicCamera ? "ortho" : "perspective");
195
+
196
+ const camPos = camera?.position ? { x: camera.position.x, y: camera.position.y, z: camera.position.z } : null;
197
+ const target = controls?.target ? { x: controls.target.x, y: controls.target.y, z: controls.target.z } : null;
198
+
199
+ const cam = {
200
+ projectionMode,
201
+ position: camPos,
202
+ target,
203
+ fov: (camera && camera.isPerspectiveCamera) ? Number(camera.fov) : null,
204
+ zoom: (camera && camera.isOrthographicCamera) ? Number(camera.zoom || 1) : null,
205
+ // MMB-pan (camera.viewOffset) — сохраняем как есть, в пикселях
206
+ viewOffset: (camera && camera.view && camera.view.enabled)
207
+ ? { enabled: true, offsetX: camera.view.offsetX || 0, offsetY: camera.view.offsetY || 0 }
208
+ : { enabled: false, offsetX: 0, offsetY: 0 },
209
+ };
210
+
211
+ const modelTransform = model ? {
212
+ position: { x: model.position.x, y: model.position.y, z: model.position.z },
213
+ quaternion: { x: model.quaternion.x, y: model.quaternion.y, z: model.quaternion.z, w: model.quaternion.w },
214
+ scale: { x: model.scale.x, y: model.scale.y, z: model.scale.z },
215
+ } : null;
216
+
217
+ const planes = viewer.clipping?.planes || [];
218
+ const clipConstants = [
219
+ planes?.[0]?.constant,
220
+ planes?.[1]?.constant,
221
+ planes?.[2]?.constant,
222
+ ];
223
+
224
+ return {
225
+ camera: cam,
226
+ modelTransform,
227
+ clipping: { constants: clipConstants },
228
+ };
229
+ }
230
+
231
+ #restoreSceneState(sceneState) {
232
+ const viewer = this.viewer;
233
+ if (!viewer || !sceneState) return;
234
+
235
+ // 1) Проекция (может заменить ссылку viewer.camera)
236
+ try {
237
+ const pm = sceneState?.camera?.projectionMode;
238
+ if (pm && typeof viewer.setProjectionMode === "function") viewer.setProjectionMode(pm);
239
+ } catch (_) {}
240
+
241
+ const camera = viewer.camera;
242
+ const controls = viewer.controls;
243
+ const model = viewer.activeModel;
244
+
245
+ // 2) Камера + target + zoom/fov
246
+ try {
247
+ const t = sceneState?.camera?.target;
248
+ if (controls && t) controls.target.set(Number(t.x) || 0, Number(t.y) || 0, Number(t.z) || 0);
249
+ } catch (_) {}
250
+ try {
251
+ const p = sceneState?.camera?.position;
252
+ if (camera && p) camera.position.set(Number(p.x) || 0, Number(p.y) || 0, Number(p.z) || 0);
253
+ } catch (_) {}
254
+ try {
255
+ if (camera?.isPerspectiveCamera && sceneState?.camera?.fov != null) {
256
+ const fov = Number(sceneState.camera.fov);
257
+ if (Number.isFinite(fov) && fov > 1e-3 && fov < 179) camera.fov = fov;
258
+ }
259
+ } catch (_) {}
260
+ try {
261
+ if (camera?.isOrthographicCamera && sceneState?.camera?.zoom != null) {
262
+ const z = Number(sceneState.camera.zoom);
263
+ if (Number.isFinite(z) && z > 1e-6) camera.zoom = z;
264
+ }
265
+ } catch (_) {}
266
+
267
+ // 3) Трансформ модели (позиция/поворот/масштаб)
268
+ try {
269
+ const mt = sceneState?.modelTransform;
270
+ if (model && mt?.position && mt?.quaternion && mt?.scale) {
271
+ model.position.set(Number(mt.position.x) || 0, Number(mt.position.y) || 0, Number(mt.position.z) || 0);
272
+ model.quaternion.set(
273
+ Number(mt.quaternion.x) || 0,
274
+ Number(mt.quaternion.y) || 0,
275
+ Number(mt.quaternion.z) || 0,
276
+ Number(mt.quaternion.w) || 1
277
+ );
278
+ model.scale.set(Number(mt.scale.x) || 1, Number(mt.scale.y) || 1, Number(mt.scale.z) || 1);
279
+ model.updateMatrixWorld?.(true);
280
+ }
281
+ } catch (_) {}
282
+
283
+ // 4) ViewOffset (MMB-pan) — применяем после смены камеры/проекции
284
+ try {
285
+ const vo = sceneState?.camera?.viewOffset;
286
+ if (camera && vo && typeof camera.setViewOffset === "function") {
287
+ const dom = viewer?.renderer?.domElement;
288
+ const rect = dom?.getBoundingClientRect?.();
289
+ const w = Math.max(1, Math.floor(rect?.width || 1));
290
+ const h = Math.max(1, Math.floor(rect?.height || 1));
291
+ if (vo.enabled) {
292
+ camera.setViewOffset(w, h, Math.round(Number(vo.offsetX) || 0), Math.round(Number(vo.offsetY) || 0), w, h);
293
+ } else if (typeof camera.clearViewOffset === "function") {
294
+ camera.clearViewOffset();
295
+ } else {
296
+ camera.setViewOffset(w, h, 0, 0, w, h);
297
+ }
298
+ }
299
+ } catch (_) {}
300
+
301
+ // 5) Клиппинг (как Home: сначала восстановили камеру+модель, затем planes)
302
+ try {
303
+ const constants = sceneState?.clipping?.constants || [];
304
+ if (typeof viewer.setSection === "function") {
305
+ ["x", "y", "z"].forEach((axis, i) => {
306
+ const c = constants[i];
307
+ const enabled = Number.isFinite(c);
308
+ const dist = -Number(c);
309
+ viewer.setSection(axis, enabled, enabled ? dist : 0);
310
+ });
311
+ }
312
+ } catch (_) {}
313
+
314
+ try { camera?.updateProjectionMatrix?.(); } catch (_) {}
315
+ try { controls?.update?.(); } catch (_) {}
316
+ }
317
+
318
+ #applyModelTransformFromState(sceneState) {
319
+ const viewer = this.viewer;
320
+ if (!viewer || !sceneState) return;
321
+ const model = viewer.activeModel;
322
+ if (!model) return;
323
+ const mt = sceneState?.modelTransform;
324
+ if (!mt?.position || !mt?.quaternion || !mt?.scale) return;
325
+ try {
326
+ model.position.set(Number(mt.position.x) || 0, Number(mt.position.y) || 0, Number(mt.position.z) || 0);
327
+ model.quaternion.set(
328
+ Number(mt.quaternion.x) || 0,
329
+ Number(mt.quaternion.y) || 0,
330
+ Number(mt.quaternion.z) || 0,
331
+ Number(mt.quaternion.w) || 1
332
+ );
333
+ model.scale.set(Number(mt.scale.x) || 1, Number(mt.scale.y) || 1, Number(mt.scale.z) || 1);
334
+ model.updateMatrixWorld?.(true);
335
+ } catch (_) {}
336
+ }
337
+
338
+ #applyClippingFromState(sceneState) {
339
+ const viewer = this.viewer;
340
+ if (!viewer || !sceneState) return;
341
+ try {
342
+ const constants = sceneState?.clipping?.constants || [];
343
+ if (typeof viewer.setSection === "function") {
344
+ ["x", "y", "z"].forEach((axis, i) => {
345
+ const c = constants[i];
346
+ const enabled = Number.isFinite(c);
347
+ const dist = -Number(c);
348
+ viewer.setSection(axis, enabled, enabled ? dist : 0);
349
+ });
350
+ }
351
+ } catch (_) {}
352
+ }
353
+
354
+ #applyViewOffset(camera, viewOffset) {
355
+ if (!camera || !viewOffset) return;
356
+ try {
357
+ const viewer = this.viewer;
358
+ const dom = viewer?.renderer?.domElement;
359
+ const rect = dom?.getBoundingClientRect?.();
360
+ const w = Math.max(1, Math.floor(rect?.width || 1));
361
+ const h = Math.max(1, Math.floor(rect?.height || 1));
362
+
363
+ if (viewOffset.enabled) {
364
+ camera.setViewOffset(w, h, Math.round(Number(viewOffset.offsetX) || 0), Math.round(Number(viewOffset.offsetY) || 0), w, h);
365
+ } else if (typeof camera.clearViewOffset === "function") {
366
+ camera.clearViewOffset();
367
+ } else {
368
+ camera.setViewOffset(w, h, 0, 0, w, h);
369
+ }
370
+ } catch (_) {}
371
+ }
372
+
373
+ #animateToSceneState(sceneState, durationMs = 550) {
374
+ const viewer = this.viewer;
375
+ if (!viewer || !sceneState) return;
376
+
377
+ // Если уже летим — отменим предыдущую анимацию
378
+ this.#cancelFly();
379
+
380
+ // 1) Сразу применяем проекцию (может сменить viewer.camera)
381
+ try {
382
+ const pm = sceneState?.camera?.projectionMode;
383
+ if (pm && typeof viewer.setProjectionMode === "function") viewer.setProjectionMode(pm);
384
+ } catch (_) {}
385
+
386
+ // 2) Сразу применяем трансформ модели (если нужен) — камера полетит уже к нужной сцене
387
+ this.#applyModelTransformFromState(sceneState);
388
+
389
+ const camera = viewer.camera;
390
+ const controls = viewer.controls;
391
+ if (!camera || !controls) return;
392
+
393
+ const from = this.#getCurrentCameraSnapshot();
394
+ if (!from) return;
395
+
396
+ // Целевые значения (камера/target/zoom/fov/offset)
397
+ const to = {
398
+ projectionMode: sceneState?.camera?.projectionMode || from.projectionMode,
399
+ camPos: sceneState?.camera?.position
400
+ ? new THREE.Vector3(Number(sceneState.camera.position.x) || 0, Number(sceneState.camera.position.y) || 0, Number(sceneState.camera.position.z) || 0)
401
+ : from.camPos.clone(),
402
+ target: sceneState?.camera?.target
403
+ ? new THREE.Vector3(Number(sceneState.camera.target.x) || 0, Number(sceneState.camera.target.y) || 0, Number(sceneState.camera.target.z) || 0)
404
+ : from.target.clone(),
405
+ fov: (camera.isPerspectiveCamera && sceneState?.camera?.fov != null) ? Number(sceneState.camera.fov) : from.fov,
406
+ zoom: (camera.isOrthographicCamera && sceneState?.camera?.zoom != null) ? Number(sceneState.camera.zoom) : from.zoom,
407
+ viewOffset: sceneState?.camera?.viewOffset || from.viewOffset,
408
+ };
409
+
410
+ // На время "долеталки" отключаем controls
411
+ try {
412
+ this._fly.prevControlsEnabled = !!controls.enabled;
413
+ controls.enabled = false;
414
+ } catch (_) {
415
+ this._fly.prevControlsEnabled = null;
416
+ }
417
+
418
+ this._fly.active = true;
419
+ this._fly.startTs = performance.now();
420
+ this._fly.durationMs = Math.max(50, Number(durationMs) || 550);
421
+ this._fly.from = from;
422
+ this._fly.to = to;
423
+
424
+ const tick = () => {
425
+ if (!this._fly.active) return;
426
+ const now = performance.now();
427
+ const t = (now - this._fly.startTs) / this._fly.durationMs;
428
+ const k = this.#easeOutCubic(t);
429
+
430
+ // position lerp
431
+ this._fly.v0.copy(from.camPos).lerp(to.camPos, k);
432
+ camera.position.copy(this._fly.v0);
433
+
434
+ // target lerp
435
+ this._fly.v1.copy(from.target).lerp(to.target, k);
436
+ controls.target.copy(this._fly.v1);
437
+
438
+ // fov/zoom
439
+ try {
440
+ if (camera.isPerspectiveCamera && to.fov != null && from.fov != null) {
441
+ const f = Number(from.fov) + (Number(to.fov) - Number(from.fov)) * k;
442
+ if (Number.isFinite(f) && f > 1e-3 && f < 179) camera.fov = f;
443
+ }
444
+ } catch (_) {}
445
+ try {
446
+ if (camera.isOrthographicCamera && to.zoom != null && from.zoom != null) {
447
+ const z = Number(from.zoom) + (Number(to.zoom) - Number(from.zoom)) * k;
448
+ if (Number.isFinite(z) && z > 1e-6) camera.zoom = z;
449
+ }
450
+ } catch (_) {}
451
+
452
+ // viewOffset lerp
453
+ try {
454
+ const vo0 = from.viewOffset || { enabled: false, offsetX: 0, offsetY: 0 };
455
+ const vo1 = to.viewOffset || { enabled: false, offsetX: 0, offsetY: 0 };
456
+ const enabled = !!(vo0.enabled || vo1.enabled);
457
+ const ox = Number(vo0.offsetX) + (Number(vo1.offsetX) - Number(vo0.offsetX)) * k;
458
+ const oy = Number(vo0.offsetY) + (Number(vo1.offsetY) - Number(vo0.offsetY)) * k;
459
+ this.#applyViewOffset(camera, { enabled, offsetX: ox, offsetY: oy });
460
+ } catch (_) {}
461
+
462
+ try { camera.updateProjectionMatrix?.(); } catch (_) {}
463
+ try { controls.update?.(); } catch (_) {}
464
+
465
+ if (t >= 1) {
466
+ // Финал: зафиксируем точные значения
467
+ try { camera.position.copy(to.camPos); } catch (_) {}
468
+ try { controls.target.copy(to.target); } catch (_) {}
469
+ try {
470
+ if (camera.isPerspectiveCamera && to.fov != null) camera.fov = to.fov;
471
+ if (camera.isOrthographicCamera && to.zoom != null) camera.zoom = to.zoom;
472
+ } catch (_) {}
473
+ try { this.#applyViewOffset(camera, to.viewOffset); } catch (_) {}
474
+
475
+ // В конце применяем clipping (чтобы ориентация плоскостей считалась по финальной камере)
476
+ this.#applyClippingFromState(sceneState);
477
+
478
+ try { camera.updateProjectionMatrix?.(); } catch (_) {}
479
+ try { controls.update?.(); } catch (_) {}
480
+
481
+ this.#cancelFly();
482
+ return;
483
+ }
484
+
485
+ this._fly.raf = requestAnimationFrame(tick);
486
+ };
487
+
488
+ this._fly.raf = requestAnimationFrame(tick);
489
+ }
490
+
491
+ #createUi() {
492
+ const btn = document.createElement("button");
493
+ btn.type = "button";
494
+ btn.className = "ifc-card-add-btn";
495
+ btn.textContent = "+ Добавить карточку";
496
+
497
+ const ghost = document.createElement("div");
498
+ ghost.className = "ifc-card-ghost";
499
+ ghost.setAttribute("aria-hidden", "true");
500
+ ghost.style.display = "none";
501
+ // Базовая позиция: двигаем transform'ом, поэтому left/top держим в 0
502
+ ghost.style.left = "0px";
503
+ ghost.style.top = "0px";
504
+
505
+ const dot = document.createElement("div");
506
+ dot.className = "ifc-card-dot";
507
+ const num = document.createElement("div");
508
+ num.className = "ifc-card-num";
509
+
510
+ ghost.appendChild(dot);
511
+ ghost.appendChild(num);
512
+
513
+ return { btn, ghost, dot, num };
514
+ }
515
+
516
+ #attachUi() {
517
+ // Важно: container должен быть position:relative (в index.html уже так).
518
+ this.container.appendChild(this._ui.btn);
519
+ this.container.appendChild(this._ui.ghost);
520
+ }
521
+
522
+ #bindEvents() {
523
+ this._onBtnClick = (e) => {
524
+ // Не даём событию уйти в canvas/OrbitControls и не ставим метку "тем же кликом".
525
+ try { e.preventDefault(); } catch (_) {}
526
+ try { e.stopPropagation(); } catch (_) {}
527
+ try { e.stopImmediatePropagation?.(); } catch (_) {}
528
+ this.startPlacement();
529
+ };
530
+ this._ui.btn.addEventListener("click", this._onBtnClick, { passive: false });
531
+
532
+ this._onKeyDown = (e) => {
533
+ if (!this._placing) return;
534
+ if (e.key === "Escape") this.cancelPlacement();
535
+ };
536
+ window.addEventListener("keydown", this._onKeyDown);
537
+
538
+ // Смещение контейнера (#app) относительно viewport может меняться при resize/scroll.
539
+ // Обновляем кэш, чтобы призрак/метки не "плыли".
540
+ this._onWindowResize = () => {
541
+ this.#refreshContainerOffset();
542
+ if (this._placing) this.#syncGhost();
543
+ };
544
+ this._onWindowScroll = () => {
545
+ this.#refreshContainerOffset();
546
+ if (this._placing) this.#syncGhost();
547
+ };
548
+ window.addEventListener("resize", this._onWindowResize, { passive: true });
549
+ // scroll слушаем в capture, чтобы ловить скролл вложенных контейнеров
550
+ window.addEventListener("scroll", this._onWindowScroll, true);
551
+
552
+ const dom = this.viewer?.renderer?.domElement;
553
+ if (!dom) return;
554
+
555
+ this._onPointerMove = (e) => {
556
+ if (!this._placing) return;
557
+ this.#updateGhostFromClient(e.clientX, e.clientY);
558
+ };
559
+ dom.addEventListener("pointermove", this._onPointerMove, { passive: true });
560
+
561
+ // Best-effort: более частые координаты, чем pointermove (Chrome).
562
+ this._onPointerRawUpdate = (e) => {
563
+ if (!this._placing) return;
564
+ this.#updateGhostFromClient(e.clientX, e.clientY);
565
+ };
566
+ try { dom.addEventListener("pointerrawupdate", this._onPointerRawUpdate, { passive: true }); } catch (_) {}
567
+
568
+ this._onPointerDownCapture = (e) => {
569
+ if (!this._placing) return;
570
+ // Только ЛКМ ставит метку. Остальные кнопки не блокируем (например, колесо/ПКМ).
571
+ if (e.button !== 0) return;
572
+
573
+ // Блокируем другие контроллеры (OrbitControls/MMB/RMB) на время постановки.
574
+ try { e.preventDefault(); } catch (_) {}
575
+ try { e.stopPropagation(); } catch (_) {}
576
+ try { e.stopImmediatePropagation?.(); } catch (_) {}
577
+
578
+ const hit = this.#pickModelPoint(e.clientX, e.clientY);
579
+ if (!hit) {
580
+ this.#log("placeAttempt:no-hit", {});
581
+ return; // остаёмся в режиме, пользователь может кликнуть ещё раз
582
+ }
583
+ this.#createMarkerAtHit(hit);
584
+ this.cancelPlacement(); // по ТЗ: “вторым кликом устанавливаем”
585
+ };
586
+ dom.addEventListener("pointerdown", this._onPointerDownCapture, { capture: true, passive: false });
587
+ }
588
+
589
+ #setGhostVisible(visible) {
590
+ if (!this._ui?.ghost) return;
591
+ this._ui.ghost.style.display = visible ? "block" : "none";
592
+ }
593
+
594
+ #refreshContainerOffset() {
595
+ const cr = this.container?.getBoundingClientRect?.();
596
+ if (!cr) {
597
+ this._containerOffset.left = 0;
598
+ this._containerOffset.top = 0;
599
+ this._containerOffsetValid = false;
600
+ return;
601
+ }
602
+ this._containerOffset.left = cr.left || 0;
603
+ this._containerOffset.top = cr.top || 0;
604
+ this._containerOffsetValid = true;
605
+ }
606
+
607
+ #applyGhostTransform() {
608
+ const g = this._ui?.ghost;
609
+ if (!g) return;
610
+ g.style.transform = `translate3d(${this._ghostPos.x}px, ${this._ghostPos.y}px, 0) translate(-50%, -50%)`;
611
+ }
612
+
613
+ #updateGhostFromClient(clientX, clientY) {
614
+ this._lastPointer = { x: clientX, y: clientY };
615
+ if (!this._containerOffsetValid) this.#refreshContainerOffset();
616
+ const x = (clientX - this._containerOffset.left);
617
+ const y = (clientY - this._containerOffset.top);
618
+ this._ghostPos.x = x;
619
+ this._ghostPos.y = y;
620
+ // Обновляем transform сразу в обработчике — без ожидания RAF.
621
+ this.#applyGhostTransform();
622
+ }
623
+
624
+ #syncGhost() {
625
+ const g = this._ui?.ghost;
626
+ if (!g) return;
627
+ this._ui.num.textContent = String(this._nextId);
628
+ // Число может меняться (id), позиция — из последних координат курсора.
629
+ this.#updateGhostFromClient(this._lastPointer.x, this._lastPointer.y);
630
+ }
631
+
632
+ #pickModelPoint(clientX, clientY) {
633
+ const model = this.viewer?.activeModel;
634
+ const camera = this.viewer?.camera;
635
+ const dom = this.viewer?.renderer?.domElement;
636
+ if (!model || !camera || !dom) return null;
637
+
638
+ const rect = dom.getBoundingClientRect?.();
639
+ if (!rect || rect.width <= 0 || rect.height <= 0) return null;
640
+
641
+ const x = ((clientX - rect.left) / rect.width) * 2 - 1;
642
+ const y = -(((clientY - rect.top) / rect.height) * 2 - 1);
643
+ this._ndc.set(x, y);
644
+
645
+ this._raycaster.setFromCamera(this._ndc, camera);
646
+ const hits = this._raycaster.intersectObject(model, true);
647
+ if (!hits || hits.length <= 0) return null;
648
+
649
+ // ВАЖНО: у модели могут быть контурные линии/оверлеи (LineSegments),
650
+ // которые перехватывают hit раньше "реального" Mesh фасада.
651
+ // Для постановки метки выбираем первый hit именно по Mesh.
652
+ let best = null;
653
+ for (const h of hits) {
654
+ if (!h || !h.point) continue;
655
+ const obj = h.object;
656
+ if (obj && obj.isMesh) { best = h; break; }
657
+ }
658
+ // fallback: если Mesh не найден (редко), берём первый валидный hit
659
+ if (!best) {
660
+ for (const h of hits) {
661
+ if (h && h.point) { best = h; break; }
662
+ }
663
+ }
664
+
665
+ if (!best || !best.point) return null;
666
+ return best;
667
+ }
668
+
669
+ #createMarkerAtHit(hit) {
670
+ const model = this.viewer?.activeModel;
671
+ if (!model) return;
672
+
673
+ const id = this._nextId++;
674
+ const el = document.createElement("div");
675
+ el.className = "ifc-card-marker";
676
+ el.setAttribute("data-id", String(id));
677
+ el.innerHTML = `<div class="ifc-card-dot"></div><div class="ifc-card-num">${id}</div>`;
678
+ // Базовая позиция: двигаем transform'ом, поэтому left/top держим в 0
679
+ el.style.left = "0px";
680
+ el.style.top = "0px";
681
+ this.container.appendChild(el);
682
+
683
+ const sceneState = this.#captureSceneState();
684
+
685
+ // Храним локальную координату модели, чтобы метка оставалась “приклеенной” к модели
686
+ this._tmpLocal.copy(hit.point);
687
+ model.worldToLocal(this._tmpLocal);
688
+
689
+ const marker = new CardMarker({
690
+ id,
691
+ localPoint: this._tmpLocal.clone(),
692
+ el,
693
+ sceneState,
694
+ });
695
+ this._markers.push(marker);
696
+
697
+ // Клик по метке: восстановить сцену (камера/зум, модель, разрез)
698
+ this._onMarkerPointerDown = (e) => {
699
+ // Важно: не даём клику попасть в canvas/OrbitControls
700
+ try { e.preventDefault(); } catch (_) {}
701
+ try { e.stopPropagation(); } catch (_) {}
702
+ try { e.stopImmediatePropagation?.(); } catch (_) {}
703
+ // если были в режиме постановки — выходим
704
+ try { this.cancelPlacement(); } catch (_) {}
705
+ // "Долеталка" камеры: быстрый старт + мягкий конец
706
+ this.#animateToSceneState(marker.sceneState, 550);
707
+ };
708
+ // capture-phase, чтобы обогнать любые handlers на canvas
709
+ try { el.addEventListener("pointerdown", this._onMarkerPointerDown, { capture: true, passive: false }); } catch (_) {
710
+ try { el.addEventListener("pointerdown", this._onMarkerPointerDown); } catch (_) {}
711
+ }
712
+
713
+ this.#log("placed", {
714
+ id,
715
+ local: { x: +marker.localPoint.x.toFixed(4), y: +marker.localPoint.y.toFixed(4), z: +marker.localPoint.z.toFixed(4) },
716
+ sceneState: sceneState ? { hasCamera: !!sceneState.camera, hasModel: !!sceneState.modelTransform, hasClip: !!sceneState.clipping } : null,
717
+ });
718
+ }
719
+
720
+ #startRaf() {
721
+ const tick = () => {
722
+ this._raf = requestAnimationFrame(tick);
723
+ this.#updateMarkerScreenspace();
724
+ };
725
+ this._raf = requestAnimationFrame(tick);
726
+ }
727
+
728
+ #updateMarkerScreenspace() {
729
+ const model = this.viewer?.activeModel;
730
+ const camera = this.viewer?.camera;
731
+ const dom = this.viewer?.renderer?.domElement;
732
+ if (!camera || !dom) return;
733
+
734
+ const rect = dom.getBoundingClientRect?.();
735
+ if (!rect || rect.width <= 0 || rect.height <= 0) return;
736
+
737
+ const w = rect.width;
738
+ const h = rect.height;
739
+
740
+ for (const m of this._markers) {
741
+ if (!m || !m.el) continue;
742
+
743
+ if (!model) {
744
+ m.el.style.display = "none";
745
+ continue;
746
+ }
747
+
748
+ // local -> world (учитывает позицию/поворот/scale модели)
749
+ this._tmpV.copy(m.localPoint);
750
+ model.localToWorld(this._tmpV);
751
+
752
+ const ndc = this._tmpV.project(camera);
753
+
754
+ // Если точка за камерой или далеко за пределами — скрываем
755
+ const inFront = Number.isFinite(ndc.z) && ndc.z >= -1 && ndc.z <= 1;
756
+ if (!inFront) {
757
+ m.el.style.display = "none";
758
+ continue;
759
+ }
760
+
761
+ const x = (ndc.x * 0.5 + 0.5) * w;
762
+ const y = (-ndc.y * 0.5 + 0.5) * h;
763
+
764
+ if (!Number.isFinite(x) || !Number.isFinite(y)) {
765
+ m.el.style.display = "none";
766
+ continue;
767
+ }
768
+
769
+ m.el.style.display = "block";
770
+ m.el.style.transform = `translate3d(${x}px, ${y}px, 0) translate(-50%, -50%)`;
771
+ }
772
+ }
773
+ }
774
+