views: borrow the world in egress instead of copying it (#28)
views.Context held copies of scene, tokens, characters, reveals, encountered and visions, so every mutation deep-copied each player's explored HashSet under the global lock; playerView then copied its own PlayerVision again and greyFor copied one per encountered entry. Context now holds six pointers (contextOf/borrow), playerView/gmView read a ptr PlayerVision and a view builds each player's visible-id set once per frame, so grey is a set test. Measured on this build's types (debug, 6 players, 40 encountered entries, 40 world tokens, 16384 / 262144 explored cells): context construction 0.227 ms / 4.87 ms -> 0.008 us; one getOrDefault of a PlayerVision 28.8 us / 591 us -> gone; GM egress pass 8.0 ms / 142.8 ms -> 0.79 ms / 0.80 ms; player pass 1.45 ms / 25.7 ms -> 0.32 ms. Behaviour is unchanged (leak/fault suites and tviews green); tviews pins the borrow by identity, the six-pointer size and both sizes inside the M5 7.5 ms budget.
This commit is contained in:
+6
-4
@@ -162,10 +162,12 @@ proc allIds(): seq[string] =
|
||||
app.tokens.mapIt(it.id) & app.characters.mapIt(it.id)
|
||||
|
||||
proc egressContext(): views.Context =
|
||||
## A read-only borrow of the world and every player's sight state. The seqs and tables are shared
|
||||
## by reference and only read before egressFrames returns, so no copy is needed.
|
||||
views.Context(scene: app.scene, tokens: app.tokens, characters: app.characters,
|
||||
reveals: app.reveals, encountered: app.encountered, visions: app.visions)
|
||||
## Six addresses, no copies (#28): the App owns the world and every player's sight state, and the
|
||||
## egress borrows them for the pass. Building this used to copy `visions` (a whole explored
|
||||
## `HashSet` per player) and the two-level `encountered` table on every mutation, under the global
|
||||
## lock; now it cannot depend on how much a player has explored. Caller holds the lock (4.3), so
|
||||
## the borrow is one consistent state for the whole fan-out.
|
||||
views.contextOf(app.scene, app.tokens, app.characters, app.reveals, app.encountered, app.visions)
|
||||
|
||||
proc pruneKnown() =
|
||||
## A closed connection's `known` table must not outlive it.
|
||||
|
||||
+79
-17
@@ -121,8 +121,24 @@ type
|
||||
fresh*: seq[(int, int)]
|
||||
|
||||
Context* = object
|
||||
## Everything the egress needs, and nothing it may modify: the world plus every player's runtime
|
||||
## sight state (read-only; the other players' entries are only reachable by a fault build).
|
||||
## A read-only *borrow* of the world and every player's runtime sight state (DESIGN 4.2/4.3;
|
||||
## #28). Every field is a pointer, so building a Context copies nothing: no `PlayerVision`, no
|
||||
## explored `HashSet`, no `Table`, however large the explored sets grew. `main.egressContext`
|
||||
## points it at the App's fields (stable for the process lifetime) while it holds the global
|
||||
## lock, so the whole egress pass reads one consistent state.
|
||||
##
|
||||
## The templates below keep the field syntax (`ctx.tokens`, `ctx.visions[pid]`) at every use
|
||||
## site; a settable template target also keeps `ctx.visions[pid].explored` an lvalue.
|
||||
pScene*: ptr SceneRec
|
||||
pTokens*: ptr seq[TokenRec]
|
||||
pCharacters*: ptr seq[CharacterRec]
|
||||
pReveals*: ptr Reveals
|
||||
pEncountered*: ptr Encountered
|
||||
pVisions*: ptr Table[int, PlayerVision]
|
||||
|
||||
ContextStore* = object
|
||||
## Owning storage with the same six fields, for tests and fixtures (`borrow` hands out a
|
||||
## Context over it). The server never uses it: `App` owns the world and hands out pointers.
|
||||
scene*: SceneRec
|
||||
tokens*: seq[TokenRec]
|
||||
characters*: seq[CharacterRec]
|
||||
@@ -138,6 +154,39 @@ type
|
||||
vision*: string ## the last `vision` payload sent, "" = never
|
||||
visionSent*: bool
|
||||
|
||||
template scene*(ctx: Context): untyped = ctx.pScene[]
|
||||
template tokens*(ctx: Context): untyped = ctx.pTokens[]
|
||||
template characters*(ctx: Context): untyped = ctx.pCharacters[]
|
||||
template reveals*(ctx: Context): untyped = ctx.pReveals[]
|
||||
template encountered*(ctx: Context): untyped = ctx.pEncountered[]
|
||||
template visions*(ctx: Context): untyped = ctx.pVisions[]
|
||||
|
||||
proc contextOf*(scene: var SceneRec, tokens: var seq[TokenRec],
|
||||
characters: var seq[CharacterRec], reveals: var Reveals,
|
||||
encountered: var Encountered,
|
||||
visions: var Table[int, PlayerVision]): Context =
|
||||
## Six addresses, not six copies: this is the whole cost of building an egress context (#28).
|
||||
Context(pScene: addr scene, pTokens: addr tokens, pCharacters: addr characters,
|
||||
pReveals: addr reveals, pEncountered: addr encountered, pVisions: addr visions)
|
||||
|
||||
proc borrow*(store: ref ContextStore): Context =
|
||||
## The test/fixture entry point: a heap store outlives the Context that points into it.
|
||||
contextOf(store.scene, store.tokens, store.characters, store.reveals, store.encountered,
|
||||
store.visions)
|
||||
|
||||
proc visionAt(ctx: Context, playerId: int, fallback: var PlayerVision): ptr PlayerVision =
|
||||
## One player's live sight state, borrowed: never a `getOrDefault` copy (#28). A player with no
|
||||
## sight state (never connected) gets `fallback`, an empty record the caller owns, so no GC'd
|
||||
## global is read from a `{.gcsafe.}` handler.
|
||||
if ctx.visions.hasKey(playerId): addr ctx.visions[playerId]
|
||||
else: addr fallback
|
||||
|
||||
proc visibleIds(ctx: Context, playerId: int, pv: ptr PlayerVision): HashSet[string] =
|
||||
## The visibility rule once per recipient per frame: every encountered entry's `grey` is then a
|
||||
## set test, not a token scan plus a polygon test per entry (#28).
|
||||
for t in ctx.tokens:
|
||||
if pv[].visibleTo(t, playerId): result.incl t.id
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------
|
||||
# Typed views
|
||||
|
||||
@@ -157,10 +206,13 @@ proc characterOf(ctx: Context, t: TokenRec): Option[CharacterRec] =
|
||||
|
||||
proc greyFor*(ctx: Context, playerId: int, entityId: string): bool =
|
||||
## DESIGN 8 `encountered.grey`: the token is no longer in that player's view, whether because it
|
||||
## moved away, was removed, or became `gm_only`. The entry stays either way.
|
||||
## moved away, was removed, or became `gm_only`. The entry stays either way. This is the
|
||||
## single-entry form (tests, and a caller holding one id); a view builds `visibleIds` once instead
|
||||
## of calling this per entry (#28).
|
||||
let idx = tokenIndex(ctx.tokens, entityId)
|
||||
if idx.isNone: return true
|
||||
not ctx.visions.getOrDefault(playerId).visibleTo(ctx.tokens[idx.get], playerId)
|
||||
var fallback: PlayerVision
|
||||
not visionAt(ctx, playerId, fallback)[].visibleTo(ctx.tokens[idx.get], playerId)
|
||||
|
||||
proc gmView*(ctx: Context): GmView =
|
||||
result.tokens = newSeqOfCap[GmTokenView](ctx.tokens.len)
|
||||
@@ -192,15 +244,20 @@ proc gmView*(ctx: Context): GmView =
|
||||
for pid in ctx.encountered.keys: pids.add pid
|
||||
pids.sort()
|
||||
for pid in pids:
|
||||
# #28: one visibility pass per player's list, then a set test per entry.
|
||||
var fallback: PlayerVision
|
||||
let visible = visibleIds(ctx, pid, visionAt(ctx, pid, fallback))
|
||||
var entries: seq[EncounteredView]
|
||||
for eid, e in ctx.encountered[pid]:
|
||||
entries.add EncounteredView(id: eid, name: e.entryName, grey: ctx.greyFor(pid, eid))
|
||||
entries.add EncounteredView(id: eid, name: e.entryName, grey: eid notin visible)
|
||||
result.encountered.add GmEncounteredView(player: pid, entries: entries)
|
||||
|
||||
proc playerView*(ctx: Context, playerId: int): PlayerView =
|
||||
var pv = ctx.visions.getOrDefault(playerId)
|
||||
# A borrowed pointer, not `getOrDefault`: the explored set is never copied (#28).
|
||||
var noSight: PlayerVision
|
||||
let pv = visionAt(ctx, playerId, noSight)
|
||||
for t in ctx.tokens:
|
||||
if not pv.visibleTo(t, playerId): continue
|
||||
if not pv[].visibleTo(t, playerId): continue
|
||||
let mine = t.owner == playerId
|
||||
let ch = ctx.characterOf(t)
|
||||
let names = subjectNamesOf(t, ctx.characters)
|
||||
@@ -227,9 +284,11 @@ proc playerView*(ctx: Context, playerId: int): PlayerView =
|
||||
actualName: c.actualName,
|
||||
propsPublic: objectOf(c.props[pbPublic]),
|
||||
propsOwner: objectOf(c.props[pbOwner]))
|
||||
for eid, e in ctx.encountered.getOrDefault(playerId):
|
||||
result.encountered.add EncounteredView(id: eid, name: e.entryName,
|
||||
grey: ctx.greyFor(playerId, eid))
|
||||
if ctx.encountered.hasKey(playerId):
|
||||
# #28: one visibility pass for the whole list.
|
||||
let visible = visibleIds(ctx, playerId, pv)
|
||||
for eid, e in ctx.encountered[playerId]:
|
||||
result.encountered.add EncounteredView(id: eid, name: e.entryName, grey: eid notin visible)
|
||||
when defined(leakfault):
|
||||
# Negative controls (DESIGN 10.3): add what the honest rule just refused, so the harness proves
|
||||
# it would notice. Never a second copy of the visibility rule.
|
||||
@@ -250,11 +309,11 @@ proc playerView*(ctx: Context, playerId: int): PlayerView =
|
||||
else: newJObject()))
|
||||
if faultActive("hidden"):
|
||||
for t in ctx.tokens:
|
||||
if t.owner != playerId and not t.gmOnly and not pv.insideAny(t.pos):
|
||||
if t.owner != playerId and not t.gmOnly and not pv[].insideAny(t.pos):
|
||||
result.tokens.add leakedView(t)
|
||||
if faultActive("gmOnly"):
|
||||
for t in ctx.tokens:
|
||||
if t.gmOnly and t.owner != playerId and pv.insideAny(t.pos):
|
||||
if t.gmOnly and t.owner != playerId and pv[].insideAny(t.pos):
|
||||
result.tokens.add leakedView(t)
|
||||
if faultActive("withhold") and result.tokens.len > 1:
|
||||
for i in countdown(result.tokens.high, 0):
|
||||
@@ -308,8 +367,8 @@ proc playerView*(ctx: Context, playerId: int): PlayerView =
|
||||
if ch.isNone or ch.get.owner == playerId: continue
|
||||
for v in result.tokens.mitems:
|
||||
if v.id == t.id: v.cpropsPublic = objectOf(ch.get.props[pbOwner])
|
||||
result.polys = pv.polys
|
||||
result.fresh = pv.fresh
|
||||
result.polys = pv[].polys
|
||||
result.fresh = pv[].fresh
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------
|
||||
# Frames. These builders are the only producers of state frames in the server.
|
||||
@@ -537,7 +596,8 @@ proc egressFrames*(r: Recipient, ctx: Context, known: var Known, resync = false)
|
||||
var polysJson = visionPolyJson(view.polys)
|
||||
when defined(leakfault):
|
||||
if faultActive("otherVision"):
|
||||
let other = ctx.visions.getOrDefault(ctx.otherPlayerId(r.playerId))
|
||||
var otherStore: PlayerVision
|
||||
let other = visionAt(ctx, ctx.otherPlayerId(r.playerId), otherStore)[]
|
||||
for p in other.polys:
|
||||
var pts = newJArray()
|
||||
for q in p.pts: pts.add %*[int(round(q.x)), int(round(q.y))]
|
||||
@@ -548,14 +608,16 @@ proc egressFrames*(r: Recipient, ctx: Context, known: var Known, resync = false)
|
||||
result.add %*{"t": "vision", "polys": polysJson}
|
||||
|
||||
if resync:
|
||||
result.add exploredFullFrame(ctx.visions.getOrDefault(r.playerId).exploredFull(ctx.scene))
|
||||
var noSight: PlayerVision
|
||||
result.add exploredFullFrame(visionAt(ctx, r.playerId, noSight)[].exploredFull(ctx.scene))
|
||||
elif view.fresh.len > 0:
|
||||
var fresh = view.fresh
|
||||
when defined(leakfault):
|
||||
if faultActive("explored"):
|
||||
fresh.add (ctx.scene.cols - 1, ctx.scene.rows - 1)
|
||||
if faultActive("otherExplored"):
|
||||
let other = ctx.visions.getOrDefault(ctx.otherPlayerId(r.playerId))
|
||||
var otherStore: PlayerVision
|
||||
let other = visionAt(ctx, ctx.otherPlayerId(r.playerId), otherStore)[]
|
||||
fresh.add other.exploredFull(ctx.scene)
|
||||
result.add exploredFreshFrame(fresh)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user