vice city online: the bare online core
This commit is contained in:
commit
2f98475c19
256 changed files with 144219 additions and 0 deletions
57
tools/build-web.sh
Normal file
57
tools/build-web.sh
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
#!/usr/bin/env bash
|
||||
# Browser build: reVC + librw (GL3 over WebGL2) compiled with Emscripten into web/dist.
|
||||
# Usage: EMSDK=/opt/emsdk tools/build-web.sh [jobs]
|
||||
set -euo pipefail
|
||||
JOBS=${1:-16}
|
||||
ROOT=$(cd "$(dirname "$0")/.." && pwd)
|
||||
cd "$ROOT"
|
||||
set +u; source "${EMSDK:-/opt/emsdk}/emsdk_env.sh" >/dev/null 2>&1; set -u
|
||||
emcc --version | head -1
|
||||
OBJ=build/web/obj
|
||||
OUT=web/dist
|
||||
mkdir -p "$OBJ" "$OUT"
|
||||
|
||||
OPT=(-O3 -g0)
|
||||
COMMON=("${OPT[@]}" -DNDEBUG -DRW_GL3 --use-port=contrib.glfw3 -Wno-everything)
|
||||
RW_FLAGS=("${COMMON[@]}" -DLODEPNG_NO_COMPILE_CPP -Ivendor/librw)
|
||||
GAME_FLAGS=("${COMMON[@]}" -std=c++17 -DLIBRW -DAUDIO_OAL -DCMAKE_BUILD -DUSE_OUR_VERSIONING
|
||||
-sUSE_MPG123=1 -Ivendor/librw -Iweb/include)
|
||||
for d in $(find src -type d); do GAME_FLAGS+=(-I"$d"); done
|
||||
|
||||
echo "#define GIT_SHA1 \"$(git rev-parse --short HEAD)\"
|
||||
const char* g_GIT_SHA1 = GIT_SHA1;" > build/web/GitSHA1.cpp
|
||||
|
||||
# One compile per source; only sources newer than their object are rebuilt.
|
||||
compile() { # src obj flags...
|
||||
local src=$1 obj=$2; shift 2
|
||||
if [ ! -f "$obj" ] || [ "$src" -nt "$obj" ]; then
|
||||
mkdir -p "$(dirname "$obj")"
|
||||
case $src in *.c) cc=emcc;; *) cc=em++;; esac
|
||||
$cc "$@" -c "$src" -o "$obj" 2>"$obj.log" || { echo "FAIL $src"; cat "$obj.log" | grep -E "error" | head -20; return 1; }
|
||||
fi
|
||||
}
|
||||
export -f compile
|
||||
|
||||
RW_SRCS=$(find vendor/librw/src -name '*.cpp' -o -name '*.c')
|
||||
GAME_SRCS=$(find src -name '*.cpp' | grep -v -e src/skel/win/ ; echo build/web/GitSHA1.cpp)
|
||||
|
||||
status=0
|
||||
printf '%s\n' $RW_SRCS | xargs -P "$JOBS" -I{} bash -c 'compile "$1" "'"$OBJ"'/$1.o" "${@:2}"' _ {} "${RW_FLAGS[@]}" || status=1
|
||||
printf '%s\n' $GAME_SRCS | xargs -P "$JOBS" -I{} bash -c 'compile "$1" "'"$OBJ"'/$1.o" "${@:2}"' _ {} "${GAME_FLAGS[@]}" || status=1
|
||||
[ $status -eq 0 ] || { echo "compile failed"; exit 1; }
|
||||
|
||||
LINK_DEBUG=()
|
||||
[ "${WEB_DEBUG:-0}" = 1 ] && LINK_DEBUG=(--profiling-funcs -sASSERTIONS=1)
|
||||
[ "${WEB_DEBUG:-0}" = names ] && LINK_DEBUG=(--profiling-funcs)
|
||||
OBJS=$(for s in $RW_SRCS $GAME_SRCS; do echo "$OBJ/$s.o"; done)
|
||||
# WEB_ASYNC=jspi: the browser switches stacks itself and the game code stays uninstrumented.
|
||||
if [ "${WEB_ASYNC:-asyncify}" = jspi ]; then ASYNC_FLAGS=(-sJSPI); ENGINE=revc-jspi; else ASYNC_FLAGS=(-sASYNCIFY -sASYNCIFY_STACK_SIZE=262144); ENGINE=revc; fi
|
||||
em++ "${OPT[@]}" "${LINK_DEBUG[@]}" $OBJS -o "$OUT/$ENGINE.js" \
|
||||
--use-port=contrib.glfw3 -sUSE_MPG123=1 -lopenal -lwebsocket.js \
|
||||
-sMIN_WEBGL_VERSION=2 -sMAX_WEBGL_VERSION=2 -sGL_ENABLE_GET_PROC_ADDRESS -sGL_TRACK_ERRORS=0 \
|
||||
"${ASYNC_FLAGS[@]}" -sSTACK_SIZE=4MB \
|
||||
-sALLOW_MEMORY_GROWTH -sINITIAL_MEMORY=512MB -sMAXIMUM_MEMORY=4GB \
|
||||
-sFETCH -sFORCE_FILESYSTEM -lidbfs.js \
|
||||
-sEXPORTED_RUNTIME_METHODS=FS,callMain -sINVOKE_RUN=0 -sEXIT_RUNTIME=0
|
||||
cp web/shell/* "$OUT"/ 2>/dev/null || true
|
||||
ls -la "$OUT"
|
||||
19
tools/build-win.ps1
Normal file
19
tools/build-win.ps1
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
# Local Windows build (MSVC, below-normal priority) and install into a game folder.
|
||||
# Usage: powershell -File tools/build-win.ps1 [-GameDir C:\Games\GTAVC] [-Jobs 4]
|
||||
param([string]$GameDir = "C:\Games\GTAVC", [int]$Jobs = 4)
|
||||
$ErrorActionPreference = "Stop"
|
||||
$root = Split-Path $PSScriptRoot -Parent
|
||||
Set-Location $root
|
||||
& .\premake5.exe vs2019 --with-librw --no-full-paths | Out-Null
|
||||
$vs = & "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" -latest -products * -requires Microsoft.Component.MSBuild -property installationPath
|
||||
$toolset = if (Test-Path "$vs\VC\Tools\MSVC\14.5*") { "v145" } else { "v143" }
|
||||
$args = @("build\reVC.sln", "/m:$Jobs", "/nologo", "/v:minimal", "/p:Configuration=Release",
|
||||
"/p:Platform=win-amd64-librw_d3d9-oal", "/p:PlatformToolset=$toolset", "/p:WindowsTargetPlatformVersion=10.0")
|
||||
$p = Start-Process -FilePath "$vs\MSBuild\Current\Bin\MSBuild.exe" -ArgumentList $args -NoNewWindow -PassThru `
|
||||
-RedirectStandardOutput build.log -RedirectStandardError build.err
|
||||
$p.PriorityClass = "BelowNormal"; $p.WaitForExit()
|
||||
$errors = Select-String -Path build.log -Pattern ": (fatal )?error " | ForEach-Object { $_.Line -replace '^.*\\src\\', 'src\' -replace ' \[.*$', '' } | Sort-Object -Unique
|
||||
if ($errors) { $errors; exit 1 }
|
||||
$bin = "bin\win-amd64-librw_d3d9-oal\Release"
|
||||
Copy-Item "$bin\reVC.exe" $GameDir -Force
|
||||
"built and installed to $GameDir"
|
||||
50
tools/font-turkish.py
Normal file
50
tools/font-turkish.py
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
#!/usr/bin/env python3
|
||||
# Adds the Turkish letters the menu font lacks, built from its own letters and accents.
|
||||
# Usage: python tools/font-turkish.py web/shell/BowlbyOne.ttf
|
||||
import sys
|
||||
from fontTools.ttLib import TTFont
|
||||
from fontTools.pens.ttGlyphPen import TTGlyphPen
|
||||
from fontTools.pens.boundsPen import BoundsPen
|
||||
|
||||
path = sys.argv[1]
|
||||
font = TTFont(path)
|
||||
glyphs = font.getGlyphSet()
|
||||
table = font['glyf']
|
||||
cmap = font.getBestCmap()
|
||||
cap_height = font['OS/2'].sCapHeight or 1400
|
||||
x_height = font['OS/2'].sxHeight or 1000
|
||||
|
||||
|
||||
def bounds(name):
|
||||
pen = BoundsPen(glyphs)
|
||||
glyphs[name].draw(pen)
|
||||
return pen.bounds
|
||||
|
||||
|
||||
def add(code, name, base, accent, above):
|
||||
if code in cmap:
|
||||
return
|
||||
b, a = bounds(base), bounds(accent)
|
||||
dx = (b[0] + b[2]) / 2 - (a[0] + a[2]) / 2
|
||||
gap = (b[3] - b[1]) * 0.06
|
||||
dy = b[3] + gap - a[1] if above else b[1] + gap - a[3]
|
||||
pen = TTGlyphPen(glyphs)
|
||||
pen.addComponent(base, (1, 0, 0, 1, 0, 0))
|
||||
pen.addComponent(accent, (1, 0, 0, 1, round(dx), round(dy)))
|
||||
glyph = pen.glyph()
|
||||
table[name] = glyph
|
||||
font['hmtx'][name] = font['hmtx'][base]
|
||||
font.setGlyphOrder(font.getGlyphOrder() if name in font.getGlyphOrder() else font.getGlyphOrder() + [name])
|
||||
for t in font['cmap'].tables:
|
||||
if t.isUnicode():
|
||||
t.cmap[code] = name
|
||||
|
||||
|
||||
add(0x11E, 'Gbreve', 'G', 'breve', True)
|
||||
add(0x11F, 'gbreve', 'g', 'breve', True)
|
||||
add(0x15E, 'Scedilla', 'S', 'cedilla', False)
|
||||
add(0x15F, 'scedilla', 's', 'cedilla', False)
|
||||
add(0x130, 'Idotaccent', 'I', 'dotaccent', True)
|
||||
font['maxp'].numGlyphs = len(font.getGlyphOrder())
|
||||
font.save(path)
|
||||
print('ok', len(font.getGlyphOrder()))
|
||||
46
tools/make-manifest.ts
Normal file
46
tools/make-manifest.ts
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
// Writes manifest.json into a game folder: the eager files (path + size) the browser
|
||||
// loads before start-up and the ranged image files it streams, chosen by web/data-pack.json. The data host serves
|
||||
// every file under its lower-case path, so the manifest uses lower case too.
|
||||
// Usage: bun tools/make-manifest.ts <game dir>
|
||||
import { Glob } from "bun";
|
||||
import { createHash } from "node:crypto";
|
||||
import { join, relative } from "node:path";
|
||||
import { existsSync, statSync, writeFileSync, readFileSync } from "node:fs";
|
||||
|
||||
const gameDir = process.argv[2];
|
||||
if (!gameDir) throw new Error("usage: bun tools/make-manifest.ts <game dir>");
|
||||
const pack = JSON.parse(readFileSync(join(import.meta.dir, "../web/data-pack.json"), "utf8"));
|
||||
const lower = (p: string) => p.replaceAll("\\", "/").toLowerCase();
|
||||
const matches = (patterns: string[], path: string) => patterns.some((g) => new Glob(lower(g)).match(path));
|
||||
|
||||
const files: { path: string; size: number }[] = [];
|
||||
const diskPath = new Map<string, string>(); // lower-case path -> real path on disk
|
||||
const ranged: { path: string; size: number; memory?: boolean }[] = [];
|
||||
for (const path of new Glob("**/*").scanSync({ cwd: gameDir, onlyFiles: true })) {
|
||||
const rel = lower(path);
|
||||
const size = statSync(join(gameDir, path)).size;
|
||||
diskPath.set(rel, path);
|
||||
if (matches(pack.skip, rel)) continue;
|
||||
// A file named exactly in "eager" beats a "ranged" folder pattern.
|
||||
const named = pack.eager.some((g: string) => !g.includes("*") && lower(g) === rel);
|
||||
if (!named && matches(pack.ranged, rel)) ranged.push(matches(pack.memory ?? [], rel) ? { path: rel, size, memory: true } : { path: rel, size });
|
||||
else if (matches(pack.eager, rel)) files.push({ path: rel, size });
|
||||
}
|
||||
files.sort((a, b) => a.path.localeCompare(b.path));
|
||||
const total = files.reduce((n, f) => n + f.size, 0);
|
||||
// All eager files in one blob, in manifest order: the browser fetches one file, not hundreds.
|
||||
const bundle = Buffer.concat(files.map((f) => readFileSync(join(gameDir, diskPath.get(f.path)!))));
|
||||
writeFileSync(join(gameDir, "eager.bin"), bundle);
|
||||
// The start pack: the pieces of the world image the game reads at the spawn point (web/start-ranges.json).
|
||||
let start: any;
|
||||
const rangesFile = join(import.meta.dir, "../web/start-ranges.json");
|
||||
if (existsSync(rangesFile)) {
|
||||
const { key, ranges } = JSON.parse(readFileSync(rangesFile, "utf8"));
|
||||
const image = readFileSync(join(gameDir, diskPath.get(key)!));
|
||||
const pack = Buffer.concat(ranges.map(([at, size]: number[]) => image.subarray(at, at + size)));
|
||||
writeFileSync(join(gameDir, "start.bin"), pack);
|
||||
start = { path: "start.bin", key, ranges, hash: createHash("sha256").update(pack).digest("hex").slice(0, 16) };
|
||||
console.log(`start pack ${(pack.length / 1048576).toFixed(1)} MB in ${ranges.length} ranges`);
|
||||
}
|
||||
writeFileSync(join(gameDir, "manifest.json"), JSON.stringify({ start, files, ranged, bundle: { path: "eager.bin", size: bundle.length, hash: createHash("sha256").update(bundle).digest("hex").slice(0, 16) } }, null, 0));
|
||||
console.log(`${files.length} files, ${(total / 1048576).toFixed(1)} MB eager; ${ranged.length} ranged`);
|
||||
60
tools/make-turkish-gxt.py
Normal file
60
tools/make-turkish-gxt.py
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
# Builds text/turkish.gxt: the Turkish text of the Gta Turk City mod (by Serdar "radreSword" Kilic),
|
||||
# with the keys it lacks (settings this engine added) taken from the game's own american.gxt.
|
||||
# Usage: python tools/make-turkish-gxt.py <mod american.gxt> <game american.gxt> <output>
|
||||
import struct, sys
|
||||
|
||||
def read(path):
|
||||
d = open(path, 'rb').read()
|
||||
assert d[:4] == b'TABL', path
|
||||
n = struct.unpack('<I', d[4:8])[0] // 12
|
||||
out = {}
|
||||
for i in range(n):
|
||||
name = d[8 + i * 12:16 + i * 12]
|
||||
off = struct.unpack('<I', d[16 + i * 12:20 + i * 12])[0]
|
||||
p = off + (8 if i else 0)
|
||||
assert d[p:p + 4] == b'TKEY', name
|
||||
size = struct.unpack('<I', d[p + 4:p + 8])[0]
|
||||
keys = p + 8
|
||||
data = keys + size + 8
|
||||
entries = {}
|
||||
for k in range(size // 12):
|
||||
o = struct.unpack('<I', d[keys + k * 12:keys + k * 12 + 4])[0]
|
||||
key = d[keys + k * 12 + 4:keys + k * 12 + 12]
|
||||
q = e = data + o
|
||||
while d[e:e + 2] != b'\0\0':
|
||||
e += 2
|
||||
entries[key] = d[q:e]
|
||||
out[name] = entries
|
||||
return out
|
||||
|
||||
def write(path, tables):
|
||||
names = [n for n in tables if n.rstrip(b'\0') == b'MAIN'] + sorted(n for n in tables if n.rstrip(b'\0') != b'MAIN')
|
||||
body = bytearray()
|
||||
start = 8 + 12 * len(names)
|
||||
index = bytearray()
|
||||
for i, name in enumerate(names):
|
||||
offset = start + len(body)
|
||||
index += name + struct.pack('<I', offset)
|
||||
if i:
|
||||
body += name
|
||||
keys, text = bytearray(), bytearray()
|
||||
for key in sorted(tables[name]):
|
||||
keys += struct.pack('<I', len(text)) + key
|
||||
text += tables[name][key] + b'\0\0'
|
||||
body += b'TKEY' + struct.pack('<I', len(keys)) + keys + b'TDAT' + struct.pack('<I', len(text)) + text
|
||||
if len(body) % 4:
|
||||
body += b'\0' * (4 - len(body) % 4)
|
||||
open(path, 'wb').write(b'TABL' + struct.pack('<I', len(index)) + index + body)
|
||||
|
||||
mod, game = read(sys.argv[1]), read(sys.argv[2])
|
||||
added = 0
|
||||
for name, entries in game.items():
|
||||
target = mod.setdefault(name, {})
|
||||
for key, value in entries.items():
|
||||
if key not in target:
|
||||
target[key] = value
|
||||
added += 1
|
||||
write(sys.argv[3], mod)
|
||||
check = read(sys.argv[3])
|
||||
assert check.keys() == mod.keys() and all(check[n] == mod[n] for n in mod)
|
||||
print(f'{sum(len(t) for t in mod.values())} keys, {added} taken from the game')
|
||||
23
tools/map-icons.ts
Normal file
23
tools/map-icons.ts
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
// Reads every map icon the game's own script can place (data/main.scm) and writes online/mapicons.json,
|
||||
// so the online map shows all locations although missions do not run. Usage: bun tools/map-icons.ts <game dir>
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
const dir = process.argv[2];
|
||||
if (!dir) throw new Error("usage: bun tools/map-icons.ts <game dir>");
|
||||
const d = readFileSync(`${dir}/data/main.scm`);
|
||||
const OPS = new Set([0x02a7, 0x02a8, 0x04ce, 0x0570]);
|
||||
const seen = new Map<string, { sprite: number; x: number; y: number; z: number }>();
|
||||
for (let i = 0; i + 24 < d.length; i++) {
|
||||
if (!OPS.has(d.readUInt16LE(i))) continue;
|
||||
if (d[i + 2] !== 6 || d[i + 7] !== 6 || d[i + 12] !== 6) continue;
|
||||
const t = d[i + 17];
|
||||
const sprite = t === 4 ? d.readInt8(i + 18) : t === 5 ? d.readInt16LE(i + 18) : t === 1 ? d.readInt32LE(i + 18) : -1;
|
||||
if (sprite <= 0 || sprite > 60) continue;
|
||||
const [x, y, z] = [d.readFloatLE(i + 3), d.readFloatLE(i + 8), d.readFloatLE(i + 13)];
|
||||
if (Math.abs(x) > 3000 || Math.abs(y) > 3000) continue;
|
||||
seen.set(`${sprite}:${Math.round(x)}:${Math.round(y)}`, { sprite, x: +x.toFixed(1), y: +y.toFixed(1), z: +z.toFixed(1) });
|
||||
}
|
||||
const icons = [...seen.values()].sort((a, b) => a.sprite - b.sprite);
|
||||
writeFileSync(`${dir}/online/mapicons.json`, JSON.stringify({ icons }));
|
||||
const count: Record<number, number> = {};
|
||||
for (const c of icons) count[c.sprite] = (count[c.sprite] || 0) + 1;
|
||||
console.log(icons.length, JSON.stringify(count));
|
||||
80
tools/mobile-icons.py
Normal file
80
tools/mobile-icons.py
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
#!/usr/bin/env python3
|
||||
# Turns the mobile version's HUD texture database (texdb/hud.dxt.*) into PNG files.
|
||||
# Usage: python tools/mobile-icons.py <dir with hud.txt, hud.dxt.toc, hud.dxt.dat> <output dir>
|
||||
import os, re, struct, sys
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
src, out = sys.argv[1], sys.argv[2]
|
||||
os.makedirs(out, exist_ok=True)
|
||||
names = re.findall(r'^"([^"]+)"', open(f'{src}/hud.txt', encoding='latin1').read(), re.M)
|
||||
toc = struct.unpack(f'<{os.path.getsize(src + "/hud.dxt.toc") // 4}I', open(f'{src}/hud.dxt.toc', 'rb').read())[1:]
|
||||
dat = open(f'{src}/hud.dxt.dat', 'rb').read()
|
||||
print(len(names), 'names', len(toc), 'offsets')
|
||||
|
||||
|
||||
def c565(c):
|
||||
return np.array([((c >> 11) & 31) * 255 // 31, ((c >> 5) & 63) * 255 // 63, (c & 31) * 255 // 31], dtype=np.int32)
|
||||
|
||||
|
||||
def colour_block(b, opaque_only):
|
||||
c0, c1, bits = struct.unpack('<HHI', b)
|
||||
p = [c565(c0), c565(c1)]
|
||||
alpha = [255, 255, 255, 255]
|
||||
if c0 > c1 or opaque_only:
|
||||
p += [(2 * p[0] + p[1]) // 3, (p[0] + 2 * p[1]) // 3]
|
||||
else:
|
||||
p += [(p[0] + p[1]) // 2, np.zeros(3, dtype=np.int32)]
|
||||
alpha[3] = 0
|
||||
px = np.zeros((4, 4, 4), dtype=np.uint8)
|
||||
for i in range(16):
|
||||
k = (bits >> (2 * i)) & 3
|
||||
px[i // 4, i % 4, :3] = p[k]
|
||||
px[i // 4, i % 4, 3] = alpha[k]
|
||||
return px
|
||||
|
||||
|
||||
def alpha5(b):
|
||||
a0, a1 = b[0], b[1]
|
||||
bits = int.from_bytes(b[2:8], 'little')
|
||||
t = [a0, a1]
|
||||
if a0 > a1:
|
||||
t += [((7 - i) * a0 + i * a1) // 7 for i in range(1, 7)]
|
||||
else:
|
||||
t += [((5 - i) * a0 + i * a1) // 5 for i in range(1, 5)] + [0, 255]
|
||||
return np.array([t[(bits >> (3 * i)) & 7] for i in range(16)], dtype=np.uint8).reshape(4, 4)
|
||||
|
||||
|
||||
def decode(kind, w, h, d):
|
||||
img = np.zeros((h, w, 4), dtype=np.uint8)
|
||||
size = 8 if kind in (0x83f0, 0x83f1) else 16
|
||||
at = 0
|
||||
for y in range(0, h, 4):
|
||||
for x in range(0, w, 4):
|
||||
if kind in (0x83f0, 0x83f1):
|
||||
px = colour_block(d[at:at + 8], False)
|
||||
elif kind == 0x83f2:
|
||||
px = colour_block(d[at + 8:at + 16], True)
|
||||
bits = int.from_bytes(d[at:at + 8], 'little')
|
||||
px[:, :, 3] = np.array([((bits >> (4 * i)) & 15) * 17 for i in range(16)], dtype=np.uint8).reshape(4, 4)
|
||||
else:
|
||||
px = colour_block(d[at + 8:at + 16], True)
|
||||
px[:, :, 3] = alpha5(d[at:at + 8])
|
||||
at += size
|
||||
img[y:y + 4, x:x + 4] = px[:min(4, h - y), :min(4, w - x)]
|
||||
return img
|
||||
|
||||
|
||||
done = 0
|
||||
kinds = {}
|
||||
for name, off in zip(names, toc):
|
||||
if off == 0xffffffff:
|
||||
continue
|
||||
_, kind, w, h = struct.unpack('<HHHH', dat[off:off + 8])
|
||||
h &= 0x7fff
|
||||
kinds[hex(kind)] = kinds.get(hex(kind), 0) + 1
|
||||
if kind not in (0x83f0, 0x83f1, 0x83f2, 0x83f3) or not w or not h or w & 3 or h & 3:
|
||||
continue
|
||||
Image.fromarray(decode(kind, w, h, dat[off + 8:]), 'RGBA').save(f'{out}/{name}.png')
|
||||
done += 1
|
||||
print('saved', done, 'formats', kinds)
|
||||
58
tools/online-icons.py
Normal file
58
tools/online-icons.py
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
#!/usr/bin/env python3
|
||||
# Puts the mobile game's pictures the page uses into <game dir>/online/icons, from the output of mobile-icons.py.
|
||||
# Button pictures keep their name, weapons become w<type>.png, and the two buttons the game has no picture for
|
||||
# are made from its own parts. Usage: python tools/online-icons.py <mobile icons dir> <game dir>
|
||||
import json, os, re, struct, sys
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
src, game = sys.argv[1], sys.argv[2]
|
||||
out = f'{game}/online/icons'
|
||||
os.makedirs(out, exist_ok=True)
|
||||
menu = json.load(open(os.path.join(os.path.dirname(__file__), '../gamefiles/online/menu.json'), encoding='utf-8'))
|
||||
|
||||
hud = lambda name: Image.open(f'{src}/hud_{name}.png').convert('RGBA')
|
||||
names = {b['icon'] for b in menu['touch']['buttons'] if 'icon' in b and 'parts' not in b} | {'circle', 'analognub'}
|
||||
for name in names:
|
||||
hud(name).save(f'{out}/{name}.png')
|
||||
for w in menu['weapons']:
|
||||
hud(w['icon']).save(f'{out}/w{w["type"]}.png')
|
||||
for b in menu['touch']['buttons']:
|
||||
if 'parts' not in b:
|
||||
continue
|
||||
base = hud(b['parts'][0])
|
||||
mark = hud(b['parts'][1])
|
||||
mark.thumbnail((base.width * 11 // 20, base.height * 11 // 20))
|
||||
base.alpha_composite(mark, ((base.width - mark.width) // 2, (base.height - mark.height) // 2))
|
||||
base.save(f'{out}/{b["icon"]}.png')
|
||||
|
||||
|
||||
# The station logos are in the PC game's menu textures: DXT3, 128 x 128.
|
||||
def c565(c):
|
||||
return np.array([((c >> 11) & 31) * 255 // 31, ((c >> 5) & 63) * 255 // 63, (c & 31) * 255 // 31])
|
||||
|
||||
|
||||
def dxt3(d, w, h):
|
||||
img = np.zeros((h, w, 4), np.uint8)
|
||||
at = 0
|
||||
for y in range(0, h, 4):
|
||||
for x in range(0, w, 4):
|
||||
alpha = int.from_bytes(d[at:at + 8], 'little')
|
||||
c0, c1, bits = struct.unpack('<HHI', d[at + 8:at + 16])
|
||||
p = [c565(c0), c565(c1)]
|
||||
p += [(2 * p[0] + p[1]) // 3, (p[0] + 2 * p[1]) // 3]
|
||||
for i in range(16):
|
||||
img[y + i // 4, x + i % 4, :3] = p[(bits >> (2 * i)) & 3]
|
||||
img[y + i // 4, x + i % 4, 3] = ((alpha >> (4 * i)) & 15) * 17
|
||||
at += 16
|
||||
return Image.fromarray(img, 'RGBA')
|
||||
|
||||
|
||||
txd = open(f'{game}/models/fronten2.txd', 'rb').read()
|
||||
stations = {r['icon']: r['station'] for r in menu['radio'] if 'icon' in r}
|
||||
for m in re.finditer(rb'\x15\x00\x00\x00', txd):
|
||||
s = m.start() + 24
|
||||
name = txd[s + 8:s + 40].split(b'\0')[0].decode('latin1')
|
||||
if name in stations:
|
||||
dxt3(txd[s + 92:s + 92 + 128 * 128], 128, 128).save(f'{out}/r{stations[name]}.png')
|
||||
print(len(os.listdir(out)), 'pictures')
|
||||
38
tools/readme-shots.ts
Normal file
38
tools/readme-shots.ts
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
// Takes the README pictures from a real two-player session: headless, muted, local game server only.
|
||||
// Needs: bun tools/serve.ts web/dist <game dir> 8790 and bun server/main.ts on 8791.
|
||||
import { chromium } from "playwright-core";
|
||||
import { mkdirSync } from "node:fs";
|
||||
const out = "docs/shots";
|
||||
mkdirSync(out, { recursive: true });
|
||||
const url = "http://127.0.0.1:8790/?mute=1&server=ws://127.0.0.1:8791/ws";
|
||||
const b = await chromium.launch({ channel: "chrome", headless: true, args: ["--mute-audio"] });
|
||||
async function player(name: string) {
|
||||
const c = await b.newContext({ viewport: { width: 1280, height: 720 } });
|
||||
await c.addInitScript((n) => { try { localStorage.setItem("vcNamed", "1"); localStorage.setItem("vcName", n); } catch (e) {} }, name);
|
||||
const p = await c.newPage();
|
||||
await p.goto(url);
|
||||
await p.waitForFunction(() => (window as any).vcPlaying, null, { timeout: 240000, polling: 500 });
|
||||
return p;
|
||||
}
|
||||
const wait = (s: number) => new Promise((r) => setTimeout(r, s * 1000));
|
||||
const shot = (p: any, name: string) => p.screenshot({ path: `${out}/${name}.jpg`, type: "jpeg", quality: 82, timeout: 90000 });
|
||||
const cmd = (p: any, c: string) => p.evaluate((x: string) => { const M = (window as any).Module; (M.vcCmds || (M.vcCmds = [])).push(x); }, c);
|
||||
const a = await player("crt"), other = await player("tommy");
|
||||
await wait(15);
|
||||
await shot(a, "players");
|
||||
await a.keyboard.press("b");
|
||||
await wait(2);
|
||||
await shot(a, "vehicles");
|
||||
await a.keyboard.press("Escape");
|
||||
await wait(1);
|
||||
await a.keyboard.down("q");
|
||||
await wait(2);
|
||||
await shot(a, "wheel");
|
||||
await a.keyboard.up("q");
|
||||
await wait(1);
|
||||
await cmd(other, "car infernus");
|
||||
await cmd(a, "car cheetah");
|
||||
await wait(8);
|
||||
await shot(a, "cars");
|
||||
await Promise.race([b.close(), wait(5)]);
|
||||
process.exit(0);
|
||||
42
tools/serve.ts
Normal file
42
tools/serve.ts
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
// Local dev server: the web build at / and a game folder at /data/, with HTTP range
|
||||
// requests and case-insensitive paths (the browser asks for lower-case names).
|
||||
// Usage: bun tools/serve.ts <dist dir> <game dir> [port]
|
||||
import { join } from "node:path";
|
||||
import { readdirSync, existsSync, statSync } from "node:fs";
|
||||
|
||||
const [dist, gameDir, port = "8790"] = process.argv.slice(2);
|
||||
if (!dist || !gameDir) throw new Error("usage: bun tools/serve.ts <dist dir> <game dir> [port]");
|
||||
|
||||
// Finds "models/gta3.img" as "MODELS/GTA3.IMG" or any other casing on disk.
|
||||
function resolveCase(root: string, rel: string): string | null {
|
||||
let dir = root;
|
||||
for (const part of rel.split("/").filter(Boolean)) {
|
||||
if (part === "..") return null;
|
||||
const hit = readdirSync(dir).find((n) => n.toLowerCase() === part.toLowerCase());
|
||||
if (!hit) return null;
|
||||
dir = join(dir, hit);
|
||||
}
|
||||
return existsSync(dir) && statSync(dir).isFile() ? dir : null;
|
||||
}
|
||||
|
||||
Bun.serve({
|
||||
port: Number(port),
|
||||
hostname: "127.0.0.1",
|
||||
fetch(req) {
|
||||
const path = decodeURIComponent(new URL(req.url).pathname);
|
||||
const file = path.startsWith("/data/")
|
||||
? resolveCase(gameDir, path.slice(6))
|
||||
: resolveCase(dist, path === "/" ? "index.html" : path.slice(1));
|
||||
if (!file) return new Response("not found", { status: 404 });
|
||||
const body = Bun.file(file);
|
||||
const range = req.headers.get("range")?.match(/bytes=(\d+)-(\d*)/);
|
||||
if (!range) return new Response(body, { headers: { "Accept-Ranges": "bytes" } });
|
||||
const start = Number(range[1]);
|
||||
const end = range[2] ? Math.min(Number(range[2]), body.size - 1) : body.size - 1;
|
||||
return new Response(body.slice(start, end + 1), {
|
||||
status: 206,
|
||||
headers: { "Content-Range": `bytes ${start}-${end}/${body.size}`, "Accept-Ranges": "bytes" },
|
||||
});
|
||||
},
|
||||
});
|
||||
console.log(`serving on http://127.0.0.1:${port}`);
|
||||
40
tools/stage-site.ts
Normal file
40
tools/stage-site.ts
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
// Builds build/site: the web build at / and exactly the game files the manifest lists at /data/,
|
||||
// under lower-case names (the browser asks for lower-case paths, a Linux server is case-sensitive).
|
||||
// Usage: bun tools/stage-site.ts <dist dir> <game dir> [out dir]
|
||||
import { join, dirname } from "node:path";
|
||||
import { readdirSync, mkdirSync, copyFileSync, existsSync, statSync, rmSync, cpSync } from "node:fs";
|
||||
|
||||
const [dist, gameDir, out = "build/site"] = process.argv.slice(2);
|
||||
if (!dist || !gameDir) throw new Error("usage: bun tools/stage-site.ts <dist dir> <game dir> [out dir]");
|
||||
|
||||
function resolveCase(root: string, rel: string): string | null {
|
||||
let dir = root;
|
||||
for (const part of rel.split("/").filter(Boolean)) {
|
||||
const hit = readdirSync(dir).find((n) => n.toLowerCase() === part.toLowerCase());
|
||||
if (!hit) return null;
|
||||
dir = join(dir, hit);
|
||||
}
|
||||
return existsSync(dir) && statSync(dir).isFile() ? dir : null;
|
||||
}
|
||||
|
||||
rmSync(out, { recursive: true, force: true });
|
||||
cpSync(dist, out, { recursive: true });
|
||||
|
||||
const manifestPath = join(gameDir, "manifest.json");
|
||||
const manifest = await Bun.file(manifestPath).json();
|
||||
mkdirSync(join(out, "data"), { recursive: true });
|
||||
copyFileSync(manifestPath, join(out, "data", "manifest.json"));
|
||||
copyFileSync(join(gameDir, "eager.bin"), join(out, "data", "eager.bin"));
|
||||
|
||||
let bytes = 0, count = 0, missing: string[] = [];
|
||||
for (const f of [...manifest.files, ...manifest.ranged] as { path: string }[]) {
|
||||
const src = resolveCase(gameDir, f.path);
|
||||
if (!src) { missing.push(f.path); continue; }
|
||||
const dst = join(out, "data", f.path.toLowerCase());
|
||||
mkdirSync(dirname(dst), { recursive: true });
|
||||
copyFileSync(src, dst);
|
||||
bytes += statSync(dst).size;
|
||||
count++;
|
||||
}
|
||||
console.log(`${count} files, ${(bytes / 1048576).toFixed(0)} MB staged in ${out}`);
|
||||
if (missing.length) { console.error("missing:", missing.slice(0, 10)); process.exit(1); }
|
||||
8
tools/stamp-index.sh
Normal file
8
tools/stamp-index.sh
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
#!/bin/bash
|
||||
# Writes build/index.stamped.html: the page with the version of the engine in web/dist.
|
||||
set -e
|
||||
V=$(cat web/dist/revc.js web/dist/revc.wasm web/dist/revc-jspi.js web/dist/revc-jspi.wasm | sha256sum | cut -c1-12)
|
||||
# Apache prefers these over the originals, so they must always match: upload them with the engine.
|
||||
for f in revc.js revc.wasm revc-jspi.js revc-jspi.wasm; do brotli -f -q 11 -k "web/dist/$f" -o "web/dist/$f.br"; done
|
||||
sed "s/__ENGINE_V__/$V/g" web/shell/index.html > build/index.stamped.html
|
||||
echo "$V"
|
||||
39
tools/thumbs.ts
Normal file
39
tools/thumbs.ts
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
// Takes the vehicle pictures for the menu from the running game (photo mode), for every vehicle in menu.json.
|
||||
// Needs: bun tools/serve.ts web/dist <game dir> 8790 and bun server/main.ts on 8791.
|
||||
// Usage: bun tools/thumbs.ts <game dir>
|
||||
import { chromium } from "playwright-core";
|
||||
import { mkdirSync, readFileSync } from "node:fs";
|
||||
const dir = process.argv[2];
|
||||
if (!dir) throw new Error("usage: bun tools/thumbs.ts <game dir>");
|
||||
const { cars, weapons } = JSON.parse(readFileSync(`${dir}/online/menu.json`, "utf8"));
|
||||
const out = `${dir}/online/thumbs`;
|
||||
mkdirSync(out, { recursive: true });
|
||||
const w = 1600, h = 900, k = w / 1280;
|
||||
const b = await chromium.launch({ channel: "chrome", headless: true, args: ["--mute-audio"] });
|
||||
const p = await (await b.newContext({ viewport: { width: w, height: h } })).newPage();
|
||||
p.on("console", (m) => { if (/error|abort|cannot|failed/i.test(m.text())) console.log("console:", m.text().slice(0, 200)); });
|
||||
p.on("pageerror", (e) => console.log("pageerror", String(e).slice(0, 300)));
|
||||
await p.addInitScript(() => { try { localStorage.setItem("vcNamed", "1"); } catch (e) {} });
|
||||
await p.goto("http://127.0.0.1:8790/?mute=1&server=ws://127.0.0.1:8791/ws");
|
||||
// Photo mode wears the engine out after a few dozen vehicles: a fresh page for each batch.
|
||||
async function ready() {
|
||||
await p.waitForFunction(() => (window as any).vcPlaying, null, { timeout: 180000, polling: 500 });
|
||||
await p.addStyleTag({ content: ".ui { display: none !important; }" });
|
||||
await new Promise((r) => setTimeout(r, 6000));
|
||||
}
|
||||
await ready();
|
||||
let shot = 0;
|
||||
for (const g of weapons) {
|
||||
await p.evaluate((t) => { const M = (window as any).Module; (M.vcCmds || (M.vcCmds = [])).push("weapon " + t); }, g.type);
|
||||
await new Promise((r) => setTimeout(r, 1200));
|
||||
await p.screenshot({ path: `${out}/w${g.type}.jpg`, type: "jpeg", quality: 85, timeout: 90000, clip: { x: 1132 * k, y: 38 * k, width: 96 * k, height: 96 * k } });
|
||||
}
|
||||
for (const c of cars) {
|
||||
if (shot++ % 12 === 0) { await p.reload(); await ready(); }
|
||||
await p.evaluate((m) => { const M = (window as any).Module; (M.vcCmds || (M.vcCmds = [])).push("photo " + m); }, c.model);
|
||||
await new Promise((r) => setTimeout(r, 2500));
|
||||
await p.screenshot({ path: `${out}/${c.model}.jpg`, type: "jpeg", quality: 80, timeout: 90000, clip: c.bike ? { x: 531 * k, y: 280 * k, width: 220 * k, height: 124 * k } : { x: 451 * k, y: 268 * k, width: 330 * k, height: 186 * k } });
|
||||
console.log(c.model);
|
||||
}
|
||||
await Promise.race([b.close(), new Promise((r) => setTimeout(r, 4000))]);
|
||||
process.exit(0);
|
||||
24
tools/trace-start.ts
Normal file
24
tools/trace-start.ts
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
// Records what the game reads from the world image at the spawn point and writes web/start-ranges.json.
|
||||
// Headless, muted, and not connected to the game server. Usage: bun tools/trace-start.ts <page url>
|
||||
import { chromium } from "playwright-core";
|
||||
import { join } from "node:path";
|
||||
const url = process.argv[2];
|
||||
const br = await chromium.launch({ channel: "chrome", headless: true, args: ["--mute-audio"] });
|
||||
const p = await (await br.newContext({ viewport: { width: 1280, height: 720 } })).newPage();
|
||||
await p.addInitScript(() => { try { localStorage.setItem("vcNamed", "1"); } catch (e) {} });
|
||||
await p.goto(`${url}?mute=1&imgdelay=900&readlog=1&server=ws://127.0.0.1:9/ws`);
|
||||
await p.waitForFunction(() => (window as any).vcPlaying, null, { timeout: 240000, polling: 500 });
|
||||
await p.waitForTimeout(30000); // the first seconds of play load what stands around the player
|
||||
const log: string[] = await p.evaluate(() => (window as any).Module.vcReadLog);
|
||||
await Promise.race([br.close(), new Promise((r) => setTimeout(r, 4000))]);
|
||||
const reads = log.map((l) => l.split(":").map(Number)).sort((a, b) => a[0] - b[0]);
|
||||
const ranges: number[][] = [];
|
||||
for (const [at, size] of reads) {
|
||||
const last = ranges[ranges.length - 1];
|
||||
if (last && at <= last[0] + last[1]) last[1] = Math.max(last[1], at + size - last[0]);
|
||||
else ranges.push([at, size]);
|
||||
}
|
||||
const total = ranges.reduce((n, r) => n + r[1], 0);
|
||||
await Bun.write(join(import.meta.dir, "../web/start-ranges.json"), JSON.stringify({ key: "models/gta3.img", ranges }));
|
||||
console.log(`${log.length} reads, ${ranges.length} ranges, ${(total / 1048576).toFixed(1)} MB`);
|
||||
process.exit(0);
|
||||
86
tools/webcheck.ts
Normal file
86
tools/webcheck.ts
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
// Plays the web build in a hidden, muted Chrome the way a player would (real key
|
||||
// events) and reports what happened: game states, frame stalls, audio level, errors.
|
||||
// Usage: bun tools/webcheck.ts [url] [--radio] [--shot out.png] [--log <regex>]
|
||||
import { chromium, type Page } from "playwright-core";
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const url = args.find((a) => a.startsWith("http")) ?? "http://127.0.0.1:8790/?mute=1";
|
||||
const shot = args.includes("--shot") ? args[args.indexOf("--shot") + 1] : null;
|
||||
const radio = args.includes("--radio");
|
||||
const dpr = args.includes("--dpr") ? Number(args[args.indexOf("--dpr") + 1]) : 1;
|
||||
const [vw, vh] = (args.includes("--size") ? args[args.indexOf("--size") + 1] : "1280x720").split("x").map(Number);
|
||||
const logFilter = args.includes("--log") ? new RegExp(args[args.indexOf("--log") + 1], "i") : null;
|
||||
|
||||
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
||||
const report: Record<string, unknown> = {};
|
||||
const errors: string[] = [];
|
||||
|
||||
async function waitLog(page: Page, re: RegExp, timeoutMs: number) {
|
||||
const start = Date.now();
|
||||
while (Date.now() - start < timeoutMs) {
|
||||
const hit = await page.evaluate((src) => (window as any).vcLog?.some((l: any) => new RegExp(src).test(l.text)) || (src.includes("GS_PLAYING_GAME") && (window as any).vcPlaying), re.source);
|
||||
if (hit) return Date.now() - start;
|
||||
await sleep(250);
|
||||
}
|
||||
const tail = await page.evaluate(() => (window as any).vcLog?.slice(-15).map((l: any) => l.text));
|
||||
throw new Error(`timed out waiting for ${re}\n${(tail ?? []).join("\n")}`);
|
||||
}
|
||||
|
||||
async function press(page: Page, key: string, holdMs = 150) {
|
||||
await page.keyboard.down(key);
|
||||
await sleep(holdMs);
|
||||
await page.keyboard.up(key);
|
||||
await sleep(1000);
|
||||
}
|
||||
|
||||
// Longest gap between frames (ms) while `action` runs.
|
||||
async function measureStall(page: Page, action: () => Promise<void>) {
|
||||
await page.evaluate(() => {
|
||||
const gl = (document.getElementById("canvas") as HTMLCanvasElement).getContext("webgl2")!;
|
||||
const w = window as any;
|
||||
w.vcFrames = [];
|
||||
if (!w.vcClearHooked) {
|
||||
const clear = gl.clear.bind(gl);
|
||||
gl.clear = (m: number) => { w.vcFrames.push(performance.now()); clear(m); };
|
||||
w.vcClearHooked = true;
|
||||
}
|
||||
});
|
||||
await action();
|
||||
return page.evaluate(() => {
|
||||
const f: number[] = (window as any).vcFrames;
|
||||
let worst = 0;
|
||||
for (let i = 1; i < f.length; i++) worst = Math.max(worst, f[i] - f[i - 1]);
|
||||
return { frames: f.length, worstGapMs: Math.round(worst) };
|
||||
});
|
||||
}
|
||||
|
||||
const browser = await chromium.launch({ channel: "chrome", headless: true, args: ["--mute-audio", "--autoplay-policy=no-user-gesture-required"] });
|
||||
try {
|
||||
const page = await browser.newPage({ viewport: { width: vw, height: vh }, deviceScaleFactor: dpr });
|
||||
|
||||
page.on("pageerror", (e) => errors.push(String(e.stack ?? e).slice(0, 1500)));
|
||||
await page.goto(url);
|
||||
report.loadMs = await waitLog(page, /GS_PLAYING_GAME/, 90000);
|
||||
await sleep(Number(process.env.VC_WAIT ?? 4000));
|
||||
if (radio) {
|
||||
await press(page, "f", 300);
|
||||
await sleep(4000);
|
||||
const switches = [];
|
||||
for (let i = 0; i < 4; i++) switches.push(await measureStall(page, async () => { await press(page, "Insert"); await sleep(2500); }));
|
||||
report.radioSwitches = switches;
|
||||
}
|
||||
if (args.includes("--pause")) { await press(page, "Escape", 300); await sleep(1500); }
|
||||
report.idle = await measureStall(page, () => sleep(3000));
|
||||
report.audioLevel = await page.evaluate(() => (window as any).vcAudioLevel?.() ?? null);
|
||||
report.audioFiles = await page.evaluate(() => [...new Set(performance.getEntriesByType("resource")
|
||||
.map((e) => e.name).filter((n) => /\/audio\//i.test(n)).map((n) => n.split("/").pop()))]);
|
||||
if (shot) await page.screenshot({ path: shot });
|
||||
if (logFilter) report.log = await page.evaluate((src) => (window as any).vcLog.filter((l: any) => new RegExp(src, "i").test(l.text)).slice(-30).map((l: any) => l.text), logFilter.source);
|
||||
report.errors = errors;
|
||||
} catch (e) {
|
||||
report.failure = String(e).slice(0, 3000);
|
||||
report.errors = errors;
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
console.log(JSON.stringify(report, null, 1));
|
||||
Loading…
Add table
Add a link
Reference in a new issue