commit bfcafe034e3503de2c19e47780235277b2ea1a80
parent 2370b14ac16cd1f153994fd4c67647b582271bdc
Author: anon <anon@example.com>
Date: Mon, 26 Oct 2026 08:22:28 +0000
Read shipped collision trees and native sphere queries
Read cells and model torso metadata directly from the bundled game archive.
Preserve authored KD/group ordering, one-sided contacts and native near ties.
Validate every outdoor cell and all model prefixes; keep live movement
integration explicitly open.
Validation: 1,229 server tests (14,060 results), 62 focused race results,
data packages, vet and independent coordinates across all 154,023 cells.
Diffstat:
11 files changed, 1384 insertions(+), 13 deletions(-)
diff --git a/TODO.md b/TODO.md
@@ -1214,15 +1214,26 @@ disconnect retention and succession policy still need period corroboration.
initialization: native snapshots omit retained direction; the accepted reverse
transition fixes facing and stopping but necessarily restarts acceleration.
See [native player movement](docs/player-movement.md) for the evidence boundary.
+- [x] Read shipped outdoor collision trees and model torso spheres directly from
+ the already bundled resource database, without duplicating the archive in a
+ geometry export. Decode all 154,023 outdoor cell records across 188 playfields
+ and all 5,326 model metadata records. Preserve authored bounds, winding,
+ triangle/group order, KD splits and invisible-to-primary fallback. The sphere
+ query kernel retains native sidedness, edge selection, traversal and near-tie
+ rules. Tests bind every decoded outdoor coordinate to an independent parser,
+ exercise malformed records, concurrent initialization and the measured wall.
+ This foundation is not yet connected to live movement.
- [ ] Integrate shipped outdoor cell collision surfaces with the shared simulation.
Source binds resource 1000013, cell ownership, KD-tree framing, invisible/primary
fallback and model-dependent body spheres. All selected surface records are v4;
- parser validation covers all 429 PF705 and 36 PF950 resources, including portals.
+ parser validation now covers every outdoor cell, including portal tails.
Ordinary wall contact corrects position while retaining cached velocity; do not
replace it with Halt. The 40-second hardware wall fixture currently produces
28.73 metres of server error before the next pose message. Preserve native segment/contact
- ordering, retries, sphere scaling and floor selection; resolve the remaining
- intermediate-slope branches before claiming full canonical collision. Test
+ ordering, retries, sphere scaling and floor selection. Apply the recovered
+ intermediate-slope and raised-probe rules, and resolve effective model selection,
+ segment queries and combined terrain/static floor selection before claiming
+ full canonical collision. Test
owner/observer/server poses, wall sliding, corners, narrow passages, multiple
forms/scales, long holds, large admitted frame steps, release/reversal and
interaction ranges while blocked. See [player geometry](docs/player-geometry.md).
diff --git a/docs/player-geometry.md b/docs/player-geometry.md
@@ -74,10 +74,87 @@ bounds align with the native stopping point. Collision can use the shipped
surface data instead of reconstructing obstacles from visual model names.
All 155,273 selected type 1000013 records are resource version 4. Source and
-normal asset parsing validate all 429 PF 705 and 36 PF 950 resources, including
-the primary/invisible KD-tree fallback and count-framed portal tails. Group
-triangle counts include cross-cell duplication. Indoor transforms, dynamic
-platforms and an unexercised large-index native branch remain separate bounds.
+normal asset parsing validate all 154,023 outdoor records across 188 playfields,
+including the primary/invisible KD-tree fallback and count-framed portal tails.
+They contain 150,620 trees, 9,419,782 vertices, 15,017,490 triangles and 1,651,254
+KD nodes. Counts include cross-cell duplication. Largest vertex and group counts
+are 3,477 and 351, so selected outdoor data exercises 8/16-bit vertex and group
+references but avoids the unreduced native 32-bit triangle-construction branch.
+Indoor transforms and dynamic platforms remain separate bounds.
+
+## Shared archive reader and sphere query foundation
+
+`server/game_database.go` reads the resource index and uses random access into
+the already bundled ResourceDatabase.dat. It checks index framing/cycles,
+duplicate identities, record identities and payload bounds. It does not read
+the full 557 MB archive into a second buffer or introduce a second geometry
+export. These readers and queries are not yet connected to the live movement
+loop; completing that integration remains the next task.
+
+`server/scene_playfield.go` derives outdoor cell dimensions from the playfield's
+tilemap and zone size. Native extents truncate tile spacing; cell selection
+truncates coordinate division and falls back to cell zero for invalid indices.
+The sphere provider queries only the center's cell. It does not expand the
+search into neighboring cells by radius.
+
+`server/scene_surface.go` decodes selected version-4 resource streams. It keeps
+both authored trees, promotes invisible geometry when primary is absent, and
+validates portal framing without using portals as collision triangles. It
+retains separate authored group bounds, ordered vertex triples and preorder KD
+nodes. Quantized coordinates round once after the wide base-plus-delta sum.
+Every outdoor coordinate matches the independent Python archive decoder: the
+ordered identity/tree-count/interleaved-vertex SHA-256 is
+`22d3412759c061e57a624ce84145118969a5552f704fe7f97b103448d030b257`.
+
+`server/surface_sphere.go` implements the KD-tree query kernel. Ordered unit
+edges produce face and edge-plane coefficients. Triangles admit only their
+front side, including exact plane equality; the first positive edge plane
+selects the edge/vertex calculation. Within a group, the native squared-distance
+epsilon is float32(0.0001), with smaller lateral distance resolving near ties.
+Across groups, strictly nearer contact wins and traversal order retains exact
+ties. KD traversal visits the center's side first, choosing the upper child at
+split equality. It prunes against authored bounds and the current distance;
+leaf aggregate bounds separately use the original radius. Initial leaf-bound
+relaxation admits exact tangency, while the final result still must be within
+the requested radius. Returned normals are triangle face normals, including
+edge and vertex contacts. Coefficients are built once and shared safely by
+concurrent queries.
+
+The kernel preserves these source branch and storage contracts for ordinary
+finite inputs. It does not claim bit-identical x87 arithmetic. Selecting between
+an additional invisible tree and primary geometry depends on a native setting
+whose ownership remains unresolved; the current kernel queries individual trees
+and does not invent that setting. Likewise, the public native fifth float output
+is not a reliable contact depth: the ordinary KD wrapper leaves it untouched.
+
+At the captured PF705 native stop, a sphere with the measured model offset and
+radius is clear of the building. A small step to [971.72,16.41,519.66] contacts
+the authored wall, with face normal [-1,0,0] and distance approximately 0.24145.
+This verifies the geometry query against the retained runtime fixture; it does
+not demonstrate that server movement stops there yet.
+
+## Model torso metadata
+
+`server/model_sphere.go` reads only the collision metadata prefix for the selected
+model resource. All 5,128 ordinary meshes use schema 3: keyframe count, 36-byte
+keyframe/name entries, then signed packed XYZR. All 198 CIR metadata records
+store a 32-byte skeleton name, encoded material count, 44-byte material entries,
+then the packed sphere. For every shipped CIR, the native reciprocal count
+calculation equals `encoded/1009-1`.
+
+Each signed byte q decodes to
+`float32(q*(q*q*float32(0.000006)+float32(0.05)))`, with wide intermediates and
+one final float store. Native collision construction replaces a negative radius
+with 0.5 before scale, retains zero radius, discards authored X/Z displacement,
+and scales Y/radius separately. Thus ordinary player radius byte 5 gives exactly
+0.25075000524520874 without a universal player-radius constant. Authored offsets
+are independent: thin Nanomage male 17909 has Y=0; hovertech 20615 has negative Y
+and the radius fallback. Tests retain both cases and scaling order.
+
+The reader requires an effective model identity. Exact precedence across player
+appearance, model stats, forms and rebuild paths remains unfinished. Incremental
+native scale updates multiply the existing primitive by new/old scale rather
+than re-decoding it; that lifecycle also belongs to the movement integration.
The native body interface obtains a scaled model torso sphere. Its radius and
offset are model-specific. For this owned visitor, raw radius and offsetY both
@@ -92,7 +169,7 @@ yet been substituted for a complete collision implementation.
## Evidence
`local/player-geometry-research/` retains runtime captures, the 28.73-metre wall
-failure, selected-archive comparisons and three source ledgers:
+failure, selected-archive comparisons and source ledgers:
- `terrain/`: 41 complete maintained bodies, initializer bindings, full grid and
coarse-corner censuses, equations and a source-only verifier.
@@ -100,14 +177,28 @@ failure, selected-archive comparisons and three source ledgers:
framing, per-resource hashes and selected 465-resource parser validation.
- `vehicle/`: 47 complete bodies, body-interface bindings, contact ordering,
projection/gravity rules and explicit unreduced branches.
+- `sphere-query/`: 31 complete bodies and two initialized-data sources; ordered
+ primitive, group ranking, KD traversal, cell dispatch and resource wrappers.
+- `body-model/`: 43 complete bodies and four initialized-data sources; all model
+ metadata, scale/fallback ordering and explicit model-selection gaps.
+- `contact-response/`: 12 complete bodies; segment/contact/raised-probe routing,
+ five-pass retries, strict ground comparisons, water separation and Halt bounds.
These counts overlap; they are not unique additional procedures. Source checks
establish maintained-code contracts and evidence integrity. Runtime probes
read state without calling native methods or modifying guest memory. Regression
tests cover selected data hashes, both diagonals, edge clamps, invalid/outside
coordinates, the current binary framing and affected gameplay consumers.
-The final suite passes all 1,213 top-level server tests (13,998 results), 18
-data tests, 256 focused race results and `go vet`. Export verification compares
-every grid against the independent selected-archive decoder. Owned player 120
-is removed after testing; unrelated SQLite rows hash unchanged and integrity
-and foreign-key checks pass. The single HTTPS8443 preview serves the update.
+The terrain milestone passed all 1,213 top-level server tests (13,998 results),
+18 data tests, 256 focused race results and `go vet`. Its export verification
+compares every grid against the independent selected-archive decoder. Owned
+player 120 is removed after testing; unrelated SQLite rows hash unchanged and
+integrity and foreign-key checks pass.
+
+The collision-query foundation passes all 1,229 top-level server tests (14,060
+results), 62 focused race results, the data packages and `go vet`.
+`local/player-collision-query/` retains test logs and the manifest binding every
+Go source and relevant bundled archive to that exact test binary. The independent
+coordinate comparison covers every outdoor cell. The sole HTTPS8443 preview
+remains on the verified terrain build; this milestone adds no live movement
+behavior, database mutations or additional test clients/servers.
diff --git a/server/game_database.go b/server/game_database.go
@@ -0,0 +1,90 @@
+package main
+
+import (
+ "encoding/binary"
+ "fmt"
+ "io"
+ "io/fs"
+)
+
+type gameDatabase struct {
+ positions map[[2]uint32]uint32
+ size int64
+ file interface {
+ io.ReaderAt
+ io.Closer
+ }
+}
+
+func readGameDatabase(files fs.FS) (*gameDatabase, error) {
+ // The same packaged archive supplies the client and server geometry.
+ index, err := fs.ReadFile(files, "anarchy-assets-14.9.1/cd_image/data/db/ResourceDatabase.idx")
+ if err != nil {
+ return nil, err
+ }
+ if len(index) < 76 {
+ return nil, fmt.Errorf("truncated game resource index")
+ }
+ database := &gameDatabase{positions: make(map[[2]uint32]uint32)}
+ seen := make(map[uint32]bool)
+ for block := binary.LittleEndian.Uint32(index[72:76]); block != 0; {
+ if seen[block] || uint64(block)+18 > uint64(len(index)) {
+ return nil, fmt.Errorf("invalid game resource index block %d", block)
+ }
+ seen[block] = true
+ count := int(binary.LittleEndian.Uint16(index[block+8 : block+10]))
+ if uint64(block)+18+uint64(count)*12 > uint64(len(index)) {
+ return nil, fmt.Errorf("truncated game resource index block %d", block)
+ }
+ for entry := range count {
+ data := index[int(block)+18+entry*12:]
+ identity := [2]uint32{binary.BigEndian.Uint32(data[4:8]), binary.BigEndian.Uint32(data[8:12])}
+ if _, exists := database.positions[identity]; exists {
+ return nil, fmt.Errorf("duplicate game resource %d/%d", identity[0], identity[1])
+ }
+ database.positions[identity] = binary.LittleEndian.Uint32(data[:4])
+ }
+ block = binary.LittleEndian.Uint32(index[block : block+4])
+ }
+
+ file, err := files.Open("anarchy-assets-14.9.1/cd_image/data/db/ResourceDatabase.dat")
+ if err != nil {
+ return nil, err
+ }
+ reader, ok := file.(interface {
+ io.ReaderAt
+ io.Closer
+ })
+ if !ok {
+ file.Close()
+ return nil, fmt.Errorf("game resource database does not support random access")
+ }
+ info, err := file.Stat()
+ if err != nil {
+ file.Close()
+ return nil, err
+ }
+ database.size = info.Size()
+ database.file = reader
+ return database, nil
+}
+
+func (database *gameDatabase) read(kind, id uint32) ([]byte, uint32, error) {
+ position, exists := database.positions[[2]uint32{kind, id}]
+ if !exists {
+ return nil, 0, fmt.Errorf("game resource %d/%d: %w", kind, id, fs.ErrNotExist)
+ }
+ header := make([]byte, 34)
+ if _, err := database.file.ReadAt(header, int64(position)); err != nil {
+ return nil, 0, fmt.Errorf("game resource %d/%d header: %w", kind, id, err)
+ }
+ size := binary.LittleEndian.Uint32(header[18:22])
+ if binary.LittleEndian.Uint32(header[10:14]) != kind || binary.LittleEndian.Uint32(header[14:18]) != id || size < 12 || int64(position)+34+int64(size)-12 > database.size {
+ return nil, 0, fmt.Errorf("invalid game resource %d/%d header", kind, id)
+ }
+ data := make([]byte, size-12)
+ if _, err := database.file.ReadAt(data, int64(position)+34); err != nil {
+ return nil, 0, fmt.Errorf("game resource %d/%d payload: %w", kind, id, err)
+ }
+ return data, binary.LittleEndian.Uint32(header[30:34]), nil
+}
diff --git a/server/game_database_test.go b/server/game_database_test.go
@@ -0,0 +1,93 @@
+package main
+
+import (
+ "encoding/binary"
+ "strings"
+ "testing"
+ "testing/fstest"
+)
+
+func gameDatabaseFixture() fstest.MapFS {
+ index := make([]byte, 106)
+ binary.LittleEndian.PutUint32(index[72:76], 76)
+ binary.LittleEndian.PutUint16(index[84:86], 1)
+ binary.BigEndian.PutUint32(index[98:102], 1000013)
+ binary.BigEndian.PutUint32(index[102:106], 46203264)
+ data := make([]byte, 37)
+ binary.LittleEndian.PutUint32(data[10:14], 1000013)
+ binary.LittleEndian.PutUint32(data[14:18], 46203264)
+ binary.LittleEndian.PutUint32(data[18:22], 15)
+ binary.LittleEndian.PutUint32(data[30:34], 4)
+ copy(data[34:], []byte{1, 2, 3})
+ return fstest.MapFS{
+ "anarchy-assets-14.9.1/cd_image/data/db/ResourceDatabase.idx": {Data: index},
+ "anarchy-assets-14.9.1/cd_image/data/db/ResourceDatabase.dat": {Data: data},
+ }
+}
+
+func TestGameDatabaseReadsIndexedIdentityAndVersion(t *testing.T) {
+ database, err := readGameDatabase(gameDatabaseFixture())
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { database.file.Close() })
+
+ data, version, err := database.read(1000013, 46203264)
+
+ if err != nil || version != 4 || string(data) != "\x01\x02\x03" {
+ t.Fatal("resource framing, identity or version", data, version, err)
+ }
+}
+
+func TestGameDatabaseRejectsBrokenIndexAndRecordFraming(t *testing.T) {
+ for _, scenario := range []struct {
+ name string
+ change func([]byte, []byte) ([]byte, []byte)
+ error string
+ }{
+ {"short index", func(index, data []byte) ([]byte, []byte) { return index[:75], data }, "truncated game resource index"},
+ {"cycle", func(index, data []byte) ([]byte, []byte) {
+ binary.LittleEndian.PutUint32(index[76:80], 76)
+ return index, data
+ }, "invalid game resource index block"},
+ {"truncated block", func(index, data []byte) ([]byte, []byte) {
+ binary.LittleEndian.PutUint32(index[72:76], 105)
+ return index, data
+ }, "invalid game resource index block"},
+ {"truncated entries", func(index, data []byte) ([]byte, []byte) {
+ binary.LittleEndian.PutUint16(index[84:86], 2)
+ return index, data
+ }, "truncated game resource index block"},
+ {"duplicate identity", func(index, data []byte) ([]byte, []byte) {
+ binary.LittleEndian.PutUint16(index[84:86], 2)
+ return append(index, index[94:106]...), data
+ }, "duplicate game resource"},
+ {"short header", func(index, data []byte) ([]byte, []byte) { return index, data[:33] }, "header:"},
+ {"wrong identity", func(index, data []byte) ([]byte, []byte) {
+ data[10] = 0
+ return index, data
+ }, "invalid game resource"},
+ {"short payload", func(index, data []byte) ([]byte, []byte) { return index, data[:36] }, "invalid game resource"},
+ {"oversized record", func(index, data []byte) ([]byte, []byte) {
+ binary.LittleEndian.PutUint32(data[18:22], 0xffffffff)
+ return index, data
+ }, "invalid game resource"},
+ } {
+ t.Run(scenario.name, func(t *testing.T) {
+ files := gameDatabaseFixture()
+ index, data := scenario.change(files["anarchy-assets-14.9.1/cd_image/data/db/ResourceDatabase.idx"].Data, files["anarchy-assets-14.9.1/cd_image/data/db/ResourceDatabase.dat"].Data)
+ files["anarchy-assets-14.9.1/cd_image/data/db/ResourceDatabase.idx"].Data = index
+ files["anarchy-assets-14.9.1/cd_image/data/db/ResourceDatabase.dat"].Data = data
+
+ database, err := readGameDatabase(files)
+ if err == nil {
+ t.Cleanup(func() { database.file.Close() })
+ _, _, err = database.read(1000013, 46203264)
+ }
+
+ if err == nil || !strings.Contains(err.Error(), scenario.error) {
+ t.Fatal("broken resource data was not rejected at its framing boundary", err)
+ }
+ })
+ }
+}
diff --git a/server/model_sphere.go b/server/model_sphere.go
@@ -0,0 +1,45 @@
+package main
+
+import (
+ "encoding/binary"
+ "fmt"
+)
+
+type collisionSphere struct {
+ offset [3]float32
+ radius float32
+}
+
+func decodeModelSphere(data []byte, kind uint32, scale float32) (collisionSphere, error) {
+ var offset uint64
+ switch kind {
+ case 1010001:
+ if len(data) < 8 || binary.LittleEndian.Uint32(data[:4]) != 3 {
+ return collisionSphere{}, fmt.Errorf("invalid model sphere mesh header")
+ }
+ offset = 8 + uint64(binary.LittleEndian.Uint32(data[4:8]))*36
+ case 1010002:
+ if len(data) < 36 || binary.LittleEndian.Uint32(data[32:36]) < 1009 {
+ return collisionSphere{}, fmt.Errorf("invalid model sphere CIR header")
+ }
+ offset = 36 + (uint64(binary.LittleEndian.Uint32(data[32:36]))/1009-1)*44
+ default:
+ return collisionSphere{}, fmt.Errorf("invalid model sphere resource kind %d", kind)
+ }
+ if offset+4 > uint64(len(data)) {
+ return collisionSphere{}, fmt.Errorf("truncated model sphere metadata")
+ }
+
+ // Sources: client/game/bbr.dll/lifted-0030.c, sub_250911D0;
+ // client/game/bbr.dll/lifted-0036.c, sub_250A2290. Store after wide arithmetic.
+ var torso [4]float32
+ for axis, packed := range data[offset : offset+4] {
+ value := float64(int8(packed))
+ torso[axis] = float32(value * (value*value*float64(float32(.000006)) + float64(float32(.05))))
+ }
+ // client/game/llr.dll/lifted-0024.c, sub_3803DD90: fallback, drop X/Z, then scale.
+ if torso[3] < 0 {
+ torso[3] = .5
+ }
+ return collisionSphere{offset: [3]float32{0, torso[1] * scale, 0}, radius: torso[3] * scale}, nil
+}
diff --git a/server/model_sphere_test.go b/server/model_sphere_test.go
@@ -0,0 +1,116 @@
+package main
+
+import (
+ "ao/server/assets"
+ "encoding/binary"
+ "testing"
+)
+
+func TestModelSpherePreservesAuthoredOffsetsFallbackAndScale(t *testing.T) {
+ database, err := readGameDatabase(assets.Files)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { database.file.Close() })
+
+ for _, scenario := range []struct {
+ name string
+ id uint32
+ scale float32
+ offset [3]float32
+ radius float32
+ }{
+ {"Solitus male", 5907, 1, [3]float32{0, .25075000524520874, 0}, .25075000524520874},
+ {"scaled Solitus", 5907, 2, [3]float32{0, .5015000104904175, 0}, .5015000104904175},
+ {"thin Nanomage male", 17909, 1, [3]float32{}, .25075000524520874},
+ {"negative authored radius", 20615, 2, [3]float32{0, -.10001200437545776, 0}, 1},
+ {"zero scale", 5907, 0, [3]float32{}, 0},
+ } {
+ t.Run(scenario.name, func(t *testing.T) {
+ payload, _, err := database.read(1010002, scenario.id)
+ if err != nil {
+ t.Fatal(err)
+ }
+ sphere, err := decodeModelSphere(payload, 1010002, scenario.scale)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if sphere.offset != scenario.offset || sphere.radius != scenario.radius {
+ t.Fatal("model torso sphere differs from authored metadata/native scaling", sphere)
+ }
+ })
+ }
+}
+
+func TestModelSphereKeepsZeroAuthoredRadius(t *testing.T) {
+ data := make([]byte, 40)
+ binary.LittleEndian.PutUint32(data[32:36], 1009)
+ copy(data[36:], []byte{5, 5, 5, 0})
+
+ sphere, err := decodeModelSphere(data, 1010002, 1)
+
+ if err != nil || sphere.offset != [3]float32{0, .25075000524520874, 0} || sphere.radius != 0 {
+ t.Fatal("only negative authored radius selects the fallback; X/Z must be discarded", sphere, err)
+ }
+}
+
+func TestModelSphereRejectsInvalidMetadata(t *testing.T) {
+ cir := make([]byte, 40)
+ binary.LittleEndian.PutUint32(cir[32:36], 1009)
+ mesh := make([]byte, 12)
+ binary.LittleEndian.PutUint32(mesh[:4], 3)
+ oversizedMesh := append([]byte(nil), mesh...)
+ binary.LittleEndian.PutUint32(oversizedMesh[4:8], 0xffffffff)
+
+ for _, scenario := range []struct {
+ name string
+ data []byte
+ kind uint32
+ }{
+ {"short mesh header", mesh[:7], 1010001},
+ {"unsupported mesh schema", make([]byte, 12), 1010001},
+ {"short keyframe list", oversizedMesh, 1010001},
+ {"missing mesh torso", mesh[:11], 1010001},
+ {"short CIR header", cir[:35], 1010002},
+ {"invalid material count", make([]byte, 40), 1010002},
+ {"missing CIR torso", cir[:39], 1010002},
+ {"wrong resource kind", cir, 1000013},
+ } {
+ t.Run(scenario.name, func(t *testing.T) {
+ if _, err := decodeModelSphere(scenario.data, scenario.kind, 1); err == nil {
+ t.Fatal("invalid model metadata was accepted")
+ }
+ })
+ }
+}
+
+func TestModelSphereCatalogDecodesEveryShippedModel(t *testing.T) {
+ database, err := readGameDatabase(assets.Files)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { database.file.Close() })
+ mesh, cir := 0, 0
+
+ for identity := range database.positions {
+ if identity[0] != 1010001 && identity[0] != 1010002 {
+ continue
+ }
+ payload, _, err := database.read(identity[0], identity[1])
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := decodeModelSphere(payload, identity[0], 1); err != nil {
+ t.Fatal("shipped model sphere", identity, err)
+ }
+ if identity[0] == 1010001 {
+ mesh++
+ } else {
+ cir++
+ }
+ }
+
+ if mesh != 5128 || cir != 198 {
+ t.Fatal("selected model resource coverage changed", mesh, cir)
+ }
+}
diff --git a/server/scene_playfield.go b/server/scene_playfield.go
@@ -0,0 +1,65 @@
+package main
+
+import (
+ "encoding/binary"
+ "fmt"
+ "math"
+)
+
+type scenePlayfield struct {
+ cellsX, cellsZ int
+ cellWidth, cellDepth float32
+}
+
+func (database *gameDatabase) outdoorPlayfields() (map[uint32]scenePlayfield, error) {
+ playfields := make(map[uint32]scenePlayfield)
+ for identity := range database.positions {
+ if identity[0] != 1000001 {
+ continue
+ }
+ data, _, err := database.read(identity[0], identity[1])
+ if err != nil {
+ return nil, err
+ }
+ if len(data) < 52 || binary.LittleEndian.Uint32(data[:4]) != 8 || binary.LittleEndian.Uint32(data[4:8]) != identity[1] {
+ return nil, fmt.Errorf("invalid scene playfield %d", identity[1])
+ }
+ tilemap := binary.LittleEndian.Uint32(data[40:44])
+ zoneSize := binary.LittleEndian.Uint32(data[44:48])
+ zoneCount := binary.LittleEndian.Uint32(data[48:52])
+ ground, _, err := database.read(1000009, tilemap)
+ if err != nil {
+ return nil, err
+ }
+ if len(ground) < 4 || string(ground[:4]) != "CHGA" {
+ continue
+ }
+ if len(ground) < 20 || zoneSize == 0 {
+ return nil, fmt.Errorf("invalid scene tilemap %d", tilemap)
+ }
+ width := uint32(binary.LittleEndian.Uint16(ground[12:14]))
+ depth := uint32(binary.LittleEndian.Uint16(ground[14:16]))
+ spacing := math.Float32frombits(binary.LittleEndian.Uint32(ground[16:20]))
+ cellsX, cellsZ := width/zoneSize, depth/zoneSize
+ if cellsX == 0 || cellsZ == 0 || cellsX*cellsZ != zoneCount || !(spacing >= 1 && spacing < math.MaxInt32) {
+ return nil, fmt.Errorf("invalid outdoor scene dimensions %d", identity[1])
+ }
+ // client/game/llr.dll/lifted-0017.c, sub_38029E90/38029EC0: truncate tile size.
+ playfields[identity[1]] = scenePlayfield{
+ cellsX: int(cellsX), cellsZ: int(cellsZ),
+ cellWidth: float32(width*uint32(spacing)) / float32(cellsX),
+ cellDepth: float32(depth*uint32(spacing)) / float32(cellsZ),
+ }
+ }
+ return playfields, nil
+}
+
+func (playfield scenePlayfield) cellID(position [3]float32) uint32 {
+ // Source: client/game/ggr.dll/lifted-0000.c, sub_30003930/30003990.
+ // CellSurface uses truncation and falls back to cell zero outside the grid.
+ x, z := int(position[0]/playfield.cellWidth), int(position[2]/playfield.cellDepth)
+ if x < 0 || x >= playfield.cellsX || z < 0 || z >= playfield.cellsZ {
+ return 0
+ }
+ return uint32(z*playfield.cellsX + x)
+}
diff --git a/server/scene_surface.go b/server/scene_surface.go
@@ -0,0 +1,244 @@
+package main
+
+import (
+ "bytes"
+ "compress/zlib"
+ "encoding/binary"
+ "fmt"
+ "io"
+ "math"
+ "sync"
+)
+
+type sceneSurface struct {
+ primary, invisible *surfaceTree
+}
+
+type surfaceTree struct {
+ vertices [][3]float32
+ groups []surfaceGroup
+ nodes []surfaceNode
+ prepare sync.Once
+}
+
+type surfaceGroup struct {
+ bounds [6]float32
+ triangles [][3]uint32
+ geometry []surfaceTriangle
+}
+
+type surfaceNode struct {
+ split float32
+ axis int32
+ groups []uint32
+ children [2]int
+ bounds [6]float32
+}
+
+type surfaceReader struct {
+ *bytes.Reader
+ err error
+}
+
+func (reader *surfaceReader) read(value any) {
+ if reader.err == nil {
+ reader.err = binary.Read(reader.Reader, binary.LittleEndian, value)
+ }
+}
+
+func (reader *surfaceReader) indices(count, limit int) []uint32 {
+ width := 1
+ if limit >= 256 {
+ width = 2
+ }
+ if limit >= 65536 {
+ width = 4
+ }
+ if count < 0 || count > reader.Len()/width {
+ reader.err = fmt.Errorf("truncated surface indices")
+ return nil
+ }
+ data := make([]byte, count*width)
+ reader.read(data)
+ indices := make([]uint32, count)
+ for index := range indices {
+ switch width {
+ case 1:
+ indices[index] = uint32(data[index])
+ case 2:
+ indices[index] = uint32(binary.LittleEndian.Uint16(data[index*2:]))
+ case 4:
+ indices[index] = binary.LittleEndian.Uint32(data[index*4:])
+ }
+ if indices[index] >= uint32(limit) {
+ reader.err = fmt.Errorf("surface index %d exceeds %d", indices[index], limit)
+ }
+ }
+ return indices
+}
+
+func (reader *surfaceReader) tree() *surfaceTree {
+ var signature [11]byte
+ var counts [4]int32
+ reader.read(&signature)
+ reader.read(&counts)
+ if reader.err != nil {
+ return nil
+ }
+ if string(signature[:]) != "KDTreeFile\x00" || counts[2] != 3 || counts[0] <= 0 || counts[1] <= 0 || counts[3] <= 0 || int(counts[0]) > reader.Len()/28 || int(counts[1]) > reader.Len()/12 || int(counts[3]) > reader.Len()/6 {
+ reader.err = fmt.Errorf("invalid surface tree header")
+ return nil
+ }
+ // Source: client/game/llr.dll/lifted-0027.c, sub_38043A00/38044530.
+ // Vertex coordinates are stored as planar arrays, with a single float store.
+ tree := &surfaceTree{vertices: make([][3]float32, counts[3]), groups: make([]surfaceGroup, counts[0])}
+ var base [3]float32
+ reader.read(&base[0])
+ if base[0] == -99999 {
+ coordinates := make([]float32, counts[3])
+ for axis := range 3 {
+ reader.read(coordinates)
+ for index, coordinate := range coordinates {
+ tree.vertices[index][axis] = coordinate
+ }
+ }
+ } else {
+ reader.read(base[1:])
+ coordinates := make([]uint16, counts[3])
+ for axis := range 3 {
+ reader.read(coordinates)
+ for index, coordinate := range coordinates {
+ tree.vertices[index][axis] = float32(float64(base[axis]) + float64(coordinate)*float64(float32(.01)))
+ }
+ }
+ }
+ for _, vertex := range tree.vertices {
+ for _, coordinate := range vertex {
+ if math.IsNaN(float64(coordinate)) || math.IsInf(float64(coordinate), 0) {
+ reader.err = fmt.Errorf("nonfinite surface vertex")
+ }
+ }
+ }
+ for index := range tree.groups {
+ var count int32
+ reader.read(&count)
+ if reader.err != nil {
+ return nil
+ }
+ if count <= 0 || count >= 1000 {
+ reader.err = fmt.Errorf("invalid surface triangle count %d", count)
+ return nil
+ }
+ reader.read(&tree.groups[index].bounds)
+ indices := reader.indices(int(count)*3, len(tree.vertices))
+ if reader.err != nil {
+ return nil
+ }
+ tree.groups[index].triangles = make([][3]uint32, count)
+ for triangle := range count {
+ copy(tree.groups[index].triangles[triangle][:], indices[triangle*3:triangle*3+3])
+ }
+ }
+ reader.node(tree, int(counts[1]))
+ if len(tree.nodes) != int(counts[1]) {
+ reader.err = fmt.Errorf("surface node count differs from header")
+ }
+ return tree
+}
+
+func (reader *surfaceReader) node(tree *surfaceTree, count int) int {
+ if reader.err != nil {
+ return 0
+ }
+ if len(tree.nodes) >= count {
+ reader.err = fmt.Errorf("surface nodes exceed header count")
+ return 0
+ }
+ var node surfaceNode
+ var groups int32
+ reader.read(&node.split)
+ reader.read(&node.axis)
+ reader.read(&groups)
+ index := len(tree.nodes)
+ tree.nodes = append(tree.nodes, node)
+ if groups != 0 {
+ tree.nodes[index].groups = reader.indices(int(groups), len(tree.groups))
+ } else {
+ if node.axis < 0 || node.axis > 2 {
+ reader.err = fmt.Errorf("invalid surface split axis %d", node.axis)
+ return index
+ }
+ left := reader.node(tree, count)
+ right := reader.node(tree, count)
+ tree.nodes[index].children = [2]int{left, right}
+ }
+ return index
+}
+
+func decodeSceneSurface(payload []byte, version uint32) (*sceneSurface, error) {
+ if version != 4 || len(payload) < 4 {
+ return nil, fmt.Errorf("invalid scene surface version or header")
+ }
+ size := binary.LittleEndian.Uint32(payload[:4])
+ if size > 4000000 {
+ return nil, fmt.Errorf("scene surface exceeds native size limit")
+ }
+ compressed, err := zlib.NewReader(bytes.NewReader(payload[4:]))
+ if err != nil {
+ return nil, err
+ }
+ defer compressed.Close()
+ data, err := io.ReadAll(io.LimitReader(compressed, int64(size)+1))
+ if err != nil {
+ return nil, err
+ }
+ if len(data) != int(size) {
+ return nil, fmt.Errorf("scene surface decompressed size differs from header")
+ }
+
+ // Keep both authored trees; version 4 promotes invisible geometry when primary is absent.
+ reader := &surfaceReader{Reader: bytes.NewReader(data)}
+ surface := &sceneSurface{}
+ for _, destination := range []**surfaceTree{&surface.primary, &surface.invisible} {
+ var size uint32
+ reader.read(&size)
+ if size != 0 {
+ start := reader.Len()
+ *destination = reader.tree()
+ if start-reader.Len() != int(size) && reader.err == nil {
+ reader.err = fmt.Errorf("surface tree length differs from header")
+ }
+ }
+ }
+ if surface.primary == nil {
+ surface.primary, surface.invisible = surface.invisible, nil
+ }
+
+ // Portals have their own count-framed body and two trailing destination integers.
+ var portal uint32
+ reader.read(&portal)
+ if portal != 0 && reader.err == nil {
+ start := reader.Len()
+ var count int32
+ reader.read(&count)
+ size := int64(8)
+ if count != 0 {
+ size += 8 + int64(count)*12
+ }
+ if count < 0 || size > int64(reader.Len()) {
+ reader.err = fmt.Errorf("invalid surface portal vertex count")
+ } else {
+ _, reader.err = reader.Seek(size, io.SeekCurrent)
+ }
+ if start-reader.Len() != int(portal) && reader.err == nil {
+ reader.err = fmt.Errorf("surface portal length differs from header")
+ }
+ }
+ if reader.err != nil {
+ return nil, reader.err
+ }
+ if reader.Len() != 0 {
+ return nil, fmt.Errorf("unexpected bytes after scene surface")
+ }
+ return surface, nil
+}
diff --git a/server/scene_surface_test.go b/server/scene_surface_test.go
@@ -0,0 +1,241 @@
+package main
+
+import (
+ "ao/server/assets"
+ "bytes"
+ "compress/zlib"
+ "crypto/sha256"
+ "encoding/binary"
+ "fmt"
+ "io"
+ "math"
+ "slices"
+ "testing"
+)
+
+func TestSceneSurfaceReadsShippedWallAndPortal(t *testing.T) {
+ database, err := readGameDatabase(assets.Files)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { database.file.Close() })
+
+ payload, version, err := database.read(1000013, 46203264)
+ if err != nil {
+ t.Fatal(err)
+ }
+ surface, err := decodeSceneSurface(payload, version)
+ if err != nil {
+ t.Fatal(err)
+ }
+ portalPayload, portalVersion, err := database.read(1000013, 46203265)
+ if err != nil {
+ t.Fatal(err)
+ }
+ portalSurface, err := decodeSceneSurface(portalPayload, portalVersion)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if surface.primary == nil || surface.invisible != nil || len(surface.primary.vertices) != 176 || len(surface.primary.groups) != 21 {
+ t.Fatal("shipped wall lost invisible-to-primary fallback or geometry")
+ }
+ if len(surface.primary.groups[4].triangles) != 12 || surface.primary.groups[4].triangles[0] != [3]uint32{144, 145, 146} {
+ t.Fatal("shipped building bounds or triangle order changed", surface.primary.groups[4])
+ }
+ for axis, expected := range [6]float32{971.94812, 16.41435, 519.74072, 972.45020, 21.42010, 521.42419} {
+ if math.Abs(float64(surface.primary.groups[4].bounds[axis]-expected)) > .0001 {
+ t.Fatal("shipped wall authored bounds changed", surface.primary.groups[4].bounds)
+ }
+ }
+ if portalSurface.primary == nil || portalSurface.invisible != nil {
+ t.Fatal("portal tail displaced ordinary static geometry")
+ }
+ t.Logf("wall payload SHA256 %x; nodes %d; first vertex %v; first wall triangle %v", sha256.Sum256(payload), len(surface.primary.nodes), surface.primary.vertices[0], surface.primary.groups[4].triangles[0])
+}
+
+func TestSceneSurfaceRejectsBrokenFramingAndReferences(t *testing.T) {
+ database, err := readGameDatabase(assets.Files)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { database.file.Close() })
+ payload, _, err := database.read(1000013, 46203264)
+ if err != nil {
+ t.Fatal(err)
+ }
+ compressed, err := zlib.NewReader(bytes.NewReader(payload[4:]))
+ if err != nil {
+ t.Fatal(err)
+ }
+ data, err := io.ReadAll(compressed)
+ compressed.Close()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(data) != 3022 {
+ t.Fatal("shipped malformed-input fixture changed", len(data))
+ }
+
+ for _, scenario := range []struct {
+ name string
+ change func([]byte) []byte
+ }{
+ {"truncated header", func(data []byte) []byte { return data[:3] }},
+ {"wrong signature", func(data []byte) []byte { data[8] = 'X'; return data }},
+ {"wrong dimension", func(data []byte) []byte { binary.LittleEndian.PutUint32(data[27:31], 4); return data }},
+ {"invalid node count", func(data []byte) []byte { binary.LittleEndian.PutUint32(data[23:27], 0); return data }},
+ {"invalid vertex reference", func(data []byte) []byte { data[1131] = 255; return data }},
+ {"wrong tree length", func(data []byte) []byte { binary.LittleEndian.PutUint32(data[4:8], 3009); return data }},
+ {"trailing data", func(data []byte) []byte { return append(data, 0) }},
+ {"truncated portal count", func(data []byte) []byte { data[3018] = 1; return data }},
+ } {
+ t.Run(scenario.name, func(t *testing.T) {
+ changed := scenario.change(append([]byte(nil), data...))
+ var output bytes.Buffer
+ writer := zlib.NewWriter(&output)
+ if _, err := writer.Write(changed); err != nil {
+ t.Fatal(err)
+ }
+ if err := writer.Close(); err != nil {
+ t.Fatal(err)
+ }
+ encoded := binary.LittleEndian.AppendUint32(nil, uint32(len(changed)))
+ encoded = append(encoded, output.Bytes()...)
+
+ _, err := decodeSceneSurface(encoded, 4)
+
+ if err == nil {
+ t.Fatal("broken scene surface was accepted")
+ }
+ })
+ }
+}
+
+func TestSceneSurfaceCatalogDecodesAllOutdoorCells(t *testing.T) {
+ database, err := readGameDatabase(assets.Files)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { database.file.Close() })
+ playfields, err := database.outdoorPlayfields()
+ if err != nil {
+ t.Fatal(err)
+ }
+ cells, trees, vertices, triangles, nodes := 0, 0, 0, 0, 0
+ maxVertices, maxGroups := 0, 0
+ var identities []uint32
+ for identity := range database.positions {
+ if identity[0] == 1000013 {
+ identities = append(identities, identity[1])
+ }
+ }
+ slices.Sort(identities)
+ coordinates := sha256.New()
+ write := func(value any) {
+ if err := binary.Write(coordinates, binary.LittleEndian, value); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ for _, identity := range identities {
+ playfield, exists := playfields[identity>>16]
+ if !exists {
+ continue
+ }
+ if int(identity&65535) >= playfield.cellsX*playfield.cellsZ {
+ t.Fatal("surface identity exceeds playfield cell count", identity)
+ }
+ payload, version, err := database.read(1000013, identity)
+ if err != nil {
+ t.Fatal(err)
+ }
+ surface, err := decodeSceneSurface(payload, version)
+ if err != nil {
+ t.Fatal("shipped surface", identity, err)
+ }
+ cells++
+ write(identity)
+ for _, tree := range []*surfaceTree{surface.primary, surface.invisible} {
+ if tree == nil {
+ write(uint32(0))
+ continue
+ }
+ write(uint32(len(tree.vertices)))
+ write(tree.vertices)
+ trees++
+ vertices += len(tree.vertices)
+ nodes += len(tree.nodes)
+ maxVertices = max(maxVertices, len(tree.vertices))
+ maxGroups = max(maxGroups, len(tree.groups))
+ for _, group := range tree.groups {
+ triangles += len(group.triangles)
+ }
+ }
+ }
+
+ if len(playfields) != 188 || cells != 154023 {
+ t.Fatal("selected outdoor resource coverage changed", len(playfields), cells)
+ }
+ if trees != 150620 || vertices != 9419782 || triangles != 15017490 || nodes != 1651254 || maxVertices != 3477 || maxGroups != 351 {
+ t.Fatal("selected scene geometry census changed", trees, vertices, triangles, nodes, maxVertices, maxGroups)
+ }
+ if digest := fmt.Sprintf("%x", coordinates.Sum(nil)); digest != "22d3412759c061e57a624ce84145118969a5552f704fe7f97b103448d030b257" {
+ t.Fatal("decoded vertices differ from the independent selected-archive parser", digest)
+ }
+ t.Log(fmt.Sprintf("cells=%d trees=%d vertices=%d triangles=%d nodes=%d maxVertices=%d maxGroups=%d", cells, trees, vertices, triangles, nodes, maxVertices, maxGroups))
+ t.Logf("ordered decoded-coordinate SHA256 %x", coordinates.Sum(nil))
+}
+
+func TestSceneSurfaceRejectsInvalidCompression(t *testing.T) {
+ for _, scenario := range []struct {
+ name string
+ payload []byte
+ version uint32
+ }{
+ {"old format", make([]byte, 4), 3},
+ {"short header", make([]byte, 3), 4},
+ {"size limit", binary.LittleEndian.AppendUint32(nil, 4000001), 4},
+ {"bad zlib stream", []byte{0, 0, 0, 0, 1, 2, 3}, 4},
+ } {
+ t.Run(scenario.name, func(t *testing.T) {
+ _, err := decodeSceneSurface(scenario.payload, scenario.version)
+
+ if err == nil {
+ t.Fatal("invalid compressed scene surface was accepted")
+ }
+ })
+ }
+}
+
+func TestScenePlayfieldUsesNativeCellSelection(t *testing.T) {
+ database, err := readGameDatabase(assets.Files)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { database.file.Close() })
+ playfields, err := database.outdoorPlayfields()
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if playfields[705] != (scenePlayfield{30, 30, 40, 40}) || playfields[950] != (scenePlayfield{6, 6, 40, 40}) {
+ t.Fatal("outdoor collision dimensions differ from native", playfields[705], playfields[950])
+ }
+ for _, scenario := range []struct {
+ position [3]float32
+ cell uint32
+ }{
+ {[3]float32{961.625, 16.41, 510.75}, 384},
+ {[3]float32{971.701416, 16.41, 519.643555}, 384},
+ {[3]float32{1000, 20, 520}, 415},
+ {[3]float32{-1, 0, 80}, 60},
+ {[3]float32{-40, 0, 80}, 0},
+ {[3]float32{1200, 0, 80}, 0},
+ {[3]float32{80, 0, 1200}, 0},
+ } {
+ if cell := playfields[705].cellID(scenario.position); cell != scenario.cell {
+ t.Fatal("native cell truncation/fallback", scenario, cell)
+ }
+ }
+}
diff --git a/server/surface_sphere.go b/server/surface_sphere.go
@@ -0,0 +1,235 @@
+package main
+
+import "math"
+
+type surfaceTriangle struct {
+ normal [3]float32
+ edges, sides [3][3]float32
+ lengths [3]float32
+ plane float32
+ side, tangent [3]float32
+}
+
+type surfaceContact struct {
+ point, normal [3]float32
+ distance float32
+ hit bool
+}
+
+func surfaceDot(first, second [3]float32) float64 {
+ return float64(first[0])*float64(second[0]) + float64(first[1])*float64(second[1]) + float64(first[2])*float64(second[2])
+}
+
+func surfaceNormal(first, second [3]float32) [3]float32 {
+ normal := [3]float32{
+ float32(float64(first[1])*float64(second[2]) - float64(first[2])*float64(second[1])),
+ float32(float64(first[2])*float64(second[0]) - float64(first[0])*float64(second[2])),
+ float32(float64(first[0])*float64(second[1]) - float64(first[1])*float64(second[0])),
+ }
+ length := math.Sqrt(surfaceDot(normal, normal))
+ if length == 0 {
+ return [3]float32{0, 1, 0}
+ }
+ for axis := range normal {
+ normal[axis] = float32(float64(normal[axis]) / length)
+ }
+ return normal
+}
+
+func newSurfaceTriangle(vertices [3][3]float32) surfaceTriangle {
+ // Source: client/game/llr.dll/lifted-0028.c, sub_380468C0.
+ // Derive oriented plane coefficients from ordered unit edges.
+ triangle := surfaceTriangle{}
+ for index := range 3 {
+ for axis := range 3 {
+ triangle.edges[index][axis] = vertices[(index+1)%3][axis] - vertices[index][axis]
+ }
+ triangle.lengths[index] = float32(math.Sqrt(surfaceDot(triangle.edges[index], triangle.edges[index])))
+ if triangle.lengths[index] != 0 {
+ for axis := range 3 {
+ triangle.edges[index][axis] /= triangle.lengths[index]
+ }
+ }
+ }
+ triangle.normal = surfaceNormal(triangle.edges[2], triangle.edges[0])
+ triangle.plane = float32(-surfaceDot(triangle.normal, vertices[0]))
+ for index := range 3 {
+ triangle.sides[index] = surfaceNormal(triangle.edges[index], triangle.normal)
+ triangle.side[index] = float32(-surfaceDot(triangle.sides[index], vertices[index]))
+ triangle.tangent[index] = float32(-surfaceDot(triangle.edges[index], vertices[index]))
+ }
+ return triangle
+}
+
+func (triangle *surfaceTriangle) candidate(center [3]float32, limit float32) (float32, float32, bool) {
+ // client/game/llr.dll/lifted-0028.c, sub_38046C00: first positive edge plane.
+ distance := surfaceDot(triangle.normal, center) + float64(triangle.plane)
+ squared := float32(distance * distance)
+ gate := float64(limit + float32(.0001))
+ if distance < 0 || float64(squared) > gate {
+ return 0, 0, false
+ }
+ for index := range 3 {
+ side := surfaceDot(triangle.sides[index], center) + float64(triangle.side[index])
+ if side <= 0 {
+ continue
+ }
+ total := float64(squared) + side*side
+ if total >= gate {
+ return 0, 0, false
+ }
+ tangent := surfaceDot(triangle.edges[index], center) + float64(triangle.tangent[index])
+ if tangent < 0 {
+ total += tangent * tangent
+ } else if tangent > float64(triangle.lengths[index]) {
+ extra := tangent - float64(triangle.lengths[index])
+ total += extra * extra
+ }
+ if total >= gate {
+ return 0, 0, false
+ }
+ return float32(total), float32(total - float64(squared)), true
+ }
+ return squared, 0, true
+}
+
+func (triangle *surfaceTriangle) contact(center [3]float32) surfaceContact {
+ // Source: client/game/llr.dll/lifted-0028.c, sub_38046D80.
+ distance := float32(surfaceDot(triangle.normal, center) + float64(triangle.plane))
+ if distance < 0 {
+ return surfaceContact{}
+ }
+ contact := surfaceContact{normal: triangle.normal, distance: distance, hit: true}
+ for axis := range 3 {
+ contact.point[axis] = center[axis] - distance*triangle.normal[axis]
+ }
+ for index := range 3 {
+ side := float32(surfaceDot(triangle.sides[index], center) + float64(triangle.side[index]))
+ if side <= 0 {
+ continue
+ }
+ tangent := float32(surfaceDot(triangle.edges[index], center) + float64(triangle.tangent[index]))
+ extra := float32(0)
+ if tangent < 0 {
+ extra = tangent
+ } else if tangent > triangle.lengths[index] {
+ extra = tangent - triangle.lengths[index]
+ }
+ for axis := range 3 {
+ contact.point[axis] -= side * triangle.sides[index][axis]
+ contact.point[axis] -= extra * triangle.edges[index][axis]
+ }
+ squared := float32(float64(distance)*float64(distance) + float64(side)*float64(side) + float64(extra)*float64(extra))
+ contact.distance = float32(math.Sqrt(float64(squared)))
+ break
+ }
+ return contact
+}
+
+func (group *surfaceGroup) sphere(center [3]float32, bound float32) surfaceContact {
+ // Source: client/game/llr.dll/lifted-0028.c, sub_38047510.
+ best, lateral := bound*bound, float32(999999995904)
+ selected := -1
+ for index := range group.geometry {
+ squared, side, hit := group.geometry[index].candidate(center, best)
+ if hit && (float64(squared)+float64(float32(.0001)) < float64(best) || side < lateral) {
+ best, lateral, selected = squared, side, index
+ }
+ }
+ if selected == -1 {
+ return surfaceContact{}
+ }
+ return group.geometry[selected].contact(center)
+}
+
+func surfaceOverlap(bounds [6]float32, center [3]float32, radius float32) bool {
+ for axis := range 3 {
+ if float64(center[axis])+float64(radius) < float64(bounds[axis]) || float64(center[axis])-float64(radius) > float64(bounds[axis+3]) {
+ return false
+ }
+ }
+ return true
+}
+
+func (tree *surfaceTree) sphere(center [3]float32, radius float32) surfaceContact {
+ // Lazy coefficients are immutable after construction, including authored bounds.
+ tree.prepare.Do(func() {
+ for index := range tree.groups {
+ group := &tree.groups[index]
+ group.geometry = make([]surfaceTriangle, len(group.triangles))
+ for index, vertices := range group.triangles {
+ group.geometry[index] = newSurfaceTriangle([3][3]float32{tree.vertices[vertices[0]], tree.vertices[vertices[1]], tree.vertices[vertices[2]]})
+ }
+ }
+ for index := len(tree.nodes) - 1; index >= 0; index-- {
+ node := &tree.nodes[index]
+ bounds := make([][6]float32, 0, len(node.groups)+2)
+ for _, group := range node.groups {
+ bounds = append(bounds, tree.groups[group].bounds)
+ }
+ if len(node.groups) == 0 {
+ for _, child := range node.children {
+ bounds = append(bounds, tree.nodes[child].bounds)
+ }
+ }
+ node.bounds = bounds[0]
+ for _, bound := range bounds[1:] {
+ for axis := range 3 {
+ node.bounds[axis] = min(node.bounds[axis], bound[axis])
+ node.bounds[axis+3] = max(node.bounds[axis+3], bound[axis+3])
+ }
+ }
+ }
+ })
+ return tree.nodeSphere(0, center, radius, radius)
+}
+
+func (tree *surfaceTree) nodeSphere(index int, center [3]float32, radius, bound float32) surfaceContact {
+ // Source: client/game/llr.dll/lifted-0027.c, sub_380447B0.
+ // Keep the first-subtree result while traversing its tail.
+ found := surfaceContact{}
+ node := &tree.nodes[index]
+ for len(node.groups) == 0 {
+ if !surfaceOverlap(node.bounds, center, bound) {
+ return found
+ }
+ position, split := float64(center[node.axis]), float64(node.split)
+ if !(position < split+float64(bound)) {
+ node = &tree.nodes[node.children[1]]
+ continue
+ }
+ if !(position >= split-float64(bound)) {
+ node = &tree.nodes[node.children[0]]
+ continue
+ }
+ first, next := node.children[0], node.children[1]
+ if position >= split {
+ first, next = next, first
+ }
+ contact := tree.nodeSphere(first, center, radius, bound)
+ if contact.hit && contact.distance <= bound {
+ if position >= split && split+float64(contact.distance) <= position || position < split && split-float64(contact.distance) > position {
+ return contact
+ }
+ bound, found = contact.distance, contact
+ }
+ node = &tree.nodes[next]
+ }
+ if len(node.groups) > 1 && !surfaceOverlap(node.bounds, center, radius) {
+ return found
+ }
+ if !found.hit && bound == radius {
+ bound += .01
+ }
+ for _, index := range node.groups {
+ group := &tree.groups[index]
+ if !surfaceOverlap(group.bounds, center, bound) {
+ continue
+ }
+ contact := group.sphere(center, bound)
+ if contact.hit && contact.distance >= 0 && contact.distance <= radius && contact.distance < bound {
+ bound, found = contact.distance, contact
+ }
+ }
+ return found
+}
diff --git a/server/surface_sphere_test.go b/server/surface_sphere_test.go
@@ -0,0 +1,140 @@
+package main
+
+import (
+ "ao/server/assets"
+ "math"
+ "sync"
+ "testing"
+)
+
+func TestSurfaceSphereUsesFrontFaceEdgesAndVertices(t *testing.T) {
+ tree := &surfaceTree{
+ vertices: [][3]float32{{0, 0, 0}, {0, 0, 2}, {0, 2, 0}},
+ groups: []surfaceGroup{{bounds: [6]float32{0, 0, 0, 0, 2, 2}, triangles: [][3]uint32{{0, 1, 2}}}},
+ nodes: []surfaceNode{{groups: []uint32{0}}},
+ }
+
+ for _, scenario := range []struct {
+ name string
+ center [3]float32
+ radius float32
+ hit bool
+ point [3]float32
+ distance float32
+ }{
+ {"face", [3]float32{-.25, .5, .5}, .5, true, [3]float32{0, .5, .5}, .25},
+ {"edge", [3]float32{-.25, -.25, .5}, .5, true, [3]float32{0, 0, .5}, .35355338},
+ {"vertex", [3]float32{-.25, -.25, -.25}, .5, true, [3]float32{}, .4330127},
+ {"tangent", [3]float32{-.5, .5, .5}, .5, true, [3]float32{0, .5, .5}, .5},
+ {"on plane", [3]float32{0, .5, .5}, .5, true, [3]float32{0, .5, .5}, 0},
+ {"back face", [3]float32{.25, .5, .5}, .5, false, [3]float32{}, 0},
+ {"beyond radius", [3]float32{-.5001, .5, .5}, .5, false, [3]float32{}, 0},
+ {"outside edge", [3]float32{-.25, -.5, .5}, .5, false, [3]float32{}, 0},
+ } {
+ t.Run(scenario.name, func(t *testing.T) {
+ contact := tree.sphere(scenario.center, scenario.radius)
+ if contact.hit != scenario.hit || contact.point != scenario.point || math.Abs(float64(contact.distance-scenario.distance)) > .000001 {
+ t.Fatal("native sphere contact", contact, scenario)
+ }
+ if contact.hit && contact.normal != [3]float32{-1, 0, 0} {
+ t.Fatal("edge/vertex contact must return the triangle face normal", contact.normal)
+ }
+ })
+ }
+}
+
+func TestSurfaceSphereSharesLazyCoefficientsAcrossQueries(t *testing.T) {
+ tree := &surfaceTree{
+ vertices: [][3]float32{{0, 0, 0}, {0, 0, 2}, {0, 2, 0}},
+ groups: []surfaceGroup{{bounds: [6]float32{0, 0, 0, 0, 2, 2}, triangles: [][3]uint32{{0, 1, 2}}}},
+ nodes: []surfaceNode{{groups: []uint32{0}}},
+ }
+ var workers sync.WaitGroup
+ contacts := make(chan surfaceContact, 16)
+
+ for range 16 {
+ workers.Add(1)
+ go func() {
+ defer workers.Done()
+ contacts <- tree.sphere([3]float32{-.25, .5, .5}, .5)
+ }()
+ }
+ workers.Wait()
+ close(contacts)
+
+ for contact := range contacts {
+ if !contact.hit || contact.distance != .25 || contact.point != [3]float32{0, .5, .5} || contact.normal != [3]float32{-1, 0, 0} {
+ t.Fatal("concurrent immutable surface query", contact)
+ }
+ }
+}
+
+func TestSurfaceSpherePreservesGroupAndKDTraversalTies(t *testing.T) {
+ vertices := [][3]float32{{0, -2, -2}, {0, -2, 2}, {0, 2, -2}, {-2, -2, 0}, {-2, 2, 0}, {2, -2, 0}}
+ groups := []surfaceGroup{
+ {bounds: [6]float32{0, -2, -2, 0, 2, 2}, triangles: [][3]uint32{{0, 1, 2}}},
+ {bounds: [6]float32{-2, -2, 0, 2, 2, 0}, triangles: [][3]uint32{{3, 4, 5}}},
+ }
+
+ for _, scenario := range []struct {
+ name string
+ nodes []surfaceNode
+ center [3]float32
+ normal [3]float32
+ }{
+ {"first group", []surfaceNode{{groups: []uint32{0, 1}}}, [3]float32{-.25, 0, -.25}, [3]float32{-1, 0, 0}},
+ {"reversed groups", []surfaceNode{{groups: []uint32{1, 0}}}, [3]float32{-.25, 0, -.25}, [3]float32{0, 0, -1}},
+ {"upper on split", []surfaceNode{{axis: 1, children: [2]int{1, 2}}, {groups: []uint32{0}}, {groups: []uint32{1}}}, [3]float32{-.25, 0, -.25}, [3]float32{0, 0, -1}},
+ {"lower below split", []surfaceNode{{axis: 1, children: [2]int{1, 2}}, {groups: []uint32{0}}, {groups: []uint32{1}}}, [3]float32{-.25, -.01, -.25}, [3]float32{-1, 0, 0}},
+ } {
+ t.Run(scenario.name, func(t *testing.T) {
+ tree := &surfaceTree{vertices: vertices, groups: append([]surfaceGroup(nil), groups...), nodes: scenario.nodes}
+ contact := tree.sphere(scenario.center, .5)
+ if !contact.hit || contact.distance != .25 || contact.normal != scenario.normal {
+ t.Fatal("authored traversal must decide equal-distance contacts", contact)
+ }
+ })
+ }
+}
+
+func TestSurfaceSpherePrefersFaceWithinSquaredDistanceTolerance(t *testing.T) {
+ tree := &surfaceTree{
+ vertices: [][3]float32{{0, -2, 0}, {0, 2, 0}, {0, -2, -2}, {.0001, -2, -2}, {.0001, -2, 2}, {.0001, 2, -2}},
+ groups: []surfaceGroup{{bounds: [6]float32{0, -2, -2, .0001, 2, 2}, triangles: [][3]uint32{{0, 1, 2}, {3, 4, 5}}}},
+ nodes: []surfaceNode{{groups: []uint32{0}}},
+ }
+
+ contact := tree.sphere([3]float32{-.25, -.5, .005}, .5)
+
+ if !contact.hit || math.Abs(float64(contact.point[0]-.0001)) > .0000001 || math.Abs(float64(contact.point[2]-.005)) > .0000001 || math.Abs(float64(contact.distance-.2501)) > .0000001 {
+ t.Fatal("near-tied face should replace the slightly closer edge within its group", contact)
+ }
+}
+
+func TestSurfaceSphereFindsShippedBuildingAtNativeStop(t *testing.T) {
+ database, err := readGameDatabase(assets.Files)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { database.file.Close() })
+ payload, version, err := database.read(1000013, 46203264)
+ if err != nil {
+ t.Fatal(err)
+ }
+ surface, err := decodeSceneSurface(payload, version)
+ if err != nil {
+ t.Fatal(err)
+ }
+ radius := float32(.25075000524520874)
+
+ stopped := surface.primary.sphere([3]float32{971.701416, 16.40999985 + radius, 519.643555}, radius)
+ penetrating := surface.primary.sphere([3]float32{971.72, 16.40999985 + radius, 519.66}, radius)
+
+ if stopped.hit {
+ t.Fatal("native separated actor should lie outside the authored wall sphere", stopped)
+ }
+ if !penetrating.hit || penetrating.distance >= radius || penetrating.normal[1] != 0 {
+ t.Fatal("a small step beyond the measured stop must contact the shipped upright wall", penetrating)
+ }
+ t.Logf("penetrating wall contact: point=%v normal=%v distance=%v", penetrating.point, penetrating.normal, penetrating.distance)
+}