M1a: survival core, pause menu, title screen and save/load
Design: docs/SURVIVAL_DESIGN.md (core loop, systems, architecture, phases). Survival core (M1a): - Items/recipes as data (data/*.json) in the addon SDK's define_item / define_recipe shape; procedural item meshes and offscreen-rendered icons - Inventory class (40 slots, hotbar = row 1) shared by player and chests; click / right-click split / shift-click quick-move - Actions autoload: the intent layer (craft, pickup, harvest_hit, place, transfer) that validates every change; becomes the RPC surface in M2 - Gathering: ground pickups (sticks, stones, flint); trees chopped with an axe fall and leave stumps; boulders mined with a pickaxe shrink per hit - Crafting screen with station checks (workbench); placement mode with green/red ghost, rotation and overlap/slope validation - Pieces: campfire (light, flames, embers), workbench, chest (16 slots) - HUD: hotbar, held tool view model with swing, prompts, toasts Menus and saving: - ESC pause menu: resume, controls, fullscreen, mouse sensitivity, quit - Title screen over a flyover of the island: Continue / New World (name + seed) / Load World (with delete) / Quit - Saves autoload: one folder per world under user://worlds, atomic writes with a .bak; stores only player changes (player, pieces, chest contents, harvested resources, taken pickups) and regenerates the rest from the seed - Autosave every 2 min, Save & Quit to title/desktop, save on window close Fixes: UI screens now fill the viewport (were pinned top-left); title backdrop no longer captures the mouse. Tests: test_survival_core (31 checks), test_save_load (round trip + slots), test_terrain_edges now checks 8 seeds for deep pits / unbanked water.
This commit is contained in:
@@ -18,10 +18,45 @@ extends Node3D
|
||||
@onready var player: CharacterBody3D = $Player
|
||||
@onready var sun: DirectionalLight3D = $Sun
|
||||
|
||||
const PIECES := {
|
||||
"campfire": preload("res://scripts/building/campfire.gd"),
|
||||
"workbench": preload("res://scripts/building/workbench.gd"),
|
||||
"chest": preload("res://scripts/building/chest.gd"),
|
||||
}
|
||||
|
||||
const AUTOSAVE_SECONDS := 120.0
|
||||
|
||||
## Set by the title screen before adding the world: no player, no HUD, no
|
||||
## saving, just a slow camera flight over the island as a menu backdrop.
|
||||
var menu_mode := false
|
||||
|
||||
var _spawn := Vector3.ZERO
|
||||
var _spawn_yaw := 0.0
|
||||
var _pieces: Node3D
|
||||
var hud: CanvasLayer
|
||||
var _session_time := 0.0 ## seconds played since the last save
|
||||
var _autosave_left := AUTOSAVE_SECONDS
|
||||
var _menu_cam: Camera3D
|
||||
var _menu_t := 0.0
|
||||
|
||||
func _ready() -> void:
|
||||
_pieces = Node3D.new()
|
||||
_pieces.name = "Pieces"
|
||||
add_child(_pieces)
|
||||
if menu_mode:
|
||||
player.process_mode = Node.PROCESS_MODE_DISABLED
|
||||
player.get_node("Camera3D").current = false
|
||||
_menu_cam = Camera3D.new()
|
||||
add_child(_menu_cam)
|
||||
_menu_cam.current = true
|
||||
$HUD.visible = false
|
||||
elif DisplayServer.get_name() != "headless":
|
||||
hud = preload("res://scripts/ui/hud.gd").new()
|
||||
add_child(hud)
|
||||
hud.bind(player)
|
||||
if Saves.has_world() and not menu_mode:
|
||||
# Save on window close instead of quitting straight away.
|
||||
get_tree().auto_accept_quit = false
|
||||
_aim_sun()
|
||||
player.set_physics_process(false)
|
||||
set_physics_process(false)
|
||||
@@ -43,13 +78,124 @@ func _on_terrain_ready() -> void:
|
||||
var to_lake := lake - Vector2(_spawn.x, _spawn.z)
|
||||
_spawn_yaw = atan2(-to_lake.x, -to_lake.y)
|
||||
player.water_level = terrain.water_level
|
||||
props.place_on(terrain, player, _spawn)
|
||||
props.place_on(terrain, player if not menu_mode else _menu_cam, _spawn)
|
||||
print("[world] scenery placed in %d ms" % (Time.get_ticks_msec() - t0))
|
||||
if menu_mode:
|
||||
return
|
||||
_respawn()
|
||||
if Saves.has_world():
|
||||
var state: Dictionary = Saves.load_state(Saves.current_id)
|
||||
if not state.is_empty():
|
||||
apply_save(state)
|
||||
print("[world] loaded '%s'" % Saves.current_id)
|
||||
player.set_physics_process(true)
|
||||
set_physics_process(true)
|
||||
_maybe_capture()
|
||||
|
||||
func _process(delta: float) -> void:
|
||||
if menu_mode:
|
||||
# Slow orbit over the valley, looking toward the lake.
|
||||
_menu_t += delta * 0.025
|
||||
var r := 70.0
|
||||
var p := Vector3(cos(_menu_t) * r, 0.0, sin(_menu_t) * r)
|
||||
p.y = maxf(terrain.sample_height(p.x, p.z), terrain.water_level) + 24.0
|
||||
_menu_cam.global_position = p
|
||||
var lake: Vector2 = terrain.lake_center
|
||||
_menu_cam.look_at(Vector3(lake.x * 0.5, 2.0, lake.y * 0.5), Vector3.UP)
|
||||
return
|
||||
if not Saves.has_world() or get_tree().paused:
|
||||
return
|
||||
_session_time += delta
|
||||
_autosave_left -= delta
|
||||
if _autosave_left <= 0.0:
|
||||
save_now()
|
||||
|
||||
# --- saving -----------------------------------------------------------------
|
||||
|
||||
## Writes the current game to the active world slot. Returns false if this
|
||||
## session isn't tied to a slot (e.g. running world.tscn directly).
|
||||
func save_now() -> bool:
|
||||
_autosave_left = AUTOSAVE_SECONDS
|
||||
if not Saves.has_world():
|
||||
return false
|
||||
var ok: bool = Saves.save_state(Saves.current_id, collect_save(), _session_time)
|
||||
if ok:
|
||||
_session_time = 0.0
|
||||
Actions.notify.emit("Game saved" if ok else "Save FAILED")
|
||||
return ok
|
||||
|
||||
func _notification(what: int) -> void:
|
||||
if what == NOTIFICATION_WM_CLOSE_REQUEST and Saves.has_world() and not menu_mode:
|
||||
save_now()
|
||||
get_tree().quit()
|
||||
|
||||
static func _xf_to_array(xf: Transform3D) -> Array:
|
||||
var b := xf.basis
|
||||
return [b.x.x, b.x.y, b.x.z, b.y.x, b.y.y, b.y.z, b.z.x, b.z.y, b.z.z, xf.origin.x, xf.origin.y, xf.origin.z]
|
||||
|
||||
static func _array_to_xf(a: Array) -> Transform3D:
|
||||
return Transform3D(Vector3(a[0], a[1], a[2]), Vector3(a[3], a[4], a[5]), Vector3(a[6], a[7], a[8]), Vector3(a[9], a[10], a[11]))
|
||||
|
||||
## Everything the player changed. The rest regenerates from the seed.
|
||||
func collect_save() -> Dictionary:
|
||||
var cam: Camera3D = player.get_node("Camera3D")
|
||||
var harvested := {}
|
||||
for uid in props.resource_nodes:
|
||||
var n = props.resource_nodes[uid]
|
||||
if not is_instance_valid(n) or n.depleted:
|
||||
harvested[uid] = 0.0
|
||||
elif n.hp < n.max_hp:
|
||||
harvested[uid] = n.hp
|
||||
var taken: Array = []
|
||||
for uid in props.pickups:
|
||||
var pk = props.pickups[uid]
|
||||
if not is_instance_valid(pk) or pk.taken:
|
||||
taken.append(uid)
|
||||
var pieces: Array = []
|
||||
for piece in _pieces.get_children():
|
||||
if piece.is_queued_for_deletion():
|
||||
continue
|
||||
var entry := {"item": piece.item_id, "xf": _xf_to_array(piece.global_transform)}
|
||||
if piece.get("inventory") != null:
|
||||
entry["inventory"] = piece.inventory.to_data()
|
||||
pieces.append(entry)
|
||||
return {
|
||||
"player": {
|
||||
"pos": [player.global_position.x, player.global_position.y, player.global_position.z],
|
||||
"yaw": player.rotation.y,
|
||||
"pitch": cam.rotation.x,
|
||||
"inventory": player.inventory.to_data(),
|
||||
"selected": player.selected,
|
||||
},
|
||||
"harvested": harvested,
|
||||
"pickups_taken": taken,
|
||||
"pieces": pieces,
|
||||
}
|
||||
|
||||
func apply_save(s: Dictionary) -> void:
|
||||
var p: Dictionary = s.get("player", {})
|
||||
if p.has("pos"):
|
||||
player.global_position = Vector3(p.pos[0], p.pos[1] + 0.05, p.pos[2])
|
||||
player.rotation = Vector3(0.0, float(p.get("yaw", 0.0)), 0.0)
|
||||
player.get_node("Camera3D").rotation.x = float(p.get("pitch", 0.0))
|
||||
if p.has("inventory"):
|
||||
player.inventory.load_data(p.inventory)
|
||||
player.select(int(p.get("selected", 0)))
|
||||
var harvested: Dictionary = s.get("harvested", {})
|
||||
for uid in harvested:
|
||||
if props.resource_nodes.has(uid):
|
||||
props.resource_nodes[uid].restore(float(harvested[uid]))
|
||||
for uid in s.get("pickups_taken", []):
|
||||
if props.pickups.has(uid) and is_instance_valid(props.pickups[uid]):
|
||||
props.pickups[uid].collected()
|
||||
for e in s.get("pieces", []):
|
||||
var def: Dictionary = ItemDB.get_item(e.get("item", ""))
|
||||
if def.is_empty() or not def.has("place"):
|
||||
continue
|
||||
var piece := spawn_piece(def, _array_to_xf(e.xf))
|
||||
if e.has("inventory") and piece.get("inventory") != null:
|
||||
piece.inventory.load_data(e.inventory)
|
||||
|
||||
func _respawn() -> void:
|
||||
player.global_position = _spawn + Vector3(0.0, 1.5, 0.0)
|
||||
player.velocity = Vector3.ZERO
|
||||
@@ -64,6 +210,42 @@ func _physics_process(_delta: float) -> void:
|
||||
push_warning("[world] player left the map at %s; respawning" % p)
|
||||
_respawn()
|
||||
|
||||
# --- building ---------------------------------------------------------------
|
||||
|
||||
## Whether a piece can go at `xf`: inside the valley, on dry fairly flat
|
||||
## ground, and not overlapping trees, rocks or other pieces.
|
||||
func placement_valid(def: Dictionary, xf: Transform3D) -> bool:
|
||||
var p := xf.origin
|
||||
if not terrain.inside_boundary(p.x, p.z, 1.5):
|
||||
return false
|
||||
if p.y < terrain.water_level + 0.15:
|
||||
return false
|
||||
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.
|
||||
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:
|
||||
return false
|
||||
# Overlap test against everything solid except the ground itself.
|
||||
var box := BoxShape3D.new()
|
||||
box.size = Vector3(hx * 2.0 - 0.1, 1.0, hz * 2.0 - 0.1)
|
||||
var q := PhysicsShapeQueryParameters3D.new()
|
||||
q.shape = box
|
||||
q.transform = Transform3D(xf.basis, p + Vector3(0, 0.75, 0))
|
||||
q.collision_mask = 1
|
||||
q.exclude = [terrain.get_node("TerrainBody").get_rid(), player.get_rid()]
|
||||
return get_world_3d().direct_space_state.intersect_shape(q, 1).is_empty()
|
||||
|
||||
func spawn_piece(def: Dictionary, xf: Transform3D) -> Node3D:
|
||||
var script: Script = PIECES.get(def.place.piece, preload("res://scripts/building/piece.gd"))
|
||||
var piece: StaticBody3D = script.new()
|
||||
piece.setup(def)
|
||||
_pieces.add_child(piece)
|
||||
piece.global_transform = xf
|
||||
return piece
|
||||
|
||||
# --- dev screenshot hook ----------------------------------------------------
|
||||
|
||||
func _maybe_capture() -> void:
|
||||
@@ -113,4 +295,46 @@ func _maybe_capture() -> void:
|
||||
var path := "%s_%s.png" % [prefix, v[0]]
|
||||
get_viewport().get_texture().get_image().save_png(path)
|
||||
print("[world] saved ", path)
|
||||
await _capture_survival(prefix, cam)
|
||||
get_tree().quit()
|
||||
|
||||
## Survival views: a small camp in front of the spawn (axe in hand), then the
|
||||
## inventory screen with a chest open.
|
||||
func _capture_survival(prefix: String, cam: Camera3D) -> void:
|
||||
_respawn()
|
||||
var inv: Inventory = player.inventory
|
||||
for pair in [["stone_axe", 1], ["stone_pickaxe", 1], ["campfire", 1], ["club", 1],
|
||||
["wood", 23], ["stick", 12], ["stone", 17], ["flint", 5]]:
|
||||
inv.add(pair[0], pair[1])
|
||||
var fwd := -player.global_basis.z
|
||||
var right := player.global_basis.x
|
||||
var chest: Node = null
|
||||
for k in [["campfire", 4.5, 0.0], ["workbench", 7.0, -2.8], ["chest", 6.5, 2.4]]:
|
||||
var p: Vector3 = player.global_position + fwd * float(k[1]) + right * float(k[2])
|
||||
p.y = terrain.sample_height(p.x, p.z)
|
||||
var piece := spawn_piece(ItemDB.get_item(k[0]), Transform3D(Basis(Vector3.UP, player.rotation.y), p))
|
||||
if k[0] == "chest":
|
||||
chest = piece
|
||||
player.select(0)
|
||||
cam.rotation.x = -0.22
|
||||
await get_tree().create_timer(2.5).timeout
|
||||
await RenderingServer.frame_post_draw
|
||||
get_viewport().get_texture().get_image().save_png("%s_camp.png" % prefix)
|
||||
print("[world] saved %s_camp.png" % prefix)
|
||||
|
||||
chest.inventory.add("wood", 40)
|
||||
chest.inventory.add("stone", 12)
|
||||
player.global_position = chest.global_position + fwd * -2.0
|
||||
hud._screen.open(chest)
|
||||
await get_tree().create_timer(0.6).timeout
|
||||
await RenderingServer.frame_post_draw
|
||||
get_viewport().get_texture().get_image().save_png("%s_inventory.png" % prefix)
|
||||
print("[world] saved %s_inventory.png" % prefix)
|
||||
|
||||
hud._screen.close()
|
||||
hud._menu.open()
|
||||
await get_tree().create_timer(0.4).timeout
|
||||
await RenderingServer.frame_post_draw
|
||||
get_viewport().get_texture().get_image().save_png("%s_menu.png" % prefix)
|
||||
print("[world] saved %s_menu.png" % prefix)
|
||||
hud._menu.close()
|
||||
|
||||
Reference in New Issue
Block a user