53# include <gtest/gtest.h>
61 using Cell = std::pair<std::int64_t, std::int64_t>;
62 using Cell_Set = std::set<Cell>;
72 { s.emplace(x,
y); });
78 for (
const auto & c : cells)
79 e.set_alive(c.first, c.second, true);
80 return engine_cells(e);
86 Cell_Set brute_force_step(
const Cell_Set & cur,
90 for (
const auto & c : cur)
91 for (int dy = -1; dy <= 1; ++dy)
92 for (
int dx = -1; dx <= 1; ++dx)
93 candidates.emplace(c.first + dx, c.second + dy);
96 for (
const auto & c : candidates)
99 for (
int dy = -1; dy <= 1; ++dy)
100 for (
int dx = -1; dx <= 1; ++dx)
102 if (dx == 0
and dy == 0)
104 if (cur.count({ c.first + dx, c.second + dy }))
107 const bool alive = cur.count(c) != 0;
108 if (rule.
apply(alive, n))
114 Cell_Set brute_force_run(Cell_Set cur,
118 for (std::uint64_t i = 0; i <
steps; ++i)
119 cur = brute_force_step(cur, rule);
127 return Cell_Set{ { 0, -1 }, { 0, 0 }, { 0, 1 } };
132 return Cell_Set{ { 0, 0 }, { 1, 0 }, { 0, 1 }, { 1, 1 } };
141 return Cell_Set{ { 1, 0 },
143 { 0, 2 }, { 1, 2 }, { 2, 2 } };
146 Cell_Set translate(
const Cell_Set & cs, std::int64_t dx, std::int64_t dy)
149 for (
const auto & c : cs)
150 out.emplace(c.first + dx, c.second + dy);
156 Cell_Set gosper_gun()
158 static const int xy[][2] = {
159 { 1, 5 }, { 1, 6 }, { 2, 5 }, { 2, 6 },
160 { 11, 5 }, { 11, 6 }, { 11, 7 }, { 12, 4 }, { 12, 8 },
161 { 13, 3 }, { 13, 9 }, { 14, 3 }, { 14, 9 },
162 { 15, 6 }, { 16, 4 }, { 16, 8 },
163 { 17, 5 }, { 17, 6 }, { 17, 7 }, { 18, 6 },
164 { 21, 3 }, { 21, 4 }, { 21, 5 },
165 { 22, 3 }, { 22, 4 }, { 22, 5 },
166 { 23, 2 }, { 23, 6 },
167 { 25, 1 }, { 25, 2 }, { 25, 6 }, { 25, 7 },
168 { 35, 3 }, { 35, 4 }, { 36, 3 }, { 36, 4 },
171 for (
const auto & p : xy)
172 s.emplace(p[0], p[1]);
182TEST(CAHashlife, EmptyUniverseHasZeroPopulation)
190TEST(CAHashlife, SetAndGetSingleCell)
199 EXPECT_EQ(bb.x_min, 3);
200 EXPECT_EQ(bb.y_min, -7);
201 EXPECT_EQ(bb.x_max, 3);
202 EXPECT_EQ(bb.y_max, -7);
203 EXPECT_EQ(bb.width(), 1);
204 EXPECT_EQ(bb.height(), 1);
211TEST(CAHashlife, SetMultipleCellsKeepsExactSet)
214 Cell_Set src{ { -100, -100 }, { 0, 0 }, { 7, 13 }, { -3, 5 } };
215 for (
const auto & c : src)
217 EXPECT_EQ(engine_cells(e), src);
221 EXPECT_EQ(bb.x_min, -100);
222 EXPECT_EQ(bb.x_max, 7);
223 EXPECT_EQ(bb.y_min, -100);
224 EXPECT_EQ(bb.y_max, 13);
227TEST(CAHashlife, ClearResetsUniverse)
230 load_cells(e, blinker());
241TEST(CAHashlife, ReadOutsideRootIsDead)
245 EXPECT_FALSE(e.
alive_at(1'000'000, 1'000'000));
246 EXPECT_FALSE(e.
alive_at(-1'000'000, -1'000'000));
254TEST(CAHashlife, BlockIsAStillLife)
257 load_cells(e, block());
258 const auto initial = engine_cells(e);
259 for (
unsigned k : { 0u, 1u, 2u, 3u, 4u, 5u })
262 EXPECT_EQ(engine_cells(e), initial)
263 <<
"block changed after advance(" <<
k <<
")";
267TEST(CAHashlife, BlinkerIsPeriod2)
270 load_cells(e, blinker());
274 const auto initial = engine_cells(e);
275 const std::uint64_t steps0 = e.
advance(0);
276 const std::uint64_t steps10 = e.
advance(10);
279 ASSERT_EQ((steps0 + steps10) % 2u, 0u)
280 <<
"advance returned an odd total of generations: "
281 << steps0 <<
" + " << steps10;
282 EXPECT_EQ(engine_cells(e), initial)
283 <<
"after " << (steps0 + steps10) <<
" generations";
287TEST(CAHashlife, GliderTravelsByOneCellEveryFourSteps)
290 const auto initial = glider();
291 load_cells(e, initial);
295 const std::uint64_t advanced = e.
run(4);
296 ASSERT_GE(advanced, 4u);
297 EXPECT_EQ(engine_cells(e), translate(initial,
298 static_cast<std::int64_t
>(advanced) / 4,
299 static_cast<std::int64_t
>(advanced) / 4));
303TEST(CAHashlife, GliderMatchesBruteForceForManySteps)
306 load_cells(e, glider());
307 Cell_Set ref = glider();
310 for (
unsigned k = 0;
k <= 9; ++
k)
312 const std::uint64_t advanced = e.
advance(
k);
314 EXPECT_EQ(engine_cells(e), ref)
315 <<
"after advance(" <<
k <<
") = " << advanced <<
" steps";
337 const auto & sample = GetParam();
339 load_cells(e, sample.seed);
343 brute_force_run(sample.seed, sample.rule, sample.steps);
344 EXPECT_EQ(engine_cells(e), ref) << sample.name;
357 [](const ::testing::TestParamInfo<Rule_Sample> & i)
358 {
return std::string(i.param.name); });
365TEST(CAHashlife, AdvanceReturnsAtLeast2ToTheK)
368 load_cells(e, glider());
369 for (
unsigned k = 0;
k <= 8; ++
k)
371 const std::uint64_t before =
static_cast<std::uint64_t
>(e.
generation());
372 const std::uint64_t advanced = e.
advance(
k);
373 EXPECT_GE(advanced, std::uint64_t{1} <<
k);
374 EXPECT_EQ(
static_cast<std::uint64_t
>(e.
generation()),
379TEST(CAHashlife, RunAtLeastReachesRequestedGeneration)
382 load_cells(e, glider());
383 const std::int64_t target = e.
generation() + 1023;
388TEST(CAHashlife, AdvanceTooLargeKThrows)
391 EXPECT_THROW(e.
advance(63), std::domain_error);
392 EXPECT_THROW(e.
advance(100), std::domain_error);
395TEST(CAHashlife, ConstructorRejectsTinyCacheCapacity)
405TEST(CAHashlife, RleRoundTripPreservesGlider)
408 load_cells(src, glider());
417 auto normalise = [](
const Cell_Set & cs)
421 std::int64_t mx = cs.begin()->first;
422 std::int64_t my = cs.begin()->second;
423 for (
const auto & c : cs)
425 if (c.first < mx) mx = c.first;
426 if (c.second < my) my = c.second;
429 for (
const auto & c : cs)
430 out.emplace(c.first - mx, c.second - my);
433 EXPECT_EQ(normalise(engine_cells(dst)), normalise(engine_cells(src)));
436TEST(CAHashlife, RleRoundTripPreservesGosperGun)
439 load_cells(src, gosper_gun());
449TEST(CAHashlife, RleHeaderEncodesRule)
452 load_cells(e, blinker());
454 EXPECT_NE(rle.find(
"rule = B36/S23"), std::string::npos)
455 <<
"rule field missing from: " << rle;
458TEST(CAHashlife, RleParseAcceptsStandardConwayDialect)
461 const std::string glider_rle =
463 "x = 3, y = 3, rule = B3/S23\n"
473TEST(CAHashlife, FormatRuleIsRoundTripStable)
479 ASSERT_TRUE(parsed.has_value());
480 EXPECT_EQ(*parsed,
r) <<
"round-trip failed for: " << s;
489TEST(CAHashlife, StatsTrackCanonicalNodes)
492 load_cells(e, glider());
494 const auto stats = e.
stats();
495 EXPECT_GT(stats.canonical_nodes, 0u);
496 EXPECT_GT(stats.result_misses, 0u);
499TEST(CAHashlife, ChangingRuleInvalidatesResultCache)
502 load_cells(e, glider());
504 const auto before = e.
stats();
505 EXPECT_GT(before.result_misses, 0u);
511TEST(CAHashlife, SmallCacheCapacityForcesPeriodicClears)
514 load_cells(e, gosper_gun());
526TEST(CAHashlife, GosperGunMatchesReferenceAt256Steps)
529 load_cells(e, gosper_gun());
532 const Cell_Set ref = brute_force_run(gosper_gun(),
Conway_Life, 256);
533 EXPECT_EQ(engine_cells(e), ref);
536TEST(CAHashlife, GosperGunPopulationGrowsLinearly)
539 load_cells(e, gosper_gun());
540 const std::uint64_t pop_initial = e.
population();
542 const std::uint64_t pop_after = e.
population();
543 EXPECT_GT(pop_after, pop_initial);
549 EXPECT_GE(pop_after, 40u);
550 EXPECT_LE(pop_after, 100u);
561 load_cells(e, blinker());
562 const auto before = engine_cells(e);
563 EXPECT_EQ(e.
run(0), 0u);
564 EXPECT_EQ(engine_cells(e), before);
568TEST(CAHashlife, LargeCoordinatesAreSupported)
572 EXPECT_TRUE(e.
alive_at(1'000'000, -1'000'000));
579TEST(CAHashlife, RepeatedSetAliveOnSameCellIsIdempotent)
582 for (
int i = 0; i < 10; ++i)
585 for (
int i = 0; i < 10; ++i)
590TEST(CAHashlife, DeepRunHashlifeStaysExactAgainstBruteForce)
598 for (
auto p : { Cell{1, 0}, Cell{2, 0}, Cell{0, 1}, Cell{1, 1}, Cell{1, 2} })
605 EXPECT_EQ(engine_cells(e), ref);
size_t size_t int32_t * out
Hashlife engine for outer-totalistic binary cellular automata.
void load_rle_string(const std::string &s)
Convenience overload that reads the pattern from a string.
BBox bbox() const
Tight bounding box of the alive cells (empty if population() == 0).
void set_rule(const Rule &r)
Replace the rule. Invalidates the result cache.
std::uint64_t run(std::uint64_t generations)
Advance by exactly generations steps.
void for_each_alive(F &&f) const
Iterate over all alive cells, calling f(x, y) for each.
Stats stats() const noexcept
Diagnostic counters and current root level.
void set_alive(const std::int64_t x, const std::int64_t y, const bool alive=true)
Set or clear the cell at world coordinates (x, y).
std::uint64_t advance(const unsigned k)
Advance the universe by 2^k generations.
std::string save_rle_string(const std::string &comment={}) const
Convenience overload returning the RLE serialisation as a string.
void clear()
Reset the universe to empty (preserves rule, capacity and node cache).
std::int64_t generation() const noexcept
Number of generations elapsed since construction (or the last clear).
bool alive_at(const std::int64_t x, const std::int64_t y) const
Read the cell at world coordinates (x, y).
std::uint64_t population() const noexcept
Number of alive cells.
std::optional< Outer_Totalistic_Binary_Rule > parse_rule(const std::string &s)
Parse a B.../S... (or Wolfram S/B) rule string.
std::string format_rule(const Outer_Totalistic_Binary_Rule &r)
Format a rule as a Conway-style Bxxx/Sxxx string.
constexpr Outer_Totalistic_Binary_Rule Conway_Life
Conway's Game of Life: B3/S23.
constexpr Outer_Totalistic_Binary_Rule HighLife
Nathan Thompson's HighLife: B36/S23 (replicators).
constexpr Outer_Totalistic_Binary_Rule Day_And_Night
Bays' Day & Night: B3678/S34678 (self-complementary).
constexpr Outer_Totalistic_Binary_Rule Seeds
Seeds: B2/S (every live cell dies, two neighbours produce a birth).
Compiler_SSA_Block & block(Compiler_SSA_Function &function, const Compiler_SSA_Block_Id id)
size_t size(Node *root) noexcept
See compute_cardinality_rec(Node * root).
and
Check uniqueness with explicit hash + equality functors.
bool is_empty() const noexcept
True iff there are no alive cells.
std::size_t result_cache_clears
times the result cache was invalidated
Outer-totalistic binary rule encoded as two 9-bit bitmasks.
constexpr bool apply(const bool current, const std::uint8_t n) const noexcept
True iff a cell with current state and n live neighbours is alive next.
Outer_Totalistic_Binary_Rule rule
Hashlife engine for outer-totalistic binary cellular automata.
INSTANTIATE_TEST_SUITE_P(CAHashlifeBruteForce, CAHashlifeBruteForceMatch, ::testing::Values(Rule_Sample{ "Conway_blinker_128", Conway_Life, blinker(), 128u }, Rule_Sample{ "Conway_block_128", Conway_Life, block(), 128u }, Rule_Sample{ "Conway_glider_256", Conway_Life, glider(), 256u }, Rule_Sample{ "HighLife_glider_128", HighLife, glider(), 128u }, Rule_Sample{ "Seeds_blinker_32", Seeds, blinker(), 32u }, Rule_Sample{ "Day_Night_block_64", Day_And_Night, block(), 64u }), [](const ::testing::TestParamInfo< Rule_Sample > &i) { return std::string(i.param.name);})
TEST_P(CAHashlifeBruteForceMatch, MatchesUnboundedReference)