castle-web-cli 0.4.238 → 0.4.240

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (404) hide show
  1. package/dist/agent.js +5 -1
  2. package/dist/api.d.ts +20 -0
  3. package/dist/api.js +57 -0
  4. package/dist/bundle.d.ts +38 -1
  5. package/dist/bundle.js +309 -13
  6. package/dist/castle-host/host.js +218 -11
  7. package/dist/castleJson.d.ts +10 -0
  8. package/dist/castleJson.js +46 -2
  9. package/dist/check.js +5 -2
  10. package/dist/devSessionServer.js +4 -1
  11. package/dist/devSessionStorage.d.ts +1 -0
  12. package/dist/devSessionStorage.js +32 -7
  13. package/dist/importOrder.d.ts +2 -0
  14. package/dist/importOrder.js +29 -0
  15. package/dist/index.js +22 -3
  16. package/dist/init.js +24 -2
  17. package/dist/multiplayerDoc.d.ts +1 -1
  18. package/dist/multiplayerDoc.js +9 -0
  19. package/dist/platformDoc.js +4 -2
  20. package/dist/playPagePolicy.d.ts +1 -0
  21. package/dist/playPagePolicy.js +12 -3
  22. package/dist/resetLeaderboards.d.ts +8 -1
  23. package/dist/resetLeaderboards.js +43 -8
  24. package/dist/roomLogs.d.ts +39 -0
  25. package/dist/roomLogs.js +166 -0
  26. package/dist/save-deck.d.ts +32 -2
  27. package/dist/save-deck.js +240 -39
  28. package/kits/base/CLAUDE.md +2 -1
  29. package/kits/base/castle.json +1 -1
  30. package/kits/base/sdk/README.md +240 -8
  31. package/kits/base/sdk/analytics.d.ts +8 -0
  32. package/kits/base/sdk/analytics.js +92 -0
  33. package/kits/base/sdk/castle.d.ts +8 -2
  34. package/kits/base/sdk/castle.js +3 -0
  35. package/kits/base/sdk/commands.d.ts +79 -0
  36. package/kits/base/sdk/commands.js +1 -0
  37. package/kits/base/sdk/debugConsole.d.ts +17 -0
  38. package/kits/base/sdk/debugConsole.js +154 -0
  39. package/kits/base/sdk/experiments.js +24 -1
  40. package/kits/base/sdk/hostRetry.d.ts +7 -0
  41. package/kits/base/sdk/hostRetry.js +57 -0
  42. package/kits/base/sdk/hub.d.ts +20 -2
  43. package/kits/base/sdk/hub.js +99 -13
  44. package/kits/base/sdk/multiplayer.d.ts +2 -0
  45. package/kits/base/sdk/multiplayer.js +198 -26
  46. package/kits/base/sdk/reconnectBudget.d.ts +6 -0
  47. package/kits/base/sdk/reconnectBudget.js +41 -1
  48. package/kits/base/sdk/rooms.d.ts +11 -0
  49. package/kits/base/sdk/rooms.js +22 -0
  50. package/kits/base/sdk/runtime.js +36 -19
  51. package/kits/base/sdk/server/hub.d.ts +19 -0
  52. package/kits/base/sdk/server/hub.js +12 -0
  53. package/kits/base/sdk/server/platformHandle.d.ts +1 -0
  54. package/kits/base/sdk/server/wrapper.d.ts +1 -1
  55. package/kits/base/sdk/server/wrapper.js +26 -1
  56. package/kits/base/sdk/store.d.ts +8 -2
  57. package/kits/base/sdk/store.js +5 -1
  58. package/kits/base/sdk/transport.d.ts +2 -1
  59. package/kits/base/sdk/transport.js +35 -0
  60. package/kits/hub-game/CLAUDE.md +66 -19
  61. package/kits/hub-game/castle.json +4 -4
  62. package/kits/hub-game/code/client/act.js +9 -6
  63. package/kits/hub-game/code/client/actCore.js +26 -6
  64. package/kits/hub-game/code/client/actGateLog.js +36 -0
  65. package/kits/hub-game/code/client/actionOverflow.js +29 -8
  66. package/kits/hub-game/code/client/actionRailSurface.js +186 -0
  67. package/kits/hub-game/code/client/actionRailTree.js +173 -0
  68. package/kits/hub-game/code/client/askSurface.js +85 -0
  69. package/kits/hub-game/code/client/askTree.js +51 -0
  70. package/kits/hub-game/code/client/attention.js +31 -6
  71. package/kits/hub-game/code/client/ballot.js +42 -5
  72. package/kits/hub-game/code/client/ballotSurface.js +115 -0
  73. package/kits/hub-game/code/client/ballotTree.js +180 -0
  74. package/kits/hub-game/code/client/catchingUp.js +19 -0
  75. package/kits/hub-game/code/client/celebrate.js +66 -0
  76. package/kits/hub-game/code/client/chrome.js +474 -53
  77. package/kits/hub-game/code/client/companion.js +93 -23
  78. package/kits/hub-game/code/client/companionDress.js +1 -1
  79. package/kits/hub-game/code/client/cornerSurface.js +106 -0
  80. package/kits/hub-game/code/client/cornerTree.js +83 -0
  81. package/kits/hub-game/code/client/decor.js +20 -11
  82. package/kits/hub-game/code/client/deviceStorage.js +121 -0
  83. package/kits/hub-game/code/client/disguise.js +23 -0
  84. package/kits/hub-game/code/client/disguiseDraw.js +87 -0
  85. package/kits/hub-game/code/client/dockSurface.js +206 -0
  86. package/kits/hub-game/code/client/dockTree.js +232 -0
  87. package/kits/hub-game/code/client/earned.js +29 -0
  88. package/kits/hub-game/code/client/emoteSurface.js +188 -0
  89. package/kits/hub-game/code/client/emoteTree.js +264 -0
  90. package/kits/hub-game/code/client/farAvatars.js +4 -3
  91. package/kits/hub-game/code/client/fpsTelemetry.js +3 -1
  92. package/kits/hub-game/code/client/grab.js +121 -50
  93. package/kits/hub-game/code/client/holdShow.js +19 -0
  94. package/kits/hub-game/code/client/hookLayer.js +96 -12
  95. package/kits/hub-game/code/client/hubControls.js +7 -1
  96. package/kits/hub-game/code/client/hudSurface.js +11 -3
  97. package/kits/hub-game/code/client/hudTree.js +7 -4
  98. package/kits/hub-game/code/client/idle.js +21 -3
  99. package/kits/hub-game/code/client/invites.js +24 -3
  100. package/kits/hub-game/code/client/keys.js +15 -0
  101. package/kits/hub-game/code/client/labelsNear.js +8 -1
  102. package/kits/hub-game/code/client/layoutCache.js +57 -8
  103. package/kits/hub-game/code/client/loadingCover.js +53 -4
  104. package/kits/hub-game/code/client/menuIcons.js +15 -0
  105. package/kits/hub-game/code/client/menuRows.js +8 -2
  106. package/kits/hub-game/code/client/menuSurface.js +102 -0
  107. package/kits/hub-game/code/client/menuTree.js +135 -0
  108. package/kits/hub-game/code/client/modelLook.js +41 -0
  109. package/kits/hub-game/code/client/pickerSurface.js +152 -0
  110. package/kits/hub-game/code/client/pickerTree.js +163 -0
  111. package/kits/hub-game/code/client/pushVisit.js +4 -2
  112. package/kits/hub-game/code/client/quality.js +188 -29
  113. package/kits/hub-game/code/client/qualityEntry.js +10 -1
  114. package/kits/hub-game/code/client/quickChatSurface.js +222 -0
  115. package/kits/hub-game/code/client/quickChatTree.js +201 -0
  116. package/kits/hub-game/code/client/rehello.js +75 -0
  117. package/kits/hub-game/code/client/renderVisibility.js +17 -0
  118. package/kits/hub-game/code/client/replay.js +118 -0
  119. package/kits/hub-game/code/client/role.js +3 -0
  120. package/kits/hub-game/code/client/safeLayout.js +441 -56
  121. package/kits/hub-game/code/client/safeStyle.js +13 -10
  122. package/kits/hub-game/code/client/say.js +2 -0
  123. package/kits/hub-game/code/client/soundSurface.js +77 -0
  124. package/kits/hub-game/code/client/soundTree.js +74 -0
  125. package/kits/hub-game/code/client/soundscape.js +12 -9
  126. package/kits/hub-game/code/client/soundscapeCues.js +1 -1
  127. package/kits/hub-game/code/client/state.js +67 -1
  128. package/kits/hub-game/code/client/stuckSurface.js +76 -0
  129. package/kits/hub-game/code/client/stuckTree.js +67 -0
  130. package/kits/hub-game/code/client/talk.js +42 -12
  131. package/kits/hub-game/code/client/talkTree.js +4 -2
  132. package/kits/hub-game/code/client/textAskSurface.js +147 -0
  133. package/kits/hub-game/code/client/textAskTree.js +67 -0
  134. package/kits/hub-game/code/client/tiers.js +252 -27
  135. package/kits/hub-game/code/client/together.js +4 -1
  136. package/kits/hub-game/code/client/uiDom.js +86 -8
  137. package/kits/hub-game/code/client/uiTree.js +33 -4
  138. package/kits/hub-game/code/client/vehicle.js +75 -52
  139. package/kits/hub-game/code/client/weakestTier.js +75 -31
  140. package/kits/hub-game/code/client/wear.js +159 -5
  141. package/kits/hub-game/code/client/worldLabels.js +215 -26
  142. package/kits/hub-game/code/companionSpec.js +4 -2
  143. package/kits/hub-game/code/server/act.js +3 -0
  144. package/kits/hub-game/code/server/actGate.js +83 -0
  145. package/kits/hub-game/code/server/actions.js +71 -15
  146. package/kits/hub-game/code/server/actors.js +20 -5
  147. package/kits/hub-game/code/server/analytics.js +40 -15
  148. package/kits/hub-game/code/server/ask.js +39 -3
  149. package/kits/hub-game/code/server/ballot.js +167 -4
  150. package/kits/hub-game/code/server/celebrate.js +64 -0
  151. package/kits/hub-game/code/server/companion.js +17 -2
  152. package/kits/hub-game/code/server/decor.js +11 -2
  153. package/kits/hub-game/code/server/disguise.js +63 -0
  154. package/kits/hub-game/code/server/doorAnalytics.js +2 -5
  155. package/kits/hub-game/code/server/earned.js +6 -2
  156. package/kits/hub-game/code/server/friendBests.js +13 -4
  157. package/kits/hub-game/code/server/friendsAmong.js +67 -8
  158. package/kits/hub-game/code/server/grab.js +12 -2
  159. package/kits/hub-game/code/server/heldOffers.js +142 -0
  160. package/kits/hub-game/code/server/holdShow.js +98 -0
  161. package/kits/hub-game/code/server/hub.js +854 -45
  162. package/kits/hub-game/code/server/idle.js +110 -9
  163. package/kits/hub-game/code/server/index.js +9 -0
  164. package/kits/hub-game/code/server/labels.js +13 -3
  165. package/kits/hub-game/code/server/loadAbandon.js +2 -5
  166. package/kits/hub-game/code/server/manifest.js +94 -6
  167. package/kits/hub-game/code/server/menu.js +26 -3
  168. package/kits/hub-game/code/server/npcs.js +55 -9
  169. package/kits/hub-game/code/server/observe.js +67 -6
  170. package/kits/hub-game/code/server/players.js +8 -1
  171. package/kits/hub-game/code/server/replay.js +135 -0
  172. package/kits/hub-game/code/server/storageLimit.js +4 -1
  173. package/kits/hub-game/code/server/townDay.js +74 -0
  174. package/kits/hub-game/code/server/trackQueue.js +29 -0
  175. package/kits/hub-game/code/server/vehicle.js +3 -0
  176. package/kits/hub-game/code/server/vis.js +26 -4
  177. package/kits/hub-game/code/server/wallet.js +677 -0
  178. package/kits/hub-game/code/server/wear.js +13 -3
  179. package/kits/hub-game/code/server/writerLease.js +191 -0
  180. package/kits/hub-game/code/shared/act.js +1 -1
  181. package/kits/hub-game/code/shared/expression.js +6 -0
  182. package/kits/hub-game/code/shared/replay.js +37 -0
  183. package/kits/hub-game/code/systems/hub.js +437 -57
  184. package/kits/hub-game/docs/analytics.md +20 -3
  185. package/kits/hub-game/docs/contract.md +942 -99
  186. package/kits/hub-game/docs/home-pieces.md +5 -6
  187. package/kits/hub-game/docs/observed-progress.md +49 -1
  188. package/kits/hub-game/docs/vehicle-preset.md +23 -0
  189. package/kits/hub-game/index.html +1 -0
  190. package/kits/hub-game/models/hats/baker-cap.pxmodel +3 -3
  191. package/kits/hub-game/models/hats/bat-clip.pxmodel +3 -3
  192. package/kits/hub-game/models/hats/beekeeper.pxmodel +3 -3
  193. package/kits/hub-game/models/hats/cap.pxmodel +3 -3
  194. package/kits/hub-game/models/hats/captain.pxmodel +3 -3
  195. package/kits/hub-game/models/hats/chef-toque.pxmodel +3 -3
  196. package/kits/hub-game/models/hats/crooked-top.pxmodel +3 -3
  197. package/kits/hub-game/models/hats/delivery-cap.pxmodel +3 -3
  198. package/kits/hub-game/models/hats/fire-helmet.pxmodel +3 -3
  199. package/kits/hub-game/models/hats/flower-crown.pxmodel +3 -3
  200. package/kits/hub-game/models/hats/foam-crown.pxmodel +3 -3
  201. package/kits/hub-game/models/hats/hard-hat.pxmodel +3 -3
  202. package/kits/hub-game/models/hats/lantern.pxmodel +3 -3
  203. package/kits/hub-game/models/hats/laurel.pxmodel +3 -3
  204. package/kits/hub-game/models/hats/lighthouse.pxmodel +3 -3
  205. package/kits/hub-game/models/hats/nurse-cap.pxmodel +3 -3
  206. package/kits/hub-game/models/hats/police-cap.pxmodel +3 -3
  207. package/kits/hub-game/models/hats/sailor.pxmodel +3 -3
  208. package/kits/hub-game/models/hats/souwester.pxmodel +3 -3
  209. package/kits/hub-game/models/hats/straw.pxmodel +3 -3
  210. package/kits/hub-game/models/hats/sunflower.pxmodel +3 -3
  211. package/kits/hub-game/models/hats/sweatband.pxmodel +3 -3
  212. package/kits/hub-game/models/hats/teacher-beret.pxmodel +3 -3
  213. package/kits/hub-game/models/hats/witch.pxmodel +3 -3
  214. package/kits/hub-game/models/hold-show/daisy.pxmodel +231 -0
  215. package/kits/hub-game/models/hold-show/moonflower.pxmodel +171 -0
  216. package/kits/hub-game/models/hold-show/rose.pxmodel +191 -0
  217. package/kits/hub-game/models/hold-show/square/daisy.pxmodel +233 -0
  218. package/kits/hub-game/models/hold-show/square/moonflower.pxmodel +173 -0
  219. package/kits/hub-game/models/hold-show/square/rose.pxmodel +193 -0
  220. package/kits/hub-game/models/hold-show/square/sunflower.pxmodel +313 -0
  221. package/kits/hub-game/models/hold-show/square/tulip.pxmodel +133 -0
  222. package/kits/hub-game/models/hold-show/sunflower.pxmodel +311 -0
  223. package/kits/hub-game/models/hold-show/tulip.pxmodel +131 -0
  224. package/kits/hub-game/package-lock.json +3 -3
  225. package/kits/hub-game/package.json +4 -3
  226. package/kits/hub-game/scripts/fixtures/engine-models-stub.mjs +1 -0
  227. package/kits/hub-game/scripts/fixtures/hud-surface.json +12 -12
  228. package/kits/hub-game/scripts/fixtures/talk-surface.json +8 -8
  229. package/kits/hub-game/scripts/gen-hats.mjs +1 -1
  230. package/kits/hub-game/scripts/gen-hold-show.mjs +27 -0
  231. package/kits/hub-game/scripts/pack.mjs +89 -23
  232. package/kits/hub-game/scripts/test-act-client.mjs +5 -0
  233. package/kits/hub-game/scripts/test-act-core.mjs +32 -0
  234. package/kits/hub-game/scripts/test-act-gate.mjs +186 -0
  235. package/kits/hub-game/scripts/test-action-rail-crowded-dom.mjs +7 -1
  236. package/kits/hub-game/scripts/test-action-rail-default-dom.mjs +102 -0
  237. package/kits/hub-game/scripts/test-action-rail-never-silent-dom.mjs +50 -0
  238. package/kits/hub-game/scripts/test-action-rail-surface.mjs +368 -0
  239. package/kits/hub-game/scripts/test-action-rail-town-jobs-dom.mjs +118 -0
  240. package/kits/hub-game/scripts/test-actions-client.mjs +5 -3
  241. package/kits/hub-game/scripts/test-actions.mjs +24 -0
  242. package/kits/hub-game/scripts/test-actors.mjs +19 -0
  243. package/kits/hub-game/scripts/test-again-corner-dom.mjs +59 -0
  244. package/kits/hub-game/scripts/test-analytics.mjs +80 -1
  245. package/kits/hub-game/scripts/test-arrival-pose-server.mjs +25 -8
  246. package/kits/hub-game/scripts/test-ask-client.mjs +9 -0
  247. package/kits/hub-game/scripts/test-ask-surface.mjs +188 -0
  248. package/kits/hub-game/scripts/test-attention.mjs +43 -1
  249. package/kits/hub-game/scripts/test-ballot-sheet-dom.mjs +71 -0
  250. package/kits/hub-game/scripts/test-ballot-surface.mjs +276 -0
  251. package/kits/hub-game/scripts/test-ballot.mjs +420 -3
  252. package/kits/hub-game/scripts/test-ban-join.mjs +1 -1
  253. package/kits/hub-game/scripts/test-celebrate-client.mjs +62 -0
  254. package/kits/hub-game/scripts/test-celebrate.mjs +116 -0
  255. package/kits/hub-game/scripts/test-chat.mjs +73 -0
  256. package/kits/hub-game/scripts/test-companion-client.mjs +203 -21
  257. package/kits/hub-game/scripts/test-companion.mjs +110 -3
  258. package/kits/hub-game/scripts/test-control-layout-dom.mjs +57 -10
  259. package/kits/hub-game/scripts/test-corner-surface.mjs +268 -0
  260. package/kits/hub-game/scripts/test-decor-client.mjs +59 -3
  261. package/kits/hub-game/scripts/test-decor.mjs +27 -0
  262. package/kits/hub-game/scripts/test-device-class.mjs +4 -1
  263. package/kits/hub-game/scripts/test-disguise-client.mjs +281 -0
  264. package/kits/hub-game/scripts/test-disguise.mjs +176 -0
  265. package/kits/hub-game/scripts/test-dock-surface.mjs +404 -0
  266. package/kits/hub-game/scripts/test-door-analytics.mjs +1 -1
  267. package/kits/hub-game/scripts/test-door-stay-client.mjs +602 -0
  268. package/kits/hub-game/scripts/test-door-stay.mjs +613 -0
  269. package/kits/hub-game/scripts/test-earned-client.mjs +119 -0
  270. package/kits/hub-game/scripts/test-emote-surface.mjs +616 -0
  271. package/kits/hub-game/scripts/test-fps-telemetry.mjs +39 -4
  272. package/kits/hub-game/scripts/test-friend-bests.mjs +38 -12
  273. package/kits/hub-game/scripts/test-ghost-click-dom.mjs +75 -0
  274. package/kits/hub-game/scripts/test-grab-client.mjs +29 -2
  275. package/kits/hub-game/scripts/test-grab-orbit.mjs +260 -11
  276. package/kits/hub-game/scripts/test-grab.mjs +10 -1
  277. package/kits/hub-game/scripts/test-hats.mjs +28 -0
  278. package/kits/hub-game/scripts/test-held-offers.mjs +394 -0
  279. package/kits/hub-game/scripts/test-high-only.mjs +3 -3
  280. package/kits/hub-game/scripts/test-hold-show-client.mjs +175 -0
  281. package/kits/hub-game/scripts/test-hold-show.mjs +355 -0
  282. package/kits/hub-game/scripts/test-hub-controls.mjs +3 -1
  283. package/kits/hub-game/scripts/test-hub-idle.mjs +348 -0
  284. package/kits/hub-game/scripts/test-hub-leaving.mjs +21 -0
  285. package/kits/hub-game/scripts/test-hub-ops.mjs +147 -0
  286. package/kits/hub-game/scripts/test-hub-trip.mjs +260 -5
  287. package/kits/hub-game/scripts/test-hud-clear.mjs +83 -0
  288. package/kits/hub-game/scripts/test-hud-rate.mjs +2 -1
  289. package/kits/hub-game/scripts/test-idle.mjs +160 -0
  290. package/kits/hub-game/scripts/test-invites-client.mjs +53 -0
  291. package/kits/hub-game/scripts/test-labels.mjs +11 -0
  292. package/kits/hub-game/scripts/test-landscape-layout.mjs +20 -0
  293. package/kits/hub-game/scripts/test-load-abandon.mjs +2 -2
  294. package/kits/hub-game/scripts/test-loading-cover.mjs +67 -1
  295. package/kits/hub-game/scripts/test-manifest.mjs +27 -0
  296. package/kits/hub-game/scripts/test-menu-client.mjs +55 -6
  297. package/kits/hub-game/scripts/test-menu-surface.mjs +236 -0
  298. package/kits/hub-game/scripts/test-npcs.mjs +128 -0
  299. package/kits/hub-game/scripts/test-observed.mjs +171 -3
  300. package/kits/hub-game/scripts/test-pack.mjs +166 -0
  301. package/kits/hub-game/scripts/test-picker-surface.mjs +321 -0
  302. package/kits/hub-game/scripts/test-placeat-server.mjs +395 -0
  303. package/kits/hub-game/scripts/test-placement-cache.mjs +1 -1
  304. package/kits/hub-game/scripts/test-pointer-clear-dom.mjs +82 -0
  305. package/kits/hub-game/scripts/test-progress-reset.mjs +184 -6
  306. package/kits/hub-game/scripts/test-push-visit.mjs +9 -0
  307. package/kits/hub-game/scripts/test-quality.mjs +312 -9
  308. package/kits/hub-game/scripts/test-quick-chat-surface.mjs +511 -0
  309. package/kits/hub-game/scripts/test-rehello.mjs +237 -0
  310. package/kits/hub-game/scripts/test-rejoin-yaw.mjs +138 -0
  311. package/kits/hub-game/scripts/test-relations-among.mjs +13 -7
  312. package/kits/hub-game/scripts/test-relations-refresh.mjs +90 -2
  313. package/kits/hub-game/scripts/test-replay-client.mjs +110 -0
  314. package/kits/hub-game/scripts/test-replay.mjs +178 -0
  315. package/kits/hub-game/scripts/test-resume-held.mjs +13 -0
  316. package/kits/hub-game/scripts/test-resume-pose-server.mjs +43 -5
  317. package/kits/hub-game/scripts/test-resync.mjs +13 -0
  318. package/kits/hub-game/scripts/test-role-client.mjs +10 -3
  319. package/kits/hub-game/scripts/test-safe-act.mjs +233 -0
  320. package/kits/hub-game/scripts/test-safe-caption.mjs +364 -0
  321. package/kits/hub-game/scripts/test-safe-layout.mjs +79 -0
  322. package/kits/hub-game/scripts/test-safe-prompt.mjs +163 -0
  323. package/kits/hub-game/scripts/test-sound-surface.mjs +256 -0
  324. package/kits/hub-game/scripts/test-soundscape.mjs +85 -2
  325. package/kits/hub-game/scripts/test-stuck-surface.mjs +174 -0
  326. package/kits/hub-game/scripts/test-stuck.mjs +31 -0
  327. package/kits/hub-game/scripts/test-talk-surface.mjs +23 -6
  328. package/kits/hub-game/scripts/test-talk-walk-dom.mjs +123 -0
  329. package/kits/hub-game/scripts/test-text-ask-surface.mjs +273 -0
  330. package/kits/hub-game/scripts/test-tiers.mjs +453 -3
  331. package/kits/hub-game/scripts/test-toast-no-row-dom.mjs +71 -0
  332. package/kits/hub-game/scripts/test-together.mjs +11 -0
  333. package/kits/hub-game/scripts/test-town-day.mjs +90 -0
  334. package/kits/hub-game/scripts/test-track-queue.mjs +64 -0
  335. package/kits/hub-game/scripts/test-try-on.mjs +39 -0
  336. package/kits/hub-game/scripts/test-ui-dom-dom.mjs +49 -2
  337. package/kits/hub-game/scripts/test-ui-tree.mjs +28 -0
  338. package/kits/hub-game/scripts/test-vehicle-client.mjs +77 -1
  339. package/kits/hub-game/scripts/test-vis.mjs +145 -0
  340. package/kits/hub-game/scripts/test-wallet.mjs +650 -0
  341. package/kits/hub-game/scripts/test-weakest-tier.mjs +135 -1
  342. package/kits/hub-game/scripts/test-world-labels.mjs +380 -0
  343. package/kits/hub-game/scripts/test-writer-lease-server.mjs +234 -0
  344. package/kits/hub-game/scripts/test-writer-lease.mjs +281 -0
  345. package/kits/hub-game/scripts/writer-storage-fixture.mjs +37 -0
  346. package/kits/hub-game/tools/hubScene/export.mjs +6 -5
  347. package/kits/hub-game/tools/hubScene/hubdata.mjs +10 -0
  348. package/kits/hub-game/tools/hubScene/test/export-fixture.mjs +48 -2
  349. package/kits/hub-game/tools/hubScene/validate-manifest.mjs +21 -3
  350. package/kits/multiplayer-3d/castle.json +5 -5
  351. package/kits/multiplayer-3d/code/client/resumeGate.js +49 -2
  352. package/kits/multiplayer-3d/code/server/ownership.js +25 -6
  353. package/kits/multiplayer-3d/code/server/world.js +19 -4
  354. package/kits/multiplayer-3d/code/systems/multiplayer.js +67 -11
  355. package/kits/multiplayer-3d/package-lock.json +1 -1
  356. package/kits/multiplayer-3d/package.json +2 -1
  357. package/kits/multiplayer-3d/scripts/test-ground-half.mjs +56 -0
  358. package/kits/multiplayer-3d/scripts/test-join-watchdog.mjs +54 -3
  359. package/kits/multiplayer-3d/scripts/test-owned-moves.mjs +190 -0
  360. package/kits/multiplayer-3d/scripts/test-resume-gate.mjs +191 -5
  361. package/kits/multiplayer-3d/scripts/test-resync-reconnect.mjs +68 -0
  362. package/kits/physics-2d/castle.json +2 -2
  363. package/kits/physics-2d/engine/scene.js +10 -2
  364. package/kits/physics-3d/CLAUDE.md +14 -0
  365. package/kits/physics-3d/behaviors/Player.jsx +39 -3
  366. package/kits/physics-3d/castle.json +3 -3
  367. package/kits/physics-3d/docs/engine-model-cache.md +109 -0
  368. package/kits/physics-3d/docs/engine-player.md +76 -0
  369. package/kits/physics-3d/docs/engine-skip-work.md +16 -0
  370. package/kits/physics-3d/docs/pxmodel-format.md +5 -1
  371. package/kits/physics-3d/engine3d/gait.js +16 -8
  372. package/kits/physics-3d/engine3d/groundsize.js +23 -0
  373. package/kits/physics-3d/engine3d/kithooks.js +50 -0
  374. package/kits/physics-3d/engine3d/look.js +110 -17
  375. package/kits/physics-3d/engine3d/lookbake.js +19 -1
  376. package/kits/physics-3d/engine3d/materialpresets.js +3 -2
  377. package/kits/physics-3d/engine3d/modelcache.js +280 -0
  378. package/kits/physics-3d/engine3d/modelcachedigest.js +37 -0
  379. package/kits/physics-3d/engine3d/modelcachegate.js +69 -0
  380. package/kits/physics-3d/engine3d/modelrefs.js +13 -0
  381. package/kits/physics-3d/engine3d/optimize.js +20 -9
  382. package/kits/physics-3d/engine3d/playerRun.js +26 -1
  383. package/kits/physics-3d/engine3d/pxmodel.js +7 -3
  384. package/kits/physics-3d/engine3d/templatecache.js +722 -0
  385. package/kits/physics-3d/engine3d/world3d.js +211 -17
  386. package/kits/physics-3d/package-lock.json +1 -1
  387. package/kits/physics-3d/package.json +2 -1
  388. package/kits/physics-3d/play/behaviors/Player.js +43 -3
  389. package/kits/physics-3d/scripts/render.mjs +56 -8
  390. package/kits/physics-3d/scripts/template-cache-fixtures.mjs +37 -0
  391. package/kits/physics-3d/scripts/template-cache-v1-bytes.json +49 -0
  392. package/kits/physics-3d/scripts/test-gait.mjs +53 -9
  393. package/kits/physics-3d/scripts/test-ground-half.mjs +120 -0
  394. package/kits/physics-3d/scripts/test-model-cache.mjs +600 -0
  395. package/kits/physics-3d/scripts/test-orbit-shadow-fade.mjs +1 -0
  396. package/kits/physics-3d/scripts/test-sleeping-models.mjs +384 -0
  397. package/kits/physics-3d/scripts/test-template-cache-minified.mjs +106 -0
  398. package/kits/physics-3d/scripts/test-template-cache.mjs +519 -0
  399. package/kits/physics-3d/scripts/test-wall-slide.mjs +272 -0
  400. package/kits/physics-3d/systems/physics3d.js +51 -2
  401. package/kits/real-time/castle.json +2 -2
  402. package/kits/real-time/code/client/connection.js +3 -0
  403. package/package.json +2 -2
  404. package/vendor/three/examples/jsm/libs/fflate.module.js +2672 -0
@@ -0,0 +1,722 @@
1
+ // Exact template codec for the opt-in play cache.
2
+ import * as THREE from 'three';
3
+ import { Deflate, inflateSync } from 'three/examples/jsm/libs/fflate.module.js';
4
+ import { lookIsEnabled, OutlineMesh, patchMaterial, patchOutlineMaterial,
5
+ templateLookBakes, templateLookClone, restoreTemplateLook } from './look';
6
+ import { templateBakeGeometry } from './lookbake';
7
+ import { finishFromVertices } from './optimize';
8
+ import { glowByColor } from './materialpresets';
9
+ import { templateHookRecipes, beginTemplateCapture, endTemplateCapture, templateRequestsArt } from './kithooks';
10
+ import { parseModelCached, modelArtSignature } from './pxmodel';
11
+ import { resolveModelRef, MAX_MODEL_DEPTH } from './modelrefs';
12
+
13
+ // Bump with ANY change to model building (including look/shader recipes),
14
+ // not just changes to this format. It is also the kit build version in keys.
15
+ export const TEMPLATE_CACHE_VERSION = 6;
16
+ export const TEMPLATE_CACHE_MAX_PAYLOAD = 16 * 1024 * 1024;
17
+ const MAGIC = 0x54434d50;
18
+ const PREFIX = 16;
19
+ const arrays = { Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array };
20
+ // Stable wire names come from explicit constructors, never minified JS names.
21
+ // Do not enumerate THREE: that keeps otherwise unused exports in every deck.
22
+ function classTable(entries) {
23
+ return { read: new Map(entries), write: new Map(entries.map(([name, Constructor]) => [Constructor, name])) };
24
+ }
25
+ const values = classTable([
26
+ ['Color', THREE.Color], ['Vector2', THREE.Vector2], ['Vector3', THREE.Vector3], ['Vector4', THREE.Vector4],
27
+ ['Quaternion', THREE.Quaternion], ['Euler', THREE.Euler], ['Matrix3', THREE.Matrix3], ['Matrix4', THREE.Matrix4],
28
+ ]);
29
+ const attributes = classTable([
30
+ ['BufferAttribute', THREE.BufferAttribute], ['InstancedBufferAttribute', THREE.InstancedBufferAttribute],
31
+ ['Int8BufferAttribute', THREE.Int8BufferAttribute], ['Uint8BufferAttribute', THREE.Uint8BufferAttribute],
32
+ ['Uint8ClampedBufferAttribute', THREE.Uint8ClampedBufferAttribute], ['Int16BufferAttribute', THREE.Int16BufferAttribute],
33
+ ['Uint16BufferAttribute', THREE.Uint16BufferAttribute], ['Int32BufferAttribute', THREE.Int32BufferAttribute],
34
+ ['Uint32BufferAttribute', THREE.Uint32BufferAttribute], ['Float16BufferAttribute', THREE.Float16BufferAttribute],
35
+ ['Float32BufferAttribute', THREE.Float32BufferAttribute],
36
+ ]);
37
+ const geometryClasses = classTable([
38
+ ['BufferGeometry', THREE.BufferGeometry], ['BoxGeometry', THREE.BoxGeometry], ['CapsuleGeometry', THREE.CapsuleGeometry],
39
+ ['CircleGeometry', THREE.CircleGeometry], ['ConeGeometry', THREE.ConeGeometry], ['CylinderGeometry', THREE.CylinderGeometry],
40
+ ['DodecahedronGeometry', THREE.DodecahedronGeometry], ['EdgesGeometry', THREE.EdgesGeometry], ['ExtrudeGeometry', THREE.ExtrudeGeometry],
41
+ ['IcosahedronGeometry', THREE.IcosahedronGeometry], ['LatheGeometry', THREE.LatheGeometry], ['OctahedronGeometry', THREE.OctahedronGeometry],
42
+ ['PlaneGeometry', THREE.PlaneGeometry], ['PolyhedronGeometry', THREE.PolyhedronGeometry], ['RingGeometry', THREE.RingGeometry],
43
+ ['ShapeGeometry', THREE.ShapeGeometry], ['SphereGeometry', THREE.SphereGeometry], ['TetrahedronGeometry', THREE.TetrahedronGeometry],
44
+ ['TorusGeometry', THREE.TorusGeometry], ['TorusKnotGeometry', THREE.TorusKnotGeometry], ['TubeGeometry', THREE.TubeGeometry],
45
+ ['WireframeGeometry', THREE.WireframeGeometry],
46
+ ]);
47
+ const materialClasses = classTable([
48
+ ['Material', THREE.Material], ['MeshBasicMaterial', THREE.MeshBasicMaterial], ['MeshDepthMaterial', THREE.MeshDepthMaterial],
49
+ ['MeshDistanceMaterial', THREE.MeshDistanceMaterial], ['MeshLambertMaterial', THREE.MeshLambertMaterial],
50
+ ['MeshMatcapMaterial', THREE.MeshMatcapMaterial], ['MeshNormalMaterial', THREE.MeshNormalMaterial],
51
+ ['MeshPhongMaterial', THREE.MeshPhongMaterial], ['MeshPhysicalMaterial', THREE.MeshPhysicalMaterial],
52
+ ['MeshStandardMaterial', THREE.MeshStandardMaterial], ['MeshToonMaterial', THREE.MeshToonMaterial],
53
+ ['LineBasicMaterial', THREE.LineBasicMaterial], ['LineDashedMaterial', THREE.LineDashedMaterial],
54
+ ['PointsMaterial', THREE.PointsMaterial], ['ShadowMaterial', THREE.ShadowMaterial], ['SpriteMaterial', THREE.SpriteMaterial],
55
+ ]);
56
+ const objects = classTable([
57
+ ['Group', THREE.Group], ['Object3D', THREE.Object3D], ['Mesh', THREE.Mesh], ['InstancedMesh', THREE.InstancedMesh],
58
+ ['OutlineMesh', OutlineMesh],
59
+ ]);
60
+ const objectFields = ['name', 'visible', 'castShadow', 'receiveShadow', 'renderOrder', 'frustumCulled', 'matrixAutoUpdate', 'matrixWorldAutoUpdate', 'matrixWorldNeedsUpdate'];
61
+ const materialRuntime = new Set(['id', 'uuid', 'version', '_listeners', 'onBeforeCompile', 'customProgramCacheKey', 'onBeforeRender']);
62
+ const nativeEndian = new Uint8Array(new Uint16Array([1]).buffer)[0];
63
+ const encoder = new TextEncoder();
64
+ const decoder = new TextDecoder('utf-8', { fatal: true });
65
+
66
+ function refuse(reason) {
67
+ throw new Error(reason);
68
+ }
69
+
70
+ // Tagged values avoid collisions with authored JSON keys and preserve undefined,
71
+ // nonfinite numbers and THREE values (branchTips, for example) without rounding.
72
+ function writer(nodes) {
73
+ const chunks = [];
74
+ const contents = new Map();
75
+ const identities = new Map();
76
+ const pending = [];
77
+ let length = 0;
78
+ const active = new Set();
79
+ const encode = (value) => {
80
+ if (value === undefined) return ['undefined'];
81
+ if (typeof value === 'number' && (!Number.isFinite(value) || Object.is(value, -0))) return ['number', String(value), Object.is(value, -0)];
82
+ if (value === null || ['string', 'boolean', 'number'].includes(typeof value)) return value;
83
+ if (typeof value !== 'object' || active.has(value)) refuse('metadata: non-JSON value or cycle');
84
+ if (value.isTexture) refuse('texture');
85
+ if (Object.getOwnPropertySymbols(value).length) refuse('metadata: symbol key');
86
+ if (nodes.has(value)) return ['node', nodes.get(value)];
87
+ if (ArrayBuffer.isView(value)) {
88
+ if (!Object.hasOwn(arrays, value.constructor.name) || arrays[value.constructor.name] !== value.constructor) refuse('typed array');
89
+ if (identities.has(value)) return identities.get(value);
90
+ const identity = identities.size;
91
+ const record = ['array', value.constructor.name, 0, value.length, value.constructor.name, identity];
92
+ pending.push({ value, record });
93
+ identities.set(value, record);
94
+ return record;
95
+ }
96
+ const kind = values.write.get(value.constructor);
97
+ if (kind) return ['three', kind, encode(value.toArray())];
98
+ active.add(value);
99
+ let out;
100
+ if (Array.isArray(value)) {
101
+ if (Object.keys(value).length !== value.length) refuse('metadata: sparse or extended array');
102
+ out = ['list', value.map(encode)];
103
+ }
104
+ else if (value instanceof Map) out = ['map', [...value].map(([key, entry]) => [encode(key), encode(entry)])];
105
+ else if (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null) out = [Object.getPrototypeOf(value) === null ? 'nullObject' : 'object', Object.entries(value).map(([key, entry]) => [key, encode(entry)])];
106
+ else refuse('metadata: unsupported class');
107
+ active.delete(value);
108
+ return out;
109
+ };
110
+ function* finish() {
111
+ for (const { value, record } of pending) {
112
+ let packed = value;
113
+ if (value instanceof Uint32Array) {
114
+ let fits = true;
115
+ for (let at = 0; at < value.length && fits; at += 8192) {
116
+ for (let n = at; n < Math.min(at + 8192, value.length); n++) if (value[n] > 65535) { fits = false; break; }
117
+ yield;
118
+ }
119
+ if (fits) {
120
+ packed = new Uint16Array(value.length);
121
+ for (let at = 0; at < value.length; at += 8192) { packed.set(value.subarray(at, at + 8192), at); yield; }
122
+ }
123
+ }
124
+ const bytes = new Uint8Array(packed.buffer, packed.byteOffset, packed.byteLength);
125
+ let digest = 0x811c9dc5;
126
+ for (let at = 0; at < bytes.length; at += 32768) {
127
+ for (let n = at; n < Math.min(at + 32768, bytes.length); n++) digest = Math.imul(digest ^ bytes[n], 0x01000193);
128
+ yield;
129
+ }
130
+ const key = `${bytes.length}:${digest >>> 0}`;
131
+ const matches = contents.get(key) ?? [];
132
+ let chunk;
133
+ for (const candidate of matches) {
134
+ let equal = true;
135
+ for (let at = 0; at < bytes.length && equal; at += 32768) {
136
+ for (let n = at; n < Math.min(at + 32768, bytes.length); n++) if (candidate.bytes[n] !== bytes[n]) { equal = false; break; }
137
+ yield;
138
+ }
139
+ if (equal) { chunk = candidate; break; }
140
+ }
141
+ if (!chunk) {
142
+ length = Math.ceil(length / 8) * 8;
143
+ chunk = { offset: length, bytes };
144
+ chunks.push(chunk);
145
+ matches.push(chunk);
146
+ contents.set(key, matches);
147
+ length += bytes.length;
148
+ if (length > TEMPLATE_CACHE_MAX_PAYLOAD) refuse('payload size');
149
+ }
150
+ record[2] = chunk.offset;
151
+ record[4] = packed.constructor.name;
152
+ }
153
+ }
154
+ return { encode, chunks, finish, get length() { return length; } };
155
+ }
156
+
157
+ function attributeData(attribute, encode) {
158
+ if (!attribute) return null;
159
+ const type = attributes.write.get(attribute.constructor);
160
+ if (attribute.isInterleavedBufferAttribute || !attribute.isBufferAttribute || !type) refuse('attribute');
161
+ if (attribute.onUploadCallback !== THREE.BufferAttribute.prototype.onUploadCallback || attribute.updateRanges.length) refuse('attribute callback or update ranges');
162
+ return {
163
+ type, array: encode(attribute.array), itemSize: attribute.itemSize,
164
+ normalized: attribute.normalized, name: attribute.name, usage: attribute.usage,
165
+ gpuType: attribute.gpuType, meshPerAttribute: attribute.meshPerAttribute ?? null,
166
+ };
167
+ }
168
+
169
+ function geometryData(geometry, encode, bounds, tasks) {
170
+ if (!templateBakeGeometry(geometry, tasks)) refuse('geometry callback');
171
+ if (Object.keys(geometry.morphAttributes).length || geometry.indirect || geometry.isInstancedBufferGeometry) refuse('morph, indirect or instanced geometry');
172
+ const kind = geometryClasses.write.get(geometry.constructor);
173
+ if (!kind) refuse('geometry class');
174
+ const box = bounds ? bounds.box : geometry.boundingBox;
175
+ const sphere = bounds ? bounds.sphere : geometry.boundingSphere;
176
+ return {
177
+ class: kind, type: geometry.type, name: geometry.name, parameters: encode(geometry.parameters), morphTargetsRelative: geometry.morphTargetsRelative,
178
+ attributes: Object.entries(geometry.attributes).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, attribute]) => [key, attributeData(attribute, encode)]),
179
+ index: attributeData(geometry.index, encode), groups: encode(geometry.groups),
180
+ drawRange: encode(geometry.drawRange), userData: encode(geometry.userData),
181
+ box: box ? encode([box.min, box.max]) : null,
182
+ sphere: sphere ? encode([sphere.center, sphere.radius]) : null,
183
+ };
184
+ }
185
+
186
+ function materialData(material, encode, hidden) {
187
+ const type = materialClasses.write.get(material.constructor);
188
+ if (!type || material.isShaderMaterial) refuse('material class');
189
+ const Constructor = materialClasses.read.get(type);
190
+ if (Object.values(material._listeners ?? {}).some((listeners) => listeners.length)) refuse('material callback');
191
+ const hooks = templateHookRecipes(material);
192
+ if (!hooks) refuse('hooks not captured');
193
+ const fresh = new Constructor();
194
+ const props = [];
195
+ for (const key of Object.keys(material)) {
196
+ if (materialRuntime.has(key)) continue;
197
+ if (key === 'clone' && hidden.has(material) && templateLookClone(material)) continue;
198
+ const value = material[key];
199
+ // materials.js/artobjects.js do not tag stable art refs yet. Refuse all
200
+ // textures, including nested uniforms, rather than inventing identity.
201
+ if (value?.isTexture) refuse('texture');
202
+ const encoded = encode(value);
203
+ if (JSON.stringify(encoded) !== JSON.stringify(encode(fresh[key]))) props.push([key, encoded]);
204
+ }
205
+ return { type, props, hooks: encode(hooks) };
206
+ }
207
+
208
+ function nodeKind(node) {
209
+ const kind = objects.write.get(node.constructor);
210
+ if (kind) return kind;
211
+ refuse('object class');
212
+ }
213
+
214
+ // Optional pose snapshot for the cooperative encoder. It does not freeze
215
+ // geometry/materials; play must encode its bytes at construction instead.
216
+ function templatePose(node) {
217
+ return {
218
+ props: objectFields.map((key) => [key, node[key]]),
219
+ position: Float64Array.from(node.position.toArray()), quaternion: Float64Array.from(node.quaternion.toArray()),
220
+ scale: Float64Array.from(node.scale.toArray()), rotation: node.rotation.clone(), up: Float64Array.from(node.up.toArray()),
221
+ matrix: Float64Array.from(node.matrix.toArray()), matrixWorld: Float64Array.from(node.matrixWorld.toArray()), layers: node.layers.mask,
222
+ };
223
+ }
224
+
225
+ export function snapshotTemplateTree(root) {
226
+ const nodes = [];
227
+ const children = new Map();
228
+ const poses = new Map();
229
+ const bounds = new Map();
230
+ root.traverse((node) => {
231
+ nodes.push(node); children.set(node, [...node.children]); poses.set(node, templatePose(node));
232
+ if (node.geometry && !bounds.has(node.geometry)) bounds.set(node.geometry, {
233
+ box: node.geometry.boundingBox?.clone() ?? null, sphere: node.geometry.boundingSphere?.clone() ?? null,
234
+ });
235
+ });
236
+ return { nodes, children, poses, bounds };
237
+ }
238
+
239
+ function* templateSteps(root, snapshot) {
240
+ const bakes = templateLookBakes(root);
241
+ const tasks = new Set(bakes.map(({ task }) => task).filter(Boolean));
242
+ const hidden = new Set(bakes.flatMap(({ outlines }) => outlines.flatMap(({ materials }) => materials)));
243
+ const nodes = snapshot?.nodes ?? [];
244
+ if (!snapshot) root.traverse((node) => nodes.push(node));
245
+ for (const node of nodes) if (templateRequestsArt(node)) refuse('art');
246
+ const ids = new Map(nodes.map((node, index) => [node, index]));
247
+ const out = writer(ids);
248
+ const { encode } = out;
249
+ const geometries = [];
250
+ const materials = [];
251
+ const geometryIds = new Map();
252
+ const materialIds = new Map();
253
+ const shared = (value, table, indices, write) => {
254
+ if (!indices.has(value)) {
255
+ indices.set(value, table.length);
256
+ table.push(write(value, encode));
257
+ }
258
+ return indices.get(value);
259
+ };
260
+ const tree = [];
261
+ const geometryRef = (geometry) => shared(geometry, geometries, geometryIds, (geometry, encode) => geometryData(geometry, encode, snapshot?.bounds.get(geometry), tasks));
262
+ const materialRef = (material) => shared(material, materials, materialIds, (material, encode) => materialData(material, encode, hidden));
263
+ for (const node of nodes) {
264
+ const kind = nodeKind(node);
265
+ if (node.animations.length || Object.values(node._listeners ?? {}).some((listeners) => listeners.length)) refuse('object animation or callback');
266
+ for (const key of ['onBeforeRender', 'onAfterRender', 'onBeforeShadow', 'onAfterShadow']) {
267
+ if (node[key] !== THREE.Object3D.prototype[key]) refuse('object callback');
268
+ }
269
+ if (node.raycast !== node.constructor.prototype.raycast && !(kind === 'InstancedMesh' && node.userData.lookOutline && node.raycast === OutlineMesh.prototype.raycast)) refuse('raycast callback');
270
+ // modelParts points to the actual groups, including empty parts left by
271
+ // merging. Never JSON-stringify a Map into {} as Object3D.clone does.
272
+ if (node.userData.modelParts) {
273
+ for (const [id, part] of node.userData.modelParts) if (!ids.has(part) || part.userData.partId !== id) refuse('modelParts outside tree or wrong partId');
274
+ }
275
+ const pose = snapshot?.poses.get(node) ?? templatePose(node);
276
+ const record = {
277
+ kind, children: (snapshot?.children.get(node) ?? node.children).map((child) => ids.get(child)),
278
+ props: encode(pose.props), position: encode(pose.position), quaternion: encode(pose.quaternion),
279
+ scale: encode(pose.scale), rotation: encode(pose.rotation), up: encode(pose.up),
280
+ matrix: encode(pose.matrix), matrixWorld: encode(pose.matrixWorld), layers: pose.layers,
281
+ userData: encode(node.userData),
282
+ };
283
+ if (node.isMesh) {
284
+ if (node.morphTargetInfluences || node.customDepthMaterial || node.customDistanceMaterial) refuse('mesh morph or custom shadow material');
285
+ record.geometry = geometryRef(node.geometry);
286
+ record.material = Array.isArray(node.material)
287
+ ? node.material.map(materialRef)
288
+ : materialRef(node.material);
289
+ }
290
+ if (node.isInstancedMesh) {
291
+ if (node.morphTexture) refuse('texture');
292
+ record.count = node.count;
293
+ record.instanceMatrix = attributeData(node.instanceMatrix, encode);
294
+ record.instanceColor = attributeData(node.instanceColor, encode);
295
+ record.box = node.boundingBox ? encode([node.boundingBox.min, node.boundingBox.max]) : null;
296
+ record.sphere = node.boundingSphere ? encode([node.boundingSphere.center, node.boundingSphere.radius]) : null;
297
+ }
298
+ tree.push(record);
299
+ yield;
300
+ }
301
+ const placed = (items) => items.map(({ geometry, matrixWorld }) => ({ geometry: geometryRef(geometry), matrixWorld }));
302
+ const lookBakes = encode(bakes.map(({ occlusion, outlines, copies, gone }) => ({
303
+ occlusion: occlusion ? { model: occlusion.model, file: occlusion.file, shape: occlusion.shape,
304
+ surfaces: placed(occlusion.surfaces), targets: placed(occlusion.targets) } : null,
305
+ outlines: outlines.map(({ geometry, parts, materials }) => ({ geometry: geometryRef(geometry), parts, materials: materials.map(materialRef) })),
306
+ copies: copies.map(([copy, geometry]) => [geometryRef(copy), geometryRef(geometry)]), gone: gone.map(geometryRef),
307
+ })));
308
+ yield* out.finish();
309
+ if (out.length > TEMPLATE_CACHE_MAX_PAYLOAD) refuse('payload size');
310
+ const payload = new Uint8Array(out.length);
311
+ for (const chunk of out.chunks) {
312
+ for (let at = 0; at < chunk.bytes.length; at += 32768) { payload.set(chunk.bytes.subarray(at, at + 32768), chunk.offset + at); yield; }
313
+ }
314
+ // Fast lossless compression after dedupe; incompressible payloads stay raw.
315
+ // Three already ships this codec, so no dependency is added to the kit.
316
+ const parts = [];
317
+ let compressedLength = 0;
318
+ const compressor = new Deflate({ level: 1 }, (part) => { parts.push(part); compressedLength += part.length; });
319
+ for (let at = 0; at < payload.length || at === 0; at += 32768) {
320
+ compressor.push(payload.subarray(at, at + 32768), at + 32768 >= payload.length);
321
+ yield;
322
+ }
323
+ const compressed = new Uint8Array(compressedLength);
324
+ let offset = 0;
325
+ for (const part of parts) { compressed.set(part, offset); offset += part.length; yield; }
326
+ const stored = compressed.length < payload.length ? compressed : payload;
327
+ const header = encoder.encode(JSON.stringify({ revision: THREE.REVISION, endian: nativeEndian,
328
+ payloadCodec: stored === compressed ? 'deflate' : 'raw', payloadLength: payload.length,
329
+ tree, geometries, materials, lookBakes }));
330
+ const start = Math.ceil((PREFIX + header.length) / 8) * 8;
331
+ const bytes = new ArrayBuffer(start + stored.length);
332
+ const prefix = new DataView(bytes);
333
+ [MAGIC, TEMPLATE_CACHE_VERSION, header.length, stored.length].forEach((value, index) => prefix.setUint32(index * 4, value, true));
334
+ new Uint8Array(bytes, PREFIX, header.length).set(header);
335
+ new Uint8Array(bytes, start).set(stored);
336
+ return { bytes, reason: null };
337
+ }
338
+
339
+ // Both drivers use exactly the same steps and compression boundaries.
340
+ export function serializeTemplate(root, options) {
341
+ try {
342
+ const steps = templateSteps(root, options?.snapshot);
343
+ let result;
344
+ do { result = steps.next(); } while (!result.done);
345
+ return result.value;
346
+ } catch (error) { return { bytes: null, reason: error.message }; }
347
+ }
348
+
349
+ export async function serializeTemplateAsync(root, { snapshot, pause, cancelled = () => false }) {
350
+ try {
351
+ const steps = templateSteps(root, snapshot);
352
+ let result;
353
+ do {
354
+ if (cancelled()) return { bytes: null, reason: 'cancelled' };
355
+ const until = performance.now() + 3;
356
+ do { result = steps.next(); } while (!result.done && performance.now() < until);
357
+ if (!result.done) await pause();
358
+ } while (!result.done);
359
+ return result.value;
360
+ } catch (error) { return { bytes: null, reason: error.message }; }
361
+ }
362
+
363
+ function reader(bytes, start, nodes) {
364
+ const identities = new Map();
365
+ const decode = (value) => {
366
+ if (!Array.isArray(value)) {
367
+ if (value !== null && !['number', 'string', 'boolean'].includes(typeof value)) refuse('value');
368
+ return value;
369
+ }
370
+ const [tag, data, offset, count] = value;
371
+ switch (tag) {
372
+ case 'undefined': return undefined;
373
+ case 'number': {
374
+ if (!['NaN', 'Infinity', '-Infinity', '0'].includes(data)) refuse('number');
375
+ return offset ? -0 : Number(data);
376
+ }
377
+ case 'node': {
378
+ if (!Number.isInteger(data) || !nodes[data]) refuse('node');
379
+ return nodes[data];
380
+ }
381
+ case 'array': {
382
+ const storage = value[4];
383
+ const identity = value[5];
384
+ if (!Number.isSafeInteger(identity) || identity < 0) refuse('array identity');
385
+ const previous = identities.get(identity);
386
+ if (previous) {
387
+ if (previous.record !== JSON.stringify(value)) refuse('array identity mismatch');
388
+ return previous.array;
389
+ }
390
+ if (!Object.hasOwn(arrays, data) || !Object.hasOwn(arrays, storage) || (storage !== data && !(data === 'Uint32Array' && storage === 'Uint16Array'))) refuse('array type');
391
+ const Constructor = arrays[storage];
392
+ if (!Number.isSafeInteger(offset) || offset < 0 || offset % 8 || !Number.isSafeInteger(count) || count < 0 || start + offset + count * Constructor.BYTES_PER_ELEMENT > bytes.byteLength) refuse('array range');
393
+ // Storage may be deduplicated, but distinct geometry arrays remain
394
+ // independently mutable and never alias the persistent cache bytes.
395
+ const stored = new Constructor(bytes.slice(start + offset, start + offset + count * Constructor.BYTES_PER_ELEMENT));
396
+ const array = storage === data ? stored : new arrays[data](stored);
397
+ identities.set(identity, { record: JSON.stringify(value), array });
398
+ return array;
399
+ }
400
+ case 'three': {
401
+ const Constructor = values.read.get(data);
402
+ if (!Constructor) refuse('value type');
403
+ const array = decode(offset);
404
+ const fresh = new Constructor();
405
+ if (!Array.isArray(array) || array.length !== fresh.toArray().length || array.some((entry, index) => typeof entry !== (data === 'Euler' && index === 3 ? 'string' : 'number'))) refuse('value shape');
406
+ return fresh.fromArray(array);
407
+ }
408
+ case 'list': return data.map(decode);
409
+ case 'map': return new Map(data.map(([key, entry]) => [decode(key), decode(entry)]));
410
+ case 'nullObject': return Object.assign(Object.create(null), Object.fromEntries(data.map(([key, entry]) => [key, decode(entry)])));
411
+ case 'object': return Object.fromEntries(data.map(([key, entry]) => [key, decode(entry)]));
412
+ default: return refuse('value tag');
413
+ }
414
+ };
415
+ return decode;
416
+ }
417
+
418
+ function readAttribute(data, decode, maxSize = 4) {
419
+ if (data === null) return null;
420
+ const Constructor = attributes.read.get(data.type);
421
+ if (!Constructor) refuse('attribute class');
422
+ const array = decode(data.array);
423
+ if (!ArrayBuffer.isView(array) || !Number.isInteger(data.itemSize) || data.itemSize < 1 || data.itemSize > maxSize || array.length % data.itemSize || typeof data.normalized !== 'boolean') refuse('attribute shape');
424
+ // Typed BufferAttribute subclasses normally copy their input array. Restore
425
+ // the original view after construction so sharing survives across classes.
426
+ const attribute = new Constructor(array, data.itemSize, data.normalized, data.meshPerAttribute ?? 1);
427
+ attribute.array = array;
428
+ attribute.name = data.name;
429
+ attribute.setUsage(data.usage);
430
+ attribute.gpuType = data.gpuType;
431
+ return attribute;
432
+ }
433
+
434
+ function readGeometry(data, decode) {
435
+ const Constructor = geometryClasses.read.get(data.class);
436
+ if (!Constructor) refuse('geometry class');
437
+ const geometry = new THREE.BufferGeometry();
438
+ // Preserve primitive clone/copy methods without invoking their procedural
439
+ // constructors: the complete attribute buffers and parameters follow.
440
+ Object.setPrototypeOf(geometry, Constructor.prototype);
441
+ geometry.type = data.type;
442
+ geometry.name = data.name;
443
+ geometry.morphTargetsRelative = data.morphTargetsRelative;
444
+ const parameters = decode(data.parameters);
445
+ if (parameters !== undefined) geometry.parameters = parameters;
446
+ for (const [key, attribute] of data.attributes) {
447
+ if (typeof key !== 'string' || ['__proto__', 'constructor', 'prototype'].includes(key) || Object.hasOwn(geometry.attributes, key)) refuse('attribute name');
448
+ geometry.setAttribute(key, readAttribute(attribute, decode));
449
+ }
450
+ geometry.setIndex(readAttribute(data.index, decode));
451
+ geometry.groups = decode(data.groups);
452
+ geometry.drawRange = decode(data.drawRange);
453
+ geometry.userData = decode(data.userData);
454
+ readBounds(geometry, data, decode);
455
+ const sizes = { position: [3], normal: [3], uv: [2], uv1: [2], uv2: [2], uv3: [2], color: [3, 4],
456
+ tangent: [4], skinIndex: [4], skinWeight: [4], partFinish: [2], lookOutlineNormal: [3], lookOutlineReach: [1], lookOcclusion: [1] };
457
+ const count = geometry.getAttribute('position')?.count ?? 0;
458
+ for (const [key, attribute] of Object.entries(geometry.attributes)) {
459
+ if (attribute.count !== count || (Object.hasOwn(sizes, key) && !sizes[key].includes(attribute.itemSize))) refuse('geometry attribute shape');
460
+ }
461
+ if (geometry.index && (geometry.index.itemSize !== 1 || geometry.index.normalized ||
462
+ ![Uint8Array, Uint16Array, Uint32Array].includes(geometry.index.array.constructor) ||
463
+ geometry.index.array.some((index) => index >= count))) refuse('geometry index');
464
+ const limit = geometry.index?.count ?? count;
465
+ if (!Array.isArray(geometry.groups) || geometry.groups.some((group) =>
466
+ !Number.isSafeInteger(group.start) || group.start < 0 || !Number.isSafeInteger(group.count) || group.count < 0 ||
467
+ group.start + group.count > limit || !Number.isSafeInteger(group.materialIndex) || group.materialIndex < 0)) refuse('geometry groups');
468
+ if (!Number.isSafeInteger(geometry.drawRange.start) || geometry.drawRange.start < 0 || geometry.drawRange.start > limit ||
469
+ (geometry.drawRange.count !== Infinity && (!Number.isSafeInteger(geometry.drawRange.count) || geometry.drawRange.count < 0 ||
470
+ geometry.drawRange.start + geometry.drawRange.count > limit))) refuse('geometry draw range');
471
+ return geometry;
472
+ }
473
+
474
+ function readBounds(target, data, decode) {
475
+ const read = (value) => {
476
+ const pair = decode(value);
477
+ if (!Array.isArray(pair) || pair.length !== 2) refuse('bounds shape');
478
+ return pair;
479
+ };
480
+ target.boundingBox = data.box ? new THREE.Box3(...read(data.box)) : null;
481
+ target.boundingSphere = data.sphere ? new THREE.Sphere(...read(data.sphere)) : null;
482
+ const finite = (vector) => vector instanceof THREE.Vector3 && vector.toArray().every(Number.isFinite);
483
+ const box = target.boundingBox, sphere = target.boundingSphere;
484
+ if (box && (!finite(box.min) || !finite(box.max) || ['x', 'y', 'z'].some((axis) => box.min[axis] > box.max[axis]))) refuse('bounding box');
485
+ if (sphere && (!finite(sphere.center) || !Number.isFinite(sphere.radius) || sphere.radius < 0)) refuse('bounding sphere');
486
+ }
487
+
488
+ function resource(table, id) {
489
+ if (!Number.isSafeInteger(id) || id < 0 || id >= table.length) refuse('resource index');
490
+ return table[id];
491
+ }
492
+
493
+ function readLookBakes(data, decode, geometries, materials) {
494
+ const recipes = decode(data);
495
+ if (!Array.isArray(recipes)) refuse('look recipes');
496
+ const geometry = (id) => resource(geometries, id);
497
+ const placed = (items) => items.map(({ geometry: id, matrixWorld }) => {
498
+ if (!(matrixWorld instanceof THREE.Matrix4) || !matrixWorld.elements.every(Number.isFinite)) refuse('look placement');
499
+ return { geometry: geometry(id), matrixWorld };
500
+ });
501
+ return recipes.map((recipe) => {
502
+ const occlusion = recipe.occlusion ? { ...recipe.occlusion,
503
+ surfaces: placed(recipe.occlusion.surfaces), targets: placed(recipe.occlusion.targets) } : null;
504
+ if (occlusion && (!occlusion.model || typeof occlusion.model !== 'object' || typeof occlusion.file !== 'string' || typeof occlusion.shape !== 'string' ||
505
+ occlusion.targets.some(({ geometry }) => !geometry.getAttribute('lookOcclusion') || !geometry.getAttribute('normal')))) refuse('look occlusion');
506
+ const outlines = recipe.outlines.map(({ geometry: id, parts, materials: ids }) => {
507
+ const own = geometry(id);
508
+ if (!own.getAttribute('normal')) refuse('look outline');
509
+ if (parts !== null && (!Array.isArray(parts) || parts.some((part) =>
510
+ ['vertex', 'vertices', 'corner', 'corners'].some((key) => !Number.isSafeInteger(part[key]) || part[key] < 0) ||
511
+ part.vertex + part.vertices > own.getAttribute('position').count || !own.index || part.corner + part.corners > own.index.count))) refuse('look parts');
512
+ return { geometry: own, parts, materials: ids.map((id) => resource(materials, id)) };
513
+ });
514
+ const originals = new Set([...outlines.map(({ geometry }) => geometry), ...(occlusion?.targets.map(({ geometry }) => geometry) ?? [])]);
515
+ const members = new Set(originals);
516
+ const copies = recipe.copies.map(([copy, original]) => {
517
+ const own = geometry(copy), from = geometry(original);
518
+ if (members.has(own) || !originals.has(from) || own.getAttribute('position').count !== from.getAttribute('position').count) refuse('look copy');
519
+ members.add(own);
520
+ return [own, from];
521
+ });
522
+ const gone = recipe.gone.map(geometry);
523
+ if (!originals.size || new Set(gone).size !== gone.length || gone.length >= members.size || gone.some((own) => !members.has(own))) refuse('look disposed');
524
+ return { occlusion, outlines, copies, gone };
525
+ });
526
+ }
527
+
528
+ function readMaterial(data, decode) {
529
+ const Constructor = materialClasses.read.get(data.type);
530
+ if (!Constructor) refuse('material class');
531
+ const material = new Constructor();
532
+ for (const [key, value] of data.props) {
533
+ if (['__proto__', 'constructor', 'prototype'].includes(key) || materialRuntime.has(key)) refuse('material property');
534
+ material[key] = decode(value);
535
+ }
536
+ for (const recipe of decode(data.hooks)) {
537
+ switch (recipe.kind) {
538
+ case 'finish': finishFromVertices(material); break;
539
+ case 'glow': glowByColor(material); break;
540
+ case 'look': {
541
+ // Only the presence of lookOcclusion matters to patchMaterial; its
542
+ // original defines and userData are already in the stored properties.
543
+ const marked = material.userData.lookPatched;
544
+ delete material.userData.lookPatched;
545
+ patchMaterial(material, recipe.look, { getAttribute: () => Object.hasOwn(material.defines ?? {}, 'LOOK_AO') });
546
+ material.userData.lookPatched = marked;
547
+ break;
548
+ }
549
+ case 'outline': patchOutlineMaterial(material, recipe.width); break;
550
+ default: refuse('hook recipe');
551
+ }
552
+ }
553
+ return material;
554
+ }
555
+
556
+ // resolveTexture is reserved for stable art refs. No current material tags
557
+ // those refs, so the codec writes no texture records and never calls the resolver.
558
+ export function deserializeTemplate(bytes, { resolveTexture: _resolveTexture } = {}) {
559
+ try {
560
+ if (!(bytes instanceof ArrayBuffer) || bytes.byteLength < PREFIX) return null;
561
+ const prefix = new DataView(bytes);
562
+ if (prefix.getUint32(0, true) !== MAGIC || prefix.getUint32(4, true) !== TEMPLATE_CACHE_VERSION) return null;
563
+ const length = prefix.getUint32(8, true);
564
+ const start = Math.ceil((PREFIX + length) / 8) * 8;
565
+ if (start + prefix.getUint32(12, true) !== bytes.byteLength) return null;
566
+ const header = JSON.parse(decoder.decode(new Uint8Array(bytes, PREFIX, length)));
567
+ if (header.revision !== THREE.REVISION || header.endian !== nativeEndian || !Array.isArray(header.tree) || !header.tree.length || !Array.isArray(header.materials) || !Array.isArray(header.geometries)) return null;
568
+ if (!Number.isSafeInteger(header.payloadLength) || header.payloadLength < 0 || header.payloadLength > TEMPLATE_CACHE_MAX_PAYLOAD) return null;
569
+ if (!['raw', 'deflate'].includes(header.payloadCodec)) return null;
570
+ const nodes = header.tree.map((data) => {
571
+ switch (data.kind) {
572
+ case 'Group': return new THREE.Group();
573
+ case 'Object3D': return new THREE.Object3D();
574
+ case 'Mesh': return new THREE.Mesh();
575
+ case 'OutlineMesh': return new OutlineMesh();
576
+ case 'InstancedMesh': return new THREE.InstancedMesh(undefined, undefined, 0);
577
+ default: return refuse('node class');
578
+ }
579
+ });
580
+ const stored = new Uint8Array(bytes, start);
581
+ let payload;
582
+ if (header.payloadCodec === 'raw') payload = stored;
583
+ else if (header.payloadCodec === 'deflate') {
584
+ const out = new Uint8Array(header.payloadLength);
585
+ const subarray = out.subarray;
586
+ // This fflate version clamps its final subarray when output overflows.
587
+ // Reject that case explicitly while keeping every write in a fixed
588
+ // buffer; malformed streams cannot trigger output-buffer growth.
589
+ // A stream that ends at once (empty input) returns `out` untouched
590
+ // without that final subarray, so only a stream that reached it and
591
+ // produced exactly the declared length counts as inflated.
592
+ let produced = -1;
593
+ out.subarray = function (begin, end) {
594
+ if (end > this.length) refuse('payload overflow');
595
+ produced = end;
596
+ return subarray.call(this, begin, end);
597
+ };
598
+ payload = inflateSync(stored, { out });
599
+ if (produced !== header.payloadLength) return null;
600
+ }
601
+ else return null;
602
+ if (payload.length !== header.payloadLength) return null;
603
+ const payloadBytes = payload.buffer.slice(payload.byteOffset, payload.byteOffset + payload.byteLength);
604
+ const decode = reader(payloadBytes, 0, nodes);
605
+ const geometries = header.geometries.map((data) => readGeometry(data, decode));
606
+ let materials;
607
+ // Restored templates retain recipes too, without enabling capture in play.
608
+ beginTemplateCapture();
609
+ try {
610
+ materials = header.materials.map((data) => readMaterial(data, decode));
611
+ } finally {
612
+ endTemplateCapture();
613
+ }
614
+ const parents = new Set([0]);
615
+ header.tree.forEach((data, index) => {
616
+ const node = nodes[index];
617
+ const props = decode(data.props);
618
+ if (!Array.isArray(data.children) || props.length !== objectFields.length || new Set(props.map(([key]) => key)).size !== objectFields.length) refuse('object fields');
619
+ for (const [key, value] of props) {
620
+ if (!objectFields.includes(key) || typeof value !== typeof node[key]) refuse('object property');
621
+ node[key] = value;
622
+ }
623
+ for (const [field, size] of [['position', 3], ['quaternion', 4], ['scale', 3], ['up', 3], ['matrix', 16], ['matrixWorld', 16]]) {
624
+ const array = decode(data[field]);
625
+ if (!(array instanceof Float64Array) || array.length !== size) refuse('transform');
626
+ node[field].fromArray(array);
627
+ }
628
+ const rotation = decode(data.rotation);
629
+ if (!(rotation instanceof THREE.Euler) || !['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'].includes(rotation.order)) refuse('rotation');
630
+ // Public Euler/quaternion setters convert one into the other. Motion
631
+ // reads Euler angles (including whole turns), so preserve both verbatim.
632
+ // These THREE internals are guarded by the revision in the header.
633
+ node.rotation._x = rotation.x;
634
+ node.rotation._y = rotation.y;
635
+ node.rotation._z = rotation.z;
636
+ node.rotation._order = rotation.order;
637
+ node.layers.mask = data.layers;
638
+ node.userData = decode(data.userData);
639
+ if (node.isMesh) {
640
+ node.geometry = resource(geometries, data.geometry);
641
+ node.material = Array.isArray(data.material) ? data.material.map((id) => resource(materials, id)) : resource(materials, data.material);
642
+ // THREE ignores group material indices for a single material (primitive
643
+ // BoxGeometry, for example, still carries its six face groups).
644
+ if (Array.isArray(node.material) && (!node.material.length || node.geometry.groups.some((group) => group.materialIndex >= node.material.length))) refuse('group material index');
645
+ }
646
+ if (node.isInstancedMesh) {
647
+ node.instanceMatrix = readAttribute(data.instanceMatrix, decode, 16);
648
+ node.instanceColor = readAttribute(data.instanceColor, decode);
649
+ if (node.instanceMatrix?.itemSize !== 16 || node.instanceColor && (node.instanceColor.itemSize !== 3 || node.instanceColor.count < data.count) ||
650
+ !Number.isInteger(data.count) || data.count < 0 || data.count > node.instanceMatrix.count) refuse('instance count');
651
+ node.count = data.count;
652
+ readBounds(node, data, decode);
653
+ if (node.userData.lookOutline) node.raycast = OutlineMesh.prototype.raycast;
654
+ }
655
+ for (const child of data.children) {
656
+ // Preorder, exactly one parent, no cycles, duplicates or orphan nodes.
657
+ if (!Number.isInteger(child) || child <= index || !nodes[child] || parents.has(child)) refuse('tree');
658
+ parents.add(child);
659
+ node.add(nodes[child]);
660
+ }
661
+ });
662
+ if (parents.size !== nodes.length) return null;
663
+ const members = new Set(nodes);
664
+ for (const node of nodes) {
665
+ const parts = node.userData.modelParts;
666
+ if (parts !== undefined) {
667
+ if (!(parts instanceof Map)) refuse('modelParts');
668
+ for (const [id, part] of parts) if (!members.has(part) || part.userData.partId !== id) refuse('modelParts');
669
+ }
670
+ }
671
+ // Adding a child sets matrixWorldNeedsUpdate, so restore that flag last.
672
+ nodes.forEach((node, index) => { node.matrixWorldNeedsUpdate = decode(header.tree[index].props).find(([key]) => key === 'matrixWorldNeedsUpdate')[1]; });
673
+ restoreTemplateLook(nodes[0], readLookBakes(header.lookBakes, decode, geometries, materials));
674
+ return nodes[0];
675
+ } catch {
676
+ return null;
677
+ }
678
+ }
679
+
680
+ // Two independent FNV-1a 32-bit lanes, over UTF-16 code units. Multiplication
681
+ // stays in 32-bit integer arithmetic; no BigInt work in the model-text loop.
682
+ function hash(text) {
683
+ let a = 0x811c9dc5;
684
+ let b = 0x9e3779b9;
685
+ for (let index = 0; index < text.length; index++) {
686
+ const code = text.charCodeAt(index);
687
+ a = Math.imul(a ^ (code & 255), 0x01000193);
688
+ a = Math.imul(a ^ (code >>> 8), 0x01000193);
689
+ b = Math.imul(b ^ (code >>> 8), 0x01000193);
690
+ b = Math.imul(b ^ (code & 255), 0x01000193);
691
+ }
692
+ return [a, b].map((value) => (value >>> 0).toString(16).padStart(8, '0')).join('');
693
+ }
694
+
695
+ // options.models is the builder's file-text map. Missing/invalid references
696
+ // participate too: adding one later must invalidate a previously empty part.
697
+ // options.sprites is the builder's art map. Include readiness/identity for the
698
+ // model and every resolved reference, even though art currently always refuses.
699
+ // Stable art content signatures are still needed before art can persist across opens.
700
+ export function templateCacheKey(modelText, file = '', options = {}) {
701
+ const references = [];
702
+ const visit = (model, chain) => {
703
+ for (const part of model?.parts ?? []) {
704
+ if (part.kind !== 'model' || typeof part.src !== 'string' || !part.src) continue;
705
+ const path = resolveModelRef(part.src, chain.at(-1));
706
+ if (chain.includes(path) || chain.length > MAX_MODEL_DEPTH) continue;
707
+ const text = options.models?.[path];
708
+ const found = parseModelCached(text);
709
+ references.push([path, text ?? null, modelArtSignature(found, options.sprites)]);
710
+ if (found) visit(found, [...chain, path]);
711
+ }
712
+ };
713
+ const model = parseModelCached(modelText);
714
+ visit(model, [file]);
715
+ const inputs = [
716
+ THREE.REVISION, nativeEndian, modelText, file, references, modelArtSignature(model, options.sprites), lookIsEnabled(),
717
+ options.optimize ?? false, options.budget ?? null, options.dropEmptyParts ?? false,
718
+ options.bakesLookLater ?? false, options.skipSurfaceBakes ?? false, options.artSignature ?? null,
719
+ ];
720
+ return `template:${TEMPLATE_CACHE_VERSION}:${hash(JSON.stringify(writer(new Map()).encode(inputs)))}`;
721
+ }
722
+