From 91d2ef6f274dac7d31ba9bbf73e8919a37c7d4f8 Mon Sep 17 00:00:00 2001 From: Vales Date: Tue, 18 Aug 2026 23:14:00 +0100 Subject: [PATCH 1/2] add certified-off hot kernel candidates --- .github/workflows/ci.yml | 4 +- Bench/Micro/spatial_query_bench.cpp | 167 ++++++++++++ CMakeLists.txt | 16 ++ Kernel/Hot/BatchGeometry.cpp | 8 +- Kernel/Hot/Filtering.cpp | 45 ++++ Kernel/Hot/SpatialGrid.cpp | 243 ++++++++++++++++++ Kernel/README.md | 8 +- docs/HOT_KERNELS.md | 34 +++ include/sc2opt/adapters/cpp/WorldView.hpp | 40 +-- include/sc2opt/kernel/hot/BatchGeometry.hpp | 11 +- include/sc2opt/kernel/hot/CombatGeometry.hpp | 54 ++++ include/sc2opt/kernel/hot/Filtering.hpp | 38 +++ include/sc2opt/kernel/hot/Geometry.hpp | 16 +- include/sc2opt/kernel/hot/SpatialGrid.hpp | 84 ++++++ include/sc2opt/kernel/hot/SpatialStrategy.hpp | 41 +++ include/sc2opt/model/WorldView.hpp | 41 +++ tests/hot_kernel_tests.cpp | 184 +++++++++++++ 17 files changed, 992 insertions(+), 42 deletions(-) create mode 100644 Bench/Micro/spatial_query_bench.cpp create mode 100644 Kernel/Hot/Filtering.cpp create mode 100644 Kernel/Hot/SpatialGrid.cpp create mode 100644 docs/HOT_KERNELS.md create mode 100644 include/sc2opt/kernel/hot/CombatGeometry.hpp create mode 100644 include/sc2opt/kernel/hot/Filtering.hpp create mode 100644 include/sc2opt/kernel/hot/SpatialGrid.hpp create mode 100644 include/sc2opt/kernel/hot/SpatialStrategy.hpp create mode 100644 include/sc2opt/model/WorldView.hpp create mode 100644 tests/hot_kernel_tests.cpp diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 77f35f4..4c9ae69 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,7 +18,9 @@ jobs: steps: - uses: actions/checkout@v4 - name: Configure - run: cmake -S . -B build -DSC2OPT_BUILD_TESTS=ON -DSC2OPT_WARNINGS_AS_ERRORS=ON + run: >- + cmake -S . -B build -DSC2OPT_BUILD_TESTS=ON + -DSC2OPT_BUILD_BENCHMARKS=ON -DSC2OPT_WARNINGS_AS_ERRORS=ON - name: Build run: cmake --build build --config Release - name: Test diff --git a/Bench/Micro/spatial_query_bench.cpp b/Bench/Micro/spatial_query_bench.cpp new file mode 100644 index 0000000..7fc8ca6 --- /dev/null +++ b/Bench/Micro/spatial_query_bench.cpp @@ -0,0 +1,167 @@ +#include "sc2opt/kernel/hot/SpatialGrid.hpp" + +#include +#include +#include +#include +#include +#include + +namespace { + +using Clock = std::chrono::steady_clock; + +struct Lcg { + std::uint32_t state = 0x12345678u; + + std::uint32_t Next() noexcept + { + state = state * 1664525u + 1013904223u; + return state; + } + + float Coordinate() noexcept + { + return static_cast(Next() & 0xffffu) * (128.0f / 65535.0f); + } +}; + +template +std::uint64_t MedianNanoseconds(Function&& function) +{ + std::array samples{}; + std::uint64_t checksum = 0; + for (std::size_t i = 0; i < samples.size(); ++i) + { + const auto start = Clock::now(); + checksum ^= function(); + const auto stop = Clock::now(); + samples[i] = static_cast( + std::chrono::duration_cast(stop - start).count()); + } + std::sort(samples.begin(), samples.end()); + // Keep observable work outside the timed region. + if (checksum == 0xFFFFFFFFFFFFFFFFull) + std::cerr << "checksum sentinel\n"; + return samples[samples.size() / 2]; +} + +std::uint64_t RunQueries(const std::vector& xy, + const std::vector& centers, + float radius, + std::vector& output) +{ + std::uint64_t checksum = 0; + for (const auto center : centers) + { + const auto result = sc2opt::kernel::hot::RadiusQueryBruteForce(xy, center, radius, output); + if (!result) + return 0; + checksum += result.written; + if (result.written != 0) + checksum ^= output[result.written - 1]; + } + return checksum; +} + +std::uint64_t RunGridQueries(sc2opt::kernel::hot::SpatialGrid2D& grid, + const std::vector& xy, + const std::vector& centers, + float radius, + std::vector& output, + sc2opt::kernel::hot::SpatialOrder order) +{ + if (grid.Rebuild(xy) != sc2opt::kernel::hot::SpatialStatus::Ok) + return 0; + + std::uint64_t checksum = 0; + for (const auto center : centers) + { + const auto result = grid.Query(center, radius, output, order); + if (!result) + return 0; + checksum += result.written; + if (result.written != 0) + checksum ^= output[result.written - 1]; + } + return checksum; +} + +bool VerifyStableEquivalence(const std::vector& xy, + const std::vector& centers, + float radius, + sc2opt::kernel::hot::SpatialGrid2D& grid, + std::vector& baseline, + std::vector& candidate) +{ + if (grid.Rebuild(xy) != sc2opt::kernel::hot::SpatialStatus::Ok) + return false; + + for (const auto center : centers) + { + const auto reference = + sc2opt::kernel::hot::RadiusQueryBruteForce(xy, center, radius, baseline); + const auto accelerated = grid.Query(center, radius, candidate, + sc2opt::kernel::hot::SpatialOrder::InputOrder); + if (!reference || !accelerated || reference.written != accelerated.written) + return false; + if (!std::equal(baseline.begin(), baseline.begin() + reference.written, + candidate.begin())) + { + return false; + } + } + return true; +} + +} // namespace + +int main() +{ + constexpr std::array sizes{8, 16, 32, 64, 128, 256, 512}; + constexpr std::size_t query_count = 256; + constexpr float radius = 8.0f; + constexpr float cell_size = 4.0f; + + std::cout << "# synthetic calibration only; do not treat CI timing as certification\n"; + std::cout << "points,queries,cell_size,radius,baseline_total_ns,grid_stable_total_ns," + "grid_unordered_total_ns\n"; + + for (const std::size_t point_count : sizes) + { + Lcg rng; + std::vector xy(point_count * 2); + for (float& value : xy) + value = rng.Coordinate(); + + std::vector centers(query_count); + for (auto& center : centers) + center = {rng.Coordinate(), rng.Coordinate()}; + + std::vector baseline(point_count); + std::vector candidate(point_count); + sc2opt::kernel::hot::SpatialGrid2D grid; + if (grid.SetCellSize(cell_size) != sc2opt::kernel::hot::SpatialStatus::Ok || + !VerifyStableEquivalence(xy, centers, radius, grid, baseline, candidate)) + { + std::cerr << "equivalence failure at point_count=" << point_count << '\n'; + return 2; + } + + const auto baseline_ns = MedianNanoseconds( + [&] { return RunQueries(xy, centers, radius, baseline); }); + const auto stable_ns = MedianNanoseconds([&] { + return RunGridQueries(grid, xy, centers, radius, candidate, + sc2opt::kernel::hot::SpatialOrder::InputOrder); + }); + const auto unordered_ns = MedianNanoseconds([&] { + return RunGridQueries(grid, xy, centers, radius, candidate, + sc2opt::kernel::hot::SpatialOrder::Unordered); + }); + + std::cout << point_count << ',' << query_count << ',' << cell_size << ',' << radius << ',' + << baseline_ns << ',' << stable_ns << ',' << unordered_ns << '\n'; + } + + return 0; +} diff --git a/CMakeLists.txt b/CMakeLists.txt index 56fe207..9354175 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,6 +2,7 @@ cmake_minimum_required(VERSION 3.20) project(SC2AIOptimize VERSION 0.1.0 LANGUAGES CXX) option(SC2OPT_BUILD_TESTS "Build SC2AIOptimize tests" ON) +option(SC2OPT_BUILD_BENCHMARKS "Build calibration/benchmark tools" OFF) option(SC2OPT_BUILD_PYTHON "Build the optional generic Python adapter" OFF) option(SC2OPT_WARNINGS_AS_ERRORS "Treat project warnings as errors" OFF) @@ -30,6 +31,8 @@ sc2opt_apply_warnings(sc2opt_registry) add_library(sc2opt_kernel STATIC Kernel/Hot/BatchGeometry.cpp + Kernel/Hot/Filtering.cpp + Kernel/Hot/SpatialGrid.cpp ) add_library(sc2opt::kernel ALIAS sc2opt_kernel) target_include_directories(sc2opt_kernel PUBLIC include) @@ -91,6 +94,12 @@ if(SC2OPT_BUILD_TESTS) sc2opt_apply_warnings(sc2opt_adapter_batch_tests) add_test(NAME sc2opt_adapter_batch_tests COMMAND sc2opt_adapter_batch_tests) + add_executable(sc2opt_hot_kernel_tests tests/hot_kernel_tests.cpp) + target_link_libraries(sc2opt_hot_kernel_tests PRIVATE sc2opt) + target_compile_features(sc2opt_hot_kernel_tests PRIVATE cxx_std_20) + sc2opt_apply_warnings(sc2opt_hot_kernel_tests) + add_test(NAME sc2opt_hot_kernel_tests COMMAND sc2opt_hot_kernel_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) @@ -107,3 +116,10 @@ if(SC2OPT_BUILD_TESTS) ) endif() endif() + +if(SC2OPT_BUILD_BENCHMARKS) + add_executable(sc2opt_spatial_query_bench Bench/Micro/spatial_query_bench.cpp) + target_link_libraries(sc2opt_spatial_query_bench PRIVATE sc2opt) + target_compile_features(sc2opt_spatial_query_bench PRIVATE cxx_std_20) + sc2opt_apply_warnings(sc2opt_spatial_query_bench) +endif() diff --git a/Kernel/Hot/BatchGeometry.cpp b/Kernel/Hot/BatchGeometry.cpp index 53029cf..4a8a182 100644 --- a/Kernel/Hot/BatchGeometry.cpp +++ b/Kernel/Hot/BatchGeometry.cpp @@ -43,7 +43,8 @@ BatchResult DistanceSquaredFromPoint(std::span xy, BatchResult WithinRadiusMaskFromPoint(std::span xy, Vec2 anchor, float radius, - std::span output) noexcept + std::span output, + BoundaryMode boundary) noexcept { const BatchResult validation = Validate(xy, output.size()); if (!validation) @@ -56,7 +57,10 @@ BatchResult WithinRadiusMaskFromPoint(std::span xy, { const float dx = xy[i * 2] - anchor.x; const float dy = xy[i * 2 + 1] - anchor.y; - output[i] = static_cast(dx * dx + dy * dy <= radius_squared); + const float distance_squared = dx * dx + dy * dy; + output[i] = static_cast( + boundary == BoundaryMode::Inclusive ? distance_squared <= radius_squared + : distance_squared < radius_squared); } return validation; diff --git a/Kernel/Hot/Filtering.cpp b/Kernel/Hot/Filtering.cpp new file mode 100644 index 0000000..95e4b0e --- /dev/null +++ b/Kernel/Hot/Filtering.cpp @@ -0,0 +1,45 @@ +#include "sc2opt/kernel/hot/Filtering.hpp" + +namespace sc2opt::kernel::hot { +namespace { + +[[nodiscard]] bool Matches(const model::UnitView& unit, UnitFilter filter) noexcept +{ + if ((unit.flags & filter.required_flags) != filter.required_flags) + return false; + if ((unit.flags & filter.excluded_flags) != 0u) + return false; + if (filter.consumer_type_id != kAnyConsumerType && + unit.consumer_type_id != filter.consumer_type_id) + { + return false; + } + return unit.health >= filter.minimum_health; +} + +} // namespace + +FilterResult FilterUnitIndices(std::span units, + UnitFilter filter, + std::span output) noexcept +{ + std::size_t required = 0; + std::size_t written = 0; + + for (std::size_t i = 0; i < units.size(); ++i) + { + if (!Matches(units[i], filter)) + continue; + + if (written < output.size()) + output[written] = static_cast(i); + ++written; + ++required; + } + + if (required > output.size()) + return {FilterStatus::OutputTooSmall, 0, required}; + return {FilterStatus::Ok, required, required}; +} + +} // namespace sc2opt::kernel::hot diff --git a/Kernel/Hot/SpatialGrid.cpp b/Kernel/Hot/SpatialGrid.cpp new file mode 100644 index 0000000..99d12ed --- /dev/null +++ b/Kernel/Hot/SpatialGrid.cpp @@ -0,0 +1,243 @@ +#include "sc2opt/kernel/hot/SpatialGrid.hpp" + +#include +#include +#include +#include + +namespace sc2opt::kernel::hot { +namespace { + +using CellKey = std::uint64_t; + +[[nodiscard]] CellKey MakeCellKey(std::int32_t x, std::int32_t y) noexcept +{ + return (static_cast(static_cast(x)) << 32) | + static_cast(y); +} + +[[nodiscard]] bool CellCoord(float value, float cell_size, std::int32_t& output) noexcept +{ + const double coordinate = std::floor(static_cast(value) / cell_size); + if (coordinate < static_cast(std::numeric_limits::min()) || + coordinate > static_cast(std::numeric_limits::max())) + { + return false; + } + output = static_cast(coordinate); + return true; +} + +[[nodiscard]] SpatialStatus ValidateCoordinates(std::span xy) noexcept +{ + if ((xy.size() & 1u) != 0u) + return SpatialStatus::InvalidCoordinateCount; + if (xy.size() / 2 > std::numeric_limits::max()) + return SpatialStatus::TooManyPoints; + for (float value : xy) + { + if (!std::isfinite(value)) + return SpatialStatus::NonFiniteCoordinate; + } + return SpatialStatus::Ok; +} + +[[nodiscard]] bool ValidQuery(Vec2 center, float radius) noexcept +{ + return std::isfinite(center.x) && std::isfinite(center.y) && std::isfinite(radius) && + radius >= 0.0f; +} + +[[nodiscard]] bool Inside(float distance_squared, + float radius_squared, + BoundaryMode boundary) noexcept +{ + return boundary == BoundaryMode::Inclusive ? distance_squared <= radius_squared + : distance_squared < radius_squared; +} + +} // namespace + +SpatialQueryResult RadiusQueryBruteForce(std::span xy, + Vec2 center, + float radius, + std::span output, + BoundaryMode boundary) noexcept +{ + const SpatialStatus coordinates = ValidateCoordinates(xy); + if (coordinates != SpatialStatus::Ok) + return {coordinates, 0, 0}; + if (!ValidQuery(center, radius)) + return {SpatialStatus::InvalidQuery, 0, 0}; + + const float radius_squared = radius * radius; + std::size_t required = 0; + const std::size_t points = xy.size() / 2; + for (std::size_t i = 0; i < points; ++i) + { + const float dx = xy[i * 2] - center.x; + const float dy = xy[i * 2 + 1] - center.y; + if (!Inside(dx * dx + dy * dy, radius_squared, boundary)) + continue; + + if (required < output.size()) + output[required] = static_cast(i); + ++required; + } + + if (required > output.size()) + return {SpatialStatus::OutputTooSmall, 0, required}; + return {SpatialStatus::Ok, required, required}; +} + +SpatialStatus SpatialGrid2D::SetCellSize(float cell_size) noexcept +{ + if (!std::isfinite(cell_size) || cell_size <= 0.0f) + { + ready_ = false; + point_count_ = 0; + active_cell_count_ = 0; + return SpatialStatus::InvalidCellSize; + } + + if (cell_size != cell_size_) + { + cell_size_ = cell_size; + cells_.clear(); + touched_cells_.clear(); + point_count_ = 0; + active_cell_count_ = 0; + ready_ = false; + } + return SpatialStatus::Ok; +} + +SpatialStatus SpatialGrid2D::Rebuild(std::span xy) noexcept +{ + const SpatialStatus coordinates = ValidateCoordinates(xy); + if (coordinates != SpatialStatus::Ok) + { + ready_ = false; + point_count_ = 0; + active_cell_count_ = 0; + return coordinates; + } + if (!std::isfinite(cell_size_) || cell_size_ <= 0.0f) + { + ready_ = false; + point_count_ = 0; + active_cell_count_ = 0; + return SpatialStatus::InvalidCellSize; + } + + const std::size_t points = xy.size() / 2; + for (std::size_t i = 0; i < points; ++i) + { + std::int32_t x = 0; + std::int32_t y = 0; + if (!CellCoord(xy[i * 2], cell_size_, x) || !CellCoord(xy[i * 2 + 1], cell_size_, y)) + { + ready_ = false; + point_count_ = 0; + active_cell_count_ = 0; + return SpatialStatus::NonFiniteCoordinate; + } + } + + for (CellKey key : touched_cells_) + { + const auto found = cells_.find(key); + if (found != cells_.end()) + found->second.clear(); + } + touched_cells_.clear(); + + const float current_capacity = + static_cast(cells_.bucket_count()) * cells_.max_load_factor(); + if (static_cast(points) > current_capacity) + cells_.reserve(points); + if (touched_cells_.capacity() < points) + touched_cells_.reserve(points); + + for (std::size_t i = 0; i < points; ++i) + { + std::int32_t cell_x = 0; + std::int32_t cell_y = 0; + static_cast(CellCoord(xy[i * 2], cell_size_, cell_x)); + static_cast(CellCoord(xy[i * 2 + 1], cell_size_, cell_y)); + const CellKey key = MakeCellKey(cell_x, cell_y); + + auto found = cells_.find(key); + if (found == cells_.end()) + found = cells_.emplace(key, std::vector{}).first; + if (found->second.empty()) + touched_cells_.push_back(key); + found->second.push_back( + {xy[i * 2], xy[i * 2 + 1], static_cast(i)}); + } + + point_count_ = points; + active_cell_count_ = touched_cells_.size(); + ready_ = true; + return SpatialStatus::Ok; +} + +SpatialQueryResult SpatialGrid2D::Query(Vec2 center, + float radius, + std::span output, + SpatialOrder order, + BoundaryMode boundary) const noexcept +{ + if (!ready_) + return {SpatialStatus::NotReady, 0, 0}; + if (!ValidQuery(center, radius)) + return {SpatialStatus::InvalidQuery, 0, 0}; + + std::int32_t min_x = 0; + std::int32_t max_x = 0; + std::int32_t min_y = 0; + std::int32_t max_y = 0; + if (!CellCoord(center.x - radius, cell_size_, min_x) || + !CellCoord(center.x + radius, cell_size_, max_x) || + !CellCoord(center.y - radius, cell_size_, min_y) || + !CellCoord(center.y + radius, cell_size_, max_y)) + { + return {SpatialStatus::InvalidQuery, 0, 0}; + } + + const float radius_squared = radius * radius; + std::size_t required = 0; + + for (std::int64_t x = min_x; x <= max_x; ++x) + { + for (std::int64_t y = min_y; y <= max_y; ++y) + { + const auto found = cells_.find( + MakeCellKey(static_cast(x), static_cast(y))); + if (found == cells_.end()) + continue; + + for (const Entry& entry : found->second) + { + const float dx = entry.x - center.x; + const float dy = entry.y - center.y; + if (!Inside(dx * dx + dy * dy, radius_squared, boundary)) + continue; + + if (required < output.size()) + output[required] = entry.index; + ++required; + } + } + } + + if (required > output.size()) + return {SpatialStatus::OutputTooSmall, 0, required}; + + if (order == SpatialOrder::InputOrder) + std::sort(output.begin(), output.begin() + static_cast(required)); + + return {SpatialStatus::Ok, required, required}; +} + +} // namespace sc2opt::kernel::hot diff --git a/Kernel/README.md b/Kernel/README.md index eff8744..352f6e5 100644 --- a/Kernel/README.md +++ b/Kernel/README.md @@ -1,5 +1,9 @@ # Kernel -Framework-independent compute lives here. `Hot` is reserved for tiny, repeatedly-called operations that have profiling evidence and an equivalence-tested baseline. Larger native jobs belong in Compute only when the larger boundary produces positive measured net benefit. +Framework-independent compute lives here. -Hot admission is earned, not guessed. +`Hot` contains small baseline/candidate operations with explicit semantics and caller-owned output where practical. An accelerated implementation is not automatically selected merely because it exists; strategy/crossover profiles default to baseline until measurement certifies otherwise. + +Larger native jobs belong in Compute only when profiling shows the larger native boundary produces positive measured net benefit. + +See `docs/HOT_KERNELS.md`. diff --git a/docs/HOT_KERNELS.md b/docs/HOT_KERNELS.md new file mode 100644 index 0000000..dd68e90 --- /dev/null +++ b/docs/HOT_KERNELS.md @@ -0,0 +1,34 @@ +# Hot kernel contract + +`Kernel/Hot` contains small operations with a known-correct baseline and explicit semantics. Presence in this directory does **not** mean every consumer should always use the accelerated candidate. + +## Geometry + +Distance/radius operations expose explicit `BoundaryMode::Strict` and `BoundaryMode::Inclusive` semantics. This exists because MMEvo Z2 demonstrated that changing `< radius` to `<= radius` during candidate reduction is a real behavioural regression. + +Facing accepts a pre-normalized facing vector and precomputed dot threshold so hot calls do not pay repeated angle/trigonometry work that the consumer can cache. + +## Filtering + +Filtering writes matching indices into caller-owned storage. No result container allocation is required. If capacity is insufficient, the call reports the required size and the caller must ignore partial output. + +## Spatial query + +`RadiusQueryBruteForce` is the exact O(n) baseline. `SpatialGrid2D` is the reusable grid candidate inspired by MMEvo Z2: + +- cell/bucket storage is retained across rebuilds; +- only active/touched bucket vectors are cleared; +- exact radius filtering happens after bucket candidate reduction; +- each input point occurs in exactly one bucket; +- stable `InputOrder` mode sorts results back to source order; +- `Unordered` mode exists only for consumers whose semantics permit it; +- query output is caller-owned; +- invalid state/query fails closed. + +The grid is **off by default** at the strategy layer. `SpatialCrossoverProfile` initializes both thresholds to `size_t::max()`, which means the brute-force baseline remains champion until target-workload calibration supplies a certified crossover. + +## Benchmark discipline + +`sc2opt_spatial_query_bench` is a synthetic calibration tool. It includes grid rebuild cost in the grid workload and verifies stable-result equivalence before timing. CI compiles it but does not run it as a performance gate and does not promote thresholds from runner timing. + +Real promotion requires the target hardware and representative workload/profile evidence. diff --git a/include/sc2opt/adapters/cpp/WorldView.hpp b/include/sc2opt/adapters/cpp/WorldView.hpp index 5081f73..4deb29e 100644 --- a/include/sc2opt/adapters/cpp/WorldView.hpp +++ b/include/sc2opt/adapters/cpp/WorldView.hpp @@ -1,38 +1,18 @@ #pragma once -#include -#include -#include +#include "sc2opt/model/WorldView.hpp" namespace sc2opt::adapters::cpp { -enum UnitFlag : std::uint32_t { - UnitAlive = 1u << 0, - UnitFlying = 1u << 1, - UnitStructure = 1u << 2, - UnitVisible = 1u << 3 -}; +// Backward-compatible C++ adapter aliases. The neutral data contract belongs to `model`, not +// to an adapter implementation, so Kernel code can consume it without depending on Adapters. +using UnitFlag = model::UnitFlag; +using UnitView = model::UnitView; +using WorldView = model::WorldView; -struct UnitView { - std::uint64_t tag = 0; - std::uint32_t consumer_type_id = 0; - std::uint32_t flags = 0; - float x = 0.0f; - float y = 0.0f; - float health = 0.0f; - float shields = 0.0f; - float energy = 0.0f; - float radius = 0.0f; -}; - -struct WorldView { - std::uint32_t frame = 0; - std::span self; - std::span enemy; - std::span neutral; -}; - -static_assert(std::is_trivially_copyable_v); -static_assert(std::is_standard_layout_v); +inline constexpr UnitFlag UnitAlive = model::UnitAlive; +inline constexpr UnitFlag UnitFlying = model::UnitFlying; +inline constexpr UnitFlag UnitStructure = model::UnitStructure; +inline constexpr UnitFlag UnitVisible = model::UnitVisible; } // namespace sc2opt::adapters::cpp diff --git a/include/sc2opt/kernel/hot/BatchGeometry.hpp b/include/sc2opt/kernel/hot/BatchGeometry.hpp index cf60297..012701c 100644 --- a/include/sc2opt/kernel/hot/BatchGeometry.hpp +++ b/include/sc2opt/kernel/hot/BatchGeometry.hpp @@ -31,10 +31,11 @@ struct BatchResult { Vec2 anchor, std::span output) noexcept; -// Writes 1 when a point is within the inclusive radius, otherwise 0. -[[nodiscard]] BatchResult WithinRadiusMaskFromPoint(std::span xy, - Vec2 anchor, - float radius, - std::span output) noexcept; +[[nodiscard]] BatchResult WithinRadiusMaskFromPoint( + std::span xy, + Vec2 anchor, + float radius, + std::span output, + BoundaryMode boundary = BoundaryMode::Inclusive) noexcept; } // namespace sc2opt::kernel::hot diff --git a/include/sc2opt/kernel/hot/CombatGeometry.hpp b/include/sc2opt/kernel/hot/CombatGeometry.hpp new file mode 100644 index 0000000..8c5d3cd --- /dev/null +++ b/include/sc2opt/kernel/hot/CombatGeometry.hpp @@ -0,0 +1,54 @@ +#pragma once + +#include "sc2opt/kernel/hot/Geometry.hpp" + +#include + +namespace sc2opt::kernel::hot { + +struct Circle2 { + Vec2 center; + float radius = 0.0f; +}; + +// SC2-style center distance with both collision radii included. Negative inputs fail closed. +[[nodiscard]] constexpr bool WithinEdgeRange(Circle2 source, + Circle2 target, + float range, + BoundaryMode boundary = BoundaryMode::Inclusive) noexcept +{ + if (source.radius < 0.0f || target.radius < 0.0f || range < 0.0f) + return false; + const float effective = source.radius + target.radius + range; + const float distance_squared = DistanceSquared(source.center, target.center); + const float effective_squared = effective * effective; + return boundary == BoundaryMode::Inclusive ? distance_squared <= effective_squared + : distance_squared < effective_squared; +} + +// `facing_unit` is a pre-normalized direction owned/cached by the caller. `minimum_dot` +// represents cos(max angular error) and must be in [-1, 1]. Coincident points are treated as +// facing because no turn is required. This avoids atan2 and avoids normalizing the facing vector +// inside a hot query. +[[nodiscard]] inline bool WithinFacingCone(Vec2 origin, + Vec2 facing_unit, + Vec2 target, + float minimum_dot, + BoundaryMode boundary = BoundaryMode::Inclusive) noexcept +{ + if (minimum_dot < -1.0f || minimum_dot > 1.0f) + return false; + + const float dx = target.x - origin.x; + const float dy = target.y - origin.y; + const float distance_squared = dx * dx + dy * dy; + if (distance_squared == 0.0f) + return true; + + const float inverse_distance = 1.0f / std::sqrt(distance_squared); + const float dot = facing_unit.x * (dx * inverse_distance) + + facing_unit.y * (dy * inverse_distance); + return boundary == BoundaryMode::Inclusive ? dot >= minimum_dot : dot > minimum_dot; +} + +} // namespace sc2opt::kernel::hot diff --git a/include/sc2opt/kernel/hot/Filtering.hpp b/include/sc2opt/kernel/hot/Filtering.hpp new file mode 100644 index 0000000..a63bdf4 --- /dev/null +++ b/include/sc2opt/kernel/hot/Filtering.hpp @@ -0,0 +1,38 @@ +#pragma once + +#include "sc2opt/model/WorldView.hpp" + +#include +#include +#include +#include + +namespace sc2opt::kernel::hot { + +inline constexpr std::uint32_t kAnyConsumerType = std::numeric_limits::max(); + +struct UnitFilter { + std::uint32_t required_flags = 0; + std::uint32_t excluded_flags = 0; + std::uint32_t consumer_type_id = kAnyConsumerType; + float minimum_health = 0.0f; +}; + +enum class FilterStatus : std::uint8_t { Ok = 0, OutputTooSmall }; + +struct FilterResult { + FilterStatus status = FilterStatus::Ok; + std::size_t written = 0; + std::size_t required = 0; + + [[nodiscard]] constexpr explicit operator bool() const noexcept + { + return status == FilterStatus::Ok; + } +}; + +[[nodiscard]] FilterResult FilterUnitIndices(std::span units, + UnitFilter filter, + std::span output) noexcept; + +} // namespace sc2opt::kernel::hot diff --git a/include/sc2opt/kernel/hot/Geometry.hpp b/include/sc2opt/kernel/hot/Geometry.hpp index fe5ebb7..2002ac1 100644 --- a/include/sc2opt/kernel/hot/Geometry.hpp +++ b/include/sc2opt/kernel/hot/Geometry.hpp @@ -1,6 +1,7 @@ #pragma once #include +#include namespace sc2opt::kernel::hot { @@ -9,6 +10,11 @@ struct Vec2 { float y = 0.0f; }; +enum class BoundaryMode : std::uint8_t { + Strict = 0, + Inclusive +}; + [[nodiscard]] constexpr float DistanceSquared(Vec2 a, Vec2 b) noexcept { const float dx = a.x - b.x; @@ -16,11 +22,17 @@ struct Vec2 { return dx * dx + dy * dy; } -[[nodiscard]] constexpr bool WithinRadius(Vec2 a, Vec2 b, float radius) noexcept +[[nodiscard]] constexpr bool WithinRadius(Vec2 a, + Vec2 b, + float radius, + BoundaryMode boundary = BoundaryMode::Inclusive) noexcept { if (radius < 0.0f) return false; - return DistanceSquared(a, b) <= radius * radius; + const float distance_squared = DistanceSquared(a, b); + const float radius_squared = radius * radius; + return boundary == BoundaryMode::Inclusive ? distance_squared <= radius_squared + : distance_squared < radius_squared; } [[nodiscard]] inline float Distance(Vec2 a, Vec2 b) noexcept diff --git a/include/sc2opt/kernel/hot/SpatialGrid.hpp b/include/sc2opt/kernel/hot/SpatialGrid.hpp new file mode 100644 index 0000000..766bf45 --- /dev/null +++ b/include/sc2opt/kernel/hot/SpatialGrid.hpp @@ -0,0 +1,84 @@ +#pragma once + +#include "sc2opt/kernel/hot/Geometry.hpp" + +#include +#include +#include +#include +#include + +namespace sc2opt::kernel::hot { + +enum class SpatialStatus : std::uint8_t { + Ok = 0, + NotReady, + InvalidCellSize, + InvalidCoordinateCount, + TooManyPoints, + NonFiniteCoordinate, + InvalidQuery, + OutputTooSmall +}; + +enum class SpatialOrder : std::uint8_t { + Unordered = 0, + InputOrder +}; + +struct SpatialQueryResult { + SpatialStatus status = SpatialStatus::Ok; + std::size_t written = 0; + std::size_t required = 0; + + [[nodiscard]] constexpr explicit operator bool() const noexcept + { + return status == SpatialStatus::Ok; + } +}; + +// Exact O(n) reference/fallback query over [x0,y0,x1,y1,...]. Results are input-index ordered. +[[nodiscard]] SpatialQueryResult RadiusQueryBruteForce( + std::span xy, + Vec2 center, + float radius, + std::span output, + BoundaryMode boundary = BoundaryMode::Inclusive) noexcept; + +class SpatialGrid2D { +public: + SpatialGrid2D() = default; + + [[nodiscard]] SpatialStatus SetCellSize(float cell_size) noexcept; + [[nodiscard]] SpatialStatus Rebuild(std::span xy) noexcept; + + [[nodiscard]] SpatialQueryResult Query( + Vec2 center, + float radius, + std::span output, + SpatialOrder order = SpatialOrder::InputOrder, + BoundaryMode boundary = BoundaryMode::Inclusive) const noexcept; + + [[nodiscard]] float CellSize() const noexcept { return cell_size_; } + [[nodiscard]] std::size_t PointCount() const noexcept { return point_count_; } + [[nodiscard]] std::size_t ActiveCellCount() const noexcept { return active_cell_count_; } + [[nodiscard]] bool Ready() const noexcept { return ready_; } + +private: + struct Entry { + float x = 0.0f; + float y = 0.0f; + std::uint32_t index = 0; + }; + + using CellKey = std::uint64_t; + + float cell_size_ = 4.0f; + std::unordered_map> cells_; + std::vector touched_cells_; + std::size_t point_count_ = 0; + std::size_t active_cell_count_ = 0; + bool ready_ = false; +}; + +} // namespace sc2opt::kernel::hot diff --git a/include/sc2opt/kernel/hot/SpatialStrategy.hpp b/include/sc2opt/kernel/hot/SpatialStrategy.hpp new file mode 100644 index 0000000..4157111 --- /dev/null +++ b/include/sc2opt/kernel/hot/SpatialStrategy.hpp @@ -0,0 +1,41 @@ +#pragma once + +#include +#include + +namespace sc2opt::kernel::hot { + +enum class SpatialQueryStrategy { + BruteForce = 0, + GridInputOrder, + GridUnordered +}; + +struct SpatialCrossoverProfile { + // `max()` means "not certified": baseline remains champion for that variant. + std::size_t grid_input_order_min_points = std::numeric_limits::max(); + std::size_t grid_unordered_min_points = std::numeric_limits::max(); +}; + +[[nodiscard]] constexpr SpatialQueryStrategy ChooseSpatialQueryStrategy( + std::size_t point_count, + bool require_input_order, + bool grid_ready, + SpatialCrossoverProfile profile) noexcept +{ + if (!grid_ready) + return SpatialQueryStrategy::BruteForce; + + if (require_input_order) + { + return point_count >= profile.grid_input_order_min_points + ? SpatialQueryStrategy::GridInputOrder + : SpatialQueryStrategy::BruteForce; + } + + return point_count >= profile.grid_unordered_min_points + ? SpatialQueryStrategy::GridUnordered + : SpatialQueryStrategy::BruteForce; +} + +} // namespace sc2opt::kernel::hot diff --git a/include/sc2opt/model/WorldView.hpp b/include/sc2opt/model/WorldView.hpp new file mode 100644 index 0000000..74600d1 --- /dev/null +++ b/include/sc2opt/model/WorldView.hpp @@ -0,0 +1,41 @@ +#pragma once + +#include +#include +#include + +namespace sc2opt::model { + +enum UnitFlag : std::uint32_t { + UnitAlive = 1u << 0, + UnitFlying = 1u << 1, + UnitStructure = 1u << 2, + UnitVisible = 1u << 3 +}; + +struct UnitView { + std::uint64_t tag = 0; + std::uint32_t consumer_type_id = 0; + std::uint32_t flags = 0; + float x = 0.0f; + float y = 0.0f; + float health = 0.0f; + float shields = 0.0f; + float energy = 0.0f; + float radius = 0.0f; +}; + +struct WorldView { + std::uint32_t frame = 0; + std::span self; + std::span enemy; + std::span neutral; +}; + +inline constexpr std::uint32_t kUnitViewAbiVersion = 1; + +static_assert(std::is_trivially_copyable_v); +static_assert(std::is_standard_layout_v); +static_assert(sizeof(UnitView) == 40, "UnitView ABI changed: bump version and re-certify adapters"); + +} // namespace sc2opt::model diff --git a/tests/hot_kernel_tests.cpp b/tests/hot_kernel_tests.cpp new file mode 100644 index 0000000..15b3373 --- /dev/null +++ b/tests/hot_kernel_tests.cpp @@ -0,0 +1,184 @@ +#include "sc2opt/kernel/hot/CombatGeometry.hpp" +#include "sc2opt/kernel/hot/Filtering.hpp" +#include "sc2opt/kernel/hot/SpatialGrid.hpp" +#include "sc2opt/kernel/hot/SpatialStrategy.hpp" +#include "sc2opt/model/WorldView.hpp" + +#include +#include +#include +#include + +namespace { + +int failures = 0; + +void Check(bool condition, const char* message) +{ + if (!condition) + { + ++failures; + std::cerr << "FAIL: " << message << '\n'; + } +} + +void TestBoundarySemantics() +{ + using namespace sc2opt::kernel::hot; + + Check(WithinRadius({0.0f, 0.0f}, {3.0f, 4.0f}, 5.0f, BoundaryMode::Inclusive), + "inclusive radius accepts exact boundary"); + Check(!WithinRadius({0.0f, 0.0f}, {3.0f, 4.0f}, 5.0f, BoundaryMode::Strict), + "strict radius rejects exact boundary"); + + const Circle2 source{{0.0f, 0.0f}, 1.0f}; + const Circle2 target{{5.0f, 0.0f}, 1.0f}; + Check(WithinEdgeRange(source, target, 3.0f, BoundaryMode::Inclusive), + "edge range includes exact boundary"); + Check(!WithinEdgeRange(source, target, 3.0f, BoundaryMode::Strict), + "edge range strict boundary"); + + Check(WithinFacingCone({0.0f, 0.0f}, {1.0f, 0.0f}, {4.0f, 0.0f}, 1.0f, + BoundaryMode::Inclusive), + "facing inclusive exact dot"); + Check(!WithinFacingCone({0.0f, 0.0f}, {1.0f, 0.0f}, {4.0f, 0.0f}, 1.0f, + BoundaryMode::Strict), + "facing strict exact dot"); + Check(WithinFacingCone({2.0f, 2.0f}, {1.0f, 0.0f}, {2.0f, 2.0f}, 0.9f), + "coincident target requires no turn"); +} + +void TestFiltering() +{ + using namespace sc2opt; + const std::array units{{ + {1, 7, model::UnitAlive | model::UnitVisible, 0, 0, 45, 0, 0, 0.375f}, + {2, 7, model::UnitAlive | model::UnitFlying, 0, 0, 125, 0, 0, 0.75f}, + {3, 9, model::UnitAlive | model::UnitVisible, 0, 0, 10, 0, 0, 0.5f}, + {4, 7, model::UnitVisible, 0, 0, 200, 0, 0, 1.0f}, + }}; + + std::array output{}; + const kernel::hot::UnitFilter filter{model::UnitAlive, model::UnitFlying, 7, 20.0f}; + const auto result = kernel::hot::FilterUnitIndices(units, filter, output); + Check(result && result.written == 1 && output[0] == 0, "unit filter exact result"); + + std::array tiny{}; + const auto too_small = kernel::hot::FilterUnitIndices(units, filter, tiny); + Check(too_small.status == kernel::hot::FilterStatus::OutputTooSmall && + too_small.required == 1 && too_small.written == 0, + "unit filter reports required capacity"); +} + +void TestSpatialEquivalence() +{ + using namespace sc2opt::kernel::hot; + + const std::array xy{ + 0.0f, 0.0f, + 3.0f, 4.0f, + 5.0f, 0.0f, + 6.0f, 0.0f, + -5.0f, 0.0f, + }; + + SpatialGrid2D grid; + Check(grid.SetCellSize(4.0f) == SpatialStatus::Ok, "valid cell size"); + Check(grid.Rebuild(xy) == SpatialStatus::Ok && grid.Ready(), "spatial rebuild"); + + std::array baseline{}; + std::array stable{}; + std::array unordered{}; + + const auto baseline_inclusive = + RadiusQueryBruteForce(xy, {0.0f, 0.0f}, 5.0f, baseline, BoundaryMode::Inclusive); + const auto grid_inclusive = grid.Query({0.0f, 0.0f}, 5.0f, stable, + SpatialOrder::InputOrder, + BoundaryMode::Inclusive); + Check(baseline_inclusive && grid_inclusive && + baseline_inclusive.written == grid_inclusive.written, + "grid inclusive count matches baseline"); + Check(std::equal(baseline.begin(), baseline.begin() + baseline_inclusive.written, + stable.begin()), + "grid stable order exactly matches baseline"); + + const auto grid_unordered = grid.Query({0.0f, 0.0f}, 5.0f, unordered, + SpatialOrder::Unordered, + BoundaryMode::Inclusive); + Check(grid_unordered && grid_unordered.written == baseline_inclusive.written, + "unordered grid count matches baseline"); + std::sort(unordered.begin(), unordered.begin() + grid_unordered.written); + Check(std::equal(baseline.begin(), baseline.begin() + baseline_inclusive.written, + unordered.begin()), + "unordered grid membership matches baseline"); + + const auto baseline_strict = + RadiusQueryBruteForce(xy, {0.0f, 0.0f}, 5.0f, baseline, BoundaryMode::Strict); + const auto grid_strict = grid.Query({0.0f, 0.0f}, 5.0f, stable, + SpatialOrder::InputOrder, + BoundaryMode::Strict); + Check(baseline_strict && grid_strict && baseline_strict.written == 1 && + grid_strict.written == 1 && baseline[0] == 0 && stable[0] == 0, + "strict boundary equivalence"); + + std::array tiny{}; + const auto overflow = grid.Query({0.0f, 0.0f}, 5.0f, tiny); + Check(overflow.status == SpatialStatus::OutputTooSmall && overflow.written == 0 && + overflow.required == baseline_inclusive.written, + "spatial query reports required capacity"); + + const std::array moved{100.0f, 100.0f, 104.0f, 100.0f}; + Check(grid.Rebuild(moved) == SpatialStatus::Ok && grid.PointCount() == 2, + "spatial storage reusable across rebuilds"); + const auto old_area = grid.Query({0.0f, 0.0f}, 5.0f, stable); + Check(old_area && old_area.written == 0, "rebuild clears prior active cells"); + + Check(grid.SetCellSize(0.0f) == SpatialStatus::InvalidCellSize && !grid.Ready(), + "invalid cell size fails closed"); +} + +void TestSpatialStrategy() +{ + using namespace sc2opt::kernel::hot; + + const SpatialCrossoverProfile uncertified{}; + Check(ChooseSpatialQueryStrategy(1000, true, true, uncertified) == + SpatialQueryStrategy::BruteForce, + "uncertified stable grid remains off"); + Check(ChooseSpatialQueryStrategy(1000, false, true, uncertified) == + SpatialQueryStrategy::BruteForce, + "uncertified unordered grid remains off"); + + const SpatialCrossoverProfile certified{64, 32}; + Check(ChooseSpatialQueryStrategy(63, true, true, certified) == + SpatialQueryStrategy::BruteForce, + "stable crossover respects threshold"); + Check(ChooseSpatialQueryStrategy(64, true, true, certified) == + SpatialQueryStrategy::GridInputOrder, + "stable grid activates at certified threshold"); + Check(ChooseSpatialQueryStrategy(32, false, true, certified) == + SpatialQueryStrategy::GridUnordered, + "unordered grid activates at certified threshold"); + Check(ChooseSpatialQueryStrategy(1000, false, false, certified) == + SpatialQueryStrategy::BruteForce, + "unready grid always falls back to baseline"); +} + +} // namespace + +int main() +{ + TestBoundarySemantics(); + TestFiltering(); + TestSpatialEquivalence(); + TestSpatialStrategy(); + + if (failures == 0) + { + std::cout << "SC2AIOptimize Hot kernel tests passed\n"; + return 0; + } + + std::cerr << failures << " Hot kernel test(s) failed\n"; + return 1; +} From b592b40889fe342451c6aece120e0422f98fe4fd Mon Sep 17 00:00:00 2001 From: Vales Date: Tue, 18 Aug 2026 23:17:08 +0100 Subject: [PATCH 2/2] fix Release hot-kernel test validation --- .github/workflows/ci.yml | 5 +++-- tests/hot_kernel_tests.cpp | 26 +++++++++++++++++++++++--- 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4c9ae69..f949c54 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,8 +19,9 @@ jobs: - uses: actions/checkout@v4 - name: Configure run: >- - cmake -S . -B build -DSC2OPT_BUILD_TESTS=ON - -DSC2OPT_BUILD_BENCHMARKS=ON -DSC2OPT_WARNINGS_AS_ERRORS=ON + cmake -S . -B build -DCMAKE_BUILD_TYPE=Release + -DSC2OPT_BUILD_TESTS=ON -DSC2OPT_BUILD_BENCHMARKS=ON + -DSC2OPT_WARNINGS_AS_ERRORS=ON - name: Build run: cmake --build build --config Release - name: Test diff --git a/tests/hot_kernel_tests.cpp b/tests/hot_kernel_tests.cpp index 15b3373..9b67db4 100644 --- a/tests/hot_kernel_tests.cpp +++ b/tests/hot_kernel_tests.cpp @@ -107,9 +107,29 @@ void TestSpatialEquivalence() BoundaryMode::Inclusive); Check(grid_unordered && grid_unordered.written == baseline_inclusive.written, "unordered grid count matches baseline"); - std::sort(unordered.begin(), unordered.begin() + grid_unordered.written); - Check(std::equal(baseline.begin(), baseline.begin() + baseline_inclusive.written, - unordered.begin()), + + std::array baseline_members{}; + std::array unordered_members{}; + bool membership_indices_valid = true; + for (std::size_t i = 0; i < baseline_inclusive.written; ++i) + { + if (baseline[i] >= baseline_members.size()) + { + membership_indices_valid = false; + break; + } + baseline_members[baseline[i]] = true; + } + for (std::size_t i = 0; i < grid_unordered.written; ++i) + { + if (unordered[i] >= unordered_members.size()) + { + membership_indices_valid = false; + break; + } + unordered_members[unordered[i]] = true; + } + Check(membership_indices_valid && baseline_members == unordered_members, "unordered grid membership matches baseline"); const auto baseline_strict =