LCOV - code coverage report
Current view: top level - src/extensions/core/load3d/composables - useLoad3d.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 70.0 % 576 403
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : import type { MaybeRef, Ref } from 'vue'
       2              : 
       3              : import { toRef, useDebounceFn } from '@vueuse/core'
       4              : import { isEqual } from 'es-toolkit'
       5              : import { getActivePinia } from 'pinia'
       6              : import { ref, toRaw, watch } from 'vue'
       7              : 
       8              : import { reportError } from '@comfyorg/telemetry/reportError'
       9              : 
      10              : import { useChainCallback } from '@/composables/functional/useChainCallback'
      11              : import type Load3d from '@comfyorg/viewport3d/load3d/Load3d'
      12              : import Load3dUtils from '@/extensions/core/load3d/Load3dUtils'
      13              : import type { ModelStats } from '@comfyorg/viewport3d/load3d/modelStats'
      14              : import { createLoad3d } from '@comfyorg/viewport3d/load3d/createLoad3d'
      15              : import { load3dHost } from '@/extensions/core/load3d/load3dHost'
      16              : import { isLoad3dResultViewerNode } from '@/extensions/core/load3d/nodeTypes'
      17              : import { recordModelChange } from '@/extensions/core/load3d/recordModelChange'
      18              : import { reportLoadModelOutcome } from '@/extensions/core/load3d/reportLoadModelOutcome'
      19              : import {
      20              :   isAssetPreviewSupported,
      21              :   persistThumbnail
      22              : } from '@/platform/assets/utils/assetPreviewUtil'
      23              : import type {
      24              :   AnimationItem,
      25              :   CameraConfig,
      26              :   CameraState,
      27              :   CameraType,
      28              :   EventCallback,
      29              :   GizmoConfig,
      30              :   GizmoMode,
      31              :   LightConfig,
      32              :   MaterialMode,
      33              :   Model3DInfo,
      34              :   ModelConfig,
      35              :   StoredModelConfig,
      36              :   SceneConfig,
      37              :   UpDirection
      38              : } from '@comfyorg/viewport3d/load3d/interfaces'
      39              : import { t } from '@/i18n'
      40              : import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode'
      41              : import { LiteGraph } from '@/lib/litegraph/src/litegraph'
      42              : import { useSettingStore } from '@/platform/settings/settingStore'
      43              : import { useToast } from '@/components/ui/toast/toastStore'
      44              : import { useCanvasStore } from '@/renderer/core/canvas/canvasStore'
      45              : import { api } from '@/scripts/api'
      46              : import { app } from '@/scripts/app'
      47              : import { keepingLoadedModel } from '@/extensions/core/load3d/load3dInstances'
      48              : 
      49              : type Load3dReadyCallback = (load3d: Load3d) => void
      50           24 : export const nodeToLoad3dMap = new Map<LGraphNode, Load3d>()
      51              : 
      52              : export type Load3dCachedOutput = {
      53              :   image: string
      54              :   mask: string
      55              :   normal: string
      56              :   camera_info: CameraState | null
      57              :   recording: string
      58              :   model_3d_info: Model3DInfo
      59              : }
      60              : 
      61           24 : const load3dSceneDirty = new WeakMap<LGraphNode, boolean>()
      62           24 : const load3dSceneRevisions = new WeakMap<LGraphNode, number>()
      63           24 : const load3dOutputCache = new WeakMap<LGraphNode, Load3dCachedOutput>()
      64              : 
      65           24 : export const markLoad3dSceneDirty = (node: LGraphNode | null): void => {
      66          110 :   if (!node) return
      67          110 :   load3dSceneRevisions.set(node, (load3dSceneRevisions.get(node) ?? 0) + 1)
      68          110 :   load3dSceneDirty.set(node, true)
      69              : }
      70              : 
      71           24 : export const getLoad3dSceneRevision = (node: LGraphNode): number =>
      72              :   load3dSceneRevisions.get(node) ?? 0
      73              : 
      74           24 : export const isLoad3dSceneDirty = (node: LGraphNode): boolean =>
      75              :   load3dSceneDirty.get(node) !== false
      76              : 
      77           24 : export const getLoad3dOutputCache = (
      78              :   node: LGraphNode
      79              : ): Load3dCachedOutput | undefined => load3dOutputCache.get(node)
      80              : 
      81           24 : export const setLoad3dOutputCache = (
      82              :   node: LGraphNode,
      83              :   output: Load3dCachedOutput,
      84              :   sceneRevision: number = getLoad3dSceneRevision(node)
      85              : ): boolean => {
      86            3 :   if (getLoad3dSceneRevision(node) !== sceneRevision) return false
      87            3 :   load3dOutputCache.set(node, output)
      88            3 :   load3dSceneDirty.set(node, false)
      89            3 :   return true
      90              : }
      91           24 : const pendingCallbacks = new Map<LGraphNode, Load3dReadyCallback[]>()
      92           24 : const persistentReadyCallbacks = new Map<LGraphNode, Load3dReadyCallback[]>()
      93              : 
      94           24 : const nodesWithCleanup = new WeakSet<LGraphNode>()
      95           24 : const rootGraphOfRemovedNodes = new WeakMap<LGraphNode, string>()
      96              : 
      97           24 : const rootGraphIdOf = (node: LGraphNode) => node.graph?.rootGraph.id
      98              : 
      99           24 : const ensureNodeCleanupChained = (node: LGraphNode): void => {
     100           77 :   if (nodesWithCleanup.has(node)) return
     101           26 :   nodesWithCleanup.add(node)
     102           26 :   node.onRemoved = useChainCallback(node.onRemoved, () => {
     103            0 :     const rootGraphId = rootGraphIdOf(node)
     104            0 :     if (rootGraphId) rootGraphOfRemovedNodes.set(node, rootGraphId)
     105            0 :     pendingCallbacks.delete(node)
     106            0 :     persistentReadyCallbacks.delete(node)
     107              :   })
     108              : }
     109              : 
     110           24 : const isReloadedCopy = (node: LGraphNode, previous: LGraphNode) =>
     111              :   node.type === previous.type &&
     112              :   rootGraphIdOf(node) !== undefined &&
     113              :   rootGraphOfRemovedNodes.get(previous) === rootGraphIdOf(node)
     114              : 
     115           24 : const reattachedNodes = new WeakSet<LGraphNode>()
     116              : 
     117           24 : const hasGizmoTransform = ({ position, rotation, scale }: GizmoConfig) =>
     118              :   [position.x, position.y, position.z, rotation.x, rotation.y, rotation.z].some(
     119              :     (value) => value !== 0
     120              :   ) || [scale.x, scale.y, scale.z].some((value) => value !== 1)
     121              : 
     122           24 : const invokePersistentReadyCallback = (
     123              :   node: LGraphNode,
     124              :   callback: Load3dReadyCallback,
     125              :   instance: Load3d
     126              : ): void => {
     127           25 :   if (reattachedNodes.has(node))
     128            0 :     keepingLoadedModel(instance, () => invokeReadyCallback(callback, instance))
     129           25 :   else invokeReadyCallback(callback, instance)
     130              : }
     131              : 
     132           24 : const nodeShowing = (instance: Load3d): LGraphNode | null => {
     133          946 :   for (const [node, shown] of nodeToLoad3dMap) {
     134          795 :     if (shown === instance) return node
     135              :   }
     136          151 :   return null
     137              : }
     138              : 
     139           24 : const dimensionsOf = (
     140              :   node: LGraphNode | null
     141              : ): { width: number; height: number } | null => {
     142         1036 :   const width = node?.widgets?.find((w) => w.name === 'width')?.value
     143         1036 :   const height = node?.widgets?.find((w) => w.name === 'height')?.value
     144         1036 :   return typeof width === 'number' && typeof height === 'number'
     145              :     ? { width, height }
     146              :     : null
     147              : }
     148              : 
     149           24 : const invokeReadyCallback = (
     150              :   callback: Load3dReadyCallback,
     151              :   instance: Load3d
     152              : ): void => {
     153           56 :   try {
     154           56 :     callback(instance)
     155              :   } catch (error) {
     156            0 :     console.error('Load3d ready callback failed:', error)
     157              :   }
     158              : }
     159              : 
     160           24 : export const useLoad3d = (nodeOrRef: MaybeRef<LGraphNode | null>) => {
     161           84 :   const nodeRef = toRef(nodeOrRef)
     162           84 :   let load3d: Load3d | null = null
     163           84 :   let viewerContainer: HTMLElement | null = null
     164           84 :   let isFirstModelLoad = true
     165              : 
     166           84 :   const markDirty = () => {
     167           95 :     const rawNode = toRaw(nodeRef.value)
     168           95 :     if (rawNode) markLoad3dSceneDirty(rawNode)
     169              :   }
     170              : 
     171           84 :   const debouncedHandleResize = useDebounceFn(() => {
     172            0 :     load3d?.handleResize()
     173              :   }, 150)
     174              : 
     175           84 :   watch(
     176              :     () => (getActivePinia() ? useCanvasStore().appScalePercentage : 0),
     177              :     debouncedHandleResize
     178              :   )
     179              : 
     180           84 :   const defaultSceneConfig = (): SceneConfig => ({
     181              :     showGrid: true,
     182              :     backgroundColor: getActivePinia()
     183              :       ? '#' + useSettingStore().get('Comfy.Load3D.BackgroundColor')
     184              :       : '#282828',
     185              :     backgroundImage: '',
     186              :     backgroundRenderMode: 'tiled'
     187              :   })
     188              : 
     189           84 :   const defaultGizmoConfig = (): GizmoConfig => ({
     190              :     enabled: false,
     191              :     mode: 'translate',
     192              :     position: { x: 0, y: 0, z: 0 },
     193              :     rotation: { x: 0, y: 0, z: 0 },
     194              :     scale: { x: 1, y: 1, z: 1 }
     195              :   })
     196              : 
     197           84 :   const defaultModelConfig = (): ModelConfig => ({
     198              :     upDirection: 'original',
     199              :     materialMode: 'original',
     200              :     showSkeleton: false,
     201              :     gizmo: defaultGizmoConfig()
     202              :   })
     203              : 
     204           84 :   const defaultCameraConfig = (): CameraConfig => ({
     205              :     cameraType: 'perspective',
     206              :     fov: 75,
     207              :     hasCustomUp: false
     208              :   })
     209              : 
     210           84 :   const defaultLightConfig = (): LightConfig => ({
     211              :     intensity: 5,
     212              :     hdri: {
     213              :       enabled: false,
     214              :       hdriPath: '',
     215              :       showAsBackground: false,
     216              :       intensity: 1
     217              :     }
     218              :   })
     219              : 
     220           84 :   const sceneConfig = ref<SceneConfig>(defaultSceneConfig())
     221           84 :   const modelConfig = ref<ModelConfig>(defaultModelConfig())
     222           84 :   const hasSkeleton = ref(false)
     223           84 :   const modelStats = ref<ModelStats | null>(null)
     224           84 :   let modelStatsAbort: AbortController | null = null
     225           84 :   const cameraConfig = ref<CameraConfig>(defaultCameraConfig())
     226           84 :   const lightConfig = ref<LightConfig>(defaultLightConfig())
     227           84 :   const lastNonHdriLightIntensity = ref(lightConfig.value.intensity)
     228              : 
     229           84 :   const isRecording = ref(false)
     230           84 :   const hasRecording = ref(false)
     231           84 :   const recordingDuration = ref(0)
     232              : 
     233           84 :   const animations = ref<AnimationItem[]>([])
     234           84 :   const playing = ref(false)
     235           84 :   const selectedSpeed = ref(1)
     236           84 :   const selectedAnimation = ref(0)
     237           84 :   const animationProgress = ref(0)
     238           84 :   const animationDuration = ref(0)
     239           84 :   const loading = ref(false)
     240           84 :   const loadingMessage = ref('')
     241           84 :   const isPreview = ref(false)
     242           84 :   const isSplatModel = ref(false)
     243           84 :   const isPlyModel = ref(false)
     244           84 :   const sourceFormat = ref<string | null>(null)
     245           84 :   const canFitToViewer = ref(true)
     246           84 :   const canCenterCameraOnModel = ref(false)
     247           84 :   const canUseGizmo = ref(true)
     248           84 :   const canUseLighting = ref(true)
     249           84 :   const canExport = ref(true)
     250           84 :   const materialModes = ref<readonly MaterialMode[]>([
     251              :     'original',
     252              :     'clay',
     253              :     'normal',
     254              :     'wireframe'
     255              :   ])
     256              : 
     257           84 :   const createNodeLoad3d = (
     258              :     container: HTMLElement,
     259              :     node: LGraphNode
     260              :   ): Load3d => {
     261           26 :     let instance: Load3d | null = null
     262           26 :     const shownNode = () => (instance && nodeShowing(instance)) ?? node
     263           26 :     const dimensions = dimensionsOf(node)
     264           26 :     instance = createLoad3d(container, load3dHost, {
     265              :       width: dimensions?.width,
     266              :       height: dimensions?.height,
     267              :       getDimensions: dimensions ? () => dimensionsOf(shownNode()) : undefined,
     268              :       getZoomScale: () => {
     269          143 :         return app.canvas.ds.scale
     270              :       },
     271              :       onContextMenu: (event) => {
     272            0 :         const target = shownNode()
     273            0 :         const menuOptions = app.canvas.getNodeMenuOptions(target)
     274            0 :         new LiteGraph.ContextMenu(menuOptions, {
     275              :           event,
     276              :           title: target.type,
     277              :           extra: target
     278              :         })
     279              :       }
     280              :     })
     281           26 :     return instance
     282              :   }
     283              : 
     284           84 :   const initializeLoad3dKeeping = async (
     285              :     containerRef: HTMLElement | null,
     286              :     kept: Load3d | null
     287              :   ) => {
     288           26 :     viewerContainer = containerRef
     289           26 :     const rawNode = toRaw(nodeRef.value)
     290           26 :     if (!containerRef || !rawNode) return
     291              : 
     292           26 :     const node = rawNode
     293              : 
     294           26 :     try {
     295           26 :       const comfyClass = node.constructor.comfyClass
     296              :       const isPreviewClass =
     297              :         typeof comfyClass === 'string' &&
     298              :         (isLoad3dResultViewerNode(comfyClass) ||
     299              :           comfyClass.startsWith('Preview'))
     300              : 
     301           26 :       if (isPreviewClass || !dimensionsOf(node)) {
     302            4 :         isPreview.value = true
     303              :       }
     304              : 
     305           26 :       if (kept) reattachedNodes.add(node)
     306           26 :       load3d = kept ?? createNodeLoad3d(containerRef, node)
     307              : 
     308           26 :       const instance = load3d
     309           26 :       await restoreConfigurationsFromNode(instance, node)
     310           25 :       if (!isCurrentInitialization(instance, node)) return
     311           25 :       if (kept) {
     312            0 :         applyEntireGizmoConfig(kept)
     313            0 :         refreshModelStats()
     314              :       }
     315              : 
     316           25 :       node.onMouseEnter = useChainCallback(node.onMouseEnter, () => {
     317            0 :         load3d?.refreshViewport()
     318            0 :         load3d?.updateStatusMouseOnNode(true)
     319              :       })
     320              : 
     321           25 :       node.onMouseLeave = useChainCallback(node.onMouseLeave, () => {
     322            0 :         load3d?.updateStatusMouseOnNode(false)
     323              :       })
     324              : 
     325           25 :       node.onResize = useChainCallback(node.onResize, () => {
     326            1 :         load3d?.handleResize()
     327              :       })
     328              : 
     329           25 :       node.onDrawBackground = useChainCallback(
     330              :         node.onDrawBackground,
     331              :         function (this: LGraphNode) {
     332            0 :           if (load3d) {
     333            0 :             load3d.domElement.hidden = this.flags.collapsed ?? false
     334              :           }
     335              :         }
     336              :       )
     337              : 
     338           25 :       ensureNodeCleanupChained(node)
     339              : 
     340           25 :       nodeToLoad3dMap.set(node, load3d)
     341              : 
     342           25 :       handleEvents('add')
     343           25 :       const initializedLoad3d = load3d
     344              : 
     345           25 :       const callbacks = pendingCallbacks.get(node)
     346              : 
     347           25 :       if (callbacks) {
     348           25 :         callbacks.forEach((callback) => {
     349           25 :           invokeReadyCallback(callback, initializedLoad3d)
     350              :         })
     351           25 :         pendingCallbacks.delete(node)
     352              :       }
     353              : 
     354           25 :       const persistent = persistentReadyCallbacks.get(node)
     355           25 :       if (persistent) {
     356           25 :         persistent.forEach((callback) => {
     357           25 :           invokePersistentReadyCallback(node, callback, initializedLoad3d)
     358              :         })
     359              :       }
     360              :     } catch (error) {
     361            1 :       console.error('Error initializing Load3d:', error)
     362            1 :       useToast().warning(t('toastMessages.failedToInitializeLoad3dViewer'))
     363              :     }
     364              :   }
     365              : 
     366           84 :   const initializeLoad3d = (containerRef: HTMLElement | null) =>
     367              :     initializeLoad3dKeeping(containerRef, null)
     368              : 
     369           84 :   const savedSceneConfigOf = (node: LGraphNode): SceneConfig => {
     370           25 :     const saved = node.properties['Scene Config'] as
     371              :       | Partial<SceneConfig>
     372              :       | undefined
     373           25 :     if (!saved) return defaultSceneConfig()
     374           25 :     return {
     375              :       ...defaultSceneConfig(),
     376              :       ...saved,
     377              :       backgroundRenderMode: saved.backgroundRenderMode || 'tiled'
     378              :     }
     379              :   }
     380              : 
     381           84 :   const savedModelConfigOf = (node: LGraphNode): ModelConfig => {
     382           25 :     const saved = node.properties['Model Config'] as
     383              :       | StoredModelConfig
     384              :       | undefined
     385           25 :     if (!saved) return defaultModelConfig()
     386           25 :     return {
     387              :       ...defaultModelConfig(),
     388              :       ...saved,
     389              :       gizmo: {
     390              :         ...defaultGizmoConfig(),
     391              :         ...saved.gizmo,
     392              :         scale: saved.gizmo?.scale ?? defaultGizmoConfig().scale
     393              :       }
     394              :     }
     395              :   }
     396              : 
     397           84 :   const savedLightConfigOf = (node: LGraphNode) => {
     398           25 :     const saved = node.properties['Light Config'] as
     399              :       | Partial<LightConfig>
     400              :       | undefined
     401           25 :     const defaults = defaultLightConfig()
     402           25 :     return {
     403              :       hdriEnabled: saved?.hdri?.enabled ?? false,
     404              :       config: {
     405              :         intensity: saved?.intensity ?? defaults.intensity,
     406              :         hdri: { ...defaults.hdri!, ...saved?.hdri, enabled: false }
     407              :       }
     408              :     }
     409              :   }
     410              : 
     411           84 :   const restoreSceneConfig = (node: LGraphNode, instance: Load3d) => {
     412           25 :     const next = savedSceneConfigOf(node)
     413           25 :     const backgroundImageWatched =
     414              :       sceneConfig.value.backgroundImage !== next.backgroundImage
     415           25 :     replaceConfig(sceneConfig, next)
     416           25 :     if (!backgroundImageWatched && next.backgroundImage)
     417            0 :       void instance.setBackgroundImage(next.backgroundImage)
     418              :   }
     419              : 
     420           84 :   const isCurrentInitialization = (instance: Load3d, node: LGraphNode) =>
     421              :     load3d === instance && toRaw(nodeRef.value) === node
     422              : 
     423           84 :   const restoreHdri = async (
     424              :     instance: Load3d,
     425              :     node: LGraphNode,
     426              :     enable: boolean
     427              :   ) => {
     428           25 :     const hdriPath = lightConfig.value.hdri?.hdriPath
     429           25 :     if (!hdriPath) return
     430            0 :     const hdriUrl = api.apiURL(
     431              :       Load3dUtils.getResourceURL(
     432              :         ...Load3dUtils.splitFilePath(hdriPath),
     433              :         'input'
     434              :       )
     435              :     )
     436           25 :     try {
     437            0 :       if (
     438              :         !Load3dUtils.isSameResourceURL(instance.hdriManager.loadedUrl, hdriUrl)
     439              :       )
     440            0 :         await instance.loadHDRI(hdriUrl)
     441              :     } catch (error) {
     442            0 :       if (!isCurrentInitialization(instance, node)) return
     443            0 :       console.warn('Failed to restore HDRI:', error)
     444            0 :       lightConfig.value = {
     445              :         ...lightConfig.value,
     446              :         hdri: { ...lightConfig.value.hdri!, hdriPath: '', enabled: false }
     447              :       }
     448            0 :       return
     449              :     }
     450           25 :     if (enable && isCurrentInitialization(instance, node)) {
     451            0 :       lightConfig.value = {
     452              :         ...lightConfig.value,
     453              :         hdri: { ...lightConfig.value.hdri!, enabled: true }
     454              :       }
     455              :     }
     456              :   }
     457              : 
     458           84 :   const restoreConfigurationsFromNode = async (
     459              :     instance: Load3d,
     460              :     node: LGraphNode
     461              :   ) => {
     462           25 :     restoreSceneConfig(node, instance)
     463           25 :     replaceConfig(modelConfig, savedModelConfigOf(node))
     464           25 :     replaceConfig(
     465              :       cameraConfig,
     466              :       (node.properties['Camera Config'] as CameraConfig | null | undefined) ??
     467              :         defaultCameraConfig()
     468              :     )
     469           25 :     const savedLight = savedLightConfigOf(node)
     470           25 :     replaceConfig(lightConfig, savedLight.config)
     471           25 :     lastNonHdriLightIntensity.value = lightConfig.value.intensity
     472           25 :     await restoreHdri(instance, node, savedLight.hdriEnabled)
     473           25 :     if (!isCurrentInitialization(instance, node)) return
     474              : 
     475           25 :     applySceneConfigToLoad3d()
     476           25 :     applyLightConfigToLoad3d()
     477              :   }
     478              : 
     479           84 :   const applySceneConfigToLoad3d = () => {
     480           25 :     if (!load3d) return
     481           25 :     const cfg = sceneConfig.value
     482           25 :     load3d.toggleGrid(cfg.showGrid)
     483           25 :     if (!lightConfig.value.hdri?.enabled) {
     484           25 :       load3d.setBackgroundColor(cfg.backgroundColor)
     485              :     }
     486           25 :     if (cfg.backgroundRenderMode) {
     487           25 :       load3d.setBackgroundRenderMode(cfg.backgroundRenderMode)
     488              :     }
     489              :   }
     490              : 
     491           84 :   const applyEntireGizmoConfig = (instance: Load3d) => {
     492            0 :     const { gizmo } = modelConfig.value
     493            0 :     if (!gizmo) return
     494            0 :     const { position, rotation, scale } = hasGizmoTransform(gizmo)
     495              :       ? gizmo
     496              :       : instance.getGizmoManager().getInitialTransform()
     497            0 :     instance.applyGizmoTransform(position, rotation, scale)
     498            0 :     instance.setGizmoEnabled(gizmo.enabled)
     499            0 :     instance.setGizmoMode(gizmo.mode)
     500              :   }
     501              : 
     502           84 :   const applyGizmoConfigToLoad3d = () => {
     503           19 :     if (!load3d) return
     504           19 :     const gizmo = modelConfig.value.gizmo
     505           19 :     if (!gizmo) return
     506           19 :     if (hasGizmoTransform(gizmo)) {
     507            0 :       load3d.applyGizmoTransform(gizmo.position, gizmo.rotation, gizmo.scale)
     508              :     }
     509           19 :     if (gizmo.enabled) {
     510            0 :       load3d.setGizmoEnabled(true)
     511              :     }
     512           19 :     if (gizmo.mode !== 'translate') {
     513            0 :       load3d.setGizmoMode(gizmo.mode)
     514              :     }
     515              :   }
     516              : 
     517           84 :   const applyLightConfigToLoad3d = () => {
     518           25 :     if (!load3d) return
     519           25 :     const cfg = lightConfig.value
     520           25 :     load3d.setLightIntensity(cfg.intensity)
     521           25 :     const hdri = cfg.hdri
     522           25 :     if (!hdri) return
     523           25 :     load3d.setHDRIIntensity(hdri.intensity)
     524           25 :     load3d.setHDRIAsBackground(hdri.showAsBackground)
     525           25 :     load3d.setHDRIEnabled(hdri.enabled)
     526              :   }
     527              : 
     528           84 :   const replaceConfig = <T>(config: Ref<T>, next: T) => {
     529          100 :     if (!isEqual(config.value, next)) config.value = next
     530              :   }
     531              : 
     532           84 :   const writeNodeConfig = (key: string, value: object, defaults: object) => {
     533           90 :     const properties = nodeRef.value?.properties
     534           90 :     if (!properties) return
     535           90 :     if (!(key in properties) && isEqual(value, defaults)) return
     536           83 :     properties[key] = value
     537              :   }
     538              : 
     539           84 :   const persistLightConfigToNode = () => {
     540           25 :     writeNodeConfig('Light Config', lightConfig.value, defaultLightConfig())
     541           25 :     markDirty()
     542              :   }
     543              : 
     544           84 :   const waitForLoad3d = (callback: Load3dReadyCallback) => {
     545           32 :     const node = toRaw(nodeRef.value)
     546           32 :     if (!node) return
     547           32 :     const existingInstance = nodeToLoad3dMap.get(node)
     548              : 
     549           32 :     if (existingInstance) {
     550            6 :       invokeReadyCallback(callback, existingInstance)
     551            6 :       return
     552              :     }
     553              : 
     554           26 :     if (!pendingCallbacks.has(node)) {
     555           26 :       pendingCallbacks.set(node, [])
     556              :     }
     557              : 
     558           26 :     pendingCallbacks.get(node)!.push(callback)
     559           26 :     ensureNodeCleanupChained(node)
     560              :   }
     561              : 
     562           84 :   const onLoad3dReady = (callback: Load3dReadyCallback) => {
     563           26 :     const node = toRaw(nodeRef.value)
     564           26 :     if (!node) return
     565              : 
     566           26 :     if (!persistentReadyCallbacks.has(node)) {
     567           26 :       persistentReadyCallbacks.set(node, [])
     568              :     }
     569           26 :     persistentReadyCallbacks.get(node)!.push(callback)
     570           26 :     ensureNodeCleanupChained(node)
     571              : 
     572           26 :     const existingInstance = nodeToLoad3dMap.get(node)
     573           26 :     if (existingInstance)
     574            0 :       invokePersistentReadyCallback(node, callback, existingInstance)
     575              :   }
     576              : 
     577           84 :   watch(
     578              :     sceneConfig,
     579              :     (newValue) => {
     580           27 :       writeNodeConfig('Scene Config', newValue, defaultSceneConfig())
     581           27 :       markDirty()
     582              :     },
     583              :     { deep: true }
     584              :   )
     585              : 
     586           84 :   watch(
     587              :     () => sceneConfig.value.showGrid,
     588              :     (showGrid) => {
     589            2 :       load3d?.toggleGrid(showGrid)
     590              :     }
     591              :   )
     592              : 
     593           84 :   watch(
     594              :     () => sceneConfig.value.backgroundColor,
     595              :     (color) => {
     596            1 :       if (!load3d || lightConfig.value.hdri?.enabled) return
     597            1 :       load3d.setBackgroundColor(color)
     598              :     }
     599              :   )
     600              : 
     601           84 :   watch(
     602              :     () => sceneConfig.value.backgroundImage,
     603              :     async (image) => {
     604            2 :       if (!load3d) return
     605            2 :       await load3d.setBackgroundImage(image || '')
     606              :     }
     607              :   )
     608              : 
     609           84 :   watch(
     610              :     () => sceneConfig.value.backgroundRenderMode,
     611              :     (mode) => {
     612            2 :       if (mode) load3d?.setBackgroundRenderMode(mode)
     613              :     }
     614              :   )
     615              : 
     616           84 :   watch(
     617              :     modelConfig,
     618              :     (newValue) => {
     619           13 :       writeNodeConfig('Model Config', newValue, defaultModelConfig())
     620           13 :       markDirty()
     621              :     },
     622              :     { deep: true }
     623              :   )
     624              : 
     625           84 :   watch(
     626              :     () => modelConfig.value.upDirection,
     627              :     (newValue) => {
     628            0 :       if (load3d) load3d.setUpDirection(newValue)
     629              :     }
     630              :   )
     631              : 
     632           84 :   watch(
     633              :     () => modelConfig.value.materialMode,
     634              :     (newValue) => {
     635            0 :       if (load3d) load3d.setMaterialMode(newValue)
     636              :     }
     637              :   )
     638              : 
     639           84 :   watch(
     640              :     () => modelConfig.value.showSkeleton,
     641              :     (newValue) => {
     642            0 :       if (load3d) load3d.setShowSkeleton(newValue)
     643              :     }
     644              :   )
     645              : 
     646           84 :   watch(
     647              :     cameraConfig,
     648              :     (newValue) => {
     649           25 :       if (load3d && nodeRef.value) {
     650           25 :         writeNodeConfig('Camera Config', newValue, defaultCameraConfig())
     651           25 :         load3d.toggleCamera(newValue.cameraType)
     652           25 :         load3d.setFOV(newValue.fov)
     653           25 :         if (newValue.hasCustomUp) {
     654            0 :           load3d.setUseCustomUp(newValue.useCustomUp)
     655              :         }
     656              :       }
     657           25 :       markDirty()
     658              :     },
     659              :     { deep: true }
     660              :   )
     661              : 
     662           84 :   watch(
     663              :     () => lightConfig.value.intensity,
     664              :     (intensity) => {
     665           25 :       if (!load3d || !nodeRef.value) return
     666           25 :       if (!lightConfig.value.hdri?.enabled) {
     667           25 :         lastNonHdriLightIntensity.value = intensity
     668              :       }
     669           25 :       persistLightConfigToNode()
     670           25 :       load3d.setLightIntensity(intensity)
     671              :     }
     672              :   )
     673              : 
     674           84 :   watch(
     675              :     () => lightConfig.value.hdri?.intensity,
     676              :     (intensity) => {
     677            0 :       if (!load3d || !nodeRef.value) return
     678            0 :       if (intensity === undefined) return
     679            0 :       persistLightConfigToNode()
     680            0 :       load3d.setHDRIIntensity(intensity)
     681              :     }
     682              :   )
     683              : 
     684           84 :   watch(
     685              :     () => lightConfig.value.hdri?.showAsBackground,
     686              :     (show) => {
     687            0 :       if (!load3d || !nodeRef.value) return
     688            0 :       if (show === undefined) return
     689            0 :       persistLightConfigToNode()
     690            0 :       load3d.setHDRIAsBackground(show)
     691              :     }
     692              :   )
     693              : 
     694           84 :   watch(
     695              :     () => lightConfig.value.hdri?.enabled,
     696              :     (enabled, prevEnabled) => {
     697            0 :       if (!load3d || !nodeRef.value) return
     698            0 :       if (enabled === undefined) return
     699            0 :       if (enabled && prevEnabled === false) {
     700            0 :         lastNonHdriLightIntensity.value = lightConfig.value.intensity
     701              :       }
     702            0 :       if (!enabled && prevEnabled === true) {
     703            0 :         lightConfig.value = {
     704              :           ...lightConfig.value,
     705              :           intensity: lastNonHdriLightIntensity.value
     706              :         }
     707              :       }
     708            0 :       persistLightConfigToNode()
     709            0 :       load3d.setHDRIEnabled(enabled)
     710              :     }
     711              :   )
     712              : 
     713           84 :   watch(playing, (newValue) => {
     714            1 :     if (load3d) {
     715            1 :       load3d.toggleAnimation(newValue)
     716              :     }
     717            1 :     markDirty()
     718              :   })
     719              : 
     720           84 :   watch(selectedSpeed, (newValue) => {
     721            0 :     if (load3d && newValue) {
     722            0 :       load3d.setAnimationSpeed(newValue)
     723              :     }
     724            0 :     markDirty()
     725              :   })
     726              : 
     727           84 :   watch(selectedAnimation, (newValue) => {
     728            0 :     if (load3d) {
     729            0 :       load3d.updateSelectedAnimation(newValue)
     730              :     }
     731            0 :     markDirty()
     732              :   })
     733              : 
     734           84 :   const handleMouseEnter = () => {
     735           19 :     load3d?.updateStatusMouseOnScene(true)
     736              :   }
     737              : 
     738           84 :   const handleMouseLeave = () => {
     739           10 :     load3d?.updateStatusMouseOnScene(false)
     740              :   }
     741              : 
     742           84 :   const handleStartRecording = async () => {
     743            2 :     if (load3d) {
     744            2 :       await load3d.startRecording()
     745            2 :       isRecording.value = true
     746            2 :       markDirty()
     747              :     }
     748              :   }
     749              : 
     750           84 :   const handleStopRecording = () => {
     751            1 :     if (load3d) {
     752            1 :       load3d.stopRecording()
     753            1 :       isRecording.value = false
     754            1 :       recordingDuration.value = load3d.getRecordingDuration()
     755            1 :       hasRecording.value = recordingDuration.value > 0
     756            1 :       if (hasRecording.value) markDirty()
     757              :     }
     758              :   }
     759              : 
     760           84 :   const handleExportRecording = () => {
     761            0 :     if (load3d) {
     762              :       const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
     763            0 :       const filename = `${timestamp}-scene-recording.mp4`
     764            0 :       load3d.exportRecording(filename)
     765              :     }
     766              :   }
     767              : 
     768           84 :   const handleClearRecording = () => {
     769            1 :     if (load3d) {
     770            1 :       load3d.clearRecording()
     771            1 :       hasRecording.value = false
     772            1 :       recordingDuration.value = 0
     773            1 :       markDirty()
     774              :     }
     775              :   }
     776              : 
     777           84 :   const handleSeek = (progress: number) => {
     778            0 :     if (load3d && animationDuration.value > 0) {
     779            0 :       const time = (progress / 100) * animationDuration.value
     780            0 :       load3d.setAnimationTime(time)
     781            0 :       markDirty()
     782              :     }
     783              :   }
     784              : 
     785           84 :   const handleHDRIFileUpdate = async (file: File | null) => {
     786            0 :     const capturedLoad3d = load3d
     787            0 :     if (!capturedLoad3d) return
     788              : 
     789            0 :     if (!file) {
     790            0 :       lightConfig.value = {
     791              :         ...lightConfig.value,
     792              :         hdri: {
     793              :           ...lightConfig.value.hdri!,
     794              :           hdriPath: '',
     795              :           enabled: false,
     796              :           showAsBackground: false
     797              :         }
     798              :       }
     799            0 :       capturedLoad3d.clearHDRI()
     800            0 :       return
     801              :     }
     802              : 
     803            0 :     const resourceFolder =
     804              :       (nodeRef.value?.properties['Resource Folder'] as string) || ''
     805              : 
     806            0 :     const subfolder = resourceFolder.trim()
     807              :       ? `3d/${resourceFolder.trim()}`
     808              :       : '3d'
     809              : 
     810            0 :     const uploadedPath = await Load3dUtils.uploadFile(file, subfolder)
     811            0 :     if (!uploadedPath) {
     812            0 :       return
     813              :     }
     814              : 
     815            0 :     if (load3d !== capturedLoad3d) return
     816              : 
     817            0 :     const hdriUrl = api.apiURL(
     818              :       Load3dUtils.getResourceURL(
     819              :         ...Load3dUtils.splitFilePath(uploadedPath),
     820              :         'input'
     821              :       )
     822              :     )
     823              : 
     824            0 :     try {
     825            0 :       loading.value = true
     826            0 :       loadingMessage.value = t('load3d.loadingHDRI')
     827            0 :       await capturedLoad3d.loadHDRI(hdriUrl)
     828              : 
     829            0 :       if (load3d !== capturedLoad3d) return
     830              : 
     831            0 :       let sceneMin = 1
     832            0 :       let sceneMax = 10
     833            0 :       if (getActivePinia() != null) {
     834            0 :         const settingStore = useSettingStore()
     835            0 :         sceneMin = settingStore.get('Comfy.Load3D.LightIntensityMinimum')
     836            0 :         sceneMax = settingStore.get('Comfy.Load3D.LightIntensityMaximum')
     837              :       }
     838            0 :       const mappedHdriIntensity = Load3dUtils.mapSceneLightIntensityToHdri(
     839              :         lightConfig.value.intensity,
     840              :         sceneMin,
     841              :         sceneMax
     842              :       )
     843            0 :       lightConfig.value = {
     844              :         ...lightConfig.value,
     845              :         hdri: {
     846              :           ...lightConfig.value.hdri!,
     847              :           hdriPath: uploadedPath,
     848              :           enabled: true,
     849              :           showAsBackground: true,
     850              :           intensity: mappedHdriIntensity
     851              :         }
     852              :       }
     853              :     } catch (error) {
     854            0 :       console.error('Failed to load HDRI:', error)
     855            0 :       capturedLoad3d.clearHDRI()
     856            0 :       lightConfig.value = {
     857              :         ...lightConfig.value,
     858              :         hdri: {
     859              :           ...lightConfig.value.hdri!,
     860              :           hdriPath: '',
     861              :           enabled: false,
     862              :           showAsBackground: false
     863              :         }
     864              :       }
     865            0 :       useToast().warning(t('toastMessages.failedToLoadHDRI'))
     866              :     } finally {
     867            0 :       loading.value = false
     868            0 :       loadingMessage.value = ''
     869              :     }
     870              :   }
     871              : 
     872           84 :   const handleBackgroundImageUpdate = async (file: File | null) => {
     873            2 :     if (!file) {
     874            1 :       sceneConfig.value.backgroundImage = ''
     875            1 :       await load3d?.setBackgroundImage('')
     876            1 :       return
     877              :     }
     878              : 
     879            2 :     const resourceFolder =
     880              :       (nodeRef.value?.properties['Resource Folder'] as string) || ''
     881              : 
     882            2 :     const subfolder = resourceFolder.trim()
     883              :       ? `3d/${resourceFolder.trim()}`
     884              :       : '3d'
     885              : 
     886            2 :     const uploadedPath = await Load3dUtils.uploadFile(file, subfolder)
     887            2 :     if (!uploadedPath) return
     888              : 
     889            1 :     sceneConfig.value.backgroundRenderMode = 'tiled'
     890            1 :     sceneConfig.value.backgroundImage = uploadedPath
     891            2 :     await load3d?.setBackgroundImage(uploadedPath)
     892              :   }
     893              : 
     894           84 :   const handleExportModel = async (format: string) => {
     895            0 :     if (!load3d) {
     896            0 :       useToast().warning(t('toastMessages.no3dSceneToExport'))
     897            0 :       return
     898              :     }
     899              : 
     900            0 :     try {
     901            0 :       await load3d.exportModel(format)
     902              :     } catch (error) {
     903            0 :       console.error('Error exporting model:', error)
     904            0 :       useToast().warning(
     905              :         t('toastMessages.failedToExportModel', {
     906              :           format: format.toUpperCase()
     907              :         })
     908              :       )
     909              :     }
     910              :   }
     911              : 
     912           84 :   const handleModelDrop = async (file: File) => {
     913            1 :     if (!load3d) {
     914            0 :       useToast().warning(t('toastMessages.no3dScene'))
     915            0 :       return
     916              :     }
     917              : 
     918            1 :     const node = toRaw(nodeRef.value)
     919            1 :     if (!node) return
     920              : 
     921            1 :     try {
     922            1 :       const resourceFolder =
     923              :         (node.properties['Resource Folder'] as string) || ''
     924              : 
     925            1 :       const subfolder = resourceFolder.trim()
     926              :         ? `3d/${resourceFolder.trim()}`
     927              :         : '3d'
     928              : 
     929            1 :       loading.value = true
     930            1 :       loadingMessage.value = t('load3d.uploadingModel')
     931              : 
     932            1 :       const uploadedPath = await Load3dUtils.uploadFile(file, subfolder)
     933              : 
     934            1 :       if (!uploadedPath) {
     935            0 :         useToast().warning(t('toastMessages.fileUploadFailed'))
     936            0 :         return
     937              :       }
     938              : 
     939            1 :       const modelUrl = api.apiURL(
     940              :         Load3dUtils.getResourceURL(
     941              :           ...Load3dUtils.splitFilePath(uploadedPath),
     942              :           isPreview.value ? 'output' : 'input'
     943              :         )
     944              :       )
     945              : 
     946            1 :       loadingMessage.value = t('load3d.loadingModel')
     947            1 :       const outcome = await load3d.loadModel(modelUrl)
     948            1 :       reportLoadModelOutcome(outcome)
     949            1 :       if (outcome !== 'loaded') return
     950              : 
     951            1 :       const modelWidget = node.widgets?.find((w) => w.name === 'model_file')
     952              : 
     953            1 :       if (modelWidget) {
     954            1 :         const options = modelWidget.options as { values?: string[] } | undefined
     955            1 :         if (options?.values && !options.values.includes(uploadedPath)) {
     956            1 :           options.values.push(uploadedPath)
     957              :         }
     958            1 :         modelWidget.value = uploadedPath
     959            1 :         recordModelChange()
     960              :       }
     961              :     } catch (error) {
     962            0 :       console.error('Model drop failed:', error)
     963            0 :       useToast().warning(t('toastMessages.failedToLoadModel'))
     964              :     } finally {
     965            1 :       loading.value = false
     966            1 :       loadingMessage.value = ''
     967              :     }
     968              :   }
     969              : 
     970           84 :   const syncSceneModels = () => {
     971           19 :     const modelInfo = load3d?.getModelInfo()
     972           19 :     sceneConfig.value.models = modelInfo ? [modelInfo] : []
     973              :   }
     974              : 
     975           84 :   const eventConfig = {
     976              :     materialModeChange: (value: string) => {
     977            0 :       modelConfig.value.materialMode = value as MaterialMode
     978              :     },
     979              :     backgroundColorChange: (value: string) => {
     980           28 :       sceneConfig.value.backgroundColor = value
     981              :     },
     982              :     backgroundRenderModeChange: (value: string) => {
     983            2 :       sceneConfig.value.backgroundRenderMode = value as 'tiled' | 'panorama'
     984              :     },
     985              :     lightIntensityChange: (value: number) => {
     986           48 :       lightConfig.value.intensity = value
     987              :     },
     988              :     fovChange: (value: number) => {
     989           48 :       cameraConfig.value.fov = value
     990              :     },
     991              :     cameraTypeChange: (value: string) => {
     992            0 :       cameraConfig.value.cameraType = value as CameraType
     993              :     },
     994              :     cameraUpStateChange: (value: {
     995              :       hasCustomUp: boolean
     996              :       usingCustomUp: boolean
     997              :     }) => {
     998            0 :       const { cameraType, fov, state } = cameraConfig.value
     999            0 :       cameraConfig.value = value.hasCustomUp
    1000              :         ? {
    1001              :             cameraType,
    1002              :             fov,
    1003              :             state,
    1004              :             hasCustomUp: true,
    1005              :             useCustomUp: value.usingCustomUp
    1006              :           }
    1007              :         : { cameraType, fov, state, hasCustomUp: false }
    1008              :     },
    1009              :     showGridChange: (value: boolean) => {
    1010           27 :       sceneConfig.value.showGrid = value
    1011              :     },
    1012              :     upDirectionChange: (value: string) => {
    1013           10 :       modelConfig.value.upDirection = value as UpDirection
    1014              :     },
    1015              :     backgroundImageChange: (value: string) => {
    1016            2 :       sceneConfig.value.backgroundImage = value
    1017              :     },
    1018              :     backgroundImageLoadingStart: () => {
    1019            2 :       loadingMessage.value = t('load3d.loadingBackgroundImage')
    1020            2 :       loading.value = true
    1021              :     },
    1022              :     backgroundImageLoadingEnd: () => {
    1023            2 :       loadingMessage.value = ''
    1024            2 :       loading.value = false
    1025              :     },
    1026              :     modelLoadingStart: () => {
    1027           19 :       loadingMessage.value = t('load3d.loadingModel')
    1028           19 :       loading.value = true
    1029           19 :       clearModelStats()
    1030           19 :       if (!isFirstModelLoad) {
    1031            7 :         modelConfig.value = {
    1032              :           upDirection: 'original',
    1033              :           materialMode: 'original',
    1034              :           showSkeleton: false,
    1035              :           gizmo: {
    1036              :             enabled: false,
    1037              :             mode: 'translate',
    1038              :             position: { x: 0, y: 0, z: 0 },
    1039              :             rotation: { x: 0, y: 0, z: 0 },
    1040              :             scale: { x: 1, y: 1, z: 1 }
    1041              :           }
    1042              :         }
    1043              :       }
    1044              :     },
    1045              :     modelCleared: () => clearModelStats(),
    1046              :     modelLoadingEnd: () => {
    1047           19 :       loadingMessage.value = ''
    1048           19 :       loading.value = false
    1049           19 :       isSplatModel.value = load3d?.isSplatModel() ?? false
    1050           19 :       isPlyModel.value = load3d?.isPlyModel() ?? false
    1051           19 :       sourceFormat.value = load3d?.getSourceFormat() ?? null
    1052           19 :       canCenterCameraOnModel.value = isSplatModel.value || isPlyModel.value
    1053           19 :       const caps = load3d?.getCurrentModelCapabilities()
    1054           19 :       canFitToViewer.value = caps?.fitToViewer ?? true
    1055           19 :       canUseGizmo.value = caps?.gizmoTransform ?? true
    1056           19 :       canUseLighting.value = caps?.lighting ?? true
    1057           19 :       canExport.value = caps?.exportable ?? true
    1058           19 :       materialModes.value = caps?.materialModes ?? [
    1059              :         'original',
    1060              :         'normal',
    1061              :         'wireframe'
    1062              :       ]
    1063           19 :       hasSkeleton.value = load3d?.hasSkeleton() ?? false
    1064           19 :       refreshModelStats()
    1065           19 :       applyGizmoConfigToLoad3d()
    1066           19 :       syncSceneModels()
    1067           19 :       isFirstModelLoad = false
    1068              :     },
    1069              :     modelReady: () => {
    1070           10 :       if (!load3d || !isAssetPreviewSupported()) return
    1071              : 
    1072            0 :       const node = nodeRef.value
    1073           10 :       if (node?.properties['Last Time Model Folder'] === 'temp') return
    1074              :       const modelWidget = node?.widgets?.find(
    1075              :         (w) => w.name === 'model_file' || w.name === 'image'
    1076              :       )
    1077           10 :       const widgetValue = modelWidget?.value
    1078           10 :       const value =
    1079              :         typeof widgetValue === 'string' && widgetValue.trim()
    1080              :           ? widgetValue
    1081              :           : node?.properties['Last Time Model File']
    1082           10 :       if (typeof value !== 'string' || !value) return
    1083              : 
    1084            0 :       const filename = value.trim().replace(/\s*\[output\]$/, '')
    1085            0 :       const modelName = Load3dUtils.splitFilePath(filename)[1]
    1086            0 :       load3d
    1087              :         .captureThumbnail(256, 256)
    1088              :         .then((dataUrl) => fetch(dataUrl).then((r) => r.blob()))
    1089              :         .then((blob) => persistThumbnail(modelName, blob))
    1090              :         .catch(() => {})
    1091              :     },
    1092              :     skeletonVisibilityChange: (value: boolean) => {
    1093            0 :       modelConfig.value.showSkeleton = value
    1094              :     },
    1095              :     exportLoadingStart: (message: string) => {
    1096            0 :       loadingMessage.value = message || t('load3d.exportingModel')
    1097            0 :       loading.value = true
    1098              :     },
    1099              :     exportLoadingEnd: () => {
    1100            0 :       loadingMessage.value = ''
    1101            0 :       loading.value = false
    1102              :     },
    1103              :     recordingStatusChange: (value: boolean) => {
    1104            4 :       isRecording.value = value
    1105              : 
    1106            4 :       if (!value && load3d) {
    1107            4 :         recordingDuration.value = load3d.getRecordingDuration()
    1108            4 :         hasRecording.value = recordingDuration.value > 0
    1109              :       }
    1110              :     },
    1111              :     animationListChange: (newValue: AnimationItem[]) => {
    1112           43 :       animations.value = newValue
    1113              :     },
    1114              :     animationProgressChange: (data: {
    1115              :       progress: number
    1116              :       currentTime: number
    1117              :       duration: number
    1118              :     }) => {
    1119            8 :       animationProgress.value = data.progress
    1120            8 :       animationDuration.value = data.duration
    1121              :     },
    1122              :     cameraChanged: (cameraState: CameraState) => {
    1123            0 :       const rawNode = toRaw(nodeRef.value)
    1124            0 :       if (rawNode) {
    1125            0 :         const node = rawNode
    1126            0 :         const cameraConfigProp = node.properties['Camera Config']
    1127              : 
    1128            0 :         if (cameraConfigProp) {
    1129            0 :           ;(cameraConfigProp as CameraConfig).state = cameraState
    1130              :         } else {
    1131            0 :           node.properties['Camera Config'] = {
    1132              :             cameraType: cameraConfig.value.cameraType,
    1133              :             fov: cameraConfig.value.fov,
    1134              :             state: cameraState
    1135              :           }
    1136              :         }
    1137            0 :         markLoad3dSceneDirty(node)
    1138              :       }
    1139              :     },
    1140              :     gizmoTransformChange: (data: GizmoConfig) => {
    1141            0 :       if (modelConfig.value.gizmo && nodeRef.value) {
    1142            0 :         modelConfig.value.gizmo.position = data.position
    1143            0 :         modelConfig.value.gizmo.rotation = data.rotation
    1144            0 :         modelConfig.value.gizmo.scale = data.scale
    1145            0 :         modelConfig.value.gizmo.enabled = data.enabled
    1146            0 :         modelConfig.value.gizmo.mode = data.mode
    1147              :       }
    1148            0 :       syncSceneModels()
    1149              :     }
    1150              :   } as const
    1151              : 
    1152           84 :   const handleToggleGizmo = (enabled: boolean) => {
    1153            3 :     if (load3d && modelConfig.value.gizmo) {
    1154            3 :       modelConfig.value.gizmo.enabled = enabled
    1155            3 :       load3d.setGizmoEnabled(enabled)
    1156              :     }
    1157              :   }
    1158              : 
    1159           84 :   const handleSetGizmoMode = (mode: GizmoMode) => {
    1160            3 :     if (load3d && modelConfig.value.gizmo) {
    1161            3 :       modelConfig.value.gizmo.mode = mode
    1162            3 :       load3d.setGizmoMode(mode)
    1163              :     }
    1164              :   }
    1165              : 
    1166           84 :   const handleFitToViewer = () => {
    1167            0 :     if (!load3d) return
    1168            0 :     load3d.fitToViewer()
    1169              : 
    1170            0 :     if (!modelConfig.value.gizmo) return
    1171            0 :     const transform = load3d.getGizmoTransform()
    1172            0 :     modelConfig.value.gizmo.position = transform.position
    1173            0 :     modelConfig.value.gizmo.scale = transform.scale
    1174            0 :     syncSceneModels()
    1175              :   }
    1176              : 
    1177           84 :   const handleCenterCameraOnModel = () => {
    1178            0 :     if (!load3d) return
    1179            0 :     load3d.centerCameraOnModel()
    1180            0 :     markDirty()
    1181              :   }
    1182              : 
    1183           84 :   const handleResetGizmoTransform = () => {
    1184            0 :     if (load3d) {
    1185            0 :       load3d.resetGizmoTransform()
    1186              :     }
    1187              :   }
    1188              : 
    1189           84 :   const handleEvents = (action: 'add' | 'remove') => {
    1190           25 :     Object.entries(eventConfig).forEach(([event, handler]) => {
    1191          600 :       const method = `${action}EventListener` as const
    1192          600 :       load3d?.[method](event, handler as EventCallback)
    1193              :     })
    1194              :   }
    1195              : 
    1196           84 :   const abortModelStats = () => {
    1197           45 :     modelStatsAbort?.abort()
    1198           45 :     modelStatsAbort = null
    1199              :   }
    1200              : 
    1201           84 :   const clearModelStats = () => {
    1202           26 :     abortModelStats()
    1203           26 :     modelStats.value = null
    1204              :   }
    1205              : 
    1206           84 :   const refreshModelStats = () => {
    1207           19 :     abortModelStats()
    1208           19 :     const controller = new AbortController()
    1209           19 :     modelStatsAbort = controller
    1210           19 :     void load3d
    1211              :       ?.getModelStats(controller.signal)
    1212              :       .then((stats) => {
    1213           19 :         if (modelStatsAbort !== controller) return
    1214           13 :         modelStats.value = stats
    1215              :       })
    1216              :       .catch((error: unknown) => {
    1217            0 :         if (controller.signal.aborted) return
    1218            0 :         reportError(error, {
    1219              :           errorType: 'error_computing_load3d_model_stats',
    1220              :           surface: 'graph'
    1221              :         })
    1222              :       })
    1223              :   }
    1224              : 
    1225           84 :   const releaseLoad3d = (keep = false): Load3d | null => {
    1226            0 :     if (keep) abortModelStats()
    1227            0 :     else clearModelStats()
    1228            0 :     handleEvents('remove')
    1229            0 :     const released = load3d
    1230            0 :     load3d = null
    1231            0 :     if (!released) return null
    1232              : 
    1233            0 :     const shownBy = nodeShowing(released)
    1234            0 :     if (shownBy) nodeToLoad3dMap.delete(shownBy)
    1235            0 :     if (keep) return released
    1236            0 :     released.remove()
    1237            0 :     return null
    1238              :   }
    1239              : 
    1240           84 :   const cleanup = () => releaseLoad3d()
    1241              : 
    1242           84 :   watch(nodeRef, (node, previous) => {
    1243            0 :     const current = node ? toRaw(node) : null
    1244            0 :     const replaced = previous ? toRaw(previous) : null
    1245            0 :     const kept = replaced
    1246              :       ? releaseLoad3d(!!current && isReloadedCopy(current, replaced))
    1247              :       : null
    1248            0 :     if (!node) viewerContainer = null
    1249            0 :     else if (viewerContainer)
    1250            0 :       void initializeLoad3dKeeping(viewerContainer, kept)
    1251              :   })
    1252              : 
    1253           84 :   return {
    1254              :     load3d,
    1255              :     sceneConfig,
    1256              :     modelConfig,
    1257              :     cameraConfig,
    1258              :     lightConfig,
    1259              :     isRecording,
    1260              :     isPreview,
    1261              :     isSplatModel,
    1262              :     isPlyModel,
    1263              :     sourceFormat,
    1264              :     canFitToViewer,
    1265              :     canCenterCameraOnModel,
    1266              :     canUseGizmo,
    1267              :     canUseLighting,
    1268              :     canExport,
    1269              :     materialModes,
    1270              :     hasSkeleton,
    1271              :     modelStats,
    1272              :     hasRecording,
    1273              :     recordingDuration,
    1274              :     animations,
    1275              :     playing,
    1276              :     selectedSpeed,
    1277              :     selectedAnimation,
    1278              :     animationProgress,
    1279              :     animationDuration,
    1280              :     loading,
    1281              :     loadingMessage,
    1282              : 
    1283              :     initializeLoad3d,
    1284              :     waitForLoad3d,
    1285              :     onLoad3dReady,
    1286              :     handleMouseEnter,
    1287              :     handleMouseLeave,
    1288              :     handleStartRecording,
    1289              :     handleStopRecording,
    1290              :     handleExportRecording,
    1291              :     handleClearRecording,
    1292              :     handleSeek,
    1293              :     handleBackgroundImageUpdate,
    1294              :     handleHDRIFileUpdate,
    1295              :     handleExportModel,
    1296              :     handleModelDrop,
    1297              :     handleToggleGizmo,
    1298              :     handleSetGizmoMode,
    1299              :     handleResetGizmoTransform,
    1300              :     handleFitToViewer,
    1301              :     handleCenterCameraOnModel,
    1302              :     cleanup
    1303              :   }
    1304              : }
        

Generated by: LCOV version 2.0-1