Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,8 @@ jobs:
echo 'Render360 Portal: mimalloc returned to the iPhone release profile.' >&2
exit 1
fi
if grep -q -- '--profiling-funcs' emscripten/build.sh; then
echo 'Render360 Portal: profiling function names returned to the iPhone release build.' >&2
exit 1
fi
# --profiling-funcs is deliberately on while iPhone crashes are being
# traced: it is the only way Safari's Wasm stacks show function names.
if grep -q 'link_libs=' emscripten/build.sh; then
echo 'Render360 Portal: SIDE_MODULEs were returned to load-time linking; Source requires runtime dlopen.' >&2
exit 1
Expand Down
105 changes: 95 additions & 10 deletions emscripten/assets/r360-controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,20 @@
TAB: { key: 'Tab', code: 'Tab', keyCode: 9 },
F6: { key: 'F6', code: 'F6', keyCode: 117 },
F9: { key: 'F9', code: 'F9', keyCode: 120 },
UP: { key: 'ArrowUp', code: 'ArrowUp', keyCode: 38 },
DOWN: { key: 'ArrowDown', code: 'ArrowDown', keyCode: 40 },
LEFT: { key: 'ArrowLeft', code: 'ArrowLeft', keyCode: 37 },
RIGHT: { key: 'ArrowRight', code: 'ArrowRight', keyCode: 39 },
};

// Two mappings. "game" drives Portal; "menu" drives Source's menus and
// dialogs: the stick moves the selection, A/Start accept, B/Pause go back.
// The mode follows the game: menu on the background map and while paused,
// game once a real map loads.
const MENU_KEYS = { a: 'ENTER', start: 'ENTER', x: 'ENTER', b: 'ESC', y: null, back: 'ESC',
lb: 'LEFT', rb: 'RIGHT', lt: null, rt: null };
let mode = 'menu';

// Portal's default bindings. Geometry is measured one-to-one from the
// reference pad (iPhone 11 landscape, 896x350 CSS px below Safari's bar):
// x/y are the top-left corner as fractions of the page, w/h in CSS px.
Expand All @@ -52,6 +64,10 @@
font: 600 9px -apple-system, BlinkMacSystemFont, "SF Pro Text", system-ui, sans-serif; color: #e9eaee;
-webkit-user-select: none; user-select: none; -webkit-touch-callout: none; }
body.r360-playing #r360c.r360c-on { display: block; }
#r360c { transition: opacity .45s ease; }
/* Fades out of the way when the screen is not being touched; any touch
brings it straight back (and still presses the button under it). */
#r360c.r360c-idle { opacity: .16; }
/* Dark, faintly tinted glass with a hairline border, as in the reference;
the fill is translucent so the game shows through. */
#r360c button, #r360c-stick { pointer-events: auto; position: absolute; appearance: none; margin: 0; padding: 0;
Expand All @@ -63,8 +79,6 @@
/* Face buttons are short pills (50x41), not circles or ellipses. */
#r360c button.r360c-face { border-radius: 999px; }
#r360c button.r360c-down { transform: scale(.94); background: rgba(var(--bd), .7); border-color: rgba(255,255,255,.55); }
#r360c.r360c-menu button:not([data-id="pause"]) { display: none; }
#r360c.r360c-menu #r360c-stick { display: none; }
.r360c-gray { --bg: 27,28,32; --bd: 60,62,68; }
.r360c-amber { --bg: 52,40,22; --bd: 120,94,48; }
.r360c-navy { --bg: 18,26,40; --bd: 44,60,86; }
Expand Down Expand Up @@ -161,22 +175,37 @@
try { button.setPointerCapture(pointer); } catch (_) {}
button.classList.add('r360c-down');
if (spec.menuToggle) {
// Escape opens the pause menu in a level and backs out of menus.
keyEvent('keydown', spec.key);
keyEvent('keyup', spec.key);
releaseAll();
root.classList.toggle('r360c-menu');
} else if (spec.key) {
if (inMap) setMode(mode === 'game' ? 'menu' : 'game');
return;
}
if (mode === 'menu') {
const name = MENU_KEYS[spec.id];
if (name) {
keyEvent('keydown', name);
keyEvent('keyup', name);
// Backing out of the pause menu returns to the game.
if (name === 'ESC' && inMap) setMode('game');
}
return;
}
if (spec.key) {
press(spec.key);
} else if (spec.mouse !== undefined) {
mouseEvent('mousedown', spec.mouse);
}
button.dataset.held = '1';
};
const up = (event) => {
if (pointer === null || event.pointerId !== pointer) return;
event.preventDefault();
pointer = null;
button.classList.remove('r360c-down');
if (spec.menuToggle) return;
if (button.dataset.held !== '1') return;
delete button.dataset.held;
if (spec.key) release(spec.key);
else if (spec.mouse !== undefined) mouseEvent('mouseup', spec.mouse);
};
Expand All @@ -198,7 +227,32 @@
let stickPointer = null;
const stickKeys = new Set();

// Menu mode: one arrow press per direction change, then auto-repeat while
// the stick is held, like a console pad in a list.
let menuDir = null;
let menuTimer = 0;
function menuStep(dir) {
if (dir === menuDir) return;
menuDir = dir;
clearTimeout(menuTimer);
if (!dir) return;
const tap = () => { keyEvent('keydown', dir); keyEvent('keyup', dir); };
tap();
const repeat = () => { if (menuDir !== dir) return; tap(); menuTimer = setTimeout(repeat, 140); };
menuTimer = setTimeout(repeat, 380);
}

function setStickKeys(next) {
if (mode === 'menu') {
let dir = null;
if (next.has('W')) dir = 'UP';
else if (next.has('S')) dir = 'DOWN';
else if (next.has('A')) dir = 'LEFT';
else if (next.has('D')) dir = 'RIGHT';
menuStep(dir);
return;
}
menuStep(null);
for (const name of stickKeys) if (!next.has(name)) { stickKeys.delete(name); release(name); }
for (const name of next) if (!stickKeys.has(name)) { stickKeys.add(name); press(name); }
}
Expand Down Expand Up @@ -347,15 +401,26 @@
}

// ------------------------------------------------------------------ state
// Shown in a real map, hidden on the menu background map so menu taps reach
// the game. The in-game menu can also show or hide it.
// Visible by default on touch screens, on the menus too, so the menus can
// be driven with the stick and A. The ••• menu can hide or show it.
let wanted = null; // null = automatic, true/false = player's choice
let inMap = false;

function setMode(next) {
if (mode === next) return;
releaseAll();
menuStep(null);
for (const name of Array.from(stickKeys)) { stickKeys.delete(name); }
mode = next;
root.dataset.mode = mode;
const label = stick.querySelector('.r360c-label');
if (label) label.textContent = mode === 'menu' ? 'Select' : 'Move';
}

function apply() {
const on = wanted === null ? inMap : wanted;
const on = wanted === null ? true : wanted;
root.classList.toggle('r360c-on', on);
if (!on) { releaseAll(); root.classList.remove('r360c-menu'); }
if (!on) { releaseAll(); menuStep(null); }
const toggle = document.getElementById('r360-controller-row');
if (toggle) toggle.textContent = on ? 'Hide controller' : 'Show controller';
}
Expand All @@ -372,14 +437,34 @@
/\bloaded\s+([A-Za-z0-9_]+)\.data\b/.exec(line);
if (!match) return;
inMap = !/^background/i.test(match[1]);
root.classList.remove('r360c-menu');
setMode(inMap ? 'game' : 'menu');
apply();
};

// Idle fade.
const IDLE_MS = 4000;
let idleTimer = 0;
function wake() {
root.classList.remove('r360c-idle');
clearTimeout(idleTimer);
idleTimer = setTimeout(() => {
// Never fade while a control is held.
if (stickPointer !== null || held.size) { wake(); return; }
root.classList.add('r360c-idle');
}, IDLE_MS);
}
for (const type of ['pointerdown', 'touchstart']) {
document.addEventListener(type, wake, { capture: true, passive: true });
}

function mount() {
root.dataset.mode = mode;
const label = stick.querySelector('.r360c-label');
if (label) label.textContent = mode === 'menu' ? 'Select' : 'Move';
document.body.appendChild(root);
layout();
apply();
wake();
}

window.addEventListener('resize', layout);
Expand Down
4 changes: 2 additions & 2 deletions emscripten/build.sh
Original file line number Diff line number Diff line change
Expand Up @@ -372,12 +372,12 @@ echo "Render360 Portal: required filesystem/engine/ToGL module set present"
# forwards them to the Source pthread where WORKERFS exposes them read-only.
# Source then opens the retail VPKs and performs its own range reads on demand.
# WORKERFS is not part of the default JS filesystem, so link it explicitly.
EMCC_FORCE_STDLIBS=libc,libc++,libc++abi emcc -Os \
EMCC_FORCE_STDLIBS=libc,libc++,libc++abi emcc -Os --profiling-funcs \
-sUSE_BZIP2=1 -sUSE_SDL=2 -sUSE_FREETYPE=1 -sUSE_LIBJPEG=1 -sUSE_LIBPNG -sMALLOC=dlmalloc \
-sMAIN_MODULE -sINCLUDE_FULL_LIBRARY=1 \
-sINITIAL_MEMORY=384mb -sALLOW_MEMORY_GROWTH=1 -sMAXIMUM_MEMORY=1024mb -sMEMORY_GROWTH_LINEAR_STEP=32mb \
-sSHARED_MEMORY=1 -sUSE_PTHREADS -sPTHREAD_POOL_SIZE=2 -sPTHREAD_POOL_SIZE_STRICT=0 \
-sFULL_ES3 -sSTACK_SIZE=4mb -sDEFAULT_PTHREAD_STACK_SIZE=1mb --shell-file=emscripten/shell.html \
-sFULL_ES3 -sSTACK_SIZE=16mb -sDEFAULT_PTHREAD_STACK_SIZE=1mb --shell-file=emscripten/shell.html \
-sASSERTIONS=1 -sSTACK_OVERFLOW_CHECK=1 \
-sPROXY_TO_PTHREAD -sOFFSCREENCANVASES_TO_PTHREAD="#canvas" -sOFFSCREENCANVAS_SUPPORT=1 \
-lworkerfs.js \
Expand Down
20 changes: 19 additions & 1 deletion emscripten/post.js
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@
let count = 0
let bytes = 0
let vpkPlaceholders = 0
let loosePlaceholders = 0
let hasPortalGameInfo = false
for(const item of Array.isArray(files) ? files : []) {
const path = normalize(item && item.path)
Expand All @@ -130,6 +131,23 @@
FS.writeFile(fullPath, new Uint8Array(0))
}
vpkPlaceholders++
continue
}

// Loose retail files (cfg/, scripts/, resource/, maps/) need names
// in this shared namespace too: Source finds them by *listing*
// directories (the New Game dialog enumerates cfg/chapter*.cfg),
// and listings come from here. Opens and stats are intercepted by
// filesystem_stdio and served from the real File, so a zero-byte
// name costs nothing and never shadows the content.
if(/^(?:portal|hl2|platform)\/(?:cfg|scripts|resource|maps)\//i.test(path)) {
ensureParent(fullPath)
try {
FS.lookupPath(fullPath, { follow: false })
} catch(_) {
FS.writeFile(fullPath, new Uint8Array(0))
}
loosePlaceholders++
}
}

Expand All @@ -147,7 +165,7 @@
Module.render360Phase3StartupMemfsBytes = bytes
Module.render360Phase3StartupMemfsFiles = count
Module.render360Phase3VpkPlaceholders = vpkPlaceholders
Module.print?.(`[Render360 Phase 3] staged ${count} startup metadata files (${bytes} bytes) plus ${vpkPlaceholders} zero-byte VPK namespace placeholders; retail VPK payload remains browser-backed`)
Module.print?.(`[Render360 Phase 3] staged ${count} startup metadata files (${bytes} bytes) plus ${vpkPlaceholders} zero-byte VPK and ${loosePlaceholders} loose-file namespace placeholders; retail payload remains browser-backed`)
try { globalThis.render360SetPhase?.(`phase3-startup-metadata-ready:vpk=${vpkPlaceholders}`) } catch(_) {}
}

Expand Down
48 changes: 30 additions & 18 deletions emscripten/pre.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,13 +95,15 @@ let render360LogTailDirty = false
function render360RememberLine(text) {
const line = String(text || '').trim()
if(!line) return
// Crash stacks are long and are the whole point; keep them intact.
const limit = line.startsWith('[Render360 worker stack]') ? 3000 : 300
if(RENDER360_NOTABLE_RE.test(line) && render360Notable.length < 60) {
const last = render360Notable[render360Notable.length - 1]
if(!last || !last.endsWith(line.slice(0, 300))) {
render360Notable.push(`${((Date.now() - render360Now) / 1000).toFixed(1)}s ${line.slice(0, 300)}`)
if(!last || !last.endsWith(line.slice(0, limit))) {
render360Notable.push(`${((Date.now() - render360Now) / 1000).toFixed(1)}s ${line.slice(0, limit)}`)
}
}
render360LogTail.push(`${((Date.now() - render360Now) / 1000).toFixed(1)}s ${line.slice(0, 300)}`)
render360LogTail.push(`${((Date.now() - render360Now) / 1000).toFixed(1)}s ${line.slice(0, limit)}`)
if(render360LogTail.length > RENDER360_LOG_TAIL_LINES) render360LogTail.splice(0, render360LogTail.length - RENDER360_LOG_TAIL_LINES)
render360LogTailDirty = true
}
Expand Down Expand Up @@ -295,7 +297,10 @@ Module['arguments'].push(
// itself whenever it believes the window is in the background.
'+snd_mute_losefocus', '0',
// Full scale is harsh on a phone speaker; still adjustable in Options.
'+volume', '0.7'
'+volume', '0.7',
// Paint further ahead than the desktop 0.1 s: phone frames are slower,
// and the ring holds 0.37 s.
'+snd_mixahead', '0.25'
)

// A phone has no keyboard and iOS has never shipped Pointer Lock, so the
Expand All @@ -316,14 +321,10 @@ if(render360IsWindow) {
// see, and textures are the largest thing a map load adds to both the
// Wasm heap and GPU memory, which is where iOS kills the page.
Module['arguments'].push('+mat_picmip', '2')
// Graphics memory is the next limit after the Wasm heap: the first
// iPhone run that reached the menu lost its WebGL context while the
// engine was caching materials. Normal maps double the texture memory
// of almost every Portal surface, specular cubemaps and shadow render
// targets add more, and none of it is worth a lost context on a phone.
// Cheaper rendering features for a phone GPU. Bump maps and specular
// stay on: turning them off makes Portal's materials ask for a
// $bumpmap texture that is not loaded (console errors).
Module['arguments'].push(
'+mat_bumpmap', '0',
'+mat_specular', '0',
'+r_shadowrendertotexture', '0',
'+r_flashlightdepthtexture', '0',
'+r_waterforceexpensive', '0',
Expand Down Expand Up @@ -827,7 +828,9 @@ if(render360IsWindow && !render360ProbableProcessReload) {
if(!render360IsWindow && typeof self !== 'undefined' && typeof self.addEventListener === 'function') {
self.addEventListener('error', event => {
const error = event?.error
const stack = String(error?.stack || '').split('\n').slice(0, 24).join(' | ')
const stack = String(error?.stack || '').split('\n').slice(0, 40)
.map(frame => frame.replace(/@\[wasm code\]$/, '').replace(/^(\d+)@wasm-function\[\1\]$/, 'f$1'))
.join(' | ')
render360Log(`[Render360 worker stack] ${error?.message || event?.message || 'error'} :: ${stack || '<no stack>'}`)
})
}
Expand Down Expand Up @@ -925,6 +928,7 @@ if(render360IsWindow) {
this.i16 = new Int16Array(d.sab);
this.i32 = new Int32Array(d.sab);
this.frac = 0;
this.abs = 0;
};
}
process(inputs, outputs) {
Expand All @@ -938,11 +942,16 @@ if(render360IsWindow) {
const frames = c.bytes >> 2;
const base = c.buf >> 1;
const step = c.rate / sampleRate;
let pos = Atomics.load(this.i32, c.readIdx);
if (pos < 0 || pos >= c.bytes) pos = 0;
let frame = pos >> 2;
// Absolute sample time read so far (the engine's "soundtime") and
// the time the engine has finished writing up to. Never play past
// what was written: replaying stale ring contents is a buzz.
const painted = c.paintedIdx >= 0 ? Atomics.load(this.i32, c.paintedIdx) : 0x7fffffff;
if (painted < this.abs - frames) this.abs = painted; // engine restarted its clock
let frame = this.abs % frames;
let frac = this.frac;
for (let i = 0; i < L.length; i++) {
let i = 0;
for (; i < L.length; i++) {
if (this.abs + 1 >= painted) break;
const next = frame + 1 === frames ? 0 : frame + 1;
const a = base + frame * 2, b = base + next * 2;
const l0 = this.i16[a], r0 = this.i16[a + 1];
Expand All @@ -952,7 +961,9 @@ if(render360IsWindow) {
const whole = frac | 0;
frac -= whole;
frame = (frame + whole) % frames;
this.abs += whole;
}
for (; i < L.length; i++) { L[i] = 0; if (R !== L) R[i] = 0; }
this.frac = frac;
Atomics.store(this.i32, c.readIdx, frame << 2);
return true;
Expand All @@ -977,10 +988,11 @@ if(render360IsWindow) {
else resumeAudio()
})

Module.render360AudioStart = (buf, bytes, readPosPtr, pausePtr, rate) => {
Module.render360AudioStart = (buf, bytes, readPosPtr, pausePtr, rate, paintedPtr) => {
try { if(navigator.audioSession) navigator.audioSession.type = 'playback' } catch(_) {}
const sab = (typeof wasmMemory !== 'undefined' && wasmMemory) ? wasmMemory.buffer : HEAP8.buffer
const config = { sab, buf, bytes, readIdx: readPosPtr >> 2, pauseIdx: pausePtr >> 2, rate }
const config = { sab, buf, bytes, readIdx: readPosPtr >> 2, pauseIdx: pausePtr >> 2, rate,
paintedIdx: paintedPtr ? paintedPtr >> 2 : -1 }
const AC = window.AudioContext || window.webkitAudioContext
if(!AC) { Module.printErr?.('[Render360 audio] Web Audio unavailable'); return }
let ctx
Expand Down
Loading
Loading