## Everything solid that players stand on, walk into and see through: a terrain ## heightfield plus axis-aligned box solids (structures, rocks). The island generator ## fills the heightfield; building adds and removes solids. ## ## All queries are pure functions of the stored data, so the server, client prediction ## and the camera all agree. class_name SimGround extends RefCounted ## Ray-marching step for terrain, in metres. Small enough for camera-length rays. const RAY_STEP: float = 0.05 const RAY_REFINE_STEPS: int = 10 ## Side of the squares the solid index buckets by, in metres. const INDEX_CELL: float = 8.0 const _NO_SOLIDS: PackedInt32Array = [] ## What a removed solid's slot holds: an empty box far below anything in the world. const REMOVED: AABB = AABB(Vector3(0.0, -1.0e6, 0.0), Vector3.ZERO) const _MARGIN_OFFSETS: Array[Vector2] = [ Vector2(1.0, 0.0), Vector2(-1.0, 0.0), Vector2(0.0, 1.0), Vector2(0.0, -1.0), Vector2(0.7071, 0.7071), Vector2(0.7071, -0.7071), Vector2(-0.7071, 0.7071), Vector2(-0.7071, -0.7071), ] ## Heights in row-major order: index = z * samples + x, `cell` metres apart, starting ## at the world origin. Outside the grid the nearest edge sample is used. var heights: PackedFloat32Array = PackedFloat32Array() var samples: int = 0 var cell: float = 1.0 ## Every solid, in the order added. Add them with add_solid(), which indexes them. var solids: Array[AABB] = [] ## Solids indexed by the INDEX_CELL squares their footprints overlap, so queries only ## test nearby boxes. Vector2i -> PackedInt32Array of indices into `solids`. var _index: Dictionary = {} ## A flat world at `height`. static func flat(height: float = 0.0) -> SimGround: var ground: SimGround = SimGround.new() ground.samples = 2 ground.cell = Tuning.WORLD_SIZE_METRES ground.heights = PackedFloat32Array([height, height, height, height]) return ground ## A heightfield of `side` x `side` samples spaced `spacing` metres apart. static func from_heights(values: PackedFloat32Array, side: int, spacing: float) -> SimGround: assert(side >= 2 and values.size() == side * side and spacing > 0.0) var ground: SimGround = SimGround.new() ground.heights = values ground.samples = side ground.cell = spacing return ground ## Adds a solid and returns its ID, which stays valid until remove_solid(). func add_solid(box: AABB) -> int: var normalised: AABB = box.abs() var id: int = solids.size() solids.append(normalised) var low: Vector2i = _cell_of(normalised.position.x, normalised.position.z) var high: Vector2i = _cell_of(normalised.end.x, normalised.end.z) for cz: int in range(low.y, high.y + 1): for cx: int in range(low.x, high.x + 1): var key: Vector2i = Vector2i(cx, cz) var bucket: PackedInt32Array = _index.get(key, PackedInt32Array()) bucket.append(id) _index[key] = bucket return id ## Removes a solid so no query sees it again. IDs are never reused: the slot in ## `solids` becomes REMOVED, a box far below the world, so other IDs keep their meaning. ## Returns false if the ID is unknown or already removed. func remove_solid(id: int) -> bool: if id < 0 or id >= solids.size() or solids[id] == REMOVED: return false var box: AABB = solids[id] var low: Vector2i = _cell_of(box.position.x, box.position.z) var high: Vector2i = _cell_of(box.end.x, box.end.z) for cz: int in range(low.y, high.y + 1): for cx: int in range(low.x, high.x + 1): var key: Vector2i = Vector2i(cx, cz) var bucket: PackedInt32Array = _index.get(key, PackedInt32Array()) var at: int = bucket.find(id) if at >= 0: bucket.remove_at(at) if bucket.is_empty(): _index.erase(key) else: _index[key] = bucket solids[id] = REMOVED return true ## Indices of solids whose footprint may overlap the rectangle. May repeat an index when ## the rectangle spans several cells, which every query tolerates. func solids_near(min_x: float, min_z: float, max_x: float, max_z: float) -> PackedInt32Array: if _index.is_empty(): return _NO_SOLIDS var low: Vector2i = _cell_of(min_x, min_z) var high: Vector2i = _cell_of(max_x, max_z) if low == high: return _index.get(low, _NO_SOLIDS) var found: PackedInt32Array = PackedInt32Array() for cz: int in range(low.y, high.y + 1): for cx: int in range(low.x, high.x + 1): found.append_array(_index.get(Vector2i(cx, cz), _NO_SOLIDS)) return found func _cell_of(x: float, z: float) -> Vector2i: return Vector2i(floori(x / INDEX_CELL), floori(z / INDEX_CELL)) ## Terrain height at (x, z), bilinearly interpolated. func terrain_height(x: float, z: float) -> float: var limit: float = float(samples - 1) var gx: float = clampf(x / cell, 0.0, limit) var gz: float = clampf(z / cell, 0.0, limit) var x0: int = mini(floori(gx), samples - 2) var z0: int = mini(floori(gz), samples - 2) var fx: float = gx - x0 var fz: float = gz - z0 var row: int = z0 * samples var h00: float = heights[row + x0] var h10: float = heights[row + x0 + 1] var h01: float = heights[row + samples + x0] var h11: float = heights[row + samples + x0 + 1] return lerpf(lerpf(h00, h10, fx), lerpf(h01, h11, fx), fz) ## Upward terrain normal at (x, z), from central differences. func terrain_normal(x: float, z: float) -> Vector3: var d: float = minf(cell * 0.5, 0.5) var dx: float = terrain_height(x + d, z) - terrain_height(x - d, z) var dz: float = terrain_height(x, z + d) - terrain_height(x, z - d) return Vector3(-dx, 2.0 * d, -dz).normalized() ## True if the terrain at (x, z) is gentle enough to stand on. func walkable_terrain(x: float, z: float) -> bool: return terrain_normal(x, z).y >= cos(deg_to_rad(Tuning.MAX_SLOPE_DEGREES)) ## The highest surface under (x, z) that is no higher than `max_y`: the terrain, or the ## top of a solid. Solid tops are always walkable. func support_height(x: float, z: float, max_y: float) -> float: var best: float = terrain_height(x, z) for id: int in solids_near(x, z, x, z): var box: AABB = solids[id] var top: float = box.end.y if top > best and top <= max_y and _inside_footprint(box, x, z, 0.0): best = top return best ## True when the best support under (x, z) up to `max_y` is the top of a solid. func support_is_solid(x: float, z: float, max_y: float) -> bool: var terrain: float = terrain_height(x, z) for id: int in solids_near(x, z, x, z): var box: AABB = solids[id] var top: float = box.end.y if top > terrain and top <= max_y and _inside_footprint(box, x, z, 0.0): return true return false ## True if a player body at `feet` overlaps a solid. Solids whose top is within ## `step` of the feet don't count, so they can be stepped onto. func body_blocked(feet: Vector3, radius: float, height: float, step: float) -> bool: for id: int in solids_near(feet.x - radius, feet.z - radius, feet.x + radius, feet.z + radius): var box: AABB = solids[id] if box.end.y <= feet.y + step or box.position.y >= feet.y + height: continue if _inside_footprint(box, feet.x, feet.z, radius): return true return false ## Casts from `from` to `to` against terrain and solids. Returns the fraction of the way ## to the first hit, or 1.0 if nothing is hit. A ray starting inside something returns 0. func raycast(from: Vector3, to: Vector3) -> float: var nearest: float = 1.0 for id: int in solids_near(minf(from.x, to.x), minf(from.z, to.z), maxf(from.x, to.x), maxf(from.z, to.z)): nearest = minf(nearest, _ray_box(from, to, solids[id])) return minf(nearest, _ray_terrain(from, to, nearest)) ## True if `point` is inside the terrain or a solid, or within `margin` of one. For the ## terrain, heights are also checked `margin` away on each side, so steep ground counts ## its sideways distance and not just the height under the point. func point_inside(point: Vector3, margin: float = 0.0) -> bool: if point.y < terrain_height(point.x, point.z) + margin: return true if margin > 0.0: for offset: Vector2 in _MARGIN_OFFSETS: var probe: Vector2 = offset * margin if point.y < terrain_height(point.x + probe.x, point.z + probe.y): return true for id: int in solids_near(point.x - margin, point.z - margin, point.x + margin, point.z + margin): if solids[id].grow(margin).has_point(point): return true return false ## Where the segment from `from` to `to` enters `box`, as a fraction of the way, or 1.0 ## for a miss. 0 if `from` is inside the box. func ray_box(from: Vector3, to: Vector3, box: AABB) -> float: return _ray_box(from, to, box) func _inside_footprint(box: AABB, x: float, z: float, radius: float) -> bool: return ( x > box.position.x - radius and x < box.end.x + radius and z > box.position.z - radius and z < box.end.z + radius ) ## Slab test. Returns the entry fraction in [0, 1], or 1.0 for a miss. func _ray_box(from: Vector3, to: Vector3, box: AABB) -> float: var direction: Vector3 = to - from var enter: float = 0.0 var leave: float = 1.0 for axis: int in 3: var start: float = from[axis] var span: float = direction[axis] var low: float = box.position[axis] var high: float = box.end[axis] if absf(span) < 0.000001: if start < low or start > high: return 1.0 continue var t1: float = (low - start) / span var t2: float = (high - start) / span enter = maxf(enter, minf(t1, t2)) leave = minf(leave, maxf(t1, t2)) if enter > leave: return 1.0 return enter ## Marches the ray up to `limit`, then refines the first crossing below the terrain. func _ray_terrain(from: Vector3, to: Vector3, limit: float) -> float: var length: float = from.distance_to(to) if length <= 0.0: return 0.0 if _below_terrain(from) else 1.0 if _below_terrain(from): return 0.0 var step: float = RAY_STEP / length var previous: float = 0.0 var t: float = step while previous < limit: t = minf(t, limit) if _below_terrain(from.lerp(to, t)): var low: float = previous var high: float = t for _index: int in RAY_REFINE_STEPS: var middle: float = (low + high) * 0.5 if _below_terrain(from.lerp(to, middle)): high = middle else: low = middle return low previous = t t += step return 1.0 func _below_terrain(point: Vector3) -> bool: return point.y < terrain_height(point.x, point.z)