From fa98e7313f3464ffa8e337951da0234f0de21300 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20K=C5=82ysz?= Date: Tue, 24 Nov 2026 10:57:02 +0000 Subject: [PATCH 1/2] feat: light sets, light zones and a better light bake The level's light sets (gameplay +0x04) and the hero's light zones (+0x80) are in the scene (Game/LightSets, Game/LightZones) and pack back. bake-light gets one bounce of light (--bounce), a soft sun (--sun-samples, --sun-soft) and each surface's own albedo. --- docs/LEVEL_EDITOR.md | 8 +- openrac/project/rc1/check.gd | 4 +- openrac/tools/carry.py | 6 +- openrac/tools/gamedata.py | 231 +++++++++++++++++++++++++++- openrac/tools/pack.py | 2 +- openrac/tools/terrain_tools.py | 114 +++++++++++--- openrac/tools/test_gamedata.py | 84 ++++++++++ openrac/tools/test_terrain_tools.py | 21 +++ 8 files changed, 438 insertions(+), 32 deletions(-) diff --git a/docs/LEVEL_EDITOR.md b/docs/LEVEL_EDITOR.md index b08d62f9..ac3e86dc 100644 --- a/docs/LEVEL_EDITOR.md +++ b/docs/LEVEL_EDITOR.md @@ -484,7 +484,9 @@ Level_NN Mobys/Vendor_0012 one node per placed moby (crates, enemies, NPCs...), named after its class and its place in the level's table LevelSettings the gameplay data (Gameplay data, below): fog, death height, - MobyGroups, Cameras, ship; groups; cameras; sounds; volumes; paths + LightSets, ship; the mobys' light sets and the hero's light zones; + LightZones, groups; cameras; sounds; volumes; paths + MobyGroups, Cameras, Sounds, Volumes, Paths, GrindPaths ``` @@ -549,6 +551,8 @@ and packed back like the mobys ([gamedata.py](../openrac/tools/gamedata.py); the |---|---|---| | `Game/LevelSettings` | `rc1_background`, `rc1_fog_colour` (r, g, b), `rc1_fog_near`, `rc1_fog_far` and their `_intensity`, `rc1_death_height`, `rc1_ship_path`, `rc1_ship_camera_cuboids` (first, last) | values | | `Game/LevelSettings/Ship` | where the player's ship lands; turn it about Z only | moved | +| `Game/LightSets` | `rc1_set_`: each light set's 16 numbers: colour A (r, g, b, back light), direction A (x, y, z, 0), colour B, direction B; 1 is full light. Mobys name a set in `rc1_light` | values; sets added, up to 12 | +| `Game/LightZones/LightZone_NNNN` | where the hero takes his light from: a box (hidden until you show `LightZones`), `rc1_colour_a` and `rc1_colour_b` (r, g, b, a; 128 is full light), blended from A at the box's -x side to B at its +x side, `rc1_set_a` and `rc1_set_b` the same way, `rc1_on`, `rc1_reach` | moved, turned, scaled, edited, added, removed, up to 32 | | `Game/MobyGroups` | `rc1_group_`: each group's members, by node name | members | | `Game/Cameras/Camera_NNNN` | position and rotation (the game's Euler angles), `rc1_class`, the common camera header and known class-specific pvars | edited in place; cameras may be added by copying a same-class record and pvars, up to 48 | | `Game/Sounds/Sound_NNNN` | the record's matrix, `rc1_class`, `rc1_m_class`, `rc1_range`, pvars (hidden) | edited in place | @@ -556,6 +560,8 @@ and packed back like the mobys ([gamedata.py](../openrac/tools/gamedata.py); the | `Game/Paths/Path_NNNN` | a `Path3D`: the points in its curve, `rc1_w` each point's fourth float | points moved, added or removed; paths added; records cannot be deleted | | `Game/GrindPaths/GrindPath_NNNN` | as paths, with `rc1_bounding_sphere` (x, y, z, r) and `rc1_flag` (1: the rail loops) | the same; pack sets each point's fourth float to the length to the next point, as the game needs | +Light zones: the game takes the first zone, in the order of the nodes, whose circle (`rc1_reach` round the box's middle, across x and y; left out, the circle that holds the box) holds the hero, and lights him from it only if he is inside its box too; else he keeps the light he had. Put small zones before the big ones round them, and give every place the hero can reach a zone. The game applies them to the hero only; other mobys keep their own `rc1_colour` and `rc1_light`. + `rc1_background` is the colour the game clears the frame to before it draws the sky (SetBackgroundColor). It is not a sky tint: it shows only where the sky's shells leave gaps or are see-through. In 15 of the 19 levels the sky's first shell is an opaque dome coloured per vertex (Novalis, Kerwan, Pokitaru and most others), which hides the background completely; there the sky's colour is that dome's, part of the sky model. The background shows in Rilgar and Umbris, and below the horizon in Orxon and Quartu. `rc1_background` and `rc1_fog_colour` take red, green and blue from 0 to 255. The editor's sky panorama is baked over the background when the level is extracted, so an edit shows in the game, not in the editor's sky until the next extraction. On a moby, camera or sound with a pvar block (its class's private diff --git a/openrac/project/rc1/check.gd b/openrac/project/rc1/check.gd index 98129c14..dfc39665 100644 --- a/openrac/project/rc1/check.gd +++ b/openrac/project/rc1/check.gd @@ -20,8 +20,8 @@ extends SceneTree # ============================================================================= ## The nodes under Game that hold the gameplay data (editor/gamedata.py's GROUPS). -const GAMEPLAY: Array[String] = ["LevelSettings", "MobyGroups", "Cameras", "Sounds", "Volumes", "Paths", - "GrindPaths"] +const GAMEPLAY: Array[String] = ["LevelSettings", "LightSets", "LightZones", "MobyGroups", "Cameras", "Sounds", + "Volumes", "Paths", "GrindPaths"] # ============================================================================= # METHODS diff --git a/openrac/tools/carry.py b/openrac/tools/carry.py index 52f864cd..6296c1f6 100644 --- a/openrac/tools/carry.py +++ b/openrac/tools/carry.py @@ -19,8 +19,8 @@ instance of, after the level's mobys. What is not carried, and listed so the player can redo it: edits of cameras, volumes, sounds, -paths, grind paths, moby groups and level settings; ties and shrubs; the level's collision and -the moby classes' collision; imported static models. Matching a moby of the old project to the +paths, grind paths, moby groups, level settings, light sets and light zones; ties and shrubs; the +level's collision and the moby classes' collision; imported static models. Matching a moby of the old project to the fresh one is by its place in the level's table when both tables list the same classes in the same order (true of the two gameplay copies of every PAL level), else by class and spawn number. @@ -50,7 +50,7 @@ # What the report calls each kind of node that is not carried. KINDS = (("Game/Cameras", "cameras"), ("Game/Sounds", "sounds"), ("Game/Volumes", "volumes"), ("Game/Paths", "paths"), ("Game/GrindPaths", "grind paths"), ("Game/LevelSettings", "level settings"), - ("Game/MobyGroups", "moby groups")) + ("Game/MobyGroups", "moby groups"), ("Game/LightSets", "light sets"), ("Game/LightZones", "light zones")) class Block: diff --git a/openrac/tools/gamedata.py b/openrac/tools/gamedata.py index 8d7f5500..b3b5246f 100644 --- a/openrac/tools/gamedata.py +++ b/openrac/tools/gamedata.py @@ -5,6 +5,13 @@ placed object starts with. The sections read and written here (header words of the decompressed gameplay file; docs/engine/formats/LEVEL.md section 8): + +0x04 light sets count, pad[3]; 0x40 records {f32 colour A[4], direction A[4], + colour B[4], direction B[4]}: two directional lights each, the + level's moby light bank (the loader takes 12 at most) + +0x80 light zones count, pad[3]; count {f32 x, y, z, radius squared} circles, then + count 0x80 records {f32 matrix[4][4] (world to the zone's unit box), + u8 colour A[4], colour B[4], s32 set A, set B, flags (1: on), 0x2C + bytes}: where the hero takes his light from (HeroEnvLighting) +0x00 level settings 0x50 bytes: background and fog colours (three s32 each), fog near and far distance and intensity, death height, ship position and rotation about Z (f32), ship path, ship camera cuboids (s32), pad[2] @@ -40,6 +47,9 @@ The scene side (godot.py calls `moby_metadata` and `write_scene`; pack.py calls `pack_level`): Game/LevelSettings metadata: the settings; child Ship, the ship's place + Game/LightSets metadata rc1_set_: each light set's 16 floats + Game/LightZones/LightZone_NNNN gameplay/light_zone.tscn: the zone's unit box through its + transform; its colours, sets, reach and whether it is on Game/MobyGroups metadata rc1_group_: each group's members, by node name Game/Cameras/Camera_NNNN gameplay/camera.tscn: position and rotation; class, pvars Game/Sounds/Sound_NNNN gameplay/sound.tscn: the shape body's matrix; class, range, pvars @@ -73,6 +83,10 @@ SETTINGS, CAMERAS, SOUNDS = 0x00, 0x08, 0x0C PATHS, GRIND_PATHS = 0x70, 0x74 CAMERA_GRID = 0x84 +LIGHT_SETS, LIGHT_ZONES = 0x04, 0x80 +LIGHT_SET_SIZE, ZONE_SIZE = 0x40, 0x80 +LIGHT_SETS_MAX, LIGHT_ZONES_MAX = 12, 32 # the loader's cap; the game's zone tables +ZONE_HEAD = struct.Struct("<16f4B4B3i") # The four shape sections: kind, header word, node group, node prefix, mesh. SHAPES = (("cuboid", 0x60, "Cuboids", "Cuboid"), ("sphere", 0x64, "Spheres", "Sphere"), ("cylinder", 0x68, "Cylinders", "Cylinder"), ("pill", 0x6C, "Pills", "Pill")) @@ -92,10 +106,12 @@ SHAPE_W = (0.0, 0.0, 0.0, struct.unpack(" bytes: *s["pad"]) +# --- light sets and light zones -------------------------------------------------------------------------------- + +def read_light_sets(g: bytes) -> list[list[float]]: + """The level's light sets: colour A, direction A, colour B, direction B (four floats each).""" + return [list(struct.unpack("<16f", r)) for r in table(g, LIGHT_SETS, LIGHT_SET_SIZE)] + + +def read_light_zones(g: bytes) -> list[dict]: + """The light zones: each one's circle (x, y, z, radius squared), the matrix that takes the world + to its unit box (column-major, as the game multiplies), colours, sets, flags and the rest.""" + at = start(g, LIGHT_ZONES) + if at <= 0: + return [] + count, = struct.unpack_from(" len(g): + raise FormatError(f"light zones: {count} zones do not fit") + out = [] + for i in range(count): + circle = struct.unpack_from("<4f", g, at + 0x10 + i * 0x10) + record = bytes(g[at + 0x10 + count * 0x10 + i * ZONE_SIZE:][:ZONE_SIZE]) + v = ZONE_HEAD.unpack_from(record) + out.append({"circle": list(circle), "matrix": list(v[0:16]), "colour_a": list(v[16:20]), + "colour_b": list(v[20:24]), "set_a": v[24], "set_b": v[25], "flags": v[26], + "tail": record[ZONE_HEAD.size:]}) + return out + + +def write_light_zones(g: bytes, zones: list[dict]) -> bytes: + at = start(g, LIGHT_ZONES) + head = bytes(g[at + 4:at + 0x10]) if at > 0 else bytes(12) + out = struct.pack(" list[float]: + """The inverse of a column-major 4 x 4 affine matrix (bottom row 0, 0, 0, 1).""" + cols = [m[0:3], m[4:7], m[8:11]] + rows = inverse3(cols) # rows of the inverse in the same row-vector form + inv = [rows[j][k] for j in range(3) for k in range(3)] + t = [-sum(m[12 + j] * rows[j][k] for j in range(3)) for k in range(3)] + return [*inv[0:3], 0.0, *inv[3:6], 0.0, *inv[6:9], 0.0, *t, 1.0] + + +def zone_box(z: dict) -> list[float]: + """A zone's unit box in the world, column-major (the scene's transform of its node).""" + m = z["matrix"] + return affine_inverse([*m[0:3], 0.0, *m[4:7], 0.0, *m[8:11], 0.0, *m[12:15], 1.0]) + + +def zone_reach(t: tuple) -> float: + """The circle that holds a box's footprint (scene transform T): from its middle to the + farthest corner, across x and y.""" + return max(math.hypot(sx * t[0] + sy * t[1] + sz * t[2], sx * t[3] + sy * t[4] + sz * t[5]) + for sx in (-1, 1) for sy in (-1, 1) for sz in (-1, 1)) + + +def zone_meta(i: int, z: dict) -> dict: + meta = {"index": i, "on": bool(z["flags"] & 1), "colour_a": z["colour_a"], "colour_b": z["colour_b"], + "set_a": z["set_a"], "set_b": z["set_b"], "reach": math.sqrt(max(z["circle"][3], 0.0))} + if z["flags"] & ~1: + meta["flags"] = z["flags"] & ~1 + return meta + + # --- shapes ---------------------------------------------------------------------------------------------------- def shape_matrix(body: bytes) -> list[float]: @@ -621,10 +705,11 @@ def write_class_scene(path: Path, kind: str) -> None: "pill": ("CapsuleMesh", {"radius": 1.0, "height": 4.0}, along_z), "camera": ("BoxMesh", {"size": Raw("Vector3(0.6, 0.6, 1)")}, None), "sound": ("SphereMesh", {"radius": 1.0, "height": 2.0}, None), - "ship": ("BoxMesh", {"size": Raw("Vector3(3, 1.5, 0.8)")}, None)} + "ship": ("BoxMesh", {"size": Raw("Vector3(3, 1.5, 0.8)")}, None), + "light_zone": ("BoxMesh", {"size": Raw("Vector3(2, 2, 2)")}, None)} mesh_type, props, placed = meshes[kind] mesh = scene.subresource(mesh_type, "mesh", material=material, **props) - scene.node(kind.capitalize(), kind="Node3D") + scene.node(kind.title().replace("_", ""), kind="Node3D") scene.node("Shape", ".", "MeshInstance3D", mesh=mesh, **({"transform": placed} if placed else {})) path.parent.mkdir(parents=True, exist_ok=True) path.write_text(scene.text(), encoding="utf-8", newline="\n") @@ -646,7 +731,7 @@ def write_scene(scene, directory: Path, res: str, g: bytes) -> dict: from godot import transform pvars, names = Pvars(g), moby_names(g) scenes = {} - for kind in ("cuboid", "sphere", "cylinder", "pill", "camera", "sound", "ship"): + for kind in ("cuboid", "sphere", "cylinder", "pill", "camera", "sound", "ship", "light_zone"): write_class_scene(directory / "gameplay" / f"{kind}.tscn", kind) scenes[kind] = scene.resource("PackedScene", f"{res}/gameplay/{kind}.tscn", f"gameplay_{kind}") stats = {} @@ -658,6 +743,17 @@ def write_scene(scene, directory: Path, res: str, g: bytes) -> dict: ship = euler_matrix(settings["ship_position"], (0.0, 0.0, settings["ship_yaw"]), 1.0) scene.node("Ship", "Game/LevelSettings", instance=scenes["ship"], transform=transform(ship)) + if start(g, LIGHT_SETS) > 0: + sets = read_light_sets(g) + scene.node("LightSets", "Game", "Node", **raw({f"set_{i}": [float(v) for v in s] for i, s in enumerate(sets)})) + stats["light_sets"] = len(sets) + zones = read_light_zones(g) + scene.node("LightZones", "Game", "Node3D", visible=False) + for i, z in enumerate(zones): + scene.node(f"LightZone_{i:04}", "Game/LightZones", instance=scenes["light_zone"], + transform=transform(zone_box(z)), **raw(zone_meta(i, z))) + stats["light_zones"] = len(zones) + groups = gp.groups(g) if start(g, gp.GROUPS) > 0 else [] scene.node("MobyGroups", "Game", "Node", **raw({f"group_{i}": [names[m] if m < len(names) else str(m) for m in members] for i, members in enumerate(groups) if members})) @@ -1013,11 +1109,136 @@ def pvar_edits(node: dict, meta: dict, base_index: int, target_index: int, layou pack_camera_grid(original, nodes, sections, changes, problems) pack_paths(original, nodes, subresources, sections, changes, problems) pack_settings(original, out, nodes, changes, problems) + pack_light_sets(original, nodes, sections, changes, problems) + pack_light_zones(original, nodes, sections, changes, problems) if sections: return gp.replace(bytes(out), sections), changes, problems return bytes(out), changes, problems +def pack_light_sets(original: bytes, nodes: dict, sections: dict, changes: list[str], problems: list[str]) -> None: + """Game/LightSets: rc1_set_0, rc1_set_1, ... (16 numbers each), the level's light sets in + order; a set edited, added or left out changes the section.""" + node = nodes.get("Game/LightSets") + if node is None: + return + meta, sets = meta_of(node), [] + wrong = [k for k in meta if not re.fullmatch(r"set_\d+", k) or int(k[4:]) >= len(meta)] + if wrong: + problems.append(f"LightSets: rc1_{wrong[0]}: the sets are rc1_set_0, rc1_set_1, ... with none left out; " + "not packed") + return + for i in range(len(meta)): + value = meta[f"set_{i}"] + if (not isinstance(value, list) or len(value) != 16 + or not all(isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v) for v in value)): + problems.append(f"LightSets: rc1_set_{i} needs 16 numbers (colour A, direction A, colour B, direction B); " + "not packed") + return + sets.append([float(v) for v in value]) + if len(sets) > LIGHT_SETS_MAX: + problems.append(f"LightSets: {len(sets)} sets; the game takes {LIGHT_SETS_MAX} at most; not packed") + return + old = read_light_sets(original) + from pack import same + if len(old) == len(sets) and all(same(tuple(a), tuple(b)) for a, b in zip(old, sets)): + return + sections[LIGHT_SETS] = write_table(original, LIGHT_SETS, [struct.pack("<16f", *s) for s in sets]) + changes.append(f"light sets: {len(sets)}") + + +def pack_light_zones(original: bytes, nodes: dict, sections: dict, changes: list[str], problems: list[str]) -> None: + """Game/LightZones: the zones in the order of their nodes (the game takes the first whose circle + holds the hero, then lights him only if he is in its box too); a zone's record is built from its + node's transform and metadata, the bytes it does not name kept from the zone it was made from. + A zone that cannot be packed keeps the level's zones as they are.""" + if "Game/LightZones" not in nodes: + return + old = read_light_zones(original) + zones, failed = [], False + for node in children(nodes, "Game/LightZones"): + meta, name = meta_of(node), node["name"] + index = meta.get("index") + base = old[index] if isinstance(index, int) and 0 <= index < len(old) else None + try: + t = placed(nodes, node) + if not all(math.isfinite(v) for v in t): + raise FormatError("a transform that is not a number") + box = [t[0], t[3], t[6], 0.0, t[1], t[4], t[7], 0.0, t[2], t[5], t[8], 0.0, t[9], t[10], t[11], 1.0] + m = affine_inverse(box) + except FormatError as e: + problems.append(f"{name}: {e}; not packed") + failed = True + continue + z = {"matrix": [*m[0:3], base["matrix"][3] if base else 0.0, *m[4:7], base["matrix"][7] if base else 0.0, + *m[8:11], base["matrix"][11] if base else 0.0, *m[12:15], base["matrix"][15] if base else 1.0], + "colour_a": base["colour_a"] if base else [128, 128, 128, 128], + "colour_b": base["colour_b"] if base else [128, 128, 128, 128], + "set_a": base["set_a"] if base else 0, "set_b": base["set_b"] if base else 0, + "flags": base["flags"] if base else 1, "tail": base["tail"] if base else bytes(ZONE_SIZE - ZONE_HEAD.size)} + ok = True + for key in ("colour_a", "colour_b"): + if key in meta: + v = meta[key] + if not isinstance(v, list) or len(v) not in (3, 4) or not all( + isinstance(c, int) and not isinstance(c, bool) and 0 <= c <= 255 for c in v): + problems.append(f"{name}: rc1_{key} needs red, green, blue (and alpha) from 0 to 255 " + "(128 is full light); not packed") + ok = False + continue + z[key] = list(v) + ([z[key][3]] if len(v) == 3 else []) + for key in ("set_a", "set_b"): + if key in meta: + v = meta[key] + if not isinstance(v, int) or isinstance(v, bool) or not -1 <= v < 16: + problems.append(f"{name}: rc1_{key} needs a light set from 0 to 15 (-1: set 11); not packed") + ok = False + continue + z[key] = v + if "on" in meta: + if not isinstance(meta["on"], bool): + problems.append(f"{name}: rc1_on needs true or false; not packed") + ok = False + else: + z["flags"] = (z["flags"] & ~1) | int(meta["on"]) + if "flags" in meta: + if not isinstance(meta["flags"], int) or isinstance(meta["flags"], bool): + problems.append(f"{name}: rc1_flags needs a whole number; not packed") + ok = False + else: + z["flags"] = (meta["flags"] & ~1) | (z["flags"] & 1) + reach = meta.get("reach") + if reach is None: + reach = zone_reach(t) + if isinstance(reach, bool) or not isinstance(reach, (int, float)) or not math.isfinite(reach) or reach <= 0: + problems.append(f"{name}: rc1_reach needs a distance above 0; not packed") + ok = False + if not ok: + failed = True + continue + r2 = float(reach) ** 2 + if base is not None and abs(math.sqrt(max(base["circle"][3], 0.0)) - float(reach)) < 1e-4 \ + and all(abs(a - b) < 1e-4 for a, b in zip(base["circle"][:2], t[9:11])): + r2 = base["circle"][3] + z["circle"] = [t[9], t[10], t[11], r2] + zones.append(z) + if failed: + return # one zone left out would move the others' places: none is packed + if len(zones) > LIGHT_ZONES_MAX: + problems.append(f"LightZones: {len(zones)} zones; the game holds {LIGHT_ZONES_MAX} at most; not packed") + return + data = write_light_zones(original, zones) + at = start(original, LIGHT_ZONES) + if at > 0: + count, = struct.unpack_from(" None: """The moby groups, in a scene that has Game/MobyGroups (an older one's groups stay as pack.py diff --git a/openrac/tools/pack.py b/openrac/tools/pack.py index f480614e..ae913eac 100644 --- a/openrac/tools/pack.py +++ b/openrac/tools/pack.py @@ -182,7 +182,7 @@ def same_fields(a: dict, b: dict) -> bool: # hides them from the packer, which would then take them for deleted). RECORD_GROUPS = ("Game/Mobys", "Game/Ties", "Game/Shrubs", "Game/Cameras", "Game/Sounds", "Game/Paths", "Game/GrindPaths", "Game/Volumes/Cuboids", "Game/Volumes/Spheres", "Game/Volumes/Cylinders", - "Game/Volumes/Pills") + "Game/Volumes/Pills", "Game/LightZones") def validate_record_folders(nodes: dict, level_id: int) -> None: diff --git a/openrac/tools/terrain_tools.py b/openrac/tools/terrain_tools.py index 246feef9..cc006172 100644 --- a/openrac/tools/terrain_tools.py +++ b/openrac/tools/terrain_tools.py @@ -4,6 +4,7 @@ python3 terrain_tools.py info TERRAIN [--near X Y R] python3 terrain_tools.py bake-light TERRAIN [--sun AZ EL] [--region X0 Y0 X1 Y1] [--ao 24] + [--bounce 1] [--sun-samples 8 --sun-soft 1.5] python3 terrain_tools.py uv TERRAIN --tile 3 [brush] python3 terrain_tools.py paint TERRAIN --texture textures/terrain_0003.png [brush] [filters] python3 terrain_tools.py sculpt TERRAIN --mode raise|lower|smooth|roughen|flatten --strength S [brush] @@ -523,15 +524,21 @@ def h(dx, dy, dz): # ---------------------------------------------------------------- light bake -def splat_depth(points, M, lo, cell, shape): - """Depth map (smallest depth along the view) of POINTS seen through rotation M.""" +def splat_depth(points, M, lo, cell, shape, values=None): + """Depth map (smallest depth along the view) of POINTS seen through rotation M; with VALUES (one + row per point), also the map of the nearest point's values.""" q = points @ M.T ij = np.floor((q[:, :2] - lo) / cell).astype(np.int64) ok = (ij[:, 0] >= 0) & (ij[:, 1] >= 0) & (ij[:, 0] < shape[0]) & (ij[:, 1] < shape[1]) depth = np.full(shape, np.inf) flat = ij[ok, 0] * shape[1] + ij[ok, 1] np.minimum.at(depth.reshape(-1), flat, q[ok, 2]) - return depth + if values is None: + return depth + seen = np.zeros((shape[0] * shape[1], values.shape[1])) + front = q[ok, 2] <= depth.reshape(-1)[flat] + seen[flat[front]] = values[ok][front] + return depth, seen def view_matrix(d): @@ -543,8 +550,9 @@ def view_matrix(d): return np.stack([x, y, d]) -def surface_points(tris, spacing, rng): - """Points spread over triangles (about one per SPACING squared), for depth maps.""" +def surface_points(tris, spacing, rng, with_faces=False): + """Points spread over triangles (about one per SPACING squared), for depth maps; WITH_FACES: + also the triangle each comes from.""" a, b, c = tris[:, 0], tris[:, 1], tris[:, 2] area = np.linalg.norm(np.cross(b - a, c - a), axis=1) / 2 count = np.maximum(1, np.round(area / (spacing * spacing) * 2)).astype(np.int64) @@ -552,12 +560,17 @@ def surface_points(tris, spacing, rng): idx = np.repeat(np.arange(len(tris)), count) r1 = np.sqrt(rng.random(len(idx))); r2 = rng.random(len(idx)) pts = a[idx] * (1 - r1)[:, None] + b[idx] * (r1 * (1 - r2))[:, None] + c[idx] * (r1 * r2)[:, None] - return np.concatenate([pts, a, b, c]) + out = np.concatenate([pts, a, b, c]) + if with_faces: + every = np.arange(len(tris)) + return out, np.concatenate([idx, every, every, every]) + return out -def occluded(points, normals, occ_pts, d, region, cell, bias): +def occluded(points, normals, occ_pts, d, region, cell, bias, values=None): """1 where something in OCC_PTS stands between POINTS and the far end of direction -D - (light coming along D), soft over a 3x3 neighbourhood.""" + (light coming along D), soft over a 3x3 neighbourhood. With VALUES (one row per point of + OCC_PTS): also the values of what stands in the way, averaged over the cells it covers.""" M = view_matrix(d) corners = np.array([[region[0], region[1], region[4]], [region[2], region[1], region[4]], [region[0], region[3], region[4]], [region[2], region[3], region[4]], @@ -568,7 +581,11 @@ def occluded(points, normals, occ_pts, d, region, cell, bias): shape = tuple(np.ceil((hi - lo) / cell).astype(int) + 1) if shape[0] * shape[1] > 30_000_000: raise SystemExit("bake region too big for this cell size: give --region or a larger --cell") - depth = splat_depth(occ_pts, M, lo, cell, shape) + if values is None: + depth = splat_depth(occ_pts, M, lo, cell, shape) + else: + depth, seen = splat_depth(occ_pts, M, lo, cell, shape, values) + gathered = np.zeros((len(points), values.shape[1])) q = (points + normals * bias) @ M.T # Slope-scaled bias: a face the light grazes changes depth fast from cell to cell, and its # neighbour cells would shade it (blotches on roofs and slopes). @@ -582,8 +599,13 @@ def occluded(points, normals, occ_pts, d, region, cell, bias): for dy in (-1, 0, 1): ii = np.clip(i0[:, 0] + dx, 0, shape[0] - 1) jj = np.clip(i0[:, 1] + dy, 0, shape[1] - 1) - shade += depth[ii, jj] < q[:, 2] - slack + hit = depth[ii, jj] < q[:, 2] - slack + shade += hit + if values is not None: + gathered += seen[ii * shape[1] + jj] * hit[:, None] n += 1 + if values is not None: + return shade / n, gathered / np.maximum(shade, 1)[:, None] return shade / n @@ -614,14 +636,21 @@ def bake_light(t, args, others=()): sun_az, sun_el = args.sun sun = np.array([math.cos(math.radians(sun_el)) * math.cos(math.radians(sun_az)), math.cos(math.radians(sun_el)) * math.sin(math.radians(sun_az)), math.sin(math.radians(sun_el))]) - tris = [] + tris, tri_albedo = [], [] verts, norms = [], [] for name, off, p in all_prims(ts): P = p.pos + off tris.append(P[p.faces]) recompute_normals(p) if "NORMAL" not in p.attrs else None verts.append(P); norms.append(p.attrs["NORMAL"]) + # How much light a face sends on (for the bounce): the caller's albedo per vertex, else + # a mid grey times the colour there now. + alb = getattr(p, "albedo", None) + if alb is None: + alb = 0.45 * np.clip(p.attrs["COLOR_0"][:, :3], 0, 2) if "COLOR_0" in p.attrs else np.full((len(P), 3), 0.45) + tri_albedo.append(np.asarray(alb, np.float64)[p.faces].mean(1)) tris = np.concatenate(tris) + tri_albedo = np.clip(np.concatenate(tri_albedo), 0, 0.95) V = np.concatenate(verts); N = np.concatenate(norms) if args.region: x0, y0, x1, y1 = args.region @@ -632,27 +661,68 @@ def bake_light(t, args, others=()): region = [x0, y0, x1, y1, float(V[inside, 2].min()) if inside.any() else 0, float(V[inside, 2].max()) if inside.any() else 1] tc = tris.mean(1) near = (tc[:, 0] > x0 - 60) & (tc[:, 0] < x1 + 60) & (tc[:, 1] > y0 - 60) & (tc[:, 1] < y1 + 60) - occ = surface_points(tris[near], args.cell * 0.7, rng) + bounce = float(getattr(args, "bounce", 0.0) or 0.0) + if bounce > 0: + occ, occ_face = surface_points(tris[near], args.cell * 0.7, rng, with_faces=True) + else: + occ = surface_points(tris[near], args.cell * 0.7, rng) lit_sun = np.clip(N @ sun, 0, 1) + sun_col = np.array(args.sun_colour) + sky_col = np.array(args.sky_colour) + bounce_col = np.array(args.bounce_colour) + # A soft sun: its shadow is the mean of SUN_SAMPLES directions across a disc SUN_SOFT degrees + # wide, so a shadow's edge blurs with its distance from what casts it. + samples = max(1, int(getattr(args, "sun_samples", 1) or 1)) + soft = math.radians(float(getattr(args, "sun_soft", 0.0) or 0.0)) + side = np.cross(sun, [0.0, 0.0, 1.0]); side /= np.linalg.norm(side) + up = np.cross(side, sun) + suns = [] + for k in range(samples): + if samples == 1 or soft <= 0: + suns.append(sun) + break + r = soft * math.sqrt((k + 0.5) / samples) + a = k * math.pi * (3 - math.sqrt(5)) + v = sun + side * math.tan(r) * math.cos(a) + up * math.tan(r) * math.sin(a) + suns.append(v / np.linalg.norm(v)) shadow = np.zeros(len(V)) ao = np.zeros(len(V)) + indirect = np.zeros((len(V), 3)) if inside.any(): - shadow[inside] = occluded(V[inside], N[inside], occ, -sun, region, args.cell, args.bias) + for s_dir in suns: + shadow[inside] += occluded(V[inside], N[inside], occ, -s_dir, region, args.cell, args.bias) / len(suns) + values = None + if bounce > 0: + # One bounce: what each sample of the surfaces sends on (its sun and sky light times its + # albedo), gathered from every sky direction it stands in. + face_n = np.cross(tris[near][:, 1] - tris[near][:, 0], tris[near][:, 2] - tris[near][:, 0]) + face_n /= np.maximum(np.linalg.norm(face_n, axis=1), 1e-9)[:, None] + on = face_n[occ_face] + occ_shadow = occluded(occ, on, occ, -sun, region, args.cell, args.bias) + sent = (sun_col[None] * (np.clip(on @ sun, 0, 1) * (1 - occ_shadow))[:, None] + + sky_col[None] * (0.35 + 0.35 * np.clip(on[:, 2], 0, 1))[:, None]) + values = sent * tri_albedo[near][occ_face] dirs = hemisphere(args.ao) weight = 0 for d in dirs: vis = np.clip(N[inside] @ d, 0, 1) - ao[inside] += occluded(V[inside], N[inside], occ, -d, region, args.cell * 1.5, args.bias * 1.5) * vis + got = occluded(V[inside], N[inside], occ, -d, region, args.cell * 1.5, args.bias * 1.5, values) + if values is not None: + got, seen = got + indirect[inside] += seen * (got * vis)[:, None] + ao[inside] += got * vis weight += vis ao[inside] = ao[inside] / np.maximum(weight, 1e-6) + indirect[inside] = indirect[inside] / np.maximum(weight, 1e-6)[:, None] sky_open = 1 - ao - # Light: sun (warm) where not in shadow, sky (cool) by how open it is, bounce from below. - sun_col = np.array(args.sun_colour) - sky_col = np.array(args.sky_colour) - bounce_col = np.array(args.bounce_colour) + # Light: sun (warm) where not in shadow, sky (cool) by how open it is, and light bounced off + # what stands round (gathered, with BOUNCE; else a warm guess from below). light = (sun_col[None] * (lit_sun * (1 - shadow))[:, None] - + sky_col[None] * (sky_open * (0.55 + 0.45 * np.clip(N[:, 2], 0, 1)))[:, None] - + bounce_col[None] * (np.clip(-N[:, 2], 0, 1) * 0.5 + 0.15)[:, None] * sky_open[:, None]) + + sky_col[None] * (sky_open * (0.55 + 0.45 * np.clip(N[:, 2], 0, 1)))[:, None]) + if bounce > 0: + light = light + bounce * indirect + else: + light = light + bounce_col[None] * (np.clip(-N[:, 2], 0, 1) * 0.5 + 0.15)[:, None] * sky_open[:, None] light = light + getattr(args, "ambient", 0.0) # a floor, so no wall goes black lights = getattr(args, "lights", None) or [] if lights: @@ -1201,6 +1271,10 @@ def main(argv=None): s.add_argument("--sun-colour", type=float, nargs=3, default=[1.15, 1.02, 0.78]) s.add_argument("--sky-colour", type=float, nargs=3, default=[0.42, 0.5, 0.62]) s.add_argument("--bounce-colour", type=float, nargs=3, default=[0.22, 0.2, 0.12]) + s.add_argument("--bounce", type=float, default=0.0, + help="light bounced once off the surfaces round, times this (0: a warm guess from below)") + s.add_argument("--sun-samples", type=int, default=1, help="sun directions for soft shadows") + s.add_argument("--sun-soft", type=float, default=0.0, help="the sun's width in degrees (soft shadow edges)") s.add_argument("--keep-tint", action="store_true", help="multiply by the colours there now instead of replacing them") s.add_argument("--models", nargs="*", default=[], help="model glbs baked with the terrain (each shades the others)") s.add_argument("--model-tint", type=float, default=0.0, help="with --models: their light times this (0: as the terrain)") diff --git a/openrac/tools/test_gamedata.py b/openrac/tools/test_gamedata.py index 3ee52e52..4e6a11d1 100644 --- a/openrac/tools/test_gamedata.py +++ b/openrac/tools/test_gamedata.py @@ -17,6 +17,13 @@ from pack import pack_level from sky import clear_colour +# A light set: a warm sun from above (its back clamp -0.17) and a cool fill from the side. +SUN = [1.0, 0.9, 0.6, -0.17, 0.0, 0.0, -1.0, 0.0, 0.2, 0.25, 0.3, 0.0, 1.0, 0.0, 0.0, 0.0] +# A light zone: a box 8 by 4 by 6 round (10, 20, 30), its colours blending from A to B along x. +ZONE = {"circle": [10.0, 20.0, 30.0, 25.0], "matrix": [0.25, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 1 / 3, 0.0, + -2.5, -10.0, -10.0, 1.0], + "colour_a": [32, 32, 40, 128], "colour_b": [96, 90, 80, 128], "set_a": 1, "set_b": 0, "flags": 1, + "tail": bytes(range(0x2C))} LAYOUT = {500: [("speed", 0x10, "f32", 0), ("count", 0x14, "s16", 0), ("ids", 0x18, "u8", 4)]} @@ -79,6 +86,8 @@ def build(groups=([0, 1], None, [2])) -> bytes: camera_cells[1 * gd.CAMERA_GRID_SIZE + 1].append( struct.pack("<4f4if3i", 10.0, 20.0, 0.0, 5.0, 3, 0, 2, 7, 1.5, -1, 0, 0)) sections[gd.CAMERA_GRID] = gd.write_camera_collision_grid(camera_cells) + sections[gd.LIGHT_SETS] = struct.pack("