Netcode in Hanamori, part 4: hit grace and everything that goes wrong
Monster hits wait long enough for your screen to have shown them coming. What is rewound, what is not, and a catalogue of the ways a real network ruins a good design.
Part 3 made other players look smooth by drawing the past. That creates a fairness problem, and the problem has a name: you dodged, but the monster hit you anyway. This post is about what the dungeon server does about it, and about what it deliberately does not do. The second half is the catalogue of everything that goes wrong in real networks, with what the code does about each. It is a long list. Networks are creative.
The series: part 1 (tick, wire, area of interest), part 2 (yourself), part 3 (everyone else), part 4 (this one: fairness and edge cases). In these posts the meadow server is Hanamori's open-world server, and realm servers run the dungeons.
The fair rule is: the server waits as long as it takes for you to see the swing and answer, then checks what you did in the meantime. If you dodged, the swing misses. If you did nothing, it lands, just a moment late. Three things are needed: how long to wait (the round trip), a trace of what the hero was doing, and the judging (check the trace when the wait is over). That is the entire design, and it is small.
1. How long to wait: measuring the round trip
The realm server pings each joined hero once a second (PING_INTERVAL_MS = 1000) with a message holding the server's current millisecond time. The client's only job is to send that number back in a Pong
(c.send({ _t: 'Pong', t: m.t, interpMs }), in 19d-net.js). The round trip is then now − t. The Pong carries one more number, the client's current interpolation delay in milliseconds (interpMs, a uint16). Section 2 uses it.
// RealmWorker.h, the Pong handler (trimmed) if (!h || h->lastPingAt == 0 || m->t() != h->lastPingAt) return; // not the stamp we sent: forged or replayed const int64_t rtt = now_ - m->t(); if (rtt < 0 || rtt > 2000) return; // nonsense h->interpMs = m->interpMs(); // the client's own delay, used in section 2 const int64_t s = std::min<int64_t>(rtt, RTT_CAP_MS); // RTT_CAP_MS = 250 h->rttMs = h->rttMs == 0 ? uint16_t(s) : uint16_t(int64_t(h->rttMs) + (s - int64_t(h->rttMs)) / 4);
Four decisions. A Pong is accepted only if it echoes the exact stamp the server last sent, so a client cannot answer with a number of its choosing and make its own RTT look short or long (a client that wanted its hits delayed forever could otherwise say it was on the Moon).
The sample is capped at 250 ms: a client cannot buy more than 250 ms of grace from its round trip by lagging on purpose. The estimate is an EWMA with weight 1/4: rtt += (sample − rtt) / 4, integer division, so a single bad sample moves it a quarter of the way. And rttMs == 0 means unknown, so a hero who has not answered a ping yet gets no grace at all. That last one matters in section 2.
(This is the one place in the whole system that uses a round trip. As part 1 said, the meadow does not: its clock is estimated from tick stamps alone, and the hanamori client never sends a Ping to the meadow, though the meadow server would answer one.)
2. The hit grace: queue it, wait, judge it
When a monster's attack connects, the realm sim calls damageHero. Normally this would apply damage at once. With a measured RTT, it does this instead:
// include/realm/sim/HeroActs.h inline void damageHero(Instance& in, uint8_t seat, const HeroHit& hit, SimCtx& c, int64_t nowMs) { if (seat >= MAX_HEROES || in.cleared) return; Hero& h = in.heroes[seat]; if (h.seat != SeatState::Active || h.g.dead) return; if (!hit.lava && !hit.unblockable && h.rttMs > 0 && in.pendN < MAX_PENDING_HITS) { const int64_t graceMs = hitGraceMs(h.rttMs, h.interpMs); in.pend[in.pendN++] = PendingHit{hit, in.tick, in.tick + uint32_t((graceMs + 49) / 50), seat}; return; // queued, not landed } const bool guard = h.g.blocking || h.g.act.kind == uint8_t(Act::BlockHit); landHit(in, seat, hit, c, nowMs, !hit.lava && h.st.iframeT > 0.f, guard && guardFaces(h, h.st.yaw, hit.sx, hit.sz)); }
The grace is hitGraceMs(rttMs, interpMs), rounded up to whole 50 ms ticks:
// include/realm/sim/HeroActs.h
inline int64_t hitGraceMs(uint16_t rttMs, uint16_t interpMs) {
return std::min<int64_t>(rttMs, RTT_CAP_MS) + std::clamp<int64_t>(interpMs, INTERP_FLOOR_MS, INTERP_CEIL_MS);
}
The rounding is (graceMs + 49) / 50, the standard integer ceiling. Worked example (illustrative): RTT 80 ms with the interpolation delay at its 100 ms floor gives 180 ms, which is 229 / 50 = 4 ticks, or 200 ms. On a jittery link the same RTT can come with a 180 ms delay: 260 ms, 309 / 50 = 6 ticks. The extremes: RTT 1 and a 100 ms delay give 101 ms, 3 ticks; RTT 250 and a 250 ms delay give 500 ms, 549 / 50 = 10 ticks. That is the maximum any hit waits.
The second term pays for what you are looking at. Monsters on your screen are drawn in the past by the interpolation delay from part 3, which the client adapts between 100 and 250 ms to the jitter it sees, so you see the swing that much later than the server started it. Your dodge has to cover that delay on top of the round trip before it is back at the server. The server cannot see the delay your client chose, so the client reports it: interpMs in its Pong, the rounded NR.delay.ms of that moment, refreshed every second with the ping. The server clamps it to the same 100..250 ms the client works in, and a hero who has not reported (0) gets the 100 ms floor. The grace covers both the round trip and what you are actually looking at.
Three kinds of hit are not delayed, and each for a reason:
- Lava (
hit.lava): the floor is not a surprise that you could dodge by reacting to an animation. Standing in it is the decision. - Unblockable hits: a hit that ignores guard has no reaction to wait for. (It is judged on the hero's state now, where iframes still dodge, except lava.)
- RTT unknown (0) or the queue is full (64 pending hits): land at once. A full queue is the safety valve; we would rather be slightly unfair than lose track of a hit.
3. The trace ring
While a hit waits, the server writes down what each hero is doing, every tick, in a ring of 16 slots per hero. The slot is tick & 15. That holds 800 ms, enough for the maximum 500 ms grace (10 ticks) with room to spare.
// include/realm/sim/HeroActs.h struct HeroTrace { uint32_t tick = 0; float yaw = 0; bool iframe = false, guard = false; }; // Instance.h inline void recordTrace(Instance& in, uint8_t seat) { // written after stepHero const Hero& h = in.heroes[seat]; in.trace[seat][in.tick & (TRACE_LEN - 1)] = // TRACE_LEN = 16 HeroTrace{in.tick, h.st.yaw, h.st.iframeT > 0.f, h.g.blocking || h.g.act.kind == uint8_t(Act::BlockHit)}; }
Each slot records three facts: were you invulnerable this tick (iframe, from a dodge), were you holding up a guard (guard), and which way were you facing (yaw). A slot also stores its tick so that, when the ring has gone round, a stale lap can be recognised and skipped.
4. Judging the hit
When a queued hit comes due, resolvePendingHits decides. Here it is, with its rules in order:
// include/realm/sim/HeroActs.h (trimmed) inline void resolvePendingHits(Instance& in, SimCtx& c, int64_t nowMs) { for (/* each pending hit p */) { if (p.dueTick > in.tick) { /* keep it */ continue; } if (in.cleared || !heroLive(in.heroes[p.seat])) continue; // hero left or died: drop it const Hero& h = in.heroes[p.seat]; if (hit.shape) { // is the hero STILL in the area? const float dx = h.st.x - hit.ax, dz = h.st.z - hit.az, dd = std::sqrt(dx*dx + dz*dz); if (!(dd < hit.ar)) continue; // walked out: no hit if (hit.shape == 2) { /* arc: dot > hit.minDot, else no hit */ } } bool dodged = false, blocked = false; for (const HeroTrace& t : in.trace[p.seat]) { if (t.tick < p.fromTick || t.tick > in.tick) continue; // stale ring slot dodged = dodged || t.iframe; blocked = blocked || (t.guard && guardFaces(h, t.yaw, hit.sx, hit.sz)); } landHit(in, p.seat, hit, c, nowMs, dodged, blocked && !dodged); // dodge wins } }
- Is the target still there? If the hero has left the instance, died, or the room was cleared, the hit is dropped silently.
- Is the target still in the hit shape? The circle or arc is re-tested against the hero's current position, not the position at swing time. If you ran out of the area while the hit waited, it misses. This is the part that makes the delay feel fair: moving away works.
- What did the trace say? Any tick from the start tick to now with
iframemeans you dodged. Any tick withguardand a guard facing the source (guardFaces: a dot product above 0.2, using the yaw recorded that tick) means you blocked. A dodge wins over a block. - Land it.
landHit: a dodge lands nothing and raises a dodged flag for the number display. A block takes0.2 × damageand0.4 × knockback(never below 1 damage), and plays the block-hit animation. Otherwise the hero plays a hurt animation, unless the current action has armor.
Note what the “any tick” rule means: a dodge that happened during the grace window counts, even for one tick, even if the hero has stopped dodging by the time the hit is judged. That is the point. The hero pressed dodge when his screen showed the swing, and the press reached the server within the window. The window is the amount of time the server is trying to be fair about.
5. What is not rewound
Here is where I have to correct an easy mistake, because it is the first thing people say about this: “it is lag compensation, so the server rewinds the world.” It does not.
- Monsters are not rewound for player attacks. When you swing at a monster, the server judges the swing against the monster's position now. The hero does not shoot at where the monster was when your screen last drew it. Aim is validated by angle (below), not by an exact point, which softens the effect but does not remove it.
- Nothing is extrapolated on the client (part 3).
- The grace is not a rewind either: it is a delay on one kind of event, a monster hit on a hero, judged against a short written log of the hero.
There is one place where the client's view is trusted a little, to compensate for the picture being in the past: aim. When you attack, the client sends the monster it was aiming at and the yaw it aimed along. The server accepts that aim if all of this holds, and otherwise falls back to its own best aim:
- the monster the client named is alive;
- it is within
maxD + radius + 1.5metres of the hero (the weapon's reach, plus slack); - the angle between the client's aim and the real bearing to that monster is at most
AIM_TOL_DEG = 20degrees.
The tolerance is a tolerance, not a rewind: it says “you aimed at roughly the right thing”. Whether the swing then connects is still judged on current positions.
There is also no area of interest in realm. A realm sends every hero to every other hero, and one shared tick frame per tick to all viewers. The per-viewer filtering of part 1 is a meadow feature only.
6. The edge cases, in one place
Everything that goes wrong, and what the code does. Most were mentioned in earlier parts; this is the list in one place.
| Situation | What happens | Where |
|---|---|---|
| Browser socket drops | Reconnect with backoff 1 s, 2 s, 4 s, then 8 s (cap). On success: a fresh Join or Resume, clock and delay reset. | part 3, conn.mjs |
| Disconnect from a realm | The server keeps the seat for 60 s (GRACE_MS). The client keeps trying for 60 s (REJOIN_WINDOW_MS), asking for a new ticket every 4 s. | 19d-net.js, StubArena.h |
| Return from a realm | The meadow snapshot comes as a Resume; prediction restarts from it, and the interpolation clock and delay are reset. | part 2, part 3 |
| Packet burst | Every packet carries its tick, so a burst is stamped at its true times. The delay estimate rises and decays slowly. | part 3 |
| Stall (hidden tab, GC) | Step loop clamps at 0.25 s. Delay ignores gaps and lateness over 1 s. Server holds your keys for 10 ticks then goes neutral. By then the prediction error is well over 4 m: snap. | part 2, part 3 |
| Clock snap (a faster packet than ever) | Clock snaps down, delay mean re-bases, ring stamps clamp forward. | part 3 |
| Out-of-order update | Delay ignores it. Ring clamps the stamp forward. Input side: stale seq dropped. | part 2, part 3 |
| Teleport or any server jump | There is no teleport message. A jump larger than 4 m is a prediction error over the snap threshold: snap. | part 2 |
| Hero dies | Queued hits on a dead hero are dropped; landHit clears the act and blocking and starts the death exit. Dead heroes send zeroed input. | HeroActs.h, 19e-netmeadow.js |
| Hero out of range of a hit by the time it is judged | The hit is dropped (re-tested at the current position). | HeroActs.h |
| Client lies about RTT | Pong must echo the server's exact stamp. Samples over 250 ms count as 250. Over 2000 or negative: ignored. The reported interpolation delay is clamped to 100..250 ms. | RealmWorker.h |
| RTT unknown, or 64 hits pending | The hit lands at once. | HeroActs.h |
| Refused or lost realm tick frame | The server marks the viewer to receive a full state next time (needFull). | part 1 |
| Version mismatch | JoinFail BAD_VERSION; the client halts with an “Update needed” badge. | part 1 |
| Too many messages | 120 per second, burst 40, then dropped. Pong exempt. Decoder never throws. | part 1 |
Non-finite viewYaw | Rejected by the codec; sim uses the current yaw. | part 2 |
| Player at the edge of a 30 m circle | Removal waits 3 passes (about 300 ms) and is cancelled if the player returns, with no new FULL. | part 1 |
7. The four things that do not exist, once more
- No ping or RTT clock sync in meadow. The server answers Ping; the client never sends it. Clocks come from tick stamps (part 3).
- No extrapolation. The client holds the last sample.
- No rewinding of monsters for player hits. Only monster hits on heroes are deferred, and judged against the hero's log.
- No area of interest in realm.
8. The trade-offs, honestly
- The grace favours the player on the receiving end. A dodge that reaches the server in time counts. The cap of 250 ms stops this being a cheat: deliberate lag buys at most 500 ms.
- Damage numbers arrive up to 500 ms after the swing animation. Normally RTT is small; on a bad link that is the price of fairness.
- The delay is self-reported. The grace trusts the client's
interpMs, so a client can claim 250 ms and have its hits wait up to 150 ms longer than the floor allows. The clamp is the limit, the same as for the round trip: at most 500 ms in all. - Hero attacks on monsters use the monster's present. On a bad link you will sometimes see a swing connect and the server say otherwise. A rewind is the usual fix, and it is not implemented here.
- The estimators trust the best-case packet. A single abnormally fast packet moves the clock. That is deliberate (it tracks the true floor) and means a sudden improvement in the network is noticed at once, while a sudden worsening takes tens of samples to be believed.
That is the whole path: a 20 Hz tick (part 1), prediction by running the same step function locally (part 2), a past you can draw smoothly (part 3), and a delayed hit judgement that waits long enough to be fair (this part). Each piece is small. The complexity is in the fact that there are four of them, and that they each lie in a slightly different direction.