Dunia.dll — The Editor-Facing API Surface (FCE_*)
See the overview for binary identification. Companion to the Lua-exposed API
surface: that page maps the mission/gameplay scripting surface
(RegisterLuaBinding); this page maps a completely different, non-scripted surface — the flat C API
the stock map editor (FC2Editor.exe) uses to drive the engine directly via P/Invoke.
Source: the stock editor's own decompiled interop layer
tools/third-party/FC2Editor_Source/ is decompiled C# source for the actual
shipped Far Cry 2 map editor — confirmed genuine via AssemblyInfo.cs's
AssemblyCopyright("Copyright (C) 2008 Ubisoft Entertainment"), not a community reimplementation. It's
a thin WinForms shell: every FC2Editor.Nomad class is a managed wrapper around
[DllImport("Dunia.dll")] private static extern ... declarations, all named with an FCE_ prefix
(FarCryEditor). 338 such externs exist, exclusively in FC2Editor.Nomad (FC2Editor.Tools
has none — its classes only call up into the Nomad wrappers).
The PC binary's export table carries these names independent of anything in the C# source, but not
their signatures: without them every one of these functions decompiles as a bare
undefined FCE_Xxx(void) regardless of its real parameter count (e.g.
FCE_CollectionManager_WriteMaskCircle shows as taking no arguments, despite genuinely taking five:
cx, cy, radius, id, update). The C# extern declarations are Microsoft's own P/Invoke marshaling —
ground truth for the real calling convention, parameter count, order, and types — and every matching
Ghidra function carries a typed prototype taken from them: 316 unique names at 317 addresses
(FCE_Document_Export exists at two separate addresses, 0x1082b750 and 0x10a21200). The other 22
names share addresses with unrelated functions — see
Names folded onto shared addresses. Two exports exist in the
binary that this particular editor build never calls (ShutdownDuniaEngine,
FCE_ObjectRenderer_SetActive), so the export table is a superset of what this WinForms shell
consumes.
Every function below has a decompiler-confirmed, source-verified signature — not inferred from disassembly, but taken directly from the original developers' own interop layer.
Second source: the Linux dedicated-server ELF
FarCry2_server exports the same FCE_* surface and keeps far more type information than
Dunia.dll — real class names, member-function names, and a distinct address per function where the
Windows build folds identical bodies together. Its ~345 exports corroborate this page.
The empty stubs are genuinely empty. In the ELF, FCE_Document_Export and all ten
FCE_Inventory_Object_*Pivot* / *ZOffset functions each occupy their own address, take no
arguments, and have bodies consisting of a bare return (or return 0) — so the identical-COMDAT
folding that merges them in Dunia.dll merges compiled-out stubs, and nothing is folded away.
Behaviour that the C# interop layer does not show:
LoadandSaveare asynchronous.FCE_Document_Loadalways returns success; the real outcome arrives later as anEResultCodehanded to theLoadCompleted/SaveCompletedcallbacks. Both push an editor state and raise a wait screen first.- The two Euler entry points disagree on component order.
FCE_Core_GetAnglesFromDirwrites pitch into component X and leaves Y zero, whileFCE_Core_GetAnglesFromAxisandFCE_Core_GetAxisFromAnglesput pitch in component Y. Reading the triple as a fixed pitch/roll/yaw across the whole API is wrong. - Splines are 2D.
FCE_Spline_AddPoint,SetPointandInsertPointall zero Z before storing; points arendVec3but the third component is never authored through this API.FCE_Spline_UpdateSplineHeightalways passes the whole-map rect, with no partial-region variant exported. FCE_Texture_Paintremaps its slot argument before use — 1→1, 2→0, 3→3, anything else→-1 — so the value passed is not the layer index the engine ends up using.- The terrain brush calls share one shape,
(x, y, strength, brush), writing into a shared per-filter singleton rather than taking a context. See Terrain, Sectors and Vegetation for the pipeline and for the eight-slot ceiling on collections thatFCE_CollectionManager_*operates against. FCE_Draw_WireBoxFromBottomZshuffles its arguments on the way through, passing them to the scene primitive helper in the order 4, 6, 5, 7.
The API, grouped by subsystem
Camera
Free-fly editor camera. Position/Angles (get/set), FrontVector/RightVector/UpVector (get,
orthonormal basis), FOV/Speed/SpeedFactor, Input_Forward/Input_Lateral (movement injection),
Rotate(pitch, roll, yaw).
Engine
Lifecycle: InitDuniaEngine(hInstance, focusWnd, renderWnd, cmdLine, launchGame, forceGpuSync, messagePumpCallback) → RunDuniaEngine → TickDuniaEngine (per-frame pump) → CloseDuniaEngine.
Also AutoAcquireInput, PersonalPath (user data dir), StormFactor, TimeOfDay, ConsoleOpened,
UpdateViewport(sizeX, sizeY).
Localizer
LocalizeText(section, text) — the one Dunia export not FCE_-prefixed; backs all in-editor string
localization (InGameEditor_PC/InGameEditor sections).
EditorDocument
Map lifecycle: Load/Save(mapPath, mapName), Reset, Validate, FinalizeMap,
Export(mapFile, exportPath, toConsole). Metadata: AuthorName/CreatorName/MapName (strings),
BattlefieldSize/PlayerSize (enums). Snapshot: ClearSnapshot, IsSnapshotSet,
SnapshotAngle/SnapshotPos, TakeSnapshot.
CFCXEditorToolTerrainTerrace is a complete tool class that the stock editor never wires to a
toolbar — the terrain toolbar binds F1–F7 to Bump, RaiseLower, SetHeight, Smooth, Ramp, Noise and
Erosion, with no entry for it. Driving it directly shows why: brief applications terrace correctly,
but held application diverges and destroys the terrain.
TerrainManager / TerrainManipulator
TerrainManager: WaterLevel, GetHeightAt(x, y), texture-layer slot binding
(AssignTextureId/ClearTextureId/GetTextureEntryFromId).
TerrainManipulator — the terrain sculpting brushes (each a Begin/apply/End triple, matching the
brush-model hotkeys F1–F7 documented in Engine Theory): Bump,
Erosion(radius, density, deformation, channelDepth, randomness), Grab(ratio), Noise(numOctaves, noiseSize, persistence, NoiseType), RaiseLower, Ramp(ptStart, ptEnd, radius, hardness),
SetHeight, Smooth, Terrace(height, falloff).
Collections (foliage/prop scattering)
CollectionInventory: tree navigation (GetRoot/GetChild/GetChildCount/GetDisplay/GetParent) plus a
burn-profile flag. CollectionManager: AssignCollectionId/ClearMaskId/GetCollectionEntryFromId
(slot binding), UpdateCollections(rect) (refresh scattered instances), WriteMaskCircle/
WriteMaskSquare(cx, cy, radius, id, update) (paint the density mask). CollectionManipulator:
Paint/Paint_End (interactive brush).
CoordinateSystem
GetAxisFromAngles/GetAnglesFromAxis — Euler ↔ 3-axis orthonormal basis, both directions.
GetAnglesFromDir (in Vec3.cs) — direction vector → Euler angles.
Editor
Callback registration (engine → managed, all void* function pointers): Update_Callback,
Event_Callback, LoadCompleted_Callback, SaveCompleted_Callback, EnableUI_Callback. State:
IsIngame, IsInitialized, IsLoadPending, ValidateIngame, ToggleIngame, GetFrameTime.
Screen/world conversion: GetScreenPointFromWorldPos, GetWorldRayFromScreenPoint. Raycasts:
RayCastPhysics/RayCastPhysics2 (object-ignore vs. selection-ignore overloads), RayCastTerrain.
EditorObject
Per-instance placed-object handle. Lifecycle: Create_FromEntry(entry, managed), AddRef/Release,
Clone, Destroy. State: IsLoaded, GetEntry, Position/Angles, GetBounds(world),
IsVisible, SetHighlight, SetFreeze. Placement: DropToGround(physics),
ComputeAutoOrientation(pos, angles, normal), GetPivot/GetClosestPivot(minDist),
SnapToClosestObject, GetPhysEntities.
EditorObjectSelection
Multi-object selection set. Membership: Create/Destroy, Get(index)/Count, Add/AddSelection,
Clear, Clone(cloneObjects), Delete, ToggleObject/ToggleSelection,
GetValidObjects/RemoveInvalidObjects. Geometry: GetCenter/SetCenter, ComputeCenter,
GetWorldBounds. Transform: MoveTo(pos, MoveMode), Rotate(angle, axis, pivot, affectCenter) (plus
Rotate3/RotateLocal3/RotateGimbal per-axis variants), DropToGround(physics, group),
SnapToPivot(source, target, preserveOrientation, snapAngle), SnapToClosestObjects. Undo-adjacent:
ClearState/LoadState/SaveState.
EditorSettings
Global editor toggles — visibility (Grid, Icons, Fog, Water, Shadow, Collections), snapping
(AutoSnappingObjects, AutoSnappingObjectsRotation, AutoSnappingObjectsTerrain,
SnappingObjectsToTerrain, GridResolution), gameplay/dev (Invincible, KillDistanceOverride,
SoundEnabled, CameraClippedTerrain, EngineQuality: Low…UltraHigh/Optimal/Custom).
Gizmo
The 3D move/rotate manipulator widget. Create/Destroy, Position, Axis (3-basis-vector frame),
Active (FC2Editor.Nomad.Axis enum: X/Y/Z/XY/XZ/YZ), Redraw, Hide, HitTest(raySrc, rayDir) → Axis.
Small value-type helpers
ImageMapEngine: GetSize, ConvertTo24bit(data, stride, min, max), Clone. Points:
Create/Destroy — opaque point-list handle used by terrain wireframe drawing. PaintBrush:
Create(circle, radius, hardness, opacity, distortion) — the shared brush descriptor used across
every terrain/texture/collection paint call. PhysEntityVector: physics-entity handle list used by
raycast-ignore and drop-to-ground calls. Snapshot: Create(width, height), GetData(data, width, height, pitch) — offscreen render target for object thumbnails.
Render
Immediate-mode debug/gizmo drawing: BeginGroup/EndGroup, Arrow, Dot, SegmentedLineSegment,
WireBoxFromBottomZ, WireRegionFromTerrain, screen-space ScreenCircleOutlined/
ScreenRectangleOutlined, and terrain-projected Terrain_Circle/Terrain_Square(center, radius, penWidth, color, zOrder) — the brush-radius preview rings visible while sculpting/painting.
ObjectInventory / ObjectManager / ObjectRenderer / ObjectViewer
ObjectInventory: placeable-object catalog tree, plus pivot/orientation metadata (GetPivotCount,
IsAutoOrientation, IsAutoPivot, GetZOffset). ObjectManager:
GetObjectFromScreenPoint(includeFrozen, ignore) (click-to-pick raycast), GetObjectsFromMagicWand
(select-similar), GetObjectsFromScreenRect (marquee select), UnfreezeObjects. ObjectRenderer/
ObjectViewer: async thumbnail-render pipeline for the object browser (RenderObject(entry) →
offscreen Snapshot → cached PNG by entry ID) plus the preview-viewport pane.
Splines (roads/zones)
Spline (base class): Create, AddPoint/InsertPoint/RemovePoint/RemoveSimilarPoints/Clear,
point indexer, HitTestPoints/HitTestSegments, OptimizePoint, Draw(penWidth, controller),
FinalizeSpline, UpdateSpline/UpdateSplineHeight. SplineController: selection/editing overlay
(SetSpline, SelectFromScreenRect(rect, penWidth, SelectMode), MoveSelection, DeleteSelection).
SplineInventory: road-type preset catalog tree. SplineManager: CreateRoad(id)/DestroyRoad(id),
GetRoadFromId(id), GetPlayableZone() — road slots (max 8) plus the single playable-area zone.
SplineRoad/SplineZone extend Spline with Entry/Width and Reset() respectively.
TextureInventory / TextureManipulator
TextureInventory: texture catalog tree. TextureManipulator: Paint(center, amount, id, brush) —
terrain texture-layer painting — plus PaintConstraints_Begin(minHeight, maxHeight, heightFuzziness, minSlope, maxSlope)/PaintConstraints/PaintConstraints_End — a height/slope-constrained
auto-texturing pass (e.g. "paint rock only above this slope").
UndoManager
RecordUndo/CommitUndo, Undo/Redo, UndoCount/RedoCount — the transaction API wrapped around
every editing operation above.
Validation
Validation.ValidateGame()/ValidateGameMode(GameModes) → ValidationReport runs the map-integrity
checks referenced by ToolValidation.cs. ValidationReport: GetCount, GetRecord(index).
ValidationRecord: GetFlags (None/Validation = 0x20), GetMessage, GetObject →
EditorObject.
BudgetManager
MemoryUsage (int) / ObjectUsage (float, fraction-of-budget) — the resource-budget meters shown in
the editor UI.
The budgets behind them are constants, set in the budget manager's constructor (GOG 0x1082A040)
(RE-verified):
| Budget | Limit | Checked by |
|---|---|---|
| Memory | 100 MiB | IsMemoryWithinBudget (0x1082A550) |
| Objects | 40,000 cost units | CanAddObjectCost (0x1082A180) |
| Objects per area | 10,000 cost units | Validate (0x1082E740) |
| Undo history | 5 MiB, each state charged its size plus 1 KiB | TrimToBudget (0x107D3370) |
The first three are skipped when CFCXEditor::Init was given its pcHosted flag; the undo budget
always applies. By its name the flag marks a PC-hosted editor such as FC2Editor, but what FC2Editor
passes was not traced. Areas are indexed x + 1 + y·8; their size in metres was not checked.
Wilderness (procedural terrain generation)
GenerateDesert(gradientWidth, gradientHeight, distorsion, noiseAdd, blurRadius). Three ways to run a
"Wilderness script" against the terrain: RunScript(scriptName), RunScriptBuffer(buffer, mapCallback, errorCallback), RunScriptEntry(entry). WildernessInventory: catalog tree of saved
Wilderness scripts. This is also a small, self-documenting reflection surface —
NumFunctions/GetFunction(index) walk a table of all 37 builtin functions' names, call prototypes,
and descriptions, compiled directly into the binary as literal strings. See the dedicated page on this
language for the full reference, recovered entirely from static data
with no game/editor execution needed.
Hosting the engine
InitDuniaEngine takes two external window handles — a top-level focus window and a separate
render window — so the engine can be driven inside a host application's own UI rather than a window
it creates itself. Passing a non-null focusWnd also forces windowed mode; passing null makes the
engine create and own its window.
The frame loop stays on the host side. RunDuniaEngine (the engine-owned loop) is exported but goes
unused by the editor, which instead calls TickDuniaEngine once per frame and pumps Win32 messages
itself. The engine calls back into managed code each frame through the Update callback.
FCE_Engine_UpdateViewport(sizeX, sizeY) resizes the render target independently of the host
window's client area, so the back buffer can be smaller than the control it draws into.
Constraints that follow from the API shape rather than from any one function:
- Singleton. No
FCE_*call takes a context or instance handle; there is exactly one engine per process. - Single instance per machine.
InitDuniaEngineopens a named mutexFarCry2Instanceand refuses to start when it already exists, unless launched with both-dedicatedand-norender. - The data root is derived from the host executable's path, not the working directory. See
data-root derivation for the exact rule. Setting the working directory
has no effect; a host started from outside the install reaches
InitDuniaEngineand dies there with an access violation. - Everything is
__cdecl. Every one of the 312 distinctFCE_*export bodies in the GOG build, and every target of the ones that tail-jump, ends in a plainret, neverret imm, so the caller cleans the stack (RE-verified). The callbacks registered throughFCE_Editor_*_Callbackare invoked__cdecltoo. - String marshalling is not uniform. Document paths are passed as explicit UTF-8 byte arrays
split into directory and filename; other string parameters are plain ANSI.
LocalizeTexttakes ANSI and returns UTF-16.
What the API does not cover
The surface is complete for terrain, texture, vegetation, spline and prop authoring, and absent for everything else a single-player level contains:
- No property access.
FCE_Object_*exposes position, angles, bounds, visibility, freeze, highlight, pivots and physics handles — and no property get or set of any kind. A placed object keeps its archetype defaults. - No entity, mission or event API.
<world>.managers.fcbcarriesCEventComponentandhidLinkswiring, andExportWorldSectorsemitsMissionLayerandPathIdtags, but nothing in the API authors either. FCE_Document_Exportdoes nothing. Driving it against a valid document writes no files anywhere; and its address0x10669070is shared, through identical-COMDAT folding, withFCE_Inventory_Object_{AddPivot,ClearPivots,SavePivots,SetPivot,SetPivots,SetAutoPivot,SetZOffset}andFCE_Wilderness_Desert. Folding merges only byte-identical bodies, so that whole group is empty stubs — the export path was compiled out of the shipping build.EditorDocument.Exportand the editor's hidden export menu items are complete on the managed side and call into nothing. Note this also means the seven pivot mutators and the desert generator are inert.- No navmesh generation. The engine contains a complete generator
(
CNavmeshGenerator,CNavmeshEdition,CNavMeshSectorWriter,CNavMeshGenComponent,BuildNavMeshLevel0,AppendNavMeshToSector), but no export reaches it, and the editor's cooker emits no.nvmdata.
Validation is worth reading in this light: CFCXEditorGameValidation checks geometry and budget
only — terrain and collision placement per object type, playable-zone containment, memory and object
budgets, and per-type count caps — plus the four multiplayer game-mode rule sets. Nothing in it
rejects content by archetype. CFCXEditor::ValidateIngame additionally destroys the entities of
any object whose error carries flag 0x40, rather than only reporting it.
Names folded onto shared addresses
22 of the 338 C#-declared names do not turn up as functions of their own in a by-name lookup of this
build of Dunia.dll:
FCE_ImageMap_Destroy, FCE_Inventory_Object_AddPivot, FCE_Inventory_Object_ClearPivots,
FCE_Inventory_Object_GetParent, FCE_Inventory_Object_SavePivots,
FCE_Inventory_Object_SetAutoPivot, FCE_Inventory_Object_SetPivot,
FCE_Inventory_Object_SetPivots, FCE_Inventory_Object_SetZOffset,
FCE_Inventory_Spline_GetParent, FCE_Inventory_Texture_GetDisplay,
FCE_Inventory_Texture_GetParent, FCE_Inventory_Wilderness_GetDisplay,
FCE_Inventory_Wilderness_GetParent, FCE_PhysEntityVector_Create,
FCE_ScriptFunction_GetPrototype, FCE_Spline_Destroy, FCE_Spline_GetNumPoints,
FCE_SplineController_Destroy, FCE_ValidationRecord_GetSeverity, FCE_ValidationReport_Destroy,
FCE_Wilderness_Desert.
Most cluster into two shapes: pure mutators on inventory entries (SetPivot, SetZOffset,
SetAutoPivot, AddPivot, ClearPivots, SavePivots), or Destroy/GetParent/GetDisplay
siblings of functions that have their own address right next to them in the same class.
Enumerating the export table of the GOG build resolves all 22 of these names — they exist,
sharing addresses with unrelated trivial functions through identical-COMDAT folding. Examples:
FCE_Wilderness_Desert and FCE_Document_Export at 0x10669070; FCE_ImageMap_Destroy,
FCE_Spline_Destroy and FCE_ValidationReport_Destroy at 0x1032ea30;
FCE_Inventory_Object_GetParent and FCE_ScriptFunction_GetPrototype at 0x108808b0;
FCE_PhysEntityVector_Create at 0x10883530.
The PE export table holds 404 names at 375 distinct addresses, so a name that appears missing is more likely folded onto a shared address than genuinely absent. The names break down as:
- 334
FCE_* - 32
FCS_Server_* - 8
FCB_Benchmark_* - 6
SND_* - 12 C++-mangled
- 12 plain: the engine lifecycle (
InitDuniaEngine,RunDuniaEngine,TickDuniaEngine,CloseDuniaEngine,ShutdownDuniaEngine),AddFunctionCB,RegisterGameFunctionProvider,GetCRCFromString,GetExePath,LocalizeText,PrintToConsoleandSwitchContext
Ghidra's export listing shows 818 because it lists each export twice, by name and by ordinal, and adds demangled aliases.
When reading other decompiled signatures in this DLL: a void-looking C#
wrapper doesn't always mean the native function is void — FCE_SplineZone_Reset and the
FCE_ScriptFunction_Get* family return a pointer that their C# callers silently discard.