← Commit history
crates/adom-aiflow/src/main.rs+31−1
@@ -29,6 +29,10 @@ enum Cmd {     SilkscreenLayout { #[arg(long)] input: PathBuf, #[arg(long)] out: PathBuf, #[arg(long)] events: Option<PathBuf> },     SilkscreenDashboard { action: String, #[arg(long, default_value="auto")] port: String, #[arg(long, default_value="wv")] surface: String, #[arg(long)] url: Option<String>, #[arg(long)] target: Option<String>, #[arg(long)] json: Option<String>, #[arg(long)] reason: Option<String> },     SilkscreenAudit { #[arg(long)] input: PathBuf, #[arg(long)] out: PathBuf },+    SilkscreenSections { #[arg(long)] input: PathBuf, #[arg(long)] out: PathBuf },+    SilkscreenPreflight { #[arg(long)] input: PathBuf, #[arg(long)] out: PathBuf },+    SilkscreenMask { #[arg(long)] board: PathBuf, #[arg(long)] out: PathBuf },+    SilkscreenContactPolicy { #[arg(long)] input: PathBuf, #[arg(long)] geometry: PathBuf, #[arg(long)] out: PathBuf, #[arg(long)] no_contact_borders: bool },      /// Start a run: copies the board, stamps the prompt time     Start { #[arg(long)] board: String, #[arg(long)] spec: String, #[arg(long)] engine: String, #[arg(long)] prompt_time: Option<String>, #[arg(long)] target: Option<String>, #[arg(long)] remote_board: Option<String>, #[arg(long)] force: bool },@@ -474,6 +478,32 @@ fn main() {         }     }     match &cli.cmd {+        Cmd::SilkscreenSections { input, out } => {+            thread(&cli); let _r=load_run(&cli);+            let result=std::process::Command::new("python3").arg("-c").arg(include_str!("../../../tools/silkscreen-sections.py")).arg("--input").arg(input).arg("--out").arg(out).output().unwrap_or_else(|e|err(&format!("section layout could not run: {e}"), &[]));+            if !result.status.success(){err(&format!("{} {}",String::from_utf8_lossy(&result.stdout),String::from_utf8_lossy(&result.stderr)), &["Keep each documentation section together. Change its region, column layout or font; never scatter its rows to claim full coverage.".into()]);}+            ok(&String::from_utf8_lossy(&result.stdout), &["Preserve headings, ordered rows, common alignment and spacing. Tables supplement physical terminal labels. Review both readable faces and native DRC before acceptance.".into()]);+        }+        Cmd::SilkscreenPreflight { input, out } => {+            thread(&cli); let _r=load_run(&cli);+            let result=std::process::Command::new("python3").arg("-c").arg(include_str!("../../../tools/silkscreen-preflight.py")).arg("--input").arg(input).arg("--out").arg(out).output().unwrap_or_else(|e|err(&format!("preflight could not run: {e}"), &[]));+            if !result.status.success(){err(&format!("{} {}",String::from_utf8_lossy(&result.stdout),String::from_utf8_lossy(&result.stderr)), &["Repack every reported collision before transferring to the EDA. Include full custom-pad mask geometry, fitted bodies, holes and footprint artwork.".into()]);}+            ok(&String::from_utf8_lossy(&result.stdout), &["Preflight passed; confirm with native DRC and inspect both faces. Association quality remains a separate visual gate.".into()]);+        }+        Cmd::SilkscreenMask { board, out } => {+            thread(&cli); let _r=load_run(&cli);+            let result=std::process::Command::new("python3").arg("-c").arg(include_str!("../../../tools/silkscreen-kicad-mask.py")).arg("--board").arg(board).arg("--out").arg(out).output().unwrap_or_else(|e|err(&format!("mask export could not run: {e}"), &[]));+            if !result.status.success(){err(&String::from_utf8_lossy(&result.stderr), &["Unsupported mask geometry is a blocking preflight error, never an anchor-box fallback.".into()]);}+            ok(&String::from_utf8_lossy(&result.stdout), &["Use these complete native mask polygons with fitted body, hole and artwork obstacles.".into()]);+        }+        Cmd::SilkscreenContactPolicy { input, geometry, out, no_contact_borders } => {+            thread(&cli); let _r=load_run(&cli);+            let mut command=std::process::Command::new("python3");command.arg("-c").arg(include_str!("../../../tools/silkscreen-contact-policy.py")).arg("--input").arg(input).arg("--geometry").arg(geometry).arg("--out").arg(out);+            if *no_contact_borders{command.arg("--no-contact-borders");}+            let result=command.output().unwrap_or_else(|e|err(&format!("contact policy could not run: {e}"), &[]));+            if !result.status.success(){err(&String::from_utf8_lossy(&result.stderr), &[]);}+            ok(&String::from_utf8_lossy(&result.stdout), &["Solve outside-first contact candidates; frames default on and reserve their stroke. Repeated connector columns share border rails and row height; record layout exceptions. Use --no-contact-borders to disable frames. Report inside fallbacks and clearance gaps.".into(), "Before layout, rank interfaces for this board. ESCs need prominent verified PHASE A/B/C, battery and ground labels; functional terminal names can outrank connector references.".into()]);+        }         Cmd::SilkscreenAudit { input, out } => {             thread(&cli); let _r = load_run(&cli);             let result = std::process::Command::new("python3").arg("-c").arg(include_str!("../../../tools/silkscreen-obstacle-check.py")).arg("--input").arg(input).arg("--out").arg(out).output().unwrap_or_else(|e| err(&format!("silkscreen audit needs python3: {e}"), &[]));@@ -501,7 +531,7 @@ fn main() {             if let Some(v)=events {command.arg("--events").arg(v);}             let result = command.output().unwrap_or_else(|e| err(&format!("silkscreen planner needs python3: {e}"), &[]));             if !result.status.success() { err(&format!("silkscreen planning incomplete: {} {}", String::from_utf8_lossy(&result.stdout), String::from_utf8_lossy(&result.stderr)), &["Inspect unresolved labels, expand candidate positions and repack nearby text before reducing fonts. Board unchanged.".into()]); }-            ok(&String::from_utf8_lossy(&result.stdout), &["Candidate rectangles only: verify native text bounds, component-body visibility and DRC, then refresh both native views. Native edits belong to the EDA bridge.".into()]);+            ok(&String::from_utf8_lossy(&result.stdout), &["Check reference/value completeness and hierarchy, outside-first ordered contacts and board-specific interface prominence. Run silkscreen-preflight before native DRC, then refresh both native views. Native edits belong to the EDA bridge.".into()]);         }         Cmd::Start { board, spec, engine, prompt_time, target, remote_board, force } => {             let t = thread(&cli);
docs/silkscreen.md+56
@@ -91,3 +91,59 @@ Reserve every via hole on both faces, including tented vias when visible labelin ## Optional live silkscreen dashboard  Offer `silkscreen-dashboard show` with the run and ai-thread flags. The shared observer renders real timestamped solver events, sampled candidate bounds and reasons, selected proposals and unresolved labels, in 2D and a fitted-model 3D preview. `silkscreen-layout --events <run>/silkscreen-dashboard/events.jsonl` emits these without AI/provider calls or deliberate solver pauses. Read `tools/silkscreen-dashboard/SKILL.md` for the manifest, transform limits, lifecycle and recording contract. Live and replay are visibly distinct; replay exports are not raw native CAD footage. Selected proposals remain unverified until native application, DRC and assembled visibility checks pass. Fusion/Altium adapters are not implemented merely because the manifest is tool-neutral.++### Release quality: references, values and visual association++Do not accept a fresh solve based on text-object coverage alone. Place each reference+and required value atomically; reference text is larger, value text is normally+60–80% of reference height. Reserve both before placing the next component. Keep+connector rows in physical pin order and preserve that constraint on both faces.+An old layout is a comparison baseline, never evidence that a new solver succeeded.++Where a nearby component could be mistaken for the label's owner, provide a short+curved pointer to the intended component's visible rim. Where space permits, a+shared outline may group the component and its reference/value. These graphics+must clear mask openings, drilled holes, other bodies and all text. Avoid extra+lines where proximity already makes ownership unambiguous. If no safe association+can be drawn, repack or flag it for review; do not silently mark it complete.++Release proof includes a solve from empty label occupancy without old positions as+candidates, name/value hierarchy and completeness checks, connector-order checks,+collision checks including fitted models and vias, native EDA readback and DRC,+and human-readable top/bottom review with the full event replay. Show bottom from+below with readable text, or explicitly mirror text in a top-view projection.++Machine contacts and machine pins use an outside-first policy: the label sits+between the contact and the nearest board edge whenever feasible. Preserve row+order and side consistency; report inside fallbacks. Printed contact/name/value+frames default on (`contactBorders: true`), with `--no-contact-borders` for a solve+without them. Reserve every frame stroke during placement, and report any small+clearance gaps required around holes. This preference applies to both board faces.++### Board-specific importance pass before layout+The AI first identifies how the real board will be connected, powered, serviced and+debugged. Rank interfaces by their importance to those tasks, using verified board,+schematic and spec data. Write that ranking into the solve input; do not give every+label equal weight. Reserve prominent connection labels first, then component+reference/value pairs and secondary service notes. Only print voltage/current+ratings supported by the design review, never guessed ratings.++ESC / BLDC controller rule: PHASE A, PHASE B and PHASE C are prominent motor-terminal+names, normally targeting 1.0–1.4 mm where geometry permits, on both service faces.+Battery input and polarity/ground also deserve prominent identification. Phase+names are primary interface labels, not small component values: their MC/connector+reference can be smaller. Preserve the mapping to the actual terminal nets; never+infer phase order from screen position. Programming/debug labels remain legible but+must not consume the space reserved for power and motor connections. Document any+geometry-driven reduction from the desired hierarchy.+++### Documentation sections are atomic+Board identity, instructions, warnings and service-reference tables must retain semantic sections. Preserve row order, a shared readable alignment, consistent line spacing and a larger heading. Place or resize the whole block; never sort individual lines by length or scatter them on generic center-column anchors. Bottom blocks align in the actual bottom-face reading orientation. Keep reference tables supplementary to labels beside physical connectors. Report an unresolved section rather than silently disassembling it. Replay one section at a time and expose its text heights.++Documentation blocks default to left-aligned visible glyphs, not merely aligned calculation boxes. Use the readable left edge on both faces, including bottom reflection. The dashboard must not recenter a shorter font rendering inside the EDA-measured box. Native exports may use equivalent centered anchors computed from measured glyph bounds, provided the actual ink shares the left edge.++### Visual consistency across connector groups+Treat repeated connector labels as a designed row or column. Prefer shared outer border rails, common widths/heights, padding, reference/value hierarchy and consistent spacing. Solve these at group level before independent placement. Reserve actual strokes against holes, masks and bodies. Never stretch borders after collision checks. Use consistent safe clearance gaps where needed; report any individual inside placement or sizing exception. Apply semantic importance first: ESC PHASE A/B/C are prominent functional labels. Documentation sections retain ordered, left-aligned text and headings rather than scattered rows.++Pin-label alignment is target-facing, not universally centered: right-align ink for labels left of their pad, left-align for labels right of their pad. Evaluate this in the visible face orientation, reversing it for the bottom view. Store the electrical target and alignment intent, keep measured native bounds, and avoid wasted visual gap between ink and the pad. Center only when it improves an intentionally symmetric group.
tools/silkscreen-associations.pyadded+46
@@ -0,0 +1,46 @@+#!/usr/bin/env python3+"""Collision-checked visual associations for a selected silkscreen layout (mm).+Try an enclosure when requested, otherwise a curved pointer to the body's rim.+Never draw across text, pads, holes or another fitted body. Report failures.+"""+import json,argparse,math+from pathlib import Path+from shapely.geometry import shape,box,LineString,Point+from shapely.ops import unary_union,nearest_points+from shapely.prepared import prep++def associate(data):+ children=data['placements'];graphics=[];unresolved=[]+ for p in children:+  ref=p.get('reference');side=p['layer']+  if p.get('contactBorder'):+   for points in p['associationSegments']:graphics.append(dict(index=p['index'],reference=ref,layer=side,kind='outline',samples=points,contactBorder=True))+   continue+  if not ref or p.get('role')=='value':continue+  target=shape(data.get('targets',{}).get(str(p['index']),data['bodies'].get(side,{}).get(ref,{'type':'GeometryCollection','geometries':[]})))+  if target.is_empty:continue+  target=target.buffer(data.get('targetMargin',.02))+  own=unary_union([box(*q['box']) for q in children if q['layer']==side and q.get('reference')==ref and (not p.get('pin') or q['index']==p['index'])]);distance=own.distance(target)+  blockers=[shape(o['polygon']) for o in data['obstacles'] if o['layer']==side]+  blockers += [box(*q['box']).buffer(.025) for q in children if q['layer']==side]+  blockers += [LineString(g['samples']).buffer(.06) for g in graphics if g['layer']==side]+  blocked=prep(unary_union(blockers))+  if data.get('style')=='enclosure' and not p.get('pin'):+   members=[box(*q['box']) for q in children if q['layer']==side and q.get('reference')==ref]+   enclosure=box(*unary_union([target]+members).bounds).buffer(.15,join_style=2).exterior+   if not blocked.intersects(enclosure.buffer(.025)):+    samples=list(enclosure.coords);p['associationOutline']=samples;graphics.append(dict(index=p['index'],reference=ref,layer=side,kind='outline',samples=samples));continue+  if distance<.20:continue+  a0,b0=nearest_points(own,target);a0=list(a0.coords)[0];b0=list(b0.coords)[0];found=None+  # Route from the label edge to just outside the target, never across its mask.+  a=tuple(a0[j]+(b0[j]-a0[j])*.10/distance for j in [0,1]);b=tuple(b0[j]-(b0[j]-a0[j])*.10/distance for j in [0,1]);dx,dy=b[0]-a[0],b[1]-a[1];length=math.hypot(dx,dy)+  if length<=.08:continue+  for bend in [.12,-.12,.3,-.3,.6,-.6,1,-1,0]:+   c1=(a[0]+dx/3-dy/length*bend,a[1]+dy/3+dx/length*bend);c2=(a[0]+dx*2/3-dy/length*bend,a[1]+dy*2/3+dx/length*bend)+   points=[a,c1,c2,b];samples=[tuple((1-t)**3*a[j]+3*(1-t)**2*t*c1[j]+3*(1-t)*t*t*c2[j]+t**3*b[j] for j in [0,1]) for t in [i/40 for i in range(41)]]+   if blocked.intersects(LineString(samples).buffer(.035)):continue+   found=dict(index=p['index'],reference=ref,layer=side,kind='curve',points=points,samples=samples);p['leaderCurve']=points;graphics.append(found);break+  if found is None:unresolved.append(dict(index=p['index'],reference=ref,layer=side,distance=distance,reason='No collision-free direct curved pointer; review enclosure or reroute'))+ return dict(placements=children,graphics=graphics,unresolvedAssociations=unresolved)+if __name__=='__main__':+ p=argparse.ArgumentParser();p.add_argument('--input',required=True);p.add_argument('--out',required=True);a=p.parse_args();r=associate(json.loads(Path(a.input).read_text()));Path(a.out).write_text(json.dumps(r,indent=2));print(len(r['graphics']),'pointers;',len(r['unresolvedAssociations']),'association reviews')
tools/silkscreen-contact-policy.pyadded+65
@@ -0,0 +1,65 @@+#!/usr/bin/env python3+"""Prefer board-edge side; optionally reserve a printed contact/name/value border.+Default contactBorders=true. The four border stroke rectangles participate in the+same collision solve as text. Full enclosure must contain no unrelated obstacles.+"""+import json,argparse,math+from pathlib import Path+from shapely.geometry import shape,Point,box,LineString+from shapely.ops import nearest_points,unary_union+from shapely.prepared import prep++def apply_policy(spec,geometry,enabled=True):+ outline=shape(geometry['outline']);stats={};bands={}+ # Shared rails and row heights are design constraints, not independent box fits.+ rows={}+ for g in spec['labels']:+  if g.get('orderGroup') and g['id'].startswith('MC') and g.get('candidates'):+   side=g['candidates'][0]['children'][0]['layer'];rows.setdefault((side,g['orderGroup']),[]).append(g)+ for (side,key),members in rows.items():+  if len(members)<3:continue+  xs=[g['anchor'][0] for g in members]+  if max(xs)-min(xs)>.1:continue+  ys=sorted(g['anchor'][1] for g in members);pitch=min(b-a for a,b in zip(ys,ys[1:]) if b-a>.1)+  targets=[shape(geometry['bodies'][side][g['id']]).bounds for g in members]+  if sum(xs)/len(xs)<outline.centroid.x:+   left=outline.bounds[0]+.12;right=max(b[2] for b in targets)+.10+  else:+   left=min(b[0] for b in targets)-.10;right=outline.bounds[2]-.12+  for g in members:bands[g['id']]=(left,right,pitch-.20,key)++ for group in spec['labels']:+  ref=group['id'];iscontact=ref.startswith(('MC','MP'))+  if not iscontact:continue+  anchor=Point(group['anchor']);edge=nearest_points(anchor,outline.exterior)[1];vx,vy=edge.x-anchor.x,edge.y-anchor.y+  side=group['candidates'][0]['children'][0]['layer'] if group['candidates'] else geometry.get('layer','F.SilkS')+  obs=[o for o in geometry['obstacles'] if o['layer']==side];target=shape(geometry['bodies'][side][ref]);fixed=prep(unary_union([shape(o['polygon']) for o in obs]));unrelated=prep(unary_union([shape(o['polygon']) for o in obs if o['reference']!=ref and o['kind'] not in ['native-silk-graphic','via-hole-and-mask']]))+  mask=unary_union([shape(o['polygon']).buffer(.04) for o in obs])+  kept=[];counts={'outside':0,'inside':0,'borderRejected':0}+  for c in group['candidates']:+   # Large primary penalty makes outside preferred ahead of font, within coverage.+   direction=(c['position'][0]-anchor.x)*vx+(c['position'][1]-anchor.y)*vy+   placementSide='outside' if direction>0 else 'inside';c['contactSide']=placementSide;c['qualityPenalty']=c.get('qualityPenalty',0)+(0 if placementSide=='outside' else 200)+   if enabled:+    bb=unary_union([target]+[box(*ch['box']) for ch in c['children']]).bounds+    region=box(bb[0]-.10,bb[1]-.10,bb[2]+.10,bb[3]+.10)+    if ref in bands and placementSide=='outside':+     left,right,height,key=bands[ref];shared=box(left,anchor.y-height/2,right,anchor.y+height/2)+     if not shared.buffer(-.06).covers(unary_union([target]+[box(*ch['box']) for ch in c['children']])):counts['borderRejected']+=1;continue+     region=shared;c['alignmentGroup']=key;c['sharedBorderBounds']=list(region.bounds)+    ring=region.exterior;stroke=ring.buffer(.03,join_style=2)+    if not outline.contains(stroke) or unrelated.intersects(region):counts['borderRejected']+=1;continue+    # Keep a visible grouping frame; make explicit safety gaps at nearby holes/artwork.+    safe=ring.difference(mask);segments=[safe] if safe.geom_type=='LineString' else list(safe.geoms) if safe.geom_type=='MultiLineString' else []+    segments=[line for line in segments if line.length>=.15]+    if not segments or sum(line.length for line in segments)<ring.length*.70:counts['borderRejected']+=1;continue+    points=list(ring.coords);paths=[list(line.coords) for line in segments]+    c['children'][0]['associationSegments']=paths;c['children'][0]['contactBorder']=True;c['contactBorder']=paths;c['borderStyle']='closed' if len(segments)==1 and segments[0].is_ring else 'interrupted-for-clearance'+    c['boxes'] += [list(LineString([a,b]).buffer(.03,cap_style=2).bounds) for line in paths for a,b in zip(line,line[1:])]+    c['box']=list(stroke.bounds)+   c['contactBorders']=enabled;kept.append(c);counts[placementSide]+=1+  group['candidates']=kept;stats[ref]=counts+ spec['contactBorders']=enabled;spec['contactPolicy']='nearest board edge first, coherent ordered rows, shared column border rails and row height, inside fallback';spec['contactPolicyStats']=stats+ return spec+if __name__=='__main__':+ p=argparse.ArgumentParser();p.add_argument('--input',required=True);p.add_argument('--geometry',required=True);p.add_argument('--out',required=True);p.add_argument('--no-contact-borders',action='store_true');a=p.parse_args();r=apply_policy(json.loads(Path(a.input).read_text()),json.loads(Path(a.geometry).read_text()),not a.no_contact_borders);Path(a.out).write_text(json.dumps(r));print(json.dumps(r['contactPolicyStats']))
tools/silkscreen-dashboard/SKILL.md+43
@@ -33,3 +33,46 @@ A full placement demonstration starts with no authored labels in the candidate o Show the active label's native text height in millimetres, including distinct reference/value sizes. Maximize readable size near its physical feature; 0.20 mm is a last-resort InstaPCB value, not a default. Prefer short curved leader lines whenever contact/pin association is unclear. Route leaders to the feature's visible rim, keep them off holes, pads, bodies and other text, and verify both faces in the native EDA. Include leaders as actual placement/rework events.  Record each face as a 1920x1080 detailed replay with an explicit replay label. End the review video with the same revision in the user's native EDA, including top and bottom inspection. A dashboard preview or API success is not proof of a faithful native transfer. Keep native raw clips separate from captioned/replayed dashboard clips.++### Face orientation and label hierarchy+- Show bottom placement from below: reflect board geometry, pad positions, obstacles, leaders and label anchors together; keep lettering readable. Do not display unmirrored bottom text on unchanged top-view geometry. State the viewing direction alongside the face name in the dashboard and video.+- Use distinct face colors plus explicit F.SilkS/B.SilkS text; color alone is insufficient.+- Place each component reference and value as a group: the reference has priority and is larger; the value is mandatory and visibly smaller. A count of placed text objects does not prove this hierarchy or readability.+- Treat machine contacts, machine pins and connector pin labels as structured groups. Preserve ordered pin mapping, nearby placement and clear curved leaders when needed; compare against the previous native layout before accepting a fresh solve.++- 2D wheel/trackpad zoom must preserve the board point beneath the pointer, including aspect-fit margins and bottom-face reflection. Manual zoom or pan cancels camera animation and disables automatic follow until the user enables it again.++- Rendering contract: only manufacturing silkscreen is solid and fully opaque. Calculation-only text bounds, keepouts and obstacle outlines use dashed strokes at approximately 50% opacity, with an explicit legend. Never make a debug bounding box look like a printed enclosure. Captured footage must preserve the distinction.++### Machine-contact grouping (default on)+Prefer the label on the board-edge side of each machine contact, machine pin or edge+connector. Determine that direction in physical board coordinates from the nearest+outline edge, independent of whether the viewer is showing top or bottom. Keep a+column on the same side where feasible, preserve physical pin order, and use an+inside fallback only when the outside cannot fit collision-free. Explain fallbacks.++By default reserve a printed frame around each contact plus its larger reference and+smaller function/value. `contactBorders: false` / `--no-contact-borders` disables+these frames without disabling the outside-first policy. Borders are placement+geometry, not decoration added after the solve. Check their full stroke against+holes, mask openings, existing artwork, text and the board edge. A frame may have+small, explicitly reported clearance gaps; never draw across a hole to close it.+Display printed frames as solid; calculation bounding boxes remain dashed at 50%.++Before solving, perform a board-specific interface importance pass. For ESCs, give+verified PHASE A/B/C motor terminals conspicuously larger connection labels (target+1.0–1.4 mm when space allows) and prioritize battery input, polarity and ground.+A functional terminal name can outrank its MC reference; component values remain+smaller than their component references. Record the chosen semantic priorities in+the input and event explanation, then reserve those groups before secondary notes.+++### Documentation sections are atomic+Board identity, instructions, warnings and service-reference tables must retain semantic sections. Preserve row order, a shared readable alignment, consistent line spacing and a larger heading. Place or resize the whole block; never sort individual lines by length or scatter them on generic center-column anchors. Bottom blocks align in the actual bottom-face reading orientation. Keep reference tables supplementary to labels beside physical connectors. Report an unresolved section rather than silently disassembling it. Replay one section at a time and expose its text heights.++Documentation blocks default to left-aligned visible glyphs, not merely aligned calculation boxes. Use the readable left edge on both faces, including bottom reflection. The dashboard must not recenter a shorter font rendering inside the EDA-measured box. Native exports may use equivalent centered anchors computed from measured glyph bounds, provided the actual ink shares the left edge.++### Visual consistency across connector groups+Treat repeated connector labels as a designed row or column. Prefer shared outer border rails, common widths/heights, padding, reference/value hierarchy and consistent spacing. Solve these at group level before independent placement. Reserve actual strokes against holes, masks and bodies. Never stretch borders after collision checks. Use consistent safe clearance gaps where needed; report any individual inside placement or sizing exception. Apply semantic importance first: ESC PHASE A/B/C are prominent functional labels. Documentation sections retain ordered, left-aligned text and headings rather than scattered rows.++Pin-label alignment is target-facing, not universally centered: right-align ink for labels left of their pad, left-align for labels right of their pad. Evaluate this in the visible face orientation, reversing it for the bottom view. Store the electrical target and alignment intent, keep measured native bounds, and avoid wasted visual gap between ink and the pad. Center only when it improves an intentionally symmetric group.
tools/silkscreen-dashboard/index.html+33−13
@@ -6,31 +6,51 @@ :root{--bg:#0d1117;--surface:#161b22;--border:#30363d;--accent:#00b8b1;font-family:Satoshi,sans-serif;color:#c9d1d9;background:var(--bg)} body{grid-template-rows:44px 44px 1fr 66px}header{height:44px;padding:0 16px;gap:16px;background:var(--surface);border-color:var(--border)} .brand{display:flex;align-items:center;gap:8px;font:600 16px Familjen,sans-serif;color:var(--accent);position:relative;white-space:nowrap}.brand img{width:16px;height:16px}.subject{border-left:1px solid var(--border);padding-left:16px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:#e6edf3}.actions{margin-left:auto;display:flex;gap:8px}.actions button{width:32px;height:32px;padding:6px}.actions svg{width:18px;height:18px;fill:none;stroke:#e6edf3;stroke-width:1.8}.toolbar{display:flex;gap:12px;align-items:center;padding:4px 16px;background:var(--surface);border-bottom:1px solid var(--border)}button,select,input{background:#21262d;border-color:var(--border);border-radius:8px}button:hover{border-color:var(--accent)}button.active{background:#163e3d}aside{background:var(--surface)}h2{font-family:Familjen,sans-serif}.muted,p{color:#8b949e}#settings{top:50%;left:50%;right:auto;transform:translate(-50%,-50%);min-width:340px;z-index:20;box-shadow:0 0 0 100vmax #0004;background:#21262d;border-color:var(--border)}#appinfo{position:absolute;top:30px;left:0;width:320px;padding:16px;background:#21262d;border:1px solid var(--border);border-radius:8px;z-index:25;color:#c9d1d9;white-space:normal;font:14px Satoshi,sans-serif;pointer-events:auto}#textsize{font-variant-numeric:tabular-nums;color:#e6edf3;padding:10px 0}#fit{margin-left:0}@media(max-width:720px){.subject{display:none}.toolbar{gap:5px}main{grid-template-columns:1fr 210px}}-</style></head><body><header><div class="brand" tabindex="0"><img src="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%23e6edf3%22%20stroke-width%3D%221.8%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Crect%20x%3D%223%22%20y%3D%223%22%20width%3D%2218%22%20height%3D%2218%22%20rx%3D%222%22/%3E%3Cpath%20d%3D%22M7%2016V8h4M7%2012h3M14%208h3M15.5%208v8M14%2016h3%22/%3E%3C/svg%3E" alt=""><span>Adom AI Flow · Silkscreen</span><div id="appinfo" hidden>Silkscreen dashboard · development build<br>Prototype: Rust CLI, Python helpers, browser UI<br>Authored by Codex Astra<br><a href="https://wiki.adom.inc/adom/adom-aiflow">AI Flow wiki and source</a></div></div><div class="subject"><span id="subject">Board</span> <span class="muted"> · full-board label placement</span></div><div class="actions"><button id="gear" aria-label="Settings" title="Settings"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="3"/><path d="m9 3-1 3-3 1 1 3-2 2 2 2-1 3 3 1 1 3h6l1-3 3-1-1-3 2-2-2-2 1-3-3-1-1-3z"/></svg></button></div></header><div class="toolbar"><span id="mode" class="badge">Connecting</span><select id="face" aria-label="Board face"><option value="F.SilkS">Top only</option><option value="B.SilkS">Bottom only</option></select><button id="two" class="active">2D layout</button><button id="threeBtn">3D inspection</button><button id="fit">Fit board</button></div><main><div id="stage"><canvas id="board"></canvas><div id="three"></div><div id="hud"><div id="headline">Loading board geometry</div><div class="muted" id="geometry"></div></div></div><aside><div class="muted">Placement decision</div><h2 id="part">Waiting</h2><p id="reason">No solver events yet.</p><div id="progress"><span></span></div><div id="count"></div><div id="textsize">Text height in mm appears with each placement</div><p id="native">Native CAD review pending</p><label>Inspect component <select id="pick"><option value="">Whole board</option></select></label><div id="legend"><div><i class="swatch" style="background:#516a78"></i>Fitted body / reserved envelope</div><div><i class="swatch" style="background:#cbad4c"></i>Via / mask opening</div><div><i class="swatch" style="background:#ffb963"></i>Sampled candidate</div><div><i class="swatch" style="background:#57dcc4"></i>Selected proposal</div><div><i class="swatch" style="background:#f18389"></i>Existing collision</div></div><p class="muted">Selection is a proposal, not an edit to the EDA board. Native text bounds drive collision checks. Preview text uses the browser font.</p><div id="error"></div></aside></main><footer><button id="live">Follow live</button><button id="play">Replay</button><input type="range" id="scrub" min="-1" max="0" value="-1" aria-label="Event timeline"><span id="stamp" class="muted">0 / 0</span><button id="record">Record walkthrough</button><button id="short">Record 5s overview</button></footer><div id="settings" hidden><b>Playback & display</b><label>Events per second <input id="speed" type="number" min="0.5" max="60" step="0.5"></label><label><input id="obstacles" type="checkbox"> Show obstacles</label><label><input id="follow" type="checkbox" checked> Follow selected component</label><label>Idle shutdown, hours <input id="ttl" type="number" min="1" max="168"></label><p class="muted">No AI/provider calls. Solver runs independently of playback.</p></div>++#gear{display:grid;place-items:center;flex:0 0 32px;padding:6px}#gear svg{display:block;flex:none;width:20px;height:20px;aspect-ratio:1;stroke-width:1.8}+#settings{position:fixed;inset:0;margin:auto;transform:none;width:min(560px,calc(100vw - 32px));min-width:0;max-height:calc(100vh - 32px);padding:0;overflow:hidden;border:1px solid #30363d;border-radius:12px;background:#161b22;color:#e6edf3;box-shadow:0 16px 60px #0006}+#settings::backdrop{background:rgba(0,0,0,.25);backdrop-filter:none}.settings-heading{display:flex;align-items:center;justify-content:space-between;padding:16px 18px;border-bottom:1px solid #30363d;cursor:move}.settings-heading h2{font-size:18px;margin:0}.settings-heading button{display:grid;place-items:center;width:32px;height:32px;padding:5px}.settings-body{padding:18px;max-height:65vh;overflow:auto;scrollbar-width:thin;scrollbar-color:#6e768166 transparent}.settings-card{background:#1c2128;border:1px solid #30363d;border-left:3px solid #00b8b173;border-radius:10px;padding:14px 17px;margin-bottom:16px}.settings-card:last-child{margin-bottom:0}.card-title{font-size:13px;font-weight:600;display:flex;align-items:center;gap:10px}.card-status{font-size:11px;color:#8b949e;font-weight:400}.card-desc{font-size:12px;line-height:1.55;color:#8b949e}.setting-row{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:10px 0;border-top:1px solid #30363d}#settings .setting-row label{margin:0;font-size:13px;line-height:1.5}.setting-row label span{color:#00b8b1}.setting-row small{display:block;color:#8b949e;font-size:11px}.setting-row input{width:86px;font-size:13px}.settings-footer{border-top:1px solid #30363d;padding:14px 18px;display:flex;align-items:center;justify-content:space-between;gap:16px;font-size:11px;color:#8b949e}.settings-footer button{font-size:12px}+.toggle{background:none;border:none;padding:2px;cursor:pointer;flex-shrink:0;transition:transform .06s ease}.toggle-track{display:block;width:32px;height:18px;background:#21262d;border:1px solid #30363d;border-radius:9px;position:relative;transition:background .15s,border-color .15s}.toggle:hover .toggle-track{border-color:#00b8b1}.toggle:active{transform:translateY(1px) scale(.97)}.toggle[aria-checked="true"] .toggle-track{background:#00b8b1;border-color:#00b8b1}.toggle-thumb{position:absolute;top:2px;left:2px;width:12px;height:12px;background:#fff;border-radius:50%;transition:transform .18s,width .12s}.toggle[aria-checked="true"] .toggle-thumb{transform:translateX(14px)}.toggle:active .toggle-thumb{width:16px}.toggle[aria-checked="true"]:active .toggle-thumb{transform:translateX(10px)}button:focus-visible,input:focus-visible{outline:2px solid #00b8b1;outline-offset:2px}button:active{transform:translateY(1px)}#settings-toast{position:fixed;bottom:80px;left:50%;transform:translateX(-50%);background:#21262d;border:1px solid #30363d;border-left:3px solid #00b8b1;padding:10px 16px;border-radius:8px;z-index:100}+</style></head><body><header><div class="brand" tabindex="0"><img src="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%23e6edf3%22%20stroke-width%3D%221.8%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Crect%20x%3D%223%22%20y%3D%223%22%20width%3D%2218%22%20height%3D%2218%22%20rx%3D%222%22/%3E%3Cpath%20d%3D%22M7%2016V8h4M7%2012h3M14%208h3M15.5%208v8M14%2016h3%22/%3E%3C/svg%3E" alt=""><span>Adom AI Flow · Silkscreen</span><div id="appinfo" hidden>Silkscreen dashboard · development build<br>Prototype: Rust CLI, Python helpers, browser UI<br>Authored by Codex Astra<br><a href="https://wiki.adom.inc/adom/adom-aiflow">AI Flow wiki and source</a></div></div><div class="subject"><span id="subject">Board</span> <span class="muted"> · full-board label placement</span></div><div class="actions"><button id="gear" aria-label="Settings" title="Settings"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24"+     fill="none" stroke="#e6edf3" stroke-width="1.8"+     stroke-linecap="round" stroke-linejoin="round">+  <!-- THE Adom settings cog: a true line drawing (strokes, no filled silhouette).+       Hardcoded #e6edf3 because this file is loaded as its own document via+       <img src> / favicon, where currentColor would resolve to black. Inline+       copies pasted into markup may swap the stroke to currentColor. -->+  <circle cx="12" cy="12" r="3"/>+  <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/>+</svg>+</button></div></header><div class="toolbar"><span id="faceCue" class="badge">Top · F.SilkS</span><span id="mode" class="badge">Connecting</span><select id="face" aria-label="Board face"><option value="F.SilkS">Top only</option><option value="B.SilkS">Bottom only</option></select><button id="two" class="active">2D layout</button><button id="threeBtn">3D inspection</button><button id="fit">Fit board</button></div><main><div id="stage"><canvas id="board"></canvas><div id="three"></div><div id="hud"><div id="headline">Loading board geometry</div><div class="muted" id="geometry"></div></div></div><aside><div class="muted">Placement decision</div><h2 id="part">Waiting</h2><p id="reason">No solver events yet.</p><div id="progress"><span></span></div><div id="count"></div><div id="textsize">Text height in mm appears with each placement</div><p id="native">Native CAD review pending</p><label>Inspect component <select id="pick"><option value="">Whole board</option></select></label><div id="legend"><div><i class="swatch" style="border:1px dashed #ffd479;opacity:.5"></i>Dashed 50%: calculation guides only</div><div>Solid text, pointers and outlines: printed silkscreen</div><div><i class="swatch" style="background:#516a78"></i>Fitted body / reserved envelope</div><div><i class="swatch" style="background:#cbad4c"></i>Via / mask opening</div><div><i class="swatch" style="background:#ffb963"></i>Sampled candidate</div><div><i class="swatch" style="background:linear-gradient(90deg,#ffd479 50%,#79b8ff 50%)"></i>Placed: top gold / bottom blue</div><div><i class="swatch" style="background:#f18389"></i>Existing collision</div></div><p class="muted">Selection is a proposal, not an edit to the EDA board. Native text bounds drive collision checks. Preview text uses the browser font.</p><div id="error"></div></aside></main><footer><button id="live">Follow live</button><button id="play">Replay</button><input type="range" id="scrub" min="-1" max="0" value="-1" aria-label="Event timeline"><span id="stamp" class="muted">0 / 0</span><button id="record">Record walkthrough</button><button id="short">Record 5s overview</button></footer><dialog id="settings" tabindex="-1" aria-labelledby="settings-title"><div class="settings-heading"><h2 id="settings-title">Silkscreen Settings</h2><button id="close-settings" aria-label="Close settings" title="Close settings"><svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="1.8"><path d="m6 6 12 12M18 6 6 18"/></svg></button></div><div class="settings-body"><section class="settings-card"><div class="card-title">Playback and display <span class="card-status">Applies immediately</span></div><p class="card-desc">Replay the recorded placement decisions at your own pace. Calculation guides are dashed and translucent; solid marks represent the silkscreen sent to the EDA tool. These controls do not change the board.</p><div class="setting-row"><label for="speed">Replay / <span>Speed</span><small>Default: 4 events per second</small></label><input id="speed" type="number" min="0.5" max="60" step="0.5" title="Changes playback speed, preserving every recorded event."></div><div class="setting-row"><label id="guides-label">Display / <span>Calculation guides</span><small>Default: On</small></label><button id="obstacles" class="toggle" role="switch" aria-labelledby="guides-label" aria-checked="true" title="Show dashed text bounds, model envelopes and hole obstacles. Printed silkscreen stays visible."><span class="toggle-track"><span class="toggle-thumb"></span></span></button></div><div class="setting-row"><label id="follow-label">Camera / <span>Follow placement</span><small>Default: On · this view only</small></label><button id="follow" class="toggle" role="switch" aria-labelledby="follow-label" aria-checked="true" title="Frame each placement during replay. Manual zoom or pan turns this off."><span class="toggle-track"><span class="toggle-thumb"></span></span></button></div></section><section class="settings-card"><div class="card-title">Local server <span class="card-status">No provider calls</span></div><p class="card-desc">The dashboard reads saved geometry and events from this run. Its idle timer stops the dashboard server after inactivity; saved board files and recordings remain on disk.</p><div class="setting-row"><label for="ttl">Server / <span>Idle shutdown</span><small>Default: 24 hours</small></label><input id="ttl" type="number" min="1" max="168" title="Hours without dashboard activity before the local server shuts down."></div></section></div><div class="settings-footer"><span>Settings save on this machine.<br>Development build · native review required.</span><button id="restore-settings">Restore defaults</button></div></dialog><div id="settings-toast" role="status" hidden></div> <script type="module">-const $=s=>document.querySelector(s),canvas=$('#board'),ctx=canvas.getContext('2d');let data,history=[],state={},selected='',bounds,view,drag=null,viewer=null,scene=null,labelTexture=null,threeGroups=[],recording=false,handledRecording=null,recordReplay;const api=async(path,body)=>{const r=await fetch(path,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({...body,aiThread:state.aiThread||'Silkscreen dashboard user'})});const j=await r.json();if(!r.ok)throw Error(j.error);if(j.state)await apply(j.state);return j};window.silkscreen={ready:false};+const $=s=>document.querySelector(s),canvas=$('#board'),ctx=canvas.getContext('2d');let data,history=[],state={},selected='',bounds,view,drag=null,viewer=null,scene=null,labelTexture=null,threeGroups=[],recording=false,handledRecording=null,recordReplay;const api=async(path,body)=>{const r=await fetch(path,{method:'POST',headers:{'Content-Type':'application/json'},signal:path==='settings'?AbortSignal.timeout(5000):undefined,body:JSON.stringify({...body,aiThread:state.aiThread||'Silkscreen dashboard user'})});const j=await r.json();if(!r.ok)throw Error(j.error);if(j.state)await apply(j.state);return j};window.silkscreen={ready:false};for(const id of ['obstacles','follow'])Object.defineProperty($('#'+id),'checked',{get(){return this.getAttribute('aria-checked')==='true'},set(v){this.setAttribute('aria-checked',String(!!v))}}); let cameraAnimation=0;function frame(b){cancelAnimationFrame(cameraAnimation);if(recording&&!state.summary&&view){const from=[...view],start=performance.now();const tick=now=>{const t=Math.min(1,(now-start)/220),ease=t*t*(3-2*t);view=from.map((v,i)=>v+(b[i]-v)*ease);draw();if(t<1)cameraAnimation=requestAnimationFrame(tick)};cameraAnimation=requestAnimationFrame(tick)}else{view=[...b];draw()}} function fitPart(ref){const os=data.obstacles.filter(o=>o.reference===ref&&o.layer===state.layer);if(!os.length)return;const b=[Math.min(...os.map(o=>o.box[0]))-3,Math.min(...os.map(o=>o.box[1]))-3,Math.max(...os.map(o=>o.box[2]))+3,Math.max(...os.map(o=>o.box[3]))+3];frame(b);if(viewer){const cam=viewer.getCamera();cam.setTarget(new window.BABYLON.Vector3((b[0]+b[2])/2,-(b[1]+b[3])/2,0));cam.radius=Math.max(b[2]-b[0],b[3]-b[1])*1.8}} function proposals(){const map=new Map();let start=0;for(let k=Math.min(state.cursor,history.length-1);k>=0;k--)if(history[k].kind==='start'){start=k;break}for(let k=start;k<=state.cursor&&k<history.length;k++){const e=history[k];if(e.kind==='placement')map.set(e.id,e.candidate)}return map}-function paint(c,w,h,extent,texture=false){c.clearRect(0,0,w,h);if(!texture){c.fillStyle='#122128';c.fillRect(0,0,w,h)}const bw=extent[2]-extent[0],bh=extent[3]-extent[1],scale=Math.min(w/bw,h/bh)*.93,sx=texture?w/bw:scale,sy=texture?h/bh:scale,ox=texture?-extent[0]*sx:(w-bw*scale)/2-extent[0]*scale,oy=texture?-extent[1]*sy:(h-bh*scale)/2-extent[1]*scale;c.save();c.translate(ox,oy);c.scale(sx,sy);c.lineWidth=1/scale;-function rect(b,color,fill=true){c.fillStyle=color;c.strokeStyle=color;if(fill)c.fillRect(b[0],b[1],b[2]-b[0],b[3]-b[1]);else c.strokeRect(b[0],b[1],b[2]-b[0],b[3]-b[1])}-if(!texture){rect(data.bounds,'#233b32');if(state.settings?.showObstacles)for(const o of data.obstacles){if(o.layer!==state.layer)continue;const col=o.kind.startsWith('fitted')?(o.reference===selected?'#607b87':'#394d58'):o.kind.startsWith('via')?'#bd9f43':'#889081';if(o.kind.startsWith('via')){const b=o.box;c.beginPath();c.arc((b[0]+b[2])/2,(b[1]+b[3])/2,(b[2]-b[0])/2,0,Math.PI*2);c.strokeStyle=col;c.stroke()}else rect(o.box,col,true)}}-const placed=proposals();const replaced=new Set([...placed.values()].flatMap(p=>(p.children||[]).map(x=>x.index)));-function label(l,color,b){if(l.leaderCurve){const p=l.leaderCurve;c.beginPath();c.moveTo(...p[0]);c.bezierCurveTo(...p[1],...p[2],...p[3]);c.strokeStyle=color;c.lineWidth=.08;c.stroke()}c.save();c.translate(l.x??l.position?.[0]??0,l.y??l.position?.[1]??0);c.rotate(-(l.angle||0)*Math.PI/180);c.font=`${l.size||l.font||.5}px sans-serif`;c.textAlign='center';c.textBaseline='middle';c.fillStyle=color;(l.text||'').split('\n').forEach((s,i,all)=>c.fillText(s,0,(i-(all.length-1)/2)*(l.size||l.font||.5)*1.5));c.restore();if(!texture&&b)rect(b,color,false)}+function paint(c,w,h,extent,texture=false){c.clearRect(0,0,w,h);if(!texture){c.fillStyle='#122128';c.fillRect(0,0,w,h)}const bw=extent[2]-extent[0],bh=extent[3]-extent[1],scale=Math.min(w/bw,h/bh)*.93,sx=texture?w/bw:scale,sy=texture?h/bh:scale,ox=texture?-extent[0]*sx:(w-bw*scale)/2-extent[0]*scale,oy=texture?-extent[1]*sy:(h-bh*scale)/2-extent[1]*scale;c.save();c.translate(ox,oy);c.scale(sx,sy);const bottomFace=state.layer==='B.SilkS';if(bottomFace&&!texture){c.translate(extent[0]+extent[2],0);c.scale(-1,1)}c.lineWidth=1/scale;+function rect(b,color,fill=true){c.save();c.fillStyle=color;c.strokeStyle=color;if(fill)c.fillRect(b[0],b[1],b[2]-b[0],b[3]-b[1]);else{c.globalAlpha=.5;c.setLineDash([5/scale,4/scale]);c.lineWidth=1/scale;c.strokeRect(b[0],b[1],b[2]-b[0],b[3]-b[1])}c.restore()}+if(!texture){rect(data.bounds,'#233b32');if(state.settings?.showObstacles)for(const o of data.obstacles){if(o.layer!==state.layer)continue;const col=o.kind.startsWith('fitted')?(o.reference===selected?'#607b87':'#394d58'):o.kind.startsWith('via')?'#bd9f43':'#889081';if(o.kind.startsWith('via')){const b=o.box;c.beginPath();c.arc((b[0]+b[2])/2,(b[1]+b[3])/2,(b[2]-b[0])/2,0,Math.PI*2);c.save();c.globalAlpha=.5;c.setLineDash([5/scale,4/scale]);c.strokeStyle=col;c.stroke();c.restore()}else{c.save();c.globalAlpha=.5;rect(o.box,col,true);c.restore();rect(o.box,col,false)}}}+const faceColor=state.layer==='B.SilkS'?'#79b8ff':'#ffd479';const placed=proposals();const replaced=new Set([...placed.values()].flatMap(p=>(p.children||[]).map(x=>x.index)));+function label(l,color,b){if(l.associationSegments){c.save();c.strokeStyle=color;c.lineWidth=.06;for(const line of l.associationSegments){c.beginPath();line.forEach((p,i)=>i?c.lineTo(...p):c.moveTo(...p));c.stroke()}c.restore()}if(l.associationOutline){c.beginPath();l.associationOutline.forEach((p,i)=>i?c.lineTo(...p):c.moveTo(...p));c.strokeStyle=color;c.lineWidth=.06;c.stroke()}if(l.leaderCurve){const p=l.leaderCurve;c.beginPath();c.moveTo(...p[0]);c.bezierCurveTo(...p[1],...p[2],...p[3]);c.strokeStyle=color;c.lineWidth=.08;c.stroke()}const aligned=Boolean(l.section||l.textAlign==='left'||l.alignmentTarget)&&l.box&&!(l.angle||0),edgeIndex=l.alignmentTarget?(l.alignmentTarget[0]>(l.box[0]+l.box[2])/2?2:0):(bottomFace?2:0),inkAlign=((edgeIndex===2)!==bottomFace)?'right':'left';c.save();c.translate(aligned?l.box[edgeIndex]:(l.x??l.position?.[0]??0),l.y??l.position?.[1]??0);c.rotate(-(l.angle||0)*Math.PI/180);if(bottomFace)c.scale(-1,1);c.font=`${l.size||l.font||.5}px sans-serif`;c.textAlign=aligned?inkAlign:'center';c.textBaseline='middle';c.fillStyle=color;(l.text||'').split('\n').forEach((s,i,all)=>{c.font=`${l.lineSizes?.[i]||l.size||l.font||.5}px sans-serif`;const yy=(i-(all.length-1)/2)*(l.size||l.font||.5)*1.5;if(aligned)c.fillText(s,0,yy,l.box[2]-l.box[0]);else c.fillText(s,0,yy)});c.restore();if(!texture&&b)rect(b,color,false)} for(let i=0;i<data.labels.length;i++){const l=data.labels[i];if(data.freshPlacement||l.layer!==state.layer||replaced.has(i))continue;label(l,l.collision?'#f1838999':'#bfccc666')}-for(const p of placed.values()){if(p.layer&&p.layer!==state.layer)continue;for(const child of p.children||[p]){const original=child.index!=null?data.labels[child.index]:null;if(original&&original.layer!==state.layer)continue;label(child,'#79f5d9',texture?null:child.box)}}+for(const p of placed.values()){if(p.layer&&p.layer!==state.layer)continue;for(const child of p.children||[p]){const original=child.index!=null?data.labels[child.index]:null;if(original&&original.layer!==state.layer)continue;label(child,faceColor,!texture&&state.settings?.showObstacles?child.box:null)}} const e=history[state.cursor];if(e?.candidate){const cs=e.candidate.children||[e.candidate];$('#textsize').textContent=cs.map(x=>(x.text||e.id)+': '+Number(x.size||x.font||0).toFixed(2)+' mm').join(' · ')}if(!texture&&e?.kind==='candidate'&&(!e.layer||e.layer===state.layer)&&(!e.candidate.layer||e.candidate.layer===state.layer)){for(const b of e.candidate.boxes||[e.candidate.box])rect(b,'#ffbd70',false);for(const child of e.candidate.children||[e.candidate])label(child,'#ffbd70')}c.restore();if(!texture&&recording){c.fillStyle='#101820df';c.fillRect(12,h-62,w-24,48);c.fillStyle='#dfece8';c.font='16px system-ui';c.fillText('REPLAY · '+(e?.id||'Silkscreen')+' · '+(e?.reason||e?.kind||''),24,h-33)} } function draw(){if(!data||!view)return;const r=canvas.getBoundingClientRect();canvas.width=Math.max(1,r.width*devicePixelRatio);canvas.height=Math.max(1,r.height*devicePixelRatio);paint(ctx,canvas.width,canvas.height,view);if(labelTexture){const t=labelTexture.getContext();paint(t,2048,2048,data.bounds,true);labelTexture.update(false)}} async function show3d(){if(viewer)return;$('#headline').textContent='Loading 3D geometry';try{await import('https://wiki.adom.inc/static/vendor/adom-3d-viewer-babylon9/adom-3d-viewer-babylon9.esm.js?v=20260915a');const B=window.BABYLON;viewer=window.Adom3DViewerBabylon9.init($('#three'),{zUp:true,showGround:false,showViewCube:false});scene=viewer.getScene();const b=data.bounds,cx=(b[0]+b[2])/2,cy=(b[1]+b[3])/2;const board=B.MeshBuilder.CreateBox('Board envelope',{width:b[2]-b[0],height:b[3]-b[1],depth:1.6},scene);board.position.set(cx,-cy,-.8);const bm=new B.PBRMaterial('board',scene);bm.albedoColor=B.Color3.FromHexString('#24563b');bm.metallic=0;bm.roughness=.85;board.material=bm; for(const o of data.obstacles.filter(o=>o.kind.startsWith('fitted'))){const b=o.box;const mesh=B.MeshBuilder.CreateBox(o.reference,{width:b[2]-b[0],height:b[3]-b[1],depth:o.height||1},scene);mesh.position.set((b[0]+b[2])/2,-(b[1]+b[3])/2,(o.height||1)/2+.03);const mat=new B.StandardMaterial('reserved envelope',scene);mat.diffuseColor=B.Color3.FromHexString('#5b707d');mat.alpha=.72;mesh.material=mat;threeGroups.push({mesh,o});if(o.glb){try{const imported=await B.SceneLoader.ImportMeshAsync('',o.glb,'',scene),group=new B.TransformNode('fitted_'+o.reference,scene);for(const m of imported.meshes)if(!m.parent)m.parent=group;group.scaling.setAll(1000);const theta=(o.at[2]||0)*Math.PI/180,dx=o.offset?.[0]||0,dy=o.offset?.[1]||0;group.position.set(o.at[0]+dx*Math.cos(theta)-dy*Math.sin(theta),-o.at[1]+dx*Math.sin(theta)+dy*Math.cos(theta),o.offset?.[2]||0);group.rotation.z=theta;mesh.setEnabled(false);const buckets=new Map();for(const m of imported.meshes){if(!m.getTotalVertices())continue;m.computeWorldMatrix(true);const mat=m.material,key=JSON.stringify([mat?.albedoColor?.asArray(),mat?.diffuseColor?.asArray(),mat?.emissiveColor?.asArray(),mat?.alpha,mat?.metallic,mat?.roughness]);if(!buckets.has(key))buckets.set(key,[]);buckets.get(key).push(m)}for(const ms of buckets.values()){const mat=ms[0].material;for(const m of ms)m.material=mat;if(ms.length>1)B.Mesh.MergeMeshes(ms,true,true,undefined,false,false)}}catch(error){$('#error').textContent='Model fallback for '+o.reference+': '+error.message}}} labelTexture=new B.DynamicTexture('silkscreen proposals',{width:2048,height:2048},scene,false);labelTexture.hasAlpha=true;const plane=B.MeshBuilder.CreatePlane('Silkscreen preview',{width:b[2]-b[0],height:b[3]-b[1]},scene);plane.position.set(cx,-cy,.015);const pm=new B.StandardMaterial('silkscreen',scene);pm.diffuseTexture=labelTexture;pm.opacityTexture=labelTexture;pm.useAlphaFromDiffuseTexture=true;pm.emissiveColor=B.Color3.White();pm.disableLighting=true;pm.backFaceCulling=false;plane.material=pm;viewer.getCamera().setTarget(new B.Vector3(cx,-cy,0));viewer.getCamera().radius=100;viewer.getCamera().beta=.65;viewer.getCamera().alpha=-1.6;viewer.getCamera().minZ=.01;viewer.getCamera().upperRadiusLimit=300;draw();$('#subject').textContent=data.name||data.sourceBoard||'Board';if(data.nativeReview)$('#native').textContent=data.nativeReview;$('#geometry').textContent='Fitted component models · rectangular board preview · native CAD review still required';}catch(e){$('#error').textContent=e.message}}-async function apply(s){const oldTotal=history.length;if(s.events)history=s.events;else if(s.total!==oldTotal){const full=await(await fetch('state')).json();history=full.events}const changedFace=s.layer&&s.layer!==state.layer;state={...state,...s};if(changedFace){selected='';view=[...bounds]}window.silkscreen.state=state;const e=history[state.cursor];$('#mode').textContent=state.mode==='live'?'Live solver feed':'Recorded-event replay';$('#part').textContent=e?.id||'Whole board';$('#reason').textContent=e?.reason|| (e?.kind==='complete'?`Search complete; ${e.unresolved?.length??0} unresolved groups.`:'Waiting for the next solver event.');$('#headline').textContent=e?.kind==='complete'?'Candidate layout · review pending':e?.id?`${e.id} · ${e.kind}`:'ESC silkscreen placement';$('#face').value=state.layer;$('#stamp').textContent=`${Math.max(0,state.cursor+1)} / ${history.length}`;$('#scrub').max=Math.max(0,history.length-1);$('#scrub').value=state.cursor;$('#count').textContent=`${[...proposals().values()].filter(p=>!p.layer||p.layer===state.layer).length} labels placed on this face`;$('#progress span').style.width=(history.length?(state.cursor+1)/history.length*100:0)+'%';$('#play').textContent=state.playing?'Pause':'Replay';$('#speed').value=state.settings.speed;$('#ttl').value=state.settings.ttlHours;$('#obstacles').checked=state.settings.showObstacles;const focus=e?.candidate?.children?.[0]?.reference||e?.id;if(focus&&selected!==focus&&$('#follow').checked){selected=focus;const child=e?.candidate?.children?.[0];if(child?.box&&!child.reference){const b=child.box;frame([b[0]-3,b[1]-3,b[2]+3,b[3]+3])}else fitPart(selected)}$('#three').style.display=state.view==='3d'?'block':'none';$('#board').style.visibility=state.view==='3d'?'hidden':'visible';if(state.view==='3d'){await show3d();if(scene){const plane=scene.getMeshByName('Silkscreen preview');if(plane)plane.position.z=state.layer==='B.SilkS'?-1.615:.015;if(s.layer)viewer.getCamera().beta=state.layer==='B.SilkS'?Math.PI-.65:.65}}draw();if(state.recordRequest&&state.recordRequest.id!==handledRecording){handledRecording=state.recordRequest.id;setTimeout(()=>recordReplay(state.recordRequest.kind==='overview').catch(e=>$('#error').textContent=e.message),0)}}+async function apply(s){const oldTotal=history.length;if(s.events)history=s.events;else if(s.total!==oldTotal){const full=await(await fetch('state')).json();history=full.events}const changedFace=s.layer&&s.layer!==state.layer;state={...state,...s};if(changedFace){selected='';view=[...bounds]}window.silkscreen.state=state;const e=history[state.cursor];$('#mode').textContent=state.mode==='live'?'Live solver feed':'Recorded-event replay';$('#part').textContent=e?.id||'Whole board';$('#reason').textContent=e?.reason|| (e?.kind==='complete'?`Search complete; ${e.unresolved?.length??0} unresolved groups.`:'Waiting for the next solver event.');$('#headline').textContent=e?.kind==='complete'?'Candidate layout · review pending':e?.id?`${e.id} · ${e.kind}`:'ESC silkscreen placement';$('#face').value=state.layer;const bottom=state.layer==='B.SilkS';$('#faceCue').textContent=bottom?'Bottom · B.SilkS · viewed from below':'Top · F.SilkS · viewed from above';$('#faceCue').style.color=bottom?'#79b8ff':'#ffd479';$('#faceCue').style.borderColor=bottom?'#79b8ff':'#ffd479';$('#stage').style.boxShadow='inset 0 4px '+(bottom?'#64abff':'#e07c75');$('#stamp').textContent=`${Math.max(0,state.cursor+1)} / ${history.length}`;$('#scrub').max=Math.max(0,history.length-1);$('#scrub').value=state.cursor;$('#count').textContent=`${[...proposals().values()].filter(p=>!p.layer||p.layer===state.layer).length} labels placed on this face`;$('#progress span').style.width=(history.length?(state.cursor+1)/history.length*100:0)+'%';$('#play').textContent=state.playing?'Pause':'Replay';$('#speed').value=state.settings.speed;$('#ttl').value=state.settings.ttlHours;$('#obstacles').checked=state.settings.showObstacles;const focus=e?.candidate?.children?.[0]?.reference||e?.id;if(focus&&selected!==focus&&$('#follow').checked){selected=focus;const child=e?.candidate?.children?.[0];if(child?.box&&!child.reference){const b=child.box;frame([b[0]-3,b[1]-3,b[2]+3,b[3]+3])}else fitPart(selected)}$('#three').style.display=state.view==='3d'?'block':'none';$('#board').style.visibility=state.view==='3d'?'hidden':'visible';if(state.view==='3d'){await show3d();if(scene){const plane=scene.getMeshByName('Silkscreen preview');if(plane)plane.position.z=state.layer==='B.SilkS'?-1.615:.015;if(s.layer)viewer.getCamera().beta=state.layer==='B.SilkS'?Math.PI-.65:.65}}draw();if(state.recordRequest&&state.recordRequest.id!==handledRecording){handledRecording=state.recordRequest.id;setTimeout(()=>recordReplay(state.recordRequest.kind==='overview').catch(e=>$('#error').textContent=e.message),0)}} try{data=await(await fetch('board.json')).json();bounds=data.bounds;view=[...bounds];const refs=[...new Set(data.obstacles.filter(o=>o.kind.startsWith('fitted')).map(o=>o.reference))].sort();for(const r of refs){const o=document.createElement('option');o.value=r;o.textContent=r;$('#pick').append(o)}$('#subject').textContent=data.name||data.sourceBoard||'Board';if(data.nativeReview)$('#native').textContent=data.nativeReview;$('#geometry').textContent=`${refs.length} fitted bodies · ${data.viaCount} vias · native measured text bounds`; await apply(await(await fetch('state')).json());const stream=new EventSource('stream');stream.addEventListener('state',e=>apply(JSON.parse(e.data)).catch(e=>$('#error').textContent=e.message));stream.onerror=()=>$('#mode').textContent='Reconnecting';window.silkscreen.ready=true;-$('#live').onclick=()=>api('control',{mode:'live'});$('#play').onclick=()=>api('control',{mode:'replay',summary:false,playing:!state.playing,cursor:state.cursor>=history.length-1?-1:state.cursor});$('#scrub').oninput=e=>api('control',{mode:'replay',playing:false,cursor:+e.target.value});$('#face').onchange=e=>api('control',{layer:e.target.value});$('#two').onclick=()=>api('control',{view:'2d'});$('#threeBtn').onclick=()=>api('control',{view:'3d'});$('#fit').onclick=()=>{selected='';frame(bounds);if(viewer){const b=bounds;viewer.getCamera().setTarget(new window.BABYLON.Vector3((b[0]+b[2])/2,-(b[1]+b[3])/2,0));viewer.getCamera().radius=100}};$('#pick').onchange=e=>{selected=e.target.value;$('#follow').checked=false;selected?fitPart(selected):frame(bounds)};$('#gear').onclick=()=>$('#settings').hidden=!$('#settings').hidden;$('#speed').onchange=e=>api('settings',{speed:+e.target.value});$('#ttl').onchange=e=>api('settings',{ttlHours:+e.target.value});$('#obstacles').onchange=e=>api('settings',{showObstacles:e.target.checked});-canvas.onwheel=e=>{e.preventDefault();const f=e.deltaY>0?1.15:.87;const r=canvas.getBoundingClientRect(),px=(e.clientX-r.left)/r.width,py=(e.clientY-r.top)/r.height,w=view[2]-view[0],h=view[3]-view[1];view=[view[0]+w*px*(1-f),view[1]+h*py*(1-f),view[0]+w*px*(1-f)+w*f,view[1]+h*py*(1-f)+h*f];draw()};canvas.onpointerdown=e=>{drag={x:e.clientX,y:e.clientY,v:[...view]};canvas.setPointerCapture(e.pointerId)};canvas.onpointermove=e=>{if(!drag)return;const r=canvas.getBoundingClientRect(),dx=(e.clientX-drag.x)/r.width*(drag.v[2]-drag.v[0]),dy=(e.clientY-drag.y)/r.height*(drag.v[3]-drag.v[1]);view=[drag.v[0]-dx,drag.v[1]-dy,drag.v[2]-dx,drag.v[3]-dy];draw()};canvas.onpointerup=()=>drag=null;-const captureCanvas=document.createElement('canvas');captureCanvas.width=1920;captureCanvas.height=1080;const captureCtx=captureCanvas.getContext('2d');function paintCapture(){paint(captureCtx,1920,1080,view);captureCtx.fillStyle='#0d1117e8';captureCtx.fillRect(0,0,1920,50);captureCtx.fillStyle='#e6edf3';captureCtx.font='22px sans-serif';captureCtx.fillText('Adom AI Flow · '+(state.layer==='F.SilkS'?'Top':'Bottom')+' silkscreen · '+$('#textsize').textContent,20,32)}+$('#live').onclick=()=>api('control',{mode:'live'});$('#play').onclick=()=>api('control',{mode:'replay',summary:false,playing:!state.playing,cursor:state.cursor>=history.length-1?-1:state.cursor});$('#scrub').oninput=e=>api('control',{mode:'replay',playing:false,cursor:+e.target.value});$('#face').onchange=e=>api('control',{layer:e.target.value});$('#two').onclick=()=>api('control',{view:'2d'});$('#threeBtn').onclick=()=>api('control',{view:'3d'});$('#fit').onclick=()=>{selected='';frame(bounds);if(viewer){const b=bounds;viewer.getCamera().setTarget(new window.BABYLON.Vector3((b[0]+b[2])/2,-(b[1]+b[3])/2,0));viewer.getCamera().radius=100}};$('#pick').onchange=e=>{selected=e.target.value;$('#follow').checked=false;selected?fitPart(selected):frame(bounds)};let toastTimer,restoreTimer,restoreArmed=false;function toast(message){const t=$('#settings-toast');t.textContent=message;t.hidden=false;clearTimeout(toastTimer);toastTimer=setTimeout(()=>t.hidden=true,3000)}async function saveSettings(patch){try{await api('settings',patch);toast('Settings saved')}catch(e){toast('Could not save: '+e.message)}}const dlg=$('#settings');$('#gear').onclick=()=>{dlg.showModal();dlg.focus();$('.settings-body').scrollTop=0;requestAnimationFrame(()=>$('.settings-body').scrollTop=0)};$('#close-settings').onclick=()=>dlg.close();dlg.addEventListener('click',e=>{if(e.target!==dlg)return;const r=dlg.getBoundingClientRect();if(e.clientX<r.left||e.clientX>r.right||e.clientY<r.top||e.clientY>r.bottom)dlg.close()});$('#speed').onchange=e=>saveSettings({speed:+e.target.value});$('#ttl').onchange=e=>saveSettings({ttlHours:+e.target.value});$('#obstacles').onclick=e=>{const b=$('#obstacles');b.checked=!b.checked;saveSettings({showObstacles:b.checked})};$('#follow').onclick=()=>{const b=$('#follow');b.checked=!b.checked;toast(b.checked?'Camera follows placement':'Manual camera control')};$('#restore-settings').onclick=()=>{if(!restoreArmed){restoreArmed=true;$('#restore-settings').textContent='Confirm restore';restoreTimer=setTimeout(()=>{restoreArmed=false;$('#restore-settings').textContent='Restore defaults'},5000);return}clearTimeout(restoreTimer);restoreArmed=false;$('#restore-settings').textContent='Restore defaults';$('#follow').checked=true;saveSettings({speed:4,ttlHours:24,showObstacles:true})};let modalDrag;$('.settings-heading').onpointerdown=e=>{if(e.target.closest('button'))return;const r=dlg.getBoundingClientRect();modalDrag={x:e.clientX,y:e.clientY,left:r.left,top:r.top};e.currentTarget.setPointerCapture(e.pointerId)};$('.settings-heading').onpointermove=e=>{if(!modalDrag)return;dlg.style.margin='0';dlg.style.left=Math.max(0,Math.min(innerWidth-dlg.offsetWidth,modalDrag.left+e.clientX-modalDrag.x))+'px';dlg.style.top=Math.max(0,Math.min(innerHeight-dlg.offsetHeight,modalDrag.top+e.clientY-modalDrag.y))+'px';dlg.style.right='auto';dlg.style.bottom='auto'};$('.settings-heading').onpointerup=$('.settings-heading').onpointercancel=()=>modalDrag=null;+function boardPoint(clientX,clientY,v=view){const r=canvas.getBoundingClientRect(),w=v[2]-v[0],h=v[3]-v[1],scale=Math.min(r.width/w,r.height/h)*.93;const dx=(clientX-r.left-r.width/2)/scale,dy=(clientY-r.top-r.height/2)/scale;return [(v[0]+v[2])/2+(state.layer==='B.SilkS'?-dx:dx),(v[1]+v[3])/2+dy]}+window.silkscreen.camera={pointAt:(x,y)=>boardPoint(x,y),get extent(){return [...view]}};+function manualCamera(){cancelAnimationFrame(cameraAnimation);$('#follow').checked=false}+canvas.addEventListener('wheel',e=>{e.preventDefault();if(!view||!e.deltaY)return;manualCamera();const r=canvas.getBoundingClientRect(),delta=e.deltaY*(e.deltaMode===1?16:e.deltaMode===2?r.height:1),requested=Math.exp(Math.max(-1,Math.min(1,delta*.0015))),span=Math.max(view[2]-view[0],view[3]-view[1]),f=Math.max(.5,Math.min(1000,span*requested))/span,p=boardPoint(e.clientX,e.clientY);view=view.map((v,i)=>p[i%2]+(v-p[i%2])*f);draw()},{passive:false});+canvas.onpointerdown=e=>{if(!view)return;manualCamera();drag={x:e.clientX,y:e.clientY,v:[...view]};canvas.setPointerCapture(e.pointerId)};canvas.onpointermove=e=>{if(!drag)return;const a=boardPoint(drag.x,drag.y,drag.v),b=boardPoint(e.clientX,e.clientY,drag.v),dx=b[0]-a[0],dy=b[1]-a[1];view=[drag.v[0]-dx,drag.v[1]-dy,drag.v[2]-dx,drag.v[3]-dy];draw()};canvas.onpointerup=canvas.onpointercancel=()=>drag=null;++const captureCanvas=document.createElement('canvas');captureCanvas.width=1920;captureCanvas.height=1080;const captureCtx=captureCanvas.getContext('2d');function paintCapture(){paint(captureCtx,1920,1080,view);captureCtx.fillStyle='#0d1117e8';captureCtx.fillRect(0,0,1920,50);captureCtx.fillStyle='#e6edf3';captureCtx.font='22px sans-serif';captureCtx.fillStyle=state.layer==='B.SilkS'?'#79b8ff':'#ffd479';captureCtx.fillText('Adom AI Flow · '+(state.layer==='F.SilkS'?'Top, viewed from above':'Bottom, viewed from below')+' silkscreen · '+$('#textsize').textContent,20,32)} recordReplay=async function(summary=false){if(recording)return;const latest=history.map((e,i)=>e.kind==='start'?i:-1).filter(i=>i>=0).pop()||0;await api('control',{mode:'replay',playing:false,summary,cursor:latest-1,view:'2d'});$('#follow').checked=!summary;frame(bounds);recording=true;const chunks=[],rec=new MediaRecorder(captureCanvas.captureStream(30),{mimeType:'video/webm'});rec.ondataavailable=e=>chunks.push(e.data);rec.onstop=()=>{recording=false;const blob=new Blob(chunks,{type:'video/webm'}),a=document.createElement('a');window.silkscreen.recordingBlob=blob;const reader=new FileReader();reader.onload=()=>api('recording',{kind:summary?'overview':'walkthrough',video:reader.result.split(',')[1]}).catch(e=>$('#error').textContent=e.message);reader.readAsDataURL(blob);a.href=URL.createObjectURL(blob);a.download='silkscreen-replay.webm';a.click();$('#record').textContent='Record replay';draw()};paintCapture();rec.start();$('#record').textContent='Recording replay…';await api('control',{playing:true});const timer=setInterval(()=>{draw();paintCapture();if(!state.playing&&state.cursor>=history.length-1){clearInterval(timer);frame(bounds);const hold=setInterval(paintCapture,33);setTimeout(()=>{clearInterval(hold);paintCapture();rec.stop()},1200)}},100)};$('#record').onclick=()=>recordReplay(false);$('#short').onclick=()=>recordReplay(true);-let infoTimer;const brand=$('.brand'),info=$('#appinfo');brand.onmouseenter=()=>{clearTimeout(infoTimer);infoTimer=setTimeout(()=>info.hidden=false,600)};brand.onmouseleave=()=>{clearTimeout(infoTimer);infoTimer=setTimeout(()=>info.hidden=true,220)};brand.onfocus=()=>info.hidden=false;document.addEventListener('keydown',e=>{if(e.key==='Escape'){$('#settings').hidden=true;info.hidden=true}});+let infoTimer;const brand=$('.brand'),info=$('#appinfo');brand.onmouseenter=()=>{clearTimeout(infoTimer);infoTimer=setTimeout(()=>info.hidden=false,600)};brand.onmouseleave=()=>{clearTimeout(infoTimer);infoTimer=setTimeout(()=>info.hidden=true,220)};brand.onfocus=()=>info.hidden=false;document.addEventListener('keydown',e=>{if(e.key==='Escape'){if($('#settings').open)$('#settings').close();info.hidden=true}}); new ResizeObserver(draw).observe($('#stage'));draw();}catch(e){$('#error').textContent=e.stack} </script></body></html>
tools/silkscreen-dashboard/settings-cog-outline.svgadded+10
@@ -0,0 +1,10 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24"+     fill="none" stroke="#e6edf3" stroke-width="1.8"+     stroke-linecap="round" stroke-linejoin="round">+  <!-- THE Adom settings cog: a true line drawing (strokes, no filled silhouette).+       Hardcoded #e6edf3 because this file is loaded as its own document via+       <img src> / favicon, where currentColor would resolve to black. Inline+       copies pasted into markup may swap the stroke to currentColor. -->+  <circle cx="12" cy="12" r="3"/>+  <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/>+</svg>
tools/silkscreen-kicad-mask.pyadded+62
@@ -0,0 +1,62 @@+#!/usr/bin/env python3+"""KiCad mask obstacles, including complete custom-pad primitives, in board mm.+Does not substitute a custom pad's anchor for its copper/mask polygon.+Unsupported custom primitives fail closed. Caller supplies body/via obstacles.+"""+import json,re,math,argparse+from pathlib import Path+from shapely.geometry import Polygon,Point,LineString,box,mapping+from shapely.affinity import rotate,translate+from shapely.ops import unary_union++def parse(text):+ ts=iter(re.findall(r'"(?:\\.|[^"\\])*"|[^\s()]+|[()]',text))+ def rec():+  a=[]+  for t in ts:+   if t==')':return a+   a.append(rec() if t=='(' else json.loads(t) if t.startswith('"') else t)+  return a+ return rec()[0]+def sub(n,k):return [x for x in n if isinstance(x,list) and x and x[0]==k]+def one(n,k):return next(iter(sub(n,k)),[k])[1:]+def xy(n,k):return tuple(map(float,one(n,k)[:2]))+def primitive(n):+ kind=n[0];width=float((one(n,'width') or [0])[0]);fill=one(n,'fill')==['yes']+ if kind=='gr_poly':+  p=Polygon([tuple(map(float,v[1:3])) for v in one(n,'pts') if v[0]=='xy']);g=p if fill else p.exterior+ elif kind=='gr_rect':+  a,b=xy(n,'start'),xy(n,'end');p=box(min(a[0],b[0]),min(a[1],b[1]),max(a[0],b[0]),max(a[1],b[1]));g=p if fill else p.exterior+ elif kind=='gr_line':g=LineString([xy(n,'start'),xy(n,'end')])+ elif kind=='gr_circle':+  center=xy(n,'center');p=Point(center).buffer(math.dist(center,xy(n,'end')),quad_segs=24);g=p if fill else p.exterior+ else:raise ValueError('Unsupported custom-pad primitive: '+kind)+ return g.buffer(width/2) if width else g++def pad_shape(p):+ w,h=map(float,one(p,'size'));kind=p[3];rect=box(-w/2,-h/2,w/2,h/2)+ if kind=='custom':+  primitives=one(p,'primitives')+  if not primitives:raise ValueError('Custom pad without primitives')+  anchor=one(one(p,'options'),'anchor');base=Point(0,0).buffer(min(w,h)/2) if anchor==['circle'] else rect+  return unary_union([base]+[primitive(n) for n in primitives])+ if kind=='rect':return rect+ if kind=='circle':return Point(0,0).buffer(w/2,quad_segs=24)+ if kind=='oval':return LineString([(-(w-h)/2,0),((w-h)/2,0)]).buffer(h/2) if w>=h else LineString([(0,-(h-w)/2),(0,(h-w)/2)]).buffer(w/2)+ if kind=='roundrect':+  r=min(w,h)*float((one(p,'roundrect_rratio') or [0])[0]);return box(-w/2+r,-h/2+r,w/2-r,h/2-r).buffer(r) if r else rect+ raise ValueError('Unsupported mask pad shape: '+kind)+def obstacles(root,clearance=0.0):+ result=[];setup=one(root,'setup');globalmargin=float((one(setup,'pad_to_mask_clearance') or [0])[0])+ for f in sub(root,'footprint'):+  ref=next((x[2] for x in sub(f,'property') if x[1]=='Reference'),'?');at=list(map(float,one(f,'at')));fa=at[2] if len(at)>2 else 0;fm=float((one(f,'solder_mask_margin') or [globalmargin])[0])+  for idx,p in enumerate(sub(f,'pad')):+   layers=one(p,'layers');sides=[s for s in ['F','B'] if s+'.Mask' in layers or '*.Mask' in layers]+   if not sides:continue+   pa=list(map(float,one(p,'at')));angle=pa[2] if len(pa)>2 else fa;center=rotate(Point(pa[:2]),-fa,origin=(0,0));margin=float((one(p,'solder_mask_margin') or [fm])[0]);g=pad_shape(p).buffer(margin+clearance)+   if g.is_empty:continue+   g=translate(rotate(g,-angle,origin=(0,0)),at[0]+center.x,at[1]+center.y)+   for side in sides:result.append(dict(id=f'{ref}:pad:{p[1]}:{idx}',reference=ref,pad=p[1],kind='pad-mask-or-hole',layer=side+'.SilkS',polygon=mapping(g),box=list(g.bounds),sourceShape=p[3],maskMargin=margin,silkClearance=clearance))+ return result+if __name__=='__main__':+ p=argparse.ArgumentParser();p.add_argument('--board',required=True);p.add_argument('--out',required=True);a=p.parse_args();r=obstacles(parse(Path(a.board).read_text()));Path(a.out).write_text(json.dumps(r));print(len(r),'native mask obstacles; custom pads',sum(o['sourceShape']=='custom' for o in r))
tools/silkscreen-layout.py+18−5
@@ -33,11 +33,20 @@ def solve_milp(spec,groups):   k=len(lo);rr.extend([k]*len(indices));cc.extend(indices);vv.extend([1.]*len(indices));lo.append(lower);hi.append(upper)  for ix in group_indices:row(ix,1,1)  gap=spec.get('clearance',.12)- for i,(g,a) in enumerate(candidates):-  if a.get('unresolved'):continue-  for j in range(i):+ # Spatial broad phase keeps full-board grouped candidate sets practical.+ from shapely.geometry import box as geometry_box+ from shapely.strtree import STRtree+ valid=[i for i,(_,a) in enumerate(candidates) if not a.get('unresolved')]+ tree=STRtree([geometry_box(*candidates[i][1]['box']).buffer(gap) for i in valid])+ for i in valid:+  g,a=candidates[i]+  nearby={valid[int(k)] for k in tree.query(geometry_box(*a['box']))}+  if g.get('orderGroup'):+   nearby.update(j for j in valid if candidates[j][0].get('orderGroup')==g['orderGroup'])+  for j in nearby:+   if j>=i:continue    h,b=candidates[j]-   if h['id']==g['id'] or b.get('unresolved'):continue+   if h['id']==g['id']:continue    bad_order=g.get('orderGroup') and g.get('orderGroup')==h.get('orderGroup') and (g['order']-h['order'])*(a['position'][1]-b['position'][1])<=0    conflict=bad_order or any(overlap(x,y,gap) for x in a.get('boxes',[a['box']]) for y in b.get('boxes',[b['box']]))    if conflict:row([i,j],-np.inf,1)@@ -51,6 +60,10 @@ def solve(spec):  for g in spec['labels']:   cs=[];sampled=0   for c in g['candidates']:+   if g.get('requiredRoles'):+    roles={x.get('role'):x for x in c.get('children',[])}+    if any(role not in roles for role in g['requiredRoles']):continue+    if 'reference' in roles and 'value' in roles and roles['value']['size']>roles['reference']['size']*g.get('maxValueRatio',.8):continue    if not all(math.isfinite(v) for v in c['box']) or c['box'][0]>=c['box'][2] or c['box'][1]>=c['box'][3]:raise ValueError('invalid bounds '+g['id'])    if math.dist(c['position'],g['anchor'])>g.get('maxDistance',math.inf):continue    rects=c.get('boxes',[c['box']])@@ -59,7 +72,7 @@ def solve(spec):    if reason.startswith('clears'):cs.append(c)   # Prefer large legible text, locality next, and stability last. Caller can tune units.   for c in cs:-   distance=math.dist(c['position'],g['anchor']);motion=math.dist(c['position'],g.get('previous',c['position']));c['score']=c['font']*spec.get('fontWeight',100)-distance*spec.get('distanceWeight',1)-motion*.1-(abs(c['position'][1]-g['anchor'][1])*spec.get('rowWeight',0) if g.get('orderGroup') else 0)-max(0,spec.get('preferredMinimumFont',0)-c['font'])*spec.get('smallFontPenalty',1000)+   distance=math.dist(c['position'],g['anchor']);motion=math.dist(c['position'],g.get('previous',c['position']));c['score']=-c.get('qualityPenalty',0)+c['font']*spec.get('fontWeight',100)-distance*spec.get('distanceWeight',1)-motion*.1-(abs(c['position'][1]-g['anchor'][1])*spec.get('rowWeight',0) if g.get('orderGroup') else 0)-max(0,spec.get('preferredMinimumFont',0)-c['font'])*spec.get('smallFontPenalty',1000)   cs.sort(key=lambda c:-c['score']);groups.append((g,cs[:spec.get('candidatesPerLabel',100)]))  if spec.get('solver')=='milp':return solve_milp(spec,groups)  # Most constrained first; beam alternatives allow earlier placements to be revised.
tools/silkscreen-pairs.pyadded+61
@@ -0,0 +1,61 @@+#!/usr/bin/env python3+"""Repair a reviewed layout using atomic reference/value candidates.+Input: labels with native normalized offsets, board outline, fixed obstacle polygons,+component anchors and body polygons. Existing non-pair labels are reserved unchanged.+Prior positions are explicit candidates, not represented as a fresh solve.+"""+import argparse,json,math,importlib.util+from pathlib import Path+from collections import defaultdict+from shapely.geometry import shape,box,Point+from shapely.ops import unary_union+from shapely.prepared import prep++def generate(d):+ labels=d['labels'];outline=shape(d['outline']);pairs=defaultdict(list)+ for i,l in enumerate(labels):+  if l.get('reference') and not l.get('pin') and l['layer']=='F.SilkS' and l['reference'].startswith(('R','C')):pairs[l['reference']].append(i)+ pairs={r:ids for r,ids in pairs.items() if len(ids)==2 and any('value' in labels[i]['role'] for i in ids)}+ paired={i for ids in pairs.values() for i in ids}+ fixed=prep(unary_union([shape(o) for o in d['obstacles']]+([] if d.get('fresh') else [box(*l['box']) for i,l in enumerate(labels) if l['layer']=='F.SilkS' and i not in paired])))+ def bounds(i,size,angle):+  l=labels[i];o=l['offset'];a=math.radians(l.get('angle',0)-angle);ps=[((u*math.cos(a)-v*math.sin(a))*size,(u*math.sin(a)+v*math.cos(a))*size) for u,v in [(o[0],o[1]),(o[0],o[3]),(o[2],o[1]),(o[2],o[3])]];xs,ys=zip(*ps);return[min(xs),min(ys),max(xs),max(ys)]+ groups=[]+ for ref,ids in pairs.items():+  ids.sort(key=lambda i:'value' in labels[i]['role']);anchor=d['parts'][ref]['anchor'];body=shape(d['parts'][ref]['body']);cs=[]+  def candidate(children,origin):+   gs=[box(*c['box']) for c in children]+   if any(not outline.contains(g) or fixed.intersects(g) for g in gs) or gs[0].buffer(.02).intersects(gs[1]):return+   if any(g.distance(body)>1.5 for g in gs):return+   bb=unary_union(gs).bounds;center=[(bb[0]+bb[2])/2,(bb[1]+bb[3])/2];separation=gs[0].distance(gs[1]);fs,vs=[c['size'] for c in children]+   cs.append(dict(font=round(fs+vs*.2,4),position=center,box=list(bb),boxes=[c['box'] for c in children],children=children,origin=origin,qualityPenalty=separation*12+(0 if children[0]['angle']==children[1]['angle'] else 2)))+  def child(i,size,angle,x,y):+   b=bounds(i,size,angle);return dict(index=i,reference=ref,text=labels[i]['text'],role='value' if 'value' in labels[i]['role'] else 'reference',layer='F.SilkS',size=size,angle=angle,x=x,y=y,box=[b[0]+x,b[1]+y,b[2]+x,b[3]+y])+  # Reviewed locations remain a repair candidate only when hierarchy is satisfied.+  for fs in [.8,.7,.6,.5,.4,.35,.3,.25]:+   if fs<.25:continue+   for vs in [.4,.35,.3,.25,.2]:+    if vs>fs*.8:continue+    if not d.get('fresh'):candidate([child(i,s,labels[i].get('angle',0),labels[i]['x'],labels[i]['y']) for i,s in zip(ids,[fs,vs])],'reviewed-position repair')+    for angle in [0,90]:+     bs=[bounds(i,s,angle) for i,s in zip(ids,[fs,vs])]+     for horizontal in [False,True]:+      w=[b[2]-b[0] for b in bs];h=[b[3]-b[1] for b in bs]+      # Shared edge/alignment; secondary value always smaller and adjacent.+      centers=[(0,0),(0,(h[0]+h[1])/2+.08)] if not horizontal else [(0,0),((w[0]+w[1])/2+.10,0)]+      local=[(cx-(b[0]+b[2])/2,cy-(b[1]+b[3])/2) for (cx,cy),b in zip(centers,bs)]+      bb=unary_union([box(b[0]+x,b[1]+y,b[2]+x,b[3]+y) for b,(x,y) in zip(bs,local)]).bounds+      x0,y0,x1,y1=body.bounds+      for gap in [.06,.2,.45]:+       for shift in [0,-.25,.25,-.5,.5,-.8,.8]:+        positions=[(anchor[0]+shift-(bb[0]+bb[2])/2,y0-gap-bb[3]),(anchor[0]+shift-(bb[0]+bb[2])/2,y1+gap-bb[1]),(x0-gap-bb[2],anchor[1]+shift-(bb[1]+bb[3])/2),(x1+gap-bb[0],anchor[1]+shift-(bb[1]+bb[3])/2)]+        for x,y in positions:candidate([child(i,s,angle,x+dx,y+dy) for i,s,(dx,dy) in zip(ids,[fs,vs],local)],'joint pair search')+  # Keep spatial diversity so neighboring groups can negotiate room.+  buckets={}+  for c in cs:+   key=(c['font'],round(c['position'][0]*2),round(c['position'][1]*2));score=c['qualityPenalty']+math.dist(c['position'],anchor)+   if key not in buckets or score<buckets[key][0]:buckets[key]=(score,c)+  cs=[v[1] for v in buckets.values()];groups.append(dict(id=ref,anchor=anchor,candidates=cs,requiredRoles=['reference','value'],maxValueRatio=.8));print(ref,len(cs),flush=True)+ return dict(bounds=list(outline.bounds),labels=groups,clearance=.025,solver='milp',solverSeconds=60,milpPerFont=5,candidatesPerLabel=1000,fontWeight=20,distanceWeight=3)+if __name__=='__main__':+ p=argparse.ArgumentParser();p.add_argument('--input',required=True);p.add_argument('--out',required=True);a=p.parse_args();Path(a.out).write_text(json.dumps(generate(json.loads(Path(a.input).read_text()))))
tools/silkscreen-preflight.pyadded+43
@@ -0,0 +1,43 @@+#!/usr/bin/env python3+"""Independent polygon preflight for text, pointer strokes and enclosure strokes.+Inputs must include native mask polygons, fitted bodies, holes and existing artwork.+Fail closed for missing required inventory or invalid association geometry.+"""+import json,argparse+from pathlib import Path+from shapely.geometry import shape,box,LineString+from shapely.strtree import STRtree++def check(data):+ errors=[];placements=data['placements'];obstacles=data['obstacles'];required=set(data.get('requiredIndices',[]));present=[p['index'] for p in placements]+ if not required:errors.append(dict(kind='missing-coverage-contract'))+ for i in sorted(required-set(present)):errors.append(dict(kind='missing-label',index=i))+ if len(present)!=len(set(present)):errors.append(dict(kind='duplicate-label'))+ for side in ['F.SilkS','B.SilkS']:+  obs=[o for o in obstacles if o['layer']==side];geoms=[shape(o['polygon']) for o in obs];tree=STRtree(geoms)+  marks=[(p['index'],'text',box(*p['box'])) for p in placements if p['layer']==side]+  for g in data.get('graphics',[]):+   if g['layer']==side:marks.append((g['index'],g['kind'],LineString(g['samples']).buffer(g.get('width',.06)/2)))+  for index,kind,g in marks:+   if not g.is_valid:errors.append(dict(kind='invalid-mark',index=index));continue+   for k in tree.query(g):+    o=obs[int(k)];other=geoms[int(k)]+    if g.intersection(other).area>1e-7:errors.append(dict(kind='obstacle-collision',index=index,mark=kind,obstacle=o.get('id',o['reference']),obstacleKind=o['kind'],layer=side))+  # Text rectangles may not overlap. Association lines also reserve their stroke width.+  tree=STRtree([g for _,_,g in marks])+  for k,(index,kind,g) in enumerate(marks):+   for j in tree.query(g):+    j=int(j)+    if j>=k:continue+    otherindex,otherkind,other=marks[j]+    if kind!='text' and otherkind!='text':continue # joined segments are allowed+    if g.intersection(other).area>1e-7:errors.append(dict(kind='mark-collision',index=index,otherIndex=otherindex,mark=kind,otherMark=otherkind,layer=side))+ groups={}+ for p in placements:+  if p.get('reference') and p.get('role') in ['reference','value']:groups.setdefault((p['layer'],p['reference']),{})[p['role']]=p+  if p.get('lineSizes') and any(z>=p['lineSizes'][0] for z in p['lineSizes'][1:]):errors.append(dict(kind='multiline-hierarchy',index=p['index']))+ for (side,ref),g in groups.items():+  if 'value' in g and ('reference' not in g or g['value']['size']>g['reference']['size']*.8):errors.append(dict(kind='pair-hierarchy',reference=ref,layer=side))+ return dict(passed=not errors,errors=errors,labels=len(placements),graphics=len(data.get('graphics',[])),obstacles=len(obstacles),nativeVerified=False)+if __name__=='__main__':+ p=argparse.ArgumentParser();p.add_argument('--input',required=True);p.add_argument('--out',required=True);a=p.parse_args();r=check(json.loads(Path(a.input).read_text()));Path(a.out).write_text(json.dumps(r,indent=2));print(('OK' if r['passed'] else 'ERROR')+': '+str(len(r['errors']))+' preflight findings');raise SystemExit(0 if r['passed'] else 2)
tools/silkscreen-sections.pyadded+70
@@ -0,0 +1,70 @@+"""Place semantic documentation blocks; never scatter or reorder their rows.+Native measured bounds are supplied by the EDA adapter. World coordinates/mm.+"""+import numpy as np+import shapely+from shapely.geometry import box+from shapely.ops import unary_union++def place_sections(sections, labels, bounds, outline, obstacle, occupied, side):+    x0,y0,x1,y1=outline.bounds+    gx,gy=np.meshgrid(np.arange(x0,x1,.35),np.arange(y0,y1,.35))+    gx,gy=gx.ravel(),gy.ravel()+    accepted=[]; unresolved=[]; reports=[]+    for section in sections:+        chosen=None+        for font in section.get('fonts',[.6,.5,.4,.35,.3]):+            rows=section['rows']; ncols=max(map(len,rows)); colwidth=[]+            for col in range(ncols):+                colwidth.append(max([bounds(i,font*section.get('sizeFactors',{}).get(str(i),1),0)[2]-bounds(i,font*section.get('sizeFactors',{}).get(str(i),1),0)[0] for row in rows for j,i in enumerate(row) if j==col]+[0])+.8)+            raw=[]; y=0+            for row in rows:+                h=max(bounds(i,font*section.get('sizeFactors',{}).get(str(i),1),0)[3]-bounds(i,font*section.get('sizeFactors',{}).get(str(i),1),0)[1] for i in row)+                for col,i in enumerate(row):+                    size=font*section.get('sizeFactors',{}).get(str(i),1); b=bounds(i,size,0)+                    # Bottom is viewed from below: align right in board coordinates,+                    # which becomes a shared left edge in the readable bottom view.+                    dx=sum(colwidth[:col])-(b[2] if side=='B.SilkS' else b[0]);dy=y-b[1]+                    raw.append((i,size,dx,dy,[b[0]+dx,b[1]+dy,b[2]+dx,b[3]+dy]))+                y+=h+max(.28,font*.65)+            envelope=unary_union([box(*r[4]) for r in raw]).bounds+            valid=shapely.contains(outline,shapely.box(gx+envelope[0],gy+envelope[1],gx+envelope[2],gy+envelope[3]))+            # Reserve the whole section against other labels, but permit holes+            # between rows when the actual strokes have clearance.+            valid &= ~shapely.intersects(occupied,shapely.box(gx+envelope[0]-.15,gy+envelope[1]-.15,gx+envelope[2]+.15,gy+envelope[3]+.15))+            for _,_,_,_,b in raw:+                indices=np.flatnonzero(valid)+                if not len(indices):break+                geoms=shapely.box(gx[indices]+b[0]-.045,gy[indices]+b[1]-.045,gx[indices]+b[2]+.045,gy[indices]+b[3]+.045)+                valid[indices] &= ~shapely.intersects(obstacle,geoms)+            indices=np.flatnonzero(valid)+            if len(indices):+                ax,ay=section['anchor']; n=indices[np.argmin((gx[indices]+(envelope[0]+envelope[2])/2-ax)**2+(gy[indices]+(envelope[1]+envelope[3])/2-ay)**2)]+                chosen=[]+                for i,size,dx,dy,b in raw:+                    l=labels[i];chosen.append(dict(index=i,text=l['text'],reference=None,layer=side,role=l['role'],section=section['id'],textAlign='left',x=float(gx[n]+dx),y=float(gy[n]+dy),size=size,angle=0,box=[float(b[0]+gx[n]),float(b[1]+gy[n]),float(b[2]+gx[n]),float(b[3]+gy[n])]))+                occupied=unary_union([occupied,box(envelope[0]+gx[n]-.15,envelope[1]+gy[n]-.15,envelope[2]+gx[n]+.15,envelope[3]+gy[n]+.15)])+                reports.append(dict(id=section['id'],font=font,indices=[p['index'] for p in chosen],status='placed'));break+        if chosen:accepted+=chosen+        else:+            ids=[i for row in section['rows'] for i in row];unresolved+=ids;reports.append(dict(id=section['id'],status='unresolved',indices=ids))+    return accepted,unresolved,occupied,reports++if __name__=='__main__':+    import argparse,json+    from pathlib import Path+    from shapely.geometry import shape,GeometryCollection+    p=argparse.ArgumentParser();p.add_argument('--input',required=True);p.add_argument('--out',required=True);a=p.parse_args()+    d=json.loads(Path(a.input).read_text());metrics=d['metrics']+    def bounds(i,size,angle):+        if angle:raise ValueError('Documentation sections require readable horizontal rows')+        return [v*size for v in metrics[str(i)]]+    out=[];missing=[];reports=[]+    for side in ['F.SilkS','B.SilkS']:+        obstacle=unary_union([shape(o['polygon']) for o in d['obstacles'] if o['layer']==side])+        occupied=unary_union([box(*p['box']).buffer(.035) for p in d.get('placements',[]) if p['layer']==side])+        ps,ms,_,rs=place_sections([s for s in d['sections'] if s['layer']==side],d['labels'],bounds,shape(d['outline']),obstacle,occupied,side)+        out+=ps;missing+=ms;reports+=rs+    Path(a.out).write_text(json.dumps(dict(placements=out,unresolved=missing,sections=reports),indent=2))+    print(('ERROR' if missing else 'OK')+f': {len(out)} documentation labels in ordered sections; {len(missing)} unresolved')+    raise SystemExit(2 if missing else 0)
tools/test-silkscreen-contact-policy.pyadded+19
@@ -0,0 +1,19 @@+import importlib.util,copy+from pathlib import Path+from shapely.geometry import box,Point,mapping+sp=importlib.util.spec_from_file_location('policy',Path(__file__).with_name('silkscreen-contact-policy.py'));m=importlib.util.module_from_spec(sp);sp.loader.exec_module(m)+g=dict(outline=mapping(box(0,0,10,10)),bodies={'F.SilkS':{'MC1':mapping(Point(2,5).buffer(.4))}},obstacles=[dict(reference='MC1',kind='pad-mask-or-hole',layer='F.SilkS',polygon=mapping(Point(2,5).buffer(.4)))])+def cand(x,font):+ bb=[x-.2,4.8,x+.2,5.2];return dict(font=font,position=[x,5],box=bb,boxes=[bb],children=[dict(index=0,reference='MC1',layer='F.SilkS',box=bb)])+s=dict(labels=[dict(id='MC1',anchor=[2,5],candidates=[cand(.8,.4),cand(3.5,.8)])]);on=m.apply_policy(copy.deepcopy(s),g);assert len(on['labels'][0]['candidates'])==2+outer,inner=on['labels'][0]['candidates'];assert outer['contactSide']=='outside';assert inner['contactSide']=='inside';assert outer['font']*20-outer['qualityPenalty']>inner['font']*20-inner['qualityPenalty'];assert outer['children'][0]['contactBorder'];assert len(outer['boxes'])>1+off=m.apply_policy(copy.deepcopy(s),g,False);assert all(not c['children'][0].get('contactBorder') for c in off['labels'][0]['candidates']);assert off['labels'][0]['candidates'][0]['contactSide']=='outside'+print('PASS: outside preference outranks font; border strokes reserved; optional off preserves side policy')+labels=[];bodies={};obstacles=[]+for k,y in enumerate([3,5,7]):+ ref=f'MC{k+1}';body=mapping(Point(2,y).buffer(.4));bodies[ref]=body;obstacles.append(dict(reference=ref,kind='pad-mask-or-hole',layer='F.SilkS',polygon=body));bb=[.5,y-.25,1.0+k*.2,y+.25]+ labels.append(dict(id=ref,anchor=[2,y],orderGroup='left-column',candidates=[dict(font=.5,position=[.8,y],box=bb,boxes=[bb],children=[dict(index=k,reference=ref,layer='F.SilkS',box=bb)])]))+a=m.apply_policy(dict(labels=labels),dict(outline=mapping(box(0,0,10,10)),bodies={'F.SilkS':bodies},obstacles=obstacles))+bs=[l['candidates'][0]['sharedBorderBounds'] for l in a['labels']]+assert len({(round(b[0],5),round(b[2],5),round(b[3]-b[1],5)) for b in bs})==1+print('PASS: unequal text widths retain shared border rails and row height')
tools/test-silkscreen-kicad-mask.pyadded+18
@@ -0,0 +1,18 @@+import importlib.util+from pathlib import Path+from shapely.geometry import shape,box+sp=importlib.util.spec_from_file_location('mask',Path(__file__).with_name('silkscreen-kicad-mask.py'));m=importlib.util.module_from_spec(sp);sp.loader.exec_module(m)+# ESC regression: rotated MOSFET drain mask extends far beyond the 1 mm anchor.+s='''(kicad_pcb (setup (pad_to_mask_clearance 0.09))+(footprint X (at 154 107 180) (property "Reference" "Q1")+(pad "5" smd custom (at 1.05 0 180) (size 1 1) (layers "F.Cu" "F.Mask")+(options (anchor rect)) (primitives (gr_poly (pts (xy -2.375 -2.305) (xy 2.375 -2.305) (xy 2.375 2.305) (xy -2.375 2.305)) (width 0) (fill yes))))))'''+o=m.obstacles(m.parse(s));assert len(o)==1;g=shape(o[0]['polygon']);assert g.intersects(box(149.928,106.387,150.788,107.613));assert abs(g.bounds[0]-150.485)<1e-6+# Global mask margin is applied exactly once; footprint rotation transforms position.+s='''(kicad_pcb (setup (pad_to_mask_clearance 0.09)) (footprint X (at 127.7 85.2 90) (property "Reference" "C6") (pad "1" smd roundrect (at -0.48 0 90) (size 0.56 0.62) (roundrect_rratio 0.25) (layers "F.Cu" "F.Mask"))))'''+g=shape(m.obstacles(m.parse(s))[0]['polygon']);assert all(abs(a-b)<1e-6 for a,b in zip(g.bounds,[127.3,85.31,128.1,86.05]))+# An unknown primitive must not silently fall back to the anchor rectangle.+try:m.primitive(['gr_unknown'])+except ValueError:pass+else:raise AssertionError('unsupported geometry accepted')+print('PASS: complete custom mask, rotated coordinates, margin once, unsupported geometry refused')
tools/test-silkscreen-layout.py+6
@@ -18,3 +18,9 @@ print('PASS: compound bounds retain empty space and pin rows stay ordered') # Optional MILP must trade a larger label for two readable labels rather than a tiny fallback. s={'solver':'milp','bounds':[-1,-1,6,3],'clearance':0,'preferredMinimumFont':.3,'smallFontPenalty':1000,'distanceWeight':0,'labels':[{'id':'a','anchor':[0,0],'candidates':[c(0,.6),c(2,.4)]},{'id':'b','anchor':[0,0],'candidates':[c(0,.4),c(4,.2)]}]} r=m.solve(s);assert not r['unresolved'];assert all(x['font']>=.3 for x in r['placements']);print('PASS: MILP avoids a tiny fallback when repacking fits both labels')+# Missing values and equal-size values are invalid even if their score is higher.+g={'id':'C1','anchor':[0,0],'requiredRoles':['reference','value'],'maxValueRatio':.8,'candidates':[]}+for roles,font in [([{'role':'reference','size':.8}],.9),([{'role':'reference','size':.4},{'role':'value','size':.4}],.8),([{'role':'reference','size':.4},{'role':'value','size':.25}],.4)]:+ x=c(0,font);x['children']=roles;g['candidates'].append(x)+r=m.solve({'bounds':[-1,-1,6,3],'labels':[g]});assert not r['unresolved'];assert r['placements'][0]['font']==.4+print('PASS: required pair roles and reference/value hierarchy cannot be traded for score')
tools/test-silkscreen-sections.pyadded+18
@@ -0,0 +1,18 @@+import importlib.util,unittest+from pathlib import Path+from shapely.geometry import box,GeometryCollection+s=importlib.util.spec_from_file_location('sections',Path(__file__).with_name('silkscreen-sections.py'));m=importlib.util.module_from_spec(s);s.loader.exec_module(m)+class Sections(unittest.TestCase):+ def test_rows_stay_ordered_and_bottom_reading_edge_aligns(self):+  labels=[dict(text=t,role='service-key') for t in ['Heading','a longer row','short']]+  bounds=lambda i,z,a:[-len(labels[i]['text'])*z/3,-z/2,len(labels[i]['text'])*z/3,z/2]+  section=dict(id='test',rows=[[0],[1],[2]],anchor=[10,10],sizeFactors={'0':1.5})+  for side in ['F.SilkS','B.SilkS']:+   p,missing,_,r=m.place_sections([section],labels,bounds,box(0,0,20,20),box(8,8,9,9),GeometryCollection(),side)+   self.assertEqual(missing,[]);self.assertEqual([x['index'] for x in p],[0,1,2]);self.assertTrue(p[0]['y']<p[1]['y']<p[2]['y']);self.assertGreater(p[0]['size'],p[1]['size'])+   edge=2 if side=='B.SilkS' else 0+   self.assertAlmostEqual(p[0]['box'][edge],p[1]['box'][edge]);self.assertAlmostEqual(p[1]['box'][edge],p[2]['box'][edge])+ def test_impossible_section_is_not_scattered(self):+  p,missing,_,_=m.place_sections([dict(id='blocked',rows=[[0],[1]],anchor=[1,1])],[dict(text='a',role='note')]*2,lambda i,z,a:[-z,-z,z,z],box(0,0,2,2),box(0,0,2,2),GeometryCollection(),'F.SilkS')+  self.assertEqual(p,[]);self.assertEqual(missing,[0,1])+if __name__=='__main__':unittest.main()