commit f613f18336d731e836e396ca5c92c39b9f3ca995
parent 0009d01fbbb98da2f58b9358cd951a9d03fdb287
Author: anon <anon@example.com>
Date: Fri, 6 Nov 2026 21:20:27 +0000
Use the original native character creator and Arrival Hall handoff
Diffstat:
50 files changed, 2219 insertions(+), 230 deletions(-)
diff --git a/DEVELOPERS.md b/DEVELOPERS.md
@@ -165,6 +165,10 @@ memory, OffscreenCanvas and WebGL 2. It loads automatically with a
randomized Solitus visitor near Bronto Burger in Omni-Entertainment. A persistent
cookie identifies your character on later visits; no account or training is
required. New visitors start in run mode with character tips disabled.
+Opt's Create character from scratch opens the original native creator. After
+naming, speak to an Arrival Hall representative to choose a faction and enter
+its training ground. Use Save this character in Opt to enable name/password
+login; until then, the browser cookie owns the character.
Opening the same character in another tab disconnects the earlier tab. That tab
shows a Reconnect button; clicking it takes the character back. Temporary network
interruptions still reconnect automatically.
diff --git a/TODO.md b/TODO.md
@@ -35,6 +35,16 @@ research separately. More screenshots and test cases do not count as new gamepla
## P0: first experience
+- [x] **Use the original native character creation flow.** Options now launches
+ the original breed, appearance, profession and naming scenes, using the shared
+ atomic creation backend. Real WASM input covers cancellation, short/duplicate
+ names, completion, walking through Arrival Hall, faction departure, saving,
+ inventory preferences, reconnect and cold recovery of both old and new saved
+ characters. Protocol tests cover duplicate submissions and competing sockets
+ without duplicate characters/items. Hall dialogue, outfits and departure
+ policy remain explicit reconstructions; see [character creation](docs/character-creation.md)
+ and [Arrival Hall](docs/arrival-hall.md).
+
- [x] **Give new visitors starter items and a separate Visitor title.** New
visitors receive the character-creation starter kit atomically. A free-text
`title` column beside `name` stores `Visitor` and clears on adoption; generated
diff --git a/client/browser/index.html b/client/browser/index.html
@@ -107,7 +107,7 @@
<p id="account-current"></p>
<fieldset id="account-choices" disabled>
<button id="create-button" type="button">Create character from scratch</button>
- <button id="claim-button" type="button" hidden>Adopt this visitor</button>
+ <button id="claim-button" type="button" hidden>Save this character</button>
<button id="password-button" type="button" hidden>Change password</button>
<button id="login-button" type="button">Log in to an existing character</button>
</fieldset>
@@ -115,30 +115,6 @@
<h2 id="account-title"></h2>
<p id="account-description"></p>
<fieldset id="account-fields">
- <fieldset id="creation-fields" hidden disabled>
- <label>Breed <select id="creation-breed">
- <option value="1">Solitus</option><option value="2">Opifex</option>
- <option value="3">Nanomage</option><option value="4">Atrox</option>
- </select></label>
- <label>Sex <select id="creation-sex"></select></label>
- <label>Head <select id="creation-head"></select></label>
- <label>Build <select id="creation-build">
- <option value="0">Slim</option><option value="1" selected>Normal</option><option value="2">Heavy</option>
- </select></label>
- <label>Height <select id="creation-height">
- <option value="90">Short</option><option value="100" selected>Normal</option><option value="110">Tall</option>
- </select></label>
- <label>Profession <select id="creation-profession" required>
- <option value="">Choose a profession</option>
- <option value="1">Soldier</option><option value="2">Martial Artist</option><option value="3">Engineer</option>
- <option value="4">Fixer</option><option value="5">Agent</option><option value="6">Adventurer</option>
- <option value="7">Trader</option><option value="8">Bureaucrat</option><option value="9">Enforcer</option>
- <option value="10">Doctor</option><option value="11">Nano-Technician</option><option value="12">Meta-Physicist</option>
- </select></label>
- <label>Side <select id="creation-side" required>
- <option value="">Choose a side</option><option value="0">Neutral</option><option value="1">Clan</option><option value="2">Omni-Tek</option>
- </select></label>
- </fieldset>
<label>Player name <input id="account-name" name="name" autocomplete="username" maxlength="254" required></label>
<label><span id="account-password-label">Password</span> <input id="account-password" name="password" type="password" autocomplete="current-password" maxlength="1024"></label>
<button id="account-back" type="button">Back</button>
@@ -405,9 +381,14 @@ show();
document.addEventListener(type, resumeAudio, true);
}
status.textContent = 'Downloading Anarchy Online client...';
- const response = await fetch('browser-launch', {method: 'POST'});
+ const launchURL = new URL(location.href);
+ const creating = launchURL.searchParams.get('create') === '1';
+ launchURL.searchParams.delete('create');
+ history.replaceState(null, '', launchURL);
+ const response = await fetch('browser-launch' + (creating ? '?create=1' : ''), {method: 'POST'});
if (!response.ok) { status.textContent = await response.text(); return; }
Module.arguments = (await response.text()).trim().split(' ').slice(1);
+ Module.worldPort = Number(response.headers.get('X-AO-World-Port')) || Number(Module.arguments.at(-3));
// The render worker owns the backing canvas after startup.
[canvas.width, canvas.height] = renderSize();
// Keep the script available when later pthreads start during a server outage.
@@ -963,35 +944,24 @@ show();
const accountError = document.querySelector('#account-error');
const accountChoices = document.querySelector('#account-choices');
const accountFields = document.querySelector('#account-fields');
- const creationFields = document.querySelector('#creation-fields');
const claimButton = document.querySelector('#claim-button');
const passwordButton = document.querySelector('#password-button');
- const creationBreed = document.querySelector('#creation-breed');
- const creationSex = document.querySelector('#creation-sex');
- const creationHead = document.querySelector('#creation-head');
- let accountAction = '', creationHeads = [];
+ let accountAction = '', currentName = '';
- // Breed and sex restrict the head list; its mesh also selects the matching skin.
- function updateCreationHeads() {
- const heads = creationHeads.filter(head => head.breed === Number(creationBreed.value) && head.sex === Number(creationSex.value));
- creationHead.replaceChildren(...heads.map((head, index) => new Option('Head ' + (index + 1), head.mesh)));
- }
- creationBreed.onchange = () => {
- creationSex.replaceChildren(...(creationBreed.value === '4' ? [new Option('Androgynous', '1')] :
- [new Option('Male', '2'), new Option('Female', '3')]));
- updateCreationHeads();
+ // Restart in the original creator; cancellation returns to the current character.
+ document.querySelector('#create-button').onclick = () => {
+ location.assign('?create=1');
};
- creationSex.onchange = updateCreationHeads;
// Keep account flows separate and clear abandoned credentials on Back.
for (const [action, title, description] of [
- ['create', 'Create character', 'Start a new level-1 character in your side\'s training grounds. Named characters remain available through Log in.'],
- ['claim', 'Adopt this visitor', 'Keep this character, including its equipment and progress, with a name and password.'],
+ ['claim', 'Save this character', 'Keep this character, including its equipment and progress, with a name and password.'],
['login', 'Log in', 'Switch to an existing character using its name and password.'],
['password', 'Change password', '']
]) {
document.querySelector('#' + action + '-button').onclick = () => {
accountAction = action;
+ if (action === 'claim') document.querySelector('#account-name').value = currentName;
accountError.textContent = '';
accountError.classList.remove('success');
const changingPassword = action === 'password';
@@ -1001,13 +971,11 @@ show();
document.querySelector('#account-description').hidden = changingPassword;
accountChoices.hidden = true;
accountForm.hidden = false;
- creationFields.hidden = creationFields.disabled = action !== 'create';
document.querySelector('#account-title').textContent = title;
- document.querySelector('#account-description').textContent = description +
- (action === 'create' && !claimButton.hidden ? ' Adopt this visitor first if you want to return to it later.' : '');
+ document.querySelector('#account-description').textContent = description;
document.querySelector('#account-submit').textContent = title;
document.querySelector('#account-password').autocomplete = action === 'login' ? 'current-password' : 'new-password';
- document.querySelector(changingPassword ? '#account-password' : action === 'create' ? '#creation-breed' : '#account-name').focus();
+ document.querySelector(changingPassword ? '#account-password' : '#account-name').focus();
};
}
document.querySelector('#account-back').onclick = () => {
@@ -1033,10 +1001,9 @@ show();
const response = await fetch('browser-account');
if (!response.ok) { accountError.textContent = await response.text(); return; }
const player = await response.json();
- document.querySelector('#account-current').textContent = `Playing as ${player.name}.`;
- creationHeads = player.heads;
- creationBreed.value = '1';
- creationBreed.onchange();
+ currentName = player.name;
+ document.querySelector('#account-current').textContent = `Playing as ${player.name}.` +
+ (player.visitor ? ' Save this character to enable name-and-password login.' : '');
claimButton.hidden = !player.visitor;
passwordButton.hidden = !player.adopted;
accountChoices.disabled = false;
@@ -1052,11 +1019,6 @@ show();
accountError.textContent = '';
const values = new URLSearchParams({name: document.querySelector('#account-name').value,
password: document.querySelector('#account-password').value});
- if (accountAction === 'create') {
- for (const [name, selector] of [['head_mesh', 'head'], ['profession', 'profession'], ['side', 'side'], ['build', 'build'], ['height', 'height']]) {
- values.set(name, document.querySelector('#creation-' + selector).value);
- }
- }
try {
const response = await fetch('browser-account/' + accountAction, {method: 'POST', body: values});
if (response.ok) {
diff --git a/client/runtime/browser_host.c b/client/runtime/browser_host.c
@@ -18,6 +18,32 @@ char *ao_asset_manifest_parse(const char *json);
char *browser_preferences_directory(const char *base);
void browser_storage_available(em_proxying_ctx *context, void *available);
+static char *preferences_directory;
+static unsigned preferences_character = UINT32_MAX;
+
+void browser_select_character(unsigned character_id)
+{
+ if (character_id == preferences_character) return;
+
+ /* Mount the new character before native preferences load on world entry. */
+ char persistent_path[4096];
+ snprintf(persistent_path, sizeof(persistent_path), "%s/%u", preferences_directory, character_id);
+ assert(mkdir(persistent_path, 0755) == 0 || errno == EEXIST);
+ char character_path[128];
+ snprintf(character_path, sizeof(character_path), "Prefs/localtest/Char%u", character_id);
+ assert(symlink(persistent_path, character_path) == 0);
+
+ /* Seed first-run settings once; native writers create the other files. */
+ strcat(character_path, "/Char.cfg");
+ int preferences_file = open(character_path, O_CREAT | O_EXCL | O_WRONLY, 0600);
+ if (preferences_file >= 0) {
+ const char first_run[] = "IsFirstTime 1\nIsTipEnabled 0\n";
+ assert(write(preferences_file, first_run, sizeof(first_run) - 1) == sizeof(first_run) - 1);
+ assert(close(preferences_file) == 0);
+ } else assert(errno == EEXIST);
+ preferences_character = character_id;
+}
+
static char *ao_asset_manifest(const char *base)
{
/* Fetch and retry on the page thread while this worker waits without JSPI. */
@@ -125,25 +151,10 @@ void browser_initialize(unsigned character_id)
assert(storage_available >= 0);
backend_t persistent = storage_available ? wasmfs_create_opfs_backend() : wasmfs_create_memory_backend();
assert(wasmfs_create_directory("/persistent", 0755, persistent) == 0);
- char *directory = browser_preferences_directory(base);
+ preferences_directory = browser_preferences_directory(base);
free(base);
- assert(mkdir(directory, 0755) == 0 || errno == EEXIST);
- char persistent_path[4096];
- snprintf(persistent_path, sizeof(persistent_path), "%s/%u", directory, character_id);
- assert(mkdir(persistent_path, 0755) == 0 || errno == EEXIST);
- free(directory);
- char character_path[128];
- snprintf(character_path, sizeof(character_path), "Prefs/localtest/Char%u", character_id);
- assert(symlink(persistent_path, character_path) == 0);
-
- /* Seed first-run settings once; native writers create the other files. */
- strcat(character_path, "/Char.cfg");
- int preferences_file = open(character_path, O_CREAT | O_EXCL | O_WRONLY, 0600);
- if (preferences_file >= 0) {
- const char first_run[] = "IsFirstTime 1\nIsTipEnabled 0\n";
- assert(write(preferences_file, first_run, sizeof(first_run) - 1) == sizeof(first_run) - 1);
- assert(close(preferences_file) == 0);
- } else assert(errno == EEXIST);
+ assert(mkdir(preferences_directory, 0755) == 0 || errno == EEXIST);
+ browser_select_character(character_id);
/* Start the guest with the viewport size, including nonstandard aspect ratios. */
int width, height;
@@ -164,6 +175,9 @@ void browser_initialize(unsigned character_id)
assert(symlink("/remote/Setupf", "Setupf") == 0);
assert(symlink("/remote/fonts", "fonts") == 0);
assert(symlink("/remote/version.id", "version.id") == 0);
+
+ /* The native creator loads its camera paths from the game directory. */
+ assert(symlink("/remote/CharCreateCamera.dat", "CharCreateCamera.dat") == 0);
setenv("ANARCHY_CD", "cd_image", 1);
setenv("ANARCHY_SETUP", "Setupf", 1);
setenv("ANARCHY", ".", 1);
diff --git a/client/runtime/browser_loop.c b/client/runtime/browser_loop.c
@@ -10,6 +10,7 @@ void ao_frame_complete(void);
void ao_frame_begin(double timestamp);
void ao_game_closed(void);
void browser_test_frame(void);
+void browser_select_character(unsigned character_id);
int browser_graphics_ready(void);
void sub_28002DA0(void);
void sub_28001000(void);
@@ -34,6 +35,8 @@ static bool browser_frame(double timestamp, void *argument)
return false;
}
assert(g_esp == loop_stack);
+ /* FFR s_nCharID changes when the creator accepts the server's new identity. */
+ browser_select_character(MEM32(0x2f01f008));
browser_test_frame();
ao_frame_complete();
return true;
diff --git a/client/runtime/browser_network.js b/client/runtime/browser_network.js
@@ -8,6 +8,29 @@ addToLibrary({
entry.socket.send(message);
},
connect(entry) {
+ // Character creation uses the original login protocol before a world stream exists.
+ if (entry.creation) {
+ const socket = entry.socket = new WebSocket(entry.url);
+ socket.binaryType = 'arraybuffer';
+ socket.onopen = () => { entry.ready = entry.connected = true; };
+ socket.onmessage = event => {
+ if (entry.closed) return;
+ const bytes = new Uint8Array(event.data);
+ if (entry.bytes + bytes.length > 8 * 1024 * 1024) {
+ socket.close(4000, 'Receive buffer full');
+ return;
+ }
+ entry.chunks.push(bytes);
+ entry.bytes += bytes.length;
+ };
+ socket.onclose = event => {
+ if (entry.closed) return;
+ entry.ready = entry.connected = false;
+ entry.closed = true;
+ entry.error = event.code !== 1000;
+ };
+ return;
+ }
const socket = entry.socket = new WebSocket(entry.url, 'ao-stream-v1');
entry.ready = false;
socket.binaryType = 'arraybuffer';
@@ -91,7 +114,7 @@ addToLibrary({
if (document.hidden) return;
// Safari can retain an OPEN socket after its underlying connection has died.
for (const entry of AOSockets.sockets.values()) {
- if (entry.closed || (!entry.ready && !entry.retry)) continue;
+ if (entry.creation || entry.closed || (!entry.ready && !entry.retry)) continue;
clearTimeout(entry.retry);
entry.retry = null;
const socket = entry.socket;
@@ -134,12 +157,14 @@ addToLibrary({
ao_socket_connect: (handle, port) => {
const entry = AOSockets.sockets.get(handle);
// Emscripten prepends the executable name; the port precedes two cookies.
- const worldPort = Number(Module['arguments'].at(-3));
- if (port !== worldPort && port !== worldPort + 1) {
+ const launchPort = Number(Module['arguments'].at(-3));
+ const worldPort = Module['worldPort'] || launchPort;
+ entry.creation = Module['arguments'].at(-5) === '0' && port === launchPort;
+ if (!entry.creation && port !== worldPort && port !== worldPort + 1) {
entry.error = true;
return;
}
- const url = new URL(port === worldPort ? 'browser-world' : 'browser-chat', document.baseURI);
+ const url = new URL(entry.creation ? 'browser-create' : port === worldPort ? 'browser-world' : 'browser-chat', document.baseURI);
url.protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
entry.url = url;
AOSockets.connect(entry);
@@ -160,6 +185,10 @@ addToLibrary({
ao_socket_send: (handle, data, size) => {
const entry = AOSockets.sockets.get(handle);
if (!entry || !entry.connected) return -10057;
+ if (entry.creation) {
+ entry.socket.send(HEAPU8.slice(data, data + size));
+ return size;
+ }
if (entry.written - entry.acknowledged + BigInt(size) > 8n * 1024n * 1024n) return -10035;
// Retain unacknowledged bytes so reconnection cannot duplicate or omit input.
for (let offset = 0; offset < size; offset += 32768) {
@@ -204,7 +233,7 @@ addToLibrary({
if (entry) {
entry.closed = true;
clearTimeout(entry.retry);
- if (entry.socket?.readyState === 1) entry.socket.send(JSON.stringify({close: true}));
+ if (!entry.creation && entry.socket?.readyState === 1) entry.socket.send(JSON.stringify({close: true}));
entry.socket?.close();
AOSockets.sockets.delete(handle);
}
diff --git a/client/runtime/browser_testing.c b/client/runtime/browser_testing.c
@@ -297,6 +297,16 @@ void browser_test_frame(void)
pick_sequence, pick_position[0], pick_position[1], pick_type, pick_id);
else fputs("null", output);
+ /* ddr.dll SceneBase_t::GetSceneID and NameScene_t::SetState. */
+ uint32_t creation = MEM32(0x2b0ee7d0);
+ fputs(",\"creation\":", output);
+ if (creation) {
+ fprintf(output, "{\"scene\":%u,\"hover\":%u,\"nameState\":%u,\"ready\":%s}",
+ MEM32(creation + 0x40), MEM32(creation + 0x5c),
+ creation == MEM32(0x2b0ee7e0) ? MEM32(creation + 0xa4) : 0,
+ MEM32(0x2b0e42a8) ? "false" : "true");
+ } else fputs("null", output);
+
fputs(",\"actors\":[", output);
uint32_t actors = MEM32(0x3806c110);
/* Resolve the engine's local actor pointer through the same directory. */
diff --git a/client/runtime/guest_crt.c b/client/runtime/guest_crt.c
@@ -749,6 +749,27 @@ static void crt_tolower(void)
g_esp += 4;
}
+static void crt_toupper(void)
+{
+ g_eax = MEM32(g_esp + 4);
+ if (g_eax >= 'a' && g_eax <= 'z') g_eax -= 'a' - 'A';
+ g_esp += 4;
+}
+
+static void crt_isupper(void)
+{
+ uint32_t value = MEM32(g_esp + 4);
+ g_eax = value >= 'A' && value <= 'Z' ? 1 : 0;
+ g_esp += 4;
+}
+
+static void crt_islower(void)
+{
+ uint32_t value = MEM32(g_esp + 4);
+ g_eax = value >= 'a' && value <= 'z' ? 2 : 0;
+ g_esp += 4;
+}
+
static void crt_stricmp(void)
{
const unsigned char *left = (const unsigned char *)ADDR(MEM32(g_esp + 4));
@@ -1126,7 +1147,8 @@ recomp_func_t guest_crt_lookup(const char *name)
{"strncmp", crt_strncmp},
{"_stricmp", crt_stricmp},
{"_strnicmp", crt_strnicmp},
- {"tolower", crt_tolower},
+ {"tolower", crt_tolower}, {"toupper", crt_toupper},
+ {"isupper", crt_isupper}, {"islower", crt_islower},
{"strrchr", crt_strrchr}, {"_mbsrchr", crt_strrchr}, /* Initial single-byte locale. */
{"memcmp", crt_memcmp}, {"memchr", crt_memchr},
{"sscanf", crt_sscanf},
diff --git a/client/runtime/guest_stdio.c b/client/runtime/guest_stdio.c
@@ -572,6 +572,34 @@ static void crt_fgetc_locked(void)
g_esp += 4;
}
+static void crt_ungetc_locked(void)
+{
+ int character = MEM32(g_esp + 4);
+ struct stream *stream = find_stream(MEM32(g_esp + 8));
+ uint32_t file = stream->file, flags = MEM32(file + 12);
+ g_eax = UINT32_MAX;
+ g_esp += 4;
+ if (character == EOF || !(flags & (1 | 0x80)) || (flags & 2)) return;
+
+ /* Guest C++ streams also inspect this buffer directly when putting back a byte. */
+ if (!MEM32(file + 8)) {
+ uint32_t buffer = guest_malloc(4096);
+ if (!buffer) { file_error(ENOMEM); return; }
+ MEM32(file) = MEM32(file + 8) = buffer;
+ MEM32(file + 24) = 4096;
+ MEM32(file + 12) |= 8;
+ }
+ if (MEM32(file) == MEM32(file + 8)) {
+ if (MEM32(file + 4)) return;
+ ++MEM32(file);
+ }
+ --MEM32(file);
+ MEM8(MEM32(file)) = (unsigned char)character;
+ ++MEM32(file + 4);
+ MEM32(file + 12) = (MEM32(file + 12) & ~0x10u) | 1;
+ g_eax = (unsigned char)character;
+}
+
static void crt_fgets_locked(void)
{
uint32_t output = MEM32(g_esp + 4);
@@ -802,6 +830,7 @@ static void crt_fseek(void) { call_stream(crt_fseek_locked, MEM32(g_esp + 4)); }
static void crt_fgetpos(void) { call_stream(crt_fgetpos_locked, MEM32(g_esp + 4)); }
static void crt_fsetpos(void) { call_stream(crt_fsetpos_locked, MEM32(g_esp + 4)); }
static void crt_fgetc(void) { call_stream(crt_fgetc_locked, MEM32(g_esp + 4)); }
+static void crt_ungetc(void) { call_stream(crt_ungetc_locked, MEM32(g_esp + 8)); }
static void crt_fscanf(void) { call_stream(crt_fscanf_locked, MEM32(g_esp + 4)); }
static void crt_filbuf(void) { call_stream(crt_filbuf_locked, MEM32(g_esp + 4)); }
@@ -836,6 +865,7 @@ recomp_func_t guest_stdio_lookup(const char *name)
{"ftell", crt_ftell}, {"fseek", crt_fseek}, {"fread", crt_fread},
{"fgetpos", crt_fgetpos}, {"fsetpos", crt_fsetpos},
{"fgetc", crt_fgetc}, {"getc", crt_fgetc}, {"_filbuf", crt_filbuf},
+ {"ungetc", crt_ungetc},
{"fgets", crt_fgets},
{"fscanf", crt_fscanf},
};
diff --git a/client/tests/browser_accounts.mjs b/client/tests/browser_accounts.mjs
@@ -28,7 +28,7 @@ function accountPage() {
document, window, navigator: {userAgent: 'Desktop'}, console, URLSearchParams,
Option: class { constructor(text, value) { this.text = text; this.value = String(value); } },
localStorage: {getItem() { return null; }},
- location: {reload: () => reloads.push(true)},
+ location: {reload: () => reloads.push(true), assign: url => reloads.push(url)},
setTimeout: callback => timers.push(callback),
updateTouchControls() {},
fetch: async (url, options) => {
@@ -51,12 +51,9 @@ function response(status, body) {
return {ok: status >= 200 && status < 300, json: async () => body, text: async () => body};
}
-const heads = [{mesh: 40681, breed: 1, sex: 2, race: 1}, {mesh: 40629, breed: 1, sex: 3, race: 1},
- {mesh: 40111, breed: 4, sex: 1, race: 1}];
-
test('Options offers visitor account flows with credentials hidden until a choice', async () => {
const page = accountPage();
- page.replies.push(response(200, {name: 'Lupeza', visitor: true, heads}));
+ page.replies.push(response(200, {name: 'Lupeza', visitor: true}));
await page.open();
@@ -67,11 +64,13 @@ test('Options offers visitor account flows with credentials hidden until a choic
assert.match(page.element('#account-current').textContent, /Playing as Lupeza/);
assert.equal(page.element('#account-password').value, '');
assert.equal(page.requests[0].url, 'browser-account');
+ page.choose('claim');
+ assert.equal(page.element('#account-name').value, 'Lupeza');
});
test('an adopted player can change password with adoption hidden', async () => {
const page = accountPage();
- page.replies.push(response(200, {name: 'Alice', visitor: false, adopted: true, heads}));
+ page.replies.push(response(200, {name: 'Alice', visitor: false, adopted: true}));
await page.open();
@@ -108,15 +107,12 @@ for (const password of ['updated password', '']) {
});
}
-for (const action of ['create', 'claim', 'login']) {
+for (const action of ['claim', 'login']) {
test(`${action} posts exact credentials and reloads after success despite a session replacement notification`, async () => {
const page = accountPage();
page.choose(action);
page.element('#account-name').value = 'Alice';
page.element('#account-password').value = ' spaced password ';
- for (const [name, value] of [['head', '40111'], ['profession', '12'], ['side', '0'], ['build', '2'], ['height', '110']]) {
- page.element('#creation-' + name).value = value;
- }
let finish;
page.replies.push(new Promise(resolve => { finish = resolve; }));
@@ -130,11 +126,6 @@ for (const action of ['create', 'claim', 'login']) {
assert.equal(page.requests[0].options.method, 'POST');
assert.equal(page.requests[0].options.body.get('name'), 'Alice');
assert.equal(page.requests[0].options.body.get('password'), ' spaced password ');
- assert.equal(page.requests[0].options.body.get('head_mesh'), action === 'create' ? '40111' : null);
- assert.equal(page.requests[0].options.body.get('profession'), action === 'create' ? '12' : null);
- assert.equal(page.requests[0].options.body.get('side'), action === 'create' ? '0' : null);
- assert.equal(page.requests[0].options.body.get('build'), action === 'create' ? '2' : null);
- assert.equal(page.requests[0].options.body.get('height'), action === 'create' ? '110' : null);
await page.submit();
finish(response(204, ''));
@@ -193,34 +184,21 @@ for (const reply of [response(401, 'Reconnect to continue.'), new Error('Offline
});
}
-test('breed and sex filter original heads, including the androgynous Atrox template', async () => {
+test('Create launches the native creator without submitting account fields', async () => {
const page = accountPage();
- page.replies.push(response(200, {name: 'Lupeza', visitor: true, heads}));
+ page.replies.push(response(200, {name: 'Lupeza', visitor: true}));
await page.open();
- page.choose('create');
-
- assert.equal(page.element('#creation-head').value, '40681');
- assert.equal(page.element('#creation-head').children.length, 1);
- assert.equal(page.element('#creation-fields').disabled, false);
- assert.equal(page.element('#account-password').autocomplete, 'new-password');
- assert.match(page.element('#account-description').textContent, /Adopt this visitor first/);
-
- page.element('#creation-sex').value = '3';
- page.element('#creation-sex').onchange();
- assert.equal(page.element('#creation-head').value, '40629');
-
- page.element('#creation-breed').value = '4';
- page.element('#creation-breed').onchange();
+ page.choose('create');
- assert.equal(page.element('#creation-sex').value, '1');
- assert.equal(page.element('#creation-sex').children.length, 1);
- assert.equal(page.element('#creation-head').value, '40111');
+ assert.deepEqual(page.reloads, ['?create=1']);
+ assert.equal(page.element('#account-form').hidden, true);
+ assert.equal(page.requests.length, 1);
});
-test('Back clears credentials and disables creation-only validation in the other flows', async () => {
+test('Back clears credentials before switching account flows', async () => {
const page = accountPage();
- page.choose('create');
+ page.choose('claim');
page.element('#account-name').value = 'Alice';
page.element('#account-password').value = 'secret';
@@ -231,12 +209,10 @@ test('Back clears credentials and disables creation-only validation in the other
assert.equal(page.element('#account-choices').hidden, false);
assert.equal(page.element('#account-name').value, '');
assert.equal(page.element('#account-password').value, '');
- assert.equal(page.element('#create-button').focused, true);
+ assert.equal(page.element('#claim-button').focused, true);
assert.equal(page.requests.length, 0);
page.choose('login');
- assert.equal(page.element('#creation-fields').disabled, true);
- assert.equal(page.element('#creation-fields').hidden, true);
assert.equal(page.element('#account-password').autocomplete, 'current-password');
});
diff --git a/client/tests/browser_loading.mjs b/client/tests/browser_loading.mjs
@@ -14,7 +14,8 @@ function fixture(response) {
const downloadFill = {style: {set width(value) { widths.push(value); }}};
const canvas = {addEventListener() {}, getContext() { return null; }};
const context = vm.createContext({
- console, WebAssembly, Response, TransformStream, crossOriginIsolated: true,
+ console, WebAssembly, Response, TransformStream, URL, crossOriginIsolated: true,
+ location: {href: 'http://localhost/'}, history: {replaceState() {}},
navigator: {userAgent: 'Mozilla/5.0 (X11; Linux x86_64)'},
updateTouchControls() {},
localStorage: {getItem() { return null; }},
@@ -119,8 +120,11 @@ async function reportsUnavailableWebGLOnBothThreadsBeforeDownloading() {
assert.equal(revoked, 'blob:graphics-probe');
}
-async function startsWithMainThreadGraphicsWithoutOffscreenCanvas() {
+async function startsWithMainThreadGraphicsWithoutOffscreenCanvas(creating) {
const test = fixture();
+ test.context.location.href = 'http://localhost/?profile=1' + (creating ? '&create=1' : '');
+ let restoredURL;
+ test.context.history.replaceState = (state, title, url) => { restoredURL = String(url); };
const canvas = test.context.document.querySelector('#canvas');
canvas.getContext = (type, attributes) => {
assert.equal(type, 'webgl2');
@@ -131,16 +135,19 @@ async function startsWithMainThreadGraphicsWithoutOffscreenCanvas() {
canvas.clientHeight = 768;
const scripts = [];
let clientScript;
- test.context.URL = {createObjectURL(blob) { clientScript = blob; return 'blob:client'; }};
+ test.context.URL = class extends URL {
+ static createObjectURL(blob) { clientScript = blob; return 'blob:client'; }
+ };
test.context.AudioContext = class {};
test.context.document.addEventListener = () => {};
test.context.document.createElement = () => ({});
test.context.document.body = {append: script => scripts.push(script.src)};
test.context.fetch = async (url, options) => {
if (url === 'wasm/game.js') return new Response('client code', {headers: {'Content-Type': 'text/javascript'}});
- assert.equal(url, 'browser-launch');
+ assert.equal(url, 'browser-launch' + (creating ? '?create=1' : ''));
assert.equal(options.method, 'POST');
- return new Response('Clientr.exe localtest localtest 73');
+ return new Response('Clientr.exe localtest localtest ' + (creating ? '0' : '73') + ' 2130706433 7600 0 0',
+ {headers: creating ? {'X-AO-World-Port': '7700'} : {}});
};
await test.context.startGame();
@@ -151,6 +158,9 @@ async function startsWithMainThreadGraphicsWithoutOffscreenCanvas() {
assert.equal(canvas.transferControlToOffscreen, undefined);
assert.equal(canvas.width, 1024);
assert.equal(canvas.height, 768);
+ assert.equal(restoredURL, 'http://localhost/?profile=1');
+ assert.equal(test.context.Module.worldPort, creating ? 7700 : 7600);
+ assert.equal(test.context.Module.arguments[2], creating ? '0' : '73');
}
async function rejectsFailedClientScript() {
@@ -172,6 +182,7 @@ hidesProgressWhenDownloadStops();
await rejectsFailedClientDownload();
await reportsMissingWebGL();
await reportsUnavailableWebGLOnBothThreadsBeforeDownloading();
-await startsWithMainThreadGraphicsWithoutOffscreenCanvas();
+await startsWithMainThreadGraphicsWithoutOffscreenCanvas(false);
+await startsWithMainThreadGraphicsWithoutOffscreenCanvas(true);
await rejectsFailedClientScript();
console.log('PASS: loading progress, streaming compilation, first frame, download failure and missing browser graphics');
diff --git a/client/tests/browser_loop.c b/client/tests/browser_loop.c
@@ -24,6 +24,10 @@ void ao_frame_begin(double timestamp)
void ao_frame_complete(void) { ++completed; }
void browser_test_frame(void) { assert(frames == completed + 1); }
void ao_game_closed(void) { ++closed; }
+void browser_select_character(unsigned character_id)
+{
+ assert(character_id == (frames < 2 ? 0 : 42));
+}
void sub_28002DA0(void)
{
@@ -37,6 +41,7 @@ void sub_28002DA0(void)
}
assert(ticks == 1 || ticks == 3 || ticks == 4);
++frames;
+ if (frames == 2) MEM32(0x2f01f008) = 42;
}
void sub_28001000(void)
@@ -57,6 +62,7 @@ int main(void)
{
assert(!emscripten_is_main_browser_thread());
assert(guest_map("browser loop fixture", 0x50000000, 0x10000));
+ assert(guest_map("FFR character identity", 0x2f010000, 0x10000));
g_ebx = 0x50001000;
g_esp = 0x5000fd00;
g_ebp = 0x5000fe00;
diff --git a/client/tests/browser_network.mjs b/client/tests/browser_network.mjs
@@ -24,7 +24,7 @@ function network(arguments_, protocol = 'https:') {
readyState = 0;
sent = [];
constructor(url, protocol) {
- assert.equal(protocol, 'ao-stream-v1');
+ assert.equal(protocol, url.pathname.endsWith('/browser-create') ? undefined : 'ao-stream-v1');
connections.push(url.href);
sockets.push(this);
}
@@ -87,6 +87,44 @@ test('unrecognized destination does not enter either service', () => {
assert.equal(context.ao_socket_status(socket), 8);
});
+test('native creator uses raw login packets then redirects to resumable world and chat', () => {
+ const {context, connections, sockets} = network(['localtest', 'localtest', '0', '2130706433', '7500', '0', '0']);
+ context.Module.worldPort = 7620;
+ const handle = context.ao_socket_create();
+ context.HEAPU8.set([0, 0, 0, 34]);
+
+ context.ao_socket_connect(handle, 7500);
+ sockets[0].open();
+ const sent = context.ao_socket_send(handle, 0, 4);
+ sockets[0].onmessage({data: Uint8Array.from([0, 0, 0, 36]).buffer});
+ const received = context.ao_socket_receive(handle, 4, 4, false);
+ context.ao_socket_close(handle);
+ context.ao_socket_connect(context.ao_socket_create(), 7620);
+ context.ao_socket_connect(context.ao_socket_create(), 7621);
+
+ assert.deepEqual(connections, ['wss://game.example/browser-create', 'wss://game.example/browser-world', 'wss://game.example/browser-chat']);
+ assert.equal(sent, 4);
+ assert.equal(received, 4);
+ assert.deepEqual([...context.HEAPU8.slice(4, 8)], [0, 0, 0, 36]);
+ assert.equal(sockets[0].sent.length, 1);
+ assert.deepEqual([...sockets[0].sent[0]], [0, 0, 0, 34]);
+});
+
+test('creator disconnect does not replay a character creation request', () => {
+ const {context, sockets, timeouts} = network(['localtest', 'localtest', '0', '2130706433', '7500', '0', '0']);
+ context.Module.worldPort = 7501;
+ const handle = context.ao_socket_create();
+ context.ao_socket_connect(handle, 7500);
+ sockets[0].open();
+
+ sockets[0].close(1006);
+ context.AOSockets.resume();
+
+ assert.equal(context.ao_socket_status(handle), 12);
+ assert.equal(timeouts.size, 0);
+ assert.equal(sockets.length, 1);
+});
+
function frame(offset, text) {
const bytes = new TextEncoder().encode(text);
const message = new Uint8Array(8 + bytes.length);
diff --git a/client/tests/browser_storage.c b/client/tests/browser_storage.c
@@ -7,6 +7,7 @@
#include <emscripten/html5.h>
void browser_initialize(unsigned character_id);
+void browser_select_character(unsigned character_id);
static void replace_occlusion_cache(void)
{
@@ -198,7 +199,16 @@ int main(void)
unsigned character_id = MAIN_THREAD_EM_ASM_INT({
return new URLSearchParams(location.search).has('other') ? 43 : 42;
});
- browser_initialize(character_id);
+ int resume = MAIN_THREAD_EM_ASM_INT({
+ return new URLSearchParams(location.search).has('resume');
+ });
+
+ browser_initialize(resume ? character_id : 0);
+
+ if (!resume) {
+ browser_select_character(character_id);
+ browser_select_character(character_id);
+ }
char path[128];
snprintf(path, sizeof(path), "Prefs/localtest/Char%u/Char.cfg", character_id);
@@ -207,9 +217,6 @@ int main(void)
char content[128] = {0};
assert(fread(content, 1, sizeof(content) - 1, preferences) == 29);
fclose(preferences);
- int resume = MAIN_THREAD_EM_ASM_INT({
- return new URLSearchParams(location.search).has('resume');
- });
assert(!strcmp(content, resume ? "IsFirstTime 0\nIsTipEnabled 1\n" : "IsFirstTime 1\nIsTipEnabled 0\n"));
int pending = MAIN_THREAD_EM_ASM_INT({
return new URLSearchParams(location.search).has('pending');
@@ -233,6 +240,7 @@ int main(void)
puts("PASS: asset reads preserve bytes across the 1 MiB boundary");
puts("PASS: private preferences use the canvas dimensions");
puts("PASS: native first-run state and character preference edits persist");
+ puts("PASS: creator identity transitions mount persistent character preferences");
puts("PASS: native icon positions use persistent browser storage");
puts("PASS: native references persist with character isolation and deletion");
puts("PASS: native ignore lists persist with character isolation and removal");
diff --git a/client/tests/browser_testing.c b/client/tests/browser_testing.c
@@ -98,6 +98,22 @@ static void snapshots_include_reclaim_booths_without_mutation(void)
assert(g_eax == 123 && g_esp == 456);
}
+static void snapshots_report_native_creation_state(void)
+{
+ MEM32(0x2b0ee7d0) = 0x5000d000;
+ MEM32(0x2b0ee7e0) = 0x5000d000;
+ MEM32(0x5000d040) = 4;
+ MEM32(0x5000d05c) = 32;
+ MEM32(0x5000d0a4) = 0x1008;
+
+ browser_test_request();
+ browser_test_frame();
+
+ assert(strstr(snapshot, "\"creation\":{\"scene\":4,\"hover\":32,\"nameState\":4104,\"ready\":true}"));
+ assert(MEM32(0x5000d0a4) == 0x1008 && g_eax == 123 && g_esp == 456);
+ MEM32(0x2b0ee7d0) = MEM32(0x2b0ee7e0) = 0;
+}
+
static void snapshots_preserve_wrapped_weapon_results(void)
{
MEM32(0x5000116c) = 0x50008100;
@@ -418,6 +434,7 @@ int main(void)
snapshots_observe_directory_clear_and_new_frames();
snapshots_observe_local_and_remote_actions_without_mutation();
snapshots_include_reclaim_booths_without_mutation();
+ snapshots_report_native_creation_state();
snapshots_preserve_wrapped_weapon_results();
snapshots_record_visible_grid_cells_and_scroll_without_mutation();
snapshots_record_dragged_identity_without_mutation();
diff --git a/client/tests/ctype.c b/client/tests/ctype.c
@@ -51,6 +51,65 @@ int main(void)
}
puts("isspace: all byte values and EOF, exact C-locale mask, errno and guest ABI passed");
+ const int uppercase_cases[][4] = {
+ {'a', 'A', 0, 2}, {'q', 'Q', 0, 2}, {'z', 'Z', 0, 2},
+ {'A', 'A', 1, 0}, {'Z', 'Z', 1, 0}, {'0', '0', 0, 0},
+ {'@', '@', 0, 0}, {'[', '[', 0, 0}, {'`', '`', 0, 0},
+ {'{', '{', 0, 0}, {128, 128, 0, 0}, {255, 255, 0, 0}, {-1, -1, 0, 0},
+ };
+ for (unsigned i = 0; i < sizeof(uppercase_cases) / sizeof(uppercase_cases[0]); ++i) {
+#ifdef _WIN32
+ int (__cdecl *uppercase)(int) = (void *)GetProcAddress(library, "toupper");
+ assert(uppercase);
+ *get_errno() = 777;
+#else
+ MEM32(guest_crt_errno_address()) = 777;
+ g_esp = 0x5000ff00;
+ MEM32(g_esp + 4) = uppercase_cases[i][0];
+ g_ebx = 123; g_esi = 234; g_edi = 345; g_ebp = 456;
+#endif
+
+#ifdef _WIN32
+ int result = uppercase(uppercase_cases[i][0]);
+#else
+ guest_crt_lookup("toupper")();
+ int result = g_eax;
+#endif
+
+ assert(result == uppercase_cases[i][1]);
+#ifdef _WIN32
+ assert(*get_errno() == 777);
+#else
+ assert(MEM32(guest_crt_errno_address()) == 777 && g_esp == 0x5000ff04);
+ assert(g_ebx == 123 && g_esi == 234 && g_edi == 345 && g_ebp == 456);
+#endif
+ const char *classifiers[] = {"isupper", "islower"};
+ for (unsigned classifier = 0; classifier < 2; ++classifier) {
+#ifdef _WIN32
+ int (__cdecl *classify_case)(int) = (void *)GetProcAddress(library, classifiers[classifier]);
+ assert(classify_case);
+#else
+ g_esp = 0x5000ff00;
+#endif
+
+#ifdef _WIN32
+ result = classify_case(uppercase_cases[i][0]);
+#else
+ guest_crt_lookup(classifiers[classifier])();
+ result = g_eax;
+#endif
+
+ assert(result == uppercase_cases[i][classifier + 2]);
+#ifdef _WIN32
+ assert(*get_errno() == 777);
+#else
+ assert(MEM32(guest_crt_errno_address()) == 777 && g_esp == 0x5000ff04);
+ assert(g_ebx == 123 && g_esi == 234 && g_edi == 345 && g_ebp == 456);
+#endif
+ }
+ }
+ puts("toupper/isupper/islower: C-locale letters, punctuation/high bytes/EOF and guest ABI passed");
+
#ifdef _WIN32
const unsigned short **table_pointer = (void *)GetProcAddress(library, "_pctype");
assert(table_pointer);
diff --git a/client/tests/stdio_input.c b/client/tests/stdio_input.c
@@ -113,6 +113,82 @@ static void binary_position_and_direct_buffer_consumption(void)
assert(call("fclose", 1, &file) == 0);
}
+static void pushback_before_read_and_seek(void)
+{
+ uint32_t file = open_file("input.bin", "rb");
+ uint32_t put[] = {'X', file};
+ uint32_t seek[] = {file, 0, 1};
+
+ assert(call("ungetc", 2, put) == 'X');
+ assert(call("fgetc", 1, &file) == 'X');
+ assert(call("fgetc", 1, &file) == 'a');
+ put[0] = 0x1ff;
+ uint32_t pushed = call("ungetc", 2, put);
+ uint32_t position = call("ftell", 1, &file);
+ assert(call("fgetc", 1, &file) == 255);
+ assert(call("ungetc", 2, put) == 255);
+ assert(call("fseek", 3, seek) == 0);
+
+ assert(pushed == 255 && position == 0);
+ assert(call("fgetc", 1, &file) == 'a');
+ assert(call("fclose", 1, &file) == 0);
+ check_contents("input.bin", "abcdef", 6);
+}
+
+static void pushback_clears_eof(void)
+{
+ uint32_t file = open_file("input.bin", "rb");
+ uint32_t put[] = {'Z', file};
+ while (call("fgetc", 1, &file) != UINT32_MAX) {}
+ uint32_t *fields = memory(file);
+ assert(fields[3] & 0x10);
+
+ uint32_t result = call("ungetc", 2, put);
+
+ assert(result == 'Z' && !(fields[3] & 0x10));
+ assert(call("ftell", 1, &file) == 5);
+ assert(call("fgetc", 1, &file) == 'Z');
+ assert(call("ftell", 1, &file) == 6);
+ assert(call("fgetc", 1, &file) == UINT32_MAX);
+ assert(call("fclose", 1, &file) == 0);
+}
+
+static void pushback_failure_preserves_input(void)
+{
+ uint32_t file = open_file("input.bin", "rb");
+ uint32_t put[] = {'X', file};
+ assert(call("fgetc", 1, &file) == 'a');
+ assert(call("ungetc", 2, put) == 'X');
+
+ put[0] = 'Y';
+ uint32_t full = call("ungetc", 2, put);
+ put[0] = UINT32_MAX;
+ uint32_t eof = call("ungetc", 2, put);
+
+ assert(full == UINT32_MAX && eof == UINT32_MAX);
+ assert(call("fgetc", 1, &file) == 'X');
+ assert(call("fgetc", 1, &file) == 'b');
+ assert(call("fclose", 1, &file) == 0);
+}
+
+static void text_pushback_preserves_translation(void)
+{
+ FILE *native = fopen("pushback.txt", "wb");
+ assert(native && fwrite("a\r\nb", 1, 4, native) == 4 && !fclose(native));
+ uint32_t file = open_file("pushback.txt", "rt");
+ uint32_t put[] = {'\n', file};
+ assert(call("fgetc", 1, &file) == 'a');
+ assert(call("fgetc", 1, &file) == '\n');
+
+ assert(call("ungetc", 2, put) == '\n');
+ uint32_t position = call("ftell", 1, &file);
+
+ assert(position == 1 && call("fgetc", 1, &file) == '\n');
+ assert(call("ftell", 1, &file) == 3);
+ assert(call("fgetc", 1, &file) == 'b');
+ assert(call("fclose", 1, &file) == 0 && !remove("pushback.txt"));
+}
+
static void partial_elements_and_eof_reset(void)
{
uint32_t file = open_file("input.bin", "rb");
@@ -427,6 +503,10 @@ int main(void)
FILE *file = fopen("input.bin", "wb");
assert(file && fwrite("abcdef", 1, 6, file) == 6 && !fclose(file));
binary_position_and_direct_buffer_consumption();
+ pushback_before_read_and_seek();
+ pushback_clears_eof();
+ pushback_failure_preserves_input();
+ text_pushback_preserves_translation();
partial_elements_and_eof_reset();
update_stream_changes_direction_after_seek();
text_output_position_includes_crlf();
diff --git a/docs/arrival-hall.md b/docs/arrival-hall.md
@@ -0,0 +1,96 @@
+# Arrival Hall introduction
+
+Native character creation enters playfield 4604 before selecting a faction.
+The player receives the profession starter kit there. Faction maps and gifts
+are issued only when leaving the Hall through one of its three representatives.
+Right-click a representative and choose the explicit departure option in the
+original client's conversation window. The other choice ends the conversation
+without committing a side.
+
+The provisional entry position `[190, 1.52, 200]` is clear lobby floor facing the
+three booths. The central gap between the queue barriers is walkable via XZ
+`[186, 181]`, then `[186, 172]`. For Omni, continue through `[178.5, 170]` to
+`[178.5, 167.5]`; the representative is within conversation distance there.
+This route was verified using native movement from a newly created character,
+without position fixtures or jumping. The original historical entry transform
+is still unknown.
+
+## Original evidence and reconstruction limits
+
+The original 14.9.1 population resource preserves these fixed placements:
+
+| Template | Maintained representative | Position XYZ | Group ID |
+| --- | --- | --- | --- |
+| CLRE | Clan Recruiter | 195.78024, 1.0163763, 163.26073 | `4604/district/0/fixed/0` |
+| NEOB | Neutral Observer | 186.17244, 1.0173757, 163.2037 | `4604/district/0/fixed/1` |
+| OMIM | Omni-Tek Immigration Officer | 176.11554, 1.0169828, 163.19379 | `4604/district/0/fixed/19` |
+
+The population source, including exact coordinates, facing and template codes,
+is retained in `server/gamedata/zones/zone_4604.yaml`; its payload SHA-256 is
+`de8921cb2085b1e67d048af686cd15a990ccb1d3b761e390530a93ce10c5152c`.
+The representative labels are existing abbreviation-based name inferences.
+Their generic Solitus bodies and original catalog garments are provisional.
+The original body resource 26088 is `solitus thin male`, not a Leet.
+Clan and Neutral representatives wear the existing rustic outfit; Omni wears
+its existing uniform outfit. These choices do not establish their historical
+heads or clothing.
+
+The shipped `cd_image/text/tips/OnEnteringArrivalHall.txt` welcomes the player
+and explains that some people speak when approached while others require a
+right-click. `tipheader.txt` binds it to `Arrival_hall`. The local Fandom mirror's
+[Gaute Godager about Notum Wars](https://anarchyonline.fandom.com/wiki/Gaute_Godager_about_Notum_Wars)
+article describes the Hall after character creation and before final side
+selection. A bounded search of that mirror found no representative dialogue
+transcripts. The implemented conversation is concise provisional guidance, with
+no invented historical lore or claim to reproduce the original wording.
+
+Resource `1000026/4604` contains no type-51016 door records. Its payload SHA-256
+is `6c11a9db46ce2a55c6cc446e0242adc69b715ae75cf8c420d01625eee8f37024`;
+the extraction is retained locally in `local/native-creation-arrival/`.
+Native conversation departure is an explicit reconstruction policy until the
+original commitment and exit trigger is established. Training destinations use
+`server/starting.go` and the existing authored training-door transforms and
+clearance policy described in [character creation](character-creation.md).
+
+Original items 201025 and 201026 execute the client commands
+`/afcm_addprogram PROGRAM_ARRIVAL_HALL` and
+`/afcm_removeprogram PROGRAM_ARRIVAL_HALL`. They establish a camera-program lead,
+but their original invocation timing is unresolved; this implementation does
+not force those commands. Other Hall NPC conversations and the complete tutorial
+remain open. Reopen historical research when an original transcript, capture,
+or server-side script provides evidence for these missing behaviors.
+
+## Persistence and protocol
+
+The existing native dialogue packets supply the menu and selected answer.
+NPC interest replay sends native stat 768 (`HasKnuBotData`) equal to one for
+scripted NPCs. The original humanoid activation `kkr.dll!sub_36082AD0` does not
+copy the spawn conversation flag into that stat; default action
+`kkr.dll!sub_3602C350` reads it. Without the stat replay, a right-click on a
+dressed representative sends a player-trade request instead of opening dialogue.
+Departure rechecks the active world connection, living player, neutral state,
+Hall playfield, representative identity, visibility and ten-metre proximity.
+A pending trade must finish first, and the inventory must have room for all
+issued items. These are current server policies.
+
+One item-store transaction writes the side, training position and return door,
+chosen startup map, and the existing Clan or Omni startup gifts. Only after
+commit does the server publish the new state, end the conversation, and send
+the ordinary native teleport and world-server redirect. Failed persistence
+leaves the player and
+items unchanged. Leaving playfield 4604 completes the one-time handoff; an old
+connection's repeated answer cannot issue rewards again. Reconnection resumes
+the committed destination and inventory.
+
+Focused protocol tests in `server/arrival_hall_test.go` cover all three sides,
+repeated answers, persistence after restart, cancellation, distance/playfield
+changes, unoffered choices, and rollback of a failed transaction. These are
+controlled fixture checks, not earned-progression evidence.
+
+`tests/e2e/arrival-hall.test.mjs` establishes a neutral Hall character with the
+native creation wire fixture, then positions it near the Neutral Observer.
+Real browser right-clicks and native choice clicks exercise cancellation and
+departure. The test checks the training playfield, exactly one starting map,
+the ended conversation, and unchanged inventory after a cold restart. The native
+widget retains its transcript until the player closes it. This
+isolates Hall behavior; it does not stand in for the full creator UI journey.
diff --git a/docs/browser-accounts.md b/docs/browser-accounts.md
@@ -13,14 +13,16 @@ A visitor can keep its generated name or choose a new name and password in
Options without creating a replacement character. The player ID, items, XP,
skills, resources, location,
team and native per-character preferences remain attached to that character.
-Options first offers Create character from scratch, Adopt this visitor, and
-Log in to an existing character. Adoption is hidden for already adopted characters.
-Adopted and newly created players also have Change password, with a single
-New password field. Saving keeps the current browser credential and game
+Options first offers Create character from scratch, Save this character, and
+Log in to an existing character. Save is hidden for characters with login credentials.
+Saved characters also have Change password, with a single
+New password field. Changing the password keeps the current browser credential and game
connections and does not reload the page. Visitors cannot change passwords.
Credentials appear only after choosing a flow; Back clears them. Creation
-also offers the original breed/sex/head, build, height, profession and side
-choices. A successful login loads that character; a failed submission leaves
+opens the original in-game breed, appearance, profession and naming scenes,
+followed by faction selection in Arrival Hall. Native creation initially uses
+the browser cookie; Save this character enables name/password login.
+A successful login loads that character; a failed submission leaves
the current player usable.
## Source and publication
@@ -170,15 +172,16 @@ submitted name, and recheck that ownership after hashing. They replace only
the existing password salt and hash; an empty password remains a login
credential and does not turn an adopted character back into a visitor.
-Creation builds a detached level-1 character, then atomically inserts the
-character, password, player row, starter item identities and locations,
+Native creation builds a detached level-1 character, then atomically inserts the
+character, player row, starter item identities and locations,
identity counters and abandoned browser credential. No shared character/item
cache or counter changes before COMMIT. Every insert must affect one row;
ignored inserts fail the transaction. The existing character and its password
-remain available for later login. The new character can be recovered by name
-and password if its success response is lost; the old cookie cannot replay
-creation after commit. An abandoned visitor has no password for later login;
-the creation form tells visitors to adopt it first if they want to return.
+remain available for later login. Browser ownership transfers to the new
+character using the existing cookie, so reload recovers a committed creation
+even if its success response is lost. The previous character's authorization
+cannot replay creation after commit. Save an unsaved character before creating
+another if you want to return to it through name/password login.
See [creation choices and starting state](character-creation.md)
for the historical evidence and remaining gameplay gaps.
@@ -193,8 +196,8 @@ account request completes, then reloads with the new cookie.
Native files remain in their existing per-character browser directories. Browser
presentation choices such as pixel resolution and touch-control visibility
-remain device preferences. This flow supplies browser login for one character,
-not the original multi-character account/character creator.
+remain device preferences. Browser login identifies one character; the original
+creator is connected without adding the original multi-character account system.
## Verification
diff --git a/docs/character-creation.md b/docs/character-creation.md
@@ -1,5 +1,55 @@
# Character creation
+## Native browser flow
+
+Options' "Create character from scratch" starts the original translated
+`ddr.dll` creator with character ID zero. Its breed, appearance, profession and
+naming scenes use the original models, controls and camera paths. The packaged
+`CharCreateCamera.dat` is exposed in the browser's game directory alongside
+the other root assets. The guest CRT implements `ungetc` for the native C++
+camera-file parser, including buffered pushback, EOF reset and text positions.
+The guest CRT also supplies the ASCII case conversion and classification used
+by breed selection and the original name validator.
+
+The browser routes the creator's login connection to `browser-create`, using
+the existing browser cookie for authorization. `server/native_creation.go`
+handles the native challenge/login exchange (`0x22/0x24`, `0x25/0x0e`), random
+names (`0x55/0x56`), creation (`0x0f` with success `0x11` or refusal `0x10`),
+and character selection/world redirect (`0x16/0x17`). Version-4 character data
+supplies the name, breed, sex, profession, build, height and head ordinal. The
+server resolves that ordinal within the selected breed/sex catalog, then uses
+the shared creation validation and starter-item backend.
+The decoder accepts the native variable-length area and ban-reason strings
+before the head/height/build fields; a captured creator packet is retained as
+a protocol regression.
+
+One transaction saves the new character, starter items, identity counters and
+browser ownership transfer. Only a successful commit publishes the new player
+and acknowledges creation. Repeated submission on that connection returns the
+same identity; a competing connection cannot reuse the previous credential to
+create another character. Refused names and failed commits preserve the
+previous session. Exiting before successful creation returns to the previous
+character; save an unsaved visitor first to make it accessible after creating
+another character.
+
+Successful creation places a neutral character in Arrival Hall 4604. The
+original creator's final world handoff remains in the same client instance.
+At the frame boundary after `ffr.dll`'s `s_nCharID` changes, the browser mounts
+the new character's persistent preferences directory and seeds first-run
+settings before world entry. Inventory layout and other native preferences
+therefore persist from the initial session. When browser storage is denied,
+the same directory layout uses the existing temporary storage fallback.
+Faction selection, deferred maps/gifts and the training-ground departure are
+described in [Arrival Hall](arrival-hall.md).
+
+The chosen name and progress are already durable, but native creation does
+not choose a password or enable name-and-password login. Use Options' **Save
+this character** to set login credentials; it prefills the current name.
+Until then, access uses the browser cookie. Cancellation does not delete an
+existing saved character or change its password.
+
+## Starting attributes and appearance
+
Creation reads the six ability baselines directly from the original 14.9.1
breed training data in `server/gamedata/ip_training.yaml`. Resource type
1000027, identities 1 through 4, contains the breed ID followed by six starting
@@ -25,10 +75,10 @@ tables are expansion-era corroboration, rather than an exact 14.9.1 server
capture.
Anonymous browser visitors use Solitus Soldiers with the complete original
-Solitus head catalog and matching skin race. Options also offers explicit new
-character creation: four breeds, seven breed/sex templates, all 255 original
-heads, three builds, gameplay heights 90/100/110, twelve professions and three
-sides. The server derives breed, sex and skin from the selected head, rejecting
+Solitus head catalog and matching skin race. The native creator offers four
+breeds, seven breed/sex templates, all 255 original heads, three builds,
+gameplay heights 90/100/110 and twelve professions. The Arrival Hall offers the
+three sides. The server derives breed, sex and skin from the selected head, rejecting
unknown meshes and unsupported choices. See [player appearance](character-appearance.md).
Profiles with explicitly supplied stats retain those values.
@@ -77,12 +127,13 @@ backyard-instance allocation remain unproven. Raw door bytes, hashes and
terrain measurements are retained in
`local/browser-creation-research/training-door-locations.json`.
-Browser creation currently bypasses the intermediate Arrival Hall and enters
-the chosen side's training ground directly. It moves 2.5 meters forward from
+Departure from the Arrival Hall enters the chosen side's training ground.
+It moves 2.5 meters forward from
the authored entrance door, retains its facing and uses terrain height +0.75m,
matching the existing zoning clearance policy. This is a usable reconstruction
-policy, not a recovered original-server spawn offset. Original Arrival Hall
-NPCs, final faction-choice sequence and initial camera state remain open.
+policy, not a recovered original-server spawn offset. The Hall's remaining
+historical dialogue, exit-trigger and entry-camera gaps are documented in
+[Arrival Hall](arrival-hall.md).
The shipped startup crystal tips instruct manual upload from inventory. They
identify the following original QL1 crystal items and resulting nanos:
@@ -130,8 +181,9 @@ prior use cannot be excluded. Stackability comes from the catalog's Can stat
Startup maps are 116693 Omni, 116696 Clan and 116697 Neutral. The same period
walkthrough supports a map, one Engineer robot shell (original QL1 identity
43328), Clan board 96358 or Omni board 99719, and Omni shirt 29426. Creation
-grants these, the profession's crystals above and its weapon/action in ordinary
-inventory. Nothing is pre-equipped or prelearned. Original resources and the
+grants the profession's crystals above and its weapon/action in ordinary
+inventory. Native creation defers the faction map and gifts until Hall
+departure. Nothing is pre-equipped or prelearned. Original resources and the
bounded source search are retained in
`local/browser-creation-flow-research/loadout-ledger.md`.
@@ -145,6 +197,50 @@ remain tracked in TODO.md.
## Verification
+### Complete native browser journey
+
+`tests/e2e/native-creation.test.mjs` passes with real Chromium/WASM input.
+It cancels the original creator back to an existing saved character, rejects
+a short name in the native UI and a duplicate name through the native server
+response, then creates a tall/heavy Atrox Enforcer with a selected head.
+The character walks from the Hall spawn through the queue barriers to the
+Omni representative and enters training through the native conversation.
+Server assertions establish four profession items in the Hall and exactly
+three additional faction items after departure.
+
+The same test moves an inventory icon, saves login credentials through Options,
+and reloads to verify the first-session native preference write. A cold server
+restart preserves the new character and its complete inventory. Password login
+recovers both the old and new characters without changed item identities.
+The passing run and captures are in `local/e2e/1793999672484-native-creation/`.
+The reusable native path in `tools/client/create_starter.mjs` also replaces the
+deleted Options-form setup in the starter equipment and mission-target tests;
+their extended earned-gameplay portions were not rerun for this change.
+
+### Native integration fixtures
+
+`server/native_creation_test.go` checks the public creation WebSocket protocol,
+duplicate submission, refusal and failed-commit rollback, competing connections,
+cookie authorization, cold persistence and explicit save before password login.
+`client/tests/browser_storage.c` checks creation-ID transitions followed by
+reloads and separate character preferences. `client/tests/browser_loop.c`
+checks the frame-boundary identity notification, while
+`client/tests/stdio_input.c` covers the camera parser's pushback dependency.
+These focused fixtures complement the real-input journey above; wire fixtures
+alone do not establish native UI behavior.
+
+The focused creation, Hall, launch, asset and catalog Go checks pass, as do the
+browser account/control/loading/network and guest CRT checks and the WASM build.
+The broader Go suite has eleven unrelated failures, all reproduced against
+unchanged `c5638cf3` source and assets; see `local/native-creation/go-suite.log` and
+`local/native-creation/baseline-failures.log`. They were left outside this change.
+
+### Prior HTTP creation and browser evidence
+
+The following creation matrix and browser results exercised the previous
+Options form and direct training-ground entry. They remain evidence for the
+shared validation, starter kits and persistence, not for the native creator UI.
+
`server/browser_creation_test.go` exercises public HTTP creation for all 255
heads, then checks cold loading. A separate matrix checks complete issued
inventories for every profession/side/body template combination. SQL failure
diff --git a/docs/feature-backlog.md b/docs/feature-backlog.md
@@ -1865,7 +1865,7 @@ persisted gameplay height are recorded in [player appearance](character-appearan
Browser selection and atomic creation are implemented. The complete original
introduction and starting-item gameplay remain open below.
-- [ ] [P1] Replace the Options character-creation form with the original native
+- [x] [P1] Replace the Options character-creation form with the original native
in-game character-creation flow. Options should launch that experience; its
web form is not the finished creation flow. Recover and connect the original
creation scenes, selection steps, camera/UI transitions and server protocol,
@@ -1874,6 +1874,11 @@ introduction and starting-item gameplay remain open below.
validation failures, duplicate submission and reconnect without duplicate
characters or starter items. Reuse the existing atomic creation and starting
state rules rather than implementing a second creation backend.
+ Implemented and verified through original WASM input, including walking to
+ the Hall representative, training departure, preferences and cold recovery.
+ Duplicate protocol submissions commit once. The Hall's dialogue, outfits
+ and departure policy remain provisional; see [creation verification](character-creation.md#verification)
+ and [reconstruction limits](arrival-hall.md#original-evidence-and-reconstruction-limits).
- [x] Choose a breed at creation. Check: the choice persists and the native
appearance and derived resource coefficients agree with it.
- [x] Choose a profession at creation. Check: profession-dependent starting
diff --git a/server/arrival_hall.go b/server/arrival_hall.go
@@ -0,0 +1,121 @@
+package main
+
+import (
+ "ao/server/gamedata"
+ "fmt"
+ "slices"
+ "time"
+)
+
+func arrivalHallSide(group string) (uint16, bool) {
+ // Original fixed placements identify the three representatives. See arrival-hall.md.
+ switch group {
+ case "4604/district/0/fixed/0":
+ return 1, true
+ case "4604/district/0/fixed/1":
+ return 0, true
+ case "4604/district/0/fixed/19":
+ return 2, true
+ }
+ return 0, false
+}
+
+func arrivalHallDialogue(group, choice string) gamedata.Dialogue {
+ side, _ := arrivalHallSide(group)
+ if choice == "goodbye" {
+ return gamedata.Dialogue{Text: "You can speak to the other representatives before deciding."}
+ }
+ if choice != "" {
+ return gamedata.Dialogue{}
+ }
+ // These concise instructions are provisional, not recovered original dialogue.
+ return gamedata.Dialogue{
+ Text: []string{
+ "You can remain neutral. If you are ready, I can send you to the Neutral Training ground with your starting map.",
+ "You can join the Clans. If you are ready, I can send you to the Clan Training ground with your starting map and Clan equipment.",
+ "You can join Omni-Tek. If you are ready, I can send you to the Omni Training ground with your starting map and Omni-Tek equipment.",
+ }[side],
+ Choices: []gamedata.DialogueChoice{
+ {ID: "depart", Text: []string{"Remain neutral and enter the training ground.", "Join the Clans and enter the training ground.", "Join Omni-Tek and enter the training ground."}[side]},
+ {ID: "goodbye", Text: "I want to look around first."},
+ },
+ }
+}
+
+func (server *server) leaveArrivalHall(client *worldClient, npcID uint32, side uint16) (string, error) {
+ server.updateMutex.Lock()
+ defer server.updateMutex.Unlock()
+ server.mutex.Lock()
+ player, npc := server.characters[client.id], server.characters[npcID]
+ if server.clients[client.id] != client || !client.ready || client.loading || player.health == 0 ||
+ player.playfield != 4604 || unpackAppearance(player.appearance).Side != 0 ||
+ npc == nil || !npc.npc || npc.playfield != 4604 || !client.npcs[npcID] {
+ server.mutex.Unlock()
+ return "", nil
+ }
+ selected, representative := arrivalHallSide(npc.npcDefinitionID)
+ position := predictedPosition_locked(player, time.Now())
+ x, y, z := npc.position[0]-position[0], npc.position[1]-position[1], npc.position[2]-position[2]
+ if !representative || selected != side || x*x+y*y+z*z > 10*10 {
+ server.mutex.Unlock()
+ return "", nil
+ }
+ if client.trade != nil || client.equipment != nil || client.shop != nil {
+ server.mutex.Unlock()
+ return "Finish your current trade before leaving the Arrival Hall.", nil
+ }
+
+ // Stage faction, arrival and the deferred faction items without changing live state.
+ start, err := server.startingPosition(side)
+ if err != nil {
+ server.mutex.Unlock()
+ return "", err
+ }
+ updated := *player
+ appearance := unpackAppearance(player.appearance)
+ appearance.Side = side
+ updated.appearance = appearance.packed()
+ updated.playfield, updated.position, updated.rotation, updated.returnDoor = start.Playfield, start.Position, start.Rotation, start.ReturnDoor
+ updated.inventory.Items = slices.Clone(player.inventory.Items)
+ templates := [][]uint32{{116697}, {116696, 96358}, {116693, 99719, 29426}}[side]
+ if uint64(server.nextItem)+uint64(len(templates)) > uint64(^uint32(0)) {
+ server.mutex.Unlock()
+ return "", fmt.Errorf("item identities exhausted")
+ }
+ updated.inventory.LastID = server.nextItem
+ for _, template := range templates {
+ slot := updated.inventory.freeSlot()
+ if slot == 94 {
+ server.mutex.Unlock()
+ return "Make room in your inventory for your starting map and equipment, then speak to me again.", nil
+ }
+ definition := gamedata.ItemTemplates[template]
+ updated.inventory.LastID++
+ updated.inventory.Items = append(updated.inventory.Items, ownedItem{
+ ID: updated.inventory.LastID, Type: definition.HeaderWords[0], Template: template,
+ Quality: *definition.Quality, Slot: slot, Count: 1,
+ })
+ }
+ server.prepareUser_locked(player, &updated)
+ store, err := server.itemStore_locked(player, updated.inventory)
+ if err != nil {
+ server.mutex.Unlock()
+ return "", err
+ }
+ store.edited = []*character{&updated}
+ if err := server.writeItemStore_locked(store); err != nil {
+ server.mutex.Unlock()
+ return "", err
+ }
+
+ // Departure is the one-time completion gate; reconnect resumes the committed zone.
+ updated.savedProfile, updated.savedPosition, updated.savedVitals = updated.profile(), start, updated.vitals()
+ updates := map[*worldClient][][]byte{client: {
+ npcDialoguePacket(0x270a4c62, client.id, npcID, []byte{0, 0, 0, 5, 0, 0, 0, 0}),
+ }}
+ client.dialogue = nil
+ server.replaceUser_locked(player, &updated, updates)
+ server.mutex.Unlock()
+ server.sendCombatUpdates(updates)
+ return "", server.teleportUser_locked(client, updated.userData(), 4604)
+}
diff --git a/server/arrival_hall_test.go b/server/arrival_hall_test.go
@@ -0,0 +1,231 @@
+package main
+
+import (
+ "encoding/binary"
+ "fmt"
+ "maps"
+ "net"
+ "reflect"
+ "slices"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestArrivalHallDressedRepresentativeReceivesNativeDialogueStat(t *testing.T) {
+ world, npc := arrivalHallTestWorld(t, "4604/district/0/fixed/1")
+ client, connection := net.Pipe()
+ defer client.Close()
+ client.SetDeadline(time.Now().Add(5 * time.Second))
+ go func() { defer connection.Close(); world.serveWorldConnection(connection) }()
+
+ client.Write(systemPacket(0x1b, []byte{0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0}))
+ var dialogueStat uint32
+ for _, packet := range readWorldUpdates(t, client) {
+ if binary.BigEndian.Uint32(packet[20:24]) == 0x2b333d6e &&
+ binary.BigEndian.Uint32(packet[28:32]) == npc && binary.BigEndian.Uint32(packet[36:40]) == 768 {
+ dialogueStat = binary.BigEndian.Uint32(packet[40:44])
+ }
+ }
+
+ if dialogueStat != 1 {
+ t.Fatal("dressed representative must open native dialogue instead of player trade")
+ }
+}
+
+func arrivalHallTestWorld(t *testing.T, group string) (*server, uint32) {
+ t.Helper()
+ world := newTestServer(t)
+ var representative *character
+ for _, npc := range world.characters {
+ if npc.npcDefinitionID == group {
+ representative = npc
+ break
+ }
+ }
+ if representative == nil {
+ t.Fatal("missing Arrival Hall representative", group)
+ }
+ world.characters = map[uint32]*character{representative.id: representative}
+ player := world.newCharacter()
+ player.appearance = 277
+ player.playfield, player.position = 4604, representative.position
+ player.position[2] += 3
+ if err := world.browserStartingItems_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ player.inventory.Items = slices.DeleteFunc(player.inventory.Items, func(item ownedItem) bool { return item.Template == 116697 })
+ if err := world.saveInventory_locked(player, player.inventory); err != nil {
+ t.Fatal(err)
+ }
+ return world, representative.id
+}
+
+func arrivalHallRequest(t *testing.T, connection net.Conn, npc, key, choice uint32) {
+ t.Helper()
+ body := binary.BigEndian.AppendUint16(nil, 2)
+ for _, word := range []uint32{50000, npc, choice} {
+ body = binary.BigEndian.AppendUint32(body, word)
+ }
+ if key != 0x2103247d {
+ body = binary.BigEndian.AppendUint32(body, 0)
+ }
+ if _, err := connection.Write(targetPacket(n3Packet(key, 50000, 1, body))); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func openArrivalHallConversation(t *testing.T, connection net.Conn, npc uint32) {
+ t.Helper()
+ arrivalHallRequest(t, connection, npc, 0x3b132d64, 0)
+ for _, key := range []uint32{0x3b132d64, 0x5d70532a, 0x55704d31} {
+ packet, err := readPacket(connection)
+ if err != nil || binary.BigEndian.Uint32(packet[16:20]) != key {
+ t.Fatalf("Arrival Hall conversation: %x %v", packet, err)
+ }
+ if key == 0x55704d31 && (binary.BigEndian.Uint32(packet[39:43]) != 2 || !strings.Contains(string(packet), "training ground.")) {
+ t.Fatalf("missing clear departure and cancellation choices: %x", packet)
+ }
+ }
+}
+
+func TestArrivalHallFactionDepartureCommitsOnceAndSurvivesRestart(t *testing.T) {
+ for _, scenario := range []struct {
+ group string
+ side uint16
+ playfield uint32
+ templates []uint32
+ }{
+ {"4604/district/0/fixed/1", 0, 954, []uint32{116628, 116629, 121569, 29092, 116697}},
+ {"4604/district/0/fixed/0", 1, 952, []uint32{116628, 116629, 121569, 29092, 116696, 96358}},
+ {"4604/district/0/fixed/19", 2, 950, []uint32{116628, 116629, 121569, 29092, 116693, 99719, 29426}},
+ } {
+ t.Run(fmt.Sprint(scenario.side), func(t *testing.T) {
+ world, npc := arrivalHallTestWorld(t, scenario.group)
+ client := connectZoningClient(t, world, true)
+ openArrivalHallConversation(t, client, npc)
+
+ arrivalHallRequest(t, client, npc, 0x2103247d, 0)
+ for _, key := range []uint32{0x270a4c62, 0x43197d22, 0x3c} {
+ packet, err := readPacket(client)
+ if err != nil || binary.BigEndian.Uint32(packet[16:20]) != key {
+ t.Fatalf("native departure: %x %v", packet, err)
+ }
+ }
+ arrivalHallRequest(t, client, npc, 0x2103247d, 0)
+ ping := systemPacket(1, nil)
+ binary.BigEndian.PutUint16(ping[2:4], 11)
+ client.Write(ping)
+ packet, err := readPacket(client)
+ client.Close()
+ restored := newTestInventoryServer(t)
+
+ if err != nil || binary.BigEndian.Uint16(packet[2:4]) != 11 {
+ t.Fatalf("replayed departure produced a second update: %x %v", packet, err)
+ }
+ player := restored.characters[1]
+ if player.playfield != scenario.playfield || unpackAppearance(player.appearance).Side != scenario.side || player.returnDoor == nil {
+ t.Fatalf("faction and training arrival were not committed: %+v", player.record())
+ }
+ var templates []uint32
+ for _, item := range player.inventory.Items {
+ templates = append(templates, item.Template)
+ }
+ if !slices.Equal(templates, scenario.templates) || player.profile() != world.characters[1].profile() ||
+ !reflect.DeepEqual(player.inventory.Items, world.characters[1].inventory.Items) || restored.nextItem != world.nextItem {
+ t.Fatalf("departure duplicated or lost items after restart: %v", templates)
+ }
+ })
+ }
+}
+
+func TestArrivalHallChoiceRevalidatesPositionAndCanBeCancelled(t *testing.T) {
+ for _, scenario := range []string{"cancel", "distant", "other playfield", "unoffered"} {
+ t.Run(scenario, func(t *testing.T) {
+ world, npc := arrivalHallTestWorld(t, "4604/district/0/fixed/19")
+ client := connectZoningClient(t, world, true)
+ openArrivalHallConversation(t, client, npc)
+ world.mutex.Lock()
+ if scenario == "distant" {
+ world.characters[1].position[0] += 30
+ } else if scenario == "other playfield" {
+ world.characters[1].playfield = 950
+ }
+ before := world.characters[1].record()
+ items := maps.Clone(world.items)
+ world.mutex.Unlock()
+ choice := uint32(0)
+ if scenario == "cancel" {
+ choice = 1
+ } else if scenario == "unoffered" {
+ choice = 2
+ }
+
+ arrivalHallRequest(t, client, npc, 0x2103247d, choice)
+ if scenario == "cancel" {
+ packet, err := readPacket(client)
+ if err != nil || binary.BigEndian.Uint32(packet[16:20]) != 0x5d70532a {
+ t.Fatalf("cancel response: %x %v", packet, err)
+ }
+ }
+ packet, err := readPacket(client)
+
+ if err != nil || binary.BigEndian.Uint32(packet[16:20]) != 0x270a4c62 ||
+ !reflect.DeepEqual(world.characters[1].record(), before) || !reflect.DeepEqual(world.items, items) {
+ t.Fatalf("invalid or cancelled choice changed the player: %x %v", packet, err)
+ }
+ })
+ }
+}
+
+func TestArrivalHallFailedDepartureRollsBackFactionItemsAndPosition(t *testing.T) {
+ world, npc := arrivalHallTestWorld(t, "4604/district/0/fixed/19")
+ client := connectZoningClient(t, world, true)
+ openArrivalHallConversation(t, client, npc)
+ before, items, lastItem := world.characters[1].record(), maps.Clone(world.items), world.nextItem
+ if _, err := world.db.Exec("CREATE TRIGGER reject_arrival BEFORE UPDATE OF playfield ON characters BEGIN SELECT RAISE(ABORT, 'arrival failure'); END"); err != nil {
+ t.Fatal(err)
+ }
+
+ arrivalHallRequest(t, client, npc, 0x2103247d, 0)
+ packet, err := readPacket(client)
+ restored := newTestInventoryServer(t)
+
+ if err == nil || len(packet) != 0 || !reflect.DeepEqual(world.characters[1].record(), before) || !reflect.DeepEqual(items, world.items) ||
+ !reflect.DeepEqual(restored.characters[1].record(), before) || !reflect.DeepEqual(restored.items, items) ||
+ world.nextItem != lastItem || restored.nextItem != lastItem {
+ t.Fatalf("failed departure published partial state: %x %v", packet, err)
+ }
+}
+
+func TestArrivalHallInsufficientInventoryRoomDoesNotGrantPartialRewards(t *testing.T) {
+ world, npc := arrivalHallTestWorld(t, "4604/district/0/fixed/19")
+ player := world.characters[1]
+ inventory := player.inventory
+ inventory.Items = slices.Clone(inventory.Items)
+ for len(inventory.Items) < 29 {
+ item := inventory.Items[2]
+ inventory.LastID++
+ item.ID, item.Slot = inventory.LastID, inventory.freeSlot()
+ inventory.Items = append(inventory.Items, item)
+ }
+ if err := world.saveInventory_locked(player, inventory); err != nil {
+ t.Fatal(err)
+ }
+ client := connectZoningClient(t, world, true)
+ openArrivalHallConversation(t, client, npc)
+ before, items, lastItem := player.record(), maps.Clone(world.items), world.nextItem
+
+ arrivalHallRequest(t, client, npc, 0x2103247d, 0)
+ message, err := readPacket(client)
+ if err != nil {
+ t.Fatal(err)
+ }
+ closed, err := readPacket(client)
+
+ if err != nil || binary.BigEndian.Uint32(message[16:20]) != 0x5d70532a || !strings.Contains(string(message), "Make room") ||
+ binary.BigEndian.Uint32(closed[16:20]) != 0x270a4c62 || !reflect.DeepEqual(player.record(), before) ||
+ !reflect.DeepEqual(world.items, items) || world.nextItem != lastItem || len(player.inventory.Items) != 29 {
+ t.Fatalf("insufficient room granted partial rewards: %x %x %v", message, closed, err)
+ }
+}
diff --git a/server/assets/anarchy-assets-14.9.1/CharCreateCamera.dat b/server/assets/anarchy-assets-14.9.1/CharCreateCamera.dat
@@ -0,0 +1,358 @@
+CameraCount: 51
+ID: 1
+Pos: 27.4753 2 7.52619
+Rot: 0 0.999574 0 -0.0292002
+degFOV: 60
+ID: 1 1
+Pos: 27.5425 2.08195 -8.86176
+Rot: -0.0012732 -0.998641 0.0317537 -0.041306
+degFOV: 60
+ID: 1 1 1
+Pos: 63.5691 108.727 39.8531
+Rot: 0.0503882 -0.697568 0.0573348 0.712441
+degFOV: 105
+ID: 1 1 1 1
+Pos: 51.407 108.882 40.0974
+Rot: 0.0503882 -0.697568 0.0573348 0.712441
+degFOV: 90
+ID: 1 1 2
+Pos: 50.4013 109.226 40.6279
+Rot: -0.0426748 0.703004 -0.0849643 -0.704793
+degFOV: 80
+ID: 1 1 3
+Pos: 47.846 108.086 40.2498
+Rot: 0.0962989 0.667907 -0.55508 -0.486297
+degFOV: 70
+ID: 1 1 4
+Pos: 43.5706 105.173 40.4868
+Rot: 0.138422 0.692378 -0.656006 -0.266628
+degFOV: 60
+ID: 1 1 5
+Pos: 40.0306 102.288 39.1336
+Rot: -0.0201204 0.665717 -0.699786 -0.25826
+degFOV: 60
+ID: 1 1 6
+Pos: 32.7067 67.6135 39.3056
+Rot: -0.0486235 0.674027 -0.718576 -0.16423
+degFOV: 60
+ID: 1 1 7
+Pos: 30.1328 28.6363 41.0657
+Rot: 0.507479 0.47343 -0.558819 0.453928
+degFOV: 60
+ID: 1 1 8
+Pos: 28.1175 14.8106 40.1833
+Rot: 0.0905802 0.681502 -0.724636 0.0474647
+degFOV: 60
+ID: 1 1 9
+Pos: 27.3271 5.31152 38.0728
+Rot: 0.214223 -0.906787 0.309954 0.189071
+degFOV: 60
+ID: 1 1 10
+Pos: 26.2529 2.74109 32.5925
+Rot: 0.198467 0.976946 -0.0654767 0.0432372
+degFOV: 60
+ID: 1 2
+Pos: 21.91 2.22681 -9.48438
+Rot: -0.00278715 -0.99865 0.0499017 0.0141855
+degFOV: 60
+ID: 1 3
+Pos: 21.4607 2.06054 -9.69557
+Rot: -0.00600416 -0.993596 0.0312068 0.108392
+degFOV: 60
+ID: 2
+Pos: 14.6785 2 -5.74946
+Rot: 1.21072e-008 -0.999574 4.69387e-007 0.0292002
+degFOV: 60
+ID: 2 1
+Pos: 15.0541 3.08764 -11.2439
+Rot: 0.000462378 0.971354 -0.141895 -0.190621
+degFOV: 60
+ID: 2 2
+Pos: 14.5174 2.96097 -12.6944
+Rot: 0.00726976 -0.997646 0.0423227 0.0534012
+degFOV: 38
+ID: 2 3
+Pos: 15.055 3.08753 -11.2437
+Rot: -0.000462664 -0.97136 0.141883 0.190598
+degFOV: 60
+ID: 3
+Pos: 0.702339 2 -4.9322
+Rot: 1.21072e-008 -0.999574 4.69387e-007 0.0292002
+degFOV: 60
+ID: 3 1
+Pos: 0.273983 1.56623 -10.6879
+Rot: -0.00349703 0.999087 0.0410584 0.0112452
+degFOV: 60
+ID: 3 1 1
+Pos: -1.13899 2.51081 -18.1828
+Rot: 0.0311289 -0.744813 0.0289005 0.66592
+degFOV: 60
+ID: 3 1 2
+Pos: -1.42419 2.29049 -21.8069
+Rot: 0.0130475 -0.588853 0.000692703 0.808135
+degFOV: 60
+ID: 3 1 3
+Pos: 0.228081 2.51723 -23.7048
+Rot: 0.039785 -0.700391 0.0284621 0.712081
+degFOV: 60
+ID: 3 1 4
+Pos: -1.56686 2.15822 -26.9335
+Rot: -0.014529 0.777692 0.0113668 -0.628375
+degFOV: 60
+ID: 3 1 5
+Pos: -1.17515 2.11286 -29.6826
+Rot: 0.0367033 -0.693089 0.0429034 0.718638
+degFOV: 60
+ID: 3 1 6
+Pos: -1.49695 2.17547 -32.073
+Rot: -0.0700409 0.737311 -0.0539148 -0.669746
+degFOV: 60
+ID: 3 1 7
+Pos: 3.42386 2.8819 -32.5632
+Rot: -0.161276 -0.748866 0.185773 -0.615368
+degFOV: 60
+ID: 3 1 8
+Pos: 3.21124 1.92939 -29.4664
+Rot: 0.0462366 0.805238 -0.0783693 0.585929
+degFOV: 60
+ID: 3 1 9
+Pos: 2.07262 2.03332 -27.556
+Rot: 0.0198983 -0.715868 -0.00606596 -0.697926
+degFOV: 60
+ID: 3 1 10
+Pos: 2.51275 2.1158 -25.0206
+Rot: 0.0359386 0.677048 -0.0316033 0.734381
+degFOV: 60
+ID: 3 1 11
+Pos: 3.33451 2.47441 -21.5716
+Rot: -0.0553176 -0.78796 0.0370247 -0.612118
+degFOV: 60
+ID: 3 1 12
+Pos: 3.64362 2.50176 -19.0776
+Rot: -0.0215194 -0.698865 0.00281831 -0.714925
+degFOV: 60
+ID: 3 2
+Pos: 0.712334 1.9277 -14.9705
+Rot: 0.0139005 -0.999612 0.0226628 0.0080171
+degFOV: 60
+ID: 3 2 1
+Pos: 0.712334 1.9277 -14.9705
+Rot: -0.00109469 -0.999711 0.0227806 0.00767629
+degFOV: 60
+ID: 3 2 1 1
+Pos: 0.622588 2.74417 -19.0109
+Rot: 0.0139005 -0.999612 0.0226628 0.0080171
+degFOV: 60
+ID: 3 2 1 1 1
+Pos: 0.576395 2.60757 -22.0074
+Rot: 0.0139005 -0.999612 0.0226628 0.0080171
+degFOV: 60
+ID: 3 2 2
+Pos: 0.623555 1.88155 -20.3733
+Rot: 0.00390391 -0.999703 0.0227419 0.00779009
+degFOV: 60
+ID: 3 2 3
+Pos: 0.551448 1.77653 -24.8725
+Rot: 0.00109461 0.999711 -0.0227806 -0.00767629
+degFOV: 60
+ID: 3 2 4
+Pos: 0.523215 1.46766 -27.2548
+Rot: -0.00136047 -0.99997 -0.00720996 0.00263989
+degFOV: 60
+ID: 3 3 1
+Pos: 1.59866 1.98865 -34.5536
+Rot: -0.000534494 -0.993944 -0.109873 -0.00151118
+degFOV: 60
+ID: 3 3 2
+Pos: -8.81206 1.99552 -36.0804
+Rot: -0.00550467 -0.993929 -0.109879 -0.000961879
+degFOV: 60
+ID: 4
+Pos: -29.585 1.99996 -43.2295
+Rot: 1.21072e-008 -0.999574 4.69387e-007 0.0292002
+degFOV: 60
+ID: 4 1
+Pos: -22.3636 2.17621 -36.697
+Rot: 0.00467254 0.991211 -0.0274361 -0.129327
+degFOV: 60
+ID: 4 2
+Pos: -25.1435 2.03344 -39.3694
+Rot: -0.002288 -0.996596 -0.0225967 0.079249
+degFOV: 60
+ID: 4 2 1
+Pos: -25.6267 2.15171 -41.1829
+Rot: -0.0015143 0.999463 0.0220105 -0.0242384
+degFOV: 60
+ID: 4 3
+Pos: -26.4521 2.21812 -56.6956
+Rot: -0.000228621 0.997574 -0.00238313 -0.0695734
+degFOV: 60
+ID: 4 3 1
+Pos: -26.6086 2.40339 -56.091
+Rot: 0.00342376 0.998419 -0.0127345 -0.0546477
+degFOV: 60
+ID: 5
+Pos: -1489.24 4.13123 52.1176
+Rot: -0.0260137 0.930527 0.089532 0.354156
+degFOV: 95
+ID: 5 1
+Pos: -1495.83 -139.602 101.02
+Rot: -0.0431698 -0.89199 -0.442899 -0.0795669
+degFOV: 60
+ID: 5 2
+Pos: -1536.83 -125.913 88.4726
+Rot: -0.0431708 -0.89199 -0.442899 -0.079568
+degFOV: 60
+TransitionCount: 23
+TransitionId: 1
+Duration: 1.8 sec
+KeyframeCount: 2
+C: 1
+C: 1 1
+TransitionId: 1 1
+Duration: 2 sec
+KeyframeCount: 3
+C: 1 1
+C: 1 2
+C: 2 1
+TransitionId: 1 1 1
+Duration: 25 sec
+KeyframeCount: 13
+C: 1 1 1
+C: 1 1 1 1
+C: 1 1 2
+C: 1 1 3
+C: 1 1 4
+C: 1 1 5
+C: 1 1 6
+C: 1 1 7
+C: 1 1 8
+C: 1 1 9
+C: 1 1 10
+C: 1
+C: 1 1
+TransitionId: 1 1 2
+Duration: 22 sec
+KeyframeCount: 11
+C: 1 1 1
+C: 1 1 1 1
+C: 1 1 3
+C: 1 1 4
+C: 1 1 5
+C: 1 1 7
+C: 1 1 8
+C: 1 1 9
+C: 1 1 10
+C: 1
+C: 1 1
+TransitionId: 1 2
+Duration: 2 sec
+KeyframeCount: 3
+C: 2 1
+C: 1 2
+C: 1 1
+TransitionId: 2
+Duration: 4 sec
+KeyframeCount: 2
+C: 1
+C: 1
+TransitionId: 2 1
+Duration: 1.9 sec
+KeyframeCount: 2
+C: 2 3
+C: 3 1
+TransitionId: 2 1 1
+Duration: 1 sec
+KeyframeCount: 2
+C: 2 1
+C: 2 2
+TransitionId: 2 1 2
+Duration: 1 sec
+KeyframeCount: 2
+C: 2 2
+C: 2 1
+TransitionId: 2 1 3
+Duration: 1.9 sec
+KeyframeCount: 2
+C: 2 3
+C: 1 1
+TransitionId: 2 2
+Duration: 1.9 sec
+KeyframeCount: 3
+C: 3 1 4
+C: 3 1
+C: 2 1
+TransitionId: 3
+Duration: 4 sec
+KeyframeCount: 2
+C: 1
+C: 1
+TransitionId: 3 1
+Duration: 1 sec
+KeyframeCount: 2
+C: 3 1
+C: 3 1 1
+TransitionId: 3 1 1
+Duration: 0.3 sec
+KeyframeCount: 3
+C: 3 1
+C: 3 2 4
+C: 3 1 6
+TransitionId: 3 2
+Duration: 0.4 sec
+KeyframeCount: 2
+C: 3 1 1
+C: 3 2
+TransitionId: 3 3
+Duration: 4 sec
+KeyframeCount: 3
+C: 3 1
+C: 3 3 1
+C: 4 1
+TransitionId: 4
+Duration: 4 sec
+KeyframeCount: 2
+C: 1
+C: 1
+TransitionId: 4 1
+Duration: 3.4 sec
+KeyframeCount: 5
+C: 3 1 6
+C: 3 1
+C: 3 3 1
+C: 3 3 2
+C: 4 1
+TransitionId: 4 2
+Duration: 3.7 sec
+KeyframeCount: 4
+C: 4 1
+C: 3 3 2
+C: 3 3 1
+C: 3 1 4
+TransitionId: 4 3
+Duration: 10.8 sec
+KeyframeCount: 4
+C: 4 1
+C: 4 2
+C: 4 2 1
+C: 4 3
+TransitionId: 5
+Duration: 4 sec
+KeyframeCount: 2
+C: 1
+C: 1
+TransitionId: 5 1
+Duration: 23 sec
+KeyframeCount: 2
+C: 5 1
+C: 5 2
+TransitionId: 5 2
+Duration: 4 sec
+KeyframeCount: 7
+C: 1
+C: 1 1
+C: 2
+C: 3 1
+C: 3 3 1
+C: 3 3 2
+C: 4 1
diff --git a/server/assets/versions.go b/server/assets/versions.go
@@ -3,6 +3,7 @@
package assets
var Versions = map[string]string{
+ "anarchy-assets-14.9.1/CharCreateCamera.dat": "\"32cc5672b5166419991209ec380444d4379255f98f48db2598814be66e462c70\"",
"anarchy-assets-14.9.1/Prefs/Main.cfg": "\"8cb3bff0f54c222207d016936dec0a6373b098b4b20f891633f3c4034c222f50\"",
"anarchy-assets-14.9.1/Prefs/localtest/Login.cfg": "\"73bed2c2b0b789ab4209f6da2edfa9eb0f5eca3c546923a13ad29b5d1304877a\"",
"anarchy-assets-14.9.1/Setupf/animcalibration.txt": "\"fdf8cfef03bc392bf5f5dc63a5578a1d75f6aea579e0914faabbd402848d7863\"",
diff --git a/server/browser_account.go b/server/browser_account.go
@@ -1,7 +1,6 @@
package main
import (
- "ao/server/gamedata"
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
@@ -43,7 +42,7 @@ func (server *server) browserAccountInfo(w http.ResponseWriter, r *http.Request)
name, visitor := player.name, !claimed
server.mutex.Unlock()
w.Header().Set("Content-Type", "application/json")
- json.NewEncoder(w).Encode(map[string]any{"name": name, "visitor": visitor, "adopted": claimed, "heads": gamedata.PlayerAppearances.Heads})
+ json.NewEncoder(w).Encode(map[string]any{"name": name, "visitor": visitor, "adopted": claimed})
}
func (server *server) browserPassword(password string, salt []byte) []byte {
diff --git a/server/browser_assets.go b/server/browser_assets.go
@@ -20,7 +20,7 @@ func browserManifest(w http.ResponseWriter, r *http.Request) {
Version string `json:"version"`
}
metadata := make(map[string]assetMetadata)
- for _, entryPath := range []string{"cd_image", "Setupf", "fonts", "Prefs", "version.id"} {
+ for _, entryPath := range []string{"cd_image", "Setupf", "fonts", "Prefs", "version.id", "CharCreateCamera.dat"} {
err := fs.WalkDir(resources, path.Join("anarchy-assets-14.9.1", entryPath), func(path string, entry fs.DirEntry, err error) error {
if err != nil {
return err
diff --git a/server/browser_assets_test.go b/server/browser_assets_test.go
@@ -149,11 +149,14 @@ func TestBrowserManifestListsLazyAssetTree(t *testing.T) {
if err := os.WriteFile("anarchy-assets-14.9.1/version.id", []byte("14.9.1"), 0644); err != nil {
t.Fatal(err)
}
+ if err := os.WriteFile("anarchy-assets-14.9.1/CharCreateCamera.dat", []byte("CameraCount: 51"), 0644); err != nil {
+ t.Fatal(err)
+ }
response := httptest.NewRecorder()
browserManifest(response, httptest.NewRequest("GET", "/browser-manifest", nil))
- if response.Code != 200 || response.Body.String() != "cd_image/\ncd_image/asset.dat\nSetupf/\nfonts/\nPrefs/\nversion.id\n" {
+ if response.Code != 200 || response.Body.String() != "cd_image/\ncd_image/asset.dat\nSetupf/\nfonts/\nPrefs/\nversion.id\nCharCreateCamera.dat\n" {
t.Fatalf("manifest: %d %q", response.Code, response.Body.String())
}
}
@@ -169,6 +172,9 @@ func TestBrowserManifestVersionsMatchAssetResponses(t *testing.T) {
if err := os.WriteFile("anarchy-assets-14.9.1/version.id", []byte("14.9.1"), 0644); err != nil {
t.Fatal(err)
}
+ if err := os.WriteFile("anarchy-assets-14.9.1/CharCreateCamera.dat", []byte("CameraCount: 51"), 0644); err != nil {
+ t.Fatal(err)
+ }
if err := os.Symlink("version.id", "anarchy-assets-14.9.1/Prefs/link"); err != nil {
t.Fatal(err)
}
@@ -189,7 +195,7 @@ func TestBrowserManifestVersionsMatchAssetResponses(t *testing.T) {
if err := json.Unmarshal(manifest.Body.Bytes(), &metadata); err != nil {
t.Fatal(err)
}
- if len(metadata) != 5 || metadata["version.id"].Size != 6 ||
+ if len(metadata) != 6 || metadata["version.id"].Size != 6 ||
metadata["version.id"].Version != asset.Header().Get("ETag") || metadata["version.id"].Version == "" {
t.Fatalf("manifest metadata: %s", manifest.Body.String())
}
diff --git a/server/browser_creation.go b/server/browser_creation.go
@@ -45,9 +45,20 @@ func (server *server) browserCreation(r *http.Request) (*character, error) {
if err != nil {
return nil, fmt.Errorf("choose an original player head")
}
+ profession, professionErr := strconv.ParseUint(r.PostForm.Get("profession"), 10, 16)
+ side, sideErr := strconv.ParseUint(r.PostForm.Get("side"), 10, 16)
+ build, buildErr := strconv.ParseUint(r.PostForm.Get("build"), 10, 16)
+ height, heightErr := strconv.ParseUint(r.PostForm.Get("height"), 10, 16)
+ if professionErr != nil || sideErr != nil || buildErr != nil || heightErr != nil {
+ return nil, fmt.Errorf("choose a profession, side, build and height")
+ }
+ return server.creationCharacter(uint32(mesh), uint16(profession), uint16(side), uint16(build), uint16(height))
+}
+
+func (server *server) creationCharacter(mesh uint32, profession, side, build, height uint16) (*character, error) {
var selected gamedata.PlayerHead
for _, head := range gamedata.PlayerAppearances.Heads {
- if head.Mesh == uint32(mesh) {
+ if head.Mesh == mesh {
selected = head
break
}
@@ -55,17 +66,12 @@ func (server *server) browserCreation(r *http.Request) (*character, error) {
if selected.Mesh == 0 {
return nil, fmt.Errorf("choose an original player head")
}
- profession, professionErr := strconv.ParseUint(r.PostForm.Get("profession"), 10, 16)
- side, sideErr := strconv.ParseUint(r.PostForm.Get("side"), 10, 16)
- build, buildErr := strconv.ParseUint(r.PostForm.Get("build"), 10, 16)
- height, heightErr := strconv.ParseUint(r.PostForm.Get("height"), 10, 16)
- if professionErr != nil || profession < 1 || profession > 12 || sideErr != nil || side > 2 ||
- buildErr != nil || build > 2 || heightErr != nil || height != 90 && height != 100 && height != 110 {
+ if profession < 1 || profession > 12 || side > 2 || build > 2 || height != 90 && height != 100 && height != 110 {
return nil, fmt.Errorf("choose a profession, side, build and height")
}
- appearance := appearanceFields{Race: selected.Race, Breed: selected.Breed, Sex: selected.Sex, Fatness: uint16(build), Side: uint16(side)}
- data := userData{Appearance: appearance.packed(), HeadMesh: selected.Mesh, Height: uint16(height),
- Profession: uint16(profession), Level: 1, Running: true}
+ appearance := appearanceFields{Race: selected.Race, Breed: selected.Breed, Sex: selected.Sex, Fatness: build, Side: side}
+ data := userData{Appearance: appearance.packed(), HeadMesh: selected.Mesh, Height: height,
+ Profession: profession, Level: 1, Running: true}
start, err := server.startingPosition(appearance.Side)
if err != nil {
diff --git a/server/browser_creation_test.go b/server/browser_creation_test.go
@@ -132,7 +132,7 @@ func TestBrowserCreationStarterInventoryForEveryProfessionSideAndBody(t *testing
}
}
-func TestBrowserCreationCatalogRequiresCookieAndExcludesCredentials(t *testing.T) {
+func TestBrowserAccountInfoRequiresCookieAndExcludesCredentials(t *testing.T) {
world := newTestServer(t)
cookie := accountVisitor(t, world)
request := httptest.NewRequest("GET", "https://example.test/browser-account", nil)
@@ -143,18 +143,17 @@ func TestBrowserCreationCatalogRequiresCookieAndExcludesCredentials(t *testing.T
world.httpHandler().ServeHTTP(response, request)
world.httpHandler().ServeHTTP(unauthorized, httptest.NewRequest("GET", "https://example.test/browser-account", nil))
var result struct {
- Name string `json:"name"`
- Visitor bool `json:"visitor"`
- Adopted bool `json:"adopted"`
- Heads []gamedata.PlayerHead `json:"heads"`
+ Name string `json:"name"`
+ Visitor bool `json:"visitor"`
+ Adopted bool `json:"adopted"`
}
decoder := json.NewDecoder(response.Body)
decoder.DisallowUnknownFields()
err := decoder.Decode(&result)
if err != nil || response.Code != 200 || response.Header().Get("Cache-Control") != "no-store" || result.Name != world.characters[1].name || !result.Visitor || result.Adopted ||
- !reflect.DeepEqual(result.Heads, gamedata.PlayerAppearances.Heads) || unauthorized.Code != 401 {
- t.Fatalf("creation catalog: %d %v", response.Code, err)
+ unauthorized.Code != 401 {
+ t.Fatalf("account info: %d %v", response.Code, err)
}
}
diff --git a/server/browser_launch.go b/server/browser_launch.go
@@ -59,5 +59,11 @@ func (server *server) browserLaunch(w http.ResponseWriter, r *http.Request) {
}
w.Header().Set("Content-Type", "text/plain")
w.Header().Set("Cache-Control", "no-store")
+ if r.URL.Query().Get("create") == "1" {
+ // Character zero selects the original creator and its login connection.
+ w.Header().Set("X-AO-World-Port", fmt.Sprint(server.worldPort))
+ fmt.Fprintf(w, "Clientr.exe localtest localtest 0 2130706433 %d 0 0", server.loginPort)
+ return
+ }
fmt.Fprintf(w, "Clientr.exe localtest localtest %d 2130706433 %d 0 0", character.id, server.worldPort)
}
diff --git a/server/browser_launch_test.go b/server/browser_launch_test.go
@@ -12,6 +12,26 @@ import (
"testing"
)
+func TestBrowserLaunchNativeCreatorPreservesCurrentCharacter(t *testing.T) {
+ world := newTestServer(t)
+ world.loginPort, world.worldPort = 7600, 7700
+ cookie := accountVisitor(t, world)
+ before := world.characters[1].record()
+ count := len(world.characters)
+ request := httptest.NewRequest("POST", "/browser-launch?create=1", nil)
+ request.AddCookie(cookie)
+ response := httptest.NewRecorder()
+
+ world.browserLaunch(response, request)
+
+ if response.Body.String() != "Clientr.exe localtest localtest 0 2130706433 7600 0 0" || response.Header().Get("X-AO-World-Port") != "7700" {
+ t.Fatal("native creator did not receive its login and world ports", response.Body.String(), response.Header())
+ }
+ if len(world.characters) != count || world.browserCharacter_locked(request).record() != before || len(response.Result().Cookies()) != 0 {
+ t.Fatal("entering the creator changed the current character or credential")
+ }
+}
+
func TestBrowserLaunchCreatesPersistentVisitor(t *testing.T) {
t.Chdir(t.TempDir())
if err := os.Mkdir("data", 0755); err != nil {
diff --git a/server/dialogue.go b/server/dialogue.go
@@ -53,6 +53,9 @@ func (server *server) handleNPCDialogue(client *worldClient, body []byte) error
if x*x+y*y+z*z <= 10*10 {
groupID = npc.npcDefinitionID
script = gamedata.NPCScripts[groupID]
+ if _, representative := arrivalHallSide(groupID); representative {
+ script.Talk = func(choice string) gamedata.Dialogue { return arrivalHallDialogue(groupID, choice) }
+ }
}
}
server.mutex.Unlock()
@@ -84,6 +87,13 @@ func (server *server) handleNPCDialogue(client *worldClient, body []byte) error
// Execute Go gamedata without holding the world lock or sharing player sessions.
reply := script.Talk(choice)
+ if side, representative := arrivalHallSide(groupID); representative && choice == "depart" {
+ message, err := server.leaveArrivalHall(client, npcID, side)
+ if err != nil || message == "" {
+ return err
+ }
+ reply = gamedata.Dialogue{Text: message}
+ }
var packets [][]byte
if key == 0x3b132d64 {
if client.dialogue != nil && client.dialogue.npc != npcID {
diff --git a/server/dialogue_test.go b/server/dialogue_test.go
@@ -104,6 +104,7 @@ func TestScriptedNPCAdvertisesNativeDialogue(t *testing.T) {
flagged bool
}{
{"scripted NPC", character{npc: true, npcDefinitionID: "710/district/0/fixed/23"}, true},
+ {"Arrival Hall representative", character{npc: true, npcDefinitionID: "4604/district/0/fixed/1"}, true},
{"ordinary NPC", character{npc: true}, false},
{"player", character{npcDefinitionID: "710/district/0/fixed/23"}, false},
} {
diff --git a/server/gamedata/npc_outfits.go b/server/gamedata/npc_outfits.go
@@ -20,6 +20,11 @@ var npcRusticOutfit = []NPCOutfitItem{
}
var NPCOutfits = map[string][]NPCOutfitItem{
+ // Original garments assigned provisionally to the Arrival Hall representatives.
+ "4604/district/0/fixed/0": npcRusticOutfit,
+ "4604/district/0/fixed/1": npcRusticOutfit,
+ "4604/district/0/fixed/19": npcUniformOutfit,
+
"710/district/0/fixed/8": npcEliteOutfit,
"710/district/0/fixed/9": npcEliteOutfit,
"710/district/0/fixed/10": npcEliteOutfit,
diff --git a/server/gamedata/zones/zone_4604.yaml b/server/gamedata/zones/zone_4604.yaml
@@ -6,14 +6,13 @@ districts:
- template_code: CLRE
name: Clan Recruiter
monster_data: 26088
- appearance: 277
+ appearance: 789
levels: [100, 200]
appearance_status: best_effort
placement_status: fixed_point
- comment: 'Original template unresolved; Leet used as a visible stand-in. Best-effort confidence: low.
- Select the role or encounter supported by the abbreviation and its authored site/level. This is a best-effort
- reconstruction; exact historical identity, head and equipment are not asserted. Source: Best-effort
- reconstruction: README.md; reports/best-effort-assignments.json Source: tools/data/npc_assignments.json'
+ comment: 'Authored 14.9.1 placement and template code. Representative name, generic Solitus body,
+ faction and catalog-backed clothing are provisional reconstruction choices. Original appearance
+ and dialogue are unresolved. See docs/arrival-hall.md.'
positions:
- [195.78024, 1.0163763, 163.26073]
id: 4604/district/0/fixed/0
@@ -25,10 +24,9 @@ districts:
levels: [100, 200]
appearance_status: best_effort
placement_status: fixed_point
- comment: 'Original template unresolved; Leet used as a visible stand-in. Best-effort confidence: low.
- Select the role or encounter supported by the abbreviation and its authored site/level. This is a best-effort
- reconstruction; exact historical identity, head and equipment are not asserted. Source: Best-effort
- reconstruction: README.md; reports/best-effort-assignments.json Source: tools/data/npc_assignments.json'
+ comment: 'Authored 14.9.1 placement and template code. Representative name, generic Solitus body,
+ faction and catalog-backed clothing are provisional reconstruction choices. Original appearance
+ and dialogue are unresolved. See docs/arrival-hall.md.'
positions:
- [186.17244, 1.0173757, 163.2037]
id: 4604/district/0/fixed/1
@@ -291,14 +289,13 @@ districts:
- template_code: OMIM
name: Omni-Tek Immigration Officer
monster_data: 26088
- appearance: 277
+ appearance: 1301
levels: [100, 200]
appearance_status: best_effort
placement_status: fixed_point
- comment: 'Original template unresolved; Leet used as a visible stand-in. Best-effort confidence: low.
- Select the role or encounter supported by the abbreviation and its authored site/level. This is a best-effort
- reconstruction; exact historical identity, head and equipment are not asserted. Source: Best-effort
- reconstruction: README.md; reports/best-effort-assignments.json Source: tools/data/npc_assignments.json'
+ comment: 'Authored 14.9.1 placement and template code. Representative name, generic Solitus body,
+ faction and catalog-backed clothing are provisional reconstruction choices. Original appearance
+ and dialogue are unresolved. See docs/arrival-hall.md.'
positions:
- [176.11554, 1.0169828, 163.19379]
id: 4604/district/0/fixed/19
diff --git a/server/http.go b/server/http.go
@@ -25,6 +25,7 @@ func (server *server) httpHandler() http.Handler {
mux.Handle("POST /browser-account/{action}", http.NewCrossOriginProtection().Handler(http.HandlerFunc(server.browserAccount)))
mux.HandleFunc("GET /browser-world", server.browserWorld)
mux.HandleFunc("GET /browser-chat", server.browserChat)
+ mux.HandleFunc("GET /browser-create", server.browserCreate)
mux.HandleFunc("GET /browser-manifest", browserManifest)
mux.HandleFunc("GET /browser-resource-index", browserResourceIndex)
mux.HandleFunc("GET /wasm/", server.browserClient)
diff --git a/server/interest.go b/server/interest.go
@@ -1,6 +1,10 @@
package main
-import "time"
+import (
+ "ao/server/gamedata"
+ "encoding/binary"
+ "time"
+)
func (server *server) npcActive_locked(npc *character, now time.Time) bool {
// Keep nearby NPCs active for fifteen minutes after the last player leaves.
@@ -62,6 +66,14 @@ func (server *server) updateNPCInterest_locked(client *worldClient, now time.Tim
} else {
updates = append(updates, characterPacket(other))
updates = append(updates, equippedItemPackets(other)...)
+ // kkr.dll sub_36082AD0 does not copy HasKnuBotData for dressed humans.
+ // Default action sub_3602C350 reads stat 768 to open native dialogue.
+ _, arrivalRepresentative := arrivalHallSide(other.npcDefinitionID)
+ if gamedata.NPCScripts[other.npcDefinitionID].Talk != nil || arrivalRepresentative {
+ body := binary.BigEndian.AppendUint32(nil, 768)
+ body = binary.BigEndian.AppendUint32(body, 1)
+ updates = append(updates, n3Packet(0x2b333d6e, 50000, other.id, body))
+ }
if other.pet != nil {
owner := server.characters[other.pet.owner]
updates = append(updates, petIdentityPacket(0x194e4f76, owner.id, other.id), petCounterPacket(owner))
diff --git a/server/native_creation.go b/server/native_creation.go
@@ -0,0 +1,215 @@
+package main
+
+import (
+ "ao/server/gamedata"
+ "context"
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/binary"
+ "fmt"
+ "io"
+ "log"
+ "net"
+ "net/http"
+ "slices"
+ "strings"
+
+ "github.com/coder/websocket"
+)
+
+func (server *server) browserCreate(w http.ResponseWriter, r *http.Request) {
+ server.mutex.Lock()
+ current := server.browserCharacter_locked(r)
+ var id uint32
+ var credential string
+ if current != nil {
+ id, credential = current.id, current.browserTokenHash
+ }
+ server.mutex.Unlock()
+ if id == 0 {
+ http.Error(w, "Open the game page to start a visitor session.", http.StatusUnauthorized)
+ return
+ }
+ socket, err := websocket.Accept(w, r, nil)
+ if err != nil {
+ return
+ }
+ defer socket.CloseNow()
+ connection := websocket.NetConn(context.Background(), socket, websocket.MessageBinary)
+ if err := server.serveNativeCreation(connection, id, credential); err != nil {
+ log.Printf("Browser creation connection: %v", err)
+ }
+}
+
+func (server *server) serveNativeCreation(conn net.Conn, currentID uint32, credential string) error {
+ var createdID uint32
+ for {
+ packet, err := readPacket(conn)
+ if err == io.EOF {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ opcode := binary.BigEndian.Uint32(packet[16:20])
+ traceLog.Printf("Creation C2S opcode=0x%02x length=%d", opcode, len(packet))
+ var response []byte
+ switch opcode {
+ case 0x22:
+ response = systemPacket(0x24, []byte("0123456789abcdef0123456789abcdef\x00"))
+ case 0x25:
+ // The browser cookie authenticates this connection, independently of launcher credentials.
+ response = systemPacket(0x0e, binary.BigEndian.AppendUint32(nil, 0))
+ case 0x55:
+ name := randomVisitorName()
+ response = systemPacket(0x56, append(binary.BigEndian.AppendUint16(nil, uint16(len(name))), name...))
+ case 0x0f:
+ var reason uint32
+ if createdID == 0 {
+ createdID, reason, err = server.createNativeCharacter(currentID, credential, packet[20:])
+ if err != nil {
+ log.Printf("Creating browser character: %v", err)
+ reason = 9
+ }
+ }
+ if reason != 0 {
+ response = systemPacket(0x10, binary.BigEndian.AppendUint32(nil, reason))
+ } else {
+ response = systemPacket(0x11, binary.BigEndian.AppendUint32(nil, createdID))
+ }
+ case 0x16:
+ if len(packet) != 24 || createdID == 0 || binary.BigEndian.Uint32(packet[20:]) != createdID {
+ return fmt.Errorf("invalid created character selection")
+ }
+ body := binary.BigEndian.AppendUint32(nil, createdID)
+ body = append(body, 127, 0, 0, 1)
+ body = binary.BigEndian.AppendUint16(body, uint16(server.worldPort))
+ body = append(body, make([]byte, 8)...)
+ response = systemPacket(0x17, body)
+ default:
+ return fmt.Errorf("unimplemented creation opcode 0x%02x", opcode)
+ }
+ if _, err := conn.Write(response); err != nil {
+ return err
+ }
+ }
+}
+
+func (server *server) createNativeCharacter(currentID uint32, credential string, body []byte) (uint32, uint32, error) {
+ // nr.dll!CharacterData_t::WriteDataStream and CharacterInfo_c::WriteStream use version 4.
+ if len(body) < 89 || binary.BigEndian.Uint32(body) != 4 || body[8] != 'a' || binary.BigEndian.Uint32(body[37:]) != 4 {
+ return 0, 9, nil
+ }
+ length := int(binary.BigEndian.Uint32(body[45:]))
+ if length < 4 || length > 12 || len(body) < 89+length {
+ return 0, 9, nil
+ }
+ name, valid := browserPlayerName(string(body[49 : 49+length]))
+ if !valid {
+ return 0, 9, nil
+ }
+ fields := body[49+length:]
+ breed, sex := binary.BigEndian.Uint32(fields), binary.BigEndian.Uint32(fields[4:])
+ profession := binary.BigEndian.Uint32(fields[8:])
+ // CharacterInfo writes variable-length area and ban-reason strings before appearance.
+ areaLength := int(binary.BigEndian.Uint32(fields[16:]))
+ if areaLength > len(fields)-40 {
+ return 0, 9, nil
+ }
+ fields = fields[20+areaLength:]
+ reasonLength := int(binary.BigEndian.Uint32(fields[4:]))
+ if reasonLength != len(fields)-20 {
+ return 0, 9, nil
+ }
+ fields = fields[8+reasonLength:]
+ headIndex, height, build := binary.BigEndian.Uint32(fields), binary.BigEndian.Uint32(fields[4:]), binary.BigEndian.Uint32(fields[8:])
+ if profession < 1 || profession > 12 || build > 2 || height != 90 && height != 100 && height != 110 {
+ return 0, 9, nil
+ }
+
+ // Native head ordinals are scoped to the selected breed/sex catalog, including Atrox sex 1.
+ var mesh uint32
+ for _, head := range gamedata.PlayerAppearances.Heads {
+ if uint32(head.Breed) == breed && uint32(head.Sex) == sex {
+ if headIndex == 0 {
+ mesh = head.Mesh
+ break
+ }
+ headIndex--
+ }
+ }
+ if mesh == 0 {
+ return 0, 9, nil
+ }
+ player, err := server.creationCharacter(mesh, uint16(profession), 0, uint16(build), uint16(height))
+ if err != nil {
+ return 0, 0, err
+ }
+ player.name = name
+ player.playfield, player.position = 4604, [3]float32{190, 1.52, 200}
+ player.rotation, player.returnDoor = [4]float32{0, 1, 0, 0}, nil
+
+ // Publish the player and transfer browser ownership only after the complete transaction commits.
+ server.updateMutex.Lock()
+ defer server.updateMutex.Unlock()
+ server.mutex.Lock()
+ defer server.mutex.Unlock()
+ current := server.characters[currentID]
+ if current == nil || current.browserTokenHash != credential {
+ return 0, 2, nil
+ }
+ for _, other := range server.characters {
+ if !other.npc && strings.EqualFold(other.name, name) {
+ return 0, 0x1e, nil
+ }
+ }
+ if server.nextCharacter >= 999999 {
+ return 0, 8, nil
+ }
+ player.id, player.browserTokenHash = server.nextCharacter+1, credential
+ if err := server.browserStartingItems_locked(player); err != nil {
+ return 0, 0, err
+ }
+ // The Arrival Hall grants the chosen side's map and gifts when the player departs.
+ player.inventory.Items = slices.DeleteFunc(player.inventory.Items, func(item ownedItem) bool { return item.Template == 116697 })
+ for index := range player.inventory.Items {
+ player.inventory.Items[index].Slot = 64 + uint32(index)
+ }
+ db, err := server.database()
+ if err != nil {
+ return 0, 0, err
+ }
+ tx, err := db.Begin()
+ if err != nil {
+ return 0, 0, err
+ }
+ defer tx.Rollback()
+ abandoned := fmt.Sprintf("%x", sha256.Sum256([]byte(rand.Text())))
+ if err := server.insertBrowserPlayer_locked(tx, player, []byte{}, []byte{}); err != nil {
+ return 0, 0, err
+ }
+ if err := updateRecord(tx, "characters", currentID, "browser_token_hash", []any{abandoned}); err != nil {
+ return 0, 0, err
+ }
+ if err := tx.Commit(); err != nil {
+ return 0, 0, err
+ }
+ server.publishBrowserPlayer_locked(player)
+ current.browserTokenHash, current.savedProfile.BrowserTokenHash = abandoned, abandoned
+ if client := server.clients[currentID]; client != nil {
+ server.cancelPlayerTrade_locked(client)
+ client.ready = false
+ if client.stream == nil {
+ client.disconnect(client.conn)
+ }
+ }
+ for _, stream := range server.browserStreams {
+ if stream.character == currentID {
+ stream.mutex.Lock()
+ stream.replaced = true
+ stream.mutex.Unlock()
+ go stream.close()
+ }
+ }
+ return player.id, 0, nil
+}
diff --git a/server/native_creation_test.go b/server/native_creation_test.go
@@ -0,0 +1,270 @@
+package main
+
+import (
+ "context"
+ "encoding/binary"
+ "encoding/hex"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "reflect"
+ "testing"
+ "time"
+
+ "github.com/coder/websocket"
+)
+
+func nativeCreationConnection(t *testing.T, world *server, cookie *http.Cookie) net.Conn {
+ t.Helper()
+ host := httptest.NewServer(world.httpHandler())
+ t.Cleanup(host.Close)
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ t.Cleanup(cancel)
+ socket, _, err := websocket.Dial(ctx, host.URL+world.baseURL+"browser-create", &websocket.DialOptions{
+ HTTPHeader: http.Header{"Cookie": {cookie.String()}},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { socket.CloseNow() })
+ return websocket.NetConn(ctx, socket, websocket.MessageBinary)
+}
+
+func nativeCreationExchange(t *testing.T, connection net.Conn, packet []byte) []byte {
+ t.Helper()
+ if _, err := connection.Write(packet); err != nil {
+ t.Fatal(err)
+ }
+ response, err := readPacket(connection)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return response[16:]
+}
+
+func nativeCreationAlice(t *testing.T) []byte {
+ t.Helper()
+ // Original serializers: CharacterData v4, proxy, CharacterInfo v4, name, appearance.
+ body, err := hex.DecodeString("000000040000000061" +
+ "0000c79c00000000000000000000000000009c5000000000" +
+ "00000000000000040000000000000005416c696365" +
+ "000000040000000100000009000000000000000000000000000000000000001d0000006e00000002")
+ if err != nil {
+ t.Fatal(err)
+ }
+ return systemPacket(0x0f, body)
+}
+
+func TestNativeCreationCapturedClientRequest(t *testing.T) {
+ for _, scenario := range []string{"native packet", "invalid area length", "invalid reason length"} {
+ t.Run(scenario, func(t *testing.T) {
+ world := newTestServer(t)
+ cookie := accountVisitor(t, world)
+ connection := nativeCreationConnection(t, world, cookie)
+ // Actual creator: Atrox Enforcer, head 29, tall, heavy, area "area unknown".
+ packet, err := hex.DecodeString("dfdf00010001008300000000000000010000000f0000000400000000610000000000000000000000000000000000000000000000000000000000000004000000000000000a4e61746976656865726f000000040000000100000009000000000000000c6172656120756e6b6e6f776e00000000000000000000001d0000006e0000000215")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if scenario == "invalid area length" {
+ binary.BigEndian.PutUint32(packet[95:99], 100)
+ }
+ if scenario == "invalid reason length" {
+ binary.BigEndian.PutUint32(packet[115:119], 100)
+ }
+
+ response := nativeCreationExchange(t, connection, packet)
+
+ if scenario != "native packet" {
+ if hex.EncodeToString(response) != "0000001000000009" || world.nextCharacter != 1 {
+ t.Fatalf("malformed native string accepted: %x", response)
+ }
+ return
+ }
+ player := world.characters[2]
+ if hex.EncodeToString(response) != "0000001100000002" || player == nil || player.name != "Nativehero" ||
+ player.profession != 9 || player.headMesh != 40132 || player.height != 110 ||
+ unpackAppearance(player.appearance) != (appearanceFields{Race: 1, Breed: 4, Sex: 1, Fatness: 2}) {
+ t.Fatalf("native client request did not preserve its appearance: %x %+v", response, player)
+ }
+ })
+ }
+}
+
+func TestNativeCreationPersistsAndRedirects(t *testing.T) {
+ world := newTestServer(t)
+ world.baseURL = "/share/test/"
+ world.worldPort = 7620
+ cookie := accountVisitor(t, world)
+ claimed := accountRequest(world, cookie, "claim", "Previous", "secret")
+ if claimed.Code != http.StatusNoContent {
+ t.Fatal(claimed.Body.String())
+ }
+ cookie = claimed.Result().Cookies()[0]
+ before := world.characters[1].profile()
+ connection := nativeCreationConnection(t, world, cookie)
+
+ challenge := nativeCreationExchange(t, connection, systemPacket(0x22, nil))
+ authenticated := nativeCreationExchange(t, connection, systemPacket(0x25, nil))
+ created := nativeCreationExchange(t, connection, nativeCreationAlice(t))
+ repeated := nativeCreationExchange(t, connection, nativeCreationAlice(t))
+ redirect := nativeCreationExchange(t, connection, systemPacket(0x16, []byte{0, 0, 0, 2}))
+ restored := newTestInventoryServer(t)
+
+ if binary.BigEndian.Uint32(challenge) != 0x24 || hex.EncodeToString(authenticated) != "0000000e00000000" ||
+ hex.EncodeToString(created) != "0000001100000002" || !reflect.DeepEqual(created, repeated) ||
+ hex.EncodeToString(redirect) != "00000017000000027f0000011dc40000000000000000" {
+ t.Fatalf("native creation replies: challenge=%x auth=%x created=%x repeat=%x redirect=%x", challenge, authenticated, created, repeated, redirect)
+ }
+ player := restored.characters[2]
+ if player.name != "Alice" || player.profession != 9 || player.headMesh != 40132 || player.height != 110 ||
+ unpackAppearance(player.appearance) != (appearanceFields{Race: 1, Breed: 4, Sex: 1, Fatness: 2}) ||
+ player.playfield != 4604 || player.position != [3]float32{190, 1.52, 200} || player.returnDoor != nil || len(player.inventory.Items) != 4 {
+ t.Fatalf("native creation state: %+v inventory=%+v", player.profile(), player.inventory)
+ }
+ if player.inventory.Items[0].Template != 116628 || player.inventory.Items[1].Template != 116629 ||
+ player.inventory.Items[2].Template != 121564 || player.inventory.Items[3].Template != 43379 {
+ t.Fatal("native starter kit differs from existing creation grants", player.inventory.Items)
+ }
+ request := httptest.NewRequest("GET", "/", nil)
+ request.AddCookie(cookie)
+ if restored.browserCharacter_locked(request) != player || restored.nextCharacter != 2 {
+ t.Fatal("browser ownership did not move atomically or repeated creation duplicated a character")
+ }
+ before.BrowserTokenHash = restored.characters[1].browserTokenHash
+ if before != restored.characters[1].profile() {
+ t.Fatal("creation changed the previous character")
+ }
+ restored.baseURL = "/"
+ if response := accountRequest(restored, cookie, "login", "Previous", "secret"); response.Code != http.StatusNoContent {
+ t.Fatal("the previous character's credentials were lost", response.Body.String())
+ }
+}
+
+func TestNativeCreationRefusalAndFailedCommitRetainSession(t *testing.T) {
+ for _, scenario := range []string{"name taken", "invalid head", "truncated", "insert failure", "ownership failure", "commit failure", "cancel"} {
+ t.Run(scenario, func(t *testing.T) {
+ world := newTestServer(t)
+ cookie := accountVisitor(t, world)
+ if scenario == "name taken" {
+ response := accountRequest(world, cookie, "claim", "Alice", "secret")
+ cookie = response.Result().Cookies()[0]
+ }
+ before := world.characters[1].profile()
+ lastItem := world.nextItem
+ packet := nativeCreationAlice(t)
+ if scenario == "invalid head" {
+ binary.BigEndian.PutUint32(packet[102:106], 30)
+ }
+ if scenario == "truncated" {
+ packet = systemPacket(0x0f, []byte{0, 0, 0, 4})
+ }
+ if scenario == "insert failure" || scenario == "ownership failure" || scenario == "commit failure" {
+ trigger := "CREATE TRIGGER reject_creation BEFORE INSERT ON item_locations BEGIN SELECT RAISE(FAIL, 'test creation failure'); END"
+ if scenario == "ownership failure" {
+ trigger = "CREATE TRIGGER reject_creation BEFORE UPDATE OF browser_token_hash ON characters WHEN OLD.id=1 BEGIN SELECT RAISE(FAIL, 'test ownership failure'); END"
+ } else if scenario == "commit failure" {
+ trigger = "CREATE TABLE pending_creation (id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER reject_creation AFTER INSERT ON players BEGIN INSERT INTO pending_creation VALUES (999999); END"
+ }
+ if _, err := world.db.Exec(trigger); err != nil {
+ t.Fatal(err)
+ }
+ }
+ connection := nativeCreationConnection(t, world, cookie)
+
+ nativeCreationExchange(t, connection, systemPacket(0x25, nil))
+ var response []byte
+ if scenario != "cancel" {
+ response = nativeCreationExchange(t, connection, packet)
+ }
+ connection.Close()
+ restored := newTestInventoryServer(t)
+
+ if scenario != "cancel" {
+ want := "0000001000000009"
+ if scenario == "name taken" {
+ want = "000000100000001e"
+ }
+ if hex.EncodeToString(response) != want {
+ t.Fatalf("refusal %x, want %s", response, want)
+ }
+ }
+ if restored.nextCharacter != 1 || restored.nextItem != lastItem || restored.characters[1].profile() != before || world.characters[1].profile() != before {
+ t.Fatal("failed creation changed the old character, credential, or identity counters")
+ }
+ var orphanItems int
+ if err := world.db.QueryRow("SELECT count(*) FROM items WHERE id>?", lastItem).Scan(&orphanItems); err != nil || orphanItems != 0 {
+ t.Fatal("failed creation left partial items", orphanItems, err)
+ }
+ if scenario == "commit failure" {
+ if _, err := world.db.Exec("DROP TRIGGER reject_creation"); err != nil {
+ t.Fatal(err)
+ }
+ retry := nativeCreationExchange(t, nativeCreationConnection(t, world, cookie), nativeCreationAlice(t))
+ if hex.EncodeToString(retry) != "0000001100000002" {
+ t.Fatal("failed commit prevented retry", hex.EncodeToString(retry))
+ }
+ }
+ })
+ }
+}
+
+func TestNativeCreationCompetingConnectionCannotCreateTwice(t *testing.T) {
+ world := newTestServer(t)
+ cookie := accountVisitor(t, world)
+ first := nativeCreationConnection(t, world, cookie)
+ second := nativeCreationConnection(t, world, cookie)
+
+ responses := make(chan []byte, 2)
+ packet := nativeCreationAlice(t)
+ for _, connection := range []net.Conn{first, second} {
+ go func() {
+ connection.Write(packet)
+ response, _ := readPacket(connection)
+ responses <- response
+ }()
+ }
+ one, two := <-responses, <-responses
+
+ if len(one) < 24 || len(two) < 24 {
+ t.Fatal("competing creation failed to return both responses", one, two)
+ }
+ if binary.BigEndian.Uint32(one[16:]) == 0x10 {
+ one, two = two, one
+ }
+ if hex.EncodeToString(one[16:]) != "0000001100000002" || hex.EncodeToString(two[16:]) != "0000001000000002" || world.nextCharacter != 2 {
+ t.Fatal("competing creation reused transferred ownership", hex.EncodeToString(one), hex.EncodeToString(two), world.nextCharacter)
+ }
+}
+
+func TestNativeCreationLoginRequiresExplicitSave(t *testing.T) {
+ for _, password := range []string{"", "chosen password"} {
+ t.Run(password, func(t *testing.T) {
+ world := newTestServer(t)
+ cookie := accountVisitor(t, world)
+ nativeCreationExchange(t, nativeCreationConnection(t, world, cookie), nativeCreationAlice(t))
+
+ beforeSave := accountRequest(world, cookie, "login", "Alice", "")
+ saved := accountRequest(world, cookie, "claim", "Alice", password)
+ if saved.Code != http.StatusNoContent {
+ t.Fatal("could not explicitly save native character", saved.Body.String())
+ }
+ loggedIn := accountRequest(world, saved.Result().Cookies()[0], "login", "Alice", password)
+
+ if beforeSave.Code != http.StatusUnauthorized || loggedIn.Code != http.StatusNoContent || world.nextCharacter != 2 {
+ t.Fatal("native creation enabled login without an explicit password choice or could not save", beforeSave.Code, loggedIn.Code)
+ }
+ })
+ }
+}
+
+func TestNativeCreationRequiresBrowserCredential(t *testing.T) {
+ world := newTestServer(t)
+ response := httptest.NewRecorder()
+
+ world.httpHandler().ServeHTTP(response, httptest.NewRequest("GET", "/browser-create", nil))
+
+ if response.Code != http.StatusUnauthorized {
+ t.Fatal("unauthenticated browser entered character creation", response.Code)
+ }
+}
diff --git a/server/world.go b/server/world.go
@@ -75,7 +75,8 @@ func characterPacket(character *character) []byte {
flags |= 1
}
// kkr.dll 0x100821d0: bit 27 supplies HasKnuBotData (stat 768).
- if gamedata.NPCScripts[character.npcDefinitionID].Talk != nil {
+ _, arrivalRepresentative := arrivalHallSide(character.npcDefinitionID)
+ if gamedata.NPCScripts[character.npcDefinitionID].Talk != nil || arrivalRepresentative {
flags |= 0x08000000
}
}
diff --git a/tests/e2e/arrival-hall.test.mjs b/tests/e2e/arrival-hall.test.mjs
@@ -0,0 +1,78 @@
+import assert from 'node:assert/strict';
+import {before, test} from 'node:test';
+import {buildServer, withFixture} from './fixture.mjs';
+
+before(buildServer);
+
+test('Arrival Hall native choice can be cancelled and commits departure once', {timeout: 360_000}, async () =>
+withFixture('arrival-hall', async fixture => {
+ const context = await fixture.visitor();
+ // Controlled precondition: the original create packet supplies a Hall player;
+ // creation-screen coverage belongs to the separate complete-flow regression.
+ // Same original Atrox Enforcer packet as server/native_creation_test.go.
+ const setup = await context.newPage();
+ await setup.goto(fixture.url + '/_test/player');
+ const body = Buffer.from('000000040000000061' +
+ '0000c79c00000000000000000000000000009c5000000000' +
+ '00000000000000040000000000000005416c696365' +
+ '000000040000000100000009000000000000000000000000000000000000001d0000006e00000002', 'hex');
+ const packet = Buffer.alloc((20 + body.length + 3) & ~3);
+ for (const offset of [0, 2, 4]) packet.writeUInt16BE(1, offset);
+ packet.writeUInt16BE(20 + body.length, 6);
+ packet.writeUInt32BE(1, 8);
+ packet.writeUInt32BE(0x0f, 16);
+ body.copy(packet, 20);
+ const result = await setup.evaluate(bytes => new Promise((resolve, reject) => {
+ const socket = new WebSocket(location.origin.replace('http', 'ws') + '/browser-create');
+ socket.binaryType = 'arraybuffer';
+ socket.onopen = () => socket.send(new Uint8Array(bytes));
+ socket.onerror = () => reject(new Error('Native creation fixture connection failed'));
+ socket.onmessage = event => { resolve(Array.from(new Uint8Array(event.data))); socket.close(); };
+ }), Array.from(packet));
+ assert.equal(Buffer.from(result).readUInt32BE(16), 0x11);
+ await setup.close();
+ const before = await fixture.setup(context, 'position', {playfield: 4604,
+ position: [186.17244, 1.8, 168], rotation: [0, 1, 0, 0]});
+ assert.equal(before.items.length, 4);
+ const game = await fixture.game(context);
+ if (!game.state.camera.firstPerson) await game.key('F8');
+ const representative = game.state.actors.find(actor => actor.type === 50000 &&
+ Math.abs(actor.position[0] - 186.17244) < 0.1 && Math.abs(actor.position[2] - 163.2037) < 0.1);
+ assert(representative);
+ await game.save(fixture.output + '/before-conversation');
+
+ await game.click(...await game.pick(50000, representative.id), 'right');
+ await game.wait('representative menu', () => game.events.some(event =>
+ event.direction === 'framereceived' && event.opcode === '55704d31'));
+ await game.save(fixture.output + '/conversation');
+ let sequence = game.sequence;
+ // Original native choice rows in the reset 1024x768 client layout.
+ await game.click(170, 390);
+ await game.wait('conversation cancelled', () => game.events.some(event => event.sequence > sequence &&
+ event.direction === 'framereceived' && event.opcode === '270a4c62'));
+ assert.equal((await fixture.state(context)).playfield, 4604);
+ assert.deepEqual((await fixture.state(context)).items, before.items);
+ sequence = game.sequence;
+ await game.click(...await game.pick(50000, representative.id), 'right');
+ await game.wait('representative reopened', () => game.events.some(event => event.sequence > sequence &&
+ event.direction === 'framereceived' && event.opcode === '55704d31'));
+ await game.click(170, 373);
+ await game.wait('training destination', state => game.local(state)?.playfield === 954, 60000);
+ await game.ready();
+ await game.save(fixture.output + '/training');
+
+ const departed = await fixture.state(context);
+ assert.equal(departed.playfield, 954);
+ assert.equal(departed.items.length, 5);
+ assert.equal(departed.items.filter(item => item.templates.includes(116697)).length, 1);
+ assert(game.events.some(event => event.sequence > sequence && event.direction === 'framereceived' &&
+ event.opcode === '270a4c62'), 'Departure ends the native conversation before zoning');
+ const cookies = await context.cookies();
+ await fixture.restart();
+ const restored = await fixture.context();
+ await restored.addCookies(cookies);
+ const resumed = await fixture.game(restored);
+ assert.equal(resumed.local().playfield, 954);
+ assert.deepEqual((await fixture.state(restored)).items, departed.items);
+ for (const client of [game, resumed]) assert.deepEqual(client.errors, []);
+}));
diff --git a/tests/e2e/native-creation.test.mjs b/tests/e2e/native-creation.test.mjs
@@ -0,0 +1,118 @@
+import assert from 'node:assert/strict';
+import {before, test} from 'node:test';
+import {buildServer, withFixture} from './fixture.mjs';
+import {startStarter, finishStarter, enterOmniTraining, saveStarter} from '../../tools/client/create_starter.mjs';
+
+before(buildServer);
+
+test('native creator preserves cancellation, validates names and saves the complete starter journey',
+{timeout: 900_000}, async () => withFixture('native-creation', async fixture => {
+ const context = await fixture.visitor();
+ const claimed = await context.request.post(fixture.url + '/browser-account/claim',
+ {form: {name: 'Existing', password: 'existing password'}});
+ assert.equal(claimed.status(), 204);
+ const original = await fixture.state(context);
+ const game = await fixture.game(context);
+ const packets = [];
+ game.page.on('websocket', socket => {
+ if (!socket.url().endsWith('/browser-create')) return;
+ for (const direction of ['framesent', 'framereceived']) socket.on(direction, ({payload}) => {
+ const packet = Buffer.from(payload);
+ packets.push({direction, packet});
+ game.record({kind: 'creation-packet', direction, hex: packet.toString('hex')});
+ });
+ });
+
+ await startStarter(game);
+ await game.click(997, 38);
+ await game.wait('native quit confirmation', state => state.regions.some(
+ ([left, top, right, bottom]) => left === 437 && top === 415 && right === 507 && bottom === 435));
+ await game.save(fixture.output + '/cancel');
+ // Exit ends the native frame loop; observe the page reload instead of waiting for another frame.
+ const point = await game.point(472, 425);
+ await game.page.mouse.move(point.x, point.y);
+ const sequence = game.sequence;
+ await game.page.mouse.down();
+ await game.waitInput(sequence, 1025);
+ await Promise.all([game.page.waitForEvent('load'), game.page.mouse.up()]);
+ await game.ready();
+ assert.equal((await fixture.state(context)).id, original.id);
+ assert.deepEqual((await fixture.state(context)).items, original.items);
+ console.log('PASS: native cancellation preserves the existing character');
+
+ await startStarter(game);
+ await game.click(507, 130);
+ await game.page.keyboard.type('ab', {delay: 60});
+ await game.click(945, 730);
+ await game.wait('native invalid-name message', state => state.regions.some(
+ ([left, top, right, bottom]) => left === 472 && top === 435 && right === 542 && bottom === 455));
+ assert.equal(packets.filter(({direction, packet}) => direction === 'framesent' && packet.readUInt32BE(16) === 0x0f).length, 0);
+ await game.save(fixture.output + '/invalid-name');
+ await game.click(507, 445);
+ await game.click(507, 130);
+ await game.key('Backspace');
+ await game.key('Backspace');
+ await game.page.keyboard.type('Existing', {delay: 60});
+ await game.click(945, 730);
+ await game.wait('server rejects an existing name', state => state.creation?.nameState === 0 &&
+ packets.some(({direction, packet}) => direction === 'framereceived' && packet.readUInt32BE(16) === 0x10 && packet.readUInt32BE(20) === 0x1e));
+ assert.equal((await fixture.state(context)).id, original.id);
+ await game.save(fixture.output + '/duplicate-name');
+ console.log('PASS: native short-name and duplicate-name errors preserve the existing character');
+ const okay = game.state.regions.find(([left, top, right, bottom]) => right - left === 70 && bottom - top === 20);
+ assert(okay);
+ await game.click((okay[0] + okay[2]) / 2, (okay[1] + okay[3]) / 2);
+ await game.click(507, 130);
+ await game.key('End');
+ for (let index = 0; index < 8; ++index) await game.key('Backspace');
+ await finishStarter(game, 'Nativehero');
+ await game.save(fixture.output + '/arrival');
+ const created = await fixture.state(context);
+ assert.equal(created.name, 'Nativehero');
+ assert.equal(created.items.length, 4);
+ assert.deepEqual(created.items.map(item => item.templates[0]), [116628, 116629, 121564, 43379]);
+ await enterOmniTraining(game);
+ await game.save(fixture.output + '/training');
+ const departed = await fixture.state(context);
+ assert.equal(departed.playfield, 950);
+ assert.equal(departed.items.length, 7);
+ assert.deepEqual(departed.items.slice(4).map(item => item.templates[0]), [116693, 99719, 29426]);
+ console.log('PASS: original creator and Arrival Hall reach training with the expected starter items');
+
+ // Verify first-session preference writes belong to the newly created identity.
+ await game.key('i');
+ const grid = state => state.grids.find(grid => grid.cells.some(cell => cell.identity[0] === 104));
+ const firstItem = state => grid(state).cells.find(cell => cell.identity[0] === 104 && cell.identity[1] === 48 && !cell.dummy);
+ const clickCell = cell => game.click((cell.bounds[0] + cell.bounds[2]) / 2, (cell.bounds[1] + cell.bounds[3]) / 2);
+ assert.equal(firstItem(game.state).index, 0);
+ await clickCell(firstItem(game.state));
+ await game.wait('starter item picked up', state => state.dragged[0] === 104);
+ await clickCell(grid(game.state).cells.find(cell => cell.index === 8));
+ await game.wait('starter layout saved', state => state.dragged[0] === 0 && firstItem(state).index === 8);
+ await saveStarter(game, 'Nativehero', 'native password');
+ if (!game.state.grids.some(grid => grid.cells.some(cell => cell.identity[0] === 104))) await game.key('i');
+ assert.equal(firstItem(game.state).index, 8);
+ console.log('PASS: newly created character preferences survive saving and reload');
+
+ assert.equal((await fixture.state(context)).id, created.id);
+ assert.deepEqual((await fixture.state(context)).items, departed.items);
+ const cookies = await context.cookies();
+ await fixture.restart();
+ const restored = await fixture.context();
+ await restored.addCookies(cookies);
+ const resumed = await fixture.game(restored);
+ assert.equal(resumed.local().playfield, 950);
+ assert.deepEqual((await fixture.state(restored)).items, departed.items);
+ const recovered = await fixture.visitor();
+ const login = await recovered.request.post(fixture.url + '/browser-account/login',
+ {form: {name: 'Existing', password: 'existing password'}});
+ assert.equal(login.status(), 204);
+ assert.equal((await fixture.state(recovered)).id, original.id);
+ assert.deepEqual((await fixture.state(recovered)).items, original.items);
+ const newLogin = await recovered.request.post(fixture.url + '/browser-account/login',
+ {form: {name: 'Nativehero', password: 'native password'}});
+ assert.equal(newLogin.status(), 204);
+ assert.equal((await fixture.state(recovered)).id, created.id);
+ assert.deepEqual((await fixture.state(recovered)).items, departed.items);
+ for (const client of [game, resumed]) assert.deepEqual(client.errors, []);
+}));
diff --git a/tools/client/create_starter.mjs b/tools/client/create_starter.mjs
@@ -0,0 +1,65 @@
+import assert from 'node:assert/strict';
+
+export async function startStarter(game) {
+ // Options launches the original creator in a new client instance.
+ await game.page.keyboard.press('Control+Alt+M');
+ await Promise.all([game.page.waitForEvent('load'), game.page.locator('#create-button').click()]);
+ await game.page.waitForFunction(() => typeof Module._browser_test_request === 'function', null, {timeout: 180000});
+ await game.wait('native breed selection', state => state.creation?.scene === 1001 && state.creation.ready, 60000);
+ await game.click(880, 350);
+ await game.wait('selected Atrox enables Next', state => state.regions.some(
+ ([left, top, right, bottom]) => left === 888 && top === 710 && right === 1006 && bottom === 749));
+ await game.click(946, 730);
+
+ // Exercise original head, height and build controls, then select Enforcer.
+ await game.wait('native appearance selection', state => state.creation?.scene === 1002 && state.creation.ready, 60000);
+ await game.click(404, 130);
+ await game.click(919, 214);
+ await game.click(920, 444);
+ await game.click(946, 730);
+ await game.wait('native profession selection', state => state.creation?.scene === 1003 && state.creation.ready, 60000);
+ await game.click(850, 514);
+ await game.wait('selected Enforcer enables Next', state => state.regions.some(
+ ([left, top, right, bottom]) => left === 888 && top === 710 && right === 1006 && bottom === 749));
+ await game.click(946, 730);
+ await game.wait('native naming', state => state.creation?.scene === 1004 && state.creation.ready, 60000);
+}
+
+export async function finishStarter(game, name) {
+ // Native Finish commits the chosen character and connects it to Arrival Hall.
+ await game.click(507, 130);
+ await game.page.keyboard.type(name, {delay: 60});
+ await game.click(945, 730);
+ await game.ready();
+ assert.equal(game.local().playfield, 4604);
+ assert.equal(game.local().stats[4], 4);
+ assert.equal(game.local().stats[60], 9);
+}
+
+export async function saveStarter(game, name, password) {
+ // Native naming keeps cookie ownership; explicitly save login credentials in Options.
+ await game.page.keyboard.press('Control+Alt+M');
+ await game.page.locator('#claim-button').click();
+ assert.equal(await game.page.locator('#account-name').inputValue(), name);
+ await game.page.locator('#account-password').fill(password);
+ await Promise.all([game.page.waitForEvent('load'), game.page.locator('#account-submit').click()]);
+ await game.ready();
+}
+
+export async function enterOmniTraining(game) {
+ // Walk through the Hall's central barrier opening to the Omni desk.
+ if (!game.state.camera.firstPerson) await game.key('F8');
+ for (const [x, z] of [[186, 181], [186, 172], [178.5, 170], [178.5, 167.5]]) await game.walk(x, z);
+ const representative = game.state.actors.find(actor => actor.type === 50000 &&
+ Math.abs(actor.position[0] - 176.11554) < 0.2 && Math.abs(actor.position[2] - 163.19379) < 0.2);
+ assert(representative);
+ const sequence = game.sequence;
+ await game.click(...await game.pick(50000, representative.id), 'right');
+ await game.wait('Omni representative menu', () => game.events.some(event => event.sequence > sequence &&
+ event.direction === 'framereceived' && event.opcode === '55704d31'));
+ await game.click(170, 373);
+ await game.wait('Omni training destination', state => game.local(state)?.playfield === 950, 60000);
+ await game.ready();
+ await game.click(538, 108);
+ assert.equal(game.local().stats[33], 2);
+}
diff --git a/tools/client/package_runtime.py b/tools/client/package_runtime.py
@@ -17,7 +17,8 @@ for name in ['cd_image', 'Setupf', 'fonts']:
files.extend((path, path.relative_to(root).as_posix())
for path in (assets / name).rglob('*') if path.is_file())
files.extend((assets / name, 'anarchy-assets-14.9.1/' + name)
- for name in ['Prefs/Main.cfg', 'Prefs/localtest/Login.cfg', 'version.id'])
+ for name in ['Prefs/Main.cfg', 'Prefs/localtest/Login.cfg', 'version.id',
+ 'CharCreateCamera.dat'])
files.extend((root / 'data' / name, name) for name in [
'terrain.bin', 'zone_links.yaml',
])
diff --git a/tools/client/prepare_portable_assets.py b/tools/client/prepare_portable_assets.py
@@ -15,7 +15,8 @@ directories = [
'cd_image/sound/music', 'cd_image/sound/sfx', 'cd_image/sound/voice',
'cd_image/sound/SourceFiles', 'Setupf', 'fonts',
]
-files = [source / name for name in ['Prefs/Main.cfg', 'Prefs/localtest/Login.cfg', 'version.id']]
+files = [source / name for name in ['Prefs/Main.cfg', 'Prefs/localtest/Login.cfg', 'version.id',
+ 'CharCreateCamera.dat']]
for name in directories:
files.extend(path for path in (source / name).rglob('*') if path.is_file())
diff --git a/tools/client/test_password_options.mjs b/tools/client/test_password_options.mjs
@@ -18,11 +18,8 @@ try {
await page.waitForFunction(() => !document.querySelector('#account-choices').disabled);
assert.equal(await page.locator('#password-button').isVisible(), false);
- // Create a character through Options and open its password form with real input.
- await page.locator('#create-button').click();
- await page.locator('#creation-breed').selectOption('4');
- await page.locator('#creation-profession').selectOption('9');
- await page.locator('#creation-side').selectOption('2');
+ // Save the current visitor through Options and open its password form with real input.
+ await page.locator('#claim-button').click();
await page.locator('#account-name').fill('Passwordtest');
await page.locator('#account-password').fill('original password');
await Promise.all([page.waitForEvent('load'), page.locator('#account-submit').click()]);
@@ -60,7 +57,7 @@ try {
assert.equal(game.navigation, navigation);
assert.deepEqual(game.errors, []);
await game.save(output + '/game');
- console.log('PASS: visitor eligibility, created player password form, Back, nonempty and empty passwords, unchanged browser credential and live game stream');
+ console.log('PASS: visitor eligibility, saved player password form, Back, nonempty and empty passwords, unchanged browser credential and live game stream');
} finally {
await browser.close();
}
diff --git a/tools/client/test_starter_equipment.mjs b/tools/client/test_starter_equipment.mjs
@@ -2,6 +2,7 @@ import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import {createRequire} from 'node:module';
import {GameTest} from './game_test.mjs';
+import {startStarter, finishStarter, enterOmniTraining, saveStarter} from './create_starter.mjs';
const {chromium} = createRequire(import.meta.url)('playwright');
const [url, output] = process.argv.slice(2);
@@ -253,7 +254,7 @@ async function outdoorFight(game, level, label) {
}
try {
- // Create both characters through the same Options form used during ordinary play.
+ // Create both characters through the original creator and Arrival Hall.
for (const name of ['Starterowner', 'Starterwatch']) {
const context = await browser.newContext({viewport: {width: 1024, height: 768}});
const page = await context.newPage();
@@ -261,16 +262,10 @@ try {
games.push(game);
await page.goto(url);
await game.ready();
- await page.keyboard.press('Control+Alt+M');
- await page.locator('#create-button').click();
- await page.locator('#creation-breed').selectOption('4');
- await page.locator('#creation-profession').selectOption('9');
- await page.locator('#creation-side').selectOption('2');
- await page.locator('#account-name').fill(name);
- await page.locator('#account-password').fill('starter regression password');
- await Promise.all([page.waitForEvent('load'), page.locator('#account-submit').click()]);
- console.log('Created ' + name + '; waiting for its native training-ground actor');
- await game.ready();
+ await startStarter(game);
+ await finishStarter(game, name);
+ await enterOmniTraining(game);
+ await saveStarter(game, name, 'starter regression password');
assert.equal(game.local().playfield, 950);
assert.equal(game.local().inventory.length, 7);
assert.equal(game.local().stats[54], 1);
@@ -286,10 +281,10 @@ try {
assert(bat);
const before = (await (await owner.page.request.get(url + '/test-state')).json()).inventory;
- // The native inventory's initial three-column layout puts the issued bat fourth.
+ // The native inventory's initial three-column layout puts the issued bat third.
await owner.key('i');
await owner.save(output + '/inventory');
- await owner.click(681, 99, 'right');
+ await owner.click(789, 45, 'right');
await owner.wait('issued bat equipped', state => owner.local(state).inventory.some(item => item.id === bat.id && item.slot === 6));
const equipped = (await (await owner.page.request.get(url + '/test-state')).json()).inventory;
assert.deepEqual(equipped.Items, before.Items.map(item => item.ID === bat.id ? {...item, Slot: 6} : item));
@@ -308,14 +303,14 @@ try {
// Remove through Wear, then equip the same instance from its original inventory cell.
await owner.click(867, 206, 'right');
- await owner.wait('issued bat returned to inventory', state => owner.local(state).inventory.some(item => item.id === bat.id && item.slot === 51));
+ await owner.wait('issued bat returned to inventory', state => owner.local(state).inventory.some(item => item.id === bat.id && item.slot === bat.slot));
const removed = (await (await owner.page.request.get(url + '/test-state')).json()).inventory;
assert.deepEqual(removed.Items, before.Items);
assert.deepEqual(owner.local().inventory, issued);
await owner.page.keyboard.press('Control+1');
await owner.key('i');
await owner.save(output + '/removed');
- await owner.click(681, 99, 'right');
+ await owner.click(789, 45, 'right');
await owner.wait('same issued bat equipped again', state => owner.local(state).inventory.some(item => item.id === bat.id && item.slot === 6));
const reworn = (await (await owner.page.request.get(url + '/test-state')).json()).inventory;
assert.deepEqual(reworn.Items, equipped.Items);
@@ -358,7 +353,7 @@ try {
const shirt = issued.find(item => item.templates[0] === 29426);
await owner.click(681, 154, 'right');
await owner.wait('issued shirt worn', state => owner.local(state).inventory.some(item => item.id === shirt.id && item.slot === 21));
- await owner.click(740, 99, 'right');
+ await owner.click(681, 99, 'right');
await owner.wait('issued crystal consumed', state => !owner.local(state).inventory.some(item => item.id === crystal.id));
await owner.page.keyboard.press('Control+8');
await owner.click(927, 96);
diff --git a/tools/client/test_starter_mission_targets.mjs b/tools/client/test_starter_mission_targets.mjs
@@ -1,6 +1,7 @@
import assert from 'node:assert/strict';
import {createRequire} from 'node:module';
import {GameTest} from './game_test.mjs';
+import {startStarter, finishStarter, enterOmniTraining, saveStarter} from './create_starter.mjs';
const {chromium} = createRequire(import.meta.url)('playwright');
const [url, output] = process.argv.slice(2);
@@ -17,15 +18,10 @@ try {
// Create the normal starter, then reach its backyard through the training exit.
await page.goto(url);
await game.ready();
- await page.keyboard.press('Control+Alt+M');
- await page.locator('#create-button').click();
- await page.locator('#creation-breed').selectOption('4');
- await page.locator('#creation-profession').selectOption('9');
- await page.locator('#creation-side').selectOption('2');
- await page.locator('#account-name').fill('Missionpick');
- await page.locator('#account-password').fill('mission target regression password');
- await Promise.all([page.waitForEvent('load'), page.locator('#account-submit').click()]);
- await game.ready();
+ await startStarter(game);
+ await finishStarter(game, 'Missionpick');
+ await enterOmniTraining(game);
+ await saveStarter(game, 'Missionpick', 'mission target regression password');
assert.equal(game.local().playfield, 950);
const issued = game.local().inventory;
await game.save(output + '/created');
diff --git a/tools/data/npc_assignments.json b/tools/data/npc_assignments.json
@@ -12221,7 +12221,7 @@
"kind": "monster_data",
"id": 26088
},
- "appearance": 277,
+ "appearance": 789,
"confidence": "low"
},
"variants": [
@@ -12231,7 +12231,7 @@
"kind": "monster_data",
"id": 26088
},
- "appearance": 277,
+ "appearance": 789,
"confidence": "low",
"reason": "Select the role or encounter supported by the abbreviation and its authored site/level. This is a best-effort reconstruction; exact historical identity, head and equipment are not asserted.",
"alternatives": [
@@ -56681,7 +56681,7 @@
"kind": "monster_data",
"id": 26088
},
- "appearance": 277,
+ "appearance": 1301,
"confidence": "low"
},
"variants": [
@@ -56691,7 +56691,7 @@
"kind": "monster_data",
"id": 26088
},
- "appearance": 277,
+ "appearance": 1301,
"confidence": "low",
"reason": "Select the role or encounter supported by the abbreviation and its authored site/level. This is a best-effort reconstruction; exact historical identity, head and equipment are not asserted.",
"alternatives": [