feat(biology): liquid-relative cellular kinematics and the Git tuning file
Foundation / checks (client) (push) Successful in 4s
Foundation / checks (checks) (push) Successful in 4s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 4s
Foundation / checks (tsan) (push) Successful in 4s
Foundation / checks (deploy) (push) Successful in 4m24s
Foundation / postgres-tools (push) Successful in 27s
Foundation / server-image (push) Successful in 4m5s
Foundation / image (push) Successful in 4m17s

Phase 1 of the region and movement plan. Adds the shared integer motion step:
Q10 velocity relative to the liquid, a 16-bit heading with a rate-limited turn,
funded forward/reverse thrust (unfunded thrust coasts), braking, separate forward
and lateral drag that decays to exactly zero, local flow, and a sub-micrometre
carry with no rounding drift. A golden trajectory digest matches across g++-14,
clang-19 and MSVC, so the server and client predictor agree exactly.

Adds deploy/kubernetes/region/dev/tuning/cellular.tuning with every v0 trial value
and a strict parser (unknown, missing, duplicate, out-of-range and inconsistent
values are refused) plus founder handling derived from it. Refreshes the DEV
session window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dingo
2026-10-21 16:30:51 -04:00
co-authored by Claude Opus 5.5
parent 816c83d68f
commit ab5df35c3f
9 changed files with 1242 additions and 2 deletions
+19 -1
View File
@@ -75,7 +75,9 @@ evo_owned_target(evo_accounting)
add_library(evo_biology STATIC
src/biology/genome.cpp src/biology/development.cpp src/biology/metabolism.cpp
src/biology/mutation.cpp src/biology/lineage.cpp src/biology/founder.cpp
src/biology/cellular_motion.cpp src/biology/cellular_uptake.cpp
src/biology/cellular_motion.cpp src/biology/cellular_kinematics.cpp
src/biology/cellular_tuning.cpp
src/biology/cellular_uptake.cpp
src/biology/cellular_habitat.cpp src/biology/cellular_step.cpp
src/biology/cellular_region_step.cpp src/biology/budding.cpp)
add_library(evo::biology ALIAS evo_biology)
@@ -480,6 +482,22 @@ if(BUILD_TESTING)
evo_owned_target(evo-cellular-motion-tests)
add_test(NAME cellular-motion-contracts COMMAND evo-cellular-motion-tests)
set_tests_properties(cellular-motion-contracts PROPERTIES TIMEOUT 60)
add_executable(evo-cellular-kinematics-tests tests/cellular_kinematics_tests.cpp)
target_link_libraries(evo-cellular-kinematics-tests PRIVATE evo::biology)
evo_owned_target(evo-cellular-kinematics-tests)
add_test(NAME cellular-kinematics-contracts COMMAND evo-cellular-kinematics-tests)
set_tests_properties(cellular-kinematics-contracts PROPERTIES TIMEOUT 60)
add_executable(evo-cellular-tuning-tests tests/cellular_tuning_tests.cpp)
target_link_libraries(evo-cellular-tuning-tests PRIVATE evo::biology)
evo_owned_target(evo-cellular-tuning-tests)
# The DEV tuning file is absent from native CI images, which copy no deploy/ tree.
set(evo_dev_tuning "${CMAKE_CURRENT_SOURCE_DIR}/deploy/kubernetes/region/dev/tuning/cellular.tuning")
if(EXISTS "${evo_dev_tuning}")
add_test(NAME cellular-tuning-contracts COMMAND evo-cellular-tuning-tests "${evo_dev_tuning}")
else()
add_test(NAME cellular-tuning-contracts COMMAND evo-cellular-tuning-tests)
endif()
set_tests_properties(cellular-tuning-contracts PROPERTIES TIMEOUT 60)
add_executable(evo-cellular-uptake-tests tests/cellular_uptake_tests.cpp)
target_link_libraries(evo-cellular-uptake-tests PRIVATE evo::biology)
evo_owned_target(evo-cellular-uptake-tests)
@@ -12,7 +12,7 @@ spec:
env:
- {name: REGION_SESSION, value: "dev"}
- {name: REGION_SESSION_LISTEN, value: "0.0.0.0:7400"}
- {name: REGION_SESSION_WINDOW, value: "dev-20261021T200606-ffa8b8ab:1792627566"}
- {name: REGION_SESSION_WINDOW, value: "dev-20261021T202403-5ff7fcb7:1792628643"}
- {name: REGION_M10_MAX_GRANT_LIFETIME, value: "14400"}
ports:
# QUIC (ADR-0090): UDP only; nothing listens on TCP 7400.
@@ -0,0 +1,60 @@
# Cellular trial tuning (Cellular_Region_Movement_Plan.md, tuning file).
# Every value here is a trial value for playtesting, not a locked rule. Edit, commit,
# push and run a full Argo sync; the region refuses an invalid file at startup.
# Format: `key = value`, integers only, `_` may separate digits. Every key is required.
# Region shape (width, height, currents) applies when a region opens; the rest applies
# when the region restarts and is recorded from that tick.
tuning.version = 1
# Region shape and capacity.
region.width_um = 60_000
region.height_um = 60_000
region.organism_cap = 2_000 # births are refused at the cap
region.deposit_limit = 8_192 # food bubbles and pools
region.perception_radius_um = 5_000
# Founder handling. Top speed = thrust / drag rate: about 190 um/s here.
founder.thrust_um_per_s2 = 400
founder.reverse_thrust_um_per_s2 = 400 # braking and reversing
founder.drag_ppm_per_tick = 95_163 # k = 2 /s: 0.5 s time constant
founder.lateral_drag_ppm_per_tick = 95_163
founder.turn_heading_per_s = 65_536 # 65,536 = one full turn per second
# Currents: 0.3x-1.5x founder speed, so the strongest cannot be swum against.
currents.min_count = 2
currents.max_count = 4
currents.min_width_um = 3_000
currents.max_width_um = 6_000
currents.min_speed_um_per_s = 60
currents.max_speed_um_per_s = 300
currents.grid_pitch_um = 250
# Moving food.
food.merged_bubble_cap_multiple = 8 # merged bubbles stop growing at 8x a scattered bubble
food.visible_moving_bubbles = 256 # per update, nearest first
food.induced_drift_radius_um = 200 # passing cells push bubbles within this distance
food.induced_drift_max_um_per_s = 100
food.induced_drift_decay_ppm_per_tick = 95_163
# Thermal map and biology, in millikelvin (273_150 = 0 C).
thermal.ambient_min_mk = 278_150 # 5 C
thermal.ambient_max_mk = 313_150 # 40 C
founder.preferred_mk = 293_150 # 20 C
founder.comfort_band_mk = 5_000 # +/- 5 C without extra cost
founder.body_tau_ms = 20_000 # body temperature lag
founder.lethal_cold_mk = 273_150 # body at or below 0 C dies
founder.lethal_heat_mk = 318_150 # body at or above 45 C dies
thermal.off_preference_per_mille_per_k = 80 # 0.08 per degree beyond the comfort band
thermal.transition_per_mille_per_k = 40 # 0.04 per degree of body-ambient difference
thermal.multiplier_cap_per_mille = 8_000 # survival cost at most 8x
# Lifecycle.
lifecycle.logout_delay_ms = 10_000 # vulnerable delay before the protected anchor
# Mutation offers.
mutation.step_points = 5 # +/- reference points per tuning selection
mutation.paired_points = 2 # paired change on the competing axis
mutation.recovery_floor_per_mille = 100 # weight floor for recovering a below-base trait
mutation.offer_interval_ms = 25_000 # of productive active play
mutation.offer_options = 3
@@ -0,0 +1,87 @@
#pragma once
#include "evo/accounting/ledger.hpp"
#include "evo/biology/cellular_motion.hpp"
#include <compare>
#include <cstdint>
#include <expected>
// Liquid-relative cellular motion (Cellular_movement_draft.md, numeric representation;
// Cellular_Region_Movement_Plan.md phase 1). Integer-only and shared by the region server
// and the client predictor, so both produce identical trajectories.
namespace evo::biology {
// Velocities are Q10: 1/1024 micrometre per second.
inline constexpr std::int64_t cellular_velocity_q10_per_um_s = 1'024;
// Relative or flow velocity components are bounded to +/- 1 m/s, so squared magnitudes fit
// comfortably in 64 bits.
inline constexpr std::int32_t cellular_velocity_limit_q10 = 1'000'000 * 1'024;
// Headings: 65,536 per turn, 0 along +x, counterclockwise.
inline constexpr std::uint32_t cellular_heading_turn = 65'536;
// Sine and cosine are Q14.
inline constexpr std::int32_t cellular_trig_one = 16'384;
// Drag rates are parts per million of velocity per tick, below one whole.
inline constexpr std::uint32_t cellular_drag_ppm_limit = 1'000'000;
// Per-cell motion state persisted with the organism.
struct CellularMotionState {
std::int32_t velocity_x_q10{}, velocity_y_q10{}; // Relative to the liquid.
std::uint16_t heading{};
// Sub-micrometre carry in 1/1024 micrometre-microseconds, below one micrometre.
std::int64_t remainder_x{}, remainder_y{};
auto operator<=>(const CellularMotionState&) const = default;
};
// Local liquid velocity at the cell, sampled by the caller from the region's flow field.
struct CellularFlowSample {
std::int32_t x_q10{}, y_q10{};
auto operator<=>(const CellularFlowSample&) const = default;
};
// An organism's handling, derived from its body; all amounts are per 50 ms tick.
struct CellularHandling {
std::uint32_t thrust_q10{}; // Velocity gained per tick at full forward throttle.
std::uint32_t reverse_thrust_q10{}; // Velocity gained per tick reversing or braking.
std::uint32_t forward_drag_ppm{}, lateral_drag_ppm{};
std::uint16_t turn{}; // Largest heading change per tick.
accounting::Picojoules thrust_cost{}, reverse_cost{}; // At full output for one tick.
auto operator<=>(const CellularHandling&) const = default;
};
// Player or controller command: a direction with throttle (the intent magnitude), or a brake.
// Braking opposes relative velocity and takes precedence over the direction.
struct CellularPropulsion {
CellularIntent direction;
bool brake{};
auto operator<=>(const CellularPropulsion&) const = default;
};
enum class CellularThrustStatus : std::uint8_t { idle, applied, unfunded };
struct CellularKinematicsResult {
CellularPosition position;
CellularMotionState state;
accounting::Picojoules cost{}; // Never more than the energy offered.
CellularThrustStatus thrust{CellularThrustStatus::idle};
std::uint64_t path_um{}; // Conservative straight-line distance travelled.
auto operator<=>(const CellularKinematicsResult&) const = default;
};
enum class CellularKinematicsError : std::uint8_t {
invalid_area,
invalid_extent,
outside_area,
invalid_intent,
invalid_state,
invalid_handling,
invalid_flow
};
[[nodiscard]] std::int32_t cellular_cos_q14(std::uint16_t heading) noexcept;
[[nodiscard]] std::int32_t cellular_sin_q14(std::uint16_t heading) noexcept;
// Integer atan2 (CORDIC); the zero vector returns 0.
[[nodiscard]] std::uint16_t cellular_heading_of(std::int64_t x, std::int64_t y) noexcept;
// One 50 ms tick: turn toward the commanded direction, apply thrust that `available_energy`
// can fund (otherwise none, and the cell coasts), apply drag toward exactly zero, add the
// local flow and carry the displacement. Region edges stop motion into them.
[[nodiscard]] std::expected<CellularKinematicsResult, CellularKinematicsError>
step_cellular_kinematics(CellularArea area, CellularPosition position, std::uint32_t extent_um,
const CellularMotionState& state, CellularPropulsion propulsion,
const CellularHandling& handling, CellularFlowSample flow,
accounting::Picojoules available_energy) noexcept;
} // namespace evo::biology
+81
View File
@@ -0,0 +1,81 @@
#pragma once
#include "evo/biology/cellular_kinematics.hpp"
#include <compare>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <string>
#include <string_view>
// Git-managed trial values (Cellular_Region_Movement_Plan.md, tuning file). The file is
// plain `key = value` lines with `#` comments and integer values; `_` may separate digits.
// Every key below is required exactly once and range-checked, so a typo fails loudly
// instead of running with a default.
namespace evo::biology {
inline constexpr std::int64_t cellular_tuning_version = 1;
inline constexpr std::size_t max_cellular_tuning_bytes = std::size_t{64} * 1'024;
struct CellularTuning {
std::int64_t version{};
// Region shape and capacity; shape applies when a region opens.
std::int64_t region_width_um{}, region_height_um{};
std::int64_t region_organism_cap{}, region_deposit_limit{}, region_perception_radius_um{};
// Founder handling.
std::int64_t founder_thrust_um_per_s2{}, founder_reverse_thrust_um_per_s2{};
std::int64_t founder_drag_ppm_per_tick{}, founder_lateral_drag_ppm_per_tick{};
std::int64_t founder_turn_heading_per_s{}; // 65,536 heading units per turn.
// Currents.
std::int64_t currents_min_count{}, currents_max_count{};
std::int64_t currents_min_width_um{}, currents_max_width_um{};
std::int64_t currents_min_speed_um_per_s{}, currents_max_speed_um_per_s{};
std::int64_t currents_grid_pitch_um{};
// Moving food.
std::int64_t food_merged_bubble_cap_multiple{}, food_visible_moving_bubbles{};
std::int64_t food_induced_drift_radius_um{}, food_induced_drift_max_um_per_s{};
std::int64_t food_induced_drift_decay_ppm_per_tick{};
// Thermal map and biology (temperatures in millikelvin).
std::int64_t thermal_ambient_min_mk{}, thermal_ambient_max_mk{};
std::int64_t founder_preferred_mk{}, founder_comfort_band_mk{}, founder_body_tau_ms{};
std::int64_t founder_lethal_cold_mk{}, founder_lethal_heat_mk{};
std::int64_t thermal_off_preference_per_mille_per_k{}, thermal_transition_per_mille_per_k{};
std::int64_t thermal_multiplier_cap_per_mille{};
// Lifecycle.
std::int64_t lifecycle_logout_delay_ms{};
// Mutation offers.
std::int64_t mutation_step_points{}, mutation_paired_points{};
std::int64_t mutation_recovery_floor_per_mille{};
std::int64_t mutation_offer_interval_ms{}, mutation_offer_options{};
auto operator<=>(const CellularTuning&) const = default;
};
enum class CellularTuningErrorKind : std::uint8_t {
too_large,
syntax,
unknown_key,
duplicate_key,
invalid_value,
out_of_range,
missing_key,
inconsistent,
unsupported_version
};
struct CellularTuningError {
CellularTuningErrorKind kind{};
std::size_t line{}; // 1-based; zero when not tied to a line.
std::string key;
auto operator<=>(const CellularTuningError&) const = default;
};
[[nodiscard]] std::expected<CellularTuning, CellularTuningError>
parse_cellular_tuning(std::string_view text);
// Canonical text: every key once, in schema order, so equal tunings encode identically.
[[nodiscard]] std::string encode_cellular_tuning(const CellularTuning& tuning);
[[nodiscard]] std::string_view describe(CellularTuningErrorKind kind) noexcept;
// Founder handling per 50 ms tick, rounded down; costs are supplied by the metabolic budget.
[[nodiscard]] CellularHandling founder_cellular_handling(const CellularTuning& tuning,
accounting::Picojoules thrust_cost,
accounting::Picojoules reverse_cost);
} // namespace evo::biology
+312
View File
@@ -0,0 +1,312 @@
#include "evo/biology/cellular_kinematics.hpp"
#include <algorithm>
#include <array>
#include <cstdlib>
#include <limits>
namespace evo::biology {
namespace {
constexpr std::int64_t tick_microseconds = cellular_motion_tick_microseconds;
// One micrometre of carry: Q10 velocity times microseconds.
constexpr std::int64_t carry_per_um = cellular_velocity_q10_per_um_s * 1'000'000;
constexpr std::int64_t quarter_turn = cellular_heading_turn / 4;
constexpr std::int64_t trig_den = cellular_trig_one;
// sin(i * pi / 512) in Q14 for the first quarter turn; 64 headings per step.
constexpr std::array<std::int32_t, 257> quarter_sine{
0, 101, 201, 302, 402, 503, 603, 704, 804, 904, 1005, 1105, 1205,
1306, 1406, 1506, 1606, 1706, 1806, 1906, 2006, 2105, 2205, 2305, 2404, 2503,
2603, 2702, 2801, 2900, 2999, 3098, 3196, 3295, 3393, 3492, 3590, 3688, 3786,
3883, 3981, 4078, 4176, 4273, 4370, 4467, 4563, 4660, 4756, 4852, 4948, 5044,
5139, 5235, 5330, 5425, 5520, 5614, 5708, 5803, 5897, 5990, 6084, 6177, 6270,
6363, 6455, 6547, 6639, 6731, 6823, 6914, 7005, 7096, 7186, 7276, 7366, 7456,
7545, 7635, 7723, 7812, 7900, 7988, 8076, 8163, 8250, 8337, 8423, 8509, 8595,
8680, 8765, 8850, 8935, 9019, 9102, 9186, 9269, 9352, 9434, 9516, 9598, 9679,
9760, 9841, 9921, 10001, 10080, 10159, 10238, 10316, 10394, 10471, 10549, 10625, 10702,
10778, 10853, 10928, 11003, 11077, 11151, 11224, 11297, 11370, 11442, 11514, 11585, 11656,
11727, 11797, 11866, 11935, 12004, 12072, 12140, 12207, 12274, 12340, 12406, 12472, 12537,
12601, 12665, 12729, 12792, 12854, 12916, 12978, 13039, 13100, 13160, 13219, 13279, 13337,
13395, 13453, 13510, 13567, 13623, 13678, 13733, 13788, 13842, 13896, 13949, 14001, 14053,
14104, 14155, 14206, 14256, 14305, 14354, 14402, 14449, 14497, 14543, 14589, 14635, 14680,
14724, 14768, 14811, 14854, 14896, 14937, 14978, 15019, 15059, 15098, 15137, 15175, 15213,
15250, 15286, 15322, 15357, 15392, 15426, 15460, 15493, 15525, 15557, 15588, 15619, 15649,
15679, 15707, 15736, 15763, 15791, 15817, 15843, 15868, 15893, 15917, 15941, 15964, 15986,
16008, 16029, 16049, 16069, 16088, 16107, 16125, 16143, 16160, 16176, 16192, 16207, 16221,
16235, 16248, 16261, 16273, 16284, 16295, 16305, 16315, 16324, 16332, 16340, 16347, 16353,
16359, 16364, 16369, 16373, 16376, 16379, 16381, 16383, 16384, 16384};
// atan(2^-i) in 1/1024 heading units, for CORDIC vectoring.
constexpr std::array<std::int64_t, 20> cordic_angles{
8388608, 4952084, 2616545, 1328199, 666677, 333664, 166872, 83441, 41721, 20861,
10430, 5215, 2608, 1304, 652, 326, 163, 81, 41, 20};
std::uint64_t integer_sqrt(std::uint64_t value) noexcept {
std::uint64_t result{}, bit = std::uint64_t{1} << 62U;
while (bit > value)
bit >>= 2U;
while (bit != 0) {
if (value >= result + bit) {
value -= result + bit;
result = (result >> 1U) + bit;
} else {
result >>= 1U;
}
bit >>= 2U;
}
return result;
}
std::uint64_t magnitude(std::int64_t x, std::int64_t y) noexcept {
const auto ux = static_cast<std::uint64_t>(std::llabs(x));
const auto uy = static_cast<std::uint64_t>(std::llabs(y));
return integer_sqrt(ux * ux + uy * uy);
}
std::int64_t floor_div(std::int64_t value, std::int64_t divisor) noexcept {
const auto quotient = value / divisor;
return value % divisor != 0 && value < 0 ? quotient - 1 : quotient;
}
// ceil(value * num / den) without overflow for num, den below 2^32.
std::uint64_t scale_ceil(std::uint64_t value, std::uint64_t num, std::uint64_t den) noexcept {
const auto whole = value / den, rest = value % den;
const auto partial = rest * num;
return whole * num + partial / den + (partial % den != 0 ? 1 : 0);
}
// Loses ceil(|v| * ppm / 10^6) of v, never crossing zero, so motion stops exactly.
std::int64_t decay(std::int64_t v, std::uint32_t ppm) noexcept {
if (v == 0 || ppm == 0)
return v;
const auto size = std::llabs(v);
const auto loss = std::min<std::int64_t>(size, (size * ppm + cellular_drag_ppm_limit - 1) /
cellular_drag_ppm_limit);
return v < 0 ? v + loss : v - loss;
}
std::int32_t interpolated_sine(std::int64_t within_quarter) noexcept {
const auto index = static_cast<std::size_t>(within_quarter >> 6U);
const auto fraction = within_quarter & 63;
if (index >= quarter_sine.size() - 1)
return quarter_sine.back();
const auto low = quarter_sine.at(index), high = quarter_sine.at(index + 1);
return low + static_cast<std::int32_t>(((high - low) * fraction + 32) / 64);
}
bool valid_intent(CellularIntent intent) noexcept {
if (intent.x < -cellular_intent_component_limit || intent.x > cellular_intent_component_limit ||
intent.y < -cellular_intent_component_limit || intent.y > cellular_intent_component_limit)
return false;
const auto x = static_cast<std::int64_t>(intent.x), y = static_cast<std::int64_t>(intent.y);
return x * x + y * y <=
std::int64_t{cellular_intent_component_limit} * cellular_intent_component_limit;
}
bool within_velocity_limit(std::int64_t component) noexcept {
return component >= -cellular_velocity_limit_q10 && component <= cellular_velocity_limit_q10;
}
std::int64_t clamp_velocity(std::int64_t component) noexcept {
return std::clamp<std::int64_t>(component, -cellular_velocity_limit_q10,
cellular_velocity_limit_q10);
}
// Moves one axis by whole micrometres, stopping at the region edge. Returns whether it was
// stopped, so the caller can drop the carry and any relative velocity into the edge.
bool advance_axis(std::uint64_t& coordinate, std::int64_t delta, std::uint64_t maximum) noexcept {
if (delta < 0) {
const auto distance = static_cast<std::uint64_t>(-delta);
if (distance > coordinate) {
coordinate = 0;
return true;
}
coordinate -= distance;
return false;
}
const auto distance = static_cast<std::uint64_t>(delta);
if (distance > maximum - coordinate) {
coordinate = maximum;
return true;
}
coordinate += distance;
return false;
}
} // namespace
std::int32_t cellular_sin_q14(std::uint16_t heading) noexcept {
const auto quadrant = heading / quarter_turn;
auto within = static_cast<std::int64_t>(heading % quarter_turn);
if (quadrant % 2 == 1)
within = quarter_turn - within;
const auto value = interpolated_sine(within);
return quadrant >= 2 ? -value : value;
}
std::int32_t cellular_cos_q14(std::uint16_t heading) noexcept {
return cellular_sin_q14(static_cast<std::uint16_t>(heading + quarter_turn));
}
std::uint16_t cellular_heading_of(std::int64_t x, std::int64_t y) noexcept {
if (x == 0 && y == 0)
return 0;
constexpr std::int64_t precise = std::int64_t{1} << 40;
while (std::llabs(x) >= precise || std::llabs(y) >= precise) {
x /= 2;
y /= 2;
}
while (std::llabs(x) < precise / 2 && std::llabs(y) < precise / 2) {
x *= 2;
y *= 2;
}
std::int64_t angle{};
if (x < 0) {
x = -x;
y = -y;
angle = static_cast<std::int64_t>(cellular_heading_turn / 2) * 1'024;
}
for (std::size_t i = 0; i < cordic_angles.size(); ++i) {
const auto shift = static_cast<unsigned>(i);
const auto next_x = y > 0 ? x + (y >> shift) : x - (y >> shift);
const auto next_y = y > 0 ? y - (x >> shift) : y + (x >> shift);
angle += y > 0 ? cordic_angles.at(i) : -cordic_angles.at(i);
x = next_x;
y = next_y;
}
const auto rounded = floor_div(angle + 512, 1'024);
return static_cast<std::uint16_t>(((rounded % cellular_heading_turn) + cellular_heading_turn) %
cellular_heading_turn);
}
std::expected<CellularKinematicsResult, CellularKinematicsError>
step_cellular_kinematics(CellularArea area, CellularPosition position, std::uint32_t extent_um,
const CellularMotionState& state, CellularPropulsion propulsion,
const CellularHandling& handling, CellularFlowSample flow,
accounting::Picojoules available_energy) noexcept {
if (area.width_um == 0 || area.height_um == 0 ||
area.width_um > cellular_motion_axis_limit_um ||
area.height_um > cellular_motion_axis_limit_um)
return std::unexpected{CellularKinematicsError::invalid_area};
if (extent_um == 0 || extent_um > area.width_um || extent_um > area.height_um)
return std::unexpected{CellularKinematicsError::invalid_extent};
if (position.x_um > area.width_um - extent_um || position.y_um > area.height_um - extent_um)
return std::unexpected{CellularKinematicsError::outside_area};
if (!valid_intent(propulsion.direction))
return std::unexpected{CellularKinematicsError::invalid_intent};
if (!within_velocity_limit(state.velocity_x_q10) ||
!within_velocity_limit(state.velocity_y_q10) ||
std::llabs(state.remainder_x) >= carry_per_um ||
std::llabs(state.remainder_y) >= carry_per_um)
return std::unexpected{CellularKinematicsError::invalid_state};
if (handling.forward_drag_ppm >= cellular_drag_ppm_limit ||
handling.lateral_drag_ppm >= cellular_drag_ppm_limit ||
handling.thrust_q10 > static_cast<std::uint32_t>(cellular_velocity_limit_q10) ||
handling.reverse_thrust_q10 > static_cast<std::uint32_t>(cellular_velocity_limit_q10) ||
handling.thrust_cost.value > std::numeric_limits<std::uint64_t>::max() / 2 ||
handling.reverse_cost.value > std::numeric_limits<std::uint64_t>::max() / 2)
return std::unexpected{CellularKinematicsError::invalid_handling};
if (!within_velocity_limit(flow.x_q10) || !within_velocity_limit(flow.y_q10))
return std::unexpected{CellularKinematicsError::invalid_flow};
std::int64_t vx = state.velocity_x_q10, vy = state.velocity_y_q10;
auto heading = state.heading;
CellularKinematicsResult result{};
if (propulsion.brake) {
const auto speed = static_cast<std::int64_t>(magnitude(vx, vy));
if (speed > 0 && handling.reverse_thrust_q10 > 0) {
const auto used = std::min<std::int64_t>(handling.reverse_thrust_q10, speed);
const auto cost =
scale_ceil(handling.reverse_cost.value, static_cast<std::uint64_t>(used),
handling.reverse_thrust_q10);
if (cost <= available_energy.value) {
vx -= vx * used / speed;
vy -= vy * used / speed;
result.cost = {cost};
result.thrust = CellularThrustStatus::applied;
} else {
result.thrust = CellularThrustStatus::unfunded;
}
}
} else {
const auto ix = static_cast<std::int64_t>(propulsion.direction.x);
const auto iy = static_cast<std::int64_t>(propulsion.direction.y);
const auto throttle = static_cast<std::int64_t>(magnitude(ix, iy));
if (throttle > 0) {
const auto target = cellular_heading_of(ix, iy);
auto turn = static_cast<std::int64_t>(static_cast<std::uint16_t>(target - heading));
if (turn > static_cast<std::int64_t>(cellular_heading_turn / 2))
turn -= cellular_heading_turn;
turn = std::clamp<std::int64_t>(turn, -handling.turn, handling.turn);
heading = static_cast<std::uint16_t>(heading + turn);
// Thrust along the body axis, forward or reversing, by its alignment with the
// command; perpendicular commands only turn.
const auto alignment = cellular_cos_q14(static_cast<std::uint16_t>(target - heading));
if (alignment != 0) {
const bool forward = alignment > 0;
const auto rate = forward ? handling.thrust_q10 : handling.reverse_thrust_q10;
const auto full = forward ? handling.thrust_cost : handling.reverse_cost;
const auto num = static_cast<std::uint64_t>(throttle * std::abs(alignment));
constexpr auto den =
static_cast<std::uint64_t>(cellular_intent_component_limit) * cellular_trig_one;
const auto accel = static_cast<std::int64_t>(std::uint64_t{rate} * num / den);
const auto cost = scale_ceil(full.value, num, den);
if (accel > 0 || cost > 0) {
if (cost <= available_energy.value) {
const auto signed_accel = forward ? accel : -accel;
vx += signed_accel * cellular_cos_q14(heading) / trig_den;
vy += signed_accel * cellular_sin_q14(heading) / trig_den;
result.cost = {cost};
result.thrust = CellularThrustStatus::applied;
} else {
result.thrust = CellularThrustStatus::unfunded;
}
}
}
}
}
vx = clamp_velocity(vx);
vy = clamp_velocity(vy);
if (handling.forward_drag_ppm == handling.lateral_drag_ppm) {
vx = decay(vx, handling.forward_drag_ppm);
vy = decay(vy, handling.forward_drag_ppm);
} else {
const std::int64_t c = cellular_cos_q14(heading), s = cellular_sin_q14(heading);
const auto along = decay((vx * c + vy * s) / trig_den, handling.forward_drag_ppm);
const auto across = decay((vy * c - vx * s) / trig_den, handling.lateral_drag_ppm);
vx = clamp_velocity((along * c - across * s) / trig_den);
vy = clamp_velocity((along * s + across * c) / trig_den);
}
auto carry_x = state.remainder_x + (vx + flow.x_q10) * tick_microseconds;
auto carry_y = state.remainder_y + (vy + flow.y_q10) * tick_microseconds;
const auto step_x = floor_div(carry_x, carry_per_um);
const auto step_y = floor_div(carry_y, carry_per_um);
carry_x -= step_x * carry_per_um;
carry_y -= step_y * carry_per_um;
auto next = position;
if (advance_axis(next.x_um, step_x, area.width_um - extent_um)) {
carry_x = 0;
if ((step_x < 0 && vx < 0) || (step_x > 0 && vx > 0))
vx = 0;
}
if (advance_axis(next.y_um, step_y, area.height_um - extent_um)) {
carry_y = 0;
if ((step_y < 0 && vy < 0) || (step_y > 0 && vy > 0))
vy = 0;
}
const auto moved_x =
static_cast<std::int64_t>(next.x_um) - static_cast<std::int64_t>(position.x_um);
const auto moved_y =
static_cast<std::int64_t>(next.y_um) - static_cast<std::int64_t>(position.y_um);
const auto path = magnitude(moved_x, moved_y);
result.path_um =
path * path == static_cast<std::uint64_t>(moved_x * moved_x + moved_y * moved_y) ? path
: path + 1;
result.position = next;
result.state = {static_cast<std::int32_t>(vx), static_cast<std::int32_t>(vy), heading, carry_x,
carry_y};
return result;
}
} // namespace evo::biology
+248
View File
@@ -0,0 +1,248 @@
#include "evo/biology/cellular_tuning.hpp"
#include <array>
#include <optional>
namespace evo::biology {
namespace {
struct Field {
std::string_view key;
std::int64_t CellularTuning::* member;
std::int64_t minimum, maximum;
};
constexpr std::int64_t axis_limit = cellular_motion_axis_limit_um;
constexpr std::int64_t speed_limit = 1'000'000; // um/s, the kinematic velocity bound.
constexpr std::int64_t kelvin_limit = 1'000'000; // 1,000 K in millikelvin.
// Schema order is the canonical encoding order.
constexpr std::array fields{
Field{"tuning.version", &CellularTuning::version, 1, 1'000},
Field{"region.width_um", &CellularTuning::region_width_um, 1'000, axis_limit},
Field{"region.height_um", &CellularTuning::region_height_um, 1'000, axis_limit},
Field{"region.organism_cap", &CellularTuning::region_organism_cap, 1, 100'000},
Field{"region.deposit_limit", &CellularTuning::region_deposit_limit, 1, 65'536},
Field{"region.perception_radius_um", &CellularTuning::region_perception_radius_um, 100,
100'000},
Field{"founder.thrust_um_per_s2", &CellularTuning::founder_thrust_um_per_s2, 0, speed_limit},
Field{"founder.reverse_thrust_um_per_s2", &CellularTuning::founder_reverse_thrust_um_per_s2, 0,
speed_limit},
Field{"founder.drag_ppm_per_tick", &CellularTuning::founder_drag_ppm_per_tick, 0, 999'999},
Field{"founder.lateral_drag_ppm_per_tick", &CellularTuning::founder_lateral_drag_ppm_per_tick,
0, 999'999},
Field{"founder.turn_heading_per_s", &CellularTuning::founder_turn_heading_per_s, 0,
10 * std::int64_t{cellular_heading_turn}},
Field{"currents.min_count", &CellularTuning::currents_min_count, 0, 16},
Field{"currents.max_count", &CellularTuning::currents_max_count, 0, 16},
Field{"currents.min_width_um", &CellularTuning::currents_min_width_um, 100, axis_limit},
Field{"currents.max_width_um", &CellularTuning::currents_max_width_um, 100, axis_limit},
Field{"currents.min_speed_um_per_s", &CellularTuning::currents_min_speed_um_per_s, 0,
speed_limit},
Field{"currents.max_speed_um_per_s", &CellularTuning::currents_max_speed_um_per_s, 0,
speed_limit},
Field{"currents.grid_pitch_um", &CellularTuning::currents_grid_pitch_um, 10, 100'000},
Field{"food.merged_bubble_cap_multiple", &CellularTuning::food_merged_bubble_cap_multiple, 1,
1'000},
Field{"food.visible_moving_bubbles", &CellularTuning::food_visible_moving_bubbles, 0, 512},
Field{"food.induced_drift_radius_um", &CellularTuning::food_induced_drift_radius_um, 0,
100'000},
Field{"food.induced_drift_max_um_per_s", &CellularTuning::food_induced_drift_max_um_per_s, 0,
speed_limit},
Field{"food.induced_drift_decay_ppm_per_tick",
&CellularTuning::food_induced_drift_decay_ppm_per_tick, 0, 999'999},
Field{"thermal.ambient_min_mk", &CellularTuning::thermal_ambient_min_mk, 0, kelvin_limit},
Field{"thermal.ambient_max_mk", &CellularTuning::thermal_ambient_max_mk, 0, kelvin_limit},
Field{"founder.preferred_mk", &CellularTuning::founder_preferred_mk, 0, kelvin_limit},
Field{"founder.comfort_band_mk", &CellularTuning::founder_comfort_band_mk, 0, kelvin_limit},
Field{"founder.body_tau_ms", &CellularTuning::founder_body_tau_ms, 1, 3'600'000},
Field{"founder.lethal_cold_mk", &CellularTuning::founder_lethal_cold_mk, 0, kelvin_limit},
Field{"founder.lethal_heat_mk", &CellularTuning::founder_lethal_heat_mk, 0, kelvin_limit},
Field{"thermal.off_preference_per_mille_per_k",
&CellularTuning::thermal_off_preference_per_mille_per_k, 0, 100'000},
Field{"thermal.transition_per_mille_per_k", &CellularTuning::thermal_transition_per_mille_per_k,
0, 100'000},
Field{"thermal.multiplier_cap_per_mille", &CellularTuning::thermal_multiplier_cap_per_mille,
1'000, 1'000'000},
Field{"lifecycle.logout_delay_ms", &CellularTuning::lifecycle_logout_delay_ms, 0, 600'000},
Field{"mutation.step_points", &CellularTuning::mutation_step_points, 1, 100},
Field{"mutation.paired_points", &CellularTuning::mutation_paired_points, 0, 100},
Field{"mutation.recovery_floor_per_mille", &CellularTuning::mutation_recovery_floor_per_mille,
0, 1'000},
Field{"mutation.offer_interval_ms", &CellularTuning::mutation_offer_interval_ms, 1'000,
3'600'000},
Field{"mutation.offer_options", &CellularTuning::mutation_offer_options, 1, 10},
};
std::string_view trim(std::string_view text) noexcept {
while (!text.empty() && (text.front() == ' ' || text.front() == '\t'))
text.remove_prefix(1);
while (!text.empty() && (text.back() == ' ' || text.back() == '\t' || text.back() == '\r'))
text.remove_suffix(1);
return text;
}
bool valid_key(std::string_view key) noexcept {
if (key.empty())
return false;
for (const char c : key)
if (!((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_' || c == '.'))
return false;
return true;
}
// Optional '-', then digits with single '_' separators between digits; at most 18 digits.
std::optional<std::int64_t> parse_integer(std::string_view text) noexcept {
const bool negative = !text.empty() && text.front() == '-';
if (negative)
text.remove_prefix(1);
if (text.empty() || text.front() == '_' || text.back() == '_')
return std::nullopt;
std::int64_t value{};
std::size_t digits{};
char previous{};
for (const char c : text) {
if (c == '_') {
if (previous == '_')
return std::nullopt;
} else if (c >= '0' && c <= '9') {
if (++digits > 18)
return std::nullopt;
value = value * 10 + (c - '0');
} else {
return std::nullopt;
}
previous = c;
}
return negative ? -value : value;
}
std::optional<CellularTuningError> inconsistent(const CellularTuning& t) {
const auto error = [](std::string_view key) {
return CellularTuningError{CellularTuningErrorKind::inconsistent, 0, std::string{key}};
};
if (t.version != cellular_tuning_version)
return CellularTuningError{CellularTuningErrorKind::unsupported_version, 0,
"tuning.version"};
if (t.currents_min_count > t.currents_max_count)
return error("currents.min_count");
if (t.currents_min_width_um > t.currents_max_width_um)
return error("currents.min_width_um");
if (t.currents_min_speed_um_per_s > t.currents_max_speed_um_per_s)
return error("currents.min_speed_um_per_s");
if (t.thermal_ambient_min_mk > t.thermal_ambient_max_mk)
return error("thermal.ambient_min_mk");
if (t.founder_lethal_cold_mk >= t.founder_preferred_mk ||
t.founder_preferred_mk >= t.founder_lethal_heat_mk)
return error("founder.preferred_mk");
return std::nullopt;
}
} // namespace
std::expected<CellularTuning, CellularTuningError> parse_cellular_tuning(std::string_view text) {
if (text.size() > max_cellular_tuning_bytes)
return std::unexpected{CellularTuningError{CellularTuningErrorKind::too_large, 0, {}}};
CellularTuning tuning{};
std::array<bool, fields.size()> seen{};
std::size_t line_number{};
while (!text.empty()) {
++line_number;
const auto end = text.find('\n');
auto line = text.substr(0, end);
text.remove_prefix(end == std::string_view::npos ? text.size() : end + 1);
if (const auto comment = line.find('#'); comment != std::string_view::npos)
line = line.substr(0, comment);
line = trim(line);
if (line.empty())
continue;
const auto equals = line.find('=');
if (equals == std::string_view::npos)
return std::unexpected{
CellularTuningError{CellularTuningErrorKind::syntax, line_number, {}}};
const auto key = trim(line.substr(0, equals));
const auto value_text = trim(line.substr(equals + 1));
if (!valid_key(key))
return std::unexpected{
CellularTuningError{CellularTuningErrorKind::syntax, line_number, {}}};
std::size_t index{};
while (index < fields.size() && fields.at(index).key != key)
++index;
if (index == fields.size())
return std::unexpected{CellularTuningError{CellularTuningErrorKind::unknown_key,
line_number, std::string{key}}};
if (seen.at(index))
return std::unexpected{CellularTuningError{CellularTuningErrorKind::duplicate_key,
line_number, std::string{key}}};
const auto value = parse_integer(value_text);
if (!value)
return std::unexpected{CellularTuningError{CellularTuningErrorKind::invalid_value,
line_number, std::string{key}}};
const auto& field = fields.at(index);
if (*value < field.minimum || *value > field.maximum)
return std::unexpected{CellularTuningError{CellularTuningErrorKind::out_of_range,
line_number, std::string{key}}};
seen.at(index) = true;
tuning.*field.member = *value;
}
for (std::size_t index = 0; index < fields.size(); ++index)
if (!seen.at(index))
return std::unexpected{CellularTuningError{CellularTuningErrorKind::missing_key, 0,
std::string{fields.at(index).key}}};
if (const auto error = inconsistent(tuning))
return std::unexpected{*error};
return tuning;
}
std::string encode_cellular_tuning(const CellularTuning& tuning) {
std::string text;
for (const auto& field : fields) {
text.append(field.key);
text.append(" = ");
text.append(std::to_string(tuning.*field.member));
text.push_back('\n');
}
return text;
}
std::string_view describe(CellularTuningErrorKind kind) noexcept {
switch (kind) {
case CellularTuningErrorKind::too_large:
return "tuning file too large";
case CellularTuningErrorKind::syntax:
return "expected 'key = value'";
case CellularTuningErrorKind::unknown_key:
return "unknown key";
case CellularTuningErrorKind::duplicate_key:
return "duplicate key";
case CellularTuningErrorKind::invalid_value:
return "value is not an integer";
case CellularTuningErrorKind::out_of_range:
return "value out of range";
case CellularTuningErrorKind::missing_key:
return "missing key";
case CellularTuningErrorKind::inconsistent:
return "values are inconsistent";
case CellularTuningErrorKind::unsupported_version:
return "unsupported tuning version";
}
return "unknown tuning error";
}
CellularHandling founder_cellular_handling(const CellularTuning& tuning,
accounting::Picojoules thrust_cost,
accounting::Picojoules reverse_cost) {
constexpr std::int64_t ticks_per_second =
1'000'000 / static_cast<std::int64_t>(cellular_motion_tick_microseconds);
const auto per_tick_velocity = [](std::int64_t um_per_s2) {
return static_cast<std::uint32_t>(um_per_s2 * cellular_velocity_q10_per_um_s /
ticks_per_second);
};
return {
.thrust_q10 = per_tick_velocity(tuning.founder_thrust_um_per_s2),
.reverse_thrust_q10 = per_tick_velocity(tuning.founder_reverse_thrust_um_per_s2),
.forward_drag_ppm = static_cast<std::uint32_t>(tuning.founder_drag_ppm_per_tick),
.lateral_drag_ppm = static_cast<std::uint32_t>(tuning.founder_lateral_drag_ppm_per_tick),
.turn = static_cast<std::uint16_t>(tuning.founder_turn_heading_per_s / ticks_per_second),
.thrust_cost = thrust_cost,
.reverse_cost = reverse_cost};
}
} // namespace evo::biology
+278
View File
@@ -0,0 +1,278 @@
#include "evo/biology/cellular_kinematics.hpp"
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <source_location>
#include <stdexcept>
#include <string>
namespace {
using namespace evo::biology;
void check(bool value, std::source_location at = std::source_location::current()) {
if (!value)
throw std::runtime_error("cellular kinematics line " + std::to_string(at.line()));
}
#define CHECK(...) check(static_cast<bool>(__VA_ARGS__))
constexpr CellularArea area{60'000, 60'000};
constexpr CellularPosition middle{30'000, 30'000};
constexpr std::uint32_t extent = 20;
constexpr evo::accounting::Picojoules plenty{1'000'000'000};
constexpr std::int32_t um_per_s = 1'024; // Q10 velocity of 1 um/s.
// v0 founder handling: 400 um/s^2 thrust, k = 2 /s drag, one turn per second.
CellularHandling founder() {
return {.thrust_q10 = 400 * um_per_s / 20,
.reverse_thrust_q10 = 400 * um_per_s / 20,
.forward_drag_ppm = 95'163,
.lateral_drag_ppm = 95'163,
.turn = 3'277,
.thrust_cost = {1'000},
.reverse_cost = {1'000}};
}
CellularKinematicsResult step(CellularPosition position, const CellularMotionState& state,
CellularPropulsion propulsion, const CellularHandling& handling,
CellularFlowSample flow = {},
evo::accounting::Picojoules energy = plenty) {
const auto result =
step_cellular_kinematics(area, position, extent, state, propulsion, handling, flow, energy);
check(result.has_value());
return *result;
}
std::int64_t heading_error(std::uint16_t a, std::uint16_t b) {
const auto difference = static_cast<std::int16_t>(static_cast<std::uint16_t>(a - b));
return std::abs(static_cast<std::int64_t>(difference));
}
void trigonometry() {
CHECK(cellular_cos_q14(0) == 16'384 && cellular_sin_q14(0) == 0);
CHECK(cellular_sin_q14(16'384) == 16'384 && cellular_cos_q14(16'384) == 0);
CHECK(cellular_cos_q14(32'768) == -16'384 && cellular_sin_q14(32'768) == 0);
CHECK(cellular_sin_q14(49'152) == -16'384);
CHECK(cellular_sin_q14(8'192) == 11'585 && cellular_cos_q14(8'192) == 11'585);
for (std::uint32_t h = 1; h < cellular_heading_turn; ++h) {
const auto heading = static_cast<std::uint16_t>(h);
const std::int64_t s = cellular_sin_q14(heading), c = cellular_cos_q14(heading);
CHECK(std::abs(s * s + c * c - std::int64_t{16'384} * 16'384) <= std::int64_t{4} * 16'384);
CHECK(cellular_sin_q14(static_cast<std::uint16_t>(cellular_heading_turn - h)) == -s);
}
}
void headings() {
CHECK(cellular_heading_of(0, 0) == 0);
CHECK(heading_error(cellular_heading_of(1, 0), 0) <= 1);
CHECK(heading_error(cellular_heading_of(0, 1), 16'384) <= 1);
CHECK(heading_error(cellular_heading_of(-1, 0), 32'768) <= 1);
CHECK(heading_error(cellular_heading_of(0, -1), 49'152) <= 1);
CHECK(heading_error(cellular_heading_of(1'000, 1'000), 8'192) <= 1);
for (std::uint32_t h = 0; h < cellular_heading_turn; h += 7) {
const auto heading = static_cast<std::uint16_t>(h);
CHECK(
heading_error(cellular_heading_of(cellular_cos_q14(heading), cellular_sin_q14(heading)),
heading) <= 3);
}
}
void acceleration_reaches_steady_speed() {
CellularMotionState state{};
auto position = middle;
std::int32_t previous{};
for (int tick = 0; tick < 120; ++tick) {
const auto next = step(position, state, {{1'000, 0}, false}, founder());
CHECK(next.thrust == CellularThrustStatus::applied && next.cost.value == 1'000);
CHECK(next.state.velocity_x_q10 >= previous && next.state.velocity_y_q10 == 0);
previous = next.state.velocity_x_q10;
position = next.position;
state = next.state;
}
// Thrust then drag settle near 190 um/s for the v0 founder.
CHECK(state.velocity_x_q10 > 189 * um_per_s && state.velocity_x_q10 < 191 * um_per_s);
CHECK(position.x_um > middle.x_um + 1'000);
}
CellularMotionState moving_east(std::int32_t speed_um_s) {
return {.velocity_x_q10 = speed_um_s * um_per_s};
}
void coasting_stops_exactly() {
auto state = moving_east(200);
auto position = middle;
int ticks{};
while (state.velocity_x_q10 != 0) {
const auto next = step(position, state, {}, founder());
CHECK(next.thrust == CellularThrustStatus::idle && next.cost.value == 0);
CHECK(next.state.velocity_x_q10 < state.velocity_x_q10 && next.state.velocity_x_q10 >= 0);
position = next.position;
state = next.state;
CHECK(++ticks < 400);
}
// About 100 um of coasting from 200 um/s with a 0.5 s time constant.
CHECK(position.x_um > middle.x_um + 80 && position.x_um < middle.x_um + 110);
}
void braking_stops_sooner_without_reversing() {
auto state = moving_east(200);
int ticks{};
while (state.velocity_x_q10 != 0) {
const auto next = step(middle, state, {{}, true}, founder());
CHECK(next.state.velocity_x_q10 >= 0 && next.thrust == CellularThrustStatus::applied);
state = next.state;
CHECK(++ticks < 20);
}
const auto stopped = step(middle, state, {{}, true}, founder());
CHECK(stopped.thrust == CellularThrustStatus::idle && stopped.cost.value == 0);
}
void reversing_uses_reverse_thrust() {
auto state = moving_east(150);
auto position = middle;
for (int tick = 0; tick < 30; ++tick) {
const auto next = step(position, state, {{-1'000, 0}, false}, founder());
position = next.position;
state = next.state;
}
CHECK(state.velocity_x_q10 < 0);
// The heading turned toward the command as well.
CHECK(heading_error(state.heading, 32'768) <= 1);
}
void turning_is_rate_limited() {
const auto turned = step(middle, {}, {{0, 1'000}, false}, founder());
CHECK(turned.state.heading == 3'277);
// Perpendicular remains mostly sideways: thrust follows the body axis.
CHECK(turned.state.velocity_x_q10 > turned.state.velocity_y_q10);
}
void flow_drift_is_exact() {
CellularMotionState state{};
auto position = middle;
for (int tick = 0; tick < 20; ++tick) {
const auto next = step(position, state, {}, founder(), {100 * um_per_s, 0});
position = next.position;
state = next.state;
}
CHECK(position == CellularPosition{middle.x_um + 100, middle.y_um});
CHECK(state == CellularMotionState{});
// Against a current faster than the founder's swimming, progress is negative.
state = moving_east(190);
const auto upstream = step(middle, state, {{1'000, 0}, false}, founder(), {-300 * um_per_s, 0});
CHECK(upstream.position.x_um < middle.x_um);
}
void fractional_travel_carries() {
auto handling = founder();
handling.forward_drag_ppm = handling.lateral_drag_ppm = 0;
auto state = moving_east(7);
auto position = middle;
for (int tick = 0; tick < 20; ++tick) {
const auto next = step(position, state, {}, handling);
position = next.position;
state = next.state;
}
CHECK(position.x_um == middle.x_um + 7 && state.remainder_x == 0);
// Slow negative drift carries too.
state = {.velocity_y_q10 = -um_per_s / 2};
position = middle;
for (int tick = 0; tick < 40; ++tick) {
const auto next = step(position, state, {}, handling);
position = next.position;
state = next.state;
}
CHECK(position.y_um == middle.y_um - 1 && state.remainder_y == 0);
}
void unfunded_thrust_coasts() {
const auto state = moving_east(100);
const auto coast = step(middle, state, {}, founder());
const auto broke = step(middle, state, {{1'000, 0}, false}, founder(), {}, {999});
CHECK(broke.thrust == CellularThrustStatus::unfunded && broke.cost.value == 0);
CHECK(broke.state == coast.state && broke.position == coast.position);
const auto half = step(middle, {}, {{500, 0}, false}, founder());
CHECK(half.cost.value == 500 && half.state.velocity_x_q10 > 0);
}
void edges_stop_motion() {
const CellularPosition edge{area.width_um - extent, 100};
const auto blocked = step(edge, moving_east(150), {{1'000, 0}, false}, founder());
CHECK(blocked.position == edge && blocked.state.velocity_x_q10 == 0);
CHECK(blocked.state.remainder_x == 0 && blocked.path_um == 0);
}
void lateral_drag_is_separate() {
auto handling = founder();
handling.forward_drag_ppm = 0;
handling.lateral_drag_ppm = 500'000;
const auto sideways = step(middle, {.velocity_y_q10 = 100 * um_per_s}, {}, handling);
CHECK(std::abs(sideways.state.velocity_y_q10 - 50 * um_per_s) <= 2);
const auto forward = step(middle, moving_east(100), {}, handling);
CHECK(std::abs(forward.state.velocity_x_q10 - 100 * um_per_s) <= 2);
}
void invalid_inputs() {
CHECK(!step_cellular_kinematics({0, 10}, {}, 1, {}, {}, founder(), {}, plenty));
CHECK(
!step_cellular_kinematics(area, {area.width_um, 0}, extent, {}, {}, founder(), {}, plenty));
CHECK(!step_cellular_kinematics(area, middle, extent, {}, {{1'000, 1'000}, false}, founder(),
{}, plenty));
CHECK(!step_cellular_kinematics(area, middle, extent,
{.remainder_x = std::int64_t{1'024} * 1'000'000}, {}, founder(),
{}, plenty));
auto bad = founder();
bad.forward_drag_ppm = 1'000'000;
CHECK(!step_cellular_kinematics(area, middle, extent, {}, {}, bad, {}, plenty));
CHECK(!step_cellular_kinematics(area, middle, extent, {}, {}, founder(),
{cellular_velocity_limit_q10 + 1, 0}, plenty));
}
// Golden trajectory: any change to this value changes shared server/client motion.
void golden_trajectory() {
CellularMotionState state{};
auto position = middle;
std::uint64_t digest = 1'469'598'103'934'665'603ULL;
const auto mix = [&digest](std::uint64_t value) {
digest = (digest ^ value) * 1'099'511'628'211ULL;
};
for (int tick = 0; tick < 200; ++tick) {
const CellularIntent intent{static_cast<std::int16_t>((tick % 50) * 20 - 500),
static_cast<std::int16_t>(tick < 100 ? 600 : -600)};
const CellularFlowSample flow{(tick % 7) * 9'000 - 20'000, 15'000};
const auto next = step(position, state, {intent, tick % 37 == 0}, founder(), flow);
position = next.position;
state = next.state;
mix(position.x_um);
mix(position.y_um);
mix(static_cast<std::uint32_t>(state.velocity_x_q10));
mix(static_cast<std::uint32_t>(state.velocity_y_q10));
mix(state.heading);
}
std::printf("golden trajectory digest %llu\n", static_cast<unsigned long long>(digest));
CHECK(digest == 8'485'405'051'858'728'694ULL);
}
} // namespace
int main() {
try {
trigonometry();
headings();
acceleration_reaches_steady_speed();
coasting_stops_exactly();
braking_stops_sooner_without_reversing();
reversing_uses_reverse_thrust();
turning_is_rate_limited();
flow_drift_is_exact();
fractional_travel_carries();
unfunded_thrust_coasts();
edges_stop_motion();
lateral_drag_is_separate();
invalid_inputs();
golden_trajectory();
} catch (const std::exception& error) {
std::fprintf(stderr, "%s\n", error.what());
return 1;
}
std::puts("cellular kinematics contracts passed");
return 0;
}
+156
View File
@@ -0,0 +1,156 @@
#include "evo/biology/cellular_tuning.hpp"
#include <cstdio>
#include <fstream>
#include <iterator>
#include <source_location>
#include <stdexcept>
#include <string>
namespace {
using namespace evo::biology;
void check(bool value, std::source_location at = std::source_location::current()) {
if (!value)
throw std::runtime_error("cellular tuning line " + std::to_string(at.line()));
}
#define CHECK(...) check(static_cast<bool>(__VA_ARGS__))
CellularTuning v0() {
return {.version = 1,
.region_width_um = 60'000,
.region_height_um = 60'000,
.region_organism_cap = 2'000,
.region_deposit_limit = 8'192,
.region_perception_radius_um = 5'000,
.founder_thrust_um_per_s2 = 400,
.founder_reverse_thrust_um_per_s2 = 400,
.founder_drag_ppm_per_tick = 95'163,
.founder_lateral_drag_ppm_per_tick = 95'163,
.founder_turn_heading_per_s = 65'536,
.currents_min_count = 2,
.currents_max_count = 4,
.currents_min_width_um = 3'000,
.currents_max_width_um = 6'000,
.currents_min_speed_um_per_s = 60,
.currents_max_speed_um_per_s = 300,
.currents_grid_pitch_um = 250,
.food_merged_bubble_cap_multiple = 8,
.food_visible_moving_bubbles = 256,
.food_induced_drift_radius_um = 200,
.food_induced_drift_max_um_per_s = 100,
.food_induced_drift_decay_ppm_per_tick = 95'163,
.thermal_ambient_min_mk = 278'150,
.thermal_ambient_max_mk = 313'150,
.founder_preferred_mk = 293'150,
.founder_comfort_band_mk = 5'000,
.founder_body_tau_ms = 20'000,
.founder_lethal_cold_mk = 273'150,
.founder_lethal_heat_mk = 318'150,
.thermal_off_preference_per_mille_per_k = 80,
.thermal_transition_per_mille_per_k = 40,
.thermal_multiplier_cap_per_mille = 8'000,
.lifecycle_logout_delay_ms = 10'000,
.mutation_step_points = 5,
.mutation_paired_points = 2,
.mutation_recovery_floor_per_mille = 100,
.mutation_offer_interval_ms = 25'000,
.mutation_offer_options = 3};
}
// Replaces the first `key = ...` line of canonical text.
std::string with(std::string text, const std::string& key, const std::string& value) {
const auto at = text.find(key + " = ");
check(at != std::string::npos);
const auto end = text.find('\n', at);
return text.replace(at, end - at, key + " = " + value);
}
CellularTuningErrorKind error_of(const std::string& text) {
const auto parsed = parse_cellular_tuning(text);
check(!parsed.has_value());
return parsed.error().kind;
}
void canonical_round_trip() {
const auto text = encode_cellular_tuning(v0());
const auto parsed = parse_cellular_tuning(text);
CHECK(parsed && *parsed == v0());
CHECK(encode_cellular_tuning(*parsed) == text);
}
void comments_separators_and_whitespace() {
auto text = "# heading\n\n" + encode_cellular_tuning(v0());
text = with(text, "region.width_um", "60_000 # trailing comment\r");
text = with(text, "region.height_um", "\t60000");
const auto parsed = parse_cellular_tuning(text);
CHECK(parsed && *parsed == v0());
}
void refusals() {
const auto base = encode_cellular_tuning(v0());
CHECK(error_of(base + "unknown.key = 1\n") == CellularTuningErrorKind::unknown_key);
CHECK(error_of(base + "region.width_um = 60000\n") == CellularTuningErrorKind::duplicate_key);
CHECK(error_of(base + "no equals sign\n") == CellularTuningErrorKind::syntax);
CHECK(error_of(base + "Region.Width = 1\n") == CellularTuningErrorKind::syntax);
CHECK(error_of(with(base, "region.width_um", "60k")) == CellularTuningErrorKind::invalid_value);
CHECK(error_of(with(base, "region.width_um", "60__000")) ==
CellularTuningErrorKind::invalid_value);
CHECK(error_of(with(base, "region.width_um", "")) == CellularTuningErrorKind::invalid_value);
CHECK(error_of(with(base, "region.width_um", "999")) == CellularTuningErrorKind::out_of_range);
CHECK(error_of(with(base, "founder.drag_ppm_per_tick", "1000000")) ==
CellularTuningErrorKind::out_of_range);
CHECK(error_of(with(base, "region.width_um", "# missing")) ==
CellularTuningErrorKind::invalid_value);
CHECK(error_of(with(base, "currents.min_count", "5")) == CellularTuningErrorKind::inconsistent);
CHECK(error_of(with(base, "founder.preferred_mk", "320000")) ==
CellularTuningErrorKind::inconsistent);
CHECK(error_of(with(base, "tuning.version", "2")) ==
CellularTuningErrorKind::unsupported_version);
auto missing = base;
missing.erase(missing.find("mutation.offer_options"));
const auto parsed = parse_cellular_tuning(missing);
CHECK(!parsed && parsed.error().kind == CellularTuningErrorKind::missing_key &&
parsed.error().key == "mutation.offer_options");
const auto line = parse_cellular_tuning(base + "\nbad\n");
CHECK(!line && line.error().line == 41);
CHECK(error_of(std::string(max_cellular_tuning_bytes + 1, '#')) ==
CellularTuningErrorKind::too_large);
}
void founder_handling() {
const auto handling = founder_cellular_handling(v0(), {1'000}, {900});
CHECK(handling.thrust_q10 == 20'480 && handling.reverse_thrust_q10 == 20'480);
CHECK(handling.forward_drag_ppm == 95'163 && handling.lateral_drag_ppm == 95'163);
CHECK(handling.turn == 3'276);
CHECK(handling.thrust_cost.value == 1'000 && handling.reverse_cost.value == 900);
}
// The checked-in DEV tuning file must parse; CTest passes its path when it is present.
void repository_file(const char* path) {
std::ifstream file(path, std::ios::binary);
CHECK(file.good());
const std::string text{std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()};
const auto parsed = parse_cellular_tuning(text);
if (!parsed)
std::fprintf(stderr, "%s: line %zu %s: %s\n", path, parsed.error().line,
parsed.error().key.c_str(),
std::string{describe(parsed.error().kind)}.c_str());
CHECK(parsed && *parsed == v0());
}
} // namespace
int main(int argc, char** argv) {
try {
canonical_round_trip();
comments_separators_and_whitespace();
refusals();
founder_handling();
if (argc > 1)
repository_file(argv[1]);
} catch (const std::exception& error) {
std::fprintf(stderr, "%s\n", error.what());
return 1;
}
std::puts("cellular tuning contracts passed");
return 0;
}