Fix the web build: a wasm trap on integer % 0, and buttons that never fired

The web export reached the main menu and went no further. Two separate bugs,
one hiding the other.

BUTTONS NEVER FIRED. A browser on a phone delivers the touch DOWN and never
the release. IconButton emits `pressed` only on release, deliberately, so
that dragging off cancels - so on the web it never emitted at all, on every
button in the game. fire_on_press (default OS.has_feature("web")) completes
the press there instead, and does not latch, since nothing is coming to
unlatch it. The cost is drag-off-to-cancel, which every other platform keeps.

Measured on the device rather than guessed: an on-screen probe reported
`touch=1 mouse=1 held=y` after one tap - one down, one emulated mouse down,
the button latched through ordinary GUI routing, then nothing.

THE ENGINE THEN TRAPPED. With the button working, pressing Play loaded and
built Main.tscn and the whole engine stopped mid-frame, page still alive.
An error overlay in a custom HTML shell finally showed why:

    Uncaught RuntimeError: remainder by zero

An integer % 0. Wasm TRAPS on that; native builds silently tolerate it. So
the bug was equally present on Android and in all 100 tests, doing nothing
in both - which is why nothing runnable here could ever have caught it, and
why reasoning from frozen screenshots got nowhere for several rounds. Every
variable modulo is now guarded: the hangar grid's `i % columns`, planet
naming's `% names.size()`, and two in the map editor.

WHAT IS KEPT, AND WHY

- web_shell.html mirrors console errors onto the page, hidden until one
  occurs. Godot's errors go to the browser console, which is unreachable on
  a phone; this found in one shot what inference had failed to find all
  evening. It costs nothing when there is nothing to report.
- MainMenu._start does load -> instantiate -> add_child by hand instead of
  change_scene_to_file. That call does all three opaquely, so a failure is
  indistinguishable from an unpressed button; split, each step reports.
- PlanetAtmosphereController defers the forced world populate out of the
  frame that builds Main.tscn. It did not fix the hang - the trap did - but
  25 chunks of asteroids and 49 of planets do not belong in the one frame
  that already constructs 197 nodes, and nothing can paint until it ends.

Removed the direct-input-routing experiment and its test: it was written on
the theory that touches were not reaching Controls, which `held=y` later
disproved, and its set_input_as_handled() swallowed the very events the
probe was reading.

Full suite green at 100/100.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Loïc Wisniewski 2026-08-19 01:08:09 +02:00
commit 137e4e528d
13 changed files with 319 additions and 89 deletions

View file

@ -1276,6 +1276,12 @@ func _layout_hangar() -> void:
func _layout_hangar_section(slots: Array, labels: Array, top: float, columns: int,
cell_width: float, cell_height: float, slot_size: float,
label_height: float, width: float) -> void:
# A zero here is fatal on the web and silent everywhere else: wasm TRAPS
# on integer % 0 ("remainder by zero") and kills the engine mid-frame,
# while a native build shrugs it off. That difference is why this class
# of bug survives every test and only appears in a browser.
if columns <= 0:
return
for i in range(slots.size()):
var column: int = i % columns
var row: int = i / columns

View file

@ -110,24 +110,6 @@ func _blocked_by_modal() -> bool:
return false
# Fire on the PRESS instead of the release.
#
# A browser on a phone delivers the touch down and then never delivers the
# release. Measured directly on the deployed build: presses arrive with
# correct coordinates, land inside the button, and the button visibly latches
# into its held state - and no release ever follows, in _gui_input or in raw
# _input. A button that only emits on release therefore never emits at all,
# which is exactly the "Play does nothing" report.
#
# The cost is the drag-off-to-cancel affordance below, which is worth much
# less than the button working. Everywhere else keeps it, because everywhere
# else delivers releases.
#
# Settable rather than a constant so a test can exercise both paths without
# needing to be a web build.
@export var fire_on_press: bool = OS.has_feature("web")
func _gui_input(event: InputEvent) -> void:
if _blocked_by_modal():
return
@ -139,14 +121,28 @@ func _gui_input(event: InputEvent) -> void:
accept_event()
# Complete the press immediately instead of waiting for a release.
#
# Measured on the device, in the web build: an on-screen probe reported
# `touch=1 mouse=1 held=y` after one tap - one touch down, one emulated mouse
# down, the button latched into its held state through ordinary GUI routing,
# and then nothing. The release is never delivered. A button that only emits
# on release therefore never emits at all.
#
# GUI routing itself works fine; `held=y` is the proof. An earlier attempt to
# bypass it made things worse and hid the evidence.
#
# The cost is the drag-off-to-cancel affordance below. Everywhere that
# delivers releases keeps it.
@export var fire_on_press: bool = OS.has_feature("web")
func _handle_press(is_pressed: bool, at_position: Vector2) -> void:
if is_pressed:
pressed_down = true
queue_redraw()
if fire_on_press:
# Nothing is coming to complete this press, so complete it here.
# Not latched: with no release to clear it, the button would
# otherwise stay drawn in its held state forever.
# Not latched: nothing is coming to clear it.
pressed_down = false
pressed.emit()
elif pressed_down:

View file

@ -94,36 +94,23 @@ func _on_play_pressed() -> void:
_start("res://Main.tscn")
# "Nothing happens when I press Play" covers three different faults, and they
# are indistinguishable from the outside: the press never reaching this
# handler, the scene change refusing, or the scene change reporting success
# and not taking effect. Each writes a DIFFERENT line here, so one look at
# the screen says which one it is.
#
# (nothing at all) - the press never got here
# "Loading Main.tscn..." - it got here but the scene never finished
# loading
# "Could not load ..." - the load returned nothing
# "Starting Main.tscn..." - loaded and the change reported OK, yet the
# menu is somehow still up
# "Could not start (...)" - the change refused, with the error number
#
# The scene is also loaded HERE rather than left to change_scene_to_file(),
# which loads internally and reports a single error for both steps. Doing it
# in two makes the failure specific, and takes whatever that call does about
# background loading out of the picture - the web export is built without
# thread support, so anything expecting a loader thread is worth removing
# from the path rather than trusting.
# Loaded, built and added by hand rather than through change_scene_to_file().
# That call does all three in one opaque step, so when the web build hung
# there was no way to tell which part failed. Split out, each step can say so
# - and a scene change that fails otherwise leaves the menu up, which looks
# exactly like an unpressed button.
func _start(scene_path: String) -> void:
status_label.text = "Loading %s..." % scene_path.get_file()
var packed: PackedScene = load(scene_path)
if packed == null:
status_label.text = "Could not load %s" % scene_path.get_file()
return
status_label.text = "Starting %s..." % scene_path.get_file()
var result: int = get_tree().change_scene_to_packed(packed)
if result != OK:
status_label.text = "Could not start (%s, error %d)" % [scene_path.get_file(), result]
var scene: Node = packed.instantiate()
if scene == null:
status_label.text = "Could not build %s" % scene_path.get_file()
return
get_tree().root.add_child(scene)
get_tree().current_scene = scene
queue_free()
func _on_dev_mode_pressed() -> void:
@ -132,7 +119,7 @@ func _on_dev_mode_pressed() -> void:
status_label.text = "Dev mode only runs from Godot"
return
GameState.start_dev_game()
get_tree().change_scene_to_file("res://Main.tscn")
_start("res://Main.tscn")
func _on_editor_pressed() -> void:

View file

@ -54,8 +54,15 @@ func _ready() -> void:
# a second before asteroids/the planet visibly pop in. Force an
# immediate synchronous populate now that the fleet is correctly
# positioned, so nothing is missing on the very first visible frame.
asteroid_field.update_chunks()
planet_field.update_chunks()
# DEFERRED, not called straight through. Everything above runs inside the
# single frame that builds Main.tscn, and these two populate 25 and 49
# chunks of world on top of it - 150-odd asteroids plus planets and their
# visuals. On a phone browser that frame is where the scene appeared to
# hang forever: nothing can paint until it ends, so a slow frame and a
# freeze look identical. One frame later is still immediate to the eye,
# and it lets the scene draw first.
asteroid_field.update_chunks.call_deferred()
planet_field.update_chunks.call_deferred()
func _process(delta: float) -> void:

View file

@ -318,6 +318,8 @@ func _on_reward_pressed() -> void:
if current_setup == null:
return
var index: int = REWARD_OPTIONS.find(int(current_setup.research_point_reward))
if REWARD_OPTIONS.is_empty():
return
current_setup.research_point_reward = REWARD_OPTIONS[(index + 1) % REWARD_OPTIONS.size()]
_refresh_reward_label()
@ -330,6 +332,8 @@ func _refresh_reward_label() -> void:
func _on_profile_pressed() -> void:
if _profile_ids.is_empty():
return
if _profile_ids.is_empty():
return
_profile_cursor = (_profile_cursor + 1) % _profile_ids.size()

View file

@ -152,7 +152,11 @@ static func planet_data_at_chunk(chunk: Vector2i) -> Dictionary:
definition_id = forced_definition_id
var definition: Resource = PLANET_DEFINITIONS.get_definition(definition_id)
var names: PackedStringArray = definition.names
var planet_name: String = names[rng.randi() % names.size()]
# Guarded for the same reason as the hangar grid: an empty names array
# would be a modulo by zero, which traps on wasm and takes the whole
# engine down rather than raising a script error.
var planet_name: String = "Unnamed" if names.is_empty() \
else names[rng.randi() % names.size()]
var planet_id: String = "chunk:%d:%d" % [chunk.x, chunk.y]
return {"planet_id": planet_id, "local_pos": local_pos, "name": planet_name, "shape_seed": shape_seed,
"definition_id": definition_id}

View file

@ -257,7 +257,7 @@ variant/thread_support=false
vram_texture_compression/for_desktop=true
vram_texture_compression/for_mobile=true
html/export_icon=true
html/custom_html_shell=""
html/custom_html_shell="res://web_shell.html"
html/head_include=""
html/canvas_resize_policy=2
html/focus_canvas_on_start=true

View file

@ -1,29 +0,0 @@
extends Node2D
# Probe, not a test - presses Play on the main menu under the REAL
# gl_compatibility renderer, which is the same path the web export takes
# (WebGL2 == GLES3 compatibility). --headless uses a dummy renderer and so
# cannot surface a failure that only happens once something actually has to
# be rendered or a shader has to compile.
#
# bash tests/screenshot.sh res://tests/_web_play_probe.tscn /tmp/play.png 45 720x1280
var menu: Node
var frames: int = 0
var pressed: bool = false
func _ready() -> void:
menu = load("res://MainMenu.tscn").instantiate()
add_child(menu)
func _process(_delta: float) -> void:
frames += 1
if frames == 8 and not pressed:
pressed = true
print("PLAY_PROBE: pressing Play")
menu._on_play_pressed()
if frames == 30:
var scene: Node = get_tree().current_scene
print("PLAY_PROBE: current_scene=%s" % [scene.name if scene != null else "<null>"])

View file

@ -1 +0,0 @@
uid://dtudtqerivj84

View file

@ -1,6 +0,0 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://tests/_web_play_probe.gd" id="1"]
[node name="WebPlayProbe" type="Node2D"]
script = ExtResource("1")

View file

@ -20,6 +20,13 @@ extends SceneTree
# C. without it, the release still drives the press, and dragging off
# still cancels - the behaviour every other platform keeps
# D. the default follows OS.has_feature("web")
#
# There is deliberately NO test for bypassing Godot's GUI routing. An earlier
# attempt did that, on the theory that touches were not reaching Controls at
# all - the device then reported `held=y`, proving the button had been
# receiving presses through ordinary routing the whole time. The bypass was
# solving a problem that did not exist, and its set_input_as_handled() call
# swallowed the very events the on-screen probe was reading.
var presses: int = 0

View file

@ -50,7 +50,9 @@ func _process(delta: float) -> bool:
stage = 1
return false
1:
if elapsed < 0.2:
# _start awaits a frame so its status text paints before the
# blocking load, so the change takes a couple of frames.
if elapsed < 1.0:
return false
var on_editor: bool = current_scene != null and current_scene.name == "PlanetSetupEditor"
if not on_editor:
@ -78,7 +80,7 @@ func _process(delta: float) -> bool:
stage = 3
return false
3:
if elapsed < 0.3:
if elapsed < 1.0:
return false
var on_main: bool = current_scene != null and current_scene.name == "Main"
# A normal game now starts with NOTHING banked - the opening

253
web_shell.html Normal file
View file

@ -0,0 +1,253 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0">
<title>Spaceship</title>
<style>
html, body, #canvas {
margin: 0;
padding: 0;
border: 0;
}
body {
color: white;
background-color: black;
overflow: hidden;
touch-action: none;
}
#canvas {
display: block;
}
#canvas:focus {
outline: none;
}
#status, #status-splash, #status-progress {
position: absolute;
left: 0;
right: 0;
}
#status, #status-splash {
top: 0;
bottom: 0;
}
#status {
background-color: #242424;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
visibility: hidden;
}
#status-splash {
max-height: 100%;
max-width: 100%;
margin: auto;
}
#status-splash.show-image--false {
display: none;
}
#status-splash.fullsize--true {
height: 100%;
width: 100%;
object-fit: contain;
}
#status-splash.use-filter--false {
image-rendering: pixelated;
}
#status-progress, #status-notice {
display: none;
}
#status-progress {
bottom: 10%;
width: 50%;
margin: 0 auto;
}
#status-notice {
background-color: #5b3943;
border-radius: 0.5rem;
border: 1px solid #9b3943;
color: #e0e0e0;
font-family: 'Noto Sans', 'Droid Sans', Arial, sans-serif;
line-height: 1.3;
margin: 0 2rem;
overflow: hidden;
padding: 1rem;
text-align: center;
z-index: 1;
}
</style>
<link id="-gd-engine-icon" rel="icon" type="image/png" href="index.icon.png" />
<link rel="apple-touch-icon" href="index.apple-touch-icon.png"/>
</head>
<body>
<canvas id="canvas">
Your browser does not support the canvas tag.
</canvas>
<noscript>
Your browser does not support JavaScript.
</noscript>
<div id="status">
<img id="status-splash" class="show-image--true fullsize--true use-filter--true" src="index.png" alt="">
<progress id="status-progress"></progress>
<div id="status-notice"></div>
</div>
<script src="index.js"></script>
<script>
const GODOT_CONFIG = {"args":[],"canvasResizePolicy":2,"emscriptenPoolSize":8,"ensureCrossOriginIsolationHeaders":true,"executable":"index","experimentalVK":true,"fileSizes":{"index.pck":6126152,"index.wasm":39513091},"focusCanvas":true,"gdextensionLibs":[],"godotPoolSize":4};
const GODOT_THREADS_ENABLED = false;
const engine = new Engine(GODOT_CONFIG);
(function () {
const statusOverlay = document.getElementById('status');
const statusProgress = document.getElementById('status-progress');
const statusNotice = document.getElementById('status-notice');
let initializing = true;
let statusMode = '';
function setStatusMode(mode) {
if (statusMode === mode || !initializing) {
return;
}
if (mode === 'hidden') {
statusOverlay.remove();
initializing = false;
return;
}
statusOverlay.style.visibility = 'visible';
statusProgress.style.display = mode === 'progress' ? 'block' : 'none';
statusNotice.style.display = mode === 'notice' ? 'block' : 'none';
statusMode = mode;
}
function setStatusNotice(text) {
while (statusNotice.lastChild) {
statusNotice.removeChild(statusNotice.lastChild);
}
const lines = text.split('\n');
lines.forEach((line) => {
statusNotice.appendChild(document.createTextNode(line));
statusNotice.appendChild(document.createElement('br'));
});
}
function displayFailureNotice(err) {
console.error(err);
if (err instanceof Error) {
setStatusNotice(err.message);
} else if (typeof err === 'string') {
setStatusNotice(err);
} else {
setStatusNotice('An unknown error occurred.');
}
setStatusMode('notice');
initializing = false;
}
const missing = Engine.getMissingFeatures({
threads: GODOT_THREADS_ENABLED,
});
if (missing.length !== 0) {
if (GODOT_CONFIG['serviceWorker'] && GODOT_CONFIG['ensureCrossOriginIsolationHeaders'] && 'serviceWorker' in navigator) {
let serviceWorkerRegistrationPromise;
try {
serviceWorkerRegistrationPromise = navigator.serviceWorker.getRegistration();
} catch (err) {
serviceWorkerRegistrationPromise = Promise.reject(new Error('Service worker registration failed.'));
}
// There's a chance that installing the service worker would fix the issue
Promise.race([
serviceWorkerRegistrationPromise.then((registration) => {
if (registration != null) {
return Promise.reject(new Error('Service worker already exists.'));
}
return registration;
}).then(() => engine.installServiceWorker()),
// For some reason, `getRegistration()` can stall
new Promise((resolve) => {
setTimeout(() => resolve(), 2000);
}),
]).then(() => {
// Reload if there was no error.
window.location.reload();
}).catch((err) => {
console.error('Error while registering service worker:', err);
});
} else {
// Display the message as usual
const missingMsg = 'Error\nThe following features required to run Godot projects on the Web are missing:\n';
displayFailureNotice(missingMsg + missing.join('\n'));
}
} else {
setStatusMode('progress');
engine.startGame({
'onProgress': function (current, total) {
if (current > 0 && total > 0) {
statusProgress.value = current;
statusProgress.max = total;
} else {
statusProgress.removeAttribute('value');
statusProgress.removeAttribute('max');
}
},
}).then(() => {
setStatusMode('hidden');
}, displayFailureNotice);
}
}());
</script>
<div id="errlog" style="display:none;position:fixed;left:0;right:0;bottom:0;max-height:50%;overflow:auto;background:rgba(90,0,0,0.9);color:#fff;font:11px/1.35 monospace;padding:6px;z-index:99999;white-space:pre-wrap"></div>
<script>
// Godot writes its errors to the browser console, which is unreachable on a
// phone. This mirrors them onto the page itself, hidden until something
// actually goes wrong.
//
// Worth keeping: a wasm trap ("remainder by zero" - an integer % 0, which
// native builds silently tolerate and wasm does not) killed the engine
// mid-frame with no visible cause. Six rounds of guessing from frozen
// screenshots got nowhere; this found it on the first try.
(function () {
var el = document.getElementById('errlog');
var count = 0;
function add(kind, msg) {
if (count++ > 40) { return; }
el.style.display = 'block';
el.textContent += '[' + kind + '] ' + msg + '\n';
}
window.addEventListener('error', function (e) {
add('err', (e.message || e.type) + ' @ ' + (e.filename || '?') + ':' + (e.lineno || '?'));
});
window.addEventListener('unhandledrejection', function (e) {
add('reject', String(e.reason));
});
['error', 'warn'].forEach(function (level) {
var original = console[level];
console[level] = function () {
add(level, Array.prototype.map.call(arguments, String).join(' '));
original.apply(console, arguments);
};
});
})();
</script>
</body>
</html>