|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Bundle KiCad VRML Inline references into one browser-viewable WRL file.""" |
| 3 | + |
| 4 | +import argparse |
| 5 | +import re |
| 6 | +import shutil |
| 7 | +from pathlib import Path |
| 8 | +from typing import Dict, List, Optional, Tuple |
| 9 | + |
| 10 | + |
| 11 | +BACKGROUND = "Background {\n skyColor [ 0.933 0.949 0.969 ]\n}\n" |
| 12 | +STRIP_TOP_LEVEL_NODES = {"WorldInfo", "NavigationInfo", "Background", "Viewpoint"} |
| 13 | + |
| 14 | + |
| 15 | +def parse_args() -> argparse.Namespace: |
| 16 | + parser = argparse.ArgumentParser(description=__doc__) |
| 17 | + parser.add_argument("input", type=Path, help="KiCad-exported board WRL") |
| 18 | + parser.add_argument("output", type=Path, help="Bundled output WRL") |
| 19 | + parser.add_argument( |
| 20 | + "--copy-shapes", |
| 21 | + type=Path, |
| 22 | + help="Optional destination for the source shapes3D directory", |
| 23 | + ) |
| 24 | + return parser.parse_args() |
| 25 | + |
| 26 | + |
| 27 | +def find_matching_brace(text: str, open_index: int) -> int: |
| 28 | + depth = 0 |
| 29 | + index = open_index |
| 30 | + in_string = False |
| 31 | + escaped = False |
| 32 | + while index < len(text): |
| 33 | + char = text[index] |
| 34 | + if in_string: |
| 35 | + if escaped: |
| 36 | + escaped = False |
| 37 | + elif char == "\\": |
| 38 | + escaped = True |
| 39 | + elif char == '"': |
| 40 | + in_string = False |
| 41 | + else: |
| 42 | + if char == '"': |
| 43 | + in_string = True |
| 44 | + elif char == "#": |
| 45 | + newline = text.find("\n", index) |
| 46 | + if newline == -1: |
| 47 | + return len(text) - 1 |
| 48 | + index = newline |
| 49 | + elif char == "{": |
| 50 | + depth += 1 |
| 51 | + elif char == "}": |
| 52 | + depth -= 1 |
| 53 | + if depth == 0: |
| 54 | + return index |
| 55 | + index += 1 |
| 56 | + raise ValueError("unclosed brace in VRML file") |
| 57 | + |
| 58 | + |
| 59 | +def iter_inline_blocks(text: str): |
| 60 | + for match in re.finditer(r"\bInline\s*\{", text): |
| 61 | + open_index = text.find("{", match.start()) |
| 62 | + close_index = find_matching_brace(text, open_index) |
| 63 | + yield match.start(), close_index + 1, text[match.start() : close_index + 1] |
| 64 | + |
| 65 | + |
| 66 | +def extract_url(inline_block: str) -> Optional[str]: |
| 67 | + match = re.search(r"\burl\s+(?:\[\s*)?\"([^\"]+)\"", inline_block) |
| 68 | + if not match: |
| 69 | + return None |
| 70 | + return match.group(1) |
| 71 | + |
| 72 | + |
| 73 | +def strip_header(text: str) -> str: |
| 74 | + text = re.sub(r"^\s*#VRML\s+V2\.0\s+utf8\s*", "", text, count=1) |
| 75 | + return text.lstrip() |
| 76 | + |
| 77 | + |
| 78 | +def strip_top_level_nodes(text: str) -> str: |
| 79 | + output: List[str] = [] |
| 80 | + index = 0 |
| 81 | + node_pattern = re.compile(r"\b(" + "|".join(sorted(STRIP_TOP_LEVEL_NODES)) + r")\s*\{") |
| 82 | + while index < len(text): |
| 83 | + match = node_pattern.search(text, index) |
| 84 | + if not match: |
| 85 | + output.append(text[index:]) |
| 86 | + break |
| 87 | + |
| 88 | + output.append(text[index : match.start()]) |
| 89 | + open_index = text.find("{", match.start()) |
| 90 | + close_index = find_matching_brace(text, open_index) |
| 91 | + index = close_index + 1 |
| 92 | + return "".join(output).strip() |
| 93 | + |
| 94 | + |
| 95 | +def normalize_url(url: str) -> str: |
| 96 | + return url.replace("\\", "/") |
| 97 | + |
| 98 | + |
| 99 | +def resolve_inline_path(base_dir: Path, url: str) -> Path: |
| 100 | + normalized = normalize_url(url) |
| 101 | + if re.match(r"^[a-zA-Z][a-zA-Z0-9+.-]*:", normalized): |
| 102 | + raise ValueError(f"remote VRML Inline URLs are not supported: {url}") |
| 103 | + return (base_dir / normalized).resolve() |
| 104 | + |
| 105 | + |
| 106 | +def bundle_body(path: Path, stack: Tuple[Path, ...], cache: Dict[Path, str]) -> str: |
| 107 | + path = path.resolve() |
| 108 | + if path in stack: |
| 109 | + chain = " -> ".join(str(item) for item in (*stack, path)) |
| 110 | + raise ValueError(f"recursive VRML Inline loop: {chain}") |
| 111 | + if path in cache: |
| 112 | + return f"USE {cache[path]}" |
| 113 | + if not path.exists(): |
| 114 | + raise FileNotFoundError(f"Inline VRML file not found: {path}") |
| 115 | + |
| 116 | + source = path.read_text(encoding="utf-8", errors="replace") |
| 117 | + body = strip_top_level_nodes(strip_header(source)) |
| 118 | + body = bundle_inlines(body, path.parent, (*stack, path), cache) |
| 119 | + |
| 120 | + def_name = f"BUNDLED_{len(cache) + 1}" |
| 121 | + cache[path] = def_name |
| 122 | + return f"DEF {def_name} Group {{\n children [\n{indent(body, 4)}\n ]\n}}" |
| 123 | + |
| 124 | + |
| 125 | +def bundle_inlines(text: str, base_dir: Path, stack: Tuple[Path, ...], cache: Dict[Path, str]) -> str: |
| 126 | + pieces: List[str] = [] |
| 127 | + cursor = 0 |
| 128 | + for start, end, block in iter_inline_blocks(text): |
| 129 | + pieces.append(text[cursor:start]) |
| 130 | + url = extract_url(block) |
| 131 | + if not url: |
| 132 | + raise ValueError(f"Inline block is missing a URL: {block[:120]}") |
| 133 | + pieces.append(bundle_body(resolve_inline_path(base_dir, url), stack, cache)) |
| 134 | + cursor = end |
| 135 | + pieces.append(text[cursor:]) |
| 136 | + return "".join(pieces) |
| 137 | + |
| 138 | + |
| 139 | +def indent(text: str, spaces: int) -> str: |
| 140 | + prefix = " " * spaces |
| 141 | + return "\n".join(prefix + line if line.strip() else line for line in text.splitlines()) |
| 142 | + |
| 143 | + |
| 144 | +def add_background(text: str) -> str: |
| 145 | + body = strip_header(text) |
| 146 | + body = re.sub(r"\bBackground\s*\{[^{}]*\}\s*", "", body, count=1) |
| 147 | + return "#VRML V2.0 utf8\n" + BACKGROUND + body.lstrip() |
| 148 | + |
| 149 | + |
| 150 | +def copy_shapes_dir(input_path: Path, destination: Optional[Path]) -> None: |
| 151 | + if destination is None: |
| 152 | + return |
| 153 | + source = input_path.parent / "shapes3D" |
| 154 | + if not source.is_dir(): |
| 155 | + return |
| 156 | + if destination.exists(): |
| 157 | + shutil.rmtree(destination) |
| 158 | + shutil.copytree(source, destination) |
| 159 | + |
| 160 | + |
| 161 | +def main() -> int: |
| 162 | + args = parse_args() |
| 163 | + input_path = args.input.resolve() |
| 164 | + output_path = args.output.resolve() |
| 165 | + output_path.parent.mkdir(parents=True, exist_ok=True) |
| 166 | + copy_shapes_dir(input_path, args.copy_shapes) |
| 167 | + |
| 168 | + source = input_path.read_text(encoding="utf-8", errors="replace") |
| 169 | + bundled = bundle_inlines(strip_header(source), input_path.parent, (input_path,), {}) |
| 170 | + with output_path.open("w", encoding="utf-8", newline="\n") as output_file: |
| 171 | + output_file.write(add_background(bundled)) |
| 172 | + return 0 |
| 173 | + |
| 174 | + |
| 175 | +if __name__ == "__main__": |
| 176 | + raise SystemExit(main()) |
0 commit comments