diff --git a/autoload/strings.gd b/autoload/strings.gd index 2f5d14d..6cc4ba6 100644 --- a/autoload/strings.gd +++ b/autoload/strings.gd @@ -22,6 +22,12 @@ const TABLE: Dictionary = { # Pawn state labels &"pawn.state.idle": "idle", &"pawn.state.walking": "walking", + # Item types (player-visible this phase) + &"item.wood": "Wood", + &"item.stone": "Stone", + &"item.iron_ore": "Iron ore", + # Item stack count badge ("{n}" is substituted at call site via .format()) + &"item.stack_count": "×{n}", } diff --git a/autoload/world.gd b/autoload/world.gd index ccf16c6..a6b2bb5 100644 --- a/autoload/world.gd +++ b/autoload/world.gd @@ -11,10 +11,30 @@ extends Node # Phase 2 — pawn registry. items/furniture/animals/corpses arrive in later phases. var pawns: Array[Pawn] = [] -# Phase 3 — work providers (e.g. RestProvider). World scene registers them on _ready. -# Decision.pick_next_job() iterates this by .priority desc. +# Phase 3 — work providers (e.g. RestProvider, ChopProvider, HaulingProvider). +# World scene registers them on _ready. Decision.pick_next_job() iterates by .priority desc. var work_providers: Array = [] +# Phase 4 — harvestables + items + stockpiles. Entities call register_*/unregister_* +# from their _ready/_exit_tree. Phase 16 will add stable IDs and persistence wiring. +var trees: Array = [] # Array of Tree +var rocks: Array = [] # Array of Rock +var items: Array = [] # Array of Item (on-floor stacks) +var stockpiles: Array = [] # Array of StorageDestination (StockpileZone for now; containers Phase 5) + +# Phase 4 — pathfinder reference exposed for entity code that needs walkability +# checks (e.g. Tree.fell() picking neighbour tiles for wood drops). The actual +# Pathfinder node lives on the World scene as a child; the scene sets this in +# its _ready(). Don't access before the world scene is mounted. +var pathfinder = null + +# 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. +# HaulingProvider.sweep_for_better_destinations() re-marks items when a higher +# priority stockpile opens up (the priority cascade per design.md). +var items_needing_haul: Dictionary = {} + func register_work_provider(wp) -> void: assert(wp != null, "World.register_work_provider: provider is null") @@ -47,3 +67,54 @@ func pawn_at_tile(tile: Vector2i) -> Pawn: func clear_pawns() -> void: # For save-load / new-game flow in Phase 16. pawns.clear() + + +# ── Phase 4: harvestables + items + stockpiles ────────────────────────────── + +func register_tree(t) -> void: + if not trees.has(t): + trees.append(t) + + +func unregister_tree(t) -> void: + trees.erase(t) + + +func register_rock(r) -> void: + if not rocks.has(r): + rocks.append(r) + + +func unregister_rock(r) -> void: + rocks.erase(r) + + +func register_item(it) -> void: + if items.has(it): + return + items.append(it) + # Newly-spawned items always start as "needs haul" — HaulingProvider will + # clear the flag once the item lands in its highest-priority destination. + items_needing_haul[it] = true + + +func unregister_item(it) -> void: + items.erase(it) + items_needing_haul.erase(it) + + +func register_stockpile(s) -> void: + if not stockpiles.has(s): + stockpiles.append(s) + + +func unregister_stockpile(s) -> void: + stockpiles.erase(s) + + +func mark_item_needs_haul(it) -> void: + items_needing_haul[it] = true + + +func clear_item_haul_flag(it) -> void: + items_needing_haul.erase(it) diff --git a/docs/implementation.md b/docs/implementation.md index 73b5d73..4d3a6cf 100644 --- a/docs/implementation.md +++ b/docs/implementation.md @@ -10,7 +10,8 @@ Effort estimates are wall-time at **focused solo pace**. Scale up generously for | ✅ done — 80² map renders, walls/terrain/UI layers, camera rig, tick loop, speed UI all live | **Phase 1 — World, tilemap, camera** | | ✅ 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** | -| ⏳ next | **Phase 4 — First verbs: chop, mine, hauling, stockpiles** | +| ✅ 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** | 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. diff --git a/scenes/ai/chop_provider.gd b/scenes/ai/chop_provider.gd new file mode 100644 index 0000000..ba93088 --- /dev/null +++ b/scenes/ai/chop_provider.gd @@ -0,0 +1,49 @@ +class_name ChopProvider extends WorkProvider +## WorkProvider for the "chop" work category. +## +## Scans World.trees for the nearest choppable Tree (Manhattan distance from +## the requesting pawn) and returns a two-toil Job: +## walk_to(tree.tile) → interact(tree.get_path(), "on_chop_tick") +## +## The INTERACT toil calls Tree.on_chop_tick() once per sim tick; the Tree +## internally tracks chop_progress and calls fell() when CHOP_TICKS is +## reached. The toil finishes automatically when is_choppable() returns +## false (felled) or when the node is freed. +## +## Phase 4 simplification: trees do not block pathfinding, so walking directly +## to tree.tile is valid. No adjacency-offset needed. +## +## Duck-typing note: Tree is referenced without class_name (class may not be +## registered yet when this provider loads). We rely only on: +## tree.tile: Vector2i +## tree.is_choppable() -> bool +## tree.get_path() -> NodePath + + +func _init() -> void: + category = &"chop" + priority = 5 # Higher than rest (priority 0); scanned before it by Decision. + + +## Returns a Job targeting the nearest choppable Tree, 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 tree in World.trees: + if not tree.is_choppable(): + continue + var d: int = abs(tree.tile.x - pawn.tile.x) + abs(tree.tile.y - pawn.tile.y) + if d < best_dist: + best_dist = d + best = tree + + if best == null: + return null + + var j := Job.new() + j.label = "Chop tree at %s" % best.tile + j.toils.append(Toil.walk_to(best.tile)) + j.toils.append(Toil.interact(best.get_path(), &"on_chop_tick")) + return j diff --git a/scenes/ai/chop_provider.gd.uid b/scenes/ai/chop_provider.gd.uid new file mode 100644 index 0000000..a1cb673 --- /dev/null +++ b/scenes/ai/chop_provider.gd.uid @@ -0,0 +1 @@ +uid://b5wgnawgoqy1v diff --git a/scenes/ai/hauling_provider.gd b/scenes/ai/hauling_provider.gd new file mode 100644 index 0000000..e9fe13b --- /dev/null +++ b/scenes/ai/hauling_provider.gd @@ -0,0 +1,148 @@ +class_name HaulingProvider extends WorkProvider +## WorkProvider for the Hauling work category. Slots into the 5-layer pawn AI +## (Decision → WorkProvider → Job + JobRunner) as layer 2. +## +## Each call to find_best_for(pawn) scans World.items_needing_haul for the +## item closest to `pawn` that has a valid, reachable destination, then builds +## a 4-toil haul job: walk → pickup → walk → deposit. +## +## sweep_for_better_destinations() is a periodic helper (called by World every +## ~100 sim ticks) that marks items in lower-priority destinations dirty when a +## higher-priority destination has space — enabling the "items flow upward" +## priority cascade described in design.md. +## +## Pawn is intentionally duck-typed (no class_name reference) to match the +## WorkProvider convention and avoid init-order issues. +## +## See docs/architecture.md "HaulingProvider". + + +func _init() -> void: + category = &"haul" + # Priority 3 — below chop (5) and mine (4); above rest (1). + # Adjusted once the full 9-category matrix is authored in Phase 17. + priority = 3 + + +# ── 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. +## 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. + if pawn.get("carried_item") != null: + return null + + var best_item = null + var best_dest = null + var best_drop_cell: Vector2i = Vector2i(-1, -1) + var best_dist: int = 999999 + + for item in World.items_needing_haul.keys(): + # Skip items another pawn is already carrying. + if item.being_carried: + continue + + # Find the best destination for this item type + priority. + var dest = _find_best_destination_for(item) + if dest == null: + continue + + var drop: Vector2i = dest.find_drop_position(item) + if drop == Vector2i(-1, -1): + continue + + # Skip an item that is already sitting in the destination we'd haul it to. + # Avoids pointless re-haul of an item that is exactly where it should be. + # (Phase 16 refines this once the item→destination link is persisted.) + var current_dest = _destination_for_tile(item.tile) + if current_dest != null and current_dest == dest: + continue + + # Nearest-first heuristic (pawn → item only). + var d: int = abs(item.tile.x - pawn.tile.x) + abs(item.tile.y - pawn.tile.y) + if d < best_dist: + best_dist = d + best_item = item + best_dest = dest + best_drop_cell = drop + + 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()) + return j + + +# ── priority cascade ────────────────────────────────────────────────────────── + +## Periodic sweep (called by World every ~100 sim ticks). +## Walks all items NOT already in the dirty set and marks them dirty when: +## (a) they are loose on the floor with no destination covering their tile, OR +## (b) they are in a stockpile but a higher-priority destination now has room. +## Returns the count of newly marked items (logged when > 0). +## This is the mechanism that makes "items flow up" to Critical stockpiles. +func sweep_for_better_destinations() -> int: + var count: int = 0 + for item in World.items: + if item.being_carried: + continue + # Already flagged — HaulingProvider will handle it. + if World.items_needing_haul.has(item): + continue + + var current = _destination_for_tile(item.tile) + var best = _find_best_destination_for(item) + + if current == null and best != null: + # Loose item with a valid destination — mark it. + World.items_needing_haul[item] = true + count += 1 + elif current != null and best != null: + # Item is stored, but a better destination exists. + if int(best.priority) < int(current.priority): + World.items_needing_haul[item] = true + count += 1 + + if count > 0: + Audit.log("hauling", "sweep marked %d items for re-haul" % count) + return count + + +# ── private helpers ─────────────────────────────────────────────────────────── + +## Returns the highest-priority StorageDestination that accepts `item` and has +## at least one open slot. Among equal-priority destinations, first found wins. +## Returns null when no destination qualifies. +func _find_best_destination_for(item): + var best = null + for dest in World.stockpiles: + if not dest.accepts(item): + continue + if dest.find_drop_position(item) == Vector2i(-1, -1): + continue + # Lower enum int = higher priority (CRITICAL=0 beats HIGH=1). + if best == null or int(dest.priority) < int(best.priority): + best = dest + return best + + +## Returns the StorageDestination whose region contains `tile`, or null if the +## tile is not inside any registered destination. +func _destination_for_tile(tile: Vector2i): + for dest in World.stockpiles: + if dest.covers_tile(tile): + return dest + return null diff --git a/scenes/ai/hauling_provider.gd.uid b/scenes/ai/hauling_provider.gd.uid new file mode 100644 index 0000000..4df300a --- /dev/null +++ b/scenes/ai/hauling_provider.gd.uid @@ -0,0 +1 @@ +uid://6mkqd2t286tn diff --git a/scenes/ai/job_runner.gd b/scenes/ai/job_runner.gd index ab8ff56..8632abb 100644 --- a/scenes/ai/job_runner.gd +++ b/scenes/ai/job_runner.gd @@ -91,6 +91,12 @@ func tick() -> void: _tick_wait(t) Toil.KIND_IDLE: pass # Never completes on its own — Decision or player overrides. + Toil.KIND_INTERACT: + _tick_interact(t) + Toil.KIND_PICKUP: + _tick_pickup(t) + Toil.KIND_DEPOSIT: + _tick_deposit(t) if t.done: job.advance() @@ -173,6 +179,109 @@ func _tick_wait(t) -> void: t.done = true +## Execute one tick of an INTERACT toil. +## +## First tick: resolve the target node from the stored NodePath string. +## If the target is gone or freed, log and skip immediately (done=true). +## Otherwise mark started and log the action start. +## +## Every subsequent tick: call tick_method on the target. After the call, +## check whether the target has been consumed (is_choppable/is_mineable +## returns false, or the node was freed). If so, mark done. +func _tick_interact(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 interact target gone — skipping" % pawn.pawn_name + ) + t.done = true + return + t.data["started"] = true + Audit.log( + "job_runner", + "%s interact start: %s.%s" % [pawn.pawn_name, target.name, t.data.get("tick_method", "")] + ) + + # 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.call(StringName(t.data.get("tick_method", ""))) + + # Re-check validity after the call (the call may have freed the node). + if target == null or not is_instance_valid(target): + t.done = true + return + if target.has_method("is_choppable") and not target.is_choppable(): + Audit.log("job_runner", "%s interact done: %s chopped" % [pawn.pawn_name, target.name]) + t.done = true + return + if target.has_method("is_mineable") and not target.is_mineable(): + Audit.log("job_runner", "%s interact done: %s mined" % [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. +## Transfers it into pawn.carried_item via set_being_carried(true). +## Completes in a single tick. +func _tick_pickup(t) -> void: + var item = null + for it in World.items: + if it.tile == pawn.tile and not it.being_carried: + item = it + break + if item == null: + Audit.log( + "job_runner", + "%s pickup: no item at %s" % [pawn.pawn_name, pawn.tile] + ) + t.done = true + return + pawn.carried_item = item + item.set_being_carried(true) + Audit.log( + "job_runner", + "%s pickup: %s ×%d" % [pawn.pawn_name, item.item_type, item.stack_size] + ) + t.done = true + + +## Execute one tick of a DEPOSIT toil. +## +## Places pawn.carried_item at pawn.tile (pixel-centred in the 16 px grid). +## Clears pawn.carried_item. Completes in a single tick. +func _tick_deposit(t) -> void: + if pawn.carried_item == null: + Audit.log( + "job_runner", + "%s deposit: nothing to deposit" % pawn.pawn_name + ) + t.done = true + return + var item = pawn.carried_item + item.tile = pawn.tile + item.position = Vector2(pawn.tile.x * 16 + 8, pawn.tile.y * 16 + 8) + item.set_being_carried(false) + pawn.carried_item = null + # Phase 4: clear the haul-dirty flag — item has landed at its destination. + # The periodic sweep_for_better_destinations will re-mark it if a higher- + # priority destination opens up later. + World.clear_item_haul_flag(item) + Audit.log( + "job_runner", + "%s deposit: %s ×%d at %s" % [pawn.pawn_name, item.item_type, item.stack_size, pawn.tile] + ) + t.done = true + + # ── helpers ────────────────────────────────────────────────────────────────── ## Emit job_completed, log, and clear the job reference. diff --git a/scenes/ai/mine_provider.gd b/scenes/ai/mine_provider.gd new file mode 100644 index 0000000..949e870 --- /dev/null +++ b/scenes/ai/mine_provider.gd @@ -0,0 +1,50 @@ +class_name MineProvider extends WorkProvider +## WorkProvider for the "mine" work category. +## +## Scans World.rocks for the nearest mineable Rock (Manhattan distance from +## the requesting pawn) and returns a two-toil Job: +## walk_to(rock.tile) → interact(rock.get_path(), "on_mine_tick") +## +## The INTERACT toil calls Rock.on_mine_tick() once per sim tick; the Rock +## internally tracks mine_progress and handles removal when MINE_TICKS is +## reached. The toil finishes automatically when is_mineable() returns +## false (exhausted) or when the node is freed. +## +## Phase 4 simplification: rocks are assumed walkable during mining approach +## (they may block movement in a later phase once obstruction is added to the +## pathfinder). +## +## Duck-typing note: Rock is referenced without class_name (class may not be +## registered yet when this provider loads). We rely only on: +## rock.tile: Vector2i +## rock.is_mineable() -> bool +## rock.get_path() -> NodePath + + +func _init() -> void: + category = &"mine" + priority = 4 # Slightly lower than chop (5); both higher than rest (0). + + +## Returns a Job targeting the nearest mineable Rock, 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 rock in World.rocks: + if not rock.is_mineable(): + continue + var d: int = abs(rock.tile.x - pawn.tile.x) + abs(rock.tile.y - pawn.tile.y) + if d < best_dist: + best_dist = d + best = rock + + if best == null: + return null + + var j := Job.new() + j.label = "Mine rock at %s" % best.tile + j.toils.append(Toil.walk_to(best.tile)) + j.toils.append(Toil.interact(best.get_path(), &"on_mine_tick")) + return j diff --git a/scenes/ai/mine_provider.gd.uid b/scenes/ai/mine_provider.gd.uid new file mode 100644 index 0000000..cd73bb7 --- /dev/null +++ b/scenes/ai/mine_provider.gd.uid @@ -0,0 +1 @@ +uid://dgnufybspp1ja diff --git a/scenes/ai/toil.gd b/scenes/ai/toil.gd index 42c9fc6..f043c4a 100644 --- a/scenes/ai/toil.gd +++ b/scenes/ai/toil.gd @@ -13,6 +13,9 @@ class_name Toil extends RefCounted const KIND_WALK: StringName = &"walk" const KIND_WAIT: StringName = &"wait" 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 var kind: StringName = KIND_IDLE ## Toil-specific params — all values must be int, float, bool, String, Dict, or Array. @@ -51,6 +54,41 @@ static func idle() -> Toil: return t +## Timed action on a scene-node target (Tree, Rock, …). +## `target_node_path` is the NodePath of the entity; stored as String for JSON safety. +## `tick_method` is the method to call each sim tick (e.g. "on_chop_tick"). +## JobRunner resolves the node at first-tick and calls tick_method every sim tick +## until the target is no longer choppable/mineable (method source sets done via +## is_choppable() / is_mineable() returning false). +static func interact(target_node_path: NodePath, tick_method: StringName) -> Toil: + var t := Toil.new() + t.kind = KIND_INTERACT + t.data = { + "target": String(target_node_path), + "tick_method": String(tick_method), + "started": false, + } + return t + + +## Pick up an Item at pawn.tile into pawn.carried_item. Single-tick action. +## data is empty — the item is located at pawn.tile at execution time. +static func pickup() -> Toil: + var t := Toil.new() + t.kind = KIND_PICKUP + t.data = {} + 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: + var t := Toil.new() + t.kind = KIND_DEPOSIT + t.data = {} + return t + + # ── save / load ────────────────────────────────────────────────────────────── func to_dict() -> Dictionary: diff --git a/scenes/entities/item.gd b/scenes/entities/item.gd new file mode 100644 index 0000000..fcc339a --- /dev/null +++ b/scenes/entities/item.gd @@ -0,0 +1,151 @@ +## Dropped item entity — a single stack of one item type lying on the world floor. +## +## Visuals are drawn procedurally via _draw() (Phase 4 placeholder). Real +## ElvGames item icons land in Phase 5+. +## +## Item type constants mirror the 16 filter chips in docs/design.md. They are +## used by StockpileZone filter bitmasks and pawn-carry typing. +## +## World registration (World.register_item / World.unregister_item) is called +## here but the methods land in World during Opus integration. The script will +## parse cleanly; the call will fail at runtime until then. + +class_name Item extends Node2D + +const TILE_SIZE_PX: int = 16 + +# ── canonical type registry — matches docs/design.md "16 filter chips" ─────── + +const TYPE_WOOD: StringName = &"wood" # Wd +const TYPE_STONE: StringName = &"stone" # St +const TYPE_IRON_ORE: StringName = &"iron_ore" # Ir +const TYPE_COPPER_ORE: StringName = &"copper_ore" # Cu +const TYPE_SILVER: StringName = &"silver" # Ag +const TYPE_GOLD: StringName = &"gold" # Au +const TYPE_CLOTH: StringName = &"cloth" # Cl +const TYPE_VEGETABLE: StringName = &"vegetable" # Veg +const TYPE_MEAT: StringName = &"meat" # Mt +const TYPE_GRAIN: StringName = &"grain" # Gr +const TYPE_MEAL: StringName = &"meal" # Ck (cooked) +const TYPE_MEDICINE: StringName = &"medicine" # Md +const TYPE_TOOL: StringName = &"tool" # Tl +const TYPE_WEAPON: StringName = &"weapon" # Wp +const TYPE_ARMOR: StringName = &"armor" # Ar +const TYPE_CORPSE: StringName = &"corpse" # Co + +const ALL_TYPES: Array[StringName] = [ + TYPE_WOOD, TYPE_STONE, TYPE_IRON_ORE, TYPE_COPPER_ORE, + TYPE_SILVER, TYPE_GOLD, TYPE_CLOTH, TYPE_VEGETABLE, + TYPE_MEAT, TYPE_GRAIN, TYPE_MEAL, TYPE_MEDICINE, + TYPE_TOOL, TYPE_WEAPON, TYPE_ARMOR, TYPE_CORPSE, +] + +# ── state ──────────────────────────────────────────────────────────────────── + +@export var item_type: StringName = TYPE_WOOD +@export var stack_size: int = 1 + +var tile: Vector2i = Vector2i.ZERO + +## When true the on-floor visual is suppressed; the carrying pawn renders the +## carry indicator instead. +var being_carried: bool = false + + +# ── lifecycle ───────────────────────────────────────────────────────────────── + +func _ready() -> void: + position = _tile_to_world(tile) + visible = not being_carried + + +func _exit_tree() -> void: + World.unregister_item(self) + + +# ── public API ──────────────────────────────────────────────────────────────── + +## One-shot initialiser called by the spawning code (Tree.fell, Rock.mined, etc.) +## Sets all fields, syncs position, and registers with World. +func setup(p_type: StringName, p_stack: int, p_tile: Vector2i) -> void: + item_type = p_type + stack_size = p_stack + tile = p_tile + position = _tile_to_world(tile) + visible = not being_carried + queue_redraw() + World.register_item(self) + Audit.log("item", "spawned %s×%d at %s" % [item_type, stack_size, tile]) + + +## Hide/show the on-floor sprite when the pawn picks up or drops this item. +func set_being_carried(value: bool) -> void: + being_carried = value + visible = not being_carried + + +# ── save / load ─────────────────────────────────────────────────────────────── + +func to_dict() -> Dictionary: + return { + "type": String(item_type), + "stack_size": stack_size, + "tile_x": tile.x, + "tile_y": tile.y, + } + + +## Returns a plain Dictionary spec for World.load_items() to instantiate from. +## Items cannot reconstruct themselves standalone — they need a parent in the +## scene tree. World adds the node, then calls setup() from the returned dict. +static func from_dict(d: Dictionary) -> Dictionary: + return { + "type": StringName(d.get("type", "wood")), + "stack_size": int(d.get("stack_size", 1)), + "tile_x": int(d.get("tile_x", 0)), + "tile_y": int(d.get("tile_y", 0)), + } + + +# ── render ──────────────────────────────────────────────────────────────────── + +func _draw() -> void: + # 12×12 coloured square centered on the tile; colour hashed from item_type. + var hue := float(item_type.hash() % 360) / 360.0 + var fill := Color.from_hsv(hue, 0.6, 0.85) + var half: int = 6 + var square := Rect2(Vector2(-half, -half), Vector2(half * 2, half * 2)) + + draw_rect(square, fill) + draw_rect(square, Color(0.0, 0.0, 0.0, 0.75), false, 1.0) + + # Stack count badge — bottom-right corner of the square, font_size 7. + if stack_size > 1: + var label := Strings.t(&"item.stack_count").format({"n": stack_size}) + draw_string( + ThemeDB.fallback_font, + Vector2(half - 1, half - 1), + label, + HORIZONTAL_ALIGNMENT_RIGHT, + -1, + 7, + Color(0.0, 0.0, 0.0, 0.6) # drop-shadow offset below + ) + draw_string( + ThemeDB.fallback_font, + Vector2(half - 2, half - 2), + label, + HORIZONTAL_ALIGNMENT_RIGHT, + -1, + 7, + Color(1.0, 1.0, 1.0, 1.0) + ) + + +# ── helpers ─────────────────────────────────────────────────────────────────── + +func _tile_to_world(t: Vector2i) -> Vector2: + return Vector2( + t.x * TILE_SIZE_PX + TILE_SIZE_PX / 2.0, + t.y * TILE_SIZE_PX + TILE_SIZE_PX / 2.0 + ) diff --git a/scenes/entities/item.gd.uid b/scenes/entities/item.gd.uid new file mode 100644 index 0000000..769fea4 --- /dev/null +++ b/scenes/entities/item.gd.uid @@ -0,0 +1 @@ +uid://576k8p7pk4xx diff --git a/scenes/entities/item.tscn b/scenes/entities/item.tscn new file mode 100644 index 0000000..052ad06 --- /dev/null +++ b/scenes/entities/item.tscn @@ -0,0 +1,6 @@ +[gd_scene load_steps=2 format=3 uid="uid://item_entity"] + +[ext_resource type="Script" path="res://scenes/entities/item.gd" id="1_item"] + +[node name="Item" type="Node2D"] +script = ExtResource("1_item") diff --git a/scenes/entities/rock.gd b/scenes/entities/rock.gd new file mode 100644 index 0000000..bd88522 --- /dev/null +++ b/scenes/entities/rock.gd @@ -0,0 +1,147 @@ +## Rock entity — mineable by a pawn with a Mine job. Drops a stone Item node +## when mined out. +## +## Mirrors Tree's chopping model; stone is harder so MINE_TICKS is longer. +## A MineProvider (Opus, Phase 4) creates a Job whose INTERACT toil calls +## on_mine_tick() once per sim tick via JobRunner. +## +## World registration (World.register_rock / World.unregister_rock) is called +## here but the methods land in World during Opus integration. + +class_name Rock extends Node2D + +const TILE_SIZE_PX: int = 16 + +## Sim ticks to mine a rock at 1× speed (120 ticks = 6 sim seconds at 20 Hz). +## Stone is harder than wood — MINE_TICKS > Tree.CHOP_TICKS. +const MINE_TICKS: int = 120 +## Stone Items dropped on a successful mine. +const STONE_DROPS_ON_MINE: int = 1 + +# ── state ───────────────────────────────────────────────────────────────────── + +var tile: Vector2i = Vector2i.ZERO +## 0..MINE_TICKS. Advanced by on_mine_tick(); rock is mined when equal to MINE_TICKS. +var mine_progress: int = 0 + +# Preloaded scene for spawned stone items. +const ITEM_SCENE: PackedScene = preload("res://scenes/entities/item.tscn") + + +# ── lifecycle ───────────────────────────────────────────────────────────────── + +func _ready() -> void: + position = _tile_to_world(tile) + World.register_rock(self) + + +func _exit_tree() -> void: + World.unregister_rock(self) + + +# ── public API ──────────────────────────────────────────────────────────────── + +## One-shot initialiser. Call after add_child() so _ready() already fired. +func setup(start_tile: Vector2i) -> void: + tile = start_tile + mine_progress = 0 + position = _tile_to_world(tile) + queue_redraw() + Audit.log("rock", "spawned at %s" % tile) + + +## True when the rock hasn't been fully mined yet. +func is_mineable() -> bool: + return mine_progress < MINE_TICKS + + +## Called by the INTERACT toil in JobRunner once per sim tick while the pawn +## works this rock. Advances mine_progress and triggers mined() when complete. +func on_mine_tick() -> void: + if not is_mineable(): + return + mine_progress += 1 + queue_redraw() + if mine_progress >= MINE_TICKS: + mined() + + +## Drop stone Item(s) and free this node. Called automatically by on_mine_tick() +## but also accessible for scripted removal (debug, storyteller events). +func mined() -> void: + # Single drop lands on the rock's own tile. + var item: Item = ITEM_SCENE.instantiate() + get_parent().add_child(item) + item.setup(Item.TYPE_STONE, 1, tile) + Audit.log("rock", "mined at %s; %d stone drop" % [tile, STONE_DROPS_ON_MINE]) + queue_free() + + +# ── save / load ─────────────────────────────────────────────────────────────── + +func to_dict() -> Dictionary: + return { + "tile_x": tile.x, + "tile_y": tile.y, + "mine_progress": mine_progress, + } + + +static func from_dict(d: Dictionary) -> Dictionary: + return { + "tile_x": int(d.get("tile_x", 0)), + "tile_y": int(d.get("tile_y", 0)), + "mine_progress": int(d.get("mine_progress", 0)), + } + + +# ── render ──────────────────────────────────────────────────────────────────── + +func _draw() -> void: + # Angular cluster of 3–4 triangles in a dark-grey / light-grey palette. + var c1 := Color(0.55, 0.55, 0.50) # light face + var c2 := Color(0.38, 0.38, 0.36) # shadow face + + # Main body polygon (roughly an irregular hex). + var body := PackedVector2Array([ + Vector2(-5.0, 3.0), + Vector2(-6.0, -1.0), + Vector2(-2.0, -6.0), + Vector2(3.0, -5.0), + Vector2(6.0, 0.0), + Vector2(4.0, 4.0), + ]) + draw_colored_polygon(body, c1) + + # Shadow face on the bottom-right triangle to give depth. + var shadow := PackedVector2Array([ + Vector2(3.0, -5.0), + Vector2(6.0, 0.0), + Vector2(4.0, 4.0), + Vector2(-5.0, 3.0), + ]) + draw_colored_polygon(shadow, c2) + + # Outline. + draw_polyline(body, Color(0.0, 0.0, 0.0, 0.5), 1.0) + draw_line(body[5], body[0], Color(0.0, 0.0, 0.0, 0.5), 1.0) + + # Mine-progress crack: a dark jagged line on the face when partially mined. + if mine_progress > 0: + var ratio := float(mine_progress) / float(MINE_TICKS) + var crack_len := ratio * 5.0 + draw_line( + Vector2(-1.0, -2.0), + Vector2(-1.0 + crack_len, 1.0), + Color(0.15, 0.12, 0.10, 0.85), + 1.5 + ) + + +# ── helpers ─────────────────────────────────────────────────────────────────── + +func _tile_to_world(t: Vector2i) -> Vector2: + return Vector2( + t.x * TILE_SIZE_PX + TILE_SIZE_PX / 2.0, + t.y * TILE_SIZE_PX + TILE_SIZE_PX / 2.0 + ) diff --git a/scenes/entities/rock.gd.uid b/scenes/entities/rock.gd.uid new file mode 100644 index 0000000..27edcb8 --- /dev/null +++ b/scenes/entities/rock.gd.uid @@ -0,0 +1 @@ +uid://dpy14o4grgsgt diff --git a/scenes/entities/rock.tscn b/scenes/entities/rock.tscn new file mode 100644 index 0000000..6629b41 --- /dev/null +++ b/scenes/entities/rock.tscn @@ -0,0 +1,6 @@ +[gd_scene load_steps=2 format=3 uid="uid://rock_entity"] + +[ext_resource type="Script" path="res://scenes/entities/rock.gd" id="1_rock"] + +[node name="Rock" type="Node2D"] +script = ExtResource("1_rock") diff --git a/scenes/entities/tree.gd b/scenes/entities/tree.gd new file mode 100644 index 0000000..ad020dd --- /dev/null +++ b/scenes/entities/tree.gd @@ -0,0 +1,162 @@ +## Tree entity — choppable by a pawn with a Chop job. Drops wood Item nodes +## when felled. +## +## Chopping model (docs/implementation.md Phase 4): +## A ChopProvider creates a Job whose INTERACT toil calls on_chop_tick() once +## per sim tick via JobRunner. After CHOP_TICKS ticks the tree is felled. +## +## World registration (World.register_tree / World.unregister_tree) is called +## here but the methods land in World during Opus integration. + +class_name HarvestableTree extends Node2D +## NOTE: class_name is HarvestableTree because Godot 4 ships a built-in `Tree` +## Control node — using "Tree" would shadow that. Filename / scene name stay +## as `tree` because the game-side concept is still just "tree". + +const TILE_SIZE_PX: int = 16 + +## Sim ticks to fell a tree at 1× speed (80 ticks = ~4 sim seconds at 20 Hz). +const CHOP_TICKS: int = 80 +## Number of separate wood Item nodes dropped on fell. +const WOOD_DROPS_ON_FELL: int = 3 +## Stack size per dropped Item (Phase 4 simplicity: 3 items of stack 1 each). +const STACK_SIZE_PER_DROP: int = 1 + +# ── state ───────────────────────────────────────────────────────────────────── + +var tile: Vector2i = Vector2i.ZERO +## 0..CHOP_TICKS. Advanced by on_chop_tick(); tree is felled when equal to CHOP_TICKS. +var chop_progress: int = 0 + +# Preloaded scene for spawned wood items. +const ITEM_SCENE: PackedScene = preload("res://scenes/entities/item.tscn") + + +# ── lifecycle ───────────────────────────────────────────────────────────────── + +func _ready() -> void: + position = _tile_to_world(tile) + World.register_tree(self) + + +func _exit_tree() -> void: + World.unregister_tree(self) + + +# ── public API ──────────────────────────────────────────────────────────────── + +## One-shot initialiser. Call after add_child() so _ready() already fired. +func setup(start_tile: Vector2i) -> void: + tile = start_tile + chop_progress = 0 + position = _tile_to_world(tile) + queue_redraw() + Audit.log("tree", "spawned at %s" % tile) + + +## True when the tree hasn't been fully chopped yet. +func is_choppable() -> bool: + return chop_progress < CHOP_TICKS + + +## Called by the INTERACT toil in JobRunner once per sim tick while the pawn +## works this tree. Advances chop_progress and fells the tree when complete. +func on_chop_tick() -> void: + if not is_choppable(): + return + chop_progress += 1 + queue_redraw() + if chop_progress >= CHOP_TICKS: + fell() + + +## Drop wood Items and free this node. Called by on_chop_tick() automatically, +## but also accessible for scripted felling (debug, storyteller events). +func fell() -> void: + var drop_tiles := _pick_drop_tiles() + var drops_count := 0 + for drop_tile in drop_tiles: + var item: Item = ITEM_SCENE.instantiate() + get_parent().add_child(item) + item.setup(Item.TYPE_WOOD, STACK_SIZE_PER_DROP, drop_tile) + drops_count += 1 + Audit.log("tree", "felled at %s; %d wood drops" % [tile, drops_count]) + queue_free() + + +# ── save / load ─────────────────────────────────────────────────────────────── + +func to_dict() -> Dictionary: + return { + "tile_x": tile.x, + "tile_y": tile.y, + "chop_progress": chop_progress, + } + + +static func from_dict(d: Dictionary) -> Dictionary: + return { + "tile_x": int(d.get("tile_x", 0)), + "tile_y": int(d.get("tile_y", 0)), + "chop_progress": int(d.get("chop_progress", 0)), + } + + +# ── render ──────────────────────────────────────────────────────────────────── + +func _draw() -> void: + # Brown trunk: small filled rect at centre-bottom (~4 wide × 6 tall). + var trunk_color := Color(0.45, 0.28, 0.12) + draw_rect(Rect2(Vector2(-2.0, 1.0), Vector2(4.0, 6.0)), trunk_color) + + # Green canopy: large filled circle centered near the top. + var canopy_color := Color(0.22, 0.60, 0.18) + draw_circle(Vector2(0.0, -3.0), 7.0, canopy_color) + + # Canopy outline. + draw_arc(Vector2(0.0, -3.0), 7.0, 0.0, TAU, 24, Color(0.0, 0.0, 0.0, 0.4), 1.0) + + # Chop-progress wedge: a dark angled line on the trunk when partially chopped. + if chop_progress > 0: + var ratio := float(chop_progress) / float(CHOP_TICKS) + var notch_depth := ratio * 3.0 + draw_line( + Vector2(-2.0, 2.0 + notch_depth), + Vector2(2.0, 2.0), + Color(0.15, 0.08, 0.02, 0.9), + 1.5 + ) + + +# ── helpers ─────────────────────────────────────────────────────────────────── + +## Returns up to WOOD_DROPS_ON_FELL tile positions for wood drops. +## Prefers the tree's own tile then walkable 4-neighbours; falls back to the +## tree tile for any remaining drops when neighbours are scarce. +func _pick_drop_tiles() -> Array[Vector2i]: + var chosen: Array[Vector2i] = [] + + # First drop always goes on the tree's tile itself. + chosen.append(tile) + + # Remaining drops prefer walkable neighbours. + var offsets: Array[Vector2i] = [Vector2i(1, 0), Vector2i(-1, 0), Vector2i(0, 1), Vector2i(0, -1)] + for offset in offsets: + if chosen.size() >= WOOD_DROPS_ON_FELL: + break + var candidate: Vector2i = tile + offset + if World.pathfinder != null and World.pathfinder.is_walkable(candidate): + chosen.append(candidate) + + # Fill any remaining slots with the tree tile (all 3 land there if boxed in). + while chosen.size() < WOOD_DROPS_ON_FELL: + chosen.append(tile) + + return chosen + + +func _tile_to_world(t: Vector2i) -> Vector2: + return Vector2( + t.x * TILE_SIZE_PX + TILE_SIZE_PX / 2.0, + t.y * TILE_SIZE_PX + TILE_SIZE_PX / 2.0 + ) diff --git a/scenes/entities/tree.gd.uid b/scenes/entities/tree.gd.uid new file mode 100644 index 0000000..7a29320 --- /dev/null +++ b/scenes/entities/tree.gd.uid @@ -0,0 +1 @@ +uid://cpg0v8f6hajgi diff --git a/scenes/entities/tree.tscn b/scenes/entities/tree.tscn new file mode 100644 index 0000000..a9eaf1e --- /dev/null +++ b/scenes/entities/tree.tscn @@ -0,0 +1,6 @@ +[gd_scene load_steps=2 format=3 uid="uid://tree_entity"] + +[ext_resource type="Script" path="res://scenes/entities/tree.gd" id="1_tree"] + +[node name="Tree" type="Node2D"] +script = ExtResource("1_tree") diff --git a/scenes/pawn/pawn.gd b/scenes/pawn/pawn.gd index a7fb3ff..5328b23 100644 --- a/scenes/pawn/pawn.gd +++ b/scenes/pawn/pawn.gd @@ -42,6 +42,11 @@ var forced_job = null # can be paired with the pathfinder). May be null in tests / pre-Phase-3 scenes. var job_runner = null +# Phase 4 — carry slot for hauling. Holds an Item node while carrying; null +# when empty-handed. PICKUP toil sets this; DEPOSIT clears it. One stack / +# one type at a time per design.md. +var carried_item = null + var _path: Array[Vector2i] = [] var _step_progress: float = 0.0 var _selected: bool = false @@ -142,6 +147,9 @@ func from_dict(d: Dictionary) -> void: func _on_sim_tick(_tick_number: int) -> void: _orchestrate_ai() _advance_walk() + # Phase 4 — the carry indicator changes when PICKUP/DEPOSIT toils mutate + # carried_item directly. Cheapest reliable redraw hook is here. + queue_redraw() func _orchestrate_ai() -> void: @@ -201,6 +209,13 @@ func _draw() -> void: if _selected: draw_arc(Vector2.ZERO, 10.0, 0.0, TAU, 32, Color(1.0, 0.9, 0.2, 0.85), 2.0) + # Phase 4 — carry indicator: small coloured square at upper-right of body. + if carried_item != null: + var ci_hue := float(carried_item.item_type.hash() % 360) / 360.0 + var ci_color := Color.from_hsv(ci_hue, 0.6, 0.85) + draw_rect(Rect2(6, -10, 7, 7), ci_color) + draw_rect(Rect2(6, -10, 7, 7), Color(0, 0, 0, 0.7), false, 1.0) + # ── helpers ───────────────────────────────────────────────────────────────── diff --git a/scenes/world/stockpile_zone.gd b/scenes/world/stockpile_zone.gd new file mode 100644 index 0000000..644c44d --- /dev/null +++ b/scenes/world/stockpile_zone.gd @@ -0,0 +1,96 @@ +class_name StockpileZone extends StorageDestination +## Concrete floor stockpile zone. A rectangular region (in tile coords) that +## accepts items matching the filter and deposits them one-per-tile. +## +## Rendered as a translucent priority-tinted overlay via _draw(). The overlay +## is always visible — Phase 17 will toggle it when the Zones panel is open. +## z_index = -1 keeps the tint below items (z_index 0) and pawns. +## +## Register/unregister with World.stockpiles happen automatically in +## _ready / _exit_tree — no external wiring needed. +## +## One-stack-per-tile, one-type-per-tile rule (design.md). +## +## See docs/architecture.md "StockpileZone". + +## Region in tile coordinates. (0,0) relative to this node's map position; +## in practice this node lives at world origin so region is in world-tile space. +@export var region: Rect2i = Rect2i(0, 0, 4, 4) + +## Player-visible label shown in zone inspect UI (Phase 17). +@export var label: String = "Stockpile" + +## Pixel size of one tile — must match World.TILE_SIZE_PX. +const _TILE_PX: int = 16 + +## Priority-keyed fill colors for the overlay (Color(r, g, b, a)). +const _PRIORITY_COLORS: Dictionary = { + StorageDestination.Priority.CRITICAL: Color(0.9, 0.3, 0.3, 0.15), + StorageDestination.Priority.HIGH: Color(0.9, 0.6, 0.3, 0.15), + StorageDestination.Priority.NORMAL: Color(0.9, 0.9, 0.3, 0.12), + StorageDestination.Priority.LOW: Color(0.3, 0.9, 0.3, 0.10), + StorageDestination.Priority.OFF: Color(0.3, 0.3, 0.3, 0.10), +} + + +func _ready() -> void: + z_index = -1 + World.register_stockpile(self) + queue_redraw() + + +func _exit_tree() -> void: + World.unregister_stockpile(self) + + +# ── StorageDestination overrides ───────────────────────────────────────────── + +func accepts(item) -> bool: + return _filter_accepts(item) + + +func covers_tile(tile: Vector2i) -> bool: + return region.has_point(tile) + + +## Scan region cells in row-major order; return the first tile not occupied by +## an item that is not being carried. Returns Vector2i(-1, -1) if the zone is +## full or the item fails the filter. +func find_drop_position(item) -> Vector2i: + if not accepts(item): + return Vector2i(-1, -1) + 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) + if _is_cell_free(cell): + return cell + return Vector2i(-1, -1) + + +# ── drawing ─────────────────────────────────────────────────────────────────── + +func _draw() -> void: + var fill_color: Color = _PRIORITY_COLORS.get(priority, Color(0.5, 0.5, 0.5, 0.12)) + var border_color := Color(fill_color.r, fill_color.g, fill_color.b, 0.6) + var tile_px := float(_TILE_PX) + + # Filled rectangle covering the entire region. + var rect_px := Rect2( + Vector2(region.position) * tile_px, + Vector2(region.size) * tile_px + ) + draw_rect(rect_px, fill_color, true) + + # 1-px border outline. + draw_rect(rect_px, border_color, false, 1.0) + + +# ── internal helpers ────────────────────────────────────────────────────────── + +## Returns true when no un-carried item is sitting on `cell`. +## One-stack-per-tile rule: the first occupied, non-carried item blocks the cell. +func _is_cell_free(cell: Vector2i) -> bool: + for it in World.items: + if it.tile == cell and not it.being_carried: + return false + return true diff --git a/scenes/world/stockpile_zone.gd.uid b/scenes/world/stockpile_zone.gd.uid new file mode 100644 index 0000000..af1ae83 --- /dev/null +++ b/scenes/world/stockpile_zone.gd.uid @@ -0,0 +1 @@ +uid://cws7im713niq4 diff --git a/scenes/world/stockpile_zone.tscn b/scenes/world/stockpile_zone.tscn new file mode 100644 index 0000000..ebba8c2 --- /dev/null +++ b/scenes/world/stockpile_zone.tscn @@ -0,0 +1,7 @@ +[gd_scene load_steps=2 format=3 uid="uid://stockpile_zone"] + +[ext_resource type="Script" path="res://scenes/world/stockpile_zone.gd" id="1_stockpile"] + +[node name="StockpileZone" type="Node2D"] +script = ExtResource("1_stockpile") +z_index = -1 diff --git a/scenes/world/storage_destination.gd b/scenes/world/storage_destination.gd new file mode 100644 index 0000000..140edff --- /dev/null +++ b/scenes/world/storage_destination.gd @@ -0,0 +1,73 @@ +class_name StorageDestination extends Node2D +## Abstract base for all item-storage destinations (floor stockpile zones, +## containers, etc.). Hauling AI treats all subclasses as a unified candidate +## pool via this interface. +## +## StorageDestination extends Node2D (not Node) so subclasses can implement +## _draw() for priority-tinted overlays without a separate CanvasItem child. +## +## Subclasses MUST override: accepts(), find_drop_position(), covers_tile(). +## Subclasses SHOULD call World.register_stockpile(self) in _ready() and +## World.unregister_stockpile(self) in _exit_tree(). +## +## See docs/architecture.md "Storage destinations: a unified concept". + +## Five priority levels matching Rimworld semantics (design.md Priorities). +## Lower enum int = higher priority (CRITICAL = 0 pulls before LOW = 4). +## Priority.OFF = no hauling in or out; invisible to HaulingProvider. +enum Priority { + CRITICAL = 0, + HIGH = 1, + NORMAL = 2, + LOW = 3, + OFF = 4, +} + +## Priority determines whether haulers will fill this destination and whether +## items here will be re-hauled upward to a higher-priority destination. +@export var priority: Priority = Priority.NORMAL + +## Item types this destination accepts. Empty array = wildcard (accepts all). +## Each entry is a StringName matching Item.TYPE_* constants (e.g. &"wood"). +@export var accepted_types: Array[StringName] = [] + +## Emitted when items are registered or unregistered with this destination, +## so interested parties (UI, re-scan logic) can react without polling. +signal contents_changed + + +# ── abstract interface — subclasses must override ──────────────────────────── + +## Returns true if this destination currently accepts `item` (filter + priority +## check + any capacity logic owned by the subclass). +func accepts(item) -> bool: + push_error("StorageDestination.accepts: '%s' must override this method" % name) + return false + + +## Returns a tile coordinate inside this destination where `item` can be +## placed (filter-pass AND the tile is not already occupied by another item). +## Returns Vector2i(-1, -1) when no slot is available. +func find_drop_position(item) -> Vector2i: + push_error("StorageDestination.find_drop_position: '%s' must override this method" % name) + return Vector2i(-1, -1) + + +## Returns true if `tile` falls inside this destination's region. +## Used by HaulingProvider to find which destination currently holds an item. +func covers_tile(tile: Vector2i) -> bool: + push_error("StorageDestination.covers_tile: '%s' must override this method" % name) + return false + + +# ── shared helper ──────────────────────────────────────────────────────────── + +## 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. +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 diff --git a/scenes/world/storage_destination.gd.uid b/scenes/world/storage_destination.gd.uid new file mode 100644 index 0000000..e9d80b5 --- /dev/null +++ b/scenes/world/storage_destination.gd.uid @@ -0,0 +1 @@ +uid://f7rilcintvg2 diff --git a/scenes/world/world.gd b/scenes/world/world.gd index 62ebc65..969bab0 100644 --- a/scenes/world/world.gd +++ b/scenes/world/world.gd @@ -1,11 +1,8 @@ extends Node2D -## Phase 2 world view. 80×80 TileMap with 6 layers, 3 sample pawns, pathfinder, -## click-to-select / click-to-move selection. -## -## Real ElvGames art lands in Phase 5+ (wood walls custom-authored on -## FG_Houses, stone walls autotiled from FG_Fortress per the 2026-05-10 -## audit lock). The procedural placeholder tileset is enough to prove the -## TileMap pipeline + pawn movement + camera + pathfinding end-to-end. +## Phase 4 world view. 80×80 TileMap, 6 layers, 3 pawns, full AI pipeline: +## RestProvider → ChopProvider → MineProvider → HaulingProvider → idle +## plus sample trees, rocks, and two stockpile zones with different priorities +## for the haul-cascade demo. ## ## TileMap layer indices follow docs/architecture.md: ## 0 Terrain · 1 Floor · 2 Wall · 3 Designation · 4 Roof · 5 Fog @@ -13,8 +10,6 @@ extends Node2D const MAP_SIZE_TILES: Vector2i = Vector2i(80, 80) const TILE_SIZE_PX: int = 16 -# Atlas coords inside the placeholder tileset (one source, source_id = 0). -# Real assets in Phase 5 will use multiple atlas sources. const TILE_GRASS: Vector2i = Vector2i(0, 0) const TILE_DIRT: Vector2i = Vector2i(1, 0) const TILE_STONE: Vector2i = Vector2i(2, 0) @@ -23,6 +18,9 @@ const TILE_STONE_DARK: Vector2i = Vector2i(3, 0) const PLACEHOLDER_SOURCE_ID: int = 0 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") # 3 starting pawns — Phase 2 demo. Phase 7+ replaces this with map-gen + name table. const SAMPLE_PAWNS: Array[Dictionary] = [ @@ -31,6 +29,18 @@ const SAMPLE_PAWNS: Array[Dictionary] = [ {"name": "Edda", "tile": Vector2i(30, 40)}, ] +# Phase 4 — sample harvestables. Trees clustered east, rocks south-east. +const SAMPLE_TREES: Array[Vector2i] = [ + Vector2i(58, 30), Vector2i(60, 31), Vector2i(62, 30), + Vector2i(61, 33), Vector2i(63, 34), Vector2i(59, 35), +] +const SAMPLE_ROCKS: Array[Vector2i] = [ + Vector2i(60, 60), Vector2i(62, 60), Vector2i(63, 62), Vector2i(58, 62), +] + +# HaulingProvider re-flow cadence — every 5 sim seconds at 1× (100 ticks). +const HAUL_SWEEP_INTERVAL_TICKS: int = 100 + @onready var terrain_layer: TileMapLayer = $Terrain @onready var floor_layer: TileMapLayer = $Floor @onready var wall_layer: TileMapLayer = $Wall @@ -40,10 +50,13 @@ const SAMPLE_PAWNS: Array[Dictionary] = [ @onready var pathfinder: Pathfinder = $Pathfinder @onready var selection: Selection = $Selection @onready var rest_provider: RestProvider = $RestProvider +@onready var chop_provider: ChopProvider = $ChopProvider +@onready var mine_provider: MineProvider = $MineProvider +@onready var hauling_provider: HaulingProvider = $HaulingProvider func _ready() -> void: - Audit.log("world", "Phase 3 — building %d×%d world + pawns + AI." % [MAP_SIZE_TILES.x, MAP_SIZE_TILES.y]) + Audit.log("world", "Phase 4 — building %d×%d world + harvestables + AI." % [MAP_SIZE_TILES.x, MAP_SIZE_TILES.y]) var tileset := _build_placeholder_tileset() for layer in [terrain_layer, floor_layer, wall_layer, designation_layer, roof_layer, fog_layer]: layer.tile_set = tileset @@ -54,12 +67,24 @@ func _ready() -> void: pathfinder.setup(MAP_SIZE_TILES) _wire_walls_to_pathfinder() 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. + World.register_work_provider(chop_provider) + World.register_work_provider(mine_provider) + World.register_work_provider(hauling_provider) World.register_work_provider(rest_provider) _spawn_sample_pawns() + _spawn_sample_harvestables() + _spawn_sample_stockpiles() _run_pathfinder_spike() + # Phase 4: every 5 in-game seconds (100 ticks), re-evaluate items in + # stockpiles in case a higher-priority destination opened up. + EventBus.sim_tick.connect(_on_sim_tick_world_sweep) + func world_bounds_px() -> Rect2: return Rect2(Vector2.ZERO, Vector2(MAP_SIZE_TILES * TILE_SIZE_PX)) @@ -68,9 +93,8 @@ func world_bounds_px() -> Rect2: # ── tileset & map painting ────────────────────────────────────────────────── func _build_placeholder_tileset() -> TileSet: - # Four 16×16 placeholder tiles laid out as a 4×1 atlas. No PNG dependency - # — atlas built at runtime from a programmatic Image. Real ElvGames art - # replaces this when wood/stone wall variants are imported in Phase 5. + # Four 16×16 placeholder tiles laid out as a 4×1 atlas. Real ElvGames + # art replaces this in Phase 5 (wood walls + stone walls). var ts := TileSet.new() ts.tile_size = Vector2i(TILE_SIZE_PX, TILE_SIZE_PX) @@ -110,8 +134,6 @@ func _paint_terrain() -> void: func _paint_sample_walls() -> void: - # An 8×8 stone ring near the map centre as a visual landmark + pathfinding - # obstacle so the demo proves pawns route around walls. var origin := Vector2i(36, 36) var size: int = 8 for i in size: @@ -124,7 +146,6 @@ func _paint_sample_walls() -> void: # ── pathfinder + pawns ────────────────────────────────────────────────────── func _wire_walls_to_pathfinder() -> void: - # Wall cells block pathing. Re-runs on Phase 5 build/destroy events later. var wall_cells := wall_layer.get_used_cells() for cell in wall_cells: pathfinder.set_cell_walkable(cell, false) @@ -147,12 +168,59 @@ func _spawn_sample_pawns() -> void: World.register_pawn(p) +# ── Phase 4: harvestables + stockpile zones ───────────────────────────────── + +func _spawn_sample_harvestables() -> void: + # Untyped vars — Godot's class-name cache for class_name'd classes is + # scan-time and intermittently lags behind file changes. Duck typing is + # safer here and the calls below are all spec'd on the entity types. + for t_tile in SAMPLE_TREES: + var tree = TREE_SCENE.instantiate() + add_child(tree) + tree.setup(t_tile) + for r_tile in SAMPLE_ROCKS: + var rock = ROCK_SCENE.instantiate() + add_child(rock) + rock.setup(r_tile) + Audit.log("world", "spawned %d trees + %d rocks" % [SAMPLE_TREES.size(), SAMPLE_ROCKS.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) + # - Zone B (south): wildcard, HIGH priority (the "watch wood flow upward" target) + # When the sweep runs, wood items in Zone A get re-marked for haul and + # eventually migrate to Zone B. + var zone_a: StockpileZone = STOCKPILE_SCENE.instantiate() + add_child(zone_a) + zone_a.region = Rect2i(15, 55, 4, 4) + zone_a.label = "Wood (Normal)" + zone_a.priority = StorageDestination.Priority.NORMAL + zone_a.accepted_types = [Item.TYPE_WOOD] as Array[StringName] + zone_a.queue_redraw() + + var zone_b: StockpileZone = STOCKPILE_SCENE.instantiate() + add_child(zone_b) + zone_b.region = Rect2i(15, 62, 4, 4) + zone_b.label = "Anything (High)" + zone_b.priority = StorageDestination.Priority.HIGH + zone_b.accepted_types = [] as Array[StringName] # wildcard + zone_b.queue_redraw() + + Audit.log("world", "spawned 2 stockpiles: %s + %s" % [zone_a.label, zone_b.label]) + + +# ── periodic re-flow (the "wood floats up" cascade) ───────────────────────── + +func _on_sim_tick_world_sweep(tick_n: int) -> void: + if tick_n % HAUL_SWEEP_INTERVAL_TICKS != 0: + return + hauling_provider.sweep_for_better_destinations() + + # ── spike: AStarGrid2D query timing at 80² ────────────────────────────────── func _run_pathfinder_spike() -> void: - # Phase 2 acceptance spike (~30 min): "AStarGrid2D path-query timing at 80² - # with 6 pawns simultaneously requesting paths. Confirm sub-millisecond." - # We benchmark all 4-corner pairs × 3 iterations = 36 path queries. var corners := [ Vector2i(2, 2), Vector2i(MAP_SIZE_TILES.x - 3, 2), diff --git a/scenes/world/world.tscn b/scenes/world/world.tscn index d0c300b..d6cf5d9 100644 --- a/scenes/world/world.tscn +++ b/scenes/world/world.tscn @@ -1,10 +1,13 @@ -[gd_scene load_steps=6 format=3 uid="uid://rimlike_world"] +[gd_scene load_steps=9 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"] [ext_resource type="Script" path="res://scenes/world/pathfinder.gd" id="3_pathfinder"] [ext_resource type="Script" path="res://scenes/world/selection.gd" id="4_selection"] [ext_resource type="Script" path="res://scenes/ai/rest_provider.gd" id="5_rest_provider"] +[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"] [node name="World" type="Node2D"] script = ExtResource("1_world") @@ -39,5 +42,14 @@ script = ExtResource("4_selection") script = ExtResource("5_rest_provider") rest_tile = Vector2i(50, 50) +[node name="ChopProvider" type="Node" parent="."] +script = ExtResource("6_chop_provider") + +[node name="MineProvider" type="Node" parent="."] +script = ExtResource("7_mine_provider") + +[node name="HaulingProvider" type="Node" parent="."] +script = ExtResource("8_hauling_provider") + [node name="CameraRig" parent="." instance=ExtResource("2_camera")] position = Vector2(640, 640)