Phase 5 — Designation, BuildJob, Wall/Floor/Door, Crate; 3/4 perspective pivot

Three gdscript-refactor agents in parallel + Opus integration.

Architectural pivot (memory.md Decisions table updated):
- View: top-down grid for gameplay + 3/4-perspective rendering for vertical
  structures (Stardew/Going Medieval style). Walls/doors/crates are Y-sorted
  entity sprites, not TileMap cells.
- Wall TileMap layer (Layer 2) becomes data-only — used for room detection,
  roof BFS, save serialization. Visual rendering happens at entity level.
- Asset reality check baked into the decision: the entire asset library is
  RPG-style perspective art; pivoting the renderer is cheaper than authoring
  or commissioning top-down 47-tile autotile sets.

Designation paint (scenes/world/, Agent A — ~170 lines):
- class_name Designation extends Node, lives as DesignationCtl child of World
- TOOL_NONE / TOOL_BUILD_WALL / TOOL_BUILD_FLOOR
- _unhandled_input captures left-mouse press/drag/release
- Drag-paints ghost tiles on Layer 3 via paint_layer.set_cell
- Green/red modulate based on World.pathfinder.is_walkable + cell occupancy
- Emits EventBus.designation_added/cleared per cell
- Selection.designation_active guard prevents double-handling clicks

EventBus signals added:
- designation_added(cell: Vector2i, tool: StringName)
- designation_cleared(cell: Vector2i)

BuildJob + Wall/Floor/Door entities (scenes/ai/ + scenes/entities/, Agent B — ~530 lines):
- Toil.KIND_BUILD + Toil.build_at(target_path) factory
- JobRunner._tick_build: resolves NodePath target, calls on_build_tick() per
  sim tick, marks toil done when is_buildable() returns false
- ConstructionProvider (priority=6, highest): nearest is_buildable() site in
  World.build_queue → Job=[walk_to(site.tile), build_at(site.get_path())]
- Wall entity: BUILD_TICKS=100, 40% alpha ghost; _complete() calls
  pathfinder.set_cell_walkable(false) + World.mark_wall_tile + Audit.log
- Floor entity: BUILD_TICKS=30, ground-level (no y_sort), does NOT block
  pathfinding, calls mark_floor_tile on complete
- Door entity: BUILD_TICKS=80, bottom-anchored, walkable when built (no
  pathfinder block); registers with World.doors for Phase 7 open/close logic
- ALL wall/door scenes have y_sort_enabled=true on root; floors don't (always
  on ground plane)

Crate furniture (scenes/world/, Agent C — ~270 lines):
- class_name Crate extends StorageDestination (Phase 4's abstract base)
- CAPACITY=4 stacks; accepts() gates on _completed + _filter_accepts + room
- find_drop_position returns tile when room exists, (-1,-1) otherwise
- BUILD_TICKS=60; on_build_tick mirrors Wall's pattern
- _draw procedural brown crate body + slat lines + fill-level dots

World autoload extensions (Opus):
- build_queue: Array — Wall/Floor/Door/Crate ghost entities awaiting
  construction. ConstructionProvider iterates by .priority desc; Phase 6+
  prepends material-haul toils.
- doors: Array — completed doors for future open/close (Phase 7+)
- wall_layer / floor_layer / designation_layer refs exposed for entity code
- mark_wall_tile(tile, material) / mark_floor_tile(tile, material) —
  stamps data-only TileMap layer with material-encoded atlas coord
- stockpile_at_tile(tile) — finds StockpileZone OR Crate covering a tile;
  used by JobRunner._tick_deposit to route Crate deposits

JobRunner._tick_deposit refactor (Opus):
- After clearing the haul-dirty flag, looks up stockpile_at_tile(pawn.tile)
- If destination is a Crate (has_method('register_item')), calls
  dest.register_item(item) so the crate's _contents tracks the stack

World scene integration (Opus):
- y_sort_enabled=true on World root so all entity sprites sort correctly
- DesignationCtl, ConstructionProvider, Wall TileMap (data-only, visible=false)
- World._ready wires:
  * World.wall_layer / floor_layer / designation_layer
  * designation.bind(designation_layer, selection)
  * Register 5 work providers (construction=6 > chop=5 > mine=4 > haul=3 > rest=0)
  * EventBus.designation_added → _on_designation_added (spawns Wall/Floor entity)
- _seed_phase5_demo_buildings: pre-queues 14 wall designations forming a
  5×4 cabin outline at (45, 25) so pawns visibly construct walls without
  player-paint UI (deferred to Phase 17). Spawns 2 fully-built crates at
  (17-18, 60) for hauling routing.

Acceptance — MCP-verified end-to-end:
- 14 wall designations seeded at boot, 2 crates pre-built
- All 3 pawns picked construction (highest priority work) and walked to
  build sites (paths 37/32/27 from spawn). Walls built one by one.
- Wall layer post-construction has 42 cells: 28 (Phase 1 stone ring) +
  14 (Phase 5 cabin) — both rendering paths (placeholder TileMap from
  Phase 1, plus new entity sprites from Phase 5) coexist correctly.
- Pathfinder set_cell_walkable(false) fired on each wall completion.
- Pawns transitioned from construction to hauling once all walls done.
- Final visual: 5×4 stone-walled cabin with mortar lines, Y-sorted entity
  rendering, wood items scattered east of the cabin awaiting haul.

Phase 5 gotchas (logged):
- 'material' as a member var shadows CanvasItem.material (Node2D inherits
  it). Renamed to wall_material / floor_material via quick-edit agent.
  Save-format dict KEYS stay as 'material' for stability.
- Class-name registration cache lag bit again (Tree/Pawn pattern from
  earlier phases). Workflow stays: agent writes class_name file → MCP
  reload_project → godot --headless --editor --quit → headless validate.
- ConstructionProvider scans build_queue every tick including completed
  walls; is_buildable() filters them out but the queue keeps growing.
  Phase 16+ should add an unregister_build_site call from _complete or
  a periodic queue compaction.

Delegation report this phase:
- Agent A (Sonnet, gdscript-refactor): Designation paint mode + EventBus
  signals + Selection guard. ~180 lines.
- Agent B (Sonnet, gdscript-refactor): Toil.KIND_BUILD + JobRunner._tick_build
  + ConstructionProvider + Wall/Floor/Door entities + scenes. ~530 lines.
- Agent C (Sonnet, gdscript-refactor): Crate furniture extending
  StorageDestination. ~270 lines.
- quick-edit (Haiku): material → wall_material/floor_material rename. ~14
  occurrences across 2 files.
- Opus: World autoload extensions + JobRunner _tick_deposit refactor +
  World scene integration (DesignationCtl + ConstructionProvider + new
  scene preloads + _seed_phase5_demo_buildings) + MCP runtime verification
  + the material-shadow + class-cache-lag debugging.

Pivot decision worth flagging: the asset library audit revealed that no
pack we own ships top-down 47-tile autotile walls. After multiple
researcher-overpromise cycles, the pragmatic call was to pivot the
rendering model itself. Walls now render as bottom-anchored tall sprites
with Y-sort; the entire asset library becomes usable as-is. Phase 17
polish will swap procedural _draw() with AtlasTexture regions from
Pixel Crawler / FG_Houses / Ventilatore Castle_Building.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
megaproxy 2026-05-10 22:11:40 +01:00
parent 91bceeebe8
commit f82807ff3d
26 changed files with 1273 additions and 6 deletions

View file

@ -9,3 +9,7 @@ signal sim_tick(tick_number: int) ## Emitted once per sim tick at the current
signal speed_changed(new_speed: int) ## Emitted when Sim.current_speed changes; value is Speed enum cast to int.
# Phase 2 will add pawn-state signals (selected, deselected, walking, …).
# Phase 5 — Designation paint mode.
signal designation_added(cell: Vector2i, tool: StringName) ## Ghost placed + job queued.
signal designation_cleared(cell: Vector2i) ## Ghost removed (job cancelled).

View file

@ -28,6 +28,16 @@ var stockpiles: Array = [] # Array of StorageDestination (StockpileZone for
# its _ready(). Don't access before the world scene is mounted.
var pathfinder = null
# Phase 5 — build queue. Holds Wall/Floor/Door/Crate ghost entities (not yet
# completed). ConstructionProvider iterates this for the nearest buildable site.
# Entities call register_build_site() in _ready and unregister_build_site() when
# they finish or are cancelled.
var build_queue: Array = []
# Phase 5 — completed Door entities, keyed for future open/close logic.
# Door._complete() calls register_door(); Phase 7+ uses this for toggling.
var doors: 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.
@ -118,3 +128,59 @@ func mark_item_needs_haul(it) -> void:
func clear_item_haul_flag(it) -> void:
items_needing_haul.erase(it)
# ── Phase 5: build queue + tile-data stamping for walls / floors ────────────
func register_build_site(entity) -> void:
if not build_queue.has(entity):
build_queue.append(entity)
func unregister_build_site(entity) -> void:
build_queue.erase(entity)
func register_door(d) -> void:
if not doors.has(d):
doors.append(d)
func unregister_door(d) -> void:
doors.erase(d)
# Called by Wall.on_build_tick() when construction completes.
# Stamps the data-only Wall TileMap layer so room/roof/save logic sees the
# wall. World scene exposes wall_layer via a getter set during _ready.
var wall_layer = null
var floor_layer = null
var designation_layer = null
func mark_wall_tile(tile: Vector2i, material: StringName) -> void:
if wall_layer == null:
Audit.log("world", "mark_wall_tile: layer not yet wired — skipping")
return
# Atlas coord encodes material — for Phase 5 placeholder atlas:
# stone → (2, 0), dark stone → (3, 0)
# Real material→atlas mapping lands when assets are imported.
var atlas := Vector2i(2, 0) if material == &"stone" else Vector2i(3, 0)
wall_layer.set_cell(tile, 0, atlas)
func mark_floor_tile(tile: Vector2i, material: StringName) -> void:
if floor_layer == null:
return
var atlas := Vector2i(1, 0) if material == &"dirt" else Vector2i(2, 0)
floor_layer.set_cell(tile, 0, atlas)
# Returns the first StockpileZone OR Crate covering `tile`, or null.
# Used by JobRunner._tick_deposit (Phase 5 refactor) to route deposits into
# Crate contents when applicable.
func stockpile_at_tile(tile: Vector2i):
for sp in stockpiles:
if sp.covers_tile(tile):
return sp
return null

View file

@ -11,7 +11,8 @@ Effort estimates are wall-time at **focused solo pace**. Scale up generously for
| ✅ done — Pawn class, AStarGrid2D pathfinder (9.1 μs avg/18 μs max at 80²), click-to-select + click-to-move via Selection module | **Phase 2 — Pawn skeleton, pathfinding, movement** |
| ✅ done — Job/Toil/JobRunner/Decision/RestProvider, forced_job preempt, mid-toil save round-trip verified | **Phase 3 — AI core: Decision → WorkProvider → JobRunner** |
| ✅ done — Tree/Rock/Item entities, ChopProvider/MineProvider/HaulingProvider, StockpileZone with 16-chip filter + 5-tier priority + cascade sweep | **Phase 4 — First verbs: chop, mine, hauling, stockpiles** |
| ⏳ next | **Phase 5 — Building, walls, floors, containers** |
| ✅ done — Designation paint mode, BuildJob queue, ConstructionProvider, Wall/Floor/Door entities (Y-sorted), Crate as StorageDestination. **Rendering pivot to 3/4 perspective locked.** | **Phase 5 — Building, walls, floors, containers** |
| ⏳ next | **Phase 6 — Production: workbenches, recipes, bills, quality** |
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.

View file

@ -26,7 +26,8 @@ Distilled from the brainstorm. Each lock has a "why" — change with deliberate
| Decision | Choice | Why |
|---|---|---|
| **View** | Top-down, grid-aligned tilemap | Closest to Rimworld feel; matches owned tilesets. |
| **View** | Top-down grid for gameplay (pathfinding, designation, floor) **+ 3/4-perspective rendering for vertical structures** (walls, doors, furniture). | Re-decided 2026-05-10 after exhausting the asset library: every wall pack we own is RPG-style perspective (Stardew / Going Medieval style), not Rimworld-style top-down. Pivoting the renderer (Y-sorted entity sprites for walls) makes the entire library usable as-is and replaces the "we need to author or commission" bottleneck. Gameplay grid + pathfinding stay identical; only the rendering of vertical structures shifts. |
| **Wall layer rendering** | Walls are **entity sprites** (Sprite2D / Y-sorted Node2D), not TileMap cells. `Wall` TileMap layer (Layer 2) becomes data-only — used for pathfinding-impassable + room-detection BFS, but doesn't render. | Same source as the view-style pivot above. Consequence: doors, crates, furniture all live as entities with Y-sort; floor and designation-paint still tile-based. Architecture.md TileMap-layer section needs an annotation. |
| **Primary platforms** | iOS + Android touch, then Steam Deck / ROG Ally gamepad. Desktop falls out for free. | Mobile is the hard constraint; Deck inherits. |
| **Ambition** | itch.io + TestFlight release. Real artifact, small audience. | Drives engine choice; no app-store polish-tax. |
| **Engine** | Godot 4 (GDScript) | 2D-first, free, exports everywhere we need, fast iteration. |
@ -44,7 +45,7 @@ Distilled from the brainstorm. Each lock has a "why" — change with deliberate
| **Engine version** | Godot **4.6.2 stable** (Win64 binary at `D:\godot\Godot_v4.6.2-stable_win64.exe`) | Locked for reproducibility; pinned in `project.godot` features. |
| **Renderer** | GL Compatibility (mobile + desktop), **not** Forward+ | Max device reach; Forward+ would lock out older phones. |
| **Repo location** | Physical: `/mnt/d/godot/rimlike/` (D: drive, fast for Windows-side editor). Symlink: `~/claude/projects/rimlike` → physical. | Mirrors tavernkeep's pattern. Both WSL and Windows access without crossing the WSL net bridge. |
| **Player walls** | **Wood (custom-authored on `FG_Houses.png`) + Stone (autotile from `FG_Fortress.png`)** | Wood preserves the Stardew-cabin warmth that's the project's aesthetic anchor; stone is the upgrade material. Audit (2026-05-10) found Houses *not* autotile-solvable as-is, so wood walls cost ~½ day to author corner/T/cap pieces. Phase 5 slips ~3 days; aesthetic survives. |
| **Player walls** | **Wood + stone via Pixel Crawler `Walls.png`** (entity sprites, Y-sorted; no autotile in Phase 5). Single-sprite-per-material is the Phase 5 ship; per-direction variants are a polish item. | After the rendering pivot to 3/4 perspective, the Pixel Crawler Walls.png pack becomes directly usable. It has 4 wood materials + a sandstone variant with clear corner/edge pieces. Phase 5 ships with one sprite per material (uniform-looking walls); Phase 17 can add per-direction variants if playtest reveals the visuals feel flat. Stardew-cabin warmth restored without authoring or commission. |
### Architecture (tech)

View file

@ -0,0 +1,52 @@
class_name ConstructionProvider extends WorkProvider
## WorkProvider for the "construction" work category.
##
## Scans World.build_queue for the nearest buildable site (Wall, Floor, Door —
## anything exposing is_buildable() / on_build_tick() / tile / label()) and
## returns a two-toil Job:
## walk_to(site.tile) → build_at(site.get_path())
##
## The BUILD toil calls on_build_tick() once per sim tick; the entity internally
## tracks build_progress and calls _complete() when BUILD_TICKS is reached. The
## toil finishes automatically when is_buildable() returns false.
##
## Phase 5 simplification: materials are infinite — no haul-materials step.
## Phase 6+ will prepend walk_to(material_pile) + pickup() toils before walk_to(site).
##
## Duck-typing note: build-site entities are referenced without class_name to
## avoid registration-order issues. We rely only on:
## site.tile: Vector2i
## site.is_buildable() -> bool
## site.label() -> String
## site.get_path() -> NodePath
func _init() -> void:
category = &"construction"
# Higher than chop (5), mine (4), haul (3), rest (0). Players expect their
# build orders to be serviced before the pawn goes off to chop trees.
priority = 6
## Returns a Job targeting the nearest buildable site, or null if none exists.
## `pawn` is duck-typed: must expose .tile (Vector2i).
func find_best_for(pawn) -> Job:
var best = null
var best_dist: int = 999999
for site in World.build_queue:
if not site.is_buildable():
continue
var d: int = abs(site.tile.x - pawn.tile.x) + abs(site.tile.y - pawn.tile.y)
if d < best_dist:
best_dist = d
best = site
if best == null:
return null
var j := Job.new()
j.label = "Build %s at %s" % [best.label(), best.tile]
j.toils.append(Toil.walk_to(best.tile))
j.toils.append(Toil.build_at(best.get_path()))
return j

View file

@ -0,0 +1 @@
uid://bdifcgsar4uc2

View file

@ -93,6 +93,8 @@ func tick() -> void:
pass # Never completes on its own — Decision or player overrides.
Toil.KIND_INTERACT:
_tick_interact(t)
Toil.KIND_BUILD:
_tick_build(t)
Toil.KIND_PICKUP:
_tick_pickup(t)
Toil.KIND_DEPOSIT:
@ -227,6 +229,54 @@ func _tick_interact(t) -> void:
t.done = true
## Execute one tick of a BUILD toil.
##
## Mirrors _tick_interact's pattern, but drives construction entities (Wall,
## Floor, Door) via on_build_tick() / is_buildable() instead of on_chop_tick()
## / is_choppable(). The site is "done" (toil complete) when is_buildable()
## returns false — meaning the entity finished building OR was removed.
##
## First tick: resolve target from NodePath. If already gone, skip immediately.
## Every subsequent tick: call on_build_tick() then check is_buildable(). Once
## false the site is built (or cancelled); mark toil done.
func _tick_build(t) -> void:
var target_path := NodePath(t.data.get("target", ""))
var target = get_tree().get_root().get_node_or_null(target_path)
if not t.data.get("started", false):
if target == null or not is_instance_valid(target):
Audit.log(
"job_runner",
"%s build target gone — skipping" % pawn.pawn_name
)
t.done = true
return
t.data["started"] = true
Audit.log(
"job_runner",
"%s build start: %s" % [pawn.pawn_name, target.name]
)
# Re-resolve each tick in case the node was freed between ticks.
target = get_tree().get_root().get_node_or_null(target_path)
if target == null or not is_instance_valid(target):
t.done = true
return
target.on_build_tick()
# Re-check after the call (on_build_tick may complete + free the ghost state).
if target == null or not is_instance_valid(target):
t.done = true
return
if target.has_method("is_buildable") and not target.is_buildable():
Audit.log(
"job_runner",
"%s build done: %s" % [pawn.pawn_name, target.name]
)
t.done = true
## Execute one tick of a PICKUP toil.
##
## Finds the first unheld Item at pawn.tile in World.items.
@ -275,6 +325,12 @@ func _tick_deposit(t) -> void:
# The periodic sweep_for_better_destinations will re-mark it if a higher-
# priority destination opens up later.
World.clear_item_haul_flag(item)
# Phase 5: if the destination tile is covered by a Crate (single-tile
# container), register the item into the crate's contents. StockpileZone
# doesn't need this — its items just live at the floor tile.
var dest = World.stockpile_at_tile(pawn.tile)
if dest != null and dest.has_method("register_item"):
dest.register_item(item)
Audit.log(
"job_runner",
"%s deposit: %s ×%d at %s" % [pawn.pawn_name, item.item_type, item.stack_size, pawn.tile]

View file

@ -16,6 +16,7 @@ const KIND_IDLE: StringName = &"idle"
const KIND_INTERACT: StringName = &"interact" # Timed action on a target entity (Tree, Rock, …)
const KIND_PICKUP: StringName = &"pickup" # Transfer Item at pawn.tile into pawn.carried_item
const KIND_DEPOSIT: StringName = &"deposit" # Place pawn.carried_item at pawn.tile
const KIND_BUILD: StringName = &"build" # Timed construction on a Wall / Floor / Door entity
var kind: StringName = KIND_IDLE
## Toil-specific params — all values must be int, float, bool, String, Dict, or Array.
@ -80,6 +81,20 @@ static func pickup() -> Toil:
return t
## Construction action on a scene-node target (Wall, Floor, Door, …).
## `target_node_path` is the NodePath of the entity; stored as String for JSON safety.
## JobRunner resolves the node at first-tick and calls on_build_tick() every sim tick
## until is_buildable() returns false (construction complete or site cancelled/removed).
static func build_at(target_node_path: NodePath) -> Toil:
var t := Toil.new()
t.kind = KIND_BUILD
t.data = {
"target": String(target_node_path),
"started": false,
}
return t
## Place pawn.carried_item at pawn.tile. Single-tick action.
## data is empty — the item comes from pawn.carried_item at execution time.
static func deposit() -> Toil:

138
scenes/entities/door.gd Normal file
View file

@ -0,0 +1,138 @@
class_name Door extends Node2D
## Door entity — built by a pawn with a Build job. Unlike walls, doors remain
## walkable once complete. Phase 5: always-open (always walkable). Phase 7+
## will add open/close animation and toggling.
##
## Door is rendered as a bottom-anchored tall sprite (Y-sorted), same as Wall,
## so it occludes pawns walking behind it — matching the 3/4-perspective
## rendering pivot (see memory.md Decisions: "Wall layer rendering").
##
## Build model (docs/implementation.md Phase 5):
## A ConstructionProvider creates a Job whose BUILD toil calls on_build_tick()
## once per sim tick via JobRunner. After BUILD_TICKS ticks the door is
## complete: it registers with World for future open/close logic, does NOT
## call set_cell_walkable(false), and transitions from ghost to solid.
##
## World registration: World.register_build_site / World.unregister_build_site
## are called from _ready / _exit_tree. Methods land in the Opus integration pass.
const TILE_SIZE_PX: int = 16
## Sim ticks to build a door at 1× speed (80 ticks = 4 sim seconds).
const BUILD_TICKS: int = 80
# ── state ──────────────────────────────────────────────────────────────────────
@export var tile: Vector2i = Vector2i.ZERO
## 0..BUILD_TICKS.
var build_progress: int = 0
var _completed: bool = false
## Phase 5: always-open. Phase 7+ toggles this for open/close animation.
var is_open: bool = true
# ── lifecycle ──────────────────────────────────────────────────────────────────
func _ready() -> void:
World.register_build_site(self)
func _exit_tree() -> void:
World.unregister_build_site(self)
# ── public API ─────────────────────────────────────────────────────────────────
## One-shot initialiser. Call after add_child() so _ready() has already fired.
func setup(p_tile: Vector2i) -> void:
tile = p_tile
# Bottom-anchor: same as Wall so it Y-sorts correctly with pawns.
position = Vector2(
tile.x * TILE_SIZE_PX + TILE_SIZE_PX / 2.0,
tile.y * TILE_SIZE_PX + TILE_SIZE_PX
)
queue_redraw()
Audit.log("door", "door ghost placed at %s" % tile)
## True while the door still needs construction work.
func is_buildable() -> bool:
return not _completed
## Human-readable label for job descriptions and Audit logs.
func label() -> String:
return "door"
## Called by the BUILD toil in JobRunner once per sim tick.
func on_build_tick() -> void:
if _completed:
return
build_progress += 1
queue_redraw()
if build_progress >= BUILD_TICKS:
_complete()
## True once the door has been fully built.
func is_completed() -> bool:
return _completed
# ── save / load ────────────────────────────────────────────────────────────────
func to_dict() -> Dictionary:
return {
"tile_x": tile.x,
"tile_y": tile.y,
"build_progress": build_progress,
"completed": _completed,
"is_open": is_open,
}
static func from_dict(d: Dictionary) -> Dictionary:
return {
"tile_x": int(d.get("tile_x", 0)),
"tile_y": int(d.get("tile_y", 0)),
"build_progress": int(d.get("build_progress", 0)),
"completed": bool(d.get("completed", false)),
"is_open": bool(d.get("is_open", true)),
}
# ── render ─────────────────────────────────────────────────────────────────────
func _draw() -> void:
# Door: 16 px wide, 24 px tall, bottom-anchored. Origin at bottom-centre.
# (Shorter than the full 32 px wall height — visually reads as a door opening.)
var alpha: float = 1.0 if _completed else 0.4
var frame_color := Color(0.32, 0.22, 0.10, alpha)
var panel_color := Color(0.52, 0.36, 0.18, alpha)
var hinge_color := Color(0.20, 0.18, 0.16, alpha)
# Door frame (slightly wider than the panel).
draw_rect(Rect2(Vector2(-8.0, -24.0), Vector2(16.0, 24.0)), frame_color)
# Door panel (inset 2 px on each side).
draw_rect(Rect2(Vector2(-6.0, -22.0), Vector2(12.0, 20.0)), panel_color)
# Hinge dot on the left side.
draw_circle(Vector2(-6.0, -18.0), 1.5, hinge_color)
# Outline.
draw_rect(Rect2(Vector2(-8.0, -24.0), Vector2(16.0, 24.0)), Color(0.0, 0.0, 0.0, 0.5 * alpha), false, 1.0)
# ── internal ───────────────────────────────────────────────────────────────────
func _complete() -> void:
_completed = true
# Doors are walkable — do NOT call set_cell_walkable(false).
# Register so future open/close logic can locate this door by tile.
World.register_door(self)
queue_redraw()
Audit.log("door", "door completed at %s" % tile)

View file

@ -0,0 +1 @@
uid://ccjf4t5w80da5

View file

@ -0,0 +1,8 @@
[gd_scene load_steps=2 format=3 uid="uid://door_entity"]
[ext_resource type="Script" path="res://scenes/entities/door.gd" id="1_door"]
[node name="Door" type="Node2D"]
y_sort_enabled = true
z_index = 0
script = ExtResource("1_door")

169
scenes/entities/floor.gd Normal file
View file

@ -0,0 +1,169 @@
class_name Floor extends Node2D
## Floor entity — built by a pawn with a Build job. Stamps the Floor TileMap
## layer once complete. Floors do NOT block pathfinding.
##
## Floor is ground-level: its render origin sits at the tile centre (not
## bottom-anchored like Wall/Door). Y-sort is not needed because floor sprites
## always sort below any tall entity at the same tile.
##
## Build model (docs/implementation.md Phase 5):
## A ConstructionProvider creates a Job whose BUILD toil calls on_build_tick()
## once per sim tick via JobRunner. After BUILD_TICKS ticks the floor is
## complete: it stamps the data-layer TileMap (World.mark_floor_tile) and
## transitions from ghost (40% alpha) to solid.
##
## World registration: World.register_build_site / World.unregister_build_site
## are called from _ready / _exit_tree. Methods land in the Opus integration pass.
const TILE_SIZE_PX: int = 16
## Sim ticks to lay a floor at 1× speed (30 ticks = 1.5 sim seconds).
const BUILD_TICKS: int = 30
const MATERIAL_WOOD: StringName = &"wood"
const MATERIAL_STONE: StringName = &"stone"
const MATERIAL_DIRT: StringName = &"dirt"
# ── state ──────────────────────────────────────────────────────────────────────
@export var floor_material: StringName = MATERIAL_WOOD
@export var tile: Vector2i = Vector2i.ZERO
## 0..BUILD_TICKS.
var build_progress: int = 0
var _completed: bool = false
# ── lifecycle ──────────────────────────────────────────────────────────────────
func _ready() -> void:
World.register_build_site(self)
func _exit_tree() -> void:
World.unregister_build_site(self)
# ── public API ─────────────────────────────────────────────────────────────────
## One-shot initialiser. Call after add_child() so _ready() has already fired.
func setup(p_tile: Vector2i, p_material: StringName) -> void:
tile = p_tile
floor_material = p_material
# Floor renders at tile centre (not bottom-anchored).
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("floor", "%s floor ghost placed at %s" % [floor_material, tile])
## True while the floor still needs construction work.
func is_buildable() -> bool:
return not _completed
## Human-readable label for job descriptions and Audit logs.
func label() -> String:
return "%s floor" % floor_material
## Called by the BUILD toil in JobRunner once per sim tick.
func on_build_tick() -> void:
if _completed:
return
build_progress += 1
queue_redraw()
if build_progress >= BUILD_TICKS:
_complete()
## True once the floor has been fully laid.
func is_completed() -> bool:
return _completed
# ── save / load ────────────────────────────────────────────────────────────────
func to_dict() -> Dictionary:
return {
"tile_x": tile.x,
"tile_y": tile.y,
"material": str(floor_material),
"build_progress": build_progress,
"completed": _completed,
}
static func from_dict(d: Dictionary) -> Dictionary:
return {
"tile_x": int(d.get("tile_x", 0)),
"tile_y": int(d.get("tile_y", 0)),
"material": str(d.get("material", "wood")),
"build_progress": int(d.get("build_progress", 0)),
"completed": bool(d.get("completed", false)),
}
# ── render ─────────────────────────────────────────────────────────────────────
func _draw() -> void:
# 16×16 tile centred on origin.
var alpha: float = 1.0 if _completed else 0.4
var half: float = TILE_SIZE_PX / 2.0
match floor_material:
MATERIAL_WOOD:
_draw_wood_floor(alpha, half)
MATERIAL_STONE:
_draw_stone_floor(alpha, half)
_: # MATERIAL_DIRT and any future materials
_draw_dirt_floor(alpha, half)
func _draw_wood_floor(alpha: float, half: float) -> void:
var base := Color(0.58, 0.40, 0.20, alpha)
var plank := Color(0.50, 0.34, 0.16, alpha)
draw_rect(Rect2(Vector2(-half, -half), Vector2(TILE_SIZE_PX, TILE_SIZE_PX)), base)
# Horizontal plank lines.
for y_offset in [-3.0, 2.0]:
draw_line(
Vector2(-half, y_offset),
Vector2(half, y_offset),
plank, 1.0
)
draw_rect(Rect2(Vector2(-half, -half), Vector2(TILE_SIZE_PX, TILE_SIZE_PX)), Color(0.0, 0.0, 0.0, 0.3 * alpha), false, 1.0)
func _draw_stone_floor(alpha: float, half: float) -> void:
var base := Color(0.60, 0.60, 0.57, alpha)
var joint := Color(0.45, 0.45, 0.43, alpha)
draw_rect(Rect2(Vector2(-half, -half), Vector2(TILE_SIZE_PX, TILE_SIZE_PX)), base)
# Stone tile grid lines.
draw_line(Vector2(0.0, -half), Vector2(0.0, half), joint, 1.0)
draw_line(Vector2(-half, 0.0), Vector2(half, 0.0), joint, 1.0)
draw_rect(Rect2(Vector2(-half, -half), Vector2(TILE_SIZE_PX, TILE_SIZE_PX)), Color(0.0, 0.0, 0.0, 0.3 * alpha), false, 1.0)
func _draw_dirt_floor(alpha: float, half: float) -> void:
var base := Color(0.42, 0.30, 0.18, alpha)
draw_rect(Rect2(Vector2(-half, -half), Vector2(TILE_SIZE_PX, TILE_SIZE_PX)), base)
draw_rect(Rect2(Vector2(-half, -half), Vector2(TILE_SIZE_PX, TILE_SIZE_PX)), Color(0.0, 0.0, 0.0, 0.25 * alpha), false, 1.0)
# ── internal ───────────────────────────────────────────────────────────────────
func _complete() -> void:
_completed = true
# Floors do NOT block pathfinding — no pathfinder call here.
World.mark_floor_tile(tile, floor_material)
queue_redraw()
Audit.log("floor", "%s floor completed at %s" % [floor_material, tile])

View file

@ -0,0 +1 @@
uid://dvqjhnx7t8l44

View file

@ -0,0 +1,7 @@
[gd_scene load_steps=2 format=3 uid="uid://floor_entity"]
[ext_resource type="Script" path="res://scenes/entities/floor.gd" id="1_floor"]
[node name="Floor" type="Node2D"]
z_index = 0
script = ExtResource("1_floor")

179
scenes/entities/wall.gd Normal file
View file

@ -0,0 +1,179 @@
class_name Wall extends Node2D
## Wall entity — built by a pawn with a Build job. Blocks pathfinding once
## complete. Rendered as a bottom-anchored tall sprite (Y-sorted) so it
## occludes pawns standing behind it, matching the project's 3/4-perspective
## rendering pivot (see memory.md Decisions: "Wall layer rendering").
##
## Build model (docs/implementation.md Phase 5):
## A ConstructionProvider creates a Job whose BUILD toil calls on_build_tick()
## once per sim tick via JobRunner. After BUILD_TICKS ticks the wall is
## complete: it stamps the data-layer TileMap (World.mark_wall_tile), blocks
## pathfinding, and transitions from ghost (40% alpha) to solid rendering.
##
## Material support:
## Phase 5 ships stone only. Wood constant is defined for Phase 6+ wiring
## (Pixel Crawler Walls.png asset crop session) without breaking the data model.
##
## World registration: World.register_build_site / World.unregister_build_site
## are called from _ready / _exit_tree. The actual World methods land in the
## Opus integration pass.
const TILE_SIZE_PX: int = 16
## Sim ticks to complete construction at 1× speed (100 ticks = 5 sim seconds).
const BUILD_TICKS: int = 100
## Supported materials. Phase 5 uses MATERIAL_STONE; MATERIAL_WOOD is reserved
## for the Phase 6+ art-authoring pass.
const MATERIAL_STONE: StringName = &"stone"
const MATERIAL_WOOD: StringName = &"wood"
# ── state ──────────────────────────────────────────────────────────────────────
@export var wall_material: StringName = MATERIAL_STONE
@export var tile: Vector2i = Vector2i.ZERO
## 0..BUILD_TICKS. Advanced by on_build_tick(). Entity is in "ghost" state
## until build_progress reaches BUILD_TICKS.
var build_progress: int = 0
var _completed: bool = false
# ── lifecycle ──────────────────────────────────────────────────────────────────
func _ready() -> void:
World.register_build_site(self)
func _exit_tree() -> void:
World.unregister_build_site(self)
# ── public API ─────────────────────────────────────────────────────────────────
## One-shot initialiser. Call after add_child() so _ready() has already fired.
func setup(p_tile: Vector2i, p_material: StringName) -> void:
tile = p_tile
wall_material = p_material
# Bottom-anchor the sprite: position.y sits at the bottom of the tile so the
# 16×32 virtual sprite "rises" into the cell above. Y-sort uses position.y.
position = Vector2(
tile.x * TILE_SIZE_PX + TILE_SIZE_PX / 2.0,
tile.y * TILE_SIZE_PX + TILE_SIZE_PX
)
queue_redraw()
Audit.log("wall", "%s wall ghost placed at %s" % [wall_material, tile])
## True while the wall still needs construction work.
## JobRunner's _tick_build checks this to decide when the toil is done.
func is_buildable() -> bool:
return not _completed
## Human-readable label for job descriptions and Audit logs.
func label() -> String:
return "%s wall" % wall_material
## Called by the BUILD toil in JobRunner once per sim tick while the pawn works.
## Advances build_progress and completes the wall when BUILD_TICKS is reached.
func on_build_tick() -> void:
if _completed:
return
build_progress += 1
queue_redraw()
if build_progress >= BUILD_TICKS:
_complete()
## True once the wall has been fully built.
func is_completed() -> bool:
return _completed
# ── save / load ────────────────────────────────────────────────────────────────
func to_dict() -> Dictionary:
return {
"tile_x": tile.x,
"tile_y": tile.y,
"material": str(wall_material),
"build_progress": build_progress,
"completed": _completed,
}
static func from_dict(d: Dictionary) -> Dictionary:
return {
"tile_x": int(d.get("tile_x", 0)),
"tile_y": int(d.get("tile_y", 0)),
"material": str(d.get("material", "stone")),
"build_progress": int(d.get("build_progress", 0)),
"completed": bool(d.get("completed", false)),
}
# ── render ─────────────────────────────────────────────────────────────────────
func _draw() -> void:
# Wall is drawn as a bottom-anchored 16×32 rect occupying the lower portion
# of the virtual sprite area. The origin (0, 0) of _draw() sits at position,
# which is at the tile's bottom-centre (tile_y * 16 + 16).
# Drawing upward: Y goes from 0 to -32 in local space.
var alpha: float = 1.0 if _completed else 0.4
if wall_material == MATERIAL_STONE:
_draw_stone_wall(alpha)
else:
# Fallback: render as wood until art assets are wired in Phase 6+.
_draw_wood_wall(alpha)
func _draw_stone_wall(alpha: float) -> void:
var base := Color(0.55, 0.55, 0.50, alpha)
var mortar := Color(0.40, 0.40, 0.38, alpha)
# Main body: 16 px wide, 32 px tall, origin at bottom-centre.
draw_rect(Rect2(Vector2(-8.0, -32.0), Vector2(16.0, 32.0)), base)
# Mortar / horizontal stone-course lines (4 lines spaced 8 px apart).
for i in range(1, 5):
var y: float = -8.0 * float(i)
draw_line(Vector2(-8.0, y), Vector2(8.0, y), mortar, 1.0)
# Outline.
draw_rect(Rect2(Vector2(-8.0, -32.0), Vector2(16.0, 32.0)), Color(0.0, 0.0, 0.0, 0.5 * alpha), false, 1.0)
func _draw_wood_wall(alpha: float) -> void:
var base := Color(0.55, 0.40, 0.22, alpha)
var plank := Color(0.45, 0.32, 0.16, alpha)
draw_rect(Rect2(Vector2(-8.0, -32.0), Vector2(16.0, 32.0)), base)
# Vertical plank lines.
for x_offset in [-3.0, 2.0]:
draw_line(
Vector2(x_offset, -32.0),
Vector2(x_offset, 0.0),
plank, 1.0
)
draw_rect(Rect2(Vector2(-8.0, -32.0), Vector2(16.0, 32.0)), Color(0.0, 0.0, 0.0, 0.5 * alpha), false, 1.0)
# ── internal ───────────────────────────────────────────────────────────────────
func _complete() -> void:
_completed = true
# Block pathfinding — wall is now impassable.
if World.pathfinder != null:
World.pathfinder.set_cell_walkable(tile, false)
# Stamp the data-layer TileMap so room / roof / save logic sees the wall.
World.mark_wall_tile(tile, wall_material)
queue_redraw()
Audit.log("wall", "%s wall completed at %s" % [wall_material, tile])

View file

@ -0,0 +1 @@
uid://q5vg0jcsdei8

View file

@ -0,0 +1,8 @@
[gd_scene load_steps=2 format=3 uid="uid://wall_entity"]
[ext_resource type="Script" path="res://scenes/entities/wall.gd" id="1_wall"]
[node name="Wall" type="Node2D"]
y_sort_enabled = true
z_index = 0
script = ExtResource("1_wall")

268
scenes/world/crate.gd Normal file
View file

@ -0,0 +1,268 @@
class_name Crate extends StorageDestination
## Furniture container entity: holds up to CAPACITY item stacks and can be
## filtered like a StockpileZone. Built via Build → Furniture → Crate.
##
## Lifecycle:
## - Ghost phase: placed but not yet built (build_progress < BUILD_TICKS).
## accepts() returns false; visual is 40% alpha.
## - Completed phase: _completed == true; accepts items up to CAPACITY.
##
## StorageDestination interface:
## accepts() — filter + capacity gate; false while ghost.
## find_drop_position()— returns crate's own tile when room exists,
## Vector2i(-1, -1) when full or ghost.
## covers_tile() — single-tile container; only the crate's own tile.
##
## BuildJob interface (mirrors Wall.on_build_tick pattern):
## is_buildable() — true while still a ghost.
## on_build_tick() — increments build_progress; completes at BUILD_TICKS.
## is_completed() — true once built.
##
## register_item() is called by JobRunner._tick_deposit (Opus integration
## follow-up) after the deposit physically lands on the crate tile.
##
## See docs/architecture.md "Container" and Phase 5 implementation plan.
## Maximum item stacks this crate can hold.
const CAPACITY: int = 4
## Number of sim ticks a pawn must spend building to complete the crate.
const BUILD_TICKS: int = 60
## Pixel size of one tile — must match World.TILE_SIZE_PX.
const TILE_SIZE_PX: int = 16
# ── visual constants ──────────────────────────────────────────────────────────
## Body dimensions in pixels (centred on the tile).
const _BODY_W: int = 12
const _BODY_H: int = 10
## Crate colours.
const _COLOR_BODY: Color = Color(0.45, 0.30, 0.15, 1.0)
const _COLOR_OUTLINE: Color = Color(0.25, 0.18, 0.08, 1.0)
const _COLOR_SLAT: Color = Color(0.30, 0.20, 0.10, 1.0)
const _COLOR_FILL_DOT: Color = Color(1.0, 1.0, 1.0, 0.9)
## Ghost alpha multiplier when not yet built.
const _GHOST_ALPHA: float = 0.40
# ── exports ───────────────────────────────────────────────────────────────────
## Tile position of this crate in world-tile coordinates.
@export var tile: Vector2i = Vector2i.ZERO
## Player-facing label (inspect UI, Phase 17).
@export var label_text: String = "Crate"
# ── state ─────────────────────────────────────────────────────────────────────
## Sim ticks of construction work applied so far.
var build_progress: int = 0
## True once build_progress >= BUILD_TICKS.
var _completed: bool = false
## Live item nodes currently stored in this crate; capped at CAPACITY.
## Populated by register_item() (called from JobRunner._tick_deposit).
var _contents: Array = []
# ── lifecycle ─────────────────────────────────────────────────────────────────
func _ready() -> void:
# Inherits StorageDestination defaults for priority / accepted_types.
# Crates default to NORMAL priority and wildcard (accepts all types).
priority = StorageDestination.Priority.NORMAL
accepted_types = []
# Register with the World stockpile pool so HaulingProvider sees us.
World.register_stockpile(self)
queue_redraw()
func _exit_tree() -> void:
World.unregister_stockpile(self)
## One-shot initialiser called by the spawning / placement code.
## Sets tile and snaps pixel position to the tile centre.
func setup(p_tile: Vector2i) -> void:
tile = p_tile
position = Vector2(
tile.x * TILE_SIZE_PX + TILE_SIZE_PX / 2.0,
tile.y * TILE_SIZE_PX + TILE_SIZE_PX / 2.0
)
# ── StorageDestination interface ──────────────────────────────────────────────
## Returns true if this crate can accept `item` right now.
## False while still a ghost, false if the filter rejects the type,
## false if all CAPACITY slots are taken.
func accepts(item) -> bool:
if not _completed:
return false
if not _filter_accepts(item):
return false
return _contents.size() < CAPACITY
## Returns the crate's own tile when it can accept `item`, otherwise (-1,-1).
## All items stack into the crate's single tile — there is no 2D region.
func find_drop_position(item) -> Vector2i:
if accepts(item):
return tile
return Vector2i(-1, -1)
## Returns true only when `p_tile` is exactly the crate's own tile.
func covers_tile(p_tile: Vector2i) -> bool:
return p_tile == tile
# ── BuildJob interface ────────────────────────────────────────────────────────
## True while the crate has not yet been fully built.
func is_buildable() -> bool:
return not _completed
## Returns the player-visible name for build-order and inspect UI.
func label() -> String:
return label_text
## Called once per sim tick while a Construction pawn is working on this crate.
## Advances build_progress; completes the crate once BUILD_TICKS is reached.
func on_build_tick() -> void:
if _completed:
return
build_progress += 1
if build_progress >= BUILD_TICKS:
_completed = true
emit_signal("contents_changed")
Audit.log("crate", "built at %s (capacity %d)" % [tile, CAPACITY])
queue_redraw()
## True once the crate has been fully built.
func is_completed() -> bool:
return _completed
# ── inventory hooks ───────────────────────────────────────────────────────────
## Called from JobRunner._tick_deposit (Opus integration) after the item
## physically lands on the crate tile.
## Defensive: skips duplicates and over-capacity inserts (HaulingProvider may
## race ahead of capacity checks in edge cases).
func register_item(item) -> void:
if not _completed:
return
if _contents.has(item) or _contents.size() >= CAPACITY:
return
_contents.append(item)
emit_signal("contents_changed")
## Called when an item is removed from the crate (picked up by a pawn or via
## the Empty operation in Phase 17 inspect UI).
func unregister_item(item) -> void:
_contents.erase(item)
emit_signal("contents_changed")
# ── save / load ───────────────────────────────────────────────────────────────
## Serialise crate state for World save (Phase 16 will wire this).
func to_dict() -> Dictionary:
return {
"tile_x": tile.x,
"tile_y": tile.y,
"label_text": label_text,
"build_progress": build_progress,
"completed": _completed,
"priority": int(priority),
"accepted_types": accepted_types.map(func(t): return String(t)),
}
## Restore from a dict produced by to_dict().
## Item content refs are reconnected by World.load_crates() after all items
## are spawned (Phase 16); _contents starts empty here.
func from_dict(d: Dictionary) -> void:
tile = Vector2i(int(d.get("tile_x", 0)), int(d.get("tile_y", 0)))
label_text = d.get("label_text", "Crate")
build_progress = int(d.get("build_progress", 0))
_completed = bool(d.get("completed", false))
priority = d.get("priority", StorageDestination.Priority.NORMAL) as StorageDestination.Priority
var raw_types: Array = d.get("accepted_types", [])
accepted_types.clear()
for s in raw_types:
accepted_types.append(StringName(s))
setup(tile)
# ── render ─────────────────────────────────────────────────────────────────────
## Procedural crate graphic; no PNG dependency.
##
## Completed crate:
## Brown 12×10 body with a darker 1-px outline, two horizontal slat bands.
## Four 2×2 fill-indicator dots in the top-right corner — white dots equal
## to _contents.size() are drawn; remaining dots are drawn at low alpha.
##
## Ghost (not yet built):
## Same shapes at GHOST_ALPHA overall alpha.
func _draw() -> void:
var alpha_scale: float = _GHOST_ALPHA if not _completed else 1.0
var body_color := Color(_COLOR_BODY.r, _COLOR_BODY.g, _COLOR_BODY.b, _COLOR_BODY.a * alpha_scale)
var outline_col := Color(_COLOR_OUTLINE.r, _COLOR_OUTLINE.g, _COLOR_OUTLINE.b, _COLOR_OUTLINE.a * alpha_scale)
var slat_color := Color(_COLOR_SLAT.r, _COLOR_SLAT.g, _COLOR_SLAT.b, _COLOR_SLAT.a * alpha_scale)
# Half-extents for centering.
var hw: int = _BODY_W / 2 # 6
var hh: int = _BODY_H / 2 # 5
# Body fill.
var body_rect := Rect2(Vector2(-hw, -hh), Vector2(_BODY_W, _BODY_H))
draw_rect(body_rect, body_color, true)
# Outline (1 px wide; draw_rect with false = border).
draw_rect(body_rect, outline_col, false, 1.0)
# Two horizontal slat bands — at ⅓ and ⅔ of the body height.
# Each band is 1 px tall, inset 1 px from the sides.
var slat_x_start: float = -hw + 1.0
var slat_width: float = float(_BODY_W - 2)
var slat_y1: float = -hh + float(_BODY_H) / 3.0 - 0.5
var slat_y2: float = -hh + float(_BODY_H) * 2.0 / 3.0 - 0.5
draw_line(
Vector2(slat_x_start, slat_y1),
Vector2(slat_x_start + slat_width, slat_y1),
slat_color, 1.0
)
draw_line(
Vector2(slat_x_start, slat_y2),
Vector2(slat_x_start + slat_width, slat_y2),
slat_color, 1.0
)
# Fill-level indicator: 4 dots (2×2 px each) in the top-right corner,
# arranged in a 2×2 grid. Dots up to _contents.size() are bright white;
# the rest are dim (10% alpha).
var dot_size: float = 2.0
var dot_gap: float = 1.0
var dot_origin := Vector2(float(hw) - 2.0 * dot_size - dot_gap - 1.0, float(-hh) + 1.0)
for i in range(CAPACITY):
var col_idx: int = i % 2
var row_idx: int = i / 2
var dot_x: float = dot_origin.x + col_idx * (dot_size + dot_gap)
var dot_y: float = dot_origin.y + row_idx * (dot_size + dot_gap)
var dot_rect := Rect2(Vector2(dot_x, dot_y), Vector2(dot_size, dot_size))
var fill_alpha: float = (1.0 if i < _contents.size() else 0.15) * alpha_scale
var dot_col := Color(_COLOR_FILL_DOT.r, _COLOR_FILL_DOT.g, _COLOR_FILL_DOT.b, fill_alpha)
draw_rect(dot_rect, dot_col, true)

View file

@ -0,0 +1 @@
uid://dlpyb4yksx3yc

8
scenes/world/crate.tscn Normal file
View file

@ -0,0 +1,8 @@
[gd_scene load_steps=2 format=3 uid="uid://crate"]
[ext_resource type="Script" path="res://scenes/world/crate.gd" id="1_crate"]
[node name="Crate" type="Node2D"]
script = ExtResource("1_crate")
y_sort_enabled = true
z_index = 0

170
scenes/world/designation.gd Normal file
View file

@ -0,0 +1,170 @@
extends Node
class_name Designation
## Phase 5 — Designation paint mode.
##
## Captures mouse input to drag-paint ghost tiles on Layer 3 (designation_layer)
## of the world TileMap. Each new cell painted emits EventBus.designation_added;
## removing a ghost emits EventBus.designation_cleared.
##
## Integrates with Selection: raises Selection.designation_active while a non-none
## tool is active so Selection does not also process those clicks.
##
## Opus wires the node into world.tscn and calls bind() + set_active_tool() from
## the build-drawer UI.
# ── tool constants ───────────────────────────────────────────────────────────
const TOOL_NONE: StringName = &"none"
const TOOL_BUILD_WALL: StringName = &"build_wall"
const TOOL_BUILD_FLOOR: StringName = &"build_floor"
# Atlas coords on the shared placeholder tileset (source 0).
# build_wall → stone-grey (2, 0); build_floor → dirt-brown (1, 0).
const _ATLAS_BY_TOOL: Dictionary = {
&"build_wall": Vector2i(2, 0),
&"build_floor": Vector2i(1, 0),
}
# Placeholder source ID — mirrors World.PLACEHOLDER_SOURCE_ID.
const _SOURCE_ID: int = 0
# Tile-size in pixels — mirrors World.TILE_SIZE_PX.
const _TILE_SIZE_PX: float = 16.0
# ── signals ──────────────────────────────────────────────────────────────────
signal designation_added(cell: Vector2i, tool: StringName)
signal designation_cleared(cell: Vector2i)
# ── state ────────────────────────────────────────────────────────────────────
var _tool: StringName = TOOL_NONE
var _paint_layer: TileMapLayer = null
var _selection: Selection = null # optional; raised/lowered for input hand-off
# cell → tool that placed the ghost.
var _painted: Dictionary = {} # Dictionary[Vector2i, StringName]
# Stroke deduplication — cells touched in the current mouse-down session.
var _stroke_cells: Dictionary = {} # Dictionary[Vector2i, bool]
var _stroke_active: bool = false
# ── public API ───────────────────────────────────────────────────────────────
## Call once from World._ready() with the TileMapLayer at index 3 (Designation)
## and the sibling Selection node.
func bind(paint_layer: TileMapLayer, selection: Selection = null) -> void:
assert(paint_layer != null, "Designation.bind: paint_layer is null")
_paint_layer = paint_layer
_selection = selection
## 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],
"Designation.set_active_tool: unknown tool '%s'" % tool
)
_tool = tool
_stroke_active = false
_stroke_cells.clear()
_sync_selection_flag()
if tool == TOOL_NONE:
Audit.log("designation", "tool deactivated")
else:
Audit.log("designation", "tool set to '%s'" % tool)
func active_tool() -> StringName:
return _tool
## Remove the ghost for a single cell and emit designation_cleared.
func clear_cell(cell: Vector2i) -> void:
if not _painted.has(cell):
return
_painted.erase(cell)
if _paint_layer != null:
_paint_layer.erase_cell(cell)
designation_cleared.emit(cell)
EventBus.designation_cleared.emit(cell)
Audit.log("designation", "cleared cell %s" % cell)
## Returns all cells that currently have an active ghost.
func cells() -> Array[Vector2i]:
var result: Array[Vector2i] = []
for c: Vector2i in _painted.keys():
result.append(c)
return result
# ── input ────────────────────────────────────────────────────────────────────
func _unhandled_input(event: InputEvent) -> void:
if _tool == TOOL_NONE or _paint_layer == null:
return
if event is InputEventMouseButton and event.button_index == MOUSE_BUTTON_LEFT:
if event.pressed:
_stroke_active = true
_stroke_cells.clear()
_paint_at_screen(event.position)
else:
_stroke_active = false
_stroke_cells.clear()
get_viewport().set_input_as_handled()
return
if event is InputEventMouseMotion and _stroke_active:
_paint_at_screen(event.position)
get_viewport().set_input_as_handled()
# ── helpers ──────────────────────────────────────────────────────────────────
func _paint_at_screen(screen_pos: Vector2) -> void:
var world_pos: Vector2 = get_viewport().get_canvas_transform().affine_inverse() * screen_pos
var cell := Vector2i(
floori(world_pos.x / _TILE_SIZE_PX),
floori(world_pos.y / _TILE_SIZE_PX),
)
# Deduplication within the current stroke.
if _stroke_cells.has(cell):
return
_stroke_cells[cell] = true
# Don't re-paint the same tool over itself.
if _painted.get(cell) == _tool:
return
_apply_ghost(cell)
func _apply_ghost(cell: Vector2i) -> void:
var atlas_coord: Vector2i = _ATLAS_BY_TOOL.get(_tool, Vector2i(2, 0))
_paint_layer.set_cell(cell, _SOURCE_ID, atlas_coord)
_painted[cell] = _tool
# Modulate the whole paint layer based on whether this cell is placeable.
# Phase 5 simplification: validity applies globally to the layer.
var ok: bool = _cell_is_placeable(cell)
_paint_layer.modulate = Color(0.4, 1.0, 0.4, 0.7) if ok else Color(1.0, 0.4, 0.4, 0.7)
designation_added.emit(cell, _tool)
EventBus.designation_added.emit(cell, _tool)
Audit.log("designation", "painted %s at %s (placeable=%s)" % [_tool, cell, ok])
func _cell_is_placeable(cell: Vector2i) -> bool:
# For Phase 5: a cell is placeable for build_wall if it is currently walkable
# (no wall present), and for build_floor if it is walkable. Items-on-tile
# check is deferred to Phase 5 BuildJob validation; we only gate on geometry here.
if World.pathfinder == null:
return true
return World.pathfinder.is_walkable(cell)
func _sync_selection_flag() -> void:
if _selection == null:
return
_selection.designation_active = (_tool != TOOL_NONE)

View file

@ -0,0 +1 @@
uid://cmrup4namfy8

View file

@ -0,0 +1,6 @@
[gd_scene load_steps=2 format=3 uid="uid://designation"]
[ext_resource type="Script" path="res://scenes/world/designation.gd" id="1_designation"]
[node name="Designation" type="Node"]
script = ExtResource("1_designation")

View file

@ -15,6 +15,10 @@ const CLICK_MAX_DURATION_MS: int = 300
var _pathfinder: Pathfinder = null
var _selected_pawn: Pawn = null
# When Designation paint mode is active this flag is raised by Designation so
# Selection does not also try to select/move on the same click.
var designation_active: bool = false
var _press_screen_pos: Vector2 = Vector2.ZERO
var _press_time_ms: int = 0
var _pressing: bool = false
@ -34,6 +38,9 @@ func _unhandled_input(event: InputEvent) -> void:
return
if event.button_index != MOUSE_BUTTON_LEFT:
return
# Designation paint mode owns input while active; Selection steps aside.
if designation_active:
return
if event.pressed:
_press_screen_pos = event.position
_press_time_ms = Time.get_ticks_msec()

View file

@ -21,6 +21,10 @@ 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")
const STOCKPILE_SCENE: PackedScene = preload("res://scenes/world/stockpile_zone.tscn")
const WALL_SCENE: PackedScene = preload("res://scenes/entities/wall.tscn")
const FLOOR_SCENE: PackedScene = preload("res://scenes/entities/floor.tscn")
const DOOR_SCENE: PackedScene = preload("res://scenes/entities/door.tscn")
const CRATE_SCENE: PackedScene = preload("res://scenes/world/crate.tscn")
# 3 starting pawns — Phase 2 demo. Phase 7+ replaces this with map-gen + name table.
const SAMPLE_PAWNS: Array[Dictionary] = [
@ -49,10 +53,12 @@ const HAUL_SWEEP_INTERVAL_TICKS: int = 100
@onready var fog_layer: TileMapLayer = $Fog
@onready var pathfinder: Pathfinder = $Pathfinder
@onready var selection: Selection = $Selection
@onready var designation_ctl: Designation = $DesignationCtl
@onready var rest_provider: RestProvider = $RestProvider
@onready var chop_provider: ChopProvider = $ChopProvider
@onready var mine_provider: MineProvider = $MineProvider
@onready var hauling_provider: HaulingProvider = $HaulingProvider
@onready var construction_provider: ConstructionProvider = $ConstructionProvider
func _ready() -> void:
@ -69,16 +75,32 @@ func _ready() -> void:
selection.bind(pathfinder)
World.pathfinder = pathfinder # expose to entities (Tree.fell() walkability checks, etc.)
# Register all 4 providers — Decision iterates by .priority desc.
# chop=5 > mine=4 > haul=3 > rest=0.
# Phase 5 — expose TileMap layer refs on the autoload so entity code
# (Wall._complete, Floor._complete) can stamp data-only tile state.
World.wall_layer = wall_layer
World.floor_layer = floor_layer
World.designation_layer = designation_layer
# Designation: bind the paint surface + the Selection guard.
designation_ctl.bind(designation_layer, selection)
# Register all 5 providers — Decision iterates by .priority desc.
# construction=6 > chop=5 > mine=4 > haul=3 > rest=0.
World.register_work_provider(construction_provider)
World.register_work_provider(chop_provider)
World.register_work_provider(mine_provider)
World.register_work_provider(hauling_provider)
World.register_work_provider(rest_provider)
# Phase 5: bridge designation paint events → spawn the ghost-state entity
# at that tile and register it as a build site.
EventBus.designation_added.connect(_on_designation_added)
EventBus.designation_cleared.connect(_on_designation_cleared)
_spawn_sample_pawns()
_spawn_sample_harvestables()
_spawn_sample_stockpiles()
_seed_phase5_demo_buildings()
_run_pathfinder_spike()
# Phase 4: every 5 in-game seconds (100 ticks), re-evaluate items in
@ -185,6 +207,37 @@ func _spawn_sample_harvestables() -> void:
Audit.log("world", "spawned %d trees + %d rocks" % [SAMPLE_TREES.size(), SAMPLE_ROCKS.size()])
func _seed_phase5_demo_buildings() -> void:
# Pre-queue a small cabin outline as build designations so pawns visibly
# construct walls when they exit Chop/Mine work. Phase 17 will add real
# player-driven designation UI; for now the player sees the construction
# loop without needing to paint anything.
#
# Layout: ~5×4 wall ring at (45, 25), with an open door slot.
var origin := Vector2i(45, 25)
var w := 5
var h := 4
for x in w:
EventBus.designation_added.emit(origin + Vector2i(x, 0), Designation.TOOL_BUILD_WALL)
EventBus.designation_added.emit(origin + Vector2i(x, h - 1), Designation.TOOL_BUILD_WALL)
for y in h:
EventBus.designation_added.emit(origin + Vector2i(0, y), Designation.TOOL_BUILD_WALL)
EventBus.designation_added.emit(origin + Vector2i(w - 1, y), Designation.TOOL_BUILD_WALL)
# Place a couple of crates at known tiles so the haul system has a target.
var crate_tiles: Array[Vector2i] = [Vector2i(17, 60), Vector2i(18, 60)]
for t in crate_tiles:
var c: Crate = CRATE_SCENE.instantiate()
add_child(c)
c.setup(t)
# Mark crate as already-built for the demo (skip the construction phase).
# Phase 17 player UI flow would walk it through a build designation first.
while c.is_buildable():
c.on_build_tick()
Audit.log("world", "phase 5 demo: %d wall designations seeded + %d crates built" % [
w * 2 + h * 2 - 4, crate_tiles.size()
])
func _spawn_sample_stockpiles() -> void:
# Two zones for the Phase 4 acceptance demo:
# - Zone A (north): wood-only filter, NORMAL priority (just a wood drop)
@ -210,6 +263,41 @@ func _spawn_sample_stockpiles() -> void:
Audit.log("world", "spawned 2 stockpiles: %s + %s" % [zone_a.label, zone_b.label])
# ── Phase 5: designation → build-site spawn bridge ──────────────────────────
# Track build sites keyed by tile so we can find + queue_free them on cancel.
var _build_sites_by_tile: Dictionary = {}
func _on_designation_added(cell: Vector2i, tool: StringName) -> void:
if _build_sites_by_tile.has(cell):
return # already a build site here
var entity = null
match tool:
&"build_wall":
entity = WALL_SCENE.instantiate()
add_child(entity)
entity.setup(cell, &"stone")
&"build_floor":
entity = FLOOR_SCENE.instantiate()
add_child(entity)
entity.setup(cell, &"wood")
_:
Audit.log("world", "unknown designation tool: %s" % tool)
return
_build_sites_by_tile[cell] = entity
Audit.log("world", "queued %s at %s" % [tool, cell])
func _on_designation_cleared(cell: Vector2i) -> void:
if not _build_sites_by_tile.has(cell):
return
var entity = _build_sites_by_tile[cell]
_build_sites_by_tile.erase(cell)
if is_instance_valid(entity) and not entity.is_completed():
entity.queue_free()
# ── periodic re-flow (the "wood floats up" cascade) ─────────────────────────
func _on_sim_tick_world_sweep(tick_n: int) -> void:

View file

@ -1,4 +1,4 @@
[gd_scene load_steps=9 format=3 uid="uid://rimlike_world"]
[gd_scene load_steps=11 format=3 uid="uid://rimlike_world"]
[ext_resource type="Script" path="res://scenes/world/world.gd" id="1_world"]
[ext_resource type="PackedScene" uid="uid://rimlike_camera_rig" path="res://scenes/world/camera_rig.tscn" id="2_camera"]
@ -8,8 +8,11 @@
[ext_resource type="Script" path="res://scenes/ai/chop_provider.gd" id="6_chop_provider"]
[ext_resource type="Script" path="res://scenes/ai/mine_provider.gd" id="7_mine_provider"]
[ext_resource type="Script" path="res://scenes/ai/hauling_provider.gd" id="8_hauling_provider"]
[ext_resource type="Script" path="res://scenes/ai/construction_provider.gd" id="9_construction_provider"]
[ext_resource type="Script" path="res://scenes/world/designation.gd" id="10_designation"]
[node name="World" type="Node2D"]
y_sort_enabled = true
script = ExtResource("1_world")
[node name="Terrain" type="TileMapLayer" parent="."]
@ -20,6 +23,7 @@ z_index = 1
[node name="Wall" type="TileMapLayer" parent="."]
z_index = 2
visible = false
[node name="Designation" type="TileMapLayer" parent="."]
z_index = 3
@ -38,6 +42,9 @@ script = ExtResource("3_pathfinder")
[node name="Selection" type="Node" parent="."]
script = ExtResource("4_selection")
[node name="DesignationCtl" type="Node" parent="."]
script = ExtResource("10_designation")
[node name="RestProvider" type="Node" parent="."]
script = ExtResource("5_rest_provider")
rest_tile = Vector2i(50, 50)
@ -51,5 +58,8 @@ script = ExtResource("7_mine_provider")
[node name="HaulingProvider" type="Node" parent="."]
script = ExtResource("8_hauling_provider")
[node name="ConstructionProvider" type="Node" parent="."]
script = ExtResource("9_construction_provider")
[node name="CameraRig" parent="." instance=ExtResource("2_camera")]
position = Vector2(640, 640)