aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


commit f978a2f3f0dfec57c0fffdbfbd2f97c5a2749443
parent 571a7661159c776f7ca996b645b3831d0fa57041
Author: anon <anon@example.com>
Date:   Sat,  7 Nov 2026 02:51:33 +0000

Batch simulation checkpoints and defer periodic health persistence

Diffstat:
MDEVELOPERS.md | 12+++++++++---
MTODO.md | 3+++
Mserver/nano_buffs.go | 11++++++++---
Mserver/nano_casting_test.go | 1+
Mserver/nano_hot_catalog_test.go | 3+++
Mserver/nano_hot_test.go | 17+++++++++++++----
Mserver/nano_periodic.go | 29+++++++++++++++--------------
Mserver/nano_periodic_test.go | 34++++++++++++++++++++++------------
Mserver/npc_checkpoint_batch_test.go | 46++++++++++++++++++++++++++++++++++------------
Mserver/npc_outcome.go | 2+-
Aserver/player_checkpoint_batch_test.go | 64++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/users.go | 31+++++++++++++++++++++----------
Mserver/world_store.go | 13+++++++++++--
13 files changed, 205 insertions(+), 61 deletions(-)

diff --git a/DEVELOPERS.md b/DEVELOPERS.md @@ -46,9 +46,15 @@ and rewards commit atomically before success is reported. See [inventory behavior](docs/inventory.md) for the current scope and wire evidence. Movement updates memory immediately. Player poses and vitals are checked once -per second and checkpointed on staggered 20-second schedules; unchanged values -are not rewritten. Observed NPCs also use periodic checkpoints, with staggered -starts and a final snapshot when their zone becomes unobserved. An unexpected +per second and checkpointed on staggered 20-second schedules. All due players +share one transaction, including effect progress; failed batches retain their +saved basis and deadline for retry. Unchanged values are not rewritten. +Nonfatal periodic damage and healing advance in memory. Death, rewards, loot +and effect installation/removal still commit coherently before publication. +Observed NPCs use periodic checkpoints, with staggered starts and a final +snapshot when their zone becomes unobserved. Living authored NPCs restart at +home with their checkpointed health, contributions and effects; roaming poses, +routes and timers do not generate writes. Corpses and pets retain their location. An unexpected stop can lose simulation changes since the last checkpoint. Ctrl+C or SIGTERM flushes player positions and world state before closing the database; check `logs/server.log` for shutdown errors. diff --git a/TODO.md b/TODO.md @@ -90,6 +90,9 @@ research separately. More screenshots and test cases do not count as new gamepla not block movement or metadata publication. Vicinity selects local recipients in the zone, then waits for chat outside it. Mission lifecycle, production routing and final checkpoint coordination remain open; this gate is not closed. + Player checkpoints now batch due actors into one transaction; nonfatal periodic + damage/healing waits for checkpoints. Living authored NPCs restart at home, + retaining checkpointed health, contributions and effects without roaming writes. - [x] **Use the original native character creation flow.** Login credentials are collected in a compact modal with password confirmation at native naming, diff --git a/server/nano_buffs.go b/server/nano_buffs.go @@ -351,13 +351,18 @@ func (server *server) loadActiveNanos() error { } func (server *server) saveActiveNanos_locked(player *character, now time.Time) error { - previous := server.characters[player.id] + // Persist effect changes with the health and progress they describe, even + // when earlier ticks have only advanced the in-memory state. + if player.npc { + _, err := server.saveDamageOutcome_locked(player, now) + return err + } write := activeNanosWrite{player: player.id, effects: slices.Clone(player.activeNanos), now: now, - health: player.health, nano: player.nano, updateVitals: player.health != previous.health || player.nano != previous.nano} + health: player.health, nano: player.nano, updateVitals: player.health != player.savedVitals.Health || player.nano != player.savedVitals.Nano} if err := server.commitWrite(write); err != nil { return err } - if player.health != previous.health || player.nano != previous.nano { + if player.health != player.savedVitals.Health || player.nano != player.savedVitals.Nano { player.savedVitals.Health, player.savedVitals.Nano = player.health, player.nano } return nil diff --git a/server/nano_casting_test.go b/server/nano_casting_test.go @@ -13,6 +13,7 @@ func newNanoCastingWorld(t *testing.T) (*server, *combatTestConn) { t.Helper() t.Chdir(t.TempDir()) world, conn := newCombatWorld(t) + world.nextCharacter = 1 player := world.characters[1] player.name = "Nano Caster" player.profession, player.nano = 8, 30 diff --git a/server/nano_hot_catalog_test.go b/server/nano_hot_catalog_test.go @@ -143,6 +143,9 @@ func TestHealingOverTimeCrystalsLearnTickClampAndExpire(t *testing.T) { t.Fatal("HoT changed HP immediately, lost NCU or charged the wrong cost") } world.advanceNanos(at.Add(time.Duration(fixture.TickInterval) * 10 * time.Millisecond)) + if err := world.flushPositions(at.Add(time.Duration(fixture.TickInterval)*10*time.Millisecond + 20*time.Second)); err != nil { + t.Fatal(err) + } cold := newTestInventoryServer(t).characters[1] if player.health < 1+fixture.Minimum || player.health > 1+fixture.Maximum || cold.health != player.health || len(cold.activeNanos) != 1 || cold.activeNanos[0].ticksLeft != fixture.TickCount-1 { diff --git a/server/nano_hot_test.go b/server/nano_hot_test.go @@ -45,6 +45,9 @@ func TestHealingOverTimeCrystalSchedulesFirstTick(t *testing.T) { t.Fatal("HoT healed before its first interval") } world.advanceNanos(completed.Add(5 * time.Second)) + if err := world.flushPositions(completed.Add(25 * time.Second)); err != nil { + t.Fatal(err) + } cold := newTestInventoryServer(t).characters[1] if player.health < 3 || player.health > 7 || player.nano != 116 || player.usedNCU() != 1 || @@ -53,7 +56,7 @@ func TestHealingOverTimeCrystalSchedulesFirstTick(t *testing.T) { } } -func TestHealingOverTimeFailedTickRollsBackAndRetries(t *testing.T) { +func TestHealingOverTimeTicksContinueWithoutDatabaseWrites(t *testing.T) { for _, failure := range []string{"health", "ignored health", "ticks", "ignored ticks", "commit"} { t.Run(failure, func(t *testing.T) { world, conn := newHealingOverTimeWorld(t, healingOverTimeFixtures(t)[0]) @@ -84,9 +87,9 @@ func TestHealingOverTimeFailedTickRollsBackAndRetries(t *testing.T) { world.advanceNanos(at) cold := newTestInventoryServer(t).characters[1] - if player.health != player.maximumHealth()-1 || cold.health != player.health || - player.activeNanos[0].ticksLeft != 40 || cold.activeNanos[0].ticksLeft != 40 || len(conn.packets) != 0 { - t.Fatal("failed HoT tick published HP or consumed progress") + if player.health != player.maximumHealth() || cold.health != player.maximumHealth()-1 || + player.activeNanos[0].ticksLeft != 39 || cold.activeNanos[0].ticksLeft != 40 || len(conn.packets) != 1 { + t.Fatal("HoT tick waited for persistence or wrote its progress") } if _, err := world.db.Exec("DROP TRIGGER fail_hot"); err != nil { t.Fatal(err) @@ -97,6 +100,9 @@ func TestHealingOverTimeFailedTickRollsBackAndRetries(t *testing.T) { go func() { defer visitors.Done(); world.advanceNanos(at) }() } visitors.Wait() + if err := world.flushPositions(at.Add(20 * time.Second)); err != nil { + t.Fatal(err) + } cold = newTestInventoryServer(t).characters[1] if player.health != player.maximumHealth() || cold.health != player.health || player.activeNanos[0].ticksLeft != 39 || cold.activeNanos[0].ticksLeft != 39 || len(conn.packets) != 1 { t.Fatal("retry or concurrent visitors duplicated a tick or lost its clamped HP") @@ -228,6 +234,9 @@ func TestHealingOverTimeSurvivesUnavailableCaster(t *testing.T) { delete(world.clients, 1) world.advanceNanos(at.Add(5 * time.Second)) + if err := world.flushPositions(at.Add(25 * time.Second)); err != nil { + t.Fatal(err) + } cold := newTestInventoryServer(t).characters[2] if patient.health < 3 || patient.health > 7 || cold.health != patient.health || patient.activeNanos[0].ticksLeft != 39 || cold.activeNanos[0].ticksLeft != 39 { diff --git a/server/nano_periodic.go b/server/nano_periodic.go @@ -51,11 +51,16 @@ func (server *server) advancePeriodicNanos_locked(now time.Time, affected []*cha } candidate.updateMovementPermission(target, now) - // Damage, tick progress, contribution and any death/reward commit together. - award, err := server.saveDamageOutcome_locked(&candidate, now) - if err != nil { - log.Printf("Periodic nano outcome: %v", err) - continue + // Ordinary damage and tick progress share the next checkpoint. Death + // must commit its contribution, corpse and rewards before publication. + var award *experienceAward + if candidate.health == 0 { + var err error + award, err = server.saveDamageOutcome_locked(&candidate, now) + if err != nil { + log.Printf("Periodic nano outcome: %v", err) + continue + } } previous := *target *target = candidate @@ -76,7 +81,7 @@ func (server *server) advanceHealingNanos_locked(now time.Time, affected []*char continue } - // Commit all due recovery and tick progress before publishing an HP snapshot. + // Advance recovery and tick progress together in memory. candidate := *target candidate.activeNanos = slices.Clone(target.activeNanos) var packets [][]byte @@ -109,15 +114,11 @@ func (server *server) advanceHealingNanos_locked(now time.Time, affected []*char effect.ticksLeft-- effect.nextTick = effect.nextTick.Add(time.Duration(hit.TickInterval) * 10 * time.Millisecond) } - var err error if candidate.health == 0 { - _, err = server.saveDamageOutcome_locked(&candidate, now) - } else { - err = server.saveActiveNanos_locked(&candidate, now) - } - if err != nil { - log.Printf("Periodic player nano outcome: %v", err) - continue + if _, err := server.saveDamageOutcome_locked(&candidate, now); err != nil { + log.Printf("Periodic player nano outcome: %v", err) + continue + } } previous := *target *target = candidate diff --git a/server/nano_periodic_test.go b/server/nano_periodic_test.go @@ -66,7 +66,7 @@ func TestPeriodicNanoColdRestoreRetainsPhaseAndPendingOverdueTicks(t *testing.T) } } -func TestPeriodicNanoConcurrentVisitorsCommitEachTickOnce(t *testing.T) { +func TestPeriodicNanoConcurrentVisitorsApplyEachTickOnce(t *testing.T) { world, conn := newPeriodicNanoWorld(t) at := castPeriodicNano(t, world, 43376) conn.packets = nil @@ -83,7 +83,7 @@ func TestPeriodicNanoConcurrentVisitorsCommitEachTickOnce(t *testing.T) { target := world.characters[1000000] if target.health != 91 || target.activeNanos[0].ticksLeft != 5 || len(conn.packets) != 3 || - newTestInventoryServer(t).characters[1000000].health != 91 { + newTestInventoryServer(t).characters[1000000].health != 100 { t.Fatal("concurrent visitors duplicated the three due ticks") } } @@ -267,6 +267,12 @@ func TestPeriodicNanoFinishesItsTicksBeforeItsLongerLifetimeExpires(t *testing.T conn.packets = nil world.advanceNanos(at.Add(40500 * time.Millisecond)) + saved := world.savedNPCs[target.id] + saved.NextSave = at + world.savedNPCs[target.id] = saved + if err := world.checkpointWorld(at.Add(40500 * time.Millisecond)); err != nil { + t.Fatal(err) + } cold := newTestInventoryServer(t).characters[1000000] world.advanceNanos(at.Add(45*time.Second - time.Nanosecond)) if target.health != 847 || len(target.activeNanos) != 1 || target.activeNanos[0].ticksLeft != 0 || @@ -362,14 +368,14 @@ func TestPeriodicNanoWaitsForItsDeadlineAndDoesNotWriteBetweenTicks(t *testing.T t.Fatal(err) } - if target.health != 97 || len(conn.packets) != 1 || ticks != 7 || delay != 7500*time.Millisecond || - cold.health != 97 || len(cold.activeNanos) != 1 || cold.activeNanos[0].ticksLeft != 7 || cold.activeNanos[0].remaining != 52500*time.Millisecond || - checkpointWrites(t, world)["active_nanos/UPDATE"] != 1 || checkpointWrites(t, world)["characters/UPDATE"] != 1 { - t.Fatal("exact-deadline tick did not commit one damage and timer advance", ticks, delay, checkpointWrites(t, world)) + if target.health != 97 || len(conn.packets) != 1 || ticks != 8 || delay != 7500*time.Millisecond || + cold.health != 100 || len(cold.activeNanos) != 1 || cold.activeNanos[0].ticksLeft != 8 || cold.activeNanos[0].remaining != 60*time.Second || + len(checkpointWrites(t, world)) != 0 { + t.Fatal("exact-deadline tick failed to advance in memory without database writes", ticks, delay, checkpointWrites(t, world)) } } -func TestPeriodicNanoFailedTicksRetainTheirExactPendingDamageForRetry(t *testing.T) { +func TestPeriodicNanoNonfatalTicksDoNotWriteToDatabase(t *testing.T) { for _, failure := range []struct{ name, statement string }{ {"health", "CREATE TRIGGER fail_tick BEFORE UPDATE OF health ON characters WHEN NEW.id=1000000 BEGIN SELECT RAISE(FAIL, 'health'); END"}, {"ignored health", "CREATE TRIGGER fail_tick BEFORE UPDATE OF health ON characters WHEN NEW.id=1000000 BEGIN SELECT RAISE(IGNORE); END"}, @@ -385,7 +391,6 @@ func TestPeriodicNanoFailedTicksRetainTheirExactPendingDamageForRetry(t *testing target := world.characters[1000000] at := castPeriodicNano(t, world, 43376) previous := world.savedNPCs[target.id] - effect := target.activeNanos[0] if _, err := world.db.Exec(failure.statement); err != nil { t.Fatal(err) } @@ -394,15 +399,20 @@ func TestPeriodicNanoFailedTicksRetainTheirExactPendingDamageForRetry(t *testing world.advanceNanos(at.Add(22500 * time.Millisecond)) cold := newTestInventoryServer(t).characters[1000000] - if target.health != 100 || cold.health != 100 || len(conn.packets) != 0 || target.activeNanos[0] != effect || - cold.activeNanos[0].ticksLeft != 8 || !reflect.DeepEqual(world.savedNPCs[target.id], previous) || len(target.damageContributors) != 0 { - t.Fatal("failed batch published health, credit or tick progress") + if target.health != 91 || cold.health != 100 || len(conn.packets) != 3 || target.activeNanos[0].ticksLeft != 5 || + cold.activeNanos[0].ticksLeft != 8 || !reflect.DeepEqual(world.savedNPCs[target.id], previous) || target.damageContributors[damageContributor{player: 1}] != 9 { + t.Fatal("nonfatal ticks waited for persistence or advanced the saved basis") } if _, err := world.db.Exec("DROP TRIGGER fail_tick"); err != nil { t.Fatal(err) } world.advanceNanos(at.Add(22500 * time.Millisecond)) - world.advanceNanos(at.Add(22500 * time.Millisecond)) + saved := world.savedNPCs[target.id] + saved.NextSave = at + world.savedNPCs[target.id] = saved + if err := world.checkpointWorld(at.Add(22500 * time.Millisecond)); err != nil { + t.Fatal(err) + } if target.health != 91 || target.activeNanos[0].ticksLeft != 5 || len(conn.packets) != 3 || target.damageContributors[damageContributor{player: 1}] != 9 || newTestInventoryServer(t).characters[1000000].health != 91 { t.Fatal("retry did not apply exactly the three pending ticks") diff --git a/server/npc_checkpoint_batch_test.go b/server/npc_checkpoint_batch_test.go @@ -29,18 +29,18 @@ func newNPCCheckpointPopulation(t *testing.T, count int) (*server, time.Time) { } func TestNPCCheckpointBatchesOnlyChangedTables(t *testing.T) { - for _, change := range []string{"position", "route", "both"} { + for _, change := range []string{"health", "roaming", "both"} { t.Run(change, func(t *testing.T) { world, start := newNPCCheckpointPopulation(t, 1000) for _, npc := range world.characters { if !npc.npc { continue } - if change != "route" { - npc.position[0] = 53 + if change != "roaming" { + npc.health = 53 } - if change != "position" { - npc.motion.destination[0] = 53 + if change != "health" { + npc.motion.roaming = false } } queries := world.databaseQueries.Load() @@ -58,11 +58,11 @@ func TestNPCCheckpointBatchesOnlyChangedTables(t *testing.T) { t.Fatalf("1000 NPC checkpoints: got %d queries, want %d", got, want) } var positions, routes int - if err := world.db.QueryRow(`SELECT sum(position_x=53), sum(destination_x=53) + if err := world.db.QueryRow(`SELECT sum(health=53), sum(idle_roaming=0) FROM characters JOIN npcs USING(id)`).Scan(&positions, &routes); err != nil { t.Fatal(err) } - if change != "route" && positions != 1000 || change != "position" && routes != 1000 { + if change != "roaming" && positions != 1000 || change != "health" && routes != 1000 { t.Fatal("batch lost NPC state", positions, routes) } deadlines := make(map[time.Time]bool) @@ -97,12 +97,12 @@ func TestNPCCheckpointBatchFailureRollsBackAndRetries(t *testing.T) { before := maps.Clone(world.savedNPCs) for _, npc := range world.characters { if npc.npc { - npc.position[0], npc.motion.destination[0] = 53, 53 + npc.health, npc.motion.home[0] = 53, 53 } } - column := "position_x" + column := "health" if table == "npcs" { - column = "destination_x" + column = "home_x" } // Fail after two full batches have already written inside the transaction. if _, err := world.db.Exec("CREATE TRIGGER reject_checkpoint BEFORE UPDATE ON " + table + @@ -118,7 +118,7 @@ func TestNPCCheckpointBatchFailureRollsBackAndRetries(t *testing.T) { var changed int if err := world.db.QueryRow(`SELECT count(*) FROM characters JOIN npcs USING(id) - WHERE position_x=53 OR destination_x=53`).Scan(&changed); err != nil { + WHERE health=53 OR home_x=53`).Scan(&changed); err != nil { t.Fatal(err) } if changed != 0 || !reflect.DeepEqual(before, world.savedNPCs) { @@ -131,10 +131,32 @@ func TestNPCCheckpointBatchFailureRollsBackAndRetries(t *testing.T) { t.Fatal(err) } if err := world.db.QueryRow(`SELECT count(*) FROM characters JOIN npcs USING(id) - WHERE position_x=53 AND destination_x=53`).Scan(&changed); err != nil || changed != 250 { + WHERE health=53 AND home_x=53`).Scan(&changed); err != nil || changed != 250 { t.Fatal("checkpoint retry lost rows", changed, err) } }) } } } + +func TestLivingNPCRoamingDoesNotWriteCheckpoints(t *testing.T) { + world, start := newNPCCheckpointPopulation(t, 1) + npc := world.characters[1000000] + npc.position[0] = 53 + npc.rotation = [4]float32{0, 1, 0, 0} + npc.motion.destination[0] = 55 + npc.motion.moving = true + npc.motion.nextMove = start.Add(time.Second) + queries := world.databaseQueries.Load() + + if err := world.checkpointWorld(start.Add(time.Minute)); err != nil { + t.Fatal(err) + } + if world.databaseQueries.Load() != queries { + t.Fatal("roaming generated database work") + } + restored := newTestInventoryServer(t).characters[1000000] + if restored.position != [3]float32{52, 14, 56} || restored.motion.moving || restored.motion.destination != restored.motion.home { + t.Fatal("living NPC did not restart at home with a fresh route") + } +} diff --git a/server/npc_outcome.go b/server/npc_outcome.go @@ -222,7 +222,7 @@ func (server *server) saveNanoOutcome_locked(player, target *character, now time batch = append(batch, recordUpdate{"characters", "health", player.id, []any{player.health}}) } var npc *npcOutcomeWrite - healthChanged := !target.npc && target.health != server.characters[target.id].health + healthChanged := !target.npc && target.health != target.savedVitals.Health if target.npc { var err error npc, err = server.prepareNPCOutcome_locked(target, now) diff --git a/server/player_checkpoint_batch_test.go b/server/player_checkpoint_batch_test.go @@ -0,0 +1,64 @@ +package main + +import ( + "context" + "net/http" + "net/url" + "testing" + "time" +) + +func TestPlayerCheckpointBatchCommitsOnceAndRetriesTogether(t *testing.T) { + world := newCheckpointWorld(t) + response := postControlForm(world, "/admin/players", url.Values{"name": {"Second"}}) + if response.Code != http.StatusSeeOther { + t.Fatal(response.Body.String()) + } + now := time.Now() + for _, id := range []uint32{1, 2} { + world.characters[id].position[0] = 123 + world.characters[id].nextPositionSave = now + } + if _, err := world.db.Exec("CREATE TRIGGER reject_second BEFORE UPDATE ON characters WHEN NEW.id=2 BEGIN SELECT RAISE(ABORT, 'second player'); END"); err != nil { + t.Fatal(err) + } + + if err := world.flushPositions(now); err == nil { + t.Fatal("partial checkpoint succeeded") + } + var changed int + if err := world.db.QueryRow("SELECT count(*) FROM characters WHERE id IN (1,2) AND position_x=123").Scan(&changed); err != nil || changed != 0 { + t.Fatal("failed batch committed its first player", changed, err) + } + for _, id := range []uint32{1, 2} { + if world.characters[id].savedPosition.Position[0] == 123 || !world.characters[id].nextPositionSave.Equal(now) { + t.Fatal("failed batch advanced its saved basis or deadline") + } + } + if _, err := world.db.Exec("DROP TRIGGER reject_second"); err != nil { + t.Fatal(err) + } + connection, err := world.db.Conn(context.Background()) + if err != nil { + t.Fatal(err) + } + commits := 0 + err = connection.Raw(func(driver any) error { + driver.(*databaseConnection).RegisterCommitHook(func() int { commits++; return 0 }) + return nil + }) + connection.Close() + if err != nil { + t.Fatal(err) + } + + if err := world.flushPositions(now.Add(time.Second)); err != nil { + t.Fatal(err) + } + if commits != 1 { + t.Fatal("players did not share one checkpoint transaction", commits) + } + if err := world.db.QueryRow("SELECT count(*) FROM characters WHERE id IN (1,2) AND position_x=123").Scan(&changed); err != nil || changed != 2 { + t.Fatal("retry lost player positions", changed, err) + } +} diff --git a/server/users.go b/server/users.go @@ -2,7 +2,6 @@ package main import ( "ao/server/gamedata" - "errors" "fmt" "io" "log" @@ -239,24 +238,36 @@ func (server *server) savePosition_locked(character *character) error { func (server *server) flushPositions(now time.Time) error { server.mutex.Lock() defer server.mutex.Unlock() - var saveErr error + var batch databaseBatch + var players []*character // Player IDs are below the NPC range, so saving never needs to scan NPCs. for id := uint32(1); id <= server.nextCharacter; id++ { character := server.characters[id] - if character == nil || character.savedProfile.ID == 0 { + if character == nil || character.savedProfile.ID == 0 || now.Before(character.nextPositionSave) { continue } - if now.Before(character.nextPositionSave) { - continue + position := playerPosition{character.playfield, character.position, character.rotation, character.returnDoor} + vitals := character.vitals() + changed := position != character.savedPosition || vitals != character.savedVitals + if changed || len(character.activeNanos) != 0 { + batch = append(batch, playerPositionWrite{record: character.record(), effects: slices.Clone(character.activeNanos), now: now, updatePosition: changed}) + } + players = append(players, character) + } + // A checkpoint is one transaction. Failed batches retain every saved basis + // and deadline so the next visitor retries the current state together. + if len(batch) != 0 { + if err := server.commitWrite(batch); err != nil { + return err } - // Keep the player's phase even when a scheduler tick is delayed. + } + for _, character := range players { + character.savedPosition = playerPosition{character.playfield, character.position, character.rotation, character.returnDoor} + character.savedVitals = character.vitals() intervals := now.Sub(character.nextPositionSave)/(20*time.Second) + 1 character.nextPositionSave = character.nextPositionSave.Add(intervals * 20 * time.Second) - if err := server.savePosition_locked(character); err != nil { - saveErr = errors.Join(saveErr, fmt.Errorf("player %d: %w", character.id, err)) - } } - return saveErr + return nil } func (server *server) saveWorld() { diff --git a/server/world_store.go b/server/world_store.go @@ -77,6 +77,13 @@ func (npc *character) worldState(present bool, respawnAt time.Time) npcState { state.IdleRoaming = npc.motion.roaming state.Motion = motionState{npc.motion.home, npc.motion.destination, npc.motion.nextMove, npc.motion.moving, npc.motion.returning} } + // Living authored NPCs restart at home. Roaming routes and timers are + // disposable; corpses and pets retain their actual location. + if npc.motion != nil && npc.pet == nil && npc.corpse == nil && npc.health != 0 && npc.npcDefinitionID != "" { + state.Character.Position.Position = npc.motion.home + state.Character.Position.Rotation = [4]float32{0, 0, 0, 1} + state.Motion = motionState{Home: npc.motion.home, Destination: npc.motion.home} + } if npc.corpse != nil { state.HasCorpse = true state.Corpse = corpseState{npc.corpse.looter, npc.corpse.team, npc.corpse.credits, npc.corpse.expiresAt, npc.corpse.lootOrder} @@ -377,8 +384,10 @@ func (server *server) checkpointWorld(now time.Time) error { active[id] = true } write := server.prepareNPCWrite_locked(itemStore{checkpointAt: now}, active) - if err := server.commitWrite(write); err != nil { - return err + if len(write.characterRows)+len(write.npcRows)+len(write.contributors)+len(write.effects)+len(write.checkpoint.removed) != 0 { + if err := server.commitWrite(write); err != nil { + return err + } } server.applyNPCCheckpoint_locked(write.checkpoint) server.activeNPCs = active