From 91bada388093cc70450c09d223705be567b851de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20K=C5=82ysz?= Date: Wed, 25 Nov 2026 15:58:04 +0000 Subject: [PATCH] feat: map check with Fix for cracks, collision and things floating or inside each other --- docs/AI_GUIDE.md | 4 +- docs/MAP_MODDING.md | 19 + docs/MCP.md | 1 + .../addons/openrac_library/mcp_tools.gd | 40 + .../project/addons/openrac_library/play.gd | 63 +- openrac/tools/collision_fix.py | 368 +++++++ openrac/tools/crack_fix.py | 426 ++++++++ openrac/tools/map_check.py | 929 ++++++++++++++++++ openrac/tools/openrac_editor.py | 66 +- openrac/tools/placement.py | 50 +- openrac/tools/planet.py | 14 +- openrac/tools/shared_map.py | 36 +- openrac/tools/test_editor_mcp.py | 2 +- openrac/tools/test_map_check.py | 153 +++ 14 files changed, 2135 insertions(+), 36 deletions(-) create mode 100644 openrac/tools/collision_fix.py create mode 100644 openrac/tools/crack_fix.py create mode 100644 openrac/tools/map_check.py create mode 100644 openrac/tools/test_map_check.py diff --git a/docs/AI_GUIDE.md b/docs/AI_GUIDE.md index f3643b60..db0a6e1a 100644 --- a/docs/AI_GUIDE.md +++ b/docs/AI_GUIDE.md @@ -33,7 +33,9 @@ server (docs/MCP.md), and to see the result in the game with OpenRAC's game serv Then `level_place` with the new things' `names` and `move`: it sets each one down on its whole underside (no floating, no sinking, none in a wall) and moves a crate off a slope. 4. `scene_save`, then `level_check` and `job_wait`: each refused edit comes with the node's path - and why. Fix and check again until none is left. + and why. Fix and check again until none is left. Check also lists what a player would see wrong + (cracks in the ground, collision off what is drawn, things floating or inside each other): run + `level_check_map` with `fix`, then mend the rest by hand. 5. To play it: `level_play` (the game starts on the level), or `planet_set` then `planet_add` for a new planet the ship can fly to. 6. To see it in the game, use the game server: `game_start` on the level with the packed folder, diff --git a/docs/MAP_MODDING.md b/docs/MAP_MODDING.md index c2a85b04..b416ca52 100644 --- a/docs/MAP_MODDING.md +++ b/docs/MAP_MODDING.md @@ -217,6 +217,25 @@ In practice, memory and frame time become the useful limits well before that. ## 3. Pack and export an added destination +### The map check + +Play, Check, Pack, **Add as a new planet** and map export first check the level for what a +player would see wrong, and stop when they find any: + +- cracks and holes in your own terrain (a line of sky through the ground); +- collision that does not follow what is drawn (the hero falls through, stands in the air or + sinks in); +- things floating over the ground, sunk into it or standing in a wall; +- ties and models standing inside each other. + +Each problem names its node and place; click it in the dialog to select the node. Press **Fix** +to mend what can be mended without a choice: cracks are welded and small holes filled, the +collision of your terrain is made again from what is drawn, ties and models are moved out of each +other and things are set down on the ground. What is left is listed again for you to mend by hand. +From a terminal: `openrac_editor.py check-map PROJECT [--fix] [--report FILE]` (`--report` also +writes a top view of the problems). Set `map/water` in `project.godot`'s `[openrac]` section to your +sea's height so nothing under it counts. `--keep-problems` packs a level as it is. + ### The quick way 1. In the editor, click the level (the top object in the **Level** list). Its **Properties** diff --git a/docs/MCP.md b/docs/MCP.md index 2ab7c121..eb710848 100644 --- a/docs/MCP.md +++ b/docs/MCP.md @@ -69,6 +69,7 @@ x and y across, z up, headings in degrees): | `behaviour_list` | The behaviour presets and their numbers | | `ground_at` | The floor under a point, from the level's collision | | `level_place` | Sets mobys, ties and shrubs down on their whole underside: no floating, sinking or wall (a job; `move` finds a level spot) | +| `level_check_map` | Lists what a player would see wrong (cracks, holes, collision off the drawn ground, things floating or inside each other); with `fix` mends what it can first (a job) | | `cutscene_list`, `cutscene_get`, `cutscene_remove` | The level's cutscenes as `.cutscene` documents ([CUTSCENE_FORMAT.md](CUTSCENE_FORMAT.md)) | | `cutscene_write`, `cutscene_add` | Write a whole cutscene, or add shots, actors, lines, sounds and events to one | | `cutscene_check` | What the game would not take or would skip | diff --git a/openrac/project/addons/openrac_library/mcp_tools.gd b/openrac/project/addons/openrac_library/mcp_tools.gd index cb3bd560..8312f31c 100644 --- a/openrac/project/addons/openrac_library/mcp_tools.gd +++ b/openrac/project/addons/openrac_library/mcp_tools.gd @@ -51,6 +51,14 @@ func register(on: Object, owner: EditorPlugin) -> void: "move": prop("boolean", "A thing that cannot stand where it is moves to the nearest good spot (default false: only listed)."), "water": prop("number", "The water's height: things afloat on it stay."), "check": prop("boolean", "Only list what is off; change nothing.")}, [], level_place) + add("level_check_map", "Checks the level for what a player would see wrong: cracks and holes in the level's own " + + "ground, collision off what is drawn (falls through, stands in the air), things floating, sunk or inside " + + "each other. Each problem as {node, path, why} (why ends with \"at (x, y, z)\"). Pack, Play, Add as planet " + + "and map export refuse a level with any. With fix it first mends what it can: cracks welded, collision " + + "made from the drawn ground, things set down and moved apart; the scene is read again. A job.", { + "fix": prop("boolean", "Mend what can be mended first (default false: only list)."), + "water": prop("number", "The sea's height: nothing under it shows (default: the project's map/water).")}, + [], level_check_map) add("planet_get", "The planet's name in the ship's menu and its id (set once it was added).", {}, [], planet_get, read_only) add("planet_set", "Names this level as a planet (the ship's menu): plain letters A-Z, digits, spaces and punctuation, " + "at most 40 characters. Saved in project.godot.", {"name": prop("string", "The planet's name.")}, ["name"], planet_set) @@ -212,6 +220,26 @@ func parsed(code: int, lines: PackedStringArray, kind: String) -> Dictionary: var result: Dictionary = {"ok": code == 0 and problems.is_empty(), "kind": kind, "problems": problems, "said": said} + if kind == "check-map": + var fixed: bool = false + + for line in said: + fixed = fixed or String(line).begins_with("fixed: ") + + # The fix wrote the scene under the editor: read it again. + if fixed and at != null: + EditorInterface.reload_scene_from_path.call_deferred(at.scene_file_path) + + if not result["ok"]: + if not problems.is_empty(): + result["error"] = "%d problem(s) a player would see: run with fix, then mend the rest (path) by hand." % problems.size() + elif not said.is_empty(): + result["error"] = "\n".join(PackedStringArray(said.slice(-5))) + else: + result["error"] = "It did not run." + + return result + if kind == "place": # The scene file was written under the editor: read it again (nothing changed with --check). if at != null and not said.is_empty() and not String(said[-1]).begins_with("would") and not String(said[-1]).begins_with("set 0 "): @@ -265,6 +293,18 @@ func level_place(args: Dictionary) -> Variant: return run_tool("place", "Set things down", extra) +func level_check_map(args: Dictionary) -> Variant: + var extra := PackedStringArray() + + if bool(args.get("fix", false)): + extra.append("--fix") + + if args.get("water") != null: + extra.append_array(["--water", str(float(args["water"]))]) + + return run_tool("check-map", "Check the map", extra) + + func planet_get(_args: Dictionary) -> Dictionary: PlanetInspector.sync_id() return {"name": String(ProjectSettings.get_setting("openrac/planet/name", "")), diff --git a/openrac/project/addons/openrac_library/play.gd b/openrac/project/addons/openrac_library/play.gd index 5bb190ec..aba7a62a 100644 --- a/openrac/project/addons/openrac_library/play.gd +++ b/openrac/project/addons/openrac_library/play.gd @@ -17,6 +17,8 @@ var dialog: AcceptDialog var problems: ItemList var summary: Label var worker: Thread +## Fix in the dialog when the map has problems (openrac_editor.py check-map --fix). +var fix_button: Button func _init() -> void: @@ -42,6 +44,12 @@ func _init() -> void: problems.item_clicked.connect(func(index: int, _at: Vector2, _button: int) -> void: select_problem(index)) box.add_child(problems) dialog.add_child(box) + fix_button = dialog.add_button("Fix", true, "fix") + fix_button.tooltip_text = "Mends what can be mended without a choice: cracks and holes in your ground welded, collision made from what you see, things set down on the ground and moved out of each other." + fix_button.visible = false + dialog.custom_action.connect(func(action: StringName) -> void: + if action == &"fix": + fix()) add_child(dialog) @@ -126,7 +134,7 @@ static func game_beside(states: String) -> String: return states.left(states.length() - name.length()) + name.replace("-states", "") -## The command for KIND ("check" or "play"), or a sentence saying what is missing. +## The command for KIND ("check", "check-map" or "play"), or a sentence saying what is missing. static func command_for(kind: String, level: Dictionary) -> Variant: var python: String = user_arg("--openrac-python") var tools: String = user_arg("--openrac-tools") @@ -170,8 +178,30 @@ func start() -> void: worker.start(run.bind(command)) +## Saves, then runs check-map --fix on this level in the background; the scene is read again after. +func fix() -> void: + if worker != null and worker.is_started(): + return + + var command: Variant = command_for("check-map", this_level()) + + if command is String: + show_result(1, PackedStringArray([command])) + return + + var args: PackedStringArray = command["args"] + args.append("--fix") + command["args"] = args + EditorInterface.save_all_scenes() + dialog.hide() + play_button.disabled = true + play_button.text = "Fixing" + worker = Thread.new() + worker.start(run.bind(command, true)) + + ## On the worker's thread: runs the command and hands its lines back to the editor's thread. -func run(command: Dictionary) -> void: +func run(command: Dictionary, fixing: bool = false) -> void: var output: Array = [] var code: int = OS.execute(command["program"], command["args"], output, true) var lines := PackedStringArray() @@ -179,15 +209,25 @@ func run(command: Dictionary) -> void: for chunk in output: lines.append_array(String(chunk).split("\n", false)) - finish.call_deferred(code, lines) + finish.call_deferred(code, lines, fixing) -func finish(code: int, lines: PackedStringArray) -> void: +func finish(code: int, lines: PackedStringArray, fixing: bool = false) -> void: worker.wait_to_finish() worker = null play_button.disabled = false play_button.text = "Play Level" + # The fix wrote the level's scene and ground: show them as they are now. + if fixing: + var root: Node = EditorInterface.get_edited_scene_root() + + if root != null and not root.scene_file_path.is_empty(): + EditorInterface.reload_scene_from_path(root.scene_file_path) + + if code != 0: + lines.append("openrac-map-problems") + # The game is up: its window says so, a dialog would only stand in the way. if code == 0 and lines.has("openrac-started"): play_button.text = "Game Started" @@ -213,7 +253,20 @@ func show_result(code: int, lines: PackedStringArray) -> void: elif not line.begins_with("openrac-"): said.append(line) - if problems.item_count > 0: + var map: bool = lines.has("openrac-map-problems") + var fixed := PackedStringArray() + + for line in said: + if line.begins_with("fixed: "): + fixed.append(line.trim_prefix("fixed: ")) + + fix_button.visible = map and fixed.is_empty() + + if problems.item_count > 0 and map: + summary.text = ("Fixed: %s.\n" % "; ".join(fixed) if not fixed.is_empty() else "") \ + + "The map has %d problems a player would see. %s Click one to find it." % [problems.item_count, + "These are left for you." if not fixed.is_empty() else "Fix mends what it can."] + elif problems.item_count > 0: summary.text = "%d edits can't be built. Click one, fix it, then play again." % problems.item_count elif code == 0: summary.text = "\n".join(said) if not said.is_empty() else "Done." diff --git a/openrac/tools/collision_fix.py b/openrac/tools/collision_fix.py new file mode 100644 index 00000000..112a7318 --- /dev/null +++ b/openrac/tools/collision_fix.py @@ -0,0 +1,368 @@ +"""Collision made from what is drawn: the map's own terrain (map_check.py's "terrain" meshes) as +the hero meets it, so he never stands in the air over it, sinks into it or falls through it. + +The drawn ground's top is sampled every STEP units where the hero can go (near the level's +collision now), then laid out as triangles from big to small squares: a square is kept when its +corners follow every sample in it within TOLERANCE, else it is cut in four. Flat ground takes a few +big triangles, a slope or a cliff many small ones, and the whole stays far under the level's +collision room. Each triangle keeps the surface type (footstep sound, slippery ground) of the old +collision under it. + +The collision nodes that were that ground's (most of their floor nearer it than any house or tie) are taken out +of Game/Collision and one node, DrawnGround (collision/drawn_ground.glb), takes their place; walls +and other nodes (a house, the ties' blocks) stay as they are.""" + +from __future__ import annotations + +import re + +import map_check as mc # noqa: F401,I001 (first: it puts the release's numpy on the path) +import numpy as np + +import placement as pl + +STEP = 1.0 # the drawn ground is sampled this often +TOLERANCE = 0.2 # a square's triangles follow every sample under them this closely (across the surface) +BIGGEST = 32 # the biggest square, in samples +NEAR = 8.0 # a collision node's floor this close to the drawn terrain may be its collision +SHARE = 0.5 # ... when at least this share of its floor is +OVER = 0.5 # an added collision floor this far over everything drawn is air +NAME = "DrawnGround" +FILE = "drawn_ground.glb" + + +def surface(level: mc.Level, water: float | None): + """The drawn ground's top over the hero's reach: (x0, y0, heights (rows, columns), mask of + the samples to keep). NaN where nothing of the map's own terrain is.""" + made = [m for m in level.drawn if m.kind == "terrain" and np.abs(m.tris).max() < mc.FAR] + if not made: + return None + ground = pl.Ground(np.concatenate([m.tris for m in made])) + old = old_collision(level) + tris = np.concatenate([t for _, t, _ in old]) if old else np.concatenate([m.tris for m in made]) + lo = tris.reshape(-1, 3).min(0)[:2] - mc.REACH + hi = tris.reshape(-1, 3).max(0)[:2] + mc.REACH + xs = np.arange(lo[0], hi[0] + STEP, STEP) + ys = np.arange(lo[1], hi[1] + STEP, STEP) + X, Y = np.meshgrid(xs, ys) + P = np.c_[X.ravel(), Y.ravel()] + near = mc.reach(level, P, X.shape, STEP) if old else np.ones(len(P), bool) + Z = np.full(len(P), np.nan) + z, _ = ground.floor(P[near], np.full(near.sum(), 1e9), np.full(near.sum(), -1e9)) + Z[near] = z + return float(lo[0]), float(lo[1]), Z.reshape(X.shape) + + +def old_collision(level: mc.Level): + """Each node of Game/Collision: (name, triangles (N, 3, 3) in game units, type bytes (N,)).""" + import collision_scene as cs + _ext, sub, nodes = cs.read_scene(level.text) + out = [] + for node in cs.layer_nodes(nodes, ("Game/Collision",)): + try: + found = cs.node_triangles(level.project, node, sub) + except Exception: # noqa: BLE001 - a node the pack cannot read stays as it is + continue + if found: + out.append((node["name"], np.array([p for p, _ in found], np.float64).reshape(-1, 3, 3), + np.array([k if k is not None else cs.DEFAULT_SURFACE for _, k in found]))) + return out + + +def squares(Z: np.ndarray) -> list[tuple[int, int, int]]: + """The squares (row, column, size in samples) that cover Z's samples, biggest first.""" + rows, cols = Z.shape + n = BIGGEST + R = -(-(rows - 1) // n) * n + 1 + C = -(-(cols - 1) // n) * n + 1 + H = np.full((R, C), np.nan) + H[:rows, :cols] = Z + taken = np.zeros((R - 1, C - 1), bool) + out = [] + s = n + while s >= 1: + win = np.lib.stride_tricks.sliding_window_view(H, (s + 1, s + 1))[::s, ::s] + u = np.linspace(0, 1, s + 1) + a, b, c, d = win[..., 0, 0], win[..., 0, -1], win[..., -1, 0], win[..., -1, -1] + top = a[..., None] + (b - a)[..., None] * u + bottom = c[..., None] + (d - c)[..., None] * u + guess = top[..., None, :] + (bottom - top)[..., None, :] * u[:, None] + # The distance across the surface, not up: steep rock may be off more in height. + size = s * STEP + gx = ((b - a) + (d - c)) / (2 * size) + gy = ((c - a) + (d - b)) / (2 * size) + with np.errstate(invalid="ignore"): + error = np.abs(win - guess).max(axis=(-1, -2)) / np.sqrt(1 + gx * gx + gy * gy) + free = ~taken[::s, ::s][:win.shape[0], :win.shape[1]] + if s > 1: + leaf = free & (error <= TOLERANCE) + else: + leaf = free & (np.isfinite(win).sum(axis=(-1, -2)) >= 3) + for i, j in zip(*np.nonzero(leaf)): + out.append((int(i * s), int(j * s), s)) + taken[i * s:i * s + s, j * s:j * s + s] = True + s //= 2 + return out + + +def triangles(x0: float, y0: float, Z: np.ndarray, found: list[tuple[int, int, int]]) -> np.ndarray: + """Each square as two triangles (the diagonal that follows its middle better), or as the ones + its sampled corners allow.""" + out = [] + for i, j, s in found: + corner = {} + for di, dj in ((0, 0), (0, s), (s, 0), (s, s)): + z = Z[i + di, j + dj] if i + di < Z.shape[0] and j + dj < Z.shape[1] else np.nan + if np.isfinite(z): + corner[(di, dj)] = (x0 + (j + dj) * STEP, y0 + (i + di) * STEP, float(z)) + if len(corner) < 3: + continue + a, b, c, d = (corner.get(k) for k in ((0, 0), (0, s), (s, 0), (s, s))) + if len(corner) == 3: + out.append([p for p in (a, b, d, c) if p is not None]) + continue + m = Z[i + s // 2, j + s // 2] if s > 1 else np.nan + if np.isfinite(m) and abs((a[2] + d[2]) / 2 - m) > abs((b[2] + c[2]) / 2 - m): + out += [[a, b, c], [b, d, c]] + else: + out += [[a, b, d], [a, d, c]] + return np.array(out, np.float64).reshape(-1, 3, 3) + + +def surface_types(new: np.ndarray, old: list) -> np.ndarray: + """Each new triangle's type byte: the old collision floor's under its middle, else the + default.""" + import collision_scene as cs + kinds = np.full(len(new), cs.DEFAULT_SURFACE) + floors = [(t, k) for _, t, k in old] + if not floors: + return kinds + tris = np.concatenate([t for t, _ in floors]) + types = np.concatenate([k for _, k in floors]) + ground = pl.Ground(tris, types.astype(str)) + centre = new.mean(1) + z, _ = ground.floor(centre[:, :2], centre[:, 2] + 3.0, centre[:, 2] - 3.0) + keys = np.floor(centre[:, :2] / pl.CELL).astype(int) + for n, k in enumerate(map(tuple, keys)): + if np.isnan(z[n]): + continue + cand = ground.floor_cells.get(k) + if cand is None: + continue + T = ground.floors[cand] + dist = np.linalg.norm(T.mean(1) - centre[n], axis=1) + kinds[n] = int(ground.floor_owner[cand][dist.argmin()]) + return kinds + + +def replaced(level: mc.Level, old: list, Z: np.ndarray, x0: float, y0: float) -> list[str]: + """The old nodes that are the terrain's collision: most of their floor (SHARE) nearer the + drawn terrain than any other drawn thing (a house, a tie), within NEAR of it. A disc tile + (Tile_XX_YY) is the level's old ground and goes too when it lies over the map's terrain.""" + others = [m.tris for m in level.drawn if m.kind == "static"] + [m.tris for m in level.things if m.kind == "tie"] + things = pl.Ground(np.concatenate(others)) if others else None + out = [] + for name, tris, _ in old: + if name == NAME: + out.append(name) + continue + n = np.cross(tris[:, 1] - tris[:, 0], tris[:, 2] - tris[:, 0]) + up = np.abs(n[:, 2]) > pl.FLOOR_NZ * np.linalg.norm(n, axis=1) + if not up.any(): + continue + c = tris[up].mean(1) + j = np.round((c[:, 0] - x0) / STEP).astype(int) + i = np.round((c[:, 1] - y0) / STEP).astype(int) + inside = (i >= 0) & (i < Z.shape[0]) & (j >= 0) & (j < Z.shape[1]) + z = np.full(len(c), np.nan) + z[inside] = Z[i[inside], j[inside]] + terrain = np.abs(z - c[:, 2]) + thing = np.full(len(c), np.inf) + if things is not None: + zt, _ = things.floor(c[:, :2], c[:, 2] + NEAR, c[:, 2] - NEAR) + thing = np.where(np.isnan(zt), np.inf, np.abs(zt - c[:, 2])) + ours = (terrain < NEAR) & (terrain <= thing) + if ours.sum() >= SHARE * len(c): + out.append(name) + return out + + +def make(level: mc.Level, water: float | None = None) -> dict | None: + """The collision for LEVEL's own terrain, written beside the scene, and the scene's text with + it in place of the nodes it replaces: {"text", "triangles", "replaced"}; None when the level + has no terrain of its own.""" + import collision_scene as cs + found = surface(level, water) + if found is None: + return None + x0, y0, Z = found + new = triangles(x0, y0, Z, squares(Z)) + old = old_collision(level) + gone = replaced(level, old, Z, x0, y0) + kinds = surface_types(new, [o for o in old if o[0] in gone]) + by_kind: dict[int, list] = {} + for t, k in zip(new, kinds): + q = tuple(tuple(int(round(v * cs.SCALE)) for v in p) for p in t) + by_kind.setdefault(int(k), []).append(q) + file = level.dir / "collision" / FILE + file.parent.mkdir(parents=True, exist_ok=True) + file.write_bytes(cs.triangles_glb(NAME, by_kind)) + res = "res://" + file.relative_to(level.project).as_posix() + text = remove_nodes(level.text, [f"Game/Collision/{name}" for name in gone]) + text = add_node(text, res) + return {"text": text, "triangles": len(new), "replaced": [g for g in gone if g != NAME]} + + +SECTION = re.compile(r'^\[node name="([^"]+)" parent="([^"]+)"', re.M) + + +def remove_nodes(text: str, paths: list[str]) -> str: + """TEXT without the nodes at PATHS (relative to the scene's root) and their children.""" + if not paths: + return text + parts = re.split(r"(?m)^(?=\[)", text) + out = [] + for part in parts: + m = SECTION.match(part) + if m: + path = f"{m.group(2)}/{m.group(1)}" + if any(path == p or path.startswith(p + "/") or m.group(2) == p or m.group(2).startswith(p + "/") + for p in paths): + continue + out.append(part) + return "".join(out) + + +def add_node(text: str, res: str) -> str: + """TEXT with a node DrawnGround under Game/Collision, an instance of RES.""" + rid = "drawn_ground" + if f'id="{rid}"' not in text: + heads = list(re.finditer(r'(?m)^\[ext_resource [^\n]*\]\n', text)) + at = heads[-1].end() if heads else text.index("\n") + 1 + text = text[:at] + f'[ext_resource type="PackedScene" path="{res}" id="{rid}"]\n' + text[at:] + text = text.rstrip("\n") + f'\n\n[node name="{NAME}" parent="Game/Collision" instance=ExtResource("{rid}")]\n' + return text + + +def follow(before: mc.Level, after_text: str) -> tuple[str, int]: + """The collision of the ties a fix moved, moved with them: the triangles of each added + collision node (not the disc's tiles, not DrawnGround) inside a moved tie's old box go by its + move. A node that changed is written again whole (collision/.glb, in level units) and + the scene points at it. Returns (the scene text, how many triangles moved).""" + import collision_scene as cs + old = {n[0]: n[4] for n in before.nodes if n[1] == "Game/Ties"} + new = {n[0]: n[4] for n in mc.scene_nodes(after_text) if n[1] == "Game/Ties"} + moves = [] + for m in before.things: + if m.kind == "tie" and m.name in new and not np.allclose(old[m.name], new[m.name], atol=1e-4): + V = m.tris.reshape(-1, 3) + moves.append((V.min(0) - [0.5, 0.5, 1.0], V.max(0) + [0.5, 0.5, 1.0], new[m.name] - old[m.name])) + if not moves: + return after_text, 0 + manifest = before.dir / "collision" / "collision.json" + tiles = set() + if manifest.is_file(): + import json + tiles = set(json.loads(manifest.read_text(encoding="utf-8")).get("tiles", {})) + _ext, sub, nodes = cs.read_scene(after_text) + text, total = after_text, 0 + for node in cs.layer_nodes(nodes, ("Game/Collision",)): + if node["name"] in tiles or node["name"] == NAME or node["instance"] is None: + continue + try: + found = cs.node_triangles(before.project, node, sub) + except Exception: # noqa: BLE001 - a node the pack cannot read stays as it is + continue + if not found: + continue + tris = np.array([p for p, _ in found], np.float64).reshape(-1, 3, 3) + kinds = [k for _, k in found] + centre = tris.mean(1) + moved = np.zeros(len(tris), bool) + for lo, hi, delta in moves: + inside = ~moved & (centre >= lo).all(1) & (centre <= hi).all(1) + tris[inside] += delta + moved |= inside + if not moved.any(): + continue + text = rewrite(before, text, node["name"], tris, kinds) + total += int(moved.sum()) + return text, total + + +def added_nodes(level: mc.Level, text: str): + """The added collision nodes of TEXT (not the disc's tiles, not DrawnGround) with their + triangles in level units and type bytes: [(name, (N, 3, 3), [kind])].""" + import json + import collision_scene as cs + manifest = level.dir / "collision" / "collision.json" + tiles = set(json.loads(manifest.read_text(encoding="utf-8")).get("tiles", {})) if manifest.is_file() else set() + _ext, sub, nodes = cs.read_scene(text) + out = [] + for node in cs.layer_nodes(nodes, ("Game/Collision",)): + if node["name"] in tiles or node["name"] == NAME or node["instance"] is None: + continue + try: + found = cs.node_triangles(level.project, node, sub) + except Exception: # noqa: BLE001 - a node the pack cannot read stays as it is + continue + if found: + out.append((node["name"], np.array([p for p, _ in found], np.float64).reshape(-1, 3, 3), + [k for _, k in found])) + return out + + +def rewrite(level: mc.Level, text: str, name: str, tris: np.ndarray, kinds: list) -> str: + """Writes Game/Collision's node NAME again as TRIS (collision/.glb) and points TEXT at it.""" + import collision_scene as cs + by_kind: dict[int, list] = {} + for t, k in zip(tris, kinds): + by_kind.setdefault(int(k), []).append(tuple(tuple(int(round(v * cs.SCALE)) for v in p) for p in t)) + file = level.dir / "collision" / f"{name.lower()}.glb" + file.write_bytes(cs.triangles_glb(name, by_kind)) + return repoint(text, name, "res://" + file.relative_to(level.project).as_posix()) + + +def trim(level: mc.Level) -> tuple[str, int]: + """The added collision's floors that lie over everything drawn (OVER above the highest drawn + surface there: a block round a rock wider than the rock, a post taller than its tree) taken + out, so the hero never stands on air. Returns (the scene text, how many went).""" + meshes = [m.tris for m in level.drawn if np.abs(m.tris).max() < mc.FAR] + [m.tris for m in level.things] + if not meshes: + return level.text, 0 + seen = pl.Ground(np.concatenate(meshes)) + text, total = level.text, 0 + for name, tris, kinds in added_nodes(level, level.text): + n = np.cross(tris[:, 1] - tris[:, 0], tris[:, 2] - tris[:, 0]) + up = n[:, 2] > pl.FLOOR_NZ * np.linalg.norm(n, axis=1) + up |= -n[:, 2] > pl.FLOOR_NZ * np.linalg.norm(n, axis=1) + if not up.any(): + continue + c = tris[up].mean(1) + z, _ = seen.floor(c[:, :2], np.full(len(c), 1e9), np.full(len(c), -1e9)) + air = np.zeros(len(tris), bool) + air[np.nonzero(up)[0]] = ~np.isnan(z) & (c[:, 2] > z + OVER) + if not air.any(): + continue + text = rewrite(level, text, name, tris[~air], [k for k, a in zip(kinds, air) if not a]) + total += int(air.sum()) + return text, total + + +def repoint(text: str, name: str, res: str) -> str: + """TEXT with Game/Collision's node NAME an instance of RES at the level's origin (its + triangles are written where they stand).""" + rid = "collision_" + re.sub(r"\W", "_", name.lower()) + if f'id="{rid}"' not in text: + heads = list(re.finditer(r'(?m)^\[ext_resource [^\n]*\]\n', text)) + at = heads[-1].end() if heads else text.index("\n") + 1 + text = text[:at] + f'[ext_resource type="PackedScene" path="{res}" id="{rid}"]\n' + text[at:] + head = re.compile(r'(?m)^\[node name="' + re.escape(name) + r'" parent="Game/Collision"[^\n]*\]\n') + m = head.search(text) + if m is None: + return text + end = text.find("\n[", m.end() - 1) + end = len(text) if end < 0 else end + 1 + body = re.sub(r"(?m)^transform = [^\n]*\n", "", text[m.end():end]) + line = f'[node name="{name}" parent="Game/Collision" instance=ExtResource("{rid}")]\n' + return text[:m.start()] + line + body + text[end:] diff --git a/openrac/tools/crack_fix.py b/openrac/tools/crack_fix.py new file mode 100644 index 00000000..6c3b216a --- /dev/null +++ b/openrac/tools/crack_fix.py @@ -0,0 +1,426 @@ +"""Mends the cracks map_check.py finds in a drawn mesh (a level's own terrain.glb): each vertex +a little off another face's edge is moved onto it, and that face is split at it, so both sides +share the vertex and no line of sky shows between them; small holes are filled. + +Works on a glb whose primitives are indexed triangles in one buffer (what the editor and the +level generators write). The new vertices take their attributes (normal, colour, texture place) +from the edge they lie on, so nothing changes in the picture but the cracks.""" + +from __future__ import annotations + +import json +import struct +from pathlib import Path + +import map_check as mc # noqa: F401,I001 (first: it puts the release's numpy on the path) +import numpy as np + + +CLOSE = 0.05 # open edges' vertices this close are one (a sliver left of a crack) + +TYPES = {5120: np.int8, 5121: np.uint8, 5122: np.int16, 5123: np.uint16, 5125: np.uint32, 5126: np.float32} +WIDTH = {"SCALAR": 1, "VEC2": 2, "VEC3": 3, "VEC4": 4, "MAT4": 16} + + +class Glb: + """A glb read into numpy: each primitive's attributes and indices, to change and write back.""" + + def __init__(self, path: Path): + data = Path(path).read_bytes() + if data[:4] != b"glTF": + raise ValueError(f"{path} is not a glb") + length = struct.unpack(" 1 or any("uri" in b for b in self.doc.get("buffers", [])): + raise ValueError(f"{path}: only one embedded buffer is supported") + + def read(self, i: int) -> np.ndarray: + a = self.doc["accessors"][i] + if "sparse" in a or "bufferView" not in a: + raise ValueError("sparse accessors are not supported") + v = self.doc["bufferViews"][a["bufferView"]] + n, dt = WIDTH[a["type"]], np.dtype(TYPES[a["componentType"]]) + off = v.get("byteOffset", 0) + a.get("byteOffset", 0) + stride = v.get("byteStride", 0) or n * dt.itemsize + raw = np.frombuffer(self.blob, np.uint8, (a["count"] - 1) * stride + n * dt.itemsize, off) if a["count"] else \ + np.zeros(0, np.uint8) + if a["count"] == 0: + return np.zeros((0, n), dt) + rows = np.lib.stride_tricks.as_strided(raw, (a["count"], n * dt.itemsize), (stride, 1)) + return rows.copy().view(dt).reshape(a["count"], n) + + def primitives(self): + """(mesh, primitive index, primitive) of every triangle primitive with indices.""" + for m, mesh in enumerate(self.doc.get("meshes", [])): + for p, prim in enumerate(mesh["primitives"]): + if prim.get("mode", 4) == 4 and "indices" in prim and "targets" not in prim: + yield m, p, prim + + def write(self, path: Path, changed: dict) -> None: + """Writes the glb with CHANGED's primitives ({(mesh, prim): (attributes {name: array}, + indices)}) in place of theirs; every other part as it was, the buffer packed again.""" + doc = json.loads(json.dumps(self.doc)) + out = bytearray() + views, accessors = [], [] + + def put(data: bytes, target: int | None = None) -> int: + while len(out) % 4: + out.append(0) + view = {"buffer": 0, "byteOffset": len(out), "byteLength": len(data)} + if target is not None: + view["target"] = target + out.extend(data) + views.append(view) + return len(views) - 1 + + def accessor(old: dict, array: np.ndarray, target: int) -> int: + a = {k: v for k, v in old.items() if k not in ("bufferView", "byteOffset", "count", "min", "max", "sparse")} + array = np.ascontiguousarray(array.astype(TYPES[old["componentType"]])) + a["bufferView"] = put(array.tobytes(), target) + a["count"] = int(len(array)) + if "min" in old and len(array): + a["min"] = array.reshape(len(array), -1).min(0).tolist() + a["max"] = array.reshape(len(array), -1).max(0).tolist() + accessors.append(a) + return len(accessors) - 1 + + # Every accessor a primitive uses is written again (changed or as it was); images keep + # their bytes. + for m, mesh in enumerate(doc.get("meshes", [])): + for p, prim in enumerate(mesh["primitives"]): + attrs, indices = changed.get((m, p), (None, None)) + for name, i in list(prim["attributes"].items()): + array = attrs[name] if attrs is not None else self.read(i) + prim["attributes"][name] = accessor(self.doc["accessors"][i], array, 34962) + if "indices" in prim: + array = indices if indices is not None else self.read(prim["indices"]).reshape(-1) + prim["indices"] = accessor(self.doc["accessors"][prim["indices"]], array.reshape(-1, 1), 34963) + for target in prim.get("targets", []): + for name, i in list(target.items()): + target[name] = accessor(self.doc["accessors"][i], self.read(i), 34962) + for image in doc.get("images", []): + if "bufferView" in image: + v = self.doc["bufferViews"][image["bufferView"]] + at = v.get("byteOffset", 0) + image["bufferView"] = put(self.blob[at:at + v["byteLength"]]) + for skin in doc.get("skins", []): + if "inverseBindMatrices" in skin: + i = skin["inverseBindMatrices"] + skin["inverseBindMatrices"] = accessor(self.doc["accessors"][i], self.read(i), None) + if doc.get("animations"): + raise ValueError("animated glbs are not mended") + doc["accessors"], doc["bufferViews"] = accessors, views + while len(out) % 4: + out.append(0) + doc["buffers"] = [{"byteLength": len(out)}] + head = json.dumps(doc, separators=(",", ":")).encode("utf-8") + head += b" " * (-len(head) % 4) + total = 12 + 8 + len(head) + 8 + len(out) + Path(path).write_bytes(b"glTF" + struct.pack(" dict[int, list[np.ndarray]]: + """Each mesh's world matrices (4 x 4), by the nodes that draw it.""" + out: dict[int, list[np.ndarray]] = {} + + def local(node): + if "matrix" in node: + return np.array(node["matrix"], np.float64).reshape(4, 4).T + m = np.eye(4) + x, y, z, w = node.get("rotation", [0, 0, 0, 1]) + r = np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)], + [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)], + [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)]]) + m[:3, :3] = r * np.array(node.get("scale", [1, 1, 1]))[None] + m[:3, 3] = node.get("translation", [0, 0, 0]) + return m + + def walk(i, parent): + node = doc["nodes"][i] + m = parent @ local(node) + if "mesh" in node: + out.setdefault(node["mesh"], []).append(m) + for c in node.get("children", []): + walk(c, m) + scene = doc.get("scenes", [{}])[doc.get("scene", 0)] if doc.get("scenes") else {"nodes": range(len(doc["nodes"]))} + for i in scene.get("nodes", []): + walk(i, np.eye(4)) + return out + + +def mend(path: Path, out: Path | None = None, water: float | None = None, holes: bool = True) -> dict: + """Mends PATH's cracks (into OUT, else in place). Returns {"moved", "split", "filled", "joined"}: + vertices moved onto an edge, faces split, holes filled, vertices joined to a close one.""" + glb = Glb(path) + worlds = node_worlds(glb.doc) + done = {"moved": 0, "split": 0, "filled": 0, "joined": 0} + changed = {} + for m, mesh in enumerate(glb.doc.get("meshes", [])): + if len(worlds.get(m, [])) != 1: + continue # a mesh drawn twice (or never) is left as it is + world = worlds[m][0] + inverse = np.linalg.inv(world) + prims = [(p, prim) for mm, p, prim in glb.primitives() if mm == m] + if not prims: + continue + attrs = {p: {k: glb.read(i).astype(np.float64) for k, i in prim["attributes"].items()} for p, prim in prims} + index = {p: glb.read(prim["indices"]).reshape(-1).astype(np.int64) for p, prim in prims} + for _round in range(10): + # Every face of the mesh, with its primitive, in world space. + owner = np.concatenate([np.full(len(index[p]) // 3, p) for p, _ in prims]) + corner = np.concatenate([index[p][:len(index[p]) // 3 * 3] for p, _ in prims]).reshape(-1, 3) + world_pos = {p: attrs[p]["POSITION"] @ world[:3, :3].T + world[:3, 3] for p, _ in prims} + tris = np.concatenate([world_pos[p][index[p][:len(index[p]) // 3 * 3]] for p, _ in prims]).reshape(-1, 3, 3) + if np.abs(tris).max(initial=0) > mc.FAR: + break + verts, edges, faces, inverse_ids, good = mc.open_edges(tris, whole=True) + if len(edges) == 0: + break + targets = np.concatenate([edges, mc.seam_edges(faces)]) + ids, dist, edge, along = mc.crack_points(verts, edges, where=True, targets=targets) + bad = dist < mc.GAP + if water is not None: + bad &= verts[ids][:, 2] > water + 0.1 + filling = holes and (not bad.any() or _round >= 3) + if not bad.any() and not filling: + break + # Corners of each welded vertex, to move them all together. + corners_of: dict[int, list[int]] = {} + for c, v in enumerate(inverse_ids): + corners_of.setdefault(int(v), []).append(c) + faces_of_edge: dict = {} + for f, (x, y, z) in enumerate(faces): + for key in ((x, y), (y, z), (z, x)): + faces_of_edge.setdefault((int(min(key)), int(max(key))), []).append(f) + splits: dict[int, dict] = {} + for v, e, t in zip(ids[bad], edge[bad], along[bad]): + a, b = targets[e] + # A vertex on the edge keeps its place, one a little off it goes onto it; the + # split puts the new corner exactly there, so both sides share it. + target = verts[a] + (verts[b] - verts[a]) * t + if dist[np.searchsorted(ids, v)] < mc.T_JUNCTION: + target = verts[v] + else: + local = (inverse @ np.append(target, 1.0))[:3] + for c in corners_of[int(v)]: + f, k = divmod(c, 3) + attrs[owner[f]]["POSITION"][corner[f, k]] = local + done["moved"] += 1 + # Every face on that edge (one on an open edge, three or more on a seam). One + # edge of a face a round: a cut on another edge waits for the next round. + for f in faces_of_edge.get((int(a), int(b)), []): + if splits.setdefault(f, {"edge": (int(a), int(b)), "cuts": []})["edge"] == (int(a), int(b)): + splits[f]["cuts"].append((t, int(v), target)) + # Holes once the cracks are closed (a crack's sliver is no hole). + cracked = set(ids[bad].tolist()) + fills = [f for f in small_holes(verts, edges, faces, good) + if (water is None or verts[f[0]][:, 2].mean() > water + 0.1) and not cracked.intersection(f[0])] \ + if filling else [] + if filling: + splits = {} + if not splits and not fills: + break + holes = holes and not filling + new_faces: dict[int, list] = {p: [] for p, _ in prims} + dropped = set() + kept = np.nonzero(good)[0] + for f_kept, split in splits.items(): + f = int(kept[f_kept]) + p = int(owner[f]) + a_w, b_w = split["edge"] + cuts = split["cuts"] + # The face's corners in its own winding, the cut edge first: (a, b, c). + ids_f = faces[f_kept].tolist() + k = next(i for i in range(3) if {ids_f[i], ids_f[(i + 1) % 3]} == {a_w, b_w}) + a_c, b_c, c_c = corner[f, k], corner[f, (k + 1) % 3], corner[f, (k + 2) % 3] + start = ids_f[k] + cuts = sorted(cuts, key=lambda q: q[0] if start == a_w else 1 - q[0]) + chain = [a_c] + for t, _v, target in cuts: + s = t if start == a_w else 1 - t + chain.append(add_vertex(attrs[p], a_c, b_c, s, (inverse @ np.append(target, 1.0))[:3])) + chain.append(b_c) + for i in range(len(chain) - 1): + new_faces[p].append((chain[i], chain[i + 1], c_c)) + dropped.add(f) + done["split"] += 1 + for ring, p_face in fills: + f = int(kept[p_face]) + p = int(owner[f]) + # Corners of the ring in this primitive: the ring's welded vertices, each through + # a corner of the primitive that holds it (else a copy of the face's nearest). + local_ids = [] + for v in ring: + hit = [c for c in corners_of[int(v)] if owner[c // 3] == p] + c = hit[0] if hit else corners_of[int(v)][0] + local_ids.append(corner[c // 3, c % 3] if hit else + add_vertex(attrs[p], corner[f, 0], corner[f, 0], 0.0, + (inverse @ np.append(verts[v], 1.0))[:3])) + centre = add_vertex(attrs[p], local_ids[0], local_ids[len(local_ids) // 2], 0.5, + (inverse @ np.append(verts[ring].mean(0), 1.0))[:3]) + for i in range(len(local_ids)): + new_faces[p].append((local_ids[(i + 1) % len(local_ids)], local_ids[i], centre)) + done["filled"] += 1 + # Write the faces back per primitive: the kept ones, then the new ones. + at = 0 + for p, _ in prims: + n = len(index[p]) // 3 + faces_p = index[p][:n * 3].reshape(-1, 3) + keep = np.array([at + i not in dropped for i in range(n)], bool) + extra = np.array(new_faces[p], np.int64).reshape(-1, 3) + index[p] = np.concatenate([faces_p[keep], extra]).reshape(-1) + at += n + done["joined"] += join_close(prims, attrs, index, world, water) + for p, prim in prims: + for k in attrs[p]: + attrs[p][k] = attrs[p][k].astype(np.float64) + changed[(m, p)] = (attrs[p], index[p]) + if any(done.values()): + glb.write(out or path, changed) + return done + + +def join_close(prims, attrs, index, world, water) -> int: + """Open edges' vertices closer than CLOSE to each other become one (at their middle) and the + faces that shrink to a line go: what is left of a crack after the splits is a sliver this + small. Changes ATTRS and INDEX in place; returns how many vertices moved.""" + inverse = np.linalg.inv(world) + owner = np.concatenate([np.full(len(index[p]) // 3, p) for p, _ in prims]) + corner = np.concatenate([index[p][:len(index[p]) // 3 * 3] for p, _ in prims]).reshape(-1, 3) + world_pos = {p: attrs[p]["POSITION"] @ world[:3, :3].T + world[:3, 3] for p, _ in prims} + tris = np.concatenate([world_pos[p][index[p][:len(index[p]) // 3 * 3]] for p, _ in prims]).reshape(-1, 3, 3) + if len(tris) == 0 or np.abs(tris).max() > mc.FAR: + return 0 + verts, edges, _faces, inverse_ids, _good = mc.open_edges(tris, whole=True) + ids = np.unique(edges.reshape(-1)) + if water is not None: + ids = ids[verts[ids][:, 2] > water + 0.1] + if len(ids) < 2: + return 0 + parent = {int(v): int(v) for v in ids} + + def find(i): + while parent[i] != i: + parent[i] = parent[parent[i]] + i = parent[i] + return i + cells: dict = {} + for v in ids: + cells.setdefault(tuple(np.floor(verts[v] / CLOSE).astype(np.int64)), []).append(int(v)) + for key, members in cells.items(): + near = [u for dx in (-1, 0, 1) for dy in (-1, 0, 1) for dz in (-1, 0, 1) + for u in cells.get((key[0] + dx, key[1] + dy, key[2] + dz), ())] + for v in members: + for u in near: + if u != v and np.linalg.norm(verts[u] - verts[v]) < CLOSE: + parent[find(u)] = find(v) + # An open edge's chain that stops (its end on one open edge only) stops at a gap: its end + # joins the nearest other open vertex within GAP. + degree = np.bincount(edges.reshape(-1), minlength=len(verts)) + ends = [int(v) for v in ids if degree[v] == 1] + if ends: + others = ids[np.isin(ids, edges[np.isin(edges, ends).any(1)].reshape(-1), invert=True) | (degree[ids] == 1)] + cell = mc.GAP + table: dict = {} + for u in others: + table.setdefault(tuple(np.floor(verts[u] / cell).astype(np.int64)), []).append(int(u)) + for v in ends: + key = np.floor(verts[v] / cell).astype(np.int64) + near = [u for dx in (-1, 0, 1) for dy in (-1, 0, 1) for dz in (-1, 0, 1) + for u in table.get((key[0] + dx, key[1] + dy, key[2] + dz), ()) if u != v] + if near: + d = np.linalg.norm(verts[near] - verts[v], axis=1) + if d.min() < mc.GAP: + parent[find(near[int(d.argmin())])] = find(v) + groups: dict = {} + for v in parent: + groups.setdefault(find(v), []).append(v) + group_of = np.arange(len(verts)) + moved = 0 + target = {} + for root, members in groups.items(): + if len(members) < 2: + continue + at = verts[members].mean(0) + for v in members: + group_of[v] = root + target[v] = (inverse @ np.append(at, 1.0))[:3] + moved += 1 + if not moved: + return 0 + for c, v in enumerate(inverse_ids): + if int(v) in target: + f, k = divmod(c, 3) + attrs[owner[f]]["POSITION"][corner[f, k]] = target[int(v)] + g = group_of[inverse_ids.reshape(-1, 3)] + flat = (g[:, 0] == g[:, 1]) | (g[:, 1] == g[:, 2]) | (g[:, 0] == g[:, 2]) + at = 0 + for p, _ in prims: + n = len(index[p]) // 3 + index[p] = index[p][:n * 3].reshape(-1, 3)[~flat[at:at + n]].reshape(-1) + at += n + return moved + + +def edge_faces(faces: np.ndarray, good: np.ndarray) -> dict: + """Each open edge's one face (index among the kept faces), by its sorted vertex pair.""" + out: dict = {} + count: dict = {} + for f, (a, b, c) in enumerate(faces): + for x, y in ((a, b), (b, c), (c, a)): + key = (min(x, y), max(x, y)) + out[key] = f + count[key] = count.get(key, 0) + 1 + return {k: v for k, v in out.items() if count[k] == 1} + + +def add_vertex(attrs: dict, a: int, b: int, t: float, position: np.ndarray) -> int: + """A new vertex between A and B (T of the way), at POSITION: its index.""" + for k, values in attrs.items(): + row = position if k == "POSITION" else values[a] + (values[b] - values[a]) * t + if k == "NORMAL": + n = np.linalg.norm(row) + row = row / n if n > 1e-9 else values[a] + attrs[k] = np.vstack([values, row[None]]) + return len(attrs["POSITION"]) - 1 + + +def small_holes(verts, edges, faces, good) -> list[tuple[list[int], int]]: + """Each small hole (map_check.hole_rings) as its vertices in order round it, and the face + beside its first edge.""" + out = [] + face_of = edge_faces(faces, good) + for es in mc.hole_rings(verts, edges, faces): + ring_edges = [tuple(edges[e]) for e in es] + nxt: dict[int, list[int]] = {} + for a, b in ring_edges: + nxt.setdefault(int(a), []).append(int(b)) + nxt.setdefault(int(b), []).append(int(a)) + if any(len(v) != 2 for v in nxt.values()) or len(nxt) < 3: + continue + start = int(ring_edges[0][0]) + ring, prev = [start], None + while True: + options = [x for x in nxt[ring[-1]] if x != prev] + prev, step = ring[-1], options[0] + if step == start: + break + ring.append(step) + if len(ring) > len(nxt): + break + if len(ring) != len(nxt): + continue + # The ring's direction so the fill faces the same way as the face beside it. + a, b = ring[0], ring[1] + f = face_of.get((min(a, b), max(a, b))) + if f is None: + continue + fv = faces[f].tolist() + k = fv.index(a) + if fv[(k + 1) % 3] != b: + ring = ring[::-1] + out.append((ring, f)) + return out diff --git a/openrac/tools/map_check.py b/openrac/tools/map_check.py new file mode 100644 index 00000000..de0ed02d --- /dev/null +++ b/openrac/tools/map_check.py @@ -0,0 +1,929 @@ +"""Checks a level for what a player would see wrong: holes and cracks in the ground, collision that +does not follow what is drawn, things floating, sunk or standing in each other. + +Every check reads the level as the game will draw it (its terrain, its static models, its ties, +shrubs and mobys) and as the hero will meet it (Game/Collision, as the pack writes it). The disc's +own parts are left alone: its terrain pieces (Terrain_NNN), and with EDITED (what a pack found +changed) its own ties, shrubs and mobys. + +- cracks: an edge of the map's own terrain with nothing on its other side. A vertex on the middle + of another edge (a T-junction) or a little off it (a gap) shows as a line of sky through the + ground; a small closed ring of such edges with nothing over it is a hole. +- collision: the walkable top of the map's own terrain (not under a tie or a model), sampled every STEP units near where the + hero can go, against the collision's top there. No collision under it lets the hero fall + through; collision over it makes him stand in the air; collision far under it sinks him. +- things: placement.py's check on the drawn ground only (never on collision nobody sees), and a + tie or shrub floating far over it. +- overlaps: a tie or static model with another one's faces through its middle. + +`openrac_editor.py check-map` runs it; Check, Play, Pack, Add as planet and map export refuse a +level with problems (--keep-problems packs it anyway). `--fix` first mends what can be mended +without a choice: cracks welded and small holes filled (crack_fix.py), collision made from the +drawn ground (collision_fix.py), ties and models moved out of each other, things set down. +numpy only (the launcher's Python has it).""" + +from __future__ import annotations + +import json +import math +import re +import struct +import sys +import zlib +from pathlib import Path + +# The release brings numpy for the launcher's Python in vendor/ (build/package.py). +sys.path.insert(0, str(Path(__file__).resolve().parent / "vendor")) + +import numpy as np # noqa: E402 + +import placement as pl # noqa: E402 + +DISC_PIECE = re.compile(r"Terrain_\d+") +STEP = 1.0 # the collision check's sample spacing, in units +REACH = 16.0 # drawn ground this far from any collision is out of the hero's reach +TOLERANCE = 0.25 # collision may be this far over or under the drawn walkable ground +STAND = 1.0 # ground with a neighbour a STEP away higher or lower than this is too steep to stand on +RIM = 1.0 # collision this far to a side of the drawn ground still holds the hero +WINDOW = 3.0 # collision further than this under the drawn ground is none (a floor below) +WELD = 0.002 # vertices this close are one +T_JUNCTION = 0.01 # a vertex this close to another edge's middle splits it in the picture only +GAP = 0.5 # open edges this close to each other are a crack, not a boundary +HOLE = 64.0 # a closed ring of open edges shorter than this, inside a mesh, is a hole +TILE = 16.0 # problems in one square this wide are one place +MIN_AREA = 4.0 # collision mismatches smaller than this many square units are not reported +CORE = 0.5 # the middle share of a thing's width that nothing else may go through +COVER = 30.0 # a hole with another drawn mesh this far over it is not seen +FLY = 60.0 # a tie or shrub with ground this far under it floats (more: over the sea) +FAR = 1.0e4 # beyond this, a mesh is scenery out of reach (the horizon) + + +# --- the level as it is drawn --- + +class Mesh: + """Triangles (N, 3, 3) of one named node, as the game draws them.""" + + def __init__(self, name: str, tris: np.ndarray, kind: str): + self.name, self.tris, self.kind = name, np.asarray(tris, np.float64).reshape(-1, 3, 3), kind + + +def node_meshes(path: Path, world: np.ndarray | None = None) -> list[tuple[str, np.ndarray]]: + """A glb's triangles per named node (its own name, as the editor shows it).""" + data = Path(path).read_bytes() + length = struct.unpack(" list[Mesh] | None: + """The collision as the pack writes it, per node, in game units; None when it is the disc's + own, untouched.""" + import collision_scene + try: + scene = collision_scene.scene_collision(self.project, self.dir, self.text) + except Exception: # noqa: BLE001 - the pack itself says what is wrong with it + return None + if scene is None: + return None + tris = np.array([q for q, _ in scene["triangles"]], np.float64).reshape(-1, 3, 3) + tris[..., 0:2] /= 64.0 + tris[..., 2] /= 64.0 + # Which node each triangle came from, to name it: nearest owner by box. + return [Mesh("Collision", tris, "collision")] + + +# --- problems --- + +class Problem(dict): + """{check, node, at: [x, y, z], size, text}: one place that is wrong.""" + + def line(self) -> str: + x, y, z = self["at"] + return f"{self['node']}: {self['text']} at ({x:.0f}, {y:.0f}, {z:.0f})" + + +def clusters(P: np.ndarray, tile: float = TILE) -> list[np.ndarray]: + """Indices of P grouped by the TILE-wide square they are in: one problem per place, never a + whole seam across the level as one.""" + if len(P) == 0: + return [] + keys = np.floor(P[:, :2] / tile).astype(np.int64) + _, group = np.unique(keys, axis=0, return_inverse=True) + group = group.reshape(-1) + return [np.nonzero(group == g)[0] for g in range(group.max() + 1)] + + +# --- cracks --- + +def open_edges(tris: np.ndarray, whole: bool = False): + """The mesh welded (vertices within WELD), and its edges used by one face only: + (vertices (V, 3), open edges (E, 2) as vertex indices, faces (F, 3)). WHOLE adds each corner's + vertex (N * 3,) and which faces are kept (not collapsed by the weld).""" + P = tris.reshape(-1, 3) + keys = np.round(P / WELD).astype(np.int64) + V, inverse = np.unique(keys, axis=0, return_inverse=True) + inverse = inverse.reshape(-1) + faces = inverse.reshape(-1, 3) + good = (faces[:, 0] != faces[:, 1]) & (faces[:, 1] != faces[:, 2]) & (faces[:, 0] != faces[:, 2]) + faces = faces[good] + verts = np.zeros((len(V), 3)) + np.add.at(verts, inverse, P) + verts /= np.bincount(inverse, minlength=len(V))[:, None] + edges = np.sort(np.concatenate([faces[:, [0, 1]], faces[:, [1, 2]], faces[:, [2, 0]]]), axis=1) + uniq, count = np.unique(edges, axis=0, return_counts=True) + if whole: + return verts, uniq[count == 1], faces, inverse, good + return verts, uniq[count == 1], faces + + +def segment_buckets(A: np.ndarray, B: np.ndarray, cell: float) -> dict: + lo = np.floor((np.minimum(A, B)[:, :2] - GAP) / cell).astype(np.int64) + hi = np.floor((np.maximum(A, B)[:, :2] + GAP) / cell).astype(np.int64) + out: dict = {} + for e in range(len(A)): + if (hi[e] - lo[e]).max() > 64: + continue # an edge hundreds of units long: the horizon's + for i in range(lo[e, 0], hi[e, 0] + 1): + for j in range(lo[e, 1], hi[e, 1] + 1): + out.setdefault((i, j), []).append(e) + return out + + +def seam_edges(faces: np.ndarray) -> np.ndarray: + """Edges three or more faces share (two pieces meeting a third along one line): an open edge + may end on one of them as on an open edge.""" + edges = np.sort(np.concatenate([faces[:, [0, 1]], faces[:, [1, 2]], faces[:, [2, 0]]]), axis=1) + uniq, count = np.unique(edges, axis=0, return_counts=True) + return uniq[count >= 3] + + +def crack_points(verts: np.ndarray, edges: np.ndarray, where: bool = False, targets: np.ndarray | None = None): + """For each vertex on an open edge: its distance to the nearest other open edge's middle part + (inf: none within GAP). Returns (vertex ids, distances); WHERE adds that edge (its index in + TARGETS: EDGES and any more edges to look for, seam_edges) and how far along it the nearest + point is (0 to 1).""" + ids = np.unique(edges.reshape(-1)) + if targets is None: + targets = edges + edges = targets + A, B = verts[edges[:, 0]], verts[edges[:, 1]] + cell = 2.0 + table = segment_buckets(A, B, cell) + P = verts[ids] + best = np.full(len(ids), np.inf) + edge = np.full(len(ids), -1) + along = np.zeros(len(ids)) + keys = np.floor(P[:, :2] / cell).astype(np.int64) + by_cell: dict = {} + for i, k in enumerate(map(tuple, keys)): + by_cell.setdefault(k, []).append(i) + for k, members in by_cell.items(): + cand = table.get(k) + if not cand: + continue + cand = np.array(cand) + m = np.array(members) + a, b = A[cand], B[cand] + ab = b - a + q = P[m] + t = np.einsum("mcj,cj->mc", q[:, None, :] - a[None], ab) / np.maximum((ab * ab).sum(1), 1e-12)[None] + inner = (t > 0.02) & (t < 0.98) + near = a[None] + ab[None] * np.clip(t, 0, 1)[..., None] + d = np.linalg.norm(q[:, None, :] - near, axis=2) + own = (edges[cand][None, :, 0] == ids[m][:, None]) | (edges[cand][None, :, 1] == ids[m][:, None]) + d = np.where(inner & ~own, d, np.inf) + k = d.argmin(1) + dk = d[np.arange(len(m)), k] + better = dk < best[m] + best[m[better]] = dk[better] + edge[m[better]] = cand[k[better]] + along[m[better]] = t[np.arange(len(m)), k][better] + if where: + return ids, best, edge, along + return ids, best + + +def hole_rings(verts: np.ndarray, edges: np.ndarray, faces: np.ndarray) -> list[np.ndarray]: + """Closed rings of open edges shorter than HOLE that are not their piece's outline.""" + if len(edges) == 0: + return [] + n = len(verts) + parent = np.arange(n) + + def find(i): + root = i + while parent[root] != root: + root = parent[root] + while parent[i] != root: + parent[i], i = root, parent[i] + return root + for a, b in edges: + ra, rb = find(a), find(b) + if ra != rb: + parent[ra] = rb + rings: dict = {} + for e, (a, b) in enumerate(edges): + rings.setdefault(find(a), []).append(e) + # The piece (faces joined by vertices) each ring belongs to; its longest ring is its outline. + piece = np.arange(n) + + def pfind(i): + root = i + while piece[root] != root: + root = piece[root] + while piece[i] != root: + piece[i], i = root, piece[i] + return root + for f in faces: + r0 = pfind(f[0]) + for v in f[1:]: + rv = pfind(v) + if rv != r0: + piece[rv] = r0 + length = np.linalg.norm(verts[edges[:, 0]] - verts[edges[:, 1]], axis=1) + longest: dict = {} + info = [] + for root, es in rings.items(): + es = np.array(es) + total = float(length[es].sum()) + owner = pfind(edges[es[0], 0]) + # A lone edge is no ring, and neither is a line of edges that stops (it runs along a + # seam where pieces of the mesh meet: no sky shows through it). + ends = np.bincount(edges[es].reshape(-1)) + if len(es) >= 3 and (ends[ends > 0] == 2).all(): + info.append((owner, total, es)) + longest[owner] = max(longest.get(owner, 0.0), total) + return [es for owner, total, es in info if total < HOLE and total < longest[owner]] + + +def covered(level: Level, name: str, at: np.ndarray) -> bool: + """Whether another drawn mesh is over AT (within COVER units): a hole there is not seen.""" + if level.cover is None: + meshes = [m for m in level.drawn if np.abs(m.tris).max() < FAR] + level.cover = pl.Ground(np.concatenate([m.tris for m in meshes]), + np.concatenate([np.full(len(m.tris), m.name, object) for m in meshes])) + z, _ = level.cover.floor(at[None, :2], np.array([at[2] + COVER]), np.array([at[2] - 0.05]), name) + return not np.isnan(z[0]) + + +def check_cracks(level: Level, water: float | None) -> list[Problem]: + problems = [] + for mesh in level.drawn: + # The ground only: a model's open edges are its leaves and cards. + if mesh.kind != "terrain" or len(mesh.tris) == 0: + continue + if np.abs(mesh.tris).max() > FAR: + continue + verts, edges, faces = open_edges(mesh.tris) + if len(edges) == 0: + continue + ids, dist = crack_points(verts, edges, targets=np.concatenate([edges, seam_edges(faces)])) + bad = dist < GAP + found = [] + for i, d in zip(ids[bad], dist[bad]): + found.append((verts[i], "T-junction" if d < T_JUNCTION else "gap")) + cracked = set(ids[bad].tolist()) + for es in hole_rings(verts, edges, faces): + vs = np.unique(edges[es].reshape(-1)) + if cracked.intersection(vs.tolist()): + continue + centre = verts[vs].mean(0) + if covered(level, mesh.name, centre): + continue # under a rock or a house: nobody sees it + found.append((centre, "hole")) + if water is not None: + found = [f for f in found if f[0][2] > water + 0.1] + if not found: + continue + P = np.array([f[0] for f in found]) + for group in clusters(P): + kinds = {found[i][1] for i in group} + what = "a hole" if kinds == {"hole"} else "a crack" + problems.append(Problem(check="cracks", node=mesh.name, at=P[group].mean(0).round(1).tolist(), + size=len(group), text=f"{what} in the drawn ground ({len(group)} " + f"{'points' if len(group) > 1 else 'point'}: {', '.join(sorted(kinds))})")) + return problems + + +# --- collision --- + +def check_collision(level: Level, water: float | None) -> list[Problem]: + if not level.made_terrain: + return [] + found = level.collision() + col = found[0].tris if found else np.zeros((0, 3, 3)) + drawn = [m for m in level.drawn if np.abs(m.tris).max() < FAR] if level.drawn else [] + if not drawn: + return [] + # Ties are drawn too: where one is the top, the ground under it is not what the hero meets. + drawn += [m for m in level.things if m.kind == "tie"] + tris = np.concatenate([m.tris for m in drawn]) + owners = np.concatenate([np.full(len(m.tris), m.name, object) for m in drawn]) + seen = pl.Ground(tris, owners) + if len(col) == 0: + return [] + hit = pl.Ground(col) + # Sample only near the collision: the hero walks there; scenery far out is not reached. + lo = col.reshape(-1, 3).min(0)[:2] - REACH + hi = col.reshape(-1, 3).max(0)[:2] + REACH + xs = np.arange(lo[0], hi[0], STEP) + STEP / 2 + ys = np.arange(lo[1], hi[1], STEP) + STEP / 2 + X, Y = np.meshgrid(xs, ys) + P = np.c_[X.ravel(), Y.ravel()] + inside = reach(level, P, X.shape, STEP) + grid = np.full(len(P), np.nan) + grid[inside], _ = seen.floor(P[inside], np.full(inside.sum(), 1e9), np.full(inside.sum(), -1e9)) + # Ground the hero can stand on: its neighbours a STEP away are within STAND of it, so a ledge + # on a cliff or a spire's tip is no ground. + G = grid.reshape(X.shape) + level_enough = np.isfinite(G) + for axis in (0, 1): + for shift in (1, -1): + other = np.roll(G, shift, axis) + with np.errstate(invalid="ignore"): + level_enough &= np.abs(other - G) <= STAND + ok = level_enough.ravel() + if water is not None: + ok &= grid > water + 0.3 + P, zd = P[ok], grid[ok] + # Owners of the drawn floor at each point (for naming), the collision top near it. + # The collision's floor nearest the drawn one, here or up to RIM to a side: the hero is a unit + # wide, so a cliff's edge that far off is not felt. + zc = np.full(len(P), np.nan) + for d in ((0, 0), (0.5, 0), (-0.5, 0), (0, 0.5), (0, -0.5), (RIM, 0), (-RIM, 0), (0, RIM), (0, -RIM)): + z, _ = hit.floor(P + np.array(d), zd + 2.0, zd - WINDOW) + closer = np.isnan(zc) | (np.abs(z - zd) < np.abs(zc - zd)) + zc = np.where(closer & ~np.isnan(z), z, zc) + zany, _ = hit.floor(P, np.full(len(P), 1e9), np.full(len(P), -1e9)) + missing = np.isnan(zc) + above = ~missing & (zc > zd + TOLERANCE) + below = ~missing & (zc < zd - TOLERANCE) + # Higher collision over the drawn ground (an invisible block) counts too. + lifted = ~np.isnan(zany) & (zany > zd + 2.0) + # Only where the ground is the modder's own: the disc's terrain and collision are the game's. + names = owner_names(seen, P, zd) + made = {m.name for m in drawn if m.kind == "terrain"} + mine = np.isin(names.astype(str), list(made)) + P, zd, zc, zany, names = P[mine], zd[mine], zc[mine], zany[mine], names[mine] + missing, above, below, lifted = missing[mine], above[mine], below[mine], lifted[mine] + problems = [] + for mask, text in ((missing, "no collision under the drawn ground: the hero falls through"), + (above | lifted, "collision over the drawn ground: the hero stands in the air"), + (below, "collision under the drawn ground: the hero sinks into it")): + idx = np.nonzero(mask)[0] + if len(idx) == 0: + continue + Q = np.c_[P[idx], zd[idx]] + for group in clusters(Q): + area = len(group) * STEP * STEP + if area < MIN_AREA: + continue + g = idx[group] + off = (zc[g] - zd[g]) if mask is not missing else None + extra = f", {np.nanmedian(np.abs(np.where(lifted[g], zany[g] - zd[g], off))):.1f} units off" \ + if off is not None else "" + name = most_common(names[g]) + problems.append(Problem(check="collision", node=name, at=Q[group].mean(0).round(1).tolist(), + size=area, text=f"{text} ({area:.0f} square units{extra})")) + return problems + + +def reach(level: Level, P: np.ndarray, shape: tuple, step: float) -> np.ndarray: + """Which of the grid points P (SHAPE, STEP apart) the hero can reach: within REACH of the + level's collision, or on the collision made from the drawn ground (collision_fix.py, itself + made that far out: so a second check or fix sees the same place).""" + import collision_fix + nodes = collision_fix.old_collision(level) + made = [t for name, t, _ in nodes if name == collision_fix.NAME] + rest = [t for name, t, _ in nodes if name != collision_fix.NAME] + out = np.zeros(len(P), bool) + if rest: + out |= dilate(coverage(np.concatenate(rest), P, step).reshape(shape), int(REACH / step)).ravel() + if made: + out |= coverage(np.concatenate(made), P, step) + return out + + +def coverage(tris: np.ndarray, P: np.ndarray, step: float = STEP) -> np.ndarray: + """Which points have a collision triangle's box over them (a cheap reach test).""" + lo, hi = tris.min(1)[:, :2], tris.max(1)[:, :2] + cells = set() + for a, b in zip(np.floor(lo / step).astype(int), np.floor(hi / step).astype(int)): + for i in range(a[0], b[0] + 1): + for j in range(a[1], b[1] + 1): + cells.add((i, j)) + keys = np.floor(P / step).astype(int) + return np.array([(int(k[0]), int(k[1])) in cells for k in keys]) + + +def dilate(mask: np.ndarray, r: int) -> np.ndarray: + out = mask.copy() + # Separable square growth: rows then columns, by cumulative sums. + for axis in (0, 1): + c = np.cumsum(np.pad(out.astype(np.int32), [(r + 1, r) if a == axis else (0, 0) for a in (0, 1)]), axis=axis) + n = out.shape[axis] + hi = np.take(c, np.arange(2 * r + 1, 2 * r + 1 + n), axis=axis) + lo = np.take(c, np.arange(0, n), axis=axis) + out = (hi - lo) > 0 + return out + + +def owner_names(ground: pl.Ground, P: np.ndarray, z: np.ndarray) -> np.ndarray: + names = np.full(len(P), "Terrain", object) + keys = np.floor(P / pl.CELL).astype(int) + for i, k in enumerate(map(tuple, keys)): + cand = ground.floor_cells.get(k) + if cand is None: + continue + T = ground.floors[cand] + d = np.abs(T[:, :, 2].mean(1) - z[i]) + np.linalg.norm(T[:, :, :2].mean(1) - P[i], axis=1) + names[i] = ground.floor_owner[cand][d.argmin()] or "Terrain" + return names + + +def most_common(values) -> str: + u, c = np.unique(np.asarray(values, str), return_counts=True) + return str(u[c.argmax()]) + + +# --- things --- + +def check_things(level: Level, water: float | None, fix: bool = False, edited=None, + move: bool = False) -> tuple[list[Problem], str]: + """placement.py on the drawn ground, for the things in EDITED (names; None: every thing). + Returns (problems, the scene text, with them set down when FIX).""" + if edited is not None and not edited: + return [], level.text + names = None if edited is None else [n.replace("[", "[[]") for n in edited] + text, report = pl.place_scene(level.project, level.text, names=names, fix=fix, water=water, move=move, + drawn_only=True) + problems = [] + for r in report: + if r["problem"]: + text_ = r["problem"] + elif not fix: + text_ = f"{r['kind']} not on the ground: it would be {r['done']}" + else: + continue + problems.append(Problem(check="things", node=r["node"], at=r["position"], size=1, text=text_)) + # placement.py leaves a thing far over the ground as it is (it may hang or fly on purpose); a + # tie or shrub of a map does not fly. + told = {p["node"] for p in problems} + ground = None + for m in level.things: + if m.kind not in ("tie", "shrub") or m.name in told or (edited is not None and m.name not in edited): + continue + V = m.tris.reshape(-1, 3) + lo, hi = V.min(0), V.max(0) + if np.linalg.norm((hi - lo)[:2]) > pl.BIG: + continue + foot = V[V[:, 2] <= lo[2] + max(0.15 * (hi[2] - lo[2]), 0.02)] + foot = foot[np.linspace(0, len(foot) - 1, min(len(foot), 32)).astype(int)] + if ground is None: + ground = pl.level_ground(level.project, text, drawn_only=True) + # Ground a little over its foot counts: a rock set into a slope is sunk, not floating. + g, _ = ground.floor(foot[:, :2], foot[:, 2] + 2.0, foot[:, 2] - FLY, m.name) + if water is not None: + g = np.where(g < water - 0.25, np.nan, g) # the sea's floor is not seen + if np.isnan(g).all(): + continue # nothing under it at all: over the sea + lift = float(np.nanmin(foot[:, 2] - g)) + if lift <= pl.LIFT or (water is not None and np.nanmax(g) < water): + continue + at = ((lo + hi) / 2).round(1).tolist() + if fix: + text = move_node(text, m.name, np.array([0.0, 0.0, -lift])) + else: + problems.append(Problem(check="things", node=m.name, at=at, size=1, + text=f"{m.kind} floats {lift:.1f} units over the ground")) + return problems, text + + +def move_node(text: str, name: str, by: np.ndarray) -> str: + """TEXT with node NAME's transform moved BY.""" + head = f'[node name="{name}" ' + at = text.find(head) + if at < 0: + return text + line = text.find("\ntransform = ", at) + nxt = text.find("\n[", at + 1) + if line < 0 or (0 <= nxt < line): + return text + end = text.find("\n", line + 1) + basis, origin = pl.read_matrix(pl.TRANSFORM.match(text[line + 1:end]).group(1)) + return text[:line + 1] + "transform = " + pl.write_matrix(basis, origin + by) + text[end:] + + +def check_overlaps(level: Level, edited=None) -> list[Problem]: + """A tie or static model with another one's faces through its middle, where one of + the two is in EDITED (names; None: any) or a static model (always the modder's own).""" + # Plants grow into each other and out of rocks; what must not is one solid thing inside another. + solid = [m for m in level.things if m.kind == "tie"] + [m for m in level.drawn if m.kind == "static"] + if len(solid) < 2: + return [] + boxes = np.array([[*m.tris.reshape(-1, 3).min(0), *m.tris.reshape(-1, 3).max(0)] for m in solid]) + size = np.linalg.norm(boxes[:, 3:5] - boxes[:, 0:2], axis=1) + keep = size < pl.BIG + cell = 8.0 + table: dict = {} + for i in np.nonzero(keep)[0]: + for a in range(int(boxes[i, 0] // cell), int(boxes[i, 3] // cell) + 1): + for b in range(int(boxes[i, 1] // cell), int(boxes[i, 4] // cell) + 1): + table.setdefault((a, b), []).append(i) + seen = set() + problems = [] + for members in table.values(): + for i in members: + for j in members: + if i >= j or (i, j) in seen: + continue + seen.add((i, j)) + if (boxes[i, 3:] < boxes[j, :3]).any() or (boxes[j, 3:] < boxes[i, :3]).any(): + continue + if edited is not None and not any(solid[k].name in edited or solid[k].kind == "static" + for k in (i, j)): + continue + for a, b in ((i, j), (j, i)): + if through_middle(solid[a], boxes[a], solid[b]): + small, big = (a, b) if size[a] <= size[b] else (b, a) + centre = (boxes[small, :3] + boxes[small, 3:]) / 2 + problems.append(Problem(check="overlaps", node=solid[small].name, + at=centre.round(1).tolist(), size=1, other=solid[big].name, + text=f"stands inside {solid[big].name}")) + break + return problems + + +def through_middle(mesh: Mesh, box: np.ndarray, other: Mesh) -> bool: + lo, hi = box[:3].copy(), box[3:].copy() + h = hi[2] - lo[2] + lo[2] += 0.2 * h # its foot may be in the ground with the other's + centre = (lo + hi) / 2 + half = (hi - lo) / 2 * np.array([CORE, CORE, 0.8]) + T = other.tris + near = ~((T.min(1) > centre + half).any(1) | (T.max(1) < centre - half).any(1)) + if not near.any(): + return False + return bool(pl.tri_box(T[near] - centre, half).any()) + + +# --- the report --- + +def edited_names(report: str) -> set[str]: + """The nodes a pack's changes.txt says were added or changed (" tie Name: moved").""" + out = set() + for line in report.splitlines(): + words = line.strip().split(": ", 1) + if len(words) == 2 and not words[0].startswith(("level ", "not packed")): + name = words[0].split(" ")[-1] + if name and not name.isdigit(): + out.add(name) + return out + + +def edited_from_scenes(pristine: str, text: str) -> set[str]: + """The ties, shrubs and mobys of TEXT that PRISTINE (the level as extracted) does not have + where they are now: added, moved or given another model.""" + before = {(n[0], n[1]): (n[2], np.round(n[3], 4).tobytes(), np.round(n[4], 3).tobytes()) + for n in scene_nodes(pristine) if n[1] in pl.KINDS} + return {n[0] for n in scene_nodes(text) if n[1] in pl.KINDS and before.get((n[0], n[1])) != + (n[2], np.round(n[3], 4).tobytes(), np.round(n[4], 3).tobytes())} + + +def water_of(project: Path) -> float | None: + """The project's map/water setting (project.godot [openrac]): the sea's height, under which + nothing shows; None when it has none.""" + import planet + try: + value = planet.settings(project).get("map/water") + return float(value) if value not in (None, "") else None + except (OSError, ValueError): + return None + + +def level_sections(report: str) -> dict[int, str]: + """A pack's changes.txt cut into its levels ("level NN" and the lines under it).""" + out: dict[int, list[str]] = {} + current = None + for line in report.splitlines(): + if line.startswith("level ") and line[6:8].isdigit(): + current = out.setdefault(int(line[6:8]), []) + elif current is not None and line.startswith(" "): + current.append(line) + return {k: "\n".join(v) for k, v in out.items()} + + +def packed_problems(project: Path, report: str) -> list[str]: + """The problems of each level a pack of PROJECT (one level's project, or its folder of them, + or one project with every level) changed, as ": at (x, y, z)" lines.""" + lines = [] + for number, section in sorted(level_sections(report).items()): + name = f"level_{number:02}" + for root in (project / name, project): + if (root / "levels" / name / f"{name}.tscn").is_file(): + break + else: + continue + found = check_level(root, water_of(root) if (root / "project.godot").is_file() else None, + edited=edited_names(section), level=number) + lines += [p.line() for ps in found["problems"].values() for p in ps] + return lines + + +def separate(level: Level, overlaps: list[Problem], text: str, water: float | None = None) -> tuple[str, int]: + """Each tie in OVERLAPS moved to the nearest spot (up to its own width away) where nothing + goes through its middle and the drawn ground is under it, at that ground's height. Returns + (the scene text, how many moved).""" + # Ties, and static models placed straight under Game/StaticAssets (their own transform is + # where they stand). + direct = {n[0] for n in level.nodes if n[1] == "Game/StaticAssets"} + ties = {m.name: m for m in level.things if m.kind == "tie"} + ties.update({m.name: m for m in level.drawn if m.kind == "static" and m.name in direct}) + solid = [m for m in level.things if m.kind == "tie"] + [m for m in level.drawn if m.kind == "static"] + ground = pl.level_ground(level.project, text, drawn_only=True) + moved = 0 + + def free_spot(mesh): + """The nearest move (up to twice its width, else down into the ground) that frees MESH, + or None.""" + V = mesh.tris.reshape(-1, 3) + lo, hi = V.min(0), V.max(0) + centre = (lo + hi) / 2 + width = float(np.linalg.norm((hi - lo)[:2])) + here, _ = ground.floor(centre[None, :2], np.array([lo[2] + 2.0]), np.array([lo[2] - FLY]), mesh.name) + if np.isnan(here[0]) or (water is not None and here[0] < water - 0.25): + here = np.array([lo[2]]) # over the sea (on a cliff's edge): its own foot + others = [m for m in solid if m is not mesh and + np.linalg.norm(m.tris.reshape(-1, 3).mean(0)[:2] - centre[:2]) < width * 3 + pl.BIG] + for r in np.arange(0.5, max(4.0, 2 * width) + 0.01, 0.5): + for k in range(int(8 + r * 4)): + a = 2 * math.pi * k / int(8 + r * 4) + d = np.array([math.cos(a) * r, math.sin(a) * r, 0.0]) + # The ground there may be higher or lower (a slope), up to half its width. + rise = max(2.0, width / 2) + g, _ = ground.floor((centre + d)[None, :2], np.array([here[0] + rise]), np.array([here[0] - rise]), + mesh.name) + if np.isnan(g[0]) or (water is not None and g[0] < water - 0.25): + continue + d[2] = g[0] - here[0] + box = np.concatenate([lo + d, hi + d]) + shifted = Mesh(mesh.name, mesh.tris + d, mesh.kind) + if not any(through_middle(shifted, box, o) or + through_middle(o, np.concatenate([o.tris.reshape(-1, 3).min(0), + o.tris.reshape(-1, 3).max(0)]), shifted) + for o in others): + return d + # No free spot near (a crowded slope): sunk into the ground, up to most of its height. + for k in np.arange(0.1, 0.71, 0.1): + d = np.array([0.0, 0.0, -k * (hi[2] - lo[2])]) + shifted = Mesh(mesh.name, mesh.tris + d, mesh.kind) + box = np.concatenate([lo + d, hi + d]) + if not any(through_middle(shifted, box, o) or + through_middle(o, np.concatenate([o.tris.reshape(-1, 3).min(0), + o.tris.reshape(-1, 3).max(0)]), shifted) + for o in others): + return d + return None + + for problem in overlaps: + # The one named first, else the one it stands inside. + other = re.search(r"stands inside (\S+)", problem["text"]) + for name in (problem["node"], other.group(1) if other else None): + mesh = ties.get(name) + spot = None if mesh is None else free_spot(mesh) + if spot is None: + continue + text = move_node(text, mesh.name, spot) + mesh.tris = mesh.tris + spot + moved += 1 + break + return text, moved + + +def check_level(project: Path, water: float | None = None, fix: bool = False, edited=None, + level: int | None = None) -> dict: + """Every check on PROJECT (one level's project; LEVEL: that level of a project with every + level). EDITED: the things a pack found changed (edited_names), so the disc's own placements + are not judged; None judges every thing. FIX mends first what can be mended (the level's own + terrain's cracks, ties inside each other, things off the drawn ground) and then checks.""" + number = level + level = Level(project, number) + fixed = [] + if fix: + if level.made_terrain: + import crack_fix + done = crack_fix.mend(level.dir / "terrain.glb", water=water) + if any(done.values()): + fixed.append(f"cracks in the terrain closed ({done['split']} faces split, {done['moved']} " + f"vertices moved onto their edge, {done['filled']} holes filled, {done['joined']} vertices " + f"joined across a sliver)") + level = Level(project, number) + import collision_fix + made = collision_fix.make(level, water) if check_collision(level, water) else None + if made is not None: + level.scene.write_text(made["text"], encoding="utf-8", newline="\n") + gone = ", ".join(made["replaced"]) or "nothing" + fixed.append(f"collision made from the drawn ground ({made['triangles']} triangles, in place of {gone})") + level = Level(project, number) + # Ties out of each other, then things set down; setting down may bring a tie back into + # another, so a few passes. + moved_total, carried_total, set_down = 0, 0, False + for _pass in range(3): + level = Level(project, number) + text, moved = separate(level, check_overlaps(level, edited), level.text, water) + moved_total += moved + original = level.text + for _round in range(6): # crates on crates settle over a few rounds + # A made thing (a crate) that cannot stand where it is goes to the nearest level spot. + _, after = check_things(with_text(level, text), water, True, edited, move=True) + if after == text: + break + text = after + level.text = original + if text == level.text: + break + set_down = set_down or text != original + # The collision made for a tie goes where the tie went (the scene on disk: where it stood). + text, carried = collision_fix.follow(Level(project, number), text) + carried_total += carried + level.scene.write_text(text, encoding="utf-8", newline="\n") + level = Level(project, number) + if not moved: + break + if moved_total: + fixed.append(f"{moved_total} tie(s) or model(s) moved out of another") + if set_down: + fixed.append("things set down on the drawn ground") + if carried_total: + fixed.append(f"{carried_total} collision triangles moved with their ties") + text, trimmed = collision_fix.trim(level) + if trimmed: + level.scene.write_text(text, encoding="utf-8", newline="\n") + fixed.append(f"{trimmed} collision floors over nothing drawn taken out") + level = Level(project, number) + found = {"cracks": check_cracks(level, water), "collision": check_collision(level, water), + "overlaps": check_overlaps(level, edited)} + found["things"], _ = check_things(level, water, False, edited) + return {"problems": found, "fixed": fixed, "level": level} + + +def with_text(level: Level, text: str) -> Level: + """LEVEL as its scene would be with TEXT (for placement, which reads the scene's text).""" + level.text = text + return level + + +def picture(level: Level, problems: dict, path: Path, size: int = 1024) -> None: + """A top view of the level: drawn ground grey, problems as coloured dots (red collision, + orange cracks, yellow things, magenta overlaps).""" + tris = [m.tris for m in level.drawn if len(m.tris) and np.abs(m.tris).max() < FAR] + pts = [np.array(p["at"]) for ps in problems.values() for p in ps] + every = np.concatenate([t.reshape(-1, 3) for t in tris]) if tris else np.array(pts).reshape(-1, 3) + if len(every) == 0: + return + lo, hi = every.min(0)[:2], every.max(0)[:2] + scale = (size - 1) / max(hi - lo).max() if (hi - lo).max() > 0 else 1.0 + img = np.full((size, size, 3), 24, np.uint8) + if tris: + c = np.concatenate([t.mean(1) for t in tris]) + ij = ((c[:, :2] - lo) * scale).astype(int).clip(0, size - 1) + img[size - 1 - ij[:, 1], ij[:, 0]] = (110, 110, 110) + colours = {"collision": (230, 40, 40), "cracks": (255, 150, 0), "things": (240, 220, 0), + "overlaps": (220, 60, 220)} + for check, ps in problems.items(): + for p in ps: + x, y = ((np.array(p["at"][:2]) - lo) * scale).astype(int) + r = 4 if check != "collision" else 3 + int(min(10, math.sqrt(p["size"]) / 2)) + img[max(0, size - 1 - y - r):size - y + r, max(0, x - r):x + r + 1] = colours[check] + write_png(path, img) + + +def write_png(path: Path, img: np.ndarray) -> None: + h, w, _ = img.shape + raw = b"".join(b"\x00" + img[y].tobytes() for y in range(h)) + + def chunk(tag, data): + return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF) + Path(path).write_bytes(b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0)) + + chunk(b"IDAT", zlib.compress(raw, 6)) + chunk(b"IEND", b"")) + + +def main(project: Path, water: float | None = None, fix: bool = False, report: Path | None = None) -> int: + """openrac_editor.py check-map: prints each problem as "openrac-problem: : at + (x, y, z)" (the editor lists them and selects the node), 1 when there is any. WATER defaults + to the project's map/water setting.""" + if water is None: + water = water_of(project) + result = check_level(project, water, fix) + for what in result["fixed"]: + print(f"openrac_editor: fixed: {what}") + total = 0 + for check, ps in result["problems"].items(): + for p in ps: + print(f"openrac-problem: {p.line()}", flush=True) + total += len(ps) + print(f"openrac_editor: {check}: {len(ps)} problem(s)") + if report is not None: + report = Path(report) + report.parent.mkdir(parents=True, exist_ok=True) + picture(result["level"], result["problems"], report.with_suffix(".png")) + report.with_suffix(".json").write_text(json.dumps( + {k: [dict(p) for p in v] for k, v in result["problems"].items()}, indent=1) + "\n", encoding="utf-8", + newline="\n") + print(f"openrac_editor: the map has {total} problem(s)" if total else "openrac_editor: the map is clean") + return 1 if total else 0 diff --git a/openrac/tools/openrac_editor.py b/openrac/tools/openrac_editor.py index ed794456..9772e832 100644 --- a/openrac/tools/openrac_editor.py +++ b/openrac/tools/openrac_editor.py @@ -343,11 +343,14 @@ def check_project(project: Path, wanted: str = "rac1") -> None: raise FormatError(f"{project} holds {game}'s levels, not {wanted}'s", code="game-not-packable") -def pack_projects(disc, survey: dict, project: Path, dest: Path, anywhere: bool = True) -> dict: +def pack_projects(disc, survey: dict, project: Path, dest: Path, anywhere: bool = True, + keep_problems: bool = False) -> dict: """PROJECT's levels packed into DEST, published whole (extract.publish: built beside it, so a refused edit never leaves half a pack or replaces the last good one); FormatError pack-incomplete, naming each edit, when any edit could not be packed (pack.py lists them in - changes.txt). Returns {"levels", "mobys", "report", "dest", "moby_names"}.""" + changes.txt), or when a changed level has a problem map_check.py finds (a hole in the + ground, collision off what is drawn, a thing floating or inside another), unless + KEEP_PROBLEMS. Returns {"levels", "mobys", "report", "dest", "moby_names"}.""" check_project(project) ours_packed(dest, disc.version.key) result, moby_names = {}, {} @@ -360,6 +363,8 @@ def build_pack(directory: Path) -> None: if incomplete: details = "\n".join(f" {line}" for line in incomplete) raise FormatError("Some edits could not be packed:\n" + details, code="pack-incomplete") + if not keep_problems: + map_problems(project, report) result.update(levels=levels, mobys=mobys, report=report) result["dest"] = publish(dest, build_pack, anywhere, replace=True) @@ -367,6 +372,22 @@ def build_pack(directory: Path) -> None: return result +MAP_PROBLEMS = "The map has problems a player would see:" + + +def map_problems(project: Path, report: str) -> None: + """FormatError pack-incomplete listing what map_check.py finds wrong in the levels a pack + changed (each ": at (x, y, z)").""" + try: + import map_check + except ImportError: + print("openrac_editor: the map check needs numpy (the editor's release brings it); not checked") + return + lines = map_check.packed_problems(project, report) + if lines: + raise FormatError(MAP_PROBLEMS + "\n" + "\n".join(f" {line}" for line in lines), code="pack-incomplete") + + def refused_lines(report: str) -> list[str]: """The "not packed: ..." lines of a pack's changes.txt, without that mark.""" return [line.strip()[len("not packed:"):].strip() for line in report.splitlines() @@ -440,17 +461,23 @@ def check_or_play(args) -> int: raise FormatError("Check and Play are for Ratchet & Clank's levels", code="game-not-packable") survey = disc.survey() try: + keep = getattr(args, "keep_problems", False) if args.command == "check": with tempfile.TemporaryDirectory(prefix=".openrac-check-") as temp: - result = pack_projects(disc, survey, projects, Path(temp) / "packed") + result = pack_projects(disc, survey, projects, Path(temp) / "packed", keep_problems=keep) else: - result = pack_projects(disc, survey, projects, args.packed.resolve()) + result = pack_projects(disc, survey, projects, args.packed.resolve(), keep_problems=keep) except FormatError as exc: if getattr(exc, "code", None) != "pack-incomplete": raise for line in str(exc).splitlines()[1:]: print(f"openrac-problem: {line.strip()}", flush=True) - print("Some edits cannot be packed yet: fix them and try again.") + if str(exc).startswith(MAP_PROBLEMS): + # The editor offers its Fix button (check-map --fix) for these. + print("openrac-map-problems", flush=True) + print("The map has problems a player would see: fix them (Fix mends what it can) and try again.") + else: + print("Some edits cannot be packed yet: fix them and try again.") return 1 print(f"openrac-check: {result['levels']} level(s), {result['mobys']} edit(s), nothing refused", flush=True) if args.command == "check": @@ -627,6 +654,8 @@ def main() -> None: packing.add_argument("--states", type=Path, metavar="FILE", help="the port's states program: refresh the packed levels' moby start states " "(moby_states.py); needs --data and --levels") + packing.add_argument("--keep-problems", action="store_true", + help="pack even when a level has problems a player would see (check-map)") packing.add_argument("--data", type=Path, help="the port's game data, for --states") packing.add_argument("--levels", type=Path, help="the port's levels, for --states") adding = commands.add_parser("planet", help="pack one level's project and add it as a new planet (planet.py)") @@ -634,17 +663,32 @@ def main() -> None: adding.add_argument("project", type=Path, help="one level's project (a project per level)") adding.add_argument("overrides", type=Path, help="the launcher's packs folder (/overrides) to add it to") adding.add_argument("--anywhere", action="store_true", help="accepted for the launcher; the planet goes to OVERRIDES") + adding.add_argument("--keep-problems", action="store_true", + help="add it even when the level has problems a player would see (check-map)") for name, about in (("check", "pack every level of a level project's folder into a throwaway folder and " "list each edit that cannot be packed"), ("play", "pack, then start the game on that level with the pack")): sub = commands.add_parser(name, help=about) sub.add_argument("project", type=Path, help="one level's project (a project per level)") + sub.add_argument("--keep-problems", action="store_true", + help="pack even when the map has problems a player would see (check-map)") if name == "play": sub.add_argument("--packed", type=Path, required=True, help="the packed levels folder (written again)") sub.add_argument("--game", type=Path, help="the game program (openrac-rac1-)") sub.add_argument("--data", type=Path, help="the port's game data") sub.add_argument("--levels", type=Path, help="the port's levels") sub.add_argument("--no-start", action="store_true", help="pack only: the game is not started") + mapping = commands.add_parser("check-map", help="list what a player would see wrong in a level: holes and " + "cracks in the ground, collision off what is drawn, things " + "floating or inside each other (map_check.py)") + mapping.add_argument("project", type=Path, help="one level's project (a project per level)") + mapping.add_argument("--fix", action="store_true", + help="mend what can be mended: things set down on the drawn ground, things inside " + "each other moved apart, cracks in the drawn ground welded") + mapping.add_argument("--water", type=float, help="the sea's height: nothing under it shows " + "(default: the project's map/water setting)") + mapping.add_argument("--report", type=Path, metavar="FILE", + help="also write FILE.json (every problem) and FILE.png (a top view with them)") placing = commands.add_parser("place", help="set a level's mobys, ties and shrubs down on its ground: no " "floating, no sinking, none in a wall (placement.py)") placing.add_argument("project", type=Path, help="one level's project (a project per level)") @@ -662,6 +706,13 @@ def main() -> None: except FormatError as exc: errors.say(exc) parser.exit(1, f"openrac_editor: {exc}\n") + if args.command == "check-map": + import map_check + try: + sys.exit(map_check.main(args.project.resolve(), args.water, args.fix, args.report)) + except (OSError, FormatError) as exc: + errors.say(exc) + parser.exit(1, f"openrac_editor: {exc}\n") if args.command == "place": import placement try: @@ -714,7 +765,7 @@ def main() -> None: if not args.anywhere and not any(root in dest.parents for root in (ROOT / "assets", ROOT / "build")): raise FormatError("output must be a directory under this repository's assets/ or build/", code="folder-not-allowed") - result = pack_projects(disc, survey, args.project, dest, args.anywhere) + result = pack_projects(disc, survey, args.project, dest, args.anywhere, args.keep_problems) print(result["report"], end="") print(f"Packed {result['levels']} level(s), {result['mobys']} edit(s): {result['dest']}") program = args.states if args.states is None or args.states.is_file() else args.states.with_suffix(".exe") @@ -730,7 +781,8 @@ def main() -> None: import overrides import planet try: - done = planet.add_planet(disc, survey, args.project.resolve(), args.overrides.resolve()) + done = planet.add_planet(disc, survey, args.project.resolve(), args.overrides.resolve(), + args.keep_problems) except overrides.PackError as exc: raise FormatError(str(exc), code=planet.code_of(exc)) from exc print(done["report"], end="") diff --git a/openrac/tools/placement.py b/openrac/tools/placement.py index 2d87e809..af0d2d74 100644 --- a/openrac/tools/placement.py +++ b/openrac/tools/placement.py @@ -256,9 +256,9 @@ def __init__(self, tris: np.ndarray, owners=None): self.floor_cells = buckets(self.floors) self.wall_cells = buckets(self.walls) - def floor(self, P: np.ndarray, top: np.ndarray, bottom: np.ndarray, exclude: str = ""): + def floor(self, P: np.ndarray, top: np.ndarray, bottom: np.ndarray, exclude: str = "", mobys: bool = True): """For each point P (N, 2): the highest floor between BOTTOM and TOP (N,), its height and - normal (NaN where there is none).""" + normal (NaN where there is none). MOBYS: other mobys' tops count too.""" P = np.asarray(P, np.float64) z = np.full(len(P), np.nan) nrm = np.full((len(P), 3), np.nan) @@ -271,9 +271,12 @@ def floor(self, P: np.ndarray, top: np.ndarray, bottom: np.ndarray, exclude: str if cand is None: continue idx = np.array(idx) - if exclude: + if exclude or not mobys: own = self.floor_owner[cand] - cand = cand[(own != exclude) & (own != "m:" + exclude)] + keep = (own != exclude) & (own != "m:" + exclude) + if not mobys: + keep &= ~np.char.startswith(own.astype(str), "m:") + cand = cand[keep] if len(cand) == 0: continue T = self.floors[cand] @@ -345,10 +348,10 @@ def tri_box(T: np.ndarray, h: np.ndarray) -> np.ndarray: return hit -def level_ground(project: Path, text: str) -> Ground: +def level_ground(project: Path, text: str, drawn_only: bool = False) -> Ground: """The level's ground: its terrain, its static models, its own collision (Game/Collision), its ties (rocks, platforms, buildings) and its still mobys (crates stand on crates), as the scene - places them.""" + places them. DRAWN_ONLY leaves the collision out: nothing may stand on ground nobody sees.""" ids = {} tris, owners = [], [] current = None @@ -373,7 +376,8 @@ def add(entry): current = None name, parent, inst = m.groups() if inst and inst in ids and ((parent == "Game" and name == "Terrain") - or parent in ("Game/StaticAssets", "Game/Collision", "Game/Ties", "Game/Mobys")): + or parent in ("Game/StaticAssets", "Game/Ties", "Game/Mobys") + or (parent == "Game/Collision" and not drawn_only)): current = [ids[inst], None, name, parent in ("Game/Ties", "Game/Mobys")] continue if current is not None and line.startswith("transform = "): @@ -418,7 +422,7 @@ def tris_of(project, entry) -> np.ndarray: # --- setting things down --- def settle(ground: Ground, shape: Shape, basis: np.ndarray, origin: np.ndarray, hard: bool, water=None, name="", - move=True): + move=True, taken=None): """Where a thing goes: (basis, origin, what was done, problem or None). A thing floating on WATER (a height: its underside within a little of it) stays.""" pose = shape.pose(basis) @@ -432,8 +436,13 @@ def look(b, o, core=False, extra=0.0): ps = shape.pose(b) F = (ps.points if core == "points" else ps.core if core else ps.feet) + o g, n = ground.floor(F[:, :2], F[:, 2] + reach + extra, F[:, 2] - LIFT - extra, name) + if water is not None and not hard: + # A plant does not grow on the sea's floor (a crate or lamp may stand in the shallows). + g = np.where(g < water - 0.25, np.nan, g) return F, g, n + if water is not None and (shape.points @ basis.T)[:, 2].max() + origin[2] < water - 1.0: + return basis, origin, None, None # wholly under the water: out of sight F, g, n = look(basis, origin) if np.isnan(g).all(): return basis, origin, None, None # nothing under it: water, sky, flying @@ -443,7 +452,7 @@ def look(b, o, core=False, extra=0.0): if pose.height < LOW * pose.size: return settle_low(shape, basis, origin, lambda b, o: look(b, o, "points", 0.7), pose.height) return settle_soft(ground, shape, basis, origin, lambda b, o: look(b, o, True), pose.height, pose.size) - return settle_hard(ground, shape, basis, origin, look, pose.size, pose.height, name, move) + return settle_hard(ground, shape, basis, origin, look, pose.size, pose.height, name, move, taken) def settle_low(shape, basis, origin, look, height): @@ -513,10 +522,11 @@ def settle_soft(ground, shape, basis, origin, look, height, size): return basis, origin + np.array([0, 0, -lift]), f"lowered {lift:.2f}", None -def settle_hard(ground, shape, basis, origin, look, size, height, name="", move=True): +def settle_hard(ground, shape, basis, origin, look, size, height, name="", move=True, taken=None): """A made thing (a crate, a lamp): no foot may float, and the high side may sink only a little (SINK of its height). Else the nearest spot within SEARCH where it can stand. A thing - being placed now (MOVE) must stand level and have room above it (not inside a block).""" + being placed now (MOVE) must stand level and have room above it (not inside a block), and + away from the things set down before it at the same height (TAKEN: (x, y, z, size) each).""" sink = max((NEW_SINK if move else HARD_SINK) * height, 0.05) def fit(o, extra=0.0): @@ -533,9 +543,13 @@ def fit(o, extra=0.0): return None if move: top = np.full(len(F), g.max() + (1 + HEADROOM) * height) - above, _ = ground.floor(F[:, :2], top, g + 0.05 * height + 0.02, name) + # (A crate stacked on it is no ceiling.) + above, _ = ground.floor(F[:, :2], top, g + 0.05 * height + 0.02, name, mobys=False) if not np.isnan(above).all(): return None # something over it: a ceiling, inside a block + if move and taken and any(math.hypot(o2[0] - x, o2[1] - y) < (size + s) / 2 and abs(o2[2] - z) < height * 0.5 + for x, y, z, s in taken): + return None # another thing set down there (not under it) return None if wall_inside(ground, shape, basis, o2, name, float(g.max()), move) else o2 first = fit(origin) @@ -597,17 +611,19 @@ def scene_path(project: Path) -> Path: def place_scene(project: Path, text: str, names=None, fix=True, hard_classes=(), soft_classes=(), hover=HOVER, - water=None, move=False): + water=None, move=False, drawn_only=False): """Every thing of the scene TEXT (or those whose names match NAMES, fnmatch patterns) set down. MOVE lets a hard thing that cannot stand where it is go to the nearest good spot (for things just placed); without it such a thing is only listed. Returns (new text, - report): report is a list of {node, kind, class, done, problem, position}.""" + report): report is a list of {node, kind, class, done, problem, position}. DRAWN_ONLY: the + ground is only what is drawn (level_ground).""" import fnmatch project = Path(project) - ground = level_ground(project, text) + ground = level_ground(project, text, drawn_only) ids, shapes = {}, {} lines = text.split("\n") report = [] + taken: list = [] i = 0 while i < len(lines): line = lines[i] @@ -647,7 +663,9 @@ def place_scene(project: Path, text: str, names=None, fix=True, hard_classes=(), continue hard = (kind == "moby" or cls in hard_classes) and cls not in soft_classes basis, origin = read_matrix(TRANSFORM.match(lines[j]).group(1)) - b2, o2, done, problem = settle(ground, shape, basis, origin, hard, water, name, move) + b2, o2, done, problem = settle(ground, shape, basis, origin, hard, water, name, move, taken) + if hard: + taken.append((float(o2[0]), float(o2[1]), float(o2[2]), shape.pose(b2).size)) if done or problem: report.append({"node": name, "kind": kind, "class": cls, "done": done, "problem": problem, "position": [round(float(v), 3) for v in o2]}) diff --git a/openrac/tools/planet.py b/openrac/tools/planet.py index 8b554a0c..af1956ce 100644 --- a/openrac/tools/planet.py +++ b/openrac/tools/planet.py @@ -181,9 +181,10 @@ def map_note(project: Path) -> tuple[str, str]: return author or settings(project).get("map/author", "").strip(), about -def add_planet(disc, survey: dict, project: Path, into: Path) -> dict: +def add_planet(disc, survey: dict, project: Path, into: Path, keep_problems: bool = False) -> dict: """Packs PROJECT's level, exports it as a new planet and installs it in the launcher's packs - folder INTO: what was done, for the report.""" + folder INTO: what was done, for the report. A level with problems a player would see + (map_check.py) is refused, unless KEEP_PROBLEMS.""" from map_mod import export_map from pack import pack if not (project / "project.godot").is_file(): @@ -199,6 +200,15 @@ def add_planet(disc, survey: dict, project: Path, into: Path) -> dict: refused = [line.strip() for line in report.splitlines() if line.lstrip().startswith("not packed:")] if refused: raise PlanetError("Some edits could not be packed:\n" + "\n".join(f" {line}" for line in refused), INCOMPLETE) + try: + import map_check + except ImportError: # no numpy: not checked (the release brings it) + keep_problems = True + if not keep_problems: + lines = map_check.packed_problems(project, report) + if lines: + raise PlanetError("The map has problems a player would see:\n" + + "\n".join(f" {line}" for line in lines), INCOMPLETE) out = Path(temp) / "planet" author, about = map_note(project) manifest = export_map(packed, project, out, name, level, destination=True, map_id=ident, diff --git a/openrac/tools/shared_map.py b/openrac/tools/shared_map.py index 4c75f591..7ec6ef2a 100644 --- a/openrac/tools/shared_map.py +++ b/openrac/tools/shared_map.py @@ -509,8 +509,10 @@ def _safe(rel: str) -> str: # ============================================================================= def export(project: Path, out: Path, author: str = "", about: str = "", credits: list[str] | None = None, - disc_path: Path | None = None) -> dict: - """Write PROJECT's map to OUT; what went in, for the report.""" + disc_path: Path | None = None, keep_problems: bool = False) -> dict: + """Write PROJECT's map to OUT; what went in, for the report. A map with problems a player would + see (map_check.py: holes, collision off what is drawn, things floating or inside each other) + is refused, unless KEEP_PROBLEMS.""" import openrac_editor from disc import Disc project = project.resolve() @@ -539,6 +541,8 @@ def export(project: Path, out: Path, author: str = "", about: str = "", credits: "(your edits are carried over)") pristine = project_files(pristine_root) edited = project_files(project) + if not keep_problems: + refuse_problems(project, level, pristine, edited) entries, blobs, report = [], {}, {"scenes": 0, "patches": 0, "game": 0, "own": [], "removed": 0} new = {rel: path for rel, path in edited.items() if rel not in pristine} # Settings Godot writes for files of the level itself are its own, not the creator's. @@ -737,6 +741,26 @@ def needs_runtime(project: Path, level: int) -> bool: return bool(moves) or (level_dir / "cutscenes").is_dir() +def refuse_problems(project: Path, level: int, pristine: dict, edited: dict) -> None: + """MapError listing what map_check.py finds wrong in the map; only the things the map adds or + moves are judged, not the disc's own.""" + try: + import map_check + except ImportError: # no numpy: not checked (the release brings it) + return + rel = f"levels/level_{level:02}/level_{level:02}.tscn" + changed = map_check.edited_from_scenes(pristine[rel].read_text(encoding="utf-8"), + edited[rel].read_text(encoding="utf-8")) \ + if rel in pristine and rel in edited else None + found = map_check.check_level(project, map_check.water_of(project), edited=changed) + lines = [p.line() for ps in found["problems"].values() for p in ps] + if lines: + shown = "\n".join(f" {line}" for line in lines[:200]) + more = f"\n ... and {len(lines) - 200} more" if len(lines) > 200 else "" + raise MapError(f"The map has {len(lines)} problem(s) a player would see (run openrac_editor.py check-map " + f"{project} --fix to mend what it can):\n{shown}{more}") + + def main(argv=None) -> int: parser = argparse.ArgumentParser(prog="openrac_editor.py map", description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) @@ -749,6 +773,8 @@ def main(argv=None) -> int: out.add_argument("--credit", action="append", default=[], help="credit for a model or texture you used (repeat)") out.add_argument("--disc", type=Path, help="the disc (default: the one the levels were read from)") out.add_argument("--anywhere", action="store_true", help="accepted for the launcher") + out.add_argument("--keep-problems", action="store_true", + help="export even when the map has problems a player would see (check-map)") into = commands.add_parser("import", help="make a project of a shared map beside your levels") into.add_argument("map", type=Path, help="the .openrac-map file") into.add_argument("projects", type=Path, help="your levels folder (where level_NN projects are)") @@ -766,7 +792,7 @@ def main(argv=None) -> int: target.mkdir(parents=True, exist_ok=True) name = planet.planet_name(args.project.resolve()) target = target / (planet.planet_id(args.project.resolve(), name) + SUFFIX) - done = export(args.project, target, args.author, args.about, args.credit, args.disc) + done = export(args.project, target, args.author, args.about, args.credit, args.disc, args.keep_problems) print(f"Map {done['name']} (level {done['level']:02}, {done['disc'].upper()} disc): " f"{done['scenes']} scene(s) changed, {done['patches']} file(s) patched, " f"{done['game']} game file(s) named, {len(done['own'])} of your own file(s), " @@ -790,7 +816,9 @@ def main(argv=None) -> int: from disc import Disc with Disc(done["disc"]) as disc: try: - added = planet.add_planet(disc, disc.survey(), done["project"], args.planet.resolve()) + # Its maker's export checked it (check-map); a player adding it is not asked to fix it. + added = planet.add_planet(disc, disc.survey(), done["project"], args.planet.resolve(), + keep_problems=True) except overrides.PackError as exc: raise FormatError(str(exc), code=planet.code_of(exc)) from exc print(f"Added it to your mods as the planet {added['name']}: turn on Mods, board the ship " diff --git a/openrac/tools/test_editor_mcp.py b/openrac/tools/test_editor_mcp.py index b71f266e..9fa4bb22 100644 --- a/openrac/tools/test_editor_mcp.py +++ b/openrac/tools/test_editor_mcp.py @@ -134,7 +134,7 @@ def tearDownClass(cls): def test_1_lists_the_level_tools_resources_and_prompts(self): names = {t["name"] for t in self.tools} for name in ("project_info", "level_check", "planet_set", "planet_add", "class_list", "class_search", - "moby_list", "moby_add", "level_place", "moby_set", "moby_remove", "ground_at", "cutscene_write", + "moby_list", "moby_add", "level_place", "level_check_map", "moby_set", "moby_remove", "ground_at", "cutscene_write", "cutscene_add", "cutscene_check", "cutscene_frame", "job_wait", "batch", "undo"): self.assertIn(name, names) prompts = {p["name"] for p in self.editor.rpc("prompts/list")["result"]["prompts"]} diff --git a/openrac/tools/test_map_check.py b/openrac/tools/test_map_check.py new file mode 100644 index 00000000..6f26b15f --- /dev/null +++ b/openrac/tools/test_map_check.py @@ -0,0 +1,153 @@ +"""map_check, crack_fix and collision_fix on made-up ground: cracks found and closed, collision +laid out from a height field, a pack's report read.""" + +import tempfile +import unittest +from pathlib import Path + +import numpy as np + +import collision_fix +import crack_fix +import map_check as mc +from test_placement import write_glb + + +def grid(x0, y0, size, n, height=lambda x, y: 0.0): + """A square of N x N cells as triangles (two per cell).""" + out = [] + s = size / n + for i in range(n): + for j in range(n): + a = (x0 + j * s, y0 + i * s) + b = (a[0] + s, a[1]) + c = (a[0], a[1] + s) + d = (a[0] + s, a[1] + s) + p = [(*q, height(*q)) for q in (a, b, c, d)] + out += [[p[0], p[1], p[3]], [p[0], p[3], p[2]]] + return np.array(out, np.float64) + + +def cracks(tris): + verts, edges, _faces = mc.open_edges(np.asarray(tris, np.float64)) + _ids, dist = mc.crack_points(verts, edges) + return int((dist < mc.T_JUNCTION).sum()), int(((dist >= mc.T_JUNCTION) & (dist < mc.GAP)).sum()) + + +class Cracks(unittest.TestCase): + def test_t_junction_and_gap_found(self): + coarse = grid(0, 0, 4, 1) + fine = grid(4, 0, 4, 2) # its middle vertex lies on the coarse edge + self.assertEqual(cracks(np.concatenate([coarse, fine]))[0], 1) + apart = grid(4.2, 0, 4, 2) # 0.2 beside the coarse one, a vertex across its middle + self.assertGreater(cracks(np.concatenate([coarse, apart]))[1], 0) + self.assertEqual(cracks(np.concatenate([coarse, grid(4, 0, 4, 1)])), (0, 0)) + + def test_mend_closes_t_junction(self): + with tempfile.TemporaryDirectory() as temp: + path = Path(temp) / "terrain.glb" + write_glb(path, np.concatenate([grid(0, 0, 4, 1), grid(4, 0, 4, 2)])) + done = crack_fix.mend(path) + self.assertGreaterEqual(done["split"], 1) + after = mc.node_meshes(path)[0][1] + self.assertEqual(cracks(after), (0, 0)) + # The ground keeps its shape: the same area, at the same height. + area = np.linalg.norm(np.cross(after[:, 1] - after[:, 0], after[:, 2] - after[:, 0]), axis=1).sum() / 2 + self.assertAlmostEqual(area, 32.0, places=4) + + def test_mend_closes_gap(self): + with tempfile.TemporaryDirectory() as temp: + path = Path(temp) / "terrain.glb" + right = grid(4.1, 0, 4, 2) + write_glb(path, np.concatenate([grid(0, 0, 4, 1), right])) + crack_fix.mend(path) + self.assertEqual(cracks(mc.node_meshes(path)[0][1]), (0, 0)) + + def test_mend_joins_close_vertices(self): + with tempfile.TemporaryDirectory() as temp: + path = Path(temp) / "terrain.glb" + # Two squares 0.03 apart: no vertex across a middle, only corners next to corners. + write_glb(path, np.concatenate([grid(0, 0, 4, 1), grid(4.03, 0, 4, 1)])) + self.assertEqual(crack_fix.mend(path)["joined"], 4) + _verts, edges, _faces = mc.open_edges(mc.node_meshes(path)[0][1]) + self.assertEqual(len(edges), 6) # one outline round both + + def test_t_junction_on_a_seam_mended(self): + # A wall on the coarse edge makes it a seam (three faces): a vertex on it still counts. + wall = np.array([[[4, 0, 0], [4, 4, 0], [4, 2, 3]], [[4, 4, 0], [4, 0, 0], [4, 2, -3]]], np.float64) + + def on_seam(tris): + verts, edges, faces = mc.open_edges(tris) + _ids, dist = mc.crack_points(verts, edges, targets=np.concatenate([edges, mc.seam_edges(faces)])) + return int((dist < mc.T_JUNCTION).sum()) + with tempfile.TemporaryDirectory() as temp: + path = Path(temp) / "terrain.glb" + write_glb(path, np.concatenate([grid(0, 0, 4, 1), wall, grid(4, 0, 4, 2)])) + self.assertGreaterEqual(on_seam(mc.node_meshes(path)[0][1]), 1) + crack_fix.mend(path) + self.assertEqual(on_seam(mc.node_meshes(path)[0][1]), 0) + + def test_hole_found(self): + tris = grid(0, 0, 8, 8) + centre = tris.mean(1) + holed = tris[~((np.abs(centre[:, 0] - 4) < 1) & (np.abs(centre[:, 1] - 4) < 1))] + verts, edges, faces = mc.open_edges(holed) + self.assertEqual(len(mc.hole_rings(verts, edges, faces)), 1) + verts, edges, faces = mc.open_edges(tris) + self.assertEqual(mc.hole_rings(verts, edges, faces), []) + + +class Collision(unittest.TestCase): + def test_flat_ground_takes_few_triangles(self): + Z = np.zeros((65, 65)) + found = collision_fix.squares(Z) + self.assertEqual(len(found), 4) + self.assertEqual(len(collision_fix.triangles(0, 0, Z, found)), 8) + + def test_triangles_follow_the_ground(self): + y, x = np.mgrid[0:65, 0:65].astype(float) + Z = np.sin(x / 7) * 2 + np.where(x > 40, 5.0, 0.0) # rolling ground and a cliff + tris = collision_fix.triangles(0, 0, Z, collision_fix.squares(Z)) + self.assertLess(len(tris), 2 * 64 * 64) + # Every sample is under a triangle within the tolerance (across the surface). + import placement + ground = placement.Ground(tris) + P = np.c_[x.ravel(), y.ravel()][(x.ravel() < 64) & (y.ravel() < 64) & (np.abs(x.ravel() - 40.5) > 1)] + z, _ = ground.floor(P + 0.001, np.full(len(P), 1e9), np.full(len(P), -1e9)) + want = np.sin(P[:, 0] / 7) * 2 + np.where(P[:, 0] > 40, 5.0, 0.0) + self.assertLess(np.nanmax(np.abs(z - want)), collision_fix.TOLERANCE * 1.5 + 0.05) + + def test_holes_in_the_ground_stay_open(self): + Z = np.zeros((33, 33)) + Z[10:20, 10:20] = np.nan + tris = collision_fix.triangles(0, 0, Z, collision_fix.squares(Z)) + centre = tris.mean(1) + self.assertFalse(((centre[:, 0] > 11) & (centre[:, 0] < 18) & (centre[:, 1] > 11) & (centre[:, 1] < 18)).any()) + + +class Reports(unittest.TestCase): + REPORT = ("level 11\n tie OM_Tie_0001: added, after 12\n shrub Shrub_0003: moved\n Crate_7: moved\n" + " 0012: deleted\n not packed: Thing: why\nlevel 02\n Moby_0001: added\n") + + def test_sections_and_names(self): + sections = mc.level_sections(self.REPORT) + self.assertEqual(sorted(sections), [2, 11]) + self.assertEqual(mc.edited_names(sections[11]), {"OM_Tie_0001", "Shrub_0003", "Crate_7"}) + + def test_edited_from_scenes(self): + head = '[ext_resource type="PackedScene" path="res://ties/tie_1.glb" id="t1"]\n\n' + node = '[node name="{}" parent="Game/Ties" instance=ExtResource("t1")]\ntransform = {}\n\n' + same = "Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 2, 3)" + moved = "Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 2, 4)" + before = head + node.format("A", same) + node.format("B", same) + after = head + node.format("A", same) + node.format("B", moved) + node.format("C", same) + self.assertEqual(mc.edited_from_scenes(before, after), {"B", "C"}) + + def test_move_node(self): + text = '[node name="A" parent="Game/Ties"]\ntransform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 2, 3)\n' + out = mc.move_node(text, "A", np.array([0.0, 0.0, -1.0])) + self.assertIn("1, 2, 2)", out) + + +if __name__ == "__main__": + unittest.main()