cat posts/en/atlantis-pbem-neu-geschrieben-11-die-berichte.md
Atlantis PbeM Rewritten (Part 11): The reports—output as specification
After every turn, each player gets a report and an orders template. Part 11 ports both through the reference's intermediate JSON step, compares every file byte for byte—and finds fields the renderer never prints.
After part 10, the Python port understands what the players want. Now it has to answer them.
In Atlantis PbeM, every faction gets a report and an orders template after every turn:
report.3 and template.3 for faction 3.
The report describes the visible world: your own units and other factions' units, regions, markets, neighbors, and events. From that, the template prepares the orders file for the next turn and lists your own units along the way.
For a compatibility port, these files are especially valuable. They're what the players actually see. A different space doesn't change any game rule, but it does change the engine's output.
So Step 10 of the roadmap ports the reports. The done criterion started out as:
The reports of a freshly created game are equivalent to the reference.
In the end, it became more than that. The port produces the player reports and templates from all 14 snapshot turns byte for byte like the reference—plus the big GM report of the freshly generated world.
What a player gets back
Here's an excerpt from the first report. The last unit belongs to faction 3:
# tests/fixtures/reports/turn_0/report.3 (excerpt)
- City Guard (1), on guard, The Guardsmen (1), 500 leaders [LEAD], 500
swords [SWOR], 500 plate armor [PARM].
- City Mage (2), The Guardsmen (1), behind, leader [LEAD].
* Unit (140), Test (3), revealing faction, won't cross water, leader
[LEAD]. Weight: 10. Capacity: 0/0/15/0. Skills: pattern [PATT] 1
(30), spirit [SPIR] 1 (30), gate lore [GATE] 1 (30). Can Study:
magical healing [MHEA], farsight [FARS], mind reading [MIND].
Here, the * marks your own unit. Other factions' units get a - in this report; when
the display of attitudes is on, the reference also uses separate characters for allied,
friendly, unfriendly, and hostile.
The text wraps at 70 columns, and continuation lines are indented by two spaces.
The orders template contains the same unit again as a comment:
# tests/fixtures/reports/turn_0/template.3 (excerpt)
#atlantis 3
;*** nexus (0,0,nexus) in Unnamed ***
unit 140
;Unit (140), revealing faction, won't cross water, leader [LEAD].
; Weight: 10. Capacity: 0/0/15/0. Skills: pattern [PATT] 1 (30),
; spirit [SPIR] 1 (30), gate lore [GATE] 1 (30). Can Study: magical
; healing [MHEA], farsight [FARS], mind reading [MIND].
#end
The text is almost the same. Among other things, the template leaves out the name of your own faction, which also shifts the line wrapping.
The first report also contains descriptions of newly known skills and items. So part of the ruleset reaches the player directly through this output.
The reference builds JSON first
The text report isn't generated directly from the object model.
Game::WriteReport first builds a JSON document for each faction, writes it as
report.3.json, and then hands the same document to the renderer for report.3 and
template.3.
In the JSON, the unit from above looks like this, shortened:
{
"capacity": { "flying": 0, "riding": 0, "swimming": 0, "walking": 15 },
"flags": {
"no_cross_water": true,
"reveal": "faction",
"spoils": "all"
},
"items": [ { "amount": 1, "name": "leader", "plural": "leaders", "tag": "LEAD" } ],
"name": "Unit",
"number": 140,
"own_unit": true,
"weight": 10
}
Among other things, the text renderer turns that into revealing faction,
won't cross water, and Capacity: 0/0/15/0.
For the port, this architecture is handy.
Instead of rebuilding one big text function in one go, there are two separate points of comparison: first the JSON as the report model, then the text rendered from it.
That's exactly how the step was split up:
- Probe, fixtures, and the JSON without the long descriptions,
- skill, item, and building descriptions,
- text renderer for the report and the three template formats,
- close-out and reconciling the porting map.
The big GM report of the fresh world goes into the repository as text. At about 2.1 MB,
its JSON is much bigger and stays a reference test artifact. The individual snapshot
reports, on the other hand, live as real files per turn under tests/fixtures/reports/.
A report before the turn runs
Once again, the model probe from part 7 serves as the oracle.
The new mode:
model_probe report turn N [long|short|map]
loads the game state of the given turn, runs PreProcessTurn, ReadPlayers, and
ReadOrders, and then calls WriteReport directly.
What's missing is RunOrders.
The actual turn processing only comes in the next step.
That raises an important question: Are the reports generated this way even the right point of comparison?
The snapshot of turn 0 answers it.
After the turn processing, it has an event:
Claims 20 silver for maintenance
and afterward, faction 3 has 5,050 silver.
The probe writes its report before that and therefore still sees 5,070.
Apart from exactly this effect of the turn, the reports match. So the cut before
RunOrders is in the right place for this step.
At first, the probe produced 45 fixture files: JSON, text report, and template for each of the 14 turns, plus the GM report of turn 0 and additional template formats for turn 13.
One detail from the real game already shows why the complete pipeline matters: In turn 5,
option template map
is in the orders file.
That's why that turn's template comes out in the map format, even though players.in
still says long before that. The OPTION order from part 10 changes the setting while
the orders are being read.
Comparing the JSON twice
The port builds the report with plain Python dicts and lists.
The serialization is surprisingly boring:
# src/atlantis_ng/core/reports/json_report.py
def dump_json(report: JsonObject) -> str:
"""The text of ``report.<n>.json``: ``nlohmann::json::dump(2)``, keys sorted, no final newline."""
return json.dumps(report, indent=2, sort_keys=True, ensure_ascii=False)
The reference uses nlohmann::json. Its regular JSON objects are based on sorted maps,
and dump(2) writes the same key order and indentation here that the port produces with
sort_keys=True and two spaces.
The numbers that occur in these reports are also serialized the same way by both
implementations, for example 16.2 and 15.0.
That's a measured result for this data, not a general promise that Python and
nlohmann::json serialize every conceivable JSON document byte for byte the same.
The check runs twice anyway:
once as a parsed JSON tree and once as finished text.
The reason showed up in the very first run.
The reference wrote:
"open": 1
the port:
"open": true
ARegion::gateopen is an int in C++. In the Python model, it had accidentally become
a bool.
The comparison of the parsed structures didn't notice a thing:
>>> 1 == True
True
In Python, bool is a subclass of int.
The byte comparison of the JSON file found the difference immediately.
This isn't just cosmetic. For a JSON consumer, 1 and true are different types.
Why an empty list is null
A second quirk comes straight from nlohmann::json.
Regions and buildings without visible units contain:
"units": null
and not:
"units": []
The C++ code first accesses units with operator[]. That creates the key with a null
value.
Only when a visible unit is actually found does push_back turn that value into an
array.
If the region or building stays empty, the null stays too.
The GM report of the freshly generated world contains 592 of them.
The Python port deliberately rebuilds the same state.
A "nicer" empty list would be a different file.
1,800 lines of description text
The second pull request brought the biggest block of pure prose.
ShowSkill::Report in skillshows.cpp is a function of about 1,800 lines with one big
switch. Depending on the skill and level, it assembles English sentences and pulls in
items, buildings, and other tables to do it.
On top of that come item_description, show_special, and object_description.
The Python port separates these texts more strictly by their actual structure.
For 34 skills whose level-1 description is just one fixed sentence, for example, there's a table:
# src/atlantis_ng/core/reports/skill_shows.py
LEVEL_ONE_TEXT: dict[SkillId, str] = {
SkillId.FARMING: "This skill deals with all aspects of grain production.",
SkillId.RANCHING: "This skill deals with all aspects of livestock production.",
# ...
}
Skills with their own logic, on the other hand, each get a _describe_* function.
Here, too, things were only merged when the texts really have the same structure.
A first attempt with three phantasmal summonings had to be pulled apart again. The
differences are small but visible: For one summoning, level 3 has exactly one balrog, and
one example sentence starts with For example where the others have Example.
In a normal refactor, differences like these would quickly get "cleaned up".
For this port, they're output.
619 descriptions as a fixture
The first complete comparison against the GM report came out as:
0 of 420 skill descriptions wrong.
0 of 154 items.
0 of 45 buildings.
After that, the port didn't need a change to a single description.
Instead, one supposed error was in the comparison script: It had matched buildings by their name.
standard, however, has two different object types named Lair: one for trents and one
for illyrthils.
Compared in table order, all 45 were correct.
That did create a testing problem, though.
The regular player reports cover only a small slice of these texts. The report of turn 0, for example, shows a mere three skill descriptions and one item description.
Almost everything is only in the big GM report. Because of its size, though, its JSON stays outside the regular fixtures and is only generated in the slower reference tests.
For everyday work, that would be weak protection for more than 2,000 lines of port code.
So the reference build now extracts just the three description lists into a fixture of their own:
descriptions.json
202 KB for 619 descriptions in total.
That way, the fast test suite compares every single one of them.
Green locally, red in CI
This very fixture led straight to the next bug.
Locally, everything was green.
CI wasn't.
The cause wasn't in the report code but in the build path.
build.py generates descriptions.json on the host after the Docker build is done. For
the reference, though, CI uses the Docker image directly, so that its layer cache is
preserved.
So the extra local step never ran there.
The fix wasn't a rework of the tests but a second entry point into the same extraction step:
build.py --descriptions-only
CI runs it after the existing reference build.
This is one of those small spots where a green local run only proves that the local path works.
If CI and development reach the same build by different paths, a new step has to be added in both places.
std::round isn't Python's round
The armor descriptions round percentages.
The reference uses std::round.
That makes a difference for halves:
std::round(2.5) -> 3
round(2.5) -> 2
Here, C++ rounds away from zero. For exact halves, Python's round uses banker's
rounding and picks the even number.
That's why the port has c_round in core/cfloat.py, next to the existing helper
functions for C and C++ arithmetic.
Three less obvious quirks of the descriptions are kept as well.
If a skill can produce a ship and something else at the same level, the other part disappears from the text, because an intermediate variable gets overwritten.
For a weapon with exactly one attack per round, you can get the sentence
1 attack every round .
including the space before the period.
And a weapon with several matching type flags doesn't automatically get all the labels
in weapon_type. The function reassigns the text several times; for a weapon with
RANGED and SHORT, only short is left at the end.
None of these cases had to be visible in a normal game of standard to get documented
during porting.
Even a description can change state
On top of that, the descriptions aren't purely functional.
While describing a skill, ShowSkill::Report can make the faction discover items through
DiscoverItem.
That happens while the report is still being generated.
And the order is decisive: First the skill_reports are built, then the
item_reports.
If a skill description discovers an item that can be produced, that item can therefore already show up among the item descriptions in the same report.
So the report doesn't just read the state.
At this point, generating it also changes it.
A port that treats the text descriptions as pure formatting could easily lose this behavior.
From stream state to format specs
The third pull request ported text_report_generator.cpp.
809 lines of C++ became 760 lines in core/reports/text.py.
The most striking example is the map format of the orders template:
# tests/fixtures/reports/turn_13/template.3.map (excerpt)
;plain (28,10) in Koheda, contains Thandianost [city]
; ____
; nw / \ ne Next clear
; ____/ \____ Tax 34403
; / \ / \ Ente 1997
; / ~ ~ \____/ \ Wage 16.2 (max 11467)
; \ ~ ~ / \ /
; \____/Thandi\____/ Sell unlim IRON @ 75
; / \ / \ unlim WOOD @ 75
; / ~ ~ \____/ \ unlim STON @ 75
In C++, the columns on the right come from stream manipulators:
// reference/text_report_generator.cpp
std::string TextReportGenerator::map_header_item(const std::string& header, const json& item) {
std::stringstream ss;
ss << header;
if (item.value("unlimited", false)) ss << "unlim";
else ss << std::setw(5) << std::right << item.value("amount", 0);
ss << " " << std::setw(4) << to_s(item["tag"]);
if (item.contains("price")) ss << " @ " << std::setw(3) << std::right << item.value("price", 0);
return ss.str();
}
Python can express that more directly:
# src/atlantis_ng/core/reports/text.py
def _map_header_item(header: str, item: JsonObject) -> str:
"""``map_header_item``: one economy line beside the hex drawing, in fixed columns."""
amount = "unlim" if item.get("unlimited", False) else f"{item.get('amount', 0):>5}"
text = f"{header}{amount} {item['tag']:>4}"
if "price" in item:
text += f" @ {item.get('price', 0):>3}"
return text
std::setw(5) << std::right becomes :>5.
std::setprecision(1) << std::fixed << std::setw(7) becomes :>7.1f.
The interesting difference is in the model: In C++, manipulators like std::right carry
state forward in the stream. In Python, the formatting sits right at the value it
applies to.
The line wrapping, on the other hand, needed nothing new.
The IndentWriter from
part 6 already
reproduces the reference's indentbuf. With its defaults, it works at 70 columns, looks
back up to 30 columns for a suitable break point, and indents continuation lines by two
spaces.
14 reports, 16 templates—equal right away
The first complete run of the text renderer was pleasantly uneventful.
All 14 player reports matched byte for byte.
So did all 16 templates: 13 of the regular snapshot templates in the long format, the map format of turn 5, plus the short and the map format for turn 13.
Only the GM report of the freshly generated world was off.
Two characters, or rather one number, were enough for that.
Character 169,146
The GM report is about 550 KB.
The first deviation was at character 169,146.
The port wrote:
Wages: $15
the reference:
Wages: $15.0
In the C++ reference, the wage is a double:
// reference/aregion.cpp
double wages = p ? p->productivity / 10.0 : 0;
The renderer then prints the JSON value directly:
// reference/text_report_generator.cpp
f << "Wages: $" << region["wages"]["amount"];
The port's helper function _num had tried to make whole floating-point numbers a bit
"nicer" and turned 15.0 into the string 15.
That was exactly the bug.
For the values that occur here, Python's normal string representation already gives the desired result:
# src/atlantis_ng/core/reports/text.py
def _num(value: Any) -> str:
"""A JSON value as the reference's stream prints it: a string as itself, everything else as ``dump`` writes it.
...
"""
if isinstance(value, str):
return value
if isinstance(value, bool):
return "true" if value else "false"
return str(value)
str(15.0) is "15.0".
So the fix mainly consisted of deleting a supposedly helpful special case.
After that, the complete GM report matched too.
You can even count why the big report mattered here: It contains 649 wage entries, 34 of
them with a whole-number value as a double, such as 15.0 or 14.0.
This case didn't occur in the 14 player reports.
The renderer looks for fields that don't exist
Porting the text output turned up another kind of bug.
For buildings, the renderer checks:
// reference/text_report_generator.cpp
if (structure.contains("decay")) f << ", about to decay";
// ...
if (structure.contains("runes")) f << ", engraved with Runes of Warding";
The report JSON, however, produces:
// reference/object.cpp
if (runes) container["warding_runes"] = true;
// ...
container["decaying"] = true;
The names don't match.
So for the report JSON this engine produces, the conditions for decay and runes are
never met.
The JSON can know that a building is decaying or carries Runes of Warding; the text report still doesn't mention it.
The intent of the code is easy to see.
The output says something else.
For the port, the output wins.
That's why the Python renderer has it too:
# src/atlantis_ng/core/reports/text.py
# The JSON says "decaying" and "warding_runes"; these two lines never fire.
if "decay" in structure:
self.write(", about to decay")
The comment is important. Without it, this line would look like a typo that someone should "fix" when they get the chance.
In fact, exactly that fix would change the output.
The reference knows the problem itself
The C++ renderer explicitly comments on another formatting quirk:
// Player reports have an extra newline. GM reports don't. This is silly, but for now we will emulate that
// behavior.
So player reports end with an extra blank line, and the GM report doesn't.
The comment is remarkable because here the C++ reference itself is already doing the same thing as the Python port:
It reproduces an existing output format, even though its authors apparently don't find it particularly pretty.
Compatibility beats the urge to tidy up.
Finally, write_reports in the port closes the same chain as Game::WriteReport:
report.<n>.json, report.<n>, and template.<n> under the usual file names, including
the chosen template type.
Factions that only get a GM report don't get a template.
An end-to-end test runs for turn 0 and turn 13, from the loaded game state to the finished files.
The porting map had gone stale itself
The fourth pull request contained no new report code.
Instead, the porting map from part 2 was compared against the actual state again.
It turned out that for six C++ files, the reports were the last missing piece.
faction.cpp, object.cpp, and unit.cpp, along with their three headers, could be
set to ported.
In faction.cpp, View still has no Python counterpart. But the method only writes a
log line for Game::ViewFactions, and that function isn't called anywhere in the
reference.
Two other entries in the map were wrong as well.
ItemList::report and SkillList::report had been assigned to Step 10 and the text
renderer.
The regular faction report doesn't use either of them.
They're only needed later: for the spoils list after a battle and for the Mind Reading report on another faction's unit.
So they belong to Step 11.
With that, the porting map is back to what it's supposed to be: a snapshot of what's actually left—not a collection of old guesses about it.
Pitfalls
- When serializing, compare the text too.
1 == Trueis true in Python. So a pure tree comparison could miss1versustrue. - Don't normalize output to be nice. The port first turned
15.0into15. Almost the same for humans, wrong for a byte-exact compatibility comparison. - Big fixtures reach rare states. Only the GM report contained whole-number
doublewages and almost all of the description texts. - Important code shouldn't depend on the slow suite alone. That's why the 619 descriptions got their own 202 KB fixture for the fast tests.
- Local and CI builds need the same artifact steps. The new fixture was generated locally, but at first not in the other CI build path.
std::roundandroundaren't the same for halves. The difference needs its own small compatibility function.- Not printing something is behavior too.
decayingandwarding_runesare in the JSON, but the renderer looks for other names. The port doesn't silently fix this mismatch. - Plans age. Two entries in the porting map pointed to the wrong step by now, and six files were in fact done.
Where things stand after part 11
The Python port can now generate the reports of Atlantis PbeM: the JSON, the text report, and the orders template in long, short, and map format.
What's verified: the player files from 14 snapshot turns, the GM report of the freshly generated world at about 550 KB, and all 619 description texts.
The compared files come out byte for byte like the reference's.
New in the port are core/reports/json_report.py with 1,033 lines,
core/reports/skill_shows.py with 1,398,
core/reports/descriptions.py with 1,036, and
core/reports/text.py with 760 lines.
In total, 4,246 lines were added under src/. The model probe grew by 64 to 3,298
lines.
In the end, tests/fixtures/reports/ holds 46 files totaling about 1.2 MB, including
the 201,948-byte descriptions.json with 420 skill, 154 item, and 45 building
descriptions.
587 fast tests run in about 29 seconds, 74 of them added in this step. 31 more tests run against the built reference.
Porting coverage rises from 40.4 to 54.3 percent.
The big jump comes from the reports being the last missing piece for several files. That adds 4,019 lines of C++ to the ported count.
No new decision record was needed. The observable behavior of the reference is preserved.
What's still missing is the actual turn.
So far, the reports describe a world in which orders have been read, but nobody has moved, traded, fought, or cast a spell yet.
That changes with Step 11: turn processing in the order of Game::RunOrders.
Before the Python port takes over the first phase of it, the C++ reference in the fork gets a state dump after every phase.
Then a difference should no longer show up only at the end of the turn.
Instead, right where it originates.
Further reading
- Atlantis PbeM Rewritten (Part 10)—the
parser whose
OPTIONorder switches the template format here. - Atlantis PbeM Rewritten (Part 6)—the
IndentWriterthat handles the wrapping of the reports here without any change. - Atlantis PbeM Rewritten (Part 7)—the model probe, which writes reports here before the actual turn processing.
- Atlantis PbeM Rewritten (Part 3)—the
question of what "equal" means, with
1 == Trueas a new example. - f-strings to the max—the format mini-language that
std::setwandstd::setprecisiontranslate into.
Sources: text_report_generator.cpp,
skillshows.cpp,
faction.cpp,
object.cpp,
and aregion.cpp
of the fork,
nlohmann/json,
std::round,
Python round,
Python json.
Keyboard shortcuts
- j k
- scroll down / up
- n p
- next / previous section
- g G
- start / end of the article
- t
- show outline
- ?
- show this help
- Esc
- close
0 comments
No comments yet. Be the first!
Sign in to leave a comment.