rimlike/scenes/world/designation.gd
megaproxy f82807ff3d 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>
2026-05-10 22:11:40 +01:00

170 lines
6.3 KiB
GDScript

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)