commit f0debd4139a55f9c7c6b49d4f9bae29de522827f
parent 58176fc4765feb0ee1c9d05b50e522ea5b034d56
Author: anon <anon@example.com>
Date: Wed, 28 Oct 2026 00:01:10 +0000
Reject obstructed combat through shared scene visibility
Use recovered eye-height endpoints, dungeon room admission and bidirectional
scene casts for ordinary attacks, Fast/Fling and nano admission/completion.
Keep costs and outcomes behind visibility checks and preserve refund retries.
Verify blocked/clear encounters, resource conservation and installed effects;
repair the startup-refund fixture's missing database initialization. Record
the native empty-passage visibility gap as a separate progression priority.
Validation: 341 selected server test functions; 5131 distinct passing results
across staged regression batches; race detector 15 functions/55 results;
go vet and build; GPU WASM entrance fight and blocked selection checks.
Diffstat:
11 files changed, 576 insertions(+), 11 deletions(-)
diff --git a/TODO.md b/TODO.md
@@ -447,12 +447,22 @@ capacity checks are recorded in [belts and NCU](docs/belts-ncu.md).
construction. See `local/aggdef-nano-fist-clock-research/findings.md`.
- [x] Replace the approximate melee range check. Check: two actors at known
positions and sizes are accepted or rejected at the recovered range boundary.
-- [ ] [P0] Reject attacks through solid obstructions. Check: the same stationary
- encounter works in the open and fails with a wall between the actors. Include
- vertically separated actors around raised mission scenery: native testing
- allowed fighting a small NPC below the tongue while the player stood above
- it, making corpse picking awkward. Recover shared eye/body LOS and verify
- the actual collision surface; do not add species-specific exceptions.
+- [x] [P0] Reject attacks through solid obstructions. Ordinary swings, Fast/Fling
+ and nano admission/completion share native +1.6Y endpoints, direct room-pair
+ admission and both directional mesh queries. Supported outdoor terrain/static
+ geometry uses the same obstruction check. Tests cover clear retries, both wall
+ directions, raised scenery, destination-room surfaces, missing links, ammunition,
+ special locks and durable cast refunds, including a failed refund followed by
+ reopening the path. Existing DoTs continue behind walls. Native WASM checks
+ distinguish clear-path attack results from occluded target selection; those
+ client selection checks alone do not establish server rejection. See
+ [combat visibility](docs/combat-visibility.md) for evidence and policy limits.
+- [ ] [P0] Synchronize native visibility across open mission passages. The current
+ empty-door-identity passage is traversable, but read-only WASM probes still show
+ room0/room1's visibility pair as open0. Recover the shared registration/status
+ rule or bind real authored doors; verify clear cross-room targeting, ordinary
+ damage presentation and nano casting in both directions. Keep this separate
+ from ray obstruction and do not hardcode a particular room pair as visible.
- [x] Reconcile quiet health without phantom damage feedback. Check: after a
long native fight, prediction drift is corrected to server HP without extra
nanobot-damage chat or floating damage, including for an observer.
diff --git a/docs/combat-client-state-machine.md b/docs/combat-client-state-machine.md
@@ -332,6 +332,10 @@ with +1.6 vertical offsets and actor zone-instance ID. Outdoors this
specific helper performs no raycast. That does not prove the original
server allowed attacks through outdoor walls.
+The server's shared implementation and evidence for the underlying LLR room
+gate and two directional Surface queries are described in
+[combat visibility](combat-visibility.md).
+
When timer hold `0x20` is set, `0x100ab740` increments a retry counter
modulo 5 and, only when it becomes 1, checks target line of sight. It
returns false at other retries. `0x100ab7a0` clears the hold. These are
diff --git a/docs/combat-visibility.md b/docs/combat-visibility.md
@@ -0,0 +1,111 @@
+# Combat visibility
+
+Ordinary attacks, Fast Attack, Fling Shot and targeted nanos share one visibility
+predicate. The predicate uses predicted player positions, current NPC positions
+and a fixed +1.6 Y offset at both ends. It does not change the separate range
+formula or scale the offset by species, model size or equipment.
+
+## Recovered geometry contract
+
+KKR `0x100721d0` supplies those endpoints. For dungeons, original LLR
+`n3Playfield_t::LineOfSight` at `0x1002c090` first calls `RoomCanSeeFromTo`
+at `0x1002c170`, then calls the Surface line query in both directions. Either
+intersection rejects visibility. The Surface query is directional; for room
+surfaces it selects the origin room, falling back to the destination room.
+Consequently the reverse ray also checks the destination room's mesh.
+
+Both dungeon endpoints must belong to rooms. The same room passes the room
+gate; different rooms require an open direct visibility-pair entry. Original
+`IsDoorOpenBetweenRooms` at `0x1002bfd0` checks a sorted room pair and requires
+its status byte to equal 1. It does not search for a path through other rooms.
+Current generated missions have paired passages without dynamic door identities;
+their existing room links supply those open pairs. Closed animated doors and
+broader visibility-pair initialization remain future work.
+
+Read-only WASM probes still report the empty-identity client pair as open0.
+Server passage admission follows the existing traversable-link policy; matching
+client visibility status is an explicit P0 follow-up. A clear server ray across
+that passage does not prove that the client's LOS-dependent presentation works.
+
+The maintained equivalents are `sub_360721D0` in
+`client/game/kkr.dll/lifted-0033.c`, `sub_3802C090`, `sub_3802C170` and
+`sub_3802BFD0` in `client/game/llr.dll/lifted-0018.c`. Fresh original LLR evidence
+is retained in `local/combat-los-research/llr-evidence.json`:
+
+- `ev_f7098e61c96591d8b02b7c427cbb1712b90e6358c378b028b44bb396101bea08`
+ establishes the two Surface calls and their rejection order.
+- `ev_f6bcaa9cb30ce4cd88fcd88dbcb0d051cfb4fc2d8f4cd523693104b8fcdcd66b`
+ establishes room membership and direct-pair admission.
+- Retained door lookup
+ `ev_71bd9ed49c16e7a4976985009e92caa6d47a22847fae67061f224d10b6a13600`
+ is in `local/mission-interior/llr-door-state-evidence.json`.
+
+The original LLR SHA256 is
+`ebb09047f6ead192388f7ddfb4795da5013a60f7c2d1c3933ec02eef58a10132`.
+Existing KKR endpoint evidence and its client scheduling limits are recorded in
+[combat client range and LOS](combat-client-state-machine.md#range-line-of-sight-and-movement).
+
+## Server admission policy
+
+The server applies the two rays to supported outdoor static geometry and terrain
+as well as generated dungeons. This outdoor enforcement is a reconstruction
+choice: the KKR helper skips outdoor raycasting and does not establish original
+server behavior. Worlds without loaded physical geometry retain their existing
+range-only admission. Characters do not become ray blockers.
+
+Visibility is checked before starting an ordinary attack and again before each
+swing's random roll, ammunition debit and durable outcome. Obstruction follows
+the existing range-loss policy: player attacks stop, while profiled NPCs retain
+their opponent, threat and swing deadline and can pursue. Clearing an obstruction
+allows one due NPC swing, without replaying missed swings. Exact original-server
+autoattack cancellation and retry timing remain unverified.
+
+Special attacks check visibility before committing their skill lock and damage.
+Nanos check it before reservation and again at completion. A blocked completion
+uses the existing durable cancellation/refund transaction; failed refunds retain
+the cancelled cast for retry. Reopening the path cannot execute that cast.
+Already installed DoTs and buffs continue normally. Self buffs bypass the
+unnecessary scenery trace after the normal signed range check.
+
+Movement keeps its native single-direction, single-room collision query. Combat
+does not replace it with an all-room trace or a creature-specific exception.
+
+## Verification
+
+The selected regression checks pass 341 server test functions across batches,
+with 5,131 distinct passing test/subtest results including the selected gamedata
+checks. The race-detector run passes 15 test functions and 55 results. The final
+focused visibility and signed-range checks, build and `go vet ./server/...` pass.
+The first broad batch was stopped before its default timeout. Its continuation
+exposed an existing startup-refund fixture that called `loadUsers` without opening
+its database; initializing that cold fixture lets its original failure/retry
+assertions run. Every selected test function subsequently passed.
+
+Handler tests submit blocked unarmed/ranged attacks and specials directly, then
+retry clear paths. They check damage, ammunition, contributions, rewards, skill
+locks, attack clocks and retained NPC threat. Harmful direct/periodic/control and
+friendly nanos check both admission and completion, durable refunds and clear
+retries. A failed refund cannot resurrect the cancelled cast when sight returns.
+An installed DoT continues through later obstruction; self buffs still respect
+signed range. Low scenery below the native query height does not block a Leet.
+Original mission meshes cover an open doorway, a same-room wall, raised scenery,
+invalid room endpoints, destination-only surfaces and an absent direct link.
+Outdoor tests cover both triangle directions and an intervening terrain ridge.
+
+The published WASM client ran on the GPU through the sole HTTPS8443 preview.
+At the ordinary mission entrance, Visitor1 at approximately (15.01,.01,15.5)
+selected Leet1068618 and pressed Q. Captured WebSocket traffic contains that
+native attack request and one ordinary three-point melee result for the same
+target; the screenshot shows the visible Leet and native damage feedback.
+At a confirmed room wall, Tab selected no occluded actor and submitted no attack.
+This native selection observation does not substitute for the direct server
+rejection tests. There were no page exceptions or adapter aborts; two resource404
+console messages remain baseline observations, without an attributed fix here.
+
+Evidence, screenshots, packet captures and test summaries are retained under
+`local/combat-los-research/`. The final entrance smoke is `runtime-open/`; the
+earlier controlled placements in `runtime/` include an invalid-room experiment
+and are not evidence of a valid walkable encounter. Owned clients were closed.
+The test player's normal pose/vitals and affected NPCs were restored, with
+inventory, cash, earned XP and the accepted mission retained. SQLite integrity,
+foreign keys and the original five-actor population were rechecked.
diff --git a/server/combat.go b/server/combat.go
@@ -55,7 +55,7 @@ func (server *server) handleCombat(client *worldClient, body []byte) error {
now := time.Now()
if !player.driving() && binary.BigEndian.Uint32(body[16:20]) == 50000 && target != nil && target.npc &&
target.appearance>>4&7 == 6 && client.npcs[target.id] && target.health > 0 &&
- target.playfield == player.playfield && server.combatInRange_locked(player, target, now) {
+ target.playfield == player.playfield && server.combatInRange_locked(player, target, now) && server.combatVisible_locked(player, target, now) {
server.startAttack_locked(player, target, now, updates)
} else {
if player.fighting == 0 {
@@ -391,8 +391,8 @@ func (server *server) advanceCombat(now time.Time) {
server.stopAttack_locked(attacker, updates)
continue
}
- if !server.combatInRange_locked(attacker, target, now) {
- // Engaged creatures wait for range without restarting combat or their swing.
+ if !server.combatInRange_locked(attacker, target, now) || !server.combatVisible_locked(attacker, target, now) {
+ // Engaged creatures wait for a clear path without restarting their swing.
if !attacker.npc || attacker.combatProfile == nil {
server.stopAttack_locked(attacker, updates)
}
diff --git a/server/combat_visibility.go b/server/combat_visibility.go
@@ -0,0 +1,51 @@
+package main
+
+import "time"
+
+func (server *server) combatVisible_locked(attacker, target *character, now time.Time) bool {
+ if attacker.playfield != target.playfield {
+ return false
+ }
+ if attacker == target || !server.geometry.physical(attacker.playfield) {
+ return true
+ }
+
+ // client/game/kkr.dll/lifted-0033.c::sub_360721D0: global positions +1.6Y.
+ first, second := attacker.position, target.position
+ if !attacker.npc {
+ first = predictedPosition_locked(attacker, now)
+ }
+ if !target.npc {
+ second = predictedPosition_locked(target, now)
+ }
+ first[1] += 1.6
+ second[1] += 1.6
+ return server.geometry.lineOfSight(attacker.playfield, first, second)
+}
+
+func (geometry *sceneGeometry) lineOfSight(playfield uint32, origin, end [3]float32) bool {
+ // client/game/llr.dll/lifted-0018.c::sub_3802C170: same room or direct open pair.
+ if scene := geometry.mission(playfield); scene != nil {
+ first, second := scene.roomAt(origin), scene.roomAt(end)
+ if first == nil || second == nil {
+ return false
+ }
+ if first != second {
+ linked := false
+ for _, link := range scene.links {
+ if link == [2]*placedRoom{first, second} || link == [2]*placedRoom{second, first} {
+ linked = true
+ break
+ }
+ }
+ if !linked {
+ return false
+ }
+ }
+ }
+
+ // client/game/llr.dll/lifted-0018.c::sub_3802C090: cast both room-local directions.
+ ground := geometry.terrain[playfield]
+ return !geometry.line(playfield, ground, origin, end, true).hit &&
+ !geometry.line(playfield, ground, end, origin, true).hit
+}
diff --git a/server/combat_visibility_test.go b/server/combat_visibility_test.go
@@ -0,0 +1,155 @@
+package main
+
+import (
+ "ao/server/gamedata"
+ "testing"
+ "time"
+)
+
+func addCombatWall(world *server) {
+ // One front-facing triangle separates two otherwise reachable outdoor actors.
+ world.geometry = &sceneGeometry{
+ playfields: map[uint32]scenePlayfield{950: {sizeX: 100, sizeZ: 100, cellsX: 1, cellsZ: 1}},
+ terrain: map[uint32]*terrain{950: {width: 2, height: 2, boundsWidth: 2, boundsHeight: 2,
+ spacing: 50, scale: 1, heights: make([]byte, 9)}},
+ surfaces: map[uint32]*sceneSurface{950 << 16: {primary: &surfaceTree{
+ vertices: [][3]float32{{15, 0, 0}, {15, 0, 100}, {15, 10, 0}},
+ groups: []surfaceGroup{{bounds: [6]float32{15, 0, 0, 15, 10, 100}, triangles: [][3]uint32{{0, 1, 2}}}},
+ nodes: []surfaceNode{{groups: []uint32{0}}},
+ }}},
+ }
+ world.characters[1].position = [3]float32{14, 0, 10}
+ world.characters[1000000].position = [3]float32{16, 0, 10}
+}
+
+func TestCombatVisibilityRejectsBothWallDirectionsAndAllowsClearRetry(t *testing.T) {
+ for _, kind := range []string{"unarmed", "ranged"} {
+ for _, reverse := range []bool{false, true} {
+ t.Run(kind+map[bool]string{false: "/front", true: "/back"}[reverse], func(t *testing.T) {
+ world, _ := newCombatWorld()
+ if kind == "ranged" {
+ world, _ = newRangedWorld(t)
+ }
+ addCombatWall(world)
+ player, target := world.characters[1], world.characters[1000000]
+ if reverse {
+ player.position, target.position = target.position, player.position
+ }
+ health := target.health
+ request := attackPacket(1, target.id)[20:]
+
+ if err := world.handleCombat(world.clients[1], request); err != nil {
+ t.Fatal(err)
+ }
+ world.advanceCombat(time.Now().Add(time.Minute))
+
+ if player.fighting != 0 || !player.nextAttack.IsZero() || !player.rechargeUntil.IsZero() || target.health != health ||
+ len(target.damageContributors) != 0 || len(world.fighting) != 0 || target.corpse != nil || player.experience != 0 {
+ t.Fatal("wall admission changed combat or rewards")
+ }
+ if kind == "ranged" && player.inventory.Items[0].Ammo != 3 {
+ t.Fatal("blocked shot consumed ammunition")
+ }
+ target.position = player.position
+ target.position[2] += 2
+ if err := world.handleCombat(world.clients[1], request); err != nil {
+ t.Fatal(err)
+ }
+ world.advanceCombat(player.nextAttack)
+ if target.health >= health || player.fighting != target.id || kind == "ranged" && player.inventory.Items[0].Ammo != 2 {
+ t.Fatal("clear retry failed to land exactly one swing", target.health)
+ }
+ })
+ }
+ }
+}
+
+func TestCombatVisibilityRechecksBeforeShotAndRetainsNPCThreat(t *testing.T) {
+ world, _ := newRangedWorld(t)
+ addCombatWall(world)
+ player, target := world.characters[1], world.characters[1000000]
+ target.position[0] = 12
+ if err := world.handleCombat(world.clients[1], attackPacket(1, target.id)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ deadline := player.nextAttack
+ target.combatProfile = gamedata.NPCCombatProfiles[17655][1]
+ target.threat = map[uint32]int64{1: 10}
+ target.fighting, target.nextAttack = 1, deadline
+ world.fighting[target.id] = target
+ npcDeadline := target.nextAttack
+ target.position[0] = 16
+ rolls := 0
+ world.combatRoll = func(limit uint32) uint32 { rolls++; return limit - 1 }
+
+ world.advanceCombat(deadline.Add(time.Minute))
+ world.advanceCombat(deadline.Add(2 * time.Minute))
+
+ if player.inventory.Items[0].Ammo != 3 || target.health != 1000 || player.health != 100 || rolls != 0 ||
+ player.fighting != 0 || !player.nextAttack.IsZero() || !player.rechargeUntil.IsZero() ||
+ target.fighting != 1 || target.nextAttack != npcDeadline || target.threat[1] != 10 {
+ t.Fatal("obstructed shot or bite changed damage, costs, clocks or threat", player.health, target.nextAttack, npcDeadline)
+ }
+ target.position[0] = 12
+ world.advanceCombat(deadline.Add(3 * time.Minute))
+ if player.health >= 100 || target.health != 1000 || rolls == 0 || target.nextAttack.Before(deadline.Add(3*time.Minute)) {
+ t.Fatal("creature did not resume a single bite after visibility returned")
+ }
+}
+
+func TestCombatVisibilitySpecialsRejectWithoutLocksOrClockChanges(t *testing.T) {
+ for _, skill := range []uint32{147, 150} {
+ t.Run(map[uint32]string{147: "Fast", 150: "Fling"}[skill], func(t *testing.T) {
+ var world *server
+ var request []byte
+ if skill == 147 {
+ world, _ = newFastAttackWorld(t)
+ request = fastAttackRequest(1, 1000000)[20:]
+ } else {
+ world, _ = newRangedWorld(t)
+ request = flingShotRequest(1, 1000000)[20:]
+ }
+ addCombatWall(world)
+ player, client, target := world.characters[1], world.clients[1], world.characters[1000000]
+ player.nextAttack, player.rechargeUntil = time.Now().Add(time.Second), time.Now().Add(time.Hour)
+ attack, recharge := player.nextAttack, player.rechargeUntil
+ client.nanoCast = &nanoCast{target: target.id, readyAt: time.Now().Add(time.Minute)}
+ cast := client.nanoCast
+
+ if err := world.handleWeaponSpecial(client, request); err != nil {
+ t.Fatal(err)
+ }
+
+ if target.health != 1000 || !player.skillLocks[skill].IsZero() || player.nextAttack != attack ||
+ player.rechargeUntil != recharge || client.nanoCast != cast || len(target.damageContributors) != 0 {
+ t.Fatal("obstructed special changed damage, lock or another action clock")
+ }
+ target.position[0] = 12
+ if err := world.handleWeaponSpecial(client, request); err != nil {
+ t.Fatal(err)
+ }
+ if target.health >= 1000 || player.skillLocks[skill].IsZero() || player.nextAttack != attack || player.rechargeUntil != recharge ||
+ client.nanoCast != cast || skill == 150 && player.inventory.Items[0].Ammo != 3 {
+ t.Fatal("clear special retry lost damage, independent clocks or pre-15.5 ammo behavior")
+ }
+ })
+ }
+}
+
+func TestCombatVisibilityUsesNativeEyeHeightAboveLowScenery(t *testing.T) {
+ world, _ := newCombatWorld()
+ addCombatWall(world)
+ wall := world.geometry.surfaces[950<<16].primary
+ wall.vertices[2][1], wall.groups[0].bounds[4] = 1, 1
+ player, target := world.characters[1], world.characters[1000000]
+ target.monsterData = 17655
+
+ if err := world.handleCombat(world.clients[1], attackPacket(1, target.id)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ world.advanceCombat(player.nextAttack)
+
+ if player.fighting != target.id || target.health >= 100 {
+ t.Fatal("low scenery blocked native eye-height rays for a small creature")
+ }
+}
diff --git a/server/nano_casting.go b/server/nano_casting.go
@@ -111,7 +111,7 @@ func (server *server) nanoTarget_locked(player, target *character, client *world
x, y, z := float64(first[0])-float64(second[0]), float64(first[1])-float64(second[1]), float64(first[2])-float64(second[2])
// kkr.dll 10066328..10066390 checks the float32 3D distance after its integer gate.
distance := float32(math.Sqrt(x*x + y*y + z*z))
- return distance <= float32(player.nanoRange(program))
+ return distance <= float32(player.nanoRange(program)) && server.combatVisible_locked(player, target, now)
}
func (server *server) handleNanoCast(client *worldClient, body []byte) error {
diff --git a/server/nano_reservation_test.go b/server/nano_reservation_test.go
@@ -175,6 +175,9 @@ func TestNanoReservationStartupFailureRetainsRefundForRetry(t *testing.T) {
t.Fatal(err)
}
restarted := &server{characters: make(map[uint32]*character)}
+ if _, err := restarted.database(); err != nil {
+ t.Fatal(err)
+ }
t.Cleanup(func() { restarted.db.Close() })
err := restarted.loadUsers()
diff --git a/server/nano_visibility_test.go b/server/nano_visibility_test.go
@@ -0,0 +1,145 @@
+package main
+
+import (
+ "testing"
+ "time"
+)
+
+func TestNanoVisibilityRejectsAdmissionAndRefundsObstructedCompletion(t *testing.T) {
+ for _, kind := range []string{"direct", "periodic", "control", "friendly"} {
+ t.Run(kind, func(t *testing.T) {
+ var world *server
+ program := uint32(29618)
+ switch kind {
+ case "direct":
+ world, _ = newNanoOutcomeWorld(t, 100)
+ case "periodic":
+ world, _ = newPeriodicNanoWorld(t)
+ program = 43376
+ case "control":
+ fixture := controlNanoFixtures(t)[0]
+ world, _ = newCombatNanoWorld(t, combatNanoFixture{Profession: fixture.Profession, Crystal: fixture.Crystal})
+ if err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 64, 1)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ program = fixture.Program
+ case "friendly":
+ world, _ = newNanoBuffWorld(t)
+ program = 27169
+ }
+ addCombatWall(world)
+ player, target, client := world.characters[1], world.characters[1000000], world.clients[1]
+ if kind == "friendly" {
+ recipient := *player
+ recipient.id, recipient.name, recipient.position = 2, "Recipient", target.position
+ world.characters[2], world.nextCharacter, target = &recipient, 2, &recipient
+ world.clients[2] = &worldClient{id: 2, conn: &combatTestConn{}, ready: true, target: true}
+ if err := world.saveUser_locked(target); err != nil {
+ t.Fatal(err)
+ }
+ }
+ nano, health := player.nano, target.health
+ request := characterActionPacket(1, [5]uint32{19, 50000, target.id, 53019, program})[20:]
+
+ if err := world.handleNanoCast(client, request); err != nil {
+ t.Fatal(err)
+ }
+
+ if client.nanoCast != nil || player.nano != nano || player.nanoReserved != 0 || !player.nanoRechargeUntil.IsZero() || target.health != health {
+ t.Fatal("obstructed admission reserved energy or started an action")
+ }
+ target.position[0] = 12
+ if err := world.handleNanoCast(client, request); err != nil {
+ t.Fatal(err)
+ }
+ if client.nanoCast == nil || player.nanoReserved == 0 {
+ t.Fatal("clear cast was not admitted")
+ }
+ at := client.nanoCast.readyAt.Add(time.Nanosecond)
+ target.position[0] = 16
+ world.advanceNanos(at)
+ world.advanceNanos(at.Add(time.Minute))
+ var storedNano, storedReserve uint32
+ if err := world.db.QueryRow("SELECT nano,nano_reserved FROM characters WHERE id=1").Scan(&storedNano, &storedReserve); err != nil {
+ t.Fatal(err)
+ }
+ if client.nanoCast != nil || player.nano != nano || player.nanoReserved != 0 || storedNano != nano || storedReserve != 0 ||
+ !player.nanoRechargeUntil.IsZero() || target.health != health || len(target.activeNanos) != 0 || len(target.threat) != 0 ||
+ len(target.damageContributors) != 0 || target.corpse != nil || player.experience != 0 {
+ t.Fatal("obstructed completion failed to refund exactly once or applied an effect")
+ }
+ target.position[0] = 12
+ if err := world.handleNanoCast(client, request); err != nil {
+ t.Fatal(err)
+ }
+ if client.nanoCast == nil {
+ t.Fatal("refunded cast could not be retried with a clear path")
+ }
+ world.advanceNanos(client.nanoCast.readyAt.Add(time.Nanosecond))
+ if player.nano >= nano || player.nanoReserved != 0 || kind == "direct" && target.health >= health ||
+ kind != "direct" && len(target.activeNanos) != 1 {
+ t.Fatal("clear retry failed to commit its resource debit and effect")
+ }
+ })
+ }
+}
+
+func TestNanoVisibilityFailedRefundCannotExecuteWhenPathReopens(t *testing.T) {
+ world, _ := newNanoOutcomeWorld(t, 1)
+ addCombatWall(world)
+ player, target, client := world.characters[1], world.characters[1000000], world.clients[1]
+ target.position[0] = 12
+ if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, target.id, 53019, 29618})[20:]); err != nil {
+ t.Fatal(err)
+ }
+ at := client.nanoCast.readyAt.Add(time.Nanosecond)
+ if _, err := world.db.Exec("CREATE TRIGGER fail_refund BEFORE UPDATE OF nano_reserved ON characters WHEN NEW.id=1 AND NEW.nano_reserved=0 BEGIN SELECT RAISE(FAIL, 'test refund'); END"); err != nil {
+ t.Fatal(err)
+ }
+ target.position[0] = 16
+
+ world.advanceNanos(at)
+ target.position[0] = 12
+ world.advanceNanos(at.Add(time.Second))
+
+ if client.nanoCast == nil || !client.nanoCast.cancelled || player.nano != 21 || player.nanoReserved != 9 || target.health != 1 || target.corpse != nil {
+ t.Fatal("failed refund let the reopened path resurrect a cancelled cast")
+ }
+ if _, err := world.db.Exec("DROP TRIGGER fail_refund"); err != nil {
+ t.Fatal(err)
+ }
+ world.advanceNanos(client.nanoCast.readyAt.Add(time.Nanosecond))
+ world.advanceNanos(at.Add(time.Minute))
+ if client.nanoCast != nil || player.nano != 30 || player.nanoReserved != 0 || target.health != 1 || target.corpse != nil || player.experience != 0 {
+ t.Fatal("refund retry changed the target or duplicated the resource return")
+ }
+}
+
+func TestNanoVisibilityDoesNotInterruptInstalledPeriodicDamageOrSelfBuffs(t *testing.T) {
+ t.Run("periodic", func(t *testing.T) {
+ world, _ := newPeriodicNanoWorld(t)
+ addCombatWall(world)
+ target := world.characters[1000000]
+ target.position[0] = 12
+ at := castPeriodicNano(t, world, 43376)
+ target.position[0] = 16
+
+ world.advanceNanos(at.Add(22500 * time.Millisecond))
+
+ if target.health != 91 || target.activeNanos[0].ticksLeft != 5 {
+ t.Fatal("wall interrupted an already installed periodic effect")
+ }
+ })
+ t.Run("self", func(t *testing.T) {
+ world, _ := newNanoBuffWorld(t)
+ addCombatWall(world)
+ player := world.characters[1]
+ player.position[0] = 15
+
+ castTestBuff(t, world, 1, 1, 27169)
+
+ if player.effectiveAbility(16) != 22 || player.nano != 56 || len(player.activeNanos) != 1 {
+ t.Fatal("self buff unnecessarily intersected scenery at its origin")
+ }
+ })
+}
diff --git a/server/scene_visibility_test.go b/server/scene_visibility_test.go
@@ -0,0 +1,86 @@
+package main
+
+import "testing"
+
+func TestSceneVisibilityUsesOriginalMissionDoorwaysWallsAndFloors(t *testing.T) {
+ geometry := missionGeometryFixture(t)
+ if err := geometry.addMission(9000001, fixedMissionLayout()); err != nil {
+ t.Fatal(err)
+ }
+ for _, scenario := range []struct {
+ name string
+ origin, end [3]float32
+ visible bool
+ }{
+ {"same room", [3]float32{15, 1.611, 29}, [3]float32{15, 1.611, 29.25}, true},
+ {"open doorway", [3]float32{15, 1.611, 29}, [3]float32{15, 1.611, 31}, true},
+ {"room wall", [3]float32{12, 1.611, 31}, [3]float32{12, 1.611, 33}, false},
+ {"clear beside wall", [3]float32{12, 1.611, 30.25}, [3]float32{12, 1.611, 31}, true},
+ {"raised scenery", [3]float32{15, .5, 20}, [3]float32{15, 3, 20}, false},
+ {"outside room", [3]float32{0, 1.611, 0}, [3]float32{15, 1.611, 25}, false},
+ } {
+ t.Run(scenario.name, func(t *testing.T) {
+ if scenario.name != "outside room" && (geometry.mission(9000001).roomAt(scenario.origin) == nil || geometry.mission(9000001).roomAt(scenario.end) == nil) {
+ t.Fatal("visibility fixture endpoint does not occupy an original room")
+ }
+ forward := geometry.lineOfSight(9000001, scenario.origin, scenario.end)
+ reverse := geometry.lineOfSight(9000001, scenario.end, scenario.origin)
+
+ if forward != scenario.visible || reverse != scenario.visible {
+ t.Fatal("native two-direction visibility", forward, reverse)
+ }
+ })
+ }
+}
+
+func TestSceneVisibilityRequiresDirectRoomPairAndDestinationSurface(t *testing.T) {
+ geometry := missionGeometryFixture(t)
+ if err := geometry.addMission(9000001, fixedMissionLayout()); err != nil {
+ t.Fatal(err)
+ }
+ scene := geometry.mission(9000001)
+ origin, end := [3]float32{15, 1.611, 29}, [3]float32{15, 1.611, 32}
+ first, second := &scene.rooms[0], &scene.rooms[1]
+ first.surface = &sceneSurface{}
+ vertices := [][3]float32{{10, 0, 31}, {10, 10, 31}, {30, 0, 31}}
+ for index := range vertices {
+ vertices[index] = second.templatePoint(vertices[index])
+ }
+ bounds := [6]float32{vertices[0][0], vertices[0][1], vertices[0][2], vertices[0][0], vertices[0][1], vertices[0][2]}
+ for _, vertex := range vertices[1:] {
+ for axis := range 3 {
+ bounds[axis], bounds[axis+3] = min(bounds[axis], vertex[axis]), max(bounds[axis+3], vertex[axis])
+ }
+ }
+ second.surface = &sceneSurface{primary: &surfaceTree{vertices: vertices,
+ groups: []surfaceGroup{{bounds: bounds, triangles: [][3]uint32{{0, 2, 1}}}}, nodes: []surfaceNode{{groups: []uint32{0}}}}}
+
+ forward := scene.line(origin, end)
+ visible := geometry.lineOfSight(9000001, origin, end)
+ second.surface = &sceneSurface{}
+ clear := geometry.lineOfSight(9000001, origin, end)
+ scene.links = nil
+ unlinked := geometry.lineOfSight(9000001, origin, end)
+
+ if forward.hit || visible || !clear || unlinked {
+ t.Fatal("destination room or direct-pair check missing", forward, visible, clear, unlinked)
+ }
+}
+
+func TestSceneVisibilityRejectsOutdoorTerrainRidge(t *testing.T) {
+ world, _ := newCombatWorld()
+ addCombatWall(world)
+ world.geometry.surfaces[950<<16] = nil
+ world.geometry.terrain[950] = &terrain{width: 3, height: 2, boundsWidth: 3, boundsHeight: 2, spacing: 10, scale: 1,
+ heights: []byte{0, 5, 0, 0, 0, 5, 0, 0, 0, 5, 0, 0}}
+ origin, end := [3]float32{2, 1.6, 5}, [3]float32{18, 1.6, 5}
+
+ blocked := world.geometry.lineOfSight(950, origin, end)
+ back := world.geometry.lineOfSight(950, end, origin)
+ origin[1], end[1] = 6, 6
+ clear := world.geometry.lineOfSight(950, origin, end)
+
+ if blocked || back || !clear {
+ t.Fatal("outdoor terrain obstruction or clear elevated ray", blocked, back, clear)
+ }
+}
diff --git a/server/weapon_special.go b/server/weapon_special.go
@@ -33,7 +33,7 @@ func (server *server) handleWeaponSpecial(client *worldClient, body []byte) erro
target := server.characters[binary.BigEndian.Uint32(body[20:24])]
now := time.Now()
if target == nil || !target.npc || target.appearance>>4&7 != 6 || !client.npcs[target.id] || target.health == 0 ||
- target.playfield != player.playfield || !server.combatInRange_locked(player, target, now) ||
+ target.playfield != player.playfield || !server.combatInRange_locked(player, target, now) || !server.combatVisible_locked(player, target, now) ||
player.sitting || player.driving() || client.equipment != nil || now.Before(client.reloadUntil) ||
now.Before(player.skillLocks[skill]) {
server.mutex.Unlock()