Line data Source code
1 : import { effectScope, watch } from 'vue'
2 :
3 : import { LOAD3D_NONE_MODEL } from '@comfyorg/viewport3d/load3d/constants'
4 : import type Load3d from '@comfyorg/viewport3d/load3d/Load3d'
5 : import Load3dUtils from '@/extensions/core/load3d/Load3dUtils'
6 : import { isKeepingLoadedModel } from '@/extensions/core/load3d/load3dInstances'
7 : import { reportLoadModelOutcome } from '@/extensions/core/load3d/reportLoadModelOutcome'
8 : import type {
9 : CameraConfig,
10 : CameraState,
11 : HDRIConfig,
12 : LightConfig,
13 : GizmoConfig,
14 : ModelConfig,
15 : SceneConfig,
16 : StoredModelConfig
17 : } from '@comfyorg/viewport3d/load3d/interfaces'
18 : import type { Dictionary } from '@comfyorg/graph-model/interfaces'
19 : import type { NodeProperty } from '@/lib/litegraph/src/LGraphNode'
20 : import type { IBaseWidget, INumericWidget } from '@comfyorg/graph-model/widgets'
21 : import { useSettingStore } from '@/platform/settings/settingStore'
22 : import { api } from '@/scripts/api'
23 : import { parseAnnotatedPath } from '@/utils/createAnnotatedPath'
24 :
25 : type Load3DConfigurationSettings = {
26 : loadFolder: string
27 : modelWidget: IBaseWidget
28 : cameraState?: CameraState
29 : width?: INumericWidget
30 : height?: INumericWidget
31 : bgImagePath?: string
32 : silentOnNotFound?: boolean
33 : /**
34 : * Called when any change to one of the wired widgets (model_file, width,
35 : * height), local or remote, makes the previously captured scene stale.
36 : * Backend caching covers these inputs by themselves; this hook lets the
37 : * caller invalidate any frontend-side capture cache so the next serialize
38 : * re-renders at the new state.
39 : */
40 : onSceneInvalidated?: () => void
41 : }
42 :
43 24 : const DEFAULT_GIZMO: GizmoConfig = {
44 : enabled: false,
45 : mode: 'translate',
46 : position: { x: 0, y: 0, z: 0 },
47 : rotation: { x: 0, y: 0, z: 0 },
48 : scale: { x: 1, y: 1, z: 1 }
49 : }
50 :
51 24 : class Load3DConfiguration {
52 : constructor(
53 28 : private load3d: Load3d,
54 28 : private properties?: Dictionary<NodeProperty | undefined>
55 : ) {}
56 :
57 : configureForSaveMesh(
58 : loadFolder: 'input' | 'output' | 'temp',
59 : filePath: string,
60 : options?: { silentOnNotFound?: boolean }
61 : ) {
62 0 : this.setupModelHandlingForSaveMesh(
63 : filePath,
64 : loadFolder,
65 : options?.silentOnNotFound ?? false
66 : )
67 0 : this.setupDefaultProperties()
68 : }
69 :
70 : configure(setting: Load3DConfigurationSettings) {
71 25 : const onModelWidgetUpdate = this.setupModelHandling(
72 : setting.modelWidget,
73 : setting.loadFolder,
74 : setting.cameraState,
75 : setting.silentOnNotFound ?? false
76 : )
77 25 : this.setupTargetSize(setting.width, setting.height)
78 25 : this.setupReactiveHandling(setting, onModelWidgetUpdate)
79 25 : this.setupDefaultProperties(setting.bgImagePath)
80 : }
81 :
82 : private setupReactiveHandling(
83 : setting: Load3DConfigurationSettings,
84 : onModelWidgetUpdate: (value: IBaseWidget['value']) => Promise<void>
85 : ): void {
86 25 : const scope = effectScope()
87 25 : scope.run(() => {
88 25 : watch(
89 : () => setting.modelWidget.value,
90 : (value) => {
91 8 : void onModelWidgetUpdate(value)
92 8 : setting.onSceneInvalidated?.()
93 : },
94 : { flush: 'sync' }
95 : )
96 :
97 25 : const { width, height } = setting
98 25 : if (width && height) {
99 21 : watch(
100 : [() => width.value, () => height.value],
101 : ([nextWidth, nextHeight]) => {
102 0 : this.load3d.setTargetSize(nextWidth, nextHeight)
103 0 : setting.onSceneInvalidated?.()
104 : },
105 : { flush: 'sync' }
106 : )
107 : }
108 : })
109 25 : this.load3d.setConfigurationCleanup(() => scope.stop())
110 : }
111 :
112 : private setupTargetSize(width?: INumericWidget, height?: INumericWidget) {
113 25 : if (width && height) {
114 21 : this.load3d.setTargetSize(width.value, height.value)
115 : }
116 : }
117 :
118 : private setupModelHandlingForSaveMesh(
119 : filePath: string,
120 : loadFolder: 'input' | 'output' | 'temp',
121 : silentOnNotFound: boolean
122 : ) {
123 0 : const onModelWidgetUpdate = this.createModelUpdateHandler(
124 : loadFolder,
125 : undefined,
126 : silentOnNotFound
127 : )
128 :
129 0 : if (filePath) {
130 0 : void onModelWidgetUpdate(filePath, isKeepingLoadedModel(this.load3d))
131 : }
132 : }
133 :
134 : private setupModelHandling(
135 : modelWidget: IBaseWidget,
136 : loadFolder: string,
137 : cameraState?: CameraState,
138 : silentOnNotFound: boolean = false
139 : ) {
140 25 : const onModelWidgetUpdate = this.createModelUpdateHandler(
141 : loadFolder,
142 : cameraState,
143 : silentOnNotFound
144 : )
145 25 : if (modelWidget.value && modelWidget.value !== LOAD3D_NONE_MODEL) {
146 5 : void onModelWidgetUpdate(
147 : modelWidget.value,
148 : isKeepingLoadedModel(this.load3d)
149 : )
150 20 : } else if (isKeepingLoadedModel(this.load3d)) {
151 0 : this.load3d.clearModel()
152 : }
153 :
154 25 : return onModelWidgetUpdate
155 : }
156 :
157 : private setupDefaultProperties(bgImagePath?: string) {
158 25 : const sceneConfig = this.loadSceneConfig()
159 25 : this.applySceneConfig(sceneConfig, bgImagePath)
160 :
161 25 : const cameraConfig = this.loadCameraConfig()
162 25 : this.applyCameraConfig(cameraConfig)
163 :
164 25 : const lightConfig = this.loadLightConfig()
165 25 : this.applyLightConfig(lightConfig)
166 25 : if (lightConfig.hdri) this.applyHDRISettings(lightConfig.hdri)
167 : }
168 :
169 : private loadSceneConfig(): SceneConfig {
170 25 : if (this.properties && 'Scene Config' in this.properties) {
171 2 : return this.properties['Scene Config'] as SceneConfig
172 : }
173 :
174 23 : return {
175 : showGrid: useSettingStore().get('Comfy.Load3D.ShowGrid'),
176 : backgroundColor:
177 : '#' + useSettingStore().get('Comfy.Load3D.BackgroundColor'),
178 : backgroundImage: ''
179 : }
180 : }
181 :
182 : private loadCameraConfig(): CameraConfig {
183 25 : if (this.properties && 'Camera Config' in this.properties) {
184 2 : return this.properties['Camera Config'] as CameraConfig
185 : }
186 :
187 23 : return {
188 : cameraType: useSettingStore().get('Comfy.Load3D.CameraType'),
189 : fov: 35
190 : }
191 : }
192 :
193 : private loadLightConfig(): LightConfig {
194 25 : const hdriDefaults: HDRIConfig = {
195 : enabled: false,
196 : hdriPath: '',
197 : showAsBackground: false,
198 : intensity: 1
199 : }
200 :
201 25 : if (this.properties && 'Light Config' in this.properties) {
202 2 : const saved = this.properties['Light Config'] as Partial<LightConfig>
203 2 : return {
204 : intensity:
205 : saved.intensity ??
206 : useSettingStore().get('Comfy.Load3D.LightIntensity'),
207 : hdri: { ...hdriDefaults, ...saved.hdri }
208 : }
209 : }
210 :
211 23 : return {
212 : intensity: useSettingStore().get('Comfy.Load3D.LightIntensity'),
213 : hdri: hdriDefaults
214 : }
215 : }
216 :
217 : private loadModelConfig(): ModelConfig {
218 10 : const stored = this.properties?.['Model Config'] as
219 : | StoredModelConfig
220 : | undefined
221 10 : const config: ModelConfig = {
222 : upDirection: 'original',
223 : materialMode: 'original',
224 : showSkeleton: false,
225 : ...stored,
226 : gizmo: { ...DEFAULT_GIZMO, ...stored?.gizmo }
227 : }
228 10 : if (stored) stored.gizmo = config.gizmo
229 10 : return config
230 : }
231 :
232 : private applySceneConfig(config: SceneConfig, bgImagePath?: string) {
233 25 : this.load3d.toggleGrid(config.showGrid)
234 25 : this.load3d.setBackgroundColor(config.backgroundColor)
235 25 : if (config.backgroundImage) {
236 0 : if (bgImagePath && bgImagePath != config.backgroundImage) {
237 0 : return
238 : }
239 :
240 0 : void this.load3d.setBackgroundImage(config.backgroundImage)
241 :
242 0 : if (config.backgroundRenderMode) {
243 0 : this.load3d.setBackgroundRenderMode(config.backgroundRenderMode)
244 : }
245 : }
246 : }
247 :
248 : private applyCameraConfig(config: CameraConfig) {
249 25 : this.load3d.toggleCamera(config.cameraType)
250 25 : this.load3d.setFOV(config.fov)
251 :
252 25 : if (config.state) {
253 2 : this.load3d.setCameraState(config.state)
254 : }
255 : }
256 :
257 : private applyLightConfig(config: LightConfig) {
258 25 : this.load3d.setLightIntensity(config.intensity)
259 : }
260 :
261 : private applyHDRISettings(config: HDRIConfig) {
262 25 : if (!config.hdriPath) return
263 0 : this.load3d.setHDRIIntensity(config.intensity)
264 0 : this.load3d.setHDRIAsBackground(config.showAsBackground)
265 0 : if (config.enabled) {
266 0 : this.load3d.setHDRIEnabled(true)
267 : }
268 : }
269 :
270 : private applyModelConfig(config: ModelConfig) {
271 10 : this.load3d.setUpDirection(config.upDirection)
272 10 : this.load3d.setMaterialMode(config.materialMode)
273 : }
274 :
275 : private createModelUpdateHandler(
276 : loadFolder: string,
277 : cameraState?: CameraState,
278 : silentOnNotFound: boolean = false
279 : ) {
280 25 : let isFirstLoad = true
281 25 : return async (value: IBaseWidget['value'], keepLoadedModel = false) => {
282 13 : if (!value || value === LOAD3D_NONE_MODEL) {
283 1 : this.load3d.clearModel()
284 1 : return
285 : }
286 :
287 12 : const { filepath: filename, rootFolder: folder } = parseAnnotatedPath(
288 : value as string,
289 : loadFolder
290 : )
291 :
292 12 : this.setResourceFolder(filename)
293 :
294 12 : const modelUrl = api.apiURL(
295 : Load3dUtils.getResourceURL(
296 : ...Load3dUtils.splitFilePath(filename),
297 : folder
298 : )
299 : )
300 :
301 13 : if (keepLoadedModel && this.isShowingModel(modelUrl)) {
302 0 : isFirstLoad = false
303 0 : return
304 : }
305 :
306 12 : const outcome = await this.load3d.loadModel(modelUrl, filename)
307 12 : reportLoadModelOutcome(outcome, { silentOnNotFound })
308 13 : if (outcome !== 'loaded') return
309 :
310 10 : const modelConfig = this.loadModelConfig()
311 10 : this.applyModelConfig(modelConfig)
312 :
313 13 : if (isFirstLoad && cameraState) {
314 2 : try {
315 2 : this.load3d.setCameraState(cameraState)
316 : } catch (error) {
317 0 : console.warn('Failed to restore camera state:', error)
318 : }
319 2 : isFirstLoad = false
320 : }
321 :
322 10 : this.load3d.emitModelReady()
323 : }
324 : }
325 :
326 : private isShowingModel(modelUrl: string): boolean {
327 0 : const { currentModel, originalURL } = this.load3d.modelManager
328 0 : return (
329 : currentModel !== null &&
330 : Load3dUtils.isSameResourceURL(originalURL, modelUrl)
331 : )
332 : }
333 :
334 : private setResourceFolder(filename: string): void {
335 12 : const pathParts = filename.split('/').filter((part) => part.trim())
336 :
337 12 : if (pathParts.length <= 2) {
338 12 : return
339 : }
340 :
341 : const subfolderParts = pathParts.slice(1, -1)
342 0 : const subfolder = subfolderParts.join('/')
343 :
344 12 : if (subfolder && this.properties) {
345 0 : this.properties['Resource Folder'] = subfolder
346 : }
347 : }
348 : }
349 :
350 : export default Load3DConfiguration
|