diff --git a/engine/include/settlement/core/deterministic_rng.hpp b/engine/include/settlement/core/deterministic_rng.hpp new file mode 100644 index 0000000..052548e --- /dev/null +++ b/engine/include/settlement/core/deterministic_rng.hpp @@ -0,0 +1,38 @@ +#pragma once + +#include + +namespace settlement { + +// SplitMix64: a small deterministic generator for reproducible scenarios. +// This is not intended for cryptographic use. +class DeterministicRng { +public: + explicit DeterministicRng(std::uint64_t seed) noexcept : state_(seed) {} + + [[nodiscard]] std::uint64_t next_u64() noexcept { + std::uint64_t value = (state_ += 0x9E3779B97F4A7C15ULL); + value = (value ^ (value >> 30U)) * 0xBF58476D1CE4E5B9ULL; + value = (value ^ (value >> 27U)) * 0x94D049BB133111EBULL; + return value ^ (value >> 31U); + } + + [[nodiscard]] std::uint64_t bounded(std::uint64_t bound) noexcept { + if (bound == 0) { + return 0; + } + + const std::uint64_t rejection_threshold = (0ULL - bound) % bound; + for (;;) { + const std::uint64_t value = next_u64(); + if (value >= rejection_threshold) { + return value % bound; + } + } + } + +private: + std::uint64_t state_; +}; + +} // namespace settlement diff --git a/engine/include/settlement/core/worker_pool.hpp b/engine/include/settlement/core/worker_pool.hpp new file mode 100644 index 0000000..b8c7cf3 --- /dev/null +++ b/engine/include/settlement/core/worker_pool.hpp @@ -0,0 +1,55 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace settlement { + +class WorkerPool { +public: + explicit WorkerPool(std::size_t thread_count); + ~WorkerPool(); + + WorkerPool(const WorkerPool&) = delete; + WorkerPool& operator=(const WorkerPool&) = delete; + + template + auto submit(Function&& function) -> std::future> { + using Result = std::invoke_result_t; + auto task = std::make_shared>(std::forward(function)); + std::future result = task->get_future(); + { + std::lock_guard lock(mutex_); + if (stopping_) { + throw std::runtime_error("cannot submit work to a stopped worker pool"); + } + tasks_.emplace([task]() { (*task)(); }); + } + work_available_.notify_one(); + return result; + } + + [[nodiscard]] std::size_t thread_count() const noexcept; + +private: + void worker_loop(); + + std::vector workers_; + std::queue> tasks_; + std::mutex mutex_; + std::condition_variable work_available_; + bool stopping_ = false; +}; + +} // namespace settlement diff --git a/engine/include/settlement/core/world.hpp b/engine/include/settlement/core/world.hpp new file mode 100644 index 0000000..25393c6 --- /dev/null +++ b/engine/include/settlement/core/world.hpp @@ -0,0 +1,376 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "settlement/core/worker_pool.hpp" + +namespace settlement { + +using AgentId = std::uint64_t; +using JobId = std::uint64_t; + +struct GridPosition { + std::int32_t x = 0; + std::int32_t y = 0; + + bool operator==(const GridPosition&) const = default; +}; + +enum class AgentState : std::uint8_t { + Idle, + Travelling, + Working, + Gathering, + Hauling, + FetchingMaterials, + GoingToEat, + Eating, + GoingToSleep, + Sleeping +}; + +enum class JobState : std::uint8_t { + Available, + InProgress, + Completed +}; + +enum class ItemType : std::uint8_t { + None, + Wood, + Stone, + Plank, + StoneBlock, + Berries, + Cloth, + Flax +}; +inline constexpr std::size_t item_type_count = static_cast(ItemType::Flax); + +enum class StorageKind : std::uint8_t { Materials, Pantry }; +enum class ResourceSite : std::uint8_t { Natural, BerryField, TreePlot, Mine, FlaxField }; + +constexpr ItemType site_resource(ResourceSite site) noexcept { + switch (site) { + case ResourceSite::BerryField: return ItemType::Berries; + case ResourceSite::TreePlot: return ItemType::Wood; + case ResourceSite::Mine: return ItemType::Stone; + case ResourceSite::FlaxField: return ItemType::Flax; + case ResourceSite::Natural: return ItemType::None; + } + return ItemType::None; +} + +enum class RecipeId : std::uint8_t { + SawPlank, + CutStoneBlock, + BuildCabin, + BuildBed, + WeaveCloth +}; +enum class BedBase : std::uint8_t { Wood, Stone }; +enum class BedStage : std::uint8_t { Legacy, Foundation, Bedding, Pillow }; + +constexpr bool is_construction(RecipeId recipe) noexcept { + return recipe == RecipeId::BuildCabin || recipe == RecipeId::BuildBed; +} + +enum class WorkPriority : std::uint8_t { Balanced, FoodFirst, BuildingFirst }; +enum class Profession : std::uint8_t { Generalist = 0, Farmer, Woodcutter, Miner, Builder }; +enum class CommandKind : std::uint8_t { + PlaceBed = 0, SetForaging = 1, SetPriority = 2, SetPaused = 3, + PlaceBerryField = 4, PlaceTreePlot = 5, PlaceMine = 6, MoveObject = 7, DemolishObject = 8, + PlaceStorage = 9, AssignProfession = 10, PlaceFlaxField = 11, PlaceLoom = 12 +}; +enum class CommandStatus : std::uint8_t { Accepted, Unavailable, Unauthorized, WrongSequence, InvalidTarget, Busy }; + +inline constexpr std::uint8_t colony_host = 1; +inline constexpr std::size_t colony_player_slots = 2; +inline constexpr std::size_t min_worker_count = 2; +inline constexpr std::size_t max_worker_count = 64; + +struct PlayerCommand { + std::uint8_t player; + std::uint64_t sequence; + CommandKind kind; + GridPosition cell{}; + std::uint8_t value = 0; + GridPosition destination{}; + AgentId resident = 0; +}; + +struct CommandReceipt { + CommandStatus status; + std::uint64_t tick; + std::uint64_t revision; +}; + +struct ScenarioProgress { + std::size_t assigned_beds; + std::size_t residents; + std::uint64_t available_food; + std::uint64_t food_goal; + bool completed; +}; + +struct TickProfile { + std::chrono::nanoseconds growth_and_needs{}; + std::chrono::nanoseconds resource_assignment{}; + std::chrono::nanoseconds production_assignment{}; + std::chrono::nanoseconds generic_assignment{}; + std::chrono::nanoseconds advancement{}; +}; + +inline constexpr std::size_t no_entity_index = static_cast(-1); +inline constexpr std::uint16_t hunger_threshold = 180; +inline constexpr std::uint16_t max_hunger = 300; +inline constexpr std::uint16_t fatigue_threshold = 200; +inline constexpr std::uint16_t max_fatigue = 300; + +class Inventory { +public: + [[nodiscard]] std::uint32_t item_count(ItemType type) const noexcept; + [[nodiscard]] bool empty() const noexcept; + void add(ItemType type, std::uint32_t count = 1) noexcept; + void remove(ItemType type, std::uint32_t count = 1) noexcept; + [[nodiscard]] ItemType first_item() const noexcept; + +private: + std::array counts_{}; +}; + +struct Agent { + AgentId id = 0; + GridPosition position; + AgentState state = AgentState::Idle; + JobId current_job = 0; + std::vector route; + std::size_t route_cursor = 0; + std::uint32_t work_remaining = 0; + std::size_t resource_node_index = no_entity_index; + std::size_t storage_index = no_entity_index; + Inventory inventory; + std::vector haul_route; + std::size_t production_index = no_entity_index; + std::uint16_t hunger = 0; + std::uint16_t fatigue = 0; + bool resting_on_ground = false; + Profession profession = Profession::Generalist; + + [[nodiscard]] bool hungry() const noexcept { return hunger >= hunger_threshold; } + [[nodiscard]] bool tired() const noexcept { return fatigue >= fatigue_threshold; } +}; + +struct WorkJob { + JobId id = 0; + GridPosition position; + std::uint32_t work_required = 1; + std::uint32_t work_remaining = 1; + JobState state = JobState::Available; +}; + +struct ResourceNode { + std::uint64_t id = 0; + GridPosition position; + ItemType type = ItemType::None; + std::uint32_t quantity = 0; + std::uint32_t initial_quantity = 0; + std::uint32_t reserved_workers = 0; + bool foraging_enabled = true; + ResourceSite site = ResourceSite::Natural; + std::uint64_t growth_at = 0; + + [[nodiscard]] bool needs_tending() const noexcept { + return site != ResourceSite::Natural && site != ResourceSite::Mine && quantity == 0 && growth_at == 0; + } +}; + +struct ItemStack { + ItemType type = ItemType::None; + std::uint32_t count = 0; + std::uint32_t reserved = 0; +}; + +struct Storage { + std::uint64_t id = 0; + GridPosition position; + std::uint32_t capacity = 0; + std::uint32_t reserved_slots = 0; + std::vector items; + StorageKind kind = StorageKind::Materials; + + [[nodiscard]] bool accepts(ItemType type) const noexcept { + return type != ItemType::None && (type == ItemType::Berries) == (kind == StorageKind::Pantry); + } + + [[nodiscard]] std::uint32_t item_count(ItemType type) const noexcept { + for (const ItemStack& stack : items) { + if (stack.type == type) return stack.count; + } + return 0; + } + + [[nodiscard]] std::uint64_t total_items() const noexcept { + std::uint64_t total = 0; + for (const ItemStack& stack : items) total += stack.count; + return total; + } + + void add_item(ItemType type); +}; + +struct MaterialReservation { + std::size_t storage_index; + ItemType type; + std::uint32_t count; +}; + +struct ConstructionStop { + std::size_t storage_index; + std::vector route_to_next; +}; + +struct ProductionOrder { + GridPosition position; + RecipeId recipe; + JobState state = JobState::Available; + std::vector materials; + std::vector delivery_stops; + std::size_t collected_stops = 0; + AgentId bed_owner = 0; + BedBase bed_base = BedBase::Wood; + BedStage bed_stage = BedStage::Legacy; + + [[nodiscard]] ItemType bed_material() const noexcept { + if (bed_stage == BedStage::Legacy) return ItemType::Plank; + if (bed_stage != BedStage::Foundation) return ItemType::Cloth; + return bed_base == BedBase::Stone ? ItemType::Stone : ItemType::Wood; + } +}; + +class World { +public: + World(std::uint64_t seed, std::int32_t width, std::int32_t height, + std::size_t workers = min_worker_count); + + void set_blocked(GridPosition position, bool blocked = true); + [[nodiscard]] bool is_walkable(GridPosition position) const noexcept; + [[nodiscard]] AgentId spawn_agent(GridPosition position); + [[nodiscard]] JobId add_job(GridPosition position, std::uint32_t work_required); + [[nodiscard]] std::uint64_t add_resource_node(GridPosition position, ItemType type, + std::uint32_t quantity); + [[nodiscard]] std::uint64_t add_storage(GridPosition position, std::uint32_t capacity, + StorageKind kind = StorageKind::Materials); + void stock_storage(std::uint64_t id, ItemType type, std::uint32_t count); + void enable_hunger() noexcept; + void queue_production(GridPosition position, RecipeId recipe); + [[nodiscard]] bool can_place_cabin(GridPosition position) const noexcept; + void queue_cabin(GridPosition position, GridPosition sawmill, GridPosition stonecutter); + void start_scenario(GridPosition sawmill); + [[nodiscard]] CommandReceipt apply_command(const PlayerCommand& command); + [[nodiscard]] std::uint64_t next_command_sequence(std::uint8_t player) const noexcept; + [[nodiscard]] bool can_place_bed(GridPosition position) const noexcept; + [[nodiscard]] bool can_place_site(GridPosition position, ResourceSite site) const noexcept; + [[nodiscard]] bool can_place_storage(GridPosition position) const noexcept; + [[nodiscard]] CommandStatus object_status(GridPosition position, bool moving) const noexcept; + [[nodiscard]] bool scenario_active() const noexcept { return scenario_active_; } + [[nodiscard]] bool staged_beds() const noexcept { return staged_beds_; } + [[nodiscard]] bool paused() const noexcept { return paused_; } + [[nodiscard]] WorkPriority work_priority() const noexcept { return work_priority_; } + [[nodiscard]] ScenarioProgress scenario_progress() const noexcept; + void step(TickProfile* profile = nullptr); + void write_svg(const std::string& path) const; + void write_save(std::ostream& stream) const; + [[nodiscard]] static std::unique_ptr read_save(std::istream& stream, std::size_t workers = min_worker_count); + + [[nodiscard]] std::uint64_t tick() const noexcept; + [[nodiscard]] std::uint64_t seed() const noexcept; + [[nodiscard]] std::int32_t width() const noexcept; + [[nodiscard]] std::int32_t height() const noexcept; + [[nodiscard]] const std::vector& agents() const noexcept; + [[nodiscard]] const std::vector& jobs() const noexcept; + [[nodiscard]] const std::vector& resource_nodes() const noexcept; + [[nodiscard]] const std::vector& storages() const noexcept; + [[nodiscard]] const std::vector& production_orders() const noexcept; + [[nodiscard]] const ProductionOrder* assigned_bed(AgentId agent) const noexcept; + [[nodiscard]] bool is_bed_cell(GridPosition position) const noexcept; + [[nodiscard]] std::uint64_t path_searches() const noexcept; + [[nodiscard]] std::uint64_t path_nodes_visited() const noexcept; + [[nodiscard]] std::uint64_t assignment_path_cache_hits() const noexcept { return assignment_path_cache_hits_; } + [[nodiscard]] std::uint64_t jobs_completed() const noexcept; + [[nodiscard]] std::uint64_t meals_eaten() const noexcept; + [[nodiscard]] std::size_t worker_count() const noexcept; + +private: + friend struct WorldSaveCodec; + struct PathResult { + std::vector positions; + std::uint64_t nodes_visited = 0; + bool reachable = false; + }; + + [[nodiscard]] std::size_t cell_index(GridPosition position) const noexcept; + [[nodiscard]] PathResult find_path(GridPosition start, GridPosition goal) const; + [[nodiscard]] PathResult assignment_path(GridPosition start, GridPosition goal); + void assign_idle_agents(); + enum class ResourceFocus { Any, Food, Materials }; + void assign_resource_tasks(ResourceFocus focus = ResourceFocus::Any); + void assign_production_tasks(bool weaving); + void assign_meals(); + void finish_meal_step(Agent& agent); + void assign_rest(); + void finish_rest_step(Agent& agent); + void advance_construction_delivery(Agent& agent); + void finish_production(Agent& agent); + void update_scenario(); + [[nodiscard]] bool resting_at(GridPosition position, AgentId except = 0) const noexcept; + [[nodiscard]] bool ground_rest_cell(GridPosition position, AgentId agent) const noexcept; + CommandStatus edit_object(GridPosition position, const GridPosition* destination); + void grow_sites(); + [[nodiscard]] bool can_reach_object_cell(GridPosition position) const; + + std::uint64_t seed_; + std::uint64_t tick_ = 0; + std::uint64_t path_searches_ = 0; + std::uint64_t path_nodes_visited_ = 0; + std::uint64_t assignment_path_cache_hits_ = 0; + std::uint64_t jobs_completed_ = 0; + std::uint64_t meals_eaten_ = 0; + bool hunger_enabled_ = false; + std::int32_t width_; + std::int32_t height_; + std::size_t worker_count_; + std::unique_ptr worker_pool_; + AgentId next_agent_id_ = 1; + JobId next_job_id_ = 1; + std::uint64_t next_resource_node_id_ = 1; + std::uint64_t next_storage_id_ = 1; + std::vector blocked_; + std::unordered_map assignment_path_cache_; + std::vector agents_; + std::vector jobs_; + std::vector resource_nodes_; + std::vector storages_; + std::vector production_orders_; + bool scenario_active_ = false; + bool staged_beds_ = false; + bool paused_ = false; + bool scenario_completed_ = false; + WorkPriority work_priority_ = WorkPriority::Balanced; + GridPosition scenario_sawmill_; + std::array player_sequences_{}; + std::uint64_t command_revision_ = 0; +}; + +inline constexpr std::int32_t first_colony_map_size = 32; +[[nodiscard]] std::unique_ptr make_first_colony(std::size_t workers); + +} // namespace settlement