Dunia.dll — Presenting a Frame, and Who Owns the Mouse
Confirmed against retail Far Cry 2 (GOG v1.03, fc2_103_retail). The addresses are Steam v1.03;
see the overview for binary identification.
Far Cry 2 draws with Direct3D 9 — or 10, where its hardware probe allows — and reads the player with
DirectInput 8. Both are chosen in Dunia.dll before any plugin gets a say.
Direct3D 9, and a Direct3D 10 renderer it loads itself
Direct3DCreate9 is a static import of Dunia.dll, so the D3D9 path is linked in and always
present. A complete Direct3D 10 backend is there too, though no D3D10 or DXGI symbol is imported: it
loads its libraries itself. Traced in the GOG build (RE-verified):
- Choosing it.
InitDuniaEnginetakes-3dplatform d3d10(ord3d10a), or, without the switch, theRenderProfilePlatformsetting, whose default isd3d9. D3D10 is used only ifIsD3D10Supported(0x103f8630) passes: it askssystemdetection.dllfor adapter 0 and wants field+8to be 3. Otherwise the game runs on D3D9 and writesd3d9back into the profile. - Loading it. The backend
LoadLibraryAsdxgi.dll,d3d10_1.dll(optional),d3d10.dllandd3dx10_38.dlland resolves everything withGetProcAddress(0x104116f0). The device is created as Direct3D 10.1, else through NvAPI where present, else as 10.0. Once D3D10 is chosen there is no fallback to D3D9. - Presenting. Both backends sit behind the engine's own device class, whose
Present(HWND)is vtable slot 16 in both (__thiscall,ret 4): D3D90x10416310callsIDirect3DDevice9::Present, D3D100x10412f10callsIDXGISwapChain::Present(SyncInterval, 0). A hook on slot 16 of the engine's device sees either; a hook onIDirect3DDevice9sees D3D9 only. - V-sync applies only in fullscreen, on both backends: a window always presents immediately.
So every plugin that works through IDirect3DDevice9 — the Sky Overhaul, the aiming overhaul,
DevTools' overlay — does nothing for a player on whose machine the game picked D3D10. Which backend a
given install actually runs has not been observed in game.
Two windows exist before the game's own, and neither is the one to draw into:
| Window class | Built by | What it is |
|---|---|---|
NomadSplash | 0x10006130 | The startup splash, a layered window fed a PNG through GDI+. FCSE recolours it. |
NomadTool9 | 0x1037c1a0 | A hidden 1×1 window created only to hold a throwaway device. |
NomadTool9 is the same trick an overlay wants. The engine
LoadLibraryA("d3d9.dll"), GetProcAddresses Direct3DCreate9, creates a device against that 1×1
window, and asks it what the hardware can do. Anyone who needs IDirect3DDevice9's functions can do
precisely this: one device of your own names the functions the game's device will call. Copy the
vtable's slots before releasing that device. A wrapper such as an overlay can keep the vtable inside
the device object and free it with the device, and reading the table after releasing the device
crashes at startup on such a machine.
A throwaway device names the functions the game's calls reach only while a wrapper in front of
d3d9.dll leaves that device unwrapped. ReShade 6.8.0 does: it skips a device whose focus window is
the desktop, so the throwaway stays a plain system device, and ReShade forwards the game's calls to
those same functions (seen in game, GOG v1.03). Under dgVoodoo 2.87.6 the throwaway device cannot be
created at all, so a plugin that reads its slots this way does nothing (seen in game, GOG v1.03).
A hook on the engine's own device class depends
on no wrapper at all.
EndScene is not once a frame
Far Cry 2 renders through offscreen passes and composites them — HDR,
bloom, tone mapping — so EndScene is called several times per frame, once per pass, and only
some of those have the back buffer bound.
Drawing from an EndScene hook therefore draws into whatever pass happens to be ending. In practice
the overlay appears correctly and a second time, doubled in size and blended through whatever the
post chain does to that surface, which reads as a multiply. It is absent in menus, because the menu
does not run the same pipeline — which is a good way to misdiagnose it as a UI-layer problem.
Present is called once, after all of it. Drawing there, with the back buffer fetched via
GetBackBuffer and bound explicitly, is the only placement that lands on the final image exactly
once. Present is outside the engine's scene, so the drawing needs a BeginScene/EndScene of its
own, and the render target the game had bound has to be put back afterwards.
What a frame actually looks like from EndScene
Counted by logging every EndScene of selected frames from an FCSE plugin, retail GOG v1.03, at
1280×720 with HDR and bloom on. Frame ordinals matched live frames exactly over a
300-frame span, so the sequence below is one whole frame.
| Order | Calls | Render target | Depth attached |
|---|---|---|---|
| World | 14–16 | offscreen, back-buffer size, D3DMULTISAMPLE_4_SAMPLES | yes, same size |
| Bloom and luminance chain | ~16 | offscreen, 320×180 halving to 1×1, A16B16G16R16F | no |
| Composite | 1 | the back buffer | no |
Render2DView (HUD, menus) | 2 | the back buffer | yes, its own surface |
Two offscreen world targets alternate: an A8R8G8B8 one and, once HDR is on, an
A16B16G16R16F one. Both are multisampled and carry the scene's depth.
The composite is the only back-buffer pass with no depth surface, and that is the reliable way
to recognise it. Render2DView allocates a DepthStencil of its own (see
the sky and cloud system for where the world's own passes come from), so
"back buffer plus depth" means the interface, not the world. Recognising a pass this way puts an
effect under the HUD rather than over it.
Do not try to tell passes apart by what is bound at c4/c8. Constants persist until something
sets them, so at EndScene they hold whatever the pass's last draw left. The interface's passes
report the world's projection, identical to the world's own passes, and a menu frame reports
zeroes. Render-target identity, size and depth attachment are the only dependable discriminators.
Only the last of the world passes has the whole scene's depth behind it, which matters to anything issuing an occlusion query. It can be recognised while it is happening, by its viewport:
The sky pass is the only world pass drawn through a viewport squeezed against the far plane. Its
MinZ measures 0.999 to 1.000 where every other pass reports 0. Testing MinZ >= 0.9 picks it out
of the frame with no false positives over a 300-frame span, and it is the pass the engine draws the
sun in, so the world's opaque depth is complete and the camera transform is the one it drew with.
That has a consequence for anything drawn there. A screen-space quad inherits the pass's depth
range, so its own vertex depth is remapped into the last thousandth before the far plane unless the
viewport is reset to MinZ = 0, MaxZ = 1 for the draw and restored afterwards.
The world's passes in order
Retail GOG v1.03 at 1920×1080 with four-sample multisampling, one whole frame recorded from an FCSE
plugin: each pass's target, depth surface and viewport at EndScene, and the render states of every
draw inside it. A frame in play held 51 to 64 passes up to the composite.
The world half of the frame runs in this order:
- Shadow map cascades, three pairs of solid then alpha-tested draws into a
NULL-format 6144×2048 target with a depth surface of their own. - The water reflection, at 1024×1024 with its own multisampled depth.
- A near-plane depth pass of about 10 to 17 draws through a viewport of
MinZ0 to 0.001, which is the first-person weapon's depth (see the first-person weapon's two passes). The stencil is cleared here. - The depth prepass, solid draws then alpha-tested ones, writing depth and the linear depth with the stencil off.
- The main colour pass for solid geometry, depth-tested against that depth without writing it.
- The foliage colour pass, every draw with
ZFUNCequal, so foliage is coloured only where its own depth landed. Taking foliage out of the depth prepass would take it out of the frame. - Further colour passes and 12 or so blended draws, some of them reading the linear depth. Every draw in passes 5 to 7 runs with the stencil enabled.
- The sky pass.
- About 18 blended draws, then a stencil clear and a handful of solid draws, which are the weapon's colour.
- Bloom, luminance and the composite.
The world's depth-stencil surface is the same one from the near-plane pass through the sky pass.
The first-person weapon's two passes
Retail GOG v1.03 at 1920×1080 with four-sample multisampling, whole frames recorded from an FCSE plugin while down the iron sights of a G3 and of a pistol.
The weapon is drawn twice, and only its depth goes through the squeezed viewport.
- Its depth comes first, before the world's depth prepass: 14 draws for the G3, through a
viewport of
MinZ0 to 0.001, into the multisampledA8R8G8B8linear-depth target, with depth test, depth write and colour write on and the stencil off. - Its colour is the 16-draw pass right after the sky pass, into the multisampled FP16 scene target through an ordinary viewport of 0 to 1. No draw after the sky pass is squeezed. Twelve of the 16 repeat a draw of the depth pass exactly: the same start index, primitive count and vertex count. That is what tells the weapon's colour pass apart.
- Its projection, at
c8toc11during those draws, has a near plane of 1 cm:c10.wreads −0.01. The vertical scalec9.yread 2.593 down the G3's iron sights and 1.738 down the pistol's.
Drawing each depth draw a second time into a single-sampled INTZ texture of the screen's size or
smaller, through a viewport of 0 to 1, gives the weapon's depth at full precision, since the
multisampled original cannot be read. Aiming Overhaul's src/engine/weapon_draws.cpp does that, and
finds the colour pass by the repeated draws.
While a scope's sight picture is up
Retail GOG v1.03 at 1920×1080 with four-sample multisampling, one frame each through the Dart Rifle, Dragunov, AS50 and M1903, held still, recorded from an FCSE plugin.
Only the SCOPE_HI part of the weapon is drawn (see
replacing a weapon),
plus the arms, which are drawn but land off screen.
- Every scope part comes from one vertex buffer, the weapon's own with a 32-byte stride. The arms are skinned, from a buffer of their own with a 40-byte stride.
- The depth pass draws the scope's opaque clusters as one draw: the Dragunov's tube, rings and housing are a single 2,088-triangle draw. A second squeezed pass follows with the reticle alone, alpha-tested, with NVIDIA's alpha-to-coverage switch on.
- The colour pass draws each opaque cluster separately (three on the Dragunov). The reticle comes
in a pass of its own after it, and then the lens in another, blended (
SRCALPHA,INVSRCALPHA) without depth writes. The reticle is the only alpha-tested draw of the scope. - The AS50's red cross and range marks are a blended draw that samples the reticle's texture, the
shared
dragunov_crosshair_d.xbt. - The projection's rows are
c8toc11,c10= (0, 0, −1.002, −0.01) andc11= (0, 0, −1, 0): right-handed, clipwis the distance ahead. The vertical scalec9.yis 8.82 on the Dart Rifle, 9.46 on the Dragunov, 13.29 on the AS50 and 9.29 on the M1903. - The position is projected through
c0toc3, notc8.c8isProjectionMatrix, which the weapon's draws carry but do not place vertices by. The prototype's mesh shaders,mesh_weapon.fxand the genericaaa.fxamong them, project throughViewRotProjectionMatrixatc0, one register for each of clip space's x, y, z and w. Changingc8for a draw moves nothing; changingc0andc1scales or shifts it in clip space. - A user clip plane cuts the scope by distance. Given in clip space as (0, 0, −1, d), with d the
stored depth
c10.z·c11.z + c10.w / metresof a distance, it keeps what lies nearer than that distance, in both the depth and the colour pass.
Cut at a run of distances, the scopes lie at:
| Rifle | Opaque scope | Reticle | Lens |
|---|---|---|---|
| Dart Rifle | 10–18 cm | 15–18 cm | 15–18 cm |
| Dragunov | 21–32 cm | 30–32 cm | 28–32 cm |
| AS50 | 15–24 cm | 23–24 cm | 23–24 cm |
| M1903 | 10–19 cm | 18–19 cm | 15–19 cm |
Drawing the world a second time
Read from Dunia.dll (Steam v1.03). The functions are annotated in the Ghidra project.
The water reflection is the only pass that draws the full-colour world from another camera into a
target of its own. The other secondary views are written out by hand where they are used, and none
of them is a general "render this camera" function: Render2DView, the editor's picking renderer,
the sector ambient pass and the shadow cascades. The CSceneViewport* strings have no code behind
them.
-
It draws at once.
CWaterReflectionRenderer::RenderWaterReflection(0x103A3250) fills the shared named passes and executes them immediately. Nothing is deferred to the frame graph. -
Where it is called.
CSceneRenderer::PrepareFrameGraph(0x10347040) calls it at0x103478A5, after the shadow cascades. It runs only whenSetupReflectionView(0x103A8640) answers true: there is reflective water at or below the camera and the reflection quality is at least 2. -
What it is called with.
__thiscallon the renderer at[[scene+0x38]+0x38], 14 arguments,RET 0x38. The ones that matter:- the view block;
- the viewport;
- the camera component, which supplies the render camera at
+0x20and the culling camera's position at+0x5E0; - the level-of-detail and kill-distance scales, both multiplied by the zoom.
-
It allocates its own targets. It pushes a "Reflection" scope on its target pool and stores it at
+0x24. It takes "Color" at the config's+0x598×+0x59C, 1024 × 1024, and draws with+0x5A4samples. The colour ends up at+0x20, an engine texture whose+0x18is theIDirect3DTexture9. The frame function pops the scope later, at0x10347C6D. -
The view block is
SWaterReflectionView, 0x870 bytes and 16-byte aligned, built by0x103A2C30. Only these fields are read:- the camera at
+0x3D0, used for both drawing and culling; - the scissor at
+0x7A0; - the clip plane at
+0x830, where (0, 0, 0, 1) turns it off; - a colour tint at
+0x850; - a quality from 2 to 7 at
+0x868; - the smallest object radius drawn, at
+0x86C.
- the camera at
-
The camera,
CCamera, is 0x3D0 bytes.- Fields: aspect at
+0x18, near and far at+0x220and+0x224, and the horizontal field of view in radians at+0x228. The view-projection is at+0x170, and+0x348flags the clip plane as a seventh frustum plane. 0x1040C800rebuilds it from those fields.0x1033AEA0assigns one camera to another and0x1039FEA0copy-constructs one.
- Fields: aspect at
-
What it leaves out:
- the depth prepass and linear depth;
- the first-person weapon;
- distortion and occlusion queries;
- objects below the smallest radius;
- object classes the quality leaves out.
Material detail is reduced too.
Retail GOG v1.03 at 1920 × 1080, from an FCSE plugin. A mid-hook on the instruction after the call ran the reflection's culling and drawing a second time each frame while a scope was up, and the image was right.
Aiming Overhaul's src/engine/second_view.cpp does this. Its view block is built by the
constructor, with:
- the player's render camera assigned to it, not mirrored;
- the unzoomed field of view written in, and the frustum's clip plane cleared;
- a full-target scissor, the clip plane off, and a neutral tint.
A fake camera component carries copies of that camera at +0x20 and +0x3F0. Then
QueryVisibility (0x103A8450) and the renderer are called, and the "Color" is copied out.
0x103A1EF0 pops the scope, and the renderer's +0x20 and +0x24 are put back.
- The second call gets a texture of its own. The pool only reuses entries not in use, and the water's reflection is still in use. Once restored, the water's own reflection is untouched.
- The zoom is in the camera, not the projection alone. Scoped through the Dart Rifle, the
render camera's
+0x228read 0.398 rad, a vertical scale of 8.82 at 16:9. Unaimed it read 1.594 rad. - The scales the reflection is called with carry the zoom. They read 0.276 scoped. Rebuilt from
the scene config's
+0x6B4and+0x6B8times the viewport's+0x34and+0x38, they are 1.0. - The renderer takes a size and sample count of its own. Setting the config's
+0x598,+0x59Cand+0x5A4for the call and putting them back drew it at half the screen without multisampling.
Whether there is a render thread
There is. CThreadingConfig has a RENDER_THREAD entry, engine\settings\defaultthreadingconfig.xml
ships it enabled (ThreadCnt="1"), and Dunia.dll:0x103430A0 reads it and builds a RenderThread
(0x103B20A0), a real OS thread. Each frame the main thread's RunFrame posts RenderLoop to it,
and the render thread runs RenderFrame — which prepares and executes the frame graph — and
Present. The next frame's tick first waits for the previous frame to finish, so the render thread
draws frame N while the game simulates frame N+1 (traced in the GOG build, RE-verified).
A hook on the sky's submission and a hook on EndScene report the same thread id, because both are on
the render thread: the sky is submitted from inside the frame graph's preparation, in the same call
that then executes it. A
plugin that reads game state from a render-side hook reads it one frame late, and needs to publish
state across the boundary.
While a loading screen is up the render thread mostly runs on its own instead: it redraws the last
frame about 30 times a second, polling with Sleep(2), and takes no new work from the main thread.
The exception is the renderer-preparation step at the end of a load, which drives it frame by frame
again; see loading a save.
The scene's depth is gone by the time the frame is
The other half of the same point. By the composite stage — the pass with the back buffer bound, and
Present after it — no depth-stencil surface is attached at all: GetDepthStencilSurface
returns nothing. So anything drawn there is drawn over a flat image. A screen-space effect that wants
to be occluded by the world cannot be depth-tested where it is drawn, and setting D3DRS_ZENABLE for
it is silently a no-op rather than an error.
Anything needing the scene's depth has to run while a pass that owns it is still open, which means one of the world passes in the table above — recognised as an offscreen back-buffer-sized target with depth attached. An occlusion query issued there reads back a frame or two later, by which time the composite stage can use the answer without ever having needed the depth buffer itself.
Depth testing against it works; sampling it does not. The world passes are multisampled four ways
and their depth surface matches, and Direct3D 9 offers no way to bind a multisampled depth surface
as a texture. The usual escape — creating an INTZ depth-format texture and binding it as the
depth-stencil target so it can also be sampled — is defined only for single-sampled surfaces.
So a screen-space effect that needs per-pixel depth, ambient occlusion being the obvious one, cannot simply read the depth-stencil surface. It has to read the engine's own linear depth instead, below, or intercept the creation of the depth surface and substitute a single-sampled readable one, which costs the game its antialiasing. An occlusion query needs none of this, because it asks the hardware to count against depth rather than to hand it over.
ReShade is bound by the same rule: with the world passes multisampled four ways, ReShade 6.8.0's
depth view (DisplayDepth.fx) shows no depth at all, with no plugin installed but DevTools (seen in
game, GOG v1.03). Effects and upscalers that take ReShade's depth get none.
The engine keeps a readable linear depth of its own
Read from Dunia.dll (Steam v1.03) and the shipped shader objects.
CSceneRenderer::PrepareFrameGraph (0x10347040) creates a render target named "Linear depth",
an A8R8G8B8 texture at the scene's size, whenever the renderer config's +0x4A0 is zero. With
multisampling on it also creates "LinearDepthMSAA", a multisampled surface of the same size and
format, for the depth pass to draw into before the texture is filled from it. "Linear depth SS"
belongs to the other renderer, CSceneRendererD3D10::PrepareFrameGraph (0x10356BC0).
That config value is most likely the depth pass mode, which was not traced to its register call. In
the DepthPass group of engine\settings\defaultrenderconfig.xml, high, veryhigh and ultrahigh
are DepthPassMode="full" with DepthPassNoPixel="0"; low and medium are partial passes with
DepthPassNoPixel="1", which would write no colour.
The texture reaches shaders as DepthVPSampler, one of the viewport's global parameters registered
in 0x103788F0. Seventy-four pixel shaders in the D3D9 shadersobj tree bind it, all at s0.
The prototype's depth.inc.fx gives the packing: view depth along CameraDirection, divided by the
view distance, split across red, green and blue as 24 bits. UncompressDepthWeights at c56 turns a
texel back into that fraction, UncompressDepthWeightsWS at c57 into world units, and
CameraDistances at c40 holds near, far, view distance and its inverse.
Each view hands the texture to its shaders. The renderer's per-view parameter update (Steam
0x10367F70, __thiscall(renderer, view), ret 4) sets DepthVPSampler, the viewport provider's
parameter at +0x4A0 with its texture at +0x4AC, from the view's +0x1C, and
ResolvedDepthVPSampler (+0x4B0) from the view's +0x20. The view's +0x1C is a device texture
whose Direct3D texture is at +0x18, so a hook on that update has the texture before any of the
view's passes draw; of the views that carry one, the world's is the last updated before the world's
passes (seen in game, GOG v1.03). Third Person reads it there. The provider is made through a factory and no global points at it.
It can also be found by recognising one of those 74 shaders as it draws, by the CRC-32 of its
bytecode, and reading what is bound at s0. Sky Overhaul's src/engine/depth_texture.cpp does that.
Retail GOG v1.03 at 1920×1080 with four-sample multisampling, read back from an FCSE plugin at the sky pass.
- It is complete and in place by the sky pass, and one texture for the whole session.
c56holds (1, 1/256, 1/65536) andc57the same times the view distance, 999.9 in the world and 1023.75 while loading.- Where nothing was drawn it holds white, which decodes to just past the view distance: 1003.8 m.
- The first-person weapon leaves it at zero.
How far neighbouring texels can be trusted
Retail GOG v1.03 at 1920×1080 with four-sample multisampling, one column of the texture read back from an FCSE plugin at the sky pass, looking down at open ground.
The prototype's CompressDepthValue hands each byte over as a multiple of 1/256, and the channel
stores 255ths, so every byte is rounded to the nearest 255th on the way in.
- The middle byte holds 127 across two of its steps, halfway through every step of the top byte: at 1.95 m, 5.86 m, 9.77 m and so on. The lowest byte wraps underneath it, so the depth there reads 1.5 cm nearer than the texel before. At 5.87 m, on rows stepping 1.24 cm apart, three rows read (1, 127, 100), (1, 127, 53) and (1, 128, 6): 5.8724, 5.8696 and 5.8821 m.
- Past each step of the top byte the depth reads a further 1.5 cm long, since
c56weighs the bytes as 256ths: 38 cm too far by 100 m. This follows from the packing; one step read back at 3.93 m jumped 2.4 cm from the row before it. - Lone texels read about a centimetre off the surface around them. On rows stepping 1.24 cm apart, one step was 2.44 cm and the next 0.14 cm. They are the storage too: the same frame held in half floats has none, below.
- Texels half a top-byte step out are rare. A repair for them changed 8 texels in a column read back every two seconds for a minute. Averaging the bytes of multisamples that lie either side of a step would make those, so the resolve does not do it often.
A 1.5 cm step is inside the tolerance any depth comparison already allows. A normal is not, because it is taken from depth differences one pixel apart. Sky Overhaul built ambient occlusion on this texture and removed it again. In game:
- Taking each axis from the neighbour nearer in depth, the usual guard against silhouettes, picks the neighbour across a backward step wherever rows lie more than 0.77 cm apart. It drew a faint dark line across the ground at 5.87 m that turned with the camera.
- Taking each axis from the side whose next two texels run straight on through the pixel removed the lines, and left dark dots at the lone texels that ran along the terrain as the camera moved.
- Taking each texel as the median of the three by three around it first was the last thing tried, and what it did was not recorded.
Storing it in half floats
Retail GOG v1.03 at 1920×1080 with four-sample multisampling. The format was switched from an FCSE plugin while the player stood still, so both formats were read back over the same frame content.
CSceneRenderer::PrepareFrameGraph passes each target's format as a raw D3DFORMAT pushed onto the
stack, 0x15 for both "Linear depth" (Steam 0x10347659) and "LinearDepthMSAA" (Steam
0x10347b8d). Writing 0x71, D3DFMT_A16B16G16R16F, over both bytes stores the same packing
exactly. The two have to change together, since the resolve needs them to agree.
- The renderer takes it. The targets are requested by name and format every frame, so the change applies on the next frame, no restart. Water, soft particles, fire and Sky Overhaul's cloud shadows all read the texture and looked unchanged.
- Every artefact above goes. Over 3.5 to 8 m of ground, the 8-bit texture had three backward steps of about 15 mm and four lone texels 8 to 12 mm off. The half-float one had none of them.
- What remains is the ground. Deviations of 3 to 20 mm sit on the same rows with the same size in both formats, so they are relief the renderer really drew.
- The 8-bit decode reads short by the same weighting error: 3.2 cm at 8.3 m.
- Normals from it are clean. On bare ground, 98% of texels turn by less than 2° from one row to the next at a one-pixel baseline, and the count grows with a wider baseline, which is what real bumps do and noise does not.
Half floats cost twice the memory of both targets: about 41 MB more at 1080p with four samples.
Patched before the device exists, from a plugin's load, the renderer creates both targets in half
floats from the first frame, and every engine reader works on them unchanged; a plugin that finds the
texture by its format has to accept D3DFMT_A16B16G16R16F too (seen in game, GOG v1.03). Sky
Overhaul does this, in src/engine/linear_depth.cpp.
Cut-out materials
Read from Dunia.dll (Steam v1.03).
Around 0x1040E9CC the renderer sets up a cut-out material. With alpha-to-coverage it goes through
the drivers' own switches, D3DRS_ADAPTIVETESS_Y set to 'ATOC' on NVIDIA and D3DRS_POINTSIZE set
to 'A2M1' on AMD, and back to zero or 'A2M0' for everything else. Either way it then sets
D3DRS_ALPHATESTENABLE, followed by the material's D3DRS_ALPHAREF.
Which switch it uses follows the adapter's vendor ID, read at device creation (0x10425177): 0x10DE
for NVIDIA, 0x1002 for AMD. NVIDIA's path is taken only if CheckDeviceFormat accepts the 'ATOC'
format, and it keeps the alpha test on beside the switch. AMD's path is taken without asking, and it
turns the alpha test off, leaving the cut-out to the driver. Under dgVoodoo 2.87.6 with four-sample
antialiasing, grass and leaves draw solid while its AdapterIDType is unset and cut out once it is
nvidia (seen in game, GOG v1.03).
Retail GOG v1.03 at 1920×1080 with four-sample multisampling, standing in a grass field, counted from an FCSE plugin that stencil-marked draws and counted the marked samples at the sky pass.
Neither state names the grass. Draws with alpha-to-coverage on covered about 5% of the frame's
samples, the detailed blades nearest the camera. Draws with alpha test on covered about 7%. The grass
carpet that fills the rest of the field is instanced: draws with D3DSTREAMSOURCE_INDEXEDDATA set
on stream 0 covered 25 to 45%. Two-sided draws covered 30 to 50%, and blended or depth-equal ones
none.
The engine's .rs render-state files use only the stencil's top bit. Marking draws with 0x40
collides with nothing, and the marks are still there at the sky pass.
Marking foliage in the stencil
Retail GOG v1.03 at 1920×1080 with four-sample multisampling, marks drawn from an FCSE plugin and shown by drawing through the stencil at the sky pass.
- Mark in the depth prepass. Every draw in the colour passes already runs with the stencil enabled, so a mark that waits for draws with the stencil off never happens there. The depth prepass draws with it off, and nothing clears the stencil between it and the sky pass.
- Clear the bit on every other depth-prepass draw. Only foliage marks, but a solid draw in front of foliage has to take the mark away again.
- Restrict it to the world's depth surface. The shadow cascades and the water reflection write depth too, into surfaces of their own.
- Put back every stencil state changed. The engine filters redundant state, so a stencil function left behind is what its next stencilled draw runs under.
- Neither render state names foliage. Marking instanced and alpha-tested draws also marks the rocks the collection system scatters, cut-out road signs, and tree trunks in the distance.
- Its vertex shader does. The grass material's shaders are the only ones that bind the wind and mesh decompression without a world matrix, and the leaf shaders bind the leaf morph or level-of-detail constants. Matching the bound vertex shader's CRC-32 against those objects marks grass and leaves and nothing else. See shader objects.
A shader cannot read the stencil. To use the marks as a texture, draw white through them into a
render target at the world's multisampling, which can share the world's depth-stencil surface, and
StretchRect it into a plain texture. What arrives is each pixel's share of foliage samples.
Ambient occlusion on this frame
Retail GOG v1.03 at 1920×1080 with four-sample multisampling, from an FCSE plugin that was built, tested and then removed from Sky Overhaul.
Ground-truth ambient occlusion works on the half-float linear depth. It ran at half resolution, with 2 slices and 6 steps per side and a fixed 4×4 pattern cancelled by a depth-aware blur. It was drawn at the sky pass, so most blended draws and the weapon come after it. Flat ground stayed white, corners darkened, and nothing moved with the camera.
- Foliage has to be left out twice. As a receiver it shades every blade. As an occluder it darkens the ground behind and between the grass.
- A pixel only partly covered by a blade counts as foliage. Its resolved depth lies between the blade and the ground, which the occlusion reads as a small occluder floating in front. Those move with the wind, and the ground behind grass flickered until any coverage at all was excluded.
- The ambient term is separable only in source. The prototype's
aaa.fxadds a hemisphere ambient after the direct light has been shadowed, so one multiply there would touch nothing else. Retail ships compiled shaders, so a plugin multiplies the finished colour instead. - Ubisoft's own attempt came later. The Far Cry 3 Blood Dragon debug package in
tools/third-partycarries a port of NVIDIA's HBAO as a Direct3D 11 compute shader over a linear depth texture. Its Direct3D 9 blur variant samples an encoded depth through the sameDepthVPSamplerstate.
It was not taken further, in favour of other work.
The obvious move — detour the sun's draw and issue the query from inside it — does not work, and fails silently rather than loudly. Those functions submit packets and return; the Direct3D calls happen later, when the frame graph is executed. A hook there runs before any of the frame's world passes, against whatever target and depth buffer the previous work left bound, so a query issued from it counts nothing and a draw lands somewhere invisible. See the sky and cloud system.
Drawing into the world's frame
What the device does to anything drawn into a pass, all of it measured with the sun-glare effect in
mods/sky-overhaul.
The device is reset, not recreated
Dunia.dll:0x104225E0 calls TestCooperativeLevel and classifies D3DERR_DEVICELOST and
D3DERR_DEVICENOTRESET separately, so an alt-tab or a resolution change goes through
IDirect3DDevice9::Reset and the device pointer survives. Any D3DPOOL_DEFAULT resource still
outstanding makes that Reset fail, and a failed reset is the game breaking rather than the plugin
misbehaving, so a plugin holding a render target must release it first.
The engine brackets its own reset with a teardown and a restore, each __thiscall taking only
this. Detouring the teardown is the seam that lets a plugin let go in time.
| Routine | GOG / retail v1.03 | Steam / Ubisoft Connect v1.03 |
|---|---|---|
Device teardown, before Reset | 0x104168A0 | 0x104246E0 |
Device restore, after Reset | 0x10416F50 | 0x10424D90 |
Detecting the change afterwards and rebuilding is not an alternative. The outstanding resource is exactly what stops the reset from happening, so there is nothing to detect.
An occlusion query counts samples, not pixels
A 32×32 patch drawn into a world pass returns 4096, not 1024 — four samples per pixel, matching the
D3DMULTISAMPLE_4_SAMPLES in the frame table. Readings of 0/4096 behind a wall, 4096/4096 in
the open and fractional values through foliage confirm the counting works as expected once the
patch is drawn in the right pass.
The multiplier is a property of whichever surface the query ran against, and nothing publishes it. Issuing a second query over the same patch with depth testing off gives the total, and the ratio of the two cancels the multiplier whatever it is. That also survives a build or a preset that multisamples differently.
Eight-bit targets cannot accumulate small weights
The world composites at back-buffer format, so a plugin's own accumulation targets usually are too.
Blending a frame in at weight w moves the destination by w times the difference, and below about
one part in 255 that product rounds to zero and the target never moves at all.
This is not a corner case here. Measured frame rates reach roughly 490 per second at 1280×720 facing
open sky, so a running mean over a five-second window has a per-frame weight near 0.0004 and stalls
completely: the target keeps whatever the first frame wrote. The symptom is an accumulation that
looks correct for a fraction of a second and then freezes, with nothing in any log. Either use a
blend that does not depend on small increments, such as D3DBLENDOP_MAX, or give the target a
format with room to accumulate.
What a mid-frame draw has to put back
A draw at Present is after everything and can be careless. A draw inside a pass the engine still
owns cannot, because the engine's redundant-state filtering assumes nothing else touched the device.
The full list one screen-space quad disturbs is in mods/sky-overhaul/src/engine/screen_draw.cpp.
Two entries on it are not obvious:
- Stream zero.
DrawPrimitiveUPleaves it unbound. An engine that filters redundantSetStreamSourcecalls then re-binds nothing and draws nothing for the rest of the frame. - The vertex declaration, not the vertex format. With a declaration bound,
GetFVFreturns 0, so restoring the format alone restores nothing.
Shader constant registers are the asymmetric case. A plugin that reads the camera out of c4, c8
or c46 during a world pass — see what a shader is given
for the full map — depends on state that a second plugin drawing into the same frame could
legitimately overwrite. Nothing in the loader arbitrates device state; it arbitrates addresses only.
Getting the camera out of a pass, and the wrong way to do it
A screen-space effect that reaches into the world needs where the camera is and where each pixel
looks. Both are in the constants the viewport provider leaves bound, and all of them are live in
the sky pass: CameraPosition at c45, CameraDirection at c46, CameraRight at c53,
CameraUp at c54, and the projection at c8, whose first two diagonal entries are how far off
centre the frustum's edges sit. The direction through a corner of the viewport is then
corner = direction + right * (±1 / projection[0][0]) + up * (±1 / projection[1][1])
The obvious alternative is to invert ViewProjectionMatrix at c4 and unproject the corners.
Measured against the registers above in a running game, that recovers the camera position to
within 1.5 mm — but the directions only to within about 0.01 in unit-vector terms, which is
half a degree, and half a degree is 35 m of error at a kilometre.
The reason is the subtraction it ends with. A corner's direction comes out as a far-plane point minus a near-plane point, both unprojected from a transform built around world coordinates in the thousands, and the near plane here is 0.1 m away. The error is small against the world's scale and large against the tenth of a metre being recovered.
It reads in game as a rigid layer stepping around a fixed position whenever the view moves, and holding still the moment it stops — not as blur or noise, which is what makes it easy to misdiagnose as aliasing.
The sky pass's state
Measured from a plugin logging its own draws, retail GOG v1.03 at 1280×720:
- The world's colour target alternates between
A16B16G16R16FandA8R8G8B8frame to frame, bothD3DMULTISAMPLE_4_SAMPLES, with aD24S8depth surface multisampled to match. - A frame can hold more than one pass with the sky's viewport. Usually one, but two while the menu is open. Anything that blends has to draw into one of them only, or it composites over itself.
- Depth bias, multisample mask, sRGB write, stencil and both alpha-to-coverage tokens are all at their neutral values in that pass, so a blended draw inherits nothing that would spoil it.
- The far plane is about 1000 m, and the world's distance fog is fully saturated by 420 m
(
FogValues.xis 1/400). An effect further out than that cannot use the distance fog the terrain uses; the sky's own fog is a function of height and heading instead. - Drawing at depth exactly 1.0 with
D3DCMP_LESSEQUALoccludes correctly at any distance, because the sky writes no depth and the cleared far value is what remains wherever the world drew nothing. A value merely close to one stops occluding roughlynear / (1 - z)metres out.
Bringing a shader of your own
A plugin's own pixel shader needs no D3DX and no DirectX SDK. fxc.exe ships with the Windows SDK
the MSVC toolchain already requires, and a developer prompt puts it on PATH, so the shader can be
compiled at build time straight into a header the plugin embeds and hands to CreatePixelShader.
The generated array is bytes; CreatePixelShader wants whole tokens, so it has to be copied into an
aligned buffer on the way through.
Target ps_2_0 unless the instruction count forces ps_2_b. Both pair with the fixed-function
vertex pipeline and a D3DFVF_XYZRHW | D3DFVF_TEX1 quad, which is the documented Direct3D 9
post-process pairing and needs no vertex shader at all.
ps_3_0 is the second working shape, and worth the machinery once an effect needs loops, volume
textures or screen-space derivatives. It requires a matching vs_3_0, which in turn requires a
vertex declaration rather than an FVF, and a quad in clip space rather than a pretransformed one.
That pairing is what carries a per-corner direction into the pixel shader: put the ray in the
vertex, give every corner w = 1 so the interpolation stays linear, and take no half-pixel
offset — that rule is for reading a texture by screen position, and a direction belonging at the
viewport's edge is already where a rasteriser interpolating to a pixel centre expects it.
The engine's draws and pass ends, before Direct3D
The renderer reaches IDirect3DDevice9 through the engine's own D3D9 device class, which holds the
game's device pointer at this+0x38. Every draw of the world and every pass end go through four of its
methods, every presented frame through a fifth and every device reset through a sixth (RE-verified,
Steam v1.03; the GOG addresses through the address library and patterns):
| Slot | Steam | GOG | Method | Calls |
|---|---|---|---|---|
| 14 | 0x10423060 | 0x10415220 | BeginScene() | targets, viewport, clear, then device slot 41 |
| 15 | 0x10422510 | 0x104146D0 | EndScene(), 22 bytes | clears the renderer's in-scene flag, then slot 42 |
| 16 | 0x10424150 | 0x10416310 | Present(HWND), ret 4 | its own end-of-frame work, then device slot 17 at 0x104244DC, between two calls of 0x10408A90 |
| 21 | 0x10422630 | 0x104147F0 | Reset(), returns true when Direct3D's reset succeeded | slot 77 of its own, then device slot 16 with the stored present parameters |
| 55 | 0x10423A70 | 0x10415C30 | DrawPrimitive(type, startVertex, count), ret 0xC | the flush, then slot 81 |
| 56 | 0x10423AF0 | 0x10415CB0 | DrawIndexedPrimitive(type, base, minIndex, vertices, startIndex, count), ret 0x18 | the flush, then slot 82 |
All are __thiscall. type is the engine's own primitive enum, turned into Direct3D's through a
table at Steam 0x10E53004: 0 and 6 are triangle lists, 1 and 2 strips, 3 a line list, 4 a line
strip, 5 a fan. The count reaches Direct3D as at least 1.
The flush (Steam 0x10422EB0, GOG 0x10415070, __cdecl(IDirect3DDevice9*), called only by the two
draws) uploads the shader constants the engine has changed since the last draw. The engine keeps a
copy of both constant files (Steam 0x1160A080 vertex, 0x1160B080 pixel, a float4 each) with a
dirty range per file, uploads that range and resets it, so a second call sends nothing. A hook on a
draw that calls the flush first finds on the device exactly what the draw will see, and can change it
before the engine's own draw runs. A few parameter blocks are uploaded directly rather than through
the copies (0x1041AE80, 0x1041B130), so the copies alone are not the whole of what is on the
device.
Inside the renderer these two draws are the only callers of Direct3D's DrawPrimitive and
DrawIndexedPrimitive, and slot 15 the only caller of EndScene; the interface's renderer
(0x10ACA570 and Magma's Read* functions) draws on its own. So a hook here sees every world draw
and pass end and nothing of another plugin's, and anything it calls on the device at this+0x38 goes
the way the game's own calls go, through whatever wrapper the game was given. The address library
does not carry slot 15; a pattern of its whole body finds it in both builds.
Slot 21 is the only caller of Direct3D's Reset in the renderer, and it runs on a window resize
too, ahead of that Reset; a plugin that frees its D3DPOOL_DEFAULT objects at its entry lets the
reset succeed (seen in game, GOG v1.03). It is a function apart from the device teardown at slot 20, which the address
library does not carry.
Slot 16 does work of its own before it presents, its own frame captures among them, so a draw over
the finished frame belongs just before its call to Direct3D's Present, where ESI holds the engine
device. Around that call 0x10408A90, a compare-and-swap spin on a device token at 0x1160966C,
turns the token from 2 to 1, which lets a loading thread borrow the device while Present runs, and
back to 2 after it. A draw belongs outside that pair, where the render thread owns the device: at
0x104244B3, the mov ebp, 1 that starts the hand-over, and at 0x104244E8, just after the device
is taken back. Neither slot 16 nor those sites are in the address library; a pattern of the call with
the hand-over around it finds them in both builds.
Sky Overhaul and Aiming Overhaul both hook slots 15, 55 and 56, and Vehicle Overhaul, Inventory
Overhaul, Third Person and DevTools slot 15; FCSE chains them. Aiming Overhaul, Vehicle Overhaul,
Inventory Overhaul and DevTools free their objects at slot 21, Sky Overhaul at the teardown. DevTools
draws its overlay at the Present call inside slot 16.
A .vso reaches Direct3D through the engine as well. The engine's vertex shader object loads one at
slot 4 of its vtable (Steam vtable 0x10E52868, method 0x1041A990, __thiscall, ret 8, the
.vso file's bytes as its first argument). It reads the parameter table, then calls the device's
CreateVertexShader with the bytecode at the offset the header gives, storing the shader at
this+0x13C, and does not check the result (RE-verified, Steam v1.03). At the load of that call
(Steam 0x1041A9ED, GOG 0x1040CB9D) its arguments, the device, the bytecode and the out pointer,
are on the stack, so a mid-hook there can hand the device other bytecode. UFCP swaps the grass
spot-light passes there. The address library carries neither address; a pattern of the call finds
the site in both builds.
Texture binds, before Direct3D
A shader parameter that holds a texture binds it with a small method of its own, __thiscall(this, IDirect3DDevice9* device, const WORD* sampler) with ret 8, which calls Direct3D's SetTexture
directly (RE-verified, Steam v1.03):
| Steam | Holds at this+0x0C | Sampler |
|---|---|---|
0x10437570 | a device texture (CTextureD3D9, its Direct3D texture at +0x18) | vertex, *sampler + 0x101 |
0x104375C0 | a device texture | pixel, *sampler |
0x10437600 | a texture (its device texture at +0x0C) | vertex, *sampler + 0x101 |
0x10437660 | a texture | pixel, *sampler |
The interface binds through the pixel pair: Inventory Overhaul's marker textures go through
0x104375C0 and the map's paper through 0x10437660 (seen in game, GOG v1.03). The address library
carries none of the four; a pattern of each body, past its first seven bytes, finds it in both builds.
DirectInput 8, and the mouse messages that never arrive
Input comes up in 0x102afff0, which calls DirectInput8Create with the IID at 0x10eda224 —
{BF798030-483A-4DA2-AA99-5D64ED369700}, which is IID_IDirectInput8A. The ANSI interface,
matching the rest of the engine's Win32 use (RegisterClassExA, CreateWindowExA,
PeekMessageA). Only the ANSI device vtable is ever created, so only IDirectInputDevice8A needs
attention.
The mouse is held exclusively — SetCooperativeLevel with DISCL_EXCLUSIVE | DISCL_FOREGROUND,
or non-exclusive with -noexmouse or -nomouse (0x102c5e30 in the GOG build, RE-verified) — and
that has a consequence nothing in the API announces:
Windows delivers no mouse button or movement messages to a window whose mouse is held
exclusively through DirectInput. WM_LBUTTONDOWN and WM_MOUSEMOVE simply never arrive, so an
overlay subclassing the window sees a pointer that hovers — GetCursorPos still tracks, so
position-driven behaviour works — and a mouse that can never click. Buttons have to be read
directly, from GetAsyncKeyState or from the DirectInput data itself.
What does still arrive: WM_KEYDOWN, WM_CHAR and, unexpectedly, WM_MOUSEWHEEL. The keyboard is
not suppressed the way the mouse is, and the wheel follows keyboard focus rather than the mouse
capture. So a subclassed window is enough for typing, hotkeys and scrolling, and short by exactly the
buttons and the movement.
Taking input away from the game means answering both halves. Window messages stop at a subclassed
WndProc. Everything that moves the player comes through IDirectInputDevice8A::GetDeviceState
(vtable slot 9) and GetDeviceData (slot 10) instead, where a message hook has no reach — those are
answered with an all-zero state, which the engine reads as an idle device. Failing them instead is
wrong: a refused read looks like a lost device and sends the engine off to reacquire it. A buffered
GetDeviceData still has to be drained and then reported as empty, or the events queue up and all
arrive at once when the overlay closes.
Gamepads are XInput only
DirectInput creates only the system mouse and the system keyboard; no joystick device is ever made.
Gamepads come from XINPUT1_3.dll alone: XInputGetState in the poll (GOG 0x102C7A60) and
XInputSetState for rumble. The pad slot is claimed per process. The engine probes the mutexes
LocalNomadPadInput0 to 3, takes the first that does not exist yet, and creates it. All of this
is RE-verified on GOG.
Where rebinds are kept
Rebound controls live in a file of their own, %APPDATA%InputUserActionMap.xml, not in the
shipped action maps. The keyboard and controller options page (GOG constructor 0x10818E10) is the
only code that names it. It writes the file, creating the folders on the way, and reads it back
when the file exists. The shipped config\inputactionmapcommon.xml, in both common and patch,
imports it as an optional file right after the console's map:
<Import file="%APPDATA%InputUserActionMap.xml" optional=""/>
This is RE-verified on GOG and seen in data. Which folder %APPDATA% expands to was not
traced.
Action signals and their listeners
A bound input reaches the game as an action signal, a CActionValue: the signal's CStringID at
+0x00, up to three float values from +0x04, and at +0x10 how many of them it has, which is how
the demo reader fills it in. The player acts only
when that count is above zero. CTerminalImpl::Execute hands the same object to each
of the terminal's listeners in the order they registered, and ignores what they return. The pause
service's listener (CFCXPauseMultiService, Steam 0x1071AF40) comes before the player's. So a
listener ahead of the player's can rewrite the signal's id in place, and the player's sees the new
one. An id no listener knows makes the signal do nothing. mods/inventory-overhaul does this to Tab,
and to the mouse wheel while its notebook is up.
The wheel is cycleweapon, an update binding whose value is the turn: below zero for a turn
towards the user, which moves down a list (seen in game).
The menu cursor
0x104EFAD0 moves the menu cursor from a two-axis signal: speed (+0x88) times each axis times
the frame time, added to the cursor's 16-bit pixel position after a truncation toward zero. A
movement below one pixel in a frame is lost, and more of it is lost the higher the frame rate.
RE-verified on Steam. UFCP carries the dropped fraction into the next frame, as FC2JackalFix
does.
What this is enough to build
DevTools' overlay is exactly the above and nothing else: a mid-hook just before the engine's
Present calls Direct3D's, the engine's Reset hooked to let go of what it holds, the back buffer
bound explicitly for the draw, the window subclassed, and the two DirectInput reads answered while it
has the input — see mods/DevTools/src/engine/ and mods/DevTools/src/overlay/.
Sky Overhaul is the other shape: an effect that belongs inside the world's frame rather than over
the finished one. It follows the engine device's EndScene and draws, classifies each pass, measures
the sun against the scene's depth during the sky pass, and paints over the composite so the result
lands under the interface.
mods/sky-overhaul/src/engine/ holds those three concerns — following the frame, guarding device
state, and letting go before a reset — in modules that know nothing about the effect itself.
Unknowns
- Which backend a given install runs: whether the D3D10 probe passes on a modern machine.
- Whether substituting a single-sampled
INTZdepth surface at creation actually yields readable scene depth here. The multisampling that rules out the direct route is measured; the substitution is untried, and it would also have to force the colour targets to match. - Whether water surfaces write
"Linear depth", and whether the resolve is the engine's ownStretchRector a shader of its own. - Whether the colour passes' stencil write mask covers bit
0x40. Marks made in the depth prepass survive to the sky pass, so it does not clear them, but it has not been read. - What the dozen blended draws before the sky pass are.
- Where the engine stores the result of its own flare visibility query. The readback wrapper is known; the functions around it are undefined code in the Ghidra project.