Compare commits

..
Author SHA1 Message Date
admin c69912c948 Use direct vector declarations in command tests 2026-06-23 13:04:18 -07:00
571 changed files with 99405 additions and 12131 deletions
-3
View File
@@ -14,7 +14,6 @@ common --worker_sandboxing
common --local_test_jobs=64
common --jobs=64
# Keep these C++ standard flags in sync with tools/copts.bzl and scripts/shardok_cpp_config.sh.
common --cxxopt="--std=c++23"
common --cxxopt="-Wno-deprecated-non-prototype"
common --per_file_copt=src/test/cpp/.*@-Wno-character-conversion
@@ -38,8 +37,6 @@ build:ubsan --strip=never
build:ubsan --copt=-fno-omit-frame-pointer
build:ubsan --copt=-Wno-macro-redefined
build:ubsan --copt=-fsanitize=undefined
# Protobuf's arena implementation trips UBSan alignment checks in external code on macOS.
build:ubsan --copt=-fno-sanitize=alignment
build:ubsan --linkopt=-fsanitize=undefined
test:ubsan --test_env=UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1
+18 -10
View File
@@ -2,17 +2,25 @@ Checks: >
-*,
bugprone-*,
performance-*,
modernize-use-nullptr,
modernize-use-override,
modernize-use-auto,
modernize-use-nodiscard,
readability-braces-around-statements,
readability-qualified-auto,
readability-redundant-member-init,
cppcoreguidelines-pro-type-cstyle-cast,
readability-*,
modernize-*,
cppcoreguidelines-*,
-bugprone-easily-swappable-parameters,
-bugprone-branch-clone,
-bugprone-signed-char-misuse
-cppcoreguidelines-avoid-magic-numbers,
-cppcoreguidelines-macro-usage,
-cppcoreguidelines-owning-memory,
-cppcoreguidelines-pro-bounds-array-to-pointer-decay,
-cppcoreguidelines-pro-bounds-constant-array-index,
-cppcoreguidelines-pro-bounds-pointer-arithmetic,
-cppcoreguidelines-pro-type-const-cast,
-cppcoreguidelines-pro-type-reinterpret-cast,
-cppcoreguidelines-pro-type-union-access,
-cppcoreguidelines-pro-type-vararg,
-modernize-use-trailing-return-type,
-readability-convert-member-functions-to-static,
-readability-function-cognitive-complexity,
-readability-identifier-length,
-readability-magic-numbers
WarningsAsErrors: ''
HeaderFilterRegex: 'src/(main|test)/cpp/net/eagle0/(shardok|common)/.*'
FormatStyle: file
-8
View File
@@ -12,9 +12,6 @@ on:
- '.bazelrc'
- 'ci/github_actions/ensure_bazel_installed.sh'
- 'ci/github_actions/summarize_bazel_bep.py'
- '.clang-tidy'
- 'scripts/run-clang-tidy.sh'
- 'scripts/check_shardok_clang_tidy.sh'
- '.github/actions/setup-bazel/**'
- '.github/workflows/bazel_test.yml'
- '!src/main/csharp/**'
@@ -29,9 +26,6 @@ on:
- '.bazelrc'
- 'ci/github_actions/ensure_bazel_installed.sh'
- 'ci/github_actions/summarize_bazel_bep.py'
- '.clang-tidy'
- 'scripts/run-clang-tidy.sh'
- 'scripts/check_shardok_clang_tidy.sh'
- '.github/actions/setup-bazel/**'
- '.github/workflows/bazel_test.yml'
- '!src/main/csharp/**'
@@ -84,8 +78,6 @@ jobs:
node-version: 'lts/*'
- name: Check JavaScript syntax
run: node --check src/main/go/net/eagle0/admin_server/static/map_editor.js
- name: Check Shardok clang-tidy gate
run: ./scripts/check_shardok_clang_tidy.sh
test:
runs-on: [self-hosted, bazel]
@@ -1,92 +0,0 @@
name: Shardok Sanitizer Test
on:
push:
branches: ["main"]
paths:
- "src/main/cpp/net/eagle0/shardok/**"
- "src/test/cpp/net/eagle0/shardok/**"
- "src/main/protobuf/net/eagle0/shardok/**"
- "src/main/protobuf/net/eagle0/common/**"
- "WORKSPACE"
- "MODULE.bazel"
- "MODULE.bazel.lock"
- "BUILD.bazel"
- ".bazelrc"
- ".github/actions/setup-bazel/**"
- ".github/workflows/shardok_sanitizer_test.yml"
- "ci/github_actions/ensure_bazel_installed.sh"
- "ci/github_actions/summarize_bazel_bep.py"
pull_request:
paths:
- "src/main/cpp/net/eagle0/shardok/**"
- "src/test/cpp/net/eagle0/shardok/**"
- "src/main/protobuf/net/eagle0/shardok/**"
- "src/main/protobuf/net/eagle0/common/**"
- "WORKSPACE"
- "MODULE.bazel"
- "MODULE.bazel.lock"
- "BUILD.bazel"
- ".bazelrc"
- ".github/actions/setup-bazel/**"
- ".github/workflows/shardok_sanitizer_test.yml"
- "ci/github_actions/ensure_bazel_installed.sh"
- "ci/github_actions/summarize_bazel_bep.py"
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}
cancel-in-progress: true
permissions:
contents: read
jobs:
shardok-sanitizer-test:
name: Shardok ${{ matrix.name }}
runs-on: [self-hosted, bazel]
strategy:
fail-fast: false
matrix:
include:
- name: ASan
config: asan
- name: UBSan
config: ubsan
steps:
- name: Ensure Git LFS available for checkout
run: |
COMMON_PATHS=(/opt/homebrew/bin /usr/local/bin)
for path in "${COMMON_PATHS[@]}"; do
if [ -d "$path" ]; then
echo "$path" >> "$GITHUB_PATH"
export PATH="$path:$PATH"
fi
done
if command -v git-lfs >/dev/null 2>&1; then
git-lfs version
exit 0
fi
brew install git-lfs
git-lfs version
- name: Checkout repository
uses: actions/checkout@v6
with:
persist-credentials: false
lfs: false
- name: Setup Bazel
uses: ./.github/actions/setup-bazel
- name: Run Shardok sanitizer tests
run: bazel test --config=${{ matrix.config }} --build_event_json_file=${{ matrix.config }}.json //src/test/cpp/net/eagle0/shardok/...
- name: Summarize Bazel build metrics
if: always()
run: python3 ci/github_actions/summarize_bazel_bep.py ${{ matrix.config }}.json
- name: Archive sanitizer test results
if: always()
uses: actions/upload-artifact@v7
with:
name: shardok-${{ matrix.config }}.json
path: ${{ matrix.config }}.json
retention-days: 3
-5
View File
@@ -11,11 +11,6 @@
**NEVER kill Unity without asking the user first.** The user might be actively using the Unity Editor. Do not kill,
force-quit, terminate, or otherwise stop Unity processes unless the user explicitly approves that specific action.
**NEVER change Unity's default/open scene as part of running checks.** Unity batchmode or editor validation may write
scene-selection churn such as `ProjectSettings/EditorBuildSettings.asset`, `ProjectSettings/SceneTemplateSettings.json`,
or scene files simply because a different scene was open or loaded. Treat those as unintended local environment changes:
do not stage them, and restore them before committing unless the user explicitly asked to change scenes/build settings.
## CRITICAL GIT RULES (NEVER VIOLATE)
**NEVER use `git -C`.** Just run `git` directly from the cwd — it finds the repo via `.git` discovery. Do not `cd` to the repo root either (see the no-`cd` bash rule above).
+1 -1
View File
@@ -71,7 +71,7 @@ LLM settings can be changed at runtime via the admin console:
1. Navigate to Admin Console → Settings
2. Change `LlmProvider` to select vendor (gemini, openai, claude)
3. Change the corresponding model name setting:
- `GeminiModelName` (default: gemini-3.1-flash-lite)
- `GeminiModelName` (default: gemini-3.1-flash-lite-preview)
- `OpenAiModelName` (default: gpt-4.1-mini)
- `ClaudeModelName` (default: claude-3-5-haiku-20241022)
-29
View File
@@ -1,29 +0,0 @@
#!/bin/bash
# Runs the curated Shardok clang-tidy gate used by CI.
#
# This intentionally checks representative files instead of the whole C++ tree.
# Keep this list low-noise; expand it as cleanup PRs make more areas tidy-clean.
set -euo pipefail
repo_root="$(git rev-parse --show-toplevel)"
source "$repo_root/scripts/shardok_cpp_config.sh"
files=(
"src/main/cpp/net/eagle0/shardok/library/ActionCost.hpp"
"src/main/cpp/net/eagle0/shardok/library/CombatDamage.hpp"
)
compiler_args=(
"-I$repo_root"
"$SHARDOK_CXX_STANDARD_ARG"
)
if command -v xcrun >/dev/null 2>&1; then
sdk_path="$(xcrun --show-sdk-path)"
compiler_args+=("-isysroot" "$sdk_path")
fi
"$repo_root/scripts/run-clang-tidy.sh" --verify-config
"$repo_root/scripts/run-clang-tidy.sh" --quiet --warnings-as-errors="*" "${files[@]}" -- "${compiler_args[@]}"
+1 -2
View File
@@ -10,14 +10,13 @@ set -e
export PATH="/opt/homebrew/bin:/usr/local/bin:$PATH"
repo_root="$(git rev-parse --show-toplevel)"
source "$repo_root/scripts/shardok_cpp_config.sh"
if [ "$#" -eq 0 ]; then
echo "Usage: scripts/run-clang-tidy.sh [clang-tidy args] <files> [-- <compiler args>]"
echo ""
echo "Examples:"
echo " scripts/run-clang-tidy.sh --verify-config"
echo " scripts/run-clang-tidy.sh src/main/cpp/net/eagle0/shardok/library/CombatDamage.hpp -- -I$repo_root $SHARDOK_CXX_STANDARD_ARG"
echo " scripts/run-clang-tidy.sh src/main/cpp/net/eagle0/shardok/library/CombatDamage.hpp -- -I$repo_root -std=c++23"
exit 2
fi
-5
View File
@@ -1,5 +0,0 @@
#!/bin/bash
# Shared C++ settings for shell scripts that invoke Shardok tooling outside Bazel.
SHARDOK_CXX_STANDARD="c++23"
SHARDOK_CXX_STANDARD_ARG="-std=${SHARDOK_CXX_STANDARD}"
@@ -28,7 +28,7 @@ static inline auto HashBuffer(const uint8_t* data, size_t size) -> uint64_t {
// Process 8 bytes at a time
while (data + 8 <= end) {
uint64_t word = 0;
uint64_t word;
// Use memcpy to avoid alignment issues and let compiler optimize
__builtin_memcpy(&word, data, sizeof(word));
hash ^= word;
@@ -9,7 +9,6 @@
#include <bit>
#include <cstdint>
#include <cstdlib>
#include <iterator>
#define ITERABLE_BITSET_INDEX_CHECKS false
@@ -105,11 +104,9 @@ public:
class Iter {
public:
using iterator_category = std::forward_iterator_tag;
using difference_type = std::ptrdiff_t;
using value_type = size_t;
using pointer = void;
using reference = size_t;
using pointer = size_t*;
using reference = size_t&;
private:
size_t storeIndex;
@@ -145,20 +142,13 @@ public:
auto operator!=(const Iter& rhs) const -> bool {
return storeIndex != rhs.storeIndex || bitIndex != rhs.bitIndex;
}
auto operator++() -> Iter& {
void operator++() {
bitIndex++;
if (bitIndex >= STORE_BITS) {
storeIndex++;
bitIndex = 0;
}
ToNext();
return *this;
}
auto operator++(int) -> Iter {
Iter previous = *this;
++(*this);
return previous;
}
auto operator*() const -> size_t { return (storeIndex << BIT_SHIFT) + bitIndex; }
@@ -8,9 +8,7 @@
#include "RandomGenerator.hpp"
#include <algorithm>
#include <ctime>
#include <stdexcept>
constexpr double kOpenEndedHighThreshold = 95.0;
constexpr double kOpenEndedLowThreshold = 5.0;
@@ -69,8 +67,7 @@ auto RandomGenerator::ReverseOpenEndedPercentile() -> double {
}
auto RandomGenerator::IntBetween(const int min, const int max) -> int {
if (min >= max) { throw std::invalid_argument("random integer range must be non-empty"); }
return std::min(int(DoubleZeroToOne() * (max - min)) + min, max - 1);
return int(DoubleZeroToOne() * (max - min)) + min;
}
auto RandomGenerator::IntBelow(const int max) -> int { return IntBetween(0, max); }
@@ -97,7 +94,6 @@ StdLibraryGenerator::StdLibraryGenerator(const std::mt19937_64::result_type seed
}
auto StdLibraryGenerator::IntBetween(const int min, const int max) -> int {
if (min >= max) { throw std::invalid_argument("random integer range must be non-empty"); }
std::uniform_int_distribution<int> unifInt(min, max - 1);
return unifInt(engine);
}
@@ -12,7 +12,6 @@
#include <cstddef>
#include <memory>
#include <random>
#include <stdexcept>
#include <vector>
class RandomGenerator;
@@ -42,7 +41,6 @@ public:
template<class T>
auto RandomElement(const std::vector<T>& vec) -> T {
if (vec.empty()) { throw std::invalid_argument("cannot choose from an empty vector"); }
return vec.at(static_cast<std::size_t>(IntBelow(static_cast<int>(vec.size()))));
}
@@ -9,9 +9,7 @@
#ifndef EAGLE0_COMMON_SEQUENCE_RANDOM_GENERATOR_HPP
#define EAGLE0_COMMON_SEQUENCE_RANDOM_GENERATOR_HPP
#include <cmath>
#include <memory>
#include <stdexcept>
#include <utility>
#include <vector>
@@ -31,24 +29,14 @@ private:
size_t position = 0;
auto DoubleZeroToOne() -> double override {
if (position >= sequence.size()) { position = 0; }
const double nextVal = sequence.at(position);
position++;
if (position >= sequence.size()) { position = 0; }
return nextVal;
}
public:
explicit SequenceRandomGenerator(std::vector<double> s) : sequence(std::move(s)) {
if (sequence.empty()) {
throw std::invalid_argument("sequence random generator requires at least one value");
}
for (const double value : sequence) {
if (!std::isfinite(value) || value < 0.0 || value > 1.0) {
throw std::invalid_argument(
"sequence random generator values must be between 0 and 1");
}
}
}
explicit SequenceRandomGenerator(std::vector<double> s) : sequence(std::move(s)) {}
static auto WithSequence(const std::vector<double>& s)
-> std::shared_ptr<SequenceRandomGenerator> {
return std::make_shared<SequenceRandomGenerator>(s);
@@ -9,7 +9,6 @@ namespace shardok {
using Coords = net::eagle0::shardok::storage::fb::Coords;
constexpr double kDefaultMorale = 50.0;
constexpr float kExplicitMoraleSentinel = -1.0f;
auto ConvertBattalion(const net::eagle0::common::CommonBattalion &battalion) -> Battalion {
Battalion shardokBattalion{};
@@ -18,9 +17,7 @@ auto ConvertBattalion(const net::eagle0::common::CommonBattalion &battalion) ->
shardokBattalion.mutate_size(battalion.size());
shardokBattalion.mutate_type(
static_cast<net::eagle0::shardok::storage::fb::BattalionTypeId>(battalion.type()));
shardokBattalion.mutate_morale(
static_cast<float>(battalion.has_morale() ? battalion.morale() : kDefaultMorale));
if (battalion.has_morale()) { shardokBattalion.mutate_base_morale(kExplicitMoraleSentinel); }
shardokBattalion.mutate_morale(kDefaultMorale);
shardokBattalion.mutate_armament(static_cast<float>(battalion.armament()));
shardokBattalion.mutate_training(static_cast<float>(battalion.training()));
@@ -128,4 +125,4 @@ auto ConvertUnit(
return shardokUnit;
}
} // namespace shardok
} // namespace shardok
+58 -89
View File
@@ -9,24 +9,18 @@
#ifndef EAGLE0_COMMON_BYTE_VECTOR_HPP
#define EAGLE0_COMMON_BYTE_VECTOR_HPP
#include <charconv>
#include <cstdint>
#include <cstring>
#include <fstream>
#include <initializer_list>
#include <sstream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
using std::string;
using std::vector;
class byte_vector {
private:
std::vector<uint8_t> bytes_;
class byte_vector : public vector<uint8_t> {
public:
class HexException : public std::exception {
const std::string description;
@@ -41,78 +35,60 @@ public:
};
private:
static auto HexCharsToByte(const std::string_view digits) -> uint8_t {
unsigned int parsedByte = 0;
const auto [ptr, ec] =
std::from_chars(digits.data(), digits.data() + digits.size(), parsedByte, 16);
if (ec != std::errc() || ptr != digits.data() + digits.size()) {
throw HexException(ptr == digits.data() + digits.size() ? digits.back() : *ptr);
static auto HexNibbleToValue(const char nibble) -> uint8_t {
if (nibble >= '0' && nibble <= '9') {
return uint8_t(nibble - '0');
} else if (nibble >= 'A' && nibble <= 'F') {
return uint8_t(nibble - 'A' + 10);
} else if (nibble >= 'a' && nibble <= 'f') {
return uint8_t(nibble - 'a' + 10);
}
return static_cast<uint8_t>(parsedByte);
throw HexException(nibble);
}
static auto HexCharsToByte(std::istringstream& str) -> uint8_t {
uint8_t b = 0;
char c = 0;
str >> c;
b |= (HexNibbleToValue(c) << 4u);
str >> c;
b |= HexNibbleToValue(c);
return b;
}
public:
byte_vector() = default;
byte_vector(const std::initializer_list<uint8_t> list) : bytes_(list) {}
byte_vector(const std::initializer_list<uint8_t> list) : vector<uint8_t>(list) {}
template<class InputIt>
byte_vector(InputIt begin, InputIt end) : bytes_(begin, end) {}
byte_vector(InputIt begin, InputIt end) : vector<uint8_t>(begin, end) {}
byte_vector(const byte_vector& rhs) = default;
byte_vector(byte_vector&& rhs) noexcept = default;
explicit byte_vector(const std::string& s) : bytes_(s.begin(), s.end()) {}
explicit byte_vector(std::vector<uint8_t> bytes) : bytes_(std::move(bytes)) {}
explicit byte_vector(const size_t size) : bytes_(size) {}
explicit byte_vector(const void* data, const size_t size) {
auto* bytes = static_cast<const uint8_t*>(data);
bytes_.assign(bytes, bytes + size);
explicit byte_vector(const std::string& s) : byte_vector(s.begin(), s.end()) {}
explicit byte_vector(const size_t size) : vector<uint8_t>(size) {}
explicit byte_vector(void* data, const size_t size) : vector<uint8_t>(size) {
this->assign((uint8_t*)data, (uint8_t*)data + size);
}
auto operator=(const byte_vector& rhs) -> byte_vector& = default;
auto operator=(byte_vector&& rhs) noexcept -> byte_vector& = default;
[[nodiscard]] auto operator==(const std::vector<uint8_t>& vec) const -> bool {
return bytes_ == vec;
auto operator==(const vector<uint8_t>& vec) -> bool {
if (this->size() != vec.size()) return false;
for (size_t i = 0; i < size(); i++) {
if ((*this)[i] != vec[i]) return false;
}
return true;
}
[[nodiscard]] auto operator==(const byte_vector& vec) const -> bool {
return bytes_ == vec.bytes_;
}
[[nodiscard]] auto data() -> uint8_t* { return bytes_.data(); }
[[nodiscard]] auto data() const -> const uint8_t* { return bytes_.data(); }
[[nodiscard]] auto size() const -> size_t { return bytes_.size(); }
[[nodiscard]] auto empty() const -> bool { return bytes_.empty(); }
void reserve(const size_t count) { bytes_.reserve(count); }
void resize(const size_t count) { bytes_.resize(count); }
void swap(byte_vector& other) noexcept { bytes_.swap(other.bytes_); }
[[nodiscard]] auto begin() -> std::vector<uint8_t>::iterator { return bytes_.begin(); }
[[nodiscard]] auto begin() const -> std::vector<uint8_t>::const_iterator {
return bytes_.begin();
}
[[nodiscard]] auto end() -> std::vector<uint8_t>::iterator { return bytes_.end(); }
[[nodiscard]] auto end() const -> std::vector<uint8_t>::const_iterator { return bytes_.end(); }
[[nodiscard]] auto cbegin() const -> std::vector<uint8_t>::const_iterator {
return bytes_.cbegin();
}
[[nodiscard]] auto cend() const -> std::vector<uint8_t>::const_iterator {
return bytes_.cend();
}
[[nodiscard]] auto operator[](const size_t index) -> uint8_t& { return bytes_[index]; }
[[nodiscard]] auto operator[](const size_t index) const -> uint8_t { return bytes_[index]; }
auto append(const char* bytes, const size_t length) {
const auto previousSize = size();
resize(previousSize + length);
std::memcpy(data() + previousSize, bytes, length);
const auto previousSize = this->size();
this->resize(previousSize + length);
std::memcpy(this->data() + previousSize, bytes, length);
}
template<class T>
auto append(const T* elts, const size_t count) {
append(reinterpret_cast<const char*>(elts), count * sizeof(T));
append((char*)elts, count * sizeof(T));
}
template<class T>
auto append(const vector<T>& elts) {
auto append(const vector<T> elts) {
append(elts.data(), elts.size());
}
@@ -122,7 +98,7 @@ public:
}
auto operator+=(const uint8_t c) -> byte_vector& {
bytes_.push_back(c);
this->insert(end(), c);
return *this;
}
@@ -135,7 +111,7 @@ public:
template<class Iterable>
auto operator+=(const Iterable& rhs) -> byte_vector& {
bytes_.insert(end(), rhs.cbegin(), rhs.cend());
this->insert(end(), rhs.cbegin(), rhs.cend());
return *this;
}
@@ -143,7 +119,7 @@ public:
if (size() < 8) {
uint64_t total = 0;
for (size_t i = 0; i < size(); i++) {
total <<= 8U;
total <<= 8u;
total += (*this)[i];
}
return total;
@@ -152,9 +128,9 @@ public:
uint64_t firstBytes = 0;
uint64_t lastBytes = 0;
for (unsigned i = 0; i < 8; i++) {
firstBytes <<= 8U;
firstBytes <<= 8u;
firstBytes += (*this)[i];
lastBytes <<= 8U;
lastBytes <<= 8u;
lastBytes += (*this)[i];
}
@@ -165,8 +141,8 @@ public:
std::ifstream inputFileStream(path, std::ios::binary | std::ios::ate);
const std::streamsize size = inputFileStream.tellg();
inputFileStream.seekg(0, std::ios::beg);
this->resize(static_cast<size_t>(size));
inputFileStream.read(reinterpret_cast<char*>(this->data()), size);
this->resize((size_t(size)));
inputFileStream.read((char*)this->data(), size);
return *this;
}
@@ -177,41 +153,34 @@ public:
}
const std::streamsize size = inputFileStream.tellg();
inputFileStream.seekg(0, std::ios::beg);
byte_vector serializedGame(static_cast<size_t>(size));
inputFileStream.read(reinterpret_cast<char*>(serializedGame.data()), size);
byte_vector serializedGame((size_t(size)));
inputFileStream.read((char*)serializedGame.data(), size);
return serializedGame;
}
static auto FromHex(const char* hexString) -> byte_vector { return FromHex(string(hexString)); }
static auto FromHex(const string& hexString) -> byte_vector {
std::string_view digits(hexString);
if (digits.starts_with("0x") || digits.starts_with("0X")) {
digits.remove_prefix(2);
} else if (digits.starts_with("x") || digits.starts_with("X")) {
digits.remove_prefix(1);
static auto FromHex(string hexString) -> byte_vector {
if (hexString[0] == '0' && (hexString[1] == 'x' || hexString[1] == 'X')) {
hexString = string(hexString.begin() + 1, hexString.end());
}
if (hexString[0] == 'x' || hexString[0] == 'X') {
hexString = string(hexString.begin() + 1, hexString.end());
}
if (digits.size() % 2 != 0) { throw HexException(digits.empty() ? '\0' : digits.back()); }
byte_vector vec;
vec.reserve(digits.size() / 2);
const size_t len = hexString.size();
vec.reserve(len / 2);
std::istringstream hexStream(hexString);
for (size_t index = 0; index < digits.size(); index += 2) {
vec += HexCharsToByte(digits.substr(index, 2));
}
while (size_t(hexStream.tellg()) < len) { vec += HexCharsToByte(hexStream); }
return vec;
}
explicit operator std::string() const { return std::string(begin(), end()); }
};
inline auto operator==(const std::vector<uint8_t>& lhs, const byte_vector& rhs) -> bool {
return rhs == lhs;
}
inline auto operator<<(std::ostream& ostr, const byte_vector& vec) -> std::ostream& {
ostr.write(reinterpret_cast<const char*>(vec.data()), static_cast<std::streamsize>(vec.size()));
inline auto operator<<(std::ostream& ostr, byte_vector vec) -> std::ostream& {
ostr.write((char*)vec.data(), (std::streamsize)vec.size());
return ostr;
}
@@ -209,8 +209,8 @@ auto AbstractMCTSAI::BuildMCTSTree(
}));
}
// Wait for all threads to complete and propagate worker exceptions.
for (auto& future : futures) { future.get(); }
// Wait for all threads to complete
for (auto& future : futures) { future.wait(); }
} else {
// Single-threaded MCTS
while (std::chrono::steady_clock::now() < deadline) {
@@ -37,7 +37,7 @@ int main(const int argc, char** argv) {
void ModifyMap(HexMapProto& map) {
const int terrainCount = map.terrain_size();
for (int i = 0; i < terrainCount; ++i) {
for (int i = 0; i < terrainCount; i++) {
const auto existingTerrainType = map.terrain(i).type();
const auto newTerrain =
static_cast<net::eagle0::shardok::common::Terrain_Type>(existingTerrainType + 2);
@@ -37,7 +37,7 @@ auto CalculateMap(
.name = mapName,
.positionsRequiringCrossing = {}};
for (std::size_t i = 0; i < hexMap->attacker_starting_positions()->size(); ++i) {
for (std::size_t i = 0; i < hexMap->attacker_starting_positions()->size(); i++) {
const auto* positionList = hexMap->attacker_starting_positions()->Get(i);
const auto* positions = positionList->positions();
if (positions->empty()) continue;
@@ -18,7 +18,7 @@ struct alignas(64) OneMapInfo {
std::map<int, int> positionsRequiringCrossing;
};
[[nodiscard]] auto CalculateMap(
auto CalculateMap(
const std::string& mapName,
const std::shared_ptr<shardok::ActionPointDistancesCache>& apdCache,
const shardok::BattalionTypeSPtr& battalionType) -> OneMapInfo;
@@ -54,7 +54,7 @@ void runBattle(const std::vector<shardok::Unit>& units) {
const auto p1UnitCount = randInt(1, static_cast<int>(maxP1UnitCount));
std::vector<shardok::Unit> p1Units{};
p1Units.reserve(p1UnitCount);
for (int i = 0; i < p1UnitCount; ++i) {
for (int i = 0; i < p1UnitCount; i++) {
auto unit = units[i];
unit.mutate_player_id(0);
p1Units.push_back(std::move(unit));
@@ -64,7 +64,7 @@ void runBattle(const std::vector<shardok::Unit>& units) {
const auto p2UnitCount = randInt(1, static_cast<int>(maxP2UnitCount));
std::vector<shardok::Unit> p2Units{};
p2Units.reserve(p2UnitCount);
for (int i = p1UnitCount; i < p1UnitCount + p2UnitCount; ++i) {
for (int i = p1UnitCount; i < p1UnitCount + p2UnitCount; i++) {
auto unit = units[i];
unit.mutate_player_id(1);
p2Units.push_back(std::move(unit));
@@ -158,7 +158,7 @@ auto main(int /*argc*/, char** argv) -> int {
std::array<std::thread, THREAD_COUNT> threads;
for (int i = 0; i < THREAD_COUNT; ++i) {
for (int i = 0; i < THREAD_COUNT; i++) {
threads[i] = std::thread(runBattlesThread, randomUnits);
}
@@ -25,44 +25,25 @@ DIST_T NormalizedCostWhenBraving(const DIST_T cost) {
struct TargetAndDistance {
Coords target;
size_t targetIndex;
CoordsSet attackLocations;
double targetPower;
DIST_T distance;
TargetAndDistance(
const Coords& t,
const size_t ti,
const CoordsSet& al,
const double tp,
const DIST_T d)
TargetAndDistance(const Coords& t, const CoordsSet& al, const double tp, const DIST_T d)
: target(t),
targetIndex(ti),
attackLocations(al),
targetPower(tp),
distance(d) {}
};
auto CoordsIndex(const Coords& coords, const int columnCount) {
return coords.row() * columnCount + coords.column();
}
auto CoordsFromIndex(const size_t index, const int columnCount) -> Coords {
return Coords(
static_cast<int8_t>(index / static_cast<size_t>(columnCount)),
static_cast<int8_t>(index % static_cast<size_t>(columnCount)));
}
auto MinDistance(
const Coords& start,
const CoordsSet& destinations,
const ActionPointDistances* apd) -> DIST_T {
DIST_T minDistance = ActionPointDistances::IMPOSSIBLE;
const int startIndex = CoordsIndex(start, destinations.ColumnCount());
for (const auto destIndex : destinations.indexIterator()) {
if (const DIST_T distance = apd->Distance(startIndex, static_cast<int>(destIndex));
distance < minDistance) {
for (const Coords& dest : destinations) {
if (const DIST_T distance = apd->Distance(start, dest); distance < minDistance) {
minDistance = distance;
}
}
@@ -132,6 +113,10 @@ auto EffectiveDistance(
auto Power(const Unit* unit) -> double { return unit->battalion().size(); }
auto CoordsIndex(const Coords& coords, const int columnCount) {
return coords.row() * columnCount + coords.column();
}
// Chooses a list of targets in priority order for each unit.
auto GenerateTargetPriorities(
const vector<const Unit*>& occupants,
@@ -178,10 +163,10 @@ auto GenerateTargetPriorities(
bravingApd = apdCache->GetRaw(map, mapId, battType, true, braveWaterCost);
}
for (const auto targetIndex : targets.indexIterator()) {
const auto& occupant = occupants[targetIndex];
for (const Coords& targetLocation : targets) {
const auto coordsIndex = CoordsIndex(targetLocation, cc);
const auto& occupant = occupants[coordsIndex];
const Coords targetLocation = CoordsFromIndex(targetIndex, cc);
const auto& attackLocations = alCache->CachedLocations(targetLocation, isLateGame);
if (occupant && occupant->player_id() != attackerId) {
@@ -194,14 +179,12 @@ auto GenerateTargetPriorities(
targetsWithDistance.emplace_back(
targetLocation,
targetIndex,
attackLocsForUnit,
occupantPower,
distance);
} else {
targetsWithDistance.emplace_back(
targetLocation,
targetIndex,
attackLocations.LocationsWithEnemyInRange(unit),
occupantPower,
ActionPointDistances::IMPOSSIBLE);
@@ -212,11 +195,13 @@ auto GenerateTargetPriorities(
// Sort by distance
std::ranges::sort(
targetsWithDistance,
[&powerAttackingEachTarget](
const TargetAndDistance& left,
const TargetAndDistance& right) {
const double powerAttackingLeft = powerAttackingEachTarget[left.targetIndex];
const double powerAttackingRight = powerAttackingEachTarget[right.targetIndex];
[&powerAttackingEachTarget,
cc](const TargetAndDistance& left, const TargetAndDistance& right) {
const auto leftIndex = CoordsIndex(left.target, cc);
const auto rightIndex = CoordsIndex(right.target, cc);
const double powerAttackingLeft = powerAttackingEachTarget[leftIndex];
const double powerAttackingRight = powerAttackingEachTarget[rightIndex];
const bool leftAlreadyOverwhelmed =
powerAttackingLeft >= kOverpowerRatio * left.targetPower;
@@ -230,7 +215,8 @@ auto GenerateTargetPriorities(
});
if (!targetsWithDistance.empty()) {
powerAttackingEachTarget[targetsWithDistance.front().targetIndex] += Power(unit);
powerAttackingEachTarget[CoordsIndex(targetsWithDistance.front().target, cc)] +=
Power(unit);
}
tpl.priorityOrder.reserve(targetsWithDistance.size());
@@ -27,7 +27,7 @@ struct TargetAndAttackLocations {
Coords target;
CoordsSet attackLocations;
[[nodiscard]] auto operator==(const TargetAndAttackLocations& rhs) const -> bool = default;
auto operator==(const TargetAndAttackLocations& rhs) const -> bool = default;
};
struct TargetPriorityList {
@@ -39,7 +39,7 @@ struct TargetPriorityList {
priorityOrder(po) {}
};
[[nodiscard]] auto EffectiveDistance(
auto EffectiveDistance(
const Unit* unit,
const HexMap* map,
const AttackLocations& attackLocations,
@@ -47,7 +47,7 @@ struct TargetPriorityList {
const BattalionTypeGetter& battalionTypeGetter,
ActionPoints braveWaterCost) -> DIST_T;
[[nodiscard]] auto EffectiveDistance(
auto EffectiveDistance(
const Unit* unit,
const HexMap* map,
const CoordsSet& locations,
@@ -55,14 +55,14 @@ struct TargetPriorityList {
const BattalionTypeGetter& battalionTypeGetter,
ActionPoints braveWaterCost) -> DIST_T;
[[nodiscard]] auto EffectiveDistance(
auto EffectiveDistance(
const Unit* unit,
const ActionPointDistances* notBravingApd,
const ActionPointDistances* bravingApd,
const CoordsSet& locations) -> DIST_T;
// Chooses a list of targets in priority order for each unit.
[[nodiscard]] auto GenerateTargetPriorities(
auto GenerateTargetPriorities(
const std::vector<const Unit*>& occupants,
const HexMap* map,
const CoordsSet& targets,
@@ -53,8 +53,8 @@ AttackLocationsCache::AttackLocationsCache(const HexMap *hexMap, const SettingsG
auto emptySet = CoordsSet(columnCount, rowCount);
for (MapIndex r = 0; r < hexMap->row_count(); ++r) {
for (MapIndex c = 0; c < hexMap->column_count(); ++c) {
for (MapIndex r = 0; r < hexMap->row_count(); r++) {
for (MapIndex c = 0; c < hexMap->column_count(); c++) {
auto location = Coords(r, c);
const auto terrain = GetTerrain(hexMap, location);
@@ -114,7 +114,8 @@ auto AttackLocationsCache::CachedLocations(const CoordsSet &targets, const bool
-> AttackLocations {
AttackLocations al(rowCount, columnCount);
for (const auto index : targets.indexIterator()) {
for (const auto &target : targets) {
const int index = target.row() * columnCount + target.column();
if (lateGame) {
al += lateGameLocations[index];
} else {
@@ -136,4 +137,4 @@ auto AttackLocationsCache::CachedLocations(const vector<const Unit *> &enemies,
return CachedLocations(targets, lateGame);
}
} // namespace shardok
} // namespace shardok
@@ -11,8 +11,6 @@
#include <iomanip>
#include <iostream>
#include <limits>
#include <sstream>
#include <stdexcept>
#include "AICommandFilter.hpp"
#include "TranspositionTable.hpp"
@@ -23,49 +21,16 @@
namespace shardok {
// No need to forward declare internal functions - use the public interface instead
// Helper constants and static variables
static const std::vector<double> kAverageSequence = {0.5};
static const auto kAverageGenerator = std::make_shared<SequenceRandomGenerator>(kAverageSequence);
constexpr bool kMultithread = true;
constexpr bool kLogging = false;
[[nodiscard]] static auto AverageGenerator() -> std::shared_ptr<SequenceRandomGenerator> {
return std::make_shared<SequenceRandomGenerator>(std::vector{0.5});
}
[[nodiscard]] static auto DescribeCommandForLog(const CommandSPtr& command) -> std::string {
if (!command) { return "<null command>"; }
std::ostringstream out;
out << "type=" << command->GetCommandType()
<< " player=" << static_cast<int>(command->GetPlayerId())
<< " actor=" << command->GetActorUnitId() << " target=("
<< static_cast<int>(command->GetTargetRow()) << ','
<< static_cast<int>(command->GetTargetColumn()) << ')';
if (command->HasOdds()) { out << " odds_percentile=" << command->GetOddsPercentile(); }
return out.str();
}
[[nodiscard]] static auto DescribeCommandAt(
const CommandListSPtr& commands,
const size_t commandIndex) -> std::string {
if (!commands) { return "command=<null command list>"; }
if (commandIndex >= commands->size()) {
std::ostringstream out;
out << "command=<index " << commandIndex << " out of " << commands->size() << ">";
return out.str();
}
std::ostringstream out;
out << "command={" << DescribeCommandForLog(commands->at(commandIndex)) << '}';
return out.str();
}
[[nodiscard]] static auto WithExceptionContext(
const std::string& context,
const std::exception& exception) -> std::runtime_error {
return std::runtime_error(context + ": " + exception.what());
}
// Helper function to determine if a command type is deterministic
static auto IsDeterministic(const CommandType type) -> bool {
switch (type) {
case net::eagle0::shardok::common::MOVE_COMMAND:
@@ -78,11 +43,13 @@ static auto IsDeterministic(const CommandType type) -> bool {
case net::eagle0::shardok::common::PLACE_HIDDEN_UNIT_COMMAND:
case net::eagle0::shardok::common::UNIT_STOP_COMMAND:
case net::eagle0::shardok::common::UNIT_REST_COMMAND:
case net::eagle0::shardok::common::FLEE_COMMAND:
case net::eagle0::shardok::common::REINFORCE_COMMAND:
case net::eagle0::shardok::common::RETREAT_COMMAND:
case net::eagle0::shardok::common::END_PLAYER_SETUP_COMMAND:
case net::eagle0::shardok::common::HIDE_COMMAND:
case net::eagle0::shardok::common::FORTIFY_COMMAND:
case net::eagle0::shardok::common::BECOME_OUTLAW_COMMAND:
case net::eagle0::shardok::common::HOLY_WAVE_COMMAND:
case net::eagle0::shardok::common::EVACUATE_PRISONERS_COMMAND:
case net::eagle0::shardok::common::REPAIR_COMMAND: return true;
@@ -96,14 +63,7 @@ static auto RandomnessSampleForRepeat(const int repeatIteration, const int maxRe
return static_cast<double>(repeatIteration) / static_cast<double>(maxRepeatCount - 1);
}
static auto SuccessSampleForOdds(const double successChance) -> double {
return successChance / 2.0;
}
static auto FailureSampleForOdds(const double successChance) -> double {
return successChance + ((1.0 - successChance) / 2.0);
}
// Helper function to sort commands by score
static auto CommandSorter(
const AICommandEvaluator::IndexAndScore& l,
const AICommandEvaluator::IndexAndScore& r) -> bool {
@@ -123,7 +83,7 @@ AICommandEvaluator::AICommandEvaluator(
BattalionTypeGetter battalionTypeGetter)
: scorer_(scorer),
apdCache_(apdCache),
battalionTypeGetter_(std::move(battalionTypeGetter)) {}
battalionTypeGetter_(std::move(battalionTypeGetter)) {} // Move the function object
auto AICommandEvaluator::PerformLookahead(
const PlayerId pid,
@@ -178,34 +138,17 @@ auto AICommandEvaluator::PerformLookahead(
std::launch::deferred,
[bestCommandFuture = std::move(bestCommandFuture),
innerEngine,
nextCommands,
pid,
nextUtility,
remainingLookahead]() mutable -> EvaluationResult {
IndexAndScore bestCommand;
try {
bestCommand = bestCommandFuture.get();
} catch (const std::exception& e) {
std::ostringstream context;
context << "AI PerformLookahead failed while resolving best command"
<< " player=" << static_cast<int>(pid)
<< " remaining_lookahead=" << remainingLookahead
<< " next_command_count=" << nextCommands->size();
throw WithExceptionContext(context.str(), e);
}
const auto bestCommand = bestCommandFuture.get();
if (!bestCommand.completed) {
return EvaluationResult{.score = nextUtility, .completed = false};
}
if (bestCommand.index >= nextCommands->size()) {
std::cerr << "AI lookahead produced command index " << bestCommand.index
<< " with only " << nextCommands->size()
<< " available commands for player " << static_cast<int>(pid)
<< " at remaining lookahead " << remainingLookahead << "\n";
return EvaluationResult{.score = nextUtility, .completed = false};
}
ScoreValue resultScore;
if (const auto& nextCommand = nextCommands->at(bestCommand.index);
if (auto& nextCommand = innerEngine->GetAvailableCommandsForAIPlayer(pid)->at(
bestCommand.index);
nextCommand->GetCommandType() !=
net::eagle0::shardok::common::END_TURN_COMMAND) {
resultScore = bestCommand.immediateScore;
@@ -256,36 +199,14 @@ auto AICommandEvaluator::EvaluateWithRandomness(
return returnValue;
}
const auto guessedCommands = guessedEngine.GetAvailableCommandsForAIPlayer(pid);
auto innerEngine = std::make_shared<ShardokEngine>(guessedEngine, false);
try {
innerEngine->PostCommand(pid, commandIndex, randomGenerator);
} catch (const std::exception& e) {
std::ostringstream context;
context << "AI EvaluateWithRandomness failed while posting simulated command"
<< " player=" << static_cast<int>(pid) << " command_index=" << commandIndex
<< " guessed_command_count=" << guessedCommands->size()
<< " remaining_lookahead=" << remainingLookahead << ' '
<< DescribeCommandAt(guessedCommands, commandIndex);
throw WithExceptionContext(context.str(), e);
}
innerEngine->PostCommand(pid, commandIndex, randomGenerator);
ScoreValue innerUtility;
try {
innerUtility = scorer_.GuessedStateScore(
isDefender,
innerEngine->GetCurrentGameState(),
attackerStrategy,
allCastleCoords);
} catch (const std::exception& e) {
std::ostringstream context;
context << "AI EvaluateWithRandomness failed while scoring simulated state"
<< " player=" << static_cast<int>(pid) << " command_index=" << commandIndex
<< " guessed_command_count=" << guessedCommands->size()
<< " remaining_lookahead=" << remainingLookahead << ' '
<< DescribeCommandAt(guessedCommands, commandIndex);
throw WithExceptionContext(context.str(), e);
}
auto innerUtility = scorer_.GuessedStateScore(
isDefender,
innerEngine->GetCurrentGameState(),
attackerStrategy,
allCastleCoords);
returnValue.immediateScore = innerUtility;
returnValue.completed = true;
@@ -300,33 +221,22 @@ auto AICommandEvaluator::EvaluateWithRandomness(
isDefender,
remainingLookahead,
maxRepeatCount,
commandIndex,
innerEngine,
attackerStrategy,
innerUtility,
guessedCommands,
allCastleCoords,
&allCastleCoords,
deadline]() -> EvaluationResult {
try {
auto lookaheadFuture = PerformLookahead(
pid,
isDefender,
remainingLookahead,
maxRepeatCount,
innerEngine,
innerUtility,
attackerStrategy,
allCastleCoords,
deadline);
return lookaheadFuture.get();
} catch (const std::exception& e) {
std::ostringstream context;
context << "AI EvaluateWithRandomness failed during recursive lookahead"
<< " player=" << static_cast<int>(pid) << " command_index=" << commandIndex
<< " remaining_lookahead=" << remainingLookahead << ' '
<< DescribeCommandAt(guessedCommands, commandIndex);
throw WithExceptionContext(context.str(), e);
}
auto lookaheadFuture = PerformLookahead(
pid,
isDefender,
remainingLookahead,
maxRepeatCount,
innerEngine,
innerUtility,
attackerStrategy,
allCastleCoords,
deadline);
return lookaheadFuture.get();
};
if constexpr (kMultithread) {
@@ -426,21 +336,9 @@ auto AICommandEvaluator::FindBestCommand(
std::vector<CommandEvaluation> commandEvaluations(commandCount);
for (uint32_t index = 0; index < commandCount; ++index) {
for (uint32_t index = 0; index < commandCount; index++) {
const auto originalIndex = filteredIndices[index];
const CommandSPtr guessedDescriptor = [&] {
try {
return guessedDescriptors->at(originalIndex);
} catch (const std::exception& e) {
std::ostringstream context;
context << "AI FindBestCommand failed while reading filtered command"
<< " player=" << static_cast<int>(pid) << " filtered_index=" << index
<< " original_index=" << originalIndex
<< " guessed_command_count=" << guessedDescriptors->size()
<< " filtered_command_count=" << filteredIndices.size();
throw WithExceptionContext(context.str(), e);
}
}();
const auto& guessedDescriptor = guessedDescriptors->at(originalIndex);
const auto guessedCommandType = guessedDescriptor->GetCommandType();
commandEvaluations[index].index = originalIndex;
@@ -458,7 +356,7 @@ auto AICommandEvaluator::FindBestCommand(
originalIndex,
remainingLookahead,
maxRepeatCount,
AverageGenerator(),
kAverageGenerator,
guessedEngine,
attackerStrategy,
allCastleCoords,
@@ -472,7 +370,7 @@ auto AICommandEvaluator::FindBestCommand(
const auto successChancePercentile = guessedDescriptor->GetOddsPercentile();
const double successChance = static_cast<double>(successChancePercentile) / 100.0;
// Success attempt uses the midpoint of the successful percentile range.
// Success attempt uses 1.0 - (successChance / 2) as the roll
auto successEvaluation = EvaluateWithRandomness(
pid,
isDefender,
@@ -480,13 +378,13 @@ auto AICommandEvaluator::FindBestCommand(
remainingLookahead,
maxRepeatCount,
std::make_shared<SequenceRandomGenerator>(
std::vector{SuccessSampleForOdds(successChance)}),
std::vector{1.0 - successChance / 2.0}),
guessedEngine,
attackerStrategy,
allCastleCoords,
deadline);
// Failure attempt uses the midpoint of the failing percentile range.
// Failure attempt uses the average of (1 - successChance) and 0 as the roll
auto failureEvaluation = EvaluateWithRandomness(
pid,
isDefender,
@@ -494,7 +392,7 @@ auto AICommandEvaluator::FindBestCommand(
remainingLookahead,
maxRepeatCount,
std::make_shared<SequenceRandomGenerator>(
std::vector{FailureSampleForOdds(successChance)}),
std::vector{(1.0 - successChance) / 2.0}),
guessedEngine,
attackerStrategy,
allCastleCoords,
@@ -525,7 +423,7 @@ auto AICommandEvaluator::FindBestCommand(
ScoreValue sum = 0.0;
const int sampleCount = std::max(1, maxRepeatCount);
commandEvaluations[index].lookaheadFutures.reserve(sampleCount);
for (int repeatIteration = 0; repeatIteration < sampleCount; ++repeatIteration) {
for (int repeatIteration = 0; repeatIteration < sampleCount; repeatIteration++) {
// In each iteration, use a double from [0, 1] as the random roll
auto sequence =
std::vector{RandomnessSampleForRepeat(repeatIteration, sampleCount)};
@@ -562,17 +460,7 @@ auto AICommandEvaluator::FindBestCommand(
ScoreValue totalLookaheadScore = 0.0;
bool completed = eval.immediateCompleted;
for (auto& future : eval.lookaheadFutures) {
EvaluationResult lookahead;
try {
lookahead = future.get();
} catch (const std::exception& e) {
std::ostringstream context;
context << "AI FindBestCommand failed while resolving lookahead future"
<< " command_index=" << eval.index
<< " command_type=" << eval.type
<< " lookahead_future_count=" << eval.lookaheadFutures.size();
throw WithExceptionContext(context.str(), e);
}
const auto lookahead = future.get();
if (!lookahead.completed) { completed = false; }
totalLookaheadScore += lookahead.score;
}
@@ -639,7 +527,7 @@ auto AICommandEvaluator::EvaluateCommand(
commandIndex,
remainingLookahead,
maxRepeatCount,
AverageGenerator(),
kAverageGenerator,
guessedEngine,
attackerStrategy,
allCastleCoords,
@@ -658,8 +546,7 @@ auto AICommandEvaluator::EvaluateCommand(
commandIndex,
remainingLookahead,
maxRepeatCount,
std::make_shared<SequenceRandomGenerator>(
std::vector{SuccessSampleForOdds(successChance)}),
std::make_shared<SequenceRandomGenerator>(std::vector{1.0 - successChance / 2.0}),
guessedEngine,
attackerStrategy,
allCastleCoords,
@@ -672,8 +559,7 @@ auto AICommandEvaluator::EvaluateCommand(
commandIndex,
remainingLookahead,
maxRepeatCount,
std::make_shared<SequenceRandomGenerator>(
std::vector{FailureSampleForOdds(successChance)}),
std::make_shared<SequenceRandomGenerator>(std::vector{(1.0 - successChance) / 2.0}),
guessedEngine,
attackerStrategy,
allCastleCoords,
@@ -701,7 +587,7 @@ auto AICommandEvaluator::EvaluateCommand(
const int sampleCount = std::max(1, maxRepeatCount);
lookaheadFutures.reserve(sampleCount);
for (int repeatIteration = 0; repeatIteration < sampleCount; ++repeatIteration) {
for (int repeatIteration = 0; repeatIteration < sampleCount; repeatIteration++) {
auto sequence = std::vector{RandomnessSampleForRepeat(repeatIteration, sampleCount)};
auto evaluation = EvaluateWithRandomness(
pid,
@@ -78,7 +78,7 @@ public:
private:
const AIScoreCalculator& scorer_;
const APDCache& apdCache_;
BattalionTypeGetter battalionTypeGetter_;
BattalionTypeGetter battalionTypeGetter_; // Store by value
struct ImmediateAndLookaheadScore {
ScoreValue immediateScore{};
@@ -104,21 +104,23 @@ auto DefenderDistanceBuf(
pointCostToDesiredTargetWithBraving);
}
std::ranges::sort(pointCosts, [](const WithoutAndWith &left, const WithoutAndWith &right) {
return left.without == right.without ? left.with < right.with
: left.without < right.without;
});
std::sort(
begin(pointCosts),
end(pointCosts),
[](const WithoutAndWith &left, const WithoutAndWith &right) {
return left.without == right.without ? left.with < right.with
: left.without < right.without;
});
// experiment: add dummy values to the end with very high cost, so there's never an advantage
// to leaving a defender unit alive in a castle.
for (size_t i = attackerUnits.size(); i < 20; ++i) { pointCosts.emplace_back(999, 999); }
for (size_t i = attackerUnits.size(); i < 20; i++) { pointCosts.emplace_back(999, 999); }
double sum = 0.0;
double decr = kPerUnitDebufDecay;
for (const WithoutAndWith &pointCost : pointCosts) {
const int effectiveCost = (pointCost.without == 999)
? static_cast<int>(1.2 * pointCost.with)
: pointCost.without;
const int effectiveCost =
(pointCost.without == 999) ? int(1.2 * pointCost.with) : pointCost.without;
sum += decr / (effectiveCost + 1);
decr *= kPerUnitDebufDecay;
}
@@ -13,7 +13,7 @@
namespace shardok {
[[nodiscard]] auto DefenderDistanceBuf(
auto DefenderDistanceBuf(
const Coords &defenderLocation,
const HexMap *hexMap,
const MapId &mapId,
@@ -12,7 +12,7 @@
namespace shardok {
[[nodiscard]] inline auto CurrentAIExperimentId() -> int {
inline auto CurrentAIExperimentId() -> int {
const char* rawValue = std::getenv("SHARDOK_SCORING_EXPERIMENT_ID");
if (rawValue == nullptr) { return 0; }
@@ -28,9 +28,7 @@ namespace shardok {
return experimentId;
}
[[nodiscard]] inline auto IsAIExperiment(const int id) -> bool {
return CurrentAIExperimentId() == id;
}
inline auto IsAIExperiment(const int id) -> bool { return CurrentAIExperimentId() == id; }
} // namespace shardok
@@ -19,8 +19,6 @@ namespace shardok {
namespace {
constexpr double kCertainCombatWinChance = 0.95;
void WritePercent(std::ostream& output, const double value) {
const auto flags = output.flags();
const auto precision = output.precision();
@@ -156,8 +154,8 @@ auto AIFleeDecisionCalculator::EvaluateFleeVsFight(
const CommandListSPtr& availableCommands,
const CommandList::const_iterator& fleeCommand,
int maxRounds,
int /*minimumFleeOddsThreshold*/,
int /*desperateFleeThreshold*/,
int minimumFleeOddsThreshold,
int desperateFleeThreshold,
bool enableDebugLogging) -> FleeDecision {
// Get flee success odds
const int fleeSuccessChance = (*fleeCommand)->GetOddsPercentile();
@@ -166,31 +164,67 @@ auto AIFleeDecisionCalculator::EvaluateFleeVsFight(
std::cout << "AI FinalRound: Evaluating flee (odds=" << fleeSuccessChance << "%)...\n";
}
const double combatWinChance = EstimateCombatSuccess(playerId, guessedState, maxRounds);
if (combatWinChance < kCertainCombatWinChance) {
// Check if flee odds are good enough to attempt
if (fleeSuccessChance >= minimumFleeOddsThreshold) {
if (enableDebugLogging) {
std::cout << "AI FinalRound: Combat not certain (";
WritePercent(std::cout, combatWinChance * 100);
std::cout << "% < ";
WritePercent(std::cout, kCertainCombatWinChance * 100);
std::cout << "%), choosing flee\n";
std::cout << "AI FinalRound: Good flee odds (" << fleeSuccessChance
<< "% >= " << minimumFleeOddsThreshold << "%), choosing flee\n";
}
return FleeDecision{
true,
GetFleeCommandIndex(fleeCommand, availableCommands),
"Last round combat not certain"};
"Good flee odds"};
}
// Low flee odds - evaluate if fighting might be better
const double combatWinChance = EstimateCombatSuccess(playerId, guessedState, maxRounds);
// If combat situation is hopeless, even bad flee odds are better than certain death
if (combatWinChance <= 0.05 && fleeSuccessChance >= desperateFleeThreshold) {
if (enableDebugLogging) {
std::cout << "AI FinalRound: Combat hopeless (";
WritePercent(std::cout, combatWinChance * 100);
std::cout << "%), desperate flee attempt (" << fleeSuccessChance << "%)\n";
}
return FleeDecision{
true,
GetFleeCommandIndex(fleeCommand, availableCommands),
"Combat hopeless, desperate flee"};
}
// Detailed flee vs fight comparison
const double fleeChance = static_cast<double>(fleeSuccessChance) / 100.0;
// Compare expected outcomes:
// - Flee: fleeChance of survival (not victory, but avoiding loss)
// - Fight: combatWinChance of victory (better than survival)
constexpr double FLEE_VS_COMBAT_MARGIN =
0.8; // Require 80% of combat chance to prefer fighting
const double adjustedCombatThreshold = combatWinChance * FLEE_VS_COMBAT_MARGIN;
if (enableDebugLogging) {
std::cout << "AI FinalRound: Combat effectively certain (";
std::cout << "AI FinalRound: Flee=" << fleeSuccessChance << "%, Combat=";
WritePercent(std::cout, combatWinChance * 100);
std::cout << "%), fighting\n";
std::cout << "%, Threshold=";
WritePercent(std::cout, adjustedCombatThreshold * 100);
std::cout << "% -> ";
}
if (fleeChance > adjustedCombatThreshold) {
if (enableDebugLogging) { std::cout << "FLEE (better odds)\n"; }
return FleeDecision{
true,
GetFleeCommandIndex(fleeCommand, availableCommands),
"Flee has better expected outcome"};
} else {
if (enableDebugLogging) { std::cout << "FIGHT (better expected outcome)\n"; }
// Return 0 to indicate we should use standard command selection
return FleeDecision{
false,
0, // Will be replaced by StandardChooseCommandIndex
"Fighting has better expected outcome"};
}
return FleeDecision{
false,
0, // Will be replaced by StandardChooseCommandIndex
"Combat effectively certain"};
}
auto AIFleeDecisionCalculator::ShouldConsiderFleeing(
@@ -5,34 +5,15 @@
#include "AIMinimumDistanceAndTarget.hpp"
namespace shardok {
namespace {
auto CoordsIndex(const Coords &coords, const int columnCount) -> int {
return coords.row() * columnCount + coords.column();
}
auto CoordsFromIndex(const size_t index, const int columnCount) -> Coords {
return Coords(
static_cast<int8_t>(index / static_cast<size_t>(columnCount)),
static_cast<int8_t>(index % static_cast<size_t>(columnCount)));
}
} // namespace
auto MinimumDistanceAndTarget(
const ActionPointDistances *apd,
const Coords &origin,
const CoordsSet &destinations) -> CoordsAndDistance {
CoordsAndDistance min{Coords(-1, -1), ActionPointDistances::IMPOSSIBLE};
const int columnCount = destinations.ColumnCount();
const int originIndex = CoordsIndex(origin, columnCount);
for (const auto destIndex : destinations.indexIterator()) {
const DIST_T dist = apd->Distance(originIndex, static_cast<int>(destIndex));
for (const auto &dest : destinations) {
const DIST_T dist = apd->Distance(origin, dest);
if (dist == ActionPointDistances::IMPOSSIBLE) continue;
if (dist < min.distance) {
min = CoordsAndDistance{CoordsFromIndex(destIndex, columnCount), dist};
}
if (dist < min.distance) min = CoordsAndDistance{dest, dist};
}
return min;
@@ -44,4 +25,4 @@ auto MinimumDistance(
const CoordsSet &destinations) -> int {
return MinimumDistanceAndTarget(apd, origin, destinations).distance;
}
} // namespace shardok
} // namespace shardok
@@ -18,12 +18,12 @@ struct CoordsAndDistance {
int distance;
};
[[nodiscard]] auto MinimumDistanceAndTarget(
auto MinimumDistanceAndTarget(
const ActionPointDistances *apd,
const Coords &origin,
const CoordsSet &destinations) -> CoordsAndDistance;
[[nodiscard]] auto MinimumDistance(
auto MinimumDistance(
const ActionPointDistances *apd,
const Coords &origin,
const CoordsSet &destinations) -> int;
@@ -20,13 +20,12 @@ using GameState = net::eagle0::shardok::storage::fb::GameState;
using PlayerInfo = net::eagle0::shardok::storage::fb::PlayerInfo;
using Unit = net::eagle0::shardok::storage::fb::Unit;
[[nodiscard]] auto HasAttachedHeroWithProfession(
auto HasAttachedHeroWithProfession(
const Unit *unit,
net::eagle0::shardok::storage::fb::Profession profession) -> bool;
[[nodiscard]] auto CastleClaimCapableAttackerUnitCount(const GameStateW &gameState) -> int;
[[nodiscard]] auto PlayerInfoForPid(const GameStateW &gameState, PlayerId pid)
-> const PlayerInfo *;
auto CastleClaimCapableAttackerUnitCount(const GameStateW &gameState) -> int;
auto PlayerInfoForPid(const GameStateW &, PlayerId pid) -> const PlayerInfo *;
} // namespace shardok
@@ -26,13 +26,11 @@ struct AIStrategy {
};
extern AIStrategy FleeStrategy;
[[nodiscard]] auto AttackUnitsStrategy(const vector<TargetPriorityList>& targetPriorities)
-> AIStrategy;
[[nodiscard]] auto AttackCastlesStrategy(const vector<TargetPriorityList>& targetPriorities)
-> AIStrategy;
auto AttackUnitsStrategy(const vector<TargetPriorityList>& targetPriorities) -> AIStrategy;
auto AttackCastlesStrategy(const vector<TargetPriorityList>& targetPriorities) -> AIStrategy;
extern AIStrategy HoldCastlesStrategy;
extern AIStrategy ScatterStrategy;
[[nodiscard]] auto CrossRiversStrategy(const CoordsSet& targetLocations) -> AIStrategy;
auto CrossRiversStrategy(const CoordsSet& targetLocations) -> AIStrategy;
} // namespace shardok
@@ -30,7 +30,7 @@ public:
AIEvaluationCounter(AIEvaluationCounter&&) = delete;
auto operator=(AIEvaluationCounter&&) -> AIEvaluationCounter& = delete;
[[nodiscard]] static int GetCurrentCount();
static int GetCurrentCount();
};
// Configuration structure for iterative deepening time budget
@@ -44,7 +44,7 @@ struct AITimeBudget {
// Time budget is calculated dynamically based on number of available commands:
// budget = msPerCommand × numCommands (clamped to 200-5000ms)
// If isAllAiBattle is true, uses allAiBattleTimeBudgetMaximum instead of the normal maximum.
[[nodiscard]] auto CalculateTimeBudget(
auto CalculateTimeBudget(
PlayerId playerId,
const GameSettingsSPtr& settings,
const GameStateW& state,
@@ -88,8 +88,8 @@ auto ContextFreeUnitValue(const Unit *unit) -> ScoreValue {
break;
}
const double battalionValue = battalionTypeMultiplier * (1.0 + (armament / 100.0)) *
(1.0 + (training / 100.0)) * (0.5 + (morale / 100.0)) *
const double battalionValue = battalionTypeMultiplier * (1.0 + armament / 100.0) *
(1.0 + training / 100.0) * (0.5 + morale / 100.0) *
unit->battalion().size();
const double heroValue =
@@ -120,16 +120,15 @@ auto archeryValue(const vector<const Unit *> &enemyUnits, const bool canShootNow
auto reduceValue(const Unit *unit, const Terrain *unitTerrain) -> double {
// TODO: make this depend on value of reducing castle too
if (unit->fortified() || unitTerrain->modifier().castle().present()) {
if (unit->fortified() || unitTerrain->modifier().castle().present())
return kReduceFortifiedPossibleValue;
}
if (AllowsFortification(unitTerrain)) { return kReduceUnfortifiedPossibleValue; }
return 0.0;
else if (AllowsFortification(unitTerrain))
return kReduceUnfortifiedPossibleValue;
else
return 0.0;
}
auto fearValue([[maybe_unused]] const vector<const Unit *> &enemyUnits) -> double {
return kFearPossibleValue;
}
auto fearValue(const vector<const Unit *> &) -> double { return kFearPossibleValue; }
auto lightningValue(const Unit *unit) -> double {
// TODO: make this depend on the value of the targets
@@ -236,8 +235,9 @@ auto meteorValue(
multiplier = kMeteorNoneRoundMultiplier * vigorFactor;
}
return maxValue * multiplier;
} else {
return 0.0;
}
return 0.0;
}
case net::eagle0::shardok::storage::fb::MultiroundMagicState_TARGET:
@@ -247,8 +247,9 @@ auto meteorValue(
map,
enemyOccupants,
friendlyOccupants);
} else {
return bestTargetValue(unit, map, enemyOccupants, friendlyOccupants, meteorRange);
}
return bestTargetValue(unit, map, enemyOccupants, friendlyOccupants, meteorRange);
case net::eagle0::shardok::storage::fb::MultiroundMagicState_CAST:
return kMeteorCastRoundMultiplier *
meteorDropRawValue(
@@ -17,9 +17,9 @@ using net::eagle0::shardok::storage::fb::Unit;
using ScoreValue = double;
class AttackLocations;
[[nodiscard]] auto ContextFreeUnitValue(const Unit *unit) -> ScoreValue;
auto ContextFreeUnitValue(const Unit *unit) -> ScoreValue;
[[nodiscard]] auto GetRangedAttackBonus(
auto GetRangedAttackBonus(
const Unit *unit,
bool isAttacker,
const HexMap *map,
@@ -32,7 +32,7 @@ class AttackLocations;
double minVigorToCast,
ActionPoints archeryActionPointCost = 0) -> double;
[[nodiscard]] auto UnitValue(
auto UnitValue(
const Unit *unit,
bool isAttacker,
const std::vector<const Unit *> &attackerUnits,
@@ -6,18 +6,9 @@
#include "AIMinimumDistanceAndTarget.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/fb_helpers/HexMapHelpers.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/map/HexMapHasher.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/util/HexMapUtils.hpp"
namespace shardok {
namespace {
auto RecomputeModifierHash(HexMap *hexMap) -> MapId {
hexMap->mutate_modifier_hash(GetModifierHash(hexMap));
return ActionPointDistancesCache::GetMapId(hexMap);
}
} // namespace
auto UnitIdsRequiringWaterCrossing(
const GameStateW &gameState,
@@ -27,7 +18,7 @@ auto UnitIdsRequiringWaterCrossing(
const BattalionTypeGetter &battalionTypeGetter) -> vector<UnitId> {
// Put out all the fires, except on bridges
fb::HexMapW mapCopy = fb::CopyHexMap(gameState->hex_map());
for (uint32_t index = 0; index < mapCopy->terrain()->size(); ++index) {
for (uint32_t index = 0; index < mapCopy->terrain()->size(); index++) {
if (IsWater(mapCopy->terrain()->Get(index)->type())) continue;
// const_cast is safe because we own the mutable buffer (mapCopy)
const_cast<net::eagle0::shardok::storage::fb::Terrain *>(
@@ -164,7 +155,7 @@ auto WaterCrossingTiles(
// 1) the tile is water
// 2) the tile does not already have a bridge (that is not on fire)
// 3) the tile is not already frozen
for (int index = 0; index < mapSize; ++index) {
for (int index = 0; index < mapSize; index++) {
const auto startTerrain = *hexMap->terrain()->Get(index);
if (!IsWater(startTerrain.type())) continue;
@@ -178,7 +169,6 @@ auto WaterCrossingTiles(
auto *terr = const_cast<net::eagle0::shardok::storage::fb::Terrain *>(
mapCopy->mutable_terrain()->GetMutableObject(index));
terr->mutable_modifier().mutable_bridge().mutate_present(true);
terr->mutable_modifier().mutable_bridge().mutate_integrity(100.0);
terr->mutable_modifier().mutable_fire().mutate_present(false);
auto hash = ActionPointDistancesCache::GetMapId(mapCopy);
@@ -195,50 +185,6 @@ auto WaterCrossingTiles(
return returnCoords;
}
// Returns currently frozen water tiles that can act as an existing crossing from origin to
// destination. The shared APD cache deliberately ignores ice, so this probes frozen tiles by
// temporarily treating one as bridged for the water-crossing strategy only.
auto FrozenWaterCrossingTiles(
const Coords &origin,
const Coords &destination,
const HexMap *hexMap,
const APDCache &apdCache,
const BattalionTypeSPtr &battalionType) -> CoordsSet {
AssertValid(origin, hexMap);
AssertValid(destination, hexMap);
auto returnCoords = CoordsSet(hexMap);
fb::HexMapW mapCopy = fb::CopyHexMap(hexMap);
const int mapSize = hexMap->row_count() * hexMap->column_count();
for (int index = 0; index < mapSize; ++index) {
const auto startTerrain = *hexMap->terrain()->Get(index);
if (!IsWater(startTerrain.type())) continue;
const auto modifier = startTerrain.modifier();
if (!modifier.ice().present() || modifier.fire().present()) continue;
auto *terr = const_cast<net::eagle0::shardok::storage::fb::Terrain *>(
mapCopy->mutable_terrain()->GetMutableObject(index));
terr->mutable_modifier().mutable_bridge().mutate_present(true);
terr->mutable_modifier().mutable_bridge().mutate_integrity(100.0);
terr->mutable_modifier().mutable_fire().mutate_present(false);
const MapId mapId = RecomputeModifierHash(mapCopy.Get());
if (const auto *distances = apdCache->GetRaw(mapCopy, mapId, battalionType, false);
distances->Distance(origin, destination) != ActionPointDistances::IMPOSSIBLE) {
returnCoords.Add(index / hexMap->column_count(), index % hexMap->column_count());
}
terr->mutable_modifier().mutable_bridge().mutate_present(false);
terr->mutable_modifier().mutable_bridge().mutate_integrity(0.0);
}
return returnCoords;
}
// Returns the set of tiles that the attacker should try to approach in order to bridge/freeze
auto IntendedCrossingStarts(
const GameStateW &gameState,
@@ -267,6 +213,7 @@ auto IntendedCrossingStarts(
using Unit = net::eagle0::shardok::storage::fb::Unit;
constexpr double kNoRequiredCrossingScore = std::numeric_limits<double>::max();
constexpr double kNoCrossingCreatorsScore = std::numeric_limits<double>::min();
auto WaterCrossingScore(
const PlayerId playerId,
@@ -309,26 +256,12 @@ auto WaterCrossingScore(
const auto unitIdsCreatingCrossing =
UnitIdsToCreateWaterCrossing(gameState, playerId, battalionTypeGetter);
if (unitIdsCreatingCrossing.empty()) return kNoCrossingCreatorsScore;
double totalScore = 0;
const auto mapId = ActionPointDistancesCache::GetMapId(gameState->hex_map());
if (unitIdsCreatingCrossing.empty()) {
for (const UnitId uid : unitIdsRequiringCrossing) {
const Unit *unit = gameState->units()->Get(uid);
const auto &battalionType = battalionTypeGetter(unit->battalion().type());
const Coords location = unit->location();
const auto *apd = apdCache->GetRaw(gameState->hex_map(), mapId, battalionType, false);
const int thisDistance =
location.row() < 0 ? 1000 : MinimumDistance(apd, location, startCrossingFrom);
totalScore -= thisDistance;
}
return totalScore;
}
// First put a big penalty on the distance for units that can create a crossing
for (const UnitId uid : unitIdsCreatingCrossing) {
const Unit *unit = gameState->units()->Get(uid);
@@ -31,7 +31,7 @@ static inline void AssertValid(const Coords& c, const HexMap* hexMap) {
}
// Units that need a water crossing to reach at least one of the destinations
[[nodiscard]] auto UnitIdsRequiringWaterCrossing(
auto UnitIdsRequiringWaterCrossing(
const GameStateW& gameState,
PlayerId pid,
const CoordsSet& destinations,
@@ -39,14 +39,14 @@ static inline void AssertValid(const Coords& c, const HexMap* hexMap) {
const BattalionTypeGetter& battalionTypeGetter) -> vector<UnitId>;
// Units belonging to the player that are capable of creating water crossings
[[nodiscard]] auto UnitIdsToCreateWaterCrossing(
auto UnitIdsToCreateWaterCrossing(
const GameStateW& gameState,
PlayerId pid,
const BattalionTypeGetter& battalionTypeGetter) -> vector<UnitId>;
// Whether a unit of the given type can reach destination from origin, given the current state
// of the map
[[nodiscard]] auto CanReach(
auto CanReach(
const Coords& origin,
const Coords& destination,
const HexMap* hexMap,
@@ -56,21 +56,11 @@ static inline void AssertValid(const Coords& c, const HexMap* hexMap) {
// Returns the *non*-water tiles from which you could bridge/freeze water to allow a unit to cross
// from origin to destination
[[nodiscard]] auto CrossingStartLocations(const HexMap* hexMap, const CoordsSet& waterCrossingTiles)
-> CoordsSet;
auto CrossingStartLocations(const HexMap* hexMap, const CoordsSet& waterCrossingTiles) -> CoordsSet;
// Returns the water tiles that, if they were bridged/frozen, would allow a unit to cross from
// origin to destination
[[nodiscard]] auto WaterCrossingTiles(
const Coords& origin,
const Coords& destination,
const HexMap* hexMap,
const APDCache& apdCache,
const BattalionTypeSPtr& battalionType) -> CoordsSet;
// Returns currently frozen water tiles that can act as an existing crossing from origin to
// destination.
[[nodiscard]] auto FrozenWaterCrossingTiles(
auto WaterCrossingTiles(
const Coords& origin,
const Coords& destination,
const HexMap* hexMap,
@@ -78,7 +68,7 @@ static inline void AssertValid(const Coords& c, const HexMap* hexMap) {
const BattalionTypeSPtr& battalionType) -> CoordsSet;
// Returns the set of tiles that the attacker should try to approach in order to bridge/freeze
[[nodiscard]] auto IntendedCrossingStarts(
auto IntendedCrossingStarts(
const GameStateW& gameState,
const vector<UnitId>& unitIdsCreatingCrossing,
const CoordsSet& tilesToStartCrossingFrom,
@@ -86,7 +76,7 @@ static inline void AssertValid(const Coords& c, const HexMap* hexMap) {
const BattalionTypeGetter& battalionTypeGetter) -> CoordsSet;
// Calculate score based on water crossing strategy
[[nodiscard]] auto WaterCrossingScore(
auto WaterCrossingScore(
PlayerId playerId,
const BattalionTypeGetter& battalionTypeGetter,
const GameStateW& gameState,
@@ -15,6 +15,7 @@ namespace shardok {
using Unit = net::eagle0::shardok::storage::fb::Unit;
constexpr ScoreValue kNoRequiredCrossingScore = std::numeric_limits<ScoreValue>::max();
constexpr ScoreValue kNoCrossingCreatorsScore = std::numeric_limits<ScoreValue>::min();
[[nodiscard]] auto AIWaterCrossingCommandChooser::WaterCrossingScore(
const BattalionTypeGetter &battalionTypeGetter,
@@ -55,26 +56,12 @@ constexpr ScoreValue kNoRequiredCrossingScore = std::numeric_limits<ScoreValue>:
const auto unitIdsCreatingCrossing =
UnitIdsToCreateWaterCrossing(gameState, playerId, battalionTypeGetter);
if (unitIdsCreatingCrossing.empty()) return kNoCrossingCreatorsScore;
ScoreValue totalScore = 0;
const auto mapId = ActionPointDistancesCache::GetMapId(gameState->hex_map());
if (unitIdsCreatingCrossing.empty()) {
for (const UnitId uid : unitIdsRequiringCrossing) {
const Unit *unit = gameState->units()->Get(uid);
const auto &battalionType = battalionTypeGetter(unit->battalion().type());
const Coords location = unit->location();
const auto *apd = apdCache->GetRaw(gameState->hex_map(), mapId, battalionType, false);
const int thisDistance =
location.row() < 0 ? 1000 : MinimumDistance(apd, location, startCrossingFrom);
totalScore -= thisDistance;
}
return totalScore;
}
// First put a big penalty on the distance for units that can create a crossing
for (const UnitId uid : unitIdsCreatingCrossing) {
const Unit *unit = gameState->units()->Get(uid);
@@ -170,6 +157,7 @@ auto AIWaterCrossingCommandChooser::StartCrossingFrom(
const auto unitIdsCreatingCrossing =
UnitIdsToCreateWaterCrossing(gameState, playerId, battalionTypeGetter);
if (unitIdsCreatingCrossing.empty()) return startCrossingFrom;
for (const UnitId uid : unitIdsRequiringCrossing) {
const Unit *unit = gameState->units()->Get(uid);
@@ -189,17 +177,6 @@ auto AIWaterCrossingCommandChooser::StartCrossingFrom(
Coords destination = *destinations.begin();
AssertValid(destination, gameState->hex_map());
auto frozenWaterCrossingTiles = FrozenWaterCrossingTiles(
origin,
destination,
gameState->hex_map(),
apdCache,
battalionType);
startCrossingFrom +=
CrossingStartLocations(gameState->hex_map(), frozenWaterCrossingTiles);
if (unitIdsCreatingCrossing.empty()) continue;
auto waterCrossingTiles = WaterCrossingTiles(
origin,
destination,
@@ -215,4 +192,4 @@ auto AIWaterCrossingCommandChooser::StartCrossingFrom(
return startCrossingFrom;
}
} // namespace shardok
} // namespace shardok
@@ -51,7 +51,7 @@ IterativeDeepeningAI::IterativeDeepeningAI(
castleCoords(castleCoords),
scorer(scorer),
apdCache(apdCache),
battalionTypeGetter(std::move(battalionTypeGetter)) {}
battalionTypeGetter(std::move(battalionTypeGetter)) {} // Move the function object
auto IterativeDeepeningAI::IterativeSearch(
const GameSettingsSPtr& settings,
@@ -79,7 +79,7 @@ private:
CoordsSet castleCoords;
const AIScoreCalculator& scorer;
const APDCache& apdCache;
BattalionTypeGetter battalionTypeGetter;
BattalionTypeGetter battalionTypeGetter; // Store by value, not reference!
// Reusable vectors to reduce memory allocations
mutable std::vector<std::vector<ScoreValue>> scoresByDepth;
@@ -19,11 +19,8 @@
#include <sstream>
#endif
#include <array>
#include <atomic>
#include <iomanip>
#include <iostream>
#include <mutex>
#include <set>
#include <unordered_map>
@@ -185,7 +182,7 @@ auto ShardokAIClient::StandardChooseCommandIndex(
<< " round=" << guessedState->current_round() << "\n";
const auto maxDump = std::max(commandCount, realAvailableCommands->size());
for (size_t i = 0; i < maxDump; ++i) {
for (size_t i = 0; i < maxDump; i++) {
const auto realName = i < realAvailableCommands->size()
? net::eagle0::shardok::common::CommandType_Name(
(*realAvailableCommands)[i]->GetCommandType())
@@ -217,13 +214,13 @@ auto ShardokAIClient::StandardChooseCommandIndex(
// Group by unit to find the missing position per unit
std::unordered_map<int, std::set<std::pair<int, int>>> realPositions;
std::unordered_map<int, std::set<std::pair<int, int>>> guessedPositions;
for (size_t i = 0; i < realAvailableCommands->size(); ++i) {
for (size_t i = 0; i < realAvailableCommands->size(); i++) {
const auto &cmd = (*realAvailableCommands)[i];
realPositions[cmd->GetActorUnitId()].emplace(
cmd->GetTargetRow(),
cmd->GetTargetColumn());
}
for (size_t i = 0; i < commandCount; ++i) {
for (size_t i = 0; i < commandCount; i++) {
const auto &cmd = (*guessedCommands)[i];
guessedPositions[cmd->GetActorUnitId()].emplace(
cmd->GetTargetRow(),
@@ -253,7 +250,7 @@ auto ShardokAIClient::StandardChooseCommandIndex(
// Dump all guessed state units for full picture
std::cerr << " Guessed state units (" << guessedState->units()->size() << " total):\n";
for (size_t i = 0; i < guessedState->units()->size(); ++i) {
for (size_t i = 0; i < guessedState->units()->size(); i++) {
const auto *u = guessedState->units()->Get(static_cast<unsigned int>(i));
std::cerr << " unit_id=" << u->unit_id() << " player=" << u->player_id()
<< " status=" << static_cast<int>(u->status()) << " loc=("
@@ -266,7 +263,7 @@ auto ShardokAIClient::StandardChooseCommandIndex(
"AI command count mismatch: guessed=" + std::to_string(commandCount) +
" real=" + std::to_string(realAvailableCommands->size()));
}
for (size_t i = 0; i < commandCount; ++i) {
for (size_t i = 0; i < commandCount; i++) {
CheckCommand((*realAvailableCommands)[i], (*guessedCommands)[i]);
}
@@ -468,10 +465,8 @@ auto ShardokAIClient::ChooseCommandIndex(
const GameSettingsSPtr &settings,
const GameStateView &gsv,
const CommandListSPtr &realAvailableCommands) const -> CommandChoiceResults {
static std::array<std::atomic<int>, net::eagle0::shardok::common::CommandType_MAX + 1>
typeChosenCount;
static std::atomic<int> totalChoices = 0;
static std::mutex reportMutex;
static int typeChosenCount[net::eagle0::shardok::common::CommandType_MAX + 1];
static int totalChoices = 0;
CommandChoiceResults results{};
@@ -489,18 +484,15 @@ auto ShardokAIClient::ChooseCommandIndex(
}
const auto chosenType = (*realAvailableCommands)[results.chosenIndex]->GetCommandType();
typeChosenCount[static_cast<size_t>(chosenType)].fetch_add(1, std::memory_order_relaxed);
const int updatedTotal = totalChoices.fetch_add(1, std::memory_order_relaxed) + 1;
typeChosenCount[static_cast<int>(chosenType)]++;
totalChoices++;
if (updatedTotal % 1000 == 0) {
std::lock_guard lock(reportMutex);
if (totalChoices % 1000 == 0) {
std::cout << "TYPES CHOSEN:\n";
vector<std::pair<int, CommandType>> choices{};
for (int i = 0; i <= net::eagle0::shardok::common::CommandType_MAX; ++i) {
if (const int count =
typeChosenCount[static_cast<size_t>(i)].load(std::memory_order_relaxed);
count != 0) {
choices.emplace_back(count, static_cast<CommandType>(i));
for (int i = 0; i <= net::eagle0::shardok::common::CommandType_MAX; i++) {
if (typeChosenCount[i] != 0) {
choices.emplace_back(typeChosenCount[i], static_cast<CommandType>(i));
}
}
@@ -38,10 +38,8 @@ TranspositionTable::probe(const GameStateW& state, int depth, PlayerId player) {
uint64_t stored_hash = entry.hash_full.load(std::memory_order_relaxed);
uint8_t stored_depth = entry.depth.load(std::memory_order_relaxed);
uint8_t stored_player = entry.player_id.load(std::memory_order_relaxed);
uint16_t stored_age = entry.age.load(std::memory_order_relaxed);
if (stored_hash == hash && stored_depth >= depth && stored_player == player &&
stored_age == current_age.load(std::memory_order_relaxed)) {
if (stored_hash == hash && stored_depth >= depth && stored_player == player) {
stats.hits++;
float score = entry.score.load(std::memory_order_relaxed);
return static_cast<ScoreValue>(score);
@@ -44,7 +44,6 @@ public:
[[nodiscard]] PlayerId getPlayer() const { return player_; }
[[nodiscard]] int getActorId() const { return actorId_; }
[[nodiscard]] std::pair<int, int> getTarget() const { return {targetRow_, targetCol_}; }
[[nodiscard]] bool hasOdds() const { return hasOdds_; }
private:
// Store only essential fields (~25 bytes, all POD, cache-friendly)
@@ -6,10 +6,8 @@
#include <algorithm>
#include <chrono>
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <mutex>
#include <numeric>
#include "ShardokAction.hpp"
@@ -34,30 +32,9 @@ auto IsDefenderPlayer(const GameStateW& gameState, const PlayerId playerId) -> b
return false;
}
auto MixCacheKey(uint64_t seed, const uint64_t value) -> uint64_t {
constexpr uint64_t kHashCombineConstant = 0x9e3779b97f4a7c15ULL;
seed ^= value + kHashCombineConstant + (seed << 6) + (seed >> 2);
return seed;
}
auto PointerIdentityHash(const void* ptr) -> uint64_t {
return static_cast<uint64_t>(reinterpret_cast<std::uintptr_t>(ptr));
}
auto LegalActionsCacheKey(
const uint64_t stateHash,
const bool rootIsDefender,
const GameSettings* gameSettings,
const APDCache* apdCache) -> uint64_t {
auto LegalActionsCacheKey(const uint64_t stateHash, const bool rootIsDefender) -> uint64_t {
constexpr uint64_t kDefenderRoleHash = 0x9e3779b97f4a7c15ULL;
uint64_t key = rootIsDefender ? stateHash ^ kDefenderRoleHash : stateHash;
// The cached action set is the output of AICommandFilter, not just the raw command list.
// Include the context objects that can affect filtering so a process-wide cache entry from
// one search cannot be reused by a different settings/APD context with the same state hash.
key = MixCacheKey(key, PointerIdentityHash(gameSettings));
key = MixCacheKey(key, PointerIdentityHash(apdCache != nullptr ? apdCache->get() : nullptr));
return key;
return rootIsDefender ? stateHash ^ kDefenderRoleHash : stateHash;
}
auto SortActionsByWeight(
@@ -66,7 +43,7 @@ auto SortActionsByWeight(
std::vector<size_t> sortedIndices(actions.size());
std::iota(sortedIndices.begin(), sortedIndices.end(), 0);
std::ranges::sort(sortedIndices, [&weights](size_t a, size_t b) {
std::sort(sortedIndices.begin(), sortedIndices.end(), [&weights](size_t a, size_t b) {
return weights[a] > weights[b];
});
@@ -95,10 +72,6 @@ std::atomic<uint64_t> ShardokGameEngine::cacheMisses_{0};
std::atomic<uint64_t> ShardokGameEngine::timeInHashComputation_{0};
std::atomic<uint64_t> ShardokGameEngine::timeInLegalActionsComputation_{0};
namespace {
std::once_flag legalActionsCacheReserveOnce;
} // namespace
ShardokGameEngine::ShardokGameEngine(
[[maybe_unused]] const ShardokEngine* engine,
const AIScoreCalculator* scoreCalculator,
@@ -119,9 +92,7 @@ ShardokGameEngine::ShardokGameEngine(
criticalTileCoords_(criticalTileCoords) {
// Thread-local cache is automatically initialized per thread
// Reserve space to reduce rehashing (based on profiling: ~30-50K unique states per search)
std::call_once(legalActionsCacheReserveOnce, [] {
ShardokGameEngine::legalActionsCache_.reserve(100000);
});
legalActionsCache_.reserve(100000);
}
std::unique_ptr<MCTSGameState> ShardokGameEngine::applyAction(
@@ -135,15 +106,27 @@ std::unique_ptr<MCTSGameState> ShardokGameEngine::applyAction(
const auto currentPlayer = static_cast<PlayerId>(state.currentPlayerId());
auto engine = std::make_shared<ShardokEngine>(
gameSettings_,
shardokState->getShardokState(),
criticalTileCoords_,
0,
false);
// Populate the AI command list before posting so the MCTS action index maps to the
// no-follow-up command ordering used by getLegalActions().
[[maybe_unused]] const auto commands = engine->GetAvailableCommandsForAIPlayer(currentPlayer);
// Use cached engine if available (avoids recomputing GetAvailableCommands for same state)
std::shared_ptr<ShardokEngine> engine;
if (auto cachedEngine = shardokState->getCachedEngine()) {
// Clone the cached engine to preserve command cache
engine = std::make_shared<ShardokEngine>(*cachedEngine);
} else {
// Create fresh engine and populate command cache
engine = std::make_shared<ShardokEngine>(
gameSettings_,
shardokState->getShardokState(),
criticalTileCoords_,
0,
false);
// Populate command cache (result intentionally unused, just populating cache)
[[maybe_unused]] const auto commands =
engine->GetAvailableCommandsForAIPlayer(currentPlayer);
// Cache the engine for future use with this state
shardokState->setCachedEngine(engine);
// Clone it for applying the action (don't mutate the cached engine)
engine = std::make_shared<ShardokEngine>(*engine);
}
// Create deterministic random generator if a specific roll is requested
// deterministicRoll of -1.0 (default) means use random generator
@@ -204,6 +187,11 @@ std::unique_ptr<MCTSGameState> ShardokGameEngine::applyAction(
*alCache_,
criticalTileCoords_);
// Cache the engine on the new state so score() can use it for END_TURN normalization
// The engine's command list may be stale after the action was applied, but that's OK -
// we'll refresh it when we call GetAvailableCommandsForAIPlayer() in score()
newState->setCachedEngine(engine);
// Don't pre-compute hash - let it be computed lazily on first use
// Many states (especially in simulation) never need their hash computed
return newState;
@@ -223,18 +211,28 @@ void ShardokGameEngine::applyActionMutable(
const auto currentPlayer = static_cast<PlayerId>(state->currentPlayerId());
auto engine = std::make_shared<ShardokEngine>(
gameSettings_,
shardokState->getShardokState(),
criticalTileCoords_,
0,
false);
// Populate the AI command list before posting so the MCTS action index maps to the
// no-follow-up command ordering used by getLegalActions().
[[maybe_unused]] const auto commands = engine->GetAvailableCommandsForAIPlayer(currentPlayer);
// Use cached engine if available
std::shared_ptr<ShardokEngine> engine;
if (auto cachedEngine = shardokState->getCachedEngine()) {
engine = std::make_shared<ShardokEngine>(*cachedEngine);
} else {
engine = std::make_shared<ShardokEngine>(
gameSettings_,
shardokState->getShardokState(),
criticalTileCoords_,
0,
false);
// Populate command cache (result intentionally unused, just populating cache)
[[maybe_unused]] const auto commands =
engine->GetAvailableCommandsForAIPlayer(currentPlayer);
shardokState->setCachedEngine(engine);
engine = std::make_shared<ShardokEngine>(*engine);
}
engine->PostCommand(currentPlayer, shardokAction->getIndex(), nullptr);
shardokState->getMutableShardokState() = engine->GetCurrentGameState();
// Clear the cached engine and hash since the state has been mutated
shardokState->setCachedEngine(nullptr);
shardokState->invalidateHashCache();
}
@@ -260,8 +258,7 @@ std::vector<std::unique_ptr<MCTSAction>> ShardokGameEngine::getLegalActions(
// Time hash computation
const auto hashStart = std::chrono::high_resolution_clock::now();
const uint64_t stateHash = shardokState->hash();
const uint64_t cacheKey =
LegalActionsCacheKey(stateHash, isDefender_, gameSettings_.get(), apdCache_);
const uint64_t cacheKey = LegalActionsCacheKey(stateHash, isDefender_);
const auto hashEnd = std::chrono::high_resolution_clock::now();
timeInHashComputation_.fetch_add(
std::chrono::duration_cast<std::chrono::microseconds>(hashEnd - hashStart).count(),
@@ -269,49 +266,40 @@ std::vector<std::unique_ptr<MCTSAction>> ShardokGameEngine::getLegalActions(
// Check transposition table for cached legal actions
if (auto it = legalActionsCache_.find(cacheKey); it != legalActionsCache_.end()) {
const auto engine = std::make_shared<ShardokEngine>(
gameSettings_,
shardokState->getShardokState(),
criticalTileCoords_);
cacheHits_.fetch_add(1, std::memory_order_relaxed);
const CommandListSPtr commands = engine->GetAvailableCommandsForAIPlayer(currentPlayer);
// Use cached engine
shardokState->setCachedEngine(it->second.engine);
bool cacheEntryMatches = commands != nullptr && commands->size() == it->second.commandCount;
for (const auto& cachedAction : it->second.actions) {
const size_t commandIndex = cachedAction.getIndex();
if (!cacheEntryMatches || commandIndex >= commands->size()) {
cacheEntryMatches = false;
break;
// Get commands from the cached engine (Engine already caches these internally)
const CommandListSPtr commands =
it->second.engine->GetAvailableCommandsForAIPlayer(currentPlayer);
if (!commands || commands->empty()) { return {}; }
// Convert to MCTSActions using stored filtered indices
std::vector<std::unique_ptr<MCTSAction>> actions;
actions.reserve(it->second.filteredIndices.size());
for (const size_t origIdx : it->second.filteredIndices) {
if (origIdx < commands->size()) {
const auto& cmd = commands->at(origIdx);
// Extract essential fields directly from command (no proto conversion!)
actions.push_back(std::make_unique<ShardokAction>(
origIdx,
cmd->GetCommandType(),
cmd->GetPlayerId(),
cmd->GetActorUnitId(),
cmd->GetTargetRow(),
cmd->GetTargetColumn(),
cmd->HasOdds()));
}
const auto& command = commands->at(commandIndex);
const auto [targetRow, targetColumn] = cachedAction.getTarget();
cacheEntryMatches = command->GetCommandType() ==
static_cast<net::eagle0::shardok::common::CommandType>(
cachedAction.getType()) &&
command->GetPlayerId() == cachedAction.getPlayer() &&
command->GetActorUnitId() == cachedAction.getActorId() &&
command->GetTargetRow() == targetRow &&
command->GetTargetColumn() == targetColumn &&
command->HasOdds() == cachedAction.hasOdds();
if (!cacheEntryMatches) { break; }
}
if (cacheEntryMatches) {
cacheHits_.fetch_add(1, std::memory_order_relaxed);
// Convert immutable cached action snapshots to MCTS action instances.
std::vector<std::unique_ptr<MCTSAction>> actions;
actions.reserve(it->second.actions.size());
for (const auto& cachedAction : it->second.actions) {
actions.push_back(cachedAction.clone());
}
// Sort actions by weight (descending) to ensure MCTS explores high-value actions first
const std::vector<double> weights = getActionWeights(actions, state);
return SortActionsByWeight(std::move(actions), weights);
}
// Sort actions by weight (descending) to ensure MCTS explores high-value actions first
const std::vector<double> weights = getActionWeights(actions, state);
return SortActionsByWeight(std::move(actions), weights);
}
cacheMisses_.fetch_add(1, std::memory_order_relaxed);
@@ -319,10 +307,17 @@ std::vector<std::unique_ptr<MCTSAction>> ShardokGameEngine::getLegalActions(
// Time legal actions computation
const auto actionsStart = std::chrono::high_resolution_clock::now();
const auto engine = std::make_shared<ShardokEngine>(
gameSettings_,
shardokState->getShardokState(),
criticalTileCoords_);
// Use cached engine if available, otherwise create and cache it
std::shared_ptr<ShardokEngine> engine;
if (auto cachedEngine = shardokState->getCachedEngine()) {
engine = cachedEngine;
} else {
engine = std::make_shared<ShardokEngine>(
gameSettings_,
shardokState->getShardokState(),
criticalTileCoords_);
shardokState->setCachedEngine(engine);
}
const CommandListSPtr commands = engine->GetAvailableCommandsForAIPlayer(currentPlayer);
@@ -343,24 +338,20 @@ std::vector<std::unique_ptr<MCTSAction>> ShardokGameEngine::getLegalActions(
// Convert only filtered commands to MCTSActions
std::vector<std::unique_ptr<MCTSAction>> actions;
actions.reserve(filteredIndices.size());
std::vector<ShardokAction> cachedActions;
cachedActions.reserve(filteredIndices.size());
for (const size_t idx : filteredIndices) {
if (idx < commands->size()) {
const auto& cmd = commands->at(idx);
// Extract essential fields directly from command (no proto conversion!)
ShardokAction action(
actions.push_back(std::make_unique<ShardokAction>(
idx,
cmd->GetCommandType(),
cmd->GetPlayerId(),
cmd->GetActorUnitId(),
cmd->GetTargetRow(),
cmd->GetTargetColumn(),
cmd->HasOdds());
actions.push_back(action.clone());
cachedActions.push_back(action);
cmd->HasOdds()));
}
}
@@ -377,20 +368,20 @@ std::vector<std::unique_ptr<MCTSAction>> ShardokGameEngine::getLegalActions(
.count(),
std::memory_order_relaxed);
// Store immutable action snapshots in the transposition table for future lookups.
// Do not store ShardokEngine here: its command cache is mutable and not safe to share
// across MCTS worker threads.
// Store in transposition table for future lookups
// Note: We only store filtered indices and the engine (which caches commands internally)
// This avoids duplicating heavy protocol buffer objects
// Use lazy_emplace_l to ensure thread-safe insertion (locks the bucket during construction)
legalActionsCache_.lazy_emplace_l(
cacheKey,
[&](typename decltype(legalActionsCache_)::value_type& v) {
// Update existing entry
v.second.commandCount = commands->size();
v.second.actions = cachedActions;
v.second.filteredIndices = filteredIndices;
v.second.engine = engine;
},
[&](const typename decltype(legalActionsCache_)::constructor& ctor) {
// Create new entry
ctor(cacheKey, LegalActionsCache{commands->size(), cachedActions});
ctor(cacheKey, LegalActionsCache{filteredIndices, engine});
});
return actions;
@@ -407,8 +398,9 @@ std::vector<size_t> ShardokGameEngine::filterActions(
const MCTSGameState& /*state*/) const {
// All filtering is already done in getLegalActions() using AICommandFilter
// This method is used by simulation policies and doesn't need additional filtering
std::vector<size_t> indices(actions.size());
std::iota(indices.begin(), indices.end(), 0);
std::vector<size_t> indices;
indices.reserve(actions.size());
for (size_t i = 0; i < actions.size(); ++i) { indices.push_back(i); }
return indices;
}
@@ -423,7 +415,15 @@ std::vector<double> ShardokGameEngine::getActionWeights(
"indicates a type mismatch in the MCTS adapter layer");
}
// Get cached engine and command list for looking up command protos
auto cachedEngine = shardokState->getCachedEngine();
if (!cachedEngine) {
throw MCTSInternalError(
"ShardokGameEngine::getActionWeights called with state that has no cached engine");
}
const auto currentPlayer = static_cast<PlayerId>(state.currentPlayerId());
const CommandListSPtr commands = cachedEngine->GetAvailableCommandsForAIPlayer(currentPlayer);
// Determine if current player is defender (not root player!)
// During simulation we need to use the correct perspective for action weighting
@@ -442,13 +442,20 @@ std::vector<double> ShardokGameEngine::getActionWeights(
"indicates a type mismatch in the MCTS adapter layer");
}
const auto [targetRow, targetColumn] = shardokAction->getTarget();
// Look up command proto from cached engine using action's index
const size_t cmdIndex = shardokAction->getIndex();
if (cmdIndex >= commands->size()) {
throw MCTSInternalError(
"ShardokGameEngine::getActionWeights: action index out of bounds");
}
const auto& cmd = commands->at(cmdIndex);
weights.push_back(AIHeuristicWeighting::GetCommandWeight(
static_cast<net::eagle0::shardok::common::CommandType>(shardokAction->getType()),
shardokAction->getActorId(),
shardokAction->getPlayer(),
Coords{static_cast<int8_t>(targetRow), static_cast<int8_t>(targetColumn)},
cmd->GetCommandType(),
cmd->GetActorUnitId(),
cmd->GetPlayerId(),
Coords{cmd->GetTargetRow(), cmd->GetTargetColumn()},
gameState,
castleCoords_,
apdCache_,
@@ -482,7 +489,7 @@ bool ShardokGameEngine::shouldStopSearch(
size_t ShardokGameEngine::mapFilteredIndexToOriginal(
size_t filteredIndex,
const MCTSGameState& state) const {
// Get the filtered actions.
// Get the filtered actions (uses cached engine)
auto actions = getLegalActions(state, state.currentPlayerId(), 0, 0);
// Check bounds
@@ -584,12 +591,22 @@ ChanceOutcomeInfo ShardokGameEngine::getBinaryOutcomeInfo(
const auto currentPlayer = static_cast<PlayerId>(state.currentPlayerId());
const auto engine = std::make_shared<ShardokEngine>(
gameSettings_,
shardokState->getShardokState(),
criticalTileCoords_,
0,
false);
// Get or create the engine for this state
std::shared_ptr<ShardokEngine> engine;
if (auto cachedEngine = shardokState->getCachedEngine()) {
engine = cachedEngine;
} else {
engine = std::make_shared<ShardokEngine>(
gameSettings_,
shardokState->getShardokState(),
criticalTileCoords_,
0,
false);
// Populate command cache
[[maybe_unused]] const auto commands =
engine->GetAvailableCommandsForAIPlayer(currentPlayer);
shardokState->setCachedEngine(engine);
}
// Get command descriptors
const auto descriptors = engine->GetAvailableCommandsForAIPlayer(currentPlayer);
@@ -15,7 +15,6 @@
#include "src/main/cpp/net/eagle0/common/mcts/abstract/MCTSGameEngine.hpp"
#include "src/main/cpp/net/eagle0/shardok/ai/AIAttackLocations.hpp"
#include "src/main/cpp/net/eagle0/shardok/ai/AIStrategy.hpp"
#include "src/main/cpp/net/eagle0/shardok/ai/mcts/adapters/ShardokAction.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/ShardokEngine.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/action_point_distances/ActionPointDistancesCache.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/map/CoordsSet.hpp"
@@ -100,12 +99,11 @@ public:
void resetCacheStatistics();
private:
// Transposition table entry for caching legal actions.
// Store immutable action snapshots only; ShardokEngine owns mutable command caches and
// must remain per-state/per-thread.
// Transposition table entry for caching legal actions
// Note: We don't store command protos since the Engine already caches them
struct LegalActionsCache {
size_t commandCount;
std::vector<ShardokAction> actions;
std::vector<size_t> filteredIndices;
std::shared_ptr<ShardokEngine> engine; // Engine with populated command cache
};
const AIScoreCalculator* scoreCalculator_;
@@ -98,6 +98,7 @@ std::unique_ptr<MCTSGameState> ShardokGameState::clone() const {
apdCache_,
alCache_,
criticalTileCoords_);
// Don't copy the cached engine - each state needs its own
return cloned;
}
@@ -10,6 +10,7 @@
#include "src/main/cpp/net/eagle0/common/mcts/abstract/MCTSGameState.hpp"
#include "src/main/cpp/net/eagle0/shardok/ai/AIStrategy.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/GameStateW.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/ShardokEngine.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/action_point_distances/ActionPointDistancesCache.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/map/CoordsSet.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/settings/GameSettings.hpp"
@@ -51,6 +52,10 @@ public:
[[nodiscard]] const GameSettings* getSettings() const { return settings_; }
[[nodiscard]] const CoordsSet& getCriticalTileCoords() const { return criticalTileCoords_; }
// Engine caching for performance (avoids recomputing available commands)
void setCachedEngine(std::shared_ptr<ShardokEngine> engine) const { cachedEngine_ = engine; }
[[nodiscard]] std::shared_ptr<ShardokEngine> getCachedEngine() const { return cachedEngine_; }
// Invalidate hash cache when state is mutated
void invalidateHashCache() const {
hashCached_ = false;
@@ -69,6 +74,7 @@ private:
mutable uint64_t cachedHash_ = 0;
mutable bool hashCached_ = false;
const CoordsSet criticalTileCoords_; // Own the data to avoid dangling references
mutable std::shared_ptr<ShardokEngine> cachedEngine_; // Engine with cached available commands
};
} // namespace mcts
@@ -133,7 +133,8 @@ auto DefenderHoldsCriticalTilesVictoryScore(
const auto cc = gameState->hex_map()->column_count();
const auto occupants = Occupants(*gameState->units(), rc, cc);
for (const auto index : criticalTileLocations.indexIterator()) {
for (const Coords& criticalTileLocation : criticalTileLocations) {
const auto index = criticalTileLocation.row() * cc + criticalTileLocation.column();
const auto& occupant = occupants[index];
if (occupant && occupant->battalion().type() !=
@@ -23,7 +23,7 @@ using net::eagle0::shardok::storage::fb::PlayerInfo;
using ScoreValue = double;
[[nodiscard]] auto AttackerHoldsCriticalTilesVictoryScore(
auto AttackerHoldsCriticalTilesVictoryScore(
const GameStateW& gameState,
const CoordsSet& criticalTileLocations,
const PlayerInfo* player,
@@ -32,12 +32,12 @@ using ScoreValue = double;
const BattalionTypeGetter& battalionTypeGetter,
ActionPoints braveWaterCost) -> ScoreValue;
[[nodiscard]] auto DefenderHoldsCriticalTilesVictoryScore(
auto DefenderHoldsCriticalTilesVictoryScore(
const GameStateW& gameState,
const CoordsSet& criticalTileLocations,
const PlayerInfo* player) -> ScoreValue;
[[nodiscard]] auto LastPlayerStandingVictoryScore(
auto LastPlayerStandingVictoryScore(
const GameStateW& gameState,
const PlayerInfo* player,
const APDCache& apdCache,
@@ -230,7 +230,7 @@ auto MakeMCTSOptimizedAIScoreCalculator(
std::vector<BattalionTypeSPtr> battalionTypes(BattalionTypeId::BattalionTypeId_MAX + 1);
for (int typeId = BattalionTypeId::BattalionTypeId_MIN;
typeId <= BattalionTypeId::BattalionTypeId_MAX;
++typeId) {
typeId++) {
auto battalionTypeId = static_cast<BattalionTypeId>(typeId);
battalionTypes[battalionTypeId] = settingsGetter.GetBattalionType(battalionTypeId);
}
@@ -356,7 +356,7 @@ auto MakeStandardAIScoreCalculatorWithExperiment(
std::vector<BattalionTypeSPtr> battalionTypes(BattalionTypeId::BattalionTypeId_MAX + 1);
for (int typeId = BattalionTypeId::BattalionTypeId_MIN;
typeId <= BattalionTypeId::BattalionTypeId_MAX;
++typeId) {
typeId++) {
auto battalionTypeId = static_cast<BattalionTypeId>(typeId);
battalionTypes[battalionTypeId] = settingsGetter.GetBattalionType(battalionTypeId);
}
@@ -7,7 +7,8 @@
#include "src/main/cpp/net/eagle0/shardok/ai/AIScoreUtilities.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/map/CoordsSet.hpp"
namespace shardok::score_calculator_internal {
namespace shardok {
namespace score_calculator_internal {
auto EffectiveDistanceCache::GetOrCompute(
const Unit* unit,
@@ -124,4 +125,5 @@ auto AttackerMultiplierForTargetDistance(
isLateGame);
}
} // namespace shardok::score_calculator_internal
} // namespace score_calculator_internal
} // namespace shardok
@@ -24,7 +24,8 @@
#include "src/main/flatbuffer/net/eagle0/shardok/storage/hex_map_generated.h"
#include "src/main/flatbuffer/net/eagle0/shardok/storage/unit_generated.h"
namespace shardok::score_calculator_internal {
namespace shardok {
namespace score_calculator_internal {
using HexMap = net::eagle0::shardok::storage::fb::HexMap;
using Unit = net::eagle0::shardok::storage::fb::Unit;
@@ -50,13 +51,13 @@ struct EffectiveDistanceCache {
struct CacheKey {
UnitId unitId;
Coords target;
[[nodiscard]] bool operator==(const CacheKey& other) const {
bool operator==(const CacheKey& other) const {
return unitId == other.unitId && target == other.target;
}
};
struct CacheKeyHash {
[[nodiscard]] size_t operator()(const CacheKey& key) const {
size_t operator()(const CacheKey& key) const {
return std::hash<UnitId>{}(key.unitId) ^ (std::hash<int>{}(key.target.row()) << 1) ^
(std::hash<int>{}(key.target.column()) << 2);
}
@@ -64,7 +65,7 @@ struct EffectiveDistanceCache {
mutable gtl::flat_hash_map<CacheKey, DIST_T, CacheKeyHash> cache;
[[nodiscard]] DIST_T GetOrCompute(
DIST_T GetOrCompute(
const Unit* unit,
const Coords& target,
const ActionPointDistances* notBravingApd,
@@ -74,12 +75,11 @@ struct EffectiveDistanceCache {
/// Calculate score for FLEE strategy
/// Returns negative score based on fleeing units
[[nodiscard]] auto FleeStrategyScoreForState(const GameStateW& gameState, PlayerId playerId)
-> ScoreValue;
auto FleeStrategyScoreForState(const GameStateW& gameState, PlayerId playerId) -> ScoreValue;
/// Calculate attacker multiplier based on distance to priority targets
/// This is used to weight attacker units by their proximity to objectives
[[nodiscard]] auto AttackerMultiplierForTargetDistance(
auto AttackerMultiplierForTargetDistance(
const Unit* attackingUnit,
const std::vector<TargetAndAttackLocations>& priorityList,
const std::vector<const Unit*>& occupants,
@@ -89,6 +89,7 @@ struct EffectiveDistanceCache {
const ActionPointDistances* bravingApd,
bool isLateGame) -> double;
} // namespace shardok::score_calculator_internal
} // namespace score_calculator_internal
} // namespace shardok
#endif // EAGLE0_SHARDOK_AI_SCORE_PRIVATE_AI_SCORE_CALCULATOR_SHARED_UTILITIES_HPP
@@ -10,7 +10,8 @@
#include <iostream>
#include <sstream>
namespace shardok::ai_battle_simulator {
namespace shardok {
namespace ai_battle_simulator {
using net::eagle0::shardok::ai_battle_simulator::AIAlgorithmType;
using net::eagle0::shardok::ai_battle_simulator::PlayerConfig;
@@ -109,4 +110,5 @@ std::string AiBattleConfigLoader::ToJsonString(const BattleConfigProto& config)
return jsonString;
}
} // namespace shardok::ai_battle_simulator
} // namespace ai_battle_simulator
} // namespace shardok
@@ -13,7 +13,8 @@
#include "src/main/protobuf/net/eagle0/shardok/ai_battle_simulator/ai_battle_config.pb.h"
#pragma clang diagnostic pop
namespace shardok::ai_battle_simulator {
namespace shardok {
namespace ai_battle_simulator {
using BattleConfigProto = net::eagle0::shardok::ai_battle_simulator::BattleConfig;
@@ -40,6 +41,7 @@ public:
[[nodiscard]] static std::string ToJsonString(const BattleConfigProto& config);
};
} // namespace shardok::ai_battle_simulator
} // namespace ai_battle_simulator
} // namespace shardok
#endif // EAGLE0_SHARDOK_AI_BATTLE_SIMULATOR_AI_BATTLE_CONFIG_HPP
@@ -28,7 +28,8 @@
#include "src/main/protobuf/net/eagle0/shardok/common/player_info.pb.h"
#pragma clang diagnostic pop
namespace shardok::ai_battle_simulator {
namespace shardok {
namespace ai_battle_simulator {
namespace {
@@ -330,6 +331,10 @@ GameStateW AiBattleSimulator::CreateInitialGameState() const {
// Load map
auto hexMapProto = LoadMap(config_.map_name());
// Create player info protos
std::vector<net::eagle0::shardok::common::PlayerInfo> playerInfoProtos;
playerInfoProtos.reserve(2);
// Attacker info
net::eagle0::shardok::common::PlayerInfo attackerInfo;
attackerInfo.set_player_id(ATTACKER_ID);
@@ -339,6 +344,7 @@ GameStateW AiBattleSimulator::CreateInitialGameState() const {
net::eagle0::shardok::common::VICTORY_CONDITION_LAST_PLAYER_STANDING);
attackerInfo.add_victory_conditions(
net::eagle0::shardok::common::VICTORY_CONDITION_HOLDS_CRITICAL_TILES);
playerInfoProtos.push_back(std::move(attackerInfo));
// Defender info
net::eagle0::shardok::common::PlayerInfo defenderInfo;
@@ -349,10 +355,7 @@ GameStateW AiBattleSimulator::CreateInitialGameState() const {
net::eagle0::shardok::common::VICTORY_CONDITION_LAST_PLAYER_STANDING);
defenderInfo.add_victory_conditions(
net::eagle0::shardok::common::VICTORY_CONDITION_WIN_AFTER_MAX_ROUNDS);
std::vector<net::eagle0::shardok::common::PlayerInfo> playerInfoProtos{
std::move(attackerInfo),
std::move(defenderInfo)};
playerInfoProtos.push_back(std::move(defenderInfo));
// Create units from config
std::vector<net::eagle0::shardok::storage::fb::Unit> units;
@@ -958,4 +961,5 @@ BattleResult AiBattleSimulator::CreateResultFromGameState(
return result;
}
} // namespace shardok::ai_battle_simulator
} // namespace ai_battle_simulator
} // namespace shardok
@@ -30,9 +30,7 @@ class ShardokEngine;
// Type alias for hex map
using HexMap = net::eagle0::shardok::storage::fb::HexMap;
} // namespace shardok
namespace shardok::ai_battle_simulator {
namespace ai_battle_simulator {
using BattleConfigProto = net::eagle0::shardok::ai_battle_simulator::BattleConfig;
@@ -148,6 +146,7 @@ private:
CreateResultFromGameState(const GameStateW& state, int totalRounds, int totalCommands) const;
};
} // namespace shardok::ai_battle_simulator
} // namespace ai_battle_simulator
} // namespace shardok
#endif // EAGLE0_SHARDOK_AI_BATTLE_SIMULATOR_AI_BATTLE_SIMULATOR_HPP
@@ -191,8 +191,7 @@ int main(int argc, char *argv[]) {
}
std::cout << "],\"has_game_status\":" << (hasGameStatus ? "true" : "false") << "}\n";
return 0;
}
if (!resultPath.empty()) {
} else if (!resultPath.empty()) {
ActionResult result;
if (!result.ParseFromString(ReadFile(resultPath))) {
throw std::runtime_error("Failed to parse Shardok action result proto");
@@ -32,7 +32,7 @@ public:
* Initialize game settings from the default configuration files.
* Must be called before creating game states.
*/
[[nodiscard]] static auto InitializeGameSettings() -> GameSettingsSPtr;
static auto InitializeGameSettings() -> GameSettingsSPtr;
/**
* Create the standard "Perf" test configuration:
@@ -44,7 +44,7 @@ public:
* @param defenderToggle If true, AI is defender; if false, AI is attacker
* @return A GameStateW with the configured battle
*/
[[nodiscard]] static auto CreatePerfTestGameState(
static auto CreatePerfTestGameState(
const GameSettingsSPtr& settings,
bool defenderToggle = false) -> GameStateW;
@@ -58,7 +58,7 @@ public:
* @param defenderToggle If true, AI is defender; if false, AI is attacker
* @return A GameStateW with the configured battle
*/
[[nodiscard]] static auto CreateCustomTestGameState(
static auto CreateCustomTestGameState(
const GameSettingsSPtr& settings,
const std::string& mapName,
int aiUnitCount,
@@ -67,11 +67,11 @@ public:
private:
// Helper functions for building game state components
[[nodiscard]] static auto
static auto
AddPlayerInfo(flatbuffers::FlatBufferBuilder& fbb, int playerId, bool isDefender, int food)
-> flatbuffers::Offset<net::eagle0::shardok::storage::fb::PlayerInfo>;
[[nodiscard]] static auto AddGenericUnit(
static auto AddGenericUnit(
PlayerId playerId,
UnitId unitId,
const net::eagle0::shardok::storage::fb::Coords& location,
@@ -7,7 +7,8 @@
#include "src/main/cpp/net/eagle0/common/mcts/abstract/MCTSTypes.hpp"
#include "src/main/cpp/net/eagle0/shardok/ai/ShardokAIClient.hpp"
namespace shardok::ai_testing_common {
namespace shardok {
namespace ai_testing_common {
auto AIClientFactory::Create(
PlayerId playerId,
@@ -29,4 +30,5 @@ auto AIClientFactory::Create(
mctsConfig);
}
} // namespace shardok::ai_testing_common
} // namespace ai_testing_common
} // namespace shardok
@@ -54,7 +54,7 @@ public:
* @param mctsConfig MCTS settings, used only when algorithmType is MCTS
* @return Unique pointer to created ShardokAIClient
*/
[[nodiscard]] static auto Create(
static auto Create(
PlayerId playerId,
bool isDefender,
const net::eagle0::shardok::storage::fb::HexMap* hexMap,
@@ -8,7 +8,8 @@
#include "src/main/cpp/net/eagle0/shardok/library/ShardokEngine.hpp"
#include "src/main/flatbuffer/net/eagle0/shardok/storage/game_state.hpp"
namespace shardok::ai_testing_common {
namespace shardok {
namespace ai_testing_common {
auto GamePhaseRunner::RunSetupPhase(
ShardokEngine& engine,
@@ -57,4 +58,5 @@ auto GamePhaseRunner::RunSingleTurn(ShardokEngine& engine, PlayerId playerId, Sh
return true;
}
} // namespace shardok::ai_testing_common
} // namespace ai_testing_common
} // namespace shardok
@@ -9,7 +9,8 @@
#include "src/main/cpp/net/eagle0/common/byte_vector.hpp"
#include "src/main/cpp/net/eagle0/shardok/util/BattalionTypeRegistrar.hpp"
namespace shardok::ai_testing_common {
namespace shardok {
namespace ai_testing_common {
auto GameSettingsFactory::CreateDefault() -> GameSettingsSPtr {
auto settings = std::make_shared<GameSettings>();
@@ -30,4 +31,5 @@ auto GameSettingsFactory::CreateDefault() -> GameSettingsSPtr {
return settings;
}
} // namespace shardok::ai_testing_common
} // namespace ai_testing_common
} // namespace shardok
@@ -10,7 +10,8 @@
#include "src/main/cpp/net/eagle0/shardok/library/settings/GameSettings.hpp"
namespace shardok::ai_testing_common {
namespace shardok {
namespace ai_testing_common {
/**
* Factory class for creating GameSettings instances with standard configuration.
@@ -29,9 +30,10 @@ public:
*
* @return Shared pointer to initialized GameSettings
*/
[[nodiscard]] static auto CreateDefault() -> GameSettingsSPtr;
static auto CreateDefault() -> GameSettingsSPtr;
};
} // namespace shardok::ai_testing_common
} // namespace ai_testing_common
} // namespace shardok
#endif // EAGLE0_SHARDOK_AI_TESTING_COMMON_GAME_SETTINGS_FACTORY_HPP
@@ -14,7 +14,6 @@
#include <iostream>
#include <iterator>
#include <ranges>
#include <sstream>
#include <string>
#include <thread>
@@ -28,77 +27,6 @@ using net::eagle0::common::ScopedShardokLatencyTrace;
using net::eagle0::shardok::common::GameStatus;
namespace {
[[nodiscard]] auto DescribeCommandForLog(const CommandSPtr &command) -> std::string {
if (!command) { return "<null command>"; }
std::ostringstream out;
out << "type=" << command->GetCommandType()
<< " player=" << static_cast<int>(command->GetPlayerId())
<< " actor=" << command->GetActorUnitId() << " target=("
<< static_cast<int>(command->GetTargetRow()) << ','
<< static_cast<int>(command->GetTargetColumn()) << ')';
if (command->HasOdds()) { out << " odds_percentile=" << command->GetOddsPercentile(); }
try {
out << " proto={" << command->GetCommandProto().ShortDebugString() << '}';
} catch (const std::exception &e) { out << " proto_error={" << e.what() << '}'; }
return out.str();
}
[[nodiscard]] auto DescribeCommandsForLog(const CommandList &commands) -> std::string {
std::ostringstream out;
out << "available_command_count=" << commands.size();
for (size_t i = 0; i < commands.size(); ++i) {
out << "\n [" << i << "] " << DescribeCommandForLog(commands[i]);
}
return out.str();
}
[[nodiscard]] auto DescribeCurrentStateForLog(const ShardokEngine &engine) -> std::string {
const auto *state = engine.GetCurrentGameState().Get();
if (state == nullptr) { return "state=<null>"; }
const auto vectorSize = [](const auto *vector) -> size_t {
return vector == nullptr ? 0 : vector->size();
};
std::ostringstream out;
out << "state={round=" << static_cast<int>(state->current_round())
<< " current_player=" << static_cast<int>(state->current_player())
<< " history_count=" << engine.GetUnfilteredHistoryCount();
if (const auto *status = state->status(); status != nullptr) {
out << " status=" << static_cast<int>(status->state()) << " end_condition=";
if (const auto *endCondition = status->end_game_condition(); endCondition != nullptr) {
out << "{type=" << static_cast<int>(endCondition->victory_type())
<< " victory_details=" << static_cast<int>(endCondition->victory_details())
<< " draw_details=" << static_cast<int>(endCondition->draw_details()) << '}';
} else {
out << "<null>";
}
} else {
out << " status=<null>";
}
out << " units=" << vectorSize(state->units())
<< " player_infos=" << vectorSize(state->player_infos());
if (const auto *hexMap = state->hex_map(); hexMap != nullptr) {
out << " map=" << hexMap->row_count() << 'x' << hexMap->column_count();
} else {
out << " map=<null>";
}
out << '}';
return out.str();
}
} // namespace
class InvalidTokenException : public std::exception {};
class MismatchedPlayerIdException : public std::exception {
@@ -226,8 +154,6 @@ void ShardokGameController::DoAIThread() {
continue;
}
std::string aiPhase = "choosing command";
int64_t chosenIndex = -1;
try {
// Phase 2: AI thinks (NO LOCK - this is the slow part)
auto results = [&] {
@@ -239,7 +165,6 @@ void ShardokGameController::DoAIThread() {
{"available_command_count", std::to_string(availableCommands->size())}});
return aiClient->ChooseCommandIndex(settings, gsv, availableCommands);
}();
chosenIndex = results.chosenIndex;
// Phase 3: Post the command (brief lock)
{
@@ -258,7 +183,6 @@ void ShardokGameController::DoAIThread() {
}
{
aiPhase = "posting chosen command";
ScopedShardokLatencyTrace trace(
"ai_engine_post_command",
cachedGameId,
@@ -269,7 +193,6 @@ void ShardokGameController::DoAIThread() {
}
LockedNotifyClients();
{
aiPhase = "posting forced follow-up commands";
ScopedShardokLatencyTrace trace(
"ai_engine_post_forced_commands",
cachedGameId,
@@ -281,32 +204,16 @@ void ShardokGameController::DoAIThread() {
aiThreadKeepGoing = !engine->GameIsOver();
}
} catch (const std::exception &e) {
std::ostringstream error;
error << "AI error in game " << cachedGameId << ", player " << playerId << ", round "
<< gsv.current_round() << ": " << e.what();
std::ostringstream context;
context << "AI failure context: phase=" << aiPhase
<< ", expected_history_count=" << expectedHistoryCount
<< ", current_history_count=" << engine->GetUnfilteredHistoryCount()
<< ", chosen_index=" << chosenIndex
<< ", current_player=" << static_cast<int>(engine->GetCurrentPlayerId()) << ", "
<< DescribeCurrentStateForLog(*engine);
const std::string commandsContext = availableCommands
? DescribeCommandsForLog(*availableCommands)
: "available_command_count=<cleared>";
std::cerr << "AI thread exception in game " << cachedGameId << ", player " << playerId
<< ", round " << gsv.current_round() << ": " << e.what() << '\n';
std::cerr << context.str() << '\n';
std::cerr << commandsContext << '\n';
void *backtraceArray[20];
const int backtraceSize = backtrace(backtraceArray, 20);
backtrace_symbols_fd(backtraceArray, backtraceSize, STDERR_FILENO);
aiThreadErrorMessage = error.str() + "\n" + context.str() + "\n" + commandsContext;
aiThreadErrorMessage = "AI error in game " + cachedGameId + ", player " +
std::to_string(playerId) + ", round " +
std::to_string(gsv.current_round()) + ": " + e.what();
aiThreadFailed.store(true);
updateCondition.notify_all();
break;
@@ -32,8 +32,9 @@ private:
static auto CannotBecomeOutlaw(const GameStateW &gameState, PlayerId pid) -> bool {
if (pid == UNCONTROLLED_PLAYER_ID) return false;
const auto &player = std::ranges::find_if(
*gameState->player_infos(),
const auto &player = std::find_if(
std::begin(*gameState->player_infos()),
std::end(*gameState->player_infos()),
[pid](const PlayerInfoFb *pi) { return pi->player_id() == pid; });
return (player != std::end(*gameState->player_infos()) && player->cannot_become_outlaw());
@@ -42,8 +43,9 @@ private:
static auto IsAttacker(const GameStateW &gameState, PlayerId pid) -> bool {
if (pid == UNCONTROLLED_PLAYER_ID) return false;
const auto &player = std::ranges::find_if(
*gameState->player_infos(),
const auto &player = std::find_if(
std::begin(*gameState->player_infos()),
std::end(*gameState->player_infos()),
[pid](const PlayerInfoFb *pi) { return pi->player_id() == pid; });
return (player == std::end(*gameState->player_infos()) || !player->is_defender());
@@ -189,13 +189,12 @@ struct BattalionType {
}
[[nodiscard]] auto GetCostToEnterTerrain(const TerrainProto &terrain) const -> ActionCost {
if (HasBridge(terrain.modifier()) && terrain.modifier().bridge().has_integrity() &&
terrain.modifier().bridge().integrity().value() > 0.0) {
return {ActionCost::standard,
if (HasBridge(terrain.modifier()))
return ActionCost(
ActionCost::standard,
ActionPoints(std::ceil(
100.0 * minimumCostToEnterBridge /
terrain.modifier().bridge().integrity().value()))};
}
terrain.modifier().bridge().integrity().value())));
if (IsFrozen(terrain.modifier())) return costToEnterIce;
auto terrainCost = GetCostToEnterTerrainType(terrain.type());
@@ -209,11 +208,11 @@ struct BattalionType {
[[nodiscard]] auto GetCostToEnterTerrain(
const net::eagle0::shardok::storage::fb::Terrain_::Type terrainType,
const net::eagle0::shardok::storage::fb::TileModifier &tm) const -> ActionCost {
if (tm.bridge().present() && tm.bridge().integrity() > 0.0) {
return {ActionCost::standard,
if (tm.bridge().present())
return ActionCost(
ActionCost::standard,
ActionPoints(
std::ceil(100.0 * minimumCostToEnterBridge / tm.bridge().integrity()))};
}
std::ceil(100.0 * minimumCostToEnterBridge / tm.bridge().integrity())));
if (tm.ice().present()) return costToEnterIce;
auto terrainCost = GetCostToEnterTerrainType(terrainType);
@@ -44,7 +44,7 @@ inline constexpr DamageType DamageType_aessence = DamageType::DamageType_aessenc
inline constexpr DamageType DamageType_impact = DamageType::DamageType_impact;
inline constexpr int NUM_DAMAGE_TYPES = static_cast<int>(DamageType::NUM_DAMAGE_TYPES);
[[nodiscard]] static inline bool DamageTypeGetsTerrainDefense(const DamageType type) {
static inline bool DamageTypeGetsTerrainDefense(const DamageType type) {
switch (type) {
case DamageType_slashing:
case DamageType_puncturing:
@@ -132,13 +132,11 @@ public:
return damageByType.at(PenetratingIndex(type));
};
[[nodiscard]] bool operator==(const CombatDamage& cmpr) const {
return damageByType == cmpr.damageByType;
}
bool operator==(const CombatDamage& cmpr) const { return damageByType == cmpr.damageByType; }
[[nodiscard]] bool operator!=(const CombatDamage& cmpr) const { return !(*this == cmpr); }
bool operator!=(const CombatDamage& cmpr) const { return !(*this == cmpr); }
[[nodiscard]] bool operator<=(const CombatDamage& cmpr) const {
bool operator<=(const CombatDamage& cmpr) const {
return std::ranges::equal(
damageByType,
cmpr.damageByType,
@@ -147,7 +145,7 @@ public:
});
}
[[nodiscard]] bool operator>=(const CombatDamage& cmpr) const {
bool operator>=(const CombatDamage& cmpr) const {
return std::ranges::equal(
damageByType,
cmpr.damageByType,
@@ -156,15 +154,11 @@ public:
});
}
[[nodiscard]] bool operator>(const CombatDamage& cmpr) const {
return ((*this >= cmpr) && !(*this == cmpr));
}
bool operator>(const CombatDamage& cmpr) const { return ((*this >= cmpr) && !(*this == cmpr)); }
[[nodiscard]] bool operator<(const CombatDamage& cmpr) const {
return ((*this <= cmpr) && !(*this == cmpr));
}
bool operator<(const CombatDamage& cmpr) const { return ((*this <= cmpr) && !(*this == cmpr)); }
[[nodiscard]] CombatDamage operator+(const CombatDamage& add) const {
CombatDamage operator+(const CombatDamage& add) const {
return Builder()
.SetSlashing(
GetNormalDamageOfType(DamageType_slashing) +
@@ -225,7 +219,7 @@ public:
.Build();
}
[[nodiscard]] CombatDamage operator*(const double factor) const {
CombatDamage operator*(const double factor) const {
return Builder()
.SetSlashing(GetNormalDamageOfType(DamageType_slashing) * factor)
.SetPuncturing(GetNormalDamageOfType(DamageType_puncturing) * factor)
@@ -448,7 +442,7 @@ public:
[[nodiscard]] auto ToBuilder() const -> Builder {
Builder builder = Builder();
for (int i = 0; i < static_cast<int>(NUM_DAMAGE_TYPES); ++i) {
for (int i = 0; i < static_cast<int>(NUM_DAMAGE_TYPES); i++) {
const auto type = static_cast<DamageType>(i);
builder.SetDamageByType(type, false, this->GetNormalDamageOfType(type));
builder.SetDamageByType(type, true, this->GetPenetratingDamageOfType(type));
@@ -457,9 +451,7 @@ public:
}
};
[[nodiscard]] inline CombatDamage operator*(const double factor, const CombatDamage& dmg) {
return dmg * factor;
}
inline CombatDamage operator*(const double factor, const CombatDamage& dmg) { return dmg * factor; }
} // namespace shardok
#endif // EAGLE0_SHARDOK_LIBRARY_COMBAT_DAMAGE_HPP
@@ -21,23 +21,19 @@ using WeatherFb = net::eagle0::shardok::storage::fb::Weather;
using TerrainProto = net::eagle0::shardok::common::Terrain;
using Terrain = net::eagle0::shardok::storage::fb::Terrain;
[[nodiscard]] auto PropensityByTerrain(const Terrain *terrain, const SettingsGetter &settings)
-> int;
auto PropensityByTerrain(const Terrain *terrain, const SettingsGetter &settings) -> int;
[[nodiscard]] auto PropensityByTerrain(const TerrainProto &terrain, const SettingsGetter &settings)
-> int;
auto PropensityByTerrain(const TerrainProto &terrain, const SettingsGetter &settings) -> int;
[[nodiscard]] auto PropensityByTerrain(
auto PropensityByTerrain(
const TerrainType &terrainType,
const TileModifierProto &modifier,
const SettingsGetter &settings) -> int;
[[nodiscard]] auto GetFireDamage(
int troops,
double openEndedPercentileRoll1,
double openEndedPercentileRoll2) -> CombatDamage;
auto GetFireDamage(int troops, double openEndedPercentileRoll1, double openEndedPercentileRoll2)
-> CombatDamage;
[[nodiscard]] auto GetExtinguishOdds(
auto GetExtinguishOdds(
const SettingsGetter &settings,
const Terrain *terrain,
const WeatherFb *currentWeather,
@@ -45,7 +41,7 @@ using Terrain = net::eagle0::shardok::storage::fb::Terrain;
double intelligence,
bool ownTile) -> PercentileRollOdds;
[[nodiscard]] auto GetStartFireOdds(
auto GetStartFireOdds(
const SettingsGetter &settings,
const Terrain &terrain,
const WeatherFb &currentWeather,
@@ -36,19 +36,25 @@ public:
using BaseType::BaseType;
// Default constructor
GameStateW() = default;
GameStateW() : BaseType() {}
// Copy constructor
GameStateW(const GameStateW& other) = default;
GameStateW(const GameStateW& other) : BaseType(other) {}
// Move constructor
GameStateW(GameStateW&& other) noexcept = default;
GameStateW(GameStateW&& other) noexcept : BaseType(std::move(other)) {}
// Copy assignment
GameStateW& operator=(const GameStateW& other) = default;
GameStateW& operator=(const GameStateW& other) {
BaseType::operator=(other);
return *this;
}
// Move assignment
GameStateW& operator=(GameStateW&& other) noexcept = default;
GameStateW& operator=(GameStateW&& other) noexcept {
BaseType::operator=(std::move(other));
return *this;
}
// Constructor from base type
GameStateW(const BaseType& base) : BaseType(base) {}
@@ -22,13 +22,13 @@ namespace shardok {
using PercentileRollOdds = net::eagle0::shardok::storage::Odds;
using OtherFactor = net::eagle0::shardok::storage::Odds_OtherFactor;
[[nodiscard]] double BonusFromStat(double stat);
double BonusFromStat(double stat);
[[nodiscard]] int16_t AverageBonusFromStats(const std::vector<double> &stats);
int16_t AverageBonusFromStats(const std::vector<double> &stats);
[[nodiscard]] OtherFactor MakeOtherFactor(int value, const std::string &id);
OtherFactor MakeOtherFactor(int value, const std::string &id);
[[nodiscard]] PercentileRollOdds MakeOdds(
PercentileRollOdds MakeOdds(
int base = 0,
int terr = 0,
int weath = 0,
@@ -36,7 +36,7 @@ using OtherFactor = net::eagle0::shardok::storage::Odds_OtherFactor;
int statF = 0,
std::span<const OtherFactor> others = {});
[[nodiscard]] PercentileRollOdds MakeOdds(
PercentileRollOdds MakeOdds(
int base,
int terr,
int weath,
@@ -44,11 +44,11 @@ using OtherFactor = net::eagle0::shardok::storage::Odds_OtherFactor;
const std::vector<double> &stats,
std::span<const OtherFactor> others = {});
[[nodiscard]] int16_t GetTotalOdds(const PercentileRollOdds &odds);
int16_t GetTotalOdds(const PercentileRollOdds &odds);
[[nodiscard]] bool PercentileRollSucceeds(const PercentileRollOdds &odds, double roll);
bool PercentileRollSucceeds(const PercentileRollOdds &odds, double roll);
[[nodiscard]] int16_t GetSuccessChance(const PercentileRollOdds &odds);
int16_t GetSuccessChance(const PercentileRollOdds &odds);
} // namespace shardok
#endif // EAGLE0_SHARDOK_LIBRARY_PERCENTILE_ROLL_ODDS_HPP
@@ -42,7 +42,7 @@ private:
[[nodiscard]] virtual auto InternalExecute(
const GameStateW& currentState,
const std::shared_ptr<RandomGenerator>& generator) const -> std::vector<ActionResult> {
return InternalExecuteWithRoll(currentState, generator, std::nullopt);
return InternalExecuteWithRoll(currentState, generator, std::optional<int32_t>());
}
[[nodiscard]] virtual auto InternalExecuteWithRoll(
@@ -140,12 +140,7 @@ ShardokEngine::ShardokEngine(const ShardokEngine &toCopy, const bool trackHistor
gameState(toCopy.gameState),
trackHistory(trackHistory),
startingHistoryCount(toCopy.startingHistoryCount),
startingHistoryState(trackHistory ? toCopy.startingHistoryState : GameStateW{}),
actionHistory(
trackHistory ? toCopy.actionHistory : std::vector<ShardokActionWithResultingState>{}),
criticalTileCoords(toCopy.criticalTileCoords),
tutorialController_(toCopy.tutorialController_),
pendingReinforcementPlacement_(toCopy.pendingReinforcementPlacement_),
cachedAvailableCommands(toCopy.cachedAvailableCommands) {}
auto ShardokEngine::GetGameStateAtStartOfAction(const ActionId startingActionId) const
@@ -448,7 +443,7 @@ void ShardokEngine::PostPlacementCommands(
reinforcementPositions);
// first make sure they're all valid and there are no duplicates
for (size_t i = 0; i < placementInfos.size(); ++i) {
for (size_t i = 0; i < placementInfos.size(); i++) {
const UnitPlacementInfo &pi = placementInfos[i];
const auto it = std::ranges::find_if(*placementCommands, [pi](const CommandSPtr &cmd) {
@@ -460,7 +455,7 @@ void ShardokEngine::PostPlacementCommands(
}
// check that we're not double-filling any location or double-placing any unit
for (size_t j = i + 1; j < placementInfos.size(); ++j) {
for (size_t j = i + 1; j < placementInfos.size(); j++) {
const UnitPlacementInfo &other = placementInfos[j];
if (pi.unitId == other.unitId)
@@ -723,8 +718,8 @@ auto SecuredByPlayerByUnitIdFromHistory(
continue;
}
if (!resolvedUnit.has_secured_by_player()) { continue; }
const auto unit = UnitFromBytes(resolvedUnit.unit_bytes());
securedByPlayerByUnitId[unit.unit_id()] = resolvedUnit.secured_by_player().value();
const auto *unit = reinterpret_cast<const Unit *>(resolvedUnit.unit_bytes().data());
securedByPlayerByUnitId[unit->unit_id()] = resolvedUnit.secured_by_player().value();
}
}
return securedByPlayerByUnitId;
@@ -31,7 +31,7 @@ auto ActionPointDistances::BraveWaterPossibleCoords(const HexMap* hexMap) const
const int indexCount = hexMap->row_count() * hexMap->column_count();
info->details.reserve(indexCount);
const auto indexToCoords = CreateIndexToCoords(hexMap);
for (int i = 0; i < indexCount; ++i) {
for (int i = 0; i < indexCount; i++) {
if (const Terrain* terrain = hexMap->terrain()->Get(i);
IsWater(terrain->type()) && !terrain->modifier().bridge().present() &&
!terrain->modifier().ice().present()) {
@@ -71,7 +71,7 @@ auto ActionPointDistances::CreateIndexToCoords(const HexMap* hexMap) -> std::vec
const int indexCount = hexMap->row_count() * columnCount;
std::vector<Coords> indexToCoords;
indexToCoords.reserve(indexCount);
for (int i = 0; i < indexCount; ++i) {
for (int i = 0; i < indexCount; i++) {
indexToCoords.emplace_back(
static_cast<int8_t>(i / columnCount),
static_cast<int8_t>(i % columnCount));
@@ -85,7 +85,7 @@ auto ActionPointDistances::CreateAdjacencyTable(const HexMap* hexMap)
const int indexCount = hexMap->row_count() * columnCount;
std::vector<std::array<int, 6>> adjacencyTable;
adjacencyTable.reserve(indexCount);
for (int i = 0; i < indexCount; ++i) {
for (int i = 0; i < indexCount; i++) {
const Coords coords(
static_cast<int8_t>(i / columnCount),
static_cast<int8_t>(i % columnCount));
@@ -119,7 +119,7 @@ void ActionPointDistances::PopulateOne(
// Find starting index (the one with distance 0)
const int distanceCount = static_cast<int>(ds.size());
for (int i = 0; i < distanceCount; ++i) {
for (int i = 0; i < distanceCount; i++) {
if (ds[i] == 0) {
pq.emplace(0, i);
break;
@@ -141,7 +141,7 @@ void ActionPointDistances::PopulateOne(
// Prefetch terrain data for all neighbors to reduce memory stalls
const std::array<int, 6>& neighbors = adjacencyTable[currentIndex];
for (int i = 0; i < 6 && neighbors[i] != -1; ++i) {
for (int i = 0; i < 6 && neighbors[i] != -1; i++) {
__builtin_prefetch(hexMap->terrain()->Get(neighbors[i]), 0, 3);
}
@@ -243,7 +243,7 @@ OnDemandActionPointDistances::OnDemandActionPointDistances(
auto braveWaterPossibleCoords = includeBravingWater ? BraveWaterPossibleCoords(map) : nullptr;
for (int fromIndex = 0; fromIndex < indexCount; ++fromIndex) {
for (int fromIndex = 0; fromIndex < indexCount; fromIndex++) {
distances[fromIndex] = std::async(
std::launch::deferred,
&OnDemandActionPointDistances::GenerateDistances,
@@ -43,7 +43,7 @@ protected:
const std::shared_ptr<BraveableTileInfo> &braveWaterPossibleCoords,
const std::vector<Coords> &indexToCoords,
const std::vector<std::array<int, 6>> &adjacencyTable);
[[nodiscard]] static auto GenerateDistances(
static auto GenerateDistances(
int fromIndex,
const HexMap *hexMap,
bool includeBravingWater,
@@ -51,15 +51,13 @@ protected:
const BattalionTypeSPtr &battalionType,
const std::shared_ptr<BraveableTileInfo> &braveWaterPossibleCoords)
-> std::vector<DIST_T>;
[[nodiscard]] auto BraveWaterPossibleCoords(const HexMap *hexMap) const
-> std::shared_ptr<BraveableTileInfo>;
auto BraveWaterPossibleCoords(const HexMap *hexMap) const -> std::shared_ptr<BraveableTileInfo>;
// Create coordinate lookup table for efficient index->coords conversion
[[nodiscard]] static auto CreateIndexToCoords(const HexMap *hexMap) -> std::vector<Coords>;
static auto CreateIndexToCoords(const HexMap *hexMap) -> std::vector<Coords>;
// Create adjacency lookup table for efficient neighbor access
[[nodiscard]] static auto CreateAdjacencyTable(const HexMap *hexMap)
-> std::vector<std::array<int, 6>>;
static auto CreateAdjacencyTable(const HexMap *hexMap) -> std::vector<std::array<int, 6>>;
[[nodiscard]] auto ToIndex(const Coords &coords) const -> int {
return coords.row() * column_count + coords.column();
@@ -72,9 +70,9 @@ public:
virtual ~ActionPointDistances() = default;
[[nodiscard]] virtual auto Distance(int fromIndex, int toIndex) const -> DIST_T = 0;
virtual auto Distance(int fromIndex, int toIndex) const -> DIST_T = 0;
[[nodiscard]] virtual auto Distance(const Coords &from, const Coords &to) const -> DIST_T = 0;
virtual auto Distance(const Coords &from, const Coords &to) const -> DIST_T = 0;
};
class OnDemandActionPointDistances final : public ActionPointDistances {
@@ -93,11 +91,11 @@ public:
~OnDemandActionPointDistances() override = default;
[[nodiscard]] auto Distance(const int fromIndex, const int toIndex) const -> int16_t override {
auto Distance(const int fromIndex, const int toIndex) const -> int16_t override {
return distances[fromIndex].get()[toIndex];
}
[[nodiscard]] auto Distance(const Coords &from, const Coords &to) const -> int16_t override {
auto Distance(const Coords &from, const Coords &to) const -> int16_t override {
return Distance(ToIndex(from), ToIndex(to));
}
};
@@ -77,7 +77,7 @@ static auto CreateIceClearedMap(const HexMap* map) -> fb::HexMapW {
auto* mutableMap = mapCopy.Get();
auto* terrainVec = mutableMap->mutable_terrain();
for (size_t i = 0; i < terrainVec->size(); ++i) {
for (size_t i = 0; i < terrainVec->size(); i++) {
// Only process tiles with ice
// const_cast is safe here because we own the mutable buffer (mapCopy)
if (auto* terrain = const_cast<Terrain*>(terrainVec->GetMutableObject(i));
@@ -22,7 +22,7 @@ struct MapId {
uint64_t terrainTypesId;
uint64_t modifierId;
[[nodiscard]] auto operator==(const MapId& other) const -> bool {
auto operator==(const MapId& other) const -> bool {
return terrainTypesId == other.terrainTypesId && modifierId == other.modifierId;
}
};
@@ -34,7 +34,7 @@ struct FullCacheKey {
bool includeBravingWater;
int braveWaterCost;
[[nodiscard]] bool operator==(const FullCacheKey& other) const {
bool operator==(const FullCacheKey& other) const {
return mapId == other.mapId && battalionTypeId == other.battalionTypeId &&
includeBravingWater == other.includeBravingWater &&
braveWaterCost == other.braveWaterCost;
@@ -43,7 +43,7 @@ struct FullCacheKey {
// Hash function for FullCacheKey
struct FullCacheKeyHash {
[[nodiscard]] size_t operator()(const FullCacheKey& key) const {
size_t operator()(const FullCacheKey& key) const {
// Pack small fields into a single 64-bit value
uint64_t packed = (static_cast<uint64_t>(key.battalionTypeId) << 32) |
(static_cast<uint64_t>(key.braveWaterCost) << 1) |
@@ -85,7 +85,7 @@ private:
// Epoch system removed - TLS cache uses size-based eviction instead
// Helper to build cache key
[[nodiscard]] static auto MakeCacheKey(
static auto MakeCacheKey(
const MapId& mapId,
const BattalionTypeSPtr& battalionType,
bool includeBravingWater,
@@ -107,7 +107,7 @@ public:
bool includeBravingWater,
int braveWaterActionPointCost = -1) -> const ActionPointDistances*;
[[nodiscard]] static auto GetMapId(const HexMap* map) -> MapId;
static auto GetMapId(const HexMap* map) -> MapId;
// Consolidate the thread-safe cache into the persistent cache and clear
// the current thread's local cache. This is only safe if we know reads
@@ -116,7 +116,7 @@ public:
// Cache management methods
static void ClearThreadLocalCache();
[[nodiscard]] static size_t GetThreadLocalCacheSize();
static size_t GetThreadLocalCacheSize();
};
using APDCache = std::shared_ptr<ActionPointDistancesCache>;
@@ -42,13 +42,13 @@ auto FixedActionPointDistances::Create(
int chunkSize = (indexCount + ASYNC_COUNT - 1) / ASYNC_COUNT;
// Break into chunks for async
for (int chunkIdx = 0; chunkIdx < ASYNC_COUNT; ++chunkIdx) {
for (int chunkIdx = 0; chunkIdx < ASYNC_COUNT; chunkIdx++) {
futures[chunkIdx] = std::async(std::launch::async, [=]() -> vector<vector<DIST_T>> {
vector<vector<DIST_T>> chunkVec;
chunkVec.reserve(chunkSize);
const int chunkStartIndex = chunkIdx * chunkSize;
for (int i = 0; i < chunkSize; ++i) {
for (int i = 0; i < chunkSize; i++) {
const auto fromIndex = chunkStartIndex + i;
if (fromIndex >= indexCount) { continue; }
chunkVec.push_back(ActionPointDistances::GenerateDistances(
@@ -65,7 +65,7 @@ auto FixedActionPointDistances::Create(
apd->distances.reserve(indexCount);
for (int chunkIdx = 0; chunkIdx < ASYNC_COUNT; ++chunkIdx) {
for (int chunkIdx = 0; chunkIdx < ASYNC_COUNT; chunkIdx++) {
auto resultsVec = futures[chunkIdx].get();
apd->distances.insert(apd->distances.end(), resultsVec.begin(), resultsVec.end());
}
@@ -24,7 +24,7 @@ private:
public:
// Factory method to create FixedActionPointDistances
[[nodiscard]] static auto Create(
static auto Create(
const HexMap *map,
const BattalionTypeSPtr &battalionType,
bool includeBravingWater,
@@ -14,7 +14,6 @@
#include "src/main/cpp/net/eagle0/shardok/library/action_result_applier/UnitHelpers.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/map/HexMapHasher.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/unit/Unit.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/util/ActionResultFlatbufferHelpers.hpp"
#include "src/main/cpp/net/eagle0/shardok/library/util/HexMapUtils.hpp"
#include "src/main/flatbuffer/net/eagle0/shardok/storage/game_state.hpp"
@@ -31,6 +30,10 @@ inline auto GetMutableUnit(GameState *state, UnitId unitId) -> Unit * {
return const_cast<Unit *>(state->mutable_units()->GetMutableObject(unitId));
}
inline auto UnitFromBytes(const std::string &unitBytes) -> const Unit & {
return *reinterpret_cast<const Unit *>(unitBytes.data());
}
using net::eagle0::shardok::storage::fb::VictoryCondition;
using net::eagle0::shardok::storage::fb::VictoryType;
@@ -65,7 +68,7 @@ void ApplyResolvedUnit(
// If a VIP was captured, alter the morale of all this player's units
if (status == net::eagle0::shardok::storage::fb::UnitStatus_CAPTURED_UNIT &&
unit.has_attached_hero() && unit.attached_hero().is_vip()) {
for (uint32_t i = 0; i < inoutState->units()->size(); ++i) {
for (uint32_t i = 0; i < inoutState->units()->size(); i++) {
auto *playerUnit = GetMutableUnit(inoutState, i);
if (playerUnit->player_id() != unit.player_id()) continue;
if (playerUnit->unit_id() == unit.unit_id()) continue;
@@ -98,7 +101,7 @@ void ApplyResolvedUnit(
GameStateT &inoutState,
const ResolvedUnitProto &resolvedUnit,
const double vipCapturedMoraleAdjustment) {
const Unit unit = UnitFromBytes(resolvedUnit.unit_bytes());
const Unit &unit = UnitFromBytes(resolvedUnit.unit_bytes());
UnitId unitId = unit.unit_id();
if (unit.has_attached_hero() &&
@@ -166,15 +169,15 @@ void MutatingAddUnits(GameStateW &mutatingState, const ActionResultProto &result
// First pass: check what kind of modifications we need
for (const auto &unitBytes : result.changed_units_fb()) {
const auto unit = UnitFromBytes(unitBytes);
maxChangedUnitId = std::max(maxChangedUnitId, unit.unit_id());
const auto *unit = &UnitFromBytes(unitBytes);
maxChangedUnitId = std::max(maxChangedUnitId, unit->unit_id());
if (static_cast<unsigned int>(unit.unit_id()) >= mutatingState->units()->size()) {
if (static_cast<unsigned int>(unit->unit_id()) >= mutatingState->units()->size()) {
// Unit ID beyond vector size - must expand
needsVectorExpansion = true;
break; // No point checking further
} else if (
mutatingState->units()->Get(unit.unit_id())->status() ==
mutatingState->units()->Get(unit->unit_id())->status() ==
net::eagle0::shardok::storage::fb::UnitStatus_RESERVED_SLOT) {
// Unit wants to use a reserved slot
needsReservedSlotConversion = true;
@@ -196,8 +199,8 @@ void MutatingAddUnits(GameStateW &mutatingState, const ActionResultProto &result
// Convert reserved slots to real units in place
// We only need to process the units that are being changed
for (const auto &unitBytes : result.changed_units_fb()) {
const auto unit = UnitFromBytes(unitBytes);
auto *mutableUnit = GetMutableUnit(mutatingState.Get(), unit.unit_id());
const auto *unit = &UnitFromBytes(unitBytes);
auto *mutableUnit = GetMutableUnit(mutatingState.Get(), unit->unit_id());
if (mutableUnit->status() ==
net::eagle0::shardok::storage::fb::UnitStatus_RESERVED_SLOT) {
// Convert this reserved slot to a real unit
@@ -245,12 +248,12 @@ void MutatingApplyResult(
static_cast<net::eagle0::shardok::storage::fb::GameStatus_::State>(
result.game_status().state())));
const int winningShardokIdCount = result.game_status().winning_shardok_ids_size();
for (int i = 0; i < winningShardokIdCount; ++i) {
for (int i = 0; i < winningShardokIdCount; i++) {
mutatingGameState->mutable_status()->mutable_winning_shardok_ids()->Mutate(
i,
result.game_status().winning_shardok_ids(i));
}
for (int i = winningShardokIdCount; i < 10; ++i) {
for (int i = winningShardokIdCount; i < 10; i++) {
mutatingGameState->mutable_status()->mutable_winning_shardok_ids()->Mutate(i, -1);
}
@@ -296,48 +299,51 @@ void MutatingApplyResult(
const double vipCapturedMoraleAdjustment = settings.Backing().vip_captured_morale_adjustment();
for (const auto &changedUnitBytes : result.changed_units_fb()) {
const Unit changedUnit = UnitFromBytes(changedUnitBytes);
const Unit *changedUnit = &UnitFromBytes(changedUnitBytes);
internalAssert(
changedUnit.unit_id() < static_cast<int32_t>(mutatingGameState->units()->size()),
changedUnit->unit_id() < static_cast<int32_t>(mutatingGameState->units()->size()),
"Got a changed unit outside acceptable range");
const auto battalionSizeAfter = changedUnit.battalion().size();
const auto battalionSizeAfter = changedUnit->battalion().size();
const int battalionSizeBefore =
(changedUnit.unit_id() < static_cast<int32_t>(initialUnitCount))
? mutatingGameState->units()->Get(changedUnit.unit_id())->battalion().size()
: changedUnit.battalion().size();
(changedUnit->unit_id() < static_cast<int32_t>(initialUnitCount))
? mutatingGameState->units()
->Get(changedUnit->unit_id())
->battalion()
.size()
: changedUnit->battalion().size();
auto status = changedUnit.status();
if (IsDestroyed(changedUnit)) {
auto status = changedUnit->status();
if (IsDestroyed(*changedUnit)) {
status =
changedUnit.has_attached_hero()
changedUnit->has_attached_hero()
? net::eagle0::shardok::storage::fb::UnitStatus_CAPTURED_UNIT
: net::eagle0::shardok::storage::fb::UnitStatus_DESTROYED_SUMMONED_UNIT;
ApplyResolvedUnit(
mutatingGameState.Get(),
changedUnit,
*changedUnit,
status,
vipCapturedMoraleAdjustment,
settings);
}
// Capture old position before applying changes
auto *mutableUnit = GetMutableUnit(mutatingGameState.Get(), changedUnit.unit_id());
auto *mutableUnit = GetMutableUnit(mutatingGameState.Get(), changedUnit->unit_id());
const auto oldLocation = mutableUnit->location();
fb::ApplyUnit(mutableUnit, &changedUnit, status);
fb::ApplyUnit(mutableUnit, changedUnit, status);
// Update occupied tiles bitfield if position changed
const auto &newLocation = changedUnit.location();
const auto &newLocation = changedUnit->location();
if (oldLocation.row() != newLocation.row() ||
oldLocation.column() != newLocation.column()) {
mutatingGameState.UpdateOccupiedTile(oldLocation, newLocation);
}
if (battalionSizeBefore != battalionSizeAfter) {
if (changedUnit.battalion().type() ==
if (changedUnit->battalion().type() ==
net::eagle0::shardok::storage::fb::BattalionTypeId_UNDEAD) {
if (battalionSizeAfter > battalionSizeBefore) {
// Undead consumed some bodies
@@ -349,7 +355,7 @@ void MutatingApplyResult(
if (battalionSizeAfter > battalionSizeBefore) {
std::ostringstream stringStream;
stringStream << "Battalion got larger! Was " << battalionSizeBefore << ", now "
<< &changedUnit << " result was " << result.DebugString();
<< changedUnit << " result was " << result.DebugString();
throw ShardokInternalErrorException(stringStream.str());
}
@@ -359,7 +365,7 @@ void MutatingApplyResult(
if (newCount != 0) {
newArmament =
(mutatingGameState->dead_count() * mutatingGameState->dead_armament() +
casualties * changedUnit.battalion().armament()) /
casualties * changedUnit->battalion().armament()) /
newCount;
}
@@ -379,10 +385,10 @@ void MutatingApplyResult(
internalAssert(mutatingGameState->mutate_eligible_charger_id(-1));
}
const int possibleChargeeCount = result.possible_chargees_size();
for (int i = 0; i < possibleChargeeCount; ++i) {
for (int i = 0; i < possibleChargeeCount; i++) {
mutatingGameState->mutable_possible_chargee_ids()->Mutate(i, result.possible_chargees(i));
}
for (int i = possibleChargeeCount; i < 6; ++i) {
for (int i = possibleChargeeCount; i < 6; i++) {
mutatingGameState->mutable_possible_chargee_ids()->Mutate(i, -1);
}
@@ -23,11 +23,11 @@ void MutatingApplyResult(
GameStateW& mutatingGameState,
const ActionResultProto& actionResult,
const SettingsGetter& settings);
[[nodiscard]] auto ApplyResult(
auto ApplyResult(
GameStateW startingState,
const ActionResultProto& actionResult,
const SettingsGetter& settings) -> GameStateW;
[[nodiscard]] auto ApplyResults(
auto ApplyResults(
const GameStateW& startingState,
const std::vector<ActionResultProto>& actionResults,
const SettingsGetter& settings) -> GameStateW;
@@ -16,7 +16,6 @@ cc_library(
"//src/main/cpp/net/eagle0/shardok/library:game_state_w",
"//src/main/cpp/net/eagle0/shardok/library/map:hex_map_hasher",
"//src/main/cpp/net/eagle0/shardok/library/unit",
"//src/main/cpp/net/eagle0/shardok/library/util:action_result_flatbuffer_helpers",
"//src/main/cpp/net/eagle0/shardok/library/util:hex_map_utils",
"//src/main/protobuf/net/eagle0/shardok/storage:action_result_cc_proto",
],
@@ -19,7 +19,7 @@ auto CopyWithExtraUnits(const GameStateW& original, int additionalCount) -> Game
// Add the requested units plus some extra slack for future use
int extraSlack = std::max(5, additionalCount * 2);
for (int i = 0; i < additionalCount + extraSlack; ++i) {
for (int i = 0; i < additionalCount + extraSlack; i++) {
Unit unit;
unit.mutate_unit_id(static_cast<int16_t>(endGST.units.size()));
if (i < additionalCount) {
@@ -9,8 +9,7 @@
namespace shardok {
[[nodiscard]] auto CopyWithExtraUnits(const GameStateW& original, int additionalCount)
-> GameStateW;
auto CopyWithExtraUnits(const GameStateW& original, int additionalCount) -> GameStateW;
} // namespace shardok
@@ -8,7 +8,7 @@
namespace shardok::fb {
using net::eagle0::shardok::storage::fb::UnitStatus;
using namespace net::eagle0::shardok::storage::fb;
auto ApplyUnit(
Unit* toUnit,
@@ -17,7 +17,7 @@
#include "src/main/cpp/net/eagle0/shardok/library/util/HexMapUtils.hpp"
namespace shardok {
using net::eagle0::shardok::common::WATER_DAMAGE;
using namespace net::eagle0::shardok::common;
auto EscapeChance(
const int base,
@@ -65,7 +65,7 @@ auto EscapeChance(
}
auto ToVector(const Units &units) -> vector<const Unit *> {
vector<const Unit *> v{};
auto v = vector<const Unit *>{};
v.reserve(units.size());
for (const Unit *u : units) { v.push_back(u); }
return v;
@@ -90,7 +90,7 @@ auto BurnStructuresResult(const GameStateW &gameState, const SettingsGetter &set
*result.mutable_changed_tile_modifiers() = {burnedTmcs.begin(), burnedTmcs.end()};
return result;
} else {
return std::nullopt;
return std::optional<ActionResultProto>();
}
}
@@ -60,8 +60,7 @@ auto StartPlayerTurnAction::InternalExecute(
->Get(startingState->month() - 1)
->is_winter() &&
!inCastle) {
effectiveBase +=
static_cast<float>(settingsGetter.Backing().winter_morale_adjustment());
effectiveBase += float(settingsGetter.Backing().winter_morale_adjustment());
}
float moraleDiff = effectiveBase - updatedUnit.battalion().morale();
MutatingMaybeAdjustMorale(
@@ -34,8 +34,7 @@ auto UndeadChangeAction::InternalExecute(
int growth = newCount - decayedSize;
float newArmament =
static_cast<float>(unit->battalion().armament() * decayedSize + armament * growth) /
newCount;
float(unit->battalion().armament() * decayedSize + armament * growth) / newCount;
auto newUnit = *unit;
newUnit.mutable_battalion().mutate_size(newCount);
@@ -25,9 +25,10 @@ static inline auto GameIsOver(const GameStatusFb* status) -> bool {
}
auto UpdateGameStatusAction::GetPlayerInfo(int playerId) const -> const PlayerInfoFb* {
return *std::ranges::find_if(*gameState->player_infos(), [playerId](const PlayerInfoFb* pi) {
return pi->player_id() == playerId;
});
return *std::find_if(
std::begin(*gameState->player_infos()),
std::end(*gameState->player_infos()),
[playerId](const PlayerInfoFb* pi) { return pi->player_id() == playerId; });
}
static inline auto HasVictoryCondition(const PlayerInfoFb* pi, const VictoryCondition condition)
@@ -29,7 +29,7 @@ auto UpdateOpponentKnowledgeAction::InternalExecute(
auto unitAfter = *unit;
for (PlayerId pid = 0; pid < 10; ++pid) {
for (PlayerId pid = 0; pid < 10; pid++) {
if (pid == unitPid) continue;
if (static_cast<unsigned int>(pid) >= playerCount) continue;
int bump = PlayerIsDefender(currentState, pid) ? defenderKnowledgeGain
@@ -126,7 +126,7 @@ void BraveWaterCommandFactory::AddAvailableBraveWaterCommands(
}
for (const auto &target : braveWaterTargets) {
std::optional<UnitId> ambusher = std::nullopt;
std::optional<UnitId> ambusher = std::optional<UnitId>();
const auto &targetOccupant = Occupant(units, target);
if (targetOccupant) { ambusher = targetOccupant->unit_id(); }
commands.push_back(BraveWaterCommandFactory(settings)
@@ -19,7 +19,7 @@ private:
public:
explicit CommandFactoriesList(const SettingsGetter& settings);
[[nodiscard]] auto GetFactories() const -> std::vector<std::shared_ptr<const CommandFactory>>;
auto GetFactories() const -> std::vector<std::shared_ptr<const CommandFactory>>;
};
} // namespace shardok
@@ -41,7 +41,7 @@ public:
virtual void AddAvailableCommands(CommandList& commands, const CommandParams& params) const = 0;
[[nodiscard]] virtual auto IncludeInFollowUps() const -> bool { return true; }
virtual auto IncludeInFollowUps() const -> bool { return true; }
};
} // namespace shardok
@@ -11,7 +11,7 @@
namespace shardok {
class EvacuatePrisonersCommandFactory : public CommandFactory {
const SettingsGetter settings;
const SettingsGetter& settings;
public:
explicit EvacuatePrisonersCommandFactory(const SettingsGetter& getter);
@@ -27,7 +27,7 @@ void FearCommandFactory::AddAvailableFearCommands(
if (costForFear.IsPossible(remainingActionPoints)) {
const int range = settings.Backing().fear_range();
for (int distance = 1; distance <= range; ++distance) {
for (int distance = 1; distance <= range; distance++) {
const auto coordsSet = TilesWithExactDistance(hexMap, position, distance);
for (const Coords &fearCoords : coordsSet) {
@@ -61,11 +61,9 @@ void FleeCommandFactory::AddAvailableFleeCommands(
const auto *occupant = Occupant(allUnits, twoAwayCoords);
if (occupant && !occupant->hidden()) {
if (std::ranges::contains(allyPids, occupant->player_id())) {
adjacentFriendliesMod +=
static_cast<int32_t>(perAdjacentFriendly * adjustmentForTwoAway);
adjacentFriendliesMod += int32_t(perAdjacentFriendly * adjustmentForTwoAway);
} else {
adjacentEnemiesMod +=
static_cast<int32_t>(perAdjacentEnemy * adjustmentForTwoAway);
adjacentEnemiesMod += int32_t(perAdjacentEnemy * adjustmentForTwoAway);
}
}
}
@@ -46,7 +46,7 @@ auto LightningBoltCommandFactory::AddAvailableLightningBoltCommands(
ActionCost::UsesAllActionCost(settings.Backing().lightning_action_point_cost());
const int lightningRange = settings.Backing().lightning_range();
if (costForLightning.IsPossible(remainingActionPoints)) {
for (int distance = 1; distance <= lightningRange; ++distance) {
for (int distance = 1; distance <= lightningRange; distance++) {
CoordsSet coords = TilesWithExactDistance(hexMap, position, distance);
for (const Coords &lightningCoords : coords) {

Some files were not shown because too many files have changed in this diff Show More