Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(art): establish terrain-first Mars base study
rubenluetke10-beep2e797dcfbcc3
diff --git a/scripts/art/build_mars_map.py b/scripts/art/build_mars_map.pynew file mode 100644index 0000000000..c93aa94ff5--- /dev/null+++ b/scripts/art/build_mars_map.py@@ -0,0 +1,440 @@+"""Author an isolated terrain/circulation blockout, not finished Mars assets.++Run Blender with --background --factory-startup --disable-autoexec --python+scripts/art/build_mars_map.py. The study manifest drives the separate GLB export.+"""++from __future__ import annotations++import json+import math+import sys+from pathlib import Path++import bpy+from mathutils import Vector+from mathutils.bvhtree import BVHTree+from mathutils.geometry import delaunay_2d_cdt++sys.path.insert(0, str(Path(__file__).resolve().parent))+from mars_map import height_at, load_layout, validate_layout # noqa: E402++ROOT = Path(__file__).resolve().parents[2]+STUDY = ROOT / "art/studies/mars-base-study"+PAD_SEGMENTS = 128+++def xyz(point):+ """Convert the study's Three.js Y-up positions to Blender Z-up."""+ return (point[0], -point[2], point[1])+++def material(name, color, emission=0):+ result = bpy.data.materials.new(name)+ result.use_nodes = True+ bsdf = result.node_tree.nodes.get("Principled BSDF")+ bsdf.inputs["Base Color"].default_value = (*color, 1)+ bsdf.inputs["Roughness"].default_value = 0.94+ bsdf.inputs["Emission Color"].default_value = (*color, 1)+ bsdf.inputs["Emission Strength"].default_value = emission+ return result+++def mesh_object(name, vertices, faces, mat, collection):+ mesh = bpy.data.meshes.new(name)+ mesh.from_pydata(vertices, [], faces)+ mesh.update()+ obj = bpy.data.objects.new(name, mesh)+ collection.objects.link(obj)+ mesh.materials.append(mat)+ return obj+++def collection(name, parent=None):+ result = bpy.data.collections.new(name)+ (parent or bpy.context.scene.collection).children.link(result)+ return result+++def move_object(obj, destination):+ for parent in list(obj.users_collection):+ parent.objects.unlink(obj)+ destination.objects.link(obj)+++def route_sample(nodes, link, t, lateral=0):+ a, b = (nodes[link[key]]["position"] for key in ("a", "b"))+ dx, dz = b[0] - a[0], b[2] - a[2]+ length = math.hypot(dx, dz)+ return (+ a[0] + dx * t - dz / length * lateral,+ a[2] + dz * t + dx / length * lateral,+ )+++def constrained_terrain(layout):+ """Triangulate roads and pads as part of the heightfield, not overlaid meshes."""+ coords = []+ ids = {}+ edges = set()++ def vertex(x, z):+ key = (round(x, 6), round(z, 6))+ if key not in ids:+ ids[key] = len(coords)+ coords.append(Vector((x, z)))+ return ids[key]++ def edge(a, b):+ if a != b:+ edges.add(tuple(sorted((a, b))))++ # The original nonuniform grid supplies outer geology detail. Constraints+ # replace its arbitrary diagonals wherever circulation needs exact contact.+ xs = list(range(-800, -400, 25)) + list(range(-400, 401, 4)) + list(range(425, 801, 25))+ zs = list(range(-640, -300, 20)) + list(range(-300, 301, 4)) + list(range(320, 641, 20))+ for z in zs:+ for x in xs:+ vertex(x, z)+ corners = [+ vertex(xs[0], zs[0]),+ vertex(xs[-1], zs[0]),+ vertex(xs[-1], zs[-1]),+ vertex(xs[0], zs[-1]),+ ]+ for index, a in enumerate(corners):+ edge(a, corners[(index + 1) % len(corners)])+ nodes = {node["id"]: node for node in layout["nodes"]}+ for node in nodes.values():+ x, _, z = node["position"]+ vertex(x, z)+ radius = node.get("radius", 0)+ if radius <= 0:+ continue+ ring = [+ vertex(+ x + radius * math.cos(i * math.tau / PAD_SEGMENTS),+ z + radius * math.sin(i * math.tau / PAD_SEGMENTS),+ )+ for i in range(PAD_SEGMENTS)+ ]+ for index, a in enumerate(ring):+ edge(a, ring[(index + 1) % len(ring)])++ for link in layout["links"]:+ if link["kind"] != "ground":+ continue+ a, b = (nodes[link[key]] for key in ("a", "b"))+ length = math.dist(a["position"][::2], b["position"][::2])+ count = max(2, math.ceil(length / 2))+ samples = {i / count for i in range(count + 1)}+ # Without these transverse edges, a triangle can straddle the break+ # between a flat pad and its ramp even when its vertices are on the road.+ samples.update(+ (min(1, a.get("radius", 0) / length), max(0, 1 - b.get("radius", 0) / length))+ )+ columns = []+ for lateral in (-link["width"] / 2, 0, link["width"] / 2):+ column = [vertex(*route_sample(nodes, link, t, lateral)) for t in sorted(samples)]+ for first, second in zip(column, column[1:], strict=False):+ edge(first, second)+ columns.append(column)+ for row in zip(*columns, strict=True):+ edge(row[0], row[1])+ edge(row[1], row[2])++ planar, _, triangles, _, _, _ = delaunay_2d_cdt(coords, sorted(edges), [], 0, 1e-5, False)+ vertices = [xyz((p.x, height_at(layout, p.x, p.y), p.y)) for p in planar]+ # CDT is counter-clockwise in X/Z; converting Z to Blender -Y reverses it.+ faces = [tuple(reversed(face)) for face in triangles]+ if any(len(face) != 3 for face in faces):+ raise ValueError("Constrained terrain must contain triangles only")+ return vertices, faces+++def terrain_material(layout, nodes, x, z):+ for node in nodes.values():+ px, _, pz = node["position"]+ if math.hypot(x - px, z - pz) <= node.get("radius", 0):+ return 2+ for link in layout["links"]:+ if link["kind"] != "ground":+ continue+ a, b = (nodes[link[key]]["position"] for key in ("a", "b"))+ dx, dz = b[0] - a[0], b[2] - a[2]+ t = max(0, min(1, ((x - a[0]) * dx + (z - a[2]) * dz) / (dx * dx + dz * dz)))+ if math.hypot(x - a[0] - t * dx, z - a[2] - t * dz) <= link["width"] / 2:+ return 1+ return 0+++def bridge_abutment(node, forward, lateral, half_width):+ """The exact polygonal pad boundary inside the bridge's width."""+ x, _, z = node["position"]+ radius = node.get("radius", 0)+ if radius <= half_width:+ raise ValueError("Bridge abutment pads must be wider than the deck")+ ring = [+ (+ x + radius * math.cos(i * math.tau / PAD_SEGMENTS),+ z + radius * math.sin(i * math.tau / PAD_SEGMENTS),+ )+ for i in range(PAD_SEGMENTS)+ ]+ points = {}++ def include(px, pz):+ u = (px - x) * forward[0] + (pz - z) * forward[1]+ v = (px - x) * lateral[0] + (pz - z) * lateral[1]+ if u >= 0 and abs(v) <= half_width + 1e-8:+ points[(round(px, 8), round(pz, 8))] = (v, px, pz)++ for index, (ax, az) in enumerate(ring):+ include(ax, az)+ bx, bz = ring[(index + 1) % len(ring)]+ av = (ax - x) * lateral[0] + (az - z) * lateral[1]+ bv = (bx - x) * lateral[0] + (bz - z) * lateral[1]+ if abs(bv - av) < 1e-10:+ continue+ for side in (-half_width, half_width):+ t = (side - av) / (bv - av)+ if 0 <= t <= 1:+ include(ax + (bx - ax) * t, az + (bz - az) * t)+ return [(px, pz) for _, px, pz in sorted(points.values())]+++def mesh_contact_report(layout, ground, bridge_contacts):+ """Raycast the actual triangulated Blender terrain, never the ideal helper."""+ mesh = ground.data+ mesh.calc_loop_triangles()+ bvh = BVHTree.FromPolygons(+ [vertex.co.copy() for vertex in mesh.vertices],+ [tuple(triangle.vertices) for triangle in mesh.loop_triangles],+ all_triangles=True,+ )+ nodes = {node["id"]: node for node in layout["nodes"]}+ samples = []+ for link in layout["links"]:+ if link["kind"] != "ground":+ continue+ a, b = (nodes[link[key]]["position"] for key in ("a", "b"))+ count = max(2, math.ceil(math.dist(a[::2], b[::2])))+ for i in range(count + 1):+ for side in (-1, 0, 1):+ x, z = route_sample(nodes, link, i / count, side * link["width"] / 2)+ samples.append(("road_edge" if side else "road_centre", link["id"], x, z))+ for node in nodes.values():+ x, _, z = node["position"]+ samples.append(("pad_centre", node["id"], x, z))+ radius = node.get("radius", 0)+ if radius > 0:+ # Twice the authored boundary resolution also probes chord interiors.+ for index in range(PAD_SEGMENTS * 2):+ angle = index * math.tau / (PAD_SEGMENTS * 2)+ samples.append(+ (+ "pad_perimeter",+ node["id"],+ x + radius * math.cos(angle),+ z + radius * math.sin(angle),+ )+ )+ for index, (x, z) in enumerate(((114.85542, -130.90194), (-149.67218, -54.37015))):+ samples.append(("previous_contact_defect", str(index + 1), x, z))+ samples.extend(("bridge_abutment", identifier, x, z) for identifier, x, z in bridge_contacts)+ maximum = 0.0+ worst = None+ violations = []+ misses = 0+ category_maxima = {}+ previous_defects = []+ for kind, identifier, x, z in samples:+ expected = height_at(layout, x, z)+ location, _, _, _ = bvh.ray_cast(Vector((x, -z, 2000)), Vector((0, 0, -1)))+ measured = float(location.z) if location is not None else None+ deviation = abs(measured - expected) if measured is not None else None+ record = {+ "kind": kind,+ "id": identifier,+ "x": x,+ "z": z,+ "expected_y": expected,+ "mesh_y": measured,+ "deviation_m": deviation,+ }+ if kind == "previous_contact_defect":+ previous_defects.append(record)+ if deviation is None:+ misses += 1+ violations.append(record)+ else:+ category_maxima[kind] = max(category_maxima.get(kind, 0.0), deviation)+ if deviation > maximum:+ maximum, worst = deviation, record+ if deviation > 0.05:+ violations.append(record)+ return {+ "method": "BVH vertical rays against actual triangulated MarsBasin mesh",+ "samples": len(samples),+ "tolerance_m": 0.05,+ "max_deviation_m": maximum,+ "worst_sample": worst,+ "category_max_deviation_m": category_maxima,+ "previous_defect_samples": previous_defects,+ "misses": misses,+ "violation_count": len(violations),+ "violations": violations[:50],+ "passed": not violations,+ }+++def main():+ layout = load_layout(STUDY / "layout.json")+ report = validate_layout(layout)+ bpy.ops.object.select_all(action="SELECT")+ bpy.ops.object.delete(use_global=False)+ map_collection = collection("MarsMap")+ terrain_collection = collection("Terrain", map_collection)+ routes_collection = collection("Circulation", map_collection)+ markers_collection = collection("BlockoutMarkers", map_collection)+ presentation = collection("ReviewOnly")+ soil = material("mars_terrain_vertex_color", (0.25, 0.09, 0.045))+ vertex_color = soil.node_tree.nodes.new("ShaderNodeVertexColor")+ vertex_color.layer_name = "TerrainColor"+ soil.node_tree.links.new(+ vertex_color.outputs["Color"],+ soil.node_tree.nodes.get("Principled BSDF").inputs["Base Color"],+ )+ road = material("route_blockout", (0.11, 0.17, 0.18))+ pad = material("reserved_site_blockout", (0.32, 0.38, 0.37))+ ink = material("review_annotation", (0.75, 0.9, 0.86), 0.35)++ vertices, faces = constrained_terrain(layout)+ ground = mesh_object("MarsBasin", vertices, faces, soil, terrain_collection)+ ground.data.materials.append(road)+ ground.data.materials.append(pad)+ colors = ground.data.color_attributes.new(+ name="TerrainColor", type="FLOAT_COLOR", domain="POINT"+ )+ for index, (x, y, h) in enumerate(vertices):+ grain = 0.5 + 0.5 * math.sin(x * 0.31 + y * 0.47) * math.sin(y * 0.21 - x * 0.17)+ strata = 0.5 + 0.5 * math.sin(h * 0.7 + x * 0.025)+ shade = 0.66 + grain * 0.16 + strata * 0.18+ colors.data[index].color = (0.32 * shade, 0.115 * shade, 0.052 * shade, 1)+ nodes = {node["id"]: node for node in layout["nodes"]}+ for polygon in ground.data.polygons:+ polygon.use_smooth = True+ center = polygon.center+ polygon.material_index = terrain_material(layout, nodes, center.x, -center.y)++ bridge_contacts = []+ for link in layout["links"]:+ if link["kind"] != "bridge":+ continue+ start, end = (nodes[link[key]] for key in ("a", "b"))+ a, b = start["position"], end["position"]+ dx, dz = b[0] - a[0], b[2] - a[2]+ length = math.hypot(dx, dz)+ forward = (dx / length, dz / length)+ lateral = (-dz / length, dx / length)+ start_arc = bridge_abutment(start, forward, lateral, link["width"] / 2)+ end_arc = bridge_abutment(end, (-forward[0], -forward[1]), lateral, link["width"] / 2)+ outline = [(x, a[1], z) for x, z in start_arc] + [+ (x, b[1], z) for x, z in reversed(end_arc)+ ]+ route_vertices = [xyz(point) for point in outline]+ route_faces = [tuple(range(len(route_vertices)))]+ bridge_contacts.extend((link["id"], x, z) for x, _, z in outline)+ obj = mesh_object(link["id"], route_vertices, route_faces, road, routes_collection)+ obj["route_id"] = link["id"]+ obj["layer"] = link["kind"]+ solid = obj.modifiers.new("Deck thickness", "SOLIDIFY")+ solid.thickness = 0.5+ solid.offset = -1+ bpy.context.view_layer.objects.active = obj+ bpy.ops.object.modifier_apply(modifier=solid.name)++ for node in layout["nodes"]:+ marker = bpy.data.objects.new("Site_" + node["id"], None)+ marker.location = xyz(node["position"])+ marker.empty_display_type = "CIRCLE"+ marker.empty_display_size = node.get("radius", 1)+ marker["site_id"] = node["id"]+ marker["status"] = "placeholder_not_architecture"+ markers_collection.objects.link(marker)+ if "label" not in node:+ continue+ x, y, z = node["position"]+ bpy.ops.object.text_add(location=xyz((x - node["radius"] * 0.75, y + 0.4, z - 3)))+ label = bpy.context.object+ label.name = "Label_" + node["id"]+ label.data.body = node["label"] + "\n" + str(y) + " m"+ label.data.size = 4.2+ label.data.extrude = 0+ label.data.materials.append(ink)+ move_object(label, presentation)++ report["mesh_contact"] = mesh_contact_report(layout, ground, bridge_contacts)+ report["terrain_triangles"] = len(faces)+ report["terrain_vertices"] = len(vertices)+ bridge_triangles = 0+ for obj in routes_collection.objects:+ obj.data.calc_loop_triangles()+ bridge_triangles += len(obj.data.loop_triangles)+ report["bridge_triangles"] = bridge_triangles+ report["export_triangles"] = len(faces) + bridge_triangles+ report["ground_route_objects"] = 0+ report["reserved_pad_objects"] = 0+ report["export_collection"] = "MarsMap"+ report["runtime_verified"] = False+ report["stage"] = "Blender terrain blockout; no final architecture or agent runtime"+ (STUDY / "evidence/layout-check.json").write_text(+ json.dumps(report, indent=2) + "\n", encoding="utf-8"+ )+ if not report["mesh_contact"]["passed"]:+ raise ValueError(f"Actual terrain contact check failed: {report['mesh_contact']}")++ bpy.ops.object.light_add(type="SUN", location=(150, -250, 400))+ sun = bpy.context.object+ sun.rotation_euler = (math.radians(30), math.radians(-25), math.radians(-32))+ sun.data.energy = 3+ sun.data.angle = math.radians(7)+ move_object(sun, presentation)+ scene = bpy.context.scene+ scene.world.color = (0.22, 0.15, 0.12)+ scene.render.engine = "CYCLES"+ scene.cycles.samples = 24+ scene.cycles.use_denoising = True+ scene.render.resolution_x = 1600+ scene.render.resolution_y = 1100+ scene.render.resolution_percentage = 100+ scene.render.image_settings.file_format = "PNG"+ scene.view_settings.view_transform = "AgX"+ bpy.ops.object.camera_add(location=(460, -620, 630))+ camera = bpy.context.object+ camera.name = "ReviewCamera"+ camera.data.clip_end = 5000+ camera.data.type = "ORTHO"+ camera.data.ortho_scale = 720+ camera.rotation_euler = (+ (Vector((25, 0, 5)) - camera.location).to_track_quat("-Z", "Y").to_euler()+ )+ scene.camera = camera+ move_object(camera, presentation)+ scene["review_stage"] = "terrain-and-circulation-blockout"+ scene["units"] = "1 Blender unit = 1 metre"+ scene.unit_settings.system = "METRIC"+ scene.render.filepath = "//../evidence/terrain-overview.png"+ bpy.ops.wm.save_as_mainfile(filepath=str(STUDY / "source/mars-map.blend"))+ bpy.ops.render.render(write_still=True)++ camera.location = (25, 0, 1100)+ camera.rotation_euler = (0, 0, 0)+ camera.data.ortho_scale = 760+ scene.render.filepath = "//../evidence/terrain-plan.png"+ bpy.ops.render.render(write_still=True)+ print(json.dumps(report))+++if __name__ == "__main__":+ main()diff --git a/scripts/art/mars_map.py b/scripts/art/mars_map.pynew file mode 100644index 0000000000..7dfdaa376d--- /dev/null+++ b/scripts/art/mars_map.py@@ -0,0 +1,288 @@+"""Dependency-free terrain and circulation checks for the isolated Mars blockout.++Coordinates use X/right, Y/up and Z/depth, in metres. These helpers describe a+heightfield and planned routes; they do not validate runtime collision or art.+"""++from __future__ import annotations++import json+import math+from pathlib import Path+from typing import Any++MAX_GRADE = 0.1+HEIGHT_TOLERANCE = 0.05+++def _number(value: Any, name: str) -> float:+ if isinstance(value, bool) or not isinstance(value, (int, float)):+ raise ValueError(f"{name} must be a finite number")+ try:+ result = float(value)+ except OverflowError as error:+ raise ValueError(f"{name} must be a finite number") from error+ if not math.isfinite(result):+ raise ValueError(f"{name} must be a finite number")+ return result+++def _identifier(value: Any, name: str) -> str:+ if not isinstance(value, str) or not value.strip():+ raise ValueError(f"{name} must be a nonempty string")+ return value+++def _smooth(value: float) -> float:+ value = max(0.0, min(1.0, value))+ return value * value * (3.0 - 2.0 * value)+++def _geology(x: float, z: float) -> float:+ """A low basin, higher northern/western ridges, and a winding deep ravine."""+ basin = 5.0 - z * 0.025 - x * 0.01+ basin += 1.5 * math.sin(x / 72) * math.cos(z / 58)+ basin += 0.65 * math.sin((x + z) / 19)+ western_ridge = 32 * math.exp(-(((x + 295) / 60) ** 2))+ western_ridge *= 0.75 + 0.25 * math.sin(z / 80)+ northern_ridge = 32 * math.exp(-(((z + 225) / 44) ** 2))+ northern_ridge *= 0.6 + 0.4 * math.cos(x / 100) ** 2+ eastern_spur = 22 * math.exp(-(((x - 230) / 75) ** 2) - ((z + 125) / 95) ** 2)+ southern_rim = 12 * math.exp(-(((z - 260) / 48) ** 2))+ ravine_x = 60 + 12 * math.sin(z / 90)+ ravine_width = 12 + 2 * math.sin(z / 60)+ ravine = 38 * math.exp(-0.5 * ((x - ravine_x) / ravine_width) ** 2)+ return basin + western_ridge + northern_ridge + eastern_spur + southern_rim - ravine+++def _segment_sample(+ a: dict[str, Any], b: dict[str, Any], x: float, z: float+) -> tuple[float, float]:+ """Return planar distance to a road and its pad-aware design elevation."""+ ax, ay, az = a["position"]+ bx, by, bz = b["position"]+ dx, dz = bx - ax, bz - az+ length = math.hypot(dx, dz)+ t = max(0.0, min(1.0, ((x - ax) * dx + (z - az) * dz) / (length * length)))+ perpendicular = math.hypot(x - ax - t * dx, z - az - t * dz)+ start, end = a.get("radius", 0), b.get("radius", 0)+ ramp_length = length - start - end+ # Coincident/overlapping pads of equal elevation need no ramp.+ progress = max(0.0, min(1.0, (t * length - start) / ramp_length)) if ramp_length > 0 else 0+ return perpendicular, ay + (by - ay) * progress+++def height_at(layout: dict[str, Any], x: float, z: float) -> float:+ """Sample a validated layout's terrain, leaving bridge spans unfilled.++ Flat pads take precedence. Ground routes grade the full road width and fade+ into terrain over a soft shoulder. At overlapping roads the nearest centreline+ wins; validation reports intersections whose requested heights conflict.+ """+ x, z = _number(x, "sample x"), _number(z, "sample z")+ nodes = {node["id"]: node for node in layout["nodes"]}+ pads = []+ for node in nodes.values():+ nx, ny, nz = node["position"]+ distance = math.hypot(x - nx, z - nz)+ if distance < 1e-9:+ return float(ny)+ radius = node.get("radius", 0)+ if radius > 0:+ pads.append((distance / radius, node["id"], distance, radius, ny))+ pads.sort()+ if pads and pads[0][0] <= 1:+ return float(pads[0][4])++ terrain = _geology(x, z)+ # Graded pad shoulders soften their edges without changing flat pad tops.+ best_pad = None+ for _, identifier, distance, radius, elevation in pads:+ shoulder = max(5.0, min(18.0, radius * 0.35))+ weight = 1 - _smooth((distance - radius) / shoulder)+ candidate = (weight, identifier, elevation)+ if weight > 0 and (best_pad is None or candidate[:2] > best_pad[:2]):+ best_pad = candidate+ if best_pad:+ weight, _, elevation = best_pad+ terrain += (elevation - terrain) * weight++ nearest_road = None+ for link in layout["links"]:+ if link["kind"] != "ground":+ continue+ distance, elevation = _segment_sample(nodes[link["a"]], nodes[link["b"]], x, z)+ half_width = link["width"] / 2+ shoulder = max(5.0, link["width"])+ weight = 1 - _smooth((distance - half_width) / shoulder)+ candidate = (distance, link["id"], elevation, weight)+ if weight > 0 and (nearest_road is None or candidate[:2] < nearest_road[:2]):+ nearest_road = candidate+ if nearest_road:+ _, _, elevation, weight = nearest_road+ if weight == 1:+ return float(elevation)+ terrain += (elevation - terrain) * weight+ return terrain+++def _terrain_issues(layout: dict[str, Any], nodes: dict[str, Any]) -> list[dict[str, Any]]:+ """Sample intended roads, explicitly reporting pad/intersection conflicts."""+ issues = []+ for link in layout["links"]:+ if link["kind"] != "ground":+ continue+ a, b = nodes[link["a"]], nodes[link["b"]]+ ax, _, az = a["position"]+ bx, _, bz = b["position"]+ length = math.hypot(bx - ax, bz - az)+ count = max(2, math.ceil(length / 2))+ samples = {i / count for i in range(count + 1)}+ samples.update(+ (min(1.0, a.get("radius", 0) / length), max(0.0, 1 - b.get("radius", 0) / length))+ )+ # Project every pad centre too: a narrow crossing must not hide between samples.+ for node in nodes.values():+ nx, _, nz = node["position"]+ t = ((nx - ax) * (bx - ax) + (nz - az) * (bz - az)) / (length * length)+ if 0 <= t <= 1:+ samples.add(t)+ conflicts = []+ for t in sorted(samples):+ x, z = ax + (bx - ax) * t, az + (bz - az) * t+ _, expected = _segment_sample(a, b, x, z)+ actual = height_at(layout, x, z)+ if abs(actual - expected) > HEIGHT_TOLERANCE:+ conflicts.append((abs(actual - expected), x, z, expected, actual))+ if conflicts:+ deviation, x, z, expected, actual = max(conflicts)+ issues.append(+ {+ "kind": "uncovered_ground_path",+ "link": link["id"],+ "position": [x, actual, z],+ "expected_height": expected,+ "max_height_error": deviation,+ "conflicting_samples": len(conflicts),+ }+ )+ return issues+++def validate_layout(data: Any) -> dict[str, Any]:+ """Validate the graph and designed ramp grades; report terrain conflicts.++ The returned report is JSON-serializable. A clear terrain report establishes+ sampled blockout consistency only, not mesh collision or runtime traversal.+ Unknown metadata is accepted and left untouched.+ """+ if not isinstance(data, dict) or type(data.get("schema")) is not int or data["schema"] != 1:+ raise ValueError("layout schema must be 1")+ if data.get("units") != "metres":+ raise ValueError("layout units must be metres")+ bounds = data.get("bounds")+ if not isinstance(bounds, dict):+ raise ValueError("layout bounds are required")+ limits = {+ key: _number(bounds.get(key), f"bounds.{key}") for key in ("minX", "maxX", "minZ", "maxZ")+ }+ if limits["minX"] >= limits["maxX"] or limits["minZ"] >= limits["maxZ"]:+ raise ValueError("layout bounds must have positive extent")+ if not isinstance(data.get("nodes"), list) or not data["nodes"]:+ raise ValueError("layout needs at least one node")+ if not isinstance(data.get("links"), list):+ raise ValueError("layout links must be a list")++ nodes: dict[str, Any] = {}+ centres: dict[tuple[float, float], float] = {}+ for item in data["nodes"]:+ if not isinstance(item, dict):+ raise ValueError("each node must be an object")+ identifier = _identifier(item.get("id"), "node id")+ if identifier in nodes:+ raise ValueError(f"duplicate node id: {identifier}")+ p = item.get("position")+ if not isinstance(p, list) or len(p) != 3:+ raise ValueError(f"node {identifier} needs position [x, y, z]")+ x, y, z = (_number(value, f"node {identifier} coordinate") for value in p)+ if not limits["minX"] <= x <= limits["maxX"] or not limits["minZ"] <= z <= limits["maxZ"]:+ raise ValueError(f"node {identifier} is outside bounds")+ radius = _number(item.get("radius", 0), f"node {identifier} radius")+ if radius < 0:+ raise ValueError(f"node {identifier} radius cannot be negative")+ if (x, z) in centres and centres[x, z] != y:+ raise ValueError("coincident pad centres cannot have different heightfield elevations")+ centres[x, z] = y+ nodes[identifier] = item++ link_ids: set[str] = set()+ adjacent: dict[str, set[str]] = {identifier: set() for identifier in nodes}+ max_grade = 0.0+ lengths = {"ground": 0.0, "bridge": 0.0}+ for link in data["links"]:+ if not isinstance(link, dict):+ raise ValueError("each link must be an object")+ identifier = _identifier(link.get("id"), "link id")+ if identifier in link_ids:+ raise ValueError(f"duplicate link id: {identifier}")+ link_ids.add(identifier)+ a_id = _identifier(link.get("a"), f"link {identifier} endpoint a")+ b_id = _identifier(link.get("b"), f"link {identifier} endpoint b")+ if a_id not in nodes or b_id not in nodes:+ raise ValueError(f"link {identifier} has an unknown endpoint")+ kind = link.get("kind")+ if kind not in ("ground", "bridge"):+ raise ValueError(f"link {identifier} kind must be ground or bridge")+ width = _number(link.get("width"), f"link {identifier} width")+ if width <= 0:+ raise ValueError(f"link {identifier} width must be positive")+ a, b = nodes[a_id], nodes[b_id]+ ax, ay, az = a["position"]+ bx, by, bz = b["position"]+ length = math.hypot(bx - ax, bz - az)+ if length <= 0:+ raise ValueError(f"link {identifier} must have positive horizontal length")+ run = length - a.get("radius", 0) - b.get("radius", 0) if kind == "ground" else length+ grade = abs(by - ay) / run if run > 0 else (0 if ay == by else math.inf)+ if grade > MAX_GRADE + 1e-9:+ raise ValueError(+ f"link {identifier} exceeds maximum grade {MAX_GRADE:.0%} between pad edges"+ )+ max_grade = max(max_grade, grade)+ lengths[kind] += length+ adjacent[a_id].add(b_id)+ adjacent[b_id].add(a_id)++ visited: set[str] = set()+ pending = [next(iter(nodes))]+ while pending:+ identifier = pending.pop()+ if identifier not in visited:+ visited.add(identifier)+ pending.extend(adjacent[identifier] - visited)+ if len(visited) != len(nodes):+ raise ValueError(+ f"layout graph is disconnected: {', '.join(sorted(nodes.keys() - visited))}"+ )+ positions = [node["position"] for node in nodes.values()]+ return {+ "node_count": len(nodes),+ "link_count": len(link_ids),+ "connected_nodes": len(visited),+ "span": {+ axis: max(p[i] for p in positions) - min(p[i] for p in positions)+ for i, axis in enumerate(("x", "y", "z"))+ },+ "max_grade": max_grade,+ "ground_length": lengths["ground"],+ "bridge_length": lengths["bridge"],+ "terrain_issues": _terrain_issues(data, nodes),+ "scope": "Sampled blockout geometry; runtime collision and traversal are unverified.",+ }+++def load_layout(path: str | Path) -> dict[str, Any]:+ """Load UTF-8 JSON (optional BOM) and reject invalid blockout geometry."""+ data = json.loads(Path(path).read_text(encoding="utf-8-sig"))+ validate_layout(data)+ return datadiff --git a/tests/unit/test_mars_map.py b/tests/unit/test_mars_map.pynew file mode 100644index 0000000000..42b9f06169--- /dev/null+++ b/tests/unit/test_mars_map.py@@ -0,0 +1,199 @@+"""Terrain blockout checks, separate from runtime or visual acceptance."""++from __future__ import annotations++import copy+import importlib.util+import json+import math+from pathlib import Path++import pytest++ROOT = Path(__file__).resolve().parents[2]+SPEC = importlib.util.spec_from_file_location("mars_map", ROOT / "scripts/art/mars_map.py")+assert SPEC and SPEC.loader+mars_map = importlib.util.module_from_spec(SPEC)+SPEC.loader.exec_module(mars_map)+++def layout() -> dict:+ nodes = [+ ("command", [-72, 12, -20], 22),+ ("junction", [-15, 10, 8], 4),+ ("terminal", [20, 8, 70], 24),+ ("habitat", [-100, 6, 100], 32),+ ("research", [-175, 18, -70], 22),+ ("bridge-west", [20, 12, -50], 5),+ ("bridge-east", [100, 12, -50], 5),+ ("workshop", [145, 6, 95], 24),+ ("ridge-turn-a", [170, 16, -80], 4),+ ("ridge-turn-b", [110, 20, -140], 4),+ ("comms", [190, 26, -180], 18),+ ("landing", [255, 2, 185], 34),+ ]+ links = [+ ("command", "junction"),+ ("junction", "terminal"),+ ("junction", "habitat"),+ ("command", "research"),+ ("junction", "bridge-west"),+ ("bridge-west", "bridge-east"),+ ("bridge-east", "workshop"),+ ("bridge-east", "ridge-turn-a"),+ ("ridge-turn-a", "ridge-turn-b"),+ ("ridge-turn-b", "comms"),+ ("workshop", "landing"),+ ]+ return {+ "schema": 1,+ "units": "metres",+ "bounds": {"minX": -320, "maxX": 330, "minZ": -245, "maxZ": 245},+ "nodes": [{"id": name, "position": p, "radius": radius} for name, p, radius in nodes],+ "links": [+ {+ "id": f"{a}/{b}",+ "a": a,+ "b": b,+ "kind": "bridge" if a == "bridge-west" else "ground",+ "width": 6,+ }+ for a, b in links+ ],+ }+++def test_compact_base_graph_is_connected_with_valid_pad_edge_ramps(layout: dict) -> None:+ report = mars_map.validate_layout(layout)+ assert report["connected_nodes"] == report["node_count"] == 12+ assert report["link_count"] == 11+ assert 0.08 < report["max_grade"] <= 0.1+ assert report["span"] == {"x": 430, "y": 24, "z": 365}+ assert report["bridge_length"] == 80+ assert report["terrain_issues"] == []+ assert "unverified" in report["scope"]+++def test_json_loader_accepts_bom_and_preserves_extra_metadata(tmp_path: Path, layout: dict) -> None:+ layout["authoring_note"] = "Blockout only"+ path = tmp_path / "layout.json"+ path.write_text(json.dumps(layout), encoding="utf-8-sig")+ assert mars_map.load_layout(path) == layout+++def test_disconnected_graph_is_rejected(layout: dict) -> None:+ layout["links"] = [link for link in layout["links"] if link["kind"] != "bridge"]+ with pytest.raises(ValueError, match="disconnected"):+ mars_map.validate_layout(layout)++[email protected]("bad", [math.inf, -math.inf, math.nan, True, "12"])+def test_invalid_coordinates_are_rejected(layout: dict, bad: object) -> None:+ layout["nodes"][0]["position"][1] = bad+ with pytest.raises(ValueError, match="finite number"):+ mars_map.validate_layout(layout)+++def test_duplicate_node_and_link_ids_are_rejected(layout: dict) -> None:+ invalid = copy.deepcopy(layout)+ invalid["nodes"].append(copy.deepcopy(invalid["nodes"][0]))+ with pytest.raises(ValueError, match="duplicate node"):+ mars_map.validate_layout(invalid)+ layout["links"].append(copy.deepcopy(layout["links"][0]))+ with pytest.raises(ValueError, match="duplicate link"):+ mars_map.validate_layout(layout)+++def test_missing_endpoint_is_rejected(layout: dict) -> None:+ layout["links"][0]["a"] = "missing"+ with pytest.raises(ValueError, match="unknown endpoint"):+ mars_map.validate_layout(layout)+++def test_out_of_bounds_node_is_rejected(layout: dict) -> None:+ layout["nodes"][0]["position"][0] = -321+ with pytest.raises(ValueError, match="outside bounds"):+ mars_map.validate_layout(layout)++[email protected]("bad", [0, -1, math.inf])+def test_invalid_route_width_is_rejected(layout: dict, bad: float) -> None:+ layout["links"][0]["width"] = bad+ with pytest.raises(ValueError, match="width"):+ mars_map.validate_layout(layout)+++def test_zero_length_route_is_rejected(layout: dict) -> None:+ layout["links"][0]["b"] = layout["links"][0]["a"]+ with pytest.raises(ValueError, match="positive horizontal length"):+ mars_map.validate_layout(layout)+++def test_grade_is_measured_between_flat_pad_edges(layout: dict) -> None:+ research = next(node for node in layout["nodes"] if node["id"] == "research")+ research["position"][1] = 20+ # Centre-to-centre grade is only 7%; the remaining ramp exceeds 10%.+ with pytest.raises(ValueError, match="maximum grade"):+ mars_map.validate_layout(layout)+++def test_pad_centres_and_interiors_keep_their_exact_design_elevation(layout: dict) -> None:+ for node in layout["nodes"]:+ x, y, z = node["position"]+ assert mars_map.height_at(layout, x, z) == y+ for dx, dz in [(0.3, 0), (-0.3, 0), (0, 0.3), (0, -0.3)]:+ assert mars_map.height_at(layout, x + dx * node["radius"], z + dz * node["radius"]) == y+++def test_ground_routes_stay_level_on_pads_and_ramp_between_their_edges(layout: dict) -> None:+ nodes = {node["id"]: node for node in layout["nodes"]}+ for link in layout["links"]:+ if link["kind"] != "ground":+ continue+ a, b = nodes[link["a"]], nodes[link["b"]]+ ax, ay, az = a["position"]+ bx, by, bz = b["position"]+ length = math.hypot(bx - ax, bz - az)+ for fraction in [0, 0.1, 0.25, 0.5, 0.75, 0.9, 1]:+ progress = max(+ 0, min(1, (fraction * length - a["radius"]) / (length - a["radius"] - b["radius"]))+ )+ expected = ay + (by - ay) * progress+ actual = mars_map.height_at(+ layout, ax + (bx - ax) * fraction, az + (bz - az) * fraction+ )+ assert actual == pytest.approx(expected, abs=1e-8), link["id"]+++def test_bridge_keeps_the_ravine_open_instead_of_creating_an_earth_dam(layout: dict) -> None:+ assert mars_map.height_at(layout, 60, -50) < -10+ filled = copy.deepcopy(layout)+ bridge = next(link for link in filled["links"] if link["kind"] == "bridge")+ bridge["kind"] = "ground"+ assert mars_map.height_at(filled, 60, -50) == 12+++def test_terrain_is_deterministic_and_has_relief_outside_the_base(layout: dict) -> None:+ points = [(-310, -220), (310, -220), (-300, 220), (310, 220), (60, 0)]+ heights = [mars_map.height_at(layout, x, z) for x, z in points]+ reverse_heights = [mars_map.height_at(layout, x, z) for x, z in reversed(points)]+ assert heights == list(reversed(reverse_heights))+ assert max(heights) - min(heights) > 40+++def test_pad_conflicts_are_reported_without_claiming_the_path_is_covered(layout: dict) -> None:+ layout["nodes"] = [+ {"id": "a", "position": [-60, 0, 0], "radius": 2},+ {"id": "b", "position": [60, 0, 0], "radius": 2},+ {"id": "raised-pad", "position": [0, 5, 0], "radius": 3},+ ]+ layout["links"] = [+ {"id": "through-pad", "a": "a", "b": "b", "kind": "ground", "width": 6},+ {"id": "pad-approach", "a": "b", "b": "raised-pad", "kind": "ground", "width": 6},+ ]+ report = mars_map.validate_layout(layout)+ assert mars_map.height_at(layout, 0, 0) == 5+ issue = next(issue for issue in report["terrain_issues"] if issue["link"] == "through-pad")+ assert issue["kind"] == "uncovered_ground_path"+ assert issue["max_height_error"] == 5