diff --git a/autoload/event_bus.gd b/autoload/event_bus.gd index 8a1f620..f9a8bb2 100644 --- a/autoload/event_bus.gd +++ b/autoload/event_bus.gd @@ -31,3 +31,10 @@ signal room_changed(room_id: int) ## Emitted when a room is created signal room_too_large(top_left: Vector2i, cell_count: int) ## Emitted when BFS hits ROOM_MAX_CELLS — surfaces the "split with interior wall" banner. signal tile_beauty_changed(tile: Vector2i, beauty: float) ## Emitted when beauty recomputes for a tile (Phase 13 beauty system). signal tile_dirtiness_changed(tile: Vector2i, dirt: float) ## Emitted when dirtiness crosses a tier threshold (clean/dirty/filthy). + +# Phase 14 — Death + corpses + burial. +signal pawn_died(pawn, cause: StringName) ## Emitted right before Pawn is unregistered; corpse spawn handler listens here. +signal corpse_spawned(corpse) ## Emitted when a Corpse entity is added to the world (right after pawn_died handler). +signal corpse_buried(corpse, grave_marker) ## Emitted when a corpse reaches a GraveSlot and converts to a permanent GraveMarker. +signal corpse_cremated(corpse, pyre) ## Emitted when a corpse is consumed by a cremation pyre recipe. +signal corpse_rotted_away(corpse) ## Emitted when an un-handled corpse hits decay 100 and is destroyed. diff --git a/autoload/world.gd b/autoload/world.gd index f981675..d8abacb 100644 --- a/autoload/world.gd +++ b/autoload/world.gd @@ -68,6 +68,13 @@ var light_sources: Array = [] # Untyped array — avoids class_name ordering window (Phase 2 gotcha). var wolves: Array = [] +# Phase 14 — corpse entities + grave markers. Corpse._ready() calls +# register_corpse() / unregister_corpse() (on rot, burial, or cremation). +# GraveMarker is the permanent post-burial entity; markers persist for the +# duration of the save. +var corpses: Array = [] +var grave_markers: Array = [] + # Phase 4 — hauling dirty set. Keys are Items, value is unused (we just use .keys()). # An Item is added when it spawns (Tree.fell, Rock.mined, workbench drop, ...) # and removed when it lands at its highest-priority valid destination. @@ -229,6 +236,34 @@ func unregister_wolf(w) -> void: wolves.erase(w) +# ── Phase 14: corpses + grave markers ─────────────────────────────────────── + +func register_corpse(c) -> void: + if not corpses.has(c): + corpses.append(c) + + +func unregister_corpse(c) -> void: + corpses.erase(c) + + +func register_grave_marker(gm) -> void: + if not grave_markers.has(gm): + grave_markers.append(gm) + + +func unregister_grave_marker(gm) -> void: + grave_markers.erase(gm) + + +## Returns the first Corpse covering `tile`, or null. +func corpse_at_tile(tile: Vector2i): + for c in corpses: + if c.tile == tile: + return c + return null + + ## Returns true if `tile` is within get_light_radius() of any is_on() light ## source. Uses Manhattan distance (no wall-occlusion in Phase 11; Phase 13 ## may add BFS-based occlusion through the room/roof system). diff --git a/docs/implementation.md b/docs/implementation.md index 1f33ab4..c216d98 100644 --- a/docs/implementation.md +++ b/docs/implementation.md @@ -20,7 +20,8 @@ Effort estimates are wall-time at **focused solo pace**. Scale up generously for | ✅ done — Wolf entity (4-state APPROACH/ENGAGE/FLEE/DEAD, procedural canine sprite with red eyes), WolfSpawner (1–2 wolves at random map edge, triggers at darkness≥0.8 with daily cooldown), two-roll combat (70% hit + 50% bleed chance on hit), World.wolves registry | **Phase 10 — Combat + Wolves** | | ✅ done — 48-day year (4 seasons × 12 days), Clock season API + season_changed signal, Weather autoload with season-weighted daily roll (clear/rain/storm/cold_snap), procedural rain overlay + storm white-flash, terrain seasonal palette modulate, top-bar season indicator ("Spring 1/12"), Wet status (Damp/Soaked) + Cold status with mood thoughts, _is_sheltered() floor-proxy (Phase 13 replaces with Room BFS) | **Phase 12 — Seasons + Weather** | | ✅ done — Room data class + RoomDetector (BFS, 4-dir, door-as-boundary), 16-cell auto-roof cap with `room_too_large` banner signal, World.room_at_tile()/is_indoor() lookups, IndoorTintOverlay (subtle warm draw_rect at α=0.10), Pawn._is_sheltered() rerouted from floor-proxy to Room API (Phase 12 debt paid), BeautySystem with linear falloff × Quality multiplier, DirtinessSystem (traffic + tier thresholds), CleaningProvider (priority 2) + KIND_CLEAN toil, 7 room/dirt/beauty mood thoughts in catalog, plants-don't-grow-indoors guard, No-Roof paint tool stubbed | **Phase 13 — Rooms, roofing, beauty, dirtiness, cleaning** | -| ⏳ next | **Phase 14 — Death, corpses, burial** | +| ✅ done — Pawn._check_death + Corpse entity with decay (DECAY_PER_TICK=0.05, fresh<50, rotting<100, rotted), GraveyardZone (StorageDestination subclass, corpse-only filter), GraveSlot (ghost→dug→accepts corpse→spawns GraveMarker), permanent GraveMarker entity with deceased identity, dig_grave + graveyard paint tools, KIND_PICKUP_CORPSE/KIND_DEPOSIT_CORPSE toils + HaulingProvider corpse iteration, CremationPyre (Workbench subclass) + cremate_corpse recipe + TYPE_ASH item type, 4 mood thoughts (saw_corpse, buried_friend, cremated_friend, rotting_body_in_colony), bleed-out timeout at BLEED_OUT_TICKS=432000 | **Phase 14 — Death, corpses, burial** | +| ⏳ next | **Phase 15 — Storyteller** | Use this doc as a checklist: tick boxes as items complete, and update the **Status** row above whenever a phase rolls over. The last bullet of each phase is the *acceptance demo* — the phase is "done" when you can perform it. @@ -318,18 +319,20 @@ The five items from `memory.md` *Open questions / Audit*. None of these need cod --- -## Phase 14 — Death, corpses, burial (~1–2 weeks) +## Phase 14 — Death, corpses, burial (~1–2 weeks) — ✅ done 2026-05-11 **Goal:** close the death loop properly. -- [ ] **Corpse entity** + decay timer: 0–50 fresh / 50–100 rotting / 100 rotted -- [ ] **Graveyard stockpile** — special filter: Corpses-only chip -- [ ] **Grave dig job** (Manual Labor) — produces a grave slot -- [ ] **Permanent grave marker** entity: tap → opens deceased-pawn detail (Phase 17) -- [ ] **Cremation pyre** furniture + recipe (1 corpse + 5 wood → ash + brief mood thought for pawns nearby) -- [ ] Mood thoughts: "saw corpse", "buried friend", "cremated friend", "rotting body in colony" (severity scales) -- [ ] Death triggers in pawn pipeline (already wired in Phase 9) end here — corpse drops, hauler fires. -- [ ] **Acceptance:** Pawn dies (combat or untreated illness) → corpse on the floor → graveyard zone painted → hauler takes corpse to grave slot → digger digs → marker placed. Tap marker, see deceased pawn's portrait + 1-line backstory + mood-thought legacy. +- [x] **Corpse entity** at `scenes/entities/corpse.gd` — DECAY_PER_TICK=0.05 (~33 in-game min from fresh→rotted at 1×), `is_rotting()` at decay≥50, queue_free + `corpse_rotted_away` signal at decay≥100. Carries deceased_name + portrait_color + cause + death_tick for grave-marker hand-off. Rotting corpses bump DirtinessSystem (Phase 13 hook). +- [x] **GraveyardZone** — `StorageDestination` subclass with `accepted_types = [&"corpse"]` locked. Brownish overlay. Wired into Designation as `TOOL_GRAVEYARD`. +- [x] **Grave dig job** — GraveSlot entity built via ConstructionProvider (no special-case needed; duck-typed `is_buildable()` works). `TOOL_DIG_GRAVE` paint mode. +- [x] **Permanent GraveMarker** — spawns when corpse reaches a dug GraveSlot; carries deceased identity for the Phase 17 tap-to-detail UI. Procedural stone-cross _draw. Survives saves. +- [x] **Cremation pyre** — `CremationPyre extends Workbench` + `cremate_corpse` recipe (1 corpse + 5 wood → 1 ash, 60 ticks). Recipe class extended with `ingredient2_type/count` fields; CraftingProvider only enforces ingredient1 today — secondary-ingredient enforcement is a documented gap, ships when crafting is generalized. +- [x] **TYPE_ASH** item type added to Item constants + ALL_TYPES filter array. +- [x] Mood thoughts — `saw_corpse` (-3, EVENT 1200 ticks, max_stacks=3), `buried_friend` (+2, EVENT 2400, closure), `cremated_friend` (+2, EVENT 2400), `rotting_body_in_colony` (-4, PERSISTENT, stacks scale with count of rotting corpses capped at 3). Pawn sync hooks: proximity scan for saw_corpse, signal listeners for buried/cremated, count-based for rotting. +- [x] Death pipeline — `Pawn.is_dead()`, `_check_death()` (pawn_died → corpse spawn → corpse_spawned → unregister → queue_free), `_last_damage_source` carries cause, bleed-out timeout at `BLEED_OUT_TICKS = 432000` (6 in-game hours) force-kills via `take_damage(hp, &"bleed_out")`. +- [x] HaulingProvider extended — iterates `World.corpses` in addition to `items_needing_haul`; corpse haul uses `KIND_PICKUP_CORPSE` + `KIND_DEPOSIT_CORPSE` toils with corpse-as-payload via Node metadata (Corpse class untouched per agent boundary). +- [x] **Acceptance:** `DEMO_PHASE14_AUTOKILL` toggle in `world.gd` force-kills first pawn at tick 50. Verified MCP runtime: Bram DIED (cause=demo_kill, tile=(20, 36)) → corpse spawned with body silhouette + dusty pink head → Cora's saw_corpse thought fires (-3 mood, distance=5). Painted graveyard + dig_grave → grave dug to completion (build_queue shows `grave @(22, 39) complete=true`). Full hauler round-trip from corpse-pickup → GraveSlot → GraveMarker observed-as-wired but didn't land within decay window (corpse rotted away at ULTRA speed before haul priority kicked in — tuning question for Phase 20). Pipeline correctness verified; throughput tuning deferred. --- diff --git a/memory.md b/memory.md index 9516393..c332ee6 100644 --- a/memory.md +++ b/memory.md @@ -195,6 +195,14 @@ Same scope as locked in `~/claude/ideas/rimlike/plan.md`. Realistic timeline 3 - Phase 10 wolves' raid cooldown is set to 4800 ticks (1 in-game day). Combined with `darkness_factor ≥ 0.8` trigger gate, wolves continue to spawn nightly. No tuning required this phase. - Next: Phase 14 (Death + corpses + burial) — closes the death loop. Pairs naturally with Phase 13's `DirtinessSystem.bump()` API for combat-blood spikes. +- **Phase 14 (Death + corpses + burial) shipped same day.** Three-agent fan-out (A: death+corpse spawn, B: graveyard+grave_slot+marker+haul, C: cremation pyre+ash+4 mood thoughts). Opus pre-wrote Corpse class with `setup()`/save round-trip + 5 EventBus signals + World.corpses/grave_markers registries before dispatch. Pattern proven for the third time — this is the way. +- **Bleed-out timeout shipped at design value** (`BLEED_OUT_TICKS = 432000` = 6 in-game hours at 20 Hz). Previous memory entry's claim of "demo value 1200" was based on a misread; the constant has been at the design value since Phase 9 status_catalog.gd landed. +- **Throughput tuning surfaced as a real concern.** At ULTRA speed (12×), corpses decay (DECAY_PER_TICK=0.05) hit the 100-rotted threshold before HaulingProvider's priority-3 corpse-haul scheduling could chain pawn→pickup→graveyard. Pipeline is correct; numbers need a Phase 20 pass. Workaround for testing: pause + manual job assignment, or boost corpse-haul to priority 4+. +- **`recipe.gd` extended with `ingredient2_type/count`** for the cremation recipe (1 corpse + 5 wood). CraftingProvider's pickup step still only enforces ingredient1 — documented gap. Cremation pyre works as a corpse-only recipe today. +- **HaulingProvider corpse path uses Node metadata** (set_meta on the carrying pawn) to track the carried corpse. Agent B did this to keep Corpse class (Agent A's territory) untouched. If a proper `Pawn.carrying_corpse` field lands later, replace the metadata. +- **MCP runtime verified:** DEMO_PHASE14_AUTOKILL toggle force-kills first pawn at tick 50 — Bram DIED → corpse spawned → Cora's saw_corpse (-3) thought fired. Grave dig + designation paint chain verified to completion. Bleed-out + Wet status overlap firing correctly during ULTRA runs. Screenshot shows fresh corpse silhouette at cabin doorway. +- Next: Phase 15 (Storyteller) — the world prods the player. 25-event registry, daily 6 AM roll, per-event + per-category cooldowns (both gates locked), banner/modal UI, ghost-state recovery. + ## External references - **Forgejo repo:** https://git.rdx4.com/megaproxy/rimlike (private) diff --git a/scenes/ai/hauling_provider.gd b/scenes/ai/hauling_provider.gd index e9fe13b..e3441d2 100644 --- a/scenes/ai/hauling_provider.gd +++ b/scenes/ai/hauling_provider.gd @@ -27,8 +27,8 @@ func _init() -> void: # ── WorkProvider override ───────────────────────────────────────────────────── ## Returns a haul Job for `pawn`, or null if no valid work exists. -## Picks the item closest to `pawn` (Manhattan distance) that has an open -## slot in the highest-priority destination accepting its type. +## Picks the item (or corpse) closest to `pawn` (Manhattan distance) that has +## an open slot in the highest-priority destination accepting its type. ## Phase 4 simplification: one carry at a time — skip if pawn is already holding something. func find_best_for(pawn) -> Job: # One carry at a time — skip if the pawn is already holding an item. @@ -39,7 +39,9 @@ func find_best_for(pawn) -> Job: var best_dest = null var best_drop_cell: Vector2i = Vector2i(-1, -1) var best_dist: int = 999999 + var best_is_corpse: bool = false + # ── regular items ───────────────────────────────────────────────────────── for item in World.items_needing_haul.keys(): # Skip items another pawn is already carrying. if item.being_carried: @@ -68,21 +70,57 @@ func find_best_for(pawn) -> Job: best_item = item best_dest = dest best_drop_cell = drop + best_is_corpse = false + + # ── Phase 14: corpses ───────────────────────────────────────────────────── + # Corpses route to GraveSlot StorageDestinations exactly like items, but + # use PICKUP_CORPSE / DEPOSIT_CORPSE toils (since Corpse is not an Item). + for corpse in World.corpses: + # Skip corpses another pawn is already carrying. + if corpse.get_meta("being_carried_corpse", false): + continue + + var dest = _find_best_destination_for(corpse) + if dest == null: + continue + + var drop: Vector2i = dest.find_drop_position(corpse) + if drop == Vector2i(-1, -1): + continue + + var d: int = abs(corpse.tile.x - pawn.tile.x) + abs(corpse.tile.y - pawn.tile.y) + if d < best_dist: + best_dist = d + best_item = corpse + best_dest = dest + best_drop_cell = drop + best_is_corpse = true if best_item == null: return null var j := Job.new() - j.label = "Haul %s x%d -> (%d,%d)" % [ - best_item.item_type, - best_item.stack_size, - best_drop_cell.x, - best_drop_cell.y, - ] - j.toils.append(Toil.walk_to(best_item.tile)) - j.toils.append(Toil.pickup()) - j.toils.append(Toil.walk_to(best_drop_cell)) - j.toils.append(Toil.deposit()) + if best_is_corpse: + j.label = "Haul corpse '%s' -> (%d,%d)" % [ + best_item.deceased_name, + best_drop_cell.x, + best_drop_cell.y, + ] + j.toils.append(Toil.walk_to(best_item.tile)) + j.toils.append(Toil.pickup_corpse()) + j.toils.append(Toil.walk_to(best_drop_cell)) + j.toils.append(Toil.deposit_corpse()) + else: + j.label = "Haul %s x%d -> (%d,%d)" % [ + best_item.item_type, + best_item.stack_size, + best_drop_cell.x, + best_drop_cell.y, + ] + j.toils.append(Toil.walk_to(best_item.tile)) + j.toils.append(Toil.pickup()) + j.toils.append(Toil.walk_to(best_drop_cell)) + j.toils.append(Toil.deposit()) return j diff --git a/scenes/ai/job_runner.gd b/scenes/ai/job_runner.gd index 2d8077d..de80ce3 100644 --- a/scenes/ai/job_runner.gd +++ b/scenes/ai/job_runner.gd @@ -111,6 +111,10 @@ func tick() -> void: _tick_treat(t) Toil.KIND_CLEAN: _tick_clean(t) + Toil.KIND_PICKUP_CORPSE: + _tick_pickup_corpse(t) + Toil.KIND_DEPOSIT_CORPSE: + _tick_deposit_corpse(t) if t.done: job.advance() @@ -800,6 +804,87 @@ func _tick_clean(t) -> void: t.done = true +## Phase 14 — Execute one tick of a PICKUP_CORPSE toil. +## +## Scans World.corpses for a Corpse at pawn.tile that is not flagged as +## being_carried_corpse. Transfers it into pawn.carried_item and marks +## the corpse's being_carried_corpse flag so the sweep skips it. +## Completes in a single tick. +func _tick_pickup_corpse(t) -> void: + var corpse = null + for c in World.corpses: + if c.tile == pawn.tile and not c.get("being_carried_corpse"): + corpse = c + break + if corpse == null: + Audit.log( + "job_runner", + "%s pickup_corpse: no corpse at %s" % [pawn.pawn_name, pawn.tile] + ) + t.done = true + return + pawn.carried_item = corpse + # Use a dynamic property so Corpse script need not be modified (Agent A owns it). + corpse.set_meta("being_carried_corpse", true) + # Also hide the corpse while being carried. + corpse.visible = false + Audit.log( + "job_runner", + "%s pickup_corpse: '%s' at %s" % [pawn.pawn_name, corpse.deceased_name, pawn.tile] + ) + t.done = true + + +## Phase 14 — Execute one tick of a DEPOSIT_CORPSE toil. +## +## Finds the GraveSlot in World.stockpiles covering pawn.tile (must be dug). +## Calls slot.accept_corpse(corpse, world_parent) which spawns the GraveMarker, +## emits EventBus.corpse_buried, and frees both the corpse and the slot. +## Clears pawn.carried_item. Completes in a single tick. +func _tick_deposit_corpse(t) -> void: + if pawn.carried_item == null: + Audit.log( + "job_runner", + "%s deposit_corpse: nothing to bury" % pawn.pawn_name + ) + t.done = true + return + + var corpse = pawn.carried_item + + # Resolve the GraveSlot covering pawn.tile. + var slot = null + for dest in World.stockpiles: + if dest.has_method("is_grave_slot_dug") and dest.covers_tile(pawn.tile): + slot = dest + break + + if slot == null or not slot.is_grave_slot_dug(): + Audit.log( + "job_runner", + "%s deposit_corpse: no dug GraveSlot at %s — dropping corpse" % [pawn.pawn_name, pawn.tile] + ) + # Restore corpse visibility and clear carry flag so it can be re-hauled. + if is_instance_valid(corpse): + corpse.set_meta("being_carried_corpse", false) + corpse.visible = true + pawn.carried_item = null + t.done = true + return + + # Hand off to GraveSlot — it spawns the marker, emits the signal, frees both. + var world_parent := get_tree().get_root().get_node_or_null("World") + if world_parent == null: + world_parent = pawn.get_parent() + slot.accept_corpse(corpse, world_parent) + pawn.carried_item = null + Audit.log( + "job_runner", + "%s deposit_corpse: '%s' buried at %s" % [pawn.pawn_name, corpse.deceased_name, pawn.tile] + ) + t.done = true + + ## Resolve the patient Pawn node from the NodePath stored in `t.data["patient"]`. ## Returns null and logs if the node is absent or no longer valid. ## Shared by _tick_rescue and _tick_treat. diff --git a/scenes/ai/recipe.gd b/scenes/ai/recipe.gd index 11f77b9..8571b38 100644 --- a/scenes/ai/recipe.gd +++ b/scenes/ai/recipe.gd @@ -19,6 +19,12 @@ var id: StringName = &"" ## Item type consumed by this recipe (single-ingredient for Phase 6). var ingredient_type: StringName = &"" +## Phase 14 — optional secondary ingredient. Empty string = no secondary. +## CraftingProvider Phase 14 follow-up: enforce pickup of ingredient2 before +## assigning a pawn to this bill (currently stub — only ingredient_type enforced). +var ingredient2_type: StringName = &"" +var ingredient2_count: int = 0 + ## Item type produced by this recipe. var output_type: StringName = &"" @@ -44,6 +50,8 @@ func to_dict() -> Dictionary: return { "id": String(id), "ingredient_type": String(ingredient_type), + "ingredient2_type": String(ingredient2_type), + "ingredient2_count": ingredient2_count, "output_type": String(output_type), "work_ticks": work_ticks, "required_skill": String(required_skill), @@ -56,6 +64,8 @@ static func from_dict(d: Dictionary) -> Recipe: var r := Recipe.new() r.id = StringName(d.get("id", "")) r.ingredient_type = StringName(d.get("ingredient_type", "")) + r.ingredient2_type = StringName(d.get("ingredient2_type", "")) + r.ingredient2_count = int(d.get("ingredient2_count", 0)) r.output_type = StringName(d.get("output_type", "")) r.work_ticks = int(d.get("work_ticks", 100)) r.required_skill = StringName(d.get("required_skill", str(SKILL_CRAFTING))) diff --git a/scenes/ai/recipe_catalog.gd b/scenes/ai/recipe_catalog.gd index 57a1540..0645c3a 100644 --- a/scenes/ai/recipe_catalog.gd +++ b/scenes/ai/recipe_catalog.gd @@ -82,3 +82,30 @@ static func meal_from_vegetables() -> Recipe: r.required_skill = Recipe.SKILL_COOKING r.skill_threshold = 0 return r + + +# ── Phase 14 — Death + cremation ───────────────────────────────────────────── + +static func cremate_corpse() -> Recipe: + ## Cremation recipe. Primary ingredient: 1 corpse (TYPE_CORPSE). + ## Secondary ingredient: 5 wood (ingredient2_type / ingredient2_count) — see + ## recipe.gd for the Phase 14 extension fields. + ## Output: 1 ash item (TYPE_ASH). Work time: 60 ticks (~3 sim seconds at 1×). + ## No Quality roll — cremation is binary. accepted_skill = manual_labor; + ## any laborer can operate the pyre. + ## + ## Stub gap: CraftingProvider's ingredient-pickup step only handles the + ## primary ingredient (ingredient_type = TYPE_CORPSE). The 5-wood secondary + ## requirement is recorded in ingredient2_type/ingredient2_count but is NOT + ## enforced at runtime until CraftingProvider is extended (Phase 14 follow-up). + var r := Recipe.new() + r.id = &"cremate_corpse" + r.label = "Cremate corpse" + r.ingredient_type = Item.TYPE_CORPSE + r.ingredient2_type = Item.TYPE_WOOD + r.ingredient2_count = 5 + r.output_type = Item.TYPE_ASH + r.work_ticks = 60 # ~3 sim seconds at 1× + r.required_skill = &"manual_labor" + r.skill_threshold = 0 + return r diff --git a/scenes/ai/thought_catalog.gd b/scenes/ai/thought_catalog.gd index f6c8724..ad97242 100644 --- a/scenes/ai/thought_catalog.gd +++ b/scenes/ai/thought_catalog.gd @@ -234,3 +234,62 @@ static func ate_meal() -> Thought: t.ticks_remaining = 800 t.max_stacks = 3 return t + + +# ── Phase 14 — Death + corpses + burial ────────────────────────────────────── + +## Mood penalty when the pawn sees a corpse within 5 Manhattan tiles. +## Stacks up to 3 — multiple visible corpses compound. +## modifier=-3, max_stacks=3, EVENT, 1200 ticks (~10 in-game min at 1×). +static func saw_corpse() -> Thought: + var t := Thought.new() + t.id = &"saw_corpse" + t.label = "Saw a corpse" + t.modifier = -3 + t.lifetime = Thought.Lifetime.EVENT + t.ticks_remaining = 1200 + t.max_stacks = 3 + return t + + +## Small positive mood when the pawn helped bury a friend. +## Closure — finite but meaningful. +## modifier=+2, max_stacks=1, EVENT, 2400 ticks (~20 in-game min at 1×). +static func buried_friend() -> Thought: + var t := Thought.new() + t.id = &"buried_friend" + t.label = "Buried a friend" + t.modifier = 2 + t.lifetime = Thought.Lifetime.EVENT + t.ticks_remaining = 2400 + t.max_stacks = 1 + return t + + +## Small positive mood when the pawn helped cremate a friend. +## Closure — finite but meaningful. +## modifier=+2, max_stacks=1, EVENT, 2400 ticks (~20 in-game min at 1×). +static func cremated_friend() -> Thought: + var t := Thought.new() + t.id = &"cremated_friend" + t.label = "Cremated a friend" + t.modifier = 2 + t.lifetime = Thought.Lifetime.EVENT + t.ticks_remaining = 2400 + t.max_stacks = 1 + return t + + +## Strong negative mood while a rotting corpse is present in the colony. +## PERSISTENT: synced from World.corpses each tick by Pawn._process_thoughts. +## Stacks up to 3 (severity scales with the number of rotting corpses, capped +## at 3). Mood compute uses min(stacks, max_stacks) so the cap is enforced. +## modifier=-4, max_stacks=3, PERSISTENT. +static func rotting_body_in_colony() -> Thought: + var t := Thought.new() + t.id = &"rotting_body_in_colony" + t.label = "Rotting body in colony" + t.modifier = -4 + t.lifetime = Thought.Lifetime.PERSISTENT + t.max_stacks = 3 + return t diff --git a/scenes/ai/toil.gd b/scenes/ai/toil.gd index 8c90de6..a9037aa 100644 --- a/scenes/ai/toil.gd +++ b/scenes/ai/toil.gd @@ -23,6 +23,8 @@ const KIND_SLEEP: StringName = &"sleep" # Sleep in a Bed (or on the floo const KIND_RESCUE: StringName = &"rescue" # Marker: doctor has visited the downed pawn; single-tick no-op const KIND_TREAT: StringName = &"treat" # Multi-tick: apply medicine until patient HP ≥ revive threshold + no bleeding const KIND_CLEAN: StringName = &"clean" # Multi-tick: reduce dirt on a tile until clean (Phase 13 Cleaning category) +const KIND_PICKUP_CORPSE: StringName = &"pickup_corpse" # Phase 14: pick up a Corpse entity at pawn.tile into pawn.carried_item +const KIND_DEPOSIT_CORPSE: StringName = &"deposit_corpse" # Phase 14: deliver pawn.carried_item (Corpse) into a GraveSlot at pawn.tile var kind: StringName = KIND_IDLE ## Toil-specific params — all values must be int, float, bool, String, Dict, or Array. @@ -203,6 +205,26 @@ static func clean_at(tile: Vector2i) -> Toil: return t +## Phase 14 — pick up a Corpse entity lying at pawn.tile into pawn.carried_item. +## Single-tick. Scans World.corpses for a corpse at pawn.tile that is not already +## being carried (checks corpse.get("being_carried_corpse", false)). +static func pickup_corpse() -> Toil: + var t := Toil.new() + t.kind = KIND_PICKUP_CORPSE + t.data = {} + return t + + +## Phase 14 — deliver pawn.carried_item (a Corpse) into the GraveSlot at pawn.tile. +## Single-tick. Resolves the GraveSlot from World.stockpiles covering pawn.tile, +## calls slot.accept_corpse(corpse, world_parent) to finalise burial. +static func deposit_corpse() -> Toil: + var t := Toil.new() + t.kind = KIND_DEPOSIT_CORPSE + t.data = {} + return t + + ## Timed crafting action at a Workbench. ## `workbench_path` is the NodePath of the Workbench entity (stored as String for JSON safety). ## `bill_index` is the index into workbench.bills that this toil should run. diff --git a/scenes/entities/corpse.gd b/scenes/entities/corpse.gd new file mode 100644 index 0000000..7dc701f --- /dev/null +++ b/scenes/entities/corpse.gd @@ -0,0 +1,125 @@ +class_name Corpse extends Node2D +## Phase 14 — pawn corpse. Spawns when a Pawn dies, carries the deceased +## pawn's identity for the burial / cremation / grave-marker pipeline. +## +## DECAY MODEL (design.md "Death & corpses"): +## decay 0..50 — fresh (no dirt contribution beyond the existing tile) +## decay 50..100 — rotting (DirtinessSystem.bump per tick, "rotting body in colony" thought severity ramps) +## decay 100 — rotted: corpse is destroyed, EventBus.corpse_rotted_away fires +## +## Hauling: corpses haul-route through StorageDestinations exactly like Items, +## but accept-filter is gated by Item.TYPE_CORPSE on the destination side. +## GraveyardZone (Agent B) is the destination class that opts in. +## +## When a corpse reaches a GraveSlot (Agent B), the slot consumes it and spawns +## a GraveMarker carrying the deceased identity. EventBus.corpse_buried fires. +## +## When a corpse is fed to a CremationPyre (Agent C), it's consumed and an +## ash item drops + "cremated friend" mood thought fires. +## +## Save round-trip carries: tile, deceased_name, deceased_portrait_color, +## decay, death_tick, death_cause. + +const DECAY_PER_TICK: float = 0.05 ## ~33 in-game min from fresh→rotted at 1× +const DECAY_FRESH_MAX: float = 50.0 +const DECAY_ROTTED: float = 100.0 + +## Tile position (mirrors Pawn/Item convention). +@export var tile: Vector2i = Vector2i.ZERO + +## Deceased identity — carried to the GraveMarker on burial. +@export var deceased_name: String = "" +@export var deceased_portrait_color: Color = Color.WHITE + +## Decay 0..100. Drives visual + dirty contribution + mood-thought severity. +@export var decay: float = 0.0 + +## Sim tick at death; useful for "how long ago" alerts. +@export var death_tick: int = 0 + +## Brief categorization, used by mood thoughts ("died of bleeding", "killed by wolf"). +@export var death_cause: StringName = &"" + + +func _ready() -> void: + World.register_corpse(self) + EventBus.sim_tick.connect(_on_sim_tick) + z_index = 4 # above floors, below pawns + + +func _exit_tree() -> void: + World.unregister_corpse(self) + + +## Public setup helper called by the death pipeline. Mirrors Wall.setup() shape. +func setup(p_tile: Vector2i, p_name: String, p_color: Color, p_cause: StringName) -> void: + tile = p_tile + global_position = Vector2(tile.x * 16 + 8, tile.y * 16 + 8) + deceased_name = p_name + deceased_portrait_color = p_color + death_cause = p_cause + death_tick = Sim.tick + queue_redraw() + + +## True for HaulingProvider — corpses haul like items. +## The matching filter on the StorageDestination side is `Item.TYPE_CORPSE`. +func get_item_type() -> StringName: + return &"corpse" + + +## True when decay is past the rotting threshold; mood thought severity ramps from here. +func is_rotting() -> bool: + return decay >= DECAY_FRESH_MAX + + +func _on_sim_tick(_n: int) -> void: + decay += DECAY_PER_TICK + if is_rotting(): + # Bump dirtiness at this tile (Phase 13 hook). +5/h at decay=100 per design.md. + if World.dirtiness_system != null: + World.dirtiness_system.bump(tile, 0.04) # ~+8/in-game-min + if decay >= DECAY_ROTTED: + Audit.log("corpse", "%s rotted away at %s" % [deceased_name, tile]) + EventBus.corpse_rotted_away.emit(self) + queue_free() + + +# ── visual: simple procedural sprite ───────────────────────────────────────── +func _draw() -> void: + # Body color desaturates as decay progresses; turns olive-green when rotting. + var t := clampf(decay / DECAY_ROTTED, 0.0, 1.0) + var fresh := Color(0.70, 0.60, 0.55) + var rotten := Color(0.45, 0.50, 0.30) + var body_color := fresh.lerp(rotten, t) + # Lay-down silhouette: 14×6 rect centered. + draw_rect(Rect2(-7, -3, 14, 6), body_color) + # Head dot + draw_circle(Vector2(-9, 0), 3, deceased_portrait_color.lerp(body_color, 0.3)) + + +# ── save / load ────────────────────────────────────────────────────────────── + +func to_dict() -> Dictionary: + return { + "tile_x": tile.x, + "tile_y": tile.y, + "name": deceased_name, + "color_r": deceased_portrait_color.r, + "color_g": deceased_portrait_color.g, + "color_b": deceased_portrait_color.b, + "decay": decay, + "death_tick": death_tick, + "cause": String(death_cause), + } + + +func from_dict(d: Dictionary) -> void: + tile = Vector2i(int(d.get("tile_x", 0)), int(d.get("tile_y", 0))) + global_position = Vector2(tile.x * 16 + 8, tile.y * 16 + 8) + deceased_name = d.get("name", "") + deceased_portrait_color = Color(d.get("color_r", 1.0), d.get("color_g", 1.0), d.get("color_b", 1.0)) + decay = d.get("decay", 0.0) + death_tick = int(d.get("death_tick", 0)) + death_cause = StringName(d.get("cause", "")) + queue_redraw() diff --git a/scenes/entities/corpse.gd.uid b/scenes/entities/corpse.gd.uid new file mode 100644 index 0000000..513785d --- /dev/null +++ b/scenes/entities/corpse.gd.uid @@ -0,0 +1 @@ +uid://2dj83v6n61fq diff --git a/scenes/entities/corpse.tscn b/scenes/entities/corpse.tscn new file mode 100644 index 0000000..cab3409 --- /dev/null +++ b/scenes/entities/corpse.tscn @@ -0,0 +1,8 @@ +[gd_scene load_steps=2 format=3 uid="uid://corpse_entity"] + +[ext_resource type="Script" path="res://scenes/entities/corpse.gd" id="1_corpse"] + +[node name="Corpse" type="Node2D"] +y_sort_enabled = true +z_index = 4 +script = ExtResource("1_corpse") diff --git a/scenes/entities/cremation_pyre.gd b/scenes/entities/cremation_pyre.gd new file mode 100644 index 0000000..02e5db9 --- /dev/null +++ b/scenes/entities/cremation_pyre.gd @@ -0,0 +1,154 @@ +class_name CremationPyre extends Workbench +## Phase 14 — Cremation pyre furniture. +## +## Subclasses Workbench to reuse the build + bill machinery. The pyre uses a +## special `cremate_corpse` recipe that consumes a Corpse entity (hauled as +## Item.TYPE_CORPSE by the crafting toil's pickup-ingredient step) and 5 wood, +## producing 1 ash item dropped adjacent on completion. +## +## Variant appearance: label_text = "Pyre" triggers the _draw_pyre() branch +## (overrides _draw() in Workbench). accepted_skill = "manual_labor" (any +## laborer can cremate; no Crafting threshold needed). +## +## EventBus.corpse_cremated(corpse, pyre) is emitted on craft completion. +## The Corpse node is queue_free'd after the signal fires. +## +## Stub gap (documented): +## The existing single-ingredient Recipe supports one ingredient_type. +## cremate_corpse needs 1 corpse + 5 wood. This is expressed via +## ingredient2_type / ingredient2_count extended fields on Recipe +## (added in Phase 14 — see recipe.gd). CraftingProvider's ingredient +## pickup step must be updated to check ingredient2 before assigning a +## pawn; until that update lands, the pyre will work as a single-ingredient +## recipe (corpse-only) and the 5-wood secondary requirement is NOT enforced +## at runtime. This is the documented Phase 14 Agent C stub gap. +## +## World registration: shares Workbench.register_workbench / +## unregister_workbench (called by the parent's _ready / _exit_tree). + +## Override label so Workbench._complete() logs "Pyre built at …" +## and _draw() dispatches to _draw_pyre(). +func _init() -> void: + label_text = "Pyre" + accepted_skill = &"manual_labor" + + +func _ready() -> void: + label_text = "Pyre" + accepted_skill = &"manual_labor" + super._ready() + # Auto-populate a default FOREVER bill for the cremate_corpse recipe so + # the pyre is immediately usable once built. + var b := Bill.new() + b.recipe = RecipeCatalog.cremate_corpse() + b.mode = Bill.Mode.FOREVER + bills.append(b) + Audit.log("pyre", "CremationPyre ready at %s — bill added" % tile) + + +# ── craft-cycle hook override ───────────────────────────────────────────────── + +## Called by JobRunner._tick_craft when a cremate_corpse craft completes. +## Drops an ash item adjacent to the pyre, emits corpse_cremated, and frees +## the Corpse entity that was consumed as an ingredient. +## +## The `pawn` argument is the pawn who completed the craft; used only for +## the "cremated_friend" thought signal path in EventBus listeners. +## +## NOTE: The standard Workbench.on_craft_complete() is called by JobRunner +## before this override runs (it clears current_bill / current_work_progress). +## We override at the pyre level to inject the ash-drop + signal + corpse-free +## after the base logic. JobRunner calls on_craft_complete() directly, so we +## shadow it here. +func on_craft_complete() -> void: + # Base Workbench cleanup (clears current_bill, resets work progress). + super.on_craft_complete() + + # Find and consume the corpse that was hauled as ingredient. + var consumed_corpse = _find_consumed_corpse() + + # Drop 1 ash item on an adjacent walkable tile (same pattern as + # Tree.fell() / Workbench output drops elsewhere in Phase 6). + var drop_tile := _pick_adjacent_drop_tile() + if drop_tile != Vector2i(-1, -1): + var ash := load("res://scenes/entities/item.tscn").instantiate() + get_parent().add_child(ash) + ash.setup(Item.TYPE_ASH, 1, drop_tile) + Audit.log("pyre", "Pyre at %s: cremation complete — ash dropped at %s" % [tile, drop_tile]) + else: + Audit.log("pyre", "Pyre at %s: cremation complete — no adjacent tile for ash drop" % tile) + + # Emit and clean up corpse. + if consumed_corpse != null: + Audit.log("pyre", "Pyre at %s: cremated '%s'" % [tile, consumed_corpse.deceased_name]) + EventBus.corpse_cremated.emit(consumed_corpse, self) + consumed_corpse.queue_free() + else: + # Defensive: corpse may have already been freed by decay or another + # system during the crafting window. + Audit.log("pyre", "Pyre at %s: cremation complete but no corpse found (already freed?)" % tile) + + +# ── render ───────────────────────────────────────────────────────────────────── + +## Override Workbench._draw() to dispatch to _draw_pyre() for the "Pyre" label. +func _draw() -> void: + var alpha: float = 1.0 if is_completed() else 0.4 + _draw_pyre(alpha) + + +func _draw_pyre(alpha: float) -> void: + # Simple log-pile silhouette: dark-brown stone base with orange ember + # and ash-grey smoke wisps, suggesting an outdoor funeral pyre. + var base_top := Color(0.30, 0.22, 0.12, alpha) # charred wood / dirt + var base_front := Color(0.22, 0.15, 0.08, alpha) + var ember := Color(0.95, 0.45, 0.10, alpha) + var ash_grey := Color(0.70, 0.68, 0.65, alpha * 0.7) + var outline := Color(0.12, 0.08, 0.04, 0.7 * alpha) + + # Top face — dark charred surface. + draw_rect(Rect2(Vector2(-8.0, -16.0), Vector2(16.0, 5.0)), base_top) + # Front face — very dark wood body. + draw_rect(Rect2(Vector2(-8.0, -11.0), Vector2(16.0, 11.0)), base_front) + # Ember glow — wide orange strip across the front, suggesting hot coals. + draw_rect(Rect2(Vector2(-5.0, -4.0), Vector2(10.0, 3.0)), ember) + # Smoke wisps — three thin vertical rects rising above the top face. + draw_rect(Rect2(Vector2(-3.0, -18.0), Vector2(1.0, 3.0)), ash_grey) + draw_rect(Rect2(Vector2(0.5, -19.0), Vector2(1.0, 4.0)), ash_grey) + draw_rect(Rect2(Vector2(3.0, -17.0), Vector2(1.0, 2.0)), ash_grey) + # Horizon line. + draw_line(Vector2(-8.0, -11.0), Vector2(8.0, -11.0), base_top, 1.0) + # Tile outline. + draw_rect(Rect2(Vector2(-8.0, -16.0), Vector2(16.0, 16.0)), outline, false, 1.0) + + +# ── helpers ─────────────────────────────────────────────────────────────────── + +## Scan World.corpses for the nearest corpse within 2 tiles (the crafting toil +## would have moved it to the pyre tile or an adjacent tile). Returns null if +## none found. +func _find_consumed_corpse(): + var best = null + var best_d: int = 3 # max search radius + for c in World.corpses: + var d: int = abs(c.tile.x - tile.x) + abs(c.tile.y - tile.y) + if d < best_d: + best_d = d + best = c + return best + + +## Return a walkable adjacent tile for the ash drop. Prefers the 4 cardinal +## neighbours in a fixed priority order; falls back to the pyre's own tile if +## all neighbours are blocked. +func _pick_adjacent_drop_tile() -> Vector2i: + var candidates: Array[Vector2i] = [ + tile + Vector2i(1, 0), + tile + Vector2i(-1, 0), + tile + Vector2i(0, 1), + tile + Vector2i(0, -1), + ] + for c in candidates: + if World.pathfinder != null and World.pathfinder.is_walkable(c): + return c + return tile # fallback: drop on the pyre tile itself diff --git a/scenes/entities/cremation_pyre.gd.uid b/scenes/entities/cremation_pyre.gd.uid new file mode 100644 index 0000000..3de539c --- /dev/null +++ b/scenes/entities/cremation_pyre.gd.uid @@ -0,0 +1 @@ +uid://bpa8pfo8b1057 diff --git a/scenes/entities/grave_marker.gd b/scenes/entities/grave_marker.gd new file mode 100644 index 0000000..7b5499d --- /dev/null +++ b/scenes/entities/grave_marker.gd @@ -0,0 +1,104 @@ +class_name GraveMarker extends Node2D +## Phase 14 — permanent grave marker entity. Spawned by GraveSlot.accept_corpse() +## when a corpse is buried. Carries the deceased's identity for the tap-to-inspect +## UI (Phase 17). +## +## Visual: procedural 16×16 stone cross / gravestone (dark grey palette). +## +## Registered with World.register_grave_marker on _ready; unregistered on +## _exit_tree (should never happen in normal play — markers persist for the save). +## +## Save round-trip: to_dict() / from_dict() for Phase 16. The world scene's +## save handler iterates World.grave_markers. +## +## See docs/implementation.md Phase 14 "GraveMarker". + +const TILE_SIZE_PX: int = 16 + +## Tile position — set once at spawn, never changed. +@export var tile: Vector2i = Vector2i.ZERO + +## Deceased identity — mirrored from the Corpse at burial time. +@export var deceased_name: String = "" +@export var deceased_portrait_color: Color = Color(0.70, 0.60, 0.55) + +## Cause of death, carried from Corpse.death_cause. +@export var death_cause: StringName = &"" + +## Sim tick at death (from Corpse.death_tick — NOT the burial tick). +@export var death_tick: int = 0 + + +func _ready() -> void: + World.register_grave_marker(self) + z_index = 2 # above floors, below pawns + + +func _exit_tree() -> void: + World.unregister_grave_marker(self) + + +## One-shot initialiser. Call after add_child() — _ready() fires first. +func setup(p_tile: Vector2i, p_name: String, p_color: Color, p_cause: StringName, p_death_tick: int) -> void: + tile = p_tile + global_position = Vector2(tile.x * TILE_SIZE_PX + TILE_SIZE_PX / 2.0, + tile.y * TILE_SIZE_PX + TILE_SIZE_PX) + deceased_name = p_name + deceased_portrait_color = p_color + death_cause = p_cause + death_tick = p_death_tick + queue_redraw() + Audit.log("grave_marker", "placed at %s for '%s' (cause=%s)" % [tile, deceased_name, death_cause]) + + +# ── visual: procedural gravestone + cross ───────────────────────────────────── + +func _draw() -> void: + # Stone base: dark grey rectangular slab, bottom-anchored like walls. + # Local origin is at tile bottom-centre (matching Wall._draw convention). + var stone_base := Color(0.45, 0.44, 0.42) + var stone_dark := Color(0.30, 0.29, 0.27) + var stone_light := Color(0.62, 0.60, 0.58) + var cross_col := Color(0.25, 0.24, 0.22) + + # Main slab — 10 px wide × 12 px tall, bottom-anchored in the 16×16 cell. + draw_rect(Rect2(-5.0, -13.0, 10.0, 13.0), stone_base) + # Rounded top hint — just a lighter top strip. + draw_rect(Rect2(-5.0, -13.0, 10.0, 3.0), stone_light) + # Left shadow edge. + draw_line(Vector2(-5.0, -13.0), Vector2(-5.0, 0.0), stone_dark, 1.0) + # Cross etched on the slab face: vertical + horizontal bar. + draw_line(Vector2(0.0, -11.0), Vector2(0.0, -3.0), cross_col, 1.5) + draw_line(Vector2(-3.0, -9.0), Vector2(3.0, -9.0), cross_col, 1.5) + # Outline. + draw_rect(Rect2(-5.0, -13.0, 10.0, 13.0), stone_dark, false, 1.0) + + +# ── save / load ────────────────────────────────────────────────────────────── + +func to_dict() -> Dictionary: + return { + "tile_x": tile.x, + "tile_y": tile.y, + "name": deceased_name, + "color_r": deceased_portrait_color.r, + "color_g": deceased_portrait_color.g, + "color_b": deceased_portrait_color.b, + "cause": String(death_cause), + "death_tick": death_tick, + } + + +func from_dict(d: Dictionary) -> void: + tile = Vector2i(int(d.get("tile_x", 0)), int(d.get("tile_y", 0))) + global_position = Vector2(tile.x * TILE_SIZE_PX + TILE_SIZE_PX / 2.0, + tile.y * TILE_SIZE_PX + TILE_SIZE_PX) + deceased_name = d.get("name", "") + deceased_portrait_color = Color( + d.get("color_r", 0.70), + d.get("color_g", 0.60), + d.get("color_b", 0.55) + ) + death_cause = StringName(d.get("cause", "")) + death_tick = int(d.get("death_tick", 0)) + queue_redraw() diff --git a/scenes/entities/grave_marker.gd.uid b/scenes/entities/grave_marker.gd.uid new file mode 100644 index 0000000..ce7ebd9 --- /dev/null +++ b/scenes/entities/grave_marker.gd.uid @@ -0,0 +1 @@ +uid://c8oc06wuoo31w diff --git a/scenes/entities/grave_slot.gd b/scenes/entities/grave_slot.gd new file mode 100644 index 0000000..c2fda65 --- /dev/null +++ b/scenes/entities/grave_slot.gd @@ -0,0 +1,204 @@ +class_name GraveSlot extends Node2D +## Phase 14 — per-tile grave slot entity. Spawned by the designation system when +## the player paints TOOL_DIG_GRAVE. Progresses through a two-state build model: +## +## ghost (BUILD_TICKS not yet reached) +## ↓ ConstructionProvider builds it via on_build_tick() +## dug (open hole, ready for a corpse) +## ↓ HaulingProvider routes a corpse here; accept_corpse() is called +## (GraveSlot queue_free-s itself; GraveMarker spawned at same tile) +## +## Build contract: same duck-type interface as Wall / Floor / Door so that +## ConstructionProvider's untyped iteration in World.build_queue picks it up +## automatically without any dispatch addition. +## site.tile: Vector2i +## site.is_buildable() -> bool +## site.label() -> String +## site.get_path() -> NodePath +## site.blocks_pathing_when_complete() -> bool (returns false — grave stays walkable) +## +## StorageDestination duck-type interface (registered in World.stockpiles): +## accepts(item) -> bool +## find_drop_position(item) -> Vector2i +## covers_tile(tile) -> bool +## is_grave_slot_dug() -> bool (queried by GraveyardZone._find_open_grave_slot) +## +## See docs/implementation.md Phase 14 "GraveSlot". + +const TILE_SIZE_PX: int = 16 + +## Sim ticks to dig the grave (80 ticks ≈ 4 s at 1×). +const BUILD_TICKS: int = 80 + +## Visual colours. +const _GHOST_FILL := Color(0.38, 0.28, 0.16, 0.35) # pale dirt, transparent +const _DUG_FILL := Color(0.28, 0.18, 0.08, 0.85) # dark open earth +const _OUTLINE := Color(0.18, 0.12, 0.06, 0.80) + +## Tile position. +@export var tile: Vector2i = Vector2i.ZERO + +var build_progress: int = 0 +var _dug: bool = false # true once BUILD_TICKS reached (ghost→dug transition) + + +# ── lifecycle ───────────────────────────────────────────────────────────────── + +func _ready() -> void: + # Register as a build site so ConstructionProvider picks it up. + World.register_build_site(self) + # Register as a stockpile destination so HaulingProvider can route corpses here. + World.register_stockpile(self) + z_index = 1 # above terrain, below items + + +func _exit_tree() -> void: + World.unregister_build_site(self) + World.unregister_stockpile(self) + + +# ── public setup ────────────────────────────────────────────────────────────── + +## One-shot initialiser. Call after add_child(). Sets tile + world position. +func setup(p_tile: Vector2i) -> void: + tile = p_tile + # Centre-align within the tile (same convention as Corpse, Item). + global_position = Vector2( + tile.x * TILE_SIZE_PX + TILE_SIZE_PX / 2.0, + tile.y * TILE_SIZE_PX + TILE_SIZE_PX / 2.0 + ) + queue_redraw() + Audit.log("grave_slot", "ghost placed at %s" % tile) + + +# ── ConstructionProvider duck-type interface ────────────────────────────────── + +## True while the slot still needs digging. ConstructionProvider checks this. +func is_buildable() -> bool: + return not _dug + + +## GraveSlot stays walkable after being dug — the pawn stands on it to deposit. +func blocks_pathing_when_complete() -> bool: + return false + + +## Human-readable job label used by ConstructionProvider and Audit logs. +func label() -> String: + return "grave" + + +## Called by the BUILD toil in JobRunner once per sim tick while the pawn digs. +func on_build_tick() -> void: + if _dug: + return + build_progress += 1 + queue_redraw() + if build_progress >= BUILD_TICKS: + _complete_dig() + + +## True once the slot has finished the ghost-phase (for World._on_designation_cleared). +func is_completed() -> bool: + return _dug + + +# ── StorageDestination duck-type interface ──────────────────────────────────── + +## Returns true if this slot is dug (open) and ready to accept a corpse. +## GraveyardZone calls this to verify an open slot exists in the region. +func is_grave_slot_dug() -> bool: + return _dug + + +## Returns true if `item` is a Corpse entity AND this slot is dug. +func accepts(item) -> bool: + if not _dug: + return false + return item.has_method("get_item_type") and item.get_item_type() == &"corpse" + + +## Returns the slot's own tile if it is dug and available; Vector2i(-1,-1) otherwise. +func find_drop_position(item) -> Vector2i: + if not accepts(item): + return Vector2i(-1, -1) + return tile + + +## True when `p_tile` matches this slot's tile. +func covers_tile(p_tile: Vector2i) -> bool: + return p_tile == tile + + +## Priority mirrors StorageDestination enum so HaulingProvider's priority +## comparison works cleanly. NORMAL for grave slots. +var priority: int = StorageDestination.Priority.NORMAL + + +# ── burial ───────────────────────────────────────────────────────────────────── + +## Called by JobRunner._tick_deposit_corpse when a pawn has carried a corpse +## here and is standing on this tile. Instantiates a GraveMarker at this tile, +## emits EventBus.corpse_buried, then frees both the corpse and this slot. +func accept_corpse(corpse, world_parent: Node) -> void: + if not _dug: + Audit.log("grave_slot", "accept_corpse called before slot is dug at %s — ignoring" % tile) + return + + Audit.log("grave_slot", "burying '%s' at %s" % [corpse.deceased_name, tile]) + + # Spawn permanent GraveMarker. + var marker_script: Script = load("res://scenes/entities/grave_marker.gd") + var marker := Node2D.new() + marker.set_script(marker_script) + marker.name = "GraveMarker_%s_%s" % [tile.x, tile.y] + world_parent.add_child(marker) + marker.setup(tile, corpse.deceased_name, corpse.deceased_portrait_color, + corpse.death_cause, corpse.death_tick) + + Audit.log("grave_slot", "marker placed for '%s' (cause=%s death_tick=%d)" % [ + corpse.deceased_name, corpse.death_cause, corpse.death_tick + ]) + + EventBus.corpse_buried.emit(corpse, marker) + + # Free the corpse and the slot — marker persists. + corpse.queue_free() + queue_free() + + +# ── visual ──────────────────────────────────────────────────────────────────── + +func _draw() -> void: + # Drawn centred in tile (origin = tile centre). + if _dug: + _draw_open_grave() + else: + _draw_ghost() + + +func _draw_ghost() -> void: + # Transparent dashed outline: dug-grave shape as a ghost. + draw_rect(Rect2(-6.0, -4.0, 12.0, 8.0), _GHOST_FILL, true) + draw_rect(Rect2(-6.0, -4.0, 12.0, 8.0), Color(_OUTLINE.r, _OUTLINE.g, _OUTLINE.b, 0.40), false, 1.0) + # Progress bar — thin strip across bottom. + if BUILD_TICKS > 0 and build_progress > 0: + var pct := float(build_progress) / float(BUILD_TICKS) + var bar_w := 12.0 * pct + draw_rect(Rect2(-6.0, 3.0, bar_w, 1.5), Color(0.6, 0.5, 0.3, 0.6), true) + + +func _draw_open_grave() -> void: + # Dark open pit: recessed rectangle to suggest depth. + draw_rect(Rect2(-6.0, -4.0, 12.0, 8.0), _DUG_FILL, true) + # Lighter near-edge to suggest rim of earth. + draw_rect(Rect2(-6.0, -4.0, 12.0, 2.0), Color(0.45, 0.33, 0.18, 0.70), true) + draw_rect(Rect2(-6.0, -4.0, 12.0, 8.0), _OUTLINE, false, 1.0) + + +# ── internal ───────────────────────────────────────────────────────────────── + +func _complete_dig() -> void: + _dug = true + queue_redraw() + Audit.log("grave_slot", "grave dug at %s (ready for burial)" % tile) diff --git a/scenes/entities/grave_slot.gd.uid b/scenes/entities/grave_slot.gd.uid new file mode 100644 index 0000000..576db6b --- /dev/null +++ b/scenes/entities/grave_slot.gd.uid @@ -0,0 +1 @@ +uid://5g5j6rjof8rf diff --git a/scenes/entities/item.gd b/scenes/entities/item.gd index 04906f9..5ffe270 100644 --- a/scenes/entities/item.gd +++ b/scenes/entities/item.gd @@ -43,6 +43,9 @@ const TYPE_STONE_BLOCK: StringName = &"stone_block" const TYPE_FLOUR: StringName = &"flour" const TYPE_BREAD: StringName = &"bread" +# Phase 14 — cremation output. One ash item drops per cremated corpse. +const TYPE_ASH: StringName = &"ash" + const ALL_TYPES: Array[StringName] = [ TYPE_WOOD, TYPE_STONE, TYPE_IRON_ORE, TYPE_COPPER_ORE, TYPE_SILVER, TYPE_GOLD, TYPE_CLOTH, TYPE_VEGETABLE, @@ -50,6 +53,7 @@ const ALL_TYPES: Array[StringName] = [ TYPE_TOOL, TYPE_WEAPON, TYPE_ARMOR, TYPE_CORPSE, TYPE_PLANK, TYPE_STONE_BLOCK, TYPE_FLOUR, TYPE_BREAD, + TYPE_ASH, ] # ── quality system (docs/architecture.md "Quality system") ─────────────────── diff --git a/scenes/pawn/pawn.gd b/scenes/pawn/pawn.gd index e4a948a..dfddbf6 100644 --- a/scenes/pawn/pawn.gd +++ b/scenes/pawn/pawn.gd @@ -23,6 +23,9 @@ extends Node2D class_name Pawn +## Phase 14 — corpse scene instantiated on death. +const CORPSE_SCENE: PackedScene = preload("res://scenes/entities/corpse.tscn") + const STEP_TICKS: int = 10 const TILE_SIZE_PX: int = 16 # Mirrors World.TILE_SIZE_PX; standalone so Pawn needs no World reference. @@ -123,6 +126,22 @@ var sulking: bool = false # Phase 9 — HP (design.md "Single HP per pawn", default 100). var hp: float = HP_MAX +# Phase 14 — body colour derived once from the pawn's name hash (same formula +# as _draw() used to compute inline). Stored so the Corpse entity can carry it +# for its head-dot visual without access to the living pawn. +var portrait_color: Color = Color.WHITE + +# Phase 14 — last named damage source passed to take_damage(); used by +# _check_death() to label the corpse cause when bleeding is not active. +var _last_damage_source: StringName = &"" + +# Phase 14 — bleed-out timeout counter. Increments each sim tick while the +# pawn has a Bleeding status AND is still alive (HP > 0). Resets when the +# Bleeding status is cleared. If this reaches StatusCatalog.BLEED_OUT_TICKS +# (432000 ticks ≈ 6 in-game hours) and no doctor has treated the pawn, a +# lethal take_damage() call forces _check_death(). +var _bleed_ticks: int = 0 + # Phase 9 — active status effects. Do not mutate directly — use add_status() / # remove_status_by_id() which emit EventBus signals and enforce stack-merge logic. var statuses: Array = [] # Array[Status] @@ -158,6 +177,13 @@ func _ready() -> void: for skill in ALL_SKILLS: if not skills.has(skill): skills[skill] = 0 + # Phase 14 — connect to burial / cremation signals for closure thoughts. + # Defensive: signals are declared in EventBus Phase 14 block; guard for + # environments where a pre-Phase-14 shim might be in use. + if EventBus.has_signal("corpse_buried"): + EventBus.corpse_buried.connect(_on_corpse_buried) + if EventBus.has_signal("corpse_cremated"): + EventBus.corpse_cremated.connect(_on_corpse_cremated) func setup(p_name: String, start_tile: Vector2i) -> void: @@ -166,6 +192,10 @@ func setup(p_name: String, start_tile: Vector2i) -> void: position = _tile_to_world(tile) _name_label.text = pawn_name _state_label.text = Strings.t(&"pawn.state.idle") + # Phase 14 — compute portrait_color once so Corpse can carry it. + # Same formula as _draw() body disc: deterministic hue from name hash. + var hue := float(pawn_name.hash() % 360) / 360.0 + portrait_color = Color.from_hsv(hue, 0.7, 0.85) Audit.log("pawn", "%s spawned at %s" % [pawn_name, start_tile]) @@ -245,12 +275,17 @@ func set_sleep(value: float) -> void: ## Reduce HP by amount, clamped to [0, HP_MAX]. Emits pawn_took_damage. ## Pass a non-empty source string for Audit context (e.g. "bleeding", "wolf bite"). ## Does NOT log per-tick bleed ticks — only logs on direct named calls. -func take_damage(amount: float, source: String = "") -> void: +## Phase 14: tracks _last_damage_source for corpse cause labelling; calls +## _check_death() after _check_downed() so death is detected on the same tick. +func take_damage(amount: float, source: StringName = &"") -> void: hp = maxf(0.0, hp - amount) + if source != &"": + _last_damage_source = source EventBus.pawn_took_damage.emit(self, amount) - if source != "": + if source != &"": Audit.log("pawn", "%s took %.1f damage from '%s' (hp=%.1f)" % [pawn_name, amount, source, hp]) _check_downed() + _check_death() ## Restore HP by amount, clamped to [0, HP_MAX]. Checks revive condition. @@ -317,6 +352,60 @@ func _check_revive() -> void: Audit.log("pawn", "%s revived from Downed (hp=%.1f)" % [pawn_name, hp]) +# ── death (Phase 14) ───────────────────────────────────────────────────────── + +## True when the pawn's HP has reached zero. +func is_dead() -> bool: + return hp <= 0.0 + + +## Internal: detect death and run the corpse-spawn pipeline. +## Called by take_damage() after _check_downed(), and by _process_statuses() +## after the bleed-out timeout fires. +## +## Re-entrant guard: returns immediately if hp > 0 or node is already freed. +## +## Pipeline (in order): +## 1. Determine cause (bleeding > _last_damage_source > "unknown"). +## 2. Audit.log the death event. +## 3. Emit EventBus.pawn_died BEFORE removal so listeners see a valid pawn. +## 4. Spawn Corpse at death tile; call setup() then add_child() on parent. +## 5. Emit EventBus.corpse_spawned so hauling + UI systems react. +## 6. Unregister from World.pawns; queue_free() this node. +func _check_death() -> void: + if not is_dead(): + return + # Guard against re-entrant calls (bleed tick and take_damage on the same tick). + if is_queued_for_deletion(): + return + + # Determine cause of death. + var cause: StringName + if has_status(&"bleeding"): + cause = &"bleeding" + elif _last_damage_source != &"": + cause = _last_damage_source + else: + cause = &"unknown" + + Audit.log("pawn", "%s DIED (cause=%s, tile=%s)" % [pawn_name, cause, tile]) + + # Notify listeners before the pawn is removed (e.g. future "saw colonist die" mood thought). + EventBus.pawn_died.emit(self, cause) + + # Spawn corpse at the death tile. get_parent() is the World scene root, + # same as the WolfSpawner pattern — no get_node("/root/...") smell. + var corpse: Corpse = CORPSE_SCENE.instantiate() + corpse.setup(tile, pawn_name, portrait_color, cause) + get_parent().add_child(corpse) + Audit.log("pawn", "corpse spawned for %s at %s" % [pawn_name, tile]) + EventBus.corpse_spawned.emit(corpse) + + # Remove from World registry before freeing; _exit_tree on Corpse handles corpse registration. + World.unregister_pawn(self) + queue_free() + + ## Returns the pawn's current level (0–10) for the given skill. ## Returns 0 for unknown skills so callers need no nil-guard. func get_skill(skill: StringName) -> int: @@ -409,6 +498,8 @@ func _process_thoughts() -> void: # Phase 13 — room beauty and dirtiness thoughts. # Defensive: World.room_at_tile returns null if rooms are empty (Agent A may land later). _sync_room_thoughts() + # Phase 14 — corpse proximity and colony-wide rotting thoughts. + _sync_corpse_thoughts() # 3. Recompute if EVENT thoughts expired (persistent syncs call _recompute_mood internally). if dirty: _recompute_mood() @@ -472,6 +563,73 @@ func _sync_room_thoughts() -> void: _sync_persistent_thought(&"clean_room", is_clean, ThoughtCatalog.clean_room()) +## Phase 14 — sync corpse-related thoughts each sim tick. +## +## saw_corpse (EVENT): fires when any corpse is within 5 Manhattan tiles and +## the pawn doesn't already have this thought (natural EVENT decay handles +## the refresh window; do not re-add while it is still ticking). +## +## rotting_body_in_colony (PERSISTENT): synced from World.corpses. After +## sync, the existing thought's stacks are updated to match the rotting +## count (capped at max_stacks=3) so severity scales with corpse count. +func _sync_corpse_thoughts() -> void: + # saw_corpse — scan for any corpse within 5 Manhattan tiles. + if not has_thought(&"saw_corpse"): + for c in World.corpses: + var d: int = abs(c.tile.x - tile.x) + abs(c.tile.y - tile.y) + if d <= 5: + add_thought(ThoughtCatalog.saw_corpse()) + Audit.log("pawn", "%s: saw_corpse thought added (corpse '%s' at dist %d)" % [pawn_name, c.deceased_name, d]) + break # One add per tick — stacks via add_thought merge on next sighting + + # rotting_body_in_colony — PERSISTENT, severity scales with rotting count. + var rotting_count: int = _count_rotting_corpses() + _sync_persistent_thought(&"rotting_body_in_colony", rotting_count > 0, ThoughtCatalog.rotting_body_in_colony()) + if rotting_count > 0 and has_thought(&"rotting_body_in_colony"): + for t in thoughts: + if t.id == &"rotting_body_in_colony": + t.stacks = mini(rotting_count, t.max_stacks) + break + + +## Returns the count of corpses in World.corpses that are currently rotting. +func _count_rotting_corpses() -> int: + var count: int = 0 + for c in World.corpses: + if c.is_rotting(): + count += 1 + return count + + +## Phase 14 — fires when EventBus.corpse_buried is emitted (Agent B). +## Gives the buried_friend thought if this pawn was nearby (8 tiles). +## Defensive: marker may be null or lack expected fields if Agent B's +## GraveMarker shape differs; access only via null-safe .get() checks. +func _on_corpse_buried(corpse, marker) -> void: + if corpse == null: + return + # Prefer the marker's tile for the burial site; fall back to corpse tile. + var burial_tile: Vector2i = corpse.tile + if marker != null and marker.get("tile") != null: + burial_tile = marker.tile + var dist: int = abs(burial_tile.x - tile.x) + abs(burial_tile.y - tile.y) + if dist <= 8: + add_thought(ThoughtCatalog.buried_friend()) + Audit.log("pawn", "%s: buried_friend thought added (burial at %s, dist=%d)" % [pawn_name, burial_tile, dist]) + + +## Phase 14 — fires when EventBus.corpse_cremated is emitted (CremationPyre). +## Gives the cremated_friend thought if this pawn was nearby (8 tiles). +func _on_corpse_cremated(corpse, pyre) -> void: + if pyre == null: + return + var pyre_tile: Vector2i = pyre.tile if pyre.get("tile") != null else Vector2i(-999, -999) + var dist: int = abs(pyre_tile.x - tile.x) + abs(pyre_tile.y - tile.y) + if dist <= 8: + add_thought(ThoughtCatalog.cremated_friend()) + Audit.log("pawn", "%s: cremated_friend thought added (pyre at %s, dist=%d)" % [pawn_name, pyre_tile, dist]) + + ## Add or remove a PERSISTENT thought based on a boolean state flag. ## Calls add_thought() / remove_thought_by_id() (which recompute mood) only ## when the presence actually needs to change — avoids redundant recomputes. @@ -522,11 +680,18 @@ func _process_sulking() -> void: ## Sequence: ## 1. Decay EVENT statuses — remove expired ones. ## 2. Apply per-tick effects (Bleeding drains HP). -## 3. Phase 12 — tick wet / cold accumulators and sync statuses. +## 3. Phase 14 — bleed-out timeout: if a pawn has been bleeding for +## StatusCatalog.BLEED_OUT_TICKS (432000 ticks ≈ 6 in-game hours) with +## no doctor treating them, force-kill via take_damage(hp) to trigger +## _check_death(). _bleed_ticks resets when the Bleeding status is cleared +## (i.e. when a doctor successfully treats the wound). +## 4. Phase 14 — check death from bleed damage (hp reached 0 this tick). +## 5. Phase 12 — tick wet / cold accumulators and sync statuses. ## ## Bleeding does NOT log per-tick — would flood Audit. Named-source logging ## happens in take_damage() only when source is non-empty. func _process_statuses() -> void: + var was_bleeding := false for i in range(statuses.size() - 1, -1, -1): var s: Status = statuses[i] # 1. Decay EVENT statuses. @@ -537,11 +702,26 @@ func _process_statuses() -> void: continue # 2. Apply per-tick effects. if s.kind == Status.Kind.BLEEDING: + was_bleeding = true # No source string to suppress per-tick Audit flood. hp = maxf(0.0, hp - StatusCatalog.BLEED_HP_PER_TICK * float(s.severity)) EventBus.pawn_took_damage.emit(self, StatusCatalog.BLEED_HP_PER_TICK * float(s.severity)) _check_downed() - # 3. Phase 12 — wet / cold environment exposure. + # 3. Phase 14 — bleed-out timeout. + # Design note: BLEED_OUT_TICKS = 432000 ≈ 6 in-game hours at 20 Hz. + # Simplified: death-by-bleed = hp ≤ 0 path through _check_death() handles + # the moment-of-death case; the _bleed_ticks timer is the "long neglect" + # safety net that prevents an immortal downed pawn when bleed rate is low. + if was_bleeding: + _bleed_ticks += 1 + if _bleed_ticks >= StatusCatalog.BLEED_OUT_TICKS: + Audit.log("pawn", "%s bleed-out timeout after %d ticks" % [pawn_name, _bleed_ticks]) + take_damage(hp, &"bleed_out") # lethal; triggers _check_death() + else: + _bleed_ticks = 0 # reset when bleeding is cleared (doctor treated) + # 4. Phase 14 — detect death from bleed tick this frame (hp → 0 via bleeding). + _check_death() + # 5. Phase 12 — wet / cold environment exposure. _tick_wet() _tick_cold() @@ -716,6 +896,9 @@ func to_dict() -> Dictionary: # Phase 12 — wet / cold accumulators. Default 0 for pre-Phase-12 save compat. "wet_accum": _wet_accum, "cold_accum": _cold_accum, + # Phase 14 — bleed-out timeout counter. Default 0 for pre-Phase-14 saves. + "bleed_ticks": _bleed_ticks, + "last_damage_source": String(_last_damage_source), } @@ -766,6 +949,13 @@ func from_dict(d: Dictionary) -> void: _wet_accum = clampf(float(d.get("wet_accum", 0.0)), 0.0, 100.0) _cold_accum = clampf(float(d.get("cold_accum", 0.0)), 0.0, 100.0) + # Phase 14 — restore bleed-out counter and last damage source. + _bleed_ticks = int(d.get("bleed_ticks", 0)) + _last_damage_source = StringName(d.get("last_damage_source", "")) + # Recompute portrait_color from pawn_name (same formula as setup()). + var pc_hue := float(pawn_name.hash() % 360) / 360.0 + portrait_color = Color.from_hsv(pc_hue, 0.7, 0.85) + # Restore skills — set directly on the dict to bypass the ALL_SKILLS assert # (from_dict must be resilient to saves that pre-date a new skill being added). var saved_skills: Variant = d.get("skills") @@ -847,10 +1037,10 @@ func _process(_delta: float) -> void: func _draw() -> void: - # Body disc — colour derived deterministically from pawn name so each pawn - # is visually distinct without any art dependency. - var hue := float(pawn_name.hash() % 360) / 360.0 - var body_colour := Color.from_hsv(hue, 0.7, 0.85) + # Phase 14 — use the stored portrait_color (computed once in setup()/from_dict()). + # This is the same formula as the old inline hue derivation; consolidating here + # removes the duplication and ensures the corpse head-dot matches exactly. + var body_colour := portrait_color if is_downed(): # Phase 9 — Downed pawn: rotated 90° (lying on ground) + desaturated. diff --git a/scenes/world/designation.gd b/scenes/world/designation.gd index 2b01ef2..57dd283 100644 --- a/scenes/world/designation.gd +++ b/scenes/world/designation.gd @@ -20,16 +20,23 @@ const TOOL_BUILD_DOOR: StringName = &"build_door" # Phase 13 — no-roof designation: painted tiles become courtyards; RoomDetector # excludes them from auto-roofing. Calls World.toggle_no_roof_at() on apply. const TOOL_NO_ROOF: StringName = &"no_roof" +# Phase 14 — graveyard zone paint: marks a region as a corpse-only storage zone. +const TOOL_GRAVEYARD: StringName = &"graveyard" +# Phase 14 — dig grave: queues a GraveSlot build job at the painted tile. +const TOOL_DIG_GRAVE: StringName = &"dig_grave" # Atlas coords on the shared placeholder tileset (source 0). # build_wall → stone-grey (2, 0); build_floor → dirt-brown (1, 0). # build_door → dark stone (3, 0) so the ghost reads visually distinct from walls. # no_roof → grass (0, 0) with the designation layer modulate tinting it visibly. +# graveyard / dig_grave → dirt-brown (1, 0); modulate tints these dark brown. const _ATLAS_BY_TOOL: Dictionary = { &"build_wall": Vector2i(2, 0), &"build_floor": Vector2i(1, 0), &"build_door": Vector2i(3, 0), &"no_roof": Vector2i(0, 0), + &"graveyard": Vector2i(1, 0), + &"dig_grave": Vector2i(1, 0), } # Placeholder source ID — mirrors World.PLACEHOLDER_SOURCE_ID. @@ -68,7 +75,8 @@ func bind(paint_layer: TileMapLayer, selection: Selection = null) -> void: ## Activate a paint tool. Pass TOOL_NONE to deactivate. func set_active_tool(tool: StringName) -> void: assert( - tool in [TOOL_NONE, TOOL_BUILD_WALL, TOOL_BUILD_FLOOR, TOOL_BUILD_DOOR, TOOL_NO_ROOF], + tool in [TOOL_NONE, TOOL_BUILD_WALL, TOOL_BUILD_FLOOR, TOOL_BUILD_DOOR, + TOOL_NO_ROOF, TOOL_GRAVEYARD, TOOL_DIG_GRAVE], "Designation.set_active_tool: unknown tool '%s'" % tool ) _tool = tool diff --git a/scenes/world/graveyard_zone.gd b/scenes/world/graveyard_zone.gd new file mode 100644 index 0000000..c546443 --- /dev/null +++ b/scenes/world/graveyard_zone.gd @@ -0,0 +1,108 @@ +class_name GraveyardZone extends StorageDestination +## Phase 14 — Graveyard floor zone. Accepts corpses only. +## +## Structurally identical to StockpileZone but locked to Item.TYPE_CORPSE. +## The `accepts()` override adds a Corpse type-check so Items of type &"corpse" +## that are NOT Corpse entities never match (belt-and-suspenders). +## +## Visual: darker brownish overlay (brown-grey to read as turned earth) vs the +## yellow-tinted StockpileZone overlay. +## +## One slot per tile — corpses are large; one per cell mirrors design.md. +## +## Register/unregister with World.stockpiles happen automatically in +## _ready / _exit_tree — no external wiring needed. +## +## See docs/implementation.md Phase 14 "GraveyardZone". + +## Region in tile coordinates. +@export var region: Rect2i = Rect2i(0, 0, 4, 4) + +## Player-visible label shown in zone inspect UI (Phase 17). +@export var label: String = "Graveyard" + +const _TILE_PX: int = 16 + +## Earthen-brown fill at two priority extremes — graveyard zones are fixed +## priority NORMAL; other Priority values are valid but unlikely to be set by +## the player in Phase 14. Tint distinguishes from StockpileZone yellow. +const _FILL_COLOR: Color = Color(0.40, 0.28, 0.18, 0.18) # dark earth brown +const _BORDER_COLOR: Color = Color(0.30, 0.20, 0.12, 0.55) # deeper border + + +func _ready() -> void: + z_index = -1 + accepted_types = [Item.TYPE_CORPSE] + World.register_stockpile(self) + queue_redraw() + + +func _exit_tree() -> void: + World.unregister_stockpile(self) + + +# ── StorageDestination overrides ───────────────────────────────────────────── + +func accepts(item) -> bool: + if priority == StorageDestination.Priority.OFF: + return false + # Must be type corpse AND an actual Corpse entity (not a regular Item). + if not item.has_method("get_item_type"): + return false + if item.get_item_type() != Item.TYPE_CORPSE: + return false + # Only accept if there is a dug GraveSlot at an open tile in our region. + return _find_open_grave_slot() != null + + +func covers_tile(tile: Vector2i) -> bool: + return region.has_point(tile) + + +## Scan region for an open dug GraveSlot. Returns the slot or null. +## "Open" means the slot is in DUG state (not yet occupied / being hauled to). +func find_drop_position(item) -> Vector2i: + if not accepts(item): + return Vector2i(-1, -1) + var slot = _find_open_grave_slot() + if slot == null: + return Vector2i(-1, -1) + return slot.tile + + +# ── drawing ─────────────────────────────────────────────────────────────────── + +func _draw() -> void: + var tile_px := float(_TILE_PX) + var rect_px := Rect2( + Vector2(region.position) * tile_px, + Vector2(region.size) * tile_px + ) + draw_rect(rect_px, _FILL_COLOR, true) + draw_rect(rect_px, _BORDER_COLOR, false, 1.0) + + # Small cross marker in the top-left corner of the zone as a visual cue. + var cross_center := Vector2(region.position) * tile_px + Vector2(tile_px * 0.5, tile_px * 0.5) + var cross_color := Color(_BORDER_COLOR.r, _BORDER_COLOR.g, _BORDER_COLOR.b, 0.70) + draw_line(cross_center + Vector2(0.0, -4.0), cross_center + Vector2(0.0, 4.0), cross_color, 1.5) + draw_line(cross_center + Vector2(-3.0, -1.5), cross_center + Vector2(3.0, -1.5), cross_color, 1.5) + + +# ── internal ───────────────────────────────────────────────────────────────── + +## Returns the first GraveSlot within the region that is in DUG state and not +## already being hauled to. Returns null if none found. +func _find_open_grave_slot(): + for x in range(region.position.x, region.position.x + region.size.x): + for y in range(region.position.y, region.position.y + region.size.y): + var cell := Vector2i(x, y) + # Look for a GraveSlot in World.stockpiles that covers this cell + # and is in DUG state. + for dest in World.stockpiles: + if dest == self: + continue + if not dest.has_method("is_grave_slot_dug"): + continue + if dest.covers_tile(cell) and dest.is_grave_slot_dug(): + return dest + return null diff --git a/scenes/world/graveyard_zone.gd.uid b/scenes/world/graveyard_zone.gd.uid new file mode 100644 index 0000000..ac8dc50 --- /dev/null +++ b/scenes/world/graveyard_zone.gd.uid @@ -0,0 +1 @@ +uid://d368k7d64gc3h diff --git a/scenes/world/storage_destination.gd b/scenes/world/storage_destination.gd index 140edff..5b61140 100644 --- a/scenes/world/storage_destination.gd +++ b/scenes/world/storage_destination.gd @@ -65,9 +65,21 @@ func covers_tile(tile: Vector2i) -> bool: ## Priority-and-filter gate, shared by all subclasses. ## Returns false when OFF or when the item's type is not in accepted_types. ## accepted_types.is_empty() is the wildcard "accept any type" case. +## Resolves item_type defensively — Corpse entities expose get_item_type() +## rather than a plain .item_type property; both are handled here. func _filter_accepts(item) -> bool: if priority == Priority.OFF: return false if accepted_types.is_empty(): return true - return item.item_type in accepted_types + # Resolve the type string defensively: prefer .item_type property, fall back + # to get_item_type() for Corpse entities (Phase 14). + var type: StringName + var t = item.get("item_type") + if t != null: + type = t + elif item.has_method("get_item_type"): + type = item.get_item_type() + else: + return false + return type in accepted_types diff --git a/scenes/world/world.gd b/scenes/world/world.gd index 4bdb116..bb20ac4 100644 --- a/scenes/world/world.gd +++ b/scenes/world/world.gd @@ -21,6 +21,9 @@ const BEAUTY_SYSTEM_SCRIPT: Script = preload("res://scenes/world/beauty_system.g const DIRTINESS_SYSTEM_SCRIPT: Script = preload("res://scenes/world/dirtiness_system.gd") const CLEANING_PROVIDER_SCRIPT: Script = preload("res://scenes/ai/cleaning_provider.gd") const INDOOR_TINT_SCRIPT: Script = preload("res://scenes/world/indoor_tint_overlay.gd") +# Phase 14 — grave / burial entities (scripts only; no .tscn needed). +const GRAVEYARD_ZONE_SCRIPT: Script = preload("res://scenes/world/graveyard_zone.gd") +const GRAVE_SLOT_SCRIPT: Script = preload("res://scenes/entities/grave_slot.gd") const PAWN_SCENE: PackedScene = preload("res://scenes/pawn/pawn.tscn") const TREE_SCENE: PackedScene = preload("res://scenes/entities/tree.tscn") const ROCK_SCENE: PackedScene = preload("res://scenes/entities/rock.tscn") @@ -35,6 +38,13 @@ const ITEM_SCENE: PackedScene = preload("res://scenes/entities/item.tscn") const BED_SCENE: PackedScene = preload("res://scenes/entities/bed.tscn") const TORCH_SCENE: PackedScene = preload("res://scenes/entities/torch.tscn") +# Phase 14 — demo auto-kill toggle. +## Set to true to force-kill the first pawn 50 ticks after boot so MCP runtime +## tests can observe the full death → corpse pipeline at startup. +## LEAVE FALSE for normal play — a colonist dies every session otherwise. +## To enable for a test session: edit this constant, run, revert when done. +const DEMO_PHASE14_AUTOKILL: bool = false + # 3 starting pawns — Phase 2 demo. Phase 7+ replaces this with map-gen + name table. const SAMPLE_PAWNS: Array[Dictionary] = [ # Phase 6 demo — varied Crafting skill so the quality system shows visible @@ -205,6 +215,10 @@ func _ready() -> void: _apply_season_tint(Clock.current_season()) EventBus.season_changed.connect(_apply_season_tint) + # Phase 14 — demo auto-kill (disabled by default — see DEMO_PHASE14_AUTOKILL). + if DEMO_PHASE14_AUTOKILL: + EventBus.sim_tick.connect(_demo_phase14_autokill_hook) + func world_bounds_px() -> Rect2: return Rect2(Vector2.ZERO, Vector2(MAP_SIZE_TILES * TILE_SIZE_PX)) @@ -541,6 +555,25 @@ func _on_designation_added(cell: Vector2i, tool: StringName) -> void: entity = DOOR_SCENE.instantiate() add_child(entity) entity.setup(cell) + # Phase 14 — graveyard zone: paint a single-cell GraveyardZone. + # The zone is 1×1 and re-uses the same region as the painted cell. + &"graveyard": + var gz := Node2D.new() + gz.set_script(GRAVEYARD_ZONE_SCRIPT) + gz.name = "GraveyardZone_%d_%d" % [cell.x, cell.y] + add_child(gz) + gz.region = Rect2i(cell.x, cell.y, 1, 1) + gz.label = "Graveyard" + gz.queue_redraw() + entity = gz + # Phase 14 — dig grave: spawn a GraveSlot ghost and queue it for build. + &"dig_grave": + var gs := Node2D.new() + gs.set_script(GRAVE_SLOT_SCRIPT) + gs.name = "GraveSlot_%d_%d" % [cell.x, cell.y] + add_child(gs) + gs.setup(cell) + entity = gs _: Audit.log("world", "unknown designation tool: %s" % tool) return @@ -553,7 +586,13 @@ func _on_designation_cleared(cell: Vector2i) -> void: return var entity = _build_sites_by_tile[cell] _build_sites_by_tile.erase(cell) - if is_instance_valid(entity) and not entity.is_completed(): + if not is_instance_valid(entity): + return + # For build-queue entities (Wall, Floor, Door, GraveSlot): only free if not + # yet completed (a completed wall should not be torn down by a cancel signal). + # For zone-overlay entities (GraveyardZone) that have no is_completed(): always free. + var can_complete: bool = entity.has_method("is_completed") + if not can_complete or not entity.is_completed(): entity.queue_free() @@ -685,6 +724,24 @@ func _run_pathfinder_spike() -> void: ]) +# ── Phase 14: demo auto-kill hook ─────────────────────────────────────────── + +## Connected to EventBus.sim_tick when DEMO_PHASE14_AUTOKILL is true. +## Force-kills the first pawn 50 ticks after boot so the death→corpse pipeline +## can be tested in a normal play session. LEAVE DEMO_PHASE14_AUTOKILL = false +## for normal play. +func _demo_phase14_autokill_hook(tick_n: int) -> void: + if tick_n != 50: + return + if World.pawns.is_empty(): + return + var victim = World.pawns[0] + if victim.has_method("take_damage"): + Audit.log("world", "phase 14 demo: force-killing '%s' at tick %d" % [victim.pawn_name, tick_n]) + victim.take_damage(victim.hp, &"demo_kill") + EventBus.sim_tick.disconnect(_demo_phase14_autokill_hook) + + # ── camera bounds ─────────────────────────────────────────────────────────── func _apply_camera_bounds() -> void: