diff --git a/.gitattributes b/.gitattributes index 7e6ab91b..45c41d8e 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,3 +1,7 @@ # These preregistered protocols are bound by exact raw-byte SHA-256 receipts. # Windows checkout must preserve their committed LF bytes rather than use CRLF. benchmarks/*.json text eol=lf +# README visual provenance hashes bind the generator's exact source bytes. +scripts/render_readme_heroes.py text eol=lf +scripts/readme_tracking_data.mjs text eol=lf +docs/assets/readme_heroes.json text eol=lf diff --git a/CHANGELOG.md b/CHANGELOG.md index 23dac59f..4f8b1368 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,11 @@ removed no sooner than the next major (see `docs/API_STABILITY.md`). ## [Unreleased] +- Refresh the README's opening animations with a shared visual style, actual + public-cloud results and synthetic Rust/WASM feature tracking. Link the + tracking animation to the mobile playground and record bounded generation + instructions, provenance and animation sizes. + - Reuse exact previous-image samples and gradients across CPU LK iterations for small patches. Retain each iteration's bounds, numerical order and public behavior with a bounded call-local array and no new heap allocation. Add a diff --git a/README.md b/README.md index 1984ef88..7ee8cc5c 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,12 @@ # SpatialRust

- SpatialRust hero: public PCL table_scene_lms400 scan, voxel downsample, plane RANSAC, and Euclidean cluster labels from a real MVP pipeline run + SpatialRust: a public PCL scan becomes voxel centroids, a segmented plane, and labeled objects through the Rust pipeline

Rust-native spatial computing
- Point clouds · wgpu · COPC · RANSAC · ICP — native Rust, no C++ binding layer. + Point clouds · image processing · wgpu · robotics · Rust/WASM camera tracking.

@@ -18,25 +18,29 @@ wgpu

-The hero GIF above is **real MVP pipeline output** (not a mockup): it uses the public PCL [`table_scene_lms400.pcd`](https://github.com/PointCloudLibrary/data/blob/master/tutorials/table_scene_lms400.pcd) sample, voxel-downsamples it, RANSAC peels off the dominant plane, and Euclidean clustering lights up objects in color — every frame rendered straight from a live pipeline run. - -

- SpatialRust MVP pipeline preview: RANSAC plane inliers, Euclidean cluster labels, and the pipeline stages -

+The hero shows **actual Rust pipeline results** from the public PCL +[`table_scene_lms400.pcd`](https://github.com/PointCloudLibrary/data/blob/master/tutorials/table_scene_lms400.pcd) +scan: voxel centroids → plane RANSAC → Euclidean clusters. Animated viewpoints +present the saved outputs; playback speed is independent of processing latency. | ⚡ GPU-accelerated | 🗂️ COPC-native | 🦀 Pure Rust | 🧩 Composable | | --- | --- | --- | --- | | explicit wgpu voxel and normal kernels, automatic CPU fallback | **bounds + LOD** partial reads straight off disk — no full-tile load | no C++ / FFI binding layer to fight | one MVP crate: **IO → filter → segment → register** |

- A multi-object point cloud rotating, each object colored by its DBSCAN cluster label - The same scene voxelized into a rotating 3D occupancy grid of cyan blocks + Actual Euclidean cluster labels from the public PCL scan, rendered from changing viewpoints + Occupied 8 cm cells computed by SpatialRust from the same public scan

-

DBSCAN clustering and voxel occupancy grids, generated by examples/make_gifs.py through the Python bindings.

+

Public point-cloud data · Rust outputs · Euclidean clustering and occupancy cells.

-Try the [mobile camera playground](https://rsasaki0109.github.io/SpatialRust/camera/): -opt-in camera or sample playback, Rust/WASM background feature flow and local AI -person masking. Experimental 2D image motion; [usage and device limits](docs/MOBILE_CAMERA_DEMO.md). +

+ Synthetic textured image playback with actual forward/backward-consistent feature tracks from the Rust/WASM camera tracker; AI is off in this recording +

+ +**[Try camera tracking on your phone →](https://rsasaki0109.github.io/SpatialRust/camera/)** +Use sample playback or opt in to your camera, with optional local AI person +masking. The GIF uses synthetic frames and the actual CPU Rust/WASM tracker, +with AI off. Experimental 2D image motion; [usage and device limits](docs/MOBILE_CAMERA_DEMO.md). ## Why SpatialRust? @@ -817,17 +821,22 @@ See also `crates/spatialrust-py/examples/make_gifs.py` and `examples/ml_preproce ## README visuals -The main README pipeline visuals use the public PCL [`table_scene_lms400.pcd`](https://github.com/PointCloudLibrary/data/blob/master/tutorials/table_scene_lms400.pcd) sample, cached under `target/readme-data/` at generation time rather than committed to the repository. Regenerate them with: +The four opening GIFs share a bounded renderer, actual Rust outputs and a +3 MB combined budget. [Generation instructions and provenance](docs/README_VISUALS.md) +cover the public scan, execution settings, synthetic tracking and current asset hashes. + +The other README pipeline visuals use the public PCL [`table_scene_lms400.pcd`](https://github.com/PointCloudLibrary/data/blob/master/tutorials/table_scene_lms400.pcd) sample, cached under `target/readme-data/` at generation time rather than committed to the repository. Regenerate them with: ```bash cargo run -p spatialrust --features mvp --example readme_mvp_preview ``` -Outputs: `readme_hero.gif` (header), `readme_mvp_preview.svg` (pipeline panel), `copc_query.gif` (COPC partial read), `benchmark_voxel.svg` (Performance chart), `architecture.svg` (crates diagram), `readme_mvp_pipeline.gif` (pipeline receipt: measured log + top-down result), and `social_preview.svg`. +Outputs: `readme_mvp_preview.svg` (pipeline panel), `copc_query.gif` (COPC partial read), `benchmark_voxel.svg` (Performance chart), `architecture.svg` (crates diagram), `readme_mvp_pipeline.gif` (pipeline receipt: measured log + top-down result), and `social_preview.svg`. This older generator also writes the former `readme_hero.gif`; regenerate the opening group last using the instructions above. Use `SPATIALRUST_README_CLOUD=/path/to/cloud.pcd` to render the same assets from another local public dataset. -The rotating `clusters_rotating.gif` and `voxelize_rotating.gif` are generated through the Python bindings from the same public sample: `python crates/spatialrust-py/examples/make_gifs.py --input target/readme-data/table_scene_lms400.pcd` (needs `maturin develop` + Matplotlib/Pillow). +`crates/spatialrust-py/examples/make_gifs.py` remains a standalone Matplotlib +example; the opening gallery now uses `scripts/render_readme_heroes.py`. ## Social preview diff --git a/docs/README_VISUALS.md b/docs/README_VISUALS.md new file mode 100644 index 00000000..8b236b4f --- /dev/null +++ b/docs/README_VISUALS.md @@ -0,0 +1,75 @@ +# README opening animations + +The opening group is rendered from actual SpatialRust results in a shared dark +palette, with readable labels and a link to the mobile camera playground. +`readme_hero.gif` presents the pipeline; the smaller animations show Euclidean +cluster labels, occupied voxel cells and Rust/WASM image-space feature tracking. +The renderer limits each GIF to 1.5 MB and the group to 3 MB. It holds bounded +frame sequences in memory instead of writing intermediate frames to disk. + +## Inputs and meaning + +- Point clouds: the public PCL + [`table_scene_lms400.pcd`](https://github.com/PointCloudLibrary/data/blob/master/tutorials/table_scene_lms400.pcd) + scan (460,400 points, 5,649,007 bytes). SHA256: + `e285d415641e0d9de695b611db874cc8fe995e8089b77a50d6056d24d8cbcc58`. + The renderer selects every sixth finite point (76,734 points), runs the Rust + pipeline through the Python extension and uses its returned downsampled and + labeled clouds. Exact output membership identifies removed plane points; + the renderer does not fit its own plane or invent cluster labels. Occupied + 8 cm cells are returned by `spatialrust.voxelize`. +- Execution: voxel policy is explicitly `cpu`. The installed extension used + for these assets does not expose resolved stage policies; its receipt records + `null` and its binary hash. The visuals make no GPU execution or speed claim. + Build the current extension to reproduce with current stage-policy receipts. +- Tracking: 48 generated 256×192 gray frames are passed to the actual + `BrowserCameraTracker` WASM API at logical 125 ms intervals. All 47 frames + after initialization track successfully. The renderer reconstructs the + same input and checks every frame's byte hash before drawing returned tracks. + No camera, person model, upload or physical-phone capture is involved; the + animation is visibly marked **SYNTHETIC / AI OFF**. The playground separately + offers opt-in camera use and optional local AI person masking. + +Viewpoint movement and GIF playback are presentation choices. They do not show +live processing latency, GPU acceleration, metric pose or SLAM qualification. + +## Regeneration + +Use a built SpatialRust Python extension (`maturin develop --release` from +`crates/spatialrust-py`), NumPy, Pillow and Node.js. Reuse a built camera package +from `scripts/build_camera_demo.py`, or generate only its Rust/WASM package: + +```sh +cargo build --release -p spatialrust-web --target wasm32-unknown-unknown +wasm-bindgen --target web --out-dir target/readme-camera-pkg target/wasm32-unknown-unknown/release/spatialrust_web.wasm +``` + +Use the wasm-bindgen CLI version matching Cargo's wasm-bindgen version. Keep +the input scan and the generated tracking report outside tracked directories. +The exporter and renderer perform no downloads. Then run from the repo root: + +```sh +node scripts/readme_tracking_data.mjs --pkg target/readme-camera-pkg --output target/readme-tracking.json +python scripts/render_readme_heroes.py --input /absolute/path/table_scene_lms400.pcd --tracking target/readme-tracking.json --font /absolute/path/sans.ttf --output docs/assets +``` + +The exporter requires a fresh output file. The renderer updates only the four +opening GIFs and `docs/assets/readme_heroes.json`; it does not modify other README +visuals. Use a local sans font such as DejaVu Sans or Segoe UI. The font hash, +Python extension hash, WASM hash, generator hashes, dependency versions, pipeline +parameters and asset hashes are recorded in that provenance receipt. Different +fonts or builds can change pixels and hashes; rerun the visual checks after +regeneration. No font binary, scan, WASM package or sensor data is committed. + +The older `readme_mvp_preview` and `make_gifs.py` examples also write some of +these filenames. Run the opening-group renderer last when regenerating all +README media. + +## Verification + +The updated group is about 1.54 MB, versus 2.83 MB for the previous three opening +GIFs, including the new tracking animation. Decode every frame, verify image +dimensions, looping, meaningful frame changes, the provenance hashes and the +combined size. Inspect all four pipeline phases and the smaller animations at +desktop and phone widths. Check that the tracking link points to the playground +and that the synthetic/AI-off label and experimental 2D description remain visible. diff --git a/docs/assets/camera_tracking.gif b/docs/assets/camera_tracking.gif new file mode 100644 index 00000000..fc86cdcf Binary files /dev/null and b/docs/assets/camera_tracking.gif differ diff --git a/docs/assets/clusters_rotating.gif b/docs/assets/clusters_rotating.gif index 95bcefaa..db93f0a5 100644 Binary files a/docs/assets/clusters_rotating.gif and b/docs/assets/clusters_rotating.gif differ diff --git a/docs/assets/readme_hero.gif b/docs/assets/readme_hero.gif index c3374148..819b971c 100644 Binary files a/docs/assets/readme_hero.gif and b/docs/assets/readme_hero.gif differ diff --git a/docs/assets/readme_heroes.json b/docs/assets/readme_heroes.json new file mode 100644 index 00000000..6984f444 --- /dev/null +++ b/docs/assets/readme_heroes.json @@ -0,0 +1,54 @@ +{ + "schema": "spatialrust.readme-heroes.v1", + "assets": [ + { + "path": "readme_hero.gif", + "bytes": 296115, + "sha256": "6567c15b48f102ecdc5595c6c1eae614de5af0545f65c1510d8658f74bca2548" + }, + { + "path": "clusters_rotating.gif", + "bytes": 92877, + "sha256": "f944d14e7349510b20a487d60ebb9bdf48ffc8135b6c0d37b74889c822d5f715" + }, + { + "path": "voxelize_rotating.gif", + "bytes": 185226, + "sha256": "a7b0d05d2903cb9c809535ef67ddc2bb65c9ba5a45aabfd2c334681dbf96ce48" + }, + { + "path": "camera_tracking.gif", + "bytes": 968718, + "sha256": "3ea5d14be5c99d2168c6f75afefd0efc05f5a43b0eb76826f3930f468dbd67c7" + } + ], + "public_input": { + "file": "table_scene_lms400.pcd", + "sha256": "e285d415641e0d9de695b611db874cc8fe995e8089b77a50d6056d24d8cbcc58", + "points": 460400, + "sampled_points": 76734 + }, + "execution": "SpatialRust Python bindings (voxel policy cpu); CPU Rust/WASM camera tracker", + "spatialrust_version": "1.0.0", + "resolved_policies": null, + "python_extension_sha256": "cba594925d83a3b495db4f1ecb97434df72767b7075fccf0380c559477e62c5c", + "generator_sha256": "d3b13cc87501d4e9f1c6ad6c8dc24ad0cedafa26e09e4c1cc0a6468932c120ec", + "tracking_generator_sha256": "0ab17ebc391cd054e1c607ed6fbf42bccab39a026c8516e09b86faee4d78c9cb", + "numpy_version": "2.3.4", + "pillow_version": "12.3.0", + "font_sha256": "8134dbcd09e7b123c9a7f229d49cffbcb01352cc72ea5e1076b65d0dca9f73cd", + "pipeline": { + "voxel_leaf_m": 0.03, + "plane_distance_m": 0.025, + "cluster_tolerance_m": 0.06, + "min_cluster_size": 8, + "downsampled_points": 4561, + "plane_inliers": 2179, + "cluster_count": 6, + "occupancy_cell_m": 0.08, + "occupied_cells": 776 + }, + "tracking_wasm_sha256": "f99c2ba94abe68021b880ba2141c087b5758d638011b04b1ea5d0b47b00493ad", + "tracking_frames": 48, + "claims": "Illustrations of actual outputs; animation playback is not a throughput benchmark. Synthetic tracking has AI disabled." +} diff --git a/docs/assets/voxelize_rotating.gif b/docs/assets/voxelize_rotating.gif index c4eac618..75485e6c 100644 Binary files a/docs/assets/voxelize_rotating.gif and b/docs/assets/voxelize_rotating.gif differ diff --git a/scripts/readme_tracking_data.mjs b/scripts/readme_tracking_data.mjs new file mode 100644 index 00000000..c2e9f97f --- /dev/null +++ b/scripts/readme_tracking_data.mjs @@ -0,0 +1,44 @@ +// Export actual Rust/WASM reports for the README's synthetic playback visual. +// No camera, AI model, browser, network request or timing benchmark is used. +import fs from "node:fs"; +import path from "node:path"; +import { createHash } from "node:crypto"; + +function arg(name) { + const i = process.argv.indexOf(name); + if (i < 0 || !process.argv[i + 1]) throw new Error(`missing ${name}`); + return path.resolve(process.argv[i + 1]); +} +const pkg = arg("--pkg"), output = arg("--output"); +if (fs.existsSync(output)) throw new Error("output already exists"); +const js = fs.readFileSync(path.join(pkg, "spatialrust_web.js")); +const wasm = fs.readFileSync(path.join(pkg, "spatialrust_web_bg.wasm")); +const { initSync, BrowserCameraTracker } = await import(`data:text/javascript;base64,${js.toString("base64")}`); +initSync({ module: wasm }); +const width = 256, height = 192, frameCount = 48; +const tracker = new BrowserCameraTracker(width, height); +const frames = []; +try { + for (let frame = 0; frame < frameCount; frame++) { + const angle = 2 * Math.PI * frame / frameCount; + const dx = Math.round(8 * Math.sin(angle)), dy = Math.round(5 * Math.cos(angle)); + const gray = new Uint8Array(width * height); + for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) { + const sx = x - dx + 32, sy = y - dy + 32; + const h = (Math.imul(sx, 73856093) ^ Math.imul(sy, 19349663)) >>> 0; + gray[y * width + x] = ((((sx >> 4) + (sy >> 4)) % 2) ? 125 : 35) + ((h ^ (h >>> 13)) & 31); + } + const report = JSON.parse(tracker.track_gray_copy(gray, new Uint8Array(0), frame * 125)); + if (report.schema !== 1 || report.tracks.length > 80) throw new Error("unexpected tracking report"); + if (frame && (report.status !== "tracking" || !report.background_flow_px)) throw new Error(`tracking lost at frame ${frame}`); + frames.push({ shift: [dx, dy], gray_sha256: createHash("sha256").update(gray).digest("hex"), report }); + } +} finally { tracker.free(); } +fs.mkdirSync(path.dirname(output), { recursive: true }); +fs.writeFileSync(output, JSON.stringify({ + schema: "spatialrust.readme-tracking.v1", synthetic_only: true, ai_enabled: false, + execution: "CPU Rust/WASM", width, height, frame_duration_ms: 125, + wasm_sha256: createHash("sha256").update(wasm).digest("hex"), + bindings_sha256: createHash("sha256").update(js).digest("hex"), frames, +}, null, 2) + "\n", { flag: "wx" }); +console.log(JSON.stringify({ frames: frames.length, tracked: frames.filter(f => f.report.status === "tracking").length, output })); diff --git a/scripts/render_readme_heroes.py b/scripts/render_readme_heroes.py new file mode 100644 index 00000000..2b4287c1 --- /dev/null +++ b/scripts/render_readme_heroes.py @@ -0,0 +1,252 @@ +"""Render README animations from SpatialRust results; no downloads or GPU claims. + +Requires the SpatialRust Python extension, NumPy and Pillow. Supply the public +PCL table_scene_lms400.pcd and reports from readme_tracking_data.mjs explicitly. +Only these four GIFs and a small provenance receipt are written to --output. +Frames are encoded in memory, without a temporary image sequence on disk. +""" +from __future__ import annotations + +import argparse +import hashlib +import json +import math +from pathlib import Path + +import numpy as np +from PIL import Image, ImageDraw, ImageFont, __version__ as pillow_version + +BG = "#080f1c" +PANEL = "#101d30" +INK = "#ecf5ff" +MUTED = "#94abc3" +CYAN = "#61dfef" +MINT = "#79f2bd" +ORANGE = "#ffbb79" +COLORS = [CYAN, ORANGE, MINT, "#bd9bff", "#ff89b1", "#fae17a"] +NAMES = ("readme_hero.gif", "clusters_rotating.gif", "voxelize_rotating.gif", "camera_tracking.gif") +MAX_GIF_BYTES = 1_500_000 +MAX_TOTAL_BYTES = 3_000_000 + + +def sha(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def font(path, size): + return ImageFont.truetype(str(path), size) + + +def text(draw, xy, value, face, color=INK): + draw.text(xy, value, font=face, fill=color) + + +def pill(draw, xy, value, face, color=CYAN): + x, y = xy + w = draw.textlength(value, font=face) + 24 + draw.rounded_rectangle((x, y, x + w, y + 27), radius=13, fill=PANEL, outline="#294054") + text(draw, (x + 12, y + 4), value, face, color) + + +def cloud_view(points, colors, size, phase, radius=1, voxel_size=None): + """Orthographic view of original XYZ, using the scan's camera-like Y axis.""" + w, h = size + center = (points.min(axis=0) + points.max(axis=0)) * .5 + p = points - center + yaw = .28 + .20 * math.sin(phase) + depth = -math.sin(yaw) * p[:, 0] + math.cos(yaw) * p[:, 2] + x = math.cos(yaw) * p[:, 0] + math.sin(yaw) * p[:, 2] + y = .94 * p[:, 1] - .34 * depth + # One fixed scale derived from XYZ extents: no per-stage zoom or cropping. + extent = np.ptp(points, axis=0) + scale = min((w - 40) / (extent[0] + .5 * extent[2]), (h - 32) / (extent[1] + .4 * extent[2])) + xy = np.column_stack((w * .5 + x * scale, h * .5 + y * scale)).round().astype(int) + view = Image.new("RGB", size, BG) + d = ImageDraw.Draw(view) + for i in np.argsort(-depth, kind="stable"): + px, py = xy[i] + color = colors[i] if not isinstance(colors, str) else colors + if voxel_size is not None and i < len(points) - 2: + corners = np.array([[-1,-1,-1], [1,-1,-1], [1,1,-1], [-1,1,-1], + [-1,-1,1], [1,-1,1], [1,1,1], [-1,1,1]]) * (voxel_size * .5) + p[i] + zc = -math.sin(yaw) * corners[:, 0] + math.cos(yaw) * corners[:, 2] + xc = math.cos(yaw) * corners[:, 0] + math.sin(yaw) * corners[:, 2] + yc = .94 * corners[:, 1] - .34 * zc + vertices = np.column_stack((w * .5 + xc * scale, h * .5 + yc * scale)) + for face, fill in [([0,1,2,3], "#2396b4"), ([1,2,6,5], "#28718f"), ([0,1,5,4], CYAN)]: + d.polygon([tuple(vertices[j]) for j in face], fill=fill, outline="#153b50") + elif radius == 1: + d.point((int(px), int(py)), fill=color) + else: + d.ellipse((int(px-radius), int(py-radius), int(px+radius), int(py+radius)), fill=color) + return view + + +def palette(): + # Fixed palette avoids both temporal color flicker and per-frame dithering. + values = [Image.new("RGB", (1, 1), c).getpixel((0, 0)) for c in [BG, PANEL, INK, MUTED, CYAN, MINT, ORANGE, *COLORS[3:], "#294054", "#24384b"]] + values += [(r, g, b) for r in range(0, 256, 51) for g in range(0, 256, 51) for b in range(0, 256, 51)] + values = (values + [(0, 0, 0)] * 256)[:256] + p = Image.new("P", (1, 1)) + p.putpalette([c for rgb in values for c in rgb]) + return p + + +def save_gif(path, frames, duration): + p = palette() + indexed = [im.quantize(palette=p, dither=Image.Dither.NONE) for im in frames] + indexed[0].save(path, save_all=True, append_images=indexed[1:], duration=duration, + loop=0, optimize=False, disposal=1) + if path.stat().st_size > MAX_GIF_BYTES: + raise ValueError(f"GIF exceeds {MAX_GIF_BYTES} bytes: {path.name}") + + +def texture(width, height, shift): + yy, xx = np.indices((height, width), dtype=np.uint32) + sx = xx + np.uint32(32 - shift[0]) + sy = yy + np.uint32(32 - shift[1]) + h = (sx * np.uint32(73856093)) ^ (sy * np.uint32(19349663)) + return (np.where(((sx >> 4) + (sy >> 4)) % 2, 125, 35) + ((h ^ (h >> 13)) & 31)).astype(np.uint8) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--input", type=Path, required=True) + parser.add_argument("--tracking", type=Path, required=True) + parser.add_argument("--font", type=Path, required=True, help="TrueType/OpenType sans font") + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + import spatialrust as sr + + args.output.mkdir(parents=True, exist_ok=True) + faces = {n: font(args.font, n) for n in [12, 14, 16, 19, 24, 32, 42]} + source = sr.read(str(args.input)) + xyz = source.xyz() + xyz = xyz[np.isfinite(xyz).all(axis=1)] + # Bounded, deterministic public input selection, matching the prior hero cap. + xyz = np.ascontiguousarray(xyz[::max(1, math.ceil(len(xyz) / 80_000))], dtype=np.float32) + cloud = sr.PointCloud.from_xyz(xyz) + result = sr.run_pipeline(cloud, leaf_size=.03, plane_distance=.025, + cluster_tolerance=.06, min_cluster_size=8, policy="cpu") + small = result.downsampled.xyz() + labeled = result.output.xyz() + labels = result.labels() + label_colors = [COLORS[int(v) % len(COLORS)] if v >= 0 else "#294054" for v in labels] + grid, origin, voxel_size = sr.voxelize(cloud, voxel_size=.08, mode="occupancy") + indices = np.argwhere(grid > 0)[:, ::-1] + centers = np.asarray(origin) + (indices + .5) * voxel_size + policies = getattr(result, "resolved_policies", None) + # Pipeline output is the labeled plane-outlier cloud. Recover its exact + # complement in the returned downsampled cloud without fitting another plane. + row_type = np.dtype((np.void, small.dtype.itemsize * 3)) + outlier_rows = np.ascontiguousarray(labeled).view(row_type).ravel() + outlier_mask = np.isin(np.ascontiguousarray(small).view(row_type).ravel(), outlier_rows) + plane, outliers = small[~outlier_mask], small[outlier_mask] + if len(plane) != result.plane_inliers or len(outliers) != len(labeled): + raise ValueError("pipeline output cannot identify plane membership exactly") + stages = [(xyz, CYAN), (small, INK), + (np.concatenate((plane, outliers)), [CYAN] * len(plane) + [ORANGE] * len(outliers)), + (labeled, label_colors)] + stage_names = ["PUBLIC SCAN", "VOXEL FILTER", "PLANE RANSAC", "OBJECT CLUSTERS"] + counts = [f"{len(xyz):,} sampled points", f"{len(small):,} centroids", f"{len(plane):,} plane inliers", f"{result.cluster_count} clusters / {len(labeled):,} points"] + header = [] + for i in range(48): + stage = i // 12 + image = Image.new("RGB", (960, 420), BG) + d = ImageDraw.Draw(image) + text(d, (32, 27), "SPATIAL COMPUTING / RUST", faces[12], CYAN) + text(d, (30, 71), "SpatialRust", faces[42]) + text(d, (32, 141), "From sensor data", faces[24]) + text(d, (32, 174), "to spatial intelligence.", faces[24]) + text(d, (32, 225), "Point clouds. Images. Robotics.", faces[16], MUTED) + pill(d, (32, 270), "RUST", faces[12]) + pill(d, (112, 270), "wgpu", faces[12], MINT) + pill(d, (197, 270), "WASM", faces[12], ORANGE) + text(d, (32, 330), "REAL DATA / ACTUAL RUST OUTPUT", faces[12], MUTED) + text(d, (32, 352), "PCL table_scene_lms400", faces[14]) + pts, cs = stages[stage] + # Use shared input bounds for every stage, including sparse object output. + padding = np.array([xyz.min(axis=0), xyz.max(axis=0)]) + colors = ([cs] * len(pts) if isinstance(cs, str) else cs) + [BG, BG] + view = cloud_view(np.concatenate((pts, padding)), colors, (570, 302), i / 48 * math.tau, 1 if stage == 0 else 2) + image.paste(view, (378, 32)) + d = ImageDraw.Draw(image) + text(d, (404, 26), stage_names[stage], faces[14], CYAN) + text(d, (404, 324), counts[stage], faces[16]) + text(d, (404, 352), "Rust pipeline / animated viewpoint", faces[12], MUTED) + for j, name in enumerate(["SCAN", "FILTER", "SEGMENT", "CLUSTER"]): + x = 32 + j * 232 + d.rounded_rectangle((x, 390, x + 216, 393), radius=1, fill=CYAN if j == stage else PANEL) + text(d, (x, 372), name, faces[12], INK if j == stage else MUTED) + header.append(image) + save_gif(args.output / NAMES[0], header, 125) + + for name, points, colors, title, detail, radius in [ + (NAMES[1], labeled, label_colors, "Separate the scene", f"{result.cluster_count} Euclidean clusters / Rust", 2), + (NAMES[2], centers, CYAN, "Build spatial structure", f"{len(centers):,} occupied cells / 0.08 m", 3), + ]: + frames = [] + for i in range(32): + image = Image.new("RGB", (464, 340), BG) + padding = np.array([xyz.min(axis=0), xyz.max(axis=0)]) + cs = ([colors] * len(points) if isinstance(colors, str) else colors) + [BG, BG] + image.paste(cloud_view(np.concatenate((points, padding)), cs, (448, 235), i / 32 * math.tau, + radius, voxel_size if name == NAMES[2] else None), (8, 58)) + d = ImageDraw.Draw(image) + text(d, (22, 18), title, faces[24]) + text(d, (22, 305), detail, faces[14], CYAN) + frames.append(image) + save_gif(args.output / name, frames, 150) + + tracking = json.loads(args.tracking.read_text(encoding="utf-8")) + if tracking["schema"] != "spatialrust.readme-tracking.v1" or not tracking["synthetic_only"] or tracking["ai_enabled"]: + raise ValueError("expected synthetic unmasked actual-WASM reports") + frames = [] + for f in tracking["frames"]: + gray = texture(tracking["width"], tracking["height"], f["shift"]) + if hashlib.sha256(gray.tobytes()).hexdigest() != f["gray_sha256"]: + raise ValueError("rendered image differs from actual WASM input") + rgb = np.stack((gray // 3, (gray.astype(np.uint16) * 1.1).clip(0, 255).astype(np.uint8), gray), axis=-1) + scene = Image.fromarray(rgb).resize((384, 288), Image.Resampling.NEAREST) + image = Image.new("RGB", (464, 400), BG) + image.paste(scene, (40, 64)) + d = ImageDraw.Draw(image) + text(d, (22, 16), "Track image motion", faces[24]) + for t in f["report"]["tracks"]: + a = (40 + t["from"][0] * 1.5, 64 + t["from"][1] * 1.5) + b = (40 + t["to"][0] * 1.5, 64 + t["to"][1] * 1.5) + d.line((a, b), fill=MINT, width=2) + d.ellipse((b[0]-2, b[1]-2, b[0]+2, b[1]+2), fill=INK) + text(d, (22, 363), f"{len(f['report']['tracks']):02d} tracks / Rust + WASM", faces[14], MINT) + flow = f["report"]["background_flow_px"] + if flow is not None: + text(d, (282, 363), f"dx {flow[0]:+.1f} px", faces[14], MUTED) + pill(d, (282, 18), "SYNTHETIC / AI OFF", faces[12], ORANGE) + frames.append(image) + save_gif(args.output / NAMES[3], frames, tracking["frame_duration_ms"]) + + assets = [{"path": name, "bytes": (args.output/name).stat().st_size, "sha256": sha(args.output/name)} for name in NAMES] + if sum(a["bytes"] for a in assets) > MAX_TOTAL_BYTES: + raise ValueError("hero group exceeds 3 MB budget") + extensions = list(Path(sr.__file__).parent.glob("*.pyd")) + list(Path(sr.__file__).parent.glob("*.so")) + receipt = dict(schema="spatialrust.readme-heroes.v1", assets=assets, + public_input=dict(file=args.input.name, sha256=sha(args.input), points=len(source), sampled_points=len(xyz)), + execution="SpatialRust Python bindings (voxel policy cpu); CPU Rust/WASM camera tracker", + spatialrust_version=sr.__version__, resolved_policies=policies, + python_extension_sha256=sha(extensions[0]) if len(extensions) == 1 else None, + generator_sha256=sha(__file__), + tracking_generator_sha256=sha(Path(__file__).with_name("readme_tracking_data.mjs")), + numpy_version=np.__version__, pillow_version=pillow_version, + font_sha256=sha(args.font), + pipeline=dict(voxel_leaf_m=.03, plane_distance_m=.025, cluster_tolerance_m=.06, + min_cluster_size=8, downsampled_points=len(small), + plane_inliers=len(plane), cluster_count=result.cluster_count, + occupancy_cell_m=.08, occupied_cells=len(centers)), + tracking_wasm_sha256=tracking["wasm_sha256"], tracking_frames=len(tracking["frames"]), + claims="Illustrations of actual outputs; animation playback is not a throughput benchmark. Synthetic tracking has AI disabled.") + (args.output / "readme_heroes.json").write_text(json.dumps(receipt, indent=2) + "\n", encoding="utf-8") + print(json.dumps(receipt, indent=2)) + + +if __name__ == "__main__": + main()