From fa8250ed0dfafeaec7ac8f2e171d6f4da8bc39e3 Mon Sep 17 00:00:00 2001 From: Vales Date: Tue, 18 Aug 2026 23:24:43 +0100 Subject: [PATCH] add generic Compute kernel foundation --- CMakeLists.txt | 11 + Kernel/Compute/CombatEvaluation.cpp | 75 +++++++ Kernel/Compute/Influence.cpp | 111 ++++++++++ Kernel/Compute/Pathing.cpp | 194 ++++++++++++++++ Kernel/Compute/Placement.cpp | 71 ++++++ Kernel/Compute/TargetSelection.cpp | 40 ++++ docs/COMPUTE.md | 43 ++++ docs/STATUS.md | 16 +- .../kernel/compute/CombatEvaluation.hpp | 59 +++++ include/sc2opt/kernel/compute/Influence.hpp | 43 ++++ include/sc2opt/kernel/compute/Pathing.hpp | 65 ++++++ include/sc2opt/kernel/compute/Placement.hpp | 48 ++++ .../sc2opt/kernel/compute/TargetSelection.hpp | 37 ++++ include/sc2opt/model/GridView.hpp | 67 ++++++ tests/compute_tests.cpp | 207 ++++++++++++++++++ 15 files changed, 1085 insertions(+), 2 deletions(-) create mode 100644 Kernel/Compute/CombatEvaluation.cpp create mode 100644 Kernel/Compute/Influence.cpp create mode 100644 Kernel/Compute/Pathing.cpp create mode 100644 Kernel/Compute/Placement.cpp create mode 100644 Kernel/Compute/TargetSelection.cpp create mode 100644 docs/COMPUTE.md create mode 100644 include/sc2opt/kernel/compute/CombatEvaluation.hpp create mode 100644 include/sc2opt/kernel/compute/Influence.hpp create mode 100644 include/sc2opt/kernel/compute/Pathing.hpp create mode 100644 include/sc2opt/kernel/compute/Placement.hpp create mode 100644 include/sc2opt/kernel/compute/TargetSelection.hpp create mode 100644 include/sc2opt/model/GridView.hpp create mode 100644 tests/compute_tests.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 9354175..7d16c64 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -33,6 +33,11 @@ add_library(sc2opt_kernel STATIC Kernel/Hot/BatchGeometry.cpp Kernel/Hot/Filtering.cpp Kernel/Hot/SpatialGrid.cpp + Kernel/Compute/CombatEvaluation.cpp + Kernel/Compute/Influence.cpp + Kernel/Compute/Pathing.cpp + Kernel/Compute/Placement.cpp + Kernel/Compute/TargetSelection.cpp ) add_library(sc2opt::kernel ALIAS sc2opt_kernel) target_include_directories(sc2opt_kernel PUBLIC include) @@ -100,6 +105,12 @@ if(SC2OPT_BUILD_TESTS) sc2opt_apply_warnings(sc2opt_hot_kernel_tests) add_test(NAME sc2opt_hot_kernel_tests COMMAND sc2opt_hot_kernel_tests) + add_executable(sc2opt_compute_tests tests/compute_tests.cpp) + target_link_libraries(sc2opt_compute_tests PRIVATE sc2opt) + target_compile_features(sc2opt_compute_tests PRIVATE cxx_std_20) + sc2opt_apply_warnings(sc2opt_compute_tests) + add_test(NAME sc2opt_compute_tests COMMAND sc2opt_compute_tests) + add_executable(sc2opt_synthetic_cpp_consumer examples/synthetic_cpp_consumer.cpp) target_link_libraries(sc2opt_synthetic_cpp_consumer PRIVATE sc2opt) target_compile_features(sc2opt_synthetic_cpp_consumer PRIVATE cxx_std_20) diff --git a/Kernel/Compute/CombatEvaluation.cpp b/Kernel/Compute/CombatEvaluation.cpp new file mode 100644 index 0000000..365acf8 --- /dev/null +++ b/Kernel/Compute/CombatEvaluation.cpp @@ -0,0 +1,75 @@ +#include "sc2opt/kernel/compute/CombatEvaluation.hpp" + +#include +#include + +namespace sc2opt::kernel::compute { + +CombatGroupAggregate AggregateCombatants(std::span combatants) noexcept +{ + CombatGroupAggregate aggregate; + for (const Combatant& combatant : combatants) + { + if (!std::isfinite(combatant.effective_health) || + !std::isfinite(combatant.effective_dps) || + combatant.effective_health < 0.0f || combatant.effective_dps < 0.0f) + { + return {CombatStatus::InvalidInput, 0.0, 0.0, 0}; + } + + if (combatant.effective_health <= 0.0f) + continue; + + aggregate.effective_health += combatant.effective_health; + aggregate.effective_dps += combatant.effective_dps; + ++aggregate.active_units; + } + + if (!std::isfinite(aggregate.effective_health) || !std::isfinite(aggregate.effective_dps)) + return {CombatStatus::InvalidInput, 0.0, 0.0, 0}; + + return aggregate; +} + +ContinuousExchangeEstimate EstimateContinuousExchange(std::span side_a, + std::span side_b) noexcept +{ + const CombatGroupAggregate a = AggregateCombatants(side_a); + const CombatGroupAggregate b = AggregateCombatants(side_b); + if (!a || !b) + return {CombatStatus::InvalidInput, ExchangeOutcome::Stalemate}; + + const double infinity = std::numeric_limits::infinity(); + const double seconds_to_clear_b = b.effective_health <= 0.0 + ? 0.0 + : (a.effective_dps > 0.0 + ? b.effective_health / a.effective_dps + : infinity); + const double seconds_to_clear_a = a.effective_health <= 0.0 + ? 0.0 + : (b.effective_dps > 0.0 + ? a.effective_health / b.effective_dps + : infinity); + + ExchangeOutcome outcome = ExchangeOutcome::Stalemate; + if (seconds_to_clear_a == infinity && seconds_to_clear_b == infinity) + { + outcome = ExchangeOutcome::Stalemate; + } + else if (seconds_to_clear_a == seconds_to_clear_b) + { + outcome = ExchangeOutcome::MutualDestruction; + } + else if (seconds_to_clear_b < seconds_to_clear_a) + { + outcome = ExchangeOutcome::SideAPrevails; + } + else + { + outcome = ExchangeOutcome::SideBPrevails; + } + + return {CombatStatus::Ok, outcome, seconds_to_clear_a, seconds_to_clear_b}; +} + +} // namespace sc2opt::kernel::compute diff --git a/Kernel/Compute/Influence.cpp b/Kernel/Compute/Influence.cpp new file mode 100644 index 0000000..027524c --- /dev/null +++ b/Kernel/Compute/Influence.cpp @@ -0,0 +1,111 @@ +#include "sc2opt/kernel/compute/Influence.hpp" + +#include +#include + +namespace sc2opt::kernel::compute { +namespace { + +[[nodiscard]] bool ValidSpec(const RadialInfluenceSpec& spec) noexcept +{ + return std::isfinite(spec.center.x) && std::isfinite(spec.center.y) && + std::isfinite(spec.inner_radius) && std::isfinite(spec.outer_radius) && + std::isfinite(spec.inner_value) && std::isfinite(spec.outer_value) && + spec.inner_radius >= 0.0f && spec.outer_radius >= spec.inner_radius; +} + +[[nodiscard]] bool EvaluateCell(float x, + float y, + const RadialInfluenceSpec& spec, + float& addition) noexcept +{ + const float dx = x - spec.center.x; + const float dy = y - spec.center.y; + const float distance_squared = dx * dx + dy * dy; + const float outer_squared = spec.outer_radius * spec.outer_radius; + + const bool inside_outer = spec.outer_boundary == hot::BoundaryMode::Inclusive + ? distance_squared <= outer_squared + : distance_squared < outer_squared; + if (!inside_outer) + return false; + + const float inner_squared = spec.inner_radius * spec.inner_radius; + if (distance_squared <= inner_squared || spec.outer_radius == spec.inner_radius) + { + addition = spec.inner_value; + return true; + } + + const float distance = std::sqrt(distance_squared); + const float t = (distance - spec.inner_radius) / (spec.outer_radius - spec.inner_radius); + addition = spec.inner_value + (spec.outer_value - spec.inner_value) * t; + return true; +} + +} // namespace + +InfluenceResult ApplyRadialInfluenceReference(model::FloatGridView grid, + RadialInfluenceSpec spec) noexcept +{ + if (!model::IsValid(grid)) + return {InfluenceStatus::InvalidGrid, 0}; + if (!ValidSpec(spec)) + return {InfluenceStatus::InvalidSpec, 0}; + + std::size_t touched = 0; + for (std::uint32_t y = 0; y < grid.height; ++y) + { + const std::size_t row = static_cast(y) * grid.stride; + for (std::uint32_t x = 0; x < grid.width; ++x) + { + float addition = 0.0f; + if (!EvaluateCell(static_cast(x), static_cast(y), spec, addition)) + continue; + grid.values[row + x] += addition; + ++touched; + } + } + return {InfluenceStatus::Ok, touched}; +} + +InfluenceResult ApplyRadialInfluenceBounded(model::FloatGridView grid, + RadialInfluenceSpec spec) noexcept +{ + if (!model::IsValid(grid)) + return {InfluenceStatus::InvalidGrid, 0}; + if (!ValidSpec(spec)) + return {InfluenceStatus::InvalidSpec, 0}; + + const double min_x_raw = std::floor(static_cast(spec.center.x) - spec.outer_radius); + const double max_x_raw = std::ceil(static_cast(spec.center.x) + spec.outer_radius); + const double min_y_raw = std::floor(static_cast(spec.center.y) - spec.outer_radius); + const double max_y_raw = std::ceil(static_cast(spec.center.y) + spec.outer_radius); + + const double grid_max_x = static_cast(grid.width - 1); + const double grid_max_y = static_cast(grid.height - 1); + if (max_x_raw < 0.0 || max_y_raw < 0.0 || min_x_raw > grid_max_x || min_y_raw > grid_max_y) + return {InfluenceStatus::Ok, 0}; + + const std::uint32_t min_x = static_cast(std::clamp(min_x_raw, 0.0, grid_max_x)); + const std::uint32_t max_x = static_cast(std::clamp(max_x_raw, 0.0, grid_max_x)); + const std::uint32_t min_y = static_cast(std::clamp(min_y_raw, 0.0, grid_max_y)); + const std::uint32_t max_y = static_cast(std::clamp(max_y_raw, 0.0, grid_max_y)); + + std::size_t touched = 0; + for (std::uint32_t y = min_y; y <= max_y; ++y) + { + const std::size_t row = static_cast(y) * grid.stride; + for (std::uint32_t x = min_x; x <= max_x; ++x) + { + float addition = 0.0f; + if (!EvaluateCell(static_cast(x), static_cast(y), spec, addition)) + continue; + grid.values[row + x] += addition; + ++touched; + } + } + return {InfluenceStatus::Ok, touched}; +} + +} // namespace sc2opt::kernel::compute diff --git a/Kernel/Compute/Pathing.cpp b/Kernel/Compute/Pathing.cpp new file mode 100644 index 0000000..0deab96 --- /dev/null +++ b/Kernel/Compute/Pathing.cpp @@ -0,0 +1,194 @@ +#include "sc2opt/kernel/compute/Pathing.hpp" + +#include +#include +#include +#include + +namespace sc2opt::kernel::compute { +namespace { + +[[nodiscard]] bool PositiveInfinity(float value) noexcept +{ + return std::isinf(value) && value > 0.0f; +} + +[[nodiscard]] bool ValidTraversalGrid(model::ConstFloatGridView grid) noexcept +{ + if (!model::IsValid(grid)) + return false; + + const std::size_t cell_count = static_cast(grid.width) * grid.height; + if (cell_count > std::numeric_limits::max()) + return false; + + for (std::uint32_t y = 0; y < grid.height; ++y) + { + const std::size_t row = static_cast(y) * grid.stride; + for (std::uint32_t x = 0; x < grid.width; ++x) + { + const float cost = grid.values[row + x]; + if (PositiveInfinity(cost)) + continue; + if (!std::isfinite(cost) || cost < 1.0f) + return false; + } + } + return true; +} + +[[nodiscard]] std::uint32_t Index(model::ConstFloatGridView grid, + model::GridPoint point) noexcept +{ + return point.y * grid.width + point.x; +} + +[[nodiscard]] model::GridPoint Point(model::ConstFloatGridView grid, + std::uint32_t index) noexcept +{ + return {index % grid.width, index / grid.width}; +} + +[[nodiscard]] float CostAt(model::ConstFloatGridView grid, model::GridPoint point) noexcept +{ + return grid.values[static_cast(point.y) * grid.stride + point.x]; +} + +[[nodiscard]] float Heuristic(model::GridPoint a, + model::GridPoint b, + PathHeuristic heuristic) noexcept +{ + if (heuristic == PathHeuristic::None) + return 0.0f; + + const std::uint32_t dx = a.x > b.x ? a.x - b.x : b.x - a.x; + const std::uint32_t dy = a.y > b.y ? a.y - b.y : b.y - a.y; + return static_cast(static_cast(dx) + dy); +} + +} // namespace + +PathResult AStarWorkspace::FindPath(model::ConstFloatGridView costs, + model::GridPoint start, + model::GridPoint goal, + std::span output, + PathHeuristic heuristic) +{ + if (!ValidTraversalGrid(costs)) + return {PathStatus::InvalidGrid, 0, 0, std::numeric_limits::infinity(), 0}; + + if (start.x >= costs.width || start.y >= costs.height || + goal.x >= costs.width || goal.y >= costs.height || + PositiveInfinity(CostAt(costs, start)) || PositiveInfinity(CostAt(costs, goal))) + { + return {PathStatus::InvalidStartOrGoal, 0, 0, + std::numeric_limits::infinity(), 0}; + } + + const std::size_t cell_count = static_cast(costs.width) * costs.height; + const float infinity = std::numeric_limits::infinity(); + const std::uint32_t no_parent = std::numeric_limits::max(); + + g_score_.assign(cell_count, infinity); + parent_.assign(cell_count, no_parent); + closed_.assign(cell_count, 0); + open_.clear(); + if (open_.capacity() < cell_count) + open_.reserve(cell_count); + + const std::uint32_t start_index = Index(costs, start); + const std::uint32_t goal_index = Index(costs, goal); + g_score_[start_index] = 0.0f; + parent_[start_index] = start_index; + open_.push_back({Heuristic(start, goal, heuristic), 0.0f, start_index}); + + const auto worse = [](const OpenNode& left, const OpenNode& right) noexcept { + if (left.f != right.f) + return left.f > right.f; + if (left.g != right.g) + return left.g > right.g; + return left.index > right.index; + }; + std::make_heap(open_.begin(), open_.end(), worse); + + std::size_t expanded = 0; + bool found = false; + + while (!open_.empty()) + { + std::pop_heap(open_.begin(), open_.end(), worse); + const OpenNode current = open_.back(); + open_.pop_back(); + + if (closed_[current.index] != 0 || current.g != g_score_[current.index]) + continue; + + closed_[current.index] = 1; + ++expanded; + if (current.index == goal_index) + { + found = true; + break; + } + + const model::GridPoint point = Point(costs, current.index); + const std::array neighbours{{ + {point.x > 0 ? point.x - 1 : point.x, point.y}, + {point.x + 1 < costs.width ? point.x + 1 : point.x, point.y}, + {point.x, point.y > 0 ? point.y - 1 : point.y}, + {point.x, point.y + 1 < costs.height ? point.y + 1 : point.y}, + }}; + + for (const model::GridPoint neighbour : neighbours) + { + if (neighbour == point) + continue; + + const float step_cost = CostAt(costs, neighbour); + if (PositiveInfinity(step_cost)) + continue; + + const std::uint32_t neighbour_index = Index(costs, neighbour); + if (closed_[neighbour_index] != 0) + continue; + + const float tentative = current.g + step_cost; + if (!std::isfinite(tentative) || tentative >= g_score_[neighbour_index]) + continue; + + g_score_[neighbour_index] = tentative; + parent_[neighbour_index] = current.index; + open_.push_back({tentative + Heuristic(neighbour, goal, heuristic), + tentative, + neighbour_index}); + std::push_heap(open_.begin(), open_.end(), worse); + } + } + + if (!found) + return {PathStatus::NoPath, 0, 0, infinity, expanded}; + + std::size_t required = 1; + for (std::uint32_t index = goal_index; index != start_index;) + { + index = parent_[index]; + if (index == no_parent) + return {PathStatus::NoPath, 0, 0, infinity, expanded}; + ++required; + } + + if (output.size() < required) + return {PathStatus::OutputTooSmall, 0, required, g_score_[goal_index], expanded}; + + std::uint32_t index = goal_index; + for (std::size_t position = required; position-- > 0;) + { + output[position] = Point(costs, index); + if (index != start_index) + index = parent_[index]; + } + + return {PathStatus::Ok, required, required, g_score_[goal_index], expanded}; +} + +} // namespace sc2opt::kernel::compute diff --git a/Kernel/Compute/Placement.cpp b/Kernel/Compute/Placement.cpp new file mode 100644 index 0000000..4daa82d --- /dev/null +++ b/Kernel/Compute/Placement.cpp @@ -0,0 +1,71 @@ +#include "sc2opt/kernel/compute/Placement.hpp" + +namespace sc2opt::kernel::compute { +namespace { + +[[nodiscard]] bool ValidFootprint(FootprintMaskView footprint) noexcept +{ + return model::GridShapeFits(footprint.values.size(), + footprint.width, + footprint.height, + footprint.stride); +} + +} // namespace + +bool CanPlaceMask(model::ByteGridView buildable, + FootprintMaskView footprint, + model::GridPoint anchor) noexcept +{ + if (!model::IsValid(buildable) || !ValidFootprint(footprint)) + return false; + if (footprint.width > buildable.width || footprint.height > buildable.height) + return false; + if (anchor.x > buildable.width - footprint.width || + anchor.y > buildable.height - footprint.height) + { + return false; + } + + for (std::uint32_t y = 0; y < footprint.height; ++y) + { + const std::size_t footprint_row = static_cast(y) * footprint.stride; + const std::size_t grid_row = static_cast(anchor.y + y) * buildable.stride; + for (std::uint32_t x = 0; x < footprint.width; ++x) + { + if (footprint.values[footprint_row + x] == 0) + continue; + if (buildable.values[grid_row + anchor.x + x] == 0) + return false; + } + } + + return true; +} + +PlacementFilterResult FilterValidPlacements(model::ByteGridView buildable, + FootprintMaskView footprint, + std::span candidates, + std::span output) noexcept +{ + if (!model::IsValid(buildable)) + return {PlacementStatus::InvalidGrid, 0, 0}; + if (!ValidFootprint(footprint)) + return {PlacementStatus::InvalidFootprint, 0, 0}; + + std::size_t required = 0; + for (std::size_t i = 0; i < candidates.size(); ++i) + { + if (!CanPlaceMask(buildable, footprint, candidates[i])) + continue; + if (required < output.size()) + output[required] = static_cast(i); + ++required; + } + + if (required > output.size()) + return {PlacementStatus::OutputTooSmall, 0, required}; + return {PlacementStatus::Ok, required, required}; +} + +} // namespace sc2opt::kernel::compute diff --git a/Kernel/Compute/TargetSelection.cpp b/Kernel/Compute/TargetSelection.cpp new file mode 100644 index 0000000..c4de962 --- /dev/null +++ b/Kernel/Compute/TargetSelection.cpp @@ -0,0 +1,40 @@ +#include "sc2opt/kernel/compute/TargetSelection.hpp" + +#include + +namespace sc2opt::kernel::compute { + +SelectionResult SelectBestScore(std::span scores, + std::span eligible, + SelectionPolicy policy) noexcept +{ + if (!eligible.empty() && eligible.size() != scores.size()) + return {SelectionStatus::LengthMismatch, 0, 0.0f}; + + SelectionResult best; + for (std::size_t i = 0; i < scores.size(); ++i) + { + if (!eligible.empty() && eligible[i] == 0) + continue; + + const float score = scores[i]; + if (!std::isfinite(score)) + continue; + + if (!best) + { + best = {SelectionStatus::Ok, i, score}; + continue; + } + + const bool better = policy.goal == ScoreGoal::Maximize ? score > best.score + : score < best.score; + const bool equal_and_last = score == best.score && policy.tie_break == TieBreak::Last; + if (better || equal_and_last) + best = {SelectionStatus::Ok, i, score}; + } + + return best; +} + +} // namespace sc2opt::kernel::compute diff --git a/docs/COMPUTE.md b/docs/COMPUTE.md new file mode 100644 index 0000000..e8146a9 --- /dev/null +++ b/docs/COMPUTE.md @@ -0,0 +1,43 @@ +# Compute kernel contract + +`Kernel/Compute` owns larger framework-independent jobs that are worth crossing the native boundary for. It does not own bot strategy semantics. + +## S15 — score selection + +`SelectBestScore` implements the MMEvo Z3 lesson generically: when only the best candidate is required, do a linear best-of reduction instead of building an ordered container. Scores and eligibility are supplied by the consumer. Non-finite scores are rejected, and equal-score tie behaviour is explicit (`First` or `Last`). + +## S16 — radial influence + +Two implementations share one exact contract: + +- `ApplyRadialInfluenceReference` scans the full logical grid. +- `ApplyRadialInfluenceBounded` scans only the clamped radial bounding square, rejects with squared distance, and calls `sqrt` only in the linear falloff ring. + +The reference remains available for equivalence and net-benefit measurement. Grid stride/padding is respected. Boundary semantics are explicit. + +## S17 — pathing + +`AStarWorkspace` owns reusable buffers and supports two exact modes: + +- `PathHeuristic::None` — Dijkstra/reference mode. +- `PathHeuristic::Manhattan` — A* challenger mode. + +The V1 traversal contract is deliberately narrow: 4-neighbour movement, finite passable costs >= 1.0, +infinity blocked, and movement pays the destination cell cost. This makes the unit-scale Manhattan heuristic admissible. Tie behaviour is deterministic by `(f, g, cell index)`. Workspace capacity is retained between searches. + +No consumer should assume A* is always the faster champion; benchmark the complete search on representative maps/workloads. + +## S18 — placement + +Placement consumes a byte buildability grid plus an arbitrary byte footprint mask. Non-zero mask cells require non-zero buildable cells. The consumer translates its own anchor convention; SC2AIOptimize does not assume SC2API footprint types or building-centre semantics. + +Candidate filtering preserves candidate order and writes indices into caller-owned output. + +## S19 — combat evaluation + +The first combat primitive intentionally consumes **effective health and effective DPS supplied by the consumer**. `EstimateContinuousExchange` is a minimal continuous-DPS estimate, not an SC2 simulator and not a strategic decision. + +This avoids baking incomplete weapon/armor/upgrade assumptions into V1 before `SC2Registry` has a fully proven combat-data extension. More detailed combat kernels must arrive with the corresponding data provenance and equivalence tests. + +## Admission rule + +Compute code is not automatically a runtime win just because it is native. For each consumer/workload, compare the original/baseline path against the full native path including packing, dispatch, cache/workspace maintenance and result handling. Baseline/OFF remains valid. diff --git a/docs/STATUS.md b/docs/STATUS.md index 2457e7b..6c5e21b 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -1,5 +1,17 @@ # Development status -This repository is pre-V1. Do not interpret implementation presence as runtime performance certification. +SC2AIOptimize is pre-V1. Implementation presence is not runtime/performance certification. -Current bootstrap target: S01-S04 foundation plus the first generic contracts required to prove the architecture. Performance claims require later representative benchmark evidence. +## Merged foundations + +- **S01-S04 — foundation:** merged. Base75689 SC2Registry provenance is exact; Linux/Windows Release CI is green. +- **S05-S08 — generic interfaces:** merged. Synthetic unrelated C++ consumer and optional Python buffer-protocol adapter are proven on Linux/Windows. +- **S09-S14 — Kernel/Hot:** merged. Geometry, filtering and spatial baseline/candidate contracts are correctness-tested; spatial optimisation remains **certified OFF by default** until target-workload crossover evidence exists. + +## Current work + +- **S15-S19 — Kernel/Compute:** target-score reduction, reference/bounded influence, Dijkstra/A* pathing workspace, generic footprint placement and minimal effective-stat combat evaluation. + +## Not yet claimed + +No target-hardware crossover, bot integration, ladder-runtime speedup, behavioural equivalence or V1 release certification is claimed yet. Those require the later benchmark/profile/output/hardening slices and representative consumer evidence. diff --git a/include/sc2opt/kernel/compute/CombatEvaluation.hpp b/include/sc2opt/kernel/compute/CombatEvaluation.hpp new file mode 100644 index 0000000..874b993 --- /dev/null +++ b/include/sc2opt/kernel/compute/CombatEvaluation.hpp @@ -0,0 +1,59 @@ +#pragma once + +#include +#include +#include +#include + +namespace sc2opt::kernel::compute { + +struct Combatant { + // Inputs are deliberately effective values. Consumers own SC2-specific armor, upgrades, + // targetability, splash, cooldown and policy semantics. + float effective_health = 0.0f; + float effective_dps = 0.0f; +}; + +enum class CombatStatus : std::uint8_t { Ok = 0, InvalidInput }; + +enum class ExchangeOutcome : std::uint8_t { + SideAPrevails = 0, + SideBPrevails, + MutualDestruction, + Stalemate +}; + +struct CombatGroupAggregate { + CombatStatus status = CombatStatus::Ok; + double effective_health = 0.0; + double effective_dps = 0.0; + std::size_t active_units = 0; + + [[nodiscard]] constexpr explicit operator bool() const noexcept + { + return status == CombatStatus::Ok; + } +}; + +struct ContinuousExchangeEstimate { + CombatStatus status = CombatStatus::Ok; + ExchangeOutcome outcome = ExchangeOutcome::Stalemate; + double seconds_to_clear_a = std::numeric_limits::infinity(); + double seconds_to_clear_b = std::numeric_limits::infinity(); + + [[nodiscard]] constexpr explicit operator bool() const noexcept + { + return status == CombatStatus::Ok; + } +}; + +[[nodiscard]] CombatGroupAggregate AggregateCombatants( + std::span combatants) noexcept; + +// Minimal continuous-DPS exchange estimate. This is a generic compute primitive, not an SC2 +// simulator or strategy decision. Consumers decide whether this approximation is useful. +[[nodiscard]] ContinuousExchangeEstimate EstimateContinuousExchange( + std::span side_a, + std::span side_b) noexcept; + +} // namespace sc2opt::kernel::compute diff --git a/include/sc2opt/kernel/compute/Influence.hpp b/include/sc2opt/kernel/compute/Influence.hpp new file mode 100644 index 0000000..5bb5455 --- /dev/null +++ b/include/sc2opt/kernel/compute/Influence.hpp @@ -0,0 +1,43 @@ +#pragma once + +#include "sc2opt/kernel/hot/Geometry.hpp" +#include "sc2opt/model/GridView.hpp" + +#include +#include + +namespace sc2opt::kernel::compute { + +enum class InfluenceStatus : std::uint8_t { Ok = 0, InvalidGrid, InvalidSpec }; + +struct RadialInfluenceSpec { + hot::Vec2 center; + float inner_radius = 0.0f; + float outer_radius = 0.0f; + float inner_value = 0.0f; + float outer_value = 0.0f; + hot::BoundaryMode outer_boundary = hot::BoundaryMode::Inclusive; +}; + +struct InfluenceResult { + InfluenceStatus status = InfluenceStatus::Ok; + std::size_t touched = 0; + + [[nodiscard]] constexpr explicit operator bool() const noexcept + { + return status == InfluenceStatus::Ok; + } +}; + +// Exact reference scans every logical grid cell. +[[nodiscard]] InfluenceResult ApplyRadialInfluenceReference( + model::FloatGridView grid, + RadialInfluenceSpec spec) noexcept; + +// Candidate scans only the clamped bounding square, rejects by squared distance, and calls sqrt +// only in the falloff ring. Semantics must remain equivalent to the reference implementation. +[[nodiscard]] InfluenceResult ApplyRadialInfluenceBounded( + model::FloatGridView grid, + RadialInfluenceSpec spec) noexcept; + +} // namespace sc2opt::kernel::compute diff --git a/include/sc2opt/kernel/compute/Pathing.hpp b/include/sc2opt/kernel/compute/Pathing.hpp new file mode 100644 index 0000000..ed0c55c --- /dev/null +++ b/include/sc2opt/kernel/compute/Pathing.hpp @@ -0,0 +1,65 @@ +#pragma once + +#include "sc2opt/model/GridView.hpp" + +#include +#include +#include +#include +#include + +namespace sc2opt::kernel::compute { + +enum class PathHeuristic : std::uint8_t { + None = 0, + Manhattan +}; + +enum class PathStatus : std::uint8_t { + Ok = 0, + InvalidGrid, + InvalidStartOrGoal, + NoPath, + OutputTooSmall +}; + +struct PathResult { + PathStatus status = PathStatus::NoPath; + std::size_t written = 0; + std::size_t required = 0; + float total_cost = std::numeric_limits::infinity(); + std::size_t expanded = 0; + + [[nodiscard]] constexpr explicit operator bool() const noexcept + { + return status == PathStatus::Ok; + } +}; + +// Traversal grid contract: finite cells must have cost >= 1.0; +infinity is blocked. +// Movement is 4-neighbour and pays the destination cell's traversal cost. That makes a +// Manhattan heuristic with unit scale admissible. `None` is the exact Dijkstra/reference mode. +class AStarWorkspace { +public: + [[nodiscard]] PathResult FindPath(model::ConstFloatGridView costs, + model::GridPoint start, + model::GridPoint goal, + std::span output, + PathHeuristic heuristic = PathHeuristic::Manhattan); + + [[nodiscard]] std::size_t Capacity() const noexcept { return g_score_.capacity(); } + +private: + struct OpenNode { + float f = 0.0f; + float g = 0.0f; + std::uint32_t index = 0; + }; + + std::vector g_score_; + std::vector parent_; + std::vector closed_; + std::vector open_; +}; + +} // namespace sc2opt::kernel::compute diff --git a/include/sc2opt/kernel/compute/Placement.hpp b/include/sc2opt/kernel/compute/Placement.hpp new file mode 100644 index 0000000..2871cd5 --- /dev/null +++ b/include/sc2opt/kernel/compute/Placement.hpp @@ -0,0 +1,48 @@ +#pragma once + +#include "sc2opt/model/GridView.hpp" + +#include +#include +#include + +namespace sc2opt::kernel::compute { + +struct FootprintMaskView { + std::span values; + std::uint32_t width = 0; + std::uint32_t height = 0; + std::uint32_t stride = 0; +}; + +enum class PlacementStatus : std::uint8_t { + Ok = 0, + InvalidGrid, + InvalidFootprint, + OutputTooSmall +}; + +struct PlacementFilterResult { + PlacementStatus status = PlacementStatus::Ok; + std::size_t written = 0; + std::size_t required = 0; + + [[nodiscard]] constexpr explicit operator bool() const noexcept + { + return status == PlacementStatus::Ok; + } +}; + +// Candidate anchor is the footprint's top-left cell. Non-zero footprint mask cells require a +// non-zero buildable grid cell. Consumers translate their own anchor/footprint convention here. +[[nodiscard]] bool CanPlaceMask(model::ByteGridView buildable, + FootprintMaskView footprint, + model::GridPoint anchor) noexcept; + +[[nodiscard]] PlacementFilterResult FilterValidPlacements( + model::ByteGridView buildable, + FootprintMaskView footprint, + std::span candidates, + std::span output) noexcept; + +} // namespace sc2opt::kernel::compute diff --git a/include/sc2opt/kernel/compute/TargetSelection.hpp b/include/sc2opt/kernel/compute/TargetSelection.hpp new file mode 100644 index 0000000..e671325 --- /dev/null +++ b/include/sc2opt/kernel/compute/TargetSelection.hpp @@ -0,0 +1,37 @@ +#pragma once + +#include +#include +#include +#include + +namespace sc2opt::kernel::compute { + +enum class ScoreGoal : std::uint8_t { Maximize = 0, Minimize }; +enum class TieBreak : std::uint8_t { First = 0, Last }; +enum class SelectionStatus : std::uint8_t { Ok = 0, LengthMismatch, NoCandidate }; + +struct SelectionPolicy { + ScoreGoal goal = ScoreGoal::Maximize; + TieBreak tie_break = TieBreak::First; +}; + +struct SelectionResult { + SelectionStatus status = SelectionStatus::NoCandidate; + std::size_t index = std::numeric_limits::max(); + float score = 0.0f; + + [[nodiscard]] constexpr explicit operator bool() const noexcept + { + return status == SelectionStatus::Ok; + } +}; + +// Linear best-of selection: no sorting/container construction. Empty `eligible` means all +// candidates. Non-finite scores are ineligible. Tie behaviour is explicit and deterministic. +[[nodiscard]] SelectionResult SelectBestScore( + std::span scores, + std::span eligible = {}, + SelectionPolicy policy = {}) noexcept; + +} // namespace sc2opt::kernel::compute diff --git a/include/sc2opt/model/GridView.hpp b/include/sc2opt/model/GridView.hpp new file mode 100644 index 0000000..1e27e62 --- /dev/null +++ b/include/sc2opt/model/GridView.hpp @@ -0,0 +1,67 @@ +#pragma once + +#include +#include +#include +#include + +namespace sc2opt::model { + +struct GridPoint { + std::uint32_t x = 0; + std::uint32_t y = 0; + + [[nodiscard]] constexpr bool operator==(const GridPoint&) const noexcept = default; +}; + +struct ConstFloatGridView { + std::span values; + std::uint32_t width = 0; + std::uint32_t height = 0; + std::uint32_t stride = 0; +}; + +struct FloatGridView { + std::span values; + std::uint32_t width = 0; + std::uint32_t height = 0; + std::uint32_t stride = 0; +}; + +struct ByteGridView { + std::span values; + std::uint32_t width = 0; + std::uint32_t height = 0; + std::uint32_t stride = 0; +}; + +[[nodiscard]] constexpr bool GridShapeFits(std::size_t storage_size, + std::uint32_t width, + std::uint32_t height, + std::uint32_t stride) noexcept +{ + if (width == 0 || height == 0 || stride < width) + return false; + const std::size_t rows = static_cast(height); + const std::size_t row_stride = static_cast(stride); + if (rows > std::numeric_limits::max() / row_stride) + return false; + return storage_size >= rows * row_stride; +} + +[[nodiscard]] constexpr bool IsValid(ConstFloatGridView grid) noexcept +{ + return GridShapeFits(grid.values.size(), grid.width, grid.height, grid.stride); +} + +[[nodiscard]] constexpr bool IsValid(FloatGridView grid) noexcept +{ + return GridShapeFits(grid.values.size(), grid.width, grid.height, grid.stride); +} + +[[nodiscard]] constexpr bool IsValid(ByteGridView grid) noexcept +{ + return GridShapeFits(grid.values.size(), grid.width, grid.height, grid.stride); +} + +} // namespace sc2opt::model diff --git a/tests/compute_tests.cpp b/tests/compute_tests.cpp new file mode 100644 index 0000000..2f140fb --- /dev/null +++ b/tests/compute_tests.cpp @@ -0,0 +1,207 @@ +#include "sc2opt/kernel/compute/CombatEvaluation.hpp" +#include "sc2opt/kernel/compute/Influence.hpp" +#include "sc2opt/kernel/compute/Pathing.hpp" +#include "sc2opt/kernel/compute/Placement.hpp" +#include "sc2opt/kernel/compute/TargetSelection.hpp" + +#include +#include +#include +#include +#include + +namespace { + +int failures = 0; + +void Check(bool condition, const char* message) +{ + if (!condition) + { + ++failures; + std::cerr << "FAIL: " << message << '\n'; + } +} + +void TestTargetSelection() +{ + using namespace sc2opt::kernel::compute; + + const std::array scores{3.0f, 8.0f, 8.0f, + std::numeric_limits::quiet_NaN(), 2.0f}; + const auto first = SelectBestScore(scores); + Check(first && first.index == 1 && first.score == 8.0f, "target first-tie selection"); + + const auto last = SelectBestScore(scores, {}, {ScoreGoal::Maximize, TieBreak::Last}); + Check(last && last.index == 2, "target last-tie selection"); + + const std::array eligible{1, 0, 0, 1, 1}; + const auto masked = SelectBestScore(scores, eligible); + Check(masked && masked.index == 0, "target eligibility mask"); + + const auto minimum = SelectBestScore(scores, {}, {ScoreGoal::Minimize, TieBreak::First}); + Check(minimum && minimum.index == 4 && minimum.score == 2.0f, "target minimize selection"); + + const std::array bad_mask{1}; + Check(SelectBestScore(scores, bad_mask).status == SelectionStatus::LengthMismatch, + "target mask length fails closed"); +} + +void TestInfluenceEquivalence() +{ + using namespace sc2opt; + using namespace sc2opt::kernel::compute; + + std::array reference{}; + std::array bounded{}; + model::FloatGridView reference_grid{reference, 7, 7, 8}; + model::FloatGridView bounded_grid{bounded, 7, 7, 8}; + + const RadialInfluenceSpec spec{{3.0f, 3.0f}, 1.0f, 3.0f, 10.0f, 2.0f, + kernel::hot::BoundaryMode::Inclusive}; + const auto reference_result = ApplyRadialInfluenceReference(reference_grid, spec); + const auto bounded_result = ApplyRadialInfluenceBounded(bounded_grid, spec); + Check(reference_result && bounded_result && reference_result.touched == bounded_result.touched, + "influence candidate touched count matches reference"); + + bool equal = true; + for (std::size_t i = 0; i < reference.size(); ++i) + { + if (std::fabs(reference[i] - bounded[i]) > 0.000001f) + { + equal = false; + break; + } + } + Check(equal, "influence bounded candidate matches reference values"); + + Check(reference[7] == 0.0f && bounded[7] == 0.0f, + "influence respects row stride padding"); + + const RadialInfluenceSpec invalid{{3.0f, 3.0f}, 4.0f, 3.0f, 1.0f, 0.0f}; + Check(ApplyRadialInfluenceBounded(bounded_grid, invalid).status == InfluenceStatus::InvalidSpec, + "invalid influence radii fail closed"); +} + +void TestPathing() +{ + using namespace sc2opt; + using namespace sc2opt::kernel::compute; + + const float blocked = std::numeric_limits::infinity(); + const std::array costs{ + 1, 1, blocked, 1, 1, + 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, + }; + const model::ConstFloatGridView grid{costs, 5, 5, 5}; + + std::array dijkstra_path{}; + std::array astar_path{}; + AStarWorkspace dijkstra; + AStarWorkspace astar; + + const auto reference = dijkstra.FindPath(grid, {0, 0}, {4, 0}, dijkstra_path, + PathHeuristic::None); + const auto candidate = astar.FindPath(grid, {0, 0}, {4, 0}, astar_path, + PathHeuristic::Manhattan); + Check(reference && candidate, "Dijkstra and A* both find path"); + Check(reference.total_cost == 6.0f && candidate.total_cost == reference.total_cost, + "A* cost matches Dijkstra baseline"); + Check(reference.written == 7 && candidate.written == 7, + "path length matches expected detour"); + Check(astar_path[0] == model::GridPoint{0, 0} && + astar_path[candidate.written - 1] == model::GridPoint{4, 0}, + "path endpoints preserved"); + Check(candidate.expanded <= reference.expanded, + "Manhattan A* does not expand more than Dijkstra on deterministic fixture"); + + std::array tiny{}; + const auto too_small = astar.FindPath(grid, {0, 0}, {4, 0}, tiny, PathHeuristic::Manhattan); + Check(too_small.status == PathStatus::OutputTooSmall && too_small.written == 0 && + too_small.required == 7, + "path output capacity fails closed with required size"); + + const std::size_t warmed_capacity = astar.Capacity(); + const auto repeated = astar.FindPath(grid, {0, 0}, {4, 0}, astar_path, + PathHeuristic::Manhattan); + Check(repeated && astar.Capacity() == warmed_capacity, + "path workspace retains allocation capacity across equal-size searches"); + + std::array invalid_costs{1.0f, 0.5f, 1.0f, 1.0f}; + Check(astar.FindPath({invalid_costs, 2, 2, 2}, {0, 0}, {1, 1}, astar_path).status == + PathStatus::InvalidGrid, + "path costs below contract fail closed"); +} + +void TestPlacement() +{ + using namespace sc2opt; + using namespace sc2opt::kernel::compute; + + std::array buildable{}; + buildable.fill(1); + buildable[2 * 5 + 2] = 0; + const model::ByteGridView grid{buildable, 5, 5, 5}; + + const std::array mask{1, 1, 1, 1}; + const FootprintMaskView footprint{mask, 2, 2, 2}; + Check(CanPlaceMask(grid, footprint, {0, 0}), "clear 2x2 placement accepted"); + Check(!CanPlaceMask(grid, footprint, {1, 1}), "blocked footprint rejected"); + Check(!CanPlaceMask(grid, footprint, {4, 4}), "out-of-bounds footprint rejected"); + + const std::array candidates{{{0, 0}, {1, 1}, {3, 3}, {4, 4}}}; + std::array output{}; + const auto result = FilterValidPlacements(grid, footprint, candidates, output); + Check(result && result.written == 2 && output[0] == 0 && output[1] == 2, + "placement filtering preserves candidate order"); +} + +void TestCombatEvaluation() +{ + using namespace sc2opt::kernel::compute; + + const std::array side_a{{{100.0f, 10.0f}, {100.0f, 10.0f}}}; + const std::array side_b{{{50.0f, 12.5f}, {50.0f, 12.5f}}}; + + const auto a = AggregateCombatants(side_a); + Check(a && a.effective_health == 200.0 && a.effective_dps == 20.0 && a.active_units == 2, + "combat aggregate"); + + const auto exchange = EstimateContinuousExchange(side_a, side_b); + Check(exchange && exchange.outcome == ExchangeOutcome::SideAPrevails, + "continuous exchange outcome"); + Check(exchange.seconds_to_clear_b == 5.0 && exchange.seconds_to_clear_a == 8.0, + "continuous exchange times"); + + const std::array harmless{{{100.0f, 0.0f}}}; + const auto stalemate = EstimateContinuousExchange(harmless, harmless); + Check(stalemate && stalemate.outcome == ExchangeOutcome::Stalemate, + "zero-dps exchange is stalemate"); + + const std::array invalid{{{-1.0f, 100.0f}}}; + Check(AggregateCombatants(invalid).status == CombatStatus::InvalidInput, + "negative effective combat input fails closed"); +} + +} // namespace + +int main() +{ + TestTargetSelection(); + TestInfluenceEquivalence(); + TestPathing(); + TestPlacement(); + TestCombatEvaluation(); + + if (failures == 0) + { + std::cout << "SC2AIOptimize Compute tests passed\n"; + return 0; + } + + std::cerr << failures << " Compute test(s) failed\n"; + return 1; +}