@fleox/agent3d 0.0.0-stage → 0.2.0

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 (455) hide show
  1. package/LICENSE +143 -0
  2. package/README.md +172 -2
  3. package/changelog.json +56 -0
  4. package/dist/agent/agent3d.mjs +11242 -0
  5. package/dist/agent/chunks/assets-BUUM9TUB.mjs +2448 -0
  6. package/dist/agent/chunks/browser-t_JL_B82.mjs +226 -0
  7. package/dist/agent/chunks/cdp-CaKRRzMX.mjs +177 -0
  8. package/dist/agent/chunks/check-CBO3Ekx1.mjs +971 -0
  9. package/dist/agent/chunks/export-BCI8vKw8.mjs +1130 -0
  10. package/dist/agent/chunks/gif-DQznzHTL.mjs +319 -0
  11. package/dist/agent/chunks/gltf-f_f0-OiV.mjs +207 -0
  12. package/dist/agent/chunks/imageCodec-BpDU9Lsq.mjs +101 -0
  13. package/dist/agent/chunks/jsonPath-DUCe1JpS.mjs +155 -0
  14. package/dist/agent/chunks/meshoptimizer-C-tN9jn5.mjs +1165 -0
  15. package/dist/agent/chunks/mp4-aOALfp3s.mjs +130 -0
  16. package/dist/agent/chunks/objects-DBAws7uf.mjs +53 -0
  17. package/dist/agent/chunks/optimizeSizing-CkZ3fZRp.mjs +540 -0
  18. package/dist/agent/chunks/package-Ck7_Nszg.mjs +75 -0
  19. package/dist/agent/chunks/png-DXfSGJZt.mjs +91 -0
  20. package/dist/agent/chunks/render-Cbuhz5uW.mjs +1511 -0
  21. package/dist/agent/chunks/rolldown-runtime-ebOQtxsr.mjs +18 -0
  22. package/dist/agent/chunks/scene-BgajNvBf.mjs +444 -0
  23. package/dist/agent/chunks/server-CACCerkZ.mjs +237 -0
  24. package/dist/agent/chunks/suggest-Cpcgv1RP.mjs +46 -0
  25. package/dist/agent/chunks/tools-DT2tetIK.mjs +1412 -0
  26. package/dist/agent/chunks/tree-BrNYGui2.mjs +75 -0
  27. package/dist/agent/chunks/webpAnim-qaq9YgKl.mjs +132 -0
  28. package/dist/runtime/agent3d-runtime.js +373 -0
  29. package/dist/runtime/agent3d-runtime.single.js +7360 -0
  30. package/dist/runtime/chunks/BufferGeometryUtils-Re3wQkXp.js +1 -0
  31. package/dist/runtime/chunks/EXRLoader-Bzm84si5.js +1 -0
  32. package/dist/runtime/chunks/FontLoader-BocwqK8V.js +2 -0
  33. package/dist/runtime/chunks/GLTFLoader-DHp1wv6J.js +1 -0
  34. package/dist/runtime/chunks/GroundedSkybox-esvlRCO0.js +1 -0
  35. package/dist/runtime/chunks/HDRLoader-DHrHp8fs.js +5 -0
  36. package/dist/runtime/chunks/OrbitControls-sjN2MF0e.js +1 -0
  37. package/dist/runtime/chunks/RectAreaLightUniformsLib-_mZ62yWn.js +1 -0
  38. package/dist/runtime/chunks/RoomEnvironment-CL4UR6ZW.js +1 -0
  39. package/dist/runtime/chunks/RoundedBoxGeometry-x-ot8ZSh.js +1 -0
  40. package/dist/runtime/chunks/SVGLoader-hRF0EwD-.js +1 -0
  41. package/dist/runtime/chunks/SkeletonUtils-DHlReJx3.js +1 -0
  42. package/dist/runtime/chunks/Sky-BrLN9Fk5.js +243 -0
  43. package/dist/runtime/chunks/audio-DbVNbf-r.js +1 -0
  44. package/dist/runtime/chunks/catalog-DL6sgPay.js +1 -0
  45. package/dist/runtime/chunks/easing-CXSz2e6P.js +1 -0
  46. package/dist/runtime/chunks/extrude-m04mghOS.js +1 -0
  47. package/dist/runtime/chunks/game-BoG2S6g4.js +20 -0
  48. package/dist/runtime/chunks/generators-OHhFCc2E.js +331 -0
  49. package/dist/runtime/chunks/materials-C2uffFEd.js +107 -0
  50. package/dist/runtime/chunks/meshGradient.glsl-BMatplLA.js +88 -0
  51. package/dist/runtime/chunks/meshopt_decoder.module-DXTYc6wn.js +1 -0
  52. package/dist/runtime/chunks/model-D-4xZz21.js +1 -0
  53. package/dist/runtime/chunks/params-DdApDOBw.js +1 -0
  54. package/dist/runtime/chunks/physicsHost-DPaVdM0R.js +1 -0
  55. package/dist/runtime/chunks/postfx-BpBXjLX3.js +1527 -0
  56. package/dist/runtime/chunks/postfx-i_J5Vf-l.js +1 -0
  57. package/dist/runtime/chunks/random-eeej60NW.js +1 -0
  58. package/dist/runtime/chunks/shaders-CmeJRio1.js +443 -0
  59. package/dist/runtime/chunks/svg-B3nZaQFD.js +1 -0
  60. package/dist/runtime/chunks/text-CmkU-b0C.js +2 -0
  61. package/dist/runtime/chunks/three.module-W4hp4qHb.js +4225 -0
  62. package/dist/runtime/chunks/toon-B5Jhf37V.js +6 -0
  63. package/dist/runtime/chunks/util-THUewKBk.js +1 -0
  64. package/dist/studio/assets/BufferGeometryUtils-wW9vV1l2.js +1 -0
  65. package/dist/studio/assets/EXRLoader-f8U8jnlr.js +1 -0
  66. package/dist/studio/assets/FontLoader-9sHudKzD.js +2 -0
  67. package/dist/studio/assets/GLTFLoader-C3C_3K62.js +1 -0
  68. package/dist/studio/assets/GroundedSkybox-BTqmv4fv.js +1 -0
  69. package/dist/studio/assets/HDRLoader-CkQyrTWY.js +5 -0
  70. package/dist/studio/assets/OrbitControls-fcOgB96a.js +1 -0
  71. package/dist/studio/assets/RectAreaLightUniformsLib-CZHWO9xf.js +1 -0
  72. package/dist/studio/assets/RoomEnvironment-BsISzuCp.js +1 -0
  73. package/dist/studio/assets/SVGLoader-BIkQDT66.js +1 -0
  74. package/dist/studio/assets/SkeletonUtils-CG5akqME.js +1 -0
  75. package/dist/studio/assets/Sky-C282PFL1.js +243 -0
  76. package/dist/studio/assets/audio-JD1kyX0A.js +1 -0
  77. package/dist/studio/assets/camera-BhKdE9ej.js +2 -0
  78. package/dist/studio/assets/editor-BgY_RoRd.js +1 -0
  79. package/dist/studio/assets/extrude-CnayHczh.js +1 -0
  80. package/dist/studio/assets/game-Dv5s4eMN.js +19 -0
  81. package/dist/studio/assets/generators-DVX3bAxe.js +331 -0
  82. package/dist/studio/assets/index-BQT0otii.css +1 -0
  83. package/dist/studio/assets/index-Dh-2Y34U.js +479 -0
  84. package/dist/studio/assets/meshopt_decoder.module-DXTYc6wn.js +1 -0
  85. package/dist/studio/assets/meshoptimizer-BCSwHBL3.js +1 -0
  86. package/dist/studio/assets/model-XZSP52pV.js +2 -0
  87. package/dist/studio/assets/physicsHost-C84FddIe.js +1 -0
  88. package/dist/studio/assets/postfx-BWWXb8i8.js +1527 -0
  89. package/dist/studio/assets/runtime-k_MFerbJ.js +572 -0
  90. package/dist/studio/assets/shaders-BEznGIct.js +443 -0
  91. package/dist/studio/assets/svg-DT8kx37i.js +2 -0
  92. package/dist/studio/assets/text-5DsJJHcj.js +3 -0
  93. package/dist/studio/assets/three.module-ByMn_ZTv.js +4225 -0
  94. package/dist/studio/index.html +16 -0
  95. package/library/LICENSES.md +77 -0
  96. package/library/fonts/LICENSES.md +42 -0
  97. package/library/fonts/anton.typeface.json +1 -0
  98. package/library/fonts/bebas-neue.typeface.json +1 -0
  99. package/library/fonts/display.typeface.json +1 -0
  100. package/library/fonts/inter-black.typeface.json +1 -0
  101. package/library/fonts/lobster.typeface.json +1 -0
  102. package/library/fonts/mono.typeface.json +1 -0
  103. package/library/fonts/montserrat-extrabold.typeface.json +1 -0
  104. package/library/fonts/pacifico.typeface.json +1 -0
  105. package/library/fonts/sans-bold.typeface.json +1 -0
  106. package/library/fonts/sans.typeface.json +1 -0
  107. package/library/fonts/serif-bold.typeface.json +1 -0
  108. package/library/fonts/serif.typeface.json +1 -0
  109. package/library/fonts/space-grotesk-bold.typeface.json +1 -0
  110. package/library/hdri/beach.hdr +0 -0
  111. package/library/hdri/beach.jpg +0 -0
  112. package/library/hdri/city.hdr +0 -0
  113. package/library/hdri/city.jpg +0 -0
  114. package/library/hdri/forest.hdr +0 -0
  115. package/library/hdri/forest.jpg +0 -0
  116. package/library/hdri/night-city.hdr +0 -0
  117. package/library/hdri/night-city.jpg +0 -0
  118. package/library/hdri/night.hdr +0 -0
  119. package/library/hdri/night.jpg +0 -0
  120. package/library/hdri/sky.hdr +0 -0
  121. package/library/hdri/sky.jpg +0 -0
  122. package/library/hdri/softbox.hdr +0 -0
  123. package/library/hdri/softbox.jpg +0 -0
  124. package/library/hdri/studio.hdr +0 -0
  125. package/library/hdri/studio.jpg +0 -0
  126. package/library/hdri/sunset.hdr +0 -0
  127. package/library/hdri/sunset.jpg +0 -0
  128. package/library/hdri/warehouse.hdr +0 -0
  129. package/library/hdri/warehouse.jpg +0 -0
  130. package/library/index.json +5510 -0
  131. package/library/models/animals/fish.glb +0 -0
  132. package/library/models/animals/fox.glb +0 -0
  133. package/library/models/buildings/castle.glb +0 -0
  134. package/library/models/buildings/house.glb +0 -0
  135. package/library/models/buildings/market.glb +0 -0
  136. package/library/models/buildings/tavern.glb +0 -0
  137. package/library/models/buildings/tower.glb +0 -0
  138. package/library/models/buildings/windmill.glb +0 -0
  139. package/library/models/characters/barbarian.glb +0 -0
  140. package/library/models/characters/knight.glb +0 -0
  141. package/library/models/characters/mage.glb +0 -0
  142. package/library/models/characters/mini-soldier.glb +0 -0
  143. package/library/models/characters/platformer-hero.glb +0 -0
  144. package/library/models/characters/robot.glb +0 -0
  145. package/library/models/characters/rogue.glb +0 -0
  146. package/library/models/characters/skeleton.glb +0 -0
  147. package/library/models/city/building-a.glb +0 -0
  148. package/library/models/city/building-b.glb +0 -0
  149. package/library/models/city/building-tall.glb +0 -0
  150. package/library/models/city/fire-hydrant.glb +0 -0
  151. package/library/models/city/road-corner.glb +0 -0
  152. package/library/models/city/road-crossing.glb +0 -0
  153. package/library/models/city/road-junction.glb +0 -0
  154. package/library/models/city/road-straight.glb +0 -0
  155. package/library/models/city/streetlight.glb +0 -0
  156. package/library/models/city/suburban-house.glb +0 -0
  157. package/library/models/city/traffic-light.glb +0 -0
  158. package/library/models/city/water-tower.glb +0 -0
  159. package/library/models/food/apple.glb +0 -0
  160. package/library/models/food/avocado.glb +0 -0
  161. package/library/models/food/baguette.glb +0 -0
  162. package/library/models/food/bread-loaf.glb +0 -0
  163. package/library/models/food/burger.glb +0 -0
  164. package/library/models/food/carrot.glb +0 -0
  165. package/library/models/food/cheese.glb +0 -0
  166. package/library/models/food/cookie.glb +0 -0
  167. package/library/models/food/croissant.glb +0 -0
  168. package/library/models/food/cupcake.glb +0 -0
  169. package/library/models/food/dinner-plate.glb +0 -0
  170. package/library/models/food/donut.glb +0 -0
  171. package/library/models/food/ketchup.glb +0 -0
  172. package/library/models/food/mug.glb +0 -0
  173. package/library/models/food/pain-au-chocolat.glb +0 -0
  174. package/library/models/food/stew.glb +0 -0
  175. package/library/models/food/tomato.glb +0 -0
  176. package/library/models/food/veggie-burger.glb +0 -0
  177. package/library/models/nature/bush.glb +0 -0
  178. package/library/models/nature/cactus.glb +0 -0
  179. package/library/models/nature/cloud.glb +0 -0
  180. package/library/models/nature/fir-tree.glb +0 -0
  181. package/library/models/nature/forest-patch.glb +0 -0
  182. package/library/models/nature/grass-small.glb +0 -0
  183. package/library/models/nature/grass.glb +0 -0
  184. package/library/models/nature/hex-grass.glb +0 -0
  185. package/library/models/nature/hex-water.glb +0 -0
  186. package/library/models/nature/hills.glb +0 -0
  187. package/library/models/nature/mountain.glb +0 -0
  188. package/library/models/nature/pine-autumn.glb +0 -0
  189. package/library/models/nature/pine-tree.glb +0 -0
  190. package/library/models/nature/pumpkin.glb +0 -0
  191. package/library/models/nature/rock-flat.glb +0 -0
  192. package/library/models/nature/rock.glb +0 -0
  193. package/library/models/nature/tree-dead.glb +0 -0
  194. package/library/models/nature/tree-slim.glb +0 -0
  195. package/library/models/nature/trees-cluster.glb +0 -0
  196. package/library/models/nature/waterlily.glb +0 -0
  197. package/library/models/platformer/blaster.glb +0 -0
  198. package/library/models/platformer/block-coin.glb +0 -0
  199. package/library/models/platformer/brick.glb +0 -0
  200. package/library/models/platformer/coin.glb +0 -0
  201. package/library/models/platformer/enemy-flying.glb +0 -0
  202. package/library/models/platformer/flag.glb +0 -0
  203. package/library/models/platformer/platform-falling.glb +0 -0
  204. package/library/models/platformer/platform-grass-round.glb +0 -0
  205. package/library/models/platformer/platform-large.glb +0 -0
  206. package/library/models/platformer/platform-medium.glb +0 -0
  207. package/library/models/platformer/platform.glb +0 -0
  208. package/library/models/platformer/target.glb +0 -0
  209. package/library/models/platformer/track-corner.glb +0 -0
  210. package/library/models/platformer/track-straight.glb +0 -0
  211. package/library/models/platformer/wall-low.glb +0 -0
  212. package/library/models/products/boombox.glb +0 -0
  213. package/library/models/products/iridescent-lamp.glb +0 -0
  214. package/library/models/products/lantern.glb +0 -0
  215. package/library/models/products/lounge-chair.glb +0 -0
  216. package/library/models/products/sneaker.glb +0 -0
  217. package/library/models/products/velvet-sofa.glb +0 -0
  218. package/library/models/products/water-bottle.glb +0 -0
  219. package/library/models/props/alarm-clock.glb +0 -0
  220. package/library/models/props/armchair.glb +0 -0
  221. package/library/models/props/barrel.glb +0 -0
  222. package/library/models/props/bench.glb +0 -0
  223. package/library/models/props/brass-vase.glb +0 -0
  224. package/library/models/props/chest.glb +0 -0
  225. package/library/models/props/coffee-table.glb +0 -0
  226. package/library/models/props/coin-stack.glb +0 -0
  227. package/library/models/props/coin.glb +0 -0
  228. package/library/models/props/couch.glb +0 -0
  229. package/library/models/props/crate.glb +0 -0
  230. package/library/models/props/flag.glb +0 -0
  231. package/library/models/props/gravestone.glb +0 -0
  232. package/library/models/props/key.glb +0 -0
  233. package/library/models/props/lamp.glb +0 -0
  234. package/library/models/props/lantern.glb +0 -0
  235. package/library/models/props/marble-bust.glb +0 -0
  236. package/library/models/props/modern-armchair.glb +0 -0
  237. package/library/models/props/potted-succulent.glb +0 -0
  238. package/library/models/props/rubber-duck.glb +0 -0
  239. package/library/models/props/shield.glb +0 -0
  240. package/library/models/props/sword-shield.glb +0 -0
  241. package/library/models/props/sword.glb +0 -0
  242. package/library/models/props/table.glb +0 -0
  243. package/library/models/props/tent.glb +0 -0
  244. package/library/models/props/torch.glb +0 -0
  245. package/library/models/props/trophy.glb +0 -0
  246. package/library/models/space/base-module.glb +0 -0
  247. package/library/models/space/lander.glb +0 -0
  248. package/library/models/space/landing-pad.glb +0 -0
  249. package/library/models/space/rocks.glb +0 -0
  250. package/library/models/space/solar-panel.glb +0 -0
  251. package/library/models/space/space-truck.glb +0 -0
  252. package/library/models/space/wind-turbine.glb +0 -0
  253. package/library/models/vehicles/car.glb +0 -0
  254. package/library/models/vehicles/hatchback.glb +0 -0
  255. package/library/models/vehicles/motorcycle.glb +0 -0
  256. package/library/models/vehicles/police-car.glb +0 -0
  257. package/library/models/vehicles/taxi.glb +0 -0
  258. package/library/models/vehicles/truck.glb +0 -0
  259. package/library/sources.json +2856 -0
  260. package/library/textures/brick-color.jpg +0 -0
  261. package/library/textures/brick-normal.jpg +0 -0
  262. package/library/textures/brick-roughness.jpg +0 -0
  263. package/library/textures/concrete-color.jpg +0 -0
  264. package/library/textures/concrete-normal.jpg +0 -0
  265. package/library/textures/concrete-roughness.jpg +0 -0
  266. package/library/textures/fabric-color.jpg +0 -0
  267. package/library/textures/fabric-normal.jpg +0 -0
  268. package/library/textures/fabric-roughness.jpg +0 -0
  269. package/library/textures/grass-ground-color.jpg +0 -0
  270. package/library/textures/grass-ground-normal.jpg +0 -0
  271. package/library/textures/grass-ground-roughness.jpg +0 -0
  272. package/library/textures/rusty-metal-color.jpg +0 -0
  273. package/library/textures/rusty-metal-normal.jpg +0 -0
  274. package/library/textures/rusty-metal-roughness.jpg +0 -0
  275. package/library/textures/wood-planks-color.jpg +0 -0
  276. package/library/textures/wood-planks-normal.jpg +0 -0
  277. package/library/textures/wood-planks-roughness.jpg +0 -0
  278. package/package.json +67 -4
  279. package/plugin/.claude-plugin/plugin.json +19 -0
  280. package/plugin/skills/agent3d-assets/SKILL.md +140 -0
  281. package/plugin/skills/agent3d-assets/references/sources.md +33 -0
  282. package/plugin/skills/agent3d-create/SKILL.md +141 -0
  283. package/plugin/skills/agent3d-create/references/art-direction.md +144 -0
  284. package/plugin/skills/agent3d-create/references/recipes.md +1357 -0
  285. package/plugin/skills/agent3d-edit/SKILL.md +121 -0
  286. package/plugin/skills/agent3d-edit/references/patch-ops.md +278 -0
  287. package/plugin/skills/agent3d-game/SKILL.md +111 -0
  288. package/plugin/skills/agent3d-game/references/game-patterns.md +262 -0
  289. package/plugin/skills/agent3d-game/references/script-api.md +211 -0
  290. package/plugin/skills/agent3d-publish/SKILL.md +161 -0
  291. package/plugin/skills/agent3d-publish/references/integrations.md +221 -0
  292. package/templates/banner-aurora-night/README.md +15 -0
  293. package/templates/banner-aurora-night/agent3d.json +8 -0
  294. package/templates/banner-aurora-night/preview.png +0 -0
  295. package/templates/banner-aurora-night/scene.json +327 -0
  296. package/templates/banner-aurora-night/template.json +24 -0
  297. package/templates/banner-data-bars/README.md +15 -0
  298. package/templates/banner-data-bars/agent3d.json +8 -0
  299. package/templates/banner-data-bars/preview.png +0 -0
  300. package/templates/banner-data-bars/scene.json +222 -0
  301. package/templates/banner-data-bars/template.json +25 -0
  302. package/templates/banner-floating-shapes/README.md +15 -0
  303. package/templates/banner-floating-shapes/agent3d.json +8 -0
  304. package/templates/banner-floating-shapes/preview.png +0 -0
  305. package/templates/banner-floating-shapes/scene.json +703 -0
  306. package/templates/banner-floating-shapes/template.json +24 -0
  307. package/templates/banner-gradient-blob/README.md +16 -0
  308. package/templates/banner-gradient-blob/agent3d.json +8 -0
  309. package/templates/banner-gradient-blob/preview.png +0 -0
  310. package/templates/banner-gradient-blob/scene.json +330 -0
  311. package/templates/banner-gradient-blob/template.json +21 -0
  312. package/templates/banner-liquid-chrome/README.md +16 -0
  313. package/templates/banner-liquid-chrome/agent3d.json +8 -0
  314. package/templates/banner-liquid-chrome/preview.png +0 -0
  315. package/templates/banner-liquid-chrome/scene.json +290 -0
  316. package/templates/banner-liquid-chrome/template.json +24 -0
  317. package/templates/banner-logo-extrude/README.md +24 -0
  318. package/templates/banner-logo-extrude/agent3d.json +8 -0
  319. package/templates/banner-logo-extrude/assets/logo.svg +6 -0
  320. package/templates/banner-logo-extrude/assets/manifest.json +13 -0
  321. package/templates/banner-logo-extrude/preview.png +0 -0
  322. package/templates/banner-logo-extrude/scene.json +332 -0
  323. package/templates/banner-logo-extrude/template.json +22 -0
  324. package/templates/banner-neon-title/README.md +18 -0
  325. package/templates/banner-neon-title/agent3d.json +8 -0
  326. package/templates/banner-neon-title/preview.png +0 -0
  327. package/templates/banner-neon-title/scene.json +494 -0
  328. package/templates/banner-neon-title/template.json +25 -0
  329. package/templates/banner-wave-grid/README.md +18 -0
  330. package/templates/banner-wave-grid/agent3d.json +8 -0
  331. package/templates/banner-wave-grid/preview.png +0 -0
  332. package/templates/banner-wave-grid/scene.json +217 -0
  333. package/templates/banner-wave-grid/template.json +23 -0
  334. package/templates/card-hover-3d/README.md +16 -0
  335. package/templates/card-hover-3d/agent3d.json +8 -0
  336. package/templates/card-hover-3d/preview.png +0 -0
  337. package/templates/card-hover-3d/scene.json +359 -0
  338. package/templates/card-hover-3d/template.json +21 -0
  339. package/templates/card-product-tilt/README.md +14 -0
  340. package/templates/card-product-tilt/agent3d.json +8 -0
  341. package/templates/card-product-tilt/preview.png +0 -0
  342. package/templates/card-product-tilt/scene.json +296 -0
  343. package/templates/card-product-tilt/template.json +23 -0
  344. package/templates/character-mascot-hero/README.md +19 -0
  345. package/templates/character-mascot-hero/agent3d.json +8 -0
  346. package/templates/character-mascot-hero/preview.png +0 -0
  347. package/templates/character-mascot-hero/scene.json +512 -0
  348. package/templates/character-mascot-hero/template.json +8 -0
  349. package/templates/character-showcase/README.md +27 -0
  350. package/templates/character-showcase/agent3d.json +8 -0
  351. package/templates/character-showcase/preview.png +0 -0
  352. package/templates/character-showcase/scene.json +440 -0
  353. package/templates/character-showcase/template.json +24 -0
  354. package/templates/diorama-city/README.md +21 -0
  355. package/templates/diorama-city/agent3d.json +8 -0
  356. package/templates/diorama-city/preview.png +0 -0
  357. package/templates/diorama-city/scene.json +432 -0
  358. package/templates/diorama-city/template.json +21 -0
  359. package/templates/game-basket/README.md +25 -0
  360. package/templates/game-basket/agent3d.json +8 -0
  361. package/templates/game-basket/preview.png +0 -0
  362. package/templates/game-basket/scene.json +640 -0
  363. package/templates/game-basket/scripts/basket.js +176 -0
  364. package/templates/game-basket/template.json +8 -0
  365. package/templates/game-coin-collector/README.md +28 -0
  366. package/templates/game-coin-collector/agent3d.json +8 -0
  367. package/templates/game-coin-collector/preview.png +0 -0
  368. package/templates/game-coin-collector/scene.json +900 -0
  369. package/templates/game-coin-collector/scripts/collector.js +210 -0
  370. package/templates/game-coin-collector/template.json +19 -0
  371. package/templates/game-maze/README.md +24 -0
  372. package/templates/game-maze/agent3d.json +8 -0
  373. package/templates/game-maze/preview.png +0 -0
  374. package/templates/game-maze/scene.json +315 -0
  375. package/templates/game-maze/scripts/maze.js +168 -0
  376. package/templates/game-maze/template.json +18 -0
  377. package/templates/game-physics-playground/README.md +30 -0
  378. package/templates/game-physics-playground/agent3d.json +8 -0
  379. package/templates/game-physics-playground/preview.png +0 -0
  380. package/templates/game-physics-playground/scene.json +1712 -0
  381. package/templates/game-physics-playground/scripts/playground.js +151 -0
  382. package/templates/game-physics-playground/template.json +19 -0
  383. package/templates/game-platformer/README.md +26 -0
  384. package/templates/game-platformer/agent3d.json +8 -0
  385. package/templates/game-platformer/preview.png +0 -0
  386. package/templates/game-platformer/scene.json +1063 -0
  387. package/templates/game-platformer/scripts/platformer.js +222 -0
  388. package/templates/game-platformer/template.json +8 -0
  389. package/templates/game-runner/README.md +30 -0
  390. package/templates/game-runner/agent3d.json +8 -0
  391. package/templates/game-runner/preview.png +0 -0
  392. package/templates/game-runner/scene.json +1317 -0
  393. package/templates/game-runner/scripts/runner.js +263 -0
  394. package/templates/game-runner/template.json +18 -0
  395. package/templates/game-tap-targets/README.md +21 -0
  396. package/templates/game-tap-targets/agent3d.json +8 -0
  397. package/templates/game-tap-targets/preview.png +0 -0
  398. package/templates/game-tap-targets/scene.json +924 -0
  399. package/templates/game-tap-targets/scripts/targets.js +159 -0
  400. package/templates/game-tap-targets/template.json +19 -0
  401. package/templates/hero-floating-island/README.md +18 -0
  402. package/templates/hero-floating-island/agent3d.json +8 -0
  403. package/templates/hero-floating-island/preview.png +0 -0
  404. package/templates/hero-floating-island/scene.json +658 -0
  405. package/templates/hero-floating-island/template.json +8 -0
  406. package/templates/hero-perfume-luxury/README.md +18 -0
  407. package/templates/hero-perfume-luxury/agent3d.json +8 -0
  408. package/templates/hero-perfume-luxury/preview.png +0 -0
  409. package/templates/hero-perfume-luxury/scene.json +529 -0
  410. package/templates/hero-perfume-luxury/template.json +27 -0
  411. package/templates/hero-product-turntable/README.md +16 -0
  412. package/templates/hero-product-turntable/agent3d.json +8 -0
  413. package/templates/hero-product-turntable/preview.png +0 -0
  414. package/templates/hero-product-turntable/scene.json +225 -0
  415. package/templates/hero-product-turntable/template.json +21 -0
  416. package/templates/hero-saas-globe/README.md +16 -0
  417. package/templates/hero-saas-globe/agent3d.json +8 -0
  418. package/templates/hero-saas-globe/preview.png +0 -0
  419. package/templates/hero-saas-globe/scene.json +318 -0
  420. package/templates/hero-saas-globe/template.json +24 -0
  421. package/templates/hero-scroll-story/README.md +26 -0
  422. package/templates/hero-scroll-story/agent3d.json +8 -0
  423. package/templates/hero-scroll-story/preview.png +0 -0
  424. package/templates/hero-scroll-story/scene.json +642 -0
  425. package/templates/hero-scroll-story/template.json +22 -0
  426. package/templates/hero-sneaker-showcase/README.md +19 -0
  427. package/templates/hero-sneaker-showcase/agent3d.json +8 -0
  428. package/templates/hero-sneaker-showcase/preview.png +0 -0
  429. package/templates/hero-sneaker-showcase/scene.json +523 -0
  430. package/templates/hero-sneaker-showcase/template.json +23 -0
  431. package/templates/hero-space-planet/README.md +17 -0
  432. package/templates/hero-space-planet/agent3d.json +8 -0
  433. package/templates/hero-space-planet/preview.png +0 -0
  434. package/templates/hero-space-planet/scene.json +330 -0
  435. package/templates/hero-space-planet/template.json +21 -0
  436. package/templates/landscape-island/README.md +21 -0
  437. package/templates/landscape-island/agent3d.json +8 -0
  438. package/templates/landscape-island/preview.png +0 -0
  439. package/templates/landscape-island/scene.json +716 -0
  440. package/templates/landscape-island/template.json +24 -0
  441. package/templates/landscape-night-galaxy/README.md +25 -0
  442. package/templates/landscape-night-galaxy/agent3d.json +8 -0
  443. package/templates/landscape-night-galaxy/preview.png +0 -0
  444. package/templates/landscape-night-galaxy/scene.json +403 -0
  445. package/templates/landscape-night-galaxy/template.json +8 -0
  446. package/templates/landscape-valley-sunset/README.md +20 -0
  447. package/templates/landscape-valley-sunset/agent3d.json +8 -0
  448. package/templates/landscape-valley-sunset/preview.png +0 -0
  449. package/templates/landscape-valley-sunset/scene.json +265 -0
  450. package/templates/landscape-valley-sunset/template.json +22 -0
  451. package/templates/scene-cozy-room/README.md +21 -0
  452. package/templates/scene-cozy-room/agent3d.json +8 -0
  453. package/templates/scene-cozy-room/preview.png +0 -0
  454. package/templates/scene-cozy-room/scene.json +728 -0
  455. package/templates/scene-cozy-room/template.json +8 -0
@@ -0,0 +1,2448 @@
1
+ import { createRequire as __a3dRequire } from "node:module";
2
+ import { fileURLToPath as __a3dPath } from "node:url";
3
+ import { dirname as __a3dDirname } from "node:path";
4
+ __a3dRequire(import.meta.url);
5
+ const __filename = __a3dPath(import.meta.url);
6
+ __a3dDirname(__filename);
7
+ import { t as __exportAll } from "./rolldown-runtime-ebOQtxsr.mjs";
8
+ import { D as slugify, F as normalizePath, M as readJsonOr, O as KB, P as writeJson, a as ASSET_MANIFEST_FILE, d as saveScene, j as nowIso, k as OpsError, u as readSceneFile } from "../agent3d.mjs";
9
+ import { t as closest } from "./suggest-Cpcgv1RP.mjs";
10
+ import { a as collectAssetRefs, i as planTextureSizes, l as visitAssetRefs, n as imageHeader, s as kindFromPath } from "./optimizeSizing-CkZ3fZRp.mjs";
11
+ import { i as modelInfo, r as modelFileBounds } from "./gltf-f_f0-OiV.mjs";
12
+ // src/ops/zip.ts
13
+ var ZipError = class extends Error {
14
+ name = "ZipError";
15
+ };
16
+ var u16 = (b, o) => b[o] | b[o + 1] << 8;
17
+ var u32 = (b, o) => (b[o] | b[o + 1] << 8 | b[o + 2] << 16 | b[o + 3] << 24) >>> 0;
18
+ var utf8 = new TextDecoder();
19
+ function listZip(zip) {
20
+ let eocd = -1;
21
+ for (let i = zip.length - 22; i >= Math.max(0, zip.length - 22 - 65535); i--) if (u32(zip, i) === 101010256) {
22
+ eocd = i;
23
+ break;
24
+ }
25
+ if (eocd < 0) throw new ZipError("Not a ZIP file (end of central directory not found).");
26
+ const count = u16(zip, eocd + 10);
27
+ let p = u32(zip, eocd + 16);
28
+ if (p === 4294967295) throw new ZipError("ZIP64 archives are not supported.");
29
+ const entries = [];
30
+ for (let i = 0; i < count; i++) {
31
+ if (u32(zip, p) !== 33639248) throw new ZipError("Corrupt ZIP central directory.");
32
+ const method = u16(zip, p + 10);
33
+ const crc32 = u32(zip, p + 16);
34
+ const compressedSize = u32(zip, p + 20);
35
+ const size = u32(zip, p + 24);
36
+ const nameLen = u16(zip, p + 28);
37
+ const extraLen = u16(zip, p + 30);
38
+ const commentLen = u16(zip, p + 32);
39
+ const offset = u32(zip, p + 42);
40
+ const name = utf8.decode(zip.subarray(p + 46, p + 46 + nameLen));
41
+ entries.push({
42
+ name,
43
+ method,
44
+ compressedSize,
45
+ size,
46
+ crc32,
47
+ offset,
48
+ dir: name.endsWith("/")
49
+ });
50
+ p += 46 + nameLen + extraLen + commentLen;
51
+ }
52
+ return entries;
53
+ }
54
+ async function defaultInflate(data) {
55
+ const DS = globalThis.DecompressionStream;
56
+ if (!DS) throw new ZipError("Deflated ZIP entries need an inflate function (no DecompressionStream on this platform).");
57
+ const stream = new Blob([data]).stream().pipeThrough(new DS("deflate-raw"));
58
+ return new Uint8Array(await new Response(stream).arrayBuffer());
59
+ }
60
+ async function readZipEntry(zip, entry, inflate) {
61
+ const p = entry.offset;
62
+ if (u32(zip, p) !== 67324752) throw new ZipError(`Corrupt local header for ${entry.name}.`);
63
+ const start = p + 30 + u16(zip, p + 26) + u16(zip, p + 28);
64
+ const raw = zip.subarray(start, start + entry.compressedSize);
65
+ if (entry.method === 0) return raw.slice();
66
+ if (entry.method === 8) return await (inflate ?? defaultInflate)(raw);
67
+ throw new ZipError(`Unsupported compression method ${entry.method} for ${entry.name}.`);
68
+ }
69
+ async function readZip(zip, opts = {}) {
70
+ const out = {};
71
+ let total = 0;
72
+ for (const e of listZip(zip)) {
73
+ if (e.dir || e.name.startsWith("__MACOSX/") || e.name.split("/").includes("..")) continue;
74
+ if (opts.filter && !opts.filter(e.name)) continue;
75
+ total += e.size;
76
+ if (opts.maxBytes && total > opts.maxBytes) throw new ZipError(`ZIP content exceeds ${Math.round(opts.maxBytes / 1048576)} MB.`);
77
+ out[e.name] = await readZipEntry(zip, e, opts.inflate);
78
+ }
79
+ return out;
80
+ }
81
+ var CRC_TABLE = null;
82
+ function crc32(data) {
83
+ if (!CRC_TABLE) {
84
+ CRC_TABLE = /* @__PURE__ */ new Uint32Array(256);
85
+ for (let n = 0; n < 256; n++) {
86
+ let c = n;
87
+ for (let k = 0; k < 8; k++) c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
88
+ CRC_TABLE[n] = c >>> 0;
89
+ }
90
+ }
91
+ let c = 4294967295;
92
+ for (let i = 0; i < data.length; i++) c = CRC_TABLE[(c ^ data[i]) & 255] ^ c >>> 8;
93
+ return (c ^ 4294967295) >>> 0;
94
+ }
95
+ // src/ops/sources/types.ts
96
+ var SOURCE_IDS = [
97
+ "polyhaven",
98
+ "ambientcg",
99
+ "kenney",
100
+ "quaternius",
101
+ "khronos"
102
+ ];
103
+ var SourceError = class extends Error {
104
+ name = "SourceError";
105
+ };
106
+ async function fetchJson(fetch, url) {
107
+ let res;
108
+ try {
109
+ res = await fetch(url, { headers: { accept: "application/json" } });
110
+ } catch (e) {
111
+ throw new SourceError(`Network error for ${url}: ${e.message}`);
112
+ }
113
+ if (!res.ok) throw new SourceError(`HTTP ${res.status} for ${url}`);
114
+ return await res.json();
115
+ }
116
+ async function fetchBytes(fetch, url) {
117
+ let res;
118
+ try {
119
+ res = await fetch(url);
120
+ } catch (e) {
121
+ throw new SourceError(`Network error for ${url}: ${e.message}`);
122
+ }
123
+ if (!res.ok) throw new SourceError(`HTTP ${res.status} for ${url}`);
124
+ return new Uint8Array(await res.arrayBuffer());
125
+ }
126
+ function nearlyEqual(a, b) {
127
+ if (a === b) return true;
128
+ if (Math.abs(a.length - b.length) > 1) return false;
129
+ let i = 0;
130
+ let j = 0;
131
+ let edits = 0;
132
+ while (i < a.length && j < b.length) {
133
+ if (a[i] === b[j]) {
134
+ i++;
135
+ j++;
136
+ continue;
137
+ }
138
+ if (++edits > 1) return false;
139
+ if (a.length > b.length) i++;
140
+ else if (b.length > a.length) j++;
141
+ else {
142
+ i++;
143
+ j++;
144
+ }
145
+ }
146
+ return edits + (a.length - i) + (b.length - j) <= 1;
147
+ }
148
+ var singular = (w) => w.length > 3 && w.endsWith("s") && !w.endsWith("ss") ? w.slice(0, -1) : w;
149
+ function score(query, fields, opts = {}) {
150
+ const words = query.toLowerCase().split(/[\s,]+/).filter(Boolean);
151
+ if (!words.length) return 1;
152
+ const title = `${fields.title ?? ""} ${fields.id ?? ""}`.toLowerCase();
153
+ const tags = (fields.tags ?? []).map((t) => t.toLowerCase());
154
+ const extra = opts.strict ? "" : (fields.extra ?? "").toLowerCase();
155
+ let total = 0;
156
+ const titleWords = title.split(/[\s_\-/]+/).filter(Boolean);
157
+ const tagWords = tags.flatMap((t) => t.split(/[\s_\-/]+/)).filter(Boolean);
158
+ const extraWords = extra.split(/[^a-z0-9]+/).filter(Boolean);
159
+ for (const raw of words) {
160
+ const w = singular(raw);
161
+ const eq = (t) => t === raw || singular(t) === w;
162
+ let s = 0;
163
+ if (titleWords.some(eq)) s = 5;
164
+ else if (titleWords.some((t) => t.startsWith(w))) s = 3;
165
+ if (tags.some(eq)) s = Math.max(s, 4);
166
+ else if (tagWords.some((t) => eq(t) || t.startsWith(w))) s = Math.max(s, 2);
167
+ if (!s && w.length >= 4 && [...titleWords, ...tagWords].some((t) => t.length >= 4 && nearlyEqual(singular(t), w))) s = 1;
168
+ if (!s && extraWords.some((t) => t.startsWith(w))) s = 1;
169
+ if (!s) return 0;
170
+ total += s;
171
+ }
172
+ return total;
173
+ }
174
+ function rank(items, limit) {
175
+ return items.filter((x) => x.score > 0).sort((a, b) => b.score - a.score).slice(0, limit).map((x) => x.item);
176
+ }
177
+ // src/ops/sources/ambientcg.ts
178
+ var API$1 = "https://ambientcg.com/api/v2/full_json";
179
+ function downloadsOf(a) {
180
+ const out = {};
181
+ for (const folder of Object.values(a.downloadFolders ?? {})) for (const cat of Object.values(folder.downloadFiletypeCategories ?? {})) for (const d of cat.downloads ?? []) {
182
+ const url = d.downloadLink ?? d.fullDownloadPath;
183
+ if (url && d.attribute) out[d.attribute] = url;
184
+ }
185
+ return out;
186
+ }
187
+ function pickDownload(downloads, resolution) {
188
+ const keys = Object.keys(downloads);
189
+ if (!keys.length) throw new SourceError("This ambientCG asset has no downloads.");
190
+ const want = (resolution ?? "1k").toUpperCase();
191
+ const pref = keys.find((k) => k.toUpperCase() === want) ?? keys.find((k) => k.toUpperCase() === `${want}-JPG`) ?? keys.find((k) => k.toUpperCase().startsWith(want)) ?? keys.find((k) => k.toUpperCase().startsWith("1K")) ?? keys[0];
192
+ return [pref, downloads[pref]];
193
+ }
194
+ var ambientcg = {
195
+ id: "ambientcg",
196
+ title: "ambientCG (CC0 PBR materials, HDRIs)",
197
+ kinds: ["texture", "hdri"],
198
+ async search(q, fetch) {
199
+ if (q.kind && q.kind !== "texture" && q.kind !== "hdri") return [];
200
+ const types = q.kind === "hdri" ? ["HDRI"] : q.kind === "texture" ? ["Material"] : ["Material", "HDRI"];
201
+ const hits = [];
202
+ for (const type of types) {
203
+ const data = await fetchJson(fetch, `${API$1}?type=${type}&q=${encodeURIComponent(q.query)}&include=downloadData,previewData&limit=${q.limit ?? 12}`);
204
+ for (const a of data.foundAssets ?? []) hits.push({
205
+ source: "ambientcg",
206
+ id: a.assetId,
207
+ title: a.displayName ?? a.assetId,
208
+ kind: type === "HDRI" ? "hdri" : "texture",
209
+ license: "CC0-1.0",
210
+ author: "ambientCG",
211
+ previewUrl: a.previewImage?.["256-PNG"] ?? a.previewImage?.["128-PNG"],
212
+ pageUrl: a.shortLink ?? `https://ambientcg.com/view?id=${a.assetId}`,
213
+ tags: a.tags?.slice(0, 8),
214
+ downloads: downloadsOf(a),
215
+ note: type === "HDRI" ? "Zip with an .hdr/.exr environment map." : "Zip with Color / NormalGL / Roughness maps (extracted)."
216
+ });
217
+ }
218
+ return hits.slice(0, q.limit ?? 20);
219
+ },
220
+ async download(hit, fetch, opts) {
221
+ const [, url] = pickDownload(hit.downloads, opts.resolution);
222
+ const bytes = await fetchBytes(fetch, url);
223
+ const isZip = bytes[0] === 80 && bytes[1] === 75;
224
+ const id = hit.id;
225
+ if (!isZip) {
226
+ const name = url.split("?")[0].split("/").pop() || `${id}.bin`;
227
+ return {
228
+ files: { [name]: bytes },
229
+ main: name
230
+ };
231
+ }
232
+ if (hit.kind === "hdri") {
233
+ const files = await readZip(bytes, {
234
+ inflate: opts.inflate,
235
+ filter: (n) => /\.(hdr|exr)$/i.test(n)
236
+ });
237
+ const names = Object.keys(files).sort((a, b) => (a.endsWith(".hdr") ? -1 : 1) - (b.endsWith(".hdr") ? -1 : 1));
238
+ if (!names.length) throw new SourceError(`ambientCG zip for ${id} contains no .hdr/.exr file.`);
239
+ const main = names[0].split("/").pop();
240
+ return {
241
+ files: { [main]: files[names[0]] },
242
+ main
243
+ };
244
+ }
245
+ const files = await readZip(bytes, {
246
+ inflate: opts.inflate,
247
+ filter: (n) => /_(Color|NormalGL|Roughness|AmbientOcclusion)\.(jpe?g|png|webp)$/i.test(n)
248
+ });
249
+ const out = {};
250
+ const material = {};
251
+ for (const [name, data] of Object.entries(files)) {
252
+ const base = name.split("/").pop();
253
+ const rel = `${id}/${base}`;
254
+ out[rel] = data;
255
+ if (/_Color\./i.test(base)) material.map = rel;
256
+ else if (/_NormalGL\./i.test(base)) material.normalMap = rel;
257
+ else if (/_Roughness\./i.test(base)) material.roughnessMap = rel;
258
+ }
259
+ const main = material.map ?? Object.keys(out)[0];
260
+ if (!main) throw new SourceError(`ambientCG zip for ${id} has no Color/NormalGL/Roughness maps.`);
261
+ return {
262
+ files: out,
263
+ main,
264
+ suggestion: { material }
265
+ };
266
+ }
267
+ };
268
+ // src/ops/sources/kenneyIndex.ts
269
+ var k = (id, title, description, tags) => ({
270
+ id,
271
+ title,
272
+ description,
273
+ tags,
274
+ pageUrl: `https://kenney.nl/assets/${id}`
275
+ });
276
+ var KENNEY_PACKS = [
277
+ k("nature-kit", "Nature Kit", "Low-poly trees, rocks, plants, cliffs, paths, tents and campfires.", [
278
+ "nature",
279
+ "tree",
280
+ "rock",
281
+ "plant",
282
+ "forest",
283
+ "camp",
284
+ "lowpoly"
285
+ ]),
286
+ k("city-kit-suburban", "City Kit (Suburban)", "Suburban houses, fences, trees and driveways.", [
287
+ "city",
288
+ "house",
289
+ "suburb",
290
+ "building",
291
+ "town"
292
+ ]),
293
+ k("city-kit-commercial", "City Kit (Commercial)", "Skyscrapers, shops and commercial buildings.", [
294
+ "city",
295
+ "building",
296
+ "skyscraper",
297
+ "shop",
298
+ "town"
299
+ ]),
300
+ k("city-kit-roads", "City Kit (Roads)", "Road tiles, crossings, bridges and street props.", [
301
+ "city",
302
+ "road",
303
+ "street",
304
+ "traffic",
305
+ "bridge"
306
+ ]),
307
+ k("car-kit", "Car Kit", "Stylised cars, trucks, police car, taxi, ambulance.", [
308
+ "car",
309
+ "vehicle",
310
+ "truck",
311
+ "taxi",
312
+ "racing"
313
+ ]),
314
+ k("racing-kit", "Racing Kit", "Race track pieces, cars and props.", [
315
+ "racing",
316
+ "car",
317
+ "track",
318
+ "vehicle"
319
+ ]),
320
+ k("train-kit", "Train Kit", "Trains, wagons and tracks.", [
321
+ "train",
322
+ "rail",
323
+ "vehicle"
324
+ ]),
325
+ k("space-kit", "Space Kit", "Rockets, astronauts, planets, space station modules and terrain.", [
326
+ "space",
327
+ "rocket",
328
+ "astronaut",
329
+ "planet",
330
+ "scifi"
331
+ ]),
332
+ k("modular-space-kit", "Modular Space Kit", "Modular sci-fi interior corridors and rooms.", [
333
+ "space",
334
+ "scifi",
335
+ "interior",
336
+ "modular",
337
+ "corridor"
338
+ ]),
339
+ k("platformer-kit", "Platformer Kit", "Platforms, coins, flags, blocks and characters for 3D platformers.", [
340
+ "platformer",
341
+ "game",
342
+ "coin",
343
+ "block",
344
+ "level"
345
+ ]),
346
+ k("prototype-kit", "Prototype Kit", "Blockout shapes, ramps, stairs for level prototyping.", [
347
+ "prototype",
348
+ "game",
349
+ "level",
350
+ "blockout"
351
+ ]),
352
+ k("mini-arena", "Mini Arena", "Small arena game pieces and characters.", [
353
+ "arena",
354
+ "game",
355
+ "character"
356
+ ]),
357
+ k("mini-characters", "Mini Characters", "Small rigged/animated characters.", [
358
+ "character",
359
+ "people",
360
+ "animated"
361
+ ]),
362
+ k("mini-dungeon", "Mini Dungeon", "Dungeon tiles, walls, chests and characters.", [
363
+ "dungeon",
364
+ "fantasy",
365
+ "game",
366
+ "chest"
367
+ ]),
368
+ k("blaster-kit", "Blaster Kit", "Toy blasters, targets and ammo.", [
369
+ "blaster",
370
+ "gun",
371
+ "weapon",
372
+ "shooter",
373
+ "game"
374
+ ]),
375
+ k("food-kit", "Food Kit", "Fruit, vegetables, meals, drinks and kitchen props.", [
376
+ "food",
377
+ "fruit",
378
+ "drink",
379
+ "kitchen",
380
+ "restaurant"
381
+ ]),
382
+ k("furniture-kit", "Furniture Kit", "Chairs, tables, sofas, beds, lamps and interior props.", [
383
+ "furniture",
384
+ "interior",
385
+ "chair",
386
+ "table",
387
+ "room",
388
+ "house"
389
+ ]),
390
+ k("castle-kit", "Castle Kit", "Castle walls, towers, gates and siege props.", [
391
+ "castle",
392
+ "medieval",
393
+ "tower",
394
+ "fantasy"
395
+ ]),
396
+ k("fantasy-town-kit", "Fantasy Town Kit", "Medieval fantasy houses, market stalls and props.", [
397
+ "fantasy",
398
+ "medieval",
399
+ "town",
400
+ "house",
401
+ "village"
402
+ ]),
403
+ k("pirate-kit", "Pirate Kit", "Ships, palm trees, treasure, cannons and docks.", [
404
+ "pirate",
405
+ "ship",
406
+ "island",
407
+ "treasure",
408
+ "boat"
409
+ ]),
410
+ k("holiday-kit", "Holiday Kit", "Christmas trees, presents, snowmen and decorations.", [
411
+ "holiday",
412
+ "christmas",
413
+ "winter",
414
+ "snow",
415
+ "gift"
416
+ ]),
417
+ k("graveyard-kit", "Graveyard Kit", "Graves, crypts, fences, pumpkins — Halloween scenes.", [
418
+ "halloween",
419
+ "graveyard",
420
+ "spooky",
421
+ "pumpkin"
422
+ ]),
423
+ k("tower-defense-kit", "Tower Defense Kit", "Towers, enemies paths and tiles for tower defense games.", [
424
+ "tower",
425
+ "defense",
426
+ "game",
427
+ "tile"
428
+ ]),
429
+ k("minigolf-kit", "Minigolf Kit", "Minigolf course pieces.", [
430
+ "golf",
431
+ "minigolf",
432
+ "game",
433
+ "sport"
434
+ ]),
435
+ k("coaster-kit", "Coaster Kit", "Roller coaster tracks and carts.", [
436
+ "coaster",
437
+ "theme park",
438
+ "track",
439
+ "fun"
440
+ ]),
441
+ k("retro-urban-kit", "Retro Urban Kit", "Retro city blocks, walls and street props.", [
442
+ "city",
443
+ "urban",
444
+ "retro",
445
+ "street"
446
+ ]),
447
+ k("survival-kit", "Survival Kit", "Tools, tents, barrels, crates and campfire.", [
448
+ "survival",
449
+ "camp",
450
+ "tool",
451
+ "crate",
452
+ "barrel"
453
+ ]),
454
+ k("hexagon-kit", "Hexagon Kit", "Hex tiles with terrain, buildings and nature.", [
455
+ "hexagon",
456
+ "tile",
457
+ "strategy",
458
+ "terrain",
459
+ "board"
460
+ ])
461
+ ];
462
+ // src/ops/sources/quaterniusIndex.ts
463
+ var q = (id, title, description, tags, drive) => ({
464
+ id,
465
+ title,
466
+ description,
467
+ tags,
468
+ pageUrl: `https://quaternius.com/packs/${id}.html`,
469
+ ...drive ? { downloadPage: `https://drive.google.com/drive/folders/${drive}?usp=sharing` } : {}
470
+ });
471
+ var QUATERNIUS_PACKS = [
472
+ q("ultimatenature", "Ultimate Nature Pack", "Trees, bushes, rocks, flowers, grass — stylised low poly.", [
473
+ "nature",
474
+ "tree",
475
+ "rock",
476
+ "flower",
477
+ "forest",
478
+ "lowpoly"
479
+ ], "1-Kl0L_Jg8awbh0S5T-z3zxh4mVlnxTpa"),
480
+ q("stylizednaturemegakit", "Stylized Nature MegaKit", "Large stylised nature kit (trees, rocks, plants, terrain pieces).", [
481
+ "nature",
482
+ "tree",
483
+ "rock",
484
+ "plant",
485
+ "stylized"
486
+ ]),
487
+ q("simplenature", "Simple Nature Pack", "Simple low-poly trees, rocks and plants.", [
488
+ "nature",
489
+ "tree",
490
+ "rock",
491
+ "simple",
492
+ "lowpoly"
493
+ ], "18hb-5HGCLL9BS8jmxkE4h31wmHGeqfts"),
494
+ q("ultimateanimatedanimals", "Ultimate Animated Animal Pack", "Animated animals (fox, deer, wolf, horse, …) with idle/walk/run clips.", [
495
+ "animal",
496
+ "animated",
497
+ "fox",
498
+ "deer",
499
+ "wolf",
500
+ "horse"
501
+ ], "1uJ3N5HfB7jKTseJUNQr3N4YaN0UuEtHk"),
502
+ q("farmanimal", "Farm Animal Pack", "Animated farm animals: cow, pig, sheep, chicken…", [
503
+ "animal",
504
+ "farm",
505
+ "animated",
506
+ "cow",
507
+ "pig",
508
+ "sheep",
509
+ "chicken"
510
+ ], "1is1ax2V0mIEDS7BbbzBV_x2Pabya1dVJ"),
511
+ q("cutefish", "Animated Cute Fish Pack", "Cute animated fish.", [
512
+ "fish",
513
+ "sea",
514
+ "ocean",
515
+ "animated",
516
+ "cute"
517
+ ], "1QK5NCgIxUZ1cYGzVwaNfcfEiQhvczqUB"),
518
+ q("animatedfish", "Animated Fish Pack", "Animated fish (realistic-stylised).", [
519
+ "fish",
520
+ "sea",
521
+ "ocean",
522
+ "animated"
523
+ ], "1SvlOveJJjmhSn-FgCRyojc1T5QHjjGkF"),
524
+ q("ultimatemonsters", "Ultimate Monsters", "Animated monsters for games.", [
525
+ "monster",
526
+ "creature",
527
+ "animated",
528
+ "game",
529
+ "enemy"
530
+ ], "18m4KpzpEzhC9wl7jzr6dUc0N8Jozr79C"),
531
+ q("cutemonsters", "Cute Animated Monsters Pack", "Cute animated monsters.", [
532
+ "monster",
533
+ "cute",
534
+ "animated",
535
+ "creature"
536
+ ], "1zLLO_7ZoWgUsS4uooYnVSErQYRu1VdS0"),
537
+ q("ultimatespaceships", "Ultimate Spaceships Pack", "Stylised spaceships.", [
538
+ "space",
539
+ "spaceship",
540
+ "scifi",
541
+ "ship"
542
+ ], "1NpfT3wqe2k3Jwue2xryi7tzxP4bWzETu"),
543
+ q("spaceships", "Spaceships Pack", "Low-poly spaceships.", [
544
+ "space",
545
+ "spaceship",
546
+ "scifi"
547
+ ], "1ZxWZ-KuSOA-9s53PA1B1-O0txRJvne2i"),
548
+ q("ultimatespacekit", "Ultimate Space Kit", "Astronauts, planets, rovers, bases and props.", [
549
+ "space",
550
+ "astronaut",
551
+ "planet",
552
+ "rover",
553
+ "scifi"
554
+ ], "17F8HlI2zPTlo32aieW5YPPwOk78xo-2m"),
555
+ q("cars", "Cars Pack", "Low-poly cars.", [
556
+ "car",
557
+ "vehicle",
558
+ "road"
559
+ ], "1fKlbDry77iY8KlEoxzUxIAZQL_XhzWlA"),
560
+ q("publictransport", "Public Transport Pack", "Buses, trams, taxis.", [
561
+ "bus",
562
+ "tram",
563
+ "vehicle",
564
+ "city",
565
+ "transport"
566
+ ], "1GUIE138uPVNraiQEf33dIx9wENhttZ15"),
567
+ q("downtowncitymegakit", "Downtown City MegaKit", "Modular downtown city buildings and props.", [
568
+ "city",
569
+ "building",
570
+ "downtown",
571
+ "modular"
572
+ ]),
573
+ q("simplebuildings", "Simple Buildings Pack", "Simple low-poly buildings.", [
574
+ "building",
575
+ "house",
576
+ "city",
577
+ "town"
578
+ ], "1r-FcNFxC6ziN0oI3GqZJdEkdzglFQHQH"),
579
+ q("buildings", "Buildings Pack", "Low-poly buildings.", [
580
+ "building",
581
+ "house",
582
+ "city"
583
+ ], "1uWCsV9QfnAu8u_QbwkYwOfuU3McME7CA"),
584
+ q("ultimatefood", "Ultimate Food Pack", "Food items: fruit, burgers, pizza, drinks…", [
585
+ "food",
586
+ "fruit",
587
+ "burger",
588
+ "pizza",
589
+ "drink"
590
+ ], "1zMfN7q9VU80M7mLAbBBJyY2OdoXslbl1"),
591
+ q("junkfood", "Junk Food Pack", "Burgers, fries, hot dogs, sodas.", [
592
+ "food",
593
+ "junk",
594
+ "burger",
595
+ "fries"
596
+ ], "127xt6nsl4Z-YRy-FZru38Sf6ElBWc8IU"),
597
+ q("ultimatefurniture", "Ultimate Furniture Pack", "Furniture: chairs, tables, beds, shelves.", [
598
+ "furniture",
599
+ "interior",
600
+ "chair",
601
+ "table",
602
+ "room"
603
+ ], "1n85oUi0RN5ZUXEIMKA-AnBsPErVXWcma"),
604
+ q("ultimatehomeinterior", "Ultimate House Interior Pack", "Home interior props and furniture.", [
605
+ "interior",
606
+ "house",
607
+ "furniture",
608
+ "room"
609
+ ], "1SNK9PwPi8xqqxmpU5xEZeiQjB26C1oX6"),
610
+ q("ultimateplatformer", "Platformer Game Kit", "Platformer level pieces, collectibles and characters.", [
611
+ "platformer",
612
+ "game",
613
+ "level",
614
+ "coin"
615
+ ], "1NDZn_aGnn0vfFV3M22Y8GPcDjO8BVcLs"),
616
+ q("modularplatformer", "Modular Platformer Pack", "Modular platform blocks.", [
617
+ "platformer",
618
+ "game",
619
+ "modular",
620
+ "block"
621
+ ], "1ku_XmbHOZ5ypgKCAjpzX6hlXaOJT7Uoq"),
622
+ q("cubeworldkit", "Cube World Kit", "Voxel-like cube world blocks, trees and characters.", [
623
+ "cube",
624
+ "voxel",
625
+ "world",
626
+ "block",
627
+ "game"
628
+ ], "1Yyag0ibcOX6lOBY9a3m6iPnz8HwjwLFJ"),
629
+ q("animatedrobot", "Animated Robot Pack", "Animated robots.", [
630
+ "robot",
631
+ "animated",
632
+ "scifi",
633
+ "character"
634
+ ], "18MU0RtRu9G6SU6uSZ_zMQFmVkRlB4zH5"),
635
+ q("rpgcharacters", "RPG Character Pack", "Animated RPG characters (warrior, mage, rogue…).", [
636
+ "character",
637
+ "rpg",
638
+ "fantasy",
639
+ "animated",
640
+ "hero"
641
+ ], "1MIRQXLfTd21HMI5rwOb6Xy0rv0xv1m8b"),
642
+ q("universalbasecharacters", "Universal Base Characters", "Rigged base humanoid characters.", [
643
+ "character",
644
+ "human",
645
+ "rigged",
646
+ "base"
647
+ ]),
648
+ q("medievalvillagemegakit", "Medieval Village MegaKit", "Modular medieval village buildings and props.", [
649
+ "medieval",
650
+ "village",
651
+ "building",
652
+ "fantasy",
653
+ "modular"
654
+ ]),
655
+ q("ultimatecrops", "Ultimate Crops Pack", "Farm crops at growth stages.", [
656
+ "farm",
657
+ "crop",
658
+ "plant",
659
+ "vegetable"
660
+ ], "1uhbi-NWp7pwqOGtraBZurbphyxAvoABZ"),
661
+ q("piratekit", "Pirate Kit", "Pirate ships, characters and props.", [
662
+ "pirate",
663
+ "ship",
664
+ "treasure",
665
+ "island"
666
+ ], "1KjMzhVsDcyvYMWeVjZcRfuu8auBLpNi2")
667
+ ];
668
+ // src/ops/sources/curated.ts
669
+ function curatedSource(id, title, packs, author) {
670
+ return {
671
+ id,
672
+ title,
673
+ kinds: ["model"],
674
+ async search(q) {
675
+ if (q.kind && q.kind !== "model") return [];
676
+ return rank(packs.map((p) => ({
677
+ score: score(q.query, {
678
+ id: p.id,
679
+ title: p.title,
680
+ tags: p.tags,
681
+ extra: p.description
682
+ }),
683
+ item: {
684
+ source: id,
685
+ id: p.id,
686
+ title: `${p.title} (pack)`,
687
+ kind: "model",
688
+ license: "CC0-1.0",
689
+ author,
690
+ pageUrl: p.pageUrl,
691
+ tags: p.tags,
692
+ downloads: {},
693
+ manual: true,
694
+ note: `${p.description} No direct download: ask the user to download the pack zip from ${p.downloadPage ?? p.pageUrl}, then import it with \`agent3d assets add <file.zip> --source ${id} --license CC0-1.0 --filter <word>\` (AI tool: assets_add { file, source: "${id}", license: "CC0-1.0", filter: ["<word>"] }). Only .glb/.gltf + textures are extracted; --filter (repeatable) keeps the models whose path contains a word.`
695
+ }
696
+ })), q.limit ?? 10);
697
+ }
698
+ };
699
+ }
700
+ var kenney = curatedSource("kenney", "Kenney (CC0 3D packs, curated index — manual zip download)", KENNEY_PACKS, "Kenney");
701
+ var quaternius = curatedSource("quaternius", "Quaternius (CC0 3D packs, curated index — manual zip download)", QUATERNIUS_PACKS, "Quaternius");
702
+ // src/ops/sources/khronos.ts
703
+ var RAW = "https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models";
704
+ var ALLOWED = /* @__PURE__ */ new Set(["CC0-1.0", "CC-BY-4.0"]);
705
+ var khronos = {
706
+ id: "khronos",
707
+ title: "Khronos glTF sample models (CC0 / CC-BY only)",
708
+ kinds: ["model"],
709
+ async search(q, fetch) {
710
+ if (q.kind && q.kind !== "model") return [];
711
+ const candidates = rank((await fetchJson(fetch, `${RAW}/model-index.json`)).filter((m) => m.variants?.["glTF-Binary"]).map((m) => ({
712
+ item: m,
713
+ score: score(q.query, {
714
+ title: m.label,
715
+ id: m.name,
716
+ tags: m.tags
717
+ })
718
+ })), Math.min(30, (q.limit ?? 10) * 2));
719
+ const hits = [];
720
+ await Promise.all(candidates.map(async (m) => {
721
+ let meta;
722
+ try {
723
+ meta = await fetchJson(fetch, `${RAW}/${m.name}/metadata.json`);
724
+ } catch {
725
+ return;
726
+ }
727
+ const legal = meta.legal ?? [];
728
+ if (!legal.length || !legal.every((l) => l.license && ALLOWED.has(l.license))) return;
729
+ const ccby = legal.some((l) => l.license === "CC-BY-4.0");
730
+ const authors = [...new Set(legal.map((l) => l.artist).filter(Boolean))];
731
+ hits.push({
732
+ source: "khronos",
733
+ id: m.name,
734
+ title: m.label,
735
+ kind: "model",
736
+ license: ccby ? "CC-BY-4.0" : "CC0-1.0",
737
+ author: authors.join(", ") || void 0,
738
+ ...ccby ? { attribution: `"${m.label}" — ${legal.map((l) => `${l.what ?? "model"} by ${l.artist ?? l.owner ?? "unknown"} (${l.license})`).join("; ")}. Source: Khronos glTF-Sample-Assets.` } : {},
739
+ previewUrl: m.screenshot ? `${RAW}/${m.name}/${m.screenshot}` : void 0,
740
+ pageUrl: `https://github.com/KhronosGroup/glTF-Sample-Assets/tree/main/Models/${m.name}`,
741
+ tags: m.tags,
742
+ downloads: { glb: `${RAW}/${m.name}/glTF-Binary/${m.variants["glTF-Binary"]}` },
743
+ note: meta.summary
744
+ });
745
+ }));
746
+ const order = new Map(candidates.map((c, i) => [c.name, i]));
747
+ return hits.sort((a, b) => (order.get(a.id) ?? 0) - (order.get(b.id) ?? 0)).slice(0, q.limit ?? 10);
748
+ },
749
+ async download(hit, fetch) {
750
+ const url = hit.downloads.glb;
751
+ if (!url) throw new SourceError(`Khronos model ${hit.id} has no .glb download.`);
752
+ const name = `${hit.id}.glb`;
753
+ return {
754
+ files: { [name]: await fetchBytes(fetch, url) },
755
+ main: name
756
+ };
757
+ }
758
+ };
759
+ // src/ops/sources/polyhaven.ts
760
+ var API = "https://api.polyhaven.com";
761
+ var TYPES = {
762
+ hdri: "hdris",
763
+ texture: "textures",
764
+ model: "models"
765
+ };
766
+ var RESOLUTIONS = [
767
+ "1k",
768
+ "2k",
769
+ "4k"
770
+ ];
771
+ var kindOfType = (t) => t === 0 ? "hdri" : t === 1 ? "texture" : "model";
772
+ // src/ops/sources/index.ts
773
+ var SOURCES = {
774
+ polyhaven: {
775
+ id: "polyhaven",
776
+ title: "Poly Haven (CC0 HDRIs, textures, models)",
777
+ kinds: [
778
+ "hdri",
779
+ "texture",
780
+ "model"
781
+ ],
782
+ async search(q, fetch) {
783
+ const kinds = q.kind ? [q.kind] : [
784
+ "hdri",
785
+ "texture",
786
+ "model"
787
+ ];
788
+ const results = [];
789
+ for (const kind of kinds) {
790
+ const t = TYPES[kind];
791
+ if (!t) continue;
792
+ const list = await fetchJson(fetch, `${API}/assets?t=${t}`);
793
+ for (const [id, a] of Object.entries(list)) {
794
+ const s = score(q.query, {
795
+ id,
796
+ title: a.name,
797
+ tags: [...a.tags ?? [], ...a.categories ?? []]
798
+ }, { strict: true });
799
+ if (!s) continue;
800
+ const k = kindOfType(a.type ?? (kind === "hdri" ? 0 : kind === "texture" ? 1 : 2));
801
+ results.push({
802
+ score: s,
803
+ item: {
804
+ source: "polyhaven",
805
+ id,
806
+ title: a.name,
807
+ kind: k,
808
+ license: "CC0-1.0",
809
+ author: Object.keys(a.authors ?? {}).join(", ") || void 0,
810
+ previewUrl: `https://cdn.polyhaven.com/asset_img/thumbs/${id}.png?width=256`,
811
+ pageUrl: `https://polyhaven.com/a/${id}`,
812
+ tags: a.tags?.slice(0, 8),
813
+ downloads: Object.fromEntries(RESOLUTIONS.map((r) => [r, `${API}/files/${id}`])),
814
+ note: k === "texture" ? "Downloads diffuse + normal (GL) + roughness maps." : k === "model" ? "Downloads a .gltf with its .bin and textures." : "Downloads an .hdr environment map."
815
+ }
816
+ });
817
+ }
818
+ }
819
+ return rank(results, q.limit ?? 20);
820
+ },
821
+ async download(hit, fetch, opts) {
822
+ const res = (opts.resolution ?? "1k").toLowerCase();
823
+ const files = await fetchJson(fetch, `${API}/files/${encodeURIComponent(hit.id)}`);
824
+ const pick = (map, fmt) => {
825
+ const byRes = files[map];
826
+ const leaf = byRes?.[res]?.[fmt] ?? byRes?.["1k"]?.[fmt];
827
+ if (!leaf) throw new SourceError(`Poly Haven "${hit.id}" has no ${map} ${fmt} at ${res} (available: ${Object.keys(byRes ?? {}).join(", ") || "none"}).`);
828
+ return leaf;
829
+ };
830
+ if (hit.kind === "hdri") {
831
+ const leaf = pick("hdri", "hdr");
832
+ const name = `${hit.id}_${res}.hdr`;
833
+ return {
834
+ files: { [name]: await fetchBytes(fetch, leaf.url) },
835
+ main: name,
836
+ suggestion: { environment: {
837
+ lighting: { hdri: `<path>` },
838
+ background: {
839
+ hdri: `<path>`,
840
+ blur: .5
841
+ }
842
+ } }
843
+ };
844
+ }
845
+ if (hit.kind === "texture") {
846
+ const out = {};
847
+ const maps = [
848
+ [
849
+ "Diffuse",
850
+ "diff",
851
+ "map"
852
+ ],
853
+ [
854
+ "nor_gl",
855
+ "nor_gl",
856
+ "normalMap"
857
+ ],
858
+ [
859
+ "Rough",
860
+ "rough",
861
+ "roughnessMap"
862
+ ]
863
+ ];
864
+ const material = {};
865
+ for (const [key, suffix, prop] of maps) {
866
+ if (!files[key]) continue;
867
+ const name = `${hit.id}/${hit.id}_${suffix}_${res}.jpg`;
868
+ out[name] = await fetchBytes(fetch, pick(key, "jpg").url);
869
+ material[prop] = name;
870
+ }
871
+ const main = material.map ?? Object.keys(out)[0];
872
+ if (!main) throw new SourceError(`Poly Haven "${hit.id}" has no downloadable texture maps.`);
873
+ return {
874
+ files: out,
875
+ main,
876
+ suggestion: { material }
877
+ };
878
+ }
879
+ const gltf = pick("gltf", "gltf");
880
+ const dir = `${hit.id}/`;
881
+ const out = { [`${dir}${hit.id}_${res}.gltf`]: await fetchBytes(fetch, gltf.url) };
882
+ for (const [rel, leaf] of Object.entries(gltf.include ?? {})) {
883
+ if (rel.split("/").includes("..")) continue;
884
+ out[`${dir}${rel}`] = await fetchBytes(fetch, leaf.url);
885
+ }
886
+ return {
887
+ files: out,
888
+ main: `${dir}${hit.id}_${res}.gltf`
889
+ };
890
+ }
891
+ },
892
+ ambientcg,
893
+ kenney,
894
+ quaternius,
895
+ khronos
896
+ };
897
+ // src/ops/optimizeGlb.ts
898
+ var meshoptModule = null;
899
+ async function meshopt() {
900
+ meshoptModule ??= import("./meshoptimizer-C-tN9jn5.mjs").then(async (m) => {
901
+ await Promise.all([
902
+ m.MeshoptEncoder.ready,
903
+ m.MeshoptDecoder.ready,
904
+ m.MeshoptSimplifier.ready
905
+ ]);
906
+ return m;
907
+ });
908
+ return meshoptModule;
909
+ }
910
+ var EXT_MESHOPT = "EXT_meshopt_compression";
911
+ var EXT_WEBP = "EXT_texture_webp";
912
+ var KHR_QUANT = "KHR_mesh_quantization";
913
+ var GLB_MAGIC = 1179937895;
914
+ var CHUNK_JSON = 1313821514;
915
+ var CHUNK_BIN = 5130562;
916
+ function readGlbChunks(bytes) {
917
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
918
+ if (bytes.byteLength < 20 || view.getUint32(0, true) !== GLB_MAGIC) throw new Error("Not a binary glTF (.glb) file.");
919
+ let off = 12;
920
+ let json = null;
921
+ let bin = null;
922
+ while (off + 8 <= bytes.byteLength) {
923
+ const len = view.getUint32(off, true);
924
+ const type = view.getUint32(off + 4, true);
925
+ const data = bytes.subarray(off + 8, off + 8 + len);
926
+ if (type === CHUNK_JSON) json = JSON.parse(new TextDecoder().decode(data));
927
+ else if (type === CHUNK_BIN && !bin) bin = data;
928
+ off += 8 + len;
929
+ }
930
+ if (!json) throw new Error("The .glb has no JSON chunk.");
931
+ return {
932
+ json,
933
+ bin
934
+ };
935
+ }
936
+ function writeGlbChunks(json, bin) {
937
+ const enc = new TextEncoder().encode(JSON.stringify(json));
938
+ const jsonLen = enc.byteLength + 3 & -4;
939
+ const binLen = bin ? bin.byteLength + 3 & -4 : 0;
940
+ const total = 20 + jsonLen + (bin ? 8 + binLen : 0);
941
+ const out = new Uint8Array(total);
942
+ const view = new DataView(out.buffer);
943
+ view.setUint32(0, GLB_MAGIC, true);
944
+ view.setUint32(4, 2, true);
945
+ view.setUint32(8, total, true);
946
+ view.setUint32(12, jsonLen, true);
947
+ view.setUint32(16, CHUNK_JSON, true);
948
+ out.set(enc, 20);
949
+ out.fill(32, 20 + enc.byteLength, 20 + jsonLen);
950
+ if (bin) {
951
+ const o = 20 + jsonLen;
952
+ view.setUint32(o, binLen, true);
953
+ view.setUint32(o + 4, CHUNK_BIN, true);
954
+ out.set(bin, o + 8);
955
+ }
956
+ return out;
957
+ }
958
+ var isFallbackBuffer = (b) => !!(b?.extensions?.[EXT_MESHOPT])?.fallback;
959
+ async function unpackGlb(bytes) {
960
+ const { json, bin } = readGlbChunks(bytes);
961
+ const buffers = json.buffers ?? [];
962
+ for (const [i, b] of buffers.entries()) {
963
+ if (isFallbackBuffer(b)) continue;
964
+ if (i !== 0 || b.uri !== void 0) throw new Error("This .glb references external buffers (.bin files): optimise the self-contained .glb instead.");
965
+ }
966
+ let wasCompressed = false;
967
+ const meta = [];
968
+ const views = [];
969
+ for (const [i, v] of (json.bufferViews ?? []).entries()) {
970
+ const ext = v.extensions?.[EXT_MESHOPT];
971
+ if (ext) {
972
+ if (ext.buffer !== 0 || !bin) throw new Error(`bufferView ${i}: meshopt data outside the GLB binary chunk.`);
973
+ const { MeshoptDecoder } = await meshopt();
974
+ const out = new Uint8Array(ext.count * ext.byteStride);
975
+ const src = bin.subarray(ext.byteOffset ?? 0, (ext.byteOffset ?? 0) + ext.byteLength);
976
+ MeshoptDecoder.decodeGltfBuffer(out, ext.count, ext.byteStride, src, ext.mode, ext.filter && ext.filter !== "NONE" ? ext.filter : void 0);
977
+ views.push(out);
978
+ meta.push({
979
+ mode: ext.mode,
980
+ stride: ext.byteStride,
981
+ count: ext.count
982
+ });
983
+ wasCompressed = true;
984
+ delete v.extensions[EXT_MESHOPT];
985
+ if (!Object.keys(v.extensions).length) delete v.extensions;
986
+ v.buffer = 0;
987
+ continue;
988
+ }
989
+ if (v.buffer !== 0 || !bin) {
990
+ if (isFallbackBuffer(buffers[v.buffer])) throw new Error(`bufferView ${i} points at a meshopt fallback buffer without compressed data.`);
991
+ throw new Error(`bufferView ${i} is outside the GLB binary chunk.`);
992
+ }
993
+ views.push(bin.slice(v.byteOffset ?? 0, (v.byteOffset ?? 0) + v.byteLength));
994
+ meta.push(void 0);
995
+ }
996
+ json.buffers = buffers.length ? [{ byteLength: 0 }] : [];
997
+ removeExtension(json, EXT_MESHOPT);
998
+ return {
999
+ json,
1000
+ views,
1001
+ meta,
1002
+ wasCompressed
1003
+ };
1004
+ }
1005
+ function addExtension(json, name, required) {
1006
+ json.extensionsUsed = [.../* @__PURE__ */ new Set([...json.extensionsUsed ?? [], name])];
1007
+ if (required) json.extensionsRequired = [.../* @__PURE__ */ new Set([...json.extensionsRequired ?? [], name])];
1008
+ }
1009
+ function removeExtension(json, name) {
1010
+ if (json.extensionsUsed) json.extensionsUsed = json.extensionsUsed.filter((e) => e !== name);
1011
+ if (json.extensionsRequired) json.extensionsRequired = json.extensionsRequired.filter((e) => e !== name);
1012
+ if (json.extensionsUsed && !json.extensionsUsed.length) delete json.extensionsUsed;
1013
+ if (json.extensionsRequired && !json.extensionsRequired.length) delete json.extensionsRequired;
1014
+ }
1015
+ var encodable = (m) => m.mode === "ATTRIBUTES" ? m.stride % 4 === 0 && m.stride <= 256 : (m.stride === 2 || m.stride === 4) && (m.mode !== "TRIANGLES" || m.count % 3 === 0);
1016
+ async function packGlb(model, opts) {
1017
+ const { json, views, meta } = model;
1018
+ const { MeshoptEncoder } = await meshopt();
1019
+ const chunks = [];
1020
+ let off = 0;
1021
+ let fallbackOff = 0;
1022
+ let compressedViews = 0;
1023
+ const place = (data) => {
1024
+ off = off + 3 & -4;
1025
+ const at = off;
1026
+ chunks.push(data);
1027
+ off += data.byteLength;
1028
+ return at;
1029
+ };
1030
+ const layout = [];
1031
+ const bvs = json.bufferViews ?? [];
1032
+ for (const [i, v] of bvs.entries()) {
1033
+ const data = views[i];
1034
+ const m = meta[i];
1035
+ let encoded = null;
1036
+ if (opts.compress && m && encodable(m)) try {
1037
+ const e = MeshoptEncoder.encodeGltfBuffer(data, m.count, m.stride, m.mode);
1038
+ if (e.byteLength < data.byteLength * .97 || m.filter) encoded = e;
1039
+ } catch {
1040
+ encoded = null;
1041
+ }
1042
+ if (m?.filter && !encoded) throw new Error(`bufferView ${i}: a meshopt filter needs compression.`);
1043
+ if (encoded) {
1044
+ const at = off = off + 3 & -4;
1045
+ chunks.push(encoded);
1046
+ layout.push({
1047
+ at,
1048
+ data: encoded
1049
+ });
1050
+ off += encoded.byteLength;
1051
+ fallbackOff = fallbackOff + 3 & -4;
1052
+ v.buffer = 1;
1053
+ v.byteOffset = fallbackOff;
1054
+ v.byteLength = data.byteLength;
1055
+ fallbackOff += data.byteLength;
1056
+ v.extensions = {
1057
+ ...v.extensions ?? {},
1058
+ [EXT_MESHOPT]: {
1059
+ buffer: 0,
1060
+ byteOffset: at,
1061
+ byteLength: encoded.byteLength,
1062
+ byteStride: m.stride,
1063
+ mode: m.mode,
1064
+ count: m.count,
1065
+ ...m.filter ? { filter: m.filter } : {}
1066
+ }
1067
+ };
1068
+ compressedViews++;
1069
+ } else {
1070
+ const at = place(data);
1071
+ layout.push({
1072
+ at,
1073
+ data
1074
+ });
1075
+ v.buffer = 0;
1076
+ v.byteOffset = at;
1077
+ v.byteLength = data.byteLength;
1078
+ }
1079
+ }
1080
+ const binLen = off + 3 & -4;
1081
+ const bin = new Uint8Array(binLen);
1082
+ for (const l of layout) bin.set(l.data, l.at);
1083
+ json.buffers = [{ byteLength: binLen }];
1084
+ if (compressedViews) {
1085
+ json.buffers.push({
1086
+ byteLength: fallbackOff + 3 & -4,
1087
+ extensions: { [EXT_MESHOPT]: { fallback: true } }
1088
+ });
1089
+ addExtension(json, EXT_MESHOPT, true);
1090
+ } else removeExtension(json, EXT_MESHOPT);
1091
+ if (!bvs.length) delete json.buffers;
1092
+ return {
1093
+ bytes: writeGlbChunks(json, bvs.length ? bin : null),
1094
+ compressedViews
1095
+ };
1096
+ }
1097
+ var COMPONENTS = {
1098
+ SCALAR: 1,
1099
+ VEC2: 2,
1100
+ VEC3: 3,
1101
+ VEC4: 4,
1102
+ MAT2: 4,
1103
+ MAT3: 9,
1104
+ MAT4: 16
1105
+ };
1106
+ var COMPONENT_BYTES = {
1107
+ 5120: 1,
1108
+ 5121: 1,
1109
+ 5122: 2,
1110
+ 5123: 2,
1111
+ 5125: 4,
1112
+ 5126: 4
1113
+ };
1114
+ var F32 = 5126;
1115
+ var U16 = 5123;
1116
+ var U32 = 5125;
1117
+ var I16 = 5122;
1118
+ var elementSize = (a) => (COMPONENTS[a.type] ?? 1) * (COMPONENT_BYTES[a.componentType] ?? 4);
1119
+ function accessorBytes(model, a) {
1120
+ const size = elementSize(a);
1121
+ const out = new Uint8Array(a.count * size);
1122
+ if (a.bufferView === void 0) return out;
1123
+ const bv = model.json.bufferViews[a.bufferView];
1124
+ const src = model.views[a.bufferView];
1125
+ const stride = bv.byteStride || size;
1126
+ const base = a.byteOffset ?? 0;
1127
+ if (stride === size) out.set(src.subarray(base, base + out.byteLength));
1128
+ else for (let i = 0; i < a.count; i++) out.set(src.subarray(base + i * stride, base + i * stride + size), i * size);
1129
+ return out;
1130
+ }
1131
+ function readFloats(bytes, a) {
1132
+ const n = a.count * (COMPONENTS[a.type] ?? 1);
1133
+ const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1134
+ const out = new Float32Array(n);
1135
+ const cb = COMPONENT_BYTES[a.componentType];
1136
+ for (let i = 0; i < n; i++) {
1137
+ const o = i * cb;
1138
+ let v;
1139
+ switch (a.componentType) {
1140
+ case 5126:
1141
+ v = dv.getFloat32(o, true);
1142
+ break;
1143
+ case 5120:
1144
+ v = dv.getInt8(o);
1145
+ if (a.normalized) v = Math.max(v / 127, -1);
1146
+ break;
1147
+ case 5121:
1148
+ v = dv.getUint8(o);
1149
+ if (a.normalized) v /= 255;
1150
+ break;
1151
+ case 5122:
1152
+ v = dv.getInt16(o, true);
1153
+ if (a.normalized) v = Math.max(v / 32767, -1);
1154
+ break;
1155
+ case 5123:
1156
+ v = dv.getUint16(o, true);
1157
+ if (a.normalized) v /= 65535;
1158
+ break;
1159
+ default: v = dv.getUint32(o, true);
1160
+ }
1161
+ out[i] = v;
1162
+ }
1163
+ return out;
1164
+ }
1165
+ function readIndices(bytes, a) {
1166
+ const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1167
+ const out = new Uint32Array(a.count);
1168
+ for (let i = 0; i < a.count; i++) out[i] = a.componentType === 5121 ? dv.getUint8(i) : a.componentType === U16 ? dv.getUint16(i * 2, true) : dv.getUint32(i * 4, true);
1169
+ return out;
1170
+ }
1171
+ function minMax(values, comps) {
1172
+ const min = new Array(comps).fill(Infinity);
1173
+ const max = new Array(comps).fill(-Infinity);
1174
+ for (let i = 0; i < values.length; i++) {
1175
+ const c = i % comps;
1176
+ if (values[i] < min[c]) min[c] = values[i];
1177
+ if (values[i] > max[c]) max[c] = values[i];
1178
+ }
1179
+ return {
1180
+ min: min.map((v) => Number.isFinite(v) ? v : 0),
1181
+ max: max.map((v) => Number.isFinite(v) ? v : 0)
1182
+ };
1183
+ }
1184
+ var POSITION_BITS = 16;
1185
+ var UV_BITS = 16;
1186
+ var NORMAL_BITS = 10;
1187
+ function geometryBlocker(json) {
1188
+ if ((json.extensionsUsed ?? []).includes("KHR_draco_mesh_compression")) return "Draco-compressed geometry (KHR_draco_mesh_compression) cannot be decoded here: geometry kept as is.";
1189
+ if ((json.accessors ?? []).some((a) => a.sparse)) return "Sparse accessors: geometry kept as is.";
1190
+ for (const a of json.accessors ?? []) if (/^MAT/.test(a.type) && (COMPONENT_BYTES[a.componentType] ?? 4) < 4) return "Padded matrix accessors: geometry kept as is.";
1191
+ return null;
1192
+ }
1193
+ async function rebuildGeometry(model, opts) {
1194
+ const { MeshoptEncoder, MeshoptSimplifier } = await meshopt();
1195
+ const { json } = model;
1196
+ const accessors = json.accessors ?? [];
1197
+ const report = {
1198
+ trianglesBefore: 0,
1199
+ trianglesAfter: 0,
1200
+ verticesBefore: 0,
1201
+ verticesAfter: 0,
1202
+ welded: 0,
1203
+ simplified: false,
1204
+ filters: [],
1205
+ notes: []
1206
+ };
1207
+ const classOf = /* @__PURE__ */ new Map();
1208
+ const users = /* @__PURE__ */ new Map();
1209
+ const use = (i, c, by) => {
1210
+ if (i === void 0 || !accessors[i]) return;
1211
+ const prev = classOf.get(i);
1212
+ if (!prev || prev === "other") classOf.set(i, c);
1213
+ if (!users.has(i)) users.set(i, /* @__PURE__ */ new Set());
1214
+ users.get(i).add(by);
1215
+ };
1216
+ const prims = [];
1217
+ for (const m of json.meshes ?? []) for (const p of m.primitives ?? []) {
1218
+ prims.push(p);
1219
+ for (const a of Object.values(p.attributes ?? {})) use(a, "vertex", p);
1220
+ for (const t of p.targets ?? []) for (const a of Object.values(t)) use(a, "target", p);
1221
+ use(p.indices, "index", p);
1222
+ }
1223
+ for (const s of json.skins ?? []) use(s.inverseBindMatrices, "other", "other");
1224
+ for (const an of json.animations ?? []) for (const s of an.samplers ?? []) use(s.input, "other", "other"), use(s.output, "other", "other");
1225
+ for (const n of json.nodes ?? []) {
1226
+ const inst = n.extensions?.EXT_mesh_gpu_instancing;
1227
+ for (const a of Object.values(inst?.attributes ?? {})) use(a, "other", "other");
1228
+ }
1229
+ const data = /* @__PURE__ */ new Map();
1230
+ for (const [i, a] of accessors.entries()) data.set(i, accessorBytes(model, a));
1231
+ const triCount = (p) => {
1232
+ const mode = p.mode ?? 4;
1233
+ const n = p.indices !== void 0 ? accessors[p.indices].count : accessors[p.attributes.POSITION]?.count ?? 0;
1234
+ return mode === 4 ? n / 3 : mode === 5 || mode === 6 ? Math.max(0, n - 2) : 0;
1235
+ };
1236
+ for (const p of prims) report.trianglesBefore += triCount(p);
1237
+ const posSeen = /* @__PURE__ */ new Set();
1238
+ for (const p of prims) if (p.attributes.POSITION !== void 0 && !posSeen.has(p.attributes.POSITION)) posSeen.add(p.attributes.POSITION), report.verticesBefore += accessors[p.attributes.POSITION].count;
1239
+ const groups = /* @__PURE__ */ new Map();
1240
+ for (const p of prims) {
1241
+ if ((p.mode ?? 4) !== 4 || p.extensions?.["KHR_draco_mesh_compression"] || p.attributes.POSITION === void 0) continue;
1242
+ const key = JSON.stringify([p.attributes, p.targets ?? []]);
1243
+ groups.set(key, [...groups.get(key) ?? [], p]);
1244
+ }
1245
+ let simplifiedAny = false;
1246
+ let errorCapped = false;
1247
+ const created = /* @__PURE__ */ new Set();
1248
+ for (const group of groups.values()) {
1249
+ const first = group[0];
1250
+ const streams = [...Object.values(first.attributes), ...(first.targets ?? []).flatMap((t) => Object.values(t))];
1251
+ const inGroup = (i) => [...users.get(i) ?? []].every((u) => u !== "other" && group.includes(u));
1252
+ if (!streams.every(inGroup)) continue;
1253
+ if (group.some((p) => p.indices !== void 0 && (users.get(p.indices).size > 1 || classOf.get(p.indices) !== "index"))) continue;
1254
+ const posAcc = accessors[first.attributes.POSITION];
1255
+ const vertexCount = posAcc.count;
1256
+ if (streams.some((s) => accessors[s].count !== vertexCount || accessors[s].bufferView === void 0)) continue;
1257
+ let lists = group.map((p) => p.indices !== void 0 ? readIndices(data.get(p.indices), accessors[p.indices]) : Uint32Array.from({ length: vertexCount }, (_, k) => k));
1258
+ if (lists.some((l) => l.length % 3)) continue;
1259
+ const sizes = streams.map((s) => elementSize(accessors[s]));
1260
+ const streamData = streams.map((s) => data.get(s));
1261
+ const canon = new Uint32Array(vertexCount);
1262
+ const seen = /* @__PURE__ */ new Map();
1263
+ let welded = 0;
1264
+ for (let v = 0; v < vertexCount; v++) {
1265
+ let key = "";
1266
+ for (let k = 0; k < streams.length; k++) {
1267
+ const d = streamData[k];
1268
+ for (let b = v * sizes[k]; b < (v + 1) * sizes[k]; b++) key += String.fromCharCode(d[b]);
1269
+ }
1270
+ const hit = seen.get(key);
1271
+ if (hit === void 0) seen.set(key, v), canon[v] = v;
1272
+ else canon[v] = hit, welded++;
1273
+ }
1274
+ if (welded) lists = lists.map((l) => l.map((i) => canon[i]));
1275
+ report.welded += welded;
1276
+ if (opts.simplify !== void 0 && opts.simplify < 1 && first.targets === void 0) {
1277
+ const pos = readFloats(data.get(first.attributes.POSITION), posAcc);
1278
+ lists = lists.map((l) => {
1279
+ const tris = l.length / 3;
1280
+ if (tris < 32) return l;
1281
+ const target = Math.max(3, Math.floor(tris * opts.simplify | 0) * 3);
1282
+ const [out, err] = MeshoptSimplifier.simplify(l, pos, 3, target, opts.simplifyError ?? .01, ["LockBorder"]);
1283
+ if (!out.length) return l;
1284
+ if (out.length > target * 1.05) errorCapped = true;
1285
+ simplifiedAny = simplifiedAny || out.length < l.length;
1286
+ return out;
1287
+ });
1288
+ }
1289
+ const all = new Uint32Array(lists.reduce((n, l) => n + l.length, 0));
1290
+ let o = 0;
1291
+ for (const l of lists) all.set(l, o), o += l.length;
1292
+ const [remap, unique] = MeshoptEncoder.reorderMesh(all, group.length === 1, true);
1293
+ o = 0;
1294
+ lists = lists.map((l) => {
1295
+ const r = all.slice(o, o + l.length);
1296
+ o += l.length;
1297
+ return r;
1298
+ });
1299
+ for (const [k, s] of streams.entries()) {
1300
+ const size = sizes[k];
1301
+ const src = streamData[k];
1302
+ const dst = new Uint8Array(unique * size);
1303
+ for (let v = 0; v < vertexCount; v++) {
1304
+ const to = remap[v];
1305
+ if (to !== 4294967295 && to < unique) dst.set(src.subarray(v * size, (v + 1) * size), to * size);
1306
+ }
1307
+ data.set(s, dst);
1308
+ const a = accessors[s];
1309
+ a.count = unique;
1310
+ a.byteOffset = 0;
1311
+ }
1312
+ for (const [k, p] of group.entries()) {
1313
+ const l = lists[k];
1314
+ const wide = unique > 65535;
1315
+ const bytes = new Uint8Array(wide ? new Uint32Array(l).buffer : new Uint16Array(l).buffer);
1316
+ let idx = p.indices;
1317
+ if (idx === void 0) {
1318
+ idx = accessors.length;
1319
+ accessors.push({
1320
+ componentType: wide ? U32 : U16,
1321
+ count: l.length,
1322
+ type: "SCALAR"
1323
+ });
1324
+ created.add(idx);
1325
+ classOf.set(idx, "index");
1326
+ users.set(idx, /* @__PURE__ */ new Set([p]));
1327
+ p.indices = idx;
1328
+ }
1329
+ const a = accessors[idx];
1330
+ a.componentType = wide ? U32 : U16;
1331
+ a.count = l.length;
1332
+ a.byteOffset = 0;
1333
+ delete a.min;
1334
+ delete a.max;
1335
+ data.set(idx, bytes);
1336
+ }
1337
+ }
1338
+ if (simplifiedAny) report.simplified = true;
1339
+ if (errorCapped) report.notes.push(`Simplification stopped early to stay within the error bound (${opts.simplifyError ?? .01} of the mesh size): raise --simplify-error to go further.`);
1340
+ for (const [i, a] of accessors.entries()) if (classOf.get(i) === "index" && a.componentType === 5121) {
1341
+ data.set(i, new Uint8Array(new Uint16Array(readIndices(data.get(i), a)).buffer));
1342
+ a.componentType = U16;
1343
+ }
1344
+ const filters = /* @__PURE__ */ new Map();
1345
+ if (opts.compress) {
1346
+ const semantic = /* @__PURE__ */ new Map();
1347
+ for (const p of prims) for (const [name, a] of Object.entries(p.attributes)) semantic.set(a, semantic.has(a) && semantic.get(a) !== name ? "?" : name);
1348
+ for (const [i, a] of accessors.entries()) {
1349
+ if (classOf.get(i) !== "vertex" || a.componentType !== F32 || a.bufferView === void 0) continue;
1350
+ if ([...users.get(i) ?? []].some((u) => u === "other")) continue;
1351
+ const name = semantic.get(i) ?? "?";
1352
+ const values = readFloats(data.get(i), a);
1353
+ if (name === "NORMAL" && a.type === "VEC3" || name === "TANGENT" && a.type === "VEC4") {
1354
+ const src = new Float32Array(a.count * 4);
1355
+ for (let v = 0; v < a.count; v++) {
1356
+ const c = a.type === "VEC3" ? 3 : 4;
1357
+ src[v * 4] = values[v * c];
1358
+ src[v * 4 + 1] = values[v * c + 1];
1359
+ src[v * 4 + 2] = values[v * c + 2];
1360
+ src[v * 4 + 3] = c === 4 ? values[v * c + 3] : 0;
1361
+ }
1362
+ data.set(i, MeshoptEncoder.encodeFilterOct(src, a.count, 8, NORMAL_BITS));
1363
+ a.componentType = I16;
1364
+ a.normalized = true;
1365
+ delete a.min;
1366
+ delete a.max;
1367
+ filters.set(i, "OCTAHEDRAL");
1368
+ addExtension(json, KHR_QUANT, true);
1369
+ } else if (name === "POSITION" || /^TEXCOORD_\d+$/.test(name)) {
1370
+ const comps = COMPONENTS[a.type];
1371
+ const bits = name === "POSITION" ? POSITION_BITS : UV_BITS;
1372
+ const enc = MeshoptEncoder.encodeFilterExp(values, a.count, comps * 4, bits, "SharedComponent");
1373
+ data.set(i, enc);
1374
+ filters.set(i, "EXPONENTIAL");
1375
+ if (name === "POSITION") Object.assign(a, minMax(decodeExp(enc), comps));
1376
+ }
1377
+ }
1378
+ report.filters = [...new Set([...filters.entries()].map(([i, f]) => `${semantic.get(i)}: ${f === "OCTAHEDRAL" ? `octahedral ${NORMAL_BITS} bits` : `exponential ${semantic.get(i) === "POSITION" ? POSITION_BITS : UV_BITS} bits`}`))].sort();
1379
+ }
1380
+ for (const p of prims) for (const s of [p.attributes.POSITION, ...(p.targets ?? []).map((t) => t.POSITION)]) {
1381
+ if (s === void 0 || filters.has(s)) continue;
1382
+ const a = accessors[s];
1383
+ if (a.bufferView === void 0) continue;
1384
+ Object.assign(a, minMax(readFloats(data.get(s), a), COMPONENTS[a.type]));
1385
+ }
1386
+ const oldViews = json.bufferViews ?? [];
1387
+ const keep = /* @__PURE__ */ new Set();
1388
+ for (const img of json.images ?? []) if (img.bufferView !== void 0) keep.add(img.bufferView);
1389
+ collectExtensionViews(json, keep);
1390
+ const remapView = /* @__PURE__ */ new Map();
1391
+ const newViews = [];
1392
+ const newData = [];
1393
+ const newMeta = [];
1394
+ for (const [i, v] of oldViews.entries()) {
1395
+ if (!keep.has(i)) continue;
1396
+ remapView.set(i, newViews.length);
1397
+ newViews.push(v);
1398
+ newData.push(model.views[i]);
1399
+ newMeta.push(model.meta[i]);
1400
+ }
1401
+ for (const [i, a] of accessors.entries()) {
1402
+ if (a.bufferView === void 0 && !created.has(i)) continue;
1403
+ const c = classOf.get(i) ?? "other";
1404
+ const size = elementSize(a);
1405
+ let bytes = data.get(i);
1406
+ const filter = filters.get(i);
1407
+ const stride = filter === "OCTAHEDRAL" ? 8 : c === "vertex" || c === "target" ? size + 3 & -4 : size;
1408
+ if (!filter && stride !== size) {
1409
+ const padded = new Uint8Array(a.count * stride);
1410
+ for (let v = 0; v < a.count; v++) padded.set(bytes.subarray(v * size, (v + 1) * size), v * stride);
1411
+ bytes = padded;
1412
+ }
1413
+ const bv = {
1414
+ buffer: 0,
1415
+ byteLength: bytes.byteLength
1416
+ };
1417
+ if (c === "vertex" || c === "target") bv.byteStride = stride, bv.target = 34962;
1418
+ if (c === "index") bv.target = 34963;
1419
+ let meta;
1420
+ if (c === "index") meta = {
1421
+ mode: [...users.get(i) ?? []].every((u) => u !== "other" && (u.mode ?? 4) === 4) && a.count % 3 === 0 ? "TRIANGLES" : "INDICES",
1422
+ stride: size,
1423
+ count: a.count
1424
+ };
1425
+ else if (stride % 4 === 0 && stride <= 256) meta = {
1426
+ mode: "ATTRIBUTES",
1427
+ stride,
1428
+ count: a.count,
1429
+ ...filter ? { filter } : {}
1430
+ };
1431
+ a.bufferView = newViews.length;
1432
+ a.byteOffset = 0;
1433
+ newViews.push(bv);
1434
+ newData.push(bytes);
1435
+ newMeta.push(meta);
1436
+ }
1437
+ for (const img of json.images ?? []) if (img.bufferView !== void 0) img.bufferView = remapView.get(img.bufferView);
1438
+ remapExtensionViews(json, remapView);
1439
+ json.bufferViews = newViews;
1440
+ model.views = newData;
1441
+ model.meta = newMeta;
1442
+ for (const p of prims) report.trianglesAfter += triCount(p);
1443
+ const posAfter = /* @__PURE__ */ new Set();
1444
+ for (const p of prims) if (p.attributes.POSITION !== void 0 && !posAfter.has(p.attributes.POSITION)) posAfter.add(p.attributes.POSITION), report.verticesAfter += accessors[p.attributes.POSITION].count;
1445
+ report.trianglesBefore = Math.round(report.trianglesBefore);
1446
+ report.trianglesAfter = Math.round(report.trianglesAfter);
1447
+ return report;
1448
+ }
1449
+ function collectExtensionViews(json, out) {
1450
+ for (const m of json.meshes ?? []) for (const p of m.primitives ?? []) for (const e of Object.values(p.extensions ?? {})) {
1451
+ const bv = e?.bufferView;
1452
+ if (typeof bv === "number") out.add(bv);
1453
+ }
1454
+ }
1455
+ function remapExtensionViews(json, remap) {
1456
+ for (const m of json.meshes ?? []) for (const p of m.primitives ?? []) for (const e of Object.values(p.extensions ?? {})) {
1457
+ const o = e;
1458
+ if (o && typeof o.bufferView === "number") o.bufferView = remap.get(o.bufferView);
1459
+ }
1460
+ }
1461
+ function decodeExp(bytes) {
1462
+ const n = bytes.byteLength / 4;
1463
+ const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1464
+ const out = new Float32Array(n);
1465
+ for (let i = 0; i < n; i++) {
1466
+ const v = dv.getInt32(i * 4, true);
1467
+ const e = v >> 24;
1468
+ const m = v << 8 >> 8;
1469
+ out[i] = m * Math.pow(2, e);
1470
+ }
1471
+ return out;
1472
+ }
1473
+ function compactViews(model) {
1474
+ const { json } = model;
1475
+ const used = /* @__PURE__ */ new Set();
1476
+ for (const a of json.accessors ?? []) if (a.bufferView !== void 0) used.add(a.bufferView);
1477
+ for (const img of json.images ?? []) if (img.bufferView !== void 0) used.add(img.bufferView);
1478
+ collectExtensionViews(json, used);
1479
+ const remap = /* @__PURE__ */ new Map();
1480
+ const views = [];
1481
+ const data = [];
1482
+ const meta = [];
1483
+ for (const [i, v] of (json.bufferViews ?? []).entries()) {
1484
+ if (!used.has(i)) continue;
1485
+ remap.set(i, views.length);
1486
+ views.push(v);
1487
+ data.push(model.views[i]);
1488
+ meta.push(model.meta[i]);
1489
+ }
1490
+ if (views.length === (json.bufferViews ?? []).length) return;
1491
+ for (const a of json.accessors ?? []) if (a.bufferView !== void 0) a.bufferView = remap.get(a.bufferView);
1492
+ for (const img of json.images ?? []) if (img.bufferView !== void 0) img.bufferView = remap.get(img.bufferView);
1493
+ remapExtensionViews(json, remap);
1494
+ json.bufferViews = views;
1495
+ model.views = data;
1496
+ model.meta = meta;
1497
+ }
1498
+ var DATA_SLOTS = /* @__PURE__ */ new Set([
1499
+ "metallicRoughnessTexture",
1500
+ "occlusionTexture",
1501
+ "clearcoatTexture",
1502
+ "clearcoatRoughnessTexture",
1503
+ "transmissionTexture",
1504
+ "thicknessTexture",
1505
+ "specularTexture",
1506
+ "sheenRoughnessTexture",
1507
+ "iridescenceTexture",
1508
+ "iridescenceThicknessTexture",
1509
+ "anisotropyTexture"
1510
+ ]);
1511
+ var NORMAL_SLOTS = /* @__PURE__ */ new Set(["normalTexture", "clearcoatNormalTexture"]);
1512
+ function textureImage(t) {
1513
+ return t.extensions?.["EXT_texture_webp"]?.source ?? t.extensions?.EXT_texture_avif?.source ?? t.extensions?.KHR_texture_basisu?.source ?? t.source;
1514
+ }
1515
+ function imageRoles(json) {
1516
+ const roles = /* @__PURE__ */ new Map();
1517
+ const rank = {
1518
+ data: 0,
1519
+ normal: 1,
1520
+ color: 2
1521
+ };
1522
+ const visit = (o, slot) => {
1523
+ if (!o || typeof o !== "object") return;
1524
+ const rec = o;
1525
+ if (typeof rec.index === "number" && slot.endsWith("Texture")) {
1526
+ const t = json.textures?.[rec.index];
1527
+ const img = t ? textureImage(t) : void 0;
1528
+ if (img !== void 0) {
1529
+ const role = NORMAL_SLOTS.has(slot) ? "normal" : DATA_SLOTS.has(slot) ? "data" : "color";
1530
+ const cur = roles.get(img);
1531
+ if (!cur || rank[role] > rank[cur]) roles.set(img, role);
1532
+ }
1533
+ return;
1534
+ }
1535
+ for (const [k, v] of Object.entries(rec)) visit(v, k);
1536
+ };
1537
+ for (const m of json.materials ?? []) visit(m, "");
1538
+ return roles;
1539
+ }
1540
+ function normalizeTextureSources(json) {
1541
+ let webp = false;
1542
+ const dropped = /* @__PURE__ */ new Set();
1543
+ for (const t of json.textures ?? []) {
1544
+ const img = textureImage(t);
1545
+ if (img === void 0) continue;
1546
+ if (typeof t.source === "number" && t.source !== img) dropped.add(t.source);
1547
+ const isWebp = json.images?.[img]?.mimeType === "image/webp";
1548
+ if (t.extensions?.EXT_texture_avif || t.extensions?.KHR_texture_basisu) continue;
1549
+ if (isWebp) {
1550
+ t.extensions = {
1551
+ ...t.extensions ?? {},
1552
+ [EXT_WEBP]: { source: img }
1553
+ };
1554
+ delete t.source;
1555
+ webp = true;
1556
+ } else {
1557
+ t.source = img;
1558
+ if (t.extensions) {
1559
+ delete t.extensions[EXT_WEBP];
1560
+ if (!Object.keys(t.extensions).length) delete t.extensions;
1561
+ }
1562
+ }
1563
+ }
1564
+ if (webp) addExtension(json, EXT_WEBP, true);
1565
+ else removeExtension(json, EXT_WEBP);
1566
+ return dropped;
1567
+ }
1568
+ function pruneImages(json, candidates) {
1569
+ const images = json.images ?? [];
1570
+ const used = /* @__PURE__ */ new Set();
1571
+ for (const t of json.textures ?? []) for (const s of [t.source, ...Object.values(t.extensions ?? {}).map((e) => e?.source)]) if (typeof s === "number") used.add(s);
1572
+ const drop = new Set([...candidates].filter((i) => !used.has(i) && images[i]));
1573
+ if (!drop.size) return 0;
1574
+ const remap = /* @__PURE__ */ new Map();
1575
+ const kept = [];
1576
+ images.forEach((img, i) => {
1577
+ if (!drop.has(i)) remap.set(i, kept.length), kept.push(img);
1578
+ });
1579
+ for (const t of json.textures ?? []) {
1580
+ if (typeof t.source === "number") t.source = remap.get(t.source);
1581
+ for (const e of Object.values(t.extensions ?? {})) if (e && typeof e.source === "number") e.source = remap.get(e.source);
1582
+ }
1583
+ json.images = kept;
1584
+ if (!kept.length) delete json.images;
1585
+ return images.length - kept.length;
1586
+ }
1587
+ // src/ops/optimize.ts
1588
+ var optimize_exports = /* @__PURE__ */ __exportAll({
1589
+ optimizeAssets: () => optimizeAssets,
1590
+ optimizedExportSources: () => optimizedExportSources,
1591
+ planOptimize: () => planOptimize
1592
+ });
1593
+ var TEXTURE_FORMATS = [
1594
+ "auto",
1595
+ "webp",
1596
+ "jpeg",
1597
+ "png",
1598
+ "keep"
1599
+ ];
1600
+ var IMAGE_EXT = {
1601
+ png: "image/png",
1602
+ jpg: "image/jpeg",
1603
+ jpeg: "image/jpeg",
1604
+ webp: "image/webp"
1605
+ };
1606
+ var EXT_FOR_MIME = {
1607
+ "image/png": "png",
1608
+ "image/jpeg": "jpg",
1609
+ "image/webp": "webp"
1610
+ };
1611
+ var ext = (p) => p.slice(p.lastIndexOf(".") + 1).toLowerCase();
1612
+ var isOptimizable = (p) => !!IMAGE_EXT[ext(p)] || ext(p) === "glb";
1613
+ var describe = (w, h, mime, bytes) => `${w}x${h} ${mime} ${KB(bytes)} KB`;
1614
+ async function optimizeTargets(fs, opts) {
1615
+ const skipped = [];
1616
+ if (opts.paths?.length) {
1617
+ const targets = [];
1618
+ for (const raw of opts.paths) {
1619
+ const p = raw.replace(/^\.\//, "");
1620
+ if (p.startsWith("library:")) {
1621
+ skipped.push({
1622
+ path: p,
1623
+ reason: "Library assets are already optimised and read-only (export --optimize can shrink the exported copies)."
1624
+ });
1625
+ continue;
1626
+ }
1627
+ if (!await fs.exists(p)) throw new OpsError("notFound", `No file "${p}" in the project.`, "List the project's assets with assets_list (CLI: agent3d assets list).");
1628
+ if (!isOptimizable(p)) {
1629
+ skipped.push({
1630
+ path: p,
1631
+ reason: p.endsWith(".gltf") ? "A .gltf keeps its textures as separate files: optimise those image files instead." : /\.(hdr|exr)$/i.test(p) ? "Radiance .hdr / .exr files are not re-encoded (image-based lighting is prefiltered to a 256 px cube map: a 1k file is plenty)." : "Not a .jpg / .png / .webp texture or a .glb model."
1632
+ });
1633
+ continue;
1634
+ }
1635
+ if (!targets.includes(p)) targets.push(p);
1636
+ }
1637
+ return {
1638
+ targets,
1639
+ skipped
1640
+ };
1641
+ }
1642
+ if (!opts.all) throw new OpsError("invalid", "Say which assets to optimise.", "Pass paths (e.g. \"assets/textures/wood/wood_diff_1k.jpg\", \"assets/models/fox.glb\") or all: true (CLI: --all).");
1643
+ return {
1644
+ targets: (await fs.list("assets/")).filter((f) => f !== ASSET_MANIFEST_FILE).filter(isOptimizable).sort(),
1645
+ skipped
1646
+ };
1647
+ }
1648
+ function checkOptions(opts) {
1649
+ if (opts.maxSize !== void 0 && !(opts.maxSize >= 16 && opts.maxSize <= 8192)) throw new OpsError("invalid", `maxSize must be between 16 and 8192 pixels (got ${opts.maxSize}).`, "Leave it out for the smart per-texture size, or use 512 (banners, small props), 1024 (heroes), 2048 (close-ups).");
1650
+ if (opts.quality !== void 0 && !(opts.quality >= 1 && opts.quality <= 100)) throw new OpsError("invalid", `quality must be between 1 and 100 (got ${opts.quality}).`, "80 is a good default for WebP / JPEG.");
1651
+ if (opts.format !== void 0 && !TEXTURE_FORMATS.includes(opts.format)) throw new OpsError("invalid", `Unknown format "${opts.format}".`, `Use ${TEXTURE_FORMATS.join(", ")} (auto = WebP).`);
1652
+ if (opts.simplify !== void 0 && !(opts.simplify > 0 && opts.simplify <= 1)) throw new OpsError("invalid", `simplify must be a ratio between 0 and 1 (got ${opts.simplify}).`, "e.g. 0.5 keeps about half of the triangles (within the error bound).");
1653
+ if (opts.simplifyError !== void 0 && !(opts.simplifyError > 0 && opts.simplifyError <= 1)) throw new OpsError("invalid", `simplifyError must be between 0 and 1 (got ${opts.simplifyError}).`, "0.01 = 1 % of the mesh size (default); 0.05 allows visible changes.");
1654
+ }
1655
+ async function readScene(fs) {
1656
+ if (!await fs.exists("scene.json")) return null;
1657
+ try {
1658
+ return await readSceneFile(fs);
1659
+ } catch {
1660
+ return null;
1661
+ }
1662
+ }
1663
+ function decisionFor(plan, path, forced) {
1664
+ if (forced) return {
1665
+ maxSize: forced,
1666
+ reason: `--max-size ${forced}`,
1667
+ uses: []
1668
+ };
1669
+ return plan.files.get(path) ?? {
1670
+ maxSize: 1024,
1671
+ reason: `not placed in scene.json (scripts / unused) → 1024 px`,
1672
+ uses: []
1673
+ };
1674
+ }
1675
+ function roleDecision(plan, path, role, forced) {
1676
+ if (forced) return {
1677
+ maxSize: forced,
1678
+ reason: `--max-size ${forced}`,
1679
+ uses: []
1680
+ };
1681
+ return plan.modelRoles.get(path)?.[role] ?? {
1682
+ maxSize: 1024,
1683
+ reason: `model not placed in scene.json → 1024 px`,
1684
+ uses: []
1685
+ };
1686
+ }
1687
+ async function planOptimize(fs, opts) {
1688
+ checkOptions(opts);
1689
+ const { targets, skipped } = await optimizeTargets(fs, opts);
1690
+ const scene = await readScene(fs);
1691
+ const sizing = await planTextureSizes(fs, scene ?? {
1692
+ target: {
1693
+ kind: "hero",
1694
+ aspect: "16:9"
1695
+ },
1696
+ camera: {
1697
+ type: "perspective",
1698
+ position: [
1699
+ 0,
1700
+ 0,
1701
+ 5
1702
+ ]
1703
+ },
1704
+ objects: []
1705
+ }, { library: opts.library });
1706
+ const format = opts.format ?? "auto";
1707
+ const compress = opts.compress !== false;
1708
+ const entries = [];
1709
+ for (const path of targets) {
1710
+ const bytes = await fs.readBytes(path);
1711
+ const kb = KB(bytes.byteLength);
1712
+ if (ext(path) === "glb") {
1713
+ const d = decisionFor(sizing, path, opts.maxSize);
1714
+ let geometry;
1715
+ let images = 0;
1716
+ try {
1717
+ const { json } = readGlbChunks(bytes);
1718
+ images = (json.images ?? []).length;
1719
+ geometry = geometryBlocker(json) ?? ([compress ? "meshopt" : "", opts.simplify && opts.simplify < 1 ? `simplify ${opts.simplify}` : ""].filter(Boolean).join(" + ") || "kept");
1720
+ } catch (e) {
1721
+ geometry = e.message;
1722
+ }
1723
+ entries.push({
1724
+ path,
1725
+ kb,
1726
+ kind: "model",
1727
+ maxSize: d.maxSize,
1728
+ reason: d.reason,
1729
+ resize: true,
1730
+ format: format === "auto" ? "webp" : format,
1731
+ geometry,
1732
+ images
1733
+ });
1734
+ } else {
1735
+ const d = decisionFor(sizing, path, opts.maxSize);
1736
+ const h = imageHeader(bytes);
1737
+ entries.push({
1738
+ path,
1739
+ kb,
1740
+ kind: "texture",
1741
+ maxSize: d.maxSize,
1742
+ reason: d.reason,
1743
+ ...h ? {
1744
+ width: h.width,
1745
+ height: h.height
1746
+ } : {},
1747
+ resize: h ? Math.max(h.width, h.height) > d.maxSize : true,
1748
+ format: format === "auto" ? "webp" : format
1749
+ });
1750
+ }
1751
+ }
1752
+ return {
1753
+ viewport: sizing.viewport,
1754
+ entries,
1755
+ skipped,
1756
+ maxSize: opts.maxSize ?? "auto",
1757
+ quality: opts.quality ?? 80,
1758
+ format,
1759
+ compress
1760
+ };
1761
+ }
1762
+ async function renameBlocker(fs, scene, path, to) {
1763
+ if (await fs.exists(to)) return `${to} already exists`;
1764
+ const base = path.slice(path.lastIndexOf("/") + 1);
1765
+ if (scene) {
1766
+ let refs = 0;
1767
+ visitAssetRefs(JSON.parse(JSON.stringify(scene)), (p) => void (p === path && refs++));
1768
+ if (JSON.stringify(scene).split(JSON.stringify(path)).length - 1 > refs) return "scene.json mentions it outside asset fields";
1769
+ }
1770
+ for (const f of [...await fs.list("scripts/"), ...(await fs.list("assets/")).filter((x) => x.endsWith(".gltf"))]) {
1771
+ if (!/\.(m?js|gltf)$/i.test(f)) continue;
1772
+ if ((await fs.readText(f)).includes(base)) return `${f} mentions it`;
1773
+ }
1774
+ return null;
1775
+ }
1776
+ async function optimizeAssets(fs, opts, codec) {
1777
+ checkOptions(opts);
1778
+ const quality = Math.round(opts.quality ?? 80);
1779
+ const forced = opts.maxSize !== void 0 ? Math.round(opts.maxSize) : void 0;
1780
+ const format = opts.format ?? "auto";
1781
+ const compress = opts.compress !== false;
1782
+ const { targets, skipped } = await optimizeTargets(fs, opts);
1783
+ let scene = await readScene(fs);
1784
+ const sizing = await planTextureSizes(fs, scene ?? {
1785
+ target: {
1786
+ kind: "hero",
1787
+ aspect: "16:9"
1788
+ },
1789
+ camera: {
1790
+ type: "perspective",
1791
+ position: [
1792
+ 0,
1793
+ 0,
1794
+ 5
1795
+ ]
1796
+ },
1797
+ objects: []
1798
+ }, { library: opts.library });
1799
+ const files = [];
1800
+ const renamed = [];
1801
+ for (const path of targets) {
1802
+ const bytes = await fs.readBytes(path);
1803
+ try {
1804
+ if (ext(path) === "glb") {
1805
+ const r = await optimizeGlbFile(bytes, path, {
1806
+ sizing,
1807
+ forced,
1808
+ quality,
1809
+ format,
1810
+ compress,
1811
+ simplify: opts.simplify,
1812
+ simplifyError: opts.simplifyError
1813
+ }, codec);
1814
+ const changed = !!r.bytes && r.bytes.byteLength < bytes.byteLength;
1815
+ if (changed && !opts.dryRun) await fs.writeBytes(path, r.bytes);
1816
+ const d = decisionFor(sizing, path, forced);
1817
+ files.push({
1818
+ path,
1819
+ beforeBytes: bytes.byteLength,
1820
+ afterBytes: changed ? r.bytes.byteLength : bytes.byteLength,
1821
+ changed,
1822
+ maxSize: d.maxSize,
1823
+ sizeReason: d.reason,
1824
+ images: r.images,
1825
+ ...r.geometry ? { geometry: r.geometry } : {},
1826
+ ...r.notes.length ? { note: r.notes.join(" ") } : !changed ? { note: "Already small enough: kept as is." } : {}
1827
+ });
1828
+ continue;
1829
+ }
1830
+ if (!codec) {
1831
+ skipped.push({
1832
+ path,
1833
+ reason: "Textures need an image codec (headless Chrome): run `agent3d assets optimize` from the CLI."
1834
+ });
1835
+ continue;
1836
+ }
1837
+ const d = decisionFor(sizing, path, forced);
1838
+ const mime = IMAGE_EXT[ext(path)];
1839
+ const role = d.uses.some((u) => u.role === "color" || u.role === "background") ? "color" : d.uses.length && d.uses.every((u) => u.role === "data") ? "data" : d.uses.some((u) => u.role === "normal") ? "normal" : "color";
1840
+ let fmt = format;
1841
+ let renameNote;
1842
+ const wanted = format === "auto" || format === "webp" ? "image/webp" : format === "jpeg" ? "image/jpeg" : format === "png" ? "image/png" : mime;
1843
+ if (wanted !== mime) {
1844
+ const to = path.slice(0, path.lastIndexOf(".") + 1) + EXT_FOR_MIME[wanted];
1845
+ const blocker = await renameBlocker(fs, scene, path, to);
1846
+ if (blocker) {
1847
+ fmt = "keep";
1848
+ renameNote = `Format kept (${blocker}).`;
1849
+ }
1850
+ }
1851
+ const out = await codec({
1852
+ bytes,
1853
+ mimeType: mime,
1854
+ maxSize: d.maxSize,
1855
+ quality: role === "normal" ? Math.max(quality, 90) : quality,
1856
+ format: fmt
1857
+ });
1858
+ const ok = worthIt(out, bytes.byteLength);
1859
+ const image = {
1860
+ name: "image",
1861
+ role: d.uses.some((u) => u.role === "background") ? "background" : d.uses.length && d.uses.every((u) => u.role === "lighting") ? "lighting" : role,
1862
+ from: describe(out.srcWidth, out.srcHeight, mime, bytes.byteLength),
1863
+ to: describe(out.width, out.height, out.mimeType, out.bytes.byteLength),
1864
+ replaced: ok,
1865
+ maxSize: d.maxSize
1866
+ };
1867
+ let newPath;
1868
+ if (ok && out.mimeType !== mime) newPath = path.slice(0, path.lastIndexOf(".") + 1) + EXT_FOR_MIME[out.mimeType];
1869
+ if (ok && !opts.dryRun) {
1870
+ if (newPath) {
1871
+ await fs.writeBytes(newPath, out.bytes);
1872
+ await fs.remove(path);
1873
+ await renameAssetEntry(fs, path, newPath);
1874
+ if (scene) {
1875
+ visitAssetRefs(scene, (p) => p === path ? newPath : void 0);
1876
+ await saveScene(fs, scene, { allowInvalid: true });
1877
+ scene = await readScene(fs);
1878
+ }
1879
+ } else await fs.writeBytes(path, out.bytes);
1880
+ }
1881
+ if (newPath && ok) renamed.push({
1882
+ from: path,
1883
+ to: newPath
1884
+ });
1885
+ const note = [
1886
+ renameNote,
1887
+ !ok ? "Already small enough: kept as is." : void 0,
1888
+ newPath ? opts.dryRun ? `Would be renamed to ${newPath} (scene references rewritten).` : `Renamed to ${newPath}; scene references rewritten.` : void 0
1889
+ ].filter(Boolean).join(" ");
1890
+ files.push({
1891
+ path,
1892
+ ...newPath ? { newPath } : {},
1893
+ beforeBytes: bytes.byteLength,
1894
+ afterBytes: ok ? out.bytes.byteLength : bytes.byteLength,
1895
+ changed: ok,
1896
+ maxSize: d.maxSize,
1897
+ sizeReason: d.reason,
1898
+ images: [image],
1899
+ ...note ? { note } : {}
1900
+ });
1901
+ } catch (e) {
1902
+ if (e instanceof OpsError) throw e;
1903
+ skipped.push({
1904
+ path,
1905
+ reason: e.message
1906
+ });
1907
+ }
1908
+ }
1909
+ if (!opts.dryRun && files.some((f) => f.changed)) await refreshAssetManifest(fs);
1910
+ const before = files.reduce((n, f) => n + f.beforeBytes, 0);
1911
+ const after = files.reduce((n, f) => n + f.afterBytes, 0);
1912
+ return {
1913
+ files,
1914
+ skipped,
1915
+ beforeKb: KB(before),
1916
+ afterKb: KB(after),
1917
+ savedKb: KB(before - after),
1918
+ maxSize: forced ?? "auto",
1919
+ quality,
1920
+ format,
1921
+ compress,
1922
+ ...opts.dryRun ? { dryRun: true } : {},
1923
+ ...renamed.length ? { renamed } : {}
1924
+ };
1925
+ }
1926
+ function worthIt(out, before) {
1927
+ return out.width < out.srcWidth || out.height < out.srcHeight ? out.bytes.byteLength < before : out.bytes.byteLength < before * .9;
1928
+ }
1929
+ async function optimizeGlbFile(bytes, path, o, codec) {
1930
+ const model = await unpackGlb(bytes);
1931
+ const { json } = model;
1932
+ const notes = [];
1933
+ const report = [];
1934
+ let touched = model.wasCompressed;
1935
+ const images = json.images ?? [];
1936
+ if (images.length && !codec) notes.push("Embedded textures not re-encoded (needs headless Chrome).");
1937
+ if (images.length && codec) {
1938
+ const roles = imageRoles(json);
1939
+ for (const [i, img] of images.entries()) {
1940
+ const name = img.name || `image${i}`;
1941
+ if (img.bufferView === void 0) continue;
1942
+ const mime = img.mimeType ?? "";
1943
+ if (![
1944
+ "image/png",
1945
+ "image/jpeg",
1946
+ "image/webp"
1947
+ ].includes(mime)) {
1948
+ report.push({
1949
+ name,
1950
+ from: mime || "unknown type",
1951
+ to: "kept (unsupported format)",
1952
+ replaced: false
1953
+ });
1954
+ continue;
1955
+ }
1956
+ const shared = images.some((x, j) => j !== i && x.bufferView === img.bufferView);
1957
+ const role = roles.get(i) ?? "color";
1958
+ const maxSize = o.roleSizes?.[role] ?? (o.sizing ? roleDecision(o.sizing, path, role, o.forced).maxSize : o.forced ?? 1024);
1959
+ const src = model.views[img.bufferView];
1960
+ const out = await codec({
1961
+ bytes: src,
1962
+ mimeType: mime,
1963
+ maxSize,
1964
+ quality: role === "normal" ? Math.max(o.quality, 90) : o.quality,
1965
+ format: o.format,
1966
+ allowJpeg: o.format === "keep"
1967
+ });
1968
+ const ok = !shared && worthIt(out, src.byteLength);
1969
+ if (ok) {
1970
+ model.views[img.bufferView] = out.bytes;
1971
+ img.mimeType = out.mimeType;
1972
+ touched = true;
1973
+ }
1974
+ report.push({
1975
+ name,
1976
+ role,
1977
+ from: describe(out.srcWidth, out.srcHeight, mime, src.byteLength),
1978
+ to: describe(out.width, out.height, out.mimeType, out.bytes.byteLength),
1979
+ replaced: ok,
1980
+ maxSize
1981
+ });
1982
+ }
1983
+ if (pruneImages(json, normalizeTextureSources(json))) touched = true;
1984
+ compactViews(model);
1985
+ }
1986
+ let geometry;
1987
+ const blocker = geometryBlocker(json);
1988
+ if (blocker && (o.compress || o.simplify !== void 0)) notes.push(blocker);
1989
+ if (!blocker && (json.meshes ?? []).length) {
1990
+ const g = await rebuildGeometry(model, {
1991
+ compress: o.compress,
1992
+ simplify: o.simplify,
1993
+ simplifyError: o.simplifyError
1994
+ });
1995
+ geometry = {
1996
+ ...g,
1997
+ compressed: false
1998
+ };
1999
+ touched = true;
2000
+ notes.push(...g.notes);
2001
+ }
2002
+ if (!touched) return {
2003
+ images: report,
2004
+ notes
2005
+ };
2006
+ const packed = await packGlb(model, { compress: o.compress });
2007
+ if (geometry) geometry.compressed = packed.compressedViews > 0;
2008
+ if (!modelInfo(path, packed.bytes)) throw new Error("Internal error: the optimised .glb could not be read back (file kept).");
2009
+ return {
2010
+ bytes: packed.bytes,
2011
+ images: report,
2012
+ ...geometry ? { geometry } : {},
2013
+ notes
2014
+ };
2015
+ }
2016
+ async function optimizedExportSources(fs, library, opts = {}) {
2017
+ const scene = await readScene(fs);
2018
+ const sizing = await planTextureSizes(fs, scene ?? {
2019
+ target: {
2020
+ kind: "hero",
2021
+ aspect: "16:9"
2022
+ },
2023
+ camera: {
2024
+ type: "perspective",
2025
+ position: [
2026
+ 0,
2027
+ 0,
2028
+ 5
2029
+ ]
2030
+ },
2031
+ objects: []
2032
+ }, {
2033
+ library: library.index,
2034
+ includeLibrary: true
2035
+ });
2036
+ const quality = opts.quality ?? 80;
2037
+ const done = /* @__PURE__ */ new Map();
2038
+ const files = [];
2039
+ const shrink = (key, bytes) => {
2040
+ let p = done.get(key);
2041
+ if (!p) {
2042
+ p = (async () => {
2043
+ try {
2044
+ const e = ext(key);
2045
+ let out;
2046
+ const d = sizing.files.get(key);
2047
+ if (e === "glb") {
2048
+ const roleSizes = sizing.modelRoles.get(key);
2049
+ out = (await optimizeGlbFile(bytes, key, {
2050
+ sizing,
2051
+ quality,
2052
+ format: "auto",
2053
+ compress: true,
2054
+ roleSizes: roleSizes ? Object.fromEntries(Object.entries(roleSizes).map(([r, v]) => [r, v.maxSize])) : void 0
2055
+ }, opts.codec)).bytes;
2056
+ } else if (IMAGE_EXT[e] && opts.codec && d) {
2057
+ const role = d.uses.every((u) => u.role === "normal") ? "normal" : "color";
2058
+ const r = await opts.codec({
2059
+ bytes,
2060
+ mimeType: IMAGE_EXT[e],
2061
+ maxSize: d.maxSize,
2062
+ quality: role === "normal" ? Math.max(quality, 90) : quality,
2063
+ format: "keep"
2064
+ });
2065
+ if (r.mimeType === IMAGE_EXT[e] && worthIt(r, bytes.byteLength)) out = r.bytes;
2066
+ }
2067
+ const result = out && out.byteLength < bytes.byteLength ? out : bytes;
2068
+ files.push({
2069
+ path: key,
2070
+ beforeBytes: bytes.byteLength,
2071
+ afterBytes: result.byteLength,
2072
+ ...d ? { maxSize: d.maxSize } : {}
2073
+ });
2074
+ return result;
2075
+ } catch {
2076
+ return bytes;
2077
+ }
2078
+ })();
2079
+ done.set(key, p);
2080
+ }
2081
+ return p;
2082
+ };
2083
+ const wrappedFs = {
2084
+ readText: (p) => fs.readText(p),
2085
+ writeText: (p, t) => fs.writeText(p, t),
2086
+ writeBytes: (p, b) => fs.writeBytes(p, b),
2087
+ exists: (p) => fs.exists(p),
2088
+ list: (p) => fs.list(p),
2089
+ remove: (p) => fs.remove(p),
2090
+ size: (p) => fs.size(p),
2091
+ readBytes: async (path) => {
2092
+ const b = await fs.readBytes(path);
2093
+ return path.startsWith("assets/") && isOptimizable(path) ? shrink(path, b) : b;
2094
+ }
2095
+ };
2096
+ const wrappedLibrary = {
2097
+ ...library,
2098
+ index: library.index,
2099
+ read: async (id) => {
2100
+ const b = await library.read(id);
2101
+ return isOptimizable(id) ? shrink(`library:${id}`, b) : b;
2102
+ }
2103
+ };
2104
+ const report = () => {
2105
+ const before = files.reduce((n, f) => n + f.beforeBytes, 0);
2106
+ const after = files.reduce((n, f) => n + f.afterBytes, 0);
2107
+ return {
2108
+ files: [...files].sort((a, b) => a.path.localeCompare(b.path)),
2109
+ beforeKb: KB(before),
2110
+ afterKb: KB(after),
2111
+ savedKb: KB(before - after)
2112
+ };
2113
+ };
2114
+ return {
2115
+ fs: wrappedFs,
2116
+ library: wrappedLibrary,
2117
+ report
2118
+ };
2119
+ }
2120
+ // src/ops/assets.ts
2121
+ var assets_exports = /* @__PURE__ */ __exportAll({
2122
+ addAsset: () => addAsset,
2123
+ downloadAsset: () => downloadAsset,
2124
+ importAssetZip: () => importAssetZip,
2125
+ listAssets: () => listAssets,
2126
+ listLibrary: () => listLibrary,
2127
+ parseResolution: () => parseResolution,
2128
+ removeAsset: () => removeAsset,
2129
+ searchAssetsDetailed: () => searchAssetsDetailed
2130
+ });
2131
+ var KIND_DIR = {
2132
+ model: "models",
2133
+ texture: "textures",
2134
+ hdri: "hdris",
2135
+ audio: "audio",
2136
+ font: "fonts",
2137
+ svg: "svg",
2138
+ other: "other"
2139
+ };
2140
+ async function readAssetManifest(fs) {
2141
+ const m = await readJsonOr(fs, ASSET_MANIFEST_FILE, { assets: [] });
2142
+ return { assets: Array.isArray(m.assets) ? m.assets : [] };
2143
+ }
2144
+ async function writeAssetManifest(fs, m) {
2145
+ m.assets.sort((a, b) => a.path.localeCompare(b.path));
2146
+ for (const a of m.assets) if (await fs.exists(a.path)) a.bytes = await fs.size(a.path);
2147
+ await writeJson(fs, ASSET_MANIFEST_FILE, m);
2148
+ }
2149
+ async function refreshAssetManifest(fs) {
2150
+ if (!await fs.exists("assets/manifest.json")) return [];
2151
+ const m = await readAssetManifest(fs);
2152
+ const changed = [];
2153
+ for (const a of m.assets) if (await fs.exists(a.path) && await fs.size(a.path) !== a.bytes) changed.push(a.path);
2154
+ if (changed.length) await writeAssetManifest(fs, m);
2155
+ return changed;
2156
+ }
2157
+ async function renameAssetEntry(fs, from, to) {
2158
+ if (!await fs.exists("assets/manifest.json")) return;
2159
+ const m = await readAssetManifest(fs);
2160
+ const e = m.assets.find((a) => a.path === from);
2161
+ if (!e) return;
2162
+ e.path = to;
2163
+ await writeAssetManifest(fs, m);
2164
+ }
2165
+ async function listAssets(fs) {
2166
+ const manifest = await readAssetManifest(fs);
2167
+ const stale = [];
2168
+ const refs = await fs.exists("scene.json") ? collectAssetRefs(await readSceneFile(fs)) : [];
2169
+ const files = new Set((await fs.list("assets/")).filter((f) => f !== ASSET_MANIFEST_FILE));
2170
+ const out = [];
2171
+ for (const a of manifest.assets) {
2172
+ const exists = files.has(a.path);
2173
+ const bytes = exists ? await fs.size(a.path) : a.bytes;
2174
+ if (exists && bytes !== a.bytes) stale.push(a.path);
2175
+ out.push({
2176
+ ...a,
2177
+ bytes,
2178
+ exists,
2179
+ usedBy: refs.filter((r) => r.path === a.path).map((r) => r.at)
2180
+ });
2181
+ files.delete(a.path);
2182
+ }
2183
+ for (const f of files) out.push({
2184
+ path: f,
2185
+ kind: kindFromPath(f),
2186
+ bytes: await fs.size(f),
2187
+ source: "local",
2188
+ license: "unknown",
2189
+ addedAt: "",
2190
+ exists: true,
2191
+ usedBy: refs.filter((r) => r.path === f).map((r) => r.at)
2192
+ });
2193
+ return {
2194
+ assets: out,
2195
+ totalKb: KB(out.reduce((a, b) => a + (b.exists ? b.bytes : 0), 0)),
2196
+ ...stale.length ? { stale } : {}
2197
+ };
2198
+ }
2199
+ async function addAsset(fs, input) {
2200
+ if (!input.license?.trim()) throw new OpsError("invalid", "An asset needs a licence.", "Pass license, e.g. \"CC0-1.0\" (public domain) or \"CC-BY-4.0\" (with author).");
2201
+ let path = input.path.replace(/^\.\//, "");
2202
+ const kind = input.kind ?? kindFromPath(path);
2203
+ if (!path.includes("/")) path = `assets/${KIND_DIR[kind]}/${path}`;
2204
+ try {
2205
+ path = normalizePath(path);
2206
+ } catch {
2207
+ throw new OpsError("invalid", `Invalid asset path "${input.path}".`, "Use a project path under assets/, e.g. \"assets/models/fox.glb\".");
2208
+ }
2209
+ if (!path.startsWith("assets/") || path === "assets/manifest.json") throw new OpsError("invalid", `Assets live under assets/ (got "${path}").`, `Use e.g. "assets/${KIND_DIR[kind]}/${path.split("/").pop()}".`);
2210
+ await fs.writeBytes(path, input.bytes);
2211
+ const entry = {
2212
+ path,
2213
+ kind,
2214
+ bytes: input.bytes.byteLength,
2215
+ source: input.source,
2216
+ ...input.sourceUrl ? { sourceUrl: input.sourceUrl } : {},
2217
+ license: input.license,
2218
+ ...input.author ? { author: input.author } : {},
2219
+ ...input.attribution ? { attribution: input.attribution } : {},
2220
+ addedAt: nowIso()
2221
+ };
2222
+ const manifest = await readAssetManifest(fs);
2223
+ manifest.assets = manifest.assets.filter((a) => a.path !== path);
2224
+ manifest.assets.push(entry);
2225
+ await writeAssetManifest(fs, manifest);
2226
+ return entry;
2227
+ }
2228
+ async function removeAsset(fs, path) {
2229
+ const manifest = await readAssetManifest(fs);
2230
+ const inManifest = manifest.assets.some((a) => a.path === path);
2231
+ const exists = await fs.exists(path);
2232
+ if (!inManifest && !exists) {
2233
+ const s = closest(path, manifest.assets.map((a) => a.path));
2234
+ throw new OpsError("notFound", `No asset "${path}".`, s ? `Did you mean "${s}"?` : "List assets with assets_list / `agent3d assets list`.");
2235
+ }
2236
+ const usedBy = await fs.exists("scene.json") ? collectAssetRefs(await readSceneFile(fs)).filter((r) => r.path === path).map((r) => r.at) : [];
2237
+ if (exists) await fs.remove(path);
2238
+ if (inManifest) {
2239
+ manifest.assets = manifest.assets.filter((a) => a.path !== path);
2240
+ await writeAssetManifest(fs, manifest);
2241
+ }
2242
+ return {
2243
+ removed: true,
2244
+ usedBy
2245
+ };
2246
+ }
2247
+ async function searchAssetsDetailed(input, fetchImpl) {
2248
+ if (!input.query?.trim()) throw new OpsError("invalid", "Empty search query.", "Search with a few words, e.g. \"pine tree\", \"wood floor\", \"sunset sky\".");
2249
+ if (input.source && !SOURCES[input.source]) throw new OpsError("invalid", `Unknown source "${input.source}".`, `${closest(input.source, SOURCE_IDS) ? `Did you mean "${closest(input.source, SOURCE_IDS)}"? ` : ""}Sources: ${SOURCE_IDS.join(", ")}.`);
2250
+ const sources = input.source ? [SOURCES[input.source]] : Object.values(SOURCES).filter((s) => !input.kind || s.kinds.includes(input.kind));
2251
+ const errors = [];
2252
+ const results = await Promise.all(sources.map(async (s) => {
2253
+ try {
2254
+ return await s.search({
2255
+ query: input.query,
2256
+ kind: input.kind,
2257
+ limit: input.limit ?? 10
2258
+ }, fetchImpl);
2259
+ } catch (e) {
2260
+ errors.push({
2261
+ source: s.id,
2262
+ message: e.message
2263
+ });
2264
+ return [];
2265
+ }
2266
+ }));
2267
+ if (input.source && errors.length) throw new OpsError("io", `Search on ${input.source} failed: ${errors[0].message}`, "Check the network connection, or try another source.");
2268
+ return {
2269
+ hits: results.flat().sort((a, b) => Number(!!a.manual) - Number(!!b.manual)),
2270
+ errors
2271
+ };
2272
+ }
2273
+ function substitute(v, map) {
2274
+ if (typeof v === "string") return map(v);
2275
+ if (Array.isArray(v)) return v.map((x) => substitute(x, map));
2276
+ if (v && typeof v === "object") return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, substitute(x, map)]));
2277
+ return v;
2278
+ }
2279
+ function parseResolution(resolution) {
2280
+ if (!resolution) return {};
2281
+ const r = resolution.trim().toLowerCase();
2282
+ const px = /^(\d+)\s*(px)?$/.exec(r);
2283
+ const k = /^(\d*\.?\d+)\s*k$/.exec(r);
2284
+ const pixels = px ? Number(px[1]) : k ? Math.round(Number(k[1]) * 1024) : NaN;
2285
+ if (!Number.isFinite(pixels)) return { resolution: r };
2286
+ if (pixels < 1024) return {
2287
+ resolution: "1k",
2288
+ maxSize: Math.max(16, pixels)
2289
+ };
2290
+ return { resolution: k ? r : `${Math.round(pixels / 1024)}k` };
2291
+ }
2292
+ async function downloadAsset(fs, hit, fetchImpl, opts = {}) {
2293
+ const source = SOURCES[hit?.source];
2294
+ if (!hit || !source) throw new OpsError("invalid", "Pass an asset hit returned by assets_search (source, id, kind, downloads…).", `Sources: ${SOURCE_IDS.join(", ")}.`);
2295
+ if (hit.manual || !source.download || !Object.keys(hit.downloads ?? {}).length) throw new OpsError("invalid", `"${hit.title}" (${hit.source}) has no direct download.`, `Ask the user to download the pack from ${hit.pageUrl ?? "the source website"}, then import the zip: \`agent3d assets add <file.zip> --source ${hit.source} --license ${hit.license}\` (importAssetZip).`);
2296
+ const res = parseResolution(opts.resolution);
2297
+ const maxSize = opts.maxSize ?? res.maxSize;
2298
+ let downloaded;
2299
+ try {
2300
+ downloaded = await source.download(hit, fetchImpl, {
2301
+ resolution: res.resolution,
2302
+ inflate: opts.inflate
2303
+ });
2304
+ } catch (e) {
2305
+ if (e instanceof SourceError) throw new OpsError("io", `Download from ${hit.source} failed: ${e.message}`, "Retry, pick another resolution (1k, 2k) or another asset.");
2306
+ throw e;
2307
+ }
2308
+ const name = slugify(opts.name ?? hit.id, "asset");
2309
+ const dir = `assets/${KIND_DIR[hit.kind]}`;
2310
+ const names = Object.keys(downloaded.files);
2311
+ const single = names.length === 1;
2312
+ const target = (rel) => {
2313
+ if (single) {
2314
+ const ext = rel.includes(".") ? rel.slice(rel.lastIndexOf(".")) : "";
2315
+ return `${dir}/${name}${ext.toLowerCase()}`;
2316
+ }
2317
+ const inner = rel.includes("/") ? rel.slice(rel.indexOf("/") + 1) : rel;
2318
+ return `${dir}/${name}/${inner}`;
2319
+ };
2320
+ const written = [];
2321
+ let mainEntry = null;
2322
+ for (const rel of [downloaded.main, ...names.filter((n) => n !== downloaded.main)]) {
2323
+ const entry = await addAsset(fs, {
2324
+ path: target(rel),
2325
+ bytes: downloaded.files[rel],
2326
+ kind: rel === downloaded.main ? hit.kind : kindFromPath(rel),
2327
+ source: hit.source,
2328
+ sourceUrl: hit.pageUrl,
2329
+ license: hit.license,
2330
+ author: hit.author,
2331
+ attribution: hit.attribution
2332
+ });
2333
+ written.push(entry.path);
2334
+ if (rel === downloaded.main) mainEntry = entry;
2335
+ }
2336
+ const suggestion = downloaded.suggestion ? substitute(downloaded.suggestion, (s) => s === "<path>" ? mainEntry.path : downloaded.files[s] ? target(s) : s) : void 0;
2337
+ let optimized;
2338
+ let note;
2339
+ const images = written.filter((p) => /\.(png|jpe?g|webp|glb)$/i.test(p));
2340
+ if (maxSize && images.length) {
2341
+ if (opts.codec) {
2342
+ optimized = await optimizeAssets(fs, {
2343
+ paths: images,
2344
+ maxSize,
2345
+ quality: opts.quality,
2346
+ format: "keep",
2347
+ compress: false
2348
+ }, opts.codec);
2349
+ mainEntry = (await readAssetManifest(fs)).assets.find((a) => a.path === mainEntry.path) ?? mainEntry;
2350
+ } else note = `Not downscaled to ${maxSize} px here (needs headless Chrome): run \`agent3d assets optimize ${images.join(" ")} --max-size ${maxSize} --yes\`.`;
2351
+ }
2352
+ let bounds;
2353
+ if (hit.kind === "model") bounds = await modelFileBounds(fs, mainEntry.path) ?? void 0;
2354
+ return {
2355
+ ...mainEntry,
2356
+ files: written,
2357
+ ...suggestion ? { suggestion } : {},
2358
+ ...optimized ? { optimized } : {},
2359
+ ...bounds ? { bounds } : {},
2360
+ ...note ? { note } : {}
2361
+ };
2362
+ }
2363
+ var IMPORT_EXT = /\.(glb|gltf|bin|png|jpe?g|webp|ktx2)$/i;
2364
+ async function importAssetZip(fs, zip, opts) {
2365
+ let files;
2366
+ try {
2367
+ files = await readZip(zip, {
2368
+ inflate: opts.inflate,
2369
+ filter: (n) => IMPORT_EXT.test(n),
2370
+ maxBytes: 209715200
2371
+ });
2372
+ } catch (e) {
2373
+ throw new OpsError("invalid", `Cannot read the zip: ${e.message}`, "Pass the original .zip downloaded from the pack page.");
2374
+ }
2375
+ let names = Object.keys(files);
2376
+ const words = (opts.filter ?? []).map((w) => w.toLowerCase()).filter(Boolean);
2377
+ const models = names.filter((n) => /\.(glb|gltf)$/i.test(n) && (!words.length || words.some((w) => n.toLowerCase().includes(w))));
2378
+ if (!models.length) throw new OpsError("invalid", "The zip contains no .glb / .gltf model" + (words.length ? ` matching ${words.join(", ")}` : "") + ".", "Kenney / Quaternius packs ship glTF in a 'GLB format' / 'glTF' folder; check the pack, or drop --filter.");
2379
+ const keepDirs = new Set(models.map((m) => m.includes("/") ? m.slice(0, m.lastIndexOf("/") + 1) : ""));
2380
+ names = names.filter((n) => models.includes(n) || !/\.(glb|gltf)$/i.test(n) && [...keepDirs].some((d) => n.startsWith(d) || n.includes("Textures") || n.includes("textures")));
2381
+ const max = opts.maxFiles ?? 400;
2382
+ const skipped = Math.max(0, names.length - max);
2383
+ names = names.slice(0, max);
2384
+ const base = `assets/models/${slugify(opts.name, "pack")}`;
2385
+ const common = commonPrefix(names);
2386
+ const out = [];
2387
+ for (const n of names) {
2388
+ const rel = n.slice(common.length).replace(/\s+/g, "-");
2389
+ out.push(await addAsset(fs, {
2390
+ path: `${base}/${rel}`,
2391
+ bytes: files[n],
2392
+ kind: kindFromPath(n),
2393
+ source: opts.source,
2394
+ license: opts.license,
2395
+ author: opts.author,
2396
+ sourceUrl: opts.sourceUrl,
2397
+ attribution: opts.attribution
2398
+ }));
2399
+ }
2400
+ return {
2401
+ assets: out,
2402
+ models: out.filter((a) => /\.(glb|gltf)$/i.test(a.path)).map((a) => a.path),
2403
+ skipped
2404
+ };
2405
+ }
2406
+ function commonPrefix(paths) {
2407
+ if (!paths.length) return "";
2408
+ const dirs = paths.map((p) => p.split("/").slice(0, -1));
2409
+ const first = dirs[0];
2410
+ let i = 0;
2411
+ while (i < first.length && dirs.every((d) => d[i] === first[i])) i++;
2412
+ return i ? `${first.slice(0, i).join("/")}/` : "";
2413
+ }
2414
+ function listLibrary(index, filter = {}) {
2415
+ let list = (index?.assets ?? []).filter((a) => !filter.kind || a.kind === filter.kind);
2416
+ if (filter.query?.trim()) list = list.map((a) => ({
2417
+ a,
2418
+ s: score(filter.query, {
2419
+ id: a.id,
2420
+ title: a.id.replace(/[/-]/g, " "),
2421
+ tags: [...a.tags, ...a.animations ?? []],
2422
+ extra: a.description
2423
+ })
2424
+ })).filter((x) => x.s > 0).sort((x, y) => y.s - x.s).map((x) => x.a);
2425
+ const total = list.length;
2426
+ const offset = Math.max(0, Math.floor(filter.offset ?? 0));
2427
+ const limit = filter.limit === 0 ? Infinity : Math.max(1, Math.floor(filter.limit ?? 50));
2428
+ const page = list.slice(offset, offset + limit);
2429
+ return {
2430
+ total,
2431
+ offset,
2432
+ more: offset + page.length < total,
2433
+ assets: page.map((a) => ({
2434
+ id: a.id,
2435
+ ref: `library:${a.id}`,
2436
+ kind: a.kind,
2437
+ license: a.license,
2438
+ ...a.author ? { author: a.author } : {},
2439
+ tags: a.tags,
2440
+ description: a.description,
2441
+ kb: KB(a.bytes),
2442
+ ...a.animations?.length ? { animations: a.animations } : {},
2443
+ ...typeof a.triangles === "number" ? { triangles: a.triangles } : {},
2444
+ ...Array.isArray(a.size) ? { size: a.size } : {}
2445
+ }))
2446
+ };
2447
+ }
2448
+ export { listAssets as a, readAssetManifest as c, optimize_exports as d, optimizedExportSources as f, importAssetZip as i, searchAssetsDetailed as l, crc32 as m, assets_exports as n, listLibrary as o, SOURCE_IDS as p, downloadAsset as r, parseResolution as s, addAsset as t, optimizeAssets as u };