customforge 0.1.0-alpha.2 → 0.1.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.
Files changed (47) hide show
  1. package/CHANGELOG.md +85 -56
  2. package/LICENSES/NunitoSans-OFL.txt +93 -93
  3. package/LICENSES/plain-mug-CC-BY-4.0.txt +11 -0
  4. package/README.md +592 -461
  5. package/README.zh-CN.md +587 -459
  6. package/dist/{ProductCustomizer-rMRyWe7L.js → ProductCustomizer-4ytA68eg.js} +869 -143
  7. package/dist/ProductCustomizer-4ytA68eg.js.map +1 -0
  8. package/dist/bridge/TextureBridge.d.ts +1 -1
  9. package/dist/core/api.d.ts +94 -0
  10. package/dist/core/api.d.ts.map +1 -0
  11. package/dist/core/config.d.ts +3 -12
  12. package/dist/core/config.d.ts.map +1 -1
  13. package/dist/core/design.d.ts.map +1 -1
  14. package/dist/core/types.d.ts +183 -5
  15. package/dist/core/types.d.ts.map +1 -1
  16. package/dist/core/uv.d.ts +8 -0
  17. package/dist/core/uv.d.ts.map +1 -0
  18. package/dist/cup_decal_small_margins.glb +0 -0
  19. package/dist/customizer/ProductCustomizer.d.ts +98 -9
  20. package/dist/customizer/ProductCustomizer.d.ts.map +1 -1
  21. package/dist/editor/DesignEditor.d.ts +118 -10
  22. package/dist/editor/DesignEditor.d.ts.map +1 -1
  23. package/dist/editor/uvBounds.d.ts +15 -0
  24. package/dist/editor/uvBounds.d.ts.map +1 -0
  25. package/dist/index.d.ts +4 -2
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +1 -1
  28. package/dist/index.js.map +1 -1
  29. package/dist/style.css +2120 -1327
  30. package/dist/viewer/ProductViewer.d.ts +37 -6
  31. package/dist/viewer/ProductViewer.d.ts.map +1 -1
  32. package/dist/viewer/uvLayout.d.ts +11 -0
  33. package/dist/viewer/uvLayout.d.ts.map +1 -0
  34. package/dist/workbench/CustomForgeWorkbench.d.ts +85 -8
  35. package/dist/workbench/CustomForgeWorkbench.d.ts.map +1 -1
  36. package/dist/workbench/config.d.ts +42 -1
  37. package/dist/workbench/config.d.ts.map +1 -1
  38. package/dist/workbench/icons.d.ts.map +1 -1
  39. package/dist/workbench/index.d.ts +3 -3
  40. package/dist/workbench/index.d.ts.map +1 -1
  41. package/dist/workbench/template.d.ts.map +1 -1
  42. package/dist/workbench/types.d.ts +261 -13
  43. package/dist/workbench/types.d.ts.map +1 -1
  44. package/dist/workbench.js +1248 -116
  45. package/dist/workbench.js.map +1 -1
  46. package/package.json +27 -20
  47. package/dist/ProductCustomizer-rMRyWe7L.js.map +0 -1
@@ -1,22 +1,21 @@
1
- import { Canvas, FabricImage, Textbox } from "fabric";
2
- import { ACESFilmicToneMapping, Box3, CanvasTexture, CircleGeometry, Color, CylinderGeometry, DirectionalLight, Group, HemisphereLight, MathUtils, Mesh, MeshStandardMaterial, PerspectiveCamera, PlaneGeometry, SRGBColorSpace, Scene, TorusGeometry, Vector3, WebGLRenderer } from "three";
1
+ import { ActiveSelection, Canvas, FabricImage, Point, Textbox } from "fabric";
2
+ import { ACESFilmicToneMapping, AmbientLight, Box3, CanvasTexture, DirectionalLight, MathUtils, Mesh, MeshStandardMaterial, PerspectiveCamera, SRGBColorSpace, Scene, Vector3, WebGLRenderer } from "three";
3
3
  import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
4
4
  import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
5
5
  /**
6
6
  * 清理产品配置并补全运行所需的默认值
7
7
  *
8
- * 远程模型默认不翻转纹理,内置演示模型默认翻转纹理
8
+ * 远程模型和随包提供的默认 GLB 模型均默认不翻转纹理
9
9
  *
10
10
  * @param product 外部传入的产品配置
11
11
  * @returns 可以直接交给编辑器和查看器使用的完整配置
12
12
  */
13
13
  function normalizeProductConfiguration(product = {}) {
14
- const modelUrl = product.modelUrl?.trim() || void 0;
15
14
  return {
16
- modelUrl,
15
+ modelUrl: product.modelUrl?.trim() || void 0,
17
16
  textureUrl: product.textureUrl?.trim() || void 0,
18
17
  surfaceMesh: product.surfaceMesh?.trim() || "PrintArea",
19
- textureFlipY: product.textureFlipY ?? !modelUrl
18
+ textureFlipY: product.textureFlipY ?? false
20
19
  };
21
20
  }
22
21
  //#endregion
@@ -63,6 +62,20 @@ function readImageRole(value, path) {
63
62
  if (value !== "element" && value !== "background") throw new TypeError(`${path} must be element or background`);
64
63
  return value;
65
64
  }
65
+ function readTextAlignment(value, path) {
66
+ if (value !== "left" && value !== "center" && value !== "right") throw new TypeError(`${path} must be left, center, or right`);
67
+ return value;
68
+ }
69
+ function readTextFontStyle(value, path) {
70
+ if (value !== "normal" && value !== "italic") throw new TypeError(`${path} must be normal or italic`);
71
+ return value;
72
+ }
73
+ function readTextFontWeight(value, path) {
74
+ if (value === "normal" || value === "bold") return value;
75
+ const weight = readFiniteNumber(value, path);
76
+ if (weight <= 0 || weight > 1e3) throw new TypeError(`${path} must be between 1 and 1000`);
77
+ return weight;
78
+ }
66
79
  function parseObjectState(object, path) {
67
80
  return {
68
81
  ...object.name === void 0 ? {} : { name: readString(object.name, `${path}.name`).trim() },
@@ -97,7 +110,14 @@ function parseObject(value, index) {
97
110
  width: readPositiveNumber(object.width, `${path}.width`),
98
111
  fontFamily: readString(object.fontFamily, `${path}.fontFamily`),
99
112
  fontSize: readPositiveNumber(object.fontSize, `${path}.fontSize`),
100
- color: readString(object.color, `${path}.color`)
113
+ color: readString(object.color, `${path}.color`),
114
+ ...object.fontWeight === void 0 ? {} : { fontWeight: readTextFontWeight(object.fontWeight, `${path}.fontWeight`) },
115
+ ...object.fontStyle === void 0 ? {} : { fontStyle: readTextFontStyle(object.fontStyle, `${path}.fontStyle`) },
116
+ ...object.underline === void 0 ? {} : { underline: readBoolean(object.underline, `${path}.underline`) },
117
+ ...object.textAlign === void 0 ? {} : { textAlign: readTextAlignment(object.textAlign, `${path}.textAlign`) },
118
+ ...object.lineHeight === void 0 ? {} : { lineHeight: readPositiveNumber(object.lineHeight, `${path}.lineHeight`) },
119
+ ...object.charSpacing === void 0 ? {} : { charSpacing: readFiniteNumber(object.charSpacing, `${path}.charSpacing`) },
120
+ ...object.backgroundColor === void 0 ? {} : { backgroundColor: readString(object.backgroundColor, `${path}.backgroundColor`) }
101
121
  };
102
122
  if (object.type === "image") {
103
123
  const src = readString(object.src, `${path}.src`);
@@ -230,6 +250,55 @@ function calculateContainmentOffset(bounds, canvasWidth, canvasHeight) {
230
250
  };
231
251
  }
232
252
  //#endregion
253
+ //#region src/editor/uvBounds.ts
254
+ function fullCanvasBounds(width, height) {
255
+ return {
256
+ left: 0,
257
+ top: 0,
258
+ width,
259
+ height
260
+ };
261
+ }
262
+ /**
263
+ * 将 UV 三角形的坐标范围转换为逻辑画布包围框
264
+ *
265
+ * UV 坐标会限制在 0 到 1 之间;布局为空、无效或退化时回退到整张画布
266
+ *
267
+ * @param layout 当前可打印 Mesh 的 UV 布局
268
+ * @param flipY 是否按照垂直翻转后的纹理方向计算
269
+ * @param canvasWidth 逻辑画布宽度
270
+ * @param canvasHeight 逻辑画布高度
271
+ * @returns 当前 UV 可打印区域在逻辑画布中的轴对齐包围框
272
+ */
273
+ function calculateUvCanvasBounds(layout, flipY, canvasWidth, canvasHeight) {
274
+ const coordinates = layout.triangleCoordinates;
275
+ let minimumX = Number.POSITIVE_INFINITY;
276
+ let minimumY = Number.POSITIVE_INFINITY;
277
+ let maximumX = Number.NEGATIVE_INFINITY;
278
+ let maximumY = Number.NEGATIVE_INFINITY;
279
+ for (let index = 0; index + 1 < coordinates.length; index += 2) {
280
+ const u = coordinates[index];
281
+ const v = coordinates[index + 1];
282
+ if (!Number.isFinite(u) || !Number.isFinite(v)) continue;
283
+ const x = Math.min(Math.max(u, 0), 1) * canvasWidth;
284
+ const normalizedY = flipY ? 1 - v : v;
285
+ const y = Math.min(Math.max(normalizedY, 0), 1) * canvasHeight;
286
+ minimumX = Math.min(minimumX, x);
287
+ minimumY = Math.min(minimumY, y);
288
+ maximumX = Math.max(maximumX, x);
289
+ maximumY = Math.max(maximumY, y);
290
+ }
291
+ const width = maximumX - minimumX;
292
+ const height = maximumY - minimumY;
293
+ if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) return fullCanvasBounds(canvasWidth, canvasHeight);
294
+ return {
295
+ left: minimumX,
296
+ top: minimumY,
297
+ width,
298
+ height
299
+ };
300
+ }
301
+ //#endregion
233
302
  //#region src/editor/imageSource.ts
234
303
  function readBlobAsDataUrl(blob) {
235
304
  return new Promise((resolve, reject) => {
@@ -261,10 +330,38 @@ async function resolvePersistentImageSource(src) {
261
330
  }
262
331
  //#endregion
263
332
  //#region src/editor/DesignEditor.ts
333
+ var EDITOR_DISPLAY_GUTTER = 56;
334
+ function normalizeEditorAppearance(appearance = {}) {
335
+ const controlSize = appearance.controlSize ?? 8;
336
+ if (!Number.isFinite(controlSize) || controlSize <= 0) throw new RangeError("appearance.editor.controlSize must be greater than zero");
337
+ return {
338
+ selectionFill: appearance.selectionFill?.trim() || "rgba(19, 113, 125, 0.12)",
339
+ selectionBorder: appearance.selectionBorder?.trim() || "#13717d",
340
+ controlFill: appearance.controlFill?.trim() || "#ffffff",
341
+ controlBorder: appearance.controlBorder?.trim() || "#13717d",
342
+ objectBorder: appearance.objectBorder?.trim() || "#13717d",
343
+ controlSize,
344
+ uvFill: appearance.uvFill?.trim() || void 0,
345
+ uvBoundary: appearance.uvBoundary?.trim() || "#dc2626"
346
+ };
347
+ }
348
+ /** 将 Fabric 主画布重绘为不含选择框的实时纹理 */
349
+ var DesignCanvas = class extends Canvas {
350
+ /** 将纯设计内容绘制到稳定的纹理 Canvas */
351
+ renderTexture(context) {
352
+ const previousSkipControlsDrawing = this.skipControlsDrawing;
353
+ this.skipControlsDrawing = true;
354
+ try {
355
+ this.renderCanvas(context, this.getObjects());
356
+ } finally {
357
+ this.skipControlsDrawing = previousSkipControlsDrawing;
358
+ }
359
+ }
360
+ };
264
361
  /**
265
362
  * 基于 Fabric.js 的二维纹理编辑器
266
363
  *
267
- * 负责基础纹理、文字、图片、对象选择和 PNG 导出
364
+ * 负责基础纹理、UV 区域辅助层、文字、图片、对象选择和 PNG 导出
268
365
  * 显示尺寸可以响应容器变化,内部逻辑尺寸保持不变
269
366
  */
270
367
  var DesignEditor = class {
@@ -273,6 +370,12 @@ var DesignEditor = class {
273
370
  host;
274
371
  width;
275
372
  height;
373
+ defaultText;
374
+ textObjectName;
375
+ imageObjectName;
376
+ backgroundObjectName;
377
+ appearance;
378
+ editableBounds;
276
379
  renderListeners = /* @__PURE__ */ new Set();
277
380
  selectionListeners = /* @__PURE__ */ new Set();
278
381
  historyListeners = /* @__PURE__ */ new Set();
@@ -285,9 +388,14 @@ var DesignEditor = class {
285
388
  imageRoles = /* @__PURE__ */ new WeakMap();
286
389
  resizeObserver;
287
390
  history;
391
+ uvOverlay;
392
+ textureRenderer;
393
+ textureCanvasElement;
394
+ textureContext;
288
395
  historySignature;
289
396
  historyTimer;
290
397
  historyBusy = false;
398
+ renderingTexture = false;
291
399
  objectIdSequence = 0;
292
400
  /**
293
401
  * @param host 二维编辑器挂载容器
@@ -297,23 +405,53 @@ var DesignEditor = class {
297
405
  this.host = host;
298
406
  this.width = options.width;
299
407
  this.height = options.height;
408
+ this.defaultText = options.defaultText ?? "Edit this text";
409
+ this.textObjectName = options.textObjectName ?? "Text";
410
+ this.imageObjectName = options.imageObjectName ?? "Image";
411
+ this.backgroundObjectName = options.backgroundObjectName ?? "Background";
412
+ this.appearance = normalizeEditorAppearance(options.appearance);
413
+ this.editableBounds = {
414
+ left: 0,
415
+ top: 0,
416
+ width: this.width,
417
+ height: this.height
418
+ };
300
419
  const element = document.createElement("canvas");
301
- element.setAttribute("aria-label", "UV texture editor");
420
+ element.setAttribute("aria-label", options.ariaLabel ?? "UV texture editor");
302
421
  host.replaceChildren(element);
303
- this.canvas = new Canvas(element, {
422
+ const canvas = new DesignCanvas(element, {
304
423
  width: this.width,
305
424
  height: this.height,
306
- backgroundColor: "#f7f7f5",
307
425
  preserveObjectStacking: true,
308
- selectionColor: "rgba(19, 113, 125, 0.12)",
309
- selectionBorderColor: "#13717d"
426
+ selectionColor: this.appearance.selectionFill,
427
+ selectionBorderColor: this.appearance.selectionBorder
310
428
  });
429
+ this.canvas = canvas;
430
+ this.textureRenderer = canvas;
431
+ this.textureCanvasElement = document.createElement("canvas");
432
+ this.textureCanvasElement.width = this.width;
433
+ this.textureCanvasElement.height = this.height;
434
+ const textureContext = this.textureCanvasElement.getContext("2d");
435
+ if (!textureContext) {
436
+ canvas.dispose();
437
+ throw new Error("Unable to create the live texture canvas");
438
+ }
439
+ this.textureContext = textureContext;
311
440
  const initialDesign = this.saveDesign();
312
441
  this.history = new DesignHistory(initialDesign, options.historyLimit);
313
442
  this.historySignature = JSON.stringify(initialDesign);
314
443
  this.canvas.wrapperEl.classList.add("customforge-design-canvas");
444
+ this.uvOverlay = document.createElement("canvas");
445
+ this.uvOverlay.width = this.width;
446
+ this.uvOverlay.height = this.height;
447
+ this.uvOverlay.className = "customforge-uv-layout";
448
+ this.uvOverlay.setAttribute("aria-hidden", "true");
449
+ this.uvOverlay.hidden = true;
450
+ this.canvas.wrapperEl.insertBefore(this.uvOverlay, this.canvas.upperCanvasEl);
315
451
  this.host.dataset.renderState = "pending";
316
452
  this.canvas.on("after:render", () => {
453
+ if (this.renderingTexture) return;
454
+ this.renderTextureCanvas();
317
455
  this.markRenderState();
318
456
  this.renderListeners.forEach((listener) => listener());
319
457
  });
@@ -341,9 +479,54 @@ var DesignEditor = class {
341
479
  this.resizeObserver.observe(host);
342
480
  this.resizeDisplay();
343
481
  }
344
- /** 供 Three.js 创建 CanvasTexture 的底层 HTML Canvas */
482
+ /** 供 Three.js 创建 CanvasTexture 的纯设计画布,不包含选择框和变换控件 */
345
483
  get textureCanvas() {
346
- return this.canvas.getElement();
484
+ return this.textureCanvasElement;
485
+ }
486
+ /**
487
+ * 在交互画布上显示目标 Mesh 的 UV 可打印区域,但不写入实时纹理或导出图片
488
+ *
489
+ * @param layout 从当前目标 Mesh 提取的 UV 布局
490
+ * @param flipY 是否按照垂直翻转后的纹理方向显示
491
+ */
492
+ setUvLayout(layout, flipY) {
493
+ this.editableBounds = calculateUvCanvasBounds(layout, flipY, this.width, this.height);
494
+ const context = this.uvOverlay.getContext("2d");
495
+ if (!context) return;
496
+ context.clearRect(0, 0, this.width, this.height);
497
+ const { triangleCoordinates, boundaryCoordinates } = layout;
498
+ if (triangleCoordinates.length === 0) {
499
+ this.uvOverlay.hidden = true;
500
+ return;
501
+ }
502
+ this.uvOverlay.hidden = false;
503
+ const accent = this.appearance.uvFill ?? (getComputedStyle(this.canvas.wrapperEl).getPropertyValue("--cfw-accent").trim() || "#268a4b");
504
+ const canvasX = (u) => Math.min(Math.max(u * this.width, 1), this.width - 1);
505
+ const canvasY = (v) => Math.min(Math.max((flipY ? 1 - v : v) * this.height, 1), this.height - 1);
506
+ context.save();
507
+ context.beginPath();
508
+ for (let index = 0; index < triangleCoordinates.length; index += 6) {
509
+ context.moveTo(canvasX(triangleCoordinates[index]), canvasY(triangleCoordinates[index + 1]));
510
+ context.lineTo(canvasX(triangleCoordinates[index + 2]), canvasY(triangleCoordinates[index + 3]));
511
+ context.lineTo(canvasX(triangleCoordinates[index + 4]), canvasY(triangleCoordinates[index + 5]));
512
+ context.closePath();
513
+ }
514
+ context.fillStyle = accent;
515
+ context.globalAlpha = .012;
516
+ context.fill();
517
+ context.beginPath();
518
+ for (let index = 0; index < boundaryCoordinates.length; index += 4) {
519
+ context.moveTo(canvasX(boundaryCoordinates[index]), canvasY(boundaryCoordinates[index + 1]));
520
+ context.lineTo(canvasX(boundaryCoordinates[index + 2]), canvasY(boundaryCoordinates[index + 3]));
521
+ }
522
+ context.globalAlpha = .28;
523
+ context.strokeStyle = this.appearance.uvBoundary;
524
+ context.lineWidth = 1;
525
+ context.lineCap = "round";
526
+ context.lineJoin = "round";
527
+ context.setLineDash([6, 6]);
528
+ context.stroke();
529
+ context.restore();
347
530
  }
348
531
  /** 当前画布中设计对象的数量,不包含产品基础纹理 */
349
532
  get objectCount() {
@@ -395,6 +578,17 @@ var DesignEditor = class {
395
578
  getObjects() {
396
579
  return this.canvas.getObjects().map((object) => this.serializeObject(object));
397
580
  }
581
+ /** 返回当前逻辑画布尺寸 */
582
+ getCanvasSize() {
583
+ return {
584
+ width: this.width,
585
+ height: this.height
586
+ };
587
+ }
588
+ /** 返回当前 UV 可打印区域的独立包围框 */
589
+ getPrintableBounds() {
590
+ return { ...this.editableBounds };
591
+ }
398
592
  /** 当前选中对象的 ID,按画布层级从后到前排列 */
399
593
  getSelectedObjectIds() {
400
594
  return this.canvas.getActiveObjects().map((object) => this.objectIds.get(object)).filter((id) => Boolean(id));
@@ -406,9 +600,34 @@ var DesignEditor = class {
406
600
  * @returns 是否找到并选中了对象
407
601
  */
408
602
  selectObject(id) {
409
- const object = this.objectsById.get(id);
410
- if (!object || !object.visible) return false;
411
- this.canvas.setActiveObject(object);
603
+ return this.selectObjects([id]);
604
+ }
605
+ /**
606
+ * 按稳定 ID 同时选中多个可见对象
607
+ *
608
+ * 所有 ID 都必须有效且对象可见,否则保持原选区不变
609
+ *
610
+ * @param ids 对象 ID,空数组表示清除选区
611
+ * @returns 是否应用了请求的选区
612
+ */
613
+ selectObjects(ids) {
614
+ const uniqueIds = [...new Set(ids)];
615
+ if (uniqueIds.length === 0) return this.clearSelection();
616
+ const objects = uniqueIds.map((id) => this.objectsById.get(id));
617
+ if (objects.some((object) => !object || !object.visible)) return false;
618
+ this.applySelection(objects);
619
+ this.canvas.requestRenderAll();
620
+ this.notifySelectionChange();
621
+ return true;
622
+ }
623
+ /**
624
+ * 清除当前画布选区,不修改设计内容或历史记录
625
+ *
626
+ * @returns 清除前是否存在选中对象
627
+ */
628
+ clearSelection() {
629
+ if (!this.canvas.getActiveObject()) return false;
630
+ this.canvas.discardActiveObject();
412
631
  this.canvas.requestRenderAll();
413
632
  this.notifySelectionChange();
414
633
  return true;
@@ -457,6 +676,29 @@ var DesignEditor = class {
457
676
  return true;
458
677
  }
459
678
  /**
679
+ * 将现有图片转换为铺满当前 UV 可打印区域的设计背景
680
+ *
681
+ * 转换会替换已有设计背景、重置旋转、锁定对象并移动到最底层
682
+ *
683
+ * @param id Design JSON 中的图片对象 ID
684
+ * @returns 是否找到普通图片并完成转换
685
+ */
686
+ setImageAsBackground(id) {
687
+ this.flushHistoryCommit();
688
+ const object = this.objectsById.get(id);
689
+ if (!(object instanceof FabricImage) || this.imageRoles.get(object) === "background") return false;
690
+ this.removeDesignBackgrounds();
691
+ this.imageRoles.set(object, "background");
692
+ this.fitImageToEditableBounds(object);
693
+ this.applyObjectLock(object, true);
694
+ this.canvas.moveObjectTo(object, 0);
695
+ this.canvas.setActiveObject(object);
696
+ this.canvas.requestRenderAll();
697
+ this.notifySelectionChange();
698
+ this.commitHistory();
699
+ return true;
700
+ }
701
+ /**
460
702
  * 修改对象在图层面板中的名称
461
703
  *
462
704
  * @param id Design JSON 中的对象 ID
@@ -508,7 +750,125 @@ var DesignEditor = class {
508
750
  return true;
509
751
  }
510
752
  /**
511
- * 设置铺满画布的基础纹理,不传地址时恢复默认背景色
753
+ * 更新对象中心位置、缩放、旋转和翻转
754
+ *
755
+ * 对象最终仍会约束在逻辑画布内,连续调用会合并为一个历史步骤
756
+ *
757
+ * @param id Design JSON 中的对象 ID
758
+ * @param options 要更新的变换字段
759
+ * @returns 约束后的对象快照,找不到对象时返回 undefined
760
+ * @throws 数值无效或缩放倍数不大于零时抛出错误
761
+ */
762
+ updateObjectTransform(id, options) {
763
+ const object = this.objectsById.get(id);
764
+ if (!object) return;
765
+ this.validateTransformOptions(options);
766
+ const selectedIds = this.getSelectedObjectIds();
767
+ if (object.group instanceof ActiveSelection) this.canvas.discardActiveObject();
768
+ const current = this.serializeTransform(object);
769
+ const x = options.x ?? current.x;
770
+ const y = options.y ?? current.y;
771
+ object.set({
772
+ scaleX: options.scaleX ?? current.scaleX,
773
+ scaleY: options.scaleY ?? current.scaleY,
774
+ angle: options.rotation ?? current.rotation,
775
+ flipX: options.flipX ?? current.flipX,
776
+ flipY: options.flipY ?? current.flipY
777
+ });
778
+ object.setPositionByOrigin(new Point(x, y), "center", "center");
779
+ this.constrainObjectToCanvas(object);
780
+ const selectedObjects = selectedIds.map((selectedId) => this.objectsById.get(selectedId)).filter((selected) => Boolean(selected?.visible));
781
+ if (selectedObjects.length > 0) this.applySelection(selectedObjects);
782
+ this.canvas.requestRenderAll();
783
+ this.notifySelectionChange();
784
+ this.scheduleHistoryCommit();
785
+ return this.serializeObject(object);
786
+ }
787
+ /**
788
+ * 修改已有文字对象的内容和排版样式
789
+ *
790
+ * 连续调用会在短暂空闲后合并为一个历史步骤
791
+ * 字体必须由消费页面提前加载,否则浏览器会使用回退字体
792
+ *
793
+ * @param id Design JSON 中的对象 ID
794
+ * @param options 要修改的文字属性,未传字段保持不变
795
+ * @returns 是否找到并更新了文字对象
796
+ * @throws 字号、行高、字距、字重或 CSS 颜色不符合约束时抛出错误
797
+ */
798
+ updateText(id, options) {
799
+ const object = this.objectsById.get(id);
800
+ if (!(object instanceof Textbox)) return false;
801
+ if (options.text !== void 0) object.set({ text: options.text });
802
+ if (options.fontFamily !== void 0) {
803
+ const fontFamily = options.fontFamily.trim();
804
+ if (!fontFamily) throw new TypeError("fontFamily must be a non-empty string");
805
+ object.set({ fontFamily });
806
+ }
807
+ if (options.fontSize !== void 0) {
808
+ if (!Number.isFinite(options.fontSize) || options.fontSize <= 0) throw new RangeError("fontSize must be greater than zero");
809
+ object.set({ fontSize: options.fontSize });
810
+ }
811
+ if (options.color !== void 0) {
812
+ if (!options.color.trim()) throw new TypeError("color must be a non-empty CSS color");
813
+ object.set({ fill: options.color });
814
+ }
815
+ if (options.fontWeight !== void 0) {
816
+ if (!(options.fontWeight === "normal" || options.fontWeight === "bold" || typeof options.fontWeight === "number" && Number.isFinite(options.fontWeight) && options.fontWeight > 0 && options.fontWeight <= 1e3)) throw new RangeError("fontWeight must be normal, bold, or between 1 and 1000");
817
+ object.set({ fontWeight: options.fontWeight });
818
+ }
819
+ if (options.fontStyle !== void 0) {
820
+ if (options.fontStyle !== "normal" && options.fontStyle !== "italic") throw new TypeError("fontStyle must be normal or italic");
821
+ object.set({ fontStyle: options.fontStyle });
822
+ }
823
+ if (options.underline !== void 0) object.set({ underline: options.underline });
824
+ if (options.textAlign !== void 0) {
825
+ if (![
826
+ "left",
827
+ "center",
828
+ "right"
829
+ ].includes(options.textAlign)) throw new TypeError("textAlign must be left, center, or right");
830
+ object.set({ textAlign: options.textAlign });
831
+ }
832
+ if (options.lineHeight !== void 0) {
833
+ if (!Number.isFinite(options.lineHeight) || options.lineHeight <= 0) throw new RangeError("lineHeight must be greater than zero");
834
+ object.set({ lineHeight: options.lineHeight });
835
+ }
836
+ if (options.charSpacing !== void 0) {
837
+ if (!Number.isFinite(options.charSpacing)) throw new TypeError("charSpacing must be a finite number");
838
+ object.set({ charSpacing: options.charSpacing });
839
+ }
840
+ if (options.backgroundColor !== void 0) {
841
+ if (options.backgroundColor !== null && !options.backgroundColor.trim()) throw new TypeError("backgroundColor must be a non-empty CSS color or null");
842
+ object.set({ backgroundColor: options.backgroundColor ?? "" });
843
+ }
844
+ object.initDimensions();
845
+ if (object.group instanceof ActiveSelection) {
846
+ object.group.triggerLayout();
847
+ this.constrainObjectToCanvas(object.group);
848
+ } else this.constrainObjectToCanvas(object);
849
+ this.canvas.requestRenderAll();
850
+ this.scheduleHistoryCommit();
851
+ return true;
852
+ }
853
+ /**
854
+ * 让一个未锁定文字对象进入画布内联编辑状态
855
+ *
856
+ * @param id Design JSON 中的对象 ID
857
+ * @returns 是否找到文字对象并进入编辑状态
858
+ */
859
+ editText(id) {
860
+ this.flushHistoryCommit();
861
+ const object = this.objectsById.get(id);
862
+ if (!(object instanceof Textbox) || !object.visible || (this.objectLocks.get(object) ?? false)) return false;
863
+ this.canvas.setActiveObject(object);
864
+ object.enterEditing();
865
+ object.hiddenTextarea?.focus();
866
+ this.canvas.requestRenderAll();
867
+ this.notifySelectionChange();
868
+ return true;
869
+ }
870
+ /**
871
+ * 设置铺满画布的基础纹理,不传地址时恢复透明背景
512
872
  *
513
873
  * 背景纹理不参与对象选择,但会包含在实时纹理和 PNG 导出中
514
874
  *
@@ -518,7 +878,7 @@ var DesignEditor = class {
518
878
  async setBackgroundTexture(url) {
519
879
  if (!url) {
520
880
  this.canvas.backgroundImage = void 0;
521
- this.canvas.backgroundColor = "#f7f7f5";
881
+ this.canvas.backgroundColor = "";
522
882
  this.canvas.requestRenderAll();
523
883
  return;
524
884
  }
@@ -545,41 +905,42 @@ var DesignEditor = class {
545
905
  * 对象过大时会等比缩小,越界时会自动移回画布
546
906
  *
547
907
  * @param options 文字内容、位置和样式
548
- * @returns 创建的 Fabric Textbox
908
+ * @returns 创建后的可持久化文字对象快照
549
909
  */
550
910
  addText(options = {}) {
551
911
  this.flushHistoryCommit();
552
- const text = new Textbox(options.text ?? "Edit this text", {
912
+ const text = new Textbox(options.text ?? this.defaultText, {
553
913
  left: options.x ?? this.width * .18,
554
914
  top: options.y ?? this.height * .36,
555
915
  width: options.width ?? this.width * .42,
556
916
  fontFamily: options.fontFamily ?? "Arial",
557
- fontSize: options.fontSize ?? Math.round(this.height * .12),
558
- fontWeight: 700,
917
+ fontSize: options.fontSize ?? 22,
918
+ fontWeight: options.fontWeight ?? 700,
919
+ fontStyle: options.fontStyle ?? "normal",
920
+ underline: options.underline ?? false,
559
921
  fill: options.color ?? "#172126",
922
+ backgroundColor: options.backgroundColor ?? "",
560
923
  originX: "left",
561
924
  originY: "top",
562
- textAlign: "center",
925
+ textAlign: options.textAlign ?? "center",
926
+ lineHeight: options.lineHeight ?? 1.16,
927
+ charSpacing: options.charSpacing ?? 0,
563
928
  editable: true,
564
- transparentCorners: false,
565
- cornerColor: "#ffffff",
566
- cornerStrokeColor: "#13717d",
567
- borderColor: "#13717d",
568
- cornerSize: 16
929
+ ...this.objectControlAppearance()
569
930
  });
570
931
  this.addAndSelect(text, options.name);
571
- return text;
932
+ return this.serializeObject(text);
572
933
  }
573
934
  /**
574
935
  * 加载、添加并选中一个图片对象
575
936
  *
576
- * role 为 background 时替换已有设计背景、铺满画布并默认锁定在最底层
937
+ * role 为 background 时替换已有设计背景、铺满当前 UV 可打印区域并默认锁定在最底层
577
938
  * 图片位置使用画布像素坐标,原点位于图片中心
578
939
  * 对象过大时会等比缩小,越界时会自动移回画布
579
940
  * 远程图片必须提供正确的 CORS 响应头才能安全导出 PNG
580
941
  *
581
942
  * @param options 图片地址、中心位置和显示宽度
582
- * @returns 创建的 FabricImage
943
+ * @returns 创建后的可持久化图片对象快照
583
944
  * @throws 图片加载失败或被 CORS 策略阻止时抛出错误
584
945
  */
585
946
  async addImage(options) {
@@ -589,22 +950,21 @@ var DesignEditor = class {
589
950
  const role = options.role ?? "element";
590
951
  const scale = (options.width ?? this.width * .22) / Math.max(image.width, 1);
591
952
  image.set({
592
- left: role === "background" ? this.width / 2 : options.x ?? this.width * .62,
593
- top: role === "background" ? this.height / 2 : options.y ?? this.height * .29,
953
+ left: options.x ?? this.width * .62,
954
+ top: options.y ?? this.height * .29,
594
955
  originX: "center",
595
956
  originY: "center",
596
- scaleX: role === "background" ? this.width / Math.max(image.width, 1) : scale,
597
- scaleY: role === "background" ? this.height / Math.max(image.height, 1) : scale,
598
- transparentCorners: false,
599
- cornerColor: "#ffffff",
600
- cornerStrokeColor: "#13717d",
601
- borderColor: "#13717d",
602
- cornerSize: 16
957
+ scaleX: scale,
958
+ scaleY: scale,
959
+ ...this.objectControlAppearance()
603
960
  });
604
- if (role === "background") this.removeDesignBackgrounds();
961
+ if (role === "background") {
962
+ this.removeDesignBackgrounds();
963
+ this.fitImageToEditableBounds(image);
964
+ }
605
965
  this.imageSources.set(image, source);
606
966
  this.addAndSelect(image, options.name, role === "background", role);
607
- return image;
967
+ return this.serializeObject(image);
608
968
  }
609
969
  /**
610
970
  * 返回与 Fabric.js 无关的当前设计快照
@@ -744,16 +1104,36 @@ var DesignEditor = class {
744
1104
  * @throws 画布被无 CORS 授权的远程图片污染时抛出安全错误
745
1105
  */
746
1106
  exportTexture(filename = "custom-texture.png") {
747
- this.canvas.discardActiveObject();
748
- this.canvas.renderAll();
749
1107
  const anchor = document.createElement("a");
750
1108
  anchor.download = filename;
751
- anchor.href = this.canvas.toDataURL({
752
- format: "png",
753
- multiplier: 1
754
- });
1109
+ anchor.href = this.getTextureDataUrl();
755
1110
  anchor.click();
756
1111
  }
1112
+ /**
1113
+ * 返回不含选择框和 UV 辅助层的 PNG Data URL
1114
+ *
1115
+ * @returns 与逻辑画布同尺寸的 PNG Data URL
1116
+ * @throws 远程图片污染 Canvas 时抛出安全错误
1117
+ */
1118
+ getTextureDataUrl() {
1119
+ this.renderTextureCanvas();
1120
+ return this.textureCanvasElement.toDataURL("image/png");
1121
+ }
1122
+ /**
1123
+ * 异步返回不含选择框和 UV 辅助层的 PNG Blob
1124
+ *
1125
+ * @returns 与逻辑画布同尺寸的 PNG Blob
1126
+ * @throws 远程图片污染 Canvas 或浏览器无法编码时抛出错误
1127
+ */
1128
+ getTextureBlob() {
1129
+ this.renderTextureCanvas();
1130
+ return new Promise((resolve, reject) => {
1131
+ this.textureCanvasElement.toBlob((blob) => {
1132
+ if (blob) resolve(blob);
1133
+ else reject(/* @__PURE__ */ new Error("The texture canvas could not be encoded as PNG"));
1134
+ }, "image/png");
1135
+ });
1136
+ }
757
1137
  /** 释放 ResizeObserver、事件监听和 Fabric Canvas */
758
1138
  destroy() {
759
1139
  if (this.historyTimer !== void 0) {
@@ -820,7 +1200,14 @@ var DesignEditor = class {
820
1200
  width: object.width,
821
1201
  fontFamily: object.fontFamily,
822
1202
  fontSize: object.fontSize,
823
- color: object.fill
1203
+ color: object.fill,
1204
+ fontWeight: object.fontWeight,
1205
+ fontStyle: object.fontStyle,
1206
+ underline: object.underline,
1207
+ textAlign: object.textAlign,
1208
+ lineHeight: object.lineHeight,
1209
+ charSpacing: object.charSpacing,
1210
+ ...object.backgroundColor ? { backgroundColor: object.backgroundColor } : {}
824
1211
  };
825
1212
  }
826
1213
  if (object instanceof FabricImage) {
@@ -861,20 +1248,21 @@ var DesignEditor = class {
861
1248
  flipX: design.transform.flipX,
862
1249
  flipY: design.transform.flipY,
863
1250
  visible: design.visible ?? true,
864
- transparentCorners: false,
865
- cornerColor: "#ffffff",
866
- cornerStrokeColor: "#13717d",
867
- borderColor: "#13717d",
868
- cornerSize: 16
1251
+ ...this.objectControlAppearance()
869
1252
  };
870
1253
  if (design.type === "text") return new Textbox(design.text, {
871
1254
  ...common,
872
1255
  width: design.width,
873
1256
  fontFamily: design.fontFamily,
874
1257
  fontSize: design.fontSize,
875
- fontWeight: 700,
1258
+ fontWeight: design.fontWeight ?? 700,
1259
+ fontStyle: design.fontStyle ?? "normal",
1260
+ underline: design.underline ?? false,
876
1261
  fill: design.color,
877
- textAlign: "center",
1262
+ backgroundColor: design.backgroundColor ?? "",
1263
+ textAlign: design.textAlign ?? "center",
1264
+ lineHeight: design.lineHeight ?? 1.16,
1265
+ charSpacing: design.charSpacing ?? 0,
878
1266
  editable: true
879
1267
  });
880
1268
  const image = await this.loadImage(design.src);
@@ -885,8 +1273,9 @@ var DesignEditor = class {
885
1273
  return FabricImage.fromURL(source, source.startsWith("data:") ? void 0 : { crossOrigin: "anonymous" });
886
1274
  }
887
1275
  createObjectName(object) {
888
- if (object instanceof Textbox) return object.text.trim().slice(0, 48) || "Text";
889
- return object instanceof FabricImage ? "Image" : "Object";
1276
+ if (object instanceof Textbox) return object.text.trim().slice(0, 48) || this.textObjectName;
1277
+ if (object instanceof FabricImage) return this.imageRoles.get(object) === "background" ? this.backgroundObjectName : this.imageObjectName;
1278
+ return "Object";
890
1279
  }
891
1280
  applyObjectLock(object, locked) {
892
1281
  this.objectLocks.set(object, locked);
@@ -970,14 +1359,55 @@ var DesignEditor = class {
970
1359
  }
971
1360
  }
972
1361
  resizeDisplay() {
973
- const availableWidth = Math.max(this.host.clientWidth - 32, 1);
974
- const availableHeight = Math.max(this.host.clientHeight - 32, 1);
1362
+ const availableWidth = Math.max(this.host.clientWidth - EDITOR_DISPLAY_GUTTER, 1);
1363
+ const availableHeight = Math.max(this.host.clientHeight - EDITOR_DISPLAY_GUTTER, 1);
975
1364
  const scale = Math.min(availableWidth / this.width, availableHeight / this.height, 1);
976
1365
  this.canvas.setDimensions({
977
1366
  width: `${Math.floor(this.width * scale)}px`,
978
1367
  height: `${Math.floor(this.height * scale)}px`
979
1368
  }, { cssOnly: true });
980
1369
  }
1370
+ applySelection(objects) {
1371
+ this.canvas.discardActiveObject();
1372
+ this.canvas.setActiveObject(objects.length === 1 ? objects[0] : new ActiveSelection(objects, { canvas: this.canvas }));
1373
+ }
1374
+ objectControlAppearance() {
1375
+ return {
1376
+ transparentCorners: false,
1377
+ cornerColor: this.appearance.controlFill,
1378
+ cornerStrokeColor: this.appearance.controlBorder,
1379
+ borderColor: this.appearance.objectBorder,
1380
+ cornerSize: this.appearance.controlSize
1381
+ };
1382
+ }
1383
+ validateTransformOptions(options) {
1384
+ for (const [name, value] of [
1385
+ ["x", options.x],
1386
+ ["y", options.y],
1387
+ ["rotation", options.rotation]
1388
+ ]) if (value !== void 0 && !Number.isFinite(value)) throw new TypeError(`${name} must be a finite number`);
1389
+ for (const [name, value] of [["scaleX", options.scaleX], ["scaleY", options.scaleY]]) if (value !== void 0 && (!Number.isFinite(value) || value <= 0)) throw new RangeError(`${name} must be greater than zero`);
1390
+ for (const [name, value] of [["flipX", options.flipX], ["flipY", options.flipY]]) if (value !== void 0 && typeof value !== "boolean") throw new TypeError(`${name} must be a boolean`);
1391
+ }
1392
+ fitImageToEditableBounds(image) {
1393
+ const bounds = this.editableBounds;
1394
+ image.set({
1395
+ left: bounds.left + bounds.width / 2,
1396
+ top: bounds.top + bounds.height / 2,
1397
+ angle: 0,
1398
+ scaleX: bounds.width / Math.max(image.width, 1),
1399
+ scaleY: bounds.height / Math.max(image.height, 1)
1400
+ });
1401
+ image.setCoords();
1402
+ }
1403
+ renderTextureCanvas() {
1404
+ this.renderingTexture = true;
1405
+ try {
1406
+ this.textureRenderer.renderTexture(this.textureContext);
1407
+ } finally {
1408
+ this.renderingTexture = false;
1409
+ }
1410
+ }
981
1411
  markRenderState() {
982
1412
  if (this.host.dataset.renderState === "nonblank") return;
983
1413
  const context = this.canvas.getContext();
@@ -1009,7 +1439,7 @@ var TextureBridge = class {
1009
1439
  stopListening;
1010
1440
  updateFrame = 0;
1011
1441
  /**
1012
- * @param editor 提供底层 HTML Canvas 和渲染事件的二维编辑器
1442
+ * @param editor 提供不含交互控件的纹理 Canvas 和渲染事件的二维编辑器
1013
1443
  * @param viewer 接收实时纹理的三维查看器
1014
1444
  * @param flipY 是否垂直翻转纹理
1015
1445
  */
@@ -1047,7 +1477,96 @@ var TextureBridge = class {
1047
1477
  }
1048
1478
  };
1049
1479
  //#endregion
1480
+ //#region src/viewer/assets/cup_decal_small_margins.glb?url&no-inline
1481
+ var cup_decal_small_margins_default = "" + new URL("cup_decal_small_margins.glb", import.meta.url).href;
1482
+ //#endregion
1483
+ //#region src/viewer/uvLayout.ts
1484
+ var UV_EDGE_PRECISION = 1e6;
1485
+ function createPointKey(u, v) {
1486
+ return `${Math.round(u * UV_EDGE_PRECISION)},${Math.round(v * UV_EDGE_PRECISION)}`;
1487
+ }
1488
+ function extractBoundaryCoordinates(triangleCoordinates) {
1489
+ const edges = /* @__PURE__ */ new Map();
1490
+ for (let index = 0; index < triangleCoordinates.length; index += 6) {
1491
+ const points = [
1492
+ [triangleCoordinates[index], triangleCoordinates[index + 1]],
1493
+ [triangleCoordinates[index + 2], triangleCoordinates[index + 3]],
1494
+ [triangleCoordinates[index + 4], triangleCoordinates[index + 5]]
1495
+ ];
1496
+ for (const [startIndex, endIndex] of [
1497
+ [0, 1],
1498
+ [1, 2],
1499
+ [2, 0]
1500
+ ]) {
1501
+ const start = points[startIndex];
1502
+ const end = points[endIndex];
1503
+ const startKey = createPointKey(start[0], start[1]);
1504
+ const endKey = createPointKey(end[0], end[1]);
1505
+ const edgeKey = startKey < endKey ? `${startKey}|${endKey}` : `${endKey}|${startKey}`;
1506
+ const edge = edges.get(edgeKey);
1507
+ if (edge) edge.occurrences += 1;
1508
+ else edges.set(edgeKey, {
1509
+ coordinates: [
1510
+ start[0],
1511
+ start[1],
1512
+ end[0],
1513
+ end[1]
1514
+ ],
1515
+ occurrences: 1
1516
+ });
1517
+ }
1518
+ }
1519
+ return new Float32Array([...edges.values()].filter((edge) => edge.occurrences === 1).flatMap((edge) => edge.coordinates));
1520
+ }
1521
+ /**
1522
+ * 提取目标 Mesh 第一个材质槽使用的 UV 三角形
1523
+ *
1524
+ * @param mesh 接收实时纹理的目标 Mesh
1525
+ * @returns 保持模型原始 V 方向的 UV 三角形和外边界布局
1526
+ * @throws Mesh 缺少 UV、面数据无效或第一个材质槽没有三角形时抛出错误
1527
+ */
1528
+ function extractUvLayout(mesh) {
1529
+ const geometry = mesh.geometry;
1530
+ const uv = geometry.getAttribute("uv");
1531
+ if (!uv) throw new Error(`Customizable mesh does not contain UV coordinates: ${mesh.name}`);
1532
+ const index = geometry.getIndex();
1533
+ const elementCount = index?.count ?? uv.count;
1534
+ const ranges = Array.isArray(mesh.material) && geometry.groups.length > 0 ? geometry.groups.filter((group) => (group.materialIndex ?? 0) === 0).map(({ start, count }) => ({
1535
+ start,
1536
+ count
1537
+ })) : [{
1538
+ start: 0,
1539
+ count: elementCount
1540
+ }];
1541
+ const coordinateCount = ranges.reduce((total, range) => {
1542
+ if (!Number.isInteger(range.start) || !Number.isInteger(range.count) || range.start < 0 || range.count < 0 || range.start + range.count > elementCount || range.count % 3 !== 0) throw new Error(`Customizable mesh has invalid triangle groups: ${mesh.name}`);
1543
+ return total + range.count * 2;
1544
+ }, 0);
1545
+ if (coordinateCount === 0) throw new Error(`Customizable mesh has no triangles in its first material slot: ${mesh.name}`);
1546
+ const triangleCoordinates = new Float32Array(coordinateCount);
1547
+ let targetIndex = 0;
1548
+ for (const range of ranges) for (let offset = range.start; offset < range.start + range.count; offset += 1) {
1549
+ const vertexIndex = index ? index.getX(offset) : offset;
1550
+ const u = uv.getX(vertexIndex);
1551
+ const v = uv.getY(vertexIndex);
1552
+ if (!Number.isFinite(u) || !Number.isFinite(v)) throw new Error(`Customizable mesh has invalid UV coordinates: ${mesh.name}`);
1553
+ triangleCoordinates[targetIndex] = u;
1554
+ triangleCoordinates[targetIndex + 1] = v;
1555
+ targetIndex += 2;
1556
+ }
1557
+ return {
1558
+ triangleCoordinates,
1559
+ boundaryCoordinates: extractBoundaryCoordinates(triangleCoordinates)
1560
+ };
1561
+ }
1562
+ //#endregion
1050
1563
  //#region src/viewer/ProductViewer.ts
1564
+ var DEFAULT_PRODUCT_HEIGHT = 2.35;
1565
+ var DEFAULT_PRODUCT_BASE_Y = -1.17;
1566
+ var DEFAULT_PRODUCT_ROTATION = MathUtils.degToRad(-72);
1567
+ var DEFAULT_CAMERA_AZIMUTH = MathUtils.degToRad(18);
1568
+ var DEFAULT_CAMERA_ELEVATION = MathUtils.degToRad(10);
1569
+ var CAMERA_VIEWPORT_FILL = .7;
1051
1570
  /**
1052
1571
  * 基于 Three.js 的三维产品查看器
1053
1572
  *
@@ -1066,10 +1585,17 @@ var ProductViewer = class {
1066
1585
  surface;
1067
1586
  texture;
1068
1587
  animationFrame = 0;
1588
+ viewChangeListeners = /* @__PURE__ */ new Set();
1589
+ handleControlsChange = () => {
1590
+ const state = this.getViewState();
1591
+ this.viewChangeListeners.forEach((listener) => listener(state));
1592
+ };
1069
1593
  /**
1070
1594
  * @param host 三维查看器挂载容器
1595
+ * @param ariaLabel 三维产品画布的无障碍名称
1596
+ * @param appearance WebGL 画布清屏颜色等外观配置
1071
1597
  */
1072
- constructor(host) {
1598
+ constructor(host, ariaLabel = "Interactive 3D product preview", appearance = {}) {
1073
1599
  this.host = host;
1074
1600
  host.replaceChildren();
1075
1601
  this.renderer = new WebGLRenderer({
@@ -1080,29 +1606,30 @@ var ProductViewer = class {
1080
1606
  this.renderer.outputColorSpace = SRGBColorSpace;
1081
1607
  this.renderer.toneMapping = ACESFilmicToneMapping;
1082
1608
  this.renderer.toneMappingExposure = 1.05;
1083
- this.renderer.shadowMap.enabled = true;
1084
- this.renderer.domElement.setAttribute("aria-label", "Interactive 3D product preview");
1609
+ if (appearance.backgroundColor?.trim()) this.renderer.setClearColor(appearance.backgroundColor.trim(), 1);
1610
+ this.renderer.domElement.setAttribute("aria-label", ariaLabel);
1085
1611
  this.renderer.domElement.classList.add("customforge-viewer-canvas");
1086
1612
  host.append(this.renderer.domElement);
1087
1613
  host.dataset.renderState = "pending";
1088
- this.scene.background = new Color("#eef0ef");
1089
1614
  this.camera.position.set(4.6, 2.8, 5.8);
1090
1615
  this.controls = new OrbitControls(this.camera, this.renderer.domElement);
1091
1616
  this.controls.enableDamping = true;
1092
1617
  this.controls.minDistance = 3.2;
1093
1618
  this.controls.maxDistance = 11;
1094
1619
  this.controls.target.set(0, 0, 0);
1095
- this.addEnvironment();
1620
+ this.controls.addEventListener("change", this.handleControlsChange);
1621
+ this.addStudioLighting();
1096
1622
  this.resizeObserver = new ResizeObserver(() => this.resize());
1097
1623
  this.resizeObserver.observe(host);
1098
1624
  this.resize();
1099
1625
  this.render();
1100
1626
  }
1101
1627
  /**
1102
- * 加载远程模型或创建内置演示模型
1628
+ * 加载远程模型或随包提供的默认 GLB 模型
1103
1629
  *
1104
1630
  * @param product 已完成默认值补全的产品配置
1105
- * @throws 模型加载失败或找不到目标 Mesh 时抛出错误
1631
+ * @returns 目标 Mesh 第一个材质槽使用的 UV 三角形布局
1632
+ * @throws 模型加载失败、找不到目标 Mesh 或目标 Mesh 缺少有效 UV 时抛出错误
1106
1633
  */
1107
1634
  async loadProduct(product) {
1108
1635
  this.removeProduct();
@@ -1111,13 +1638,18 @@ var ProductViewer = class {
1111
1638
  this.productRoot = gltf.scene;
1112
1639
  this.surface = this.findSurface(gltf.scene, product.surfaceMesh);
1113
1640
  } else {
1114
- const demo = this.createDemoProduct();
1115
- this.productRoot = demo.root;
1116
- this.surface = demo.surface;
1641
+ const gltf = await this.loader.loadAsync(cup_decal_small_margins_default);
1642
+ this.productRoot = gltf.scene;
1643
+ this.surface = this.findSurface(gltf.scene, product.surfaceMesh);
1644
+ this.prepareBundledProduct(gltf.scene, this.surface);
1117
1645
  }
1646
+ const surface = this.surface;
1647
+ if (!surface) throw new Error("Customizable mesh was not initialized");
1648
+ const uvLayout = extractUvLayout(surface);
1118
1649
  this.scene.add(this.productRoot);
1119
1650
  if (this.texture) this.attachTexture(this.texture);
1120
1651
  this.fitCamera(this.productRoot);
1652
+ return uvLayout;
1121
1653
  }
1122
1654
  /**
1123
1655
  * 保存并绑定二维编辑器生成的实时纹理
@@ -1134,71 +1666,82 @@ var ProductViewer = class {
1134
1666
  resetView() {
1135
1667
  if (this.productRoot) this.fitCamera(this.productRoot);
1136
1668
  }
1669
+ /** 返回当前相机位置和轨道控制目标点的独立快照 */
1670
+ getViewState() {
1671
+ return {
1672
+ position: this.vectorToValue(this.camera.position),
1673
+ target: this.vectorToValue(this.controls.target)
1674
+ };
1675
+ }
1676
+ /**
1677
+ * 恢复相机位置和轨道控制目标点
1678
+ *
1679
+ * @param state 要恢复的三维观察视角
1680
+ * @returns 应用后的独立视角快照
1681
+ * @throws 坐标不是有限数值或相机与目标点重合时抛出错误
1682
+ */
1683
+ setViewState(state) {
1684
+ this.validateViewState(state);
1685
+ this.camera.position.set(state.position.x, state.position.y, state.position.z);
1686
+ this.controls.target.set(state.target.x, state.target.y, state.target.z);
1687
+ this.camera.updateProjectionMatrix();
1688
+ this.controls.update();
1689
+ return this.getViewState();
1690
+ }
1691
+ /**
1692
+ * 订阅三维视角变化
1693
+ *
1694
+ * 用户旋转、缩放、平移以及 API 恢复视角时都会触发
1695
+ *
1696
+ * @param listener 接收独立视角快照的监听函数
1697
+ * @returns 用于取消本次订阅的函数
1698
+ */
1699
+ onViewChange(listener) {
1700
+ this.viewChangeListeners.add(listener);
1701
+ return () => this.viewChangeListeners.delete(listener);
1702
+ }
1137
1703
  /** 释放动画帧、相机控制、模型材质和 WebGLRenderer */
1138
1704
  destroy() {
1139
1705
  cancelAnimationFrame(this.animationFrame);
1140
1706
  this.resizeObserver.disconnect();
1707
+ this.controls.removeEventListener("change", this.handleControlsChange);
1141
1708
  this.controls.dispose();
1709
+ this.viewChangeListeners.clear();
1142
1710
  this.removeProduct();
1143
1711
  this.renderer.dispose();
1144
1712
  this.renderer.domElement.remove();
1145
1713
  }
1146
- addEnvironment() {
1147
- const sky = new HemisphereLight("#ffffff", "#7c8581", 2.2);
1148
- this.scene.add(sky);
1149
- const key = new DirectionalLight("#ffffff", 3.8);
1150
- key.position.set(4, 6, 5);
1151
- key.castShadow = true;
1714
+ addStudioLighting() {
1715
+ this.scene.add(new AmbientLight("#ffffff", .9));
1716
+ const key = new DirectionalLight("#ffffff", 2.1);
1717
+ key.position.set(4, 5, 6);
1152
1718
  this.scene.add(key);
1153
- const fill = new DirectionalLight("#b7dce0", 1.2);
1154
- fill.position.set(-5, 2, 3);
1719
+ const fill = new DirectionalLight("#e8f0f2", 1.15);
1720
+ fill.position.set(-5, 2, 4);
1155
1721
  this.scene.add(fill);
1156
- const floor = new Mesh(new PlaneGeometry(30, 30), new MeshStandardMaterial({
1157
- color: "#dfe3e1",
1158
- roughness: .95
1159
- }));
1160
- floor.rotation.x = -Math.PI / 2;
1161
- floor.position.y = -1.34;
1162
- floor.receiveShadow = true;
1163
- this.scene.add(floor);
1164
- }
1165
- createDemoProduct() {
1166
- const root = new Group();
1167
- root.rotation.y = MathUtils.degToRad(-14);
1168
- const bodyMaterial = new MeshStandardMaterial({
1169
- color: "#ffffff",
1170
- roughness: .42,
1171
- metalness: 0
1172
- });
1173
- const surface = new Mesh(new CylinderGeometry(1.28, 1.16, 2.35, 96, 1, true), bodyMaterial);
1174
- surface.name = "PrintArea";
1175
- surface.castShadow = true;
1176
- surface.receiveShadow = true;
1177
- root.add(surface);
1178
- const ceramic = new MeshStandardMaterial({
1179
- color: "#f4f4f1",
1180
- roughness: .35
1722
+ const rim = new DirectionalLight("#ffffff", .8);
1723
+ rim.position.set(1, 4, -5);
1724
+ this.scene.add(rim);
1725
+ }
1726
+ prepareBundledProduct(root, surface) {
1727
+ surface.renderOrder = 1;
1728
+ (Array.isArray(surface.material) ? surface.material : [surface.material]).forEach((material) => {
1729
+ material.depthWrite = false;
1730
+ material.polygonOffset = true;
1731
+ material.polygonOffsetFactor = -1;
1732
+ material.polygonOffsetUnits = -1;
1181
1733
  });
1182
- const rim = new Mesh(new TorusGeometry(1.28, .08, 20, 96), ceramic);
1183
- rim.rotation.x = Math.PI / 2;
1184
- rim.position.y = 1.18;
1185
- rim.castShadow = true;
1186
- root.add(rim);
1187
- const inside = new Mesh(new CircleGeometry(1.2, 96), new MeshStandardMaterial({
1188
- color: "#29312f",
1189
- roughness: .7
1190
- }));
1191
- inside.rotation.x = -Math.PI / 2;
1192
- inside.position.y = 1.16;
1193
- root.add(inside);
1194
- const bottom = new Mesh(new CircleGeometry(1.15, 96), ceramic);
1195
- bottom.rotation.x = Math.PI / 2;
1196
- bottom.position.y = -1.17;
1197
- root.add(bottom);
1198
- return {
1199
- root,
1200
- surface
1201
- };
1734
+ const initialHeight = new Box3().setFromObject(root).getSize(new Vector3()).y;
1735
+ if (!Number.isFinite(initialHeight) || initialHeight <= 0) throw new Error("The bundled product has invalid bounds");
1736
+ root.scale.multiplyScalar(DEFAULT_PRODUCT_HEIGHT / initialHeight);
1737
+ root.rotation.y = DEFAULT_PRODUCT_ROTATION;
1738
+ root.updateMatrixWorld(true);
1739
+ const bounds = new Box3().setFromObject(root);
1740
+ const center = bounds.getCenter(new Vector3());
1741
+ root.position.x -= center.x;
1742
+ root.position.y += DEFAULT_PRODUCT_BASE_Y - bounds.min.y;
1743
+ root.position.z -= center.z;
1744
+ root.updateMatrixWorld(true);
1202
1745
  }
1203
1746
  /**
1204
1747
  * 按名称查找接收实时纹理的 Mesh
@@ -1231,19 +1774,59 @@ var ProductViewer = class {
1231
1774
  material.color.set("#ffffff");
1232
1775
  material.needsUpdate = true;
1233
1776
  }
1234
- fitCamera(root) {
1777
+ fitCamera(root, direction) {
1235
1778
  const bounds = new Box3().setFromObject(root);
1236
1779
  const size = bounds.getSize(new Vector3());
1237
1780
  const center = bounds.getCenter(new Vector3());
1238
- const radius = Math.max(size.x, size.y, size.z) * .5;
1239
- const distance = Math.max(radius / Math.tan(MathUtils.degToRad(this.camera.fov / 2)), 3);
1781
+ const diagonal = size.length();
1782
+ if (!Number.isFinite(diagonal) || diagonal <= 0) throw new Error("The product has invalid bounds");
1783
+ const viewDirection = direction?.clone() ?? this.defaultCameraDirection();
1784
+ if (viewDirection.lengthSq() === 0) viewDirection.copy(this.defaultCameraDirection());
1785
+ viewDirection.normalize();
1786
+ const right = new Vector3().crossVectors(this.camera.up, viewDirection);
1787
+ if (right.lengthSq() < 1e-8) right.set(1, 0, 0);
1788
+ else right.normalize();
1789
+ const up = new Vector3().crossVectors(viewDirection, right).normalize();
1790
+ const verticalSlope = Math.tan(MathUtils.degToRad(this.camera.fov / 2)) * CAMERA_VIEWPORT_FILL;
1791
+ const horizontalSlope = verticalSlope * Math.max(this.camera.aspect, .1);
1792
+ let distance = 0;
1793
+ for (const x of [bounds.min.x, bounds.max.x]) for (const y of [bounds.min.y, bounds.max.y]) for (const z of [bounds.min.z, bounds.max.z]) {
1794
+ const offset = new Vector3(x, y, z).sub(center);
1795
+ const depth = offset.dot(viewDirection);
1796
+ distance = Math.max(distance, depth + Math.abs(offset.dot(right)) / horizontalSlope, depth + Math.abs(offset.dot(up)) / verticalSlope);
1797
+ }
1798
+ distance = Math.max(distance, diagonal * .55, .1);
1240
1799
  this.controls.target.copy(center);
1241
- this.camera.position.copy(center).add(new Vector3(distance * .55, distance * .42, distance));
1242
- this.camera.near = Math.max(distance / 100, .01);
1243
- this.camera.far = distance * 100;
1800
+ this.camera.position.copy(center).addScaledVector(viewDirection, distance);
1801
+ this.camera.near = Math.max(Math.min(distance * .02, diagonal * .01), .01);
1802
+ this.camera.far = Math.max(distance + diagonal * 2, 10);
1244
1803
  this.camera.updateProjectionMatrix();
1804
+ this.controls.minDistance = Math.max(diagonal * .45, distance * .3, .05);
1805
+ this.controls.maxDistance = Math.max(distance * 4, diagonal * 4);
1245
1806
  this.controls.update();
1246
1807
  }
1808
+ defaultCameraDirection() {
1809
+ const horizontal = Math.cos(DEFAULT_CAMERA_ELEVATION);
1810
+ return new Vector3(horizontal * Math.sin(DEFAULT_CAMERA_AZIMUTH), Math.sin(DEFAULT_CAMERA_ELEVATION), horizontal * Math.cos(DEFAULT_CAMERA_AZIMUTH));
1811
+ }
1812
+ vectorToValue(vector) {
1813
+ return {
1814
+ x: vector.x,
1815
+ y: vector.y,
1816
+ z: vector.z
1817
+ };
1818
+ }
1819
+ validateViewState(state) {
1820
+ if (![
1821
+ state.position.x,
1822
+ state.position.y,
1823
+ state.position.z,
1824
+ state.target.x,
1825
+ state.target.y,
1826
+ state.target.z
1827
+ ].every(Number.isFinite)) throw new TypeError("View position and target must contain finite numbers");
1828
+ if ((state.position.x - state.target.x) ** 2 + (state.position.y - state.target.y) ** 2 + (state.position.z - state.target.z) ** 2 <= Number.EPSILON) throw new RangeError("View position and target must not be identical");
1829
+ }
1247
1830
  removeProduct() {
1248
1831
  if (!this.productRoot) return;
1249
1832
  this.scene.remove(this.productRoot);
@@ -1258,9 +1841,11 @@ var ProductViewer = class {
1258
1841
  resize() {
1259
1842
  const width = Math.max(this.host.clientWidth, 1);
1260
1843
  const height = Math.max(this.host.clientHeight, 1);
1844
+ const direction = this.camera.position.clone().sub(this.controls.target);
1261
1845
  this.renderer.setSize(width, height, false);
1262
1846
  this.camera.aspect = width / height;
1263
- this.camera.updateProjectionMatrix();
1847
+ if (this.productRoot && direction.lengthSq() > 0) this.fitCamera(this.productRoot, direction);
1848
+ else this.camera.updateProjectionMatrix();
1264
1849
  }
1265
1850
  render = () => {
1266
1851
  this.animationFrame = requestAnimationFrame(this.render);
@@ -1312,6 +1897,7 @@ var ProductCustomizer = class ProductCustomizer {
1312
1897
  stopSelectionListener;
1313
1898
  stopRenderListener;
1314
1899
  stopHistoryListener;
1900
+ stopViewListener;
1315
1901
  destroyed = false;
1316
1902
  constructor(options) {
1317
1903
  const editorHost = resolveElement(options.editor, "Editor");
@@ -1323,9 +1909,15 @@ var ProductCustomizer = class ProductCustomizer {
1323
1909
  this.editor = new DesignEditor(editorHost, {
1324
1910
  width: options.editorWidth ?? 1024,
1325
1911
  height: options.editorHeight ?? 512,
1326
- historyLimit
1912
+ historyLimit,
1913
+ ariaLabel: options.editorAriaLabel,
1914
+ defaultText: options.defaultText,
1915
+ textObjectName: options.textObjectName,
1916
+ imageObjectName: options.imageObjectName,
1917
+ backgroundObjectName: options.backgroundObjectName,
1918
+ appearance: options.appearance?.editor
1327
1919
  });
1328
- this.viewer = new ProductViewer(viewerHost);
1920
+ this.viewer = new ProductViewer(viewerHost, options.viewerAriaLabel, options.appearance?.viewer);
1329
1921
  this.textureBridge = new TextureBridge(this.editor, this.viewer, this.product.textureFlipY);
1330
1922
  this.stopSelectionListener = this.editor.onSelectionChange((objectIds) => {
1331
1923
  this.emit("selectionchange", {
@@ -1339,6 +1931,9 @@ var ProductCustomizer = class ProductCustomizer {
1339
1931
  this.stopHistoryListener = this.editor.onHistoryChange((state) => {
1340
1932
  this.emit("historychange", state);
1341
1933
  });
1934
+ this.stopViewListener = this.viewer.onViewChange((state) => {
1935
+ this.emit("viewchange", state);
1936
+ });
1342
1937
  }
1343
1938
  /**
1344
1939
  * 创建实例并完成初始产品加载
@@ -1377,27 +1972,56 @@ var ProductCustomizer = class ProductCustomizer {
1377
1972
  * 创建后和用户变换期间,对象会自动缩放或平移以保持完整可见
1378
1973
  *
1379
1974
  * @param options 文字内容、位置和样式配置
1975
+ * @returns 创建后的可持久化文字对象快照
1380
1976
  */
1381
1977
  addText(options) {
1382
- this.editor.addText(options);
1978
+ return this.editor.addText(options);
1383
1979
  }
1384
1980
  /**
1385
1981
  * 加载图片并将其添加到二维画布
1386
1982
  *
1387
- * role 为 background 时会替换已有设计背景并默认锁定在最底层
1983
+ * role 为 background 时会替换已有设计背景、铺满当前 UV 可打印区域并默认锁定在最底层
1388
1984
  * 创建后和用户变换期间,对象会自动缩放或平移以保持完整可见
1389
1985
  *
1390
1986
  * @param options 图片地址、位置和显示宽度
1987
+ * @returns 创建后的可持久化图片对象快照
1391
1988
  * @throws 图片无法访问、加载失败或被 CORS 策略阻止时抛出错误
1392
1989
  */
1393
1990
  async addImage(options) {
1394
1991
  try {
1395
- await this.editor.addImage(options);
1992
+ return await this.editor.addImage(options);
1396
1993
  } catch (error) {
1397
1994
  this.reportError(error);
1398
1995
  throw error;
1399
1996
  }
1400
1997
  }
1998
+ /** 返回产品、画布、对象、选区、历史和视角的独立状态快照 */
1999
+ getState() {
2000
+ return {
2001
+ product: this.getProduct(),
2002
+ canvas: this.getCanvasSize(),
2003
+ printableBounds: this.getPrintableBounds(),
2004
+ objects: this.getObjects(),
2005
+ selectedObjectIds: this.getSelectedObjectIds(),
2006
+ history: {
2007
+ canUndo: this.canUndo(),
2008
+ canRedo: this.canRedo()
2009
+ },
2010
+ view: this.getViewState()
2011
+ };
2012
+ }
2013
+ /** 返回当前补全默认值后的产品配置独立快照 */
2014
+ getProduct() {
2015
+ return { ...this.product };
2016
+ }
2017
+ /** 返回当前二维逻辑画布尺寸 */
2018
+ getCanvasSize() {
2019
+ return this.editor.getCanvasSize();
2020
+ }
2021
+ /** 返回当前产品 UV 在逻辑画布中的可打印包围框 */
2022
+ getPrintableBounds() {
2023
+ return this.editor.getPrintableBounds();
2024
+ }
1401
2025
  /**
1402
2026
  * 返回当前可编辑对象的独立快照
1403
2027
  *
@@ -1420,6 +2044,25 @@ var ProductCustomizer = class ProductCustomizer {
1420
2044
  return this.editor.selectObject(id);
1421
2045
  }
1422
2046
  /**
2047
+ * 按稳定 ID 同时选中多个可见对象
2048
+ *
2049
+ * 所有 ID 都必须有效且可见,否则保持原选区不变;空数组清除选区
2050
+ *
2051
+ * @param ids Design JSON 中的对象 ID
2052
+ * @returns 是否应用了请求的选区
2053
+ */
2054
+ selectObjects(ids) {
2055
+ return this.editor.selectObjects(ids);
2056
+ }
2057
+ /**
2058
+ * 清除当前画布选区,不修改设计内容或历史记录
2059
+ *
2060
+ * @returns 清除前是否存在选中对象
2061
+ */
2062
+ clearSelection() {
2063
+ return this.editor.clearSelection();
2064
+ }
2065
+ /**
1423
2066
  * 按稳定 ID 删除一个对象
1424
2067
  *
1425
2068
  * @param id Design JSON 中的对象 ID
@@ -1439,6 +2082,17 @@ var ProductCustomizer = class ProductCustomizer {
1439
2082
  return this.editor.moveObject(id, index);
1440
2083
  }
1441
2084
  /**
2085
+ * 将现有图片转换为铺满当前 UV 可打印区域的设计背景
2086
+ *
2087
+ * 转换会替换已有设计背景、重置旋转、锁定对象并移动到最底层
2088
+ *
2089
+ * @param id Design JSON 中的图片对象 ID
2090
+ * @returns 是否找到普通图片并完成转换
2091
+ */
2092
+ setImageAsBackground(id) {
2093
+ return this.editor.setImageAsBackground(id);
2094
+ }
2095
+ /**
1442
2096
  * 修改对象在图层面板中的名称
1443
2097
  *
1444
2098
  * @param id Design JSON 中的对象 ID
@@ -1469,6 +2123,39 @@ var ProductCustomizer = class ProductCustomizer {
1469
2123
  return this.editor.setObjectLocked(id, locked);
1470
2124
  }
1471
2125
  /**
2126
+ * 更新对象中心位置、缩放、旋转和翻转
2127
+ *
2128
+ * @param id Design JSON 中的对象 ID
2129
+ * @param options 要更新的变换字段
2130
+ * @returns 约束后的对象快照,找不到对象时返回 undefined
2131
+ * @throws 数值无效或缩放倍数不大于零时抛出错误
2132
+ */
2133
+ updateObjectTransform(id, options) {
2134
+ return this.editor.updateObjectTransform(id, options);
2135
+ }
2136
+ /**
2137
+ * 修改已有文字对象的内容和排版样式
2138
+ *
2139
+ * 连续调用会在短暂空闲后合并为一个撤销步骤
2140
+ *
2141
+ * @param id Design JSON 中的对象 ID
2142
+ * @param options 要修改的文字属性,未传字段保持不变
2143
+ * @returns 是否找到并更新了文字对象
2144
+ * @throws 字号、行高、字距、字重或 CSS 颜色不符合约束时抛出错误
2145
+ */
2146
+ updateText(id, options) {
2147
+ return this.editor.updateText(id, options);
2148
+ }
2149
+ /**
2150
+ * 让一个未锁定文字对象进入画布内联编辑状态
2151
+ *
2152
+ * @param id Design JSON 中的对象 ID
2153
+ * @returns 是否找到文字对象并进入编辑状态
2154
+ */
2155
+ editText(id) {
2156
+ return this.editor.editText(id);
2157
+ }
2158
+ /**
1472
2159
  * 删除二维编辑器中的当前对象或选区
1473
2160
  *
1474
2161
  * @returns 是否删除了至少一个对象
@@ -1552,6 +2239,28 @@ var ProductCustomizer = class ProductCustomizer {
1552
2239
  this.editor.clearHistory();
1553
2240
  }
1554
2241
  /**
2242
+ * 返回当前合成纹理的 PNG Data URL
2243
+ *
2244
+ * 结果与逻辑画布同尺寸,不包含选择框和 UV 辅助层
2245
+ *
2246
+ * @returns PNG Data URL
2247
+ * @throws 远程图片污染 Canvas 时抛出安全错误
2248
+ */
2249
+ getTextureDataUrl() {
2250
+ return this.editor.getTextureDataUrl();
2251
+ }
2252
+ /**
2253
+ * 异步返回当前合成纹理的 PNG Blob
2254
+ *
2255
+ * 结果与逻辑画布同尺寸,不包含选择框和 UV 辅助层
2256
+ *
2257
+ * @returns PNG Blob
2258
+ * @throws 远程图片污染 Canvas 或浏览器无法编码时抛出错误
2259
+ */
2260
+ getTextureBlob() {
2261
+ return this.editor.getTextureBlob();
2262
+ }
2263
+ /**
1555
2264
  * 将当前二维设计合成为 PNG 并触发浏览器下载
1556
2265
  *
1557
2266
  * @param filename 下载文件名,默认为 `custom-texture.png`
@@ -1564,6 +2273,20 @@ var ProductCustomizer = class ProductCustomizer {
1564
2273
  resetView() {
1565
2274
  this.viewer.resetView();
1566
2275
  }
2276
+ /** 返回当前三维相机位置和观察目标点 */
2277
+ getViewState() {
2278
+ return this.viewer.getViewState();
2279
+ }
2280
+ /**
2281
+ * 恢复三维观察视角
2282
+ *
2283
+ * @param state 要恢复的相机位置和观察目标点
2284
+ * @returns 应用后的独立视角快照
2285
+ * @throws 坐标不是有限数值或相机与目标点重合时抛出错误
2286
+ */
2287
+ setViewState(state) {
2288
+ return this.viewer.setViewState(state);
2289
+ }
1567
2290
  /**
1568
2291
  * 更换模型、基础纹理和接收纹理的目标 Mesh
1569
2292
  *
@@ -1576,12 +2299,13 @@ var ProductCustomizer = class ProductCustomizer {
1576
2299
  const nextProduct = normalizeProductConfiguration(product);
1577
2300
  this.emit("status", { message: "Loading product" });
1578
2301
  try {
1579
- await this.viewer.loadProduct(nextProduct);
2302
+ const uvLayout = await this.viewer.loadProduct(nextProduct);
1580
2303
  await this.editor.setBackgroundTexture(nextProduct.textureUrl);
1581
2304
  this.textureBridge.setFlipY(nextProduct.textureFlipY);
2305
+ this.editor.setUvLayout(uvLayout, nextProduct.textureFlipY);
1582
2306
  this.product = nextProduct;
1583
2307
  this.editor.clearHistory();
1584
- this.emit("ready", { product: this.product });
2308
+ this.emit("ready", { product: this.getProduct() });
1585
2309
  this.emit("status", { message: nextProduct.modelUrl ? "Remote product ready" : "Demo product ready" });
1586
2310
  } catch (error) {
1587
2311
  this.reportError(error);
@@ -1599,15 +2323,17 @@ var ProductCustomizer = class ProductCustomizer {
1599
2323
  this.stopSelectionListener?.();
1600
2324
  this.stopRenderListener?.();
1601
2325
  this.stopHistoryListener?.();
2326
+ this.stopViewListener?.();
1602
2327
  this.textureBridge.destroy();
1603
2328
  this.editor.destroy();
1604
2329
  this.viewer.destroy();
1605
2330
  }
1606
2331
  async initialize() {
1607
- await this.viewer.loadProduct(this.product);
2332
+ const uvLayout = await this.viewer.loadProduct(this.product);
1608
2333
  await this.editor.setBackgroundTexture(this.product.textureUrl);
1609
2334
  this.textureBridge.setFlipY(this.product.textureFlipY);
1610
- this.emit("ready", { product: this.product });
2335
+ this.editor.setUvLayout(uvLayout, this.product.textureFlipY);
2336
+ this.emit("ready", { product: this.getProduct() });
1611
2337
  }
1612
2338
  emit(event, detail) {
1613
2339
  this.events.dispatchEvent(new CustomEvent(event, { detail }));
@@ -1621,4 +2347,4 @@ var ProductCustomizer = class ProductCustomizer {
1621
2347
  //#endregion
1622
2348
  export { resolveElement as n, ProductCustomizer as t };
1623
2349
 
1624
- //# sourceMappingURL=ProductCustomizer-rMRyWe7L.js.map
2350
+ //# sourceMappingURL=ProductCustomizer-4ytA68eg.js.map