diff --git a/app/build_app.sh b/app/build_app.sh
index 30b4608..9382937 100755
--- a/app/build_app.sh
+++ b/app/build_app.sh
@@ -32,6 +32,9 @@ rm -rf "$T"
for a in x86_64 arm64; do /usr/bin/python3 -c 'import sys; p=sys.argv[1]; b=open(p,"rb").read(); w=bytes.fromhex("47454d494e49"); n=b.count(w); assert n==1, n; open(p,"wb").write(b.replace(w,w[:3]+b"1"+w[4:]))' "$C/Resources/py/$a/bin/python3.12" || exit 1; done
find "$C/Resources/py" -name '*.pyc' -delete; find "$C/Resources/py" -name __pycache__ -type d -empty -delete
mkdir -p "$C/Resources/bin"; cp "$X/7z/7zz" "$C/Resources/bin/"; cp "$X/7z/License.txt" "$C/Resources/bin/7zz-License.txt"
+# 32-bit system libraries older games use without shipping them (msvcr80/90, d3dx9_NN), from Microsoft's redistributables
+# (tools/fetch_sys32.sh); a DAISY_SYS that already holds x86/ keeps its own
+[ -f "$C/Resources/kit/sys/x86/msvcr80.dll" ] || DAISY_7ZZ="$C/Resources/bin/7zz" "$H/tools/fetch_sys32.sh" "$C/Resources/kit/sys/x86" >/dev/null || { echo "could not fetch the 32-bit system libraries" >&2; exit 1; }
cat > "$C/Info.plist" <<'P'
diff --git a/app/convert.sh b/app/convert.sh
index 30cb1bf..6823f58 100755
--- a/app/convert.sh
+++ b/app/convert.sh
@@ -8,6 +8,9 @@
R="$(cd "$(dirname "$0")" && pwd)"; K="$HOME/Library/Application Support/DAISY"; OUT="${DAISY_GAMES:-$HOME/Library/Application Support/DAISY/Games}"
# the app goes where Mac software goes, so Launchpad and Spotlight list it; the program's own files (game data,
# saves it writes, learned shaders) stay in Application Support, named by Contents/Resources/daisy-root
+# macOS asks before a program sends to the local network (LAN games: broadcasts are refused with "no route to host"
+# until the user allows it); the prompt shows this reason
+LNET="Lets the game find and join games on your local network (LAN play)."
APPS="${DAISY_APPS:-/Applications}"; [ -w "$APPS" ] || APPS="$HOME/Applications"
[ -n "$DAISY_TMP" ] && export TMPDIR="$DAISY_TMP/" # the compiler's own temporary files go with the build, not to the system disk
install_app() { # install_app
: the .app in $1.app moves to $APPS, signed in place
@@ -218,7 +221,7 @@ if [ -d "$MA/Contents/MacOS" ]; then
/usr/libexec/PlistBuddy -c "Delete :LSRequiresCarbon" "$B/$n.app/Contents/Info.plist" >/dev/null 2>&1
else
cp -R "$MA/Contents/Resources/." "$B/data/" 2>/dev/null
- printf 'CFBundleExecutable%sCFBundleIdentifierdaisy.%sCFBundleName%sCFBundlePackageTypeAPPLLSMinimumSystemVersion13.0NSHighResolutionCapable' "$n" "$n" "$n" > "$B/$n.app/Contents/Info.plist"
+ printf 'CFBundleExecutable%sCFBundleIdentifierdaisy.%sCFBundleName%sCFBundlePackageTypeAPPLLSMinimumSystemVersion13.0NSHighResolutionCapableNSLocalNetworkUsageDescription%s' "$n" "$n" "$n" "$LNET" > "$B/$n.app/Contents/Info.plist"
fi
echo "STAGE Finishing"; echo "PROGRESS 97"
rm -rf "$B/o" "$B/thin" "$B"/lib[0-9]* "$B/build.log" "$W"; [ -d "$D/data" ] && cp -Rn "$D/data/." "$B/data/" 2>/dev/null # files the user added to data are kept
@@ -249,6 +252,7 @@ fi
# intake says why it stopped (a lone program in Downloads, a DRM-locked program, nothing to unpack); else the general reason
[ $rc = 0 ] && [ -n "$j" ] || { why=$(tail -1 "$W/intake.err" 2>/dev/null); [ -n "$why" ] || why="could not unpack or find the game's program"; echo "FAILED: $why"; exit 1; }
f=$(get folder); exe=$(get exe); bits=$(get bits); top=$(get top); [ -n "$top" ] || top="$f"
+largs=$(get args); launcher=$(get launcher) # a launcher's game: the program it runs (exe, maybe in a sub-folder) and its arguments
# A dropped folder is the game's whole folder even when its program sits in a sub-folder (files beside that
# sub-folder belong to the game too); an unpacked archive or installer likewise.
whole="$1"; [ -d "$1" ] || whole="$W/game"; whole=$(cd "$whole" 2>/dev/null && pwd -P); ff=$(cd "$f" 2>/dev/null && pwd -P)
@@ -268,9 +272,11 @@ fi
t="${DAISY_TITLE:-$in}"; t=$(printf '%s' "$t" | tr -d '/:'); n=$(printf '%s' "$t" | tr -cd 'A-Za-z0-9' | cut -c1-24); [ -n "$n" ] || n=game
case "$t" in ''|.|..|-*|*/*) t="$n";; esac # the folder below is replaced: it must be a plain child of OUT
D="$OUT/$t"; B=$(mktemp -d "${DAISY_TMP:-/tmp}/daisy.XXXXXX") || exit 1
-echo "STAGE Rewriting $exe"
+[ -n "$launcher" ] && echo "LAUNCHER $launcher runs $exe${largs:+ ($largs)}"
+echo "STAGE Rewriting $(basename "$exe")"
# daisy64 prints "@P "; each stage owns a slice of the bar: rewrite 12-50, copy 50-60, compile 60-97
-known=$("$PY" -I -B -c 'import json,sys; print(json.load(open(sys.argv[1])).get(sys.argv[2].lower(), ""))' "$K/kit/tools/known.json" "$exe" 2>/dev/null) # start-up settings a known program needs
+known=$("$PY" -I -B -c 'import json,sys; print(json.load(open(sys.argv[1])).get(sys.argv[2].lower(), ""))' "$K/kit/tools/known.json" "$(basename "$exe")" 2>/dev/null) # start-up settings a known program needs
+[ -n "$known" ] || known="$largs"
# libraries in sub-folders (add-ins the program loads by name: "plugins", Qt "platforms"...) are built in too
plug=""; np=$(find "$top" -mindepth 2 -maxdepth 4 -iname '*.dll' 2>/dev/null | head -400 | wc -l); [ "$np" -gt 0 ] && [ "$np" -lt 400 ] && plug="--plugins"
# Direct3D 12 and the Direct3D 11 stages that go through it (tessellation, geometry shaders): requests a run of the
@@ -286,14 +292,14 @@ MACOSX_DEPLOYMENT_TARGET=${MACOSX_DEPLOYMENT_TARGET:-13.0} DAISY_HOST=local DAIS
{ print > lf; fflush(lf) }'
else # 32-bit: the program and its libraries are rewritten and linked with the 32-bit runtime; its folder stays whole beside the app
mkdir -p "$B/data" "$B/o32"; echo "STAGE Copying game files"; rsync -a "${f%/}/" "$B/data/" || { echo "FAILED: could not copy the program files"; exit 1; }
- echo "PROGRESS 20"; echo "STAGE Rewriting $exe"
- MACOSX_DEPLOYMENT_TARGET=13.0 "$PY" -I -B "$K/kit/tools/build.py" "$f" "$B/o32" "$exe" --auto 2>&1 \
+ echo "PROGRESS 20"; echo "STAGE Rewriting $(basename "$exe")"
+ MACOSX_DEPLOYMENT_TARGET=13.0 "$PY" -I -B "$K/kit/tools/build.py" "$f" "$B/o32" "$exe" --auto --data "$B/data" ${known:+--args "$known"} 2>&1 \
| /usr/bin/awk -v lf="$B/build.log" '$1 == "@P" { print "PROGRESS " int(($2 == "rewrite" ? 20 : 90) + ($2 == "rewrite" ? 70 : 7) * $3); if ($2 == "compile") print "STAGE Building the Mac app"; fflush(); next }
{ print > lf; fflush(lf) }'
- x=$(printf '%s' "${exe%.*}" | tr 'A-Z' 'a-z')
+ x=$(basename "$exe"); x=$(printf '%s' "${x%.*}" | tr 'A-Z' 'a-z')
if [ -x "$B/o32/$x" ]; then
mkdir -p "$B/$n.app/Contents/MacOS"; cp "$B/o32/$x" "$B/$n.app/Contents/MacOS/$n"
- printf 'CFBundleExecutable%sCFBundleIdentifierdaisy.%sCFBundleName%sCFBundlePackageTypeAPPLLSMinimumSystemVersion13.0NSHighResolutionCapable' "$n" "$n" "$n" > "$B/$n.app/Contents/Info.plist"
+ printf 'CFBundleExecutable%sCFBundleIdentifierdaisy.%sCFBundleName%sCFBundlePackageTypeAPPLLSMinimumSystemVersion13.0NSHighResolutionCapableNSLocalNetworkUsageDescription%s' "$n" "$n" "$n" "$LNET" > "$B/$n.app/Contents/Info.plist"
mkdir -p "$B/$n.app/Contents/Resources"
fi
rm -rf "$B/o32"
@@ -304,6 +310,10 @@ cp "$B/build.log" "$K/last-build.log" 2>/dev/null # kept for a failed conversi
# uses for the first time is recorded there, rewritten to Metal source by the tool and compiled by the system, so no
# Metal compiler is needed and nothing has to be learned ahead of time.
mkdir -p "$B/learn/d3d9" "$B/$n.app/Contents/Helpers"; [ -d "$D/learn" ] && cp -R "$D/learn/." "$B/learn/" 2>/dev/null
+# Converting again (as after playing, to build the learned shaders ahead) keeps what the player made: profiles, saves
+# and settings (the Windows user folders) and the program's registry. The folder below is replaced as a whole.
+[ -d "$D/Documents and Settings" ] && cp -Rp "$D/Documents and Settings" "$B/" 2>/dev/null
+[ -f "$D/registry.txt" ] && cp -p "$D/registry.txt" "$B/" 2>/dev/null
clang -arch x86_64 -arch arm64 -O1 -w -DDAISY_BUILDER -o "$B/$n.app/Contents/Helpers/shtool" "$K/kit/tools/shtool.c" "$K/kit/runtime/d3d9_shader.c" "$K/kit/runtime/d3d9_ff.c" 2>>"$B/build.log" \
|| { echo "FAILED: could not build the shader tool"; exit 1; }
# Direct3D 11: the same idea. Its shader rewriter is a Python tool, so a program that uses Direct3D 11 also gets the
@@ -323,6 +333,7 @@ cd "$D" || exit 1
/usr/libexec/PlistBuddy -c "Set :CFBundleName $t" "$t.app/Contents/Info.plist" >/dev/null 2>&1
# the program's own icon, from the .exe's resources; DAISY's only when it has none
ep="$f/$exe"; [ -f "$ep" ] || ep=$(find "$f" -iname "$(basename "$exe")" 2>/dev/null | head -1)
+[ -n "$launcher" ] && [ -f "$f/$launcher" ] && ep="$f/$launcher" # a launcher carries the game's icon
"$PY" -I -B "$K/kit/tools/exeicon.py" "$ep" "$t.app/Contents/Resources/AppIcon.icns" 2>>"$D/build-icon.log" || cp "$R/daisy.icns" "$t.app/Contents/Resources/AppIcon.icns" 2>/dev/null
[ -f "$t.app/Contents/Resources/AppIcon.icns" ] && /usr/libexec/PlistBuddy -c 'Add :CFBundleIconFile string AppIcon' "$t.app/Contents/Info.plist" >/dev/null 2>&1
strip -S "$t.app/Contents/MacOS/"* 2>/dev/null; install_app "$t" "$D"
diff --git a/docs/32bit-game-fixes.md b/docs/32bit-game-fixes.md
new file mode 100644
index 0000000..17c96d5
--- /dev/null
+++ b/docs/32bit-game-fixes.md
@@ -0,0 +1,321 @@
+# Fixes from bringing up 32-bit Direct3D 9 games (Command & Conquer 3: Tiberium Wars and Kane's Wrath)
+
+C&C 3 (EA's SAGE engine, 2007) did not start after conversion. Getting it from "closes immediately" to playable
+skirmishes exposed gaps that are not specific to this game: launchers, programs linked without relocations, system
+libraries a game expects Windows to provide, exclusive fullscreen, lost devices, and resource lifetime. Each fix below
+is written against Windows behaviour, not against C&C 3, so other games of the same era benefit. Every entry names the
+symptom, what Windows does, and where the change is.
+
+Tools added along the way:
+
+- `tools/missing32.py [--binary ]` lists the Windows functions a program and its
+ libraries import that the runtime does not implement. With `--binary` it reads the converted app's own table of
+ natives (`__DATA,pe2nat`), so natives generated by macros count too. Run it before a conversion to see what a game
+ still lacks; each missing function would otherwise stop the game at its first call.
+- `tools/fetch_sys32.sh ` downloads Microsoft's redistributables and extracts the 32-bit system libraries below.
+- The crash report now lists the game's own call chain (return addresses into rewritten code found on its stack).
+- Low memory (below 4 GB) running out is now logged instead of surfacing later as a null pointer.
+
+## Conversion
+
+**Launchers** (`tools/intake.py`, `tools/build.py`, `runtime/main.c`, `runtime/loader.c`, `app/convert.sh`).
+Many games start from a small launcher `.exe` that runs the real program, a Windows program kept under another
+extension. DAISY converted the launcher, which then failed (DAISY does not start processes). Intake now recognises
+three forms and converts the real program, keeping the launcher's folder as the game folder and its icon for the app:
+- a `*.SkuDef` with `set-exe ` (EA SAGE: C&C 3, Kane's Wrath, Red Alert 3, BFME 2); the launcher passes
+ `-config `, given as `%GAMEDIR%\name.SkuDef` and expanded at start (the game resolves a
+ relative path against its own folder, not the working folder);
+- a launcher that holds the program's file name (C&C Generals, BFME 1: `game.dat`);
+- a program with the launcher's name and another extension (SafeDisc: `game.icd`).
+The program may sit in a sub-folder (`RetailExe\1.9\cnc3game.dat`): the runtime loads it from there, reports that
+path from `GetModuleFileName`/`GetModuleFileNameEx` whatever its extension, and passes the launcher's arguments when
+the app is opened without any.
+
+**System libraries the game does not ship** (`tools/fetch_sys32.sh`, `tools/build.py`, `runtime/loader.c`,
+`app/build_app.sh`). Games relied on Windows' copies of `msvcr80`/`msvcr90` and `d3dx9_NN`. The app now carries them in
+`kit/sys/x86` (from Microsoft's VC++ 2005/2008 SP1 and DirectX June 2010 redistributables; the C runtimes are the
+`nosxs` builds, which load without the side-by-side manifest check). `build.py` rewrites one with the game when the
+game imports it and has no copy of its own, and copies it beside the game. The system `msvcrt.dll` is served by
+whichever versioned C runtime is built in (`msvcr71`, `msvcr80`, `msvcr90`); with none, `msvcr80` is added.
+
+**Converting again keeps the player's files** (`app/convert.sh`). Converting a game again (as the README suggests after
+playing, so learned shaders are built ahead) replaced its whole folder and kept only `learn`: profiles, saves, replays
+and settings under `Documents and Settings`, and `registry.txt`, were deleted. Both are now carried over.
+
+## Rewriter (`pe2mac/rewrite.py`)
+
+**Programs linked without relocations.** An `.exe` linked `/FIXED` at 0x400000 has no relocation table, so code
+reached only through pointers (vtables, callbacks, the C runtime's initialiser table) was never found and the program
+stopped at its first indirect branch ("indirect branch to ... which has no rewritten code"). Such images now get a
+second discovery pass (`discover_unrelocated`): aligned words in data, words in code no instruction covers, 32-bit
+immediates and the entries of indexed tables that point into code are tried as starts, each judged speculatively like
+a relocation target, in rounds until nothing new is found (progress on stderr). Guesses are never written into the
+program's data: an indirect branch to a real one is mapped at run time by the loader, so a value that only looks like
+an address is left as it was. Starts inside an instruction another guess decoded are still tried (streams may overlap).
+
+**Switch tables.** `jmp [reg*4 + table]` tables in the code section are bounded by the compare before them
+(`cmp reg, N; ja default`, or in unoptimised code `cmp [ebp-x], N; ja; mov reg, [ebp-x]`); their `N + 1` entries are
+decoded as certain code rather than guessed. Each one is tried once: one that decodes to nothing (for example, it lies
+past the section's bytes in the file) used to be retried forever. Kane's Wrath's `cnc3ep1.dat` has two of them, and
+the conversion hung at "Rewriting" with no output. It now takes about 36 s. A decode also reads only the 16 bytes of
+one instruction instead of copying from there to the end of the section.
+
+**Instructions.** `ud0`/`ud1` (a library failed to assemble) are traps like `ud2`. `enter`'s size is an unsigned 16-bit
+value (was printed negative). The CET `notrack` prefix on `call`/`jmp` is a plain branch. `jcxz` (jump if cx is 0) is
+emitted flag-preserving (no 64-bit form). `jecxz` and `loop`, which only have an 8-bit reach, go through a local label,
+since the rewritten code between them and their target can be far longer than the original.
+
+## Runtime (32-bit)
+
+**Sockets as Winsock reports them** (`runtime/win_misc.c`, matching `w64/net.c`). A non-blocking `connect` that has
+started failed with `WSAEINPROGRESS` (10036) where Windows gives `WSAEWOULDBLOCK` (10035), which programs check for,
+so TCP connections from a 32-bit program failed. The error table now has the full errno mapping (`EACCES`, `ENETDOWN`,
+`EHOSTDOWN`...). `setsockopt` takes one-byte BOOL values, and gives send and receive timeouts (milliseconds on Windows)
+as a `timeval`: they used to be refused and the refusal ignored, so a receive meant to time out blocked forever. It also
+maps TCP option numbers and accepts and ignores options only Windows has. `getsockopt` returns timeouts in
+milliseconds, linger as Windows' two shorts, and `SO_ERROR` as a Winsock code.
+
+**Missing functions** (`runtime/win_extra32.c`, `runtime/win_misc.c`). 55 functions C&C 3 and its libraries import,
+from `GetModuleHandleExA`, `GlobalReAlloc`, `wsprintfA/W` (Windows' own small printf) and the Winsock event functions to
+those Windows itself may fail (process snapshots, NetBIOS, IME candidate lists, overlapped socket receive), which fail
+the same way. Most are thin forms of natives implemented elsewhere.
+
+**Low memory and Metal** (`runtime/lowheap.c` `pages_zero`, `runtime/k32_core.c` `VirtualFree`). Freed low memory
+was zeroed by remapping it in 4 KB pages. A program under Rosetta sees 4 KB pages, but Apple silicon's are 16 KB, and a
+hardware page remapped in 4 KB pieces is memory Metal cannot wrap without copying: `newBufferWithBytesNoCopy` returned
+nil for vertex and index buffers placed there later, and their draws were dropped (pieces of the scene, often after a
+Reset, missing). Only whole 16 KB pages are remapped now; the ends are cleared in place. Direct3D buffer memory is also
+taken at 16 KB alignment, and a refusal is logged ("Metal refused a ... byte buffer").
+
+**Accelerated library exports** (`runtime/loader.c` `accel_for`, `runtime/d3d9_device.m`). A library a game ships may
+hold hot loops that, rewritten and run under Rosetta, are many times slower than on Windows; D3DX converts pixels one at
+a time with x87 arithmetic, which Rosetta emulates slowly. The runtime may implement such a function natively, registered
+under the library's family name (`NATIVE(d3dx9, ...)` serves every `d3dx9_NN.dll`): imports and `GetProcAddress` bind to
+the native, which handles the common cases and calls the library's own code, kept by the loader (`pe2_accel_orig`), for
+the rest. The first is `D3DXLoadSurfaceFromMemory` for 32-bit ARGB/XRGB into a device surface (a fill from one pixel, a
+copy at the same size, a point-filtered scale). C&C 3 fills thousands of textures from a one-pixel source after each
+Reset; D3DX took ten seconds for it on every return to the game. To find such a loop: attach `lldb` while the game is
+slow and interrupt it a few times; the frames are named `m__L`, and the address leads to the export.
+
+**LAN games** (`runtime/win_misc.c`, `app/convert.sh`, `tools/daisy64.py`). `gethostbyname` of the machine's own name
+listed 127.0.0.1 with the real addresses. Windows lists loopback only when there is no network; C&C 3 (like other SAGE
+games) sorts the list and takes the first address for LAN play, took 127.0.0.1, and in that case announces its games on
+loopback only (to other copies on the same machine): no other computer saw them. Loopback is now listed only when there is
+no other address, and the game broadcasts to the network (255.255.255.255, ports 8086-8093). macOS also asks before a
+program sends to the local network; until the user allows it, every broadcast fails with "no route to host". Converted
+apps now carry `NSLocalNetworkUsageDescription`, the reason shown in that prompt, and a failed `sendto` is logged with
+`PE2_TRACE_SOCK`.
+
+## Window layer (`w64/`, used by 32-bit programs with a window interface through `runtime/w32glue.m`)
+
+**Exclusive fullscreen** (`w64/win.h` `w64_fullscreen`, `runtime/w32glue.m` `pe2_set_mode`). A Direct3D 9 device with
+`Windowed = FALSE` stayed a normal window. As on Windows, the device window now covers the display at the new mode:
+its size is the mode, `GetSystemMetrics` and the desktop rectangle report the mode as the screen, and `SetWindowPos` and
+the Mac window's own resize notifications cannot change it. The Mac window covers the screen (menu bar and Dock
+hidden), the picture scaled to fit with black bars. Every mouse position (messages, `MSG.pt`, `GetCursorPos`,
+`GetMessagePos`, `SetCursorPos`) is mapped between the screen and the mode, clamped to its edges (a strategy game
+scrolls when the cursor reaches the edge). The mapping uses the fullscreen window whichever window an event names (a
+game's device window and main window may differ). Without this, clicks landed at a fraction of the pointer's position.
+
+**Native resolutions** (`runtime/d3d9_api.m`). The adapter's mode list adds the Mac display's own sizes (its pixels and
+its points), so a game can run at a Retina screen's native resolution.
+
+**A fullscreen window minimised in the background** (`w64/user32.m`, `w64/win.h` `IsIconic`). As Windows does with an
+exclusive-fullscreen window whose program goes to the background, it is minimised (`IsIconic` true, `WM_SIZE
+SIZE_MINIMIZED`, `WM_ACTIVATE` with the minimised flag) and restored on the way back (`WM_SIZE SIZE_RESTORED`); the Mac
+window itself stays. Games poll `IsIconic` to stop drawing and simulating while away (C&C 3 calls it every frame).
+
+**DirectInput and focus** (`runtime/client_misc.c`). A `DISCL_FOREGROUND` device is unacquired when its program is
+deactivated: the next read returns `DIERR_INPUTLOST`, and `Acquire` fails with `DIERR_OTHERAPPHASPRIO` until the program
+is active again, as on Windows. Before, input kept flowing to a program in the background.
+
+**DirectInput** (`runtime/w32glue.m`, `w64/user32.m`). In the full window layer DirectInput read no keys or motion.
+The event loop now feeds it: keys as DirectInput scancodes in order (extended keys as `0x80 | code`), mouse motion
+accumulated, buttons with presses shorter than one read kept, the wheel.
+
+**A clipped, visible cursor** (`w64/user32.m` `mouse_apply`). `ClipCursor` detached the Mac pointer from the mouse, so a
+strategy game that keeps its visible cursor inside its window got the same position forever. The pointer is now held
+still only for a game that clips and hides the cursor (a shooter reading raw motion).
+
+**Text into 24- and 16-bit bitmaps** (`w64/draw.h` `cg`). Text, lines and shapes were drawn only into 32-bit bitmaps;
+others silently got nothing. C&C 3 renders every glyph into a 24-bit DIB, so it had no text at all. Those depths are now
+drawn through a 32-bit copy that is converted back.
+
+**Cursor files** (`w64/menu.h` `w64_cursor_file`, `runtime/w32glue.m` `LoadCursorFromFile`). `.cur`, `.ico` and
+animated `.ani` files become Mac cursors with their hotspots; an animated one plays at its file's rate.
+
+## Direct3D 9 (`runtime/d3d9_*`)
+
+**Lost devices** (`d3d9_device.m` `dev_state`). An exclusive-fullscreen device is lost while its program is not active
+(Command-Tab, another Space): `TestCooperativeLevel` and `Present` say `D3DERR_DEVICELOST` and `Reset` fails the same
+way; once active again they say `D3DERR_DEVICENOTRESET` until `Reset`. Games release their default-pool resources on the
+first and create them again after the `Reset`; always answering `D3D_OK` made them draw with what they had just
+released, and crash. A windowed device is never lost.
+
+**Resource lifetime** (`d3d9_device.m` `res_released`, `free_pending`). `Release` freed nothing: every texture and
+buffer a game ever made kept its CPU copies and buffer memory in the 2 GB below 4 GB that the program itself must live
+in, and its GPU texture. A game that makes and drops them continually ran the low memory out and crashed on the null an
+allocation returned. A texture (with all its surfaces) or a vertex or index buffer whose last reference is released now
+waits until nothing has it bound (binding takes no reference here), then gives back its CPU copies, its GPU texture and
+its buffer memory, at the next `Present`. A standalone surface (`CreateOffscreenPlainSurface`, `CreateRenderTarget`, `CreateDepthStencilSurface`) is a
+one-level texture the program never sees; that texture held a reference of its own, so no such surface was ever freed:
+C&C 3's LAN lobby makes and drops hundreds a second and ran the low memory out in two minutes. The frame-rate line reports
+the low memory in use (`low memory N MB`). Work already queued keeps what it uses (command buffers retain their
+textures; buffer memory is reused only once the GPU is done with it). The object itself stays, so a stale handle a
+state block still holds finds an empty resource rather than freed memory; a buffer locked again gets memory again.
+
+**`StretchRect` scales** (`d3d9_device.m` `blit_scaled`). Between rectangles of different sizes it draws the source
+into the destination, point or linear filtered as asked; it copied the top-left part unscaled. Games shrink the frame
+into a small texture for distortion effects (heat haze, smoke, C&C 3's Tiberium glow): they sampled a magnified corner
+of the screen, smeared in long streaks across the view.
+
+**The display mode** (`d3d9_api.m` `GetAdapterDisplayMode`) is an exclusive-fullscreen device's mode while there is
+one, otherwise the display's own pixels. It was the size in points: a game offered resolutions only up to it (so
+native resolution was dropped when options were applied) and placed effects sized from it off.
+
+**Coming back to a fullscreen game** (`w64/win.h` `fs_space_watch`): arriving on the Space that holds its window
+activates it, as switching to a fullscreen game does on Windows; its device stayed lost otherwise and it drew nothing. The fullscreen window is told of the application's activation as on Windows (`WM_ACTIVATEAPP`, `WM_ACTIVATE`,
+`w64/user32.m`), from the application becoming active or inactive rather than only from its window becoming key, which
+could be missed on the way back.
+
+**Texture uploads** (`d3d9_device.m` `upload_sub_rect`). `UnlockRect` uploads only the rectangle `LockRect` named
+(whole blocks for compressed formats), not the whole level: a game that redraws a large texture in small pieces (C&C 3
+rebuilds its map textures cell by cell after a Reset) made thousands of uploads of the full texture. Uploads are staged
+in the frame's transient ring and share one blit pass until the next draw, instead of a new Metal buffer and a break in
+the command stream each. The five-second frame-rate line reports uploads and their size.
+
+**`UpdateSurface`** follows its definition: the source rectangle and destination point (it copied the whole source to
+the corner), clipped to both surfaces, whole blocks for compressed formats, and `D3DERR_INVALIDCALL` instead of a crash
+when a surface has no memory.
+
+**Indexed draws without an index buffer** fail with `D3DERR_INVALIDCALL` as on Windows; handed to Metal they crashed
+the driver.
+
+**Point sprites** (`d3d9_shader.c`, `d3d9_draw.m`). With `D3DRS_POINTSPRITEENABLE` texture coordinate set 0 is the
+position across each sprite (Metal's `point_coord`), and the size is the one the vertex shader writes (`oPts`, or a
+vs_3_0 output declared PSIZE) rather than `D3DRS_POINTSIZE` alone. Each sprite sampled one texel and drew a flat square:
+C&C 3's Tiberium gas and smoke were hard-edged rectangles. The shader key keeps its layout (points 1, sprites 2), so
+recorded shaders stay valid.
+
+**Relative constant reads** (`d3d9_shader.c` `gen_crel`). `c[a0.x + n]` reads, as on D3D9 hardware, the value the
+shader defines itself (`def`) for a register it defines, the program's constant for any other register, and 0 outside
+the register file (as Wine and DXVK). The index was clamped into the program's constants, so a shader that keeps a table
+in its own definitions read whatever the game had last set there instead: C&C 3's particles take their quad corners from
+`def c21..c24` through `c[a0.w + 16]`, and the smoke and dust of a finished refinery became beams and a sheet of haze
+over the whole view as the harvester came out (the "white flash"). Shaders cached in a game's `learn/d3d9` were
+translated before; delete them after updating.
+
+**Shaders** (`d3d9_shader.c`). Pixel shader 3.0 input registers indexed by the loop counter (`v[aL + n]`) are read from
+an array of the declared inputs (they produced a shader that did not compile, so the effect was missing).
+
+**Adapter identity** (`d3d9_api.m`, `d3d9_device.m`, `dxdiag.c`). The adapter reports a GeForce 8800 GTX with 768 MB
+(driver 169.21). Games of the time choose their detail from tables that know nothing newer: an unknown card, or the
+7800 GTX reported before, got their lowest settings on GPUs many times faster.
+
+**Uploads between draws no longer end the render pass** (`d3d9_device.m` `upload_sub_rect`). Each texture upload ended
+the open render pass for a blit, and the next draw started a new pass that loaded the whole colour and depth targets
+again. In some C&C 3 scenes the game updates thousands of small textures between draws (44,000 in 5 s): the game
+froze for seconds at 4.7 fps, and the sound broke up. A texture the open command buffer has not used yet is now filled
+in a command buffer of its own, committed just before the frame's (the GPU runs them in that order); only a texture the
+frame already used is updated in order inside it, as before. Every texture the GPU touches is marked with the command
+buffer that used it (`gpu_use`: draws, render targets, copies, fills, mipmap generation).
+
+**Less work per draw** (`d3d9_draw.m`). Everything runs as translated Intel code under Rosetta, Metal included, and
+C&C 3 makes 300-700 draws a frame, so each draw now sends only what changed since the previous draw in the same
+encoder: pipeline, depth/stencil state, stencil reference, blend colour, cull, fill, depth clip, depth bias, viewport,
+scissor, driver constants, textures, samplers and vertex buffers (offsets alone through `setVertexBufferOffset`). The
+front-face winding is set once per encoder. Shader constants were 7.5 KB per draw (all 256 vertex and 224 pixel
+registers): a shader without relative reads now gets the registers up to the highest it reads (its `def` values are
+literals in its code), and they are sent again only after the program changed constants, applied a state block or reset
+(`d->cgen`). Consecutive draws with the same pipeline key skip the dictionary lookup. Two `getenv` calls per draw are
+read once.
+
+**Anisotropic filtering** (`d3d9_draw.m` `sampler`). Like a driver's control panel, mipmapped textures filtered linearly
+are sampled with 16x anisotropy (`PE2_ANISO=`, 0 = only what the game asks for): ground seen at an angle stays sharp.
+Textures without mipmaps (interface, text) and point-filtered ones keep the game's settings.
+
+**Pipelines made ahead** (`d3d9_draw.m` `d3d_warm_pipelines`, `pipeline_make`). A scene that brings in new effects (a
+building blowing up: fire, smoke, debris) made dozens of pipelines in one frame, each compiling two shaders from learned
+Metal source: up to 400 ms at once. Every pipeline made is now recorded in `learn/d3d9/pipelines.bin` by what Metal
+needs to make it (function names, vertex layout, attachment formats, blending; `pdesc`), and when the game creates its
+device the recorded ones are made on background threads (`dispatch_apply`). A draw finds a made pipeline by that
+description, so the game's object ids, which change between runs, do not matter. The first session of a game records;
+later ones start warm. `PE2_NO_WARM=1` turns it off. The pipeline key also leaves out what the pipeline is not made
+from (blend factors with blending off, strides and step rates of streams the layout does not read), which made a new
+pipeline for the same one.
+
+**Messages about missing functions once** (`k32_core.c`). A failed `GetProcAddress` was written to stderr every time,
+traced or not, and `LoadLibrary` with tracing: C&C 3 asks for `d3d9.dll` and its `DebugSetMute` a dozen times a second
+for its whole run (12% of the CPU samples at the menu were these writes). Each name is now reported its first 3 times.
+
+## Diagnostics
+
+The frame-rate line (every 5 s, `PE2_TRACE=1`) gives, besides frames, draws and uploads: render passes per frame,
+uploads that ended a pass, uploads moved ahead, CPU waits for the GPU (locks of buffers still in use, with time), time
+spent waiting for a frame slot (GPU-bound), pipelines made (with time, and how many the warm-up had ready), and the CPU
+time spent converting uploads and in draw calls. A slow window where these add up to little is the program's own work.
+
+**`PE2_PROF=1`: a CPU profiler** (`runtime/prof.c`). Apple's samplers (`sample`, Instruments) cannot read a process
+under Rosetta: every frame is `???`. The runtime samples itself instead: a profiling timer interrupts the busy thread
+1000 times a second and counts the interrupted address. Every `PE2_PROF_SECS` (5) seconds stderr gets `prof:` lines (all
+threads), `prof main:` lines (the program's main thread only: what makes a frame late) and `prof yields:` (who calls
+`Sleep(0)`/`SwitchToThread`, by the program's return address). Rewritten code is named by its original address
+(`m__L008675d4` is 0x8675d4 in the game's own image), so a hot spot can be looked up in a disassembly of the
+original program. Attaching `lldb` to the game also works, but stops it (sound loops, the picture freezes) for as long
+as the debugger holds it.
+
+**`PE2_INPUTLOG=1`** logs every key the window layer receives (Mac key code, the virtual key and scancode it becomes),
+`TranslateMessage` calls, and DirectInput acquisition and reads: where a key gets lost.
+
+- `PE2_TRACE_BURST=n` logs the next `n` calls into the runtime and window messages after each Direct3D `Reset`: what a
+ game does on its way back from the background, without a full trace.
+- `d3d: N fps, D draws/frame, U uploads (M MB)` every five seconds.
+- `PE2_DRAWLOG_TRIGGER=`: when the file appears (`touch` it), every draw of the next `PE2_DRAWLOG_FRAMES` frames
+ (60) is logged and, with `PE2_SHOT_DIR`, every third frame saved as a picture. Catches an artifact that lasts a moment.
+- `PE2_SKIP_SHADER=vs_,ps_`: drop the draws that use those shaders (names as in the draw log), to find the
+ effect behind an artifact by bisection.
+- `W64_MSGLOG=1`: log every message dispatched to a window (mouse motion aside).
+
+## Method (what worked, for the next game)
+
+- **Measure before changing.** Every fix above came from a counter or a log line that named the cost; guesses (a
+ shader prewarm, earlier) measured useless and were reverted. The frame-rate line is the first place to look: a slow
+ window with few draws, no pass breaks and no GPU waits is not a graphics problem.
+- **Under Rosetta everything is translated**: the game, the runtime, and Metal's own Intel code. Work per draw costs
+ several times what it would natively, so sending only what changed pays even when the GPU is idle.
+- **Apple GPUs are tile-based**: ending a render pass stores the whole target and the next pass loads it again. Anything
+ that ends a pass between draws (an upload, a copy, a query) costs a full-screen store and load at 3456x2234; count
+ passes per frame.
+- **A hitch that comes with new things on screen** (an explosion, a new unit) is a first use: a pipeline, a shader, a
+ texture format. Make it ahead, record it for the next run, and normalise keys so one thing is not made twice.
+- **Converting is fast now** (a few minutes for C&C 3); a converter that sits at "Rewriting" with no output is looping,
+ not slow: Python's `faulthandler.dump_traceback_later` on a copy of the run shows where.
+- **Test loop**: build into a copy of the app, install it only once the game is closed (replacing the binary of a
+ running program can kill it), keep the previous build for going back, and watch the trace with a filter for slow
+ windows and errors while someone plays. A test of another app's focus (switching to a terminal to report) changes
+ what the game does: fullscreen games pause and minimise in the background.
+
+## Not solved yet
+
+- **No pause menu on return.** On Windows C&C 3 is said to show its pause menu when it comes back from the background;
+ here it resumes (Escape opens the menu normally). The window is now minimised in the background and DirectInput loses
+ its devices, as on Windows, and the game receives `WM_ACTIVATEAPP`, `WM_ACTIVATE` and `WM_SIZE` in the Windows order,
+ yet it does not pause: its `WM_ACTIVATEAPP` handler pauses through an object (at 0xbe1a24 in 1.9) that is null in a
+ skirmish here. Not yet known whether that object exists on Windows or the menu comes from elsewhere.
+- MSAA: `CheckDeviceMultiSampleType` offers none, so a game's anti-aliasing option stays off.
+- C&C 3 draws at 30 frames per second: its simulation runs at 30 ticks and draws one frame per tick, as on Windows.
+ Raising it would speed up the game, not smooth it.
+- LAN: the lobby, hosting and broadcasting work on one Mac; a game between two computers is not yet tried.
+- Each Direct3D object keeps a 48-byte record in low memory after it is freed (so a stale handle never reaches freed
+ memory): a program that makes hundreds of objects a second grows by about 0.1 MB a second (C&C 3's LAN lobby).
+- **The game's own CPU work at some moments** (a building destroyed, many units dying): Direct3D accounts for under
+ 200 ms of such a 5 s window, so the rest is the program (rewritten Intel code under Rosetta) or the runtime
+ services it calls. `PE2_PROF` measures it. Seen so far: 70% of all samples are `sched_yield` from `Sleep(0)` /
+ `SwitchToThread` loops in game threads (as on Windows, where such a loop also takes a core) and 2.3% are
+ `pe2_fix_target` (indirect branches to addresses the rewriter did not map ahead).
+- **Losing focus during start-up.** Kane's Wrath once stayed on its first screen (one draw a frame) after the window
+ went to the background before the device was reset; coming back to it did not resume loading. Restarting with the
+ game in front worked.
+- **Enter (chat) and Tab (statistics) reported doing nothing in a match**; not yet reproduced with `PE2_INPUTLOG`.
+- Translated shaders cached in a game's `learn/d3d9` are not regenerated when the translator changes; delete them after
+ changing `d3d9_shader.c`.
diff --git a/pe2mac/macho32.py b/pe2mac/macho32.py
index 18a0332..d5f48fe 100644
--- a/pe2mac/macho32.py
+++ b/pe2mac/macho32.py
@@ -225,10 +225,13 @@ def u32(self, rva):
def is_exec(self, rva):
return any(va <= rva < va + vs and ch for _, va, vs, _, _, ch in self.sections)
- def code_bytes(self, rva):
+ def code_bytes(self, rva, n=None):
+ """The code bytes from rva to the end of its section (at most n of them), and where that section ends. A
+ decoder reading one instruction asks for 16: slicing to the section's end copied megabytes per instruction."""
for _, va, vs, rs, rp, ch in self.sections:
if va <= rva < va + rs and ch:
- return self.b[rp + (rva - va):rp + rs], va + rs
+ a = rp + (rva - va)
+ return self.b[a:rp + rs if n is None else min(a + n, rp + rs)], va + rs
return None, None
def text_range(self):
diff --git a/pe2mac/rewrite.py b/pe2mac/rewrite.py
index 6495d73..b9261b7 100644
--- a/pe2mac/rewrite.py
+++ b/pe2mac/rewrite.py
@@ -35,7 +35,7 @@
# Instructions that do not exist in 64-bit mode or change the meaning of rcx/rsp upper halves. Reaching one is an
# error the rewriter reports by name instead of emitting something subtly wrong.
UNSUPPORTED = {'aaa', 'aas', 'daa', 'das', 'aam', 'aad', 'bound', 'into', 'lds', 'les', 'arpl', 'salc',
- 'jcxz', 'pushaw', 'popaw', 'in', 'out', 'insb', 'insd',
+ 'pushaw', 'popaw', 'in', 'out', 'insb', 'insd',
'outsb', 'outsd', 'sysenter', 'retf', 'iretd', 'lcall', 'ljmp'}
LOOPS = {'loop', 'loope', 'loopne'}
@@ -53,7 +53,7 @@
def flow_mn(m):
"""The mnemonic of a branch without the prefixes that do not change it: 'repz ret' (the AMD two-byte return
that compilers emit after a jump target) and MPX 'bnd' are plain ret/jmp/call/jcc."""
- for p in ('repz ', 'rep ', 'bnd '):
+ for p in ('repz ', 'rep ', 'bnd ', 'notrack '):
if m.startswith(p) and m[len(p):].split(' ')[0] in {'ret', 'jmp', 'call'} | JCC:
return m[len(p):]
return m
@@ -92,6 +92,9 @@ def __init__(self, path, newbase=None):
chars = struct.unpack_from(' 10), or None."""
+ src = None # unoptimized code: "cmp [ebp-x], N; ja; mov eax, [ebp-x]; jmp [eax*4+t]"
+ memkey = lambda o: (o.mem.base, o.mem.index, o.mem.scale, o.mem.disp, o.size)
+ for d in range(1, 40):
+ ins = self.insns.get(r - d)
+ if ins is None or r - d + ins.size > r: continue
+ ops = ins.operands
+ if ins.mnemonic == 'mov' and src is None and len(ops) == 2 and ops[0].type == X.X86_OP_REG and ops[0].reg == index \
+ and ops[1].type == X.X86_OP_MEM:
+ src = memkey(ops[1]); continue
+ if ins.mnemonic == 'cmp' and len(ops) == 2 and ops[1].type == X.X86_OP_IMM and 0 <= ops[1].imm < 4096 and (
+ (ops[0].type == X.X86_OP_REG and ops[0].reg == index) or (ops[0].type == X.X86_OP_MEM and src == memkey(ops[0]))):
+ return ops[1].imm + 1
+ if flow_mn(ins.mnemonic) in ('jmp', 'ret', 'call'): return None # past the code that leads here
+ return None
+
+ def _in_code(self, v):
+ v = (v - self.pe.base) & 0xffffffff
+ for a, b in self._code:
+ if a <= v < b: return True
+ return False
+
+ def discover_unrelocated(self):
+ """Code found through guessed pointers (pointer_targets). A guess is only a start for decoding, judged like a
+ relocation target (speculatively), never a change to the program's data: these words are not patched, so a
+ value that only looks like an address stays as it was, and a branch through a real one is mapped by the
+ loader's address map (pe2_fix_target). New code holds new pointers, so rounds repeat until nothing is new."""
+ pe, kept, tried, dropped, rnd, sure_tried = self.pe, 0, set(), [], 0, set()
+ def attempt(cands):
+ nonlocal kept
+ acc, rej = 0, []
+ for c in cands:
+ if c in self.insns:
+ self.entries.add(c); continue
+ # a start inside an instruction another guess decoded is still judged on its own: that decode may be
+ # the guess that was wrong (streams may overlap, see decode_from)
+ new = self.decode_from(c, speculative=True)
+ if new is None:
+ rej.append(c); continue
+ self.commit(new); self.entries.add(c); kept += 1; acc += 1
+ while self.pending_calls: # direct callees of accepted code are real code
+ todo = sorted(self.pending_calls - set(self.insns)); self.pending_calls = set()
+ for c in todo:
+ self.commit(self.decode_from(c)); self.entries.add(c)
+ return acc, rej
+ while True:
+ # switch-table targets are code without guessing: decoded the trusted way first, each once (one that
+ # decodes to nothing, e.g. past the section's file bytes, stays undecoded: retrying it looped forever)
+ sure = sorted(c for c in getattr(self, '_sure', ()) if c not in self.insns and c not in sure_tried and pe.is_exec(c))
+ sure_tried.update(sure)
+ for c in sure:
+ self.commit(self.decode_from(c)); self.entries.add(c)
+ for c in getattr(self, '_sure', ()): self.entries.add(c)
+ if sure:
+ while self.pending_calls:
+ todo = sorted(self.pending_calls - set(self.insns)); self.pending_calls = set()
+ for c in todo: self.commit(self.decode_from(c)); self.entries.add(c)
+ print(f' switch targets: {len(sure)} decoded, {len(self.insns)} instructions', file=sys.stderr, flush=True)
+ # new guesses, each tried once, until the code they add holds no new ones
+ new_t = sorted(c for c in self.pointer_targets() - tried
+ if pe.is_exec(c) and not pe.is_string_literal(c) and c not in self.data_targets)
+ if not new_t and any(c not in self.insns and c not in sure_tried and pe.is_exec(c) for c in self._sure):
+ continue # switch targets found by the last scan come first
+ if new_t:
+ tried.update(new_t); acc, rej = attempt(new_t); dropped += rej; rnd += 1
+ print(f' guess round {rnd}: {len(new_t)} new, {acc} kept, {len(self.insns)} instructions', file=sys.stderr, flush=True)
+ continue
+ # then the refused ones once more: their path may now merge into code found since
+ acc, dropped = attempt(dropped); rnd += 1
+ print(f' guess retry {rnd}: {acc} kept, {len(dropped)} refused, {len(self.insns)} instructions', file=sys.stderr, flush=True)
+ if not acc:
+ break
+ return kept
def keep_original(self, t):
"""an address that stays the original one wherever the program holds it (code immediates and data alike, so
@@ -417,10 +544,16 @@ def emit_insn(self, rva, insn, nxt):
if m in UNSUPPORTED:
self.problems[f'unsupported:{m}'].append(rva)
return ['ud2']
- if m in ('int3', 'hlt', 'int', 'ud2', 'int1', 'icebp', 'into'):
+ if m in ('int3', 'hlt', 'int', 'ud2', 'ud0', 'ud1', 'int1', 'icebp', 'into'):
return ['ud2']
if m.startswith('bnd '):
m = m[4:] # the MPX prefix on a branch changes nothing without MPX
+ if m == 'jcxz' and ops[0].type == X.X86_OP_IMM and ops[0].imm - self.pe.base in self.insns: # its 0x67 prefix is not addressing
+ # jump if cx (the low 16 bits) is 0, flags untouched: no 64-bit form, so test a zero-extended copy with
+ # jecxz and put rcx back on both paths (mov, movzx and jecxz change no flags)
+ k = self.L(rva) + '_cz'
+ return ['mov r11, rcx', 'movzx ecx, cx', f'jecxz {k}', 'mov rcx, r11', f'jmp {self.L(nxt)}',
+ f'{k}:', 'mov rcx, r11', f'jmp {self.L(ops[0].imm - self.pe.base)}']
if insn.prefix[3] == 0x67:
raise ValueError('16-bit addressing') # no 32-bit program addresses memory this way; bytes of data
if any(op.type == X.X86_OP_MEM and op.mem.segment == X.X86_REG_FS for op in ops) and \
@@ -430,11 +563,16 @@ def emit_insn(self, rva, insn, nxt):
return ['ud2'] # far transfer through a 16:32 pointer: never real code here
if insn.prefix[0] in (0xf0,) and m in ('push', 'pop', 'call', 'jmp', 'ret'):
raise ValueError('lock on control flow')
- if (m in JCC or m in ('jecxz', 'jmp', 'call') or m in LOOPS) and ops[0].type == X.X86_OP_IMM \
+ if (m in JCC or m in ('jecxz', 'jcxz', 'jmp', 'call') or m in LOOPS) and ops[0].type == X.X86_OP_IMM \
and ops[0].imm - self.pe.base not in self.insns:
# only reachable through bytes that were never real code (data decoded after a no-return call)
return ['ud2']
- if m in JCC or m == 'jecxz' or (m == 'jmp' and ops[0].type == X.X86_OP_IMM):
+ if m == 'jecxz':
+ # only a short (8-bit) form exists, and the rewritten code between it and its target may be far longer:
+ # it reaches a local label, which jumps anywhere
+ k = self.L(rva) + '_cz'
+ return [f'jecxz {k}', f'jmp {self.L(nxt)}', f'{k}:', f'jmp {self.L(ops[0].imm - self.pe.base)}']
+ if m in JCC or (m == 'jmp' and ops[0].type == X.X86_OP_IMM):
return [f'{m} {self.L(ops[0].imm - self.pe.base)}']
if m == 'call':
if ops[0].type == X.X86_OP_IMM:
@@ -459,9 +597,10 @@ def emit_insn(self, rva, insn, nxt):
return ['mov r11d, dword ptr [esp]', 'lea esp, [esp + 4]', f'mov {self.operand(ops[0])}, r11d']
if m in LOOPS:
# in 64-bit mode loop counts in rcx; keep it to ecx: decrement without touching flags, then branch
- t = self.L(ops[0].imm - self.pe.base); out = ['lea ecx, [ecx - 1]', f'jecxz {self.L(nxt)}']
+ t = self.L(ops[0].imm - self.pe.base); k = self.L(rva) + '_lz'
+ out = ['lea ecx, [ecx - 1]', f'jecxz {k}'] # the same short reach: a local label, then the way on
out.append(f'jmp {t}' if m == 'loop' else f'{"je" if m == "loope" else "jne"} {t}')
- return out
+ return out + [f'{k}:', f'jmp {self.L(nxt)}']
if m == 'pushal':
return ['mov r11d, esp', 'lea esp, [esp - 32]', 'mov dword ptr [esp + 28], eax', 'mov dword ptr [esp + 24], ecx',
'mov dword ptr [esp + 20], edx', 'mov dword ptr [esp + 16], ebx', 'mov dword ptr [esp + 12], r11d',
@@ -473,7 +612,7 @@ def emit_insn(self, rva, insn, nxt):
if m == 'enter':
if ops[1].imm != 0:
raise ValueError('enter with nesting level')
- return ['mov r11d, ebp', 'lea esp, [esp - 4]', 'mov dword ptr [esp], r11d', 'mov ebp, esp', f'lea esp, [esp - {ops[0].imm}]']
+ return ['mov r11d, ebp', 'lea esp, [esp - 4]', 'mov dword ptr [esp], r11d', 'mov ebp, esp', f'lea esp, [esp - {ops[0].imm & 0xffff}]'] # an unsigned 16-bit size
if m == 'leave':
return ['mov esp, ebp', 'mov ebp, dword ptr [esp]', 'lea esp, [esp + 4]']
if m == 'pushfd':
@@ -518,7 +657,7 @@ def emit(self, out):
for ln in lines:
w(f' {ln}\n')
# fall-through must reach the instruction at nxt; with overlapping streams that may not be the next label
- falls = flow_mn(insn.mnemonic) not in ('ret', 'jmp', 'int3', 'hlt', 'ud2') and insn.mnemonic not in UNSUPPORTED
+ falls = flow_mn(insn.mnemonic) not in ('ret', 'jmp', 'int3', 'hlt', 'ud2', 'ud0', 'ud1') and insn.mnemonic not in UNSUPPORTED
if falls:
following = order[i + 1] if i + 1 < len(order) else None
if nxt not in self.insns:
diff --git a/runtime/client_misc.c b/runtime/client_misc.c
index faee74e..a56cfe9 100644
--- a/runtime/client_misc.c
+++ b/runtime/client_misc.c
@@ -67,7 +67,19 @@ static const char *DID_M[] = {"QueryInterface", "AddRef", "Release", "GetCapabil
"GetObjectInfo", "GetDeviceInfo", "RunControlPanel", "Initialize", "CreateEffect", "EnumEffects", "GetEffectInfo",
"GetForceFeedbackState", "SendForceFeedbackCommand", "EnumCreatedEffectObjects", "Escape", "Poll", "SendDeviceData",
"EnumEffectsInFile", "WriteEffectToFile", "BuildActionMap", "SetActionMap", "GetImageInfo"};
-typedef struct { uint32_t vtbl, ref, kind, exclusive, acquired; int32_t lx, ly, lz; uint8_t lastbtn[8]; uint32_t seq; } didev;
+typedef struct { uint32_t vtbl, ref, kind, exclusive, acquired; int32_t lx, ly, lz; uint8_t lastbtn[8]; uint32_t seq; uint32_t fg, epoch; } didev;
+/* Focus, as Windows gives DirectInput: a DISCL_FOREGROUND device is unacquired when its program is deactivated; the
+ next read says DIERR_INPUTLOST, and Acquire fails (DIERR_OTHERAPPHASPRIO) until the program is active again. Games
+ take the lost input as their cue to pause (C&C 3 opens its pause menu on return). The window layer reports the
+ program's activation here (pe2_input_focus). */
+static volatile int g_inactive; static volatile uint32_t g_focus_epoch;
+void pe2_input_focus(int active) { if (!active && !g_inactive) g_focus_epoch++; g_inactive = !active; }
+static int di_lost(didev *d) { /* a foreground device that lost its acquisition to a deactivation */
+ if (!d->fg || !d->acquired || (!g_inactive && d->epoch == g_focus_epoch)) return 0;
+ d->acquired = 0; if (d->kind == 2) pe2_set_mouse_capture(0);
+ if (getenv("PE2_INPUTLOG")) fprintf(stderr, "pe2: DInput kind %u input lost (program deactivated)\n", d->kind);
+ return 1;
+}
static uint32_t g_di_vt, g_did_vt;
NATIVE(dinput8, DirectInput8Create, 5) {
if (!g_di_vt) g_di_vt = com_vtable("IDirectInput8A", DI_M, 11);
@@ -101,8 +113,9 @@ COM(IDirectInputDevice8A, EnumObjects, 4) { return 0; }
COM(IDirectInputDevice8A, GetProperty, 3) { return 0; }
COM(IDirectInputDevice8A, SetProperty, 3) { return 0; }
COM(IDirectInputDevice8A, Acquire, 1) {
- didev *d = P(a[0]); if (d->acquired) return 1; /* S_FALSE, no effect: pending motion must survive */
- d->acquired = 1;
+ didev *d = P(a[0]); di_lost(d); if (d->acquired) return 1; /* S_FALSE, no effect: pending motion must survive */
+ if (d->fg && g_inactive) return 0x80070005; /* DIERR_OTHERAPPHASPRIO: in the background */
+ d->acquired = 1; d->epoch = g_focus_epoch;
if (getenv("PE2_INPUTLOG")) fprintf(stderr, "pe2: DInput acquire kind %u exclusive %u\n", d->kind, d->exclusive);
if (d->kind == 2) { if (d->exclusive && !getenv("PE2_NO_MOUSE_CAPTURE")) pe2_set_mouse_capture(1); pe2_mouse_dx = pe2_mouse_dy = pe2_mouse_dz = 0; }
return 0;
@@ -111,6 +124,7 @@ COM(IDirectInputDevice8A, Unacquire, 1) { didev *d = P(a[0]); d->acquired = 0; i
static void pump_if_main(void) { if (pthread_main_np()) pe2_pump_events(); }
COM(IDirectInputDevice8A, GetDeviceState, 3) {
didev *d = P(a[0]); pump_if_main();
+ if (di_lost(d)) return 0x8007001E; /* DIERR_INPUTLOST */
if (!d->acquired) return 0x8007000C; /* DIERR_NOTACQUIRED */
if (d->kind == 1) { memcpy(P(a[2]), pe2_dik, a[1] < 256 ? a[1] : 256); return 0; }
int32_t *m = P(a[2]); memset(m, 0, a[1]);
@@ -122,6 +136,7 @@ COM(IDirectInputDevice8A, GetDeviceData, 5) {
didev *d = P(a[0]); pump_if_main();
uint32_t cap = *(uint32_t *)P(a[3]), n = 0, osz = a[1] ? a[1] : 20;
uint8_t *out = a[2] ? P(a[2]) : 0;
+ if (di_lost(d)) { *(uint32_t *)P(a[3]) = 0; return 0x8007001E; } /* DIERR_INPUTLOST */
if (!d->acquired) { *(uint32_t *)P(a[3]) = 0; return 0x8007000C; }
#define EMIT(ofs, data) do { if (out && n < cap) { uint32_t *e = (uint32_t *)(out + n * osz); memset(e, 0, osz); e[0] = (ofs); e[1] = (data); e[2] = (uint32_t)(clock() / 1000); e[3] = d->seq++; } n++; } while (0)
if (d->kind == 1) {
@@ -138,14 +153,16 @@ COM(IDirectInputDevice8A, GetDeviceData, 5) {
pe2_mouse_press[b] = 0; EMIT(12 + b, pe2_mouse_btn[b]); d->lastbtn[b] = pe2_mouse_btn[b]; }
}
*(uint32_t *)P(a[3]) = n < cap ? n : cap;
+ if (n && getenv("PE2_INPUTLOG")) { fprintf(stderr, "pe2: DInput %s read %u:", d->kind == 1 ? "keys" : "mouse", n < cap ? n : cap);
+ for (uint32_t i = 0; out && i < n && i < cap && i < 6; i++) { uint32_t *e = (uint32_t *)(out + i * osz); fprintf(stderr, " %#x=%d", e[0], (int32_t)e[1]); } fputc('\n', stderr); }
return 0;
}
COM(IDirectInputDevice8A, SetDataFormat, 2) { return 0; }
COM(IDirectInputDevice8A, SetEventNotification, 2) { return 0; }
-COM(IDirectInputDevice8A, SetCooperativeLevel, 3) { didev *d = P(a[0]); d->exclusive = a[2] & 1; return 0; }
+COM(IDirectInputDevice8A, SetCooperativeLevel, 3) { didev *d = P(a[0]); d->exclusive = a[2] & 1; d->fg = (a[2] & 4) != 0; if (getenv("PE2_INPUTLOG")) fprintf(stderr, "pe2: DInput kind %u cooperative %#x\n", d->kind, a[2]); return 0; }
COM(IDirectInputDevice8A, GetDeviceInfo, 2) { uint32_t *i = P(a[1]); uint32_t sz = i[0]; memset(i + 1, 0, sz - 4); return 0; }
COM(IDirectInputDevice8A, GetObjectInfo, 4) { return 0x80070057; }
-COM(IDirectInputDevice8A, Poll, 1) { pump_if_main(); return 1; } /* DI_NOEFFECT */
+COM(IDirectInputDevice8A, Poll, 1) { pump_if_main(); return di_lost(P(a[0])) ? 0x8007001E : 1; } /* DI_NOEFFECT */
/* ---------------- winmm (waveOut has no device; DirectSound is in dsound.c) ---------------- */
NATIVE(winmm, timeGetTime, 0) { struct timespec t; clock_gettime(CLOCK_UPTIME_RAW, &t); return (uint32_t)(t.tv_sec * 1000 + t.tv_nsec / 1000000); }
diff --git a/runtime/d3d9_api.m b/runtime/d3d9_api.m
index 53e643a..cfdddc4 100644
--- a/runtime/d3d9_api.m
+++ b/runtime/d3d9_api.m
@@ -29,24 +29,51 @@
COM(IDirect3D9, GetAdapterCount, 1) { return 1; }
COM(IDirect3D9, GetAdapterIdentifier, 4) {
uint8_t *id = P(a[3]); memset(id, 0, 1100);
- strcpy((char *)id, "nv4_disp.dll"); strcpy((char *)id + 512, "NVIDIA GeForce 7800 GTX"); strcpy((char *)id + 1024, "\\\\.\\DISPLAY1");
- /* DriverVersion 6.14.10.8198 (ForceWare 81.98): LowPart = 10 << 16 | 8198, HighPart = 6 << 16 | 14.
- The demo asks for at least the 77.30 driver it shipped with and shows an "update your driver" box below that. */
- uint32_t *v = (uint32_t *)(id + 1056); v[0] = (10u << 16) | 8198; v[1] = (6u << 16) | 14;
- v[2] = 0x10de; v[3] = 0x0091; v[4] = 0; v[5] = 0xa1;
+ /* The fastest card of the Direct3D 9 era, so a game's own hardware table (which knows nothing newer: an unknown
+ card gets its lowest settings) offers its highest detail on a Mac GPU that outruns it many times over. */
+ strcpy((char *)id, "nv4_disp.dll"); strcpy((char *)id + 512, "NVIDIA GeForce 8800 GTX"); strcpy((char *)id + 1024, "\\\\.\\DISPLAY1");
+ /* DriverVersion 6.14.11.6921 (ForceWare 169.21): LowPart = 11 << 16 | 6921, HighPart = 6 << 16 | 14.
+ A demo asks for at least the 77.30 driver it shipped with and shows an "update your driver" box below that. */
+ uint32_t *v = (uint32_t *)(id + 1056); v[0] = (11u << 16) | 6921; v[1] = (6u << 16) | 14;
+ v[2] = 0x10de; v[3] = 0x0191; v[4] = 0; v[5] = 0xa2;
return D3D_OK;
}
static const uint32_t MODES[][2] = {{640,480},{800,600},{1024,768},{1152,864},{1280,720},{1280,768},{1280,800},{1280,960},
{1280,1024},{1360,768},{1440,900},{1600,900},{1600,1200},{1680,1050},{1920,1080}};
-#define NMODES (sizeof MODES / sizeof *MODES)
-COM(IDirect3D9, GetAdapterModeCount, 3) { return a[2] == 22 || a[2] == 23 ? NMODES : 0; }
+/* the list above, then the Mac display's own sizes (its pixels and its points: a Retina screen's native resolution
+ and the size the system draws at), in ascending order without repeats */
+static uint32_t g_modes[24][2]; static uint32_t g_nmodes;
+static void modes_init(void) {
+ if (g_nmodes) return;
+ uint32_t extra[2][2] = {{0, 0}, {0, 0}};
+ CGDirectDisplayID dpy = CGMainDisplayID(); CGRect b = CGDisplayBounds(dpy);
+ extra[0][0] = (uint32_t)b.size.width; extra[0][1] = (uint32_t)b.size.height;
+ CGDisplayModeRef dm = CGDisplayCopyDisplayMode(dpy);
+ if (dm) { extra[1][0] = (uint32_t)CGDisplayModeGetPixelWidth(dm); extra[1][1] = (uint32_t)CGDisplayModeGetPixelHeight(dm); CGDisplayModeRelease(dm); }
+ uint32_t all[24][2], n = 0;
+ for (size_t i = 0; i < sizeof MODES / sizeof *MODES; i++) { all[n][0] = MODES[i][0]; all[n][1] = MODES[i][1]; n++; }
+ for (int i = 0; i < 2; i++) if (extra[i][0] && extra[i][1]) { all[n][0] = extra[i][0]; all[n][1] = extra[i][1]; n++; }
+ for (uint32_t i = 0; i < n; i++) for (uint32_t j = i + 1; j < n; j++)
+ if (all[j][0] < all[i][0] || (all[j][0] == all[i][0] && all[j][1] < all[i][1])) { uint32_t t0 = all[i][0], t1 = all[i][1]; all[i][0] = all[j][0]; all[i][1] = all[j][1]; all[j][0] = t0; all[j][1] = t1; }
+ for (uint32_t i = 0; i < n; i++) if (!g_nmodes || all[i][0] != g_modes[g_nmodes - 1][0] || all[i][1] != g_modes[g_nmodes - 1][1]) { g_modes[g_nmodes][0] = all[i][0]; g_modes[g_nmodes][1] = all[i][1]; g_nmodes++; }
+}
+COM(IDirect3D9, GetAdapterModeCount, 3) { modes_init(); return a[2] == 22 || a[2] == 23 ? g_nmodes : 0; }
COM(IDirect3D9, EnumAdapterModes, 5) {
- if (a[3] >= NMODES) return D3DERR_INVALIDCALL;
- uint32_t *m = P(a[4]); m[0] = MODES[a[3]][0]; m[1] = MODES[a[3]][1]; m[2] = 60; m[3] = a[2]; return D3D_OK;
+ modes_init(); if (a[3] >= g_nmodes) return D3DERR_INVALIDCALL;
+ uint32_t *m = P(a[4]); m[0] = g_modes[a[3]][0]; m[1] = g_modes[a[3]][1]; m[2] = 60; m[3] = a[2]; return D3D_OK;
}
+/* The display's current mode, as Windows reports it: an exclusive-fullscreen device's mode while there is one (the
+ display was switched to it), otherwise the display's own pixels (a Retina screen's native size; its size in points
+ is what the system draws at, not a mode). A game offers resolutions up to this one and may size full-screen
+ effect textures from it: the size in points made it drop native resolution and place such effects off. */
COM(IDirect3D9, GetAdapterDisplayMode, 3) {
- CGRect b = CGDisplayBounds(CGMainDisplayID()); uint32_t *m = P(a[2]);
- m[0] = b.size.width; m[1] = b.size.height; m[2] = 60; m[3] = 22; return D3D_OK;
+ uint32_t *m = P(a[2]); m[2] = 60; m[3] = 22;
+ extern int pe2_d3d_fullscreen_mode(uint32_t *w, uint32_t *h);
+ if (pe2_d3d_fullscreen_mode(&m[0], &m[1])) return D3D_OK;
+ CGDirectDisplayID dpy = CGMainDisplayID(); CGDisplayModeRef dm = CGDisplayCopyDisplayMode(dpy);
+ if (dm) { m[0] = (uint32_t)CGDisplayModeGetPixelWidth(dm); m[1] = (uint32_t)CGDisplayModeGetPixelHeight(dm); CGDisplayModeRelease(dm); }
+ else { CGRect b = CGDisplayBounds(dpy); m[0] = b.size.width; m[1] = b.size.height; }
+ return D3D_OK;
}
COM(IDirect3D9, CheckDeviceType, 6) { return D3D_OK; }
static int fmt_ok(uint32_t f) {
diff --git a/runtime/d3d9_device.m b/runtime/d3d9_device.m
index ba73cb6..53229f4 100644
--- a/runtime/d3d9_device.m
+++ b/runtime/d3d9_device.m
@@ -6,6 +6,7 @@
* draw or clear for the bound targets and closes when targets change, an upload needs a blit, or the frame ends.
*/
#include "d3d9_priv.h"
+#import
#include
#include
#include
@@ -18,6 +19,11 @@
void pe2_window_size(gp h, int *cw, int *ch);
void pe2_d3d_caps(uint32_t *c);
device *g_dev;
+/* the mode of an exclusive-fullscreen device, if there is one (the adapter's display mode: d3d9_api.m) */
+int pe2_d3d_fullscreen_mode(uint32_t *w, uint32_t *h) {
+ if (!g_dev || g_dev->pp[8] || !g_dev->pp[0] || !g_dev->pp[1]) return 0;
+ *w = g_dev->pp[0]; *h = g_dev->pp[1]; return 1;
+}
/* ---------------- formats (unsupported packed 16-bit formats are widened to BGRA8 on upload) ---------------- */
#define SWZ(r, g, b, a) {MTLTextureSwizzle##r, MTLTextureSwizzle##g, MTLTextureSwizzle##b, MTLTextureSwizzle##a}
@@ -118,9 +124,21 @@ void cmd_begin(device *d) {
atomic_store(&dd->done, id_);
}];
}
-void enc_end(device *d) { if (d->enc) { [d->enc endEncoding]; [d->enc release]; d->enc = nil; } }
+void enc_end(device *d) {
+ if (d->enc) { [d->enc endEncoding]; [d->enc release]; d->enc = nil; }
+ if (d->blit) { [d->blit endEncoding]; [d->blit release]; d->blit = nil; }
+}
+/* texture uploads share one blit pass until the next draw or other GPU work: a game that fills thousands of textures
+ in a row (loading, or recreating its resources after Reset) made one pass and one command-buffer break each */
+static id blit_enc(device *d) {
+ if (d->blit) return d->blit;
+ enc_end(d); cmd_begin(d);
+ d->blit = [[d->cmd blitCommandEncoder] retain];
+ return d->blit;
+}
void cmd_commit(device *d, int wait) {
enc_end(d);
+ if (d->upcmd) { [d->upblit endEncoding]; [d->upblit release]; d->upblit = nil; [d->upcmd commit]; [d->upcmd release]; d->upcmd = nil; }
if (!d->cmd) return;
[d->cmd commit];
if (wait) [d->cmd waitUntilCompleted];
@@ -128,8 +146,10 @@ void cmd_commit(device *d, int wait) {
}
static void wait_for(device *d, uint64_t id_) {
if (id_ == 0 || atomic_load(&d->done) >= id_) return;
+ double t0 = CACurrentMediaTime(); d->n_wait++;
if (d->cmd && id_ >= d->submit) { cmd_commit(d, 0); }
while (atomic_load(&d->done) < id_) usleep(100);
+ d->t_wait += CACurrentMediaTime() - t0;
}
/* ---------------- textures ---------------- */
@@ -189,6 +209,11 @@ static void level_pitch(res *t, uint32_t l, uint32_t *pitch, uint32_t *rows) {
static res *surf_create(device *d, uint32_t w, uint32_t h, uint32_t fmt, uint32_t usage) {
res *t = tex_create(d, K_TEX, w, h, 1, 1, usage, fmt, 0);
if (!t) return 0;
+ /* a standalone surface (CreateOffscreenPlainSurface, CreateRenderTarget, CreateDepthStencilSurface) is a one-level
+ texture the program never sees: only the surface holds a reference, so releasing it frees both. The hidden
+ texture kept the reference it was made with, and no surface of this kind was ever freed: C&C 3's LAN lobby makes
+ and drops hundreds a second and ran the low memory out in two minutes */
+ t->ref = 0;
res *s = surface_for(t, 0, 0); s->ref = 1;
return s;
}
@@ -211,7 +236,7 @@ static void readback(device *d, res *t, uint32_t l, uint32_t face) {
uint32_t i = face * t->levels + l, pitch, rows; level_pitch(t, l, &pitch, &rows);
uint32_t w, h, dd; level_dims(t, l, &w, &h, &dd);
if (!t->shadow[i]) { t->shadow[i] = SH_ALLOC(pitch * rows * dd); t->pitch[i] = pitch; t->slice[i] = pitch * rows; }
- if (t->gpu_dirty) readback(d, t, l, face);
+ if (t->gpu_dirty) { @autoreleasepool { readback(d, t, l, face); } }
*pitch_out = pitch; if (slice_out) *slice_out = pitch * rows;
return t->shadow[i];
}
@@ -228,21 +253,59 @@ static void convert_row(const fmtinfo *fi, const uint8_t *src, uint8_t *dst, uin
dst[4 * x] = b; dst[4 * x + 1] = g; dst[4 * x + 2] = r; dst[4 * x + 3] = a;
}
}
-static void upload_sub(device *d, res *t, uint32_t l, uint32_t face) {
+/* copy level l (face) from its CPU copy to the GPU texture; rc (left, top, right, bottom in pixels), when given, limits
+ it to that rectangle. A game that redraws a large texture in small pieces (C&C 3 rebuilds its map textures cell by
+ cell after a Reset) locks a small rectangle each time; uploading the whole level for each made thousands of uploads of
+ megabytes, and coming back to the game took minutes */
+static uint64_t g_up_n, g_up_bytes; /* uploads since the last frame-rate line */
+static void upload_sub_rect_(device *d, res *t, uint32_t l, uint32_t face, const int32_t *rc);
+static void upload_sub_rect(device *d, res *t, uint32_t l, uint32_t face, const int32_t *rc) {
+ double t0 = CACurrentMediaTime(); upload_sub_rect_(d, t, l, face, rc); d->t_up += CACurrentMediaTime() - t0;
+}
+static void upload_sub_rect_(device *d, res *t, uint32_t l, uint32_t face, const int32_t *rc) {
uint32_t i = face * t->levels + l, pitch, rows; level_pitch(t, l, &pitch, &rows);
uint32_t w, h, dd; level_dims(t, l, &w, &h, &dd);
- if (!t->shadow[i] || t->fi->depth) return;
- uint32_t dpitch = t->fi->cv ? w * 4 : pitch;
- id b = [d->dev newBufferWithLength:dpitch * rows * dd options:MTLResourceStorageModeShared];
- if (t->fi->cv) { for (uint32_t z = 0; z < dd; z++) for (uint32_t y = 0; y < rows; y++) convert_row(t->fi, t->shadow[i] + z * pitch * rows + y * pitch, (uint8_t *)b.contents + z * dpitch * rows + y * dpitch, w); }
- else memcpy(b.contents, t->shadow[i], pitch * rows * dd);
- enc_end(d); cmd_begin(d);
- id be = [d->cmd blitCommandEncoder];
- [be copyFromBuffer:b sourceOffset:0 sourceBytesPerRow:dpitch sourceBytesPerImage:t->kind == K_VOL ? dpitch * rows : 0 sourceSize:MTLSizeMake(w, h, dd)
- toTexture:t->tex destinationSlice:face destinationLevel:l destinationOrigin:MTLOriginMake(0, 0, 0)];
+ if (!t->shadow[i] || t->fi->depth || !t->tex) return;
+ uint32_t blk = t->fi->block == 4 ? 4 : 1, x0 = 0, y0 = 0, x1 = w, y1 = h;
+ if (rc && dd == 1) {
+ int32_t a = rc[0], b = rc[1], c = rc[2], e = rc[3];
+ if (a < 0) a = 0; if (b < 0) b = 0; if (c > (int32_t)w) c = w; if (e > (int32_t)h) e = h;
+ if (a >= c || b >= e) return;
+ x0 = a / blk * blk; y0 = b / blk * blk; x1 = c; y1 = e;
+ }
+ uint32_t bx0 = x0 / blk, by0 = y0 / blk, bx1 = (x1 + blk - 1) / blk, by1 = (y1 + blk - 1) / blk; /* in blocks (pixels when blk is 1) */
+ uint32_t nrow = by1 - by0, spitch = t->fi->cv ? (x1 - x0) * 4 : (bx1 - bx0) * t->fi->bpp, size = spitch * nrow * dd;
+ /* staged in this frame's transient ring (reused once the GPU is done with the frame); only an upload too big for
+ it gets a buffer of its own */
+ id b, own = nil; uint8_t *dst; uint32_t off = 0;
+ if (size <= (8u << 20)) { void *p; off = ring_alloc(d, size, 256, &p, &b); dst = p; }
+ else { own = b = [d->dev newBufferWithLength:size options:MTLResourceStorageModeShared]; dst = b.contents; }
+ for (uint32_t z = 0; z < dd; z++) for (uint32_t y = 0; y < nrow; y++) {
+ const uint8_t *src = t->shadow[i] + z * pitch * rows + (by0 + y) * pitch + bx0 * t->fi->bpp;
+ uint8_t *o = dst + z * spitch * nrow + y * spitch;
+ if (t->fi->cv) convert_row(t->fi, src, o, x1 - x0); else memcpy(o, src, spitch);
+ }
+ g_up_n++; g_up_bytes += size;
+ /* A texture the open command buffer has not used is filled ahead of it, in a command buffer committed just before
+ (the GPU runs them in that order), so the render pass goes on. C&C 3 updates thousands of small textures between
+ draws in some scenes; each ended the pass, and the next one reloaded the whole 3456x2234 colour and depth
+ targets: the game stalled for seconds (4.7 fps, sound breaking up). A texture already used by this command buffer
+ is updated in order inside it, as before. */
+ id be;
+ cmd_begin(d);
+ if (t->use_seq != d->submit) {
+ if (!d->upcmd) { d->upcmd = [[d->q commandBuffer] retain]; d->upblit = [[d->upcmd blitCommandEncoder] retain]; }
+ be = d->upblit; d->n_preup++;
+ } else { if (d->enc) d->n_break++; be = blit_enc(d); }
+ [be copyFromBuffer:b sourceOffset:off sourceBytesPerRow:spitch sourceBytesPerImage:t->kind == K_VOL ? spitch * nrow : 0 sourceSize:MTLSizeMake(x1 - x0, y1 - y0, dd)
+ toTexture:t->tex destinationSlice:face destinationLevel:l destinationOrigin:MTLOriginMake(x0, y0, 0)];
if ((t->usage & 0x400) && l == 0 && t->levels > 1) [be generateMipmapsForTexture:t->tex];
- [be endEncoding];
- [b release];
+ [own release];
+}
+static void upload_sub(device *d, res *t, uint32_t l, uint32_t face) { upload_sub_rect(d, t, l, face, 0); }
+/* UnlockRect: the rectangle LockRect named, or the whole level */
+static void unlock_upload(device *d, res *t, uint32_t l, uint32_t face) {
+ upload_sub_rect(d, t, l, face, t->lk_part && t->lk_sub == face * t->levels + l ? t->lk_rect : 0); t->lk_part = 0;
}
/* ---------------- buffers ---------------- */
@@ -252,10 +315,17 @@ static void upload_sub(device *d, res *t, uint32_t l, uint32_t face) {
if (b->size >= size && b->size <= size * 2 + 4096 && b->last_use <= atomic_load(&d->done)) { *pp = b->next; b->next = 0; return b; }
}
backing *b = calloc(1, sizeof *b);
- b->size = (size + 0xfff) & ~0xfffu;
- b->mem = P(pages_alloc(b->size));
- if (!b->mem) { fprintf(stderr, "d3d: out of low memory for a %u byte buffer\n", size); free(b); return 0; }
+ /* Metal wraps memory without copying only at the GPU's page size (16 KB on Apple silicon, whatever page size this
+ process sees), start and length; the low heap hands out 4 KB pages, so take a little more and give back the ends.
+ A buffer that could not be wrapped had no Metal buffer, and its draws were dropped */
+ b->size = (size + 0x3fff) & ~0x3fffu;
+ uint32_t raw = pages_alloc(b->size + 0x3000), at = (raw + 0x3fff) & ~0x3fffu;
+ if (!raw) { fprintf(stderr, "d3d: out of low memory for a %u byte buffer\n", size); free(b); return 0; }
+ if (at > raw) pages_free(raw, at - raw);
+ if (raw + 0x3000 > at) pages_free(at + b->size, raw + 0x3000 - at);
+ b->mem = P(at);
b->buf = [d->dev newBufferWithBytesNoCopy:b->mem length:b->size options:MTLResourceStorageModeShared deallocator:nil];
+ if (!b->buf) fprintf(stderr, "d3d: Metal refused a %u byte buffer at %#x\n", b->size, at);
return b;
}
static void bk_retire(device *d, backing *b) { b->next = d->free_bk; d->free_bk = b; }
@@ -284,7 +354,7 @@ static void upload_sub(device *d, res *t, uint32_t l, uint32_t face) {
static uint32_t g_dev_vt;
static void state_defaults(device *d) {
- dstate *s = &d->s; memset(s, 0, sizeof *s);
+ dstate *s = &d->s; memset(s, 0, sizeof *s); d->cgen++;
uint32_t *rs = s->rs;
rs[7] = d->pp[9] ? 1 : 0; rs[8] = 3; rs[9] = 2; rs[14] = 1; rs[16] = 1; rs[19] = 2; rs[20] = 1; rs[22] = 3; rs[23] = 4;
rs[25] = 8; rs[37] = u_of(1.0f); rs[38] = u_of(1.0f); rs[53] = rs[54] = rs[55] = 1; rs[56] = 8;
@@ -315,6 +385,7 @@ static void make_backbuffer(device *d) {
d->layer.drawableSize = CGSizeMake(w, h); [CATransaction flush]; /* this thread never sleeps in a run loop: send the change now */
extern void pe2_set_mode(gp, int, int);
if (!d->pp[8]) pe2_set_mode(d->hwnd, w, h); /* exclusive fullscreen: the display is now this mode */
+ else pe2_set_mode(d->hwnd, 0, 0); /* windowed (again, after a Reset) */
set_default_viewport(d);
}
COM(IDirect3D9, CreateDevice, 7) {
@@ -333,6 +404,7 @@ static void make_backbuffer(device *d) {
d->libs = [NSMutableDictionary new]; d->pipes = [NSMutableDictionary new]; d->dss = [NSMutableDictionary new];
d->samplers = [NSMutableDictionary new]; d->fvfdecls = [NSMutableDictionary new];
for (int i = 0; i < 3; i++) d->ring[i] = [d->dev newBufferWithLength:32u << 20 options:MTLResourceStorageModeShared];
+ d3d_warm_pipelines(d);
cmd_begin(d);
make_backbuffer(d);
state_defaults(d);
@@ -349,8 +421,25 @@ static void make_backbuffer(device *d) {
COM(IDirect3DDevice9, QueryInterface, 3) { PUTOBJ(a[2], a[0]); return 0; }
COM(IDirect3DDevice9, AddRef, 1) { return ++((uint32_t *)P(a[0]))[CO_REF]; }
COM(IDirect3DDevice9, Release, 1) { uint32_t *o = P(a[0]); return o[CO_REF] ? --o[CO_REF] : 0; }
-COM(IDirect3DDevice9, TestCooperativeLevel, 1) { return D3D_OK; }
-COM(IDirect3DDevice9, GetAvailableTextureMem, 1) { return 256u << 20; }
+/* A lost device, as Windows makes one: an exclusive-fullscreen device (Windowed = FALSE) is lost while its program is
+ not the active one (Command-Tab, another Space). TestCooperativeLevel and Present then say D3DERR_DEVICELOST and Reset
+ fails the same way; once the program is active again they say D3DERR_DEVICENOTRESET until it calls Reset. A game
+ releases its D3DPOOL_DEFAULT resources on the first and creates them again after the Reset: without these answers it
+ went on drawing with what it had just released. A windowed device is never lost. */
+#define D3DERR_DEVICELOST 0x88760868u
+#define D3DERR_DEVICENOTRESET 0x88760869u
+static int g_lost;
+static uint32_t dev_state(device *d) {
+ if (!d || d->pp[8]) return D3D_OK;
+ /* lost while the program is not active, as on Windows: a game releases its resources on its own deactivation and
+ makes them again only through this cycle (answering "not lost" while it was merely covered crashed it). Coming
+ back to the fullscreen window's Space activates the program again (w64/win.h), as switching to a fullscreen
+ game does on Windows; without that it stayed lost and drew nothing. */
+ if (!NSApp.isActive) { if (!g_lost && getenv("PE2_TRACE")) fprintf(stderr, "d3d: device lost (program inactive)\n"); g_lost = 1; return D3DERR_DEVICELOST; }
+ return g_lost ? D3DERR_DEVICENOTRESET : D3D_OK;
+}
+COM(IDirect3DDevice9, TestCooperativeLevel, 1) { return dev_state(g_dev); }
+COM(IDirect3DDevice9, GetAvailableTextureMem, 1) { return 768u << 20; } /* the GeForce 8800 GTX the adapter reports */
COM(IDirect3DDevice9, EvictManagedResources, 1) { return D3D_OK; }
extern uint32_t pe2_d3d9_obj;
COM(IDirect3DDevice9, GetDirect3D, 2) { PUTOBJ(a[1], pe2_d3d9_obj); if (pe2_d3d9_obj) ((uint32_t *)P(pe2_d3d9_obj))[CO_REF]++; return pe2_d3d9_obj ? D3D_OK : D3DERR_INVALIDCALL; }
@@ -420,12 +509,19 @@ static void dump_frame(device *d, uint64_t n) {
fprintf(stderr, "d3d: wrote %s\n", path);
}
static uint64_t g_total_frames;
+uint64_t pe2_drawlog_until; /* frames below this are logged draw by draw (PE2_DRAWLOG_TRIGGER) */
uint64_t pe2_frame_no(void) { return g_total_frames; }
static uint32_t present(device *d) {
@autoreleasepool {
enc_end(d); cmd_begin(d);
g_total_frames++;
if (g_total_frames % 600 == 2 && getenv("PE2_LAYER_TRACE") && pe2_layer_trace) pe2_layer_trace(d->layer); /* where the game's layer is */
+ /* PE2_DRAWLOG_TRIGGER=: when the file appears (touch it), log every draw of the next PE2_DRAWLOG_FRAMES
+ frames (60) and, with PE2_SHOT_DIR, keep every 3rd frame's picture: an artifact that comes and goes is caught
+ while it happens */
+ { static const char *trig = (const char *)-1; if (trig == (const char *)-1) trig = getenv("PE2_DRAWLOG_TRIGGER");
+ if (trig && !access(trig, F_OK)) { unlink(trig); pe2_drawlog_until = g_total_frames + (getenv("PE2_DRAWLOG_FRAMES") ? atoi(getenv("PE2_DRAWLOG_FRAMES")) : 60); fprintf(stderr, "d3d: drawlog frames %llu..%llu\n", g_total_frames, pe2_drawlog_until); }
+ if (g_total_frames < pe2_drawlog_until) { fprintf(stderr, "d3d: frame %llu\n", g_total_frames); if (getenv("PE2_SHOT_DIR") && g_total_frames % 3 == 0) dump_frame(d, g_total_frames); } }
if (getenv("PE2_SHOT_DIR")) { int every = getenv("PE2_SHOT_EVERY") ? atoi(getenv("PE2_SHOT_EVERY")) : 300; if (every > 0 && g_total_frames % every == 0) dump_frame(d, g_total_frames); }
if (pe2_present_surface && pe2_present_surface(d->layer, d->bb->parent->tex, d->cmd, 0)) goto shown;
id dr = [d->layer nextDrawable];
@@ -442,7 +538,7 @@ static uint32_t present(device *d) {
}
shown:;
dispatch_semaphore_t sem = d->inflight;
- dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
+ { double t0 = CACurrentMediaTime(); dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER); d->t_sem += CACurrentMediaTime() - t0; } /* time the GPU kept the program waiting */
[d->cmd addCompletedHandler:^(id cb) { if (cb.status == MTLCommandBufferStatusError) { static int said; if (said++ < 3) fprintf(stderr, "d3d: frame command buffer failed: %s\n", cb.error.localizedDescription.UTF8String); } dispatch_semaphore_signal(sem); }]; /* a failed buffer drops its frame */
d->ring_use[d->ring_idx] = d->submit;
cmd_commit(d, 0);
@@ -453,19 +549,23 @@ static uint32_t present(device *d) {
g_frames++;
double now = CACurrentMediaTime();
if (!g_t0) g_t0 = now;
- if (now - g_t0 >= 5.0) { fprintf(stderr, "d3d: %.1f fps, %llu draws/frame\n", g_frames / (now - g_t0), d->draws / (g_frames ? g_frames : 1)); g_frames = 0; d->draws = 0; g_t0 = now; }
+ if (now - g_t0 >= 5.0) { { extern uint64_t pe2_low_used(void); fprintf(stderr, "d3d: %.1f fps, %llu draws/frame, %llu uploads (%llu MB), low memory %llu MB, passes/frame %llu, upload breaks %llu, ahead %llu, gpu waits %llu (%.0f ms), waiting for frames %.0f ms, new pipelines %llu (%.0f ms, %llu made ahead), uploads %.0f ms, draws %.0f ms\n", g_frames / (now - g_t0), d->draws / (g_frames ? g_frames : 1), g_up_n, g_up_bytes >> 20, pe2_low_used() >> 20, d->n_pass / (g_frames ? g_frames : 1), d->n_break, d->n_preup, d->n_wait, d->t_wait * 1000, d->t_sem * 1000, d->n_pipe, d->t_pipe * 1000, d->n_warm_hit, d->t_up * 1000, d->t_draw * 1000); d->n_pass = d->n_break = d->n_preup = d->n_wait = d->n_pipe = d->n_warm_hit = 0; d->t_wait = d->t_sem = d->t_pipe = d->t_up = d->t_draw = 0; } g_up_n = g_up_bytes = 0; g_frames = 0; d->draws = 0; g_t0 = now; }
extern void pe2_pump_events(void); extern void pe2_autoclick_frame(uint64_t);
pe2_autoclick_frame(g_total_frames);
pe2_pump_events();
}
return D3D_OK;
}
-COM(IDirect3DDevice9, Present, 5) { return present(g_dev); }
-COM(D3DSwap, Present, 6) { return present(g_dev); }
+static void free_pending(device *d); /* resource lifetime, below */
+COM(IDirect3DDevice9, Present, 5) { if (dev_state(g_dev)) { pe2_pump_events(); return D3DERR_DEVICELOST; } free_pending(g_dev); return present(g_dev); }
+COM(D3DSwap, Present, 6) { if (dev_state(g_dev)) { pe2_pump_events(); return D3DERR_DEVICELOST; } free_pending(g_dev); return present(g_dev); }
COM(IDirect3DDevice9, GetBackBuffer, 5) { DEV; d->bb->ref++; PUTOBJ(a[4], d->bb->obj); return D3D_OK; }
COM(IDirect3DDevice9, Reset, 2) {
@autoreleasepool { DEV; uint32_t ppv[14]; pp_in(ppv, P(a[1])); uint32_t *pp = ppv;
+ if (dev_state(d) == D3DERR_DEVICELOST) return D3DERR_DEVICELOST; /* still in the background: Windows refuses too */
+ g_lost = 0;
fprintf(stderr, "d3d: Reset %ux%u fmt %u windowed %u\n", pp[0], pp[1], pp[2], pp[8]);
+ if (getenv("PE2_TRACE_BURST")) pe2_trace_burst = atoi(getenv("PE2_TRACE_BURST"));
cmd_commit(d, 1);
memcpy(d->pp, pp, 56);
cmd_begin(d);
@@ -493,10 +593,53 @@ static uint32_t present(device *d) {
COM(IDirect3DDevice9, CreateVertexBuffer, 7) { @autoreleasepool { DEV; return out_obj(a[5], buf_create(d, K_VB, a[1], a[2], a[3], a[4])); } }
COM(IDirect3DDevice9, CreateIndexBuffer, 7) { @autoreleasepool { DEV; return out_obj(a[5], buf_create(d, K_IB, a[1], a[2], a[3], a[4])); } }
+/* Resource lifetime. Release freed nothing, so every texture and buffer a game ever made stayed: their CPU copies and
+ buffer memory below 4 GB (where the program's own heap is too) and their GPU textures. A game that makes and drops
+ them all the time (C&C 3: thousands a session) ran the low memory out and crashed on the null an allocation
+ returned. A texture (with all its surfaces) or a vertex or index buffer whose last reference is released now waits on
+ a list until nothing has it bound (binding takes no reference here), then gives back its CPU copies, its GPU texture
+ and its buffer memory. Work already queued keeps what it uses: command buffers retain their textures, and buffer
+ memory is reused only after the GPU is done with it (bk_new, last_use). The object itself stays, so a stale handle a
+ state block still holds finds an empty resource rather than freed memory. */
+static res **g_pend; static uint32_t g_npend, g_cpend;
+static res *top_res(res *r) { return r && (r->kind == K_SURF || r->kind == K_VOLUME) && r->parent ? r->parent : r; }
+static int unreferenced(res *t) {
+ if (t->ref) return 0;
+ if (t->sub_obj) { uint32_t n = t->levels * (t->faces ? t->faces : 1); for (uint32_t i = 0; i < n; i++) if (t->sub_obj[i] && R(t->sub_obj[i])->ref) return 0; }
+ return 1;
+}
+static int in_use(device *d, res *t) {
+ if (!d) return 1;
+ if (top_res(d->bb) == t || top_res(d->ds_auto) == t || top_res(d->ds) == t) return 1;
+ for (int i = 0; i < 4; i++) if (top_res(d->rt[i]) == t) return 1;
+ for (int i = 0; i < 20; i++) if (d->s.tex[i] && top_res(R(d->s.tex[i])) == t) return 1;
+ for (int i = 0; i < 16; i++) if (d->s.stream[i] && R(d->s.stream[i]) == t) return 1;
+ return d->s.indices && R(d->s.indices) == t;
+}
+static void res_released(res *r) {
+ res *t = top_res(r);
+ if (t->dead || !unreferenced(t)) return;
+ if (t->kind != K_TEX && t->kind != K_CUBE && t->kind != K_VOL && t->kind != K_VB && t->kind != K_IB) return;
+ if (g_npend == g_cpend) { g_cpend = g_cpend ? 2 * g_cpend : 256; g_pend = realloc(g_pend, g_cpend * sizeof *g_pend); }
+ t->dead = 1; g_pend[g_npend++] = t;
+}
+static void free_pending(device *d) { /* at each Present */
+ uint32_t k = 0;
+ for (uint32_t i = 0; i < g_npend; i++) {
+ res *t = g_pend[i];
+ if (!unreferenced(t)) { t->dead = 0; continue; } /* referenced again */
+ if (in_use(d, t)) { g_pend[k++] = t; continue; }
+ if (t->kind == K_VB || t->kind == K_IB) { if (t->bk) { bk_retire(d, t->bk); t->bk = 0; } continue; }
+ if (t->shadow) { uint32_t n = t->levels * (t->faces ? t->faces : 1); for (uint32_t j = 0; j < n; j++) if (t->shadow[j]) { lo_free(t->shadow[j]); t->shadow[j] = 0; } }
+ if (t->view) { [t->view release]; t->view = nil; }
+ if (t->tex) { [t->tex release]; t->tex = nil; }
+ }
+ g_npend = k;
+}
#define RESCOMMON(I) \
COM(I, QueryInterface, 3) { PUTOBJ(a[2], a[0]); R(a[0])->ref++; return 0; } \
COM(I, AddRef, 1) { return ++R(a[0])->ref; } \
- COM(I, Release, 1) { res *r = R(a[0]); if (r->ref) r->ref--; return r->ref; } \
+ COM(I, Release, 1) { res *r = R(a[0]); if (r->ref && !--r->ref) res_released(r); return r->ref; } \
COM(I, GetDevice, 2) { PUTOBJ(a[1], g_dev->obj); return D3D_OK; } \
COM(I, SetPrivateData, 5) { return D3D_OK; } \
COM(I, GetPrivateData, 4) { return 0x88760866u; } \
@@ -515,7 +658,7 @@ static uint32_t present(device *d) {
COM(I, SetLOD, 2) { return 0; } COM(I, GetLOD, 1) { return 0; } \
COM(I, GetLevelCount, 1) { return R(a[0])->levels; } \
COM(I, SetAutoGenFilterType, 2) { return D3D_OK; } COM(I, GetAutoGenFilterType, 1) { return 2; } \
- COM(I, GenerateMipSubLevels, 1) { @autoreleasepool { res *t = R(a[0]); device *d = g_dev; enc_end(d); cmd_begin(d); if (t->levels > 1) { id be = [d->cmd blitCommandEncoder]; [be generateMipmapsForTexture:t->tex]; [be endEncoding]; } return 0; } }
+ COM(I, GenerateMipSubLevels, 1) { @autoreleasepool { res *t = R(a[0]); device *d = g_dev; enc_end(d); cmd_begin(d); gpu_use(d, t); if (t->levels > 1) { id be = [d->cmd blitCommandEncoder]; [be generateMipmapsForTexture:t->tex]; [be endEncoding]; } return 0; } }
BASETEX(D3DTexture) BASETEX(D3DCube) BASETEX(D3DVolTex)
static void level_desc(res *t, uint32_t l, uint32_t *o) {
@@ -530,18 +673,17 @@ static void level_desc(res *t, uint32_t l, uint32_t *o) {
COM(D3DVolTex, GetVolumeLevel, 3) { res *t = R(a[0]); res *s = surface_for(t, a[1], 0); s->ref++; PUTOBJ(a[2], s->obj); return D3D_OK; }
static uint32_t lock_rect(res *t, uint32_t l, uint32_t face, gp lr, gp rect) {
uint32_t pitch; device *d = g_dev;
- @autoreleasepool {
- uint8_t *p = lock_sub(d, t, l, face, &pitch, 0);
- if (rect) { int32_t *rc = P(rect); p += t->fi->block == 4 ? (rc[1] / 4) * pitch + (rc[0] / 4) * t->fi->bpp : rc[1] * pitch + rc[0] * t->fi->bpp; }
- uint32_t *o = P(lr); o[0] = pitch; PUTPTR(lr + sizeof(gp), p); /* D3DLOCKED_RECT: pBits follows at pointer alignment */
- return D3D_OK;
- }
+ uint8_t *p = lock_sub(d, t, l, face, &pitch, 0);
+ t->lk_part = 0;
+ if (rect) { int32_t *rc = P(rect); memcpy(t->lk_rect, rc, 16); t->lk_part = 1; t->lk_sub = face * t->levels + l; p += t->fi->block == 4 ? (rc[1] / 4) * pitch + (rc[0] / 4) * t->fi->bpp : rc[1] * pitch + rc[0] * t->fi->bpp; }
+ uint32_t *o = P(lr); o[0] = pitch; PUTPTR(lr + sizeof(gp), p); /* D3DLOCKED_RECT: pBits follows at pointer alignment */
+ return D3D_OK;
}
COM(D3DTexture, LockRect, 5) { res *t = R(a[0]); if (a[1] >= t->levels) return D3DERR_INVALIDCALL; t->locked_off = a[4]; return lock_rect(t, a[1], 0, a[2], a[3]); }
-COM(D3DTexture, UnlockRect, 2) { @autoreleasepool { res *t = R(a[0]); if (!(t->locked_off & 0x10)) upload_sub(g_dev, t, a[1], 0); return D3D_OK; } }
+COM(D3DTexture, UnlockRect, 2) { @autoreleasepool { res *t = R(a[0]); if (!(t->locked_off & 0x10)) unlock_upload(g_dev, t, a[1], 0); else t->lk_part = 0; return D3D_OK; } }
COM(D3DTexture, AddDirtyRect, 2) { return D3D_OK; }
COM(D3DCube, LockRect, 6) { res *t = R(a[0]); t->locked_off = a[5]; return lock_rect(t, a[2], a[1], a[3], a[4]); }
-COM(D3DCube, UnlockRect, 3) { @autoreleasepool { res *t = R(a[0]); if (!(t->locked_off & 0x10)) upload_sub(g_dev, t, a[2], a[1]); return D3D_OK; } }
+COM(D3DCube, UnlockRect, 3) { @autoreleasepool { res *t = R(a[0]); if (!(t->locked_off & 0x10)) unlock_upload(g_dev, t, a[2], a[1]); else t->lk_part = 0; return D3D_OK; } }
COM(D3DCube, AddDirtyRect, 3) { return D3D_OK; }
COM(D3DVolTex, LockBox, 5) { @autoreleasepool { res *t = R(a[0]); uint32_t pitch, slice; uint8_t *p = lock_sub(g_dev, t, a[1], 0, &pitch, &slice); uint32_t *o = P(a[2]); o[0] = pitch; o[1] = slice; PUTPTR(A32(o + 2), p); return D3D_OK; } }
COM(D3DVolTex, UnlockBox, 2) { @autoreleasepool { upload_sub(g_dev, R(a[0]), a[1], 0); return D3D_OK; } }
@@ -565,12 +707,13 @@ static uint32_t lock_rect(res *t, uint32_t l, uint32_t face, gp lr, gp rect) {
}
COM(D3DSurface, GetDesc, 2) { res *s = R(a[0]); uint32_t *o = P(a[1]); o[0] = s->fmt; o[1] = 1; o[2] = s->usage; o[3] = s->pool; o[4] = 0; o[5] = 0; o[6] = s->w; o[7] = s->h; return 0; }
COM(D3DSurface, LockRect, 4) { res *s = R(a[0]); s->locked_off = a[3]; return lock_rect(s->parent, s->level, s->face, a[1], a[2]); }
-COM(D3DSurface, UnlockRect, 1) { @autoreleasepool { res *s = R(a[0]); if (!(s->locked_off & 0x10)) upload_sub(g_dev, s->parent, s->level, s->face); return 0; } }
+COM(D3DSurface, UnlockRect, 1) { @autoreleasepool { res *s = R(a[0]); if (!(s->locked_off & 0x10)) unlock_upload(g_dev, s->parent, s->level, s->face); else s->parent->lk_part = 0; return 0; } }
COM(D3DSurface, GetDC, 2) { *(uint32_t *)P(a[1]) = 0x00060001; return 0; }
COM(D3DSurface, ReleaseDC, 2) { return 0; }
static uint32_t buf_lock(res *b, uint32_t off, gp pp, uint32_t flags) {
device *d = g_dev;
+ if (!b->bk && !(b->bk = bk_new(d, b->size))) return 0x8876017Cu; /* freed after a release (free_pending): memory again; D3DERR_OUTOFVIDEOMEMORY */
if (flags & 0x2000) {
if (b->bk->last_use > atomic_load(&d->done)) { backing *nb = bk_new(d, b->size); if (nb) { bk_retire(d, b->bk); b->bk = nb; } }
} else if (!(flags & 0x1000) && !(flags & 0x10)) {
@@ -587,11 +730,64 @@ static uint32_t buf_lock(res *b, uint32_t off, gp pp, uint32_t flags) {
COM(D3DIB, GetDesc, 2) { res *b = R(a[0]); uint32_t *o = P(a[1]); o[0] = b->fmt; o[1] = 7; o[2] = b->usage; o[3] = b->pool; o[4] = b->size; return 0; }
/* ---------------- copies ---------------- */
-static void blit_copy(device *d, res *src, const int32_t *sr, res *dst, const int32_t *dr) {
+/* StretchRect between rectangles of different sizes scales, as on Windows: the source rectangle is drawn into the
+ destination one, point or linear filtered (D3DTEXF_POINT 1, D3DTEXF_LINEAR 2). It used to copy the top-left part
+ unscaled: a game that shrinks its frame into a texture for distortion effects (heat haze, smoke, C&C 3's Tiberium
+ glow) sampled a magnified corner of the screen, smeared across the whole view. */
+static const char *BLIT_SRC =
+ "#include \nusing namespace metal;\n"
+ "struct VO { float4 pos [[position]]; float2 uv; };\n"
+ "vertex VO blit_vs(uint v [[vertex_id]], constant float4 *r [[buffer(0)]]) {\n"
+ " float2 t = float2((v & 1) ? 1.0 : 0.0, (v & 2) ? 1.0 : 0.0); VO o;\n"
+ " o.pos = float4(mix(r[0].x, r[0].z, t.x), mix(r[0].y, r[0].w, t.y), 0.0, 1.0);\n"
+ " o.uv = float2(mix(r[1].x, r[1].z, t.x), mix(r[1].y, r[1].w, t.y)); return o; }\n"
+ "fragment float4 blit_fs(VO i [[stage_in]], texture2d s [[texture(0)]], sampler sm [[sampler(0)]]) { return s.sample(sm, i.uv); }\n";
+static int blit_scaled(device *d, res *src, uint32_t sx, uint32_t sy, uint32_t sw, uint32_t sh, res *dst, const int32_t *dr, int linear) {
+ res *st = src->parent, *dt = dst->parent; gpu_use(d, st); gpu_use(d, dt);
+ if (!st->tex || !dt->tex || st->fi->depth || dt->fi->depth || !(dt->tex.usage & MTLTextureUsageRenderTarget) || st->tex.textureType != MTLTextureType2D && st->tex.textureType != MTLTextureTypeCube) return 0;
+ static NSMutableDictionary *pipes; static id smp[2]; static id lib;
+ if (!lib) { NSError *e = nil; lib = [d->dev newLibraryWithSource:@(BLIT_SRC) options:nil error:&e]; if (!lib) { fprintf(stderr, "d3d: StretchRect shader: %s\n", e.localizedDescription.UTF8String); return 0; } }
+ if (!pipes) pipes = [NSMutableDictionary new];
+ NSNumber *key = @(dt->tex.pixelFormat); id ps = pipes[key];
+ if (!ps) {
+ MTLRenderPipelineDescriptor *pd = [MTLRenderPipelineDescriptor new];
+ id vf = [lib newFunctionWithName:@"blit_vs"], ff = [lib newFunctionWithName:@"blit_fs"];
+ pd.vertexFunction = vf; pd.fragmentFunction = ff; pd.colorAttachments[0].pixelFormat = dt->tex.pixelFormat;
+ NSError *e = nil; ps = [d->dev newRenderPipelineStateWithDescriptor:pd error:&e];
+ [vf release]; [ff release]; [pd release];
+ if (!ps) { fprintf(stderr, "d3d: StretchRect pipeline: %s\n", e.localizedDescription.UTF8String); return 0; }
+ pipes[key] = ps; [ps release];
+ }
+ if (!smp[linear]) { MTLSamplerDescriptor *sd = [MTLSamplerDescriptor new]; sd.minFilter = sd.magFilter = linear ? MTLSamplerMinMagFilterLinear : MTLSamplerMinMagFilterNearest;
+ sd.sAddressMode = sd.tAddressMode = MTLSamplerAddressModeClampToEdge; smp[linear] = [d->dev newSamplerStateWithDescriptor:sd]; [sd release]; }
+ /* the source level as a 2D view (a cube face, a mip level), the destination level and face as the attachment */
+ id sv = [st->tex newTextureViewWithPixelFormat:st->tex.pixelFormat textureType:MTLTextureType2D levels:NSMakeRange(src->level, 1) slices:NSMakeRange(src->face, 1)];
+ if (!sv) return 0;
+ uint32_t SW = src->w, SH = src->h, DW = dst->w, DH = dst->h;
+ float r[8] = { (float)dr[0] / DW * 2 - 1, 1 - (float)dr[1] / DH * 2, (float)dr[2] / DW * 2 - 1, 1 - (float)dr[3] / DH * 2,
+ (float)sx / SW, (float)sy / SH, (float)(sx + sw) / SW, (float)(sy + sh) / SH };
+ enc_end(d); cmd_begin(d);
+ MTLRenderPassDescriptor *rp = [MTLRenderPassDescriptor renderPassDescriptor];
+ rp.colorAttachments[0].texture = dt->tex; rp.colorAttachments[0].level = dst->level; rp.colorAttachments[0].slice = dst->face;
+ rp.colorAttachments[0].loadAction = MTLLoadActionLoad; rp.colorAttachments[0].storeAction = MTLStoreActionStore;
+ id e = [d->cmd renderCommandEncoderWithDescriptor:rp];
+ [e setRenderPipelineState:ps]; [e setVertexBytes:r length:sizeof r atIndex:0];
+ [e setFragmentTexture:sv atIndex:0]; [e setFragmentSamplerState:smp[linear] atIndex:0];
+ [e drawPrimitives:MTLPrimitiveTypeTriangleStrip vertexStart:0 vertexCount:4];
+ [e endEncoding]; [sv release];
+ dt->gpu_dirty = 1; return 1;
+}
+static void blit_copy_f(device *d, res *src, const int32_t *sr, res *dst, const int32_t *dr, uint32_t filter);
+static void blit_copy(device *d, res *src, const int32_t *sr, res *dst, const int32_t *dr) { blit_copy_f(d, src, sr, dst, dr, 2); }
+static void blit_copy_f(device *d, res *src, const int32_t *sr, res *dst, const int32_t *dr, uint32_t filter) {
res *st = src->parent, *dt = dst->parent;
uint32_t sx = sr ? sr[0] : 0, sy = sr ? sr[1] : 0, w = sr ? sr[2] - sr[0] : src->w, h = sr ? sr[3] - sr[1] : src->h;
uint32_t dx = dr ? dr[0] : 0, dy = dr ? dr[1] : 0;
+ int32_t full[4] = {0, 0, (int32_t)dst->w, (int32_t)dst->h};
+ if (!dr && sr && (w != dst->w || h != dst->h)) dr = full; /* no destination rectangle: all of it */
+ if (!dr && !sr && (src->w != dst->w || src->h != dst->h)) dr = full;
if (dr && ((uint32_t)(dr[2] - dr[0]) != w || (uint32_t)(dr[3] - dr[1]) != h)) {
+ if (blit_scaled(d, src, sx, sy, w, h, dst, dr, filter != 1)) return;
static int warned; if (!warned++) fprintf(stderr, "d3d: scaled StretchRect copies unscaled (first %ux%u -> %dx%d)\n", w, h, dr[2] - dr[0], dr[3] - dr[1]);
if ((uint32_t)(dr[2] - dr[0]) < w) w = dr[2] - dr[0];
if ((uint32_t)(dr[3] - dr[1]) < h) h = dr[3] - dr[1];
@@ -600,19 +796,32 @@ static void blit_copy(device *d, res *src, const int32_t *sr, res *dst, const in
if (st->fi->mtl != dt->fi->mtl) { static int warned2; if (!warned2++) fprintf(stderr, "d3d: copy between formats %#x -> %#x skipped\n", st->fmt, dt->fmt); return; }
if (sx + w > src->w) w = src->w - sx; if (sy + h > src->h) h = src->h - sy;
if (dx + w > dst->w) w = dst->w - dx; if (dy + h > dst->h) h = dst->h - dy;
- enc_end(d); cmd_begin(d);
+ enc_end(d); cmd_begin(d); gpu_use(d, st); gpu_use(d, dt);
id be = [d->cmd blitCommandEncoder];
[be copyFromTexture:st->tex sourceSlice:src->face sourceLevel:src->level sourceOrigin:MTLOriginMake(sx, sy, 0) sourceSize:MTLSizeMake(w, h, 1)
toTexture:dt->tex destinationSlice:dst->face destinationLevel:dst->level destinationOrigin:MTLOriginMake(dx, dy, 0)];
[be endEncoding];
dt->gpu_dirty = 1;
}
-COM(IDirect3DDevice9, StretchRect, 6) { @autoreleasepool { DEV; blit_copy(d, R(a[1]), a[2] ? P(a[2]) : 0, R(a[3]), a[4] ? P(a[4]) : 0); return 0; } }
+COM(IDirect3DDevice9, StretchRect, 6) { @autoreleasepool { DEV; blit_copy_f(d, R(a[1]), a[2] ? P(a[2]) : 0, R(a[3]), a[4] ? P(a[4]) : 0, a[5]); return 0; } }
+/* (this, src surface, src RECT or 0 = all, dst surface, dst POINT or 0 = 0,0): the rectangle, clipped to both surfaces,
+ in whole blocks for compressed formats */
COM(IDirect3DDevice9, UpdateSurface, 5) {
@autoreleasepool { DEV; res *s = R(a[1]), *t = R(a[3]);
+ if (!s || !t || !s->fi || !t->fi || !s->parent || !t->parent) return D3DERR_INVALIDCALL;
+ int32_t r[4] = {0, 0, (int32_t)s->w, (int32_t)s->h}; if (a[2]) memcpy(r, P(a[2]), 16);
+ int32_t dx = 0, dy = 0; if (a[4]) { int32_t *pt = P(a[4]); dx = pt[0]; dy = pt[1]; }
+ if (r[0] < 0) r[0] = 0; if (r[1] < 0) r[1] = 0; if (r[2] > (int32_t)s->w) r[2] = s->w; if (r[3] > (int32_t)s->h) r[3] = s->h;
+ if (dx < 0 || dy < 0) return D3DERR_INVALIDCALL;
+ int32_t w = r[2] - r[0], h = r[3] - r[1];
+ if (w > (int32_t)t->w - dx) w = (int32_t)t->w - dx; if (h > (int32_t)t->h - dy) h = (int32_t)t->h - dy;
+ if (w <= 0 || h <= 0) return D3D_OK;
uint32_t sp, dp; uint8_t *sm = lock_sub(d, s->parent, s->level, s->face, &sp, 0), *dm = lock_sub(d, t->parent, t->level, t->face, &dp, 0);
- uint32_t rows = s->fi->block == 4 ? (s->h + 3) / 4 : s->h;
- for (uint32_t y = 0; y < rows; y++) memcpy(dm + y * dp, sm + y * sp, sp < dp ? sp : dp);
+ if (!sm || !dm) return D3DERR_INVALIDCALL;
+ uint32_t blk = s->fi->block ? s->fi->block : 1, unit = s->fi->bpp;
+ uint32_t rows = (uint32_t)(h + blk - 1) / blk, bytes = (uint32_t)(w + blk - 1) / blk * unit;
+ for (uint32_t y = 0; y < rows; y++)
+ memcpy(dm + (dy / blk + y) * dp + (dx / blk) * unit, sm + (r[1] / blk + y) * sp + (r[0] / blk) * unit, bytes);
upload_sub(d, t->parent, t->level, t->face); return 0; }
}
COM(IDirect3DDevice9, UpdateTexture, 3) {
@@ -625,8 +834,10 @@ static void blit_copy(device *d, res *src, const int32_t *sr, res *dst, const in
}
COM(IDirect3DDevice9, GetRenderTargetData, 3) {
@autoreleasepool { DEV; res *s = R(a[1]), *t = R(a[2]);
+ if (!s || !t || !s->parent || !t->parent) return D3DERR_INVALIDCALL;
uint32_t sp, dp; s->parent->gpu_dirty = 1; uint8_t *sm = lock_sub(d, s->parent, s->level, s->face, &sp, 0), *dm = lock_sub(d, t->parent, t->level, t->face, &dp, 0);
- for (uint32_t y = 0; y < s->h; y++) memcpy(dm + y * dp, sm + y * sp, sp < dp ? sp : dp);
+ if (!sm || !dm) return D3DERR_INVALIDCALL;
+ for (uint32_t y = 0; y < s->h && y < t->h; y++) memcpy(dm + y * dp, sm + y * sp, sp < dp ? sp : dp);
return 0; }
}
COM(IDirect3DDevice9, GetFrontBufferData, 3) { return D3D_OK; }
@@ -636,7 +847,7 @@ static void blit_copy(device *d, res *src, const int32_t *sr, res *dst, const in
rp.colorAttachments[0].texture = s->parent->tex; rp.colorAttachments[0].level = s->level; rp.colorAttachments[0].slice = s->face;
rp.colorAttachments[0].loadAction = MTLLoadActionClear; rp.colorAttachments[0].storeAction = MTLStoreActionStore;
rp.colorAttachments[0].clearColor = MTLClearColorMake(((c >> 16) & 255) / 255.0, ((c >> 8) & 255) / 255.0, (c & 255) / 255.0, (c >> 24) / 255.0);
- enc_end(d); cmd_begin(d);
+ enc_end(d); cmd_begin(d); gpu_use(d, s->parent);
id e = [d->cmd renderCommandEncoderWithDescriptor:rp]; [e endEncoding];
s->parent->gpu_dirty = 1; return 0; }
}
@@ -657,19 +868,19 @@ static void blit_copy(device *d, res *src, const int32_t *sr, res *dst, const in
COM(IDirect3DDevice9, GetDepthStencilSurface, 2) { DEV; if (!d->ds) { *(uint32_t *)P(a[1]) = 0; return 0x8876086Cu; } d->ds->ref++; PUTOBJ(a[1], d->ds->obj); return 0; }
void begin_pass(device *d) {
if (d->enc) return;
- cmd_begin(d);
+ enc_end(d); cmd_begin(d);
MTLRenderPassDescriptor *rp = [MTLRenderPassDescriptor renderPassDescriptor];
for (int i = 0; i < 4; i++) {
res *s = d->rt[i]; if (!s) continue;
rp.colorAttachments[i].texture = s->parent->tex; rp.colorAttachments[i].level = s->level; rp.colorAttachments[i].slice = s->face;
- rp.colorAttachments[i].storeAction = MTLStoreActionStore;
+ rp.colorAttachments[i].storeAction = MTLStoreActionStore; gpu_use(d, s->parent);
if (d->clear_flags & 1) { rp.colorAttachments[i].loadAction = MTLLoadActionClear; rp.colorAttachments[i].clearColor = MTLClearColorMake(d->clear_color[0], d->clear_color[1], d->clear_color[2], d->clear_color[3]); }
else rp.colorAttachments[i].loadAction = MTLLoadActionLoad;
s->parent->gpu_dirty = 1;
}
res *ds = d->ds;
if (ds && ds->w >= d->rt[0]->w && ds->h >= d->rt[0]->h) {
- rp.depthAttachment.texture = ds->parent->tex; rp.depthAttachment.storeAction = MTLStoreActionStore;
+ rp.depthAttachment.texture = ds->parent->tex; rp.depthAttachment.storeAction = MTLStoreActionStore; gpu_use(d, ds->parent);
if (d->clear_flags & 2) { rp.depthAttachment.loadAction = MTLLoadActionClear; rp.depthAttachment.clearDepth = d->clear_z; }
else rp.depthAttachment.loadAction = MTLLoadActionLoad;
if (ds->fi->stencil) {
@@ -679,7 +890,8 @@ void begin_pass(device *d) {
}
}
d->clear_flags = 0;
- d->enc = [[d->cmd renderCommandEncoderWithDescriptor:rp] retain];
+ d->enc = [[d->cmd renderCommandEncoderWithDescriptor:rp] retain]; d->n_pass++;
+ memset(&d->ec, 0, sizeof d->ec); [d->enc setFrontFacingWinding:MTLWindingClockwise];
}
COM(IDirect3DDevice9, Clear, 7) {
@autoreleasepool { DEV;
@@ -746,19 +958,20 @@ void begin_pass(device *d) {
COM(IDirect3DDevice9, SetPixelShader, 2) { DEV; ST(d)->ps = a[1]; if (MK(d)) MK(d)->ps = 1; return 0; }
COM(IDirect3DDevice9, GetPixelShader, 2) { DEV; PUTOBJ(a[1], d->s.ps); if (d->s.ps) R(d->s.ps)->ref++; return 0; }
#define CONSTS(NAME, field, lim, width) \
- COM(IDirect3DDevice9, Set##NAME, 4) { DEV; if (a[1] + a[3] > lim) return D3DERR_INVALIDCALL; memcpy(ST(d)->field[a[1]], P(a[2]), a[3] * width); if (MK(d)) memset(MK(d)->field + a[1], 1, a[3]); return 0; } \
+ COM(IDirect3DDevice9, Set##NAME, 4) { DEV; if (a[1] + a[3] > lim) return D3DERR_INVALIDCALL; memcpy(ST(d)->field[a[1]], P(a[2]), a[3] * width); d->cgen++; if (MK(d)) memset(MK(d)->field + a[1], 1, a[3]); return 0; } \
COM(IDirect3DDevice9, Get##NAME, 4) { DEV; if (a[1] + a[3] > lim) return D3DERR_INVALIDCALL; memcpy(P(a[2]), d->s.field[a[1]], a[3] * width); return 0; }
CONSTS(VertexShaderConstantF, vsf, 256, 16)
CONSTS(PixelShaderConstantF, psf, 224, 16)
CONSTS(VertexShaderConstantI, vsi, 16, 16)
CONSTS(PixelShaderConstantI, psi, 16, 16)
-COM(IDirect3DDevice9, SetVertexShaderConstantB, 4) { DEV; if (a[1] + a[3] > 16) return D3DERR_INVALIDCALL; memcpy(&ST(d)->vsb[a[1]], P(a[2]), a[3] * 4); if (MK(d)) memset(MK(d)->vsb + a[1], 1, a[3]); return 0; }
+COM(IDirect3DDevice9, SetVertexShaderConstantB, 4) { DEV; if (a[1] + a[3] > 16) return D3DERR_INVALIDCALL; memcpy(&ST(d)->vsb[a[1]], P(a[2]), a[3] * 4); d->cgen++; if (MK(d)) memset(MK(d)->vsb + a[1], 1, a[3]); return 0; }
COM(IDirect3DDevice9, GetVertexShaderConstantB, 4) { DEV; memcpy(P(a[2]), &d->s.vsb[a[1] & 15], a[3] * 4); return 0; }
-COM(IDirect3DDevice9, SetPixelShaderConstantB, 4) { DEV; if (a[1] + a[3] > 16) return D3DERR_INVALIDCALL; memcpy(&ST(d)->psb[a[1]], P(a[2]), a[3] * 4); if (MK(d)) memset(MK(d)->psb + a[1], 1, a[3]); return 0; }
+COM(IDirect3DDevice9, SetPixelShaderConstantB, 4) { DEV; if (a[1] + a[3] > 16) return D3DERR_INVALIDCALL; memcpy(&ST(d)->psb[a[1]], P(a[2]), a[3] * 4); d->cgen++; if (MK(d)) memset(MK(d)->psb + a[1], 1, a[3]); return 0; }
COM(IDirect3DDevice9, GetPixelShaderConstantB, 4) { DEV; memcpy(P(a[2]), &d->s.psb[a[1] & 15], a[3] * 4); return 0; }
/* ---------------- state blocks ---------------- */
static void sb_apply(device *d, sblock *b, int capture) {
+ d->cgen++;
dstate *src = capture ? &d->s : &b->s, *dst = capture ? &b->s : &d->s; smask *m = &b->m;
for (int i = 0; i < 256; i++) if (m->rs[i]) dst->rs[i] = src->rs[i];
for (int i = 0; i < 8; i++) for (int k = 0; k < 33; k++) if (m->tss[i][k]) dst->tss[i][k] = src->tss[i][k];
@@ -856,3 +1069,42 @@ static uint32_t create_shader(device *d, int kind, gp code, gp pp) {
if (a[1] && a[2] >= 4) *(uint32_t *)P(a[1]) = r->qtype == 8 ? 1 : 100000;
return D3D_OK; }
}
+
+/* ---------------- D3DX accelerations (see accel_for in loader.c) ---------------- */
+/* D3DXLoadSurfaceFromMemory for 32-bit ARGB/XRGB into one of this device's surfaces, without a palette, colour key or
+ sRGB conversion: a copy at the same size, a point-filtered scale, or a fill from a single pixel (any filter gives that
+ colour). Everything else goes to the game's D3DX. C&C 3 fills its textures from a one-pixel source after each Reset;
+ D3DX's per-pixel x87 conversion of thousands of them froze the game for ten seconds on every return to it. */
+NATIVE(d3dx9, D3DXLoadSurfaceFromMemory, 10) {
+ @autoreleasepool {
+ res *s = a[0] ? R(a[0]) : 0; uint32_t fmt = a[4], filt = a[8];
+ int ok = s && s->kind == K_SURF && s->parent && s->parent->kind != K_VOL && !a[1] && !a[6] && !a[9] && a[3] &&
+ (fmt == 21 || fmt == 22) && (s->fmt == 21 || s->fmt == 22) && (filt == 0xffffffff || !(filt & 0x7f0000)); /* no sRGB/mirror flags */
+ if (ok) {
+ int32_t dr[4] = {0, 0, (int32_t)s->w, (int32_t)s->h}, sr[4];
+ if (a[2]) memcpy(dr, P(a[2]), 16);
+ if (a[7]) memcpy(sr, P(a[7]), 16); else ok = 0; /* D3DX requires the source rectangle */
+ int dw = dr[2] - dr[0], dh = dr[3] - dr[1], sw = ok ? sr[2] - sr[0] : 0, sh = ok ? sr[3] - sr[1] : 0;
+ uint32_t f = filt == 0xffffffff ? 5 : filt & 0xff; /* D3DX_DEFAULT: triangle */
+ if (ok && (dr[0] < 0 || dr[1] < 0 || dw <= 0 || dh <= 0 || dr[2] > (int32_t)s->w || dr[3] > (int32_t)s->h || sw <= 0 || sh <= 0)) ok = 0;
+ if (ok && !((sw == 1 && sh == 1) || (sw == dw && sh == dh) || f == 2)) ok = 0;
+ if (ok) {
+ res *t = s->parent; device *d = g_dev; uint32_t pitch;
+ uint8_t *base = lock_sub(d, t, s->level, s->face, &pitch, 0);
+ const uint8_t *src = P(a[3]); uint32_t spitch = a[5];
+ uint32_t amask = fmt == 22 && s->fmt == 21 ? 0xff000000u : 0; /* X8 into A8: opaque */
+ for (int y = 0; y < dh; y++) {
+ uint32_t *o = (uint32_t *)(base + (dr[1] + y) * pitch) + dr[0];
+ const uint32_t *row = (const uint32_t *)(src + (sr[1] + (sh == 1 ? 0 : (int)((int64_t)y * sh / dh))) * spitch) + sr[0];
+ if (sw == 1) { uint32_t v = row[0] | amask; for (int x = 0; x < dw; x++) o[x] = v; }
+ else if (sw == dw && !amask) memcpy(o, row, 4 * dw);
+ else for (int x = 0; x < dw; x++) o[x] = row[sw == dw ? x : (int)((int64_t)x * sw / dw)] | amask;
+ }
+ upload_sub_rect(d, t, s->level, s->face, dr);
+ return D3D_OK;
+ }
+ }
+ }
+ uint32_t orig = pe2_accel_orig("D3DXLoadSurfaceFromMemory");
+ return orig ? pe2_callback(orig, a, 10) : D3DERR_INVALIDCALL;
+}
diff --git a/runtime/d3d9_draw.m b/runtime/d3d9_draw.m
index 416f53d..3a726f9 100644
--- a/runtime/d3d9_draw.m
+++ b/runtime/d3d9_draw.m
@@ -118,9 +118,13 @@ static MTLBlendOperation bop(uint32_t o) {
/* A program converted on a Mac without the Metal compiler carries its shaders as Metal source instead of a compiled
library: one file per function in Resources/-src, written when it was converted. The system compiles
each on first use. Nothing is translated here: the source is already Metal. */
+#include
+static pthread_mutex_t g_fn_lock = PTHREAD_MUTEX_INITIALIZER; /* source_function's cache: the warm-up threads use it too */
static id source_function(NSString *name) {
- static NSMutableDictionary *seen; if (!seen) seen = [NSMutableDictionary new];
- id c = seen[name]; if (c) return c == (id)NSNull.null ? nil : [c retain]; /* the caller owns what it gets and releases it; the cache keeps its own reference */
+ static NSMutableDictionary *seen;
+ pthread_mutex_lock(&g_fn_lock); if (!seen) seen = [NSMutableDictionary new];
+ id c = [seen[name] retain]; pthread_mutex_unlock(&g_fn_lock);
+ if (c) { if (c == (id)NSNull.null) { [c release]; return nil; } return c; } /* the caller owns what it gets and releases it; the cache keeps its own reference */
NSString *p = [[NSBundle mainBundle] pathForResource:name ofType:@"metal" inDirectory:SHADERLIB @"-src"]; id f = nil;
if (!p && learn_dir()) { p = [NSString stringWithFormat:@"%s/%@.metal", learn_dir(), name]; if (access(p.fileSystemRepresentation, R_OK)) p = nil; }
NSString *src = p ? [NSString stringWithContentsOfFile:p encoding:NSUTF8StringEncoding error:nil] : nil;
@@ -130,7 +134,9 @@ static MTLBlendOperation bop(uint32_t o) {
id l = [g_srcdev newLibraryWithSource:src options:o error:&e]; f = [l newFunctionWithName:name]; [l release]; [o release]; /* the function keeps its library */
if (!f) fprintf(stderr, "d3d: shader source %s did not compile: %s\n", name.UTF8String, e.localizedDescription.UTF8String ?: "no such function");
}
- if (f || src) seen[name] = f ?: (id)NSNull.null; /* a name with no source yet may get one (make_source) */
+ pthread_mutex_lock(&g_fn_lock);
+ if (f || src) { id prev = seen[name]; if (prev && prev != (id)NSNull.null && f) { [f release]; f = [prev retain]; } else seen[name] = f ?: (id)NSNull.null; } /* a name with no source yet may get one (make_source) */
+ pthread_mutex_unlock(&g_fn_lock);
return f;
}
/* A shader the program has not used before: its recipe (learn) is turned into Metal source by the converter's shader
@@ -167,8 +173,9 @@ static void learn(const char *name, uint32_t kind, const shader_key *k, const vl
if (k) r.key = *k; if (l) r.link = *l; if (f) r.ff = *f;
FILE *o = fopen(path, "wb"); if (!o) return; fwrite(&r, sizeof r, 1, o); if (n) fwrite(code, 4, n, o); fclose(o);
}
-static id shader_function(device *d, res *sh, const shader_key *k0, res *ps_for_link) {
- load_library(d);
+/* the function name a shader gets under a key (its code hash and the variant the key makes), and the key and link
+ its source is generated with */
+static void shader_name(res *sh, const shader_key *k0, res *ps_for_link, char name[48], shader_key *kout, vlink *lout) {
shader_key k = *k0;
vlink link = {0};
uint32_t variant = 0;
@@ -181,22 +188,30 @@ static void learn(const char *name, uint32_t kind, const shader_key *k, const vl
k.depth_mask = dm; k.proj_mask = pm; for (int i = 0; i < 16; i++) k.samp_kind[i] = kinds[i] ? kinds[i] : 2;
int any = dm || pm; for (int i = 0; i < 16; i++) any |= kinds[i];
if (any) variant = (uint32_t)fnv64(kinds, 16) ^ dm * 40503u ^ pm * 2654435761u;
+ if (k.points == 2) variant ^= 0x85ebca6bu; /* point sprites read their coordinates */
} else {
if (k.points) variant ^= 0x9e3779b9u;
if (sh->info.major >= 3 && ps_for_link) { link = ps_for_link->info.link; variant ^= (uint32_t)fnv64(&link, sizeof link); }
}
- char name[48];
- snprintf(name, sizeof name, "%s_%016llx", sh->info.ps ? "ps" : "vs", fnv64(sh->code, 4 * sh->ncode));
- if (variant) snprintf(name + strlen(name), sizeof name - strlen(name), "_v%08x", variant);
+ snprintf(name, 48, "%s_%016llx", sh->info.ps ? "ps" : "vs", fnv64(sh->code, 4 * sh->ncode));
+ if (variant) snprintf(name + strlen(name), 48 - strlen(name), "_v%08x", variant);
+ *kout = k; *lout = link;
+}
+static id shader_function(device *d, res *sh, const shader_key *k0, res *ps_for_link) {
+ load_library(d);
+ char name[48]; shader_key k; vlink link; shader_name(sh, k0, ps_for_link, name, &k, &link);
NSString *ns = [NSString stringWithUTF8String:name];
if (g_aot) { id f = [g_aot newFunctionWithName:ns]; if (f) return f; }
{ id f = source_function(ns); if (f) return f; }
learn(name, sh->info.ps ? 1 : 0, &k, &link, 0, sh->code, sh->ncode);
{ id f = make_source(name); if (!f) report_missing(name); return f; }
}
-static id ff_function(const ff_key *f, const vlink *link, int ps) {
+static void ff_name(const ff_key *f, const vlink *link, int ps, char name[48]) {
struct { ff_key f; vlink l; } key; memset(&key, 0, sizeof key); key.f = *f; if (!ps) key.l = *link;
- char name[48]; snprintf(name, sizeof name, "%s_%016llx", ps ? "ffp" : "ffv", fnv64(&key, sizeof key));
+ snprintf(name, 48, "%s_%016llx", ps ? "ffp" : "ffv", fnv64(&key, sizeof key));
+}
+static id ff_function(const ff_key *f, const vlink *link, int ps) {
+ char name[48]; ff_name(f, link, ps, name);
id fn = [g_aot newFunctionWithName:[NSString stringWithUTF8String:name]];
if (!fn) fn = source_function([NSString stringWithUTF8String:name]);
if (!fn) { learn(name, ps ? 3 : 2, 0, link, f, 0, 0); fn = make_source(name); if (!fn) report_missing(name); }
@@ -212,73 +227,189 @@ void d3d_harvest_shader(res *sh) {
if ([[NSBundle mainBundle] pathForResource:[NSString stringWithUTF8String:name] ofType:@"metal" inDirectory:SHADERLIB @"-src"]) return; /* carried as source */
vlink none = {0}; learn(name, sh->info.ps ? 1 : 0, &k, &none, 0, sh->code, sh->ncode);
}
+static id pipeline_lookup(device *d, pkey *k, const elem *el, int nel, res *vs, res *ps);
+static id pipeline_make(device *d, pkey *k, NSData *key, const elem *el, int nel, res *vs, res *ps);
+/* the previous draw's key and pipeline: consecutive draws often share one, and the dictionary lookup (a key object
+ and a hash of the whole key) is skipped then. Pipelines stay in d->pipes for the device's life, so it stays valid. */
static id pipeline(device *d, pkey *k, const elem *el, int nel, res *vs, res *ps) {
+ static pkey last; static id last_p; static device *last_d;
+ if (last_d == d && !memcmp(&last, k, sizeof *k)) return last_p;
+ id p = pipeline_lookup(d, k, el, nel, vs, ps);
+ memcpy(&last, k, sizeof *k); last_p = p; last_d = d;
+ return p;
+}
+static id pipeline_lookup(device *d, pkey *k, const elem *el, int nel, res *vs, res *ps) {
NSData *key = [NSData dataWithBytes:k length:sizeof *k];
id p = d->pipes[key];
if (p) return (id)p == (id)[NSNull null] ? nil : p;
- id vf = vs ? shader_function(d, vs, &k->vk, ps) : nil, pf = ps ? shader_function(d, ps, &k->pk, 0) : nil;
- if (!vs || !ps) {
- load_library(d); vlink link = {0}; if (ps) link = ps->info.link;
- if (!vs) vf = ff_function(&k->ff, &link, 0);
- if (!ps) pf = ff_function(&k->ff, &link, 1);
- }
- if (!vf || !pf) { [vf release]; [pf release]; d->pipes[key] = [NSNull null]; return nil; }
- MTLRenderPipelineDescriptor *pd = [MTLRenderPipelineDescriptor new];
- pd.vertexFunction = vf; pd.fragmentFunction = pf; [vf release]; [pf release];
+ double t0 = CACurrentMediaTime(); d->n_pipe++;
+ p = pipeline_make(d, k, key, el, nel, vs, ps);
+ d->t_pipe += CACurrentMediaTime() - t0;
+ return p;
+}
+/* ---- pipeline warm-up ----
+ Making a pipeline compiles its two shaders (from the learned Metal source) and the pipeline itself; a scene that
+ brings in new effects (a building blowing up: fire, smoke, debris) made dozens at once mid-game, a visible hitch of a
+ few hundred milliseconds. Every pipeline made is recorded in the learn folder (pipelines.bin) by what Metal needs to
+ make it again: its function names, vertex layout, attachments and blending. When the game creates its device, the
+ recorded ones are made on background threads, so by the time a battle needs them they are ready. A pipeline is
+ found by that description, so the game's own object ids (which change from run to run) do not matter. */
+typedef struct {
+ uint32_t magic;
+ char vf[48], pf[48];
+ uint32_t slots; uint8_t afmt[31], abuf[31]; uint16_t aoff[31];
+ uint32_t lays; uint32_t lstride[31], lrate[31]; uint8_t lfn[31];
+ uint32_t cfmt[4]; uint8_t cmask[4], cblend[4], csrc[4], cdst[4], cop[4], csa[4], cda[4], copa[4];
+ uint32_t dsfmt, stfmt; uint32_t points;
+} pdesc;
+#define PDESC_MAGIC 0x31445050u /* "PPD1" */
+static pthread_mutex_t g_warm_lock = PTHREAD_MUTEX_INITIALIZER;
+static NSMutableDictionary *g_warm; /* NSData(pdesc) -> pipeline, or NSNull when it could not be made */
+static NSMutableSet *g_recorded; /* descriptions already in pipelines.bin */
+static _Atomic int g_warm_left;
+
+static void pdesc_fill(pdesc *q, pkey *k, const elem *el, int nel, res *vs, const char *vname, const char *pname) {
+ memset(q, 0, sizeof *q); q->magic = PDESC_MAGIC;
+ snprintf(q->vf, sizeof q->vf, "%s", vname); snprintf(q->pf, sizeof q->pf, "%s", pname);
/* elements go to the fixed slots the shaders read (attr_slot_for); inputs the layout lacks read (0,0,0,1) */
- MTLVertexDescriptor *vd = [MTLVertexDescriptor vertexDescriptor];
- uint32_t used_streams = 0, slots = 0;
+ uint32_t used_streams = 0;
for (int i = 0; i < nel; i++) {
int sl = attr_slot_for(el[i].usage, el[i].index);
- if (sl < 0 || (slots >> sl & 1)) continue;
- slots |= 1u << sl;
- uint8_t isint; vd.attributes[sl].format = vfmt(el[i].type, &isint);
- vd.attributes[sl].offset = el[i].offset; vd.attributes[sl].bufferIndex = 16 + el[i].stream;
+ if (sl < 0 || (q->slots >> sl & 1)) continue;
+ q->slots |= 1u << sl;
+ uint8_t isint; q->afmt[sl] = (uint8_t)vfmt(el[i].type, &isint); q->aoff[sl] = el[i].offset; q->abuf[sl] = 16 + el[i].stream;
used_streams |= 1u << el[i].stream;
}
uint32_t want = 0;
if (vs) { for (int v = 0; v < 16; v++) if (vs->info.vin_used[v]) { int sl = attr_slot_for(vs->info.vin_usage[v], vs->info.vin_index[v]); if (sl >= 0) want |= 1u << sl; } }
else { want = 1; for (int i = 0; i < 8; i++) if (k->ff.attr_tex[i] >= 0) want |= 1u << (10 + i); if (k->ff.attr_diffuse >= 0) want |= 1u << 5; if (k->ff.attr_specular >= 0) want |= 1u << 6; }
int defaults = 0;
- for (int sl = 0; sl < 31; sl++) if ((want >> sl & 1) && !(slots >> sl & 1)) {
- vd.attributes[sl].format = MTLVertexFormatFloat4; vd.attributes[sl].offset = 0; vd.attributes[sl].bufferIndex = ATTR_DEFAULT_BUFFER; defaults = 1;
+ for (int sl = 0; sl < 31; sl++) if ((want >> sl & 1) && !(q->slots >> sl & 1)) {
+ q->slots |= 1u << sl; q->afmt[sl] = (uint8_t)MTLVertexFormatFloat4; q->aoff[sl] = 0; q->abuf[sl] = ATTR_DEFAULT_BUFFER; defaults = 1;
}
/* a layout no attribute reads is an error on Apple's drivers (assertion at pipeline creation on an M1) */
- if (defaults) { vd.layouts[ATTR_DEFAULT_BUFFER].stepFunction = MTLVertexStepFunctionConstant; vd.layouts[ATTR_DEFAULT_BUFFER].stepRate = 0; vd.layouts[ATTR_DEFAULT_BUFFER].stride = 16; }
+ if (defaults) { q->lays |= 1u << ATTR_DEFAULT_BUFFER; q->lfn[ATTR_DEFAULT_BUFFER] = (uint8_t)MTLVertexStepFunctionConstant; q->lrate[ATTR_DEFAULT_BUFFER] = 0; q->lstride[ATTR_DEFAULT_BUFFER] = 16; }
for (int s = 0; s < 16; s++) if (used_streams >> s & 1) {
- uint32_t st = k->strides[s];
- if (!st) { vd.layouts[16 + s].stepFunction = MTLVertexStepFunctionConstant; vd.layouts[16 + s].stepRate = 0; vd.layouts[16 + s].stride = 16; }
+ uint32_t st = k->strides[s], b = 16 + s; q->lays |= 1u << b;
+ if (!st) { q->lfn[b] = (uint8_t)MTLVertexStepFunctionConstant; q->lrate[b] = 0; q->lstride[b] = 16; }
else {
- vd.layouts[16 + s].stride = (st + 3) & ~3u;
- if (k->stepfn[s]) { vd.layouts[16 + s].stepFunction = MTLVertexStepFunctionPerInstance; vd.layouts[16 + s].stepRate = k->stepfn[s]; }
+ q->lstride[b] = (st + 3) & ~3u; q->lfn[b] = (uint8_t)MTLVertexStepFunctionPerVertex; q->lrate[b] = 1;
+ if (k->stepfn[s]) { q->lfn[b] = (uint8_t)MTLVertexStepFunctionPerInstance; q->lrate[b] = k->stepfn[s]; }
}
}
- pd.vertexDescriptor = vd;
for (int i = 0; i < 4; i++) {
if (!k->rtfmt[i]) continue;
- MTLRenderPipelineColorAttachmentDescriptor *ca = pd.colorAttachments[i];
- ca.pixelFormat = (MTLPixelFormat)k->rtfmt[i];
+ q->cfmt[i] = k->rtfmt[i];
uint32_t mask = (k->blend[8] >> (4 * i)) & 0xf;
- ca.writeMask = (mask & 1 ? MTLColorWriteMaskRed : 0) | (mask & 2 ? MTLColorWriteMaskGreen : 0) | (mask & 4 ? MTLColorWriteMaskBlue : 0) | (mask & 8 ? MTLColorWriteMaskAlpha : 0);
+ q->cmask[i] = (mask & 1 ? MTLColorWriteMaskRed : 0) | (mask & 2 ? MTLColorWriteMaskGreen : 0) | (mask & 4 ? MTLColorWriteMaskBlue : 0) | (mask & 8 ? MTLColorWriteMaskAlpha : 0);
if (k->blend[0]) {
- uint32_t s = k->blend[1], dd = k->blend[2];
- if (s == 12) { s = 5; dd = 6; } else if (s == 13) { s = 6; dd = 5; }
+ uint32_t sf = k->blend[1], dd = k->blend[2];
+ if (sf == 12) { sf = 5; dd = 6; } else if (sf == 13) { sf = 6; dd = 5; }
+ q->cblend[i] = 1;
+ q->csrc[i] = (uint8_t)bf(sf, 0); q->cdst[i] = (uint8_t)bf(dd, 0); q->cop[i] = (uint8_t)bop(k->blend[3]);
+ if (k->blend[4]) { q->csa[i] = (uint8_t)bf(k->blend[5], 1); q->cda[i] = (uint8_t)bf(k->blend[6], 1); q->copa[i] = (uint8_t)bop(k->blend[7]); }
+ else { q->csa[i] = (uint8_t)bf(sf, 1); q->cda[i] = (uint8_t)bf(dd, 1); q->copa[i] = (uint8_t)bop(k->blend[3]); }
+ }
+ }
+ q->dsfmt = k->dsfmt; q->stfmt = k->stfmt; q->points = k->blend[9] != 0;
+}
+static id pdesc_make(id dev, const pdesc *q, id vf, id pf, NSError **err) {
+ MTLRenderPipelineDescriptor *pd = [MTLRenderPipelineDescriptor new];
+ pd.vertexFunction = vf; pd.fragmentFunction = pf;
+ MTLVertexDescriptor *vd = [MTLVertexDescriptor vertexDescriptor];
+ for (int sl = 0; sl < 31; sl++) if (q->slots >> sl & 1) { vd.attributes[sl].format = (MTLVertexFormat)q->afmt[sl]; vd.attributes[sl].offset = q->aoff[sl]; vd.attributes[sl].bufferIndex = q->abuf[sl]; }
+ for (int b = 0; b < 31; b++) if (q->lays >> b & 1) { vd.layouts[b].stride = q->lstride[b]; vd.layouts[b].stepFunction = (MTLVertexStepFunction)q->lfn[b]; vd.layouts[b].stepRate = q->lrate[b]; }
+ pd.vertexDescriptor = vd;
+ for (int i = 0; i < 4; i++) {
+ if (!q->cfmt[i]) continue;
+ MTLRenderPipelineColorAttachmentDescriptor *ca = pd.colorAttachments[i];
+ ca.pixelFormat = (MTLPixelFormat)q->cfmt[i]; ca.writeMask = q->cmask[i];
+ if (q->cblend[i]) {
ca.blendingEnabled = YES;
- ca.sourceRGBBlendFactor = bf(s, 0); ca.destinationRGBBlendFactor = bf(dd, 0); ca.rgbBlendOperation = bop(k->blend[3]);
- if (k->blend[4]) { ca.sourceAlphaBlendFactor = bf(k->blend[5], 1); ca.destinationAlphaBlendFactor = bf(k->blend[6], 1); ca.alphaBlendOperation = bop(k->blend[7]); }
- else { ca.sourceAlphaBlendFactor = bf(s, 1); ca.destinationAlphaBlendFactor = bf(dd, 1); ca.alphaBlendOperation = bop(k->blend[3]); }
+ ca.sourceRGBBlendFactor = (MTLBlendFactor)q->csrc[i]; ca.destinationRGBBlendFactor = (MTLBlendFactor)q->cdst[i]; ca.rgbBlendOperation = (MTLBlendOperation)q->cop[i];
+ ca.sourceAlphaBlendFactor = (MTLBlendFactor)q->csa[i]; ca.destinationAlphaBlendFactor = (MTLBlendFactor)q->cda[i]; ca.alphaBlendOperation = (MTLBlendOperation)q->copa[i];
}
}
- pd.depthAttachmentPixelFormat = (MTLPixelFormat)k->dsfmt;
- pd.stencilAttachmentPixelFormat = (MTLPixelFormat)k->stfmt;
- if (k->blend[9]) pd.inputPrimitiveTopology = MTLPrimitiveTopologyClassPoint;
- NSError *e = nil;
- p = [d->dev newRenderPipelineStateWithDescriptor:pd error:&e];
+ pd.depthAttachmentPixelFormat = (MTLPixelFormat)q->dsfmt;
+ pd.stencilAttachmentPixelFormat = (MTLPixelFormat)q->stfmt;
+ if (q->points) pd.inputPrimitiveTopology = MTLPrimitiveTopologyClassPoint;
+ id p = [dev newRenderPipelineStateWithDescriptor:pd error:err];
[pd release];
+ return p;
+}
+static void pdesc_record(const pdesc *q, NSData *qd) {
+ const char *dir = learn_dir(); if (!dir) return;
+ pthread_mutex_lock(&g_warm_lock);
+ int fresh = g_recorded && ![g_recorded containsObject:qd];
+ if (fresh) [g_recorded addObject:qd];
+ pthread_mutex_unlock(&g_warm_lock);
+ if (!fresh) return;
+ char path[1100]; snprintf(path, sizeof path, "%s/pipelines.bin", dir);
+ FILE *o = fopen(path, "ab"); if (!o) return; fwrite(q, sizeof *q, 1, o); fclose(o);
+}
+/* a function by name, as the draw would find it: the app's compiled library, else the learned source */
+static id fn_by_name(const char *name) {
+ NSString *ns = [NSString stringWithUTF8String:name];
+ if (g_aot) { id f = [g_aot newFunctionWithName:ns]; if (f) return f; }
+ return source_function(ns);
+}
+/* at device creation: every recorded pipeline, made on background threads (Metal makes pipelines on any thread) */
+void d3d_warm_pipelines(device *d) {
+ static int once; if (once) return; once = 1;
+ if (getenv("PE2_NO_WARM")) return;
+ g_warm = [NSMutableDictionary new]; g_recorded = [NSMutableSet new];
+ const char *dir = learn_dir(); if (!dir) return;
+ load_library(d);
+ char path[1100]; snprintf(path, sizeof path, "%s/pipelines.bin", dir);
+ NSData *all = [NSData dataWithContentsOfFile:[NSString stringWithUTF8String:path]]; if (!all) return;
+ NSUInteger n = all.length / sizeof(pdesc); const pdesc *v = all.bytes; NSMutableArray *todo = [NSMutableArray array];
+ for (NSUInteger i = 0; i < n; i++) {
+ if (v[i].magic != PDESC_MAGIC) continue;
+ NSData *qd = [NSData dataWithBytes:&v[i] length:sizeof(pdesc)];
+ if ([g_recorded containsObject:qd]) continue;
+ [g_recorded addObject:qd]; [todo addObject:qd];
+ }
+ id dev = [d->dev retain]; double t0 = CACurrentMediaTime(); NSUInteger total = todo.count;
+ atomic_store(&g_warm_left, (int)total);
+ fprintf(stderr, "d3d: making %lu recorded pipelines in the background\n", (unsigned long)total);
+ [todo retain];
+ dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{
+ dispatch_apply(total, dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^(size_t i) { @autoreleasepool {
+ NSData *qd = todo[i]; const pdesc *q = qd.bytes;
+ id vf = fn_by_name(q->vf), pf = fn_by_name(q->pf);
+ id p = vf && pf ? pdesc_make(dev, q, vf, pf, 0) : nil;
+ [vf release]; [pf release];
+ if (p) { pthread_mutex_lock(&g_warm_lock); if (!g_warm[qd]) g_warm[qd] = p; pthread_mutex_unlock(&g_warm_lock); [p release]; }
+ atomic_fetch_sub(&g_warm_left, 1);
+ } });
+ fprintf(stderr, "d3d: %lu recorded pipelines made in %.1f s\n", (unsigned long)total, CACurrentMediaTime() - t0);
+ [todo release]; [dev release];
+ });
+}
+/* a pipeline not made yet this session: one the warm-up made, else its shaders (from the learned sources, compiled by
+ the system) and its state, recorded for the next run */
+static id pipeline_make(device *d, pkey *k, NSData *key, const elem *el, int nel, res *vs, res *ps) {
+ load_library(d);
+ vlink link = {0}; if (ps) link = ps->info.link;
+ char vname[48], pname[48]; shader_key tk; vlink tl;
+ if (vs) shader_name(vs, &k->vk, ps, vname, &tk, &tl); else ff_name(&k->ff, &link, 0, vname);
+ if (ps) shader_name(ps, &k->pk, 0, pname, &tk, &tl); else ff_name(&k->ff, &link, 1, pname);
+ pdesc q; pdesc_fill(&q, k, el, nel, vs, vname, pname);
+ NSData *qd = [NSData dataWithBytes:&q length:sizeof q];
+ pthread_mutex_lock(&g_warm_lock); id p = [g_warm[qd] retain]; pthread_mutex_unlock(&g_warm_lock);
+ if (p) { d->n_warm_hit++; d->pipes[key] = p; [p release]; return p; }
+ id vf = vs ? shader_function(d, vs, &k->vk, ps) : ff_function(&k->ff, &link, 0);
+ id pf = ps ? shader_function(d, ps, &k->pk, 0) : ff_function(&k->ff, &link, 1);
+ if (!vf || !pf) { [vf release]; [pf release]; d->pipes[key] = [NSNull null]; return nil; }
+ NSError *e = nil;
+ p = pdesc_make(d->dev, &q, vf, pf, &e);
+ [vf release]; [pf release];
if (!p) {
static int shown; if (shown++ < 6) fprintf(stderr, "d3d: pipeline failed (vs %u ps %u): %s\n", vs ? vs->sh_id : 0, ps ? ps->sh_id : 0, e.localizedDescription.UTF8String);
d->pipes[key] = [NSNull null]; return nil;
}
+ pthread_mutex_lock(&g_warm_lock); if (g_warm && !g_warm[qd]) g_warm[qd] = p; pthread_mutex_unlock(&g_warm_lock);
+ pdesc_record(&q, qd);
d->pipes[key] = p; [p release];
return p;
}
@@ -326,8 +457,15 @@ static MTLSamplerAddressMode addr(uint32_t a) {
uint32_t bc = ss[4];
uint32_t border = (bc >> 24) < 0x80 ? 0 : (bc & 0xffffff) > 0x808080 ? 2 : 1;
uint32_t maxmip = ss[9] < (uint32_t)levels ? ss[9] : 0;
+ /* Anisotropic filtering, as a driver's control panel forces it: a mipmapped texture filtered linearly is sampled
+ with up to PE2_ANISO (default 16, 0 = only what the game asks for) samples along the slant, so ground seen at an
+ angle (all of an RTS view) stays sharp instead of blurring with distance. Textures without mipmaps (interface,
+ text) and point-filtered ones are left as the game set them. */
+ static int force = -1; if (force < 0) { const char *e = getenv("PE2_ANISO"); force = e ? atoi(e) : 16; if (force > 16) force = 16; if (force < 0) force = 0; }
+ uint32_t aniso = (ss[6] == 3 || ss[5] == 3) && ss[10] > 1 ? (ss[10] > 16 ? 16 : ss[10]) : 0;
+ if (force > 1 && levels > 1 && ss[6] >= 2 && ss[7] >= 1 && (uint32_t)force > aniso) aniso = force;
uint64_t k = (ss[1] & 7) | (ss[2] & 7) << 3 | (ss[3] & 7) << 6 | (ss[5] & 3) << 9 | (ss[6] & 3) << 11 | (ss[7] & 3) << 13 |
- (uint64_t)(ss[10] & 31) << 15 | (uint64_t)border << 20 | (uint64_t)(maxmip & 15) << 22;
+ (uint64_t)(aniso & 31) << 15 | (uint64_t)border << 20 | (uint64_t)(maxmip & 15) << 22;
NSNumber *key = @(k);
id s = d->samplers[key];
if (s) return s;
@@ -336,7 +474,7 @@ static MTLSamplerAddressMode addr(uint32_t a) {
sd.magFilter = ss[5] >= 2 ? MTLSamplerMinMagFilterLinear : MTLSamplerMinMagFilterNearest;
sd.minFilter = ss[6] >= 2 ? MTLSamplerMinMagFilterLinear : MTLSamplerMinMagFilterNearest;
sd.mipFilter = ss[7] == 0 ? MTLSamplerMipFilterNotMipmapped : ss[7] == 1 ? MTLSamplerMipFilterNearest : MTLSamplerMipFilterLinear;
- if ((ss[6] == 3 || ss[5] == 3) && ss[10] > 1) sd.maxAnisotropy = ss[10] > 16 ? 16 : ss[10];
+ if (aniso > 1) sd.maxAnisotropy = aniso;
sd.borderColor = border == 0 ? MTLSamplerBorderColorTransparentBlack : border == 1 ? MTLSamplerBorderColorOpaqueBlack : MTLSamplerBorderColorOpaqueWhite;
sd.lodMinClamp = maxmip;
s = [d->dev newSamplerStateWithDescriptor:sd];
@@ -346,7 +484,7 @@ static MTLSamplerAddressMode addr(uint32_t a) {
}
/* ---------------- transient data ---------------- */
-static uint32_t ring_alloc(device *d, uint32_t size, uint32_t align, void **ptr, id *buf) {
+uint32_t ring_alloc(device *d, uint32_t size, uint32_t align, void **ptr, id *buf) {
uint32_t off = (d->ring_off + align - 1) & ~(align - 1);
if (off + size > d->ring[d->ring_idx].length) {
/* this frame's ring is full: finish the frame's work so far and start the ring over */
@@ -369,8 +507,23 @@ static MTLPrimitiveType mprim(uint32_t prim) {
switch (prim) { case 1: return MTLPrimitiveTypePoint; case 2: return MTLPrimitiveTypeLine; case 3: return MTLPrimitiveTypeLineStrip; case 5: return MTLPrimitiveTypeTriangleStrip; default: return MTLPrimitiveTypeTriangle; }
}
+/* an indexed draw with no usable index buffer (none set, or one without memory): Windows fails the call
+ (D3DERR_INVALIDCALL); handed to Metal it crashed the driver */
+static uint32_t no_ib(res *ib) {
+ static int said; if (said++ < 5) fprintf(stderr, "d3d: indexed draw without an index buffer (%s) skipped\n", !ib ? "none set" : !ib->bk ? "no backing" : "no Metal buffer");
+ return D3DERR_INVALIDCALL;
+}
+static uint32_t draw_one(device *d, uint32_t prim, uint32_t count, int indexed, uint32_t base, uint32_t min_index, uint32_t num_verts,
+ uint32_t start, const void *up_vb, uint32_t up_stride, const void *up_ib, uint32_t up_ifmt);
uint32_t draw_common(device *d, uint32_t prim, uint32_t count, int indexed, uint32_t base, uint32_t min_index, uint32_t num_verts,
uint32_t start, const void *up_vb, uint32_t up_stride, const void *up_ib, uint32_t up_ifmt) {
+ double t0 = CACurrentMediaTime();
+ uint32_t r = draw_one(d, prim, count, indexed, base, min_index, num_verts, start, up_vb, up_stride, up_ib, up_ifmt);
+ d->t_draw += CACurrentMediaTime() - t0;
+ return r;
+}
+static uint32_t draw_one(device *d, uint32_t prim, uint32_t count, int indexed, uint32_t base, uint32_t min_index, uint32_t num_verts,
+ uint32_t start, const void *up_vb, uint32_t up_stride, const void *up_ib, uint32_t up_ifmt) {
(void)min_index; (void)num_verts;
if (!count || prim < 1 || prim > 6) return D3D_OK;
extern uint64_t pe2_frame_no(void);
@@ -398,7 +551,7 @@ uint32_t draw_common(device *d, uint32_t prim, uint32_t count, int indexed, uint
/* shader keys */
memset(k.vk.attr_slot, -1, sizeof k.vk.attr_slot);
int points = prim == 1;
- k.vk.points = k.pk.points = points;
+ k.vk.points = points; k.pk.points = points ? (d->s.rs[156] ? 2 : 1) : 0; /* D3DRS_POINTSPRITEENABLE */
int nrt = 0; for (int i = 0; i < 4; i++) if (d->rt[i]) { k.rtfmt[i] = (uint32_t)d->rt[i]->parent->tex.pixelFormat; nrt = i + 1; }
k.vk.num_rt = k.pk.num_rt = nrt;
res *dsr = d->ds && d->ds->w >= d->rt[0]->w && d->ds->h >= d->rt[0]->h ? d->ds : 0;
@@ -444,32 +597,46 @@ uint32_t draw_common(device *d, uint32_t prim, uint32_t count, int indexed, uint
k.blend[0] = rs[27]; k.blend[1] = rs[19]; k.blend[2] = rs[20]; k.blend[3] = rs[171]; k.blend[4] = rs[206];
k.blend[5] = rs[207]; k.blend[6] = rs[208]; k.blend[7] = rs[209];
k.blend[8] = (rs[168] & 0xf) | (rs[190] & 0xf) << 4 | (rs[191] & 0xf) << 8 | (rs[192] & 0xf) << 12;
- k.blend[9] = points;
+ k.blend[9] = k.pk.points; /* points, or point sprites: their pixel shaders differ */
+ /* only what the pipeline is made from counts: blend factors with blending off, and the strides and step rates of
+ streams the layout does not read, made a new pipeline (and a new compile) for the same one */
+ if (!k.blend[0]) for (int i = 1; i < 8; i++) k.blend[i] = 0;
+ else if (!k.blend[4]) for (int i = 5; i < 8; i++) k.blend[i] = 0;
+ { uint32_t used = 0; for (int x = 0; x < nel; x++) used |= 1u << (el[x].stream & 15);
+ for (int i = 0; i < 16; i++) if (!(used >> i & 1)) k.strides[i] = k.stepfn[i] = 0; }
@autoreleasepool {
begin_pass(d);
id p = pipeline(d, &k, el, nel, vs, ps);
if (trd) fprintf(stderr, "d3d: draw prim %u count %u fvf %#x vs %u ps %u pipeline %s rt %ux%u\n", prim, count, s->fvf, k.vs, k.ps, p ? "ok" : "NONE", d->rt[0] ? d->rt[0]->w : 0, d->rt[0] ? d->rt[0]->h : 0);
if (!p) return D3D_OK;
- id e = d->enc;
- [e setRenderPipelineState:p];
+ id e = d->enc; enc_cache *ec = &d->ec;
+ /* only what differs from the previous draw in this encoder is sent: under Rosetta every Metal call is translated
+ code, and C&C 3 makes 300-700 draws a frame */
+ if (ec->pipe != (void *)p) { [e setRenderPipelineState:p]; ec->pipe = (void *)p; }
static int nodepth = -1; if (nodepth < 0) nodepth = getenv("PE2_NODEPTH") != 0;
- [e setDepthStencilState:dsstate(d, dsr != 0 && !nodepth, dsr && dsr->fi->stencil && !nodepth)];
- [e setStencilReferenceValue:rs[57] & 0xff];
- float bc[4]; argb(rs[193], bc); [e setBlendColorRed:bc[0] green:bc[1] blue:bc[2] alpha:bc[3]];
- [e setFrontFacingWinding:MTLWindingClockwise];
- [e setCullMode:rs[22] == 2 ? MTLCullModeFront : rs[22] == 3 ? MTLCullModeBack : MTLCullModeNone];
- [e setTriangleFillMode:rs[8] == 2 ? MTLTriangleFillModeLines : MTLTriangleFillModeFill];
+ id dss = dsstate(d, dsr != 0 && !nodepth, dsr && dsr->fi->stencil && !nodepth);
+ if (ec->dss != (void *)dss) { [e setDepthStencilState:dss]; ec->dss = (void *)dss; }
+ uint32_t sref = (rs[57] & 0xff) | 0x100;
+ if (ec->stref != sref) { [e setStencilReferenceValue:rs[57] & 0xff]; ec->stref = sref; }
+ float bc[4]; argb(rs[193], bc);
+ if (memcmp(ec->bc, bc, 16) || !ec->vp_set) { [e setBlendColorRed:bc[0] green:bc[1] blue:bc[2] alpha:bc[3]]; memcpy(ec->bc, bc, 16); }
+ uint32_t cull = (rs[22] == 2 ? MTLCullModeFront : rs[22] == 3 ? MTLCullModeBack : MTLCullModeNone) + 1;
+ if (ec->cull != cull) { [e setCullMode:(MTLCullMode)(cull - 1)]; ec->cull = cull; }
+ uint32_t fill = (rs[8] == 2 ? MTLTriangleFillModeLines : MTLTriangleFillModeFill) + 1;
+ if (ec->fill != fill) { [e setTriangleFillMode:(MTLTriangleFillMode)(fill - 1)]; ec->fill = fill; }
/* D3DRS_CLIPPING off: D3D9 hardware still rasterizes geometry whose depth leaves [0,1]; Metal would clip it */
- [e setDepthClipMode:rs[136] ? MTLDepthClipModeClip : MTLDepthClipModeClamp];
+ uint32_t clipm = (rs[136] ? MTLDepthClipModeClip : MTLDepthClipModeClamp) + 1;
+ if (ec->clip != clipm) { [e setDepthClipMode:(MTLDepthClipMode)(clipm - 1)]; ec->clip = clipm; }
if (drawlog >= 0 && pe2_frame_no() == (uint64_t)drawlog) fprintf(stderr, "clip: rs136 %u\n", rs[136]);
- float bias = f_of(rs[195]), slope = f_of(rs[175]);
- [e setDepthBias:bias * (dsr && dsr->fi->mtl == MTLPixelFormatDepth16Unorm ? 65535.0f : 16777215.0f) slopeScale:slope clamp:0];
+ float bias[2] = {f_of(rs[195]) * (dsr && dsr->fi->mtl == MTLPixelFormatDepth16Unorm ? 65535.0f : 16777215.0f), f_of(rs[175])};
+ if (memcmp(ec->bias, bias, 8) || !ec->vp_set) { [e setDepthBias:bias[0] slopeScale:bias[1] clamp:0]; memcpy(ec->bias, bias, 8); }
uint32_t rtw = d->rt[0]->w, rth = d->rt[0]->h;
uint32_t vx = s->vp[0], vy = s->vp[1], vw = s->vp[2], vh = s->vp[3];
if (vx >= rtw) vx = 0; if (vy >= rth) vy = 0;
if (vx + vw > rtw) vw = rtw - vx; if (vy + vh > rth) vh = rth - vy;
if (!vw || !vh) return D3D_OK;
- [e setViewport:(MTLViewport){vx, vy, vw, vh, s->vpz[0], s->vpz[1]}];
+ MTLViewport mvp = {vx, vy, vw, vh, s->vpz[0], s->vpz[1]};
+ if (!ec->vp_set || memcmp(&ec->vp, &mvp, sizeof mvp)) { [e setViewport:mvp]; ec->vp = mvp; ec->vp_set = 1; }
MTLScissorRect sc = {0, 0, rtw, rth};
if (rs[174]) {
int32_t x0 = s->scissor[0] < 0 ? 0 : s->scissor[0], y0 = s->scissor[1] < 0 ? 0 : s->scissor[1];
@@ -477,7 +644,7 @@ uint32_t draw_common(device *d, uint32_t prim, uint32_t count, int indexed, uint
if (x1 <= x0 || y1 <= y0) return D3D_OK;
sc = (MTLScissorRect){(NSUInteger)x0, (NSUInteger)y0, (NSUInteger)(x1 - x0), (NSUInteger)(y1 - y0)};
}
- [e setScissorRect:sc];
+ if (!ec->sc_set || memcmp(&ec->sc, &sc, sizeof sc)) { [e setScissorRect:sc]; ec->sc = sc; ec->sc_set = 1; }
/* driver constants */
drv_t dv; memset(&dv, 0, sizeof dv);
dv.pixofs[0] = 1.0f / vw; dv.pixofs[1] = -1.0f / vh;
@@ -506,13 +673,23 @@ uint32_t draw_common(device *d, uint32_t prim, uint32_t count, int indexed, uint
dv.bumpmat[8 + i][0] = f_of(s->tss[i][22]); dv.bumpmat[8 + i][1] = f_of(s->tss[i][23]);
}
dv.ffmisc[0] = f_of(rs[154]); dv.ffmisc[1] = rs[29] ? 1.0f : 0.0f;
- [e setVertexBytes:&dv length:sizeof dv atIndex:3];
- [e setFragmentBytes:&dv length:sizeof dv atIndex:3];
- /* constants */
+ _Static_assert(sizeof dv <= sizeof ec->drv, "drv_t grew past the encoder cache");
+ if (ec->drv_n != sizeof dv || memcmp(ec->drv, &dv, sizeof dv)) {
+ [e setVertexBytes:&dv length:sizeof dv atIndex:3];
+ [e setFragmentBytes:&dv length:sizeof dv atIndex:3];
+ memcpy(ec->drv, &dv, sizeof dv); ec->drv_n = sizeof dv;
+ }
+ /* constants: a shader without relative reads gets the registers up to the highest it reads (its own def values
+ are literals in its code); one with them gets all. Sent again only after the program changed constants
+ (d->cgen) or a shader needs more of them. */
if (vs) {
- [e setVertexBytes:s->vsf length:sizeof s->vsf atIndex:0];
- [e setVertexBytes:s->vsi length:sizeof s->vsi atIndex:1];
- [e setVertexBytes:s->vsb length:sizeof s->vsb atIndex:2];
+ uint32_t n = vs->info.uses_rel_c || vs->info.max_const < 0 || vs->info.max_const >= 255 ? 256 : (uint32_t)vs->info.max_const + 1;
+ if (ec->vkind != 1 || ec->cgen_v != d->cgen || ec->vn < n) {
+ [e setVertexBytes:s->vsf length:16 * n atIndex:0];
+ [e setVertexBytes:s->vsi length:sizeof s->vsi atIndex:1];
+ [e setVertexBytes:s->vsb length:sizeof s->vsb atIndex:2];
+ ec->vkind = 1; ec->cgen_v = d->cgen; ec->vn = n;
+ }
} else {
float C[64][4]; memset(C, 0, sizeof C);
float wv[16], wvp[16]; mat_mul(s->xf[256], s->xf[2], wv); mat_mul(wv, s->xf[3], wvp);
@@ -521,13 +698,20 @@ uint32_t draw_common(device *d, uint32_t prim, uint32_t count, int indexed, uint
C[8][0] = s->vp[0]; C[8][1] = s->vp[1]; C[8][2] = s->vp[2]; C[8][3] = s->vp[3];
memcpy(C[10], s->material, 16); argb(rs[139], C[11]); argb(rs[60], C[12]);
for (int st = 0; st < 8; st++) { const float *m = s->xf[16 + st]; for (int j = 0; j < 4; j++) for (int i = 0; i < 4; i++) C[16 + 4 * st + j][i] = m[i * 4 + j]; }
- [e setVertexBytes:C length:sizeof C atIndex:0];
- [e setFragmentBytes:C length:sizeof C atIndex:0];
+ _Static_assert(sizeof C == sizeof ec->ffc, "fixed-function constants and their cache differ");
+ int same = ec->ffc_set && !memcmp(ec->ffc, C, sizeof C);
+ if (!same) memcpy(ec->ffc, C, sizeof C), ec->ffc_set = 1;
+ if (ec->vkind != 2 || !same) { [e setVertexBytes:C length:sizeof C atIndex:0]; ec->vkind = 2; }
+ if (!ps && (ec->fkind != 2 || !same)) { [e setFragmentBytes:C length:sizeof C atIndex:0]; ec->fkind = 2; }
}
if (ps) {
- [e setFragmentBytes:s->psf length:sizeof s->psf atIndex:0];
- [e setFragmentBytes:s->psi length:sizeof s->psi atIndex:1];
- [e setFragmentBytes:s->psb length:sizeof s->psb atIndex:2];
+ uint32_t n = ps->info.uses_rel_c || ps->info.max_const < 0 || ps->info.max_const >= 223 ? 224 : (uint32_t)ps->info.max_const + 1;
+ if (ec->fkind != 1 || ec->cgen_f != d->cgen || ec->fn < n) {
+ [e setFragmentBytes:s->psf length:16 * n atIndex:0];
+ [e setFragmentBytes:s->psi length:sizeof s->psi atIndex:1];
+ [e setFragmentBytes:s->psb length:sizeof s->psb atIndex:2];
+ ec->fkind = 1; ec->cgen_f = d->cgen; ec->fn = n;
+ }
}
/* textures and samplers */
uint32_t want = ps ? ps->info.samp_used : 0;
@@ -542,41 +726,55 @@ uint32_t draw_common(device *d, uint32_t prim, uint32_t count, int indexed, uint
else tx = (k.pk.depth_mask >> i & 1) ? g_dummy[1] : !ps && !t && kind == 2 ? g_white : g_dummy[kind];
if (!(t && tk == kind) && drawlog >= 0 && pe2_frame_no() == (uint64_t)drawlog)
fprintf(stderr, "texmiss: ps %u(%d.%d) s%d wants kind %d, bound %s kind %d fmt %#x\n", ps ? ps->sh_id : 0, ps ? ps->info.major : 0, ps ? ps->info.minor : 0, i, kind, t ? "tex" : "nothing", tk, t ? t->fmt : 0);
- [e setFragmentTexture:tx atIndex:i];
- if (k.pk.depth_mask >> i & 1) [e setFragmentSamplerState:g_cmp_sampler atIndex:i];
- else [e setFragmentSamplerState:sampler(d, s->samp[i], t ? t->levels : 1) atIndex:i];
+ if (t && tk == kind) gpu_use(d, t);
+ if (ec->ftex[i] != (void *)tx) { [e setFragmentTexture:tx atIndex:i]; ec->ftex[i] = (void *)tx; }
+ id sm = (k.pk.depth_mask >> i & 1) ? g_cmp_sampler : sampler(d, s->samp[i], t ? t->levels : 1);
+ if (ec->fsmp[i] != (void *)sm) { [e setFragmentSamplerState:sm atIndex:i]; ec->fsmp[i] = (void *)sm; }
}
if (vs) for (int i = 0; i < 4; i++) if (vs->info.samp_used >> i & 1) {
- res *t = R(s->tex[16 + i]);
- [e setVertexTexture:t && t->kind == K_TEX ? t->view : g_dummy[2] atIndex:i];
- [e setVertexSamplerState:sampler(d, s->samp[16 + i], t ? t->levels : 1) atIndex:i];
+ res *t = R(s->tex[16 + i]); gpu_use(d, t);
+ id tx = t && t->kind == K_TEX ? t->view : g_dummy[2];
+ if (ec->vtex[i] != (void *)tx) { [e setVertexTexture:tx atIndex:i]; ec->vtex[i] = (void *)tx; }
+ id sm = sampler(d, s->samp[16 + i], t ? t->levels : 1);
+ if (ec->vsmp[i] != (void *)sm) { [e setVertexSamplerState:sm atIndex:i]; ec->vsmp[i] = (void *)sm; }
}
static const float def_attr[4] = {0, 0, 0, 1}; /* D3D reads (0,0,0,1) for inputs a layout lacks */
- [e setVertexBytes:def_attr length:16 atIndex:ATTR_DEFAULT_BUFFER];
+ if (!ec->def_set) { [e setVertexBytes:def_attr length:16 atIndex:ATTR_DEFAULT_BUFFER]; ec->def_set = 1; }
/* vertex streams */
uint32_t nv = vcount(prim, count);
if (up_vb) {
uint32_t span = indexed ? (min_index + num_verts) * up_stride : nv * up_stride;
void *dst; id rb; uint32_t off = ring_alloc(d, span ? span : 4, 16, &dst, &rb);
memcpy(dst, up_vb, span);
- [e setVertexBuffer:rb offset:off atIndex:16];
+ if (ec->vb[0] != (void *)rb) { [e setVertexBuffer:rb offset:off atIndex:16]; ec->vb[0] = (void *)rb; ec->vboff[0] = off; }
+ else if (ec->vboff[0] != off) { [e setVertexBufferOffset:off atIndex:16]; ec->vboff[0] = off; }
} else {
for (int i = 0; i < 16; i++) {
int used = 0; for (int x = 0; x < nel; x++) if (el[x].stream == i) used = 1;
if (!used) continue;
res *b = R(s->stream[i]);
- if (!b) { [e setVertexBuffer:g_dev->ring[0] offset:0 atIndex:16 + i]; continue; }
- b->bk->last_use = d->submit;
- [e setVertexBuffer:b->bk->buf offset:s->stream_off[i] atIndex:16 + i];
+ id vbuf = b && b->bk ? b->bk->buf : g_dev->ring[0]; /* none, or released and freed: a harmless buffer */
+ uint32_t vo = b && b->bk ? s->stream_off[i] : 0;
+ if (b && b->bk) b->bk->last_use = d->submit;
+ if (ec->vb[i] != (void *)vbuf) { [e setVertexBuffer:vbuf offset:vo atIndex:16 + i]; ec->vb[i] = (void *)vbuf; ec->vboff[i] = vo; }
+ else if (ec->vboff[i] != vo) { [e setVertexBufferOffset:vo atIndex:16 + i]; ec->vboff[i] = vo; }
}
}
d->draws++;
+ /* PE2_SKIP_SHADER=vs_,ps_,...: drop draws that use one of those shaders (diagnostic: which effect
+ makes an artifact; the names are the draw log's vsname/psname) */
+ { static const char *sk = (const char *)-1; if (sk == (const char *)-1) sk = getenv("PE2_SKIP_SHADER");
+ if (sk) { char nm[24]; if (vs) { snprintf(nm, sizeof nm, "vs_%016llx", fnv64(vs->code, 4 * vs->ncode)); if (strstr(sk, nm)) return D3D_OK; }
+ if (ps) { snprintf(nm, sizeof nm, "ps_%016llx", fnv64(ps->code, 4 * ps->ncode)); if (strstr(sk, nm)) return D3D_OK; } } }
/* PE2_SKIP_TEX=WxH: drop draws whose texture 0 has that size (diagnostic: which draws make an artifact) */
- if (getenv("PE2_SKIP_TEX") && R(s->tex[0])) { char sz[32]; snprintf(sz, sizeof sz, "%ux%u", R(s->tex[0])->w, R(s->tex[0])->h); if (!strcmp(sz, getenv("PE2_SKIP_TEX"))) return D3D_OK; }
+ static const char *skip_tex = (const char *)-1, *log_tex = (const char *)-1;
+ if (skip_tex == (const char *)-1) { skip_tex = getenv("PE2_SKIP_TEX"); log_tex = getenv("PE2_DRAWLOG_TEX"); }
+ if (skip_tex && R(s->tex[0])) { char sz[32]; snprintf(sz, sizeof sz, "%ux%u", R(s->tex[0])->w, R(s->tex[0])->h); if (!strcmp(sz, skip_tex)) return D3D_OK; }
/* PE2_DRAWLOG_TEX=WxH: log the first 3 draws whose texture 0 has that size, whatever the frame */
static int texlog_left = 3; int texlog = 0;
- if (getenv("PE2_DRAWLOG_TEX") && texlog_left > 0 && R(s->tex[0])) { char sz[32]; snprintf(sz, sizeof sz, "%ux%u", R(s->tex[0])->w, R(s->tex[0])->h); if (!strcmp(sz, getenv("PE2_DRAWLOG_TEX"))) { texlog = 1; texlog_left--; } }
- if (texlog || (drawlog >= 0 && pe2_frame_no() == (uint64_t)drawlog)) {
+ if (log_tex && texlog_left > 0 && R(s->tex[0])) { char sz[32]; snprintf(sz, sizeof sz, "%ux%u", R(s->tex[0])->w, R(s->tex[0])->h); if (!strcmp(sz, log_tex)) { texlog = 1; texlog_left--; } }
+ extern uint64_t pe2_drawlog_until;
+ if (texlog || (drawlog >= 0 && pe2_frame_no() == (uint64_t)drawlog) || pe2_frame_no() < pe2_drawlog_until) {
fprintf(stderr, "draw %llu: vs %u ps %u(%d.%d) prim %u n %u idx %d up %d | rt0 %ux%u fmt %#x ds %s | blend %u %u/%u zen %u zw %u zf %u cull %u at %u/%u fog %u | vp %u,%u %ux%u | tex",
d->draws, k.vs, k.ps, ps ? ps->info.major : 0, ps ? ps->info.minor : 0, prim, count, indexed, up_vb != 0,
d->rt[0]->w, d->rt[0]->h, d->rt[0]->fmt, dsr ? "yes" : "no", rs[27], rs[19], rs[20], rs[7], rs[14], rs[23], rs[22], rs[15], rs[24], rs[28],
@@ -592,10 +790,10 @@ uint32_t draw_common(device *d, uint32_t prim, uint32_t count, int indexed, uint
fprintf(stderr, " | sc %u [%d,%d,%d,%d] cwm %#x srgb %u", rs[174], s->scissor[0], s->scissor[1], s->scissor[2], s->scissor[3], rs[168], rs[194]);
fprintf(stderr, " | c4 %.3g %.3g %.3g %.3g", s->vsf[4][0], s->vsf[4][1], s->vsf[4][2], s->vsf[4][3]);
for (int ci = 5; ci <= 10; ci++) fprintf(stderr, " c%d %.3g %.3g %.3g %.3g", ci, s->vsf[ci][0], s->vsf[ci][1], s->vsf[ci][2], s->vsf[ci][3]);
- { res *vb0 = R(s->stream[0]); if (vb0 && !up_vb && s->stream_stride[0] == 16) { int16_t *sh = (int16_t *)(vb0->bk->mem + s->stream_off[0] + base * 16); uint8_t *ub = (uint8_t *)sh; fprintf(stderr, " | raw %d %d %d %d col %02x%02x%02x%02x tc %d %d", sh[0], sh[1], sh[2], sh[3], ub[8], ub[9], ub[10], ub[11], sh[6], sh[7]); } }
+ { res *vb0 = R(s->stream[0]); if (vb0 && vb0->bk && !up_vb && s->stream_stride[0] == 16) { int16_t *sh = (int16_t *)(vb0->bk->mem + s->stream_off[0] + base * 16); uint8_t *ub = (uint8_t *)sh; fprintf(stderr, " | raw %d %d %d %d col %02x%02x%02x%02x tc %d %d", sh[0], sh[1], sh[2], sh[3], ub[8], ub[9], ub[10], ub[11], sh[6], sh[7]); } }
/* first vertex of stream 0 as floats, and the declaration */
res *vb = R(s->stream[0]);
- if (vb && !up_vb) { float *v = (float *)(vb->bk->mem + s->stream_off[0] + (indexed ? base : base) * s->stream_stride[0]); fprintf(stderr, " | v0 %.4g %.4g %.4g %.4g stride %u", v[0], v[1], v[2], v[3], s->stream_stride[0]); }
+ if (vb && vb->bk && !up_vb) { float *v = (float *)(vb->bk->mem + s->stream_off[0] + (indexed ? base : base) * s->stream_stride[0]); fprintf(stderr, " | v0 %.4g %.4g %.4g %.4g stride %u", v[0], v[1], v[2], v[3], s->stream_stride[0]); }
for (int x = 0; x < nel; x++) fprintf(stderr, " [s%u o%u t%u u%u.%u]", el[x].stream, el[x].offset, el[x].type, el[x].usage, el[x].index);
fprintf(stderr, "\n");
}
@@ -606,7 +804,7 @@ uint32_t draw_common(device *d, uint32_t prim, uint32_t count, int indexed, uint
const uint8_t *src = 0; int i16 = 1;
if (indexed) {
if (up_ib) { src = up_ib; i16 = up_ifmt == 101; }
- else { res *ib = R(s->indices); if (!ib) return D3D_OK; src = ib->bk->mem; i16 = ib->fmt == 101; src += start * (i16 ? 2 : 4); }
+ else { res *ib = R(s->indices); if (!ib || !ib->bk || !ib->bk->mem) return no_ib(ib); src = ib->bk->mem; i16 = ib->fmt == 101; src += start * (i16 ? 2 : 4); }
}
for (uint32_t t = 0; t < tris; t++) {
uint32_t v[3] = {0, t + 1, t + 2};
@@ -627,11 +825,12 @@ uint32_t draw_common(device *d, uint32_t prim, uint32_t count, int indexed, uint
if (up_ib) {
i16 = up_ifmt == 101; void *dst; ioff = ring_alloc(d, nv * (i16 ? 2 : 4), 4, &dst, &ibuf); memcpy(dst, up_ib, nv * (i16 ? 2 : 4));
} else {
- res *ib = R(s->indices); if (!ib) return D3D_OK;
+ res *ib = R(s->indices); if (!ib || !ib->bk || !ib->bk->buf) return no_ib(ib);
i16 = ib->fmt == 101; ib->bk->last_use = d->submit;
ibuf = ib->bk->buf; ioff = start * (i16 ? 2 : 4);
if (ioff & 3) { void *dst; ioff = ring_alloc(d, nv * 2, 4, &dst, &ibuf); memcpy(dst, ib->bk->mem + start * 2, nv * 2); }
}
+ if (!ibuf) return no_ib(0);
[e drawIndexedPrimitives:mp indexCount:nv indexType:i16 ? MTLIndexTypeUInt16 : MTLIndexTypeUInt32 indexBuffer:ibuf indexBufferOffset:ioff
instanceCount:inst baseVertex:up_ib ? 0 : base baseInstance:0];
}
diff --git a/runtime/d3d9_priv.h b/runtime/d3d9_priv.h
index f730d89..c537e6d 100644
--- a/runtime/d3d9_priv.h
+++ b/runtime/d3d9_priv.h
@@ -27,12 +27,15 @@ struct res {
uint32_t *sub_obj;
uint8_t **shadow; uint32_t *pitch, *slice;
uint8_t gpu_dirty;
+ uint8_t dead; /* released by the program, waiting to be freed (d3d9_device.m free_pending) */
res *parent; uint32_t level, face;
uint32_t size, fvf; backing *bk; uint32_t locked_off;
+ int32_t lk_rect[4]; uint32_t lk_sub; uint8_t lk_part; /* the rectangle the open LockRect named, if it named one */
uint32_t *elems; uint32_t nelem; uint32_t decl_id;
uint32_t *code; uint32_t ncode; shader_info_t info; uint32_t sh_id;
uint32_t qtype; uint64_t qsubmit; uint32_t qissued;
void *sb;
+ uint64_t use_seq; /* the command buffer (device submit id) that last used it on the GPU */
};
static inline res *R(uint32_t obj) { if (!obj) return 0; uint64_t p; memcpy(&p, (uint32_t *)P(obj) + CO_RES, 8); return (res *)(uintptr_t)p; }
@@ -73,10 +76,16 @@ static inline void pp_out(uint32_t *d, const uint32_t *s, gp hwnd) {
memcpy(d, s, 56); (void)hwnd;
#endif
}
+/* what the open render encoder was last given, so a draw sends only what changed (reset with each new encoder) */
+typedef struct {
+ void *pipe, *dss, *vb[16], *vtex[4], *vsmp[4], *ftex[16], *fsmp[16];
+ uint32_t vboff[16], stref, cull, fill, clip, vp_set, sc_set, def_set, cgen_v, cgen_f, vn, fn, vkind, fkind;
+ float bc[4], bias[2]; MTLViewport vp; MTLScissorRect sc; uint8_t drv[1024], ffc[1024]; uint32_t drv_n, ffc_set;
+} enc_cache;
typedef struct {
uint32_t obj;
id dev; id q; CAMetalLayer *layer;
- id cmd; id enc;
+ id cmd; id enc; id blit;
uint64_t submit; _Atomic uint64_t done; dispatch_semaphore_t inflight;
dstate s; sblock *rec;
uint32_t pp[14]; gp hwnd;
@@ -89,13 +98,22 @@ typedef struct {
backing *free_bk;
uint32_t swap;
uint64_t draws;
+ /* texture uploads for textures the open command buffer has not used yet: a command buffer of their own, committed
+ just before it, so an upload between two draws does not end the render pass (see upload_sub_rect) */
+ id upcmd; id upblit;
+ uint64_t n_pass, n_break, n_preup, n_wait, n_pipe, n_warm_hit; double t_wait, t_sem, t_pipe, t_up, t_draw;
+ uint32_t cgen; /* bumped whenever shader constants may change */
+ enc_cache ec; /* render passes, passes ended by an upload, uploads moved ahead (stats) */
} device;
+static inline void gpu_use(device *d, res *t) { if (t) t->use_seq = d->submit; }
extern device *g_dev;
void cmd_begin(device *d);
void enc_end(device *d);
+uint32_t ring_alloc(device *d, uint32_t size, uint32_t align, void **ptr, id *buf);
void cmd_commit(device *d, int wait);
void begin_pass(device *d);
+void d3d_warm_pipelines(device *d);
res *res_new(int kind);
float f_of(uint32_t u);
uint32_t u_of(float f);
diff --git a/runtime/d3d9_shader.c b/runtime/d3d9_shader.c
index d834f4e..6fe7760 100644
--- a/runtime/d3d9_shader.c
+++ b/runtime/d3d9_shader.c
@@ -203,7 +203,11 @@ static void reg_name(gen *g, char *o, size_t cap, uint32_t tok, int is_dst, cons
case R_TEMP: case R_TEMPF16: snprintf(o, cap, "r%d", n); break;
case R_INPUT:
if (p->ps) {
- if (p->major >= 3 && pr && pr->has_rel) { snprintf(o, cap, "vin_rel_unsupported"); break; }
+ if (p->major >= 3 && pr && pr->has_rel) { /* v[aL + n]: the inputs as an array (VIN, made in the prologue) */
+ int rt = regtype(pr->rel), comp = (pr->rel >> 16) & 3;
+ const char *idx = rt == R_LOOP ? "aL" : comp == 0 ? "a0.x" : comp == 1 ? "a0.y" : comp == 2 ? "a0.z" : "a0.w";
+ snprintf(o, cap, "VIN[clamp(int(%s) + %d, 0, 15)]", idx, n); break;
+ }
snprintf(o, cap, "v%d", n);
} else snprintf(o, cap, "v%d", n);
break;
@@ -215,7 +219,8 @@ static void reg_name(gen *g, char *o, size_t cap, uint32_t tok, int is_dst, cons
int rt = regtype(pr->rel), comp = (pr->rel >> 16) & 3;
idx = rt == R_LOOP ? "aL" : comp == 0 ? "a0.x" : comp == 1 ? "a0.y" : comp == 2 ? "a0.z" : "a0.w";
}
- snprintf(o, cap, "C[clamp(%s + %d, 0, 255)]", idx, base);
+ if (base < 256) snprintf(o, cap, "d3d_crel(C, %s + %d)", idx, base);
+ else snprintf(o, cap, "C[clamp(%s + %d, 0, 255)]", idx, base);
} else if (base < 256 && p->defc_set[base]) snprintf(o, cap, "D%d", base);
else snprintf(o, cap, "C[%d]", base);
break;
@@ -599,9 +604,23 @@ int attr_slot_for(int usage, int index) {
default: return -1;
}
}
+/* Relative constant reads (c[a0.x + n]) as D3D9 makes them: a register the shader defines itself (def) reads that value,
+ as the hardware loads defined constants into the same register file the index reaches; any other register in range
+ reads the program's constant; an index outside the file reads 0, as on the hardware (and in Wine and DXVK). Clamping
+ the index into C[] instead made C&C 3's particles take their quad corners (defined in the shader at c21..c24 and
+ reached as c[a0.w + 16]) from whatever the game had last set there: a refinery's dust became beams and sheets
+ across the whole view. */
+static void gen_crel(sb *b, const prog *p) {
+ if (!p->uses_rel_c) return;
+ sbf(b, "static inline float4 d3d_crel(constant float4 *C, int i) {\n switch (i) {\n");
+ for (int i = 0; i < 256; i++) if (p->defc_set[i])
+ sbf(b, " case %d: return float4(%.9g, %.9g, %.9g, %.9g);\n", i, p->defc[i][0], p->defc[i][1], p->defc[i][2], p->defc[i][3]);
+ sbf(b, " default: return uint(i) < %uu ? C[i] : float4(0.0);\n }\n}\n", p->ps ? 224u : 256u);
+}
static char *gen_vs(prog *p, const shader_key *key, const vlink *pslink) {
sb b = {0}; gen g = {p, &b, key, 0, ""};
sbf(&b, "%s", PRELUDE);
+ gen_crel(&b, p);
vout outs[32]; int nout = vs_outputs(p, outs);
/* the varying struct carries everything the vs writes and everything the paired ps reads */
vout all[48]; int nall = 0;
@@ -662,7 +681,12 @@ static char *gen_vs(prog *p, const shader_key *key, const vlink *pslink) {
else sbf(&b, " out.%s = float4(0.0);\n", vn);
}
sbf(&b, " out.fog = oFog;\n");
- if (key->points) sbf(&b, " out.psize = %s;\n", p->writes_pts || p->major >= 3 ? "max(drv.ffmisc.x, 1.0)" : "max(drv.ffmisc.x, 1.0)");
+ if (key->points) { /* the size the shader writes (oPts, or a vs_3_0 output declared PSIZE), else D3DRS_POINTSIZE */
+ char ps[32] = "drv.ffmisc.x";
+ if (p->major >= 3) { for (int i = 0; i < 16; i++) if (p->vout[i].used && p->vout[i].usage == 4) { snprintf(ps, sizeof ps, "o%d.x", i); break; } }
+ else if (p->writes_pts) snprintf(ps, sizeof ps, "oPts");
+ sbf(&b, " out.psize = max(%s, 1.0);\n", ps);
+ }
sbf(&b, " for (int i = 0; i < 6; i++) out.clip[i] = (drv.misc.x >> i) & 1 ? dot(oPos, drv.clip[i]) : 1.0;\n");
/* D3D9 pixel centers sit half a pixel off GL/Metal ones */
sbf(&b, " oPos.xy += drv.pixofs.xy * oPos.w;\n out.pos = oPos;\n return out;\n}\n");
@@ -673,6 +697,7 @@ static char *gen_vs(prog *p, const shader_key *key, const vlink *pslink) {
static char *gen_ps(prog *p, const shader_key *key) {
sb b = {0}; gen g = {p, &b, key, 0, ""};
sbf(&b, "%s", PRELUDE);
+ gen_crel(&b, p);
sbf(&b, "struct PSIn {\n float4 pos [[position]];\n");
int ninp = 0;
if (p->major >= 3) {
@@ -693,6 +718,11 @@ static char *gen_ps(prog *p, const shader_key *key) {
sbf(&b, "};\n");
sbf(&b, "fragment PSOut %s(PSIn in [[stage_in]], constant float4 *C [[buffer(0)]], constant int4 *I [[buffer(1)]], constant uint *B [[buffer(2)]], constant Drv &drv [[buffer(3)]], bool vFaceB [[front_facing]]",
key->fname[0] ? key->fname : "ps_main");
+ /* point sprites: texture coordinate set 0 is the position across the sprite, 0 to 1 (as Direct3D 9 does); without
+ it each sprite sampled one texel and drew a flat square (smoke, gas, sparks). Other sets keep what the vertex
+ shader wrote (a particle's screen position for a soft fade, its colour ramp) */
+ int sprite = key->points == 2;
+ if (sprite) sbf(&b, ", float2 pc [[point_coord]]");
for (int s = 0; s < 16; s++) if (p->samp_used >> s & 1) {
int ty = p->samp_type[s] ? p->samp_type[s] : key->samp_kind[s] ? key->samp_kind[s] : 2;
if ((key->depth_mask >> s & 1) && ty == 2) sbf(&b, ", depth2d s%d [[texture(%d)]], sampler ss%d [[sampler(%d)]]", s, s, s, s);
@@ -702,11 +732,21 @@ static char *gen_ps(prog *p, const shader_key *key) {
declare_temps(&g);
sbf(&b, " float4 vPos = float4(in.pos.xy, 0.0, 0.0); float4 vFace = float4(vFaceB ? 1.0 : -1.0); (void)vPos; (void)vFace;\n");
sbf(&b, " float tm[3] = {0.0, 0.0, 0.0}; (void)tm;\n");
- if (p->major >= 3) { for (int i = 0; i < 16; i++) if (p->pin[i].used) sbf(&b, " float4 v%d = in.v%d;\n", i, i); }
+ if (p->major >= 3) {
+ for (int i = 0; i < 16; i++) if (p->pin[i].used) {
+ if (sprite && p->pin[i].usage == 5 && p->pin[i].index == 0) sbf(&b, " float4 v%d = float4(pc, 0.0, 1.0);\n", i); /* TEXCOORD0 */
+ else sbf(&b, " float4 v%d = in.v%d;\n", i, i);
+ }
+ /* a shader that indexes its inputs (v[aL + n]) reads them from an array; inputs it does not declare are 0 */
+ int rel = 0;
+ for (int k = 0; k < p->nins && !rel; k++) for (int j = 0; j < p->ins[k].nsrc; j++)
+ if (regtype(p->ins[k].src[j].tok) == R_INPUT && p->ins[k].src[j].has_rel) { rel = 1; break; }
+ if (rel) { sbf(&b, " float4 VIN[16] = {"); for (int i = 0; i < 16; i++) { if (p->pin[i].used) sbf(&b, "%sv%d", i ? ", " : "", i); else sbf(&b, "%sfloat4(0.0)", i ? ", " : ""); } sbf(&b, "};\n"); }
+ }
else {
for (int i = 0; i < 2; i++) sbf(&b, " float4 v%d = %s;\n", i, p->pin[i].used ? (i ? "saturate(in.v1)" : "saturate(in.v0)") : "float4(0.0)");
for (int i = 0; i < 8; i++) {
- if (p->tex_used_ps1 >> i & 1) sbf(&b, " float4 tc%d = in.tc%d;\n", i, i);
+ if (p->tex_used_ps1 >> i & 1) sbf(&b, sprite && i == 0 ? " float4 tc%d = float4(pc, 0.0, 1.0);\n" : " float4 tc%d = in.tc%d;\n", i, i);
else sbf(&b, " float4 tc%d = float4(0.0);\n", i);
/* ps2.x reads texcoords as t#; ps1.x t# registers start as the coordinates, then hold sample results */
sbf(&b, " float4 t%d = tc%d;\n", i, i);
@@ -756,7 +796,7 @@ int shader_info(const uint32_t *tok, size_t ntok, shader_info_t *info, char *err
for (int i = 0; i < 8; i++) if (p.tex_used_ps1 >> i & 1) { info->link.usage[info->link.n] = 5; info->link.index[info->link.n++] = i; }
}
}
- info->max_const = p.max_const;
+ info->max_const = p.max_const; info->uses_rel_c = p.uses_rel_c;
free(p.ins);
return 0;
}
diff --git a/runtime/d3d9_shader.h b/runtime/d3d9_shader.h
index 9e6fcd0..01e844b 100644
--- a/runtime/d3d9_shader.h
+++ b/runtime/d3d9_shader.h
@@ -9,7 +9,7 @@ typedef struct {
uint16_t depth_mask; /* samplers bound to depth textures (shadow compare) */
uint16_t proj_mask; /* ps1.x: D3DTTFF_PROJECTED per stage */
uint8_t num_rt; /* fixed-function only; shader outputs follow the shader's own oC# writes */
- uint8_t points; /* drawing a point list */
+ uint8_t points; /* drawing a point list: 1 points, 2 point sprites (D3DRS_POINTSPRITEENABLE) */
char fname[32]; /* entry point (default vs_main / ps_main); the precompiled library uses vs_ */
} shader_key;
/* Fixed Metal vertex attribute slot for a declaration usage/index, so a vertex shader compiles once for every
@@ -22,7 +22,7 @@ typedef struct {
uint8_t vin_used[16], vin_usage[16], vin_index[16];
uint32_t samp_used; uint8_t samp_type[16];
vlink link; /* ps: the varyings it reads */
- int max_const;
+ int max_const, uses_rel_c; /* highest constant register read, and whether any read is relative (c[a0 + n]) */
} shader_info_t;
int shader_info(const uint32_t *tok, size_t ntok, shader_info_t *info, char *err, size_t errcap);
char *shader_to_msl(const uint32_t *tok, size_t ntok, const shader_key *key, const vlink *pslink, char *err, size_t errcap);
diff --git a/runtime/dxdiag.c b/runtime/dxdiag.c
index b8bffed..85e7c60 100644
--- a/runtime/dxdiag.c
+++ b/runtime/dxdiag.c
@@ -42,8 +42,8 @@ COM(IDxDiagContainer, GetProp, 3) {
else if (!strcmp(n, "szDirectXVersionLetter")) { *(uint16_t *)v = 8; *(uint32_t *)(v + 8) = bstr("c"); }
else if (!strcmp(n, "szDirectXVersionEnglish")) { *(uint16_t *)v = 8; *(uint32_t *)(v + 8) = bstr("4.09.0000.0904"); }
else if (!strcmp(n, "bIsD3DDebugRuntime")) { *(uint16_t *)v = 11; }
- else if (!strcmp(n, "szDisplayMemoryEnglish")) { *(uint16_t *)v = 8; *(uint32_t *)(v + 8) = bstr("256.0 MB"); }
- else if (!strcmp(n, "szDescription")) { *(uint16_t *)v = 8; *(uint32_t *)(v + 8) = bstr("NVIDIA GeForce 7800 GTX"); }
+ else if (!strcmp(n, "szDisplayMemoryEnglish")) { *(uint16_t *)v = 8; *(uint32_t *)(v + 8) = bstr("768.0 MB"); }
+ else if (!strcmp(n, "szDescription")) { *(uint16_t *)v = 8; *(uint32_t *)(v + 8) = bstr("NVIDIA GeForce 8800 GTX"); }
else r = 0x80070057;
if (getenv("PE2_TRACE")) fprintf(stderr, "pe2: DxDiag prop %s -> %s\n", n, r ? "missing" : "ok");
free(n); return r;
diff --git a/runtime/k32_core.c b/runtime/k32_core.c
index e6bde1b..08c3a71 100644
--- a/runtime/k32_core.c
+++ b/runtime/k32_core.c
@@ -77,7 +77,7 @@ NATIVE(kernel32, VirtualFree, 3) {
}
pthread_mutex_unlock(&g_vl);
uint32_t s = a[0] & ~0xfffu, n = (a[1] + (a[0] & 0xfff) + 0xfff) & ~0xfffu; /* MEM_DECOMMIT: zero it */
- mmap(P(s), n, PROT_READ | PROT_WRITE, MAP_FIXED | MAP_ANON | MAP_PRIVATE, -1, 0);
+ pages_zero(s, n);
return 1;
}
NATIVE(kernel32, VirtualProtect, 4) { if (a[3]) *(uint32_t *)P(a[3]) = 4; return 1; }
@@ -302,9 +302,10 @@ NATIVE(kernel32, GetCurrentThread, 0) { return 0xfffffffe; }
NATIVE(kernel32, GetCurrentThreadId, 0) { return *teb32(TEB_TID); }
NATIVE(kernel32, GetCurrentProcess, 0) { return 0xffffffff; }
NATIVE(kernel32, GetCurrentProcessId, 0) { return (uint32_t)getpid(); }
-NATIVE(kernel32, Sleep, 1) { if (a[0] == 0) sched_yield(); else usleep(a[0] * 1000); return 0; }
-NATIVE(kernel32, SleepEx, 2) { if (a[0] == 0) sched_yield(); else usleep(a[0] * 1000); return 0; }
-NATIVE(kernel32, SwitchToThread, 0) { sched_yield(); return 1; }
+extern int pe2_prof_on; void pe2_prof_spin(uint32_t ret); /* prof.c: who yields (a[-1] is the caller's return address) */
+NATIVE(kernel32, Sleep, 1) { if (a[0] == 0) { if (pe2_prof_on) pe2_prof_spin(a[-1]); sched_yield(); } else usleep(a[0] * 1000); return 0; }
+NATIVE(kernel32, SleepEx, 2) { if (a[0] == 0) { if (pe2_prof_on) pe2_prof_spin(a[-1]); sched_yield(); } else usleep(a[0] * 1000); return 0; }
+NATIVE(kernel32, SwitchToThread, 0) { if (pe2_prof_on) pe2_prof_spin(a[-1]); sched_yield(); return 1; }
NATIVE(kernel32, DuplicateHandle, 7) {
uint32_t src = a[1];
if (src == 0xfffffffe) { wobj *o = calloc(1, sizeof *o); o->teb = pe2_teb; o->exitcode = 259; src = h_new(H_THREAD, o); }
@@ -416,16 +417,30 @@ static uint32_t modfilename(uint32_t h, char *out, uint32_t cap) {
const char *n = pe2_module_name(h ? h : pe2_exe_base);
if (!n) { set_last_error(126); return 0; }
char tmp[300]; int k = snprintf(tmp, sizeof tmp, "%s\\%s", pe2_gamedir_win, n);
- if (strcasecmp(n + strlen(n) - 4, ".exe") && strcasecmp(n + strlen(n) - 4, ".dll")) k = snprintf(tmp, sizeof tmp, "C:\\WINDOWS\\system32\\%s", n);
+ if ((h ? h : pe2_exe_base) == pe2_exe_base) k = snprintf(tmp, sizeof tmp, "%s", pe2_program_path_win()); /* any extension (cnc3game.dat) */
+ else if (strcasecmp(n + strlen(n) - 4, ".exe") && strcasecmp(n + strlen(n) - 4, ".dll")) k = snprintf(tmp, sizeof tmp, "C:\\WINDOWS\\system32\\%s", n);
if (!cap) return 0;
snprintf(out, cap, "%s", tmp);
return (uint32_t)k < cap ? (uint32_t)k : cap;
}
NATIVE(kernel32, GetModuleFileNameA, 3) { return modfilename(a[0], P(a[1]), a[2]); }
NATIVE(kernel32, GetModuleFileNameW, 3) { char t[300]; uint32_t n = modfilename(a[0], t, sizeof t); if (!n) return 0; return u2w(t, P(a[1]), a[2]); }
+/* a message about a name is written its first 3 times: C&C 3 asks for d3d9.dll and its DebugSetMute (absent, as in
+ Windows' release runtime) a dozen times a second for its whole run, and wrote two lines each time, even untraced */
+static int first_times(const char *a, const char *b) {
+ static uint64_t seen[256]; static uint8_t cnt[256]; static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
+ uint64_t h = 0xcbf29ce484222325ull; for (const char *s = a; s && *s; s++) h = (h ^ (uint8_t)(*s | 0x20)) * 0x100000001b3ull;
+ h = (h ^ 0xff) * 0x100000001b3ull; for (const char *s = b; s && *s; s++) h = (h ^ (uint8_t)*s) * 0x100000001b3ull;
+ pthread_mutex_lock(&m); int r = 1;
+ for (int i = 0, j = (int)(h & 255); i < 256; i++, j = (j + 1) & 255) {
+ if (seen[j] == h) { r = cnt[j] < 3; if (r) cnt[j]++; break; }
+ if (!seen[j]) { seen[j] = h; cnt[j] = 1; break; }
+ }
+ pthread_mutex_unlock(&m); return r;
+}
NATIVE(kernel32, LoadLibraryA, 1) {
uint32_t h = pe2_load_library(P(a[0]));
- if (trace() || !h) fprintf(stderr, "pe2: LoadLibrary(%s) = %#x\n", (char *)P(a[0]), h);
+ if ((trace() || !h) && first_times(P(a[0]), 0)) fprintf(stderr, "pe2: LoadLibrary(%s) = %#x\n", (char *)P(a[0]), h);
if (!h) set_last_error(126);
return h;
}
@@ -436,7 +451,8 @@ NATIVE(kernel32, DisableThreadLibraryCalls, 1) { return 1; }
NATIVE(kernel32, GetProcAddress, 2) {
uint32_t r = a[1] >> 16 ? pe2_get_proc(a[0], P(a[1]), 0) : pe2_get_proc(a[0], 0, a[1]);
if (!r) {
- if (trace() || 1) fprintf(stderr, "pe2: GetProcAddress(%s, %s) = 0\n", pe2_module_name(a[0]) ? pe2_module_name(a[0]) : "?", a[1] >> 16 ? (char *)P(a[1]) : "#ord");
+ const char *mn = pe2_module_name(a[0]) ? pe2_module_name(a[0]) : "?", *fn = a[1] >> 16 ? (char *)P(a[1]) : "#ord";
+ if (first_times(mn, fn)) fprintf(stderr, "pe2: GetProcAddress(%s, %s) = 0\n", mn, fn);
set_last_error(127);
}
return r;
diff --git a/runtime/loader.c b/runtime/loader.c
index c2fccc4..20009e9 100644
--- a/runtime/loader.c
+++ b/runtime/loader.c
@@ -48,6 +48,7 @@ static uint16_t rd16(const void *p) { uint16_t v; memcpy(&v, p, 2); return v; }
static void fatal(const char *fmt, const char *a) { fprintf(stderr, "pe2: "); fprintf(stderr, fmt, a); fputc('\n', stderr); exit(70); }
static int g_tracenat = -1;
+volatile int pe2_trace_burst;
uint64_t pe2_dispatch(uint32_t idx, uint32_t *args) {
/* PE2_TRACE_NAT=name1,name2: log only natives whose name contains one of them (a full trace of a running
game writes gigabytes in minutes) */
@@ -56,6 +57,11 @@ uint64_t pe2_dispatch(uint32_t idx, uint32_t *args) {
const char *e = getenv("PE2_TRACE_NAT"); g_tracenat = e != 0;
while (e && *e && nf < 16) { const char *c = strchr(e, ','); size_t n = c ? (size_t)(c - e) : strlen(e); snprintf(filt[nf++], 48, "%.*s", (int)n, e); e = c ? c + 1 : 0; }
}
+ if (pe2_trace_burst > 0) { /* a burst of calls after an event (PE2_TRACE_BURST=n: n calls after each Direct3D Reset) */
+ pe2_trace_burst--; uint64_t r = g_nat[idx].fn(args);
+ fprintf(stderr, "[burst %u] %s(%#x, %#x, %#x, %#x) = %#llx\n", *teb32(TEB_TID), g_nat[idx].name, args[0], args[1], args[2], args[3], r);
+ return r;
+ }
if (!g_tracenat) return g_nat[idx].fn(args);
/* PE2_TRACE_FRAMES=from,to: trace only while the client is between those frames ("*" = every native) */
static long tf0 = -2, tf1; if (tf0 == -2) { const char *e = getenv("PE2_TRACE_FRAMES"); tf0 = -1; if (e) sscanf(e, "%ld,%ld", &tf0, &tf1); }
@@ -152,6 +158,24 @@ const char *pe2_module_name(uint32_t h) {
return 0;
}
+/* Accelerated exports. Some library functions a game ships are hot paths that, rewritten, run far slower than on Windows
+ (D3DX converts pixels one at a time with x87 arithmetic, which Rosetta emulates slowly). The runtime may implement
+ such a function natively for the common cases, registered under the library's family name (d3dx9.dll for every
+ d3dx9_NN.dll). The export then binds to the native, which calls the library's own code, kept here, for the rest. */
+static struct { char name[48]; uint32_t orig; } g_accel[32]; static int g_naccel;
+static uint32_t accel_for(uint32_t base, const char *name, uint32_t orig) {
+ module *m = mod_by_base(base); if (!m || strncasecmp(m->name, "d3dx9_", 6)) return 0;
+ uint32_t a = native_lookup("d3dx9.dll", name, 0); if (!a) return 0;
+ int i = 0; while (i < g_naccel && strcmp(g_accel[i].name, name)) i++;
+ if (i == g_naccel && g_naccel < 32) { snprintf(g_accel[i].name, sizeof g_accel[i].name, "%s", name); g_naccel++; }
+ if (i < 32) g_accel[i].orig = orig;
+ return a;
+}
+uint32_t pe2_accel_orig(const char *name) {
+ for (int i = 0; i < g_naccel; i++) if (!strcmp(g_accel[i].name, name)) return g_accel[i].orig;
+ return 0;
+}
+
static uint32_t export_of(uint32_t base, const char *name, uint32_t ordinal) {
uint8_t *img = P(base);
uint32_t pe = rd32(img + 0x3c), ed = rd32(img + pe + 24 + 96), esz = rd32(img + pe + 24 + 100);
@@ -171,6 +195,7 @@ static uint32_t export_of(uint32_t base, const char *name, uint32_t ordinal) {
return h ? pe2_get_proc(h, dot + 1, 0) : 0;
}
uint32_t c = code_at(base + rva); /* a function: its rewritten code; data stays where it is */
+ if (c && name) { uint32_t a = accel_for(base, name, base + rva); if (a) return a; }
return c ? c : base + rva;
}
@@ -180,9 +205,16 @@ uint32_t pe2_get_proc(uint32_t h, const char *name, uint32_t ordinal) {
return dll ? native_lookup(dll, name, ordinal) : 0;
}
+/* The system msvcrt.dll is served by a versioned C runtime rewritten with the program, which exports the same names:
+ the game's own msvcr71.dll, or the msvcr80/msvcr90 DAISY carries for a game that relied on the system's copy. */
+static const char *crt_for_msvcrt(void) {
+ static const char *const v[] = {"msvcr71.dll", "msvcr80.dll", "msvcr90.dll"};
+ for (int i = 0; i < 3; i++)
+ for (const pe2_modreg *r = pe2_modules; r->name; r++) if (!strcasecmp(r->name, v[i])) return v[i];
+ return "msvcr71.dll";
+}
static const pe2_modreg *find_reg(const char *name) {
- /* the system msvcrt.dll is served by the game's own (rewritten) msvcr71.dll, which exports the same names */
- if (!strcasecmp(name, "msvcrt.dll")) name = "msvcr71.dll";
+ if (!strcasecmp(name, "msvcrt.dll")) name = crt_for_msvcrt();
for (const pe2_modreg *r = pe2_modules; r->name; r++) if (!strcasecmp(r->name, name)) return r;
return 0;
}
@@ -218,7 +250,7 @@ static void dll_attach(module *m);
uint32_t pe2_load_library(const char *name) {
char tmp[80]; snprintf(tmp, sizeof tmp, "%s", base_name(name));
if (!strchr(tmp, '.')) strlcat(tmp, ".dll", sizeof tmp);
- if (!strcasecmp(tmp, "msvcrt.dll")) snprintf(tmp, sizeof tmp, "msvcr71.dll");
+ if (!strcasecmp(tmp, "msvcrt.dll")) snprintf(tmp, sizeof tmp, "%s", crt_for_msvcrt());
uint32_t h = pe2_module_by_name(tmp);
module *m = h ? mod_by_base(h) : 0;
if (m) {
@@ -244,11 +276,21 @@ static char *read_file(const char *path, long *n) {
return b;
}
+const char *pe2_program_path_win(void) {
+ static char w[400];
+ if (!w[0]) snprintf(w, sizeof w, "%s\\%s%s%s", pe2_gamedir_win, pe2_program_dir, pe2_program_dir[0] ? "\\" : "", pe2_program_exe);
+ return w;
+}
static uint32_t load_module(const char *name) {
pthread_mutex_lock(&g_ldr);
const pe2_modreg *r = find_reg(name);
if (!r) fatal("no rewritten module %s", name);
char path[1024]; snprintf(path, sizeof path, "%s/%s", g_gamedir_host, r->name);
+ if (r == pe2_modules && pe2_program_dir[0]) { /* the program kept in a sub-folder by its launcher's game */
+ char sub[400]; snprintf(sub, sizeof sub, "%s", pe2_program_dir);
+ for (char *c = sub; *c; c++) if (*c == '\\') *c = '/';
+ snprintf(path, sizeof path, "%s/%s/%s", g_gamedir_host, sub, r->name);
+ }
long n; uint8_t *b = (uint8_t *)read_file(path, &n);
if (!b) fatal("cannot read %s", path);
uint32_t pe = rd32(b + 0x3c), opt = pe + 24;
@@ -290,7 +332,7 @@ static uint32_t load_module(const char *name) {
const char *dll = (char *)img + rd32(img + d + 12);
uint32_t oft = rd32(img + d), ft = rd32(img + d + 16);
uint32_t h = find_reg(dll) ? pe2_load_library(dll) : 0;
- if (!strcasecmp(dll, "msvcrt.dll") && !h) h = pe2_load_library("msvcr71.dll");
+ if (!strcasecmp(dll, "msvcrt.dll") && !h) h = pe2_load_library(crt_for_msvcrt());
if (h) { module *dm = mod_by_base(h); if (dm) dm->refs += 1000000; } /* static imports are never unloaded */
for (uint32_t k = 0;; k++) {
uint32_t e = rd32(img + (oft ? oft : ft) + 4 * k);
@@ -466,6 +508,13 @@ static void crash(int sig, siginfo_t *si, void *uc_) {
if (s->__rsp < 0x100000000ull) {
uint32_t *st = P(s->__rsp);
fprintf(stderr, "pe2: stack %08x %08x %08x %08x %08x %08x\n", st[0], st[1], st[2], st[3], st[4], st[5]);
+ /* the game's own call chain: return addresses into rewritten code found on its stack, nearest first (the
+ frames above only follow native frame pointers, which rewritten code does not keep) */
+ for (int i = 0, k = 0; i < 512 && k < 12; i++) {
+ uint64_t v = st[i]; Dl_info di;
+ if (v < g_text_lo || v >= g_text_hi || !dladdr((void *)(uintptr_t)v, &di) || !di.dli_sname || strncmp(di.dli_sname, "m_", 2)) continue;
+ fprintf(stderr, "pe2: called from %s + %#llx (stack +%#x)\n", di.dli_sname, (unsigned long long)(v - (uint64_t)(uintptr_t)di.dli_saddr), 4 * i); k++;
+ }
/* strings referenced from the frame: usually the message an assertion or logger was about to print */
uint32_t lo = (uint32_t)s->__rsp, hi = (uint32_t)s->__rbp + 64 > lo + 1024 ? lo + 1024 : (uint32_t)s->__rbp + 64;
for (uint32_t p = lo; p + 4 <= hi; p += 4) {
diff --git a/runtime/lowheap.c b/runtime/lowheap.c
index 44dddd2..46efdf3 100644
--- a/runtime/lowheap.c
+++ b/runtime/lowheap.c
@@ -1,3 +1,4 @@
+#include
/* Memory below 4 GB for everything game code can see: a page allocator over one reserved region, and a
size-class allocator on top for HeapAlloc/malloc-style requests. */
#include "pe2.h"
@@ -66,6 +67,8 @@ static void reserve_region(void) {
/* sizes come from game code: anything that would wrap the 32-bit rounding below is refused */
#define MAX_ALLOC 0x7fff0000u
+static volatile uint64_t g_pages_used; /* bytes of the low heap handed out (pages_alloc minus pages_free) */
+uint64_t pe2_low_used(void) { return g_pages_used; }
static uint32_t pages_alloc_locked(uint32_t size) {
if (!g_free) reserve_region();
if (size == 0 || size > MAX_ALLOC) return 0;
@@ -75,6 +78,7 @@ static uint32_t pages_alloc_locked(uint32_t size) {
uint32_t a = g_free[i].start;
g_free[i].start += size; g_free[i].len -= size;
if (!g_free[i].len) { memmove(g_free + i, g_free + i + 1, (g_nfree - i - 1) * sizeof(range)); g_nfree--; }
+ g_pages_used += size;
return a;
}
return 0;
@@ -87,12 +91,24 @@ uint32_t pages_alloc(uint32_t size) {
return a; /* fresh from the reservation or zeroed on free, so always zero */
}
+/* zero [addr, addr + size) by remapping. Only whole 16 KB pages are remapped (the hardware page on Apple silicon); the
+ 4 KB ends are cleared in place. A program under Rosetta sees 4 KB pages, and a hardware page remapped in 4 KB pieces
+ is no longer memory Metal can use without copying: Direct3D buffers placed there later got no Metal buffer
+ (newBufferWithBytesNoCopy returned nil) and their draws were dropped */
+void pages_zero(uint32_t addr, uint32_t size) {
+ uint32_t lo = (addr + 0x3fff) & ~0x3fffu, hi = (addr + size) & ~0x3fffu;
+ if (hi > lo) {
+ memset(P(addr), 0, lo - addr); memset(P(hi), 0, addr + size - hi);
+ mmap(P(lo), hi - lo, PROT_READ | PROT_WRITE, MAP_FIXED | MAP_ANON | MAP_PRIVATE, -1, 0);
+ } else memset(P(addr), 0, size);
+}
+
void pages_free(uint32_t addr, uint32_t size) {
if (!size || size > MAX_ALLOC || addr < PE2_HEAP_LO || addr + size > PE2_HEAP_HI || addr + size < addr) return;
size = (size + 0xfff) & ~0xfffu;
- /* zero by remapping, so the next pages_alloc hands out zeroed memory */
- mmap(P(addr), size, PROT_READ | PROT_WRITE, MAP_FIXED | MAP_ANON | MAP_PRIVATE, -1, 0);
+ pages_zero(addr, size); /* so the next pages_alloc hands out zeroed memory */
pthread_mutex_lock(&g_lock);
+ g_pages_used -= size;
uint32_t i = 0;
while (i < g_nfree && g_free[i].start < addr) i++;
if (g_nfree + 1 > g_capfree) { g_capfree *= 2; g_free = realloc(g_free, sizeof(range) * g_capfree); }
@@ -136,7 +152,7 @@ void *lo_alloc(uint32_t size, int zero) {
if (c == LARGE) {
uint32_t a = pages_alloc_locked(need);
pthread_mutex_unlock(&g_lock);
- if (!a) return 0;
+ if (!a) { static int said; if (said++ < 5) fprintf(stderr, "pe2: low memory (below 4 GB) exhausted: %u bytes not available\n", size); return 0; }
blk = P(a);
((uint32_t *)blk)[0] = size; ((uint32_t *)blk)[1] = LARGE;
return blk + 16; /* fresh pages are zero */
diff --git a/runtime/main.c b/runtime/main.c
index 151ac54..714c74e 100644
--- a/runtime/main.c
+++ b/runtime/main.c
@@ -8,8 +8,18 @@ extern const char *pe2_program_exe; /* generated */
void pe2_set_cmdline(const char *exe_win, int argc, char **argv);
void pe2_set_cwd_win(const char *w);
static void start(int argc, char **argv) {
- char exe_win[300]; snprintf(exe_win, sizeof exe_win, "%s\\%s", pe2_gamedir_win, pe2_program_exe);
- pe2_set_cmdline(exe_win, argc - 1, argv + 1);
+ /* opened without arguments (from the Finder): the ones the game's own launcher passes, if the build named any */
+ /* %GAMEDIR% in one of them is the game folder as the program sees it (C:\data): a launcher passes full paths */
+ int n = 0; while (pe2_program_args[n]) n++;
+ char *def[64]; if (n > 64) n = 64;
+ for (int i = 0; i < n; i++) {
+ const char *s = pe2_program_args[i], *g = strstr(s, "%GAMEDIR%");
+ if (!g) { def[i] = (char *)s; continue; }
+ size_t k = strlen(s) + strlen(pe2_gamedir_win); def[i] = malloc(k);
+ snprintf(def[i], k, "%.*s%s%s", (int)(g - s), s, pe2_gamedir_win, g + 9);
+ }
+ if (argc <= 1 && n) pe2_set_cmdline(pe2_program_path_win(), n, def);
+ else pe2_set_cmdline(pe2_program_path_win(), argc - 1, argv + 1);
pe2_set_cwd_win(pe2_gamedir_win);
pe2_run(pe2_program_exe);
}
@@ -21,8 +31,9 @@ static void start(int argc, char **argv) {
#include
void w64_main_loop(void);
static int g_argc; static char **g_argv; static dispatch_semaphore_t g_ready;
+void pe2_prof_main(void);
static void *program(void *x) {
- (void)x; pe2_init(g_argc, g_argv); dispatch_semaphore_signal(g_ready);
+ (void)x; pe2_prof_main(); pe2_init(g_argc, g_argv); dispatch_semaphore_signal(g_ready);
start(g_argc, g_argv); fflush(0); exit(0);
}
int main(int argc, char **argv) {
diff --git a/runtime/pe2.h b/runtime/pe2.h
index 61d6719..a044fdd 100644
--- a/runtime/pe2.h
+++ b/runtime/pe2.h
@@ -71,6 +71,8 @@ void *lo_realloc(void *p, uint32_t size, int zero);
uint32_t lo_size(void *p);
uint32_t pages_alloc(uint32_t size); /* page-aligned, zeroed; 0 on failure */
void pages_free(uint32_t addr, uint32_t size);
+extern volatile int pe2_trace_burst; /* natives still to log (loader.c) */
+void pages_zero(uint32_t addr, uint32_t size); /* zero in place, keeping 16 KB hardware pages whole */
void pe2_claim(uint32_t lo, uint32_t hi);
char *lo_strdup(const char *s);
@@ -82,6 +84,7 @@ uint32_t pe2_get_proc(uint32_t hmod, const char *name, uint32_t ordinal);
uint32_t pe2_module_by_name(const char *name);
const char *pe2_module_name(uint32_t hmod);
uint64_t pe2_callback(uint32_t orig, const uint32_t *args, uint32_t n);
+uint32_t pe2_accel_orig(const char *name); /* the library's own code for an accelerated export (loader.c) */
uint32_t pe2_native_addr(const char *dll, const char *name);
int pe2_is_program_code(uint64_t addr); /* inside a module's rewritten code */
pe2_fn pe2_native_fn(const char *dll, const char *name); /* C entry of a registered native, 0 if none */
@@ -97,6 +100,9 @@ void pe2_thread_attach(int attach);
void pe2_run(const char *exe);
extern const char *pe2_root; /* host directory that is drive C: */
extern const char *pe2_program_exe; /* the program's exe name (generated) */
+extern const char *pe2_program_dir; /* its sub-folder of the game folder, "" for none (generated: RetailExe\1.9) */
+extern const char *pe2_program_args[]; /* arguments for an app opened without any, 0-terminated (generated) */
+const char *pe2_program_path_win(void); /* C:\data[\]\ */
extern const char *pe2_gamedir_win; /* e.g. C:\BF2 */
/* strings & paths */
diff --git a/runtime/prof.c b/runtime/prof.c
new file mode 100644
index 0000000..147049f
--- /dev/null
+++ b/runtime/prof.c
@@ -0,0 +1,125 @@
+/* PE2_PROF=1: a sampling CPU profiler for the converted program. macOS's own samplers cannot read code running under
+ Rosetta (they show "???"), so the program samples itself: a profiling timer interrupts whichever thread is using
+ the CPU 1000 times a second and the handler counts the instruction address it interrupted. Every PE2_PROF_SECS
+ (default 5) seconds the busiest addresses are written to stderr as "prof:" lines, with a name where the dynamic
+ linker knows one (the runtime's own functions, system libraries). Rewritten program code has no exported names:
+ its addresses resolve offline with atos against the app's binary (it loads at a fixed address), e.g.
+ atos -o KW.app/Contents/MacOS/KW -arch x86_64 0xa1234567
+ The handler only increments counters in a fixed table: no allocation, no locks. */
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#define PROF_N (1u << 16) /* distinct addresses kept per interval (power of two) */
+static _Atomic uint64_t g_addr[PROF_N]; /* address + 1; 0 = free slot */
+static _Atomic uint32_t g_count[PROF_N];
+static _Atomic uint32_t g_total, g_lost;
+/* the game's main thread (pe2_prof_main, from the program thread) gets a table of its own: what makes a frame late */
+static pthread_t g_main; static _Atomic uint64_t m_addr[PROF_N]; static _Atomic uint32_t m_count[PROF_N]; static _Atomic uint32_t m_total;
+void pe2_prof_main(void) { g_main = pthread_self(); }
+/* yields (Sleep(0), SwitchToThread) by the program address that asked, and whether the main thread asked */
+#define SPIN_N 64
+static _Atomic uint32_t s_ret[SPIN_N], s_cnt[SPIN_N], s_main[SPIN_N];
+int pe2_prof_on;
+void pe2_prof_spin(uint32_t ret) {
+ uint32_t h = (ret * 2654435761u) % SPIN_N; int main = pthread_equal(pthread_self(), g_main);
+ for (int i = 0; i < SPIN_N; i++, h = (h + 1) % SPIN_N) {
+ uint32_t cur = atomic_load(&s_ret[h]);
+ if (cur == ret || (!cur && (atomic_compare_exchange_strong(&s_ret[h], &cur, ret) || cur == ret))) { atomic_fetch_add(&s_cnt[h], 1); if (main) atomic_fetch_add(&s_main[h], 1); return; }
+ }
+}
+static void count_in(_Atomic uint64_t *addr, _Atomic uint32_t *count, uint64_t pc) {
+ uint64_t key = pc + 1; uint32_t h = (uint32_t)((pc >> 2) * 2654435761u) & (PROF_N - 1);
+ for (int probe = 0; probe < 32; probe++, h = (h + 1) & (PROF_N - 1)) {
+ uint64_t cur = atomic_load_explicit(&addr[h], memory_order_relaxed);
+ if (cur == key) { atomic_fetch_add_explicit(&count[h], 1, memory_order_relaxed); return; }
+ if (!cur) {
+ uint64_t z = 0;
+ if (atomic_compare_exchange_strong(&addr[h], &z, key) || z == key) { atomic_fetch_add_explicit(&count[h], 1, memory_order_relaxed); return; }
+ }
+ }
+}
+
+static void on_prof(int sig, siginfo_t *si, void *ctx) {
+ (void)sig; (void)si;
+ ucontext_t *uc = ctx; if (!uc || !uc->uc_mcontext) return;
+#if defined(__x86_64__)
+ uint64_t pc = uc->uc_mcontext->__ss.__rip;
+#elif defined(__arm64__)
+ uint64_t pc = __darwin_arm_thread_state64_get_pc(uc->uc_mcontext->__ss);
+#endif
+ atomic_fetch_add_explicit(&g_total, 1, memory_order_relaxed);
+ count_in(g_addr, g_count, pc);
+ if (g_main && pthread_equal(pthread_self(), g_main)) { atomic_fetch_add_explicit(&m_total, 1, memory_order_relaxed); count_in(m_addr, m_count, pc); }
+}
+
+typedef struct { uint64_t pc; uint32_t n; } hit;
+static int by_count(const void *a, const void *b) { const hit *x = a, *y = b; return x->n < y->n ? 1 : x->n > y->n ? -1 : 0; }
+
+static void report(const char *tag, _Atomic uint64_t *addr, _Atomic uint32_t *count, uint32_t total, int secs, int top) {
+ static hit h[PROF_N]; uint32_t n = 0;
+ for (uint32_t i = 0; i < PROF_N; i++) {
+ uint64_t a = atomic_exchange(&addr[i], 0); uint32_t c = atomic_exchange(&count[i], 0);
+ if (a && c) { h[n].pc = a - 1; h[n].n = c; n++; }
+ }
+ if (!total) return;
+ qsort(h, n, sizeof *h, by_count);
+ fprintf(stderr, "%s: %u samples in %d s (%.0f%% of a core), %u distinct\n", tag, total, secs, total / (10.0 * secs), n);
+ for (uint32_t i = 0; i < n && i < (uint32_t)top; i++) {
+ Dl_info di; const char *nm = 0, *lib = 0; uint64_t off = 0;
+ if (dladdr((void *)(uintptr_t)h[i].pc, &di)) { if (di.dli_sname) { nm = di.dli_sname; off = h[i].pc - (uint64_t)(uintptr_t)di.dli_saddr; } if (di.dli_fname) lib = strrchr(di.dli_fname, '/'); }
+ fprintf(stderr, "%s: %5.1f%% %#llx %s+%#llx %s\n", tag, 100.0 * h[i].n / total, (unsigned long long)h[i].pc, nm ? nm : "?", (unsigned long long)off, lib ? lib + 1 : "");
+ }
+}
+static void *dumper(void *arg) {
+ int secs = (int)(intptr_t)arg; static hit h[PROF_N];
+ for (;;) {
+ sleep(secs);
+ report("prof main", m_addr, m_count, atomic_exchange(&m_total, 0), secs, 25);
+ { uint32_t tot = 0, best[6] = {0}, bi[6] = {0};
+ for (int i = 0; i < SPIN_N; i++) { uint32_t c = atomic_load(&s_cnt[i]); tot += c;
+ for (int j = 0; j < 6; j++) if (c > best[j]) { for (int k = 5; k > j; k--) { best[k] = best[k - 1]; bi[k] = bi[k - 1]; } best[j] = c; bi[j] = i; break; } }
+ if (tot) { fprintf(stderr, "prof yields: %u Sleep(0)/SwitchToThread in %d s; by caller:", tot, secs);
+ for (int j = 0; j < 6 && best[j]; j++) fprintf(stderr, " %#x x%u (main %u)", atomic_load(&s_ret[bi[j]]), best[j], atomic_load(&s_main[bi[j]]));
+ fprintf(stderr, "\n"); }
+ for (int i = 0; i < SPIN_N; i++) { atomic_store(&s_cnt[i], 0); atomic_store(&s_main[i], 0); atomic_store(&s_ret[i], 0); } }
+ uint32_t total = atomic_exchange(&g_total, 0), lost = atomic_exchange(&g_lost, 0), n = 0;
+ for (uint32_t i = 0; i < PROF_N; i++) {
+ uint64_t a = atomic_exchange(&g_addr[i], 0); uint32_t c = atomic_exchange(&g_count[i], 0);
+ if (a && c) { h[n].pc = a - 1; h[n].n = c; n++; }
+ }
+ if (!total) continue;
+ qsort(h, n, sizeof *h, by_count);
+ /* a rough split: the program's own image (rewritten code and runtime, below 4 GB here) against the system */
+ uint64_t low = 0; for (uint32_t i = 0; i < n; i++) if (h[i].pc < 0x100000000ull) low += h[i].n;
+ fprintf(stderr, "prof: %u samples in %d s (%.0f%% of a core), %u distinct, %u not counted; in the app image %.0f%%\n",
+ total, secs, total / (10.0 * secs), n, lost, 100.0 * low / total);
+ for (uint32_t i = 0; i < n && i < 40; i++) {
+ Dl_info di; const char *nm = 0; uint64_t off = 0;
+ if (dladdr((void *)(uintptr_t)h[i].pc, &di) && di.dli_sname) { nm = di.dli_sname; off = h[i].pc - (uint64_t)(uintptr_t)di.dli_saddr; }
+ const char *lib = dladdr((void *)(uintptr_t)h[i].pc, &di) && di.dli_fname ? strrchr(di.dli_fname, '/') : 0;
+ fprintf(stderr, "prof: %5.1f%% %#llx %s+%#llx %s\n", 100.0 * h[i].n / total, (unsigned long long)h[i].pc,
+ nm ? nm : "?", (unsigned long long)off, lib ? lib + 1 : "");
+ }
+ }
+ return 0;
+}
+
+__attribute__((constructor)) static void prof_start(void) {
+ const char *e = getenv("PE2_PROF"); if (!e || !*e || *e == '0') return;
+ pe2_prof_on = 1;
+ int secs = getenv("PE2_PROF_SECS") ? atoi(getenv("PE2_PROF_SECS")) : 5; if (secs < 1) secs = 5;
+ struct sigaction sa; memset(&sa, 0, sizeof sa); sa.sa_sigaction = on_prof; sa.sa_flags = SA_SIGINFO | SA_RESTART; sigemptyset(&sa.sa_mask);
+ sigaction(SIGPROF, &sa, 0);
+ pthread_t t; pthread_create(&t, 0, dumper, (void *)(intptr_t)secs); pthread_detach(t);
+ struct itimerval it = {{0, 1000}, {0, 1000}}; setitimer(ITIMER_PROF, &it, 0);
+ fprintf(stderr, "prof: sampling every 1 ms of CPU, report every %d s\n", secs);
+}
diff --git a/runtime/w32glue.m b/runtime/w32glue.m
index e5a0457..473efd4 100644
--- a/runtime/w32glue.m
+++ b/runtime/w32glue.m
@@ -692,18 +692,54 @@ static uint64_t getobj(uint32_t *a, const char *nm) {
return ly;
}
void pe2_window_size(uint32_t h, int *cw, int *ch) { *cw = 800; *ch = 600; if (h && w64_view(P(h))) w64_client_size(P(h), cw, ch); if (*cw <= 0) *cw = 800; if (*ch <= 0) *ch = 600; }
-void pe2_set_mode(uint32_t h, int mw, int mh) { (void)h; (void)mw; (void)mh; }
+void w64_fullscreen(void *p, int mw, int mh);
+void pe2_set_mode(uint32_t h, int mw, int mh) { if (h) w64_fullscreen(P(h), mw, mh); } /* exclusive fullscreen; 0 x 0: windowed again */
void pe2_pump_events(void) {}
void pe2_autoclick_frame(uint64_t f) { (void)f; }
int pe2_autoclick_pos(int32_t *x, int32_t *y) { (void)x; (void)y; return 0; }
-void pe2_dik_event(uint8_t scan, int down) { (void)scan; (void)down; }
-int pe2_dik_pop(uint8_t *scan, int *down, uint32_t *time, uint32_t *seq) { (void)scan; (void)down; (void)time; (void)seq; return 0; }
void pe2_set_mouse_capture(int on) { (void)on; }
-/* DirectInput state the classic runtime keeps (its keyboard and mouse come from the window layer there); here
- DirectInput reads no keys or motion */
+/* a program's cursor files (.cur, .ico, animated .ani): the window layer makes Mac cursors of them (w64/menu.h) */
+void *w64_cursor_file(const uint8_t *d, uint32_t n);
+static uint32_t cursor_from_file(const char *win) {
+ char *h = win2host(win); FILE *f = fopen(h, "rb");
+ if (!f) { if (getenv("W64_TRACE")) fprintf(stderr, "w64: LoadCursorFromFile %s: not found\n", win); free(h); set_last_error(2); return 0; }
+ free(h); fseek(f, 0, SEEK_END); long n = ftell(f); fseek(f, 0, SEEK_SET);
+ uint8_t *d = malloc(n > 0 ? n : 1); size_t got = n > 0 ? fread(d, 1, n, f) : 0; fclose(f);
+ void *c = got ? w64_cursor_file(d, (uint32_t)got) : 0; free(d);
+ if (!c) { if (getenv("W64_TRACE")) fprintf(stderr, "w64: LoadCursorFromFile %s: not a cursor\n", win); set_last_error(13); return 0; }
+ return A32(c);
+}
+NATIVE(user32, LoadCursorFromFileA, 1) { return cursor_from_file(P(a[0])); }
+NATIVE(user32, LoadCursorFromFileW, 1) { char *u = w2u(P(a[0])); uint32_t c = cursor_from_file(u); free(u); return c; }
+/* DirectInput state (client_misc.c reads it), fed by the window layer's event loop through pe2_w64_key/mouse/button
+ (weak no-ops in w64/user32.m): keys as scancodes in order, mouse motion as accumulated counts, buttons with presses
+ shorter than one read kept */
uint8_t pe2_dik[256], pe2_vk[256], pe2_mouse_btn[8], pe2_mouse_press[8];
int32_t pe2_mouse_dx, pe2_mouse_dy, pe2_mouse_dz;
int pe2_mouse_captured;
+typedef struct { uint8_t scan, down; uint32_t time, seq; } dikev;
+static dikev g_dq[256]; static int g_dqh, g_dqt; static uint32_t g_dqseq; static pthread_mutex_t g_dqm = PTHREAD_MUTEX_INITIALIZER;
+static uint32_t dq_ms(void) { return (uint32_t)(clock_gettime_nsec_np(CLOCK_UPTIME_RAW) / 1000000); }
+void pe2_dik_event(uint8_t scan, int down) {
+ pthread_mutex_lock(&g_dqm);
+ if ((g_dqt + 1) % 256 == g_dqh) g_dqh = (g_dqh + 1) % 256; /* full: the oldest goes */
+ g_dq[g_dqt] = (dikev){scan, (uint8_t)down, dq_ms(), g_dqseq++}; g_dqt = (g_dqt + 1) % 256;
+ pthread_mutex_unlock(&g_dqm);
+}
+int pe2_dik_pop(uint8_t *scan, int *down, uint32_t *time, uint32_t *seq) {
+ pthread_mutex_lock(&g_dqm); int r = g_dqh != g_dqt;
+ if (r) { dikev e = g_dq[g_dqh]; g_dqh = (g_dqh + 1) % 256; *scan = e.scan; *down = e.down; *time = e.time; *seq = e.seq; }
+ pthread_mutex_unlock(&g_dqm); return r;
+}
+void pe2_w64_key(uint32_t sc, int down) { /* sc: the set-1 scancode, 0x1xx extended; DIK_ is 0x80 | xx then */
+ uint8_t dik = (uint8_t)((sc & 0x7f) | (sc & 0x100 ? 0x80 : 0)); if (!dik) return;
+ pe2_dik[dik] = down ? 0x80 : 0; pe2_dik_event(dik, down);
+}
+void pe2_w64_mouse(double dx, double dy, int dz) {
+ static double rx, ry; rx += dx; ry += dy; int32_t ix = (int32_t)rx, iy = (int32_t)ry; rx -= ix; ry -= iy;
+ pe2_mouse_dx += ix; pe2_mouse_dy += iy; pe2_mouse_dz += dz;
+}
+void pe2_w64_button(int b, int down) { if (b < 0 || b > 7) return; pe2_mouse_btn[b] = down ? 0x80 : 0; if (down) pe2_mouse_press[b] = 0x80; }
/* ================= window-interface functions the 64-bit layer does not have ================= */
#define NFN(ty, var, dll, name) static __typeof__(ty) var; if (!var) var = (__typeof__(ty))nfn(dll, name)
diff --git a/runtime/win_extra32.c b/runtime/win_extra32.c
new file mode 100644
index 0000000..0e736a1
--- /dev/null
+++ b/runtime/win_extra32.c
@@ -0,0 +1,213 @@
+/* Windows functions older 32-bit games import that the rest of the runtime does not have (found with
+ tools/missing32.py on C&C 3 and its d3dx9/msvcr80). Most are thin forms of functions implemented elsewhere: they
+ call those natives (pe2_native_fn) with their arguments converted. Where Windows itself may fail and programs handle
+ it (no process snapshots, no NetBIOS, no IME candidate lists, no overlapped socket receive), they fail the same way. */
+#include "pe2.h"
+#include
+#include
+#include
+#include
+#include
+#include
+
+static uint64_t call(const char *dll, const char *name, uint32_t *args) {
+ pe2_fn f = pe2_native_fn(dll, name);
+ if (!f) { fprintf(stderr, "pe2: %s!%s is needed by another function and missing\n", dll, name); return 0; }
+ return f(args);
+}
+static uint16_t *lo_w(const char *s) { /* a low-memory wide copy a native can take */
+ if (!s) return 0;
+ size_t n = strlen(s) + 1; uint16_t *w = lo_alloc((uint32_t)(n * 2), 1); u2w(s, w, (uint32_t)n); return w;
+}
+
+/* ---------------- kernel32 ---------------- */
+extern uint32_t pe2_exe_base;
+NATIVE(kernel32, GetModuleHandleExA, 3) {
+ /* GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS (4): the module holding an address; the program's code is rewritten
+ into one Mac binary, so an address in it answers with the program */
+ uint32_t h;
+ if (a[0] & 4) h = pe2_exe_base;
+ else { uint32_t p[1] = {a[1]}; h = (uint32_t)call("kernel32.dll", "GetModuleHandleA", p); }
+ if (a[2]) *(uint32_t *)P(a[2]) = h;
+ if (!h) set_last_error(126);
+ return h != 0;
+}
+NATIVE(kernel32, CopyFileA, 3) {
+ uint16_t *x = lo_w(P(a[0])), *y = lo_w(P(a[1])); uint32_t p[3] = {A32(x), A32(y), a[2]};
+ uint32_t r = (uint32_t)call("kernel32.dll", "CopyFileW", p); lo_free(x); lo_free(y); return r;
+}
+NATIVE(kernel32, CreateToolhelp32Snapshot, 2) { set_last_error(50); return 0xffffffff; } /* ERROR_NOT_SUPPORTED */
+NATIVE(kernel32, Thread32First, 2) { set_last_error(18); return 0; }
+NATIVE(kernel32, Thread32Next, 2) { set_last_error(18); return 0; }
+NATIVE(kernel32, DebugBreak, 0) { return 0; }
+NATIVE(kernel32, ExpandEnvironmentStringsA, 3) {
+ const char *s = P(a[0]); char out[8192]; size_t o = 0;
+ pe2_fn get = pe2_native_fn("kernel32.dll", "GetEnvironmentVariableA");
+ while (*s && o < sizeof out - 1) {
+ const char *e = *s == '%' ? strchr(s + 1, '%') : 0;
+ if (e && e > s + 1 && get) {
+ char *name = lo_alloc((uint32_t)(e - s), 1), *val = lo_alloc(4096, 1); memcpy(name, s + 1, e - s - 1);
+ uint32_t p[3] = {A32(name), A32(val), 4096}; uint32_t n = (uint32_t)get(p);
+ if (n && n < 4096) { size_t k = strlen(val); if (o + k >= sizeof out) k = sizeof out - 1 - o; memcpy(out + o, val, k); o += k; s = e + 1; }
+ else { size_t k = e - s + 1; if (o + k >= sizeof out) k = sizeof out - 1 - o; memcpy(out + o, s, k); o += k; s = e + 1; } /* unknown: kept as written */
+ lo_free(name); lo_free(val);
+ } else out[o++] = *s++;
+ }
+ out[o] = 0;
+ if (a[1] && a[2] > o) memcpy(P(a[1]), out, o + 1);
+ return (uint32_t)o + 1; /* characters needed, with the NUL */
+}
+NATIVE(kernel32, GetConsoleTitleA, 2) { return 0; }
+NATIVE(kernel32, SetConsoleCursorInfo, 2) { return 1; }
+NATIVE(kernel32, WriteConsoleOutputA, 5) { return 1; }
+NATIVE(kernel32, SetNamedPipeHandleState, 4) { set_last_error(6); return 0; }
+NATIVE(kernel32, GetDiskFreeSpaceExW, 4) {
+ struct statvfs v; if (statvfs(pe2_root, &v)) { host_errno_to_win(); return 0; }
+ uint64_t avail = (uint64_t)v.f_bavail * v.f_frsize, total = (uint64_t)v.f_blocks * v.f_frsize, free_ = (uint64_t)v.f_bfree * v.f_frsize;
+ if (a[1]) memcpy(P(a[1]), &avail, 8);
+ if (a[2]) memcpy(P(a[2]), &total, 8);
+ if (a[3]) memcpy(P(a[3]), &free_, 8);
+ return 1;
+}
+NATIVE(kernel32, GetLongPathNameW, 3) { /* no short (8.3) names here: the long name is the name given */
+ uint32_t n = wlen(P(a[0]));
+ if (!a[1] || a[2] <= n) return n + 1;
+ memmove(P(a[1]), P(a[0]), 2 * (n + 1)); return n;
+}
+NATIVE(kernel32, GetTempFileNameA, 4) {
+ uint16_t *d = lo_w(P(a[0])), *pre = a[1] ? lo_w(P(a[1])) : 0, *out = lo_alloc(2 * 600, 1);
+ uint32_t p[4] = {A32(d), A32(pre), a[2], A32(out)};
+ uint32_t r = (uint32_t)call("kernel32.dll", "GetTempFileNameW", p);
+ if (r) { char *u = w2u(out); snprintf(P(a[3]), 260, "%s", u); free(u); }
+ lo_free(d); if (pre) lo_free(pre); lo_free(out); return r;
+}
+NATIVE(kernel32, GetTimeFormatW, 6) {
+ char t[64]; uint32_t p[6] = {a[0], a[1], a[2], 0, A32(t), sizeof t};
+ char *tl = lo_alloc(sizeof t, 1); p[4] = A32(tl);
+ uint32_t k = (uint32_t)call("kernel32.dll", "GetTimeFormatA", p);
+ if (k && a[5]) u2w(tl, P(a[4]), a[5]);
+ lo_free(tl); return k;
+}
+NATIVE(kernel32, GlobalReAlloc, 3) {
+ if (!a[0]) { uint32_t p[2] = {a[2], a[1]}; return call("kernel32.dll", "GlobalAlloc", p); }
+ void *n = lo_realloc(P(a[0]), a[1] ? a[1] : 1, (a[2] & 0x40) != 0); /* GMEM_ZEROINIT */
+ if (!n) set_last_error(8);
+ return A32(n);
+}
+NATIVE(kernel32, OpenEventA, 3) { set_last_error(2); return 0; } /* events here have no names: none is open */
+NATIVE(kernel32, QueueUserAPC, 3) { set_last_error(50); return 0; }
+NATIVE(kernel32, ReadProcessMemory, 5) { /* only this process exists: a copy within it */
+ if (a[3]) memmove(P(a[2]), P(a[1]), a[3]);
+ if (a[4]) *(uint32_t *)P(a[4]) = a[3];
+ return 1;
+}
+NATIVE(kernel32, lstrcpyW, 2) { memmove(P(a[0]), P(a[1]), 2 * (wlen(P(a[1])) + 1)); return a[0]; }
+
+/* ---------------- gdi32: text-layout queries are refused (programs then measure with GetTextExtentPoint) ---------------- */
+NATIVE(gdi32, GetCharacterPlacementA, 6) { return 0; }
+NATIVE(gdi32, GetCharacterPlacementW, 6) { return 0; }
+NATIVE(gdi32, GetFontLanguageInfo, 1) { return 0; }
+NATIVE(gdi32, GetGlyphOutlineA, 7) { return 0xffffffff; } /* GDI_ERROR, as GetGlyphOutlineW */
+NATIVE(gdi32, GetOutlineTextMetricsA, 3) { return 0; }
+NATIVE(gdi32, GetTextExtentPointI, 4) { return 0; }
+NATIVE(gdi32, SetDeviceGammaRamp, 2) { return 1; } /* accepted; the Mac display keeps its own */
+NATIVE(gdi32, SetMapMode, 2) { return 1; } /* MM_TEXT, the only mode here */
+NATIVE(gdi32, TranslateCharsetInfo, 3) { return 0; }
+
+/* ---------------- imm32: no input method window ---------------- */
+NATIVE(imm32, ImmCreateContext, 0) { return 0; }
+NATIVE(imm32, ImmDestroyContext, 1) { return 1; }
+NATIVE(imm32, ImmGetCandidateListCountW, 2) { if (a[1]) *(uint32_t *)P(a[1]) = 0; return 0; }
+NATIVE(imm32, ImmGetCandidateListW, 4) { return 0; }
+NATIVE(imm32, ImmGetIMEFileNameA, 3) { return 0; }
+NATIVE(imm32, ImmGetProperty, 2) { return 0; }
+
+/* ---------------- others ---------------- */
+NATIVE(netapi32, Netbios, 1) { uint8_t *ncb = P(a[0]); ncb[1] = 0x40; return 0x40; } /* NRC_SYSTEM: no NetBIOS */
+NATIVE(ole32, CoGetObject, 4) { if (a[3]) *(uint32_t *)P(a[3]) = 0; return 0x800401e4u; } /* MK_E_SYNTAX */
+NATIVE(ole32, OleRun, 1) { return 0; }
+NATIVE(wininet, InternetCrackUrlA, 4) { set_last_error(12006); return 0; } /* ERROR_INTERNET_UNRECOGNIZED_SCHEME */
+NATIVE_ORD(dsound, DirectSoundCaptureEnumerateW, 8, 2) { return 0; } /* no capture devices: the callback never runs */
+
+NATIVE(shlwapi, PathFindFileNameA, 1) {
+ char *s = P(a[0]), *f = s;
+ for (char *c = s; *c; c++) if ((*c == '\\' || *c == '/' || *c == ':') && c[1]) f = c + 1;
+ return A32(f);
+}
+NATIVE(shlwapi, PathRemoveExtensionA, 1) {
+ char *s = P(a[0]), *dot = 0;
+ for (char *c = s; *c; c++) { if (*c == '.') dot = c; else if (*c == '\\' || *c == '/' || *c == ' ') dot = 0; }
+ if (dot) *dot = 0;
+ return 0;
+}
+
+/* ws2_32 event objects are kernel events */
+NATIVE(ws2_32, WSACreateEvent, 0) { uint32_t p[4] = {0, 1, 0, 0}; return call("kernel32.dll", "CreateEventA", p); } /* manual reset */
+NATIVE(ws2_32, WSACloseEvent, 1) { uint32_t p[1] = {a[0]}; return call("kernel32.dll", "CloseHandle", p); }
+NATIVE(ws2_32, WSASetEvent, 1) { uint32_t p[1] = {a[0]}; return call("kernel32.dll", "SetEvent", p); }
+NATIVE(ws2_32, WSAResetEvent, 1) { uint32_t p[1] = {a[0]}; return call("kernel32.dll", "ResetEvent", p); }
+NATIVE(ws2_32, WSAWaitForMultipleEvents, 5) { /* WSA_WAIT_EVENT_0 / WSA_WAIT_TIMEOUT match WaitForMultipleObjects */
+ uint32_t p[4] = {a[0], a[1], a[2], a[3]}; return call("kernel32.dll", "WaitForMultipleObjects", p);
+}
+NATIVE(ws2_32, WSARecv, 7) { set_last_error(10045); return 0xffffffff; } /* WSAEOPNOTSUPP: overlapped I/O */
+NATIVE(ws2_32, WSARecvFrom, 9) { set_last_error(10045); return 0xffffffff; }
+NATIVE(ws2_32, WSAGetOverlappedResult, 5) { set_last_error(10045); return 0; }
+
+/* ---------------- user32 ---------------- */
+#ifndef PE2_GUI32 /* the full window layer reads the cursor file itself (w32glue.m) */
+NATIVE(user32, LoadCursorFromFileA, 1) { /* .cur/.ani files are not read: the arrow, so a pointer still shows */
+ uint32_t p[2] = {0, 32512}; pe2_fn f = pe2_native_fn("user32.dll", "LoadCursorA");
+ return f ? f(p) : 32512;
+}
+#endif
+
+/* wsprintfA/W: Windows' own small printf (no floating point). Arguments follow the format on the stack. */
+static uint32_t wfmt(char *out, uint32_t cap, const char *f, const uint32_t *arg, int wide) {
+ uint32_t o = 0;
+ #define PUT(ch) do { if (o + 1 < cap) out[o] = (ch); o++; } while (0)
+ while (*f) {
+ if (*f != '%') { PUT(*f++); continue; }
+ f++;
+ if (*f == '%') { PUT('%'); f++; continue; }
+ char spec[16] = "%"; int k = 1;
+ while (*f && strchr("-#0 +", *f) && k < 6) spec[k++] = *f++;
+ int width = 0, prec = -1;
+ while (*f >= '0' && *f <= '9') width = width * 10 + (*f++ - '0');
+ if (*f == '.') { f++; prec = 0; while (*f >= '0' && *f <= '9') prec = prec * 10 + (*f++ - '0'); }
+ int lng = 0, sht = 0, i64 = 0;
+ for (;;) {
+ if (*f == 'l') { lng = 1; f++; } else if (*f == 'h') { sht = 1; f++; }
+ else if (f[0] == 'I' && f[1] == '6' && f[2] == '4') { i64 = 1; f += 3; } else break;
+ }
+ char c = *f ? *f++ : 0, buf[512]; buf[0] = 0;
+ if (width) k += snprintf(spec + k, sizeof spec - k, "%d", width);
+ if (prec >= 0) k += snprintf(spec + k, sizeof spec - k, ".%d", prec);
+ switch (c) {
+ case 'd': case 'i': case 'u': case 'x': case 'X': {
+ uint64_t v = *arg++; if (i64) v |= (uint64_t)*arg++ << 32;
+ snprintf(spec + k, sizeof spec - k, "ll%c", c);
+ if (c == 'd' || c == 'i') snprintf(buf, sizeof buf, spec, i64 ? (long long)v : (long long)(sht ? (int16_t)v : (int32_t)v));
+ else snprintf(buf, sizeof buf, spec, (unsigned long long)(sht ? (uint16_t)v : v));
+ break; }
+ case 'p': snprintf(buf, sizeof buf, "%08X", *arg++); break;
+ case 'c': case 'C': {
+ uint32_t v = *arg++; int w = c == 'C' ? !wide : wide; if (lng) w = 1; if (sht) w = 0;
+ char ch[8] = {0}; if (w) { uint16_t ws[2] = {(uint16_t)v, 0}; char *u = w2u(ws); snprintf(ch, sizeof ch, "%s", u); free(u); } else ch[0] = (char)v;
+ spec[k] = 's'; spec[k + 1] = 0; snprintf(buf, sizeof buf, spec, ch); break; }
+ case 's': case 'S': {
+ uint32_t v = *arg++; int w = c == 'S' ? !wide : wide; if (lng) w = 1; if (sht) w = 0;
+ char *s = !v ? strdup("(null)") : w ? w2u(P(v)) : strdup(P(v));
+ spec[k] = 's'; spec[k + 1] = 0; snprintf(buf, sizeof buf, spec, s); free(s); break; }
+ default: if (c) { PUT('%'); PUT(c); } continue;
+ }
+ for (char *b = buf; *b; b++) PUT(*b);
+ }
+ if (cap) out[o < cap ? o : cap - 1] = 0;
+ return o < cap ? o : cap - 1;
+ #undef PUT
+}
+CDECL(user32, wsprintfA) { return wfmt(P(a[0]), 1025, P(a[1]), a + 2, 0); } /* the output buffer is at most 1024 */
+CDECL(user32, wsprintfW) {
+ char *f = w2u(P(a[1])), tmp[4096]; wfmt(tmp, sizeof tmp, f, a + 2, 1); free(f);
+ return u2w(tmp, P(a[0]), 1025);
+}
diff --git a/runtime/win_misc.c b/runtime/win_misc.c
index ec7fb1f..e8ede06 100644
--- a/runtime/win_misc.c
+++ b/runtime/win_misc.c
@@ -206,18 +206,19 @@ NATIVE(advapi32, RegFlushKey, 1) { pthread_mutex_lock(&g_rl); reg_load(); reg_sa
NATIVE(advapi32, GetUserNameA, 2) { strcpy(P(a[0]), "Player"); *(uint32_t *)P(a[1]) = 7; return 1; }
/* ---------------- sockets ---------------- */
-static void wsa_err(void) {
- uint32_t e;
- switch (errno) {
- case EWOULDBLOCK: e = 10035; break; case EINPROGRESS: e = 10036; break; case EALREADY: e = 10037; break;
- case ENOTSOCK: e = 10038; break; case EMSGSIZE: e = 10040; break; case EADDRINUSE: e = 10048; break;
- case EADDRNOTAVAIL: e = 10049; break; case ENETUNREACH: e = 10051; break; case ECONNABORTED: e = 10053; break;
- case ECONNRESET: e = 10054; break; case ENOBUFS: e = 10055; break; case EISCONN: e = 10056; break;
- case ENOTCONN: e = 10057; break; case ETIMEDOUT: e = 10060; break; case ECONNREFUSED: e = 10061; break;
- case EHOSTUNREACH: e = 10065; break; case EBADF: e = 10009; break; default: e = 10022;
- }
- set_last_error(e);
+/* errno -> Winsock error, as w64/net.c. A non-blocking connect that has started is WSAEWOULDBLOCK on Windows (10035),
+ not WSAEINPROGRESS (10036, a blocking call already running): a program checks for 10035 and took 10036 as failure */
+static uint32_t wsa_code(int e) {
+ static const int t[][2] = {{EWOULDBLOCK, 10035}, {EINPROGRESS, 10035}, {EINTR, 10004}, {EBADF, 10038}, {EACCES, 10013},
+ {EFAULT, 10014}, {EINVAL, 10022}, {EMFILE, 10024}, {EALREADY, 10037}, {ENOTSOCK, 10038}, {EDESTADDRREQ, 10039},
+ {EMSGSIZE, 10040}, {EPROTOTYPE, 10041}, {ENOPROTOOPT, 10042}, {EPROTONOSUPPORT, 10043}, {EOPNOTSUPP, 10045},
+ {EAFNOSUPPORT, 10047}, {EADDRINUSE, 10048}, {EADDRNOTAVAIL, 10049}, {ENETDOWN, 10050}, {ENETUNREACH, 10051},
+ {ECONNABORTED, 10053}, {ECONNRESET, 10054}, {EPIPE, 10054}, {ENOBUFS, 10055}, {EISCONN, 10056}, {ENOTCONN, 10057},
+ {ETIMEDOUT, 10060}, {ECONNREFUSED, 10061}, {EHOSTDOWN, 10064}, {EHOSTUNREACH, 10065}};
+ for (unsigned i = 0; i < sizeof t / sizeof *t; i++) if (t[i][0] == e) return t[i][1];
+ return 10022;
}
+static void wsa_err(void) { set_last_error(wsa_code(errno)); }
static void dump_pkt(const char *what, uint32_t fd, const uint8_t *b, int n);
/* Windows sockaddr starts with u16 family; BSD has u8 len, u8 family */
static socklen_t sa_in(uint32_t p, uint32_t len, struct sockaddr_storage *o) {
@@ -277,16 +278,40 @@ static void dump_pkt(const char *what, uint32_t fd, const uint8_t *b, int n) {
for (int i = 0; i < k; i++) asc[i] = b[i] >= 32 && b[i] < 127 ? b[i] : '.'; asc[k] = 0;
fprintf(stderr, "sock: %s fd %u %d bytes %s |%s|\n", what, fd, n, hex, asc);
}
-BOTH(20, sendto, 6, { dump_pkt("send", a[0], P(a[1]), a[2]); struct sockaddr_storage s; socklen_t l = sa_in(a[4], a[5], &s); ssize_t r = sendto(a[0], P(a[1]), a[2], a[3], a[4] ? (struct sockaddr *)&s : 0, a[4] ? l : 0); if (r < 0) { wsa_err(); return 0xffffffff; } return r; })
+BOTH(20, sendto, 6, { dump_pkt("send", a[0], P(a[1]), a[2]); struct sockaddr_storage s; socklen_t l = sa_in(a[4], a[5], &s); ssize_t r = sendto(a[0], P(a[1]), a[2], a[3], a[4] ? (struct sockaddr *)&s : 0, a[4] ? l : 0); if (r < 0) { if (getenv("PE2_TRACE_SOCK")) fprintf(stderr, "sock: sendto failed: %s\n", strerror(errno)); wsa_err(); return 0xffffffff; } return r; })
BOTH(22, shutdown, 2, { return shutdown(a[0], a[1]) ? (wsa_err(), 0xffffffff) : 0; })
+/* Windows option values: an int, or a one-byte BOOL; send/receive timeouts are milliseconds (a timeval here); options
+ only Windows has are accepted and ignored (SO_EXCLUSIVEADDRUSE, SO_DONTLINGER, SO_CONDITIONAL_ACCEPT, the
+ SO_UPDATE_* and SO_*_CONTEXT ones); TCP_MAXSEG/KEEPCNT/KEEPINTVL have other numbers here. As in w64/net.c. */
BOTH(21, setsockopt, 5, {
- int lvl = a[1], opt = a[2];
- if (lvl == 0xffff && opt == 0x80) { uint16_t *w = P(a[3]); struct linger lg = {w[0], w[1]}; setsockopt(a[0], SOL_SOCKET, SO_LINGER, &lg, sizeof lg); return 0; }
- if (lvl == 0xffff && opt == 0xfffffffb) return 0; /* SO_DONTLINGER */
- if (setsockopt(a[0], lvl, opt, P(a[3]), a[4])) { if (errno == ENOPROTOOPT || errno == EINVAL) return 0; wsa_err(); return 0xffffffff; }
+ int lvl = a[1], opt = a[2], n = a[4], x = 0; const void *v = a[3] ? P(a[3]) : 0;
+ if (v && n >= 4) memcpy(&x, v, 4); else if (v && n) x = *(const uint8_t *)v;
+ int r;
+ if (lvl == 0xffff) {
+ if (opt == 0x80) { const uint16_t *w = v; struct linger lg = {w ? w[0] : 0, w ? w[1] : 0}; setsockopt(a[0], SOL_SOCKET, SO_LINGER, &lg, sizeof lg); return 0; }
+ if (opt == 0x1005 || opt == 0x1006) { struct timeval t = {x / 1000, x % 1000 * 1000}; r = setsockopt(a[0], SOL_SOCKET, opt, &t, sizeof t); }
+ else if (opt == ~4 || opt == ~0x80 || opt == 0x3002 || opt == 0x3005 || opt == 0x3006 || opt == 0x700b || opt == 0x7010) return 0;
+ else r = setsockopt(a[0], SOL_SOCKET, opt, &x, 4);
+ } else if (lvl == 6) { if (opt == 3) opt = 0x10; else if (opt == 17) opt = 0x101; else if (opt == 16) opt = 0x102; r = setsockopt(a[0], 6, opt, &x, 4); }
+ else r = setsockopt(a[0], lvl, opt, v, n);
+ if (r) { if (errno == ENOPROTOOPT || errno == EINVAL) return 0; wsa_err(); return 0xffffffff; }
+ return 0;
+})
+BOTH(7, getsockopt, 5, {
+ uint32_t *n = P(a[4]); uint8_t *v = P(a[3]); int lvl = a[1], opt = a[2];
+ if (lvl == 0xffff && (opt == 0x1005 || opt == 0x1006)) {
+ struct timeval t = {0}; socklen_t k = sizeof t; if (getsockopt(a[0], SOL_SOCKET, opt, &t, &k)) { wsa_err(); return 0xffffffff; }
+ uint32_t ms = (uint32_t)(t.tv_sec * 1000 + t.tv_usec / 1000); memcpy(v, &ms, 4); *n = 4; return 0;
+ }
+ if (lvl == 6) { if (opt == 3) opt = 0x10; else if (opt == 17) opt = 0x101; else if (opt == 16) opt = 0x102; }
+ if (lvl == 0xffff && opt == 0x80) { struct linger lg; socklen_t k = sizeof lg; if (getsockopt(a[0], SOL_SOCKET, SO_LINGER, &lg, &k)) { wsa_err(); return 0xffffffff; }
+ uint16_t w[2] = {(uint16_t)lg.l_onoff, (uint16_t)lg.l_linger}; memcpy(v, w, *n < 4 ? *n : 4); *n = 4; return 0; }
+ int x = 0; socklen_t k = 4;
+ if (getsockopt(a[0], lvl, opt, &x, &k)) { wsa_err(); return 0xffffffff; }
+ if (lvl == 0xffff && opt == 0x1007 && x) x = (int)wsa_code(x); /* SO_ERROR: a Winsock code, as WSAGetLastError */
+ if (*n >= 4) { memcpy(v, &x, 4); *n = 4; } else if (*n) { *v = (uint8_t)x; *n = 1; }
return 0;
})
-BOTH(7, getsockopt, 5, { socklen_t l = *(uint32_t *)P(a[4]); if (getsockopt(a[0], a[1], a[2], P(a[3]), &l)) { wsa_err(); return 0xffffffff; } *(uint32_t *)P(a[4]) = l; return 0; })
BOTH2(10, 12, ioctlsocket, 3, {
if (a[1] == 0x8004667e) { int fl = fcntl(a[0], F_GETFL); fcntl(a[0], F_SETFL, *(uint32_t *)P(a[2]) ? fl | O_NONBLOCK : fl & ~O_NONBLOCK); return 0; }
if (a[1] == 0x4004667f) { int n = 0; ioctl(a[0], FIONREAD, &n); *(uint32_t *)P(a[2]) = n; return 0; }
@@ -328,11 +353,14 @@ static int is_local(const char *name) { char h[256]; gethostname(h, sizeof h); c
static int local_addrs(uint32_t *out, int cap) {
struct ifaddrs *ifs, *i; int n = 0;
if (getifaddrs(&ifs)) return 0;
- for (i = ifs; i && n < cap; i = i->ifa_next) /* real interfaces first, loopback last */
- if (i->ifa_addr && i->ifa_addr->sa_family == AF_INET && (i->ifa_flags & IFF_UP) && !(i->ifa_flags & IFF_LOOPBACK))
+ /* the machine's own addresses, as Windows resolves its own name: the real interfaces, and loopback only when there is
+ none. Listed with them, 127.0.0.1 could be the one a game picks for LAN play (C&C 3 sorts the list and takes the
+ first), and the game then announced itself on loopback only: no other machine saw it */
+ for (i = ifs; i && n < cap; i = i->ifa_next)
+ if (i->ifa_addr && i->ifa_addr->sa_family == AF_INET && (i->ifa_flags & IFF_UP) && (i->ifa_flags & IFF_RUNNING) && !(i->ifa_flags & IFF_LOOPBACK))
out[n++] = ((struct sockaddr_in *)i->ifa_addr)->sin_addr.s_addr;
freeifaddrs(ifs);
- if (n < cap) out[n++] = htonl(INADDR_LOOPBACK);
+ if (!n) out[n++] = htonl(INADDR_LOOPBACK);
return n;
}
static uint64_t hostent_for(const char *name, uint32_t addr) {
@@ -388,6 +416,8 @@ NATIVE(shell32, SHGetSpecialFolderPathA, 4) { const char *p = csidl_path(a[2]);
NATIVE(shell32, SHFileOperationW, 1) { return 0; }
NATIVE(shell32, ShellExecuteExA, 1) { set_last_error(2); return 0; }
NATIVE(shell32, ShellExecuteA, 6) { return 2; }
+NATIVE(shell32, ShellExecuteW, 6) { return 2; } /* SE_ERR_FNF: no other program is opened */
+NATIVE(shell32, SHGetSpecialFolderPathW, 4) { const char *p = csidl_path(a[2]); mkdirs_host(p); u2w(p, P(a[1]), 260); return 1; }
NATIVE(dbghelp, MiniDumpWriteDump, 7) { return 0; }
NATIVE(psapi, GetModuleInformation, 4) { memset(P(a[2]), 0, a[3]); return 0; }
NATIVE(psapi, GetProcessMemoryInfo, 3) { memset(P(a[1]), 0, a[2]); return 1; }
@@ -402,4 +432,4 @@ NATIVE(psapi, GetPerformanceInfo, 2) {
return 1;
}
NATIVE(psapi, GetModuleBaseNameA, 4) { const char *n = pe2_module_name(a[1] ? a[1] : 0x400000); if (!n) n = pe2_program_exe; snprintf(P(a[2]), a[3], "%s", n); return strlen(P(a[2])); }
-NATIVE(psapi, GetModuleFileNameExA, 4) { snprintf(P(a[2]), a[3], "%s\\%s", pe2_gamedir_win, pe2_program_exe); return strlen(P(a[2])); }
+NATIVE(psapi, GetModuleFileNameExA, 4) { snprintf(P(a[2]), a[3], "%s", pe2_program_path_win()); return strlen(P(a[2])); }
diff --git a/tools/build.py b/tools/build.py
index 99ba4e6..79f3d97 100755
--- a/tools/build.py
+++ b/tools/build.py
@@ -2,14 +2,28 @@
# build.py ...
# build.py --auto --plugin a VST 2 plug-in DLL: the helper a converted plug-in's
# shim starts (runtime/plughost.c), with the window layer
+# --args a,b,... arguments the program gets when the app is opened without any (what its own launcher passes)
+# --data the program's folder in the app: system libraries DAISY carries (kit/sys/x86) that the program
+# needs and does not ship are copied there, beside its own
+# may sit in a sub-folder of (RetailExe/1.9/cnc3game.dat); stays the program's folder (cwd).
import os, re, subprocess, sys
from concurrent.futures import ProcessPoolExecutor
HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
CC = ['clang', '-target', 'x86_64-apple-macos13']
+SYS32 = os.path.join(HERE, 'sys', 'x86') # Windows system libraries a game may use without shipping them (msvcr80, d3dx9_NN)
def find(gamedir, name):
- for f in os.listdir(gamedir):
- if f.lower() == name.lower(): return os.path.join(gamedir, f)
+ d = gamedir
+ for part in name.replace('\\', '/').split('/')[:-1]: # a program in a sub-folder; names differ in case on a Mac disk
+ m = [f for f in os.listdir(d) if f.lower() == part.lower()]
+ if not m: raise SystemExit(f'{name} not in {gamedir}')
+ d = os.path.join(d, m[0])
+ base = os.path.basename(name.replace('\\', '/'))
+ for f in os.listdir(d):
+ if f.lower() == base.lower(): return os.path.join(d, f)
+ if os.path.isdir(SYS32):
+ for f in os.listdir(SYS32):
+ if f.lower() == base.lower(): return os.path.join(SYS32, f)
raise SystemExit(f'{name} not in {gamedir}')
def prefix(name): return 'm_' + re.sub(r'[^a-z0-9]', '_', name.lower())
@@ -39,6 +53,11 @@ def auto_modules(gamedir, exe):
sys.path.insert(0, HERE); from pe2mac.rewrite import PE
import struct
idx = {f.lower(): os.path.join(gamedir, f) for f in os.listdir(gamedir) if f.lower().endswith(('.dll', '.exe'))}
+ idx[exe.lower()] = find(gamedir, exe)
+ ship = set(idx)
+ if os.path.isdir(SYS32): # the game's own copy wins; DAISY's only fills in what it lacks
+ for f in os.listdir(SYS32):
+ if f.lower().endswith('.dll') and f.lower() not in idx: idx[f.lower()] = os.path.join(SYS32, f)
def is32(p):
b = open(p, 'rb').read(4096)
try: return b[:2] == b'MZ' and struct.unpack_from('/dev/null) $(ls src/m*.s) src/w64/*.c src/w64/*.s src/w64/*.m -Wa,-Isrc $(cat src/flags) 2>&1 | grep -E 'error|Undefined|"_' | head -20
A={name}.app; rm -rf $A; mkdir -p $A/Contents/MacOS $A/Contents/Resources; cp bin $A/Contents/MacOS/{name}; cp -R Resources/* $A/Contents/Resources/ 2>/dev/null
-printf 'CFBundleExecutable{name}CFBundleIdentifierdaisy.{name}CFBundleName{name}CFBundlePackageTypeAPPLNSHighResolutionCapable' > $A/Contents/Info.plist; codesign -s - -f $A 2>/dev/null; ls -la $A/Contents/MacOS | tail -1'''
+printf 'CFBundleExecutable{name}CFBundleIdentifierdaisy.{name}CFBundleName{name}CFBundlePackageTypeAPPLNSHighResolutionCapableNSLocalNetworkUsageDescriptionLets the game find and join games on your local network (LAN play).' > $A/Contents/Info.plist; codesign -s - -f $A 2>/dev/null; ls -la $A/Contents/MacOS | tail -1'''
top = opt('--top') or folder; sub = os.path.relpath(folder, top); sub = '' if sub == '.' else sub
if host == 'local': # build on this Mac: the app and the program's files go to DAISY_OUT (default build/run/app_)
L = os.path.abspath(os.environ.get('DAISY_OUT') or f'{H}/build/run/app_{name}'); os.makedirs(L + '/data', exist_ok=True)
diff --git a/tools/fetch_sys32.sh b/tools/fetch_sys32.sh
new file mode 100755
index 0000000..121e35c
--- /dev/null
+++ b/tools/fetch_sys32.sh
@@ -0,0 +1,30 @@
+#!/bin/bash
+# fetch_sys32.sh : the 32-bit Windows system libraries older games use without shipping them, from
+# Microsoft's own redistributable packages (the ones a game's installer would have run):
+# msvcr80/msvcp80 (Visual C++ 2005 SP1), msvcr90/msvcp90 (Visual C++ 2008 SP1), d3dx9_24 ... d3dx9_43 (DirectX June 2010)
+# build.py rewrites one with the game when the game imports it and has no copy of its own (kit/sys/x86).
+# The C runtimes are the "nosxs" builds: they load without the Windows side-by-side manifest check.
+set -e
+OUT="${1:?usage: fetch_sys32.sh }"; mkdir -p "$OUT"
+Z="${DAISY_7ZZ:-$(command -v 7zz || echo "$(dirname "$0")/../bin/7zz")}"
+T=$(mktemp -d "${TMPDIR:-/tmp}/sys32.XXXXXX"); trap 'rm -rf "$T"' EXIT
+get() { mkdir -p "$T/$1"; curl -fsSL -o "$T/$1/pkg.exe" "$2"; }
+crt() { # crt : the C runtime inside the redistributable (in a .cab, or a merge module in its MSI)
+ get "$1" "$2"; "$Z" x -y -o"$T/$1/x" "$T/$1/pkg.exe" >/dev/null
+ for k in 1 2 3; do # unpack nested packages: exe -> msi/cab -> msm -> files
+ find "$T/$1/x" \( -iname '*.msi' -o -iname '*.msm' -o -iname '*.cab' \) ! -iname '*policy*' | while IFS= read -r a; do
+ [ -d "$a.x" ] || "$Z" x -y -o"$a.x" "$a" >/dev/null 2>&1 || true
+ done
+ done
+ for d in msvcr msvcp; do
+ f=$(find "$T/$1/x" -name "nosxs_${d}${1}.dll*" | head -1)
+ [ -n "$f" ] || f=$(find "$T/$1/x" -name "${d}${1}.dll*" ! -name 'ul_*' | head -1)
+ [ -n "$f" ] && cp "$f" "$OUT/${d}${1}.dll" && echo "$OUT/${d}${1}.dll"
+ done
+}
+crt 80 "https://download.microsoft.com/download/8/B/4/8B42259F-5D70-43F4-AC2E-4B208FD8D66A/vcredist_x86.EXE"
+crt 90 "https://download.microsoft.com/download/5/D/8/5D8C65CB-C849-4025-8E95-C3966CAFD8AE/vcredist_x86.exe"
+get dx "https://download.microsoft.com/download/8/4/A/84A35BF1-DAFE-4AE8-82AF-AD2AE20B6B14/directx_Jun2010_redist.exe"
+"$Z" x -y -o"$T/dx/x" "$T/dx/pkg.exe" '*d3dx9_*_x86.cab' >/dev/null
+for c in "$T/dx/x"/*d3dx9_*_x86.cab; do "$Z" e -y -o"$T/dx/d" "$c" 'd3dx9_*.dll' >/dev/null; done
+for f in "$T/dx/d"/d3dx9_*.dll; do cp "$f" "$OUT/"; echo "$OUT/$(basename "$f")"; done
diff --git a/tools/intake.py b/tools/intake.py
index 850c9a4..73c7b81 100644
--- a/tools/intake.py
+++ b/tools/intake.py
@@ -38,6 +38,42 @@ def sections(f):
o = struct.unpack_from('"; the launcher passes "-config " (%GAMEDIR%: the game folder, see main.c)
+ * the launcher holds the program's file name (C&C Generals and BFME 1: game.dat)
+ * the program has the launcher's name with another extension (SafeDisc: game.exe loads game.icd)"""
+ d = os.path.dirname(g); stem = os.path.splitext(os.path.basename(g))[0].lower()
+ skus = sorted(glob.glob(glob.escape(d) + '/*.[sS][kK][uU][dD][eE][fF]'), key=lambda k: ('english' not in k.lower(), k.lower()))
+ for sku in skus:
+ for ln in open(sku, 'rb').read().decode('latin-1').splitlines():
+ ln = ln.strip()
+ if ln.lower().startswith('set-exe '):
+ rel = ln[8:].strip().strip('"').replace('\\', '/'); real = os.path.join(d, rel)
+ if not os.path.isfile(real): # names differ in case on a Mac disk
+ real = d
+ for part in rel.split('/'):
+ m = [x for x in os.listdir(real) if x.lower() == part.lower()] if os.path.isdir(real) else []
+ if not m: real = None; break
+ real = os.path.join(real, m[0])
+ if real and is_program(real): return real, ['-config', '%GAMEDIR%\\' + os.path.basename(sku)] # a full path: the game reads it from its own folder otherwise
+ raw = open(g, 'rb').read().lower(); best = None
+ for f in glob.glob(glob.escape(d) + '/**/*', recursive=True):
+ n = os.path.basename(f).lower(); x = os.path.splitext(n)[1]
+ if x in ('.exe', '.dll', '.sys', '.ocx', '.ax', '.cpl', '.drv', '.asi', '.flt', '.mui', '.tlb', '.scr') or not os.path.isfile(f): continue
+ if f.count(os.sep) - d.count(os.sep) > 3 or os.path.getsize(f) <= os.path.getsize(g) or not is_program(f): continue
+ if os.path.splitext(n)[0] == stem or n.encode() in raw or n.encode('utf-16le') in raw:
+ if not best or os.path.getsize(f) > os.path.getsize(best): best = f
+ return (best, []) if best else None
pick = None
if os.path.isdir(src): out = src
else:
@@ -52,7 +88,10 @@ def sections(f):
if pick: e = [x for x in e if x[1] == pick] or [(0, pick, pe(pick))]
if not e: sys.exit('no Windows program found')
if '.bind' in sections(e[0][1]): sys.exit("the game's program is locked by Steam's DRM (SteamStub), which DAISY cannot rewrite")
-_, g, b = e[0]; f = os.path.dirname(g); top = f; eng = ''
+_, g, b = e[0]; f = os.path.dirname(g); top = f; eng = ''; args = []; launcher = ''
+if b == 32 and (lr := launched(g)): # the program the launcher runs; the launcher's folder stays the game's
+ launcher = os.path.basename(g); g, args = lr
+exe = os.path.relpath(g, f)
if f.replace('\\', '/').endswith('Binaries/Win64'): top = os.path.dirname(os.path.dirname(os.path.dirname(f))); eng = 'Unreal'
elif os.path.exists(f + '/UnityPlayer.dll'): eng = 'Unity IL2CPP' if os.path.exists(f + '/GameAssembly.dll') else 'Unity Mono (makes code while running: not supported)'
-print(json.dumps(dict(folder=f, exe=os.path.basename(g), bits=b, top=top, engine=eng, anticheat=anticheat.found(top), offline=bool(anticheat.found(top)))))
+print(json.dumps(dict(folder=f, exe=exe, bits=b, top=top, engine=eng, args=','.join(args), launcher=launcher, anticheat=anticheat.found(top), offline=bool(anticheat.found(top)))))
diff --git a/tools/missing32.py b/tools/missing32.py
new file mode 100644
index 0000000..5649680
--- /dev/null
+++ b/tools/missing32.py
@@ -0,0 +1,79 @@
+# missing32.py [dll ...] [--binary ]: the Windows functions a 32-bit program and its own libraries import that
+# DAISY's runtime does not implement (runtime/*: NATIVE, CDECL and NATIVE_ORD). A call to one stops the program with
+# "game called unimplemented !", so this lists, before a run, what a conversion still lacks.
+# Functions fetched with GetProcAddress at run time are not imports and are not seen here.
+import sys; sys.dont_write_bytecode = True
+import os, re, struct
+HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+sys.path.insert(0, HERE); sys.path.insert(0, os.path.join(HERE, 'tools'))
+from pe2mac.rewrite import PE
+from build import find, auto_modules
+
+def imports(p):
+ pe = PE(p); out = {}; rva = pe.dirs[1][0]
+ while rva:
+ oft, _, _, nm, ft = struct.unpack_from(' [--zip]
+# Makes a converted game portable: a folder holding the .app beside the game's own files, which can be copied to
+# another Mac (Apple silicon with Rosetta, or Intel) or an external drive and run from there.
+#
+# An installed app names the folder with its files (game data, saves, learned shaders, registry) in
+# Contents/Resources/daisy-root, under ~/Library/Application Support/DAISY/Games/. Without that file the
+# runtime looks for them next to the .app (runtime/loader.c), so the portable form is:
+# //.app (no daisy-root)
+# //data, learn, Documents and Settings, registry.txt, ...
+# Saves and settings then live in that folder too, so it must be writable where it is run.
+# registry.txt holds what the game keeps in the registry, CD keys included: share the folder only with whom may have them.
+# The app is signed ad hoc (no Apple identity): on another Mac, open it the first time with right-click > Open, or
+# remove the quarantine flag (xattr -dr com.apple.quarantine ).
+set -euo pipefail
+[ $# -ge 2 ] || { sed -n '2,3p' "$0"; exit 64; }
+APP="${1%/}"; DEST="${2%/}"; ZIP="${3:-}"
+[ -d "$APP/Contents/MacOS" ] || { echo "not an app: $APP" >&2; exit 1; }
+ROOTF="$APP/Contents/Resources/daisy-root"
+[ -f "$ROOTF" ] || { echo "$APP has no daisy-root: it is already portable (its files sit next to it)" >&2; exit 1; }
+ROOT="$(head -n 1 "$ROOTF")"
+[ -d "$ROOT/data" ] || { echo "the game's files are missing: $ROOT/data" >&2; exit 1; }
+TITLE="$(basename "$APP" .app)"; OUT="$DEST/$TITLE"
+[ -e "$OUT" ] && { echo "already exists: $OUT" >&2; exit 1; }
+
+need=$(du -sk "$ROOT" "$APP" | awk '{s += $1} END {print s}')
+mkdir -p "$DEST"; free=$(df -k "$DEST" | awk 'NR == 2 {print $4}')
+[ "$free" -gt "$need" ] || { echo "not enough space in $DEST: need $((need / 1048576)) GB, $((free / 1048576)) GB free" >&2; exit 1; }
+
+echo "packing $TITLE ($((need / 1048576)) GB) into $OUT"
+mkdir -p "$OUT"
+# the game's files: everything in its folder but the converter's own logs
+rsync -a --info=progress2 --exclude 'build*.log' "$ROOT/" "$OUT/" 2>/dev/null || rsync -a --exclude 'build*.log' "$ROOT/" "$OUT/"
+ditto "$APP" "$OUT/$TITLE.app"
+rm -f "$OUT/$TITLE.app/Contents/Resources/daisy-root"
+codesign -s - -f --deep "$OUT/$TITLE.app" >/dev/null 2>&1 || codesign -s - -f "$OUT/$TITLE.app" >/dev/null
+cat > "$OUT/README.txt" < Open (it is not signed with an Apple identity).
+EOF
+if [ "$ZIP" = --zip ]; then
+ echo "compressing"; (cd "$DEST" && ditto -c -k --keepParent "$TITLE" "$TITLE.zip"); echo "DONE $DEST/$TITLE.zip"
+else
+ echo "DONE $OUT"
+fi
diff --git a/w64/draw.h b/w64/draw.h
index ac8bd64..86e0385 100644
--- a/w64/draw.h
+++ b/w64/draw.h
@@ -72,7 +72,7 @@ G(CreateBitmapIndirect, void *, const uint8_t *b) { int32_t v[4]; memcpy(v, b, 1
G(CreateDiscardableBitmap, void *, gdc *d, int w, int h) { return bmp(w, -h, 32); }
static uint32_t palat(const uint8_t *bi) { uint32_t sz; memcpy(&sz, bi, 4); uint32_t comp; memcpy(&comp, bi + 16, 4); return sz + (comp == 3 && sz == 40 ? 12 : 0); }
static void palget(gobj *b, const uint8_t *bi, uint32_t u) { uint32_t used; memcpy(&used, bi + 32, 4); int n = 1 << b->bpp; if (used && (int)used < n) n = used; if (u == 0) memcpy(b->pal, bi + palat(bi), 4u * n); }
-G(CreateDIBSection, void *, void *d, const uint8_t *bi, uint32_t u, void **bits, void *s, uint32_t o) { int32_t w, h; uint16_t bp; memcpy(&w, bi + 4, 4); memcpy(&h, bi + 8, 4); memcpy(&bp, bi + 14, 2); gobj *b = bmp(w, h, bp); if (bp <= 8) palget(b, bi, u); if (bits) *bits = b->bits; return b; }
+G(CreateDIBSection, void *, void *d, const uint8_t *bi, uint32_t u, void **bits, void *s, uint32_t o) { int32_t w, h; uint16_t bp; memcpy(&w, bi + 4, 4); memcpy(&h, bi + 8, 4); memcpy(&bp, bi + 14, 2); gobj *b = bmp(w, h, bp); if (bp <= 8) palget(b, bi, u); if (bits) *bits = b->bits; if (getenv("W64_TRACE")) fprintf(stderr, "w64: CreateDIBSection %dx%d %d bpp compression %u\n", w, h, bp, *(uint32_t *)(bi + 16)); return b; }
G(SelectObject, void *, gdc *d, gobj *o) { if (!OK(d) || d->kind != 9 || !OK(o)) return 0; gobj *p = 0; switch (o->kind) { case 1: p = d->bmp; d->bmp = o; return p ? p : w64_stock(15); case 4: p = d->font; d->font = o; return p ? p : w64_stock(13); case 2: p = d->br; d->br = o; return p; case 5: p = d->pen; d->pen = o; return p; case 6: w64_rg_free(d->clip); d->clip = w64_rg_op(o, 0, 5); for (int i = 0; i < d->clip->nr; i++) { d->clip->rr[4*i] += d->ox; d->clip->rr[4*i+2] += d->ox; d->clip->rr[4*i+1] += d->oy; d->clip->rr[4*i+3] += d->oy; } reff(d); return (void *)2; } return w64_stock(15); }
G(SelectClipRgn, int, gdc *d, gobj *o) { if (!OK(d)) return 0; if (o) { w_gdi32_SelectObject(d, o); return rkind(o); } w64_rg_free(d->clip); d->clip = 0; reff(d); return 2; }
static int cliprect(gdc *d, int a, int b, int c, int e, int m) { int32_t r[4] = {a + DX(d), b + DY(d), c + DX(d), e + DY(d)}; gobj *q = w64_rg(1, r); int32_t all[4] = {-32768, -32768, 32767, 32767}; gobj *base = d->clip ? d->clip : w64_rg(1, all); d->clip = w64_rg_op(base, q, m); w64_rg_free(base); w64_rg_free(q); reff(d); return rkind(d->eff); }
@@ -182,10 +182,25 @@ void w64_surface_dirty(void *w) { for (int i = 0; i < 128; i++) if (w && g_srf[i
void w64_surface_flush(void) { uint64_t t = clock_gettime_nsec_np(CLOCK_UPTIME_RAW); for (int i = 0; i < 128; i++) if (g_srf[i].w && g_srf[i].dirty && t - g_srf[i].last > 12000000) show(i); }
void w64_surface_gone(void *w) { for (int i = 0; i < 128; i++) if (w && g_srf[i].w == w) { g_srf[i].w = 0; free(g_srf[i].px); g_srf[i].px = 0; g_srf[i].dirty = 0; } }
/* ---- lines, shapes and text on Core Graphics */
-static CGContextRef cg(gdc *d, tgt *t) { gobj *b = t->real; if (b->bpp != 32) return 0; int H = abs(b->h); CGColorSpaceRef cs = CGColorSpaceCreateDeviceRGB(); CGContextRef c = CGBitmapContextCreate(b->bits, b->w, H, 8, b->stride, cs, kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Little); CGColorSpaceRelease(cs); if (!c) return 0; if (b->h < 0) { CGContextTranslateCTM(c, 0, H); CGContextScaleCTM(c, 1, -1); } if (d->eff) { CGRect *q = malloc(sizeof *q * (d->eff->nr + 1)); for (int i = 0; i < d->eff->nr; i++) { int32_t *r = d->eff->rr + 4 * i; q[i] = CGRectMake(r[0], r[1], r[2] - r[0], r[3] - r[1]); } if (d->eff->nr) CGContextClipToRects(c, q, d->eff->nr); else CGContextClipToRect(c, CGRectZero); free(q); } CGContextTranslateCTM(c, DX(d), DY(d)); return c; }
+/* CoreGraphics draws only into 32-bit pixels: a 24- or 16-bit (5-5-5) bitmap is drawn through a 32-bit copy that cgdone
+ converts back (a game's glyph cache: C&C 3 renders each character into a 24-bit DIB and reads its pixels) */
+static __thread struct { gobj *b; uint8_t *px; } g_sh;
+static void sh_copy(gobj *b, uint8_t *px, int out) {
+ int W = abs(b->w), H = abs(b->h);
+ for (int y = 0; y < H; y++) { uint8_t *s = b->bits + (size_t)y * b->stride, *q = px + (size_t)y * W * 4;
+ for (int x = 0; x < W; x++, q += 4) {
+ if (b->bpp == 24) { if (out) { s[3 * x] = q[0]; s[3 * x + 1] = q[1]; s[3 * x + 2] = q[2]; } else { q[0] = s[3 * x]; q[1] = s[3 * x + 1]; q[2] = s[3 * x + 2]; q[3] = 255; } }
+ else { uint16_t *v = (uint16_t *)s + x;
+ if (out) *v = (uint16_t)((q[2] >> 3) << 10 | (q[1] >> 3) << 5 | q[0] >> 3);
+ else { q[0] = (*v & 31) * 255 / 31; q[1] = (*v >> 5 & 31) * 255 / 31; q[2] = (*v >> 10 & 31) * 255 / 31; q[3] = 255; } } } }
+}
+static void cgdone(CGContextRef c) { CGContextRelease(c); if (g_sh.b) { sh_copy(g_sh.b, g_sh.px, 1); free(g_sh.px); g_sh.b = 0; } }
+static CGContextRef cg(gdc *d, tgt *t) { gobj *b = t->real; if (b->bpp != 32 && b->bpp != 24 && b->bpp != 16) return 0; int H = abs(b->h); uint8_t *bits = b->bits; size_t stride = b->stride;
+ if (b->bpp != 32) { if (g_sh.b) { sh_copy(g_sh.b, g_sh.px, 1); free(g_sh.px); g_sh.b = 0; } bits = malloc((size_t)abs(b->w) * H * 4); if (!bits) return 0; sh_copy(b, bits, 0); g_sh.b = b; g_sh.px = bits; stride = (size_t)abs(b->w) * 4; }
+ CGColorSpaceRef cs = CGColorSpaceCreateDeviceRGB(); CGContextRef c = CGBitmapContextCreate(bits, abs(b->w), H, 8, stride, cs, kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Little); CGColorSpaceRelease(cs); if (!c) return 0; if (b->h < 0) { CGContextTranslateCTM(c, 0, H); CGContextScaleCTM(c, 1, -1); } if (d->eff) { CGRect *q = malloc(sizeof *q * (d->eff->nr + 1)); for (int i = 0; i < d->eff->nr; i++) { int32_t *r = d->eff->rr + 4 * i; q[i] = CGRectMake(r[0], r[1], r[2] - r[0], r[3] - r[1]); } if (d->eff->nr) CGContextClipToRects(c, q, d->eff->nr); else CGContextClipToRect(c, CGRectZero); free(q); } CGContextTranslateCTM(c, DX(d), DY(d)); return c; }
static uint32_t pencol(gdc *d) { gobj *p = d->pen; return p->style == 100 ? d->dcp : p->color; }
void w64_line(gdc *d, int x0, int y0, int x1, int y1, uint32_t c) { int dx = abs(x1 - x0), dy = abs(y1 - y0); gobj b = {2}; b.color = c; if (!dy) { w64_rop_fill(d, x1 < x0 ? x1 + 1 : x0, y0, dx, 1, &b, 0xf00021); return; } if (!dx) { w64_rop_fill(d, x0, y1 < y0 ? y1 + 1 : y0, 1, dy, &b, 0xf00021); return; } int sx = x0 < x1 ? 1 : -1, sy = y0 < y1 ? 1 : -1, e = dx - dy; while (x0 != x1 || y0 != y1) { w64_rop_fill(d, x0, y0, 1, 1, &b, 0xf00021); int e2 = 2 * e; if (e2 > -dy) { e -= dy; x0 += sx; } if (e2 < dx) { e += dx; y0 += sy; } } }
-static void seg(gdc *d, int x0, int y0, int x1, int y1) { gobj *p = d->pen; if (!OK(p) || p->style == 5) return; if (p->w > 1) { tgt t; if (!tg(d, &t)) return; CGContextRef c = cg(d, &t); if (!c) return; uint32_t k = pencol(d); CGContextSetRGBStrokeColor(c, (k & 255) / 255., (k >> 8 & 255) / 255., (k >> 16 & 255) / 255., 1); CGContextSetLineWidth(c, p->w); CGContextMoveToPoint(c, x0 + .5, y0 + .5); CGContextAddLineToPoint(c, x1 + .5, y1 + .5); CGContextStrokePath(c); CGContextRelease(c); return; }
+static void seg(gdc *d, int x0, int y0, int x1, int y1) { gobj *p = d->pen; if (!OK(p) || p->style == 5) return; if (p->w > 1) { tgt t; if (!tg(d, &t)) return; CGContextRef c = cg(d, &t); if (!c) return; uint32_t k = pencol(d); CGContextSetRGBStrokeColor(c, (k & 255) / 255., (k >> 8 & 255) / 255., (k >> 16 & 255) / 255., 1); CGContextSetLineWidth(c, p->w); CGContextMoveToPoint(c, x0 + .5, y0 + .5); CGContextAddLineToPoint(c, x1 + .5, y1 + .5); CGContextStrokePath(c); cgdone(c); return; }
if (p->style >= 1 && p->style <= 4 && (x0 == x1 || y0 == y1)) { int n = abs(x1 - x0) + abs(y1 - y0), sx = x1 > x0 ? 1 : x1 < x0 ? -1 : 0, sy = y1 > y0 ? 1 : y1 < y0 ? -1 : 0, per = p->style == 2 ? 3 : 6; for (int i = 0; i < n; i++) if (i % per < (p->style == 2 ? 1 : 4)) w_gdi32_SetPixel(d, x0 + i * sx, y0 + i * sy, pencol(d)); return; }
if (d->rop == 6 || d->rop == 7 || d->rop == 10) { gobj b = {2}; b.color = pencol(d); w64_rop_fill(d, rmin(x0, x1), rmin(y0, y1), abs(x1 - x0) ? abs(x1 - x0) : 1, abs(y1 - y0) ? abs(y1 - y0) : 1, &b, d->rop == 7 ? 0x5a0049 : d->rop == 6 ? 0x550009 : 0xa50065); return; } w64_line(d, x0, y0, x1, y1, pencol(d)); }
G(MoveToEx, int, gdc *d, int x, int y, int32_t *o) { if (!OK(d)) return 0; if (o) { o[0] = d->x; o[1] = d->y; } d->x = x; d->y = y; return 1; }
@@ -193,7 +208,7 @@ G(LineTo, int, gdc *d, int x, int y) { if (!OK(d)) return 0; seg(d, d->x, d->y,
G(GetCurrentPositionEx, int, gdc *d, int32_t *o) { o[0] = d->x; o[1] = d->y; return 1; }
G(Polyline, int, gdc *d, const int32_t *p, int n) { for (int i = 0; i + 1 < n; i++) seg(d, p[2*i], p[2*i+1], p[2*i+2], p[2*i+3]); return 1; }
G(PolylineTo, int, gdc *d, const int32_t *p, int n) { for (int i = 0; i < n; i++) w_gdi32_LineTo(d, p[2*i], p[2*i+1]); return 1; }
-static void shape(gdc *d, CGPathRef path) { tgt t; if (!tg(d, &t)) return; CGContextRef c = cg(d, &t); if (!c) return; if (OK(d->br) && d->br->kind == 2 && d->br->style != 1) { uint32_t k = d->br->style == 100 ? d->dcb : d->br->color; CGContextSetRGBFillColor(c, (k & 255) / 255., (k >> 8 & 255) / 255., (k >> 16 & 255) / 255., 1); CGContextAddPath(c, path); CGContextEOFillPath(c); } if (OK(d->pen) && d->pen->style != 5) { uint32_t k = pencol(d); CGContextSetRGBStrokeColor(c, (k & 255) / 255., (k >> 8 & 255) / 255., (k >> 16 & 255) / 255., 1); CGContextSetLineWidth(c, d->pen->w > 1 ? d->pen->w : 1); CGContextAddPath(c, path); CGContextStrokePath(c); } CGContextRelease(c); CGPathRelease(path); }
+static void shape(gdc *d, CGPathRef path) { tgt t; if (!tg(d, &t)) return; CGContextRef c = cg(d, &t); if (!c) return; if (OK(d->br) && d->br->kind == 2 && d->br->style != 1) { uint32_t k = d->br->style == 100 ? d->dcb : d->br->color; CGContextSetRGBFillColor(c, (k & 255) / 255., (k >> 8 & 255) / 255., (k >> 16 & 255) / 255., 1); CGContextAddPath(c, path); CGContextEOFillPath(c); } if (OK(d->pen) && d->pen->style != 5) { uint32_t k = pencol(d); CGContextSetRGBStrokeColor(c, (k & 255) / 255., (k >> 8 & 255) / 255., (k >> 16 & 255) / 255., 1); CGContextSetLineWidth(c, d->pen->w > 1 ? d->pen->w : 1); CGContextAddPath(c, path); CGContextStrokePath(c); } cgdone(c); CGPathRelease(path); }
G(Polygon, int, gdc *d, const int32_t *p, int n) { if (!OK(d) || n < 2) return 0; CGMutablePathRef q = CGPathCreateMutable(); for (int i = 0; i < n; i++) if (i) CGPathAddLineToPoint(q, 0, p[2*i] + .5, p[2*i+1] + .5); else CGPathMoveToPoint(q, 0, p[0] + .5, p[1] + .5); CGPathCloseSubpath(q); shape(d, q); return 1; }
G(Ellipse, int, gdc *d, int a, int b, int c, int e) { if (!OK(d)) return 0; shape(d, CGPathCreateWithEllipseInRect(CGRectMake(a + .5, b + .5, c - a - 1, e - b - 1), 0)); return 1; }
G(RoundRect, int, gdc *d, int a, int b, int c, int e, int w, int h) { if (!OK(d)) return 0; double rw = w / 2., rh = h / 2., W = c - a - 1, H = e - b - 1; if (rw > W / 2) rw = W / 2; if (rh > H / 2) rh = H / 2; if (W < 1 || H < 1) return 1; shape(d, CGPathCreateWithRoundedRect(CGRectMake(a + .5, b + .5, W, H), rw, rh, 0)); return 1; }
@@ -203,7 +218,7 @@ static int text(gdc *d, int x, int y, uint32_t fl, const int32_t *rc, const uint
if (d->bkmode == 2 && !(fl & 2)) w64_rop_fill(d, x, base - f->asc, tw, f->asc + f->desc, &bb, 0xf00021);
if (tg(d, &t)) { CGContextRef c = cg(d, &t); if (c) { if ((fl & 4) && rc) CGContextClipToRect(c, CGRectMake(rc[0], rc[1], rc[2] - rc[0], rc[3] - rc[1])); CGContextSetTextMatrix(c, CGAffineTransformMakeScale(1, -1)); CGContextSetRGBFillColor(c, (d->text & 255) / 255.0, (d->text >> 8 & 255) / 255.0, (d->text >> 16 & 255) / 255.0, 1); double X = x; int k = 0; CGGlyph *gg = malloc(n * 2); for (int i = 0; i < n; i++) { CGPoint p = CGPointMake(X, base); X += dx ? dx[fl & 0x2000 ? 2 * i : i] : adv(f, g[i]);
if (!(fl & 0x10) && !g[i] && s[i] > 127 && !(s[i] >= 0xdc00 && s[i] < 0xe000)) { int l = s[i] >= 0xd800 && s[i] < 0xdc00 && i + 1 < n ? 2 : 1; CFStringRef q = CFStringCreateWithCharacters(0, s + i, l); CTFontRef ff = CTFontCreateForString(f->ct, q, CFRangeMake(0, l)); CGGlyph fg[2] = {0}; if (ff && CTFontGetGlyphsForCharacters(ff, s + i, fg, l) && fg[0]) (p.y = -p.y, CTFontDrawGlyphs(ff, fg, &p, 1, c)); if (ff) CFRelease(ff); CFRelease(q); continue; } if (!(fl & 0x10) && s[i] < 32) continue; gg[k] = g[i]; pt[k++] = p; }
- /* CTFontDrawGlyphs places by the text matrix: positions are given in its flipped space */ for (int i = 0; i < k; i++) pt[i].y = -pt[i].y; if (k) CTFontDrawGlyphs(f->ct, gg, pt, k, c); free(gg); if (f->under) { CGContextFillRect(c, CGRectMake(x, base + 1, tw, 1)); } CGContextRelease(c); }
+ /* CTFontDrawGlyphs places by the text matrix: positions are given in its flipped space */ for (int i = 0; i < k; i++) pt[i].y = -pt[i].y; if (k) CTFontDrawGlyphs(f->ct, gg, pt, k, c); free(gg); if (f->under) { CGContextFillRect(c, CGRectMake(x, base + 1, tw, 1)); } cgdone(c); }
else if (t.real->bpp == 1) { uint8_t *a = calloc((size_t)t.real->w * abs(t.real->h), 1); CGContextRef m = CGBitmapContextCreate(a, t.real->w, abs(t.real->h), 8, t.real->w, 0, kCGImageAlphaOnly); for (int i = 0; i < n; i++) { pt[i] = CGPointMake(x + DX(d), abs(t.real->h) - base - DY(d)); x += dx ? dx[i] : adv(f, g[i]); } CTFontDrawGlyphs(f->ct, g, pt, n, m); for (int Y = 0; Y < abs(t.real->h); Y++) for (int X = 0; X < t.real->w; X++) if (a[(size_t)Y * t.real->w + X] > 127) setpix(t.real, X, Y, bgr(d->text) ? 0xffffff : 0); CGContextRelease(m); free(a); } }
free(g); free(pt); return 1; }
G(ExtTextOutW, int, gdc *d, int x, int y, uint32_t fl, const int32_t *rc, const uint16_t *s, uint32_t n, const int32_t *dx) { return text(d, x, y, fl, rc, s, n, dx); }
diff --git a/w64/menu.h b/w64/menu.h
index fbeba55..dfab2ed 100644
--- a/w64/menu.h
+++ b/w64/menu.h
@@ -31,7 +31,73 @@ U(LookupIconIdFromDirectoryEx, int, const uint8_t *g, int ic, int x, int y, uint
W64(shell32, ExtractIconExW, uint32_t, const uint16_t *f, int i, void **l, void **s, uint32_t n) { return 0; }
/* ---- cursors */
static void *g_curs = (void *)32512;
-U(SetCursor, void *, void *c) { void *o = g_curs; if (c == o) return o; g_curs = c; uint64_t k = (uint64_t)c; if (!k || k > 0x10000) k = 32512; on_main(^{ NSCursor *q = k == 32513 ? [NSCursor IBeamCursor] : k == 32515 ? [NSCursor crosshairCursor] : k == 32649 ? [NSCursor pointingHandCursor] : k == 32644 ? [NSCursor resizeLeftRightCursor] : k == 32645 ? [NSCursor resizeUpDownCursor] : k == 32648 ? [NSCursor operationNotAllowedCursor] : k == 32646 ? [NSCursor openHandCursor] : [NSCursor arrowCursor]; [q set]; }); return o; }
+/* A program's own cursors, from .cur/.ico files and animated .ani files (LoadCursorFromFile): each frame an NSCursor
+ with the file's hotspot, shown at the size Windows shows it (its pixels as points); an animated one steps through
+ its frames at the file's rate (1/60 s units) on the main thread while it is the cursor. */
+#define CURMAGIC 0x43555231u
+typedef struct { uint32_t magic; int n; uint32_t jif[128]; void *cur[128]; } filecur;
+static filecur *g_anim; static dispatch_source_t g_animt; static int g_animi;
+static void *nscur(gobj *ic, int hx, int hy) {
+ if (!ic || !ic->px || ic->w <= 0 || ic->h <= 0) return 0;
+ int w = ic->w, h = abs(ic->h);
+ NSBitmapImageRep *r = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:0 pixelsWide:w pixelsHigh:h bitsPerSample:8 samplesPerPixel:4 hasAlpha:YES isPlanar:NO colorSpaceName:NSDeviceRGBColorSpace bytesPerRow:w * 4 bitsPerPixel:32];
+ uint8_t *d = r.bitmapData; for (int i = 0; i < w * h; i++) { uint32_t v = ic->px[i]; d[4*i] = v >> 16; d[4*i+1] = v >> 8; d[4*i+2] = v; d[4*i+3] = v >> 24; }
+ NSImage *im = [[NSImage alloc] initWithSize:NSMakeSize(w, h)]; [im addRepresentation:r];
+ NSCursor *c = [[NSCursor alloc] initWithImage:im hotSpot:NSMakePoint(hx < w ? hx : 0, hy < h ? hy : 0)];
+ return (void *)CFBridgingRetain(c);
+}
+static void *curfile(const uint8_t *d, uint32_t n) { /* an ICONDIR (.cur, .ico): the largest image up to 64 */
+ if (n < 22 || d[0] || d[1] || (d[2] != 1 && d[2] != 2)) return 0;
+ int cnt = d[4] | d[5] << 8, best = -1, bw = 0;
+ for (int i = 0; i < cnt && 6 + 16 * (i + 1) <= (int)n; i++) { const uint8_t *e = d + 6 + 16 * i; int w = e[0] ? e[0] : 256; if (w <= 64 && w > bw) { bw = w; best = i; } }
+ if (best < 0) best = 0;
+ const uint8_t *e = d + 6 + 16 * best; uint32_t sz, off; memcpy(&sz, e + 8, 4); memcpy(&off, e + 12, 4);
+ if (off >= n || sz > n - off) return 0;
+ gobj *ic = w64_icon(d + off, sz); if (!ic) return 0;
+ int hx = d[2] == 2 ? (e[4] | e[5] << 8) : ic->w / 2, hy = d[2] == 2 ? (e[6] | e[7] << 8) : abs(ic->h) / 2;
+ return nscur(ic, hx, hy); /* the decoded image stays (a few KB per cursor file, loaded once) */
+}
+void *w64_cursor_file(const uint8_t *d, uint32_t n) {
+ __block filecur *fc = 0;
+ on_main(^{ @autoreleasepool {
+ if (n >= 12 && !memcmp(d, "RIFF", 4) && !memcmp(d + 8, "ACON", 4)) { /* .ani */
+ void *fr[128]; int nf = 0, ns = 0; uint32_t rate60 = 6, *rate = 0, *seq = 0, nrate = 0, nseq = 0;
+ for (uint32_t o = 12; o + 8 <= n;) {
+ uint32_t sz; memcpy(&sz, d + o + 4, 4); if (sz > n - o - 8) sz = n - o - 8;
+ const uint8_t *c = d + o + 8;
+ if (!memcmp(d + o, "anih", 4) && sz >= 36) { memcpy(&ns, c + 8, 4); memcpy(&rate60, c + 28, 4); }
+ else if (!memcmp(d + o, "rate", 4)) { rate = (uint32_t *)c; nrate = sz / 4; }
+ else if (!memcmp(d + o, "seq ", 4)) { seq = (uint32_t *)c; nseq = sz / 4; }
+ else if (!memcmp(d + o, "LIST", 4) && sz >= 4 && !memcmp(c, "fram", 4))
+ for (uint32_t q = 4; q + 8 <= sz && nf < 128;) { uint32_t isz; memcpy(&isz, c + q + 4, 4); if (isz > sz - q - 8) isz = sz - q - 8;
+ if (!memcmp(c + q, "icon", 4)) fr[nf++] = curfile(c + q + 8, isz); q += 8 + isz + (isz & 1); }
+ o += 8 + sz + (sz & 1);
+ }
+ if (!nf) return;
+ if (ns <= 0 || ns > 128) ns = nf;
+ fc = calloc(1, sizeof *fc); fc->magic = CURMAGIC; fc->n = ns;
+ for (int i = 0; i < ns; i++) { uint32_t k = seq && (uint32_t)i < nseq ? seq[i] : (uint32_t)i; if ((int)k >= nf) k = 0;
+ fc->cur[i] = fr[k] ? (void *)CFBridgingRetain((__bridge id)fr[k]) : 0; fc->jif[i] = rate && (uint32_t)i < nrate ? rate[i] : rate60; if (!fc->jif[i]) fc->jif[i] = 6; }
+ for (int i = 0; i < nf; i++) if (fr[i]) CFRelease(fr[i]);
+ } else { void *c = curfile(d, n); if (!c) return; fc = calloc(1, sizeof *fc); fc->magic = CURMAGIC; fc->n = 1; fc->cur[0] = c; fc->jif[0] = 6; }
+ } });
+ return fc;
+}
+static void anim_stop(void) { if (g_animt) { dispatch_source_cancel(g_animt); g_animt = 0; } g_anim = 0; }
+static void anim_step(void) { /* main thread */
+ filecur *f = g_anim; if (!f) return;
+ g_animi = (g_animi + 1) % f->n; if (f->cur[g_animi]) [(__bridge NSCursor *)f->cur[g_animi] set];
+ dispatch_source_set_timer(g_animt, dispatch_time(DISPATCH_TIME_NOW, (int64_t)f->jif[g_animi] * NSEC_PER_SEC / 60), DISPATCH_TIME_FOREVER, NSEC_PER_MSEC);
+}
+U(SetCursor, void *, void *c) { void *o = g_curs; if (c == o) return o; g_curs = c;
+ filecur *fc = (uint64_t)c > 0x10000 && ((filecur *)c)->magic == CURMAGIC ? c : 0;
+ if (fc) { on_main(^{ anim_stop(); g_animi = 0; if (fc->cur[0]) [(__bridge NSCursor *)fc->cur[0] set];
+ if (fc->n > 1) { g_anim = fc; g_animt = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
+ dispatch_source_set_event_handler(g_animt, ^{ anim_step(); });
+ dispatch_source_set_timer(g_animt, dispatch_time(DISPATCH_TIME_NOW, (int64_t)fc->jif[0] * NSEC_PER_SEC / 60), DISPATCH_TIME_FOREVER, NSEC_PER_MSEC);
+ dispatch_resume(g_animt); } }); return o; }
+ on_main(^{ anim_stop(); });
+ uint64_t k = (uint64_t)c; if (!k || k > 0x10000) k = 32512; on_main(^{ NSCursor *q = k == 32513 ? [NSCursor IBeamCursor] : k == 32515 ? [NSCursor crosshairCursor] : k == 32649 ? [NSCursor pointingHandCursor] : k == 32644 ? [NSCursor resizeLeftRightCursor] : k == 32645 ? [NSCursor resizeUpDownCursor] : k == 32648 ? [NSCursor operationNotAllowedCursor] : k == 32646 ? [NSCursor openHandCursor] : [NSCursor arrowCursor]; [q set]; }); return o; }
U(GetCursor, void *, void) { return g_curs; }
U(LoadCursorW, void *, void *m, const uint16_t *n) { return !m && (uint64_t)n < 0x10000 ? (void *)n : (void *)32512; }
U(LoadCursorA, void *, void *m, const char *n) { return !m && (uint64_t)n < 0x10000 ? (void *)n : (void *)32512; }
@@ -185,7 +251,7 @@ W64(comctl32, CreateStatusWindowW, void *, int st, const uint16_t *t, void *h, u
W64(comctl32, PropertySheetW, int64_t, void *p) { fprintf(stderr, "w64: property sheet not built\n"); return -1; }
/* ---- the rest of a desktop program's needs */
U(SendInput, uint32_t, uint32_t n, void *p, int s) { return n; } U(mouse_event, void, uint32_t f, uint32_t x, uint32_t y, uint32_t d, uint64_t e) {} U(keybd_event, void, uint8_t k, uint8_t s, uint32_t f, uint64_t e) {}
-U(GetMessagePos, uint32_t, void) { NSPoint m = [NSEvent mouseLocation]; return ((uint32_t)(uint16_t)(w64_screen().height - m.y)) << 16 | (uint16_t)m.x; }
+U(GetMessagePos, uint32_t, void) { int32_t q[2]; w_user32_GetCursorPos(q); return ((uint32_t)(uint16_t)q[1]) << 16 | (uint16_t)q[0]; } /* GetCursorPos: in exclusive fullscreen, the mode's coordinates */
U(CloseWindow, int, void *h) { return w_user32_ShowWindow(h, 6); } U(OpenIcon, int, void *h) { return w_user32_ShowWindow(h, 9); } U(GetShellWindow, void *, void) { return 0; } U(IsMenuChar, int, void) { return 0; } U(DragDetect, int, void *w, uint64_t p) { return 0; } U(GetKeyNameTextW, int, int l, uint16_t *o, int n) { uint32_t sc = l >> 16 & 255; int v = 0; for (int i = 0; i < 128; i++) if ((km[i][1] & 0xff) == sc) v = km[i][0]; if (n > 1 && v > 32 && v < 127) { o[0] = v; o[1] = 0; return 1; } if (n) o[0] = 0; return 0; }
W64(comdlg32, ChooseColorW, int, uint8_t *p) { __block int ok = 0; __block uint32_t c = I32(p, 24); on_main(^{ NSColorPanel *cp = [NSColorPanel sharedColorPanel]; cp.color = [NSColor colorWithDeviceRed:(c & 255) / 255. green:(c >> 8 & 255) / 255. blue:(c >> 16 & 255) / 255. alpha:1]; NSAlert *al = [NSAlert new]; al.messageText = @"Pick a color"; [al addButtonWithTitle:@"OK"]; [al addButtonWithTitle:@"Cancel"]; NSColorWell *cw = [[NSColorWell alloc] initWithFrame:NSMakeRect(0, 0, 120, 32)]; cw.color = cp.color; al.accessoryView = cw; if ([al runModal] == NSAlertFirstButtonReturn) { NSColor *q = [cw.color colorUsingColorSpace:[NSColorSpace deviceRGBColorSpace]]; c = (uint32_t)lround(q.redComponent * 255) | (uint32_t)lround(q.greenComponent * 255) << 8 | (uint32_t)lround(q.blueComponent * 255) << 16; ok = 1; } [cp orderOut:nil]; }); if (ok) I32(p, 24) = c; return ok; }
W64(comdlg32, PrintDlgW, int, void *p) { return 0; } W64(comdlg32, PrintDlgExW, uint32_t, void *p) { return 0x80004001u; } W64(comdlg32, PageSetupDlgW, int, void *p) { return 0; } W64(comdlg32, CommDlgExtendedError, uint32_t, void) { return 0; } W64(comdlg32, ChooseFontW, int, void *p) { return 0; }
diff --git a/w64/user32.m b/w64/user32.m
index 5ef1c00..a0ca6d0 100644
--- a/w64/user32.m
+++ b/w64/user32.m
@@ -9,7 +9,7 @@
typedef WINAPI64 int64_t (*wndproc)(void *, uint32_t, uint64_t, int64_t);
typedef struct { void *h; uint32_t m, pad; uint64_t w; int64_t l; uint32_t t; int32_t x, y; } msg64;
typedef struct { int min, max, page, pos, track, drag; } sbar; struct gobj; struct gdc;
-typedef struct w64win { uint32_t magic; NSWindow *win; wndproc proc; uint32_t style, ex, cs; char cls[64]; int shown; uint32_t tid; int msgonly; struct w64win *parent, *owner, *kid, *next, *lastf; int rx, ry, rw, rh; uint16_t *t16; uint64_t id; void *inst; uint8_t *xb; int nx, klass, ansi; int64_t ud; struct gobj *br; struct gobj *font; struct gdc *ownDC; int dirty, erase, ncdirty, whole, dying, clear, trk, extra, cblis; int32_t dr[4]; sbar sb[2]; int sbon[2]; void *ctl; struct hm *menu; void *subs, *subold; } w64win;
+typedef struct w64win { uint32_t magic; NSWindow *win; wndproc proc; uint32_t style, ex, cs; char cls[64]; int shown; uint32_t tid; int msgonly; struct w64win *parent, *owner, *kid, *next, *lastf; int rx, ry, rw, rh; uint16_t *t16; uint64_t id; void *inst; uint8_t *xb; int nx, klass, ansi; int64_t ud; struct gobj *br; struct gobj *font; struct gdc *ownDC; int dirty, erase, ncdirty, whole, dying, clear, trk, extra, cblis; int32_t dr[4]; sbar sb[2]; int sbon[2]; void *ctl; struct hm *menu; void *subs, *subold; int fs, fsx, fsy, fsw, fsh; int iconic; } w64win; /* fs: exclusive fullscreen, the Mac frame it had; iconic: minimised as Windows does an inactive fullscreen window */
#define NWIN 8192
#include
#include
@@ -48,15 +48,22 @@ - (BOOL)windowShouldClose:(id)s { post(w, 0x10, 0, 0); return NO; }
- (void)windowDidBecomeKey:(id)n { void w64_bar(w64win *); w64_bar(w); post(w, 0x7fe0, 0, 0); }
- (void)quitw:(id)s { post(w, 0x10, 0, 0); }
- (void)windowDidResignKey:(id)n { memset(g_key, 0, 256); post(w, 6, 0, 0); if (![NSApp isActive]) post(w, 0x1c, 0, 0); }
-- (void)moved { NSRect c = [w->win contentRectForFrameRect:w->win.frame]; int x = c.origin.x, y = w64_screen().height - c.origin.y - c.size.height; post(w, 0x7fe1, (uint64_t)(uint32_t)x << 32 | (uint32_t)y, (int64_t)((uint64_t)(uint32_t)(int)c.size.width << 32 | (uint32_t)(int)c.size.height)); }
+- (void)moved { if (w->fs) return; /* exclusive fullscreen: the window is the display at the mode's size, not its Mac frame (in points) */
+ NSRect c = [w->win contentRectForFrameRect:w->win.frame]; int x = c.origin.x, y = w64_screen().height - c.origin.y - c.size.height; post(w, 0x7fe1, (uint64_t)(uint32_t)x << 32 | (uint32_t)y, (int64_t)((uint64_t)(uint32_t)(int)c.size.width << 32 | (uint32_t)(int)c.size.height)); }
- (void)windowDidResize:(id)n { [self moved]; }
- (void)windowDidMove:(id)n { [self moved]; }
@end
/* Mac key code -> {virtual key, scan code}; scan bit 0x100 = extended */
static const uint16_t km[128][2] = {[0]={'A',0x1e},[1]={'S',0x1f},[2]={'D',0x20},[3]={'F',0x21},[4]={'H',0x23},[5]={'G',0x22},[6]={'Z',0x2c},[7]={'X',0x2d},[8]={'C',0x2e},[9]={'V',0x2f},[11]={'B',0x30},[12]={'Q',0x10},[13]={'W',0x11},[14]={'E',0x12},[15]={'R',0x13},[16]={'Y',0x15},[17]={'T',0x14},[18]={'1',2},[19]={'2',3},[20]={'3',4},[21]={'4',5},[22]={'6',7},[23]={'5',6},[24]={0xbb,0xd},[25]={'9',0xa},[26]={'7',8},[27]={0xbd,0xc},[28]={'8',9},[29]={'0',0xb},[30]={0xdd,0x1b},[31]={'O',0x18},[32]={'U',0x16},[33]={0xdb,0x1a},[34]={'I',0x17},[35]={'P',0x19},[36]={0xd,0x1c},[37]={'L',0x26},[38]={'J',0x24},[39]={0xde,0x28},[40]={'K',0x25},[41]={0xba,0x27},[42]={0xdc,0x2b},[43]={0xbc,0x33},[44]={0xbf,0x35},[45]={'N',0x31},[46]={'M',0x32},[47]={0xbe,0x34},[48]={9,0xf},[49]={0x20,0x39},[50]={0xc0,0x29},[51]={8,0xe},[53]={0x1b,1},[54]={0x5c,0x15c},[55]={0x5b,0x15b},[56]={0xa0,0x2a},[57]={0x14,0x3a},[58]={0xa4,0x38},[59]={0xa2,0x1d},[60]={0xa1,0x36},[61]={0xa5,0x138},[62]={0xa3,0x11d},[65]={0x6e,0x53},[67]={0x6a,0x37},[69]={0x6b,0x4e},[75]={0x6f,0x135},[76]={0xd,0x11c},[78]={0x6d,0x4a},[82]={0x60,0x52},[83]={0x61,0x4f},[84]={0x62,0x50},[85]={0x63,0x51},[86]={0x64,0x4b},[87]={0x65,0x4c},[88]={0x66,0x4d},[89]={0x67,0x47},[91]={0x68,0x48},[92]={0x69,0x49},[96]={0x74,0x3f},[97]={0x75,0x40},[98]={0x76,0x41},[99]={0x72,0x3d},[100]={0x77,0x42},[101]={0x78,0x43},[103]={0x7a,0x57},[109]={0x79,0x44},[111]={0x7b,0x58},[114]={0x2d,0x152},[115]={0x24,0x147},[116]={0x21,0x149},[117]={0x2e,0x153},[118]={0x73,0x3e},[119]={0x23,0x14f},[120]={0x71,0x3c},[121]={0x22,0x151},[122]={0x70,0x3b},[123]={0x25,0x14b},[124]={0x27,0x14d},[125]={0x28,0x150},[126]={0x26,0x148}};
static void rawpush(int kind, int dx, int dy, uint32_t btn, uint32_t wheel, uint32_t vk, uint32_t sc, int up) { if (!(g_raw & (kind ? 2 : 1))) return; uint32_t i = g_rawn++ % 256; g_rawq[i].kind = kind; g_rawq[i].dx = dx; g_rawq[i].dy = dy; g_rawq[i].btn = btn; g_rawq[i].wheel = wheel; g_rawq[i].vk = vk; g_rawq[i].scan = sc; g_rawq[i].up = up; post(g_focus, 0xff, 0, 0x1000 + i); }
-static uint8_t g_code[256]; static void keyev(w64win *w, int code, int down, int rep) { uint32_t vk = km[code & 127][0], sc = km[code & 127][1]; if (!vk) return; g_code[vk & 255] = code & 127; uint32_t g = vk >= 0xa0 && vk <= 0xa1 ? 0x10 : vk >= 0xa2 && vk <= 0xa3 ? 0x11 : vk >= 0xa4 && vk <= 0xa5 ? 0x12 : vk; g_key[vk] = g_key[g] = down ? 0x80 : 0; int sys = g == 0x12 || (g_key[0x12] && g != 0x11); rawpush(1, 0, 0, 0, 0, g, sc, !down); post(w, (sys ? 0x104 : 0x100) + !down, g, 1 | (int64_t)(sc & 0xff) << 16 | (int64_t)(sc >> 8) << 24 | (rep ? 1ll << 30 : 0) | (down ? 0 : 3ll << 30)); }
-static void mouse(w64win *w, uint32_t m, int vk, int down, uint32_t rbtn, uint64_t extra) { if (vk) g_key[vk] = down ? 0x80 : 0; uint64_t k = (g_key[1] ? 1 : 0) | (g_key[2] ? 2 : 0) | (g_key[0x10] ? 4 : 0) | (g_key[0x11] ? 8 : 0) | (g_key[4] ? 16 : 0); post(w, m, k | extra, ((int64_t)(int)g_my & 0xffff) << 16 | ((int)g_mx & 0xffff)); if (rbtn) rawpush(0, 0, 0, rbtn, (uint32_t)(extra >> 16), 0, 0, 0); }
+/* DirectInput's view of the keyboard and mouse: the 32-bit layer reads them through these (runtime/w32glue.m) */
+__attribute__((weak)) void pe2_w64_key(uint32_t sc, int down) { (void)sc; (void)down; }
+__attribute__((weak)) void pe2_w64_mouse(double dx, double dy, int dz) { (void)dx; (void)dy; (void)dz; }
+__attribute__((weak)) void pe2_w64_button(int b, int down) { (void)b; (void)down; }
+static uint8_t g_code[256]; static void keyev(w64win *w, int code, int down, int rep) { uint32_t vk = km[code & 127][0], sc = km[code & 127][1];
+ { static int lg = -1; if (lg < 0) lg = getenv("PE2_INPUTLOG") != 0; if (lg) fprintf(stderr, "w64: key mac %d -> vk %#x sc %#x %s%s to %p\n", code, vk, sc, down ? "down" : "up", rep ? " (repeat)" : "", (void *)w); }
+ if (!vk) return; if (!rep) pe2_w64_key(sc, down); g_code[vk & 255] = code & 127; uint32_t g = vk >= 0xa0 && vk <= 0xa1 ? 0x10 : vk >= 0xa2 && vk <= 0xa3 ? 0x11 : vk >= 0xa4 && vk <= 0xa5 ? 0x12 : vk; g_key[vk] = g_key[g] = down ? 0x80 : 0; int sys = g == 0x12 || (g_key[0x12] && g != 0x11); rawpush(1, 0, 0, 0, 0, g, sc, !down); post(w, (sys ? 0x104 : 0x100) + !down, g, 1 | (int64_t)(sc & 0xff) << 16 | (int64_t)(sc >> 8) << 24 | (rep ? 1ll << 30 : 0) | (down ? 0 : 3ll << 30)); }
+static void mouse(w64win *w, uint32_t m, int vk, int down, uint32_t rbtn, uint64_t extra) { if (vk) g_key[vk] = down ? 0x80 : 0; if (vk == 1 || vk == 2 || vk == 4) pe2_w64_button(vk == 1 ? 0 : vk == 2 ? 1 : 2, down); uint64_t k = (g_key[1] ? 1 : 0) | (g_key[2] ? 2 : 0) | (g_key[0x10] ? 4 : 0) | (g_key[0x11] ? 8 : 0) | (g_key[4] ? 16 : 0); post(w, m, k | extra, ((int64_t)(int)g_my & 0xffff) << 16 | ((int)g_mx & 0xffff)); if (rbtn) rawpush(0, 0, 0, rbtn, (uint32_t)(extra >> 16), 0, 0, 0); }
static void poschanged(w64win *w) { uint8_t b[40] = {0}; memcpy(b, &w, 8); int32_t v[5] = {w->rx, w->ry, w->rw, w->rh, 3}; memcpy(b + 16, v, 20); wsend(w, 0x47, 0, (int64_t)b); }
static w64win *of(NSWindow *n) { for (int i = 0; i < g_nw; i++) if (g_w[i] && g_w[i]->win == n) return g_w[i]; return 0; }
static int g_app; static unichar g_chars; static uint16_t g_typed[128];
@@ -72,28 +79,66 @@ - (void)windowDidMove:(id)n { [self moved]; }
static int g_clip, g_letgo, g_cursor_hidden; static volatile int g_owned = 1;
static void mouse_apply(void) { /* main thread */
int own = NSApp.isActive && !g_letgo; if (own != g_owned && getenv("W64_TRACE")) fprintf(stderr, "w64: mouse %s\n", own ? "taken by the game" : "given back"); g_owned = own;
- CGAssociateMouseAndMouseCursorPosition(!(own && g_clip));
+ /* the pointer is held still (motion only as raw deltas) for a game that clips the cursor and hides it (a shooter);
+ one that clips a visible cursor (a strategy game keeping it in its window) needs positions that follow the mouse */
+ CGAssociateMouseAndMouseCursorPosition(!(own && g_clip && g_hide));
int hide = own && g_hide; if (hide != g_cursor_hidden) { if (hide) [NSCursor hide]; else [NSCursor unhide]; g_cursor_hidden = hide; }
}
+static w64win *fs_window(void);
static void mouse_watch(void) { /* main thread, once */
static int once; if (once) return; once = 1; NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
- [nc addObserverForName:NSApplicationDidResignActiveNotification object:nil queue:nil usingBlock:^(NSNotification *n) { (void)n; mouse_apply(); }];
- [nc addObserverForName:NSApplicationDidBecomeActiveNotification object:nil queue:nil usingBlock:^(NSNotification *n) { (void)n; g_letgo = 0; mouse_apply(); }];
+ /* a fullscreen game hears of its activation as on Windows, from the application's: WM_ACTIVATEAPP and WM_ACTIVATE
+ follow the program going to the background and coming back (Command-Tab, another Space), whatever the key window
+ did. Sent only from the window becoming key, it could be missed on the way back: C&C 3 reset its device and then
+ drew nothing, waiting to be told it was active again */
+ [nc addObserverForName:NSApplicationDidResignActiveNotification object:nil queue:nil usingBlock:^(NSNotification *n) { (void)n; mouse_apply();
+ w64win *f = fs_window(); if (getenv("PE2_TRACE")) fprintf(stderr, "w64: application inactive%s\n", f ? " (fullscreen window told)" : "");
+ /* and, as Windows does with an exclusive-fullscreen window whose program goes to the background, it is
+ minimised (IsIconic, WM_SIZE SIZE_MINIMIZED) and restored on the way back; the Mac window itself stays. Games
+ read that as "paused": C&C 3 shows its pause menu on return */
+ { extern volatile int pe2_trace_burst __attribute__((weak)); if (&pe2_trace_burst && getenv("PE2_TRACE_BURST")) pe2_trace_burst = atoi(getenv("PE2_TRACE_BURST")); }
+ { extern void pe2_input_focus(int) __attribute__((weak)); if (pe2_input_focus) pe2_input_focus(0); }
+ if (f) { post(f, 6, 0x10000, 0); post(f, 0x1c, 0, 0); f->iconic = 1; post(f, 5, 1, 0); } }];
+ [nc addObserverForName:NSApplicationDidBecomeActiveNotification object:nil queue:nil usingBlock:^(NSNotification *n) { (void)n; g_letgo = 0; mouse_apply();
+ w64win *f = fs_window(); if (getenv("PE2_TRACE")) fprintf(stderr, "w64: application active%s\n", f ? " (fullscreen window told)" : "");
+ { extern void pe2_input_focus(int) __attribute__((weak)); if (pe2_input_focus) pe2_input_focus(1); }
+ if (f) { [f->win makeKeyAndOrderFront:nil]; if (f->iconic) { f->iconic = 0; post(f, 5, 0, (int64_t)((uint32_t)(f->rh & 0xffff) << 16 | (f->rw & 0xffff))); } post(f, 0x7fe0, 0, 0); } }];
}
+/* exclusive fullscreen (w64_fullscreen in win.h): the window's picture fills the screen at its aspect, centred; a
+ point in the Mac window (origin bottom left) becomes one in the window's own rw x rh */
+static void fs_scale(w64win *w, double *s, double *ox, double *oy) {
+ NSSize v = w->win.contentView.bounds.size; double sx = v.width / (w->rw ? w->rw : 1), sy = v.height / (w->rh ? w->rh : 1);
+ *s = sx < sy ? sx : sy; if (*s <= 0) *s = 1; *ox = (v.width - w->rw * *s) / 2; *oy = (v.height - w->rh * *s) / 2;
+}
+static void fs_map(w64win *w, NSPoint *p, double *H) {
+ double s, ox, oy; fs_scale(w, &s, &ox, &oy); p->x = (p->x - ox) / s; p->y = (p->y - oy) / s; *H = w->rh;
+ /* the black bars and the screen's edge are the display's edge: a strategy game scrolls when the cursor reaches it */
+ if (p->x < 0) p->x = 0; if (p->x > w->rw - 1) p->x = w->rw - 1; if (p->y < 1) p->y = 1; if (p->y > w->rh) p->y = w->rh;
+}
+static w64win *g_fsw; /* the window in exclusive fullscreen, if any: screen coordinates are its own */
+static w64win *fs_window(void) { return g_fsw && g_fsw->fs && g_fsw->win ? g_fsw : 0; }
static void events(int wait) {
@autoreleasepool { autoclick(); mouse_watch(); NSEvent *e; NSDate *until = wait ? [NSDate dateWithTimeIntervalSinceNow:0.5] : nil;
while ((e = [NSApp nextEventMatchingMask:NSEventMaskAny untilDate:until inMode:NSDefaultRunLoopMode dequeue:YES])) { until = nil; w64win *w = of(e.window); if (!w) w = g_focus; int fwd = 1;
if (w) { NSPoint p = e.window == w->win ? e.locationInWindow : [w->win convertPointFromScreen:[NSEvent mouseLocation]]; double H = w->win.contentView.bounds.size.height;
+ /* exclusive fullscreen: the screen shows that window, whichever window the event names (a game's device
+ window and its main window may differ), so positions are in its size */
+ { w64win *f = w->fs ? w : g_fsw && g_fsw->fs && g_fsw->win ? g_fsw : 0;
+ NSPoint raw = p, scr = [NSEvent mouseLocation];
+ if (f) { if (f != w || e.window != w->win) p = [f->win convertPointFromScreen:[NSEvent mouseLocation]]; fs_map(f, &p, &H); }
+ if (e.type == NSEventTypeLeftMouseDown && getenv("W64_TRACE")) { NSWindow *fw = f ? f->win : w->win; NSRect fr = fw.frame; NSSize vb = fw.contentView.bounds.size;
+ fprintf(stderr, "w64: click screen %.0f,%.0f in-window %.0f,%.0f | event window %p, w %p (fs %d, %dx%d), fullscreen %p (%dx%d) | frame %.0f,%.0f %.0fx%.0f view %.0fx%.0f | sent %.0f,%.0f | mode %dx%d\n",
+ scr.x, scr.y, raw.x, raw.y, (__bridge void *)e.window, (void *)w, w->fs, w->rw, w->rh, (void *)f, f ? f->rw : 0, f ? f->rh : 0, fr.origin.x, fr.origin.y, fr.size.width, fr.size.height, vb.width, vb.height, p.x, H - p.y, g_w64_mw, g_w64_mh); } }
switch (e.type) {
case NSEventTypeKeyDown: { int cmd = (e.modifierFlags & NSEventModifierFlagCommand) != 0, desk = w->kid || w->menu || w->owner; if (cmd && desk && e.keyCode != 12 && e.keyCode != 4) { g_key[0x11] = 0x80; keyev(w, e.keyCode, 1, e.isARepeat); keyev(w, e.keyCode, 0, 0); fwd = 0; } else if (!cmd) { keyev(w, e.keyCode, 1, e.isARepeat); g_chars = e.characters.length ? [e.characters characterAtIndex:0] : 0; if (desk && g_chars >= 32 && g_chars < 0xf700 && g_chars != 127 && !(e.modifierFlags & NSEventModifierFlagControl)) g_typed[e.keyCode & 127] = (uint16_t)g_chars; else g_typed[e.keyCode & 127] = 0; fwd = 0; } break; }
case NSEventTypeKeyUp: keyev(w, e.keyCode, 0, 0); fwd = 0; break;
case NSEventTypeFlagsChanged: if ((e.modifierFlags & NSEventModifierFlagCommand) && (g_clip || g_hide) && !g_letgo) { g_letgo = 1; mouse_apply(); } /* Command gives the pointer back */
{ uint32_t vk = km[e.keyCode & 127][0]; if ((vk == 0x5b || vk == 0x5c) && (w->kid || w->menu || w->owner)) { int dn = (e.modifierFlags & NSEventModifierFlagCommand) != 0; g_key[0x11] = g_key[0xa2] = dn ? 0x80 : 0; post(w, dn ? 0x100 : 0x101, 0x11, 1 | 0x1dll << 16 | (dn ? 0 : 3ll << 30)); } else if (vk) keyev(w, e.keyCode, !g_key[vk], 0); break; }
- case NSEventTypeMouseMoved: case NSEventTypeLeftMouseDragged: case NSEventTypeRightMouseDragged: case NSEventTypeOtherMouseDragged: g_mx = p.x; g_my = H - p.y; { static double fx, fy; fx += e.deltaX; fy += e.deltaY; int ix = (int)fx, iy = (int)fy; fx -= ix; fy -= iy; if (ix || iy) rawpush(0, ix, iy, 0, 0, 0, 0, 0); } mouse(w, 0x200, 0, 0, 0, 0); break;
+ case NSEventTypeMouseMoved: case NSEventTypeLeftMouseDragged: case NSEventTypeRightMouseDragged: case NSEventTypeOtherMouseDragged: g_mx = p.x; g_my = H - p.y; pe2_w64_mouse(e.deltaX, e.deltaY, 0); { static double fx, fy; fx += e.deltaX; fy += e.deltaY; int ix = (int)fx, iy = (int)fy; fx -= ix; fy -= iy; if (ix || iy) rawpush(0, ix, iy, 0, 0, 0, 0, 0); } mouse(w, 0x200, 0, 0, 0, 0); break;
case NSEventTypeLeftMouseDown: if (g_letgo) { g_letgo = 0; mouse_apply(); } /* a click in the game takes it again */
g_mx = p.x; g_my = H - p.y; mouse(w, e.clickCount == 2 ? 0x203 : 0x201, 1, 1, 1, 0); break; case NSEventTypeLeftMouseUp: g_mx = p.x; g_my = H - p.y; mouse(w, 0x202, 1, 0, 2, 0); break;
case NSEventTypeRightMouseDown: g_mx = p.x; g_my = H - p.y; mouse(w, 0x204, 2, 1, 4, 0); break; case NSEventTypeRightMouseUp: mouse(w, 0x205, 2, 0, 8, 0); break; case NSEventTypeOtherMouseDown: mouse(w, 0x207, 4, 1, 0x10, 0); break; case NSEventTypeOtherMouseUp: mouse(w, 0x208, 4, 0, 0x20, 0); break;
- case NSEventTypeScrollWheel: { int d = (int)(e.hasPreciseScrollingDeltas ? e.scrollingDeltaY * 12 : e.scrollingDeltaY * 120); g_mx = p.x; g_my = H - p.y; if (d) mouse(w, 0x20a, 0, 0, 0x400, (uint64_t)(uint16_t)d << 16); break; }
+ case NSEventTypeScrollWheel: { int d = (int)(e.hasPreciseScrollingDeltas ? e.scrollingDeltaY * 12 : e.scrollingDeltaY * 120); if (d) pe2_w64_mouse(0, 0, d); g_mx = p.x; g_my = H - p.y; if (d) mouse(w, 0x20a, 0, 0, 0x400, (uint64_t)(uint16_t)d << 16); break; }
default: break; } }
if (fwd) [NSApp sendEvent:e]; } } }
/* Core Animation sends the main thread's layer changes to the screen when the run loop goes to sleep; this loop polls for
@@ -109,9 +154,10 @@ screen and every frame presented into it was dropped (presentedTime 0). */
#define CX1 ((int)w64_screen().width)
#define CY1 ((int)w64_screen().height)
static int mine(void) { uint32_t me = self(); int r = 0; pthread_mutex_lock(&g_m); for (uint32_t i = g_qr; i != g_qw; i++) if (!g_qt[i % 4096] || g_qt[i % 4096] == me) { r = 1; break; } if (g_quit >= 0 && g_quit_t == me) r = 1; for (sreq *q = g_sr; q; q = q->next) if (q->w->tid == me) r = 1; uint64_t t = nowms(); for (int i = 0; i < 256; i++) if (g_tm[i].ms && g_tm[i].tid == me && t >= g_tm[i].due) r = 1; pthread_mutex_unlock(&g_m); return r; }
-U(TranslateMessage, int, msg64 *m) { if (m->m != 0x100 || (g_key[0x11] && !(g_key[0x12]))) { if (m->m == 0x100 && g_key[0x11] && m->w >= 'A' && m->w <= 'Z') post(m->h, 0x102, m->w - 64, m->l); return m->m == 0x100; } { uint16_t ty = g_typed[g_code[m->w & 255]]; if (ty) { post(m->h, 0x102, ty, m->l); return 1; } } uint32_t k = (uint32_t)m->w; int sh = g_key[0x10] != 0; uint32_t c = k >= 'A' && k <= 'Z' ? (sh ? k : k + 32) : k >= '0' && k <= '9' ? (sh ? ")!@#$%^&*("[k - '0'] : k) : k == 0x20 || k == 8 || k == 13 || k == 27 || k == 9 ? k : 0; if (!c) { static const char *t = "\xba;:\xbb=+\xbc,<\xbd-_\xbe.>\xbf/?\xc0`~\xdb[{\xdc\\|\xdd]}\xde'\""; for (int i = 0; t[i]; i += 3) if ((uint8_t)t[i] == k) c = t[i + 1 + sh]; } if (c) post(m->h, 0x102, c, m->l); return c != 0; }
+U(TranslateMessage, int, msg64 *m) { { static int lg = -1; if (lg < 0) lg = getenv("PE2_INPUTLOG") != 0; if (lg && (m->m == 0x100 || m->m == 0x104)) fprintf(stderr, "w64: TranslateMessage %#x vk %#llx\n", m->m, (unsigned long long)m->w); } if (m->m != 0x100 || (g_key[0x11] && !(g_key[0x12]))) { if (m->m == 0x100 && g_key[0x11] && m->w >= 'A' && m->w <= 'Z') post(m->h, 0x102, m->w - 64, m->l); return m->m == 0x100; } { uint16_t ty = g_typed[g_code[m->w & 255]]; if (ty) { post(m->h, 0x102, ty, m->l); return 1; } } uint32_t k = (uint32_t)m->w; int sh = g_key[0x10] != 0; uint32_t c = k >= 'A' && k <= 'Z' ? (sh ? k : k + 32) : k >= '0' && k <= '9' ? (sh ? ")!@#$%^&*("[k - '0'] : k) : k == 0x20 || k == 8 || k == 13 || k == 27 || k == 9 ? k : 0; if (!c) { static const char *t = "\xba;:\xbb=+\xbc,<\xbd-_\xbe.>\xbf/?\xc0`~\xdb[{\xdc\\|\xdd]}\xde'\""; for (int i = 0; t[i]; i += 3) if ((uint8_t)t[i] == k) c = t[i + 1 + sh]; } if (c) post(m->h, 0x102, c, m->l); return c != 0; }
static void *w_user32_CopyImage_(void *b, int x, int y) { WINAPI64 void *(*f)(void *, uint32_t, int, int, uint32_t) = w64_native_fn("user32.dll", "CopyImage"); return f(b, 0, x, y, 0); }
static WINAPI64 void *w_user32_SetCursor(void *);
+static WINAPI64 int w_user32_GetCursorPos(int32_t *); /* menu.h: GetMessagePos */
#include "win.h"
void w64_bar(w64win *w) { showbar(w); }
/* Windows activates a window when its program shows it; macOS may delay or refuse focus, and then no key event arrives */
@@ -119,8 +165,13 @@ screen and every frame presented into it was dropped (presentedTime 0). */
U(GetAsyncKeyState, int16_t, int k) { pump(0); return g_key[k & 255] ? (int16_t)0x8000 : 0; }
U(GetKeyState, int16_t, int k) { return g_key[k & 255] ? (int16_t)0x8000 : 0; }
U(GetKeyboardState, int, uint8_t *o) { memcpy(o, g_key, 256); return 1; }
-U(GetCursorPos, int, int32_t *p) { NSPoint m = [NSEvent mouseLocation]; p[0] = m.x; p[1] = w64_screen().height - m.y; return 1; }
-U(SetCursorPos, int, int x, int y) { { static int n; if (getenv("W64_TRACE") && n++ < 3) fprintf(stderr, "w64: SetCursorPos %d,%d owned %d\n", x, y, g_owned); } if (!g_owned) return 1; CGWarpMouseCursorPosition(CGPointMake(x, y)); return 1; }
+U(GetCursorPos, int, int32_t *p) { NSPoint m = [NSEvent mouseLocation];
+ w64win *f = g_fsw; if (f && f->fs && f->win) { __block NSPoint q; __block double H; on_main(^{ q = [f->win convertPointFromScreen:m]; H = 0; fs_map(f, &q, &H); }); p[0] = q.x; p[1] = H - q.y; return 1; } /* the display is the mode */
+ p[0] = m.x; p[1] = w64_screen().height - m.y; return 1; }
+U(SetCursorPos, int, int x, int y) { { static int n; if (getenv("W64_TRACE") && n++ < 3) fprintf(stderr, "w64: SetCursorPos %d,%d owned %d\n", x, y, g_owned); } if (!g_owned) return 1;
+ w64win *f = g_fsw; if (f && f->fs && f->win) { on_main(^{ double s, ox, oy; fs_scale(f, &s, &ox, &oy); NSRect fr = f->win.frame; double SH = NSScreen.screens.firstObject.frame.size.height;
+ CGWarpMouseCursorPosition(CGPointMake(fr.origin.x + ox + x * s, SH - (fr.origin.y + oy + (f->rh - y) * s))); }); return 1; }
+ CGWarpMouseCursorPosition(CGPointMake(x, y)); return 1; }
U(ShowCursor, int, int s) { static int c; c += s ? 1 : -1; int h = c < 0; if (h != g_hide) { g_hide = h; on_main(^{ mouse_apply(); }); } return c; }
U(ClipCursor, int, const int32_t *r) { int k = r != 0; if (k != g_clip) { g_clip = k; on_main(^{ mouse_apply(); }); } return 1; }
U(GetDesktopWindow, void *, void) { return 0; }
diff --git a/w64/w64.h b/w64/w64.h
index e895b38..b523169 100644
--- a/w64/w64.h
+++ b/w64/w64.h
@@ -7,7 +7,10 @@
/* the primary screen's size in points. [NSScreen mainScreen] is main-thread only and is nil while the app is still
launching, which gave Windows programs a 0 x 0 screen on their own thread (ScummVM failed 1 start in 3).
CoreGraphics answers from any thread. */
-static inline CGSize w64_screen(void) { return CGDisplayBounds(CGMainDisplayID()).size; }
+/* the screen as a program sees it: in exclusive fullscreen (w64_fullscreen) the display has the mode's size, as when
+ Windows switches the display mode; otherwise the Mac display's size in points */
+static int g_w64_mw, g_w64_mh;
+static inline CGSize w64_screen(void) { if (g_w64_mw > 0 && g_w64_mh > 0) return CGSizeMake(g_w64_mw, g_w64_mh); return CGDisplayBounds(CGMainDisplayID()).size; }
#endif
#ifdef DAISY_W32
#include "w32.h"
diff --git a/w64/win.h b/w64/win.h
index 58dec71..039bcb2 100644
--- a/w64/win.h
+++ b/w64/win.h
@@ -87,7 +87,8 @@ static int setpos(w64win *w, void *after, int x, int y, int cx, int cy, uint32_t
uint8_t b[40] = {0}; memcpy(b, &w, 8); memcpy(b + 8, &after, 8); int32_t v[5] = {x, y, cx, cy, (int)f}; memcpy(b + 16, v, 20); if (!(f & 0x400)) wsend(w, 0x46, 0, (int64_t)b); memcpy(v, b + 16, 20); x = v[0]; y = v[1]; cx = v[2]; cy = v[3]; f = v[4]; if (cx < 0) cx = 0; if (cy < 0) cy = 0; int ow = w->rw, oh = w->rh, ox = w->rx, oy = w->ry; int vis = w->parent ? shown(w) : 0;
int nx = f & 2 ? w->rx : x, ny = f & 2 ? w->ry : y, nw = f & 1 ? w->rw : cx, nh = f & 1 ? w->rh : cy; int mv = nx != ox || ny != oy, sz = nw != ow || nh != oh;
if (w->parent) { if (vis && (mv || sz)) under(w); w->rx = nx; w->ry = ny; w->rw = nw; w->rh = nh; if (!(f & 4) && w->parent) { relink(w, after == (void *)-1 || after == (void *)-2 ? 0 : after); } if (vis && mv && !sz) invalall(w); }
- else { if (!nw || !nh) { nw = imax(nw, 1); nh = imax(nh, 1); } w->rx = nx; w->ry = ny; w->rw = nw; w->rh = nh; if (w->win && (mv || sz)) { double H = w64_screen().height; NSRect c = NSMakeRect(nx, H - ny - nh, nw, nh); on_main(^{ [w->win setFrame:[w->win frameRectForContentRect:c] display:YES]; }); } if (!(f & 4) && w->win && w->shown && !(f & 0x10)) on_main(^{ [w->win orderFront:nil]; }); }
+ else { if (w->fs && g_w64_mw > 0) { nx = ny = 0; nw = g_w64_mw; nh = g_w64_mh; } /* fullscreen: the window is the display */
+ if (!nw || !nh) { nw = imax(nw, 1); nh = imax(nh, 1); } w->rx = nx; w->ry = ny; w->rw = nw; w->rh = nh; if (w->win && (mv || sz) && !w->fs) { double H = w64_screen().height; NSRect c = NSMakeRect(nx, H - ny - nh, nw, nh); on_main(^{ [w->win setFrame:[w->win frameRectForContentRect:c] display:YES]; }); } if (!(f & 4) && w->win && w->shown && !(f & 0x10)) on_main(^{ [w->win orderFront:nil]; }); }
if (f & 0x80 && (w->parent ? w->style & 0x10000000 : w->shown)) { if (w->parent) { under(w); w->style &= ~0x10000000; } else showwin(w, 0); }
if (mv || sz || f & 0x20) { sized(w, f & 0x20 && !sz ? ow - 1 : ow, oh, mv); } else wsend(w, 0x47, 0, (int64_t)b);
if (f & 0x40) showwin(w, f & 0x10 ? 4 : 5); return 1; }
@@ -150,7 +151,7 @@ U(IsWindow, int, void *h) { return W(h) != 0; }
U(IsWindowVisible, int, void *h) { w64win *w = W(h); return w && shown(w); }
U(IsWindowEnabled, int, void *h) { w64win *w = W(h); return w && !(w->style & 0x08000000); }
U(EnableWindow, int, void *h, int e) { w64win *w = W(h); if (!w) return 0; int was = (w->style & 0x08000000) != 0; if (e) w->style &= ~0x08000000; else w->style |= 0x08000000; if (was == !!e) { if (!e && g_focus == w) setfocus(w->parent); wsend(w, 0xa, e != 0, 0); invalall(w); if (w->clear) under(w); } return was; }
-U(IsIconic, int, void *h) { w64win *w = W(h); return w && w->win && w->win.miniaturized; }
+U(IsIconic, int, void *h) { w64win *w = W(h); return w && (w->iconic || (w->win && w->win.miniaturized)); }
U(IsZoomed, int, void *h) { w64win *w = W(h); return w && w->win && (w->win.styleMask & NSWindowStyleMaskResizable) && w->win.zoomed; }
U(GetClientRect, int, void *h, int32_t *r) { w64win *w = W(h); r[0] = r[1] = r[2] = r[3] = 0; if (!w) { if (!h) { NSSize s = w64_screen(); r[2] = s.width; r[3] = s.height; return 1; } return 0; } csize(w, r + 2, r + 3); return 1; }
U(GetWindowRect, int, void *h, int32_t *r) { w64win *w = W(h); if (!w) { memset(r, 0, 16); if (!h) { NSSize s = w64_screen(); r[2] = s.width; r[3] = s.height; } return !h; } int x, y; w64win *t = top(w); wo(w, &x, &y); r[0] = x + t->rx; r[1] = y + t->ry; r[2] = r[0] + w->rw; r[3] = r[1] + w->rh; return 1; }
@@ -236,7 +237,7 @@ static int nchit(w64win *w, int x, int y) { int a, b, l, t, r, bb; wo(w, &a, &b)
static void setcur(w64win *w, int ht, uint32_t m) { wsend(w, 0x20, (uint64_t)w, ht | (int64_t)m << 16); }
static struct { w64win *w; } g_leave;
/* turns a queued top-window mouse or key message into the one the program sees; 0 = swallowed */
-static int fix(msg64 *o) { w64win *t = o->h; if (o->m == 0x7fe1) { if (!W(t)) return 0; int32_t r[4] = {(int32_t)(o->w >> 32), (int32_t)o->w, (int32_t)(o->l >> 32), (int32_t)o->l}; int ow = t->rw, oh = t->rh, ox = t->rx, oy = t->ry; t->rx = r[0]; t->ry = r[1]; t->rw = r[2]; t->rh = r[3]; if (ow != r[2] || oh != r[3] || ox != r[0] || oy != r[1]) sized(t, ow, oh, ox != r[0] || oy != r[1]); return 0; }
+static int fix(msg64 *o) { w64win *t = o->h; if (o->m == 0x7fe1) { if (!W(t) || t->fs) return 0; int32_t r[4] = {(int32_t)(o->w >> 32), (int32_t)o->w, (int32_t)(o->l >> 32), (int32_t)o->l}; int ow = t->rw, oh = t->rh, ox = t->rx, oy = t->ry; t->rx = r[0]; t->ry = r[1]; t->rw = r[2]; t->rh = r[3]; if (ow != r[2] || oh != r[3] || ox != r[0] || oy != r[1]) sized(t, ow, oh, ox != r[0] || oy != r[1]); return 0; }
if (o->m == 0x7fe0) { if (!W(t)) return 0; if (!usable(t)) { for (int i = 0; i < g_nw; i++) if (g_w[i] && g_w[i]->owner == t && g_w[i]->shown && usable(g_w[i])) { activate(g_w[i]); break; } return 0; } wsend(t, 0x1c, 1, 0); wsend(t, 0x86, 1, 0); wsend(t, 6, 1, 0); if (!W(g_focus) || top(g_focus) != t) { w64win *f = W(t->lastf); if (!f || top(f) != t || !usable(f)) f = t; setfocus(f); } return 0; }
if (!o->h || !W(o->h)) return o->h == 0; if (o->m >= 0x100 && o->m <= 0x108) { if (!t->parent && W(g_focus) && o->m <= 0x105 && top(g_focus) == t && g_focus->tid == self()) o->h = g_focus; if (!usable(o->h)) return 0; return 1; }
if (o->m < 0x200 || o->m > 0x20e || t->parent) return 1; int big = o->m == 0x20a || o->m == 0x20e; int x = (int16_t)o->l, y = (int16_t)(o->l >> 16); w64win *c = W(g_cap); w64win *k = c && top(c) == t ? c : c ? c : (t->kid ? kidat(t, x, y) : t); if (!usable(k)) { if (o->m == 0x201 && !usable(top(k))) for (int i = 0; i < g_nw; i++) if (g_w[i] && g_w[i]->owner == top(k) && g_w[i]->shown && usable(g_w[i])) { w64win *z = g_w[i]; on_main(^{ [z->win makeKeyAndOrderFront:nil]; }); } return 0; } int ht = c ? 1 : nchit(k, x, y); int sx = x + t->rx, sy = y + t->ry;
@@ -273,7 +274,7 @@ static int peek(msg64 *o, w64win *w, uint32_t lo, uint32_t hi, uint32_t rm) { pu
static int get(msg64 *o, w64win *w, uint32_t lo, uint32_t hi) { for (;;) { drain(); if (taken(o, w, lo, hi, 1)) break; if ((!lo || (lo <= 0x113 && hi >= 0x113)) && due(o, w)) break; if (wantpaint(lo, hi) && paintmsg(o, w)) break; blink(0); w64_surface_flush(); pump(1); } return o->m != 0x12; }
/* the next untranslated message of this thread, for drag loops */
static int nextraw(msg64 *o) { drain(); if (take(o, 0, 0x200, 0x20e, 1)) return 1; if (take(o, 0, 0x7fe0, 0x7fe1, 1)) { if (o->m < 0x7fe0) return 1; fix(o); return 0; } blink(0); w64_surface_flush(); pump(1); return 0; }
-static int64_t disp(msg64 *m) { if (m->m == 0x113 && m->l) { GCALL(int, (WINAPI64 void (*)(void *, uint32_t, uint64_t, uint32_t))m->l, 4, m->h, 0x113, m->w, m->t); return 0; } if (!W(m->h)) return 0; return wsend(m->h, m->m, m->w, m->l); }
+static int64_t disp(msg64 *m) { { static int ml = -1; if (ml < 0) ml = getenv("W64_MSGLOG") != 0; if (ml && m->m != 0x200 && m->m != 0xff) fprintf(stderr, "w64: message %#x wp %#llx lp %#llx to %p\n", m->m, (unsigned long long)m->w, (unsigned long long)m->l, (void *)m->h); } { extern volatile int pe2_trace_burst __attribute__((weak)); if (&pe2_trace_burst && pe2_trace_burst > 0) fprintf(stderr, "[burst] message %#x wp %#llx lp %#llx\n", m->m, (unsigned long long)m->w, (unsigned long long)m->l); } { static int tr = -1; if (tr < 0) tr = getenv("W64_TRACE") != 0; if (tr && ((m->m >= 0x201 && m->m <= 0x209) || m->m == 0x100 || m->m == 0x102)) fprintf(stderr, "w64: dispatch %#x to %p wparam %#llx lparam %#llx\n", m->m, m->h, (unsigned long long)m->w, (unsigned long long)m->l); } if (m->m == 0x113 && m->l) { GCALL(int, (WINAPI64 void (*)(void *, uint32_t, uint64_t, uint32_t))m->l, 4, m->h, 0x113, m->w, m->t); return 0; } if (!W(m->h)) return 0; return wsend(m->h, m->m, m->w, m->l); }
U(PeekMessageA, int, msg64 *o, void *w, uint32_t a, uint32_t b, uint32_t r) { return peek(o, w, a, b, r); }
U(PeekMessageW, int, msg64 *o, void *w, uint32_t a, uint32_t b, uint32_t r) { return peek(o, w, a, b, r); }
U(GetMessageA, int, msg64 *o, void *w, uint32_t a, uint32_t b) { return get(o, w, a, b); }
@@ -328,3 +329,38 @@ U(IsCharAlphaW, int, uint16_t c) { return iswalpha(c) != 0; } U(IsCharAlphaNumer
#include "ctl.h"
#include "menu.h"
#include "plugwin.h"
+
+/* Exclusive fullscreen (Direct3D 9 with Windowed = FALSE), from the 32-bit layer's pe2_set_mode: as on Windows the
+ device window covers the display at the new mode, so its own size becomes the mode (client area = mw x mh) and the
+ program keeps seeing that; the Mac window covers the screen without menu bar and Dock, the picture scaled to fit
+ with black bars (kCAGravityResizeAspect), and the mouse is mapped back (fs_map). mw = 0 leaves fullscreen. */
+static void fs_space_watch(void);
+void w64_fullscreen(void *p, int mw, int mh) {
+ w64win *w = W(p); while (w && w->parent) w = w->parent;
+ if (!w) return;
+ if (mw > 0 && mh > 0) {
+ int l, t, r, b; inset(w, &l, &t, &r, &b);
+ w->rx = w->ry = 0; w->rw = mw + l + r; w->rh = mh + t + b; g_fsw = w; g_w64_mw = w->rw; g_w64_mh = w->rh;
+ if (!w->fs) { w->fs = 1; on_main(^{ NSRect f = w->win.frame; w->fsx = f.origin.x; w->fsy = f.origin.y; w->fsw = f.size.width; w->fsh = f.size.height; }); }
+ on_main(^{ fs_space_watch(); NSWindow *win = w->win; if (!win) return; NSScreen *sc = win.screen ? win.screen : NSScreen.mainScreen;
+ [NSApp setPresentationOptions:NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar];
+ [win setFrame:sc.frame display:YES]; win.level = NSNormalWindowLevel;
+ NSView *v = win.contentView; v.wantsLayer = YES; v.layer.backgroundColor = NSColor.blackColor.CGColor; v.layer.contentsGravity = kCAGravityResizeAspect;
+ [win makeKeyAndOrderFront:nil]; });
+ sized(w, -1, -1, 1);
+ } else if (w->fs) {
+ w->fs = 0; if (g_fsw == w) { g_fsw = 0; g_w64_mw = g_w64_mh = 0; }
+ on_main(^{ [NSApp setPresentationOptions:NSApplicationPresentationDefault]; if (w->win && w->fsw > 0) [w->win setFrame:NSMakeRect(w->fsx, w->fsy, w->fsw, w->fsh) display:YES]; });
+ }
+}
+/* Coming back to the Space that holds an exclusive-fullscreen window (a swipe, Control-arrow, Mission Control)
+ shows it without making its program active, and an inactive program's Direct3D device stays lost
+ (runtime/d3d9_device.m dev_state): it drew nothing until a click. On Windows switching to a fullscreen game
+ activates it, so arriving on its Space does here. */
+static void fs_space_watch(void) { /* main thread, once */
+ static int once; if (once) return; once = 1;
+ [[NSWorkspace sharedWorkspace].notificationCenter addObserverForName:NSWorkspaceActiveSpaceDidChangeNotification object:nil queue:nil usingBlock:^(NSNotification *n) {
+ (void)n; w64win *w = g_fsw;
+ if (w && w->fs && w->win && w->win.isOnActiveSpace && !NSApp.isActive) { [NSApp activateIgnoringOtherApps:YES]; [w->win makeKeyAndOrderFront:nil]; }
+ }];
+}