feat: add polished loading overlay with progress bar

Replace the bare "Please wait... Loading webassembly" text with a
branded loading screen featuring a Rosebud logo (base64-embedded),
rotating theme-park phrases, gradient progress bar, and phase labels
that track actual engine/asset loading stages.

- rosebud/static/index.html: dark overlay with CSS animations, JS
  helpers (updateLoadingBar, showLoadingError, dismissOverlay)
- rosebud/static/index.js: fork copy of upstream index.js wired to
  report 14 progress stages and 6 error paths through the overlay
- .claude/verification.md: project-specific verification instructions

Key fixes during development:
- Canvas must be visible before callMain() for WebGL init
- Progress helpers use window scope so file-level functions can call them
- Body flex layout reset on dismiss to prevent canvas offset

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Mike LiuandClaude Opus 4.6 committed 2026-03-03 23:27:25 +00:00
1 parent 1d6534f3b2
commit 54048c6bac
3 files changed
+538 -27

No files matched your search

+68
View File
@@ -0,0 +1,68 @@
# OpenRCT2-Web Verification
## Build Before Verify
Visual changes must be tested against the full game, not standalone HTML. Always ensure `build/www/` has the latest overlay before serving.
```dot
digraph build {
"What changed?" [shape=diamond];
"C++ / CMake / deps" [shape=box];
"rosebud/static/ only" [shape=box];
"Full WASM build" [shape=box];
"Re-overlay only" [shape=box];
"Serve build/www" [shape=box];
"What changed?" -> "C++ / CMake / deps" [label="C++/WASM"];
"What changed?" -> "rosebud/static/ only" [label="HTML/CSS/JS"];
"C++ / CMake / deps" -> "Full WASM build";
"rosebud/static/ only" -> "Re-overlay only";
"Full WASM build" -> "Serve build/www";
"Re-overlay only" -> "Serve build/www";
}
```
### Re-overlay (fast — for rosebud/static/ changes only)
```bash
cp -r rosebud/static/* build/www/
```
Requires a previous `build/www/` from a prior WASM build. If `build/www/` doesn't exist, do a full build first.
### Full WASM build (slow — for C++/CMake/dependency changes)
```bash
rosebud/docker-build
```
This automatically overlays `rosebud/static/` at the end.
## Serve Command
Always use the project server — never bare `python3 -m http.server`:
```bash
python3 rosebud/serve.py --host 0.0.0.0 --port 8000
```
Default directory is `build/www/`. Sets required COOP/COEP/CORP headers for SharedArrayBuffer.
## By Change Type
| Change type | Build step | Then |
|-------------|------------|------|
| **Loading overlay / UI** | Re-overlay | Serve, Playwright screenshot, test JS API |
| **index.js wiring** | `node --check rosebud/static/index.js` + re-overlay | Serve and verify in browser |
| **C++ / WASM** | Full build via `rosebud/docker-build` | Serve `build/www/` |
| **Asset packaging** | Full build | Verify all three zips load |
## Scope Your Claims
- **Overlay-only test**: State "overlay renders correctly; full game load not tested (requires WASM build)"
- **Full build test**: State "game loads end-to-end through loading screen"
- Never say "all checks pass" when only testing a subset
## Visual Verification
For any CSS/HTML/UI change: `playwright-capture` then `visual-judge`. Code review alone is not verification.
+163 -27
View File
@@ -1,31 +1,167 @@
<!DOCTYPE html>
<html>
<head>
<title>OpenRCT2</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<script src="https://cdn.jsdelivr.net/npm/jszip@3.10.1/dist/jszip.min.js" crossorigin=anonymous></script>
<style>
* { padding: 0; margin: 0; }
body { overflow: hidden; }
canvas {
display: block;
margin: 0 auto;
position: fixed;
left: 0;
right: 0;
width: 100%;
height: 100%;
touch-action: none;
}
</style>
<script src="index.js"></script>
</head>
<body>
<p id="loadingWebassembly">Please wait... Loading webassembly</p>
<div id="beforeLoad" style="display:none;">
<p id="statusMsg">Please select your RCT2 assets (zip file):</p>
<input type="file" id="selectFile"></input>
<head>
<title>OpenRCT2</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<script src="https://cdn.jsdelivr.net/npm/jszip@3.10.1/dist/jszip.min.js" crossorigin=anonymous></script>
<style>
* { padding: 0; margin: 0; }
body {
background: #000;
display: flex;
justify-content: center;
align-items: center;
overflow: hidden;
}
#loading-overlay {
position: fixed;
inset: 0;
z-index: 1000;
background: #1a1a2e;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
transition: opacity 0.5s ease;
}
#loading-overlay.fade-out {
opacity: 0;
pointer-events: none;
}
#loading-logo {
width: 96px;
height: 96px;
margin-bottom: 24px;
animation: pulse 2s ease-in-out infinite;
}
@keyframes pulse {
0%, 100% { transform: scale(1); filter: drop-shadow(0 0 8px rgba(232, 121, 121, 0.3)); }
50% { transform: scale(1.06); filter: drop-shadow(0 0 16px rgba(232, 121, 121, 0.6)); }
}
#loading-message {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
font-size: 16px;
font-style: italic;
color: #c8b8a0;
height: 24px;
margin-bottom: 24px;
transition: opacity 0.4s ease;
}
#loading-bar-track {
width: 320px;
height: 14px;
background: #2a2a4a;
border-radius: 7px;
box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.3);
overflow: hidden;
}
#loading-bar-fill {
width: 0%;
height: 100%;
background: linear-gradient(90deg, #e87979, #e8a079);
border-radius: 7px;
transition: width 0.3s ease;
}
#loading-phase {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
font-size: 13px;
color: #8a8aaa;
margin-top: 12px;
}
canvas {
display: block;
margin: 0 auto;
position: fixed;
left: 0;
right: 0;
width: 100%;
height: 100%;
touch-action: none;
}
</style>
</head>
<body>
<div id="loading-overlay">
<img id="loading-logo" alt="Rosebud"
src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAhGVYSWZNTQAqAAAACAAFARIAAwAAAAEAAQAAARoABQAAAAEAAABKARsABQAAAAEAAABSASgAAwAAAAEAAgAAh2kABAAAAAEAAABaAAAAAAAAAEgAAAABAAAASAAAAAEAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAgKADAAQAAAABAAAAgAAAAAC7tGl0AAAACXBIWXMAAAsTAAALEwEAmpwYAAACymlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG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iOW+eyos8JM14C4Bhfx75BAw+BcilJ+l6PraTz7YoVT7G34dPC2nv3UMdaopw+NeeUznotuQh4L54RJVEPJmegi3vFoX2gTMsZGTKd7eZxoqDwzAjzNN2lQUjdnkeM+0hxgikrKePmF7Cq/9KU7GL77//ya+2DWb36OdsHQGXvXUi0rbPmzRiIzMWLine truncated
<div id="loading-message">Building the perfect roller coaster...</div>
<div id="loading-bar-track">
<div id="loading-bar-fill"></div>
</div>
<canvas id="canvas" style="display:none;"></canvas>
</body>
<div id="loading-phase">Initializing...</div>
</div>
<canvas id="canvas" style="display:none;"></canvas>
<script>
(() => {
const phrases = [
"Building the perfect roller coaster...",
"Guests are lining up at the entrance...",
"Hiring handymen and mechanics...",
"Testing the log flume for safety...",
"Rosie is landscaping your park...",
"Convincing Mr. Bones the ride never ends...",
"Placing benches near the nausea zones..."
];
let phraseIndex = 0;
const msgEl = document.getElementById("loading-message");
const phraseInterval = setInterval(() => {
msgEl.style.opacity = "0";
setTimeout(() => {
phraseIndex = (phraseIndex + 1) % phrases.length;
msgEl.textContent = phrases[phraseIndex];
msgEl.style.opacity = "1";
}, 400);
}, 4000);
window._loadingPhraseInterval = phraseInterval;
window.updateLoadingBar = function(pct, phase) {
const fill = document.getElementById("loading-bar-fill");
const phaseEl = document.getElementById("loading-phase");
if (fill) fill.style.width = pct + "%";
if (phaseEl) phaseEl.textContent = phase;
};
window.showLoadingError = function(msg) {
clearInterval(phraseInterval);
const msgEl = document.getElementById("loading-message");
const track = document.getElementById("loading-bar-track");
const phaseEl = document.getElementById("loading-phase");
if (msgEl) {
msgEl.style.fontStyle = "normal";
msgEl.style.color = "#ffffff";
msgEl.style.height = "auto";
msgEl.textContent = msg;
msgEl.style.opacity = "1";
}
if (track) track.style.display = "none";
if (phaseEl) phaseEl.style.display = "none";
};
window.dismissOverlay = function() {
updateLoadingBar(100, "Opening the gates!");
clearInterval(phraseInterval);
// Canvas must be visible BEFORE callMain() — game needs
// non-zero dimensions when initializing its GL context.
const canvas = document.getElementById("canvas");
if (canvas) canvas.style.display = "";
// Reset body flex layout — it centers the overlay but shifts
// the fixed-position canvas off-screen by half the viewport.
document.body.style.display = "block";
setTimeout(() => {
const overlay = document.getElementById("loading-overlay");
if (overlay) {
overlay.classList.add("fade-out");
overlay.addEventListener("transitionend", () => {
overlay.remove();
});
}
}, 300);
};
})();
</script>
<script src="index.js"></script>
</body>
</html>
+307
View File
@@ -0,0 +1,307 @@
/*****************************************************************************
* Copyright (c) 2014-2025 OpenRCT2 developers
*
* For a complete list of all authors, please refer to contributors.md
* Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2
*
* OpenRCT2 is licensed under the GNU General Public License version 3.
*****************************************************************************/
(async () =>
{
// Globals so updateAssets() and other file-scope functions can use them.
window.setProgress = (pct, phase) => {
if (typeof updateLoadingBar === 'function') updateLoadingBar(pct, phase);
};
window.setError = (msg) => {
if (typeof showLoadingError === 'function') showLoadingError(msg);
else {
const el = document.getElementById("loadingWebassembly");
if (el) el.innerText = msg;
}
};
await new Promise(res => window.addEventListener("DOMContentLoaded", res));
if (!window.SharedArrayBuffer)
{
setError("Error! SharedArrayBuffer is not defined. This page required the CORP and COEP response headers.");
return;
}
if (!window.WebAssembly)
{
setError("Error! This page requires WebAssembly. Please upgrade your browser or enable WebAssembly support.");
return;
}
setProgress(5, "Loading game engine...");
let assets;
try
{
let req = await fetch("openrct2.zip");
if (!req.ok) {
throw new Error("Response is not ok!")
}
let data = await req.blob();
setProgress(15, "Unpacking game engine...");
let zip = new JSZip();
let contents = await zip.loadAsync(data);
assets = {
js: URL.createObjectURL(new Blob([await zip.file("openrct2.js").async("uint8array")], {type: 'application/json'})),
wasm: URL.createObjectURL(new Blob([await zip.file("openrct2.wasm").async("uint8array")], {type: 'application/wasm'}))
}
setProgress(25, "Loading game engine...");
}
catch(e)
{
assets = null;
console.warn("Failed to fetch openrct2.zip. Will pull not-compressed files", e);
}
await new Promise(resolve => {
const script = document.createElement("script");
script.src = assets === null ? "openrct2.js" : assets.js;
script.addEventListener("load", resolve);
script.addEventListener("error", (e) => {
setError("Error loading openrct2.js!");
console.error(e);
});
document.body.appendChild(script);
})
setProgress(30, "Initializing engine...");
window.Module = await window.OPENRCT2_WEB({
noInitialRun: true,
arguments: [],
preRun: [],
postRun: [],
canvas: document.getElementById("canvas"),
print: function(msg)
{
console.log(msg);
},
printErr: function(msg)
{
console.log(msg);
},
totalDependencies: 0,
monitorRunDependencies: () => {},
locateFile: function(fileName)
{
if (assets !== null && fileName === "openrct2.wasm")
{
return assets.wasm;
}
console.log("loading", fileName);
return fileName;
}
});
setProgress(35, "Mounting filesystems...");
Module.FS.mkdir("/persistent");
Module.FS.mount(Module.FS.filesystems.IDBFS, {autoPersist: true}, '/persistent');
Module.FS.mkdir("/RCT");
Module.FS.mount(Module.FS.filesystems.IDBFS, {autoPersist: true}, '/RCT');
Module.FS.mkdir("/OpenRCT2");
Module.FS.mount(Module.FS.filesystems.IDBFS, {autoPersist: true}, '/OpenRCT2');
await new Promise(res => Module.FS.syncfs(true, res));
setProgress(40, "Checking park assets...");
const assetsOK = await updateAssets();
if (!assetsOK)
{
return;
}
let changelog = "";
try {
const request = await fetch("https://api.github.com/repos/OpenRCT2/OpenRCT2/releases/latest");
const json = JSON.parse(await request.text());
changelog = json.body;
} catch(e) {
console.log("Failed to fetch changelog with error:", e);
}
Module.FS.writeFile("/OpenRCT2/changelog.txt", changelog);
setProgress(75, "Checking ride data...");
let filesFound = fileExists("/RCT/Data/ch.dat") && fileExists("/RCT/ObjData/BALLN.DAT");
if (!filesFound)
{
setProgress(80, "Downloading ride data...");
await extractDefaultRct2Data();
filesFound = fileExists("/RCT/Data/ch.dat");
if (!filesFound)
{
setError("Error! Could not auto-load RCT2 data. Place rct2-content.zip (containing Data/ch.dat and ObjData) next to index.html.");
return;
}
setProgress(90, "Ride data loaded");
}
setProgress(95, "Preparing your park...");
if (typeof dismissOverlay === 'function') {
dismissOverlay();
} else {
const loadEl = document.getElementById("loadingWebassembly");
if (loadEl) loadEl.remove();
Module.canvas.style.display = "";
}
Module.callMain(["--user-data-path=/persistent/", "--openrct2-data-path=/OpenRCT2/"]);
})();
async function updateAssets() {
let currentVersion = "";
try {
currentVersion = Module.FS.readFile("/OpenRCT2/version", {encoding: "utf8"});
console.log("Found asset version", currentVersion);
} catch(e) {
console.log("No asset version found");
};
let assetsVersion = "DEBUG";
try {
assetsVersion = Module.ccall("GetVersion", "string");
} catch(e) {
console.warn("Could not call 'GetVersion'! Is it added to EXPORTED_FUNCTIONS? Is ccall added to EXPORTED_RUNTIME_METHODS?");
};
// If key files are missing, force a refresh even when version matches.
const hasRequiredAssets = fileExists("/OpenRCT2/language/en-US.txt")
&& fileExists("/OpenRCT2/g2.dat")
&& fileExists("/OpenRCT2/object/official/footpath_surface/openrct2.footpath_surface.invisible.json")
&& fileExists("/OpenRCT2/sequence/openrct2.parkseq");
if (!hasRequiredAssets)
{
console.warn("OpenRCT2 data files are incomplete, forcing an asset refresh.");
currentVersion = "";
}
//Always pull assets on a debug build
if (currentVersion !== assetsVersion || assetsVersion.includes("DEBUG"))
{
console.log("Updating assets to", assetsVersion);
setProgress(45, "Downloading park assets...");
await clearDatabase("/OpenRCT2/");
// Fetch the assets.zip file
const response = await fetch("assets.zip");
if (!response.ok) {
if (response.status === 404) {
setError("Error! Assets file not found (404).");
} else {
setError(`Error! Failed to download assets (status: ${response.status}).`);
}
return false;
} else {
setProgress(65, "Unpacking park assets...");
}
await extractZip(await response.blob(), () => {
return "/OpenRCT2/";
});
setProgress(70, "Park assets ready");
Module.FS.writeFile("/OpenRCT2/version", assetsVersion.toString());
}
return true;
}
async function extractDefaultRct2Data() {
try {
const response = await fetch("rct2-content.zip");
if (!response.ok) {
console.warn(`Failed to fetch rct2-content.zip (status: ${response.status})`);
return false;
}
return await extractZip(await response.blob(), (zip) => {
if (zip !== null)
{
if (zip.file("Data/ch.dat") && zip.file("ObjData/BALLN.DAT"))
{
return "/RCT/";
}
if (zip.file("RCT/Data/ch.dat") && zip.file("RCT/ObjData/BALLN.DAT"))
{
return "/";
}
}
console.warn("rct2-content.zip must contain Data/ch.dat and ObjData/BALLN.DAT");
return false;
});
} catch (e) {
console.warn("Failed to auto-load rct2-content.zip", e);
return false;
}
}
async function extractZip(data, checkZip) {
let zip = new JSZip();
let contents;
try {
contents = await zip.loadAsync(data);
} catch(e) {
if (typeof checkZip === "function")
{
checkZip(null);
}
throw e;
}
let base = "/";
if (typeof checkZip === "function")
{
const cont = checkZip(contents);
if (cont === false) return false;
base = cont;
}
for (const k in contents.files) {
const entry = contents.files[k];
if (entry.dir)
{
try {
Module.FS.mkdir(base+k);
} catch(e) {}
}
else
{
Module.FS.writeFile(base+k, await entry.async("uint8array"));
}
}
return true;
}
async function clearDatabase(dir) {
await new Promise(res => Module.FS.syncfs(false, res));
const processFolder = (path) => {
let contents;
try {
contents = Module.FS.readdir(path);
} catch(e) {
return;
}
contents.forEach((entry) => {
if ([".", ".."].includes(entry)) return;
try {
Module.FS.readFile(path + entry);
Module.FS.unlink(path + entry);
} catch(e) {
processFolder(path + entry + "/");
}
})
if (path === dir) return;
try {
Module.FS.rmdir(path, {recursive: true});
} catch(e) {
console.log("Could not remove:", path);
}
}
processFolder(dir);
await new Promise(res => Module.FS.syncfs(false, res));
}
function fileExists(path) {
try {
Module.FS.readFile(path);
return true;
} catch(e) {};
return false;
}