aorecomp

Anarchy Online classic in the browser

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


server/browser_faction_progression_test.go (7175B)


      1 package main
      2 
      3 import (
      4 	"ao/server/gamedata"
      5 	"context"
      6 	"crypto/sha256"
      7 	"encoding/binary"
      8 	"encoding/json"
      9 	"fmt"
     10 	"math"
     11 	"net/http"
     12 	"net/http/httptest"
     13 	"os"
     14 	"os/exec"
     15 	"path/filepath"
     16 	"reflect"
     17 	"runtime"
     18 	"testing"
     19 	"time"
     20 )
     21 
     22 func TestBrowserFactionLevelAndMissionRepeat(t *testing.T) {
     23 	if os.Getenv("AO_GAME_TEST") != "1" {
     24 		t.Skip("set AO_GAME_TEST=1 for the Clan/Neutral progression checkpoints")
     25 	}
     26 	_, source, _, _ := runtime.Caller(0)
     27 	root := filepath.Dir(filepath.Dir(source))
     28 	output := filepath.Join(root, "local/alpha-faction-progression", time.Now().Format("20060102-150405"))
     29 	for _, fixture := range []struct {
     30 		name  string
     31 		booth uint32
     32 		side  uint16
     33 	}{{"Clan", 3221228572, 1}, {"Neutral", 3221228532, 0}} {
     34 		t.Run(fixture.name, func(t *testing.T) {
     35 			groups := gamedata.NPCGroups
     36 			world, _ := newCreatedStarterCombatWorld(t, 9, 40132)
     37 			for _, encounter := range gamedata.MissionTemplates[fixture.booth].Encounters {
     38 				gamedata.NPCGroups[encounter.Definition] = groups[encounter.Definition]
     39 			}
     40 			player, target, client := world.characters[2], world.characters[1000000], world.clients[2]
     41 			booth := gamedata.MissionBooths[fixture.booth]
     42 			player.appearance = player.appearance&^(3<<9) | fixture.side<<9
     43 			player.playfield, player.position = booth.Playfield, booth.Position
     44 			// Grant only a near-level XP checkpoint and the first request fee.
     45 			player.experience = gamedata.ExperienceLevels[0] - 100
     46 			player.inventory.Credits = 1
     47 			player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte("faction-progression")))
     48 			if err := world.saveUser(player); err != nil {
     49 				t.Fatal(err)
     50 			}
     51 			if err := world.saveInventory(player, player.inventory); err != nil {
     52 				t.Fatal(err)
     53 			}
     54 			request := missionOffersRequest()
     55 			binary.BigEndian.PutUint32(request[8:12], player.id)
     56 			originator, admitted := world.missionBoothEligibility(client, booth)
     57 			if !admitted {
     58 				t.Fatal("faction checkpoint cannot use its original booth")
     59 			}
     60 			request[28] = byte(originator)
     61 			binary.BigEndian.PutUint32(request[33:37], fixture.booth)
     62 			if err := world.handleMissionOffers(client, request); err != nil || client.missionOffer == nil {
     63 				t.Fatal("initial offer", err)
     64 			}
     65 			request = missionAcceptanceRequest(*client.missionOffer)
     66 			binary.BigEndian.PutUint32(request[8:12], player.id)
     67 			if err := world.handleMissionAcceptance(client, request); err != nil {
     68 				t.Fatal(err)
     69 			}
     70 			initialIP := player.stats.ImprovementPoints
     71 
     72 			for phase := 0; phase < 2; phase++ {
     73 				// Objective collection and return placement are controlled checkpoints.
     74 				// Native input performs the level, training, settlement and repeat request.
     75 				client = &worldClient{id: player.id, conn: &combatTestConn{}, ready: true, target: true, npcs: map[uint32]bool{target.id: true}}
     76 				world.clients[player.id] = client
     77 				if len(player.missions) != 1 {
     78 					t.Fatal("expected one accepted contract", len(player.missions))
     79 				}
     80 				mission := player.missions[0]
     81 				itemCount := len(player.inventory.Items)
     82 				player.position = mission.offer.definition.Position
     83 				player.movement = playerMovement{}
     84 				if err := world.handleMovement(client, playerMovementRequest(player, 1)); err != nil {
     85 					t.Fatal(err)
     86 				}
     87 				world.clients[player.id], client.ready, client.loading = client, true, false
     88 				mission = player.missions[0]
     89 				player.position = world.worldItems[mission.objective].position
     90 				player.movement = playerMovement{}
     91 				if err := world.handleInventory(client, worldPickupRequest(player.id, mission.objective)); err != nil {
     92 					t.Fatal(err)
     93 				}
     94 				if mission.objective == 0 || len(player.inventory.Items) != itemCount+1 {
     95 					t.Fatal("checkpoint did not collect its mission book", player.inventory)
     96 				}
     97 				player.playfield, player.position = booth.Playfield, booth.Position
     98 				player.position[1] += .5
     99 				player.position[2] += 3
    100 				yaw := math.Atan2(float64(booth.Position[0]-player.position[0]), float64(booth.Position[2]-player.position[2]))
    101 				player.rotation = [4]float32{0, float32(math.Sin(yaw / 2)), 0, float32(math.Cos(yaw / 2))}
    102 				if phase == 0 {
    103 					target.playfield, target.position = player.playfield, player.position
    104 					target.position[0] += 1
    105 					target.position[2] -= 2
    106 					target.motion.home = target.position
    107 				}
    108 				if err := world.savePosition(player); err != nil {
    109 					t.Fatal(err)
    110 				}
    111 				delete(world.clients, player.id)
    112 
    113 				// Persist the cross-zone checkpoint before partitioning owners.
    114 				if err := world.flushWorld(); err != nil {
    115 					t.Fatal(err)
    116 				}
    117 				shutdown := startTestService(t, world)
    118 				mux := http.NewServeMux()
    119 				mux.Handle("/", world.httpHandler())
    120 				mux.HandleFunc("GET /test-state", testPlayerHTTP(world, 2, func(world *server, w http.ResponseWriter, r *http.Request) {
    121 					player, target := world.characters[2], world.characters[1000000]
    122 					missions := []map[string]any{}
    123 					for _, accepted := range player.missions {
    124 						missions = append(missions, map[string]any{"id": accepted.id, "objective": accepted.objective, "definition": accepted.offer.definition})
    125 					}
    126 					var offer any
    127 					if client := world.clients[player.id]; client != nil && client.missionOffer != nil {
    128 						offer = client.missionOffer.definition
    129 					}
    130 					json.NewEncoder(w).Encode(map[string]any{"phase": phase, "booth": fixture.booth, "id": player.id,
    131 						"health": player.health, "level": player.level, "experience": player.experience, "stats": player.stats,
    132 						"inventory": player.inventory, "target": target.id, "targetHealth": target.health,
    133 						"completed": world.missionWorld(mission.world).completed, "definition": mission.offer.definition, "missions": missions, "offer": offer})
    134 				}))
    135 				host := httptest.NewServer(mux)
    136 				ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
    137 				artifacts := filepath.Join(output, fixture.name, fmt.Sprint(phase))
    138 				command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/test_faction_progression.mjs"), host.URL, artifacts)
    139 				command.Dir, command.Stdout, command.Stderr = root, os.Stdout, os.Stderr
    140 				err := command.Run()
    141 				cancel()
    142 				host.Close()
    143 				if err := shutdown(); err != nil {
    144 					t.Fatal(err)
    145 				}
    146 				t.Logf("Browser artifacts: %s", artifacts)
    147 				if err != nil {
    148 					t.Fatal(err)
    149 				}
    150 				cold := newServerForTest(t)
    151 				restored := cold.characters[player.id]
    152 				expected := player.inventory
    153 				expected.LastID = cold.nextItem
    154 				if restored.level != 2 || restored.experience != 0 || restored.stats != player.stats || restored.health != player.health ||
    155 					!reflect.DeepEqual(restored.inventory, expected) || len(restored.missions) != 1-phase || !cold.missionWorld(mission.world).completed {
    156 					t.Fatal("faction progression changed on cold load", restored.profile(), restored.inventory)
    157 				}
    158 				world, player = cold, restored
    159 				target = world.characters[1000000]
    160 			}
    161 			if player.stats.Body.BodyDevelopment != 15 || player.stats.ImprovementPoints != initialIP+4000-69 || player.inventory.Credits != 1498 {
    162 				t.Fatal("repeat contract or earned training accounting changed", player.stats, player.inventory)
    163 			}
    164 		})
    165 	}
    166 }