customforge 0.1.0-alpha.1 → 0.1.0-alpha.2

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 (38) hide show
  1. package/CHANGELOG.md +37 -11
  2. package/LICENSES/NunitoSans-OFL.txt +93 -0
  3. package/README.md +233 -62
  4. package/README.zh-CN.md +231 -60
  5. package/dist/NunitoSans-Variable.ttf +0 -0
  6. package/dist/ProductCustomizer-rMRyWe7L.js +1624 -0
  7. package/dist/ProductCustomizer-rMRyWe7L.js.map +1 -0
  8. package/dist/core/design.d.ts.map +1 -1
  9. package/dist/core/types.d.ts +35 -4
  10. package/dist/core/types.d.ts.map +1 -1
  11. package/dist/customizer/ProductCustomizer.d.ts +78 -0
  12. package/dist/customizer/ProductCustomizer.d.ts.map +1 -1
  13. package/dist/editor/DesignEditor.d.ts +108 -6
  14. package/dist/editor/DesignEditor.d.ts.map +1 -1
  15. package/dist/editor/DesignHistory.d.ts +27 -0
  16. package/dist/editor/DesignHistory.d.ts.map +1 -0
  17. package/dist/index.d.ts +1 -1
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +1 -1108
  20. package/dist/index.js.map +1 -1
  21. package/dist/style.css +1319 -0
  22. package/dist/workbench/CustomForgeWorkbench.d.ts +128 -0
  23. package/dist/workbench/CustomForgeWorkbench.d.ts.map +1 -0
  24. package/dist/workbench/assets/catalog.d.ts +8 -0
  25. package/dist/workbench/assets/catalog.d.ts.map +1 -0
  26. package/dist/workbench/config.d.ts +55 -0
  27. package/dist/workbench/config.d.ts.map +1 -0
  28. package/dist/workbench/icons.d.ts +4 -0
  29. package/dist/workbench/icons.d.ts.map +1 -0
  30. package/dist/workbench/index.d.ts +25 -0
  31. package/dist/workbench/index.d.ts.map +1 -0
  32. package/dist/workbench/template.d.ts +3 -0
  33. package/dist/workbench/template.d.ts.map +1 -0
  34. package/dist/workbench/types.d.ts +294 -0
  35. package/dist/workbench/types.d.ts.map +1 -0
  36. package/dist/workbench.js +1920 -0
  37. package/dist/workbench.js.map +1 -0
  38. package/package.json +70 -71
@@ -0,0 +1,1624 @@
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";
3
+ import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
4
+ import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
5
+ /**
6
+ * 清理产品配置并补全运行所需的默认值
7
+ *
8
+ * 远程模型默认不翻转纹理,内置演示模型默认翻转纹理
9
+ *
10
+ * @param product 外部传入的产品配置
11
+ * @returns 可以直接交给编辑器和查看器使用的完整配置
12
+ */
13
+ function normalizeProductConfiguration(product = {}) {
14
+ const modelUrl = product.modelUrl?.trim() || void 0;
15
+ return {
16
+ modelUrl,
17
+ textureUrl: product.textureUrl?.trim() || void 0,
18
+ surfaceMesh: product.surfaceMesh?.trim() || "PrintArea",
19
+ textureFlipY: product.textureFlipY ?? !modelUrl
20
+ };
21
+ }
22
+ //#endregion
23
+ //#region src/core/dom.ts
24
+ /**
25
+ * 将 HTMLElement 或 CSS 选择器解析为挂载容器
26
+ *
27
+ * @param target DOM 元素或 CSS 选择器
28
+ * @param label 错误消息中使用的容器名称
29
+ * @returns 解析得到的 DOM 元素
30
+ * @throws CSS 选择器无法找到对应元素时抛出错误
31
+ */
32
+ function resolveElement(target, label) {
33
+ if (target instanceof HTMLElement) return target;
34
+ const element = document.querySelector(target);
35
+ if (!element) throw new Error(`${label} element was not found: ${target}`);
36
+ return element;
37
+ }
38
+ function isRecord(value) {
39
+ return typeof value === "object" && value !== null && !Array.isArray(value);
40
+ }
41
+ function readRecord(value, path) {
42
+ if (!isRecord(value)) throw new TypeError(`${path} must be an object`);
43
+ return value;
44
+ }
45
+ function readString(value, path, allowEmpty = false) {
46
+ if (typeof value !== "string" || !allowEmpty && value.trim().length === 0) throw new TypeError(`${path} must be ${allowEmpty ? "a string" : "a non-empty string"}`);
47
+ return value;
48
+ }
49
+ function readFiniteNumber(value, path) {
50
+ if (typeof value !== "number" || !Number.isFinite(value)) throw new TypeError(`${path} must be a finite number`);
51
+ return value;
52
+ }
53
+ function readPositiveNumber(value, path) {
54
+ const number = readFiniteNumber(value, path);
55
+ if (number <= 0) throw new TypeError(`${path} must be greater than zero`);
56
+ return number;
57
+ }
58
+ function readBoolean(value, path) {
59
+ if (typeof value !== "boolean") throw new TypeError(`${path} must be a boolean`);
60
+ return value;
61
+ }
62
+ function readImageRole(value, path) {
63
+ if (value !== "element" && value !== "background") throw new TypeError(`${path} must be element or background`);
64
+ return value;
65
+ }
66
+ function parseObjectState(object, path) {
67
+ return {
68
+ ...object.name === void 0 ? {} : { name: readString(object.name, `${path}.name`).trim() },
69
+ visible: object.visible === void 0 ? true : readBoolean(object.visible, `${path}.visible`),
70
+ locked: object.locked === void 0 ? false : readBoolean(object.locked, `${path}.locked`)
71
+ };
72
+ }
73
+ function parseTransform(value, path) {
74
+ const transform = readRecord(value, path);
75
+ return {
76
+ x: readFiniteNumber(transform.x, `${path}.x`),
77
+ y: readFiniteNumber(transform.y, `${path}.y`),
78
+ scaleX: readPositiveNumber(transform.scaleX, `${path}.scaleX`),
79
+ scaleY: readPositiveNumber(transform.scaleY, `${path}.scaleY`),
80
+ rotation: readFiniteNumber(transform.rotation, `${path}.rotation`),
81
+ flipX: readBoolean(transform.flipX, `${path}.flipX`),
82
+ flipY: readBoolean(transform.flipY, `${path}.flipY`)
83
+ };
84
+ }
85
+ function parseObject(value, index) {
86
+ const path = `design.objects[${index}]`;
87
+ const object = readRecord(value, path);
88
+ const id = readString(object.id, `${path}.id`);
89
+ const transform = parseTransform(object.transform, `${path}.transform`);
90
+ const state = parseObjectState(object, path);
91
+ if (object.type === "text") return {
92
+ id,
93
+ type: "text",
94
+ ...state,
95
+ transform,
96
+ text: readString(object.text, `${path}.text`, true),
97
+ width: readPositiveNumber(object.width, `${path}.width`),
98
+ fontFamily: readString(object.fontFamily, `${path}.fontFamily`),
99
+ fontSize: readPositiveNumber(object.fontSize, `${path}.fontSize`),
100
+ color: readString(object.color, `${path}.color`)
101
+ };
102
+ if (object.type === "image") {
103
+ const src = readString(object.src, `${path}.src`);
104
+ if (src.startsWith("blob:")) throw new TypeError(`${path}.src must not use a Blob URL`);
105
+ return {
106
+ id,
107
+ type: "image",
108
+ ...state,
109
+ transform,
110
+ src,
111
+ ...object.role === void 0 ? {} : { role: readImageRole(object.role, `${path}.role`) }
112
+ };
113
+ }
114
+ throw new TypeError(`${path}.type is not supported`);
115
+ }
116
+ /**
117
+ * 校验并净化外部 Design JSON
118
+ *
119
+ * @param value JSON.parse 结果或其他未知输入
120
+ * @returns 只包含当前 Schema 字段的新设计文档
121
+ * @throws 文档版本、字段类型、对象 ID 或图片来源不符合契约时抛出 TypeError
122
+ */
123
+ function parseDesignDocument(value) {
124
+ const design = readRecord(value, "design");
125
+ if (design.version !== 1) throw new TypeError(`design.version must be 1`);
126
+ const canvas = readRecord(design.canvas, "design.canvas");
127
+ if (!Array.isArray(design.objects)) throw new TypeError("design.objects must be an array");
128
+ const objects = design.objects.map(parseObject);
129
+ const ids = /* @__PURE__ */ new Set();
130
+ let backgroundCount = 0;
131
+ for (const object of objects) {
132
+ if (ids.has(object.id)) throw new TypeError(`design object id is duplicated: ${object.id}`);
133
+ ids.add(object.id);
134
+ if (object.type === "image" && object.role === "background") {
135
+ backgroundCount += 1;
136
+ if (backgroundCount > 1) throw new TypeError("design must not contain more than one background");
137
+ if (objects.indexOf(object) !== 0) throw new TypeError("design background must be the first object");
138
+ }
139
+ }
140
+ return {
141
+ version: 1,
142
+ canvas: {
143
+ width: readPositiveNumber(canvas.width, "design.canvas.width"),
144
+ height: readPositiveNumber(canvas.height, "design.canvas.height")
145
+ },
146
+ objects
147
+ };
148
+ }
149
+ //#endregion
150
+ //#region src/editor/DesignHistory.ts
151
+ /** 固定容量的设计快照历史 */
152
+ var DesignHistory = class {
153
+ limit;
154
+ entries;
155
+ index = 0;
156
+ /**
157
+ * @param initial 初始设计快照
158
+ * @param limit 最多保留的撤销步骤数量
159
+ */
160
+ constructor(initial, limit) {
161
+ this.limit = limit;
162
+ if (!Number.isInteger(limit) || limit < 1) throw new RangeError("History limit must be a positive integer");
163
+ this.entries = [initial];
164
+ }
165
+ /** 当前撤销与重做可用状态 */
166
+ get state() {
167
+ return {
168
+ canUndo: this.index > 0,
169
+ canRedo: this.index < this.entries.length - 1
170
+ };
171
+ }
172
+ /** 当前步骤之前的快照 */
173
+ peekUndo() {
174
+ return this.entries[this.index - 1];
175
+ }
176
+ /** 当前步骤之后的快照 */
177
+ peekRedo() {
178
+ return this.entries[this.index + 1];
179
+ }
180
+ /** 添加新快照并丢弃当前步骤之后的重做分支 */
181
+ push(snapshot) {
182
+ this.entries.splice(this.index + 1);
183
+ this.entries.push(snapshot);
184
+ if (this.entries.length > this.limit + 1) this.entries.splice(0, this.entries.length - this.limit - 1);
185
+ this.index = this.entries.length - 1;
186
+ }
187
+ /** 在目标快照成功恢复后确认一次撤销 */
188
+ confirmUndo() {
189
+ if (this.index > 0) this.index -= 1;
190
+ }
191
+ /** 在目标快照成功恢复后确认一次重做 */
192
+ confirmRedo() {
193
+ if (this.index < this.entries.length - 1) this.index += 1;
194
+ }
195
+ /** 以当前快照重新开始历史记录 */
196
+ reset(snapshot) {
197
+ this.entries = [snapshot];
198
+ this.index = 0;
199
+ }
200
+ };
201
+ //#endregion
202
+ //#region src/editor/objectBounds.ts
203
+ /**
204
+ * 计算对象完整进入画布所需的最大等比缩放系数
205
+ *
206
+ * @param bounds 对象当前的轴对齐包围盒
207
+ * @param canvasWidth 画布逻辑宽度
208
+ * @param canvasHeight 画布逻辑高度
209
+ * @returns 不大于 1 的缩放系数,对象已经可容纳时返回 1
210
+ */
211
+ function calculateContainmentScale(bounds, canvasWidth, canvasHeight) {
212
+ const widthScale = bounds.width > canvasWidth ? canvasWidth / bounds.width : 1;
213
+ const heightScale = bounds.height > canvasHeight ? canvasHeight / bounds.height : 1;
214
+ return Math.min(widthScale, heightScale, 1);
215
+ }
216
+ /**
217
+ * 计算可容纳对象移回画布所需的平移距离
218
+ *
219
+ * 调用前应先确保包围盒不大于画布,否则无法同时满足两侧边界
220
+ *
221
+ * @param bounds 对象当前的轴对齐包围盒
222
+ * @param canvasWidth 画布逻辑宽度
223
+ * @param canvasHeight 画布逻辑高度
224
+ * @returns 应叠加到对象位置的画布坐标偏移量
225
+ */
226
+ function calculateContainmentOffset(bounds, canvasWidth, canvasHeight) {
227
+ return {
228
+ x: bounds.left < 0 ? -bounds.left : Math.min(0, canvasWidth - bounds.left - bounds.width),
229
+ y: bounds.top < 0 ? -bounds.top : Math.min(0, canvasHeight - bounds.top - bounds.height)
230
+ };
231
+ }
232
+ //#endregion
233
+ //#region src/editor/imageSource.ts
234
+ function readBlobAsDataUrl(blob) {
235
+ return new Promise((resolve, reject) => {
236
+ const reader = new FileReader();
237
+ reader.addEventListener("load", () => {
238
+ if (typeof reader.result === "string") resolve(reader.result);
239
+ else reject(/* @__PURE__ */ new Error("Blob image could not be converted to a Data URL"));
240
+ });
241
+ reader.addEventListener("error", () => {
242
+ reject(reader.error ?? /* @__PURE__ */ new Error("Blob image could not be read"));
243
+ });
244
+ reader.readAsDataURL(blob);
245
+ });
246
+ }
247
+ /**
248
+ * 将短生命周期 Blob URL 转换为可写入 Design JSON 的 Data URL
249
+ *
250
+ * 远程 URL 和已有 Data URL 会保持不变
251
+ *
252
+ * @param src 图片来源
253
+ * @returns 可跨页面会话重新加载的图片来源
254
+ * @throws Blob URL 已失效或浏览器无法读取对应 Blob 时抛出错误
255
+ */
256
+ async function resolvePersistentImageSource(src) {
257
+ if (!src.startsWith("blob:")) return src;
258
+ const response = await fetch(src);
259
+ if (!response.ok) throw new Error(`Blob image could not be loaded: ${response.status}`);
260
+ return readBlobAsDataUrl(await response.blob());
261
+ }
262
+ //#endregion
263
+ //#region src/editor/DesignEditor.ts
264
+ /**
265
+ * 基于 Fabric.js 的二维纹理编辑器
266
+ *
267
+ * 负责基础纹理、文字、图片、对象选择和 PNG 导出
268
+ * 显示尺寸可以响应容器变化,内部逻辑尺寸保持不变
269
+ */
270
+ var DesignEditor = class {
271
+ /** 当前实例使用的 Fabric Canvas */
272
+ canvas;
273
+ host;
274
+ width;
275
+ height;
276
+ renderListeners = /* @__PURE__ */ new Set();
277
+ selectionListeners = /* @__PURE__ */ new Set();
278
+ historyListeners = /* @__PURE__ */ new Set();
279
+ objectIds = /* @__PURE__ */ new WeakMap();
280
+ objectsById = /* @__PURE__ */ new Map();
281
+ objectNames = /* @__PURE__ */ new WeakMap();
282
+ objectLocks = /* @__PURE__ */ new WeakMap();
283
+ usedObjectIds = /* @__PURE__ */ new Set();
284
+ imageSources = /* @__PURE__ */ new WeakMap();
285
+ imageRoles = /* @__PURE__ */ new WeakMap();
286
+ resizeObserver;
287
+ history;
288
+ historySignature;
289
+ historyTimer;
290
+ historyBusy = false;
291
+ objectIdSequence = 0;
292
+ /**
293
+ * @param host 二维编辑器挂载容器
294
+ * @param options 画布逻辑尺寸和历史容量
295
+ */
296
+ constructor(host, options) {
297
+ this.host = host;
298
+ this.width = options.width;
299
+ this.height = options.height;
300
+ const element = document.createElement("canvas");
301
+ element.setAttribute("aria-label", "UV texture editor");
302
+ host.replaceChildren(element);
303
+ this.canvas = new Canvas(element, {
304
+ width: this.width,
305
+ height: this.height,
306
+ backgroundColor: "#f7f7f5",
307
+ preserveObjectStacking: true,
308
+ selectionColor: "rgba(19, 113, 125, 0.12)",
309
+ selectionBorderColor: "#13717d"
310
+ });
311
+ const initialDesign = this.saveDesign();
312
+ this.history = new DesignHistory(initialDesign, options.historyLimit);
313
+ this.historySignature = JSON.stringify(initialDesign);
314
+ this.canvas.wrapperEl.classList.add("customforge-design-canvas");
315
+ this.host.dataset.renderState = "pending";
316
+ this.canvas.on("after:render", () => {
317
+ this.markRenderState();
318
+ this.renderListeners.forEach((listener) => listener());
319
+ });
320
+ const notifySelection = () => this.notifySelectionChange();
321
+ this.canvas.on("selection:created", notifySelection);
322
+ this.canvas.on("selection:updated", notifySelection);
323
+ this.canvas.on("selection:cleared", notifySelection);
324
+ const constrainTarget = ({ target }) => {
325
+ this.constrainObjectToCanvas(target);
326
+ };
327
+ this.canvas.on("object:moving", constrainTarget);
328
+ this.canvas.on("object:scaling", constrainTarget);
329
+ this.canvas.on("object:rotating", constrainTarget);
330
+ this.canvas.on("object:skewing", constrainTarget);
331
+ this.canvas.on("object:resizing", constrainTarget);
332
+ this.canvas.on("object:modified", ({ target }) => {
333
+ this.constrainObjectToCanvas(target);
334
+ this.commitHistory();
335
+ });
336
+ this.canvas.on("text:changed", ({ target }) => {
337
+ this.constrainObjectToCanvas(target);
338
+ this.scheduleHistoryCommit();
339
+ });
340
+ this.resizeObserver = new ResizeObserver(() => this.resizeDisplay());
341
+ this.resizeObserver.observe(host);
342
+ this.resizeDisplay();
343
+ }
344
+ /** 供 Three.js 创建 CanvasTexture 的底层 HTML Canvas */
345
+ get textureCanvas() {
346
+ return this.canvas.getElement();
347
+ }
348
+ /** 当前画布中设计对象的数量,不包含产品基础纹理 */
349
+ get objectCount() {
350
+ return this.canvas.getObjects().length;
351
+ }
352
+ /**
353
+ * 订阅 Fabric Canvas 完成渲染事件
354
+ *
355
+ * @param listener 每次画布完成渲染后调用的函数
356
+ * @returns 用于取消本次订阅的函数
357
+ */
358
+ onRender(listener) {
359
+ this.renderListeners.add(listener);
360
+ return () => this.renderListeners.delete(listener);
361
+ }
362
+ /**
363
+ * 订阅画布选中状态变化
364
+ *
365
+ * @param listener 接收当前选中对象 ID 的函数
366
+ * @returns 用于取消本次订阅的函数
367
+ */
368
+ onSelectionChange(listener) {
369
+ this.selectionListeners.add(listener);
370
+ return () => this.selectionListeners.delete(listener);
371
+ }
372
+ /**
373
+ * 订阅撤销与重做可用状态变化
374
+ *
375
+ * @param listener 接收最新历史状态的函数
376
+ * @returns 用于取消本次订阅的函数
377
+ */
378
+ onHistoryChange(listener) {
379
+ this.historyListeners.add(listener);
380
+ return () => this.historyListeners.delete(listener);
381
+ }
382
+ /** 当前是否存在可以撤销的设计快照 */
383
+ get canUndo() {
384
+ return this.history.state.canUndo;
385
+ }
386
+ /** 当前是否存在可以重做的设计快照 */
387
+ get canRedo() {
388
+ return this.history.state.canRedo;
389
+ }
390
+ /**
391
+ * 返回当前对象的独立 Design JSON 快照
392
+ *
393
+ * @returns 按画布层级从后到前排列的对象数组
394
+ */
395
+ getObjects() {
396
+ return this.canvas.getObjects().map((object) => this.serializeObject(object));
397
+ }
398
+ /** 当前选中对象的 ID,按画布层级从后到前排列 */
399
+ getSelectedObjectIds() {
400
+ return this.canvas.getActiveObjects().map((object) => this.objectIds.get(object)).filter((id) => Boolean(id));
401
+ }
402
+ /**
403
+ * 按稳定 ID 选中一个可见对象
404
+ *
405
+ * @param id Design JSON 中的对象 ID
406
+ * @returns 是否找到并选中了对象
407
+ */
408
+ selectObject(id) {
409
+ const object = this.objectsById.get(id);
410
+ if (!object || !object.visible) return false;
411
+ this.canvas.setActiveObject(object);
412
+ this.canvas.requestRenderAll();
413
+ this.notifySelectionChange();
414
+ return true;
415
+ }
416
+ /**
417
+ * 按稳定 ID 删除一个对象
418
+ *
419
+ * @param id Design JSON 中的对象 ID
420
+ * @returns 是否找到并删除了对象
421
+ */
422
+ removeObject(id) {
423
+ this.flushHistoryCommit();
424
+ const object = this.objectsById.get(id);
425
+ if (!object) return false;
426
+ if (this.canvas.getActiveObjects().includes(object)) this.canvas.discardActiveObject();
427
+ this.canvas.remove(object);
428
+ this.unregisterObject(object);
429
+ object.dispose();
430
+ this.canvas.requestRenderAll();
431
+ this.notifySelectionChange();
432
+ this.commitHistory();
433
+ return true;
434
+ }
435
+ /**
436
+ * 将对象移动到指定图层索引
437
+ *
438
+ * @param id Design JSON 中的对象 ID
439
+ * @param index 从 0 开始的索引,0 表示最底层
440
+ * @returns 对象层级是否发生变化
441
+ */
442
+ moveObject(id, index) {
443
+ this.flushHistoryCommit();
444
+ const object = this.objectsById.get(id);
445
+ const objects = this.canvas.getObjects();
446
+ if (!object || !Number.isInteger(index) || objects.length === 0) return false;
447
+ const currentIndex = objects.indexOf(object);
448
+ const role = object instanceof FabricImage ? this.imageRoles.get(object) ?? "element" : "element";
449
+ const backgroundCount = objects.filter((entry) => entry instanceof FabricImage && this.imageRoles.get(entry) === "background").length;
450
+ const minimumIndex = role === "background" ? 0 : backgroundCount;
451
+ const maximumIndex = role === "background" ? 0 : objects.length - 1;
452
+ const nextIndex = Math.min(Math.max(index, minimumIndex), maximumIndex);
453
+ if (currentIndex === nextIndex) return false;
454
+ this.canvas.moveObjectTo(object, nextIndex);
455
+ this.canvas.requestRenderAll();
456
+ this.commitHistory();
457
+ return true;
458
+ }
459
+ /**
460
+ * 修改对象在图层面板中的名称
461
+ *
462
+ * @param id Design JSON 中的对象 ID
463
+ * @param name 非空图层名称
464
+ * @returns 是否找到并更新了对象
465
+ */
466
+ renameObject(id, name) {
467
+ this.flushHistoryCommit();
468
+ const object = this.objectsById.get(id);
469
+ const normalizedName = name.trim();
470
+ if (!object || !normalizedName) return false;
471
+ this.objectNames.set(object, normalizedName);
472
+ this.canvas.requestRenderAll();
473
+ this.commitHistory();
474
+ return true;
475
+ }
476
+ /**
477
+ * 修改对象是否参与渲染
478
+ *
479
+ * @param id Design JSON 中的对象 ID
480
+ * @param visible 是否参与二维画布、三维纹理和 PNG 渲染
481
+ * @returns 是否找到并更新了对象
482
+ */
483
+ setObjectVisibility(id, visible) {
484
+ this.flushHistoryCommit();
485
+ const object = this.objectsById.get(id);
486
+ if (!object || object.visible === visible) return Boolean(object);
487
+ if (!visible && this.canvas.getActiveObjects().includes(object)) this.canvas.discardActiveObject();
488
+ object.set({ visible });
489
+ this.canvas.requestRenderAll();
490
+ this.notifySelectionChange();
491
+ this.commitHistory();
492
+ return true;
493
+ }
494
+ /**
495
+ * 修改对象是否允许通过画布控件变换
496
+ *
497
+ * @param id Design JSON 中的对象 ID
498
+ * @param locked 是否锁定移动、缩放、旋转、倾斜和文字编辑
499
+ * @returns 是否找到并更新了对象
500
+ */
501
+ setObjectLocked(id, locked) {
502
+ this.flushHistoryCommit();
503
+ const object = this.objectsById.get(id);
504
+ if (!object) return false;
505
+ this.applyObjectLock(object, locked);
506
+ this.canvas.requestRenderAll();
507
+ this.commitHistory();
508
+ return true;
509
+ }
510
+ /**
511
+ * 设置铺满画布的基础纹理,不传地址时恢复默认背景色
512
+ *
513
+ * 背景纹理不参与对象选择,但会包含在实时纹理和 PNG 导出中
514
+ *
515
+ * @param url 基础纹理地址
516
+ * @throws 图片加载失败或被 CORS 策略阻止时抛出错误
517
+ */
518
+ async setBackgroundTexture(url) {
519
+ if (!url) {
520
+ this.canvas.backgroundImage = void 0;
521
+ this.canvas.backgroundColor = "#f7f7f5";
522
+ this.canvas.requestRenderAll();
523
+ return;
524
+ }
525
+ const image = await FabricImage.fromURL(url, { crossOrigin: "anonymous" });
526
+ const scaleX = this.width / Math.max(image.width, 1);
527
+ const scaleY = this.height / Math.max(image.height, 1);
528
+ image.set({
529
+ left: 0,
530
+ top: 0,
531
+ originX: "left",
532
+ originY: "top",
533
+ scaleX,
534
+ scaleY,
535
+ selectable: false,
536
+ evented: false
537
+ });
538
+ this.canvas.backgroundImage = image;
539
+ this.canvas.requestRenderAll();
540
+ }
541
+ /**
542
+ * 添加并选中一个可编辑文字对象
543
+ *
544
+ * 文字位置使用画布像素坐标,原点位于对象左上角
545
+ * 对象过大时会等比缩小,越界时会自动移回画布
546
+ *
547
+ * @param options 文字内容、位置和样式
548
+ * @returns 创建的 Fabric Textbox
549
+ */
550
+ addText(options = {}) {
551
+ this.flushHistoryCommit();
552
+ const text = new Textbox(options.text ?? "Edit this text", {
553
+ left: options.x ?? this.width * .18,
554
+ top: options.y ?? this.height * .36,
555
+ width: options.width ?? this.width * .42,
556
+ fontFamily: options.fontFamily ?? "Arial",
557
+ fontSize: options.fontSize ?? Math.round(this.height * .12),
558
+ fontWeight: 700,
559
+ fill: options.color ?? "#172126",
560
+ originX: "left",
561
+ originY: "top",
562
+ textAlign: "center",
563
+ editable: true,
564
+ transparentCorners: false,
565
+ cornerColor: "#ffffff",
566
+ cornerStrokeColor: "#13717d",
567
+ borderColor: "#13717d",
568
+ cornerSize: 16
569
+ });
570
+ this.addAndSelect(text, options.name);
571
+ return text;
572
+ }
573
+ /**
574
+ * 加载、添加并选中一个图片对象
575
+ *
576
+ * role 为 background 时替换已有设计背景、铺满画布并默认锁定在最底层
577
+ * 图片位置使用画布像素坐标,原点位于图片中心
578
+ * 对象过大时会等比缩小,越界时会自动移回画布
579
+ * 远程图片必须提供正确的 CORS 响应头才能安全导出 PNG
580
+ *
581
+ * @param options 图片地址、中心位置和显示宽度
582
+ * @returns 创建的 FabricImage
583
+ * @throws 图片加载失败或被 CORS 策略阻止时抛出错误
584
+ */
585
+ async addImage(options) {
586
+ this.flushHistoryCommit();
587
+ const source = await resolvePersistentImageSource(options.src);
588
+ const image = await this.loadImage(source);
589
+ const role = options.role ?? "element";
590
+ const scale = (options.width ?? this.width * .22) / Math.max(image.width, 1);
591
+ 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,
594
+ originX: "center",
595
+ 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
603
+ });
604
+ if (role === "background") this.removeDesignBackgrounds();
605
+ this.imageSources.set(image, source);
606
+ this.addAndSelect(image, options.name, role === "background", role);
607
+ return image;
608
+ }
609
+ /**
610
+ * 返回与 Fabric.js 无关的当前设计快照
611
+ *
612
+ * 文档包含设计背景等设计对象和逻辑画布尺寸,不包含产品基础纹理或模型配置
613
+ *
614
+ * @returns 可以安全传给 JSON.stringify 的 Design JSON 文档
615
+ * @throws 画布包含不支持的对象或非字符串文字填充时抛出错误
616
+ */
617
+ saveDesign() {
618
+ return {
619
+ version: 1,
620
+ canvas: {
621
+ width: this.width,
622
+ height: this.height
623
+ },
624
+ objects: this.getObjects()
625
+ };
626
+ }
627
+ /**
628
+ * 校验并恢复 Design JSON,图片全部加载成功后才替换当前对象
629
+ *
630
+ * 背景纹理和当前产品保持不变,恢复后不选中任何对象
631
+ *
632
+ * @param value JSON.parse 结果或符合 DesignDocument 的对象
633
+ * @throws Schema 无效、画布尺寸不匹配或图片无法加载时抛出错误
634
+ */
635
+ async loadDesign(value) {
636
+ this.flushHistoryCommit();
637
+ await this.replaceDesign(value);
638
+ this.commitHistory();
639
+ }
640
+ async replaceDesign(value) {
641
+ const design = parseDesignDocument(value);
642
+ if (design.canvas.width !== this.width || design.canvas.height !== this.height) throw new RangeError(`Design canvas ${design.canvas.width}x${design.canvas.height} does not match editor canvas ${this.width}x${this.height}`);
643
+ const entries = [];
644
+ try {
645
+ for (const object of design.objects) entries.push({
646
+ id: object.id,
647
+ object: await this.createObjectFromDesign(object),
648
+ source: object.type === "image" ? object.src : void 0,
649
+ name: object.name,
650
+ locked: object.locked ?? false,
651
+ role: object.type === "image" ? object.role ?? "element" : "element"
652
+ });
653
+ } catch (error) {
654
+ entries.forEach(({ object }) => object.dispose());
655
+ throw error;
656
+ }
657
+ const previousObjects = this.canvas.getObjects();
658
+ this.canvas.discardActiveObject();
659
+ this.canvas.remove(...previousObjects);
660
+ previousObjects.forEach((object) => object.dispose());
661
+ this.usedObjectIds.clear();
662
+ this.objectsById.clear();
663
+ for (const entry of entries) {
664
+ this.registerObject(entry.object, entry.id, entry.name, entry.locked, entry.role);
665
+ if (entry.object instanceof FabricImage && entry.source) this.imageSources.set(entry.object, entry.source);
666
+ this.canvas.add(entry.object);
667
+ this.constrainObjectToCanvas(entry.object);
668
+ }
669
+ this.canvas.requestRenderAll();
670
+ this.notifySelectionChange();
671
+ }
672
+ /**
673
+ * 恢复上一个设计快照
674
+ *
675
+ * @returns 是否成功恢复了一个历史步骤
676
+ */
677
+ async undo() {
678
+ this.flushHistoryCommit();
679
+ const target = this.history.peekUndo();
680
+ if (!target || this.historyBusy) return false;
681
+ this.historyBusy = true;
682
+ try {
683
+ await this.replaceDesign(target);
684
+ this.history.confirmUndo();
685
+ this.historySignature = JSON.stringify(this.saveDesign());
686
+ this.notifyHistoryChange();
687
+ return true;
688
+ } finally {
689
+ this.historyBusy = false;
690
+ }
691
+ }
692
+ /**
693
+ * 恢复下一个设计快照
694
+ *
695
+ * @returns 是否成功恢复了一个历史步骤
696
+ */
697
+ async redo() {
698
+ this.flushHistoryCommit();
699
+ const target = this.history.peekRedo();
700
+ if (!target || this.historyBusy) return false;
701
+ this.historyBusy = true;
702
+ try {
703
+ await this.replaceDesign(target);
704
+ this.history.confirmRedo();
705
+ this.historySignature = JSON.stringify(this.saveDesign());
706
+ this.notifyHistoryChange();
707
+ return true;
708
+ } finally {
709
+ this.historyBusy = false;
710
+ }
711
+ }
712
+ /** 以当前设计为起点清空撤销与重做历史 */
713
+ clearHistory() {
714
+ this.flushHistoryCommit();
715
+ const current = this.saveDesign();
716
+ this.history.reset(current);
717
+ this.historySignature = JSON.stringify(current);
718
+ this.notifyHistoryChange();
719
+ }
720
+ /**
721
+ * 删除当前对象或多选选区
722
+ *
723
+ * @returns 是否删除了至少一个对象
724
+ */
725
+ deleteSelected() {
726
+ this.flushHistoryCommit();
727
+ const selection = this.canvas.getActiveObjects();
728
+ if (selection.length === 0) return false;
729
+ this.canvas.remove(...selection);
730
+ selection.forEach((object) => {
731
+ this.unregisterObject(object);
732
+ object.dispose();
733
+ });
734
+ this.canvas.discardActiveObject();
735
+ this.canvas.requestRenderAll();
736
+ this.notifySelectionChange();
737
+ this.commitHistory();
738
+ return true;
739
+ }
740
+ /**
741
+ * 将当前画布内容导出为 PNG 并触发浏览器下载
742
+ *
743
+ * @param filename 下载文件名
744
+ * @throws 画布被无 CORS 授权的远程图片污染时抛出安全错误
745
+ */
746
+ exportTexture(filename = "custom-texture.png") {
747
+ this.canvas.discardActiveObject();
748
+ this.canvas.renderAll();
749
+ const anchor = document.createElement("a");
750
+ anchor.download = filename;
751
+ anchor.href = this.canvas.toDataURL({
752
+ format: "png",
753
+ multiplier: 1
754
+ });
755
+ anchor.click();
756
+ }
757
+ /** 释放 ResizeObserver、事件监听和 Fabric Canvas */
758
+ destroy() {
759
+ if (this.historyTimer !== void 0) {
760
+ clearTimeout(this.historyTimer);
761
+ this.historyTimer = void 0;
762
+ }
763
+ this.resizeObserver.disconnect();
764
+ this.renderListeners.clear();
765
+ this.selectionListeners.clear();
766
+ this.historyListeners.clear();
767
+ this.objectsById.clear();
768
+ this.usedObjectIds.clear();
769
+ this.canvas.dispose();
770
+ this.host.replaceChildren();
771
+ }
772
+ addAndSelect(object, name, locked = false, role = "element") {
773
+ this.registerObject(object, void 0, name, locked, role);
774
+ this.canvas.add(object);
775
+ if (object instanceof FabricImage && role === "background") this.canvas.moveObjectTo(object, 0);
776
+ this.constrainObjectToCanvas(object);
777
+ this.canvas.setActiveObject(object);
778
+ this.canvas.requestRenderAll();
779
+ this.notifySelectionChange();
780
+ this.commitHistory();
781
+ }
782
+ registerObject(object, id = this.createObjectId(), name, locked = false, role = "element") {
783
+ if (this.usedObjectIds.has(id)) throw new Error(`Design object id is already in use: ${id}`);
784
+ this.usedObjectIds.add(id);
785
+ this.objectIds.set(object, id);
786
+ this.objectsById.set(id, object);
787
+ if (name) this.objectNames.set(object, name);
788
+ if (object instanceof FabricImage) this.imageRoles.set(object, role);
789
+ this.applyObjectLock(object, locked);
790
+ }
791
+ unregisterObject(object) {
792
+ const id = this.objectIds.get(object);
793
+ if (id) this.objectsById.delete(id);
794
+ }
795
+ createObjectId() {
796
+ let id;
797
+ do {
798
+ this.objectIdSequence += 1;
799
+ id = `object-${this.objectIdSequence}`;
800
+ } while (this.usedObjectIds.has(id));
801
+ return id;
802
+ }
803
+ serializeObject(object) {
804
+ const id = this.objectIds.get(object);
805
+ if (!id) throw new Error("Design object is missing its stable id");
806
+ const transform = this.serializeTransform(object);
807
+ const state = {
808
+ name: this.objectNames.get(object) ?? this.createObjectName(object),
809
+ visible: object.visible,
810
+ locked: this.objectLocks.get(object) ?? false
811
+ };
812
+ if (object instanceof Textbox) {
813
+ if (typeof object.fill !== "string") throw new Error(`Text object ${id} uses an unsupported non-string fill`);
814
+ return {
815
+ id,
816
+ type: "text",
817
+ ...state,
818
+ transform,
819
+ text: object.text,
820
+ width: object.width,
821
+ fontFamily: object.fontFamily,
822
+ fontSize: object.fontSize,
823
+ color: object.fill
824
+ };
825
+ }
826
+ if (object instanceof FabricImage) {
827
+ const src = this.imageSources.get(object) ?? object.getSrc();
828
+ if (!src || src.startsWith("blob:")) throw new Error(`Image object ${id} does not have a persistent source`);
829
+ return {
830
+ id,
831
+ type: "image",
832
+ ...state,
833
+ transform,
834
+ src,
835
+ role: this.imageRoles.get(object) ?? "element"
836
+ };
837
+ }
838
+ throw new Error(`Design object ${id} has an unsupported type`);
839
+ }
840
+ serializeTransform(object) {
841
+ const center = object.getCenterPoint();
842
+ return {
843
+ x: center.x,
844
+ y: center.y,
845
+ scaleX: Math.abs(object.scaleX),
846
+ scaleY: Math.abs(object.scaleY),
847
+ rotation: object.angle,
848
+ flipX: object.scaleX < 0 ? !object.flipX : object.flipX,
849
+ flipY: object.scaleY < 0 ? !object.flipY : object.flipY
850
+ };
851
+ }
852
+ async createObjectFromDesign(design) {
853
+ const common = {
854
+ left: design.transform.x,
855
+ top: design.transform.y,
856
+ originX: "center",
857
+ originY: "center",
858
+ scaleX: design.transform.scaleX,
859
+ scaleY: design.transform.scaleY,
860
+ angle: design.transform.rotation,
861
+ flipX: design.transform.flipX,
862
+ flipY: design.transform.flipY,
863
+ visible: design.visible ?? true,
864
+ transparentCorners: false,
865
+ cornerColor: "#ffffff",
866
+ cornerStrokeColor: "#13717d",
867
+ borderColor: "#13717d",
868
+ cornerSize: 16
869
+ };
870
+ if (design.type === "text") return new Textbox(design.text, {
871
+ ...common,
872
+ width: design.width,
873
+ fontFamily: design.fontFamily,
874
+ fontSize: design.fontSize,
875
+ fontWeight: 700,
876
+ fill: design.color,
877
+ textAlign: "center",
878
+ editable: true
879
+ });
880
+ const image = await this.loadImage(design.src);
881
+ image.set(common);
882
+ return image;
883
+ }
884
+ loadImage(source) {
885
+ return FabricImage.fromURL(source, source.startsWith("data:") ? void 0 : { crossOrigin: "anonymous" });
886
+ }
887
+ createObjectName(object) {
888
+ if (object instanceof Textbox) return object.text.trim().slice(0, 48) || "Text";
889
+ return object instanceof FabricImage ? "Image" : "Object";
890
+ }
891
+ applyObjectLock(object, locked) {
892
+ this.objectLocks.set(object, locked);
893
+ object.set({
894
+ hasBorders: !locked,
895
+ hasControls: !locked,
896
+ lockMovementX: locked,
897
+ lockMovementY: locked,
898
+ lockRotation: locked,
899
+ lockScalingX: locked,
900
+ lockScalingY: locked,
901
+ lockSkewingX: locked,
902
+ lockSkewingY: locked
903
+ });
904
+ if (object instanceof Textbox) object.set({ editable: !locked });
905
+ }
906
+ notifySelectionChange() {
907
+ const objectIds = this.getSelectedObjectIds();
908
+ this.selectionListeners.forEach((listener) => listener(objectIds));
909
+ }
910
+ removeDesignBackgrounds() {
911
+ const backgrounds = this.canvas.getObjects().filter((object) => object instanceof FabricImage && this.imageRoles.get(object) === "background");
912
+ if (backgrounds.length === 0) return;
913
+ if (backgrounds.some((object) => this.canvas.getActiveObjects().includes(object))) this.canvas.discardActiveObject();
914
+ this.canvas.remove(...backgrounds);
915
+ backgrounds.forEach((object) => {
916
+ this.unregisterObject(object);
917
+ object.dispose();
918
+ });
919
+ }
920
+ scheduleHistoryCommit() {
921
+ if (this.historyBusy) return;
922
+ if (this.historyTimer !== void 0) clearTimeout(this.historyTimer);
923
+ this.historyTimer = setTimeout(() => {
924
+ this.historyTimer = void 0;
925
+ this.commitHistory();
926
+ }, 320);
927
+ }
928
+ flushHistoryCommit() {
929
+ if (this.historyTimer === void 0) return;
930
+ clearTimeout(this.historyTimer);
931
+ this.historyTimer = void 0;
932
+ this.commitHistory();
933
+ }
934
+ commitHistory() {
935
+ if (this.historyBusy) return;
936
+ if (this.historyTimer !== void 0) {
937
+ clearTimeout(this.historyTimer);
938
+ this.historyTimer = void 0;
939
+ }
940
+ const snapshot = this.saveDesign();
941
+ const signature = JSON.stringify(snapshot);
942
+ if (signature === this.historySignature) return;
943
+ this.history.push(snapshot);
944
+ this.historySignature = signature;
945
+ this.notifyHistoryChange();
946
+ }
947
+ notifyHistoryChange() {
948
+ const state = this.history.state;
949
+ this.historyListeners.forEach((listener) => listener(state));
950
+ }
951
+ constrainObjectToCanvas(object) {
952
+ object.setCoords();
953
+ let bounds = object.getBoundingRect();
954
+ const scale = calculateContainmentScale(bounds, this.width, this.height);
955
+ if (scale < 1) {
956
+ object.set({
957
+ scaleX: object.scaleX * scale,
958
+ scaleY: object.scaleY * scale
959
+ });
960
+ object.setCoords();
961
+ bounds = object.getBoundingRect();
962
+ }
963
+ const offset = calculateContainmentOffset(bounds, this.width, this.height);
964
+ if (offset.x !== 0 || offset.y !== 0) {
965
+ object.set({
966
+ left: object.left + offset.x,
967
+ top: object.top + offset.y
968
+ });
969
+ object.setCoords();
970
+ }
971
+ }
972
+ resizeDisplay() {
973
+ const availableWidth = Math.max(this.host.clientWidth - 32, 1);
974
+ const availableHeight = Math.max(this.host.clientHeight - 32, 1);
975
+ const scale = Math.min(availableWidth / this.width, availableHeight / this.height, 1);
976
+ this.canvas.setDimensions({
977
+ width: `${Math.floor(this.width * scale)}px`,
978
+ height: `${Math.floor(this.height * scale)}px`
979
+ }, { cssOnly: true });
980
+ }
981
+ markRenderState() {
982
+ if (this.host.dataset.renderState === "nonblank") return;
983
+ const context = this.canvas.getContext();
984
+ let minimum = 255;
985
+ let maximum = 0;
986
+ let opaqueSamples = 0;
987
+ for (let row = 1; row < 8; row += 1) for (let column = 1; column < 16; column += 1) {
988
+ const x = Math.floor(column / 16 * this.width);
989
+ const y = Math.floor(row / 8 * this.height);
990
+ const pixel = context.getImageData(x, y, 1, 1).data;
991
+ const luminance = (pixel[0] + pixel[1] + pixel[2]) / 3;
992
+ minimum = Math.min(minimum, luminance);
993
+ maximum = Math.max(maximum, luminance);
994
+ if (pixel[3] > 0) opaqueSamples += 1;
995
+ }
996
+ if (opaqueSamples > 0 && maximum - minimum > 8) this.host.dataset.renderState = "nonblank";
997
+ }
998
+ };
999
+ //#endregion
1000
+ //#region src/bridge/TextureBridge.ts
1001
+ /**
1002
+ * 将二维编辑画布转换为 Three.js 实时纹理
1003
+ *
1004
+ * 多次画布渲染会合并到下一个动画帧,避免重复标记纹理更新
1005
+ */
1006
+ var TextureBridge = class {
1007
+ /** 绑定到三维产品材质的实时 CanvasTexture */
1008
+ texture;
1009
+ stopListening;
1010
+ updateFrame = 0;
1011
+ /**
1012
+ * @param editor 提供底层 HTML Canvas 和渲染事件的二维编辑器
1013
+ * @param viewer 接收实时纹理的三维查看器
1014
+ * @param flipY 是否垂直翻转纹理
1015
+ */
1016
+ constructor(editor, viewer, flipY) {
1017
+ this.texture = new CanvasTexture(editor.textureCanvas);
1018
+ this.texture.colorSpace = SRGBColorSpace;
1019
+ this.texture.flipY = flipY;
1020
+ this.texture.anisotropy = 4;
1021
+ viewer.setTexture(this.texture);
1022
+ this.stopListening = editor.onRender(() => this.scheduleUpdate());
1023
+ this.scheduleUpdate();
1024
+ }
1025
+ /**
1026
+ * 更新纹理垂直翻转状态并立即标记刷新
1027
+ *
1028
+ * @param flipY 是否垂直翻转纹理
1029
+ */
1030
+ setFlipY(flipY) {
1031
+ this.texture.flipY = flipY;
1032
+ this.texture.needsUpdate = true;
1033
+ }
1034
+ /** 取消编辑器订阅、动画帧并释放 CanvasTexture */
1035
+ destroy() {
1036
+ this.stopListening();
1037
+ cancelAnimationFrame(this.updateFrame);
1038
+ this.texture.dispose();
1039
+ }
1040
+ /** 将同一帧内的多次画布渲染合并为一次纹理更新 */
1041
+ scheduleUpdate() {
1042
+ if (this.updateFrame) return;
1043
+ this.updateFrame = requestAnimationFrame(() => {
1044
+ this.updateFrame = 0;
1045
+ this.texture.needsUpdate = true;
1046
+ });
1047
+ }
1048
+ };
1049
+ //#endregion
1050
+ //#region src/viewer/ProductViewer.ts
1051
+ /**
1052
+ * 基于 Three.js 的三维产品查看器
1053
+ *
1054
+ * 负责模型加载、目标 Mesh 查找、实时纹理绑定、相机控制和资源释放
1055
+ * 当前只将纹理应用到目标 Mesh 的第一个材质槽
1056
+ */
1057
+ var ProductViewer = class {
1058
+ host;
1059
+ scene = new Scene();
1060
+ camera = new PerspectiveCamera(35, 1, .05, 100);
1061
+ renderer;
1062
+ controls;
1063
+ loader = new GLTFLoader();
1064
+ resizeObserver;
1065
+ productRoot;
1066
+ surface;
1067
+ texture;
1068
+ animationFrame = 0;
1069
+ /**
1070
+ * @param host 三维查看器挂载容器
1071
+ */
1072
+ constructor(host) {
1073
+ this.host = host;
1074
+ host.replaceChildren();
1075
+ this.renderer = new WebGLRenderer({
1076
+ antialias: true,
1077
+ alpha: true
1078
+ });
1079
+ this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
1080
+ this.renderer.outputColorSpace = SRGBColorSpace;
1081
+ this.renderer.toneMapping = ACESFilmicToneMapping;
1082
+ this.renderer.toneMappingExposure = 1.05;
1083
+ this.renderer.shadowMap.enabled = true;
1084
+ this.renderer.domElement.setAttribute("aria-label", "Interactive 3D product preview");
1085
+ this.renderer.domElement.classList.add("customforge-viewer-canvas");
1086
+ host.append(this.renderer.domElement);
1087
+ host.dataset.renderState = "pending";
1088
+ this.scene.background = new Color("#eef0ef");
1089
+ this.camera.position.set(4.6, 2.8, 5.8);
1090
+ this.controls = new OrbitControls(this.camera, this.renderer.domElement);
1091
+ this.controls.enableDamping = true;
1092
+ this.controls.minDistance = 3.2;
1093
+ this.controls.maxDistance = 11;
1094
+ this.controls.target.set(0, 0, 0);
1095
+ this.addEnvironment();
1096
+ this.resizeObserver = new ResizeObserver(() => this.resize());
1097
+ this.resizeObserver.observe(host);
1098
+ this.resize();
1099
+ this.render();
1100
+ }
1101
+ /**
1102
+ * 加载远程模型或创建内置演示模型
1103
+ *
1104
+ * @param product 已完成默认值补全的产品配置
1105
+ * @throws 模型加载失败或找不到目标 Mesh 时抛出错误
1106
+ */
1107
+ async loadProduct(product) {
1108
+ this.removeProduct();
1109
+ if (product.modelUrl) {
1110
+ const gltf = await this.loader.loadAsync(product.modelUrl);
1111
+ this.productRoot = gltf.scene;
1112
+ this.surface = this.findSurface(gltf.scene, product.surfaceMesh);
1113
+ } else {
1114
+ const demo = this.createDemoProduct();
1115
+ this.productRoot = demo.root;
1116
+ this.surface = demo.surface;
1117
+ }
1118
+ this.scene.add(this.productRoot);
1119
+ if (this.texture) this.attachTexture(this.texture);
1120
+ this.fitCamera(this.productRoot);
1121
+ }
1122
+ /**
1123
+ * 保存并绑定二维编辑器生成的实时纹理
1124
+ *
1125
+ * 如果模型尚未加载,纹理会在模型加载完成后自动绑定
1126
+ *
1127
+ * @param texture 由二维画布创建的 CanvasTexture
1128
+ */
1129
+ setTexture(texture) {
1130
+ this.texture = texture;
1131
+ if (this.surface) this.attachTexture(texture);
1132
+ }
1133
+ /** 根据当前模型包围盒恢复默认相机位置 */
1134
+ resetView() {
1135
+ if (this.productRoot) this.fitCamera(this.productRoot);
1136
+ }
1137
+ /** 释放动画帧、相机控制、模型材质和 WebGLRenderer */
1138
+ destroy() {
1139
+ cancelAnimationFrame(this.animationFrame);
1140
+ this.resizeObserver.disconnect();
1141
+ this.controls.dispose();
1142
+ this.removeProduct();
1143
+ this.renderer.dispose();
1144
+ this.renderer.domElement.remove();
1145
+ }
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;
1152
+ this.scene.add(key);
1153
+ const fill = new DirectionalLight("#b7dce0", 1.2);
1154
+ fill.position.set(-5, 2, 3);
1155
+ 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
1181
+ });
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
+ };
1202
+ }
1203
+ /**
1204
+ * 按名称查找接收实时纹理的 Mesh
1205
+ *
1206
+ * @throws 找不到对象或同名对象不是 Mesh 时抛出错误
1207
+ */
1208
+ findSurface(root, meshName) {
1209
+ const object = root.getObjectByName(meshName);
1210
+ if (!(object instanceof Mesh)) throw new Error(`Customizable mesh was not found: ${meshName}`);
1211
+ return object;
1212
+ }
1213
+ /**
1214
+ * 将纹理应用到目标 Mesh 的第一个材质槽
1215
+ *
1216
+ * 非 MeshStandardMaterial 会被替换为基础标准材质
1217
+ */
1218
+ attachTexture(texture) {
1219
+ if (!this.surface) return;
1220
+ const material = (Array.isArray(this.surface.material) ? this.surface.material : [this.surface.material])[0];
1221
+ if (!(material instanceof MeshStandardMaterial)) {
1222
+ const replacement = new MeshStandardMaterial({
1223
+ color: "#ffffff",
1224
+ roughness: .45,
1225
+ map: texture
1226
+ });
1227
+ this.surface.material = replacement;
1228
+ return;
1229
+ }
1230
+ material.map = texture;
1231
+ material.color.set("#ffffff");
1232
+ material.needsUpdate = true;
1233
+ }
1234
+ fitCamera(root) {
1235
+ const bounds = new Box3().setFromObject(root);
1236
+ const size = bounds.getSize(new Vector3());
1237
+ 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);
1240
+ 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;
1244
+ this.camera.updateProjectionMatrix();
1245
+ this.controls.update();
1246
+ }
1247
+ removeProduct() {
1248
+ if (!this.productRoot) return;
1249
+ this.scene.remove(this.productRoot);
1250
+ this.productRoot.traverse((object) => {
1251
+ if (!(object instanceof Mesh)) return;
1252
+ object.geometry.dispose();
1253
+ (Array.isArray(object.material) ? object.material : [object.material]).forEach((material) => material.dispose());
1254
+ });
1255
+ this.productRoot = void 0;
1256
+ this.surface = void 0;
1257
+ }
1258
+ resize() {
1259
+ const width = Math.max(this.host.clientWidth, 1);
1260
+ const height = Math.max(this.host.clientHeight, 1);
1261
+ this.renderer.setSize(width, height, false);
1262
+ this.camera.aspect = width / height;
1263
+ this.camera.updateProjectionMatrix();
1264
+ }
1265
+ render = () => {
1266
+ this.animationFrame = requestAnimationFrame(this.render);
1267
+ this.controls.update();
1268
+ this.renderer.render(this.scene, this.camera);
1269
+ this.markRenderState();
1270
+ };
1271
+ markRenderState() {
1272
+ if (this.host.dataset.renderState === "nonblank") return;
1273
+ const context = this.renderer.getContext();
1274
+ const width = context.drawingBufferWidth;
1275
+ const height = context.drawingBufferHeight;
1276
+ if (width < 2 || height < 2) return;
1277
+ const pixel = /* @__PURE__ */ new Uint8Array(4);
1278
+ let minimum = 255;
1279
+ let maximum = 0;
1280
+ for (const xRatio of [
1281
+ .25,
1282
+ .5,
1283
+ .75
1284
+ ]) for (const yRatio of [
1285
+ .25,
1286
+ .5,
1287
+ .75
1288
+ ]) {
1289
+ context.readPixels(Math.floor(width * xRatio), Math.floor(height * yRatio), 1, 1, context.RGBA, context.UNSIGNED_BYTE, pixel);
1290
+ const luminance = (pixel[0] + pixel[1] + pixel[2]) / 3;
1291
+ minimum = Math.min(minimum, luminance);
1292
+ maximum = Math.max(maximum, luminance);
1293
+ }
1294
+ if (maximum - minimum > 8) this.host.dataset.renderState = "nonblank";
1295
+ }
1296
+ };
1297
+ //#endregion
1298
+ //#region src/customizer/ProductCustomizer.ts
1299
+ /**
1300
+ * 统一管理二维编辑器、三维查看器和实时纹理同步
1301
+ *
1302
+ * 仅支持具有 DOM、Canvas、WebGL 和 ResizeObserver 的浏览器环境
1303
+ * 每个实例独立持有 DOM 事件、Fabric 状态和 WebGL 资源
1304
+ * 不再使用实例时必须调用 `destroy()`
1305
+ */
1306
+ var ProductCustomizer = class ProductCustomizer {
1307
+ events = new EventTarget();
1308
+ textureBridge;
1309
+ editor;
1310
+ viewer;
1311
+ product;
1312
+ stopSelectionListener;
1313
+ stopRenderListener;
1314
+ stopHistoryListener;
1315
+ destroyed = false;
1316
+ constructor(options) {
1317
+ const editorHost = resolveElement(options.editor, "Editor");
1318
+ const viewerHost = resolveElement(options.viewer, "Viewer");
1319
+ if (editorHost === viewerHost) throw new Error("Editor and viewer must use different elements");
1320
+ const historyLimit = options.historyLimit ?? 50;
1321
+ if (!Number.isInteger(historyLimit) || historyLimit < 1) throw new RangeError("historyLimit must be a positive integer");
1322
+ this.product = normalizeProductConfiguration(options.product);
1323
+ this.editor = new DesignEditor(editorHost, {
1324
+ width: options.editorWidth ?? 1024,
1325
+ height: options.editorHeight ?? 512,
1326
+ historyLimit
1327
+ });
1328
+ this.viewer = new ProductViewer(viewerHost);
1329
+ this.textureBridge = new TextureBridge(this.editor, this.viewer, this.product.textureFlipY);
1330
+ this.stopSelectionListener = this.editor.onSelectionChange((objectIds) => {
1331
+ this.emit("selectionchange", {
1332
+ hasSelection: objectIds.length > 0,
1333
+ objectIds
1334
+ });
1335
+ });
1336
+ this.stopRenderListener = this.editor.onRender(() => {
1337
+ this.emit("change", { objectCount: this.editor.objectCount });
1338
+ });
1339
+ this.stopHistoryListener = this.editor.onHistoryChange((state) => {
1340
+ this.emit("historychange", state);
1341
+ });
1342
+ }
1343
+ /**
1344
+ * 创建实例并完成初始产品加载
1345
+ *
1346
+ * @param options 产品定制器初始化配置
1347
+ * @returns 初始化完成的产品定制器实例
1348
+ * @throws DOM 容器无效或初始化失败时释放已创建资源并继续抛出原始错误
1349
+ */
1350
+ static async create(options) {
1351
+ const customizer = new ProductCustomizer(options);
1352
+ try {
1353
+ await customizer.initialize();
1354
+ return customizer;
1355
+ } catch (error) {
1356
+ customizer.destroy();
1357
+ throw error;
1358
+ }
1359
+ }
1360
+ /**
1361
+ * 订阅产品定制器事件
1362
+ *
1363
+ * @param event 事件名称
1364
+ * @param listener 接收对应事件载荷的监听函数
1365
+ * @returns 用于取消本次订阅的函数
1366
+ */
1367
+ on(event, listener) {
1368
+ const wrapped = (browserEvent) => {
1369
+ listener(browserEvent.detail);
1370
+ };
1371
+ this.events.addEventListener(event, wrapped);
1372
+ return () => this.events.removeEventListener(event, wrapped);
1373
+ }
1374
+ /**
1375
+ * 在二维画布中添加并选中一个文字对象
1376
+ *
1377
+ * 创建后和用户变换期间,对象会自动缩放或平移以保持完整可见
1378
+ *
1379
+ * @param options 文字内容、位置和样式配置
1380
+ */
1381
+ addText(options) {
1382
+ this.editor.addText(options);
1383
+ }
1384
+ /**
1385
+ * 加载图片并将其添加到二维画布
1386
+ *
1387
+ * role 为 background 时会替换已有设计背景并默认锁定在最底层
1388
+ * 创建后和用户变换期间,对象会自动缩放或平移以保持完整可见
1389
+ *
1390
+ * @param options 图片地址、位置和显示宽度
1391
+ * @throws 图片无法访问、加载失败或被 CORS 策略阻止时抛出错误
1392
+ */
1393
+ async addImage(options) {
1394
+ try {
1395
+ await this.editor.addImage(options);
1396
+ } catch (error) {
1397
+ this.reportError(error);
1398
+ throw error;
1399
+ }
1400
+ }
1401
+ /**
1402
+ * 返回当前可编辑对象的独立快照
1403
+ *
1404
+ * @returns 按画布层级从后到前排列的 Design JSON 对象
1405
+ */
1406
+ getObjects() {
1407
+ return this.editor.getObjects();
1408
+ }
1409
+ /** 当前选中对象的 ID,按画布层级从后到前排列 */
1410
+ getSelectedObjectIds() {
1411
+ return this.editor.getSelectedObjectIds();
1412
+ }
1413
+ /**
1414
+ * 按稳定 ID 选中一个可见对象
1415
+ *
1416
+ * @param id Design JSON 中的对象 ID
1417
+ * @returns 是否找到并选中了对象
1418
+ */
1419
+ selectObject(id) {
1420
+ return this.editor.selectObject(id);
1421
+ }
1422
+ /**
1423
+ * 按稳定 ID 删除一个对象
1424
+ *
1425
+ * @param id Design JSON 中的对象 ID
1426
+ * @returns 是否找到并删除了对象
1427
+ */
1428
+ removeObject(id) {
1429
+ return this.editor.removeObject(id);
1430
+ }
1431
+ /**
1432
+ * 将对象移动到指定图层索引
1433
+ *
1434
+ * @param id Design JSON 中的对象 ID
1435
+ * @param index 从 0 开始的索引,0 表示最底层
1436
+ * @returns 对象层级是否发生变化
1437
+ */
1438
+ moveObject(id, index) {
1439
+ return this.editor.moveObject(id, index);
1440
+ }
1441
+ /**
1442
+ * 修改对象在图层面板中的名称
1443
+ *
1444
+ * @param id Design JSON 中的对象 ID
1445
+ * @param name 非空图层名称
1446
+ * @returns 是否找到并更新了对象
1447
+ */
1448
+ renameObject(id, name) {
1449
+ return this.editor.renameObject(id, name);
1450
+ }
1451
+ /**
1452
+ * 修改对象是否参与渲染
1453
+ *
1454
+ * @param id Design JSON 中的对象 ID
1455
+ * @param visible 是否参与二维画布、三维纹理和 PNG 渲染
1456
+ * @returns 是否找到并更新了对象
1457
+ */
1458
+ setObjectVisibility(id, visible) {
1459
+ return this.editor.setObjectVisibility(id, visible);
1460
+ }
1461
+ /**
1462
+ * 修改对象是否允许通过画布控件变换
1463
+ *
1464
+ * @param id Design JSON 中的对象 ID
1465
+ * @param locked 是否锁定移动、缩放、旋转、倾斜和文字编辑
1466
+ * @returns 是否找到并更新了对象
1467
+ */
1468
+ setObjectLocked(id, locked) {
1469
+ return this.editor.setObjectLocked(id, locked);
1470
+ }
1471
+ /**
1472
+ * 删除二维编辑器中的当前对象或选区
1473
+ *
1474
+ * @returns 是否删除了至少一个对象
1475
+ */
1476
+ deleteSelected() {
1477
+ return this.editor.deleteSelected();
1478
+ }
1479
+ /**
1480
+ * 创建当前二维设计的版本化 JSON 快照
1481
+ *
1482
+ * 快照不包含产品模型、目标 Mesh 或基础纹理配置
1483
+ * Blob URL 图片会在添加时转换为 Data URL,因此返回值可以跨页面会话保存
1484
+ *
1485
+ * @returns 可以安全传给 JSON.stringify 的 DesignDocument
1486
+ * @throws 设计中存在不支持的对象或文字填充时抛出错误
1487
+ */
1488
+ saveDesign() {
1489
+ return this.editor.saveDesign();
1490
+ }
1491
+ /**
1492
+ * 校验并恢复版本化 Design JSON
1493
+ *
1494
+ * 图片全部加载成功后才替换当前二维对象,产品和基础纹理保持不变
1495
+ * 输入画布尺寸必须与当前编辑器的逻辑尺寸完全一致
1496
+ *
1497
+ * @param value JSON.parse 结果或符合 DesignDocument 的对象
1498
+ * @throws Schema 无效、画布尺寸不匹配或图片加载失败时抛出错误
1499
+ */
1500
+ async loadDesign(value) {
1501
+ this.emit("status", { message: "Loading design" });
1502
+ try {
1503
+ await this.editor.loadDesign(value);
1504
+ this.emit("status", { message: "Design loaded" });
1505
+ } catch (error) {
1506
+ this.reportError(error);
1507
+ throw error;
1508
+ }
1509
+ }
1510
+ /** 当前是否存在可以撤销的设计快照 */
1511
+ canUndo() {
1512
+ return this.editor.canUndo;
1513
+ }
1514
+ /** 当前是否存在可以重做的设计快照 */
1515
+ canRedo() {
1516
+ return this.editor.canRedo;
1517
+ }
1518
+ /**
1519
+ * 恢复上一个设计快照
1520
+ *
1521
+ * @returns 是否成功恢复了一个历史步骤
1522
+ * @throws 历史中的图片无法恢复时抛出错误
1523
+ */
1524
+ async undo() {
1525
+ try {
1526
+ const changed = await this.editor.undo();
1527
+ if (changed) this.emit("status", { message: "Undo complete" });
1528
+ return changed;
1529
+ } catch (error) {
1530
+ this.reportError(error);
1531
+ throw error;
1532
+ }
1533
+ }
1534
+ /**
1535
+ * 恢复下一个设计快照
1536
+ *
1537
+ * @returns 是否成功恢复了一个历史步骤
1538
+ * @throws 历史中的图片无法恢复时抛出错误
1539
+ */
1540
+ async redo() {
1541
+ try {
1542
+ const changed = await this.editor.redo();
1543
+ if (changed) this.emit("status", { message: "Redo complete" });
1544
+ return changed;
1545
+ } catch (error) {
1546
+ this.reportError(error);
1547
+ throw error;
1548
+ }
1549
+ }
1550
+ /** 以当前设计为起点清空撤销与重做历史 */
1551
+ clearHistory() {
1552
+ this.editor.clearHistory();
1553
+ }
1554
+ /**
1555
+ * 将当前二维设计合成为 PNG 并触发浏览器下载
1556
+ *
1557
+ * @param filename 下载文件名,默认为 `custom-texture.png`
1558
+ * @throws 远程图片污染 Canvas 时可能抛出安全错误
1559
+ */
1560
+ exportTexture(filename) {
1561
+ this.editor.exportTexture(filename);
1562
+ }
1563
+ /** 恢复三维产品的默认相机位置 */
1564
+ resetView() {
1565
+ this.viewer.resetView();
1566
+ }
1567
+ /**
1568
+ * 更换模型、基础纹理和接收纹理的目标 Mesh
1569
+ *
1570
+ * 成功后保留当前设计对象,并将当前设计设为新的历史起点
1571
+ *
1572
+ * @param product 新的产品配置
1573
+ * @throws 模型或纹理加载失败、目标 Mesh 不存在时抛出错误
1574
+ */
1575
+ async loadProduct(product) {
1576
+ const nextProduct = normalizeProductConfiguration(product);
1577
+ this.emit("status", { message: "Loading product" });
1578
+ try {
1579
+ await this.viewer.loadProduct(nextProduct);
1580
+ await this.editor.setBackgroundTexture(nextProduct.textureUrl);
1581
+ this.textureBridge.setFlipY(nextProduct.textureFlipY);
1582
+ this.product = nextProduct;
1583
+ this.editor.clearHistory();
1584
+ this.emit("ready", { product: this.product });
1585
+ this.emit("status", { message: nextProduct.modelUrl ? "Remote product ready" : "Demo product ready" });
1586
+ } catch (error) {
1587
+ this.reportError(error);
1588
+ throw error;
1589
+ }
1590
+ }
1591
+ /**
1592
+ * 释放事件监听、Fabric Canvas、纹理和 WebGL 资源
1593
+ *
1594
+ * 重复调用不会再次释放资源,首次调用后不得继续使用其他实例方法
1595
+ */
1596
+ destroy() {
1597
+ if (this.destroyed) return;
1598
+ this.destroyed = true;
1599
+ this.stopSelectionListener?.();
1600
+ this.stopRenderListener?.();
1601
+ this.stopHistoryListener?.();
1602
+ this.textureBridge.destroy();
1603
+ this.editor.destroy();
1604
+ this.viewer.destroy();
1605
+ }
1606
+ async initialize() {
1607
+ await this.viewer.loadProduct(this.product);
1608
+ await this.editor.setBackgroundTexture(this.product.textureUrl);
1609
+ this.textureBridge.setFlipY(this.product.textureFlipY);
1610
+ this.emit("ready", { product: this.product });
1611
+ }
1612
+ emit(event, detail) {
1613
+ this.events.dispatchEvent(new CustomEvent(event, { detail }));
1614
+ }
1615
+ reportError(error) {
1616
+ const normalized = error instanceof Error ? error : new Error(String(error));
1617
+ this.emit("error", { error: normalized });
1618
+ this.emit("status", { message: normalized.message });
1619
+ }
1620
+ };
1621
+ //#endregion
1622
+ export { resolveElement as n, ProductCustomizer as t };
1623
+
1624
+ //# sourceMappingURL=ProductCustomizer-rMRyWe7L.js.map