diff --git a/external_plugins/product-3d-showcase/.zcode-plugin/plugin.json b/external_plugins/product-3d-showcase/.zcode-plugin/plugin.json new file mode 100644 index 00000000..d68ba771 --- /dev/null +++ b/external_plugins/product-3d-showcase/.zcode-plugin/plugin.json @@ -0,0 +1,68 @@ +{ + "name": "product-3d-showcase", + "version": "0.1.0", + "description": "Turn a glTF/GLB product model into a consistent set of marketing assets: multi-angle product images on white or transparent backgrounds with studio lighting and a soft ground shadow, a frame-exact 360° turntable video (WebM, plus MP4 with ffmpeg) and a self-contained web 3D viewer that works offline. Renders locally with three.js; no API keys.", + "description_i18n": { + "en": "Turn a glTF/GLB product model into a consistent set of marketing assets: multi-angle product images on white or transparent backgrounds with studio lighting and a soft ground shadow, a frame-exact 360° turntable video (WebM, plus MP4 with ffmpeg) and a self-contained web 3D viewer that works offline. Renders locally with three.js; no API keys.", + "zh-CN": "把 glTF/GLB 产品模型做成一整套统一风格的展示素材:白底或透明底的多角度产品图(影棚灯光、柔和地面阴影)、逐帧精确的 360° 旋转视频(WebM,装了 ffmpeg 再出 MP4),以及可离线打开的网页 3D 展示。用 three.js 在本地渲染,无需 API 密钥。" + }, + "author": { + "name": "Penova", + "url": "https://github.com/ppppp2005-p" + }, + "license": "MIT", + "keywords": [ + "3d", + "product", + "gltf", + "glb", + "three.js", + "turntable", + "360", + "product photo", + "viewer", + "产品图", + "3D 展示", + "白底图", + "360 度" + ], + "skills": "skills", + "mcpServers": { + "product-3d-showcase": { + "type": "stdio", + "command": "node", + "args": [ + "${ZCODE_PLUGIN_ROOT}/dist/server.mjs" + ], + "cwd": "${ZCODE_PROJECT_DIR}", + "timeoutMs": 900000, + "env": { + "ZCODE_WORKSPACE_ROOT": "${ZCODE_PROJECT_DIR}", + "FFMPEG_PATH": "${user_config.ffmpegPath}" + } + } + }, + "ui": { + "surfaces": [ + { + "id": "editor", + "title": { + "zh-CN": "产品 3D 展示", + "en-US": "Product 3D Showcase" + }, + "icon": "box", + "server": "product-3d-showcase", + "resourceUri": "ui://product-3d-showcase/panel.html", + "availability": "session" + } + ] + }, + "userConfig": { + "ffmpegPath": { + "type": "string", + "default": "", + "title": "ffmpeg 路径(可选)", + "description": "可选。只有把 360° 视频另存为 MP4 时需要 ffmpeg。默认在 PATH 和 /opt/homebrew/bin、/usr/local/bin 中查找。" + } + } +} diff --git a/external_plugins/product-3d-showcase/LICENSE b/external_plugins/product-3d-showcase/LICENSE new file mode 100644 index 00000000..67e98093 --- /dev/null +++ b/external_plugins/product-3d-showcase/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Penova + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/external_plugins/product-3d-showcase/README.md b/external_plugins/product-3d-showcase/README.md new file mode 100644 index 00000000..4875e4d4 --- /dev/null +++ b/external_plugins/product-3d-showcase/README.md @@ -0,0 +1,58 @@ +# Product 3D Showcase + +Turn a glTF/GLB product model into a consistent set of marketing assets: multi-angle product images, a 360° turntable video and a web 3D viewer. + +## Features + +- **Studio scene**: three.js with a neutral room environment, key/fill/rim lights (presets: studio, soft, dramatic), ACES tone mapping and exposure control. + - The model is centred, placed on the floor and auto-framed so it fills the shot the same way for every angle. + - An optional soft ground shadow is rendered on an invisible floor, so it also works on transparent backgrounds. +- **Angles**: presets (front, three-quarter left/right, side, back, top) or your own. Drag the live preview to a view and press **+ Add this view**. Each angle has a name, yaw, pitch and zoom. +- **Product images**: one PNG per angle, square, 256–4096 px, on white, transparent or any colour. +- **360° turntable video**: + - Rendered frame by frame and encoded with WebCodecs (VP9/VP8) into WebM, so it is smooth and frame-exact even on slow machines. Length and size are configurable; 30 fps. + - With ffmpeg installed, an H.264 MP4 (yuv420p, faststart) is also written for shops and social media. +- **Web 3D viewer**: `viewer/index.html` + `viewer.js` + `model.js`. It opens from disk (file://) with no server and no network, with drag-to-rotate, zoom, auto-rotate and the same lighting. You can put it on any static host. +- **Models**: `.glb`, or `.gltf` with external `.bin` and textures, which are inlined automatically. + +## Usage + +Ask the agent in ZCode Desktop: + +- "Make white-background product shots of bottle.glb: front, 45° left and right, side and back" +- "Add a 6-second 360° video and a web 3D viewer, with transparent PNGs" +- "Use softer lighting and add a low hero angle" + +## Tools + +| Tool | Purpose | +|---|---| +| `showcase_open` | Open a model with optional settings; shows what is inside (meshes, materials, textures, size) | +| `showcase_save` | Save angles, lighting, background, shadow, exposure, sizes, video and viewer options | +| `showcase_export` | Render and save all outputs in the open panel | + +Output goes to `showcase//`: `.png`, `turntable.webm` (+ `.mp4`), `viewer/` and `showcase.json` (the settings, reused next time). + +## Scope (v0.1) + +- glTF 2.0 only. Convert OBJ/FBX/USDZ first, for example with Blender (File → Export → glTF 2.0). +- Draco/meshopt-compressed and KTX2-textured models are not supported yet. +- Rendering needs WebGL in the panel. The video background is never transparent; with a transparent background, the video uses white. +- No AI image generation or background scenes. + +## Privacy, network and files + +- **Everything runs locally.** No network, no uploads, no API keys or accounts. +- Reads only the model you choose and the files it refers to. Writes only to the output folder in the workspace. +- ffmpeg (optional) is called with argument arrays, without a shell. No hooks. + +## Build and test (developers) + +- Source: `ui-plugins/product-3d-showcase/`. +- Build: `pnpm install --frozen-lockfile && pnpm build`, then add `dist/local-marketplace` as a local source. +- Tests: `pnpm --filter @penova/plugin-product-3d-showcase test` and `test:e2e`. +- `E2E_MODELS` points to a folder with `WaterBottle.glb` and `avocado/` from the Khronos glTF-Sample-Assets (CC0). + +## Third-party components and licenses + +MIT licensed (author: Penova). Bundled: three.js (MIT), MCP SDK and ext-apps (MIT), zod (MIT); the full list is in `dist/THIRD_PARTY_NOTICES.txt`. ffmpeg is not bundled. diff --git a/external_plugins/product-3d-showcase/README_CN.md b/external_plugins/product-3d-showcase/README_CN.md new file mode 100644 index 00000000..b34d9e02 --- /dev/null +++ b/external_plugins/product-3d-showcase/README_CN.md @@ -0,0 +1,77 @@ +# 产品 3D 展示 + +把 glTF/GLB 产品模型做成一整套统一风格的展示素材:多角度产品图、360° 旋转视频和网页 3D 展示。 + +## 功能 + +- **影棚场景**:three.js 渲染,中性室内环境光,加主光、补光、轮廓光。 + - 灯光预设:影棚、柔光、戏剧。 + - ACES 色调映射,曝光可调。 + - 模型自动居中、落地、取景,每个角度占画面的比例一致。 + - 可选柔和地面阴影,画在看不见的地面上,透明底也能用。 +- **角度**: + - 预设:正面、左右 45°、侧面、背面、俯视。也可以自定义。 + - 在实时预览里拖到想要的视角,点“+ 加入这个角度”。 + - 每个角度有名字、水平角、俯仰角和缩放。 +- **产品图**:每个角度一张方形 PNG,256–4096 px,白底、透明底或任意颜色。 +- **360° 旋转视频**: + - 逐帧渲染,用 WebCodecs(VP9/VP8)编码成 WebM。机器慢也不会掉帧,帧数精确。 + - 时长和尺寸可调,30 fps。 + - 装了 ffmpeg 会再出一份 H.264 MP4(yuv420p、faststart),方便传电商平台和社交媒体。 +- **网页 3D 展示**: + - 由 `viewer/index.html`、`viewer.js` 和 `model.js` 组成。 + - 直接双击就能打开(file://),不需要服务器和网络。 + - 可拖动旋转、缩放、自动旋转,灯光与产品图一致。 + - 也可以放到任何静态托管上。 +- **模型**:`.glb`;也支持带外部 `.bin` 和贴图的 `.gltf`,会自动内联。 + +## 使用 + +在 ZCode Desktop 里对 Agent 说: + +- “用 bottle.glb 做一套白底产品图:正面、左右 45°、侧面、背面” +- “再出一段 6 秒的 360° 旋转视频和网页 3D 展示,图片要透明底” +- “灯光柔和一点,再加一个低机位的主图角度” + +## 工具 + +| 工具 | 作用 | +|---|---| +| `showcase_open` | 打开模型,可同时传设置。会报告模型里有什么:网格、材质、贴图、大小 | +| `showcase_save` | 保存设置:角度、灯光、背景、阴影、曝光、尺寸、视频和网页展示选项 | +| `showcase_export` | 在打开的面板里渲染并保存全部输出 | + +输出在 `showcase/<模型名>/`: + +- `<角度>.png` +- `turntable.webm`,以及 `.mp4` +- `viewer/` +- `showcase.json`:设置,下次打开时沿用 + +## 范围(v0.1) + +- 只支持 glTF 2.0。OBJ/FBX/USDZ 请先转换,例如用 Blender:文件 → 导出 → glTF 2.0。 +- 暂不支持 Draco/meshopt 压缩和 KTX2 贴图的模型。 +- 渲染需要面板里的 WebGL。 +- 视频背景不支持透明;透明底时视频用白底。 +- 不含 AI 生图或背景场景生成。 + +## 隐私、网络与文件 + +- **全部在本地运行。** 不联网、不上传,不需要 API 密钥或账号。 +- 只读取你选择的模型及其引用的文件;只写入工作区里的输出文件夹。 +- ffmpeg(可选)以参数数组调用,不经过 shell。没有 hooks。 + +## 构建与测试(开发者) + +- 源码:`ui-plugins/product-3d-showcase/`。 +- 构建:`pnpm install --frozen-lockfile && pnpm build`,再把 `dist/local-marketplace` 添加为本地来源。 +- 测试:`pnpm --filter @penova/plugin-product-3d-showcase test` 和 `test:e2e`。 +- `E2E_MODELS` 指向含 `WaterBottle.glb` 与 `avocado/` 的文件夹。这两个模型来自 Khronos glTF-Sample-Assets,CC0 授权。 + +## 第三方组件与许可证 + +本插件以 MIT 许可证发布,作者 Penova。 + +- 打包进插件的组件:three.js(MIT)、MCP SDK 与 ext-apps(MIT)、zod(MIT)。完整清单见 `dist/THIRD_PARTY_NOTICES.txt`。 +- 不打包 ffmpeg。 diff --git a/external_plugins/product-3d-showcase/skills/product-3d-showcase/SKILL.md b/external_plugins/product-3d-showcase/skills/product-3d-showcase/SKILL.md new file mode 100644 index 00000000..7b8dd96b --- /dev/null +++ b/external_plugins/product-3d-showcase/skills/product-3d-showcase/SKILL.md @@ -0,0 +1,25 @@ +--- +name: product-3d-showcase +description: 把 glTF/GLB 产品模型做成多角度产品图(白底/透明底)、360° 旋转视频(WebM/MP4)和可离线打开的网页 3D 展示。用户提到“产品 3D 展示 / 产品图 / 白底图 / 360 度视频 / 3D 模型展示 / glb”时使用。 +--- + +# 产品 3D 展示 + +1. 打开:`showcase_open(model: "xx.glb" 或 "xx.gltf", settings?)`。 + - 结果会说明模型的网格、材质、贴图数量和大小。 + - OBJ/FBX/USDZ 不支持:请用户先用 Blender 导出 glTF 2.0。 +2. 按用户的要求设置,然后调用 `showcase_save(settings)`。settings 必须带 `model`。 + - 角度 `angles`: + - 预设名:front、three-quarter-left、three-quarter-right、side、back、top。 + - 也可以写 `{name, yaw, pitch, zoom}`。yaw 0 是正面,正数向右转;pitch 是俯视角度,低机位用 0–5。 + - 背景 `background`:`"#ffffff"`、`"transparent"` 或其他颜色。 + - 其他选项: + - `lighting`:"studio"、"soft" 或 "dramatic"。 + - `shadow`、`exposure`。 + - `size`:图片像素。 + - `video: {enabled, seconds, size}`、`viewer`、`output`。 + - 告诉用户也可以在面板里拖动预览选角度。 +3. 导出:`showcase_export(settings)`。 + - 渲染在面板里完成,面板要保持打开。 + - 完成后面板会把文件清单发回上下文。 + - 告诉用户输出文件夹里有什么:PNG、`turntable.webm`(装了 ffmpeg 还有 `.mp4`)和 `viewer/index.html`。网页展示可以直接双击打开,或放到任何静态托管上。 diff --git a/marketplace.json b/marketplace.json index 32e8c8ef..ec3f2779 100644 --- a/marketplace.json +++ b/marketplace.json @@ -1673,6 +1673,57 @@ "把上一个 Hi3D 任务生成的模型按角色拆分成部件" ] } + }, + { + "name": "product-3d-showcase", + "componentTypes": [ + "ui" + ], + "source": "./external_plugins/product-3d-showcase", + "displayName": "Product 3D Showcase", + "displayName_i18n": { + "en": "Product 3D Showcase", + "zh-CN": "产品 3D 展示" + }, + "description": "Turn a glTF/GLB product model into a consistent set of marketing assets: multi-angle product images on white or transparent backgrounds with studio lighting and a soft ground shadow, a frame-exact 360° turntable video (WebM, plus MP4 with ffmpeg) and a self-contained web 3D viewer that works offline. Renders locally with three.js; no API keys.", + "description_i18n": { + "en": "Turn a glTF/GLB product model into a consistent set of marketing assets: multi-angle product images on white or transparent backgrounds with studio lighting and a soft ground shadow, a frame-exact 360° turntable video (WebM, plus MP4 with ffmpeg) and a self-contained web 3D viewer that works offline. Renders locally with three.js; no API keys.", + "zh-CN": "把 glTF/GLB 产品模型做成一整套统一风格的展示素材:白底或透明底的多角度产品图(影棚灯光、柔和地面阴影)、逐帧精确的 360° 旋转视频(WebM,装了 ffmpeg 再出 MP4),以及可离线打开的网页 3D 展示。用 three.js 在本地渲染,无需 API 密钥。" + }, + "version": "0.1.0", + "author": { + "name": "Penova", + "url": "https://github.com/ppppp2005-p" + }, + "license": "MIT", + "category": "productivity", + "keywords": [ + "3d", + "product", + "gltf", + "glb", + "three.js", + "turntable", + "360", + "product photo", + "viewer", + "产品图", + "3D 展示", + "白底图", + "360 度" + ], + "examplePrompts": [ + "Make white-background product shots of bottle.glb: front, 45° left and right, side and back", + "Add a 6-second 360° video and a web 3D viewer, with transparent PNGs", + "Use softer lighting and add a low hero angle" + ], + "examplePrompts_i18n": { + "zh-CN": [ + "用 bottle.glb 做一套白底产品图:正面、左右 45°、侧面、背面", + "再出一段 6 秒的 360° 旋转视频和网页 3D 展示,图片要透明底", + "灯光柔和一点,再加一个低机位的主图角度" + ] + } } ] } \ No newline at end of file diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 14b35f76..4ae142cf 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -224,6 +224,43 @@ importers: ui-plugins/photocraft: {} + ui-plugins/product-3d-showcase: + dependencies: + '@modelcontextprotocol/sdk': + specifier: 1.29.0 + version: 1.29.0(zod@4.6.5) + three: + specifier: 0.181.2 + version: 0.181.2 + zod: + specifier: ^4.6.5 + version: 4.6.5 + devDependencies: + '@modelcontextprotocol/core': + specifier: 2.0.0 + version: 2.0.0 + '@modelcontextprotocol/ext-apps': + specifier: 2.0.0 + version: 2.0.0(@modelcontextprotocol/client@2.2.0)(@modelcontextprotocol/core@2.0.0)(@modelcontextprotocol/server@2.0.0)(react-dom@19.2.7(react@19.2.7))(react@19.2.7)(zod@4.6.5) + '@types/node': + specifier: 25.5.0 + version: 25.5.0 + '@types/three': + specifier: 0.181.0 + version: 0.181.0 + esbuild: + specifier: ^0.25.12 + version: 0.25.12 + playwright-core: + specifier: 1.59.1 + version: 1.59.1 + typescript: + specifier: 6.0.2 + version: 6.0.2 + vitest: + specifier: 4.1.4 + version: 4.1.4(@opentelemetry/api@1.9.1)(@types/node@25.5.0)(msw@2.13.3(@types/node@25.5.0)(typescript@6.0.2))(vite@8.3.1(@types/node@25.5.0)(esbuild@0.25.12)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.0)) + ui-plugins/soundcraft: {} ui-plugins/typst-workbench: @@ -414,6 +451,9 @@ packages: '@codemirror/view@6.43.13': resolution: {integrity: sha512-sihaFrUzAsYBQsL9J2t69y8nfMQGwcYmggAZsk+kjPbjYZMyuf2hU8tUNTZ+P+isb6XRr8JE22TZlJxBoVdH1A==} + '@dimforge/rapier3d-compat@0.12.0': + resolution: {integrity: sha512-uekIGetywIgopfD97oDL5PfeezkFpNhwlzlaEYNOA0N6ghdsOvh/HYjSMek5Q2O1PYvRSDFcqFVJl4r4ZBwOow==} + '@esbuild/aix-ppc64@0.25.12': resolution: {integrity: sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==} engines: {node: '>=18'} @@ -1770,6 +1810,9 @@ packages: '@tauri-apps/api@2.11.1': resolution: {integrity: sha512-M2FPuYND2m+wh5hfW9ZpSdxMPdEJovPBWwoHJmwUpysTYNHaOkVFN419m/K0LIgjb/7KU2vBgsUepJWugQCvAA==} + '@tweenjs/tween.js@23.1.3': + resolution: {integrity: sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA==} + '@types/chai@5.2.3': resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==} @@ -1895,15 +1938,24 @@ packages: '@types/react@19.2.14': resolution: {integrity: sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w==} + '@types/stats.js@0.17.4': + resolution: {integrity: sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA==} + '@types/statuses@2.0.6': resolution: {integrity: sha512-xMAgYwceFhRA2zY+XbEA7mxYbA093wdiW8Vu6gZPGWy9cmOyU9XesH1tNcEWsKFd5Vzrqx5T3D38PWx1FIIXkA==} + '@types/three@0.181.0': + resolution: {integrity: sha512-MLF1ks8yRM2k71D7RprFpDb9DOX0p22DbdPqT/uAkc6AtQXjxWCVDjCy23G9t1o8HcQPk7woD2NIyiaWcWPYmA==} + '@types/trusted-types@2.0.7': resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==} '@types/web-bluetooth@0.0.21': resolution: {integrity: sha512-oIQLCGWtcFZy2JW77j9k8nHzAOpqMHLQejDA48XXMWH6tjCQHz5RCFz1bzsmROyL6PUm+LLnUiI4BCn221inxA==} + '@types/webxr@0.5.24': + resolution: {integrity: sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg==} + '@upsetjs/venn.js@2.0.0': resolution: {integrity: sha512-WbBhLrooyePuQ1VZxrJjtLvTc4NVfpOyKx0sKqioq9bX1C1m7Jgykkn8gLrtwumBioXIqam8DLxp88Adbue6Hw==} @@ -2475,10 +2527,6 @@ packages: resolution: {integrity: sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==} engines: {node: '>= 0.6'} - eventsource-parser@3.1.0: - resolution: {integrity: sha512-kJezFj9YFAMLeORyi7aCLxLbD5/qWMQnoMVlVPyHIll7lgRJCc3JVln9Vgl9nwQi0YkMnhdGTMNn7CkRRAptMg==} - engines: {node: '>=18.0.0'} - eventsource-parser@3.1.1: resolution: {integrity: sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==} engines: {node: '>=18.0.0'} @@ -2714,9 +2762,6 @@ packages: jose@6.2.12: resolution: {integrity: sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw==} - jose@6.2.2: - resolution: {integrity: sha512-d7kPDd34KO/YnzaDOlikGpOurfF0ByC2sEV4cANCtdqLlTfBlw2p14O/5d/zv40gJPbIQxfES3nSx1/oYNyuZQ==} - jotai-scope@0.7.2: resolution: {integrity: sha512-Gwed97f3dDObrO43++2lRcgOqw4O2sdr4JCjP/7eHK1oPACDJ7xKHGScpJX9XaflU+KBHXF+VhwECnzcaQiShg==} peerDependencies: @@ -2898,6 +2943,9 @@ packages: mermaid@11.14.0: resolution: {integrity: sha512-GSGloRsBs+JINmmhl0JDwjpuezCsHB4WGI4NASHxL3fHo3o/BRXTxhDLKnln8/Q0lRFRyDdEjmk1/d5Sn1Xz8g==} + meshoptimizer@0.22.0: + resolution: {integrity: sha512-IebiK79sqIy+E4EgOr+CAw+Ke8hAspXKzBd0JdgEmPHiAwmvEj2S4h1rfvo+o/BnfEYd/jAOg5IeeIjzlzSnDg==} + mime-db@1.54.0: resolution: {integrity: sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==} engines: {node: '>= 0.6'} @@ -3068,10 +3116,6 @@ packages: resolution: {integrity: sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==} engines: {node: '>=8.6'} - picomatch@4.0.4: - resolution: {integrity: sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==} - engines: {node: '>=12'} - picomatch@4.0.7: resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} engines: {node: '>=12'} @@ -3380,21 +3424,16 @@ packages: thenify@3.3.1: resolution: {integrity: sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==} + three@0.181.2: + resolution: {integrity: sha512-k/CjiZ80bYss6Qs7/ex1TBlPD11whT9oKfT8oTGiHa34W4JRd1NiH/Tr1DbHWQ2/vMUypxksLnF2CfmlmM5XFQ==} + tinybench@2.9.0: resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} - tinyexec@1.1.1: - resolution: {integrity: sha512-VKS/ZaQhhkKFMANmAOhhXVoIfBXblQxGX1myCQ2faQrfmobMftXeJPcZGp0gS07ocvGJWDLZGyOZDadDBqYIJg==} - engines: {node: '>=18'} - tinyexec@1.3.1: resolution: {integrity: sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==} engines: {node: '>=18'} - tinyglobby@0.2.16: - resolution: {integrity: sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg==} - engines: {node: '>=12.0.0'} - tinyglobby@0.2.17: resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} engines: {node: '>=12.0.0'} @@ -3742,7 +3781,7 @@ snapshots: '@antfu/install-pkg@1.1.0': dependencies: package-manager-detector: 1.6.0 - tinyexec: 1.1.1 + tinyexec: 1.3.1 '@atlaskit/pragmatic-drag-and-drop-hitbox@1.2.0': dependencies: @@ -3896,6 +3935,8 @@ snapshots: style-mod: 4.1.4 w3c-keyname: 2.2.8 + '@dimforge/rapier3d-compat@0.12.0': {} + '@esbuild/aix-ppc64@0.25.12': optional: true @@ -4285,11 +4326,11 @@ snapshots: cors: 2.8.6 cross-spawn: 7.0.6 eventsource: 3.0.7 - eventsource-parser: 3.1.0 + eventsource-parser: 3.1.1 express: 5.2.1 express-rate-limit: 8.3.2(express@5.2.1) hono: 4.12.12 - jose: 6.2.2 + jose: 6.2.12 json-schema-typed: 8.0.2 pkce-challenge: 5.0.1 raw-body: 3.0.2 @@ -4980,6 +5021,8 @@ snapshots: '@tauri-apps/api@2.11.1': {} + '@tweenjs/tween.js@23.1.3': {} + '@types/chai@5.2.3': dependencies: '@types/deep-eql': 4.0.2 @@ -5129,14 +5172,28 @@ snapshots: dependencies: csstype: 3.2.3 + '@types/stats.js@0.17.4': {} + '@types/statuses@2.0.6': optional: true + '@types/three@0.181.0': + dependencies: + '@dimforge/rapier3d-compat': 0.12.0 + '@tweenjs/tween.js': 23.1.3 + '@types/stats.js': 0.17.4 + '@types/webxr': 0.5.24 + '@webgpu/types': 0.1.21 + fflate: 0.8.3 + meshoptimizer: 0.22.0 + '@types/trusted-types@2.0.7': optional: true '@types/web-bluetooth@0.0.21': {} + '@types/webxr@0.5.24': {} + '@upsetjs/venn.js@2.0.0': optionalDependencies: d3-selection: 3.0.0 @@ -5809,13 +5866,11 @@ snapshots: etag@1.8.1: {} - eventsource-parser@3.1.0: {} - eventsource-parser@3.1.1: {} eventsource@3.0.7: dependencies: - eventsource-parser: 3.1.0 + eventsource-parser: 3.1.1 expect-type@1.4.0: {} @@ -5869,10 +5924,6 @@ snapshots: fast-uri@3.1.0: {} - fdir@6.5.0(picomatch@4.0.4): - optionalDependencies: - picomatch: 4.0.4 - fdir@6.5.0(picomatch@4.0.7): optionalDependencies: picomatch: 4.0.7 @@ -6048,8 +6099,6 @@ snapshots: jose@6.2.12: {} - jose@6.2.2: {} - jotai-scope@0.7.2(jotai@2.11.0(@types/react@19.2.14)(react@19.2.7))(react@19.2.7): dependencies: jotai: 2.11.0(@types/react@19.2.14)(react@19.2.7) @@ -6218,6 +6267,8 @@ snapshots: ts-dedent: 2.2.0 uuid: 11.1.0 + meshoptimizer@0.22.0: {} + mime-db@1.54.0: {} mime-types@3.0.2: @@ -6406,8 +6457,6 @@ snapshots: picomatch@2.3.2: {} - picomatch@4.0.4: {} - picomatch@4.0.7: {} pirates@4.0.7: {} @@ -6745,7 +6794,7 @@ snapshots: lines-and-columns: 1.2.4 mz: 2.7.0 pirates: 4.0.7 - tinyglobby: 0.2.16 + tinyglobby: 0.2.17 ts-interface-checker: 0.1.13 svg-pathdata@6.0.3: @@ -6777,17 +6826,12 @@ snapshots: dependencies: any-promise: 1.3.0 - tinybench@2.9.0: {} + three@0.181.2: {} - tinyexec@1.1.1: {} + tinybench@2.9.0: {} tinyexec@1.3.1: {} - tinyglobby@0.2.16: - dependencies: - fdir: 6.5.0(picomatch@4.0.4) - picomatch: 4.0.4 - tinyglobby@0.2.17: dependencies: fdir: 6.5.0(picomatch@4.0.7) diff --git a/ui-plugins/product-3d-showcase/package.json b/ui-plugins/product-3d-showcase/package.json new file mode 100644 index 00000000..3053a274 --- /dev/null +++ b/ui-plugins/product-3d-showcase/package.json @@ -0,0 +1,34 @@ +{ + "name": "@penova/plugin-product-3d-showcase", + "version": "0.1.0", + "private": true, + "license": "MIT", + "type": "module", + "scripts": { + "build": "node scripts/build.mjs", + "typecheck": "tsc -p tsconfig.json --noEmit", + "test": "vitest run", + "test:e2e": "node --experimental-strip-types scripts/e2e.mts" + }, + "zcode": { + "title": "Product 3D Showcase" + }, + "engines": { + "node": ">=22.0.0" + }, + "dependencies": { + "@modelcontextprotocol/sdk": "1.29.0", + "zod": "^4.6.5", + "three": "0.181.2" + }, + "devDependencies": { + "@modelcontextprotocol/core": "2.0.0", + "@modelcontextprotocol/ext-apps": "2.0.0", + "@types/node": "25.5.0", + "esbuild": "^0.25.12", + "playwright-core": "1.59.1", + "typescript": "6.0.2", + "vitest": "4.1.4", + "@types/three": "0.181.0" + } +} diff --git a/ui-plugins/product-3d-showcase/scripts/build.mjs b/ui-plugins/product-3d-showcase/scripts/build.mjs new file mode 100644 index 00000000..b0a34d7d --- /dev/null +++ b/ui-plugins/product-3d-showcase/scripts/build.mjs @@ -0,0 +1,77 @@ +import { build } from "esbuild"; +import { copyFile, cp, mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import { createRequire } from "node:module"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { writeNotices } from "./licenses.mjs"; + +const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const dist = join(root, "dist"); +const pkg = JSON.parse(await readFile(join(root, "package.json"), "utf8")); +await rm(dist, { recursive: true, force: true }); +await mkdir(join(dist, "ui"), { recursive: true }); + +// 宿主只提供 HTML 本身,JS 与 CSS 全部内联到一个页面里。 +const ui = await build({ + metafile: true, + entryPoints: [join(root, "ui/main.ts")], + bundle: true, + format: "iife", + platform: "browser", + target: "es2022", + minify: true, + write: false, + outdir: join(dist, "ui"), + legalComments: "none", + loader: { ".css": "text" }, +}); +const js = ui.outputFiles.find((file) => file.path.endsWith(".js")).text; +const escape = (text) => text.replace(/<\/script/gi, "<\\/script"); +const html = `${pkg.zcode?.title ?? pkg.name}
`; +const htmlBytes = Buffer.byteLength(html); +if (htmlBytes > 4 * 1024 * 1024 - 64 * 1024) throw new Error(`panel.html is ${Math.round(htmlBytes / 1024)} KiB; keep it below 4 MiB`); +await writeFile(join(dist, "ui/panel.html"), html); + +// 导出的网页展示包使用的查看器脚本(经典脚本,file:// 下也能打开)。 +const viewer = await build({ metafile: true, entryPoints: [join(root, "ui/viewer.ts")], outfile: join(dist, "viewer.js"), bundle: true, format: "iife", platform: "browser", target: "es2020", minify: true, legalComments: "none" }); + +// 用不到、且许可证不明的可选依赖(package.json 的 zcode.stub)替换为空模块。 +const stubs = pkg.zcode?.stub ?? []; +const stubPlugin = { + name: "stub", + setup(b) { + if (!stubs.length) return; + const filter = new RegExp(`^(${stubs.map((s) => s.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&")).join("|")})$`); + b.onResolve({ filter }, (args) => ({ path: args.path, namespace: "stub" })); + b.onLoad({ filter: /.*/, namespace: "stub" }, () => ({ contents: "module.exports = {};", loader: "js" })); + }, +}; + +const server = await build({ + plugins: [stubPlugin], + metafile: true, + entryPoints: [join(root, "src/main.ts")], + outfile: join(dist, "server.mjs"), + bundle: true, + platform: "node", + format: "esm", + target: "node22", + legalComments: "none", + banner: { + js: 'import { createRequire as __createRequire } from "node:module"; const require=__createRequire(import.meta.url);', + }, +}); + +// 运行时需要的 wasm 等文件(package.json 的 zcode.assets:{ 包内路径: 输出文件名 })。 +const require = createRequire(join(root, "package.json")); +for (const [from, to] of Object.entries(pkg.zcode?.assets ?? {})) await copyFile(require.resolve(from), join(dist, to)); + +// 整个目录(package.json 的 zcode.dirs:{ "包名:子目录": 输出目录 }),例如 pdf.js 的 CMap。 +for (const [spec, to] of Object.entries(pkg.zcode?.dirs ?? {})) { + const [name, sub] = spec.split(":"); + const base = dirname(require.resolve(`${name}/package.json`)); + await cp(join(base, sub), join(dist, to), { recursive: true, filter: (path) => !/(_nowasm_fallback\.js|quickjs-eval\.(js|wasm))$/.test(path) }); +} + +await writeNotices([ui.metafile, viewer.metafile, server.metafile], join(dist, "THIRD_PARTY_NOTICES.txt"), Object.keys(pkg.zcode?.assets ?? {})); +process.stdout.write(`${pkg.name}: panel ${Math.round(htmlBytes / 1024)} KiB, server ${Math.round((await readFile(join(dist, "server.mjs"))).length / 1024)} KiB\n`); diff --git a/ui-plugins/product-3d-showcase/scripts/e2e.mts b/ui-plugins/product-3d-showcase/scripts/e2e.mts new file mode 100644 index 00000000..9d317419 --- /dev/null +++ b/ui-plugins/product-3d-showcase/scripts/e2e.mts @@ -0,0 +1,121 @@ +// 浏览器端到端测试:真实打包的 server + 官方 AppBridge 宿主 + 隔离 iframe 中的面板(WebGL)。需要 Chrome 与 ffprobe。 +// E2E_MODELS 指向含 WaterBottle.glb 与 avocado/ 的文件夹(Khronos glTF-Sample-Assets,CC0,见 SOURCES.txt)。 +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { cp, mkdir, mkdtemp, readFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { pathToFileURL } from "node:url"; +import { startHarness } from "./harness.mjs"; + +const shots = process.env.E2E_SHOTS ?? join(tmpdir(), "product-3d-showcase-shots"); +await mkdir(shots, { recursive: true }); +const workspace = await mkdtemp(join(tmpdir(), "p3d-e2e-")); +const models = process.env.E2E_MODELS ?? "/workspace/zcode-new-plugins/samples/models"; +await cp(join(models, "WaterBottle.glb"), join(workspace, "products/bottle.glb"), { recursive: true }); +await cp(join(models, "avocado"), join(workspace, "products/avocado"), { recursive: true }); + +/** PNG 尺寸与四角/中心像素的透明度(在浏览器里解码)。 */ +async function pngStats(page: any, file: string) { + const b64 = (await readFile(file)).toString("base64"); + return page.evaluate(async (data: string) => { + const img = new Image(); + img.src = `data:image/png;base64,${data}`; + await img.decode(); + const c = document.createElement("canvas"); + c.width = img.width; c.height = img.height; + const g = c.getContext("2d")!; + g.drawImage(img, 0, 0); + const px = (x: number, y: number) => Array.from(g.getImageData(x, y, 1, 1).data); + const d = g.getImageData(0, 0, c.width, c.height).data; + let opaque = 0; + for (let i = 3; i < d.length; i += 4) if (d[i] > 200) opaque++; + return { w: img.width, h: img.height, corner: px(2, 2), center: px(img.width >> 1, img.height >> 1), opaqueShare: opaque / (d.length / 4) }; + }, b64); +} + +const harness = await startHarness({ workspace }); +const step = (text: string) => process.stdout.write(`• ${text}\n`); +try { + const { outer, frame } = await harness.open("?locale=zh-CN", { width: 1300, height: 950 }); + step("agent opens the water bottle with transparent background"); + const r = await harness.agent(outer, "showcase_open", { model: "products/bottle.glb", settings: { title: "Water Bottle", angles: ["front", "three-quarter-left", "three-quarter-right", "back"], background: "transparent", size: 1200, video: { seconds: 3, size: 720 } } }); + assert.equal(r.structuredContent.info.textures, 4); + await frame.waitForFunction(() => document.querySelectorAll(".ang img").length === 4 && [...document.querySelectorAll(".ang img")].every((i) => i.src.startsWith("data:image/png")), undefined, { timeout: 120_000 }); + step("user drags the preview to a low hero angle and adds it"); + const box = (await frame.locator(".stage canvas").boundingBox())!; + const outerBox = (await outer.locator("iframe").boundingBox())!; + const ox = outerBox.x + box.x + box.width / 2, oy = outerBox.y + box.y + box.height / 2; + await outer.mouse.move(ox, oy); + await outer.mouse.down(); + await outer.mouse.move(ox - 120, oy - 40, { steps: 10 }); + await outer.mouse.up(); + await frame.waitForTimeout(600); + await frame.locator("button", { hasText: "加入这个角度" }).click(); + await frame.waitForFunction(() => document.querySelectorAll(".ang img").length === 5 && [...document.querySelectorAll(".ang img")].every((i) => i.src.startsWith("data:image/png")), undefined, { timeout: 60_000 }); + const hero = await frame.locator(".ang").nth(4).locator(".muted").textContent(); + assert.notEqual(hero, "0° / 8°"); + await outer.screenshot({ path: join(shots, "01-angles.png") }); + step("user switches to soft lighting and exports everything"); + await frame.locator(".settings select").first().selectOption("soft"); + await frame.waitForTimeout(800); + await frame.locator("button", { hasText: "导出全部" }).click(); + await frame.locator(".card.done").waitFor({ timeout: 300_000 }); + const out = join(workspace, "showcase/bottle"); + const saved = JSON.parse(await readFile(join(out, "showcase.json"), "utf8")); + assert.equal(saved.lighting, "soft"); + assert.equal(saved.angles.length, 5); + for (const a of saved.angles) { + const st = await pngStats(outer, join(out, `${a.name}.png`)); + assert.equal(st.w, 1200); + assert.equal(st.corner[3], 0, `${a.name}: corner should be transparent`); + assert.ok(st.center[3] > 200, `${a.name}: product should be in the centre ${st.center}`); + assert.ok(st.opaqueShare > 0.05 && st.opaqueShare < 0.7, `${a.name}: product fills ${st.opaqueShare}`); + } + const front = await pngStats(outer, join(out, "front.png")); + const back = await pngStats(outer, join(out, "back.png")); + assert.notDeepEqual(front.center, back.center); + const dur = Number(execFileSync("ffprobe", ["-v", "error", "-show_entries", "format=duration:stream=width,height,codec_name", "-of", "default=nw=1", join(out, "turntable.webm")]).toString().match(/duration=([\d.]+)/)?.[1] ?? 0); + const probe = execFileSync("ffprobe", ["-v", "error", "-count_frames", "-show_entries", "stream=width,height,nb_read_frames", "-of", "csv=p=0", join(out, "turntable.webm")]).toString().trim(); + step(`webm: ${probe}, ${dur || "?"}s`); + assert.match(probe, /^720,720,(\d+)/); + assert.equal(Number(probe.split(",")[2]), 90, "3 s × 30 fps, frame-exact"); + assert.ok(Math.abs(dur - 3) < 0.1); + const mp4 = execFileSync("ffprobe", ["-v", "error", "-count_frames", "-show_entries", "stream=codec_name,pix_fmt,nb_read_frames", "-of", "csv=p=0", join(out, "turntable.mp4")]).toString().trim(); + assert.equal(mp4, "h264,yuv420p,90"); + await outer.screenshot({ path: join(shots, "02-exported.png") }); + + step("the exported web viewer works from file:// for a .gltf with external textures"); + await harness.agent(outer, "showcase_open", { model: "products/avocado/Avocado.gltf", settings: { title: "Avocado", angles: ["front", "top"], video: { enabled: false }, background: "#f1f5f9" } }); + await frame.waitForFunction(() => document.querySelectorAll(".ang img").length === 2 && [...document.querySelectorAll(".ang img")].every((i) => i.src.startsWith("data:image/png")), undefined, { timeout: 120_000 }); + await harness.agent(outer, "showcase_export", { settings: JSON.parse(await readFile(join(workspace, "showcase/Avocado/showcase.json"), "utf8")) }); + await frame.locator(".card.done", { hasText: "Avocado" }).waitFor({ timeout: 300_000 }); + const page = await outer.context().newPage(); + const errors: string[] = []; + page.on("pageerror", (e: Error) => errors.push(e.message)); + await page.setViewportSize({ width: 900, height: 700 }); + await page.goto(pathToFileURL(join(workspace, "showcase/Avocado/viewer/index.html")).href); + await page.waitForFunction(() => !document.getElementById("loading"), undefined, { timeout: 60_000 }); + await page.waitForTimeout(1500); + const nonBg = await page.evaluate(() => { + const c = document.getElementById("view") as HTMLCanvasElement; + const t = document.createElement("canvas"); + t.width = c.width; t.height = c.height; + const g = t.getContext("2d")!; + g.drawImage(c, 0, 0); + const d = g.getImageData(0, 0, t.width, t.height).data; + let n = 0; + for (let i = 0; i < d.length; i += 4) if (Math.abs(d[i] - 241) + Math.abs(d[i + 1] - 245) + Math.abs(d[i + 2] - 249) > 40) n++; + return n / (d.length / 4); + }); + assert.ok(nonBg > 0.03, `viewer shows the model (${nonBg})`); + await page.screenshot({ path: join(shots, "03-viewer.png") }); + assert.deepEqual(errors, []); + assert.deepEqual(harness.errors, []); + step(`ok — screenshots in ${shots}`); +} catch (error) { + console.error("page errors:", harness.errors, harness.stderr.join("")); + throw error; +} finally { + await harness.close(); +} diff --git a/ui-plugins/product-3d-showcase/scripts/harness.mjs b/ui-plugins/product-3d-showcase/scripts/harness.mjs new file mode 100644 index 00000000..eb81f616 --- /dev/null +++ b/ui-plugins/product-3d-showcase/scripts/harness.mjs @@ -0,0 +1,164 @@ +import assert from "node:assert/strict"; +import { createServer } from "node:http"; +import { readFile } from "node:fs/promises"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { build } from "esbuild"; +import { chromium } from "playwright-core"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; +import { ResourceUpdatedNotificationSchema } from "@modelcontextprotocol/sdk/types.js"; + +/** + * 浏览器测试宿主:真实打包的 server(stdio)+ 官方 AppBridge 宿主页 + 隔离 iframe 中的面板。 + * 宿主页用与 ZCode 相同的 CSP 约束面板。测试脚本同时扮演 Agent:经同一个 MCP 连接调用工具, + * 并像宿主一样把结果推给页面。 + */ +const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); + +// 与 ZCode 给 MCP App 页面的限制一致:没有网络,允许 wasm(声明了 zcode/csp.wasmUnsafeEval)。 +export const PANEL_CSP = + "default-src 'none'; script-src 'self' 'unsafe-inline' blob: data: 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; media-src 'self' data: blob:; worker-src 'self' blob:; connect-src 'none'; frame-src 'none'; base-uri 'self'; form-action 'none'"; + +/** server:要运行的 server 入口(默认真实打包的 dist/server.mjs)。 */ +export async function startHarness({ env = {}, workspace, server = join(root, "dist/server.mjs") }) { + const client = new Client({ name: "kit-harness", version: "1" }); + const sseClients = new Set(); + client.setNotificationHandler(ResourceUpdatedNotificationSchema, (notification) => { + for (const response of sseClients) response.write(`data: ${JSON.stringify(notification.params)}\n\n`); + }); + const stderr = []; + const transport = new StdioClientTransport({ + command: process.execPath, + args: [server], + cwd: workspace, + env: { ...process.env, ZCODE_WORKSPACE_ROOT: workspace, ...env }, + stderr: "pipe", + }); + transport.stderr?.on("data", (chunk) => stderr.push(String(chunk))); + await client.connect(transport); + const html = await readFile(join(root, "dist/ui/panel.html"), "utf8"); + const hostJs = await build({ + stdin: { + contents: ` +import { AppBridge, PostMessageTransport } from "@modelcontextprotocol/ext-apps/app-bridge"; +import { z } from "zod"; +const WidgetState = z.object({ method: z.literal('ui/set-widget-state'), params: z.object({ widgetState: z.unknown() }) }); +const rpc = async (method, args) => { + const response = await fetch('/rpc', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({method,args})}); + const result = await response.json(); if (!response.ok) throw Error(result.error); return result; +}; +const params = new URLSearchParams(location.search); +const context = { theme: params.get('theme') || 'light', locale: params.get('locale') || 'en-US', displayMode: params.get('mode') || 'fullscreen' }; +const bridge = new AppBridge(null, {name:"kit-harness",version:"1"}, { + serverTools:{}, serverResources:{ listChanged: true }, message:{text:{}}, updateModelContext:{text:{}, structuredContent:{}}, openLinks:{}, + experimental: params.get('nosub') ? { "zcode/widgetState": {} } : { "zcode/resourceSubscribe": {}, "zcode/widgetState": {} }, +}, {hostContext:{...context, "zcode/widgetState": JSON.parse(sessionStorage.getItem('widgetState') || 'null')}}); +window.__messages = []; +window.__context = []; +window.__links = []; +window.__calls = []; +window.__initializations = 0; +bridge.oncalltool = (args) => { window.__calls.push(args.name); return rpc('callTool', args); }; +bridge.onreadresource = (args) => rpc('readResource', args); +bridge.onmessage = async (params) => { window.__messages.push(params.content[0].text); return {}; }; +bridge.onupdatemodelcontext = async (params) => { window.__context.push(params); return {}; }; +bridge.onopenlink = async (params) => { window.__links.push(params.url); return {}; }; +bridge.setRequestHandler('resources/subscribe', async (request) => { await rpc('subscribe', { uri: request.params.uri }); return {}; }); +bridge.setRequestHandler('resources/unsubscribe', async (request) => { await rpc('unsubscribe', { uri: request.params.uri }); return {}; }); +bridge.setRequestHandler(WidgetState, async (request) => { sessionStorage.setItem('widgetState', JSON.stringify(request.params.widgetState)); return {}; }); +bridge.oninitialized = () => { window.__initializations++; }; +window.__sendToolResult = (result) => bridge.sendToolResult(result); +window.__setContext = (patch) => bridge.setHostContext({ ...context, ...patch }); +new EventSource('/events').onmessage = (event) => { + bridge.notification({ method: 'notifications/resources/updated', params: JSON.parse(event.data) }); +}; +const frame = document.querySelector('iframe'); +await bridge.connect(new PostMessageTransport(frame.contentWindow, frame.contentWindow)); +frame.src = '/panel'; +`, + resolveDir: root, + sourcefile: "browser-host.mjs", + }, + bundle: true, + format: "esm", + platform: "browser", + write: false, + }); + const http = createServer(async (request, response) => { + try { + const url = new URL(request.url, "http://localhost"); + if (url.pathname === "/") { + response.setHeader("Content-Type", "text/html; charset=utf-8"); + response.end( + '', + ); + } else if (url.pathname === "/host.js") { + response.setHeader("Content-Type", "text/javascript"); + response.end(hostJs.outputFiles[0].text); + } else if (url.pathname === "/panel") { + response.setHeader("Content-Type", "text/html; charset=utf-8"); + response.setHeader("Content-Security-Policy", PANEL_CSP); + response.end(html); + } else if (url.pathname === "/events") { + response.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" }); + response.write(": connected\n\n"); + sseClients.add(response); + request.on("close", () => sseClients.delete(response)); + } else if (request.method === "POST" && url.pathname === "/rpc") { + let body = ""; + for await (const chunk of request) body += chunk; + const { method, args } = JSON.parse(body); + const result = + method === "readResource" + ? await client.readResource(args) + : method === "subscribe" + ? await client.subscribeResource(args) + : method === "unsubscribe" + ? await client.unsubscribeResource(args) + : await client.callTool(args, undefined, { timeout: 300_000 }); + response.setHeader("Content-Type", "application/json"); + response.end(JSON.stringify(result ?? {})); + } else if (url.pathname === "/favicon.ico") response.writeHead(204).end(); + else response.writeHead(404).end(); + } catch (error) { + response.writeHead(500, { "Content-Type": "application/json" }).end(JSON.stringify({ error: String(error) })); + } + }); + await new Promise((done) => http.listen(0, "127.0.0.1", done)); + const base = `http://127.0.0.1:${http.address().port}`; + // WebGL 在无 GPU 的无头 Chrome 里走 SwiftShader。 + const args = ["--enable-unsafe-swiftshader", "--use-angle=swiftshader"]; + const browser = await chromium.launch(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH, args } : { channel: "chrome", args }); + const errors = []; + const contexts = []; + + const open = async (query = "", viewport = { width: 720, height: 900 }) => { + const context = await browser.newContext({ viewport, deviceScaleFactor: 2 }); + contexts.push(context); + const outer = await context.newPage(); + outer.on("pageerror", (error) => errors.push(String(error))); + outer.on("console", (message) => { + if (message.type() === "error" && !/favicon/.test(message.text())) errors.push(message.text()); + }); + await outer.goto(`${base}/${query}`); + await outer.waitForFunction(() => window.__initializations === 1); + const frame = outer.frames().find((item) => item !== outer.mainFrame()); + assert.ok(frame, "official App iframe exists"); + return { outer, frame, context }; + }; + /** 扮演 Agent:调用工具,再像宿主一样把结果推给页面。 */ + const agent = async (outer, name, args, { expectError = false } = {}) => { + const result = await client.callTool({ name, arguments: args }, undefined, { timeout: 300_000 }); + if (expectError) assert.ok(result.isError, `${name} should fail`); + else assert.ok(!result.isError, `${name}: ${JSON.stringify(result.content)}`); + if (outer) await outer.evaluate((value) => window.__sendToolResult(value), result); + return result; + }; + const close = async () => { + await browser.close().catch(() => undefined); + await client.close().catch(() => undefined); + http.close(); + }; + return { client, open, agent, close, errors, stderr, base, contexts: () => contexts.filter((context) => context.pages().length) }; +} diff --git a/ui-plugins/product-3d-showcase/scripts/licenses.mjs b/ui-plugins/product-3d-showcase/scripts/licenses.mjs new file mode 100644 index 00000000..162c2a73 --- /dev/null +++ b/ui-plugins/product-3d-showcase/scripts/licenses.mjs @@ -0,0 +1,43 @@ +import { readFile, readdir, writeFile } from "node:fs/promises"; +import { dirname, join, resolve } from "node:path"; + +// 从实际参与打包的模块收集许可证,避免只列直接依赖而漏掉 Canvas/SDK 的传递依赖。 +export async function writeNotices(metafiles, destination, extra = []) { + const packages = new Map(); + const { createRequire } = await import("node:module"); + const require = createRequire(resolve("package.json")); + const extraInputs = extra.map((spec) => require.resolve(spec)); + for (const input of [...metafiles.flatMap((meta) => Object.keys(meta.inputs)), ...extraInputs]) { + if (!input.includes("node_modules/")) continue; + let directory = dirname(resolve(input)); + while (directory.includes("node_modules")) { + try { + const pkg = JSON.parse(await readFile(join(directory, "package.json"), "utf8")); + if (pkg.name) { + packages.set(directory, pkg); + break; + } + } catch (error) { + if (error.code !== "ENOENT") throw error; + } + directory = dirname(directory); + } + } + const notices = []; + const seen = new Set(); + for (const [directory, pkg] of [...packages].sort((a, b) => a[1].name.localeCompare(b[1].name))) { + const key = `${pkg.name}@${pkg.version}`; + if (seen.has(key)) continue; + seen.add(key); + const files = (await readdir(directory)).filter((name) => + /^(license|copying|notice)([.-]|$)/i.test(name), + ); + const texts = await Promise.all(files.map((file) => readFile(join(directory, file), "utf8"))); + if (!texts.length && !pkg.license) throw new Error(`Missing license for bundled dependency ${key}`); + if (!texts.length) texts.push(`(No license file is shipped in this package; its package.json declares the ${pkg.license} license.)`); + notices.push( + `${key} — ${typeof pkg.license === "string" ? pkg.license : JSON.stringify(pkg.license)}\n${texts.join("\n\n")}`, + ); + } + await writeFile(destination, notices.join("\n\n----------------------------------------\n\n")); +} diff --git a/ui-plugins/product-3d-showcase/src/kit/console.ts b/ui-plugins/product-3d-showcase/src/kit/console.ts new file mode 100644 index 00000000..f6817656 --- /dev/null +++ b/ui-plugins/product-3d-showcase/src/kit/console.ts @@ -0,0 +1,5 @@ +// stdout 只留给 MCP 协议;依赖库的日志改写到 stderr。 +console.log = (...args: unknown[]) => process.stderr.write(`${args.map(String).join(" ")}\n`); +console.info = console.log; +console.warn = console.log; +console.debug = console.log; diff --git a/ui-plugins/product-3d-showcase/src/kit/ffmpeg.ts b/ui-plugins/product-3d-showcase/src/kit/ffmpeg.ts new file mode 100644 index 00000000..34ad626d --- /dev/null +++ b/ui-plugins/product-3d-showcase/src/kit/ffmpeg.ts @@ -0,0 +1,128 @@ +import { spawn } from "node:child_process"; +import { access, constants } from "node:fs/promises"; +import { delimiter, join } from "node:path"; +import { KitError } from "./workspace.ts"; + +/** 查找用户电脑上已安装的 ffmpeg / ffprobe(不随插件分发)。 */ +const COMMON_DIRS = ["/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "C:\\ffmpeg\\bin", "C:\\Program Files\\ffmpeg\\bin"]; +let found: Promise<{ ffmpeg: string; ffprobe: string }> | undefined; + +async function which(name: string, explicit?: string) { + const exe = process.platform === "win32" ? `${name}.exe` : name; + const dirs = [...(process.env.PATH ?? "").split(delimiter), ...COMMON_DIRS].filter(Boolean); + const candidates = explicit ? [explicit] : dirs.map((d) => join(d, exe)); + for (const c of candidates) { + try { + await access(c, constants.X_OK); + return c; + } catch { + // 下一个 + } + } + return undefined; +} + +export function findFfmpeg(): Promise<{ ffmpeg: string; ffprobe: string }> { + found ??= (async () => { + const ffmpeg = await which("ffmpeg", process.env.FFMPEG_PATH || undefined); + const ffprobe = await which("ffprobe", process.env.FFPROBE_PATH || (process.env.FFMPEG_PATH ? process.env.FFMPEG_PATH.replace(/ffmpeg(\.exe)?$/i, "ffprobe$1") : undefined)); + if (!ffmpeg || !ffprobe) { + found = undefined; + throw new KitError( + "ffmpeg_missing", + "ffmpeg was not found. Install it (macOS: `brew install ffmpeg`; Windows: `winget install ffmpeg`; Linux: your package manager) or set the plugin's ffmpeg path setting.", + ); + } + return { ffmpeg, ffprobe }; + })(); + return found; +} + +export interface RunOptions { + timeoutMs?: number; + /** 0..1 进度(需要传 duration)。 */ + onProgress?: (fraction: number) => void; + duration?: number; + cwd?: string; +} + +/** 运行 ffmpeg,失败时返回 stderr 末尾。参数数组,不经过 shell。 */ +export async function ffmpeg(args: string[], options: RunOptions = {}): Promise<{ stderr: string; stdout: Buffer }> { + const { ffmpeg: bin } = await findFfmpeg(); + return run(bin, ["-hide_banner", "-nostdin", "-y", ...args], options); +} + +export async function run(bin: string, args: string[], options: RunOptions = {}): Promise<{ stderr: string; stdout: Buffer }> { + return new Promise((resolve, reject) => { + const child = spawn(bin, args, { cwd: options.cwd, stdio: ["ignore", "pipe", "pipe"] }); + const out: Buffer[] = []; + let err = ""; + const timer = options.timeoutMs ? setTimeout(() => child.kill("SIGKILL"), options.timeoutMs) : undefined; + child.stdout.on("data", (d: Buffer) => out.push(d)); + child.stderr.on("data", (d: Buffer) => { + const text = d.toString(); + err = (err + text).slice(-20000); + if (options.onProgress && options.duration) { + const m = /time=(\d+):(\d+):([\d.]+)/.exec(text); + if (m) options.onProgress(Math.min(1, (Number(m[1]) * 3600 + Number(m[2]) * 60 + Number(m[3])) / options.duration)); + } + }); + child.on("error", (e) => reject(new KitError("ffmpeg_failed", e.message))); + child.on("close", (code) => { + if (timer) clearTimeout(timer); + if (code === 0) resolve({ stderr: err, stdout: Buffer.concat(out) }); + else reject(new KitError("ffmpeg_failed", `ffmpeg exited with ${code}: ${err.split("\n").filter(Boolean).slice(-6).join(" | ")}`)); + }); + }); +} + +export interface MediaInfo { + duration: number; + width?: number; + height?: number; + fps?: number; + hasVideo: boolean; + hasAudio: boolean; + sampleRate?: number; + channels?: number; +} + +export async function probe(path: string): Promise { + const { ffprobe } = await findFfmpeg(); + let json: any; + try { + const { stdout } = await run(ffprobe, ["-v", "error", "-print_format", "json", "-show_format", "-show_streams", path], { timeoutMs: 60_000 }); + json = JSON.parse(stdout.toString()); + } catch { + throw new KitError("bad_media", `Cannot read media file ${path.split(/[\\/]/).pop()}.`); + } + const v = json.streams?.find((s: any) => s.codec_type === "video" && s.disposition?.attached_pic !== 1); + const a = json.streams?.find((s: any) => s.codec_type === "audio"); + const rate = v?.avg_frame_rate && v.avg_frame_rate !== "0/0" ? v.avg_frame_rate : v?.r_frame_rate; + const [n, d] = String(rate ?? "0/1").split("/").map(Number); + let duration = Number(json.format?.duration ?? v?.duration ?? a?.duration ?? 0); + if (!Number.isFinite(duration)) duration = 0; + return { + duration, + hasVideo: !!v, + hasAudio: !!a, + ...(v ? { width: Number(v.width), height: Number(v.height), fps: d ? n / d : undefined } : {}), + ...(a ? { sampleRate: Number(a.sample_rate), channels: Number(a.channels) } : {}), + }; +} + +/** 抽一帧 JPEG(用于面板预览)。 */ +export async function frameAt(path: string, seconds: number, maxWidth = 960): Promise { + const { stdout } = await ffmpeg([...(seconds > 0 ? ["-ss", String(seconds)] : []), "-i", path, "-frames:v", "1", "-vf", `scale='min(${maxWidth},iw)':-2`, "-q:v", "4", "-f", "image2pipe", "-c:v", "mjpeg", "pipe:1"], { timeoutMs: 60_000 }); + if (!stdout.length) throw new KitError("no_frame", `No frame at ${seconds}s.`); + return stdout; +} + +export const fmtTime = (s: number) => { + const sign = s < 0 ? "-" : ""; + s = Math.round(Math.abs(s) * 10) / 10; + const h = Math.floor(s / 3600); + const m = Math.floor((s % 3600) / 60); + const sec = s % 60; + return `${sign}${h ? `${h}:` : ""}${String(m).padStart(h ? 2 : 1, "0")}:${sec.toFixed(1).padStart(4, "0")}`; +}; diff --git a/ui-plugins/product-3d-showcase/src/kit/server-kit.ts b/ui-plugins/product-3d-showcase/src/kit/server-kit.ts new file mode 100644 index 00000000..6bc31594 --- /dev/null +++ b/ui-plugins/product-3d-showcase/src/kit/server-kit.ts @@ -0,0 +1,84 @@ +import { readFile } from "node:fs/promises"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import type { z } from "zod"; +import { KitError } from "./workspace.ts"; + +export const HTML_MIME = "text/html;profile=mcp-app"; +type Visibility = ("model" | "app")[]; +type Content = { type: "text"; text: string } | { type: "image"; data: string; mimeType: string }; + +export interface ToolOutput { + text: string; + structured?: Record; + images?: { data: string; mimeType: string }[]; +} + +export interface KitServerOptions { + name: string; + version: string; + panelUri: string; + surface: string; + panelHtml: () => Promise; + log?: (line: string) => void; + /** 页面资源的额外 _meta,例如 { "zcode/csp": { wasmUnsafeEval: true } }。 */ + panelMeta?: Record; +} + +/** 统一的工具注册:所有工具都关联同一个侧栏面板,错误带 code 返回给 Agent 与页面。 */ +export function createKitServer(options: KitServerOptions) { + const log = options.log ?? (() => undefined); + const server = new McpServer({ name: options.name, version: options.version }, { capabilities: { logging: {} } }); + const panelMeta = { ui: { prefersBorder: false }, ...options.panelMeta }; + server.registerResource("panel", options.panelUri, { mimeType: HTML_MIME, _meta: panelMeta }, async () => ({ + contents: [{ uri: options.panelUri, mimeType: HTML_MIME, _meta: panelMeta, text: await options.panelHtml() }], + })); + + const tool = ( + name: string, + config: { + description: string; + input: Record; + visibility?: Visibility; + openPanel?: boolean; + readOnly?: boolean; + timeoutMs?: number; + }, + run: (input: any) => Promise, + ) => { + server.registerTool( + name, + { + description: config.description, + inputSchema: config.input, + annotations: { readOnlyHint: !!config.readOnly, ...(config.readOnly ? {} : { destructiveHint: false }), openWorldHint: false }, + _meta: { + ui: { resourceUri: options.panelUri, surface: options.surface, visibility: config.visibility ?? ["model", "app"] }, + ...(config.timeoutMs ? { timeoutMs: config.timeoutMs } : {}), + ...(config.openPanel ? { "openai/ui": { preferredModelDisplayMode: "fullscreen" } } : {}), + }, + }, + async (input: unknown) => { + try { + const output = await run(input); + const content: Content[] = [{ type: "text", text: output.text }]; + for (const image of output.images ?? []) content.push({ type: "image", ...image }); + return { content, ...(output.structured ? { structuredContent: output.structured } : {}) }; + } catch (error) { + const code = error instanceof KitError ? error.code : "internal_error"; + const message = error instanceof Error ? error.message : String(error); + if (!(error instanceof KitError)) log(`${name} failed: ${error instanceof Error ? error.stack : message}`); + return { + isError: true, + content: [{ type: "text" as const, text: `[${code}] ${message}` }], + structuredContent: { error: { code, message } }, + }; + } + }, + ); + }; + return { server, tool }; +} + +export async function readPanel(path: string) { + return readFile(path, "utf8"); +} diff --git a/ui-plugins/product-3d-showcase/src/kit/workspace.ts b/ui-plugins/product-3d-showcase/src/kit/workspace.ts new file mode 100644 index 00000000..f02c4fcb --- /dev/null +++ b/ui-plugins/product-3d-showcase/src/kit/workspace.ts @@ -0,0 +1,151 @@ +import { lstatSync, readlinkSync, realpathSync } from "node:fs"; +import { mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises"; +import { dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path"; + +export class KitError extends Error { + readonly code: string; + constructor(code: string, message: string) { + super(message); + this.code = code; + this.name = "KitError"; + } +} + +const SKIP = new Set(["node_modules", ".git", "dist", "build", ".next", ".cache", "__pycache__"]); + +/** 只允许读写当前工作区内的文件;所有路径都相对工作区根目录。 */ +export class Workspace { + readonly root: string; + constructor(root: string) { + this.root = resolve(root); + } + + resolve(path: string): string { + if (typeof path !== "string" || !path.trim()) throw new KitError("bad_path", "Path is empty."); + const absolute = resolve(this.root, path); + const rel = relative(this.root, absolute); + if (rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) + throw new KitError("outside_workspace", `Path is outside the workspace: ${path}`); + this.assertRealInside(absolute, path); + return absolute; + } + + private realRoot?: string; + + /** + * 符号链接不能把读写带出工作区:从目标往上找到第一个已存在的路径,取它的真实路径, + * 必须仍在工作区根目录的真实路径之下。还不存在的写入目标按其已存在的上级目录判断; + * 指向不存在位置的悬空链接一律拒绝(否则 writeFile 会顺着它在外部建文件)。 + */ + private assertRealInside(absolute: string, path: string) { + let realRoot: string; + try { + realRoot = this.realRoot ??= realpathSync(this.root); + } catch { + return; // 根目录本身不存在时,没有可逃出的链接 + } + const outside = (real: string) => { + const rel = relative(realRoot, real); + return rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel); + }; + let probe = absolute; + for (;;) { + let real: string | undefined; + try { + real = realpathSync(probe); + } catch { + let link = false; + try { + link = lstatSync(probe).isSymbolicLink(); + } catch {} + if (link) { + const target = resolve(dirname(probe), readlinkSync(probe)); + throw new KitError("outside_workspace", outside(target) ? `Path leaves the workspace through a link: ${path}` : `Path goes through a broken link: ${path}`); + } + } + if (real !== undefined) { + if (outside(real)) throw new KitError("outside_workspace", `Path leaves the workspace through a link: ${path}`); + return; + } + const parent = dirname(probe); + if (parent === probe) return; + probe = parent; + } + } + + rel(absolute: string): string { + return relative(this.root, absolute).split(sep).join("/") || "."; + } + + async exists(path: string): Promise { + try { + await stat(this.resolve(path)); + return true; + } catch { + return false; + } + } + + async read(path: string, maxBytes = 200 * 1024 * 1024): Promise { + const absolute = this.resolve(path); + let info; + try { + info = await stat(absolute); + } catch { + throw new KitError("not_found", `File not found: ${path}`); + } + if (!info.isFile()) throw new KitError("not_a_file", `Not a file: ${path}`); + if (info.size > maxBytes) throw new KitError("too_large", `File is larger than ${Math.round(maxBytes / 1048576)} MB: ${path}`); + return readFile(absolute); + } + + async readText(path: string): Promise { + return (await this.read(path, 20 * 1024 * 1024)).toString("utf8"); + } + + async write(path: string, data: Uint8Array | string): Promise { + const absolute = this.resolve(path); + await mkdir(dirname(absolute), { recursive: true }); + await writeFile(absolute, data); + return this.rel(absolute); + } + + /** 列出文件(默认递归、跳过依赖与构建目录),按路径排序。 */ + async list({ dir = ".", exts, recursive = true, limit = 2000 }: { dir?: string; exts?: string[]; recursive?: boolean; limit?: number } = {}) { + const wanted = exts?.map((ext) => ext.toLowerCase()); + const out: { path: string; size: number }[] = []; + const walk = async (absolute: string, depth: number) => { + if (out.length >= limit || depth > 8) return; + let entries; + try { + entries = await readdir(absolute, { withFileTypes: true }); + } catch { + return; + } + entries.sort((a, b) => a.name.localeCompare(b.name, "en", { numeric: true })); + for (const entry of entries) { + if (out.length >= limit) return; + if (entry.name.startsWith(".") && entry.name !== ".") continue; + const child = join(absolute, entry.name); + if (entry.isDirectory()) { + if (recursive && !SKIP.has(entry.name)) await walk(child, depth + 1); + } else if (entry.isFile() && (!wanted || wanted.includes(extname(entry.name).toLowerCase()))) { + out.push({ path: this.rel(child), size: (await stat(child)).size }); + } + } + }; + await walk(this.resolve(dir), 0); + return out; + } +} + +/** 把文件名中不适合的字符替换掉,保留中文。 */ +export function safeFileName(name: string, fallback = "file"): string { + const cleaned = name + .replace(/[\\/:*?"<>|]+/g, "_") + .replace(/\p{Cc}+/gu, "_") + .replace(/\s+/g, " ") + .trim() + .replace(/^\.+/, ""); + return (cleaned || fallback).slice(0, 120); +} diff --git a/ui-plugins/product-3d-showcase/src/main.ts b/ui-plugins/product-3d-showcase/src/main.ts new file mode 100644 index 00000000..712397ee --- /dev/null +++ b/ui-plugins/product-3d-showcase/src/main.ts @@ -0,0 +1,14 @@ +import "./kit/console.ts"; +import { dirname, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; +import { createServer } from "./server.ts"; + +const here = dirname(fileURLToPath(import.meta.url)); +const server = createServer({ + workspaceRoot: resolve(process.env.ZCODE_WORKSPACE_ROOT || process.cwd()), + assetRoot: here, + log: (line) => process.stderr.write(`[product-3d-showcase] ${line}\n`), +}); +process.stdin.once("end", () => process.exit(0)); +await server.connect(new StdioServerTransport()); diff --git a/ui-plugins/product-3d-showcase/src/model.ts b/ui-plugins/product-3d-showcase/src/model.ts new file mode 100644 index 00000000..6bfe7cb7 --- /dev/null +++ b/ui-plugins/product-3d-showcase/src/model.ts @@ -0,0 +1,42 @@ +import { posix } from "node:path"; +import { KitError, type Workspace } from "./kit/workspace.ts"; + +const MIME: Record = { png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", webp: "image/webp", ktx2: "image/ktx2", bin: "application/octet-stream" }; + +/** 读模型:GLB 原样(base64);.gltf 把外部 buffer / 贴图内联成 data URI,得到一个自包含的 JSON。 */ +export async function readModel(ws: Workspace, path: string) { + const ext = path.toLowerCase().split(".").pop(); + if (ext === "glb") { + const buf = await ws.read(path, 300 * 1024 * 1024); + if (buf.toString("ascii", 0, 4) !== "glTF") throw new KitError("bad_model", `${path} is not a binary glTF (.glb) file.`); + const len = buf.readUInt32LE(12); + const json = JSON.parse(buf.toString("utf8", 20, 20 + len)); + return { format: "glb" as const, data: buf.toString("base64"), info: info(json, buf.length) }; + } + if (ext !== "gltf") throw new KitError("bad_model", `${path}: only glTF 2.0 (.glb / .gltf) is supported. Convert OBJ/FBX/USDZ to glTF first (e.g. Blender → Export → glTF 2.0).`); + let json: any; + try { + json = JSON.parse(await ws.readText(path)); + } catch { + throw new KitError("bad_model", `${path} is not valid glTF JSON.`); + } + const dir = posix.dirname(path); + let bytes = 0; + for (const item of [...(json.buffers ?? []), ...(json.images ?? [])]) { + if (!item.uri || item.uri.startsWith("data:")) continue; + const rel = posix.normalize(posix.join(dir, decodeURIComponent(item.uri))); + if (!(await ws.exists(rel))) throw new KitError("missing_resource", `${path} refers to ${item.uri}, which is missing next to it.`); + const b = await ws.read(rel, 300 * 1024 * 1024); + bytes += b.length; + item.uri = `data:${item.mimeType ?? MIME[rel.split(".").pop()!.toLowerCase()] ?? "application/octet-stream"};base64,${b.toString("base64")}`; + } + const text = JSON.stringify(json); + return { format: "gltf" as const, data: text, info: info(json, text.length + bytes) }; +} + +function info(json: any, bytes: number) { + const version = String(json?.asset?.version ?? ""); + if (!version.startsWith("2")) throw new KitError("bad_model", `glTF ${version || "?"} is not supported (need 2.0).`); + const prims = (json.meshes ?? []).reduce((s: number, m: any) => s + (m.primitives?.length ?? 0), 0); + return { meshes: json.meshes?.length ?? 0, primitives: prims, materials: json.materials?.length ?? 0, textures: json.textures?.length ?? 0, animations: json.animations?.length ?? 0, extensions: json.extensionsUsed ?? [], megabytes: Math.round((bytes / 1048576) * 10) / 10, generator: json.asset?.generator ?? "" }; +} diff --git a/ui-plugins/product-3d-showcase/src/server.ts b/ui-plugins/product-3d-showcase/src/server.ts new file mode 100644 index 00000000..7a124e25 --- /dev/null +++ b/ui-plugins/product-3d-showcase/src/server.ts @@ -0,0 +1,169 @@ +import { readFile } from "node:fs/promises"; +import { join, posix } from "node:path"; +import { z } from "zod"; +import { createKitServer } from "./kit/server-kit.ts"; +import { KitError, Workspace } from "./kit/workspace.ts"; +import { ffmpeg } from "./kit/ffmpeg.ts"; +import { readModel } from "./model.ts"; +import { normalizeSettings, type Settings } from "./settings.ts"; + +export const NAME = "product-3d-showcase"; +export const VERSION = "0.1.0"; +export const PANEL_URI = `ui://${NAME}/panel.html`; +/** Largest model_data part, in characters; keeps every stdio message well under ZCode's 10 MB limit. */ +export const MODEL_CHUNK = 4 * 1024 * 1024; + +export interface ServerOptions { + workspaceRoot: string; + assetRoot: string; + log?: (line: string) => void; +} + +const esc = (s: string) => s.replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]!); + +export function createServer(options: ServerOptions) { + const ws = new Workspace(options.workspaceRoot); + const { server, tool } = createKitServer({ + name: NAME, + version: VERSION, + panelUri: PANEL_URI, + surface: "editor", + panelHtml: () => readFile(join(options.assetRoot, "ui/panel.html"), "utf8"), + log: options.log, + }); + + async function settingsFrom(raw: any) { + const model = String(raw?.model ?? ""); + if (!model) throw new KitError("missing_model", "Pass `model`: a .glb or .gltf file."); + const m = await readModel(ws, model); + return { s: normalizeSettings(raw, model), m }; + } + const settingsPath = (s: Settings) => `${s.output}/showcase.json`; + const describe = (s: Settings, info: Record) => + [ + `${s.title} (${s.model}): ${info.meshes} mesh(es), ${info.materials} material(s), ${info.textures} texture(s), ${info.megabytes} MB${(info.extensions as string[]).length ? `; extensions ${(info.extensions as string[]).join(", ")}` : ""}.`, + `Angles: ${s.angles.map((a) => `${a.name} (yaw ${a.yaw}°, pitch ${a.pitch}°${a.zoom !== 1 ? `, zoom ${a.zoom}` : ""})`).join(", ")}.`, + `Look: ${s.lighting} lighting, background ${s.background}${s.shadow ? ", ground shadow" : ""}, exposure ${s.exposure}; stills ${s.size}×${s.size}; ${s.video.enabled ? `360° video ${s.video.seconds}s at ${s.video.size}px` : "no video"}; ${s.viewer ? "web viewer" : "no viewer"} → ${s.output}/.`, + ].join("\n"); + const settingsSchema = z + .record(z.string(), z.unknown()) + .describe('{model, title, angles: ["front","three-quarter-left","three-quarter-right","side","back","top"] or [{name, yaw (deg, 0 = front), pitch (deg), zoom}], lighting "studio"|"soft"|"dramatic", background "#ffffff"|"transparent"|"#rrggbb", shadow, exposure, size (px), video {enabled, seconds, size, pitch}, viewer (bool), output}'); + + tool( + "showcase_open", + { + description: + "Open Product 3D Showcase with a glTF/GLB product model. The panel renders it in a consistent studio (lighting preset, ground shadow, auto-framed camera) and exports multi-angle product images (PNG, white or transparent background), a 360° turntable video (WebM, plus MP4 when ffmpeg is installed) and a self-contained web viewer (three.js, works offline). Settings can be passed now or later with showcase_save.", + input: { model: z.string(), settings: settingsSchema.optional() }, + openPanel: true, + timeoutMs: 120_000, + }, + async ({ model, settings }) => { + let raw: any = { ...(settings ?? {}), model }; + if (!settings) { + const prev = normalizeSettings({}, model); + if (await ws.exists(settingsPath(prev))) raw = { ...JSON.parse(await ws.readText(settingsPath(prev))), model }; + } + const { s, m } = await settingsFrom(raw); + await ws.write(settingsPath(s), JSON.stringify(s, null, 1) + "\n"); + return { text: `${describe(s, m.info)}\nThe panel shows a live preview. Change settings with showcase_save; showcase_export renders and saves everything (in the panel, which must stay open).`, structured: { kind: "settings", settings: s, info: m.info } }; + }, + ); + + tool( + "showcase_save", + { description: "Validate and save showcase settings (angles, lighting, background, shadow, exposure, sizes, video, viewer, output).", input: { settings: settingsSchema } }, + async ({ settings }) => { + const { s, m } = await settingsFrom(settings); + await ws.write(settingsPath(s), JSON.stringify(s, null, 1) + "\n"); + return { text: `${describe(s, m.info)}\nSaved ${settingsPath(s)}.`, structured: { kind: "settings", settings: s, info: m.info } }; + }, + ); + + tool( + "showcase_export", + { + description: "Render and save all outputs with the current settings: one PNG per angle, the 360° WebM and the web viewer. Rendering runs in the open panel (WebGL); files appear in the output folder within a few seconds to a minute, and the panel reports them.", + input: { settings: settingsSchema }, + }, + async ({ settings }) => { + const { s, m } = await settingsFrom(settings); + await ws.write(settingsPath(s), JSON.stringify(s, null, 1) + "\n"); + const expected = [...s.angles.map((a) => `${s.output}/${a.name}.png`), ...(s.video.enabled ? [`${s.output}/turntable.webm`, `${s.output}/turntable.mp4 (if ffmpeg is installed)`] : []), ...(s.viewer ? [`${s.output}/viewer/index.html`] : [])]; + return { text: `Rendering in the panel → ${expected.join(", ")}.`, structured: { kind: "export", settings: s, info: m.info, expected } }; + }, + ); + + tool( + "model_data", + { + description: "Model bytes (GLB base64, or self-contained glTF JSON) for the panel, in parts of at most MODEL_CHUNK characters: call again with offset until offset + data.length reaches total.", + input: { model: z.string(), offset: z.number().int().min(0).optional() }, + visibility: ["app"], + readOnly: true, + timeoutMs: 120_000, + }, + async ({ model, offset }) => { + // ZCode Desktop drops a stdio MCP server whose single message exceeds 10 MB, so large models go in parts. + const m = await readModel(ws, model); + const start = Math.min(offset ?? 0, m.data.length); + const data = m.data.slice(start, start + MODEL_CHUNK); + return { text: `${m.format} ${m.info.megabytes} MB (${start + data.length}/${m.data.length})`, structured: { format: m.format, data, offset: start, total: m.data.length, info: m.info } }; + }, + ); + + tool( + "save_output", + { description: "Save a rendered PNG or WebM from the panel into the output folder.", input: { settings: settingsSchema, name: z.string(), data: z.string() }, visibility: ["app"] }, + async ({ settings, name, data }) => { + const s = normalizeSettings(settings, String((settings as any)?.model ?? "model.glb")); + if (!/^[\w.-]+\.(png|webm)$/i.test(name)) throw new KitError("bad_name", "Only .png / .webm files can be saved."); + // 只为确实存在且有效的模型保存输出;空数据也给出可读错误(TEST-FINDINGS #8) + if (!(await ws.exists(s.model))) throw new KitError("not_found", `Model ${s.model} not found; open it with showcase_open first.`); + await readModel(ws, s.model); + const buf = Buffer.from(data, "base64"); + if (buf.length < 8) throw new KitError("bad_data", `${name}: no image/video data received from the panel.`); + const png = buf[0] === 0x89 && buf.toString("ascii", 1, 4) === "PNG"; + const webm = buf.readUInt32BE(0) === 0x1a45dfa3; + if (!(name.endsWith(".png") ? png : webm)) throw new KitError("bad_data", `${name}: data is not a ${name.split(".").pop()} file.`); + const path = await ws.write(posix.join(s.output, name), buf); + if (!webm) return { text: path, structured: { path, bytes: buf.length } }; + // 电商平台多要 MP4:有 ffmpeg 就顺手转一份 H.264(yuv420p,+faststart)。 + const mp4 = path.replace(/\.webm$/i, ".mp4"); + try { + await ffmpeg(["-i", ws.resolve(path), "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", "-preset", "medium", "-movflags", "+faststart", "-an", ws.resolve(mp4)], { timeoutMs: 300_000 }); + return { text: `${path}, ${mp4}`, structured: { path, mp4, bytes: buf.length } }; + } catch (error) { + const note = error instanceof KitError && error.code === "ffmpeg_missing" ? "WebM saved; install ffmpeg to also get an MP4." : `WebM saved; MP4 conversion failed: ${error instanceof Error ? error.message.slice(-200) : error}`; + return { text: `${path} (${note})`, structured: { path, bytes: buf.length, note } }; + } + }, + ); + + tool( + "save_viewer", + { description: "Write the offline web viewer (index.html + viewer.js + model.js).", input: { settings: settingsSchema }, visibility: ["app"], timeoutMs: 120_000 }, + async ({ settings }) => { + const { s, m } = await settingsFrom(settings); + const dir = `${s.output}/viewer`; + const look = { lighting: s.lighting, background: s.background === "transparent" ? "#ffffff" : s.background, shadow: s.shadow, exposure: s.exposure }; + const files = [ + await ws.write(`${dir}/viewer.js`, await readFile(join(options.assetRoot, "viewer.js"))), + await ws.write(`${dir}/model.js`, `window.SHOWCASE=${JSON.stringify({ title: s.title, look, autoRotate: true, model: { format: m.format, data: m.data } })};\n`), + await ws.write( + `${dir}/index.html`, + `${esc(s.title)}

${esc(s.title)}

Loading 3D model…
Drag to rotate · scroll to zoom · 拖动旋转 · 滚轮缩放
\n`, + ), + ]; + return { text: files.join(", "), structured: { files } }; + }, + ); + + tool( + "workspace_files", + { description: "glTF models for the panel.", input: {}, visibility: ["app"], readOnly: true }, + async () => ({ text: "", structured: { models: (await ws.list({ exts: [".glb", ".gltf"], limit: 2000 })).map((f) => f.path) } }), + ); + + return server; +} diff --git a/ui-plugins/product-3d-showcase/src/settings.ts b/ui-plugins/product-3d-showcase/src/settings.ts new file mode 100644 index 00000000..9dc78d52 --- /dev/null +++ b/ui-plugins/product-3d-showcase/src/settings.ts @@ -0,0 +1,56 @@ +import { safeFileName } from "./kit/workspace.ts"; + +export interface Angle { name: string; yaw: number; pitch: number; zoom: number } +export interface Settings { + version: 1; + model: string; + title: string; + angles: Angle[]; + lighting: "studio" | "soft" | "dramatic"; + background: string; // "transparent" | "#rrggbb" + shadow: boolean; + exposure: number; + size: number; + video: { enabled: boolean; seconds: number; size: number; pitch: number }; + viewer: boolean; + output: string; +} +export const DEFAULT_ANGLES: Angle[] = [ + { name: "front", yaw: 0, pitch: 8, zoom: 1 }, + { name: "three-quarter-left", yaw: -35, pitch: 15, zoom: 1 }, + { name: "three-quarter-right", yaw: 35, pitch: 15, zoom: 1 }, + { name: "side", yaw: 90, pitch: 5, zoom: 1 }, + { name: "back", yaw: 180, pitch: 10, zoom: 1 }, + { name: "top", yaw: 20, pitch: 60, zoom: 1 }, +]; +const clamp = (v: unknown, lo: number, hi: number, d: number) => { const n = Number(v); return Number.isFinite(n) ? Math.max(lo, Math.min(hi, n)) : d; }; + +export function normalizeSettings(raw: any, model: string): Settings { + const stem = model.split("/").pop()!.replace(/\.[^.]+$/, ""); + const angles: Angle[] = []; + const seen = new Set(); + for (const a of Array.isArray(raw?.angles) ? raw.angles : DEFAULT_ANGLES.slice(0, 4)) { + const preset = typeof a === "string" ? DEFAULT_ANGLES.find((d) => d.name === a) : undefined; + const src = preset ?? a; + let name = safeFileName(String(src?.name ?? `angle-${angles.length + 1}`).toLowerCase().replace(/\s+/g, "-"), "angle"); + for (let k = 2; seen.has(name); k++) name = `${src?.name}-${k}`; + seen.add(name); + angles.push({ name, yaw: clamp(src?.yaw, -360, 360, 0), pitch: clamp(src?.pitch, -30, 89, 10), zoom: clamp(src?.zoom, 0.3, 4, 1) }); + } + if (!angles.length) angles.push({ ...DEFAULT_ANGLES[0] }); + const bg = String(raw?.background ?? "#ffffff").toLowerCase(); + return { + version: 1, + model, + title: String(raw?.title ?? stem).slice(0, 80) || stem, + angles: angles.slice(0, 24), + lighting: ["studio", "soft", "dramatic"].includes(raw?.lighting) ? raw.lighting : "studio", + background: bg === "transparent" || /^#[0-9a-f]{6}$/.test(bg) ? bg : "#ffffff", + shadow: raw?.shadow !== false, + exposure: clamp(raw?.exposure, 0.2, 3, 1), + size: Math.round(clamp(raw?.size, 256, 4096, 2000)), + video: { enabled: raw?.video?.enabled !== false, seconds: clamp(raw?.video?.seconds, 2, 30, 6), size: Math.round(clamp(raw?.video?.size, 360, 2160, 1080) / 2) * 2, pitch: clamp(raw?.video?.pitch, -10, 60, 12) }, + viewer: raw?.viewer !== false, + output: String(raw?.output ?? "").replace(/^\/+|\/+$/g, "") || `showcase/${safeFileName(stem, "product")}`, + }; +} diff --git a/ui-plugins/product-3d-showcase/test/_mkclient.ts b/ui-plugins/product-3d-showcase/test/_mkclient.ts new file mode 100644 index 00000000..ab96ba54 --- /dev/null +++ b/ui-plugins/product-3d-showcase/test/_mkclient.ts @@ -0,0 +1,18 @@ +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import { createServer } from "../src/server.ts"; + +export async function mkclient(prefix: string) { + const root = mkdtempSync(join(tmpdir(), prefix)); + const server = createServer({ workspaceRoot: root, assetRoot: join(import.meta.dirname, "../dist") } as any); + const [a, b] = InMemoryTransport.createLinkedPair(); + await server.connect(a); + const client = new Client({ name: "t", version: "1" }); + await client.connect(b); + const call = async (name: string, args: Record) => (await client.callTool({ name, arguments: args })) as any; + const text = (r: any) => (r.content ?? []).map((c: any) => c.text ?? "").join(" "); + return { root, call, text }; +} diff --git a/ui-plugins/product-3d-showcase/test/findings-fixes.test.ts b/ui-plugins/product-3d-showcase/test/findings-fixes.test.ts new file mode 100644 index 00000000..d7dcda7b --- /dev/null +++ b/ui-plugins/product-3d-showcase/test/findings-fixes.test.ts @@ -0,0 +1,22 @@ +import { randomBytes } from "node:crypto"; +import { existsSync, mkdirSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { mkclient } from "./_mkclient.ts"; + +const PNG = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg==", "base64"); + +describe("TEST-FINDINGS #8: save_output needs a real model", () => { + it("rejects missing, empty and damaged models and empty data without writing anything", async () => { + const { root, call, text } = await mkclient("p3d-"); + mkdirSync(join(root, "模型")); + writeFileSync(join(root, "模型/空.glb"), ""); + writeFileSync(join(root, "模型/坏.glb"), randomBytes(2048)); + for (const [model, code] of [["模型/不存在.glb", "not_found"], ["模型/空.glb", "bad_model"], ["模型/坏.glb", "bad_model"]]) { + const r = await call("save_output", { settings: { model }, name: "front.png", data: PNG.toString("base64") }); + expect(r.isError, model).toBe(true); + expect(text(r)).toContain(code); + } + expect(existsSync(join(root, "showcase"))).toBe(false); + }); +}); diff --git a/ui-plugins/product-3d-showcase/test/model-parts.test.ts b/ui-plugins/product-3d-showcase/test/model-parts.test.ts new file mode 100644 index 00000000..e491505b --- /dev/null +++ b/ui-plugins/product-3d-showcase/test/model-parts.test.ts @@ -0,0 +1,50 @@ +import { mkdirSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { expect, it } from "vitest"; +import { MODEL_CHUNK } from "../src/server.ts"; +import { mkclient } from "./_mkclient.ts"; + +/** A valid GLB with a large BIN chunk (one triangle plus padding bytes). */ +function bigGlb(binBytes: number) { + const json = Buffer.from(JSON.stringify({ + asset: { version: "2.0" }, scenes: [{ nodes: [0] }], nodes: [{ mesh: 0 }], + meshes: [{ primitives: [{ attributes: { POSITION: 0 } }] }], + accessors: [{ bufferView: 0, componentType: 5126, count: 3, type: "VEC3", min: [0, 0, 0], max: [1, 1, 0] }], + bufferViews: [{ buffer: 0, byteOffset: 0, byteLength: 36 }], buffers: [{ byteLength: binBytes }], + }).padEnd(Math.ceil(400 / 4) * 4, " ")); + const jsonPadded = Buffer.concat([json, Buffer.alloc((4 - (json.length % 4)) % 4, 0x20)]); + const bin = Buffer.alloc(binBytes, 7); + [0, 0, 0, 1, 0, 0, 0, 1, 0].forEach((v, i) => bin.writeFloatLE(v, i * 4)); + const total = 12 + 8 + jsonPadded.length + 8 + bin.length; + const head = Buffer.alloc(12); head.write("glTF", 0, "ascii"); head.writeUInt32LE(2, 4); head.writeUInt32LE(total, 8); + const jh = Buffer.alloc(8); jh.writeUInt32LE(jsonPadded.length, 0); jh.write("JSON", 4, "ascii"); + const bh = Buffer.alloc(8); bh.writeUInt32LE(bin.length, 0); bh.writeUInt32LE(0x004e4942, 4); + return Buffer.concat([head, jh, jsonPadded, bh, bin]); +} + +// ZCode Desktop closes a stdio MCP server whose single message is over 10 MB (the 9 MB WaterBottle.glb +// came back as one 12 MB message and the panel lost its connection). model_data must send large models in parts. +it("model_data sends a large model in parts that stay well under 10 MB and reassemble exactly", async () => { + const { root, call } = await mkclient("p3d-parts-"); + const glb = bigGlb(9 * 1024 * 1024); + mkdirSync(join(root, "models"), { recursive: true }); + writeFileSync(join(root, "models/big.glb"), glb); + const parts: string[] = []; + let offset = 0; + let total = Infinity; + while (offset < total) { + const r = await call("model_data", { model: "models/big.glb", offset }); + expect(r.isError).toBeFalsy(); + expect(JSON.stringify(r).length).toBeLessThan(6 * 1024 * 1024); + const s = r.structuredContent; + expect(s.format).toBe("glb"); + expect(s.offset).toBe(offset); + expect(s.data.length).toBeLessThanOrEqual(MODEL_CHUNK); + expect(s.data.length).toBeGreaterThan(0); + total = s.total; + parts.push(s.data); + offset += s.data.length; + } + expect(parts.length).toBeGreaterThan(1); + expect(Buffer.from(parts.join(""), "base64").equals(glb)).toBe(true); +}); diff --git a/ui-plugins/product-3d-showcase/test/tools.test.ts b/ui-plugins/product-3d-showcase/test/tools.test.ts new file mode 100644 index 00000000..17691158 --- /dev/null +++ b/ui-plugins/product-3d-showcase/test/tools.test.ts @@ -0,0 +1,142 @@ +import { existsSync } from "node:fs"; +import { cp, mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import { beforeAll, describe, expect, it } from "vitest"; +import { normalizeSettings } from "../src/settings.ts"; +import { createServer } from "../src/server.ts"; + +// 真实样本(Khronos WaterBottle.glb、Avocado glTF,CC0)不在仓库里时,用现场生成的同结构模型。 +const SAMPLES = process.env.E2E_MODELS ?? "/workspace/zcode-new-plugins/samples/models"; +const REAL = existsSync(join(SAMPLES, "WaterBottle.glb")); + +/** 一个三角形;textures 个贴图(1×1 PNG)。GLB 内嵌,或 .gltf + 外部 .bin/.png。 */ +function model(textures: number) { + const bin = Buffer.alloc(36); + [0, 0, 0, 1, 0, 0, 0, 1, 0].forEach((v, i) => bin.writeFloatLE(v, i * 4)); + const json: any = { + asset: { version: "2.0", generator: "test" }, + scenes: [{ nodes: [0] }], nodes: [{ mesh: 0 }], + meshes: [{ primitives: [{ attributes: { POSITION: 0 }, material: 0 }] }], + materials: [{ pbrMetallicRoughness: textures ? { baseColorTexture: { index: 0 } } : {} }], + accessors: [{ bufferView: 0, componentType: 5126, count: 3, type: "VEC3", min: [0, 0, 0], max: [1, 1, 0] }], + bufferViews: [{ buffer: 0, byteOffset: 0, byteLength: 36 }], + buffers: [{ byteLength: 36 }], + }; + if (textures) { json.images = Array.from({ length: textures }, (_, i) => ({ uri: `tex${i}.png` })); json.textures = json.images.map((_: unknown, i: number) => ({ source: i })); } + return { json, bin }; +} +function glb() { + const { json, bin } = model(0); + const j = Buffer.from(JSON.stringify(json).padEnd(Math.ceil(JSON.stringify(json).length / 4) * 4, " ")); + const head = Buffer.alloc(12); head.write("glTF", 0); head.writeUInt32LE(2, 4); head.writeUInt32LE(12 + 8 + j.length + 8 + bin.length, 8); + const ch = (len: number, type: string) => { const b = Buffer.alloc(8); b.writeUInt32LE(len, 0); b.write(type, 4); return b; }; + return Buffer.concat([head, ch(j.length, "JSON"), j, ch(bin.length, "BIN\0"), bin]); +} +let workspace: string; +let client: Client; +const call = async (name: string, args: Record) => (await client.callTool({ name, arguments: args }, undefined, { timeout: 300_000 })) as any; +const PNG = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg==", "base64"); + +beforeAll(async () => { + workspace = await mkdtemp(join(tmpdir(), "p3d-")); + if (REAL) { + await cp(join(SAMPLES, "WaterBottle.glb"), join(workspace, "models/bottle.glb"), { recursive: true }); + await cp(join(SAMPLES, "avocado"), join(workspace, "models/avocado"), { recursive: true }); + } else { + await mkdir(join(workspace, "models/avocado"), { recursive: true }); + await writeFile(join(workspace, "models/bottle.glb"), glb()); + const { json, bin } = model(3); + json.buffers[0].uri = "Avocado.bin"; + await writeFile(join(workspace, "models/avocado/Avocado.gltf"), JSON.stringify(json)); + await writeFile(join(workspace, "models/avocado/Avocado.bin"), bin); + for (let i = 0; i < 3; i++) await writeFile(join(workspace, `models/avocado/tex${i}.png`), PNG); + } + await writeFile(join(workspace, "models/broken.glb"), "not a model"); + await writeFile(join(workspace, "models/v1.gltf"), JSON.stringify({ asset: { version: "1.0" } })); + const server = createServer({ workspaceRoot: workspace, assetRoot: join(import.meta.dirname, "../dist") }); + const [a, b] = InMemoryTransport.createLinkedPair(); + await server.connect(a); + client = new Client({ name: "t", version: "1" }); + await client.connect(b); +}); + +describe("settings", () => { + it("fills defaults, resolves presets and clamps", () => { + const s = normalizeSettings({ angles: ["front", "back", { name: "Hero Shot", yaw: 400, pitch: 120, zoom: 9 }, "front"], background: "red", size: 99999, video: { seconds: 100, size: 1081 } }, "models/bottle.glb"); + expect(s.angles.map((a) => a.name)).toEqual(["front", "back", "hero-shot", "front-2"]); + expect(s.angles[2]).toMatchObject({ yaw: 360, pitch: 89, zoom: 4 }); + expect(s).toMatchObject({ title: "bottle", background: "#ffffff", size: 4096, output: "showcase/bottle", lighting: "studio", shadow: true, viewer: true }); + expect(s.video).toMatchObject({ enabled: true, seconds: 30, size: 1082 }); + expect(normalizeSettings({ background: "transparent" }, "a.glb").background).toBe("transparent"); + expect(normalizeSettings({}, "a.glb").angles).toHaveLength(4); + }); +}); + +describe("tools", () => { + it("opens a GLB, reports what is inside and saves settings", async () => { + const r = await call("showcase_open", { model: "models/bottle.glb", settings: { angles: ["front", "three-quarter-left", "back"], background: "transparent" } }); + expect(r.isError).toBeFalsy(); + expect(r.structuredContent.kind).toBe("settings"); + expect(r.structuredContent.info).toMatchObject({ meshes: 1, materials: 1, textures: REAL ? 4 : 0 }); + expect(r.content[0].text).toMatch(/front \(yaw 0°/); + const saved = JSON.parse(await readFile(join(workspace, "showcase/bottle/showcase.json"), "utf8")); + expect(saved.background).toBe("transparent"); + // 不传 settings 时沿用已保存的 + const again = await call("showcase_open", { model: "models/bottle.glb" }); + expect(again.structuredContent.settings.angles).toHaveLength(3); + }); + + it("inlines external buffers and textures of a .gltf", async () => { + let r = await call("model_data", { model: "models/avocado/Avocado.gltf" }); + expect(r.structuredContent.format).toBe("gltf"); + let data = r.structuredContent.data as string; + while (data.length < r.structuredContent.total) { + r = await call("model_data", { model: "models/avocado/Avocado.gltf", offset: data.length }); + data += r.structuredContent.data; + } + const json = JSON.parse(data); + expect(json.buffers[0].uri).toMatch(/^data:application\/octet-stream;base64,/); + expect(json.images.map((i: any) => i.uri.slice(0, 22))).toEqual(Array(3).fill("data:image/png;base64,")); + expect(Buffer.from(json.buffers[0].uri.split(",")[1], "base64").length).toBe(json.buffers[0].byteLength); + }); + + it("explains bad models", async () => { + expect((await call("showcase_open", { model: "models/broken.glb" })).content[0].text).toMatch(/not a binary glTF/); + expect((await call("showcase_open", { model: "models/v1.gltf" })).content[0].text).toMatch(/glTF 1.0 is not supported/); + expect((await call("showcase_open", { model: "models/x.obj" })).content[0].text).toMatch(/only glTF 2.0/); + }); + + it("export lists the expected outputs", async () => { + const r = await call("showcase_export", { settings: { model: "models/bottle.glb", angles: ["front", "side"], video: { enabled: false } } }); + expect(r.structuredContent.kind).toBe("export"); + expect(r.structuredContent.expected).toEqual(["showcase/bottle/front.png", "showcase/bottle/side.png", "showcase/bottle/viewer/index.html"]); + }); + + it("saves only real PNG/WebM files into the output folder", async () => { + const settings = { model: "models/bottle.glb" }; + const ok = await call("save_output", { settings, name: "front.png", data: PNG.toString("base64") }); + expect(ok.structuredContent.path).toBe("showcase/bottle/front.png"); + expect((await call("save_output", { settings, name: "../../evil.png", data: PNG.toString("base64") })).isError).toBe(true); + expect((await call("save_output", { settings, name: "x.webm", data: PNG.toString("base64") })).isError).toBe(true); + expect((await call("save_output", { settings, name: "x.html", data: "PGgxPg==" })).isError).toBe(true); + }); + + it("writes a self-contained web viewer", async () => { + const r = await call("save_viewer", { settings: { model: "models/avocado/Avocado.gltf", title: "Avocado <3" } }); + expect(r.structuredContent.files).toEqual(["showcase/Avocado/viewer/viewer.js", "showcase/Avocado/viewer/model.js", "showcase/Avocado/viewer/index.html"]); + const html = await readFile(join(workspace, "showcase/Avocado/viewer/index.html"), "utf8"); + expect(html).toContain("Avocado <3"); + expect(html).toContain(''); + const model = await readFile(join(workspace, "showcase/Avocado/viewer/model.js"), "utf8"); + expect(model.startsWith("window.SHOWCASE=")).toBe(true); + expect(model).not.toMatch(/"uri":"Avocado/); + }); + + it("lists models", async () => { + const r = await call("workspace_files", {}); + expect(r.structuredContent.models).toEqual(expect.arrayContaining(["models/bottle.glb", "models/avocado/Avocado.gltf"])); + }); +}); diff --git a/ui-plugins/product-3d-showcase/test/workspace-links.test.ts b/ui-plugins/product-3d-showcase/test/workspace-links.test.ts new file mode 100644 index 00000000..f3dae538 --- /dev/null +++ b/ui-plugins/product-3d-showcase/test/workspace-links.test.ts @@ -0,0 +1,43 @@ +import { existsSync, mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { Workspace } from "../src/kit/workspace.ts"; + +// 回归测试:工作区里的符号链接不能把读写带到工作区之外(TEST-FINDINGS #2) +describe("workspace symlink containment", () => { + const base = mkdtempSync(join(tmpdir(), "wslinks-")); + const root = join(base, "项目 ws"), outside = join(base, "outside"); + mkdirSync(join(root, "inner"), { recursive: true }); + mkdirSync(outside, { recursive: true }); + writeFileSync(join(outside, "secret.txt"), "SECRET"); + writeFileSync(join(root, "inner", "ok.txt"), "ok"); + symlinkSync(outside, join(root, "out-link")); + symlinkSync(join(outside, "secret.txt"), join(root, "secret-link.txt")); + symlinkSync(join(outside, "new-file.txt"), join(root, "dangling.txt")); + symlinkSync(join(root, "inner"), join(root, "inner-link")); + symlinkSync(root, join(base, "root-link")); + const ws = new Workspace(root); + + it("refuses to read through a link to outside (directory and file links)", async () => { + await expect(ws.read("out-link/secret.txt")).rejects.toMatchObject({ code: "outside_workspace" }); + await expect(ws.read("secret-link.txt")).rejects.toMatchObject({ code: "outside_workspace" }); + expect(await ws.exists("out-link/secret.txt")).toBe(false); + }); + it("refuses to write through a link, including to targets that do not exist yet", async () => { + await expect(ws.write("out-link/a/b/new.txt", "x")).rejects.toMatchObject({ code: "outside_workspace" }); + await expect(ws.write("dangling.txt", "x")).rejects.toMatchObject({ code: "outside_workspace" }); + expect(existsSync(join(outside, "a"))).toBe(false); + expect(existsSync(join(outside, "new-file.txt"))).toBe(false); + }); + it("still allows normal paths, new nested files and links that stay inside", async () => { + expect(await ws.write("新 目录/子/文件.txt", "中文")).toBe("新 目录/子/文件.txt"); + expect((await ws.read("inner-link/ok.txt")).toString()).toBe("ok"); + await expect(ws.read("../outside/secret.txt")).rejects.toMatchObject({ code: "outside_workspace" }); + }); + it("works when the workspace root itself is reached through a link", async () => { + const viaLink = new Workspace(join(base, "root-link")); + expect((await viaLink.read("inner/ok.txt")).toString()).toBe("ok"); + await expect(viaLink.read("out-link/secret.txt")).rejects.toMatchObject({ code: "outside_workspace" }); + }); +}); diff --git a/ui-plugins/product-3d-showcase/tsconfig.json b/ui-plugins/product-3d-showcase/tsconfig.json new file mode 100644 index 00000000..39f7ab60 --- /dev/null +++ b/ui-plugins/product-3d-showcase/tsconfig.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "lib": ["ES2023", "DOM", "DOM.Iterable"], + "strict": true, + "skipLibCheck": true, + "noEmit": true, + "allowImportingTsExtensions": true, + "types": ["node"] + }, + "include": ["src/**/*.ts", "ui/**/*.ts", "test/**/*.ts"] +} diff --git a/ui-plugins/product-3d-showcase/ui/env.d.ts b/ui-plugins/product-3d-showcase/ui/env.d.ts new file mode 100644 index 00000000..4210a464 --- /dev/null +++ b/ui-plugins/product-3d-showcase/ui/env.d.ts @@ -0,0 +1,4 @@ +declare module "*.css" { + const text: string; + export default text; +} diff --git a/ui-plugins/product-3d-showcase/ui/kit.css b/ui-plugins/product-3d-showcase/ui/kit.css new file mode 100644 index 00000000..398bc83a --- /dev/null +++ b/ui-plugins/product-3d-showcase/ui/kit.css @@ -0,0 +1,34 @@ +:root { --bg:#fff; --fg:#1d1f23; --muted:#6b7280; --line:#e5e7eb; --panel:#f7f7f8; --accent:#2563eb; --warn:#b45309; --warnbg:#fef3c7; --bad:#b91c1c; --badbg:#fee2e2; --okbg:#dcfce7; --ok:#15803d; } +[data-theme="dark"] { --bg:#18191b; --fg:#e8e8ea; --muted:#9ca3af; --line:#2e3035; --panel:#222327; --accent:#60a5fa; --warn:#fbbf24; --warnbg:#3b2f10; --bad:#f87171; --badbg:#3b1717; --okbg:#12301d; --ok:#4ade80; } +* { box-sizing: border-box; } +html, body { margin:0; background:var(--bg); color:var(--fg); font:13px/1.45 -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif; } +#root { padding: 12px; } +h1 { font-size: 15px; margin: 0 0 8px; } +h2 { font-size: 13px; margin: 14px 0 6px; color: var(--muted); font-weight: 600; text-transform: none; } +button { font: inherit; border:1px solid var(--line); background:var(--panel); color:var(--fg); border-radius:6px; padding:5px 10px; cursor:pointer; } +button.primary { background:var(--accent); border-color:var(--accent); color:#fff; } +button:disabled { opacity:.5; cursor:default; } +input, select, textarea { font: inherit; color: var(--fg); background: var(--bg); border:1px solid var(--line); border-radius:5px; padding:4px 6px; } +input[type="color"] { padding: 0; width: 32px; height: 26px; } +input[type="range"] { padding: 0; } +label { display:flex; gap:6px; align-items:center; } +.row { display:flex; gap:8px; align-items:center; flex-wrap:wrap; margin: 6px 0; } +.muted { color: var(--muted); } +.card { border:1px solid var(--line); border-radius:8px; padding:10px; background:var(--panel); margin: 8px 0; } +.grid { display:grid; grid-template-columns:repeat(auto-fill, minmax(150px, 1fr)); gap:8px; } +.thumb { border:1px solid var(--line); border-radius:6px; overflow:hidden; background: var(--bg); cursor:pointer; position:relative; } +.thumb img { width:100%; display:block; aspect-ratio:1; object-fit:contain; background: repeating-conic-gradient(#ddd 0 25%, #fff 0 50%) 50% / 16px 16px; } +.thumb .cap { padding:4px 6px; font-size:12px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; } +.thumb.selected { outline: 2px solid var(--accent); } +.badge { display:inline-block; font-size:11px; padding:1px 6px; border-radius:10px; background:var(--warnbg); color:var(--warn); } +.badge.bad { background: var(--badbg); color: var(--bad); } +.badge.ok { background: var(--okbg); color: var(--ok); } +table.data { border-collapse: collapse; width: 100%; } +table.data td, table.data th { border:1px solid var(--line); padding:3px 6px; text-align:left; vertical-align:top; } +table.data th { background: var(--panel); } +.toast { position: fixed; right: 12px; bottom: 12px; padding: 8px 12px; border-radius: 6px; background: var(--okbg); color: var(--ok); z-index: 10; max-width: 80%; } +.toast.error { background: var(--badbg); color: var(--bad); } +.empty { padding: 24px; text-align:center; color: var(--muted); border: 1px dashed var(--line); border-radius: 8px; } +.busy { opacity:.6; pointer-events:none; } +.split { display:grid; grid-template-columns: minmax(0,1fr) minmax(0,1fr); gap: 10px; } +@media (max-width: 640px) { .split { grid-template-columns: 1fr; } } diff --git a/ui-plugins/product-3d-showcase/ui/kit.ts b/ui-plugins/product-3d-showcase/ui/kit.ts new file mode 100644 index 00000000..b0646f25 --- /dev/null +++ b/ui-plugins/product-3d-showcase/ui/kit.ts @@ -0,0 +1,133 @@ +import { App } from "@modelcontextprotocol/ext-apps"; + +export class ToolError extends Error { + readonly code: string; + constructor(code: string, message: string) { + super(message); + this.code = code; + } +} + +let app: App | undefined; +let connection: Promise | undefined; +let created!: () => void; +const appCreated = new Promise((resolve) => (created = resolve)); +const resultListeners = new Set<(value: Record | undefined, tool?: string) => void>(); +const contextListeners = new Set<() => void>(); + +export function initHost(name: string, version: string) { + app = new App({ name, version }, { availableDisplayModes: ["inline", "fullscreen"] }); + app.ontoolresult = (result) => { + const content = result.structuredContent as Record | undefined; + resultListeners.forEach((listener) => listener(content)); + }; + app.onhostcontextchanged = () => contextListeners.forEach((listener) => listener()); + created(); + return ready(); +} + +export function ready(): Promise { + if (!app) return appCreated.then(() => ready()); + return (connection ??= app.connect().then(() => contextListeners.forEach((listener) => listener()))); +} + +export function onToolResult(listener: (value: Record | undefined) => void) { + resultListeners.add(listener); +} + +export function onHostContext(listener: () => void) { + contextListeners.add(listener); +} + +export function hostContext() { + return app?.getHostContext(); +} + +export function locale(): "zh" | "en" { + const fromHost = (app?.getHostContext()?.locale as string | undefined) ?? navigator.language ?? "en"; + return /^zh/i.test(fromHost) ? "zh" : "en"; +} + +export async function call>(name: string, args: Record = {}, timeout = 300_000): Promise { + await ready(); + let result; + try { + result = await app!.callServerTool({ name, arguments: args }, { timeout }); + } catch (error) { + throw new ToolError("host_error", error instanceof Error ? error.message : String(error)); + } + const content = result.structuredContent as Record | undefined; + const error = content?.error as { code?: string; message?: string } | undefined; + if (result.isError || error) { + const text = (result.content?.[0] as { text?: string } | undefined)?.text; + throw new ToolError(error?.code ?? "tool_error", error?.message ?? text ?? "The tool failed."); + } + return (content ?? {}) as T; +} + +/** 读取插件资源(二进制)。 */ +export async function readBlob(uri: string): Promise { + await ready(); + const result = await app!.readServerResource({ uri }); + const first = result.contents[0] as { blob?: string; text?: string } | undefined; + if (typeof first?.blob !== "string") throw new ToolError("host_error", first?.text?.slice(0, 300) ?? `Empty resource ${uri}`); + return base64ToBytes(first.blob); +} + +export function base64ToBytes(base64: string): Uint8Array { + const binary = atob(base64); + const bytes = new Uint8Array(binary.length); + for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index); + return bytes; +} + +/** 由用户点击触发:把一句话发到对话里交给 Agent。 */ +export async function sendMessage(text: string) { + await ready(); + return app!.sendMessage({ role: "user", content: [{ type: "text", text }] }); +} + +export async function updateContext(text: string) { + await ready(); + return app!.updateModelContext({ content: [{ type: "text", text }] }); +} + +type Child = Node | string | number | null | undefined | false; +/** 极简 DOM 构建器。 */ +export function h( + tag: K, + props: Record = {}, + ...children: (Child | Child[])[] +): HTMLElementTagNameMap[K] { + const element = document.createElement(tag); + for (const [key, value] of Object.entries(props)) { + if (value === undefined || value === null || value === false) continue; + if (key.startsWith("on") && typeof value === "function") element.addEventListener(key.slice(2).toLowerCase(), value as EventListener); + else if (key === "class") element.className = String(value); + else if (key === "style" && typeof value === "object") Object.assign(element.style, value); + else if (key === "value" || (key in element && typeof value !== "string")) (element as any)[key] = value; + else element.setAttribute(key, value === true ? "" : String(value)); + } + for (const child of children.flat()) { + if (child === null || child === undefined || child === false) continue; + element.append(child instanceof Node ? child : String(child)); + } + return element; +} + +export function toast(message: string, kind: "ok" | "error" = "ok") { + const node = h("div", { class: `toast ${kind}`, role: "status" }, message); + document.body.append(node); + setTimeout(() => node.remove(), kind === "error" ? 6000 : 3000); +} + +/** 主题:跟随宿主的浅色 / 深色。 */ +export function applyTheme() { + const theme = (app?.getHostContext()?.theme as string | undefined) ?? "light"; + document.documentElement.dataset.theme = theme === "dark" ? "dark" : "light"; +} + +/** replaceChildren,跳过 null / false。 */ +export function put(element: Element, ...children: (Node | string | null | undefined | false)[]) { + element.replaceChildren(...(children.filter((c) => c !== null && c !== undefined && c !== false) as (Node | string)[])); +} diff --git a/ui-plugins/product-3d-showcase/ui/main.ts b/ui-plugins/product-3d-showcase/ui/main.ts new file mode 100644 index 00000000..4680d45b --- /dev/null +++ b/ui-plugins/product-3d-showcase/ui/main.ts @@ -0,0 +1,284 @@ +import css from "./kit.css"; +import panelCss from "./panel.css"; +import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js"; +import { applyTheme, call, h, initHost, locale, onHostContext, onToolResult, put, toast, updateContext } from "./kit.ts"; +import { ANGLE_PRESETS, loadModel, Studio, type Angle } from "./scene.ts"; +import { muxWebm, type Frame } from "./webm.ts"; + +const style = document.createElement("style"); +style.textContent = css + panelCss; +document.head.append(style); + +interface Settings { version: 1; model: string; title: string; angles: Angle[]; lighting: "studio" | "soft" | "dramatic"; background: string; shadow: boolean; exposure: number; size: number; video: { enabled: boolean; seconds: number; size: number; pitch: number }; viewer: boolean; output: string } +type Info = Record; +const T = (cn: string, en: string) => (locale() === "zh" ? cn : en); +const state: { s?: Settings; info?: Info; models: string[]; thumbs: Map; dirty: boolean; done?: string[]; progress?: string; loadedModel?: string } = { models: [], thumbs: new Map(), dirty: false }; +const root = document.getElementById("root")!; + +// 预览(可拖动)与离屏渲染(导出用)各一个 WebGL 画布。 +const previewCanvas = h("canvas", {}) as HTMLCanvasElement; +const preview = new Studio(previewCanvas); +const controls = new OrbitControls(preview.camera, previewCanvas); +controls.enableDamping = true; +controls.maxPolarAngle = Math.PI / 2 - 0.01; +const shotCanvas = h("canvas", { class: "offscreen" }) as HTMLCanvasElement; +document.body.append(shotCanvas); +const shot = new Studio(shotCanvas); +const hud = h("div", { class: "hud" }); + +const look = (s: Settings) => ({ lighting: s.lighting, background: s.background, shadow: s.shadow, exposure: s.exposure }); +function currentAngle(): Angle { + const d = preview.camera.position.clone().sub(controls.target); + const dist = d.length(); + const fov = (preview.camera.fov * Math.PI) / 180; + const fit = Math.min(fov, 2 * Math.atan(Math.tan(fov / 2) * preview.camera.aspect)); + const base = (preview.radius / Math.sin(fit / 2)) * 1.08; + const r = (x: number) => Math.round(x); + return { name: "custom", yaw: r((Math.atan2(d.x, d.z) * 180) / Math.PI), pitch: r((Math.asin(d.y / dist) * 180) / Math.PI), zoom: Math.round((base / dist) * 100) / 100 }; +} +function viewAngle(a: Angle) { + const w = previewCanvas.clientWidth || 640, hh = previewCanvas.clientHeight || 480; + preview.renderer.setSize(w, hh, false); + preview.frame(a, w / hh); + controls.target.copy(preview.center); + controls.update(); +} +let lastSize = ""; +function loop() { + const w = previewCanvas.clientWidth, hh = previewCanvas.clientHeight; + if (w && hh) { + if (`${w}x${hh}` !== lastSize) { lastSize = `${w}x${hh}`; preview.renderer.setPixelRatio(Math.min(2, devicePixelRatio)); preview.renderer.setSize(w, hh, false); preview.camera.aspect = w / hh; preview.camera.updateProjectionMatrix(); } + controls.update(); + preview.renderer.render(preview.scene, preview.camera); + const a = currentAngle(); + hud.textContent = `yaw ${a.yaw}° · pitch ${a.pitch}° · zoom ${a.zoom}`; + } + requestAnimationFrame(loop); +} + +async function busy(work: () => Promise, label = ""): Promise { + root.classList.add("busy"); + state.progress = label; + updateStatus(); + try { return await work(); } catch (error) { toast(error instanceof Error ? error.message : String(error), "error"); return undefined; } finally { root.classList.remove("busy"); state.progress = ""; updateStatus(); } +} +function updateStatus() { const st = document.getElementById("status"); if (st) st.textContent = state.progress ?? ""; } + +async function ensureModel(s: Settings) { + if (state.loadedModel === s.model) return; + // model_data comes in parts (a large model in one message would exceed the host's limit). + type Part = { format: "glb" | "gltf"; data: string; offset: number; total: number }; + let part = await call("model_data", { model: s.model, offset: 0 }, 300_000); + const format = part.format; + const parts = [part.data]; + let got = part.data.length; + while (got < (part.total ?? got) && part.data.length > 0) { + part = await call("model_data", { model: s.model, offset: got }, 300_000); + parts.push(part.data); + got += part.data.length; + } + const m = { format, data: parts.join("") }; + const [a, b] = await Promise.all([loadModel(m), loadModel(m)]); + preview.setModel(a); + shot.setModel(b); + state.loadedModel = s.model; + viewAngle(s.angles[0] ?? ANGLE_PRESETS[0]); +} +function applyLook() { + if (!state.s) return; + preview.setLook(look(state.s)); + shot.setLook(look(state.s)); +} + +function renderShot(a: Angle, size: number, background?: string): HTMLCanvasElement { + if (background) shot.setLook({ ...look(state.s!), background }); + shot.frame(a, 1); + const c = shot.render(size, size); + if (background) shot.setLook(look(state.s!)); + return c; +} +const toB64 = (blob: Blob) => blob.arrayBuffer().then((b) => { const u = new Uint8Array(b); let s = ""; for (let i = 0; i < u.length; i += 0x8000) s += String.fromCharCode(...u.subarray(i, i + 0x8000)); return btoa(s); }); +const canvasPng = (c: HTMLCanvasElement) => new Promise((res, rej) => c.toBlob((b) => (b ? res(b) : rej(new Error("PNG encode failed"))), "image/png")); + +async function refreshThumbs() { + const s = state.s; + if (!s || state.loadedModel !== s.model) return; + state.thumbs.clear(); + for (const a of s.angles) state.thumbs.set(a.name, renderShot(a, 240).toDataURL("image/png")); + renderAngles(); +} + +const FPS = 30; +/** 逐帧渲染并用 WebCodecs 编码(与渲染速度无关,帧数精确);没有 WebCodecs 时退回实时 MediaRecorder。 */ +async function recordTurntable(s: Settings): Promise { + const size = s.video.size; + const bg = s.background === "transparent" ? "#ffffff" : undefined; // WebM 不保留透明,透明背景时视频用白底 + if (bg) shot.setLook({ ...look(s), background: bg }); + shot.renderer.setPixelRatio(1); + shot.renderer.setSize(size, size, false); + const total = Math.round(s.video.seconds * FPS); + const draw = (k: number) => { shot.frame({ name: "spin", yaw: (360 * k) / total, pitch: s.video.pitch, zoom: 1 }, 1); shot.renderer.render(shot.scene, shot.camera); }; + const progress = (k: number) => { state.progress = T(`渲染 360° 视频… ${Math.round((k / total) * 100)}%`, `Rendering 360° video… ${Math.round((k / total) * 100)}%`); updateStatus(); }; + try { + if (typeof VideoEncoder !== "undefined") { + for (const [codec, name] of [["vp09.00.40.08", "V_VP9"], ["vp8", "V_VP8"]] as const) { + const config = { codec, width: size, height: size, bitrate: Math.round(size * size * FPS * 0.1), framerate: FPS }; + if (!(await VideoEncoder.isConfigSupported(config)).supported) continue; + const frames: Frame[] = []; + let failure: unknown; + const encoder = new VideoEncoder({ output: (chunk) => { const data = new Uint8Array(chunk.byteLength); chunk.copyTo(data); frames.push({ data, ms: chunk.timestamp / 1000, key: chunk.type === "key" }); }, error: (e) => (failure = e) }); + encoder.configure(config); + for (let k = 0; k < total; k++) { + draw(k); + const frame = new VideoFrame(shotCanvas, { timestamp: Math.round((k * 1e6) / FPS), duration: Math.round(1e6 / FPS) }); + encoder.encode(frame, { keyFrame: k % (FPS * 2) === 0 }); + frame.close(); + if (encoder.encodeQueueSize > 4) await new Promise((r) => setTimeout(r, 0)); + if (k % 5 === 0) { progress(k); await new Promise((r) => requestAnimationFrame(r)); } + if (failure) throw failure; + } + await encoder.flush(); + encoder.close(); + if (failure) throw failure; + return new Blob([muxWebm(frames, size, size, name, (total * 1000) / FPS) as BlobPart], { type: "video/webm" }); + } + } + // 退路:实时录制(慢机器上帧数可能偏少) + const stream = shotCanvas.captureStream(FPS); + const type = ["video/webm;codecs=vp9", "video/webm;codecs=vp8", "video/webm"].find((t) => MediaRecorder.isTypeSupported(t)) ?? "video/webm"; + const rec = new MediaRecorder(stream, { mimeType: type, videoBitsPerSecond: Math.round(size * size * FPS * 0.1) }); + const chunks: Blob[] = []; + rec.ondataavailable = (e) => e.data.size && chunks.push(e.data); + const stopped = new Promise((r) => (rec.onstop = () => r())); + rec.start(250); + const t0 = performance.now(); + await new Promise((done) => { + const step = () => { const t = Math.min(1, (performance.now() - t0) / (s.video.seconds * 1000)); draw(t * total); progress(t * total); if (t < 1) requestAnimationFrame(step); else done(); }; + requestAnimationFrame(step); + }); + rec.stop(); + await stopped; + stream.getTracks().forEach((t) => t.stop()); + return new Blob(chunks, { type: "video/webm" }); + } finally { + if (bg) shot.setLook(look(s)); + } +} + +async function exportAll(s: Settings) { + await ensureModel(s); + applyLook(); + const files: string[] = []; + for (const [i, a] of s.angles.entries()) { + state.progress = T(`渲染 ${a.name}(${i + 1}/${s.angles.length})…`, `Rendering ${a.name} (${i + 1}/${s.angles.length})…`); + updateStatus(); + const r = await call<{ path: string }>("save_output", { settings: s, name: `${a.name}.png`, data: await toB64(await canvasPng(renderShot(a, s.size))) }); + files.push(r.path); + } + if (s.video.enabled) { + const blob = await recordTurntable(s); + state.progress = T("保存视频…", "Saving video…"); + updateStatus(); + const v = await call<{ path: string; mp4?: string; note?: string }>("save_output", { settings: s, name: "turntable.webm", data: await toB64(blob) }, 600_000); + files.push(v.path, ...(v.mp4 ? [v.mp4] : [])); + if (v.note) toast(v.note); + } + if (s.viewer) { + state.progress = T("写网页展示…", "Writing web viewer…"); + updateStatus(); + files.push(...(await call<{ files: string[] }>("save_viewer", { settings: s }, 300_000)).files.filter((f) => f.endsWith("index.html"))); + } + state.done = files; + render(); + toast(T(`已导出 ${files.length} 个文件`, `Exported ${files.length} files`)); + await updateContext(`Product 3D Showcase exported ${s.title}: ${files.join(", ")}`).catch(() => undefined); +} + +function load(v: Record) { + state.s = v.settings as Settings; + state.info = v.info as Info; + state.dirty = false; + state.done = undefined; + render(); + return busy(async () => { await ensureModel(state.s!); applyLook(); await refreshThumbs(); }, T("加载模型…", "Loading model…")); +} +onToolResult((v) => { + if (!v) return; + if (v.kind === "settings") void load(v); + if (v.kind === "export") void load(v).then(() => busy(() => exportAll(state.s!), T("导出中…", "Exporting…"))); +}); + +function changed(thumbs = true) { + state.dirty = true; + const b = document.getElementById("save") as HTMLButtonElement | null; + if (b) b.disabled = false; + applyLook(); + if (thumbs) void refreshThumbs(); +} + +function renderAngles() { + const box = document.getElementById("angles"); + const s = state.s; + if (!box || !s) return; + put(box, ...s.angles.map((a, i) => h("div", { class: "ang" }, + h("img", { src: state.thumbs.get(a.name) ?? "", alt: a.name, title: T("点击在预览里查看", "Click to view in the preview"), onclick: () => viewAngle(a) }), + h("div", { class: "row" }, + h("input", { type: "text", value: a.name, onchange: (e: Event) => { a.name = (e.target as HTMLInputElement).value.trim().replace(/\s+/g, "-") || a.name; changed(); } }), + h("button", { title: T("删除", "Remove"), onclick: () => { s.angles.splice(i, 1); changed(); } }, "✕")), + h("div", { class: "muted" }, `${a.yaw}° / ${a.pitch}°${a.zoom !== 1 ? ` ×${a.zoom}` : ""}`)))); +} + +function render() { + applyTheme(); + const s = state.s; + const toolbar = h("div", { class: "toolbar" }, + h("b", {}, T("产品 3D 展示", "Product 3D Showcase")), + h("select", { onchange: (e: Event) => { const v = (e.target as HTMLSelectElement).value; if (v) void busy(async () => load(await call("showcase_open", { model: v }))); } }, + h("option", { value: "" }, s ? `📦 ${s.model}` : T("选择 glTF / GLB 模型…", "Choose a glTF / GLB model…")), + ...state.models.map((f) => h("option", { value: f }, f))), + h("span", { id: "status", class: "muted" }, state.progress ?? ""), + h("span", { class: "spacer" }), + s ? h("button", { id: "save", disabled: !state.dirty, onclick: () => void busy(async () => { await load(await call("showcase_save", { settings: s })); toast(T("已保存", "Saved")); }) }, T("保存", "Save")) : null, + s ? h("button", { class: "primary", onclick: () => void busy(async () => { await call("showcase_save", { settings: s }); state.dirty = false; await exportAll(s); }, T("导出中…", "Exporting…")) }, T("导出全部", "Export all")) : null); + if (!s) { + put(root, toolbar, h("div", { class: "empty" }, T("选择一个 .glb / .gltf 产品模型,或对 Agent 说:“用 bottle.glb 做一套白底产品图:正面、左右 45°、侧面、背面,再出一段 6 秒的 360° 旋转视频和网页 3D 展示”。", "Choose a .glb / .gltf product model, or ask the agent: make white-background product shots of bottle.glb — front, 45° left and right, side, back — plus a 6-second 360° video and a web 3D viewer."))); + return; + } + const num = (label: string, value: number, min: number, max: number, step: number, set: (v: number) => void, thumbs = true) => + h("label", {}, h("span", {}, label), h("input", { type: "number", value, min, max, step, onchange: (e: Event) => { set(Number((e.target as HTMLInputElement).value)); changed(thumbs); } })); + const bgSel = s.background === "transparent" ? "transparent" : s.background === "#ffffff" ? "#ffffff" : "custom"; + const settings = h("div", { class: "settings" }, + h("label", {}, h("span", {}, T("标题", "Title")), h("input", { type: "text", value: s.title, onchange: (e: Event) => { s.title = (e.target as HTMLInputElement).value; changed(false); } })), + h("label", {}, h("span", {}, T("灯光", "Lighting")), h("select", { onchange: (e: Event) => { s.lighting = (e.target as HTMLSelectElement).value as Settings["lighting"]; changed(); } }, ...[["studio", T("影棚", "Studio")], ["soft", T("柔光", "Soft")], ["dramatic", T("戏剧", "Dramatic")]].map(([v, l]) => h("option", { value: v, selected: s.lighting === v }, l)))), + h("label", {}, h("span", {}, T("背景", "Background")), + h("select", { onchange: (e: Event) => { const v = (e.target as HTMLSelectElement).value; s.background = v === "custom" ? "#f1f5f9" : v; changed(); render(); } }, ...[["#ffffff", T("白色", "White")], ["transparent", T("透明", "Transparent")], ["custom", T("自定义", "Custom")]].map(([v, l]) => h("option", { value: v, selected: bgSel === v }, l))), + bgSel === "custom" ? h("input", { type: "color", value: s.background, onchange: (e: Event) => { s.background = (e.target as HTMLInputElement).value; changed(); } }) : null), + h("label", {}, h("span", {}, T("地面阴影", "Shadow")), h("input", { type: "checkbox", checked: s.shadow, onchange: (e: Event) => { s.shadow = (e.target as HTMLInputElement).checked; changed(); } })), + h("label", {}, h("span", {}, T("曝光", "Exposure")), h("input", { type: "range", min: 0.3, max: 2.5, step: 0.05, value: s.exposure, onchange: (e: Event) => { s.exposure = Number((e.target as HTMLInputElement).value); changed(); } })), + num(T("图片尺寸", "Image px"), s.size, 256, 4096, 100, (v) => (s.size = v), false), + h("label", {}, h("span", {}, T("360° 视频", "360° video")), h("input", { type: "checkbox", checked: s.video.enabled, onchange: (e: Event) => { s.video.enabled = (e.target as HTMLInputElement).checked; changed(false); render(); } })), + s.video.enabled ? num(T("视频秒数", "Seconds"), s.video.seconds, 2, 30, 1, (v) => (s.video.seconds = v), false) : null, + s.video.enabled ? num(T("视频尺寸", "Video px"), s.video.size, 360, 2160, 2, (v) => (s.video.size = v), false) : null, + h("label", {}, h("span", {}, T("网页展示", "Web viewer")), h("input", { type: "checkbox", checked: s.viewer, onchange: (e: Event) => { s.viewer = (e.target as HTMLInputElement).checked; changed(false); } })), + h("label", {}, h("span", {}, T("输出", "Output")), h("input", { type: "text", value: s.output, onchange: (e: Event) => { s.output = (e.target as HTMLInputElement).value; changed(false); } })), + h("div", { class: "info muted" }, `${state.info?.meshes ?? "?"} mesh · ${state.info?.materials ?? "?"} mat · ${state.info?.textures ?? "?"} tex · ${state.info?.megabytes ?? "?"} MB`), + h("div", { class: "small muted" }, T("拖动预览选角度,点“+ 加入这个角度”。透明背景只用于图片,视频用白底。", "Drag the preview to pick a view and press “+ Add this view”. Transparent background applies to images; the video uses white."))); + const presetSel = h("select", { onchange: (e: Event) => { const v = (e.target as HTMLSelectElement).value; const p = ANGLE_PRESETS.find((a) => a.name === v); if (p && !s.angles.some((a) => a.name === p.name)) { s.angles.push({ ...p }); changed(); render(); } } }, + h("option", { value: "" }, T("+ 预设角度…", "+ Preset angle…")), ...ANGLE_PRESETS.map((a) => h("option", { value: a.name }, a.name))); + const addView = h("button", { class: "add primary", onclick: () => { const a = currentAngle(); let n = 1; while (s.angles.some((x) => x.name === `view-${n}`)) n++; s.angles.push({ ...a, name: `view-${n}` }); changed(); render(); } }, T("+ 加入这个角度", "+ Add this view")); + put(root, toolbar, + state.done ? h("div", { class: "card done" }, h("b", {}, T(`已导出到 ${s.output}/`, `Exported to ${s.output}/`)), ...state.done.map((f) => h("div", { class: "small" }, f))) : null, + h("div", { class: "layout" }, + h("div", {}, h("div", { class: "stage" }, previewCanvas, hud, addView), h("div", { class: "toolbar", style: "border:0;margin:6px 0 0" }, h("b", {}, T(`角度(${s.angles.length})`, `Angles (${s.angles.length})`)), presetSel), h("div", { id: "angles", class: "angles" })), + settings)); + lastSize = ""; + renderAngles(); +} + +onHostContext(() => render()); +render(); +requestAnimationFrame(loop); +void initHost("product-3d-showcase", "0.1.0").then(async () => { + state.models = (await call<{ models: string[] }>("workspace_files").catch(() => ({ models: [] }))).models; + render(); +}); diff --git a/ui-plugins/product-3d-showcase/ui/panel.css b/ui-plugins/product-3d-showcase/ui/panel.css new file mode 100644 index 00000000..f2665ae9 --- /dev/null +++ b/ui-plugins/product-3d-showcase/ui/panel.css @@ -0,0 +1,22 @@ +.toolbar { display:flex; gap:8px; align-items:center; flex-wrap:wrap; padding-bottom:8px; border-bottom:1px solid var(--line); margin-bottom:8px; } +.spacer { flex:1; } +.layout { display:grid; grid-template-columns: minmax(0,1fr) 250px; gap: 12px; align-items:start; } +@media (max-width: 820px) { .layout { grid-template-columns: 1fr; } } +.stage { position:relative; border:1px solid var(--line); border-radius:10px; overflow:hidden; background: repeating-conic-gradient(#e5e7eb 0 25%, #f8fafc 0 50%) 0 0/16px 16px; } +.stage canvas { width:100%; aspect-ratio: 4/3; display:block; touch-action:none; } +.stage .hud { position:absolute; left:8px; bottom:8px; font-size:11px; background:rgba(15,23,42,.65); color:#fff; padding:2px 6px; border-radius:6px; } +.stage .add { position:absolute; right:8px; bottom:8px; } +.angles { display:grid; grid-template-columns: repeat(auto-fill, minmax(120px,1fr)); gap:8px; margin-top:8px; } +.ang { border:1px solid var(--line); border-radius:8px; padding:4px; font-size:11px; background: var(--panel); } +.ang img { width:100%; aspect-ratio:1; object-fit:contain; display:block; border-radius:6px; background: repeating-conic-gradient(#e5e7eb 0 25%, #f8fafc 0 50%) 0 0/12px 12px; cursor:pointer; } +.ang .row { display:flex; gap:4px; align-items:center; margin-top:3px; } +.ang input { width:100%; min-width:0; font-size:11px; } +.settings { display:flex; flex-direction:column; gap:6px; font-size:12px; } +.settings label { display:flex; gap:6px; align-items:center; } +.settings label > span { width:72px; color: var(--muted); flex:none; } +.settings select, .settings input[type=text], .settings input[type=number] { flex:1; min-width:0; } +.settings input[type=range] { flex:1; } +.info { font-size:11px; } +.done a { display:block; font-size:12px; } +.small { font-size: 11px; } +.offscreen { position:fixed; left:-20000px; top:0; } diff --git a/ui-plugins/product-3d-showcase/ui/scene.ts b/ui-plugins/product-3d-showcase/ui/scene.ts new file mode 100644 index 00000000..f098a74e --- /dev/null +++ b/ui-plugins/product-3d-showcase/ui/scene.ts @@ -0,0 +1,142 @@ +// 面板与导出的查看器共用:影棚灯光、地面阴影、按包围盒自动取景。 +import * as THREE from "three"; +import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js"; +import { RoomEnvironment } from "three/examples/jsm/environments/RoomEnvironment.js"; + +export type Lighting = "studio" | "soft" | "dramatic"; +export interface Look { lighting: Lighting; background: string; shadow: boolean; exposure: number } +export interface Angle { name: string; yaw: number; pitch: number; zoom: number } + +export const ANGLE_PRESETS: Angle[] = [ + { name: "front", yaw: 0, pitch: 8, zoom: 1 }, + { name: "three-quarter-left", yaw: -35, pitch: 15, zoom: 1 }, + { name: "three-quarter-right", yaw: 35, pitch: 15, zoom: 1 }, + { name: "side", yaw: 90, pitch: 5, zoom: 1 }, + { name: "back", yaw: 180, pitch: 10, zoom: 1 }, + { name: "top", yaw: 20, pitch: 60, zoom: 1 }, +]; + +/** + * 面板的 CSP 禁止 fetch(connect-src 'none'),而 GLTFLoader 默认用 fetch 读 data:/blob: 资源。 + * 这里改用 加载贴图(img-src 允许 data:/blob:),并直接解码内联的 data: buffer。 + */ +function noFetch(parser: any) { + parser.textureLoader = new THREE.TextureLoader(parser.options.manager); + const decoded = new Map(); + return { + name: "zcode_no_fetch", + loadBufferView(index: number) { + const view = parser.json.bufferViews[index]; + const buffer = parser.json.buffers[view.buffer]; + if (!buffer?.uri?.startsWith("data:")) return null; + if (!decoded.has(view.buffer)) { + const b64 = buffer.uri.slice(buffer.uri.indexOf(",") + 1); + decoded.set(view.buffer, Uint8Array.from(atob(b64), (c) => c.charCodeAt(0)).buffer); + } + const start = view.byteOffset ?? 0; + return Promise.resolve(decoded.get(view.buffer)!.slice(start, start + view.byteLength)); + }, + }; +} + +export function loadModel(data: { format: "glb" | "gltf"; data: string }): Promise { + const loader = new GLTFLoader().register(noFetch); + const payload: ArrayBuffer | string = data.format === "glb" ? Uint8Array.from(atob(data.data), (c) => c.charCodeAt(0)).buffer : data.data; + return new Promise((resolve, reject) => loader.parse(payload, "", (g) => resolve(g.scene), (e) => reject(e instanceof Error ? e : new Error(String((e as any)?.message ?? e))))); +} + +export class Studio { + renderer: THREE.WebGLRenderer; + scene = new THREE.Scene(); + camera = new THREE.PerspectiveCamera(30, 1, 0.01, 1000); + root = new THREE.Group(); + ground: THREE.Mesh; + lights = new THREE.Group(); + size = new THREE.Vector3(1, 1, 1); + center = new THREE.Vector3(); + radius = 1; + private env?: THREE.Texture; + + constructor(canvas?: HTMLCanvasElement) { + this.renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true, preserveDrawingBuffer: true }); + this.renderer.outputColorSpace = THREE.SRGBColorSpace; + this.renderer.toneMapping = THREE.ACESFilmicToneMapping; + this.renderer.shadowMap.enabled = true; + this.renderer.shadowMap.type = THREE.PCFSoftShadowMap; + const pmrem = new THREE.PMREMGenerator(this.renderer); + this.env = pmrem.fromScene(new RoomEnvironment(), 0.04).texture; + this.scene.environment = this.env; + this.ground = new THREE.Mesh(new THREE.PlaneGeometry(1, 1), new THREE.ShadowMaterial({ opacity: 0.22 })); + this.ground.rotation.x = -Math.PI / 2; + this.ground.receiveShadow = true; + this.scene.add(this.root, this.ground, this.lights); + } + + /** 放入模型:居中、底面贴地,所有网格投射阴影。 */ + setModel(model: THREE.Object3D) { + this.root.clear(); + const box = new THREE.Box3().setFromObject(model); + const c = box.getCenter(new THREE.Vector3()); + model.position.sub(new THREE.Vector3(c.x, box.min.y, c.z)); + model.traverse((o) => { + const m = o as THREE.Mesh; + if (m.isMesh) { m.castShadow = true; m.receiveShadow = true; } + }); + this.root.add(model); + box.setFromObject(this.root); + box.getSize(this.size); + box.getCenter(this.center); + this.radius = Math.max(1e-3, box.getBoundingSphere(new THREE.Sphere()).radius); + this.ground.scale.setScalar(this.radius * 12); + } + + setLook(look: Look) { + this.renderer.toneMappingExposure = look.exposure; + this.lights.clear(); + const r = this.radius; + const key = new THREE.DirectionalLight(0xffffff, look.lighting === "dramatic" ? 3.2 : look.lighting === "soft" ? 1.2 : 2.2); + key.position.set(r * 2.2, r * 4, r * 2.5); + key.castShadow = look.shadow; + key.shadow.mapSize.set(2048, 2048); + const cam = key.shadow.camera as THREE.OrthographicCamera; + Object.assign(cam, { left: -r * 2, right: r * 2, top: r * 2, bottom: -r * 2, near: 0.01, far: r * 12 }); + cam.updateProjectionMatrix(); + key.shadow.radius = look.lighting === "soft" ? 8 : 4; + key.shadow.bias = -0.0005; + key.target = this.root; + this.lights.add(key); + if (look.lighting !== "dramatic") { + const fill = new THREE.DirectionalLight(0xffffff, look.lighting === "soft" ? 0.9 : 0.6); + fill.position.set(-r * 3, r * 1.5, r * 2); + this.lights.add(fill); + } + const rim = new THREE.DirectionalLight(0xffffff, look.lighting === "dramatic" ? 2.5 : 0.8); + rim.position.set(-r, r * 2, -r * 3); + this.lights.add(rim); + this.scene.environmentIntensity = look.lighting === "dramatic" ? 0.35 : look.lighting === "soft" ? 1.1 : 0.8; + this.ground.visible = look.shadow; + if (look.background === "transparent") { this.scene.background = null; this.renderer.setClearColor(0x000000, 0); } + else { this.scene.background = new THREE.Color(look.background); this.renderer.setClearColor(look.background, 1); } + } + + /** 按角度取景:相机绕模型中心,距离让包围球正好装进画面。 */ + frame(angle: Angle, aspect: number) { + this.camera.aspect = aspect; + const fov = (this.camera.fov * Math.PI) / 180; + const fit = Math.min(fov, 2 * Math.atan(Math.tan(fov / 2) * aspect)); + const dist = (this.radius / Math.sin(fit / 2)) * 1.08 / angle.zoom; + const yaw = (angle.yaw * Math.PI) / 180, pitch = (angle.pitch * Math.PI) / 180; + this.camera.position.set(this.center.x + dist * Math.sin(yaw) * Math.cos(pitch), this.center.y + dist * Math.sin(pitch), this.center.z + dist * Math.cos(yaw) * Math.cos(pitch)); + this.camera.near = dist / 100; + this.camera.far = dist * 10; + this.camera.lookAt(this.center); + this.camera.updateProjectionMatrix(); + } + + render(width: number, height: number) { + this.renderer.setPixelRatio(1); + this.renderer.setSize(width, height, false); + this.renderer.render(this.scene, this.camera); + return this.renderer.domElement; + } +} diff --git a/ui-plugins/product-3d-showcase/ui/viewer.ts b/ui-plugins/product-3d-showcase/ui/viewer.ts new file mode 100644 index 00000000..a8c9b36d --- /dev/null +++ b/ui-plugins/product-3d-showcase/ui/viewer.ts @@ -0,0 +1,34 @@ +// 导出的网页展示包:index.html + viewer.js(本文件)+ model.js(window.SHOWCASE = {model, look, title})。 +import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js"; +import { loadModel, Studio } from "./scene.ts"; + +declare global { interface Window { SHOWCASE: { model: { format: "glb" | "gltf"; data: string }; look: any; title: string; autoRotate: boolean } } } + +async function main() { + const cfg = window.SHOWCASE; + const canvas = document.getElementById("view") as HTMLCanvasElement; + const studio = new Studio(canvas); + studio.setModel(await loadModel(cfg.model)); + studio.setLook(cfg.look); + const resize = () => { + const w = canvas.clientWidth, h = canvas.clientHeight; + studio.renderer.setPixelRatio(Math.min(2, devicePixelRatio)); + studio.renderer.setSize(w, h, false); + studio.frame({ name: "front", yaw: 30, pitch: 15, zoom: 1 }, w / h); + }; + resize(); + const controls = new OrbitControls(studio.camera, canvas); + controls.target.copy(studio.center); + controls.enableDamping = true; + controls.autoRotate = cfg.autoRotate; + controls.autoRotateSpeed = 1.5; + controls.maxPolarAngle = Math.PI / 2 - 0.02; + controls.minDistance = studio.radius * 1.2; + controls.maxDistance = studio.radius * 8; + addEventListener("resize", () => { const t = controls.target.clone(); const p = studio.camera.position.clone(); resize(); studio.camera.position.copy(p); controls.target.copy(t); }); + canvas.addEventListener("pointerdown", () => (controls.autoRotate = false)); + document.getElementById("loading")?.remove(); + const loop = () => { controls.update(); studio.renderer.render(studio.scene, studio.camera); requestAnimationFrame(loop); }; + loop(); +} +main().catch((e) => { const l = document.getElementById("loading"); if (l) l.textContent = `Cannot show the model: ${e?.message ?? e}`; }); diff --git a/ui-plugins/product-3d-showcase/ui/webm.ts b/ui-plugins/product-3d-showcase/ui/webm.ts new file mode 100644 index 00000000..38cc40e2 --- /dev/null +++ b/ui-plugins/product-3d-showcase/ui/webm.ts @@ -0,0 +1,34 @@ +// 极简 WebM(Matroska)封装:一条 VP8/VP9 视频轨,供 WebCodecs 逐帧编码的输出使用。 +type Part = Uint8Array; +const enc = new TextEncoder(); +function id(n: number): Part { const b: number[] = []; while (n > 0) { b.unshift(n & 0xff); n = Math.floor(n / 256); } return Uint8Array.from(b); } +function size(n: number): Part { const b = new Uint8Array(8); b[0] = 0x01; for (let i = 7; i > 0; i--) { b[i] = n & 0xff; n = Math.floor(n / 256); } return b; } +function uint(n: number): Part { const b: number[] = []; do { b.unshift(n & 0xff); n = Math.floor(n / 256); } while (n > 0); return Uint8Array.from(b); } +function float(n: number): Part { const b = new Uint8Array(8); new DataView(b.buffer).setFloat64(0, n); return b; } +function cat(parts: Part[]): Part { const out = new Uint8Array(parts.reduce((s, p) => s + p.length, 0)); let o = 0; for (const p of parts) { out.set(p, o); o += p.length; } return out; } +const el = (tag: number, ...body: Part[]) => { const b = cat(body); return cat([id(tag), size(b.length), b]); }; + +export interface Frame { data: Uint8Array; ms: number; key: boolean } + +export function muxWebm(frames: Frame[], width: number, height: number, codec: "V_VP8" | "V_VP9", durationMs: number): Uint8Array { + const header = el(0x1a45dfa3, el(0x4286, uint(1)), el(0x42f7, uint(1)), el(0x42f2, uint(4)), el(0x42f3, uint(8)), el(0x4282, enc.encode("webm")), el(0x4287, uint(4)), el(0x4285, uint(2))); + const info = el(0x1549a966, el(0x2ad7b1, uint(1_000_000)), el(0x4489, float(durationMs)), el(0x4d80, enc.encode("product-3d-showcase")), el(0x5741, enc.encode("product-3d-showcase"))); + const tracks = el(0x1654ae6b, el(0xae, el(0xd7, uint(1)), el(0x73c5, uint(1)), el(0x83, uint(1)), el(0x86, enc.encode(codec)), el(0xe0, el(0xb0, uint(width)), el(0xba, uint(height))))); + const clusters: Part[] = []; + let i = 0; + while (i < frames.length) { + const base = frames[i].ms; + const blocks: Part[] = []; + do { + const f = frames[i]; + const head = new Uint8Array(4); + head[0] = 0x81; + new DataView(head.buffer).setInt16(1, Math.round(f.ms - base)); + head[3] = f.key ? 0x80 : 0; + blocks.push(el(0xa3, head, f.data)); + i++; + } while (i < frames.length && !frames[i].key && frames[i].ms - base < 30_000); + clusters.push(el(0x1f43b675, el(0xe7, uint(Math.round(base))), ...blocks)); + } + return cat([header, el(0x18538067, info, tracks, ...clusters)]); +} diff --git a/ui-plugins/product-3d-showcase/vitest.config.ts b/ui-plugins/product-3d-showcase/vitest.config.ts new file mode 100644 index 00000000..27153a26 --- /dev/null +++ b/ui-plugins/product-3d-showcase/vitest.config.ts @@ -0,0 +1,2 @@ +import { defineConfig } from "vitest/config"; +export default defineConfig({ test: { include: ["src/**/*.test.ts", "test/**/*.test.ts"], testTimeout: 120000, hookTimeout: 120000 } });