@joplo-app/plugin-3d 0.0.0-stage → 0.4.1

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.
package/LICENSE ADDED
@@ -0,0 +1,97 @@
1
+ Required Notice: Copyright 2026 Joplo-app (https://joplo.app, support@joplo.app)
2
+
3
+ Licensor Line of Business: Joplo, a tool for authoring, previewing, reviewing, and publishing interactive product prototypes, demos, and presentations (https://joplo.app)
4
+ Licensor Line of Business: Joplo Cloud, a service for hosting, sharing, commenting on, reviewing, and measuring Joplo prototypes and presentations (https://joplo.app)
5
+
6
+ What counts as competing, and how to ask about other uses: see COMMERCIAL.md
7
+ https://github.com/Joplo-app/Joplo/blob/main/COMMERCIAL.md
8
+
9
+ # PolyForm Shield License 1.0.0
10
+
11
+ <https://polyformproject.org/licenses/shield/1.0.0>
12
+
13
+ ## Acceptance
14
+
15
+ In order to get any license under these terms, you must agree to them as both strict obligations and conditions to all your licenses.
16
+
17
+ ## Copyright License
18
+
19
+ The licensor grants you a copyright license for the software to do everything you might do with the software that would otherwise infringe the licensor's copyright in it for any permitted purpose. However, you may only distribute the software according to [Distribution License](#distribution-license) and make changes or new works based on the software according to [Changes and New Works License](#changes-and-new-works-license).
20
+
21
+ ## Distribution License
22
+
23
+ The licensor grants you an additional copyright license to distribute copies of the software. Your license to distribute covers distributing the software with changes and new works permitted by [Changes and New Works License](#changes-and-new-works-license).
24
+
25
+ ## Notices
26
+
27
+ You must ensure that anyone who gets a copy of any part of the software from you also gets a copy of these terms or the URL for them above, as well as copies of any plain-text lines beginning with `Required Notice:` that the licensor provided with the software. For example:
28
+
29
+ > Required Notice: Copyright Yoyodyne, Inc. (http://example.com)
30
+
31
+ ## Changes and New Works License
32
+
33
+ The licensor grants you an additional copyright license to make changes and new works based on the software for any permitted purpose.
34
+
35
+ ## Patent License
36
+
37
+ The licensor grants you a patent license for the software that covers patent claims the licensor can license, or becomes able to license, that you would infringe by using the software.
38
+
39
+ ## Noncompete
40
+
41
+ Any purpose is a permitted purpose, except for providing any product that competes with the software or any product the licensor or any of its affiliates provides using the software.
42
+
43
+ ## Competition
44
+
45
+ Goods and services compete even when they provide functionality through different kinds of interfaces or for different technical platforms. Applications can compete with services, libraries with plugins, frameworks with development tools, and so on, even if they're written in different programming languages or for different computer architectures. Goods and services compete even when provided free of charge. If you market a product as a practical substitute for the software or another product, it definitely competes.
46
+
47
+ ## New Products
48
+
49
+ If you are using the software to provide a product that does not compete, but the licensor or any of its affiliates brings your product into competition by providing a new version of the software or another product using the software, you may continue using versions of the software available under these terms beforehand to provide your competing product, but not any later versions.
50
+
51
+ ## Discontinued Products
52
+
53
+ You may begin using the software to compete with a product or service that the licensor or any of its affiliates has stopped providing, unless the licensor includes a plain-text line beginning with `Licensor Line of Business:` with the software that mentions that line of business. For example:
54
+
55
+ > Licensor Line of Business: YoyodyneCMS Content Management System (http://example.com/cms)
56
+
57
+ ## Sales of Business
58
+
59
+ If the licensor or any of its affiliates sells a line of business developing the software or using the software to provide a product, the buyer can also enforce [Noncompete](#noncompete) for that product.
60
+
61
+ ## Fair Use
62
+
63
+ You may have "fair use" rights for the software under the law. These terms do not limit them.
64
+
65
+ ## No Other Rights
66
+
67
+ These terms do not allow you to sublicense or transfer any of your licenses to anyone else, or prevent the licensor from granting licenses to anyone else. These terms do not imply any other licenses.
68
+
69
+ ## Patent Defense
70
+
71
+ If you make any written claim that the software infringes or contributes to infringement of any patent, your patent license for the software granted under these terms ends immediately. If your company makes such a claim, your patent license ends immediately for work on behalf of your company.
72
+
73
+ ## Violations
74
+
75
+ The first time you are notified in writing that you have violated any of these terms, or done anything with the software not covered by your licenses, your licenses can nonetheless continue if you come into full compliance with these terms, and take practical steps to correct past violations, within 32 days of receiving notice. Otherwise, all your licenses end immediately.
76
+
77
+ ## No Liability
78
+
79
+ ***As far as the law allows, the software comes as is, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim.***
80
+
81
+ ## Definitions
82
+
83
+ The **licensor** is the individual or entity offering these terms, and the **software** is the software the licensor makes available under these terms.
84
+
85
+ A **product** can be a good or service, or a combination of them.
86
+
87
+ **You** refers to the individual or entity agreeing to these terms.
88
+
89
+ **Your company** is any legal entity, sole proprietorship, or other kind of organization that you work for, plus all its affiliates.
90
+
91
+ **Affiliates** means the other organizations than an organization has control over, is under the control of, or is under common control with.
92
+
93
+ **Control** means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect.
94
+
95
+ **Your licenses** are all the licenses granted to you for the software under these terms.
96
+
97
+ **Use** means anything you do with the software requiring one of your licenses.
package/README.md CHANGED
@@ -1,3 +1,20 @@
1
- # Temporary Holding Version
1
+ # @joplo-app/plugin-3d
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Optional Joplo 3D scenes (three.js), self-contained GLB loading and local Tripo model generation. Not installed by the starter. Plugin id: `scene3d`.
4
+
5
+ ```tsx
6
+ import scene3d, { Scene3D, model } from '@joplo-app/plugin-3d';
7
+ import { config, asset } from '@joplo-app/kit';
8
+ export default config({ name: 'Spatial demo', plugins: [scene3d] });
9
+ // Inside a page; declare scripted interactions or mark the model unmodeled:
10
+ <Scene3D id="scene"><Scene3D.Model id="subject" src={asset('./assets/models/subject.glb')} unmodeled /></Scene3D>
11
+ // Optional author-only request: src={model('An original low-poly apple, no ground')}
12
+ ```
13
+
14
+ Run `npx joplo skill install`, then `joplo skill scene3d`, `scene3d/models` and `scene3d/generation`. Existing GLB files work offline without a key. `/runtime` loads browser drawing only; `/local` contains the optional Node compiler and does not send requests on import.
15
+
16
+ Before generation run `joplo resources --dry-run`. Confirm each estimate; unattended generation requires `--allow-spend`. Check/build/render never generate. Commit `assets/models/<hash>.glb` and matching JSON; filenames depend only on normalized model request, never package/plugin identity, so package moves and compiler upgrades reuse existing output. If missing, restore from Git before approving another task.
17
+
18
+ Save the optional key in Voice → Manage keys, or set `TRIPO_API_KEY`. The host stores it at `~/.joplo/plugins/scene3d/keys/tripo.json` (0600; `JOPLO_HOME` supported), prioritizes the environment, and injects it as `ctx.keys.tripo` only into this plugin's local compiler. Never put keys in source, request parameters or asset provenance.
19
+
20
+ A recorded task resumes polling; unknown creation outcomes require manual recovery of the task id, never journal deletion and blind retries. Inspect actual triangles/bytes: face_limit does not guarantee them. Reduce oversized textures locally before paying for regeneration; keep ordinary embedded textures or meshopt geometry. See the generation skill for all recovery and cost rules.
@@ -0,0 +1,3 @@
1
+ export declare const skill = "## When to use\nA spatial product: smart home, retail shelf, factory line, data center, venue map, a physical device. The 3D view shows where things are and what changed; the rest of the screen (app UI, captions) stays normal Joplo components. Prefer ordinary components when space does not matter.\n\n## Enable\nInstall @joplo-app/plugin-3d, import its default manifest into joplo.config.ts and add it once to config.plugins. Run npx joplo skill install. The package uses plugin id scene3d for components, actions, skill topics and local resources; the starter intentionally omits it. The /local entry is Node-only; three.js stays in the runtime.\n\n## Minimal example\n```tsx\nimport { $ } from '@joplo-app/kit';\nimport { Scene3D } from '@joplo-app/plugin-3d';\n\n<Scene3D id=\"home\" height={440} focus={$.ui.focus} label=\"Living room\">\n <Scene3D.Object shape=\"floor\" size={[8, 0.1, 6]} />\n <Scene3D.Object shape=\"wall\" at={[0, 1.5, -3]} size={[8, 3, 0.1]} />\n <Scene3D.Object shape=\"sofa\" at={[-1.5, 0, -1.8]} />\n <Scene3D.Target id=\"lamp\" shape=\"lamp\" at={[2.6, 0, -2.2]} lit={$.data.lampOn} label=\"Floor lamp\" />\n <Scene3D.Target id=\"window\" shape=\"window\" at={[-1, 1.6, -2.95]} open={$.data.windowOpen} label=\"Window\" />\n</Scene3D>\n```\nThen in the option's flow: .click('lamp', 'Turn the lamp on', set($.data.lampOn, true), set($.ui.focus, 'lamp')).\n\n## Coordinates and sizes\n- Units are meters; y is up; the floor is y = 0. at is the bottom center of the object (for wall and window: the center). Keep scenes within about 10 \u00D7 8 m.\n- size overrides the preset size. Presets: floor 6\u00D70.1\u00D76, wall 6\u00D73\u00D70.1, lamp 0.5\u00D71.7\u00D70.5, door 0.9\u00D72.1\u00D70.08, window 1.4\u00D71.1\u00D70.08, sofa 2\u00D70.8\u00D70.9, table 1.2\u00D70.75\u00D70.8, bed 1.6\u00D70.6\u00D72.1, tv 1.4\u00D70.85\u00D70.08 (wall mounted, at is its center), plant 0.5\u00D71\u00D70.5, speaker 0.3\u00D70.5\u00D70.3, ac 0.9\u00D70.3\u00D70.25 (wall mounted, at is its center).\n- color: a theme color name (surface, subtle, line, ink, muted, accent, info, ok, warn, danger) or a CSS color; the default follows the theme, so the scene matches every theme.\n\n## State and steps\n- lit (lamp glows, tv and ac screens light up, other shapes glow), open (door and window swing open), color, label, and when may all bind state; set() in a step changes the scene. Disabled targets are drawn faded and show their disabledReason when clicked.\n- focus={$.ui.focus}: set($.ui.focus, 'lamp') moves the 3D camera to that object over about 0.7s; set($.ui.focus, null) shows the whole scene again. Use it once per step with the step's subject.\n- The Joplo camera, spotlight(), mark(), callout(), and shot() also work on Target and Object ids: they use the object's position on screen.\n\n## Pitfalls\n- Every Target needs a step, disabled + disabledReason, or unmodeled (UNBOUND_INTERACTIVE). Decorative items are Object, not Target.\n- Scene3D is the JSX export; the catalog name is scene3d:Scene. Use joplo components scene3d:Scene scene3d:Model when looking up props.\n- Object and Target must be direct children of Scene3D (PLUGIN_PARENT); other components inside Scene3D are ignored.\n- Dragging orbits locally. A scripted orbit uses .act('scene3d:rotate', 'home', { azimuth: 90, elevation: 32 }, set($.ui.azimuth, 90), set($.ui.elevation, 32)); bind these state paths to Scene3D azimuth/elevation for deterministic replay and screenshots. Matching tolerates 6 degrees; the demonstrator samples the engine clock. Arrow keys orbit too (Shift = fine adjustment). Playing/resetting discards an audience orbit.\n- Free device reactions use option({ free: { light: free.click('lamp', set($.data.lamp, false)) } }). A matching next action or another reachable scenario takes priority; the first stage input during playback pauses and applies immediately, including the same orbit drag or arrow key. Hover never pauses.\n- Do not put text inside the scene to explain things; use captions, callout() on the object, or the surrounding UI.\n\nFor real GLB geometry read npx joplo skill scene3d/models. For optional model() generation, cost approval and task recovery read npx joplo skill scene3d/generation. Existing GLB rendering needs no key.\n";
2
+ export declare const modelsGuide = "# Real GLB models\n\nUse Scene3D.Model (also exported as Model) for one self-contained binary GLB. First find suitable CC0 models or public-domain images; use a generation plugin for gaps in an original style. Do not hand-write complicated geometry or SVG to replace real assets.\n\nEnable scene3d in config.plugins, import { asset } from '@joplo-app/kit', then write:\n\n```tsx\n<Scene3D id=\"scene\" focus={$.ui.focus}>\n <Scene3D.Model id=\"fruit\" src={asset('./assets/models/fruit.glb')}\n size={[1, 1, 1]} at={[0, 0, 0]} label=\"Fruit\" outline={false} />\n</Scene3D>\n```\n\nasset paths are relative to the calling source file. The same package exports model() for a declarative generated src. Read npx joplo skill scene3d/generation for cost confirmation and recovery. Commit model files and their metadata; a missing model must never silently trigger paid generation during check/build/render.\n\nsize is a bounding fit preserving the original aspect ratio; at is bottom-center with Y up; rotate is degrees around Y. Keep the original textures by omitting color; color explicitly tints the material with a theme role or CSS color. outline defaults true; turn it off for smooth textured assets to avoid distracting triangle edges. lit, visibility, disabled state, label and showLabel work with state. Material tint and outlines follow theme changes. Changing only color reuses the loaded model and textures, without a loading placeholder; removing color restores the original material color. showLabel={false} hides the visible nameplate even for an interactive model, while its labeled anchor remains available for input and accessibility.\n\nEach model is interactive: use a click step, free reaction, disabledReason or unmodeled. It must be a direct child of Scene3D. focus, shot, spotlight and callout target its id. Drag/arrow keys orbit the scene; scripted rotation uses scene3d:rotate targeting the Scene3D id. A paused raycast hover honors the author-declared .hover/free.hover dwell; moving away cancels it. Hover during playback never pauses or fires. Provide a click button for touch/keyboard audiences. A model drag reports the existing drag action, and may land on a named ordinary DOM target outside the 3D canvas; bind its at to state to show a deterministic position change. Free experience resets on play/jump/reset.\n\nThe loader supports embedded textures and meshopt geometry compression without external decoder URLs. It holds screenshot/export readiness until its first model frame is drawn; changing src or unmounting releases obsolete holds and disposes geometry/textures. Corrupt, missing, external-buffer GLB and unsupported formats show MODEL_LOAD_FAILED and a readable box; restore/re-export the GLB, then reload. Draco/KTX2 compressed assets are not enabled\u2014re-export with embedded ordinary textures and meshopt or uncompressed geometry.\n\n## A model over archival artwork\n- Scene3D clears to transparent. Put the licensed Image and a legibility gradient behind it as siblings; never put a 2D background or labels inside Scene3D. Its children must be declared scene objects/models.\n- Keep one model centered at the same screen position across an era change, and swap the visible model while changing the background and score. This is a model replacement, not geometric morphing. Use one visible subject and sparse surrounding text.\n- For a film close-up, use the enclosing content Canvas camera. Scene3D focus gives a contextual view of an object and is not a fixed zoom multiplier; with only one object it can be wider than the whole-scene framing. Inspect both frames instead of guessing from the focus id.\n- For a whole-object flight or drop, animate a stable wrapper with the content plugin's motion property. Changing a model's structural at/size/src rebuilds it; do not expect vertex morphs or physical gravity. Keep a static frame target so screenshots and direct jumps still match.\n- Check mouse rotation, keyboard arrows, a declared object drag, hover, and a click independently. A declared model drag takes priority over orbit; drag empty canvas to rotate that scene. Reset/play discard local orbit, but snapshots always read scripted angles.\n\nKeep web geometry around 10k\u201350k faces and GLB below 5 MB. Inspect actual GLB accessor/index counts and bytes; a generation parameter alone is not proof of the exported budget. Models above 5 MB warn, above 50 MB fail. Check the initial frame and a focused frame, then open the build with npx joplo preview and no other network. A GLB download succeeding alone does not prove texture, anchoring or camera fit.\n";
3
+ export declare const generationGuide = "## When to use\nFirst look for suitable CC0 models and public-domain reference images; use Tripo to fill gaps in your own style. Do not hand-write complex geometry or SVG to imitate a model. Do not copy protected character designs or trademarks.\n\n## Start\nInstall @joplo-app/plugin-3d and enable its default plugin in config.plugins for both rendering and optional generation. Import { model } from '@joplo-app/plugin-3d'; set a model component's src to model('A single red apple, short brown stem, matte skin, original low-poly style, no ground'). Or model({ prompt: 'Description', image: asset('./reference.png') }) for image-to-model. References upload through /v3/files only after confirmation; use PNG/JPEG (asset() limits images to 2 MB; the upload API allows up to 20 MB), with one clearly separated subject.\n\nRun npx joplo resources --dry-run to inspect each estimate. Then npx joplo resources asks before each generation in a terminal; unattended runs require --allow-spend. Check/build/render never generate, even with a key. Missing output stays a readable placeholder with a diagnostic. Never add credentials to model() or project config.\n\n## A small, reviewable production batch\n- Write assets/SOURCES.md before generating: public-domain/CC0 artwork, the original model prompts that fill the gaps, author/license URLs, intended modifications and a total credit ceiling. A reference painting sets the period; it need not be uploaded when a clear text prompt is sufficient.\n- Generate one model first and inspect it in the intended renderer. Check silhouette, orientation, textures, actual bytes and triangles before repeating the settings. Describe a single isolated subject without ground, text or a pedestal when it must sit over a painting. Explicitly avoid protected character or trademark shapes when creating an original interpretation.\n- Re-run resources --dry-run before each batch. Sum credits_consumed from successful metadata separately from the estimates and any queued jobs; a timeout with a task_id is a poll/resume, not a new generation request. Keep keys out of command output and the asset ledger.\n- face_limit is a generation target, not a byte limit or proof of final triangle count. Textures can dominate even a small mesh. If a model is over the delivery budget, try local texture resizing before paying for a different model: for example glTF Transform resize input.glb output.glb --width 1024 --height 1024. Preserve self-contained ordinary PNG/JPEG textures (or meshopt geometry supported by the renderer); do not choose Draco/KTX2 unless the renderer explicitly supports their decoders.\n- Keep the generation JSON with its GLB, record postprocessing in SOURCES.md, and inspect the optimized file again. Do not change the prompt merely to describe that local optimization: that creates a new paid resource identity. Rebuild and test file:// after replacing bytes.\n\n## Geometry and cost\nDescribe one subject, shape, material and style. Web models usually need 10k\u201350k faces; default smart_low_poly:true uses 10k and accepts 500\u201320k. To use 50k, disable smart_low_poly. Model is pinned to v3.1-20260211. Text generation estimates 10 credits untextured / 20 textured; image generation 20 / 30; smart_low_poly adds 10; detailed texture adds 10. pbr requires texture. Inspect the downloaded GLB triangle count and bytes instead of assuming face_limit proves the exported size; any paid decimation is a separate approved operation. Every generation displays the estimate; actual credits_consumed comes from Tripo. Failed/cancelled tasks refund frozen credits according to Tripo; verify the account rather than assuming a local timeout is a refund.\n\n## Persistence and recovery\nCommit assets/models/<description-and-parameters-hash>.glb AND its .json metadata. Builds on other machines read that output without a key or network. Changing description, parameters, reference bytes or model version creates a different path. Plugin code updates do not regenerate existing models. Do not store temporary model URLs.\n\nSave a key in the board \u2192 Voice \u2192 Manage keys \u2192 Tripo, or use TRIPO_API_KEY. Saved keys stay in ~/.joplo/plugins/scene3d/keys/tripo.json (0600), never IR or published files. JOPLO_HOME may override the local directory.\n\nA network failure after task_id is saved: rerun resources to poll the same task. A creating/unknown journal: inspect Tripo task history, recover task_id into the matching JSON and set status to queued; never delete the journal and blindly create again. For invalid keys, update the local key. For insufficient credits (2010), stop and tell the user; do not purchase. For moderation (2008), revise the content. For damaged GLB, restore from Git or resume the saved successful task after removing only the damaged GLB. Large models warn at 5 MB and fail at 50 MB; reduce geometry/texture before sharing. Verify the model in the board, screenshot and file:// build before delivery.\n";
package/dist/guide.js ADDED
@@ -0,0 +1,96 @@
1
+ export const skill = `## When to use
2
+ A spatial product: smart home, retail shelf, factory line, data center, venue map, a physical device. The 3D view shows where things are and what changed; the rest of the screen (app UI, captions) stays normal Joplo components. Prefer ordinary components when space does not matter.
3
+
4
+ ## Enable
5
+ Install @joplo-app/plugin-3d, import its default manifest into joplo.config.ts and add it once to config.plugins. Run npx joplo skill install. The package uses plugin id scene3d for components, actions, skill topics and local resources; the starter intentionally omits it. The /local entry is Node-only; three.js stays in the runtime.
6
+
7
+ ## Minimal example
8
+ \`\`\`tsx
9
+ import { $ } from '@joplo-app/kit';
10
+ import { Scene3D } from '@joplo-app/plugin-3d';
11
+
12
+ <Scene3D id="home" height={440} focus={$.ui.focus} label="Living room">
13
+ <Scene3D.Object shape="floor" size={[8, 0.1, 6]} />
14
+ <Scene3D.Object shape="wall" at={[0, 1.5, -3]} size={[8, 3, 0.1]} />
15
+ <Scene3D.Object shape="sofa" at={[-1.5, 0, -1.8]} />
16
+ <Scene3D.Target id="lamp" shape="lamp" at={[2.6, 0, -2.2]} lit={$.data.lampOn} label="Floor lamp" />
17
+ <Scene3D.Target id="window" shape="window" at={[-1, 1.6, -2.95]} open={$.data.windowOpen} label="Window" />
18
+ </Scene3D>
19
+ \`\`\`
20
+ Then in the option's flow: .click('lamp', 'Turn the lamp on', set($.data.lampOn, true), set($.ui.focus, 'lamp')).
21
+
22
+ ## Coordinates and sizes
23
+ - Units are meters; y is up; the floor is y = 0. at is the bottom center of the object (for wall and window: the center). Keep scenes within about 10 × 8 m.
24
+ - size overrides the preset size. Presets: floor 6×0.1×6, wall 6×3×0.1, lamp 0.5×1.7×0.5, door 0.9×2.1×0.08, window 1.4×1.1×0.08, sofa 2×0.8×0.9, table 1.2×0.75×0.8, bed 1.6×0.6×2.1, tv 1.4×0.85×0.08 (wall mounted, at is its center), plant 0.5×1×0.5, speaker 0.3×0.5×0.3, ac 0.9×0.3×0.25 (wall mounted, at is its center).
25
+ - color: a theme color name (surface, subtle, line, ink, muted, accent, info, ok, warn, danger) or a CSS color; the default follows the theme, so the scene matches every theme.
26
+
27
+ ## State and steps
28
+ - lit (lamp glows, tv and ac screens light up, other shapes glow), open (door and window swing open), color, label, and when may all bind state; set() in a step changes the scene. Disabled targets are drawn faded and show their disabledReason when clicked.
29
+ - focus={$.ui.focus}: set($.ui.focus, 'lamp') moves the 3D camera to that object over about 0.7s; set($.ui.focus, null) shows the whole scene again. Use it once per step with the step's subject.
30
+ - The Joplo camera, spotlight(), mark(), callout(), and shot() also work on Target and Object ids: they use the object's position on screen.
31
+
32
+ ## Pitfalls
33
+ - Every Target needs a step, disabled + disabledReason, or unmodeled (UNBOUND_INTERACTIVE). Decorative items are Object, not Target.
34
+ - Scene3D is the JSX export; the catalog name is scene3d:Scene. Use joplo components scene3d:Scene scene3d:Model when looking up props.
35
+ - Object and Target must be direct children of Scene3D (PLUGIN_PARENT); other components inside Scene3D are ignored.
36
+ - Dragging orbits locally. A scripted orbit uses .act('scene3d:rotate', 'home', { azimuth: 90, elevation: 32 }, set($.ui.azimuth, 90), set($.ui.elevation, 32)); bind these state paths to Scene3D azimuth/elevation for deterministic replay and screenshots. Matching tolerates 6 degrees; the demonstrator samples the engine clock. Arrow keys orbit too (Shift = fine adjustment). Playing/resetting discards an audience orbit.
37
+ - Free device reactions use option({ free: { light: free.click('lamp', set($.data.lamp, false)) } }). A matching next action or another reachable scenario takes priority; the first stage input during playback pauses and applies immediately, including the same orbit drag or arrow key. Hover never pauses.
38
+ - Do not put text inside the scene to explain things; use captions, callout() on the object, or the surrounding UI.
39
+
40
+ For real GLB geometry read npx joplo skill scene3d/models. For optional model() generation, cost approval and task recovery read npx joplo skill scene3d/generation. Existing GLB rendering needs no key.
41
+ `;
42
+ export const modelsGuide = `# Real GLB models
43
+
44
+ Use Scene3D.Model (also exported as Model) for one self-contained binary GLB. First find suitable CC0 models or public-domain images; use a generation plugin for gaps in an original style. Do not hand-write complicated geometry or SVG to replace real assets.
45
+
46
+ Enable scene3d in config.plugins, import { asset } from '@joplo-app/kit', then write:
47
+
48
+ \`\`\`tsx
49
+ <Scene3D id="scene" focus={$.ui.focus}>
50
+ <Scene3D.Model id="fruit" src={asset('./assets/models/fruit.glb')}
51
+ size={[1, 1, 1]} at={[0, 0, 0]} label="Fruit" outline={false} />
52
+ </Scene3D>
53
+ \`\`\`
54
+
55
+ asset paths are relative to the calling source file. The same package exports model() for a declarative generated src. Read npx joplo skill scene3d/generation for cost confirmation and recovery. Commit model files and their metadata; a missing model must never silently trigger paid generation during check/build/render.
56
+
57
+ size is a bounding fit preserving the original aspect ratio; at is bottom-center with Y up; rotate is degrees around Y. Keep the original textures by omitting color; color explicitly tints the material with a theme role or CSS color. outline defaults true; turn it off for smooth textured assets to avoid distracting triangle edges. lit, visibility, disabled state, label and showLabel work with state. Material tint and outlines follow theme changes. Changing only color reuses the loaded model and textures, without a loading placeholder; removing color restores the original material color. showLabel={false} hides the visible nameplate even for an interactive model, while its labeled anchor remains available for input and accessibility.
58
+
59
+ Each model is interactive: use a click step, free reaction, disabledReason or unmodeled. It must be a direct child of Scene3D. focus, shot, spotlight and callout target its id. Drag/arrow keys orbit the scene; scripted rotation uses scene3d:rotate targeting the Scene3D id. A paused raycast hover honors the author-declared .hover/free.hover dwell; moving away cancels it. Hover during playback never pauses or fires. Provide a click button for touch/keyboard audiences. A model drag reports the existing drag action, and may land on a named ordinary DOM target outside the 3D canvas; bind its at to state to show a deterministic position change. Free experience resets on play/jump/reset.
60
+
61
+ The loader supports embedded textures and meshopt geometry compression without external decoder URLs. It holds screenshot/export readiness until its first model frame is drawn; changing src or unmounting releases obsolete holds and disposes geometry/textures. Corrupt, missing, external-buffer GLB and unsupported formats show MODEL_LOAD_FAILED and a readable box; restore/re-export the GLB, then reload. Draco/KTX2 compressed assets are not enabled—re-export with embedded ordinary textures and meshopt or uncompressed geometry.
62
+
63
+ ## A model over archival artwork
64
+ - Scene3D clears to transparent. Put the licensed Image and a legibility gradient behind it as siblings; never put a 2D background or labels inside Scene3D. Its children must be declared scene objects/models.
65
+ - Keep one model centered at the same screen position across an era change, and swap the visible model while changing the background and score. This is a model replacement, not geometric morphing. Use one visible subject and sparse surrounding text.
66
+ - For a film close-up, use the enclosing content Canvas camera. Scene3D focus gives a contextual view of an object and is not a fixed zoom multiplier; with only one object it can be wider than the whole-scene framing. Inspect both frames instead of guessing from the focus id.
67
+ - For a whole-object flight or drop, animate a stable wrapper with the content plugin's motion property. Changing a model's structural at/size/src rebuilds it; do not expect vertex morphs or physical gravity. Keep a static frame target so screenshots and direct jumps still match.
68
+ - Check mouse rotation, keyboard arrows, a declared object drag, hover, and a click independently. A declared model drag takes priority over orbit; drag empty canvas to rotate that scene. Reset/play discard local orbit, but snapshots always read scripted angles.
69
+
70
+ Keep web geometry around 10k–50k faces and GLB below 5 MB. Inspect actual GLB accessor/index counts and bytes; a generation parameter alone is not proof of the exported budget. Models above 5 MB warn, above 50 MB fail. Check the initial frame and a focused frame, then open the build with npx joplo preview and no other network. A GLB download succeeding alone does not prove texture, anchoring or camera fit.
71
+ `;
72
+ export const generationGuide = `## When to use
73
+ First look for suitable CC0 models and public-domain reference images; use Tripo to fill gaps in your own style. Do not hand-write complex geometry or SVG to imitate a model. Do not copy protected character designs or trademarks.
74
+
75
+ ## Start
76
+ Install @joplo-app/plugin-3d and enable its default plugin in config.plugins for both rendering and optional generation. Import { model } from '@joplo-app/plugin-3d'; set a model component's src to model('A single red apple, short brown stem, matte skin, original low-poly style, no ground'). Or model({ prompt: 'Description', image: asset('./reference.png') }) for image-to-model. References upload through /v3/files only after confirmation; use PNG/JPEG (asset() limits images to 2 MB; the upload API allows up to 20 MB), with one clearly separated subject.
77
+
78
+ Run npx joplo resources --dry-run to inspect each estimate. Then npx joplo resources asks before each generation in a terminal; unattended runs require --allow-spend. Check/build/render never generate, even with a key. Missing output stays a readable placeholder with a diagnostic. Never add credentials to model() or project config.
79
+
80
+ ## A small, reviewable production batch
81
+ - Write assets/SOURCES.md before generating: public-domain/CC0 artwork, the original model prompts that fill the gaps, author/license URLs, intended modifications and a total credit ceiling. A reference painting sets the period; it need not be uploaded when a clear text prompt is sufficient.
82
+ - Generate one model first and inspect it in the intended renderer. Check silhouette, orientation, textures, actual bytes and triangles before repeating the settings. Describe a single isolated subject without ground, text or a pedestal when it must sit over a painting. Explicitly avoid protected character or trademark shapes when creating an original interpretation.
83
+ - Re-run resources --dry-run before each batch. Sum credits_consumed from successful metadata separately from the estimates and any queued jobs; a timeout with a task_id is a poll/resume, not a new generation request. Keep keys out of command output and the asset ledger.
84
+ - face_limit is a generation target, not a byte limit or proof of final triangle count. Textures can dominate even a small mesh. If a model is over the delivery budget, try local texture resizing before paying for a different model: for example glTF Transform resize input.glb output.glb --width 1024 --height 1024. Preserve self-contained ordinary PNG/JPEG textures (or meshopt geometry supported by the renderer); do not choose Draco/KTX2 unless the renderer explicitly supports their decoders.
85
+ - Keep the generation JSON with its GLB, record postprocessing in SOURCES.md, and inspect the optimized file again. Do not change the prompt merely to describe that local optimization: that creates a new paid resource identity. Rebuild and test file:// after replacing bytes.
86
+
87
+ ## Geometry and cost
88
+ Describe one subject, shape, material and style. Web models usually need 10k–50k faces; default smart_low_poly:true uses 10k and accepts 500–20k. To use 50k, disable smart_low_poly. Model is pinned to v3.1-20260211. Text generation estimates 10 credits untextured / 20 textured; image generation 20 / 30; smart_low_poly adds 10; detailed texture adds 10. pbr requires texture. Inspect the downloaded GLB triangle count and bytes instead of assuming face_limit proves the exported size; any paid decimation is a separate approved operation. Every generation displays the estimate; actual credits_consumed comes from Tripo. Failed/cancelled tasks refund frozen credits according to Tripo; verify the account rather than assuming a local timeout is a refund.
89
+
90
+ ## Persistence and recovery
91
+ Commit assets/models/<description-and-parameters-hash>.glb AND its .json metadata. Builds on other machines read that output without a key or network. Changing description, parameters, reference bytes or model version creates a different path. Plugin code updates do not regenerate existing models. Do not store temporary model URLs.
92
+
93
+ Save a key in the board → Voice → Manage keys → Tripo, or use TRIPO_API_KEY. Saved keys stay in ~/.joplo/plugins/scene3d/keys/tripo.json (0600), never IR or published files. JOPLO_HOME may override the local directory.
94
+
95
+ A network failure after task_id is saved: rerun resources to poll the same task. A creating/unknown journal: inspect Tripo task history, recover task_id into the matching JSON and set status to queued; never delete the journal and blindly create again. For invalid keys, update the local key. For insufficient credits (2010), stop and tell the user; do not purchase. For moderation (2008), revise the content. For damaged GLB, restore from Git or resume the saved successful task after removing only the damaged GLB. Large models warn at 5 MB and fail at 50 MB; reduce geometry/texture before sharing. Verify the model in the board, screenshot and file:// build before delivery.
96
+ `;
@@ -0,0 +1,18 @@
1
+ import { type ModelOptions } from './request.js';
2
+ export { type ModelOptions } from './request.js';
3
+ /** Declarative model request; no network or credentials in author code. */
4
+ export declare const model: (options: ModelOptions | string) => {
5
+ kind: "local-resource";
6
+ plugin: string;
7
+ compiler: string;
8
+ input: string;
9
+ };
10
+ declare const plugin: import("@joplo-app/kit").PluginDef;
11
+ export default plugin;
12
+ /** JSX 标记:<Scene3D>、<Scene3D.Object>、<Scene3D.Target>。 */
13
+ export declare const Scene3D: ((props: import("@joplo-app/kit").JoploProps) => any) & {
14
+ Object: (props: import("@joplo-app/kit").JoploProps) => any;
15
+ Target: (props: import("@joplo-app/kit").JoploProps) => any;
16
+ Model: (props: import("@joplo-app/kit").JoploProps) => any;
17
+ };
18
+ export declare const Model: (props: import("@joplo-app/kit").JoploProps) => any;
package/dist/index.js ADDED
@@ -0,0 +1,39 @@
1
+ /**
2
+ * @joplo-app/plugin-3d 入口(Node 端载入,只返回数据):插件清单、JSX 标记、给 Agent 读的技能。
3
+ * 画面由 ./runtime.ts(浏览器端,three.js)负责。
4
+ */
5
+ import { skill, modelsGuide, generationGuide } from "./guide.js";
6
+ import { definePlugin, pluginComponent, localResource } from '@joplo-app/kit/plugin';
7
+ import info from './version.json' with { type: 'json' };
8
+ import { normalize } from "./request.js";
9
+ export {} from "./request.js";
10
+ /** Declarative model request; no network or credentials in author code. */
11
+ export const model = (options) => localResource('scene3d', 'glb', JSON.stringify(normalize(typeof options === 'string' ? { prompt: options } : options)));
12
+ const SHAPES = 'box, cylinder, sphere, cone, floor, wall, lamp, door, window, sofa, table, bed, tv, plant, speaker, ac';
13
+ const plugin = definePlugin({
14
+ id: 'scene3d',
15
+ title: '3D scene',
16
+ version: info.version,
17
+ packageName: '@joplo-app/plugin-3d',
18
+ description: 'Interactive 3D scenes (three.js): steps click objects, state drives lights, doors, windows, and the camera',
19
+ runtime: new URL(new URL(import.meta.url).pathname.endsWith('.ts') ? './runtime.ts' : './runtime.js', import.meta.url),
20
+ local: new URL(new URL(import.meta.url).pathname.endsWith('.ts') ? './local.ts' : './local.js', import.meta.url),
21
+ keys: [{ id: 'tripo', title: 'Tripo · 3D', description: 'Optional model generation; existing GLB files work offline without a key.', url: 'https://platform.tripo3d.ai/api-keys', env: 'TRIPO_API_KEY' }],
22
+ actions: { rotate: { caption: 'Rotate {label} to {data.azimuth}°', durationMs: 1000, targets: ['scene3d:Scene'], fields: { azimuth: { type: 'number', min: -180, max: 180, tolerance: 6 }, elevation: { type: 'number', min: 6, max: 86, tolerance: 6 } } } },
23
+ components: {
24
+ Model: { parent: 'Scene', interactive: true, traits: { text: ['label'] }, doc: 'src: asset(GLB) or local resource; at, size (bounding fit, preserves aspect), rotate, color (optional tint), outline, label, showLabel (false hides the nameplate), lit; clickable model' },
25
+ Scene: { traits: { text: ['label'] }, doc: 'height (px, default 420), focus (child id or null: the 3D camera frames it), view ("iso" | "front" | "top"), azimuth / elevation (degrees, bind to state for a scripted view), label; root of a 3D scene, viewers drag to orbit' },
26
+ Object: { parent: 'Scene', traits: { text: ['label'] }, doc: `shape (${SHAPES}), at [x, y, z], size [w, h, d], rotate (degrees around the vertical axis), color, lit, open, label, showLabel; decorative or state-driven object` },
27
+ Target: { parent: 'Scene', interactive: true, traits: { text: ['label'] }, doc: 'same props as Object; an object viewers click (steps: .click(id)); always shows its label' },
28
+ },
29
+ skill,
30
+ skillTopics: { generation: { description: 'Optional Tripo generation, cost confirmation, persisted models and task recovery', body: generationGuide }, models: { description: 'GLB assets, loading readiness, material tint, anchors and offline checks', body: modelsGuide } },
31
+ });
32
+ export default plugin;
33
+ /** JSX 标记:<Scene3D>、<Scene3D.Object>、<Scene3D.Target>。 */
34
+ export const Scene3D = Object.assign(pluginComponent(plugin, 'Scene'), {
35
+ Object: pluginComponent(plugin, 'Object'),
36
+ Target: pluginComponent(plugin, 'Target'),
37
+ Model: pluginComponent(plugin, 'Model'),
38
+ });
39
+ export const Model = Scene3D.Model;
@@ -0,0 +1,2 @@
1
+ /** Visible labels are optional; the interactive anchor keeps its accessible name. */
2
+ export declare function visibleLabel(props: Record<string, unknown>, interactive: boolean): string | null;
package/dist/label.js ADDED
@@ -0,0 +1,5 @@
1
+ /** Visible labels are optional; the interactive anchor keeps its accessible name. */
2
+ export function visibleLabel(props, interactive) {
3
+ const text = typeof props.label === 'string' ? props.label : '';
4
+ return text && props.showLabel !== false && (interactive || props.showLabel === true) ? text : null;
5
+ }
@@ -0,0 +1,35 @@
1
+ import { estimate, type ModelRequest } from './request.js';
2
+ export { estimate };
3
+ export declare const modelPath: (root: string, request: ModelRequest) => string;
4
+ export declare function validateGLB(bytes: Uint8Array): void;
5
+ export type GenerateOptions = {
6
+ projectDir: string;
7
+ key?: string;
8
+ allowSpend?: boolean;
9
+ maxBytes?: number;
10
+ timeoutMs?: number;
11
+ fetch?: typeof fetch;
12
+ sleep?: (ms: number) => Promise<void>;
13
+ };
14
+ export declare function generate(input: ModelRequest, opts: GenerateOptions): Promise<Uint8Array>;
15
+ declare const _default: {
16
+ compilers: {
17
+ glb: {
18
+ version: string;
19
+ mime: string;
20
+ persistent: true;
21
+ estimate: (input: string) => {
22
+ credits: number;
23
+ };
24
+ compile: (input: string, ctx: {
25
+ directory: string;
26
+ projectDir?: string;
27
+ keys: Readonly<Record<string, string>>;
28
+ cacheDir: string;
29
+ allowSpend?: boolean;
30
+ maxBytes: number;
31
+ }) => Promise<Uint8Array<ArrayBufferLike>>;
32
+ };
33
+ };
34
+ };
35
+ export default _default;
package/dist/local.js ADDED
@@ -0,0 +1,199 @@
1
+ /** Node-only; never exported by the runtime. Committed output is the first and offline fast path. */
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import crypto from 'node:crypto';
5
+ import { normalize, estimate } from "./request.js";
6
+ export { estimate };
7
+ const BASE = 'https://openapi.tripo3d.ai/v3';
8
+ function fail(code, message) { throw Object.assign(new Error(message), { code: `LOCAL_RESOURCE_${code}` }); }
9
+ const sha = (value) => crypto.createHash('sha256').update(value).digest('hex');
10
+ export const modelPath = (root, request) => path.join(root, 'assets', 'models', `${sha(JSON.stringify(normalize(request)))}.glb`);
11
+ export function validateGLB(bytes) {
12
+ const b = Buffer.from(bytes);
13
+ if (b.length < 24 || b.toString('ascii', 0, 4) !== 'glTF' || b.readUInt32LE(4) !== 2 || b.readUInt32LE(8) !== b.length)
14
+ fail('GLB_INVALID', 'Invalid GLB v2 header or length; replace the damaged model.');
15
+ try {
16
+ if (b.readUInt32LE(16) !== 0x4e4f534a || b.readUInt32LE(12) > b.length - 20)
17
+ throw new Error();
18
+ const json = JSON.parse(b.toString('utf8', 20, 20 + b.readUInt32LE(12)));
19
+ // Self-contained GLB only: external textures/buffers break offline and can leak viewer requests.
20
+ if ([...(json.buffers ?? []), ...(json.images ?? [])].some((v) => v.uri && !v.uri.startsWith('data:')))
21
+ throw new Error();
22
+ }
23
+ catch {
24
+ fail('GLB_INVALID', 'Invalid or externally referenced GLB; export a self-contained binary GLB.');
25
+ }
26
+ }
27
+ function write(file, value) { const temp = `${file}.${crypto.randomUUID()}.tmp`; fs.writeFileSync(temp, JSON.stringify(value, null, 2) + '\n'); fs.renameSync(temp, file); }
28
+ function apiError(code) {
29
+ const errors = { 2: ['AUTH', 'Invalid Tripo key; update it in Manage keys.'], 1002: ['AUTH', 'Invalid Tripo key; update it in Manage keys.'], 2010: ['BALANCE', 'Insufficient Tripo credits. No automatic purchase or retry.'], 2008: ['MODERATION', 'Tripo rejected the content. Revise the description or reference image.'], 1004: ['INPUT', 'Tripo rejected the parameters. Check face_limit and texture options.'], 2015: ['VERSION', 'Tripo model version retired. Update the plugin.'] };
30
+ const e = errors[code] ?? ['API', `Tripo request failed (code ${Number.isFinite(code) ? code : 'unknown'}). Check the account/task before retrying.`];
31
+ fail(`TRIPO_${e[0]}`, e[1]);
32
+ }
33
+ export async function generate(input, opts) {
34
+ const r = normalize(input), file = modelPath(opts.projectDir, r), max = opts.maxBytes ?? 50 * 1024 * 1024;
35
+ const existing = () => { if (!fs.existsSync(file))
36
+ return; if (fs.statSync(file).size > max)
37
+ fail('TOO_LARGE', 'Model exceeds the resource size limit.'); const b = fs.readFileSync(file); validateGLB(b); return b; };
38
+ const hit = existing();
39
+ if (hit)
40
+ return hit;
41
+ if (!opts.allowSpend)
42
+ fail('SPEND_REQUIRED', `Model missing. Estimated ${estimate(r)} credits. Run joplo resources --allow-spend (or confirm interactively) to generate it; check/build/render never generate.`);
43
+ const key = opts.key;
44
+ if (!key)
45
+ fail('TRIPO_NO_KEY', 'Set TRIPO_API_KEY or save a key in the board → Voice → Manage keys.');
46
+ fs.mkdirSync(path.dirname(file), { recursive: true });
47
+ const lock = `${file}.lock`;
48
+ try {
49
+ fs.writeFileSync(lock, String(process.pid), { flag: 'wx' });
50
+ }
51
+ catch {
52
+ let alive = true;
53
+ try {
54
+ process.kill(Number(fs.readFileSync(lock, 'utf8')), 0);
55
+ }
56
+ catch (e) {
57
+ if (e.code === 'ESRCH')
58
+ alive = false;
59
+ }
60
+ if (alive)
61
+ fail('TRIPO_BUSY', 'This model is already being generated. Wait for that process to finish.');
62
+ fs.rmSync(lock);
63
+ return generate(r, opts);
64
+ }
65
+ try {
66
+ const hit = existing();
67
+ if (hit)
68
+ return hit;
69
+ const journal = file.replace(/\.glb$/, '.json');
70
+ let saved = {};
71
+ if (fs.existsSync(journal)) {
72
+ try {
73
+ saved = JSON.parse(fs.readFileSync(journal, 'utf8'));
74
+ }
75
+ catch {
76
+ fail('TRIPO_UNKNOWN', 'Unreadable task journal; recover task_id from Tripo before retrying.');
77
+ }
78
+ }
79
+ if (saved.status === 'creating' || saved.status === 'unknown')
80
+ fail('TRIPO_UNKNOWN', 'Creation outcome unknown. Recover task_id from Tripo task history and set journal status to queued; do not delete the journal or blindly retry.');
81
+ if (saved.status === 'failed' || saved.status === 'cancelled')
82
+ fail('TRIPO_FAILED', 'Task failed/cancelled; Tripo refunds frozen credits. Verify in your account; revise input for a new confirmed task.');
83
+ const deadline = Date.now() + (opts.timeoutMs ?? 20 * 60 * 1000), net = opts.fetch ?? fetch, sleep = opts.sleep ?? (ms => new Promise(resolve => setTimeout(resolve, ms)));
84
+ const check = () => { if (Date.now() >= deadline)
85
+ fail('TRIPO_TIMEOUT', 'Tripo timed out; the recorded task can be resumed with joplo resources.'); };
86
+ const api = async (endpoint, body, form) => {
87
+ for (let attempt = 0; attempt < 5; attempt++) {
88
+ check();
89
+ let response;
90
+ try {
91
+ response = await net(`${BASE}${endpoint}`, { method: body !== undefined || form ? 'POST' : 'GET', headers: { Authorization: `Bearer ${key}`, ...(!form && body !== undefined ? { 'Content-Type': 'application/json' } : {}) }, ...(body !== undefined ? { body: JSON.stringify(body) } : form ? { body: form } : {}), signal: AbortSignal.timeout(Math.max(1, Math.min(30000, deadline - Date.now()))), redirect: 'error' });
92
+ }
93
+ catch {
94
+ fail('TRIPO_NETWORK', 'Tripo connection interrupted. Resume the recorded task; creation outcome may be unknown.');
95
+ }
96
+ if (response.status === 429) {
97
+ const retry = Number(response.headers.get('Retry-After'));
98
+ await sleep(Math.min(30000, Math.max(1000, Number.isFinite(retry) ? retry * 1000 : 1000 * 2 ** attempt)));
99
+ continue;
100
+ }
101
+ let envelope;
102
+ try {
103
+ envelope = await response.json();
104
+ }
105
+ catch {
106
+ fail('TRIPO_UNKNOWN', 'Invalid Tripo response; creation outcome may be unknown. Check task history.');
107
+ }
108
+ if (!response.ok || envelope.code !== 0)
109
+ apiError(envelope.code ?? (response.status === 401 ? 1002 : -1));
110
+ return envelope.data;
111
+ }
112
+ fail('TRIPO_RATE_LIMIT', 'Tripo rate limit persists; wait and resume. No duplicate creation was sent after an unknown result.');
113
+ };
114
+ const { image, ...parameters } = r;
115
+ const metadata = { ...parameters, ...(image ? { image_sha256: sha(image) } : {}) };
116
+ const persist = () => write(journal, { ...metadata, ...saved });
117
+ if (!saved.task_id) {
118
+ let token;
119
+ if (image) {
120
+ const [header, data] = image.split(',');
121
+ const bytes = Buffer.from(data, 'base64');
122
+ if (bytes.length > 20 * 1024 * 1024)
123
+ fail('TRIPO_INPUT', 'Reference image exceeds 20 MB.');
124
+ const form = new FormData();
125
+ form.append('file', new Blob([bytes], { type: header.includes('png') ? 'image/png' : 'image/jpeg' }), 'reference.' + (header.includes('png') ? 'png' : 'jpg'));
126
+ token = (await api('/files', undefined, form))?.file_token;
127
+ if (typeof token !== 'string' || !token)
128
+ fail('TRIPO_API', 'Upload returned no file token.');
129
+ }
130
+ saved = { status: 'creating', created_at: new Date().toISOString() };
131
+ persist();
132
+ try {
133
+ const { prompt, ...imageParameters } = parameters;
134
+ const result = await api(`/generation/${image ? 'image' : 'text'}-to-model`, image ? { ...imageParameters, input: token } : parameters);
135
+ if (typeof result?.task_id !== 'string' || !/^[\w-]+$/.test(result.task_id))
136
+ fail('TRIPO_UNKNOWN', 'Creation outcome unknown: missing task_id; inspect task history.');
137
+ saved = { ...saved, task_id: result.task_id, status: 'queued' };
138
+ persist();
139
+ }
140
+ catch (e) {
141
+ const code = e.code;
142
+ // An explicit rejection did not create a task; transport/invalid responses remain ambiguous.
143
+ if (['LOCAL_RESOURCE_TRIPO_AUTH', 'LOCAL_RESOURCE_TRIPO_BALANCE', 'LOCAL_RESOURCE_TRIPO_MODERATION', 'LOCAL_RESOURCE_TRIPO_VERSION', 'LOCAL_RESOURCE_TRIPO_RATE_LIMIT', 'LOCAL_RESOURCE_TRIPO_INPUT'].includes(code ?? '')) {
144
+ fs.rmSync(journal);
145
+ throw e;
146
+ }
147
+ saved.status = 'unknown';
148
+ persist();
149
+ fail('TRIPO_UNKNOWN', 'Creation outcome unknown. Recover task_id from Tripo history before retrying; no automatic duplicate POST.');
150
+ }
151
+ }
152
+ while (true) {
153
+ check();
154
+ const task = await api(`/tasks/${encodeURIComponent(saved.task_id)}`);
155
+ if (task.status === 'failed' || task.status === 'cancelled') {
156
+ saved.status = task.status;
157
+ persist();
158
+ if (task.error_code)
159
+ apiError(task.error_code);
160
+ fail('TRIPO_FAILED', 'Tripo task failed/cancelled; frozen credits are refunded by Tripo. Check the account before starting another task.');
161
+ }
162
+ if (task.status === 'success') {
163
+ const url = task.output?.model_url;
164
+ if (typeof url !== 'string' || !url.startsWith('https://'))
165
+ fail('TRIPO_DOWNLOAD', 'Tripo returned no HTTPS GLB URL. Resume to refresh the URL.');
166
+ saved = { ...saved, status: 'success', generated_at: saved.generated_at ?? new Date().toISOString(), credits_consumed: typeof task.credits_consumed === 'number' ? task.credits_consumed : null };
167
+ persist();
168
+ let response;
169
+ try {
170
+ response = await net(url, { signal: AbortSignal.timeout(Math.max(1, Math.min(60000, deadline - Date.now()))), redirect: 'error' });
171
+ }
172
+ catch {
173
+ fail('TRIPO_DOWNLOAD', 'Model download interrupted; resume the task to obtain a fresh URL.');
174
+ }
175
+ if (!response.ok)
176
+ fail('TRIPO_DOWNLOAD', 'Model download failed; resume the task to refresh the signed URL.');
177
+ const chunks = [];
178
+ let length = 0;
179
+ for await (const chunk of response.body ?? []) {
180
+ length += chunk.length;
181
+ if (length > max)
182
+ fail('TOO_LARGE', 'Generated model exceeds the size limit; reduce face_limit or texture quality.');
183
+ chunks.push(chunk);
184
+ }
185
+ const bytes = Buffer.concat(chunks);
186
+ validateGLB(bytes);
187
+ const temp = `${file}.${crypto.randomUUID()}.tmp`;
188
+ fs.writeFileSync(temp, bytes);
189
+ fs.renameSync(temp, file);
190
+ return bytes;
191
+ }
192
+ await sleep(1500);
193
+ }
194
+ }
195
+ finally {
196
+ fs.rmSync(lock, { force: true });
197
+ }
198
+ }
199
+ export default { compilers: { glb: { version: 'tripo-v3-1', mime: 'model/gltf-binary', persistent: true, estimate: (input) => ({ credits: estimate(normalize(JSON.parse(input))) }), compile: (input, ctx) => generate(normalize(JSON.parse(input)), { projectDir: ctx.projectDir, allowSpend: ctx.allowSpend, maxBytes: ctx.maxBytes, key: ctx.keys.tripo }) } } };
@@ -0,0 +1,5 @@
1
+ import * as THREE from 'three';
2
+ export declare function modelStructureKey(props: Record<string, unknown>): string;
3
+ /** Parse self-contained GLB bytes; no external buffer/texture or decoder requests. */
4
+ export declare function loadModel(src: unknown): Promise<THREE.Group>;
5
+ export declare function disposeModel(model: THREE.Object3D): void;
package/dist/model.js ADDED
@@ -0,0 +1,48 @@
1
+ import * as THREE from 'three';
2
+ import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
3
+ import { MeshoptDecoder } from 'three/addons/libs/meshopt_decoder.module.js';
4
+ import { embeddedAsset } from '@joplo-app/kit/plugin';
5
+ export function modelStructureKey(props) {
6
+ return JSON.stringify([props.at, props.size, props.rotate, props.outline]);
7
+ }
8
+ /** Parse self-contained GLB bytes; no external buffer/texture or decoder requests. */
9
+ export async function loadModel(src) {
10
+ const url = embeddedAsset(src, 'model');
11
+ if (!url)
12
+ throw new Error('Use asset(GLB) or a compiled local model resource');
13
+ const response = await fetch(url, { signal: AbortSignal.timeout(30000) });
14
+ if (!response.ok)
15
+ throw new Error('Model unavailable');
16
+ const bytes = await response.arrayBuffer(), view = new DataView(bytes);
17
+ if (bytes.byteLength < 24 || view.getUint32(0, true) !== 0x46546c67 || view.getUint32(4, true) !== 2 || view.getUint32(8, true) !== bytes.byteLength || view.getUint32(16, true) !== 0x4e4f534a)
18
+ throw new Error('Invalid GLB');
19
+ const json = JSON.parse(new TextDecoder().decode(new Uint8Array(bytes, 20, view.getUint32(12, true))));
20
+ if ([...(json.buffers ?? []), ...(json.images ?? [])].some((v) => v.uri && !v.uri.startsWith('data:')))
21
+ throw new Error('GLB must embed textures and buffers');
22
+ const loader = new GLTFLoader().setMeshoptDecoder(MeshoptDecoder);
23
+ const model = await loader.parseAsync(bytes, '');
24
+ return model.scene;
25
+ }
26
+ export function disposeModel(model) {
27
+ const textures = new Set(), materials = new Set(), geometries = new Set();
28
+ model.traverse(o => {
29
+ if (!(o instanceof THREE.Mesh) && !(o instanceof THREE.LineSegments))
30
+ return;
31
+ geometries.add(o.geometry);
32
+ for (const m of Array.isArray(o.material) ? o.material : [o.material]) {
33
+ materials.add(m);
34
+ for (const v of Object.values(m))
35
+ if (v instanceof THREE.Texture)
36
+ textures.add(v);
37
+ }
38
+ });
39
+ for (const t of textures) {
40
+ t.dispose();
41
+ if (typeof ImageBitmap !== 'undefined' && t.image instanceof ImageBitmap)
42
+ t.image.close();
43
+ }
44
+ for (const m of materials)
45
+ m.dispose();
46
+ for (const g of geometries)
47
+ g.dispose();
48
+ }