M1c: weather, snap building, shelter, beds and regrowth

- Seeded weather (clear/cloudy/rain/storm, snow and blizzards on cold days
  and above the snowline), lightning, synthesised rain/wind/thunder sound
- Rain/snow particles stopped by roofs; wet ground, settled snow and wind
  via global shader uniforms
- Snap-together wood floor, wall, door, roof and gable with structural
  support, collapse and X to dismantle
- Shelter detection: dry under a roof, warmer and Rested inside with a fire;
  rain burns an uncovered campfire faster
- Bed sets the spawn point and lets you sleep through the night
- Trees, boulders and ground pickups regrow; timers saved
- Grass cleared under floors; shorter HUD hint
- New test_weather_building suite (62 checks) and tests/run_all.sh, which
  also fails on script errors
This commit is contained in:
Paul Bailey
2026-11-04 10:16:41 +00:00
parent fc7eb3cfed
commit fed96ef118
36 changed files with 2421 additions and 58 deletions

View File

@@ -21,7 +21,11 @@ const PIECES := {
"workbench": preload("res://scripts/building/workbench.gd"),
"chest": preload("res://scripts/building/chest.gd"),
"grave": preload("res://scripts/building/grave.gd"),
"build": preload("res://scripts/building/build_piece.gd"),
"door": preload("res://scripts/building/door.gd"),
"bed": preload("res://scripts/building/bed.gd"),
}
const BuildPiece = preload("res://scripts/building/build_piece.gd")
const AUTOSAVE_SECONDS := 120.0
@@ -38,6 +42,12 @@ var _autosave_left := AUTOSAVE_SECONDS
var _menu_cam: Camera3D
var _menu_t := 0.0
var day_night: Node ## day_night.gd: time of day, sun, sky
var weather: Node ## weather.gd: the weather model
var weather_fx: Node3D ## weather_fx.gd: rain/snow particles, sound
var build: Node ## build_system.gd: snapping, support, shelter
var has_bed_spawn := false
var bed_spawn := Vector3.ZERO ## position of the bed you respawn at
var _loading := false ## applying a save: defer support recompute
func _ready() -> void:
_pieces = Node3D.new()
@@ -47,6 +57,22 @@ func _ready() -> void:
day_night.name = "DayNight"
add_child(day_night)
day_night.setup(sun, $WorldEnvironment.environment)
weather = preload("res://scripts/world/weather.gd").new()
weather.name = "Weather"
add_child(weather)
weather.snowline = terrain.snow_height - 8.0
weather.frozen = menu_mode
weather.setup(terrain.noise_seed, day_night)
day_night.weather = weather
build = preload("res://scripts/building/build_system.gd").new()
build.name = "Build"
add_child(build)
build.setup(self)
if not menu_mode and DisplayServer.get_name() != "headless":
weather_fx = preload("res://scripts/world/weather_fx.gd").new()
weather_fx.name = "WeatherFX"
add_child(weather_fx)
weather_fx.setup(weather, player)
if menu_mode:
day_night.time = 9.5 / 24.0
day_night.frozen = true
@@ -75,10 +101,17 @@ func _ready() -> void:
# --- survival environment ---------------------------------------------------
## 0..100 air warmth at `pos` before fires: time of day, minus altitude.
func air_warmth(pos: Vector3) -> float:
## 0..100 air warmth at `pos` before fires: time of day, minus altitude,
## plus the weather. A proper shelter keeps out most of the weather and adds a
## little warmth of its own.
func air_warmth(pos: Vector3, sheltered: bool = false) -> float:
var w: float = day_night.air_warmth()
w -= maxf(pos.y - 12.0, 0.0) * 0.9
var ww: float = weather.warmth_at(pos)
if sheltered:
w += ww * 0.25 + 8.0
else:
w += ww
return w
## 0..1 heat from fires and a held torch.
@@ -108,10 +141,71 @@ func _on_player_died() -> void:
player.inventory.load_data(Inventory.new(player.inventory.size()).to_data())
if hud != null:
hud.close_screens()
_respawn()
var bed := spawn_bed()
if bed != null:
_respawn_at_bed(bed)
else:
_respawn()
if has_bed_spawn:
has_bed_spawn = false
Actions.notify.emit("Your bed is gone, so you woke at the island start")
player.survival.reset_after_death()
Actions.notify.emit("You died. Your belongings are in your grave." if has_items else "You died.")
# --- beds and sleeping ------------------------------------------------------
## The bed you respawn at, if it still exists.
func spawn_bed() -> Node3D:
if not has_bed_spawn:
return null
for p in _pieces.get_children():
if p.item_id == "bed" and not p.is_queued_for_deletion() and p.global_position.distance_to(bed_spawn) < 0.3:
return p
return null
func set_bed_spawn(bed: Node3D) -> void:
has_bed_spawn = true
bed_spawn = bed.global_position
func _respawn_at_bed(bed: Node3D) -> void:
player.global_position = bed.global_position + Vector3(0, 0.9, 0)
player.velocity = Vector3.ZERO
player.rotation = Vector3(0.0, bed.global_basis.get_euler().y + PI, 0.0)
player.get_node("Camera3D").rotation.x = 0.0
## Why you can't sleep in `bed` right now ("" = you can).
func sleep_block_reason(bed: Node3D) -> String:
var h: float = day_night.hours()
if h > 5.5 and h < 19.5:
return "You can only sleep at night (after 19:30)"
if not build.sheltered_at(bed.global_position):
return "Your bed needs a roof and walls around it"
return ""
## Sleeps until 06:00: the clock, fires, regrowth and weather all move on.
func sleep(p: Node3D) -> void:
var secs: float = fposmod(6.0 - day_night.hours(), 24.0) / 24.0 * day_night.day_length
if hud != null:
hud.fade(func(): _finish_sleep(p, secs))
else:
_finish_sleep(p, secs)
func _finish_sleep(p: Node3D, secs: float) -> void:
skip_time(secs)
p.survival.after_sleep(secs)
save_now()
Actions.notify.emit("You slept until morning")
## Fast-forwards the world (not the player) by `secs`.
func skip_time(secs: float) -> void:
day_night.advance(secs)
day_night.apply(true)
weather.snap()
props.skip_time(secs)
for f in get_tree().get_nodes_in_group("heat"):
if f.has_method("burn"):
f.burn(secs)
func _on_terrain_ready() -> void:
var t0 := Time.get_ticks_msec()
_spawn = terrain.find_spawn(Vector2.ZERO)
@@ -217,7 +311,9 @@ func collect_save() -> Dictionary:
"stats": player.survival.to_data(),
},
"time": {"day": day_night.day, "time": day_night.time},
"spawn": {"bed": has_bed_spawn, "pos": [bed_spawn.x, bed_spawn.y, bed_spawn.z]},
"forage_regrow": regrow,
"regrow": props.regrow.duplicate(),
"harvested": harvested,
"pickups_taken": taken,
"pieces": pieces,
@@ -250,6 +346,14 @@ func apply_save(s: Dictionary) -> void:
for uid in s.get("pickups_taken", []):
if props.pickups.has(uid) and is_instance_valid(props.pickups[uid]):
props.pickups[uid].collected()
# Regrowth timers (older saves have none: everything gone starts a fresh timer).
props.restore_regrow(s.get("regrow", {}))
var sp: Dictionary = s.get("spawn", {})
has_bed_spawn = bool(sp.get("bed", false))
if sp.has("pos"):
bed_spawn = Vector3(sp.pos[0], sp.pos[1], sp.pos[2])
weather.snap()
_loading = true
for e in s.get("pieces", []):
var def: Dictionary = ItemDB.get_item(e.get("item", ""))
if def.is_empty() or not def.has("place"):
@@ -259,6 +363,9 @@ func apply_save(s: Dictionary) -> void:
piece.inventory.load_data(e.inventory)
if e.has("extra") and piece.has_method("load_extra"):
piece.load_extra(e.extra)
_loading = false
build.recompute() # same terrain, same pieces: nothing collapses on load
_update_grass_cuts()
func _respawn() -> void:
player.global_position = _spawn + Vector3(0.0, 1.5, 0.0)
@@ -277,8 +384,11 @@ func _physics_process(_delta: float) -> void:
# --- building ---------------------------------------------------------------
## Whether a piece can go at `xf`: inside the valley, on dry fairly flat
## ground, and not overlapping trees, rocks or other pieces.
## ground (or a floor), and not overlapping trees, rocks or other pieces.
## Building pieces have their own rules (build_system.gd).
func placement_valid(def: Dictionary, xf: Transform3D) -> bool:
if BuildPiece.is_build(def):
return build.check(def, xf).is_empty()
var p := xf.origin
if not terrain.inside_boundary(p.x, p.z, 1.5):
return false
@@ -287,10 +397,12 @@ func placement_valid(def: Dictionary, xf: Transform3D) -> bool:
var fp: Array = def.place.get("footprint", [1.0, 1.0])
var hx := float(fp[0]) * 0.5
var hz := float(fp[1]) * 0.5
# Ground under the corners must be within reach of the base.
# Something solid (ground or a floor) under each corner, close to the base.
var space := get_world_3d().direct_space_state
for c in [Vector3(-hx, 0, -hz), Vector3(hx, 0, -hz), Vector3(-hx, 0, hz), Vector3(hx, 0, hz)]:
var w: Vector3 = xf * c
if absf(terrain.sample_height(w.x, w.z) - p.y) > 0.45:
var rq := PhysicsRayQueryParameters3D.create(w + Vector3(0, 0.45, 0), w - Vector3(0, 0.45, 0), 1, [player.get_rid()])
if space.intersect_ray(rq).is_empty():
return false
# Overlap test against everything solid except the ground itself.
var box := BoxShape3D.new()
@@ -308,8 +420,75 @@ func spawn_piece(def: Dictionary, xf: Transform3D) -> Node3D:
piece.setup(def)
_pieces.add_child(piece)
piece.global_transform = xf
if piece.is_in_group("build") and not _loading:
build.recompute()
if piece.kind == "floor":
_update_grass_cuts()
return piece
## Grass doesn't grow up through floors.
func _update_grass_cuts() -> void:
var xfs: Array = []
for p in _pieces.get_children():
if p.is_in_group("build") and p.kind == "floor" and not p.is_queued_for_deletion():
xfs.append(p.global_transform)
props.set_grass_cuts(xfs, 1.02)
## Takes a piece out of the world (dismantled). Anything that loses its
## support collapses, and its item goes back to `refund_to` if there's room.
## Returns how many pieces collapsed.
func remove_piece(piece: Node3D, refund_to: Node3D = null) -> int:
if piece.item_id == "bed" and spawn_bed() == piece:
has_bed_spawn = false
Actions.notify.emit("Spawn point cleared")
var was_build := piece.is_in_group("build")
_pieces.remove_child(piece)
piece.queue_free()
if not was_build:
return 0
var weak: Array = build.recompute()
for w in weak:
if refund_to != null:
Actions._give(refund_to, w.item_id, 1)
_collapse_fx(w)
_pieces.remove_child(w)
w.queue_free()
if not weak.is_empty():
build.recompute()
Actions.notify.emit("%d piece%s collapsed" % [weak.size(), "" if weak.size() == 1 else "s"])
_settle_loose_pieces()
_update_grass_cuts()
return weak.size()
## A collapsing piece: a copy of its mesh tumbles down and sinks away.
func _collapse_fx(piece: Node3D) -> void:
if DisplayServer.get_name() == "headless":
return
var mi := MeshInstance3D.new()
mi.mesh = piece.get_node("Mesh").mesh
mi.material_override = ItemDB.item_material()
add_child(mi)
mi.global_transform = piece.global_transform
var tw := mi.create_tween().set_parallel(true)
tw.tween_property(mi, "global_position:y", mi.global_position.y - 4.0, 1.2).set_trans(Tween.TRANS_QUAD).set_ease(Tween.EASE_IN)
tw.tween_property(mi, "rotation:x", mi.rotation.x + randf_range(-0.8, 0.8), 1.2)
tw.chain().tween_callback(mi.queue_free)
## Chests, fires and beds left hanging after a collapse drop to whatever is
## below them.
func _settle_loose_pieces() -> void:
var space := get_world_3d().direct_space_state
for p in _pieces.get_children():
if p.is_in_group("build") or p.is_queued_for_deletion():
continue
var at: Vector3 = p.global_position
var rq := PhysicsRayQueryParameters3D.create(at + Vector3(0, 0.3, 0), at - Vector3(0, 0.5, 0), 1, [p.get_rid()])
if not space.intersect_ray(rq).is_empty():
continue
rq = PhysicsRayQueryParameters3D.create(at, at - Vector3(0, 80, 0), 1, [p.get_rid(), player.get_rid()])
var hit := space.intersect_ray(rq)
p.global_position.y = hit.position.y if not hit.is_empty() else terrain.sample_height(at.x, at.z)
# --- dev screenshot hook ----------------------------------------------------
func _maybe_capture() -> void:
@@ -415,3 +594,65 @@ func _capture_survival(prefix: String, cam: Camera3D) -> void:
get_viewport().get_texture().get_image().save_png("%s_menu.png" % prefix)
print("[world] saved %s_menu.png" % prefix)
hud._menu.close()
await _capture_weather(prefix, cam)
## Weather views: a snapped-together hut in clear weather, rain, a storm and
## snow, and the view out of its open door in the rain.
func _capture_weather(prefix: String, cam: Camera3D) -> void:
_respawn()
player.set_physics_process(false)
var yaw: float = player.rotation.y
var hb := Basis(Vector3.UP, yaw)
var site: Vector3 = build.debug_find_site(player.global_position - player.global_basis.z * 11.0, 3.0)
var hut: Dictionary = await build.debug_build_hut(site, yaw)
print("[world] demo hut: %d pieces, failed %s" % [hut.placed, hut.failed])
var top: float = hut.pieces[0].global_position.y
spawn_piece(ItemDB.get_item("bed"), Transform3D(hb, site + hb * Vector3(1.0, top - site.y, -0.6)))
var fire_at: Vector3 = site + hb * Vector3(-0.6, 0, 4.5)
fire_at.y = terrain.sample_height(fire_at.x, fire_at.z)
var fire: Node = spawn_piece(ItemDB.get_item("campfire"), Transform3D(hb, fire_at))
fire.fuel = fire.MAX_FUEL
var door: Node = null
for p in hut.pieces:
if p.item_id == "wood_door":
door = p
player.select(4) # wood: nothing lit in hand
var outside_eye: Vector3 = site + hb * Vector3(4.2, 0, 8.5)
outside_eye.y = terrain.sample_height(outside_eye.x, outside_eye.z) + 1.7
var look: Vector3 = site + Vector3(0, 1.4, 0)
day_night.time = 10.5 / 24.0
for shot in [["hut_clear", "clear", 10.5], ["hut_rain", "rain", 10.5], ["hut_storm", "storm", 16.0], ["hut_snow", "snow", 11.0]]:
weather.force(shot[1])
if shot[1] == "snow":
weather.snow_cover = 1.0
weather.ground_wet = 0.0
day_night.time = float(shot[2]) / 24.0
day_night.apply(true)
_aim_camera(cam, outside_eye, look)
await get_tree().create_timer(2.0).timeout
if shot[1] == "storm":
weather.flash = 0.8
day_night.apply(true)
await RenderingServer.frame_post_draw
get_viewport().get_texture().get_image().save_png("%s_%s.png" % [prefix, shot[0]])
print("[world] saved %s_%s.png" % [prefix, shot[0]])
# From inside, out through the open door, in the rain.
weather.force("rain")
weather.snow_cover = 0.0
day_night.time = 17.5 / 24.0
day_night.apply(true)
door.set_open(true, false)
var in_eye: Vector3 = site + hb * Vector3(0.6, top - site.y + 1.6, -1.2)
_aim_camera(cam, in_eye, site + hb * Vector3(1.2, top - site.y + 1.2, 6.0))
await get_tree().create_timer(2.0).timeout
await RenderingServer.frame_post_draw
get_viewport().get_texture().get_image().save_png("%s_hut_inside.png" % prefix)
print("[world] saved %s_hut_inside.png" % prefix)
weather.force("")
func _aim_camera(cam: Camera3D, eye: Vector3, at: Vector3) -> void:
var dir := at - eye
player.global_position = eye - Vector3(0.0, cam.position.y, 0.0)
player.rotation = Vector3(0.0, atan2(-dir.x, -dir.z), 0.0)
cam.rotation.x = atan2(dir.y, Vector2(dir.x, dir.z).length())
props._update_grass(100000)