-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathImportMirabufPanel.tsx
More file actions
515 lines (472 loc) · 20.3 KB
/
Copy pathImportMirabufPanel.tsx
File metadata and controls
515 lines (472 loc) · 20.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
import React, { ReactNode, useCallback, useEffect, useLayoutEffect, useMemo, useState } from "react"
import { LabelSize } from "@/components/Label"
import {
Data,
getMirabufFiles,
hasMirabufFiles,
MirabufFilesStatusUpdateEvent,
MirabufFilesUpdateEvent,
requestMirabufFiles,
} from "@/aps/APSDataManagement"
import MirabufCachingService, {
backUpFields,
backUpRobots,
canOPFS,
MirabufCacheInfo,
MirabufRemoteInfo,
MiraType,
} from "@/mirabuf/MirabufLoader"
import World from "@/systems/World"
import { useTooltipControlContext } from "@/ui/TooltipContext"
import { createMirabuf } from "@/mirabuf/MirabufSceneObject"
import { Box } from "@mui/material"
import { ToggleButton, ToggleButtonGroup } from "@/ui/components/ToggleButtonGroup"
import { usePanelControlContext } from "@/ui/helpers/UsePanelManager"
import { useModalControlContext } from "@/ui/helpers/UseModalManager"
import TaskStatus from "@/util/TaskStatus"
import {
DeleteButton,
PositiveButton,
RefreshButton,
SectionDivider,
SectionLabel,
SynthesisIcons,
} from "@/ui/components/StyledComponents"
import { ProgressHandle } from "@/ui/components/ProgressNotificationData"
import Panel, { PanelPropsImpl } from "@/ui/components/Panel"
import Button from "@/ui/components/Button"
import { globalAddToast, globalOpenPanel } from "@/ui/components/GlobalUIControls"
import { PAUSE_REF_ASSEMBLY_SPAWNING } from "@/systems/physics/PhysicsSystem"
import { mirabufPanelState } from "@/panels/mirabuf/MirabufState.tsx"
import { SoundPlayer } from "@/systems/sound/SoundPlayer"
interface ItemCardProps {
id: string
name: string
primaryButtonNode: ReactNode
primaryOnClick: () => void
secondaryOnClick?: () => void
}
const ItemCard: React.FC<ItemCardProps> = ({ id, name, primaryButtonNode, primaryOnClick, secondaryOnClick }) => {
return (
<Box
component={"div"}
display={"flex"}
key={id}
justifyContent={"space-between"}
alignItems={"center"}
gap={"1rem"}
>
<SectionLabel className="text-wrap break-all">{name.replace(/.mira$/, "")}</SectionLabel>
<Box
component={"div"}
display={"flex"}
key={`button-box-${id}`}
flexDirection={"row-reverse"}
gap={"0.25rem"}
justifyContent={"center"}
alignItems={"center"}
>
<PositiveButton value={primaryButtonNode} onClick={primaryOnClick} />
{secondaryOnClick && DeleteButton(secondaryOnClick)}
</Box>
</Box>
)
}
export type MiraManifest = {
robots: MirabufRemoteInfo[]
fields: MirabufRemoteInfo[]
}
function getCacheInfo(miraType: MiraType): MirabufCacheInfo[] {
return Object.values(
canOPFS ? MirabufCachingService.getCacheMap(miraType) : miraType == MiraType.ROBOT ? backUpRobots : backUpFields
)
}
function spawnCachedMira(info: MirabufCacheInfo, type: MiraType, progressHandle?: ProgressHandle) {
// If spawning a field, then remove all other fields
if (type == MiraType.FIELD) {
World.sceneRenderer.removeAllFields()
}
if (!progressHandle) {
progressHandle = new ProgressHandle(info.name ?? info.cacheKey)
}
World.physicsSystem.holdPause(PAUSE_REF_ASSEMBLY_SPAWNING)
MirabufCachingService.get(info.id, type)
.then(assembly => {
if (assembly) {
createMirabuf(assembly).then(x => {
if (x) {
World.sceneRenderer.registerSceneObject(x)
progressHandle.done()
globalOpenPanel("initial-config")
} else {
progressHandle.fail()
}
})
if (!info.name) MirabufCachingService.cacheInfo(info.cacheKey, type, assembly.info?.name ?? undefined)
} else {
progressHandle.fail()
console.error("Failed to spawn robot")
}
})
.catch(() => progressHandle.fail())
.finally(() => {
setTimeout(() => World.physicsSystem.releasePause(PAUSE_REF_ASSEMBLY_SPAWNING), 500)
})
}
const ImportMirabufPanel: React.FC<PanelPropsImpl> = ({ panelId }) => {
const { showTooltip } = useTooltipControlContext()
const { closePanel } = usePanelControlContext()
const { openModal } = useModalControlContext()
const [cachedRobots, setCachedRobots] = useState(getCacheInfo(MiraType.ROBOT))
const [cachedFields, setCachedFields] = useState(getCacheInfo(MiraType.FIELD))
const [manifest, setManifest] = useState<MiraManifest | undefined>()
const [viewType, setViewType] = useState<MiraType>(MiraType.ROBOT)
const [filesStatus, setFilesStatus] = useState<TaskStatus>({ isDone: false, message: "Waiting on APS..." })
const [files, setFiles] = useState<Data[] | undefined>(undefined)
useEffect(() => {
const updateFilesStatus = (e: Event) => {
setFilesStatus((e as MirabufFilesStatusUpdateEvent).status)
}
const updateFiles = (e: Event) => {
setFiles((e as MirabufFilesUpdateEvent).data)
}
window.addEventListener(MirabufFilesStatusUpdateEvent.EVENT_KEY, updateFilesStatus)
window.addEventListener(MirabufFilesUpdateEvent.EVENT_KEY, updateFiles)
return () => {
window.removeEventListener(MirabufFilesStatusUpdateEvent.EVENT_KEY, updateFilesStatus)
window.removeEventListener(MirabufFilesUpdateEvent.EVENT_KEY, updateFiles)
}
})
useEffect(() => {
if (!hasMirabufFiles()) {
requestMirabufFiles()
} else {
setFiles(getMirabufFiles())
}
}, [])
useLayoutEffect(() => {
if (mirabufPanelState.hasUnconfirmedImport) {
closePanel("import-mirabuf")
globalAddToast("warning", "You're already importing a model!", "Confirm that one before importing another.")
return
}
closePanel("configure")
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
// Get Default Mirabuf Data, Load into manifest.
useEffect(() => {
// To remove the prettier warning
const x = async () => {
fetch(`/api/mira/manifest.json`)
.then(x => x.json())
.then(x => {
const map = MirabufCachingService.getCacheMap(MiraType.ROBOT)
const robots: MirabufRemoteInfo[] = []
for (const src of x["robots"]) {
if (typeof src == "string") {
const str = `/api/mira/robots/${src}`
if (!map[str]) robots.push({ displayName: src, src: str })
} else {
if (!map[src["src"]]) robots.push({ displayName: src["displayName"], src: src["src"] })
}
}
const fields: MirabufRemoteInfo[] = []
for (const src of x["fields"]) {
if (typeof src == "string") {
const str = `/api/mira/fields/${src}`
if (!map[str]) fields.push({ displayName: src, src: str })
} else {
if (!map[src["src"]]) fields.push({ displayName: src["displayName"], src: src["src"] })
}
}
setManifest({
robots,
fields,
})
})
}
x()
}, [])
// Select a mirabuf assembly from the cache.
const selectCache = useCallback(
(info: MirabufCacheInfo, type: MiraType) => {
spawnCachedMira(info, type)
showTooltip("controls", [
{ control: "WASD", description: "Drive" },
{ control: "E", description: "Intake" },
{ control: "Q", description: "Dispense" },
])
closePanel(panelId)
},
[showTooltip, closePanel, panelId]
)
// Cache a selected remote mirabuf assembly, load from cache.
const selectRemote = useCallback(
(info: MirabufRemoteInfo, type: MiraType) => {
const status = new ProgressHandle(info.displayName)
status.update("Downloading from Synthesis...", 0.05)
MirabufCachingService.cacheRemote(info.src, type)
.then(cacheInfo => {
if (cacheInfo) {
spawnCachedMira(cacheInfo, type, status)
} else {
status.fail("Failed to cache")
}
})
.catch(() => status.fail())
closePanel(panelId)
},
[closePanel, panelId]
)
// Cache a selected remote mirabuf assembly, without load.
const cacheRemoteOnly = useCallback((info: MirabufRemoteInfo, type: MiraType) => {
const status = new ProgressHandle(info.displayName)
status.update("Downloading from Synthesis...", 0.05)
MirabufCachingService.cacheRemote(info.src, type)
.then(cacheInfo => {
if (cacheInfo) {
status.done()
} else {
status.fail("Failed to cache")
}
})
.catch(() => status.fail())
}, [])
const selectAPS = useCallback(
(data: Data, type: MiraType) => {
const status = new ProgressHandle(data.attributes.displayName ?? data.id)
status.update("Downloading from APS...", 0.05)
MirabufCachingService.cacheAPS(data, type)
.then(cacheInfo => {
if (cacheInfo) {
spawnCachedMira(cacheInfo, type, status)
} else {
status.fail("Failed to cache")
}
})
.catch(() => status.fail())
closePanel(panelId)
},
[closePanel, panelId]
)
// Generate Item cards for cached robots.
const cachedRobotElements = useMemo(
() =>
cachedRobots
.sort((a, b) => a.name?.localeCompare(b.name ?? "") ?? -1)
.map(info =>
ItemCard({
name: info.name || info.cacheKey || "Unnamed Robot",
id: info.id,
primaryButtonNode: SynthesisIcons.ADD_LARGE,
primaryOnClick: () => {
console.log(`Selecting cached robot: ${info.cacheKey}`)
selectCache(info, MiraType.ROBOT)
},
secondaryOnClick: () => {
console.log(`Deleting cache of: ${info.cacheKey}`)
MirabufCachingService.remove(info.cacheKey, info.id, MiraType.ROBOT)
setCachedRobots(getCacheInfo(MiraType.ROBOT))
},
})
),
[cachedRobots, selectCache, setCachedRobots]
)
// Generate Item cards for cached fields.
const cachedFieldElements = useMemo(
() =>
cachedFields
.sort((a, b) => a.name?.localeCompare(b.name ?? "") ?? -1)
.map(info =>
ItemCard({
name: info.name || info.cacheKey || "Unnamed Field",
id: info.id,
primaryButtonNode: SynthesisIcons.ADD_LARGE,
primaryOnClick: () => {
console.log(`Selecting cached field: ${info.cacheKey}`)
selectCache(info, MiraType.FIELD)
},
secondaryOnClick: () => {
console.log(`Deleting cache of: ${info.cacheKey}`)
MirabufCachingService.remove(info.cacheKey, info.id, MiraType.FIELD)
setCachedFields(getCacheInfo(MiraType.FIELD))
},
})
),
[cachedFields, selectCache, setCachedFields]
)
// Generate Item cards for remote robots.
const remoteRobotElements = useMemo(() => {
const remoteRobots = manifest?.robots.filter(
path => !cachedRobots.some(info => info.cacheKey.includes(path.src))
)
return remoteRobots
?.sort((a, b) => a.displayName.localeCompare(b.displayName))
.map(path =>
ItemCard({
name: path.displayName,
id: path.src,
primaryButtonNode: SynthesisIcons.DOWNLOAD_LARGE,
primaryOnClick: () => {
console.log(`Selecting remote: ${path}`)
selectRemote(path, MiraType.ROBOT)
},
})
)
}, [manifest?.robots, cachedRobots, selectRemote])
// Generate Item cards for remote fields.
const remoteFieldElements = useMemo(() => {
const remoteFields = manifest?.fields.filter(
path => !cachedFields.some(info => info.cacheKey.includes(path.src))
)
return remoteFields
?.sort((a, b) => a.displayName.localeCompare(b.displayName))
.map(path =>
ItemCard({
name: path.displayName,
id: path.src,
primaryButtonNode: SynthesisIcons.DOWNLOAD_LARGE,
primaryOnClick: () => {
console.log(`Selecting remote: ${path}`)
selectRemote(path, MiraType.FIELD)
},
})
)
}, [manifest?.fields, cachedFields, selectRemote])
function downloadAllRemote(cached: MirabufCacheInfo[]): () => void {
// eslint-disable-next-line react-hooks/rules-of-hooks
return useCallback(() => {
const miraType: MiraType | undefined = cached[0]?.miraType
const property = miraType === MiraType.ROBOT ? "robots" : "fields"
const remotes = manifest ? manifest[property] : []
remotes
.filter(path => !cached.some(info => info.cacheKey.includes(path.src)))
.forEach(path => cacheRemoteOnly(path, miraType))
closePanel(panelId)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [manifest, cached, cacheRemoteOnly, closePanel, panelId])
}
const downloadAllRemoteRobots = downloadAllRemote(cachedRobots)
const downloadAllRemoteFields = downloadAllRemote(cachedFields)
// Generate Item cards for APS robots and fields.
const hubElements = useMemo(
() =>
files
?.sort((a, b) => a.attributes.displayName!.localeCompare(b.attributes.displayName!))
.map(file =>
ItemCard({
name: `${file.attributes.displayName!.replace(".mira", "")}${file.attributes.versionNumber != undefined ? ` (v${file.attributes.versionNumber})` : ""}`,
id: file.id,
primaryButtonNode: SynthesisIcons.DOWNLOAD_LARGE,
primaryOnClick: () => {
console.debug(file.raw)
selectAPS(file, viewType)
},
})
),
[files, selectAPS, viewType]
)
useEffect(() => {
setViewType(mirabufPanelState.currentMode)
mirabufPanelState.currentMode = mirabufPanelState.defaultMode
}, [])
return (
<Panel
name={"Spawn Asset"}
icon={SynthesisIcons.ADD_LARGE}
panelId={panelId}
acceptEnabled={false}
cancelName="Back"
openLocation="right"
>
<div className="flex overflow-y-auto flex-col gap-2 bg-background-secondary rounded-md p-2">
<ToggleButtonGroup
value={viewType}
exclusive
onChange={(_, v) => {
if (v != null) {
setViewType(v)
}
}}
{...SoundPlayer.buttonSoundEffects()}
sx={{
alignSelf: "center",
}}
>
<ToggleButton value={MiraType.ROBOT}>Robots</ToggleButton>
<ToggleButton value={MiraType.FIELD}>Fields</ToggleButton>
</ToggleButtonGroup>
{viewType == MiraType.ROBOT ? (
<>
<SectionLabel size={LabelSize.MEDIUM} className="text-center mt-[4pt] mb-[2pt] mx-[5%]">
{cachedRobotElements
? `${cachedRobotElements.length} Saved Robot${cachedRobotElements.length == 1 ? "" : "s"}`
: "Loading Saved Robots"}
</SectionLabel>
<SectionDivider />
{cachedRobotElements}
</>
) : (
<>
<SectionLabel size={LabelSize.MEDIUM} className="text-center mt-[4pt] mb-[2pt] mx-[5%]">
{cachedFieldElements
? `${cachedFieldElements.length} Saved Field${cachedFieldElements.length == 1 ? "" : "s"}`
: "Loading Saved Fields"}
</SectionLabel>
<SectionDivider />
{cachedFieldElements}
</>
)}
<Box
component={"div"}
display={"flex"}
key={`remote-label-container`}
flexDirection={"row"}
gap={"0.25rem"}
justifyContent={"center"}
alignItems={"center"}
>
<SectionLabel size={LabelSize.MEDIUM} className="text-center mt-[4pt] mb-[2pt] mx-[5%]">
{hubElements
? `${hubElements.length} Remote Asset${hubElements.length == 1 ? "" : "s"}`
: filesStatus.message}
</SectionLabel>
{hubElements && filesStatus.isDone ? RefreshButton(() => requestMirabufFiles()) : <></>}
</Box>
<SectionDivider />
{hubElements}
{viewType == MiraType.ROBOT ? (
<>
<SectionLabel size={LabelSize.MEDIUM} className="text-center mt-[4pt] mb-[2pt] mx-[5%]">
{remoteRobotElements
? `${remoteRobotElements.length} Default Robot${remoteRobotElements.length == 1 ? "" : "s"}`
: "Loading Default Robots"}
</SectionLabel>
<SectionDivider />
{remoteRobotElements}
<Box display="flex" justifyContent="center" mt={1}>
<PositiveButton value="Download All" onClick={downloadAllRemoteRobots} />
</Box>
</>
) : (
<>
<SectionLabel size={LabelSize.MEDIUM} className="text-center mt-[4pt] mb-[2pt] mx-[5%]">
{remoteFieldElements
? `${remoteFieldElements.length} Default Field${remoteFieldElements.length == 1 ? "" : "s"}`
: "Loading Default Fields"}
</SectionLabel>
<SectionDivider />
{remoteFieldElements}
<Box display="flex" justifyContent="center" mt={1}>
<PositiveButton value="Download All" onClick={downloadAllRemoteFields} />
</Box>
</>
)}
<Box alignSelf={"center"}>
<Button value="Import from File" onClick={() => openModal("import-local-mirabuf")} />
</Box>
</div>
</Panel>
)
}
export default ImportMirabufPanel