This commit is contained in:
@@ -33,6 +33,10 @@ The agent supplies real native project, schematic, routed layout, extracted asse
|
||||
|
||||
These software checks do not establish hardware/thermal/RF performance; native DRC is not a replacement for an engineering review. ESP32 acceptance additionally checks model readability, exported previews and electrical intent evidence. Backend validation never alters circuit or layout to obtain a pass.
|
||||
|
||||
New STEP deliveries must preserve the native assembly's surface colors. The appearance check follows applied STEP style references and rejects missing or uniform palettes before native delivery verification; the tool returns repair feedback to the same running agent, without marking the task failed or complete. Native geometry and electrical checks remain mandatory. When rebuilding XCAF assemblies, the agent must preserve color attributes alongside shape/face and instance transforms, then reopen the final exported file to verify appearance. A colored render is not evidence that the STEP is colored.
|
||||
|
||||
Existing deliveries are immutable. For historical colorless STEP files, the website can load a checksum-verified companion OBJ/MTL archive for colored appearance, clearly labeled separately from the original STEP used for mechanical measurements. Optional archive failures fall back to the original STEP and preserve all downloads. The viewer never invents colors. New tasks are instructed to include the genuine final OBJ/MTL archive when available.
|
||||
|
||||
## Operations
|
||||
|
||||
```sh
|
||||
@@ -52,3 +56,41 @@ The root `start.sh` starts the new services. All requests are asynchronous and t
|
||||
5. Review/comment/approve in the UI; record source hash and approval.
|
||||
6. Observe only. No developer design scripts, prompt steering or backend edits after approval. Agent-authored script fixes are allowed and recorded.
|
||||
7. Collect terminal outcome, source hash comparison, native checks, downloadable files, independent STEP parse and visual review. Failed runs are retained and reported honestly. A backend correction requires a new numbered run.
|
||||
|
||||
## Freerouting 无交互部署注意事项(2026-11-11)
|
||||
|
||||
已验证版本:Freerouting 1.9.0(build-date 2023-10-30)。本服务使用通用启动入口 `codex_pcb/freerouting.py`;它只处理参数、进程和输出文件,不指定电路、布局或布线算法。
|
||||
|
||||
### 两类弹窗的原因
|
||||
|
||||
- “Select the design file / Neither the design file nor the directory were specified”:1.9.0 只支持 `-help`,不支持 `--help`。直接执行 `java -jar freerouting.jar --help` 会忽略错误参数并进入等待选文件的窗口。它不是计算进度窗口,也不会自行完成绘板。不要无输入启动 JAR 来探测用法;启动入口的 `--help` 使用 Python 直接输出帮助,不启动 Java。
|
||||
- “Autorouter confirmation / Start Now”:原生程序默认倒计时 20 秒。启动入口固定加入 `-dct 0`,直接启动布线而不显示此确认框。手动运行时可以点击 Start Now;Cancel 或关闭确认框不会启动这一轮布线。
|
||||
- 不要用 `-Djava.awt.headless=true` 替代虚拟显示:该版本仍访问 Java AWT 屏幕和窗口,会抛出 `HeadlessException`。默认通过独立的 `xvfb-run` 运行,既保持 GUI 依赖,又不打扰服务器桌面。`--visible` 只用于人工诊断,仍然跳过倒计时。
|
||||
|
||||
### 新服务器部署与使用
|
||||
|
||||
1. 安装 Python 3、可运行此 JAR 的 Java(1.9.0 官方要求 Java 17)、`xvfb` 和 `xauth`。Debian/Ubuntu 可以安装 `openjdk-17-jre xvfb xauth`;若已有兼容 Java,可保留现有版本。
|
||||
2. 将已验证的 JAR 放到 `$PCB_SESSION_ROOT/resources/freerouting.jar`,或使用 `PCB_FREEROUTING_JAR` / `--jar` 指定绝对路径。未配置运行根目录时,默认仍是当前部署的 `/home/wpz/auto_pcb_2/persistent-runtime`,迁移必须修改它。
|
||||
3. 生产会话应使用批准消息提供的启动命令。下面路径需要按目标服务器替换:
|
||||
|
||||
```sh
|
||||
python3 /path/to/vibemake-pcb-studio/codex_pcb/freerouting.py --help
|
||||
python3 /path/to/vibemake-pcb-studio/codex_pcb/freerouting.py \
|
||||
--input /path/to/task/board.dsn \
|
||||
--output /path/to/task/route-01.ses \
|
||||
--jar /path/to/runtime/resources/freerouting.jar \
|
||||
--timeout 900 -- -mp 30 -mt 1 > /path/to/task/router-01.log 2>&1
|
||||
```
|
||||
|
||||
`--` 后传递已支持的版本参数,例如 `-mp/-mt/-oit/-us/-hr/-is/-inc/-dr/-l` 和 `-im/-da`。AI 仍可选择布线参数和超时;输入、输出、倒计时和帮助参数由启动入口统一管理,未知参数直接报错。默认超时 900 秒,不意味着布线需要固定等待 900 秒。
|
||||
|
||||
入口拒绝缺失输入和已有输出。每次尝试使用新的 SES 文件名,避免把旧结果误当成功;临时输入和 Java/Xvfb 缓存放在输出目录下,结束后清理。输入副本与旧 `.rules`/快照隔离,防止额外恢复确认;需要规则文件时显式传入 `-dr`。超时或取消只清理本次进程组,不执行 `pkill java` 等全局操作,不发布半成品 SES。正常完成后核对 SES 标识并发布到指定路径。
|
||||
|
||||
4. 部署检查:帮助命令应立即退出且不弹窗;缺失输入应立即报错;用隔离的 DSN 副本完成一次真实布线,确认日志没有 20 秒启动等待、桌面没有新增 Freerouting 窗口、SES 能读回。运行 `python3 -m unittest discover -s codex_pcb/tests -p test_freerouting.py -v` 检查启动边界。
|
||||
5. 路由器成功退出不代表整板布通,仍需由会话导入 SES、检查未连网络、运行嘉立创原生 DRC 和最终交付验证。
|
||||
|
||||
更新运行说明或 Python 源码会改变生产冻结哈希。先确认没有活动任务再部署并重启 `vibemake-pcb2-session.service`;旧版本已批准但未完成的任务不能通过改写哈希强行续跑,应保留记录并新建任务。
|
||||
|
||||
版本升级时重新核对参数和弹窗行为,不将 1.9.0 的命令行约定直接套到其他版本。
|
||||
|
||||
依据:[1.9.0 命令行说明](https://github.com/freerouting/freerouting/blob/v1.9.0/README.md#using-the-command-line-arguments)、[参数解析](https://github.com/freerouting/freerouting/blob/v1.9.0/src/main/java/app/freerouting/gui/StartupOptions.java)、[确认框与自动启动](https://github.com/freerouting/freerouting/blob/v1.9.0/src/main/java/app/freerouting/gui/MainApplication.java#L430-L488)。
|
||||
|
||||
@@ -5,3 +5,5 @@ The current implementation is the new **persistent Codex session** service. See
|
||||
The former `backend/easyeda_backend/design_runtime` pipeline and `backend/providers/codex.py` adapter are **not used** by the current website entry. The old PCB2 API systemd service is disabled; no old task is migrated into the new session engine.
|
||||
|
||||
Open <https://192.168.1.200:15182/pcb/?ai=1>.
|
||||
|
||||
部署 Freerouting 前请阅读 [无交互部署注意事项](CODEX-SESSION.md#freerouting-无交互部署注意事项2026-11-11)。生产会话统一使用 `codex_pcb/freerouting.py`,避免错误帮助参数和默认确认倒计时导致停顿。
|
||||
|
||||
+2
-1
@@ -303,7 +303,8 @@ async def approve(tid:str,req:Approval):
|
||||
This server-owned approval authorizes production of the accepted proposal in this same persistent session. Earlier requests to wait applied only to review.
|
||||
Workspace: {workspace(t)}
|
||||
Official API documentation: {workspace(t)}/api-reference/references/_index.md
|
||||
External router: {ROOT}/resources/freerouting.jar (Java installed). Blender: /snap/bin/blender.
|
||||
External router launcher: python3 {SOURCE}/freerouting.py --input <board.dsn> --output <new-result.ses> --jar {ROOT}/resources/freerouting.jar --timeout 900 -- -mp 30 -mt 1
|
||||
Use this launcher for Freerouting, including --help. It validates paths, skips the startup countdown and runs on a private virtual display. Choose routing options and timeout according to the board; do not invoke the JAR directly. Blender: /snap/bin/blender.
|
||||
Now use native Codex tools and pcb_eda to implement, inspect, fix, route, verify and export the real board. You write the design scripts yourself. No fixed backend design pipeline exists. Keep working until pcb_deliver accepts native project, schematic, layout, assembled STEP and real 3D render. Do not edit backend code or use legacy PCB flows. Backend source is frozen for this run.
|
||||
Accepted proposal:\n{p['markdown']}'''
|
||||
schedule(t,prompt,True)
|
||||
|
||||
@@ -4,6 +4,7 @@ import zipfile
|
||||
from pathlib import Path
|
||||
from .storage import workspace, task_dir, inside, digest, write
|
||||
from .eda import verify_native
|
||||
from .step_colors import validate_step_colors
|
||||
|
||||
REQUIRED = {'project','schematic','layout','step','render'}
|
||||
|
||||
@@ -15,6 +16,7 @@ def inspect(path, kind):
|
||||
if kind == 'step':
|
||||
if ext not in {'.stp','.step'} or not data.lstrip().startswith(b'ISO-10303-21;') or b'END-ISO-10303-21;' not in data or b'CARTESIAN_POINT' not in data or b'SHAPE_REPRESENTATION' not in data:
|
||||
raise ValueError('STEP must be an extracted, real ISO10303 model')
|
||||
validate_step_colors(data)
|
||||
elif kind == 'project':
|
||||
if ext not in {'.epro','.epro2','.zip'}:
|
||||
raise ValueError('Editable native EasyEDA project required')
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run the installed Freerouting 1.9.0 without interactive startup dialogs.
|
||||
|
||||
This is a process/argument adapter, not a PCB design or routing algorithm.
|
||||
"""
|
||||
import argparse
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
|
||||
# Version-specific CLI contract. Never pass unknown/help/input/dialog switches
|
||||
# through to Java: 1.9.0 silently ignores some of them and opens an idle GUI.
|
||||
VALUE_OPTIONS = {'-mp', '-mt', '-oit', '-us', '-hr', '-is', '-inc', '-dr', '-l'}
|
||||
FLAG_OPTIONS = {'-im', '-da'}
|
||||
|
||||
|
||||
def router_options(values):
|
||||
values = list(values)
|
||||
if values[:1] == ['--']:
|
||||
values.pop(0)
|
||||
result = []
|
||||
while values:
|
||||
option = values.pop(0)
|
||||
if option in FLAG_OPTIONS:
|
||||
result.append(option)
|
||||
elif option in VALUE_OPTIONS:
|
||||
if not values or values[0].startswith('-'):
|
||||
raise ValueError(f'{option} requires a value')
|
||||
result.extend([option, values.pop(0)])
|
||||
else:
|
||||
raise ValueError(f'Unsupported router option: {option}; use wrapper --help')
|
||||
return result
|
||||
|
||||
|
||||
def stop_process(process):
|
||||
# Java and the private Xvfb belong to this process group only.
|
||||
try:
|
||||
os.killpg(process.pid, signal.SIGTERM)
|
||||
except ProcessLookupError:
|
||||
return
|
||||
try:
|
||||
process.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
pass
|
||||
try:
|
||||
os.killpg(process.pid, signal.SIGKILL)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
process.wait()
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--input', required=True, type=Path, help='Existing DSN input')
|
||||
parser.add_argument('--output', required=True, type=Path, help='New SES output; existing files are refused')
|
||||
default_jar = Path(os.environ.get('PCB_SESSION_ROOT', '/home/wpz/auto_pcb_2/persistent-runtime')) / 'resources/freerouting.jar'
|
||||
parser.add_argument('--jar', type=Path, default=os.environ.get('PCB_FREEROUTING_JAR', str(default_jar)))
|
||||
parser.add_argument('--timeout', type=float, default=900, help='Maximum process seconds (default 900); partial output is not accepted')
|
||||
parser.add_argument('--visible', action='store_true', help='Diagnostic only: use the current desktop instead of private Xvfb')
|
||||
parser.add_argument('router_args', nargs=argparse.REMAINDER, help='After --: Freerouting options, e.g. -mp 30 -mt 1')
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
options = router_options(args.router_args)
|
||||
source, target, jar = args.input.resolve(), args.output.resolve(), args.jar.resolve()
|
||||
if not math.isfinite(args.timeout) or args.timeout <= 0:
|
||||
raise ValueError('--timeout must be a positive finite number')
|
||||
if not source.is_file() or source.suffix.lower() != '.dsn':
|
||||
raise ValueError('--input must be an existing .dsn file')
|
||||
if target.suffix.lower() != '.ses' or target.exists() or args.output.is_symlink():
|
||||
raise ValueError('--output must be a new .ses file (choose a new name for each attempt)')
|
||||
if not jar.is_file():
|
||||
raise ValueError(f'Freerouting JAR not found: {jar}')
|
||||
java = shutil.which('java')
|
||||
if not java:
|
||||
raise ValueError('Java is not installed or not on PATH')
|
||||
xvfb = shutil.which('xvfb-run')
|
||||
if not args.visible and (not xvfb or not shutil.which('Xvfb') or not shutil.which('xauth')):
|
||||
raise ValueError('Install xvfb and xauth for unattended routing; --visible is diagnostic only')
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
with tempfile.TemporaryDirectory(prefix='.freerouting-', dir=target.parent) as temporary:
|
||||
temporary = Path(temporary)
|
||||
home = temporary / 'home'
|
||||
home.mkdir()
|
||||
# Do not auto-load an adjacent old .rules/.bin snapshot and prompt
|
||||
# for confirmation. Explicit -dr remains available to the agent.
|
||||
isolated_source = temporary / 'board.dsn'
|
||||
shutil.copyfile(source, isolated_source)
|
||||
pending = temporary / 'result.ses'
|
||||
command = [java, f'-Duser.home={home}', f'-Djava.io.tmpdir={temporary}', '-jar', str(jar),
|
||||
'-de', str(isolated_source), '-do', str(pending), *options, '-dct', '0', '-da']
|
||||
if not args.visible:
|
||||
command = [xvfb, '-a', '-f', str(temporary / 'Xauthority'), '-s', '-screen 0 1280x1024x24 -nolisten tcp', *command]
|
||||
env = dict(os.environ, TMPDIR=str(temporary))
|
||||
print(f'Freerouting: {source} -> {target}; confirmation disabled; timeout={args.timeout:g}s', flush=True)
|
||||
process = subprocess.Popen(command, env=env, start_new_session=True)
|
||||
try:
|
||||
code = process.wait(timeout=args.timeout)
|
||||
except subprocess.TimeoutExpired:
|
||||
stop_process(process)
|
||||
print('Freerouting timed out; no output published. Inspect the log before choosing another attempt.', file=sys.stderr)
|
||||
return 124
|
||||
except KeyboardInterrupt:
|
||||
stop_process(process)
|
||||
return 130
|
||||
if code:
|
||||
print(f'Freerouting exited with {code}; no output published', file=sys.stderr)
|
||||
return code if code > 0 else 1
|
||||
if not pending.is_file() or pending.stat().st_size < 20 or not pending.read_bytes().lstrip().startswith(b'(session'):
|
||||
raise ValueError('Freerouting did not produce a valid SES session file')
|
||||
# Same filesystem, no overwrite race and no stale/partial SES success.
|
||||
os.link(pending, target)
|
||||
print(f'Saved {target} ({target.stat().st_size} bytes). Import and run native DRC; process success is not board validation.', flush=True)
|
||||
return 0
|
||||
except (ValueError, OSError) as error:
|
||||
print(f'Freerouting launcher: {error}', file=sys.stderr)
|
||||
return 2
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -12,6 +12,10 @@ The helper `await pcb_export(file, 'relative/name.ext')` inside pcb_eda stores a
|
||||
|
||||
External utilities: Java/Freerouting and Blender are installed. You may export DSN and import SES, use native routing APIs, or implement your own routing scripts. Decide from evidence; no website algorithm dictates routing. If external router output is partial, retain the best actual result and fix remaining connections. Use genuine exported OBJ/STEP geometry for renders. Never draw a substitute board picture or invent 3D components. STEP exports may be ZIP-wrapped: inspect, extract and independently validate them. Do not treat a successful export or empty DRC array as proof of electrical correctness.
|
||||
|
||||
Freerouting deployment contract: use the Python freerouting.py launcher supplied in the production message for all external Freerouting runs. Its --help is handled locally and does not launch Java. The installed 1.9.0 JAR understands -help, NOT --help: the latter opens an idle file-selection window. Never invoke the JAR without an existing DSN input and a new SES output, and do not use raw java -jar probes. The launcher always supplies -dct 0 (no 20-second confirmation) and runs in private Xvfb; do not add -Djava.awt.headless=true because this GUI-based version throws HeadlessException. Keep logs in your workspace; after a timeout inspect evidence and choose a recovery rather than blindly retrying. Use a new output filename for each attempt. The launcher only controls process startup, not engineering decisions. SES existence or router exit zero does not prove full connectivity or native DRC success.
|
||||
|
||||
Engineering: verify regulator pinout, supply limits/decoupling, reset/boot behavior, programming access and connector pin labeling. Check exact chip/module manufacturer's reference circuitry. Antenna keepout, plug access and component envelopes must be respected. Layout and routing must correspond to the actual schematic pin/net mapping. Never remove required nets/components, mask checks, disable DRC categories or weaken rules to obtain a pass. Use sensible manufacturing clearances and trace widths and leave unconnected pins intentionally marked, not accidentally unrouted. Save and reopen/check the native design when practical. Inspect schematic, top layout and genuine 3D views yourself before submission.
|
||||
|
||||
Delivery: export native editable project, schematic image/PDF, routed layout image/PDF, assembled board STEP and a rendered 3D PNG/JPEG. Also include BOM, pin/net evidence and verification notes. Use pcb_deliver with those files and actual schematic/PCB document IDs. The service independently runs native checks and validates file formats. If rejected, inspect feedback and correct the design in this same session; do not claim completion before delivery succeeds. A failed design can be retained with pcb_blocked and exact evidence, but do not use this for ordinary recoverable mistakes. Real hardware testing is outside this software delivery; do not claim bench verification.
|
||||
Model appearance: the final assembled STEP must retain the actual native board/component/face colors, not just geometry. If you rebuild or transform an assembly, preserve XCAF color/material attributes and instance/face associations alongside the shapes. Transferring bare TopoDS shapes into a new document loses these attributes even when STEPCAFControl_Writer is used. Export with color mode enabled, then reopen the exact final STEP and verify its applied surface colors and rendered appearance. A colored OBJ/MTL or PNG does not prove that STEP colors survived. Do not arbitrarily paint geometry or add unused color declarations to satisfy validation. If a conversion loses appearance, repair the model export in this same session without redesigning the circuit or weakening electrical checks. Also deliver the genuine final OBJ/MTL and referenced textures as a clearly named assembled-3d-obj.zip when available, matching the final board geometry; this supports an independent colored appearance preview.
|
||||
|
||||
Delivery: export native editable project, schematic image/PDF, routed layout image/PDF, assembled board STEP and a rendered 3D PNG/JPEG. Also include BOM, pin/net evidence and verification notes. Use pcb_deliver with those files and actual schematic/PCB document IDs. The service independently runs native checks and validates file formats and applied STEP surface colors. If rejected, inspect feedback and correct the design in this same session; do not claim completion before delivery succeeds. A failed design can be retained with pcb_blocked and exact evidence, but do not use this for ordinary recoverable mistakes. Real hardware testing is outside this software delivery; do not claim bench verification.
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
"""Check that STEP surface styles retain a non-uniform source palette.
|
||||
|
||||
This is an appearance check, not a geometry or engineering validator. It follows
|
||||
style references instead of accepting unused COLOUR_RGB declarations.
|
||||
"""
|
||||
import re
|
||||
|
||||
STYLE_TYPES = {
|
||||
'COLOUR_RGB', 'DRAUGHTING_PRE_DEFINED_COLOUR', 'FILL_AREA_STYLE_COLOUR',
|
||||
'FILL_AREA_STYLE', 'SURFACE_STYLE_FILL_AREA', 'SURFACE_SIDE_STYLE',
|
||||
'SURFACE_STYLE_USAGE', 'SURFACE_STYLE_RENDERING',
|
||||
'SURFACE_STYLE_RENDERING_WITH_PROPERTIES', 'PRESENTATION_STYLE_ASSIGNMENT',
|
||||
'PRESENTATION_STYLE_BY_CONTEXT', 'STYLED_ITEM', 'OVER_RIDING_STYLED_ITEM',
|
||||
}
|
||||
NAMED_COLORS = {
|
||||
'black': (0., 0., 0.), 'white': (1., 1., 1.), 'red': (1., 0., 0.),
|
||||
'green': (0., 1., 0.), 'blue': (0., 0., 1.), 'yellow': (1., 1., 0.),
|
||||
'magenta': (1., 0., 1.), 'cyan': (0., 1., 1.),
|
||||
}
|
||||
|
||||
|
||||
def validate_step_colors(data):
|
||||
text = re.sub(r'/\*.*?\*/', '', data.decode('latin-1'), flags=re.S)
|
||||
pattern = r'#(\d+)\s*=\s*(' + '|'.join(sorted(STYLE_TYPES, key=len, reverse=True)) + r')\s*\((.*?)\)\s*;'
|
||||
records = {m[1]: (m[2], m[3]) for m in re.finditer(pattern, text, re.S | re.I)}
|
||||
colors = {}
|
||||
for key, (kind, body) in records.items():
|
||||
if kind.upper() == 'COLOUR_RGB':
|
||||
values = body.rsplit(',', 3)
|
||||
try:
|
||||
rgb = tuple(float(v.strip()) for v in values[-3:]) if len(values) == 4 else ()
|
||||
if len(rgb) == 3 and all(0 <= v <= 1 for v in rgb):
|
||||
colors[key] = tuple(round(v, 6) for v in rgb)
|
||||
except ValueError:
|
||||
pass
|
||||
elif kind.upper() == 'DRAUGHTING_PRE_DEFINED_COLOUR':
|
||||
rgb = NAMED_COLORS.get(body.strip().strip("'").lower())
|
||||
if rgb is not None:
|
||||
colors[key] = rgb
|
||||
|
||||
roots = []
|
||||
for kind, body in records.values():
|
||||
if kind.upper() not in {'STYLED_ITEM', 'OVER_RIDING_STYLED_ITEM'}:
|
||||
continue
|
||||
# name, (presentation styles), actual representation item [, overridden style]
|
||||
match = re.match(r"\s*'(?:[^']|'')*'\s*,\s*\(([^)]*)\)\s*,\s*#(\d+)", body, re.S)
|
||||
if match:
|
||||
roots.append((match[1], match[2]))
|
||||
candidates = {target for _, target in roots}
|
||||
defined = {m[1] for m in re.finditer(r'#(\d+)\s*=', text) if m[1] in candidates}
|
||||
palette, targets = set(), set()
|
||||
for styles, target in roots:
|
||||
if target not in defined or target in records:
|
||||
continue
|
||||
todo, seen, used = re.findall(r'#(\d+)', styles), set(), set()
|
||||
while todo:
|
||||
ref = todo.pop()
|
||||
if ref in seen:
|
||||
continue
|
||||
seen.add(ref)
|
||||
if ref in colors:
|
||||
used.add(colors[ref])
|
||||
elif ref in records:
|
||||
todo.extend(re.findall(r'#(\d+)', records[ref][1]))
|
||||
if used:
|
||||
targets.add(target)
|
||||
palette.update(used)
|
||||
if len(palette) < 2 or not targets:
|
||||
raise ValueError(
|
||||
'STEP appearance check failed: the delivered assembly has no usable multi-color surface styles. '
|
||||
'Repair the STEP in this same session using the actual native model colors. '
|
||||
'When rebuilding an XCAF assembly, copy document/shape/face and instance color attributes '
|
||||
'with their transformed geometry; copying TopoDS shapes alone loses colors. '
|
||||
'Enable STEPCAF color export and reopen the exact final file to verify it. '
|
||||
'A colored PNG or OBJ does not replace a colored STEP. Do not invent colors to pass.'
|
||||
)
|
||||
return {'distinct_colors': len(palette), 'styled_items': len(targets)}
|
||||
@@ -0,0 +1,83 @@
|
||||
"""Launcher boundaries; no live EDA application or real board is modified."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
LAUNCHER = Path(__file__).resolve().parents[1] / 'freerouting.py'
|
||||
|
||||
|
||||
class LauncherTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory(dir=Path(__file__).parent)
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.root = Path(self.temp.name)
|
||||
self.source = self.root / 'board.dsn'
|
||||
self.source.write_text('(pcb test)')
|
||||
self.jar = self.root / 'router.jar'
|
||||
self.jar.touch()
|
||||
self.output = self.root / 'result.ses'
|
||||
java = self.root / 'java'
|
||||
java.write_text(f'#!{sys.executable}\n' + '''import json,os,sys,time
|
||||
from pathlib import Path
|
||||
args=sys.argv[1:]
|
||||
Path(os.environ['CALL_LOG']).write_text(json.dumps(args))
|
||||
if os.environ.get('STALL'):time.sleep(30)
|
||||
if not os.environ.get('NO_OUTPUT'):
|
||||
Path(args[args.index('-do')+1]).write_text('(session board (routes (network)))')
|
||||
''')
|
||||
java.chmod(0o755)
|
||||
self.env = dict(os.environ, PATH=str(self.root), CALL_LOG=str(self.root / 'calls.json'))
|
||||
|
||||
def run_cli(self, *extra, help_only=False):
|
||||
args = [] if help_only else ['--input', str(self.source), '--output', str(self.output), '--jar', str(self.jar), '--visible']
|
||||
return subprocess.run([sys.executable, str(LAUNCHER), *args, *extra], env=self.env, capture_output=True, text=True, timeout=10)
|
||||
|
||||
def test_help_never_starts_java(self):
|
||||
r = self.run_cli('--help', help_only=True)
|
||||
self.assertEqual(r.returncode, 0)
|
||||
self.assertFalse((self.root / 'calls.json').exists())
|
||||
|
||||
def test_missing_input_does_not_open_file_picker(self):
|
||||
self.source.unlink()
|
||||
self.assertEqual(self.run_cli().returncode, 2)
|
||||
self.assertFalse((self.root / 'calls.json').exists())
|
||||
|
||||
def test_unknown_help_and_dialog_override_are_rejected(self):
|
||||
for args in [('--', '--help'), ('--', '-dct', '20')]:
|
||||
self.assertEqual(self.run_cli(*args).returncode, 2)
|
||||
self.assertFalse((self.root / 'calls.json').exists())
|
||||
|
||||
def test_route_publishes_ses_without_changing_source(self):
|
||||
r = self.run_cli('--', '-mp', '7', '-mt', '1')
|
||||
self.assertEqual(r.returncode, 0, r.stderr)
|
||||
args = json.loads((self.root / 'calls.json').read_text())
|
||||
self.assertEqual(args[args.index('-dct')+1], '0')
|
||||
self.assertNotEqual(args[args.index('-de')+1], str(self.source))
|
||||
self.assertEqual(self.source.read_text(), '(pcb test)')
|
||||
self.assertTrue(self.output.read_text().startswith('(session'))
|
||||
self.assertEqual(list(self.root.glob('.freerouting-*')), [])
|
||||
|
||||
def test_existing_output_is_preserved(self):
|
||||
self.output.write_text('previous result')
|
||||
self.assertEqual(self.run_cli().returncode, 2)
|
||||
self.assertEqual(self.output.read_text(), 'previous result')
|
||||
self.assertFalse((self.root / 'calls.json').exists())
|
||||
|
||||
def test_exit_zero_without_output_is_failure(self):
|
||||
self.env['NO_OUTPUT'] = '1'
|
||||
self.assertEqual(self.run_cli().returncode, 2)
|
||||
self.assertFalse(self.output.exists())
|
||||
|
||||
def test_timeout_does_not_publish_partial_result(self):
|
||||
self.env['STALL'] = '1'
|
||||
self.assertEqual(self.run_cli('--timeout', '0.2').returncode, 124)
|
||||
self.assertFalse(self.output.exists())
|
||||
self.assertEqual(list(self.root.glob('.freerouting-*')), [])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,35 @@
|
||||
import unittest
|
||||
from codex_pcb.step_colors import validate_step_colors
|
||||
|
||||
VALID=b'''ISO-10303-21;
|
||||
#1=COLOUR_RGB('',0.,0.5,0.2);
|
||||
#2=COLOUR_RGB('',0.1,0.1,0.1);
|
||||
#3=FILL_AREA_STYLE_COLOUR('',#1);
|
||||
#4=FILL_AREA_STYLE('',(#3));
|
||||
#5=SURFACE_STYLE_FILL_AREA(#4);
|
||||
#6=SURFACE_SIDE_STYLE('',(#5));
|
||||
#7=SURFACE_STYLE_USAGE(.BOTH.,#6);
|
||||
#8=PRESENTATION_STYLE_ASSIGNMENT((#7));
|
||||
#9=STYLED_ITEM('',(#8),#90);
|
||||
#10=SURFACE_STYLE_RENDERING(#2);
|
||||
#11=PRESENTATION_STYLE_ASSIGNMENT((#10));
|
||||
#12=STYLED_ITEM('',(#11),#91);
|
||||
#90=ADVANCED_FACE('example');
|
||||
#91=MANIFOLD_SOLID_BREP('example');
|
||||
END-ISO-10303-21;'''
|
||||
|
||||
class Colors(unittest.TestCase):
|
||||
def test_bound_surface_colors(self):
|
||||
self.assertEqual(validate_step_colors(VALID),{'distinct_colors':2,'styled_items':2})
|
||||
def test_unused_declarations_are_not_evidence(self):
|
||||
with self.assertRaises(ValueError):validate_step_colors(b"#1=COLOUR_RGB('',1.,0.,0.);#2=COLOUR_RGB('',0.,1.,0.);")
|
||||
def test_unknown_surface_and_dangling_links(self):
|
||||
for old,new in ((b"#90=ADVANCED_FACE",b"#190=ADVANCED_FACE"),(b"#10=SURFACE_STYLE_RENDERING(#2)",b"#10=SURFACE_STYLE_RENDERING(#222)")):
|
||||
with self.assertRaises(ValueError):validate_step_colors(VALID.replace(old,new))
|
||||
def test_comments_and_uniform_palette_do_not_pass(self):
|
||||
with self.assertRaises(ValueError):validate_step_colors(b'/*'+VALID+b'*/')
|
||||
with self.assertRaises(ValueError):validate_step_colors(VALID.replace(b'0.1,0.1,0.1',b'0.,0.5,0.2'))
|
||||
def test_cycles_terminate(self):
|
||||
with self.assertRaises(ValueError):validate_step_colors(VALID.replace(b"#10=SURFACE_STYLE_RENDERING(#2)",b"#10=SURFACE_STYLE_RENDERING(#11)"))
|
||||
|
||||
if __name__=='__main__':unittest.main(verbosity=2)
|
||||
@@ -2,6 +2,7 @@ import { useEffect, useRef, useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import './codex-pcb.css';
|
||||
import { DeliveryModel3D } from './DeliveryModel3D.js';
|
||||
import { findObjArchive } from './model-appearance.js';
|
||||
import { TaskProgress } from './TaskProgress.js';
|
||||
import { Markdown as RichMarkdown } from '@ziroeda/ai/markdown.js';
|
||||
|
||||
@@ -59,6 +60,7 @@ export function CodexPcbDock(): JSX.Element {
|
||||
const resume = () => action(async () => { setTask(await api<Session>(`/sessions/${active}/resume`, {})); setTab('activity'); });
|
||||
const downloadable = (f: Artifact) => `${BASE}/sessions/${active}/files/${encodeURIComponent(f.name)}`;
|
||||
const step = task?.delivery?.files.find(f => f.kind === 'step' && /\.(step|stp)$/i.test(f.name));
|
||||
const objArchive = findObjArchive(task?.delivery?.files ?? []);
|
||||
const canReview = task && !task.approval && !task.busy && ['review','needs_input','failed'].includes(task.state);
|
||||
const interesting = entries.filter(e => ['message','activity','eda.started','eda.error','session.reconnecting','session.failed','production.blocked','delivery.completed','proposal.approved','session.resumed'].includes(e.type));
|
||||
const view = <div className="cp-root" data-native-text-shortcuts="true">
|
||||
@@ -73,7 +75,7 @@ export function CodexPcbDock(): JSX.Element {
|
||||
{task.error && <div className="cp-error">{task.error}</div>}
|
||||
{tab === 'plan' && <div className="cp-plan"><details><summary>原始需求</summary><p>{task.request}</p></details>{task.proposal ? <Markdown value={task.proposal.markdown}/> : <p className="cp-muted">AI 正在研究需求和制定方案,可以在运行记录中查看进度。</p>}{task.approval && <div className="cp-approved">已确认方案 v{task.approval.revision},设计按此方案执行。</div>}{canReview && <div className="cp-review"><label htmlFor="cp-comment">对方案有修改意见?</label><textarea id="cp-comment" value={comment} onChange={e => setComment(e.target.value)} placeholder="补充要求或指出需要修改的地方…" rows={3}/><div className="cp-actions"><button disabled={busy || comment.trim().length < 5} onClick={send}>提交意见,修改方案</button><button className="cp-primary" disabled={busy || task.state !== 'review' || !!comment.trim()} onClick={approve}>同意此方案,开始运行</button></div>{comment.trim() && <small>请先提交修改意见,待新方案生成后再确认。</small>}</div>}</div>}
|
||||
{tab === 'activity' && <div className="cp-activity" ref={activity}>{interesting.map(e => <article key={e.seq} className={e.type === 'message' ? `cp-message ${text(e.data.role)}` : 'cp-event'}><time>{new Date(e.at * 1000).toLocaleTimeString()}</time>{e.type === 'message' ? <Markdown value={text(e.data.text)}/> : <><strong>{e.type === 'eda.started' ? '嘉立创 EDA · ' + text(e.data.label) : e.type === 'activity' ? ({ commandExecution: '执行脚本', webSearch: '查阅资料', dynamicToolCall: '调用工具', fileChange: '编辑文件' }[text(e.data.kind)] || text(e.data.kind)) : ({ 'eda.error':'EDA 返回错误,AI 可继续处理', 'session.reconnecting':'正在恢复会话', 'session.failed':'会话失败', 'production.blocked':'遇到阻碍', 'delivery.completed':'交付校验通过', 'proposal.approved':'方案已确认,开始设计', 'session.resumed':'已继续原会话' }[e.type] || e.type)}</strong>{text(e.data.message) && <p>{text(e.data.message)}</p>}{text(e.data.command) && <details><summary>查看执行命令</summary><pre>{text(e.data.command)}</pre></details>}</>}</article>)}{task.busy && <p className="cp-muted">● AI 正在继续处理,请稍候…</p>}<details className="cp-session-info"><summary>会话信息</summary><code>{task.thread_id || '正在创建'}</code><p>模型:GPT-6.1 Sol · 方案与生产共用此会话</p></details></div>}
|
||||
{tab === 'files' && <div className="cp-files">{!task.delivery ? <p className="cp-muted">完成设计和原生检查后,交付文件会显示在这里。</p> : <>{step && <DeliveryModel3D key={`${active}/${step.name}/${step.sha256}`} url={downloadable(step)} sha256={step.sha256} name={step.name}/>}<p>{task.delivery.notes}</p>{task.delivery.files.filter(f => ['render','layout','schematic'].includes(f.kind) && /\.(png|jpe?g|svg)$/i.test(f.name)).map(f => <figure key={f.name}><img src={downloadable(f)} alt={f.label}/><figcaption>{f.label}</figcaption></figure>)}{task.delivery.files.map(f => <a className="cp-file" key={f.name} href={downloadable(f)} download><div><strong>{f.label}</strong><small>{f.name} · {(f.bytes / 1024).toFixed(1)} KB</small></div><span>下载 ↓</span></a>)}</>}</div>}
|
||||
{tab === 'files' && <div className="cp-files">{!task.delivery ? <p className="cp-muted">完成设计和原生检查后,交付文件会显示在这里。</p> : <>{step && <DeliveryModel3D key={`${active}/${step.name}/${step.sha256}`} url={downloadable(step)} sha256={step.sha256} name={step.name} objUrl={objArchive ? downloadable(objArchive) : undefined} objSha256={objArchive?.sha256}/>}<p>{task.delivery.notes}</p>{task.delivery.files.filter(f => ['render','layout','schematic'].includes(f.kind) && /\.(png|jpe?g|svg)$/i.test(f.name)).map(f => <figure key={f.name}><img src={downloadable(f)} alt={f.label}/><figcaption>{f.label}</figcaption></figure>)}{task.delivery.files.map(f => <a className="cp-file" key={f.name} href={downloadable(f)} download><div><strong>{f.label}</strong><small>{f.name} · {(f.bytes / 1024).toFixed(1)} KB</small></div><span>下载 ↓</span></a>)}</>}</div>}
|
||||
</>}
|
||||
</main></div></div>
|
||||
</section>}
|
||||
|
||||
@@ -1,13 +1,19 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { readVerifiedModel, stepHasColors, unpackColoredObj } from './model-appearance.js';
|
||||
|
||||
/** Preview the delivered STEP itself; the download remains the original artifact. */
|
||||
export function DeliveryModel3D({ url, sha256, name }: { url: string; sha256: string; name: string }) {
|
||||
/** Preserve delivered colors; old colorless STEP can use its companion OBJ/MTL for appearance. */
|
||||
export function DeliveryModel3D({ url, sha256, name, objUrl, objSha256 }: {
|
||||
url: string; sha256: string; name: string; objUrl?: string; objSha256?: string;
|
||||
}) {
|
||||
const host = useRef<HTMLDivElement>(null);
|
||||
const reset = useRef<(() => void) | null>(null);
|
||||
const [retry, setRetry] = useState(0);
|
||||
const [status, setStatus] = useState('正在加载 PCB 三维模型…');
|
||||
const [failed, setFailed] = useState(false);
|
||||
const [forceStep, setForceStep] = useState(false);
|
||||
const [colorless, setColorless] = useState(false);
|
||||
const [appearance, setAppearance] = useState('');
|
||||
|
||||
// biome-ignore lint/correctness/useExhaustiveDependencies: retry explicitly restarts the failed download and preview.
|
||||
useEffect(() => {
|
||||
@@ -17,18 +23,34 @@ export function DeliveryModel3D({ url, sha256, name }: { url: string; sha256: st
|
||||
let dispose: (() => void) | undefined;
|
||||
setStatus('正在加载 PCB 三维模型…');
|
||||
setFailed(false);
|
||||
setAppearance('');
|
||||
void (async () => {
|
||||
try {
|
||||
const response = await fetch(url, { signal: controller.signal, credentials: 'same-origin' });
|
||||
if (!response.ok) throw new Error('模型文件读取失败,请重试或下载 STEP 文件查看。');
|
||||
const limit = 128 * 1024 * 1024;
|
||||
if (Number(response.headers.get('content-length')) > limit) throw new Error('模型较大,请下载 STEP 文件查看。');
|
||||
const bytes = new Uint8Array(await response.arrayBuffer());
|
||||
if (bytes.byteLength > limit) throw new Error('模型较大,请下载 STEP 文件查看。');
|
||||
const hash = Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)))
|
||||
.map(value => value.toString(16).padStart(2, '0')).join('');
|
||||
if (hash !== sha256) throw new Error('模型文件校验失败,请重新加载。');
|
||||
const bytes = await readVerifiedModel(url, sha256, controller.signal);
|
||||
if (controller.signal.aborted) return;
|
||||
const hasColors = stepHasColors(bytes);
|
||||
setColorless(!hasColors);
|
||||
let info = hasColors ? 'STEP 原始颜色' : '原始 STEP 未包含颜色';
|
||||
if (!hasColors && !forceStep && objUrl && objSha256) {
|
||||
setStatus('正在加载交付包中的彩色外观模型…');
|
||||
try {
|
||||
const packed = await readVerifiedModel(objUrl, objSha256, controller.signal, 64 * 1024 * 1024);
|
||||
if (controller.signal.aborted) return;
|
||||
const files = unpackColoredObj(packed);
|
||||
const { mountProjectObj } = await import('../pcb-service/project-model-obj.js');
|
||||
if (controller.signal.aborted) return;
|
||||
const viewer = mountProjectObj(element, files);
|
||||
dispose = viewer.dispose;
|
||||
reset.current = viewer.reset;
|
||||
setAppearance('彩色外观来自已交付的 OBJ/MTL;机械尺寸请以原始 STEP 为准。');
|
||||
setStatus('');
|
||||
return;
|
||||
} catch {
|
||||
if (controller.signal.aborted) return;
|
||||
// An optional appearance preview must never hide the STEP or block downloads.
|
||||
info = '彩色外观暂不可用,当前显示原始 STEP;可重新加载彩色外观。';
|
||||
}
|
||||
}
|
||||
setStatus('正在解析装配模型,首次打开可能需要一些时间…');
|
||||
const { mountDeliveryStep } = await import('./delivery-step-viewer.js');
|
||||
if (controller.signal.aborted) return;
|
||||
@@ -37,6 +59,7 @@ export function DeliveryModel3D({ url, sha256, name }: { url: string; sha256: st
|
||||
if (controller.signal.aborted) { viewer.dispose(); return; }
|
||||
dispose = viewer.dispose;
|
||||
reset.current = viewer.reset;
|
||||
setAppearance(info);
|
||||
setStatus('');
|
||||
} catch (error) {
|
||||
if (!controller.signal.aborted) {
|
||||
@@ -51,18 +74,25 @@ export function DeliveryModel3D({ url, sha256, name }: { url: string; sha256: st
|
||||
dispose?.();
|
||||
reset.current = null;
|
||||
};
|
||||
}, [url, sha256, retry]);
|
||||
}, [url, sha256, retry, forceStep, objUrl, objSha256]);
|
||||
|
||||
const reload = () => { setStatus('正在重新加载模型…'); setRetry(value => value + 1); };
|
||||
const switchSource = () => { setStatus('正在切换模型…'); setForceStep(value => !value); };
|
||||
|
||||
return <section className="cp-model" aria-label="PCB 交互式三维模型">
|
||||
<div className="cp-model-header">
|
||||
<div><h3>PCB 3D 模型</h3><p>左键拖拽旋转 · 滚轮缩放 · 右键拖拽平移</p></div>
|
||||
<button disabled={!!status} onClick={() => reset.current?.()}>复位视角</button>
|
||||
<div><h3>PCB 3D 模型</h3><p>左键拖拽旋转 · 滚轮缩放 · 右键拖拽平移</p>{appearance && <small className="cp-model-source">{appearance}</small>}</div>
|
||||
<div className="cp-model-actions">
|
||||
{colorless && objUrl && <button disabled={!!status} onClick={switchSource}>{forceStep ? '查看彩色外观' : '查看原始 STEP'}</button>}
|
||||
{colorless && objUrl && !forceStep && appearance.startsWith('彩色外观暂不可用') && <button disabled={!!status} onClick={reload}>重新加载彩色外观</button>}
|
||||
<button disabled={!!status} onClick={() => reset.current?.()}>复位视角</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="cp-model-stage" aria-busy={!!status && !failed}>
|
||||
<div ref={host} className="cp-model-canvas" aria-label="可旋转和缩放的 PCB 模型" />
|
||||
{status && <div className="cp-model-message">
|
||||
<p role="status">{status}</p>
|
||||
{failed && <button onClick={() => setRetry(value => value + 1)}>重新加载模型</button>}
|
||||
{failed && <button onClick={reload}>重新加载模型</button>}
|
||||
</div>}
|
||||
</div>
|
||||
<div className="cp-model-footer"><span>{name}</span><a href={url} download>下载 STEP 模型 ↓</a></div>
|
||||
|
||||
@@ -5,3 +5,5 @@
|
||||
.cp-model{border:1px solid var(--cp-border);border-radius:12px;overflow:hidden;margin-bottom:24px;background:#142233}.cp-model-header{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:16px 20px}.cp-model-header h3{font-size:17px;margin:0}.cp-model-header p{color:var(--cp-muted);font-size:12px;margin:4px 0 0}.cp-model-header button{flex-shrink:0}.cp-model-stage{position:relative;height:clamp(320px,52vh,600px)}.cp-model-canvas{width:100%;height:100%;background:#101a27}.cp-model-canvas canvas{display:block;touch-action:none}.cp-model-message{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;padding:24px;text-align:center;background:#101a27;color:var(--cp-muted)}.cp-model-footer{display:flex;justify-content:space-between;gap:16px;padding:12px 20px;color:var(--cp-muted);font-size:12px;border-top:1px solid var(--cp-border)}.cp-model-footer span{overflow-wrap:anywhere;min-width:0}.cp-model-footer a{color:var(--cp-blue);white-space:nowrap;text-decoration:none}.cp-model-footer a:hover{text-decoration:underline}@media(max-width:550px){.cp-model-header{padding:12px;flex-wrap:wrap}.cp-model-footer{padding:12px;flex-wrap:wrap}.cp-model-stage{height:340px}}
|
||||
|
||||
.cp-content{display:flex;flex-direction:column;flex:1;min-width:0;min-height:0}.cp-progress{flex-shrink:0;padding:18px 34px 14px;border-bottom:1px solid var(--cp-border);background:#142233}.cp-progress-heading,.cp-progress-timing{display:flex;justify-content:space-between;align-items:center;gap:10px;flex-wrap:wrap}.cp-progress-heading strong{color:#b7e2ff;font-size:15px}.cp-progress-heading>div>span{margin-left:12px;color:var(--cp-muted);font-size:12px}.cp-progress-elapsed{font-variant-numeric:tabular-nums;color:var(--cp-muted);font-size:12px}.cp-progress-track{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:8px;margin:14px 0}.cp-progress-segment{height:5px;overflow:hidden;border-radius:4px;background:var(--cp-border);margin-bottom:9px}.cp-progress-segment i{display:block;height:100%;width:0;background:var(--cp-blue);border-radius:inherit}.cp-progress-step.is-done .cp-progress-segment i{width:100%;background:#78d7b1}.cp-progress-step.is-current .cp-progress-segment i{width:45%;animation:cp-pulse 1.8s infinite}.cp-progress-step>span{color:var(--cp-muted);font-size:12px;display:flex;align-items:center;gap:6px}.cp-progress-step b{font-size:11px;font-weight:500;display:inline-flex;justify-content:center;align-items:center;width:18px;height:18px;border:1px solid var(--cp-border);border-radius:50%;flex-shrink:0}.cp-progress-step.is-done>span{color:#a3dfc5}.cp-progress-step.is-current>span{color:#c7eaff;font-weight:600}.cp-progress-step.is-current b{border-color:var(--cp-blue);color:var(--cp-blue)}.cp-progress-timing strong{font-size:13px;font-weight:500;color:#c7eaff}.cp-progress-timing>span{font-size:11px;color:var(--cp-muted)}.cp-progress-note{font-size:11px;margin:7px 0 0;color:var(--cp-muted)}.cp-progress.is-paused .is-current .cp-progress-segment i{animation:none;background:#e4b875}.cp-progress.is-paused .cp-progress-heading strong{color:#e4b875}.cp-progress.is-complete .cp-progress-heading strong{color:#a3dfc5}@media(max-width:850px){.cp-progress{padding:14px 18px 12px}.cp-progress-track{gap:5px}.cp-progress-step>span{font-size:11px;gap:4px}}@media(max-width:550px){.cp-progress{padding:12px}.cp-progress-heading>div>span{margin-left:7px}.cp-progress-track{margin:10px 0}.cp-progress-step>span{flex-direction:column;align-items:flex-start;gap:4px}.cp-progress-note{font-size:10px}}@media(prefers-reduced-motion:reduce){.cp-progress-step.is-current .cp-progress-segment i{animation:none}}
|
||||
|
||||
.cp-model-actions{display:flex;gap:8px;flex-wrap:wrap;justify-content:flex-end}.cp-model-source{display:block;font-size:12px;margin-top:4px;color:var(--cp-muted)}@media(max-width:850px){.cp-model-header{flex-wrap:wrap}.cp-model-actions{justify-content:flex-start}}
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import { unzipSync } from 'fflate';
|
||||
|
||||
/** Fast selection for old deliveries; new STEP deliveries receive server-side style validation. */
|
||||
export function stepHasColors(bytes: Uint8Array): boolean {
|
||||
const text = new TextDecoder().decode(bytes).replace(/\/\*[\s\S]*?\*\//g, '');
|
||||
return /\b(?:COLOUR_RGB|DRAUGHTING_PRE_DEFINED_COLOUR)\s*\(/i.test(text)
|
||||
&& /\b(?:STYLED_ITEM|OVER_RIDING_STYLED_ITEM)\s*\(/i.test(text);
|
||||
}
|
||||
|
||||
export function findObjArchive<T extends { name: string; kind: string }>(files: readonly T[]): T | undefined {
|
||||
return files.find(file => file.kind !== 'bundle' && /\.zip$/i.test(file.name) && /(?:obj|3d|model)/i.test(file.name));
|
||||
}
|
||||
|
||||
export function unpackColoredObj(bytes: Uint8Array): Record<string, Uint8Array> {
|
||||
if (bytes.byteLength > 64 * 1024 * 1024) throw new Error('彩色模型包超过预览大小限制');
|
||||
let total = 0, count = 0;
|
||||
const files = unzipSync(bytes, { filter: entry => {
|
||||
if (++count > 2000 || (total += entry.originalSize) > 128 * 1024 * 1024) throw new Error('彩色模型包解压后过大');
|
||||
if (entry.name.startsWith('/') || entry.name.includes('\\') || entry.name.split('/').includes('..')) throw new Error('彩色模型包路径无效');
|
||||
return /\.(obj|mtl|png|jpe?g)$/i.test(entry.name);
|
||||
} });
|
||||
const names = Object.keys(files), decoder = new TextDecoder();
|
||||
const objects = names.filter(name => /\.obj$/i.test(name));
|
||||
if (objects.length !== 1) throw new Error('彩色模型包需要一个完整装配模型');
|
||||
const objectName = objects[0]!;
|
||||
const object = decoder.decode(files[objectName]);
|
||||
const library = /^mtllib\s+(.+)$/m.exec(object)?.[1]?.trim();
|
||||
const directory = objectName.slice(0, objectName.lastIndexOf('/') + 1);
|
||||
const materialName = library ? directory + library.replace(/^\.\//, '') : names.find(name => /\.mtl$/i.test(name));
|
||||
if (!materialName || !files[materialName]) throw new Error('彩色模型缺少对应材质文件');
|
||||
const material = decoder.decode(files[materialName]);
|
||||
if (!/^usemtl\s+\S+/m.test(object) || !/^Kd\s+[\d.]+\s+[\d.]+\s+[\d.]+/m.test(material)) throw new Error('模型包没有可用的原始颜色');
|
||||
return files;
|
||||
}
|
||||
|
||||
export async function readVerifiedModel(url: string, sha256: string, signal: AbortSignal, limit = 128 * 1024 * 1024): Promise<Uint8Array> {
|
||||
const response = await fetch(url, { signal, credentials: 'same-origin' });
|
||||
if (!response.ok) throw new Error('模型文件读取失败,请重试或下载原文件查看。');
|
||||
if (Number(response.headers.get('content-length')) > limit) throw new Error('模型较大,请下载原文件查看。');
|
||||
const bytes = new Uint8Array(await response.arrayBuffer());
|
||||
if (bytes.byteLength > limit) throw new Error('模型较大,请下载原文件查看。');
|
||||
const hash = Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)))
|
||||
.map(value => value.toString(16).padStart(2, '0')).join('');
|
||||
if (hash !== sha256) throw new Error('模型文件校验失败,请重新加载。');
|
||||
return bytes;
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { strToU8, zipSync } from 'fflate';
|
||||
import { findObjArchive, stepHasColors, unpackColoredObj } from '../../../designer/src/codex-pcb/model-appearance.js';
|
||||
|
||||
const obj = strToU8('mtllib board.mtl\nv 0 0 0\nv 1 0 0\nv 0 1 0\nusemtl board\nf 1 2 3\n');
|
||||
const mtl = strToU8('newmtl board\nKd 0.1 0.5 0.2\n');
|
||||
describe('delivered model appearance', () => {
|
||||
it('prefers original colored STEP and ignores color mentions inside comments', () => {
|
||||
expect(stepHasColors(strToU8("#1=COLOUR_RGB('',0.,1.,0.);#2=STYLED_ITEM('',(#3),#4);"))).toBe(true);
|
||||
expect(stepHasColors(strToU8('ISO-10303-21; /* COLOUR_RGB( STYLED_ITEM( */'))).toBe(false);
|
||||
expect(stepHasColors(strToU8('ISO-10303-21; COLOUR_RGB( )'))).toBe(false);
|
||||
});
|
||||
it('finds the companion archive without selecting a generic delivery or Gerber ZIP', () => {
|
||||
const files = [{name:'delivery.zip',kind:'bundle'},{name:'12-gerber.zip',kind:'other'},{name:'14-final-obj.zip',kind:'other'}];
|
||||
expect(findObjArchive(files)?.name).toBe('14-final-obj.zip');
|
||||
expect(findObjArchive([{name:'16-ESP32-R1-3D.zip',kind:'other'}])?.name).toContain('3D');
|
||||
expect(findObjArchive(files.slice(0,2))).toBeUndefined();
|
||||
});
|
||||
it('preserves the actual nested OBJ, MTL and textures', () => {
|
||||
const files = {'model/board.obj':obj,'model/board.mtl':mtl,'model/texture.png':new Uint8Array([1,2,3])};
|
||||
expect(unpackColoredObj(zipSync(files))).toEqual(files);
|
||||
});
|
||||
it('rejects missing/mismatched material libraries and ambiguous geometry', () => {
|
||||
for (const files of [{ 'board.obj': obj }, {'board.obj':obj,'wrong.mtl':mtl}, {'a.obj':obj,'b.obj':obj,'board.mtl':mtl}]) {
|
||||
expect(() => unpackColoredObj(zipSync(files))).toThrow();
|
||||
}
|
||||
});
|
||||
it('rejects traversal and malformed archives', () => {
|
||||
expect(() => unpackColoredObj(zipSync({'../board.obj':obj,'board.mtl':mtl}))).toThrow('路径');
|
||||
expect(() => unpackColoredObj(new Uint8Array([1,2,3]))).toThrow();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user