Introduction  Getting Started  Module Index  Quick Start  API Reference
[ Complete API Reference & Documentation ]

XEngine3D

A Windows-native 3D game engine built on OpenGL 1.1 and DirectSound. Provides a complete set of modules for 3D rendering, 2D graphics, input handling, audio playback, AVI video, terrain, MD2 animated models, and file packaging.

 
00

Introduction

XEngine3D is a complete C-language game engine for Windows targeting real-time 3D applications and games. It wraps OpenGL 1.1 fixed-function pipeline rendering with a clean procedural API, and integrates DirectSound for audio, DirectInput for joystick/gamepad support, DirectShow for AVI video cutscenes, and the Windows MCI interface for CD audio and MIDI playback.

The engine is composed of independent header modules. Include only what you need. All engine subsystems are initialized individually and should be shut down in reverse order.

Platform: XEngine3D targets Windows (Win32 API). All functions assume a valid Win32 window handle (HWND) has been created by xInit() before any rendering or input calls are made.
01

Getting Started

Setting up XEngine3D in Microsoft Visual C++ 6.0. Follow these steps to configure your project include paths, library paths, and linker settings before writing your first line of code.

1
Create a new Win32 Application project
Launch Microsoft Visual C++ 6.0. Go to File -> New, select the Projects tab, and choose Win32 Application. Give your project a name, set the location, and click OK. When prompted for the app type, select An empty project.
2
Open the Directories options
In the menu bar, navigate to:
Tools > Options > Directories
This is where you register the engine's header and library paths with the compiler.
3
Add the Include directory
In the Show directories for dropdown, make sure Include files is selected. Click the empty row at the bottom of the list and enter the path to the engine headers:
C:\XEngine3D\Include
Adjust the drive letter and folder name to match your actual installation path.
4
Add the Library directory
In the same Directories dialog, switch the dropdown to Library files. Add a new entry with the path to the engine's compiled .lib files:
C:\XEngine3D\lib
Adjust the path to match where you placed the XEngine3D lib folder.
5
Move both paths to the top of the list
After adding the Include and Library paths, select each one and use the up arrow button on the right side of the list to move them to the very top. This ensures the compiler finds the XEngine3D headers and libraries before any other directories.
6
Create main.c in your project
In the Workspace panel on the left, expand your project tree and right-click the Source Files folder. Choose New -> C++ Source File, name it main.c, and click OK. The .c extension tells MSVC to compile it as C rather than C++.
7
Open Project Settings -> Link tab
In the menu bar, go to:
Project > Settings > Link
Make sure All Configurations is selected in the Settings For dropdown so the changes apply to both Debug and Release builds.
8
Add the required libraries
In the Object/Library modules field, append the following libraries at the end of whatever is already there (leave a space before them):
xengine.lib opengl32.lib glu32.lib winmm.lib
xengine.lib is the main engine library. opengl32.lib and glu32.lib are the standard Windows OpenGL libraries. winmm.lib is required for CD audio and MIDI via the Windows MCI interface.
9
Ignore the LIBCMT library
Still in the Link tab, look above the current category for the General sub-category. Switch to Input and find the Ignore libraries (or Ignore specific library) field. Enter the following value:
LIBCMT
This prevents linker errors caused by conflicting C runtime library versions between the engine and your project.

Setup Complete

Your project is now fully configured. You can start writing code using the XEngine3D API. Begin with xInit() to create a window and OpenGL context, then build your game loop around xIsRunning(), xBeginFrame(), and xEndFrame(). See the Quick Start section for a minimal working example.

02

Module Index

03

Quick Start

Minimal application skeleton demonstrating engine initialization, the main loop, and shutdown.

#include "xengine.h"
#include "xsound.h"

int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR lpCmd, int nShow)
{
    /* 1. Initialize engine: creates window and OpenGL context */
    if (!xInit(hInst, 800, 600, "My Game"))
        return 1;

    /* 2. Initialize subsystems */
    xSoundInit(xGetWindow());
    x3DInit(xGetWidth(), xGetHeight());

    /* 3. Load assets ... */
    TCamera cam;
    x3DCreateCameraFPS(&cam, x3DVec3(0, 2, 5), 0.0f, 0.0f);

    /* 4. Main loop */
    while (xIsRunning())
    {
        xProcessEvents();
        xTimerUpdate();
        xKeyboardUpdate();
        xMouseUpdate();

        if (xKeyPressed(KEY_ESCAPE)) xQuit();

        xBeginFrame();
        xClear(BLACK);

        x3DBegin();            /* start 3D rendering */
        x3DSetCamera(&cam);
        /* ... draw 3D scene ... */
        x3DEnd();              /* return to 2D mode */

        xEndFrame();
    }

    /* 5. Shutdown */
    xSoundShutdown();
    xShutdown();
    return 0;
}
Frame order: Call xProcessEvents() -> xTimerUpdate() -> input updates -> game logic -> xBeginFrame() -> rendering -> xEndFrame() every iteration.
04

Engine Core — xengine.h

The engine core handles window creation, the OpenGL rendering context, the main-loop control, and fullscreen/resolution management. It includes xgfx.h, xtimer.h, xkeybrd.h, xmouse.h, xfont.h, xres.h, and x3d.h automatically.

Initialization & Shutdown

intxInit(HINSTANCE hInstance, int width, int height, const char* title)
Creates the application window and initializes the OpenGL rendering context. Returns 1 on success, 0 on failure. Must be called first.
voidxShutdown(void)
Destroys the window and releases all engine resources. Call last, after shutting down all subsystems.

Main Loop

intxIsRunning(void)
Returns 1 while the application should continue running. Returns 0 when the window is closed or xQuit() is called.
voidxProcessEvents(void)
Processes the Windows message queue. Must be called every frame.
voidxBeginFrame(void)
Begins a new render frame. Call before any drawing operations.
voidxEndFrame(void)
Finalizes the frame and swaps the front/back buffers (presents to screen).
voidxQuit(void)
Signals the engine to exit. xIsRunning() will return 0 after this call.

Window Information

intxGetWidth(void)
Returns the current window/viewport width in pixels.
intxGetHeight(void)
Returns the current window/viewport height in pixels.
HWNDxGetWindow(void)
Returns the Win32 window handle. Required when initializing subsystems like sound and joystick.

Fullscreen & Resolution

intxIsFullscreen(void)
Returns 1 if the application is currently in fullscreen mode.
voidxToggleFullscreen(void)
Toggles between windowed and fullscreen mode. Typically bound to Alt+Enter.
voidxSetFullscreen(int fullscreen)
Sets fullscreen mode explicitly. Pass 1 for fullscreen, 0 for windowed.
intxChangeResolution(int resolutionIndex)
Changes to a predefined resolution by index (from the resolution list in xres.h). Returns 1 on success.
intxChangeResolutionCustom(int width, int height)
Changes to any arbitrary resolution. Returns 1 on success.
voidxApplyResolution(void)
Applies pending resolution changes. Call after modifying resolution settings.
05

Timer — xtimer.h

Frame timing utilities. xTimerUpdate() must be called once per frame to refresh delta time and FPS calculations.

voidxTimerInit(void)
Initializes the high-resolution timer. Called automatically by xInit().
voidxTimerUpdate(void)
Updates the timer state. Must be called once at the start of every frame.
floatxGetDelta(void)
Returns the time elapsed since the last frame in seconds (delta time). Use to make movement frame-rate independent.
floatxGetFPS(void)
Returns the current frames-per-second count.
DWORDxGetTicks(void)
Returns elapsed milliseconds since engine start.
voidxWait(float targetDelta)
Sleeps the calling thread to cap the frame rate to a target delta (in seconds). E.g., pass 1.0f/60.0f for 60 FPS.

System date and time queries (from the OS clock):

unsigned intxGetSeconds(void)
Current second (0–59).
unsigned intxGetMinutes(void)
Current minute (0–59).
unsigned intxGetHours(void)
Current hour (0–23).
unsigned intxGetDay(void)
Current day of month (1–31).
unsigned intxGetMonth(void)
Current month (1–12).
unsigned intxGetYear(void)
Current year (e.g., 2026).
06

Resolution — xres.h

Manages the list of supported screen resolutions and aspect ratios.

TResolution Structure

TResolution struct
intwidthWidth in pixels
intheightHeight in pixels
floataspectRatioPrecomputed aspect ratio
char[32]nameHuman-readable name, e.g. "1920x1080"

Aspect Ratio Constants

ASPECT_4_30Standard 4:3
ASPECT_16_91Widescreen 16:9
ASPECT_16_102Widescreen 16:10
intxGetResolutionCount(void)
Returns the total number of available resolutions.
TResolution*xGetResolution(int index)
Returns a pointer to the resolution at the given index.
TResolution*xGetCurrentResolution(void)
Returns a pointer to the currently active resolution.
intxSetResolution(int index)
Activates a resolution by its index. Returns 1 on success.
intxSetResolutionCustom(int width, int height)
Sets a custom resolution. Returns 1 on success.
intxGetResolutionsByAspect(int aspectType, int* indices, int maxCount)
Fills indices[] with the indices of all resolutions matching the given aspect type. Returns the number found.
floatxGetAspectRatio(void)
Returns the current aspect ratio as a float (e.g., 1.777 for 16:9).
voidxListAvailableResolutions(void)
Debug helper: prints all available resolutions to the output console.
07

2D Graphics — xgfx.h

2D rendering API for primitives, bitmaps, and screen-space effects. All coordinates are in pixels matching the window size.

Core Types

TColor struct
floatr, g, bRed, green, blue components (0.0–1.0)
TBitmap struct
unsigned inttextureIDOpenGL texture ID
intwidth, heightOriginal image dimensions
inttexWidth, texHeightPower-of-2 OpenGL texture dimensions
intuseColorKey1 = enable color-key transparency
unsigned charkeyR, keyG, keyBColor-key color
intuseAlphaAdd1 = additive blending (GL_ONE,GL_ONE)
unsigned char*alphaMaskPer-pixel alpha mask (width×height bytes)

Predefined color constants: RED, GREEN, BLUE, YELLOW, CYAN, MAGENTA, WHITE, BLACK, GRAY, ORANGE, PURPLE, BROWN, PINK, LIME, NAVY, TEAL, GOLD, SILVER and more.

Drawing Primitives

voidxClear(TColor color)
Clears the screen to the given color.
voidxSetColor(TColor color)
Sets the active drawing color for subsequent primitive draw calls.
TColorxRGB(float r, float g, float b)
Constructs a TColor from component values in the range 0.0–1.0.
voidxDrawLine(float x1, float y1, float x2, float y2)
Draws a line between two screen-space points.
voidxDrawRect(float x, float y, float w, float h)
Draws a hollow rectangle outline.
voidxDrawRectFilled(float x, float y, float w, float h)
Draws a solid filled rectangle.
voidxDrawCircle(float x, float y, float radius, int segments)
Draws a circle outline. More segments = smoother circle.
voidxDrawCircleFilled(float x, float y, float radius, int segments)
Draws a filled circle.
voidxDrawTriangle(float x1,y1, x2,y2, x3,y3)
Draws a triangle outline.
voidxDrawTriangleFilled(float x1,y1, x2,y2, x3,y3)
Draws a filled triangle.
voidxDrawPolygon(TPoint* points, int count)
Draws a polygon outline from an array of TPoint structures.
voidxDrawPolygonFilled(TPoint* points, int count)
Draws a filled polygon.

Bitmap Functions

intxLoadBitmap(TBitmap* bitmap, const char* filename)
Loads a bitmap from a file into a TBitmap structure, uploading it as an OpenGL texture. Returns 1 on success.
intxLoadBitmapColorKey(TBitmap* bitmap, const char* filename, unsigned char r, g, b)
Loads a bitmap with a color-key: pixels of the specified color are rendered transparent.
voidxFreeBitmap(TBitmap* bitmap)
Frees the OpenGL texture and the alpha mask. Always call when done with a bitmap.
voidxDrawBitmap(TBitmap* bitmap, float x, float y)
Draws the bitmap at its original size at position (x, y).
voidxDrawBitmapScaled(TBitmap*, float x,y,width,height)
Draws the bitmap scaled to the given dimensions.
voidxDrawBitmapEx(TBitmap*, float x,y,w,h,angle,alpha)
Draws the bitmap with rotation (degrees) and alpha transparency (0.0–1.0). Preserves original bitmap colors.
voidxDrawBitmapExColor(TBitmap*, float x,y,w,h,angle,alpha, TColor color)
Same as xDrawBitmapEx but applies a color tint (modulation) over the bitmap.

Alpha Add (Additive Blending)

Additive blending renders a bitmap by adding its pixel values to the background, creating a glow or light effect.

voidxEnableBitmapAlphaAdd(TBitmap* bitmap)
Enables additive blending (GL_ONE, GL_ONE) for this bitmap.
voidxDisableBitmapAlphaAdd(TBitmap* bitmap)
Disables additive blending, returning to standard alpha blending.
voidxSetBitmapAlphaAddColor(TBitmap*, TColor color)
Sets the modulation color for additive blending (default: WHITE).
voidxSetBitmapAlphaAddIntensity(TBitmap*, float intensity)
Sets the intensity of the additive effect. Range 0.0–1.0.

Fade Effects

FunctionDescription
xFadeIn(alpha)Manual fade-in overlay. Alpha 0.0 = fully visible, 1.0 = black.
xFadeOut(alpha)Manual fade-out overlay.
xFadeToColor(color, alpha)Fades to a specific color.
xStartFadeIn(duration)Starts an automatic fade-in over duration seconds.
xStartFadeOut(duration)Starts an automatic fade-out over duration seconds.
xUpdateFade()Updates the automatic fade timer. Call every frame.
xDrawFade()Draws the current automatic fade overlay. Call after scene rendering.
xIsFading()Returns 1 while an automatic fade is in progress.
xGetFadeProgress()Returns fade progress 0.0–1.0.
08

Fonts — xfont.h

Two font types are supported: Windows TrueType fonts (rendered via OpenGL display lists) and Bitmap fonts loaded from a .met metrics file paired with a bitmap image.

Font Type Constants

FONT_TYPE_WINDOWS0Windows TrueType font
FONT_TYPE_BITMAP1Bitmap .met font
ALIGN_LEFT / ALIGN_RIGHT / ALIGN_CENTER0 / 2 / 1Horizontal alignment
ALIGN_TOP / ALIGN_MIDDLE / ALIGN_BOTTOM0 / 4 / 8Vertical alignment

Windows TrueType Fonts

intxCreateFont(TFont* font, const char* faceName, int height, int weight, int italic)
Creates a Windows TrueType font. weight uses the FONT_WEIGHT_* constants (e.g. FONT_WEIGHT_BOLD = 700). Pass 1 for italic. Returns 1 on success.
voidxFreeFont(TFont* font)
Frees the OpenGL display list for this font.
voidxDrawText(TFont*, float x, y, const char* text)
Draws text at position (x, y).
voidxDrawTextF(TFont*, float x, y, const char* format, ...)
Printf-style formatted text drawing.
voidxDrawTextAligned(TFont*, float x, y, int align, const char* text)
Draws text with horizontal alignment (ALIGN_LEFT, ALIGN_CENTER, ALIGN_RIGHT).
voidxSetTextColor(TColor color)
Sets the color for all subsequent TrueType text rendering.
voidxSetTextShadow(float ox,oy, TColor color, float alpha)
Configures all shadow parameters at once: offset, color, and opacity.
voidxSetTextOutline(float thickness, TColor color)
Configures text outline: thickness in pixels and color.

Bitmap Fonts (.met)

Bitmap fonts require a .met metrics file that describes each character's position and dimensions within the accompanying bitmap image.

intxCreateBitmapFont(TFont* font, const char* metFilename)
Loads a bitmap font from a .met file. The associated bitmap file is referenced from within the .met file.
intxCreateBitmapFontColorKey(TFont*, const char* metFilename, unsigned char r,g,b)
Loads a bitmap font with color-key transparency applied to the bitmap.
voidxDrawBitmapText(TFont*, float x,y, const char* text)
Draws text using a bitmap font at original scale.
voidxDrawBitmapTextScaled(TFont*, float x,y,scale, const char* text)
Draws bitmap text with a uniform scale factor.
voidxDrawBitmapTextEx(TFont*, float x,y,scale,spacing, const char* text)
Full-control bitmap text with custom scale and character spacing.
voidxDrawBitmapTextShadow(TFont*, float x,y, const char* text, float sox,soy, TColor textColor,shadowColor)
Renders bitmap text with a drop shadow at offset (sox, soy).
voidxDrawBitmapTextOutline(TFont*, float x,y, const char* text, int thickness, TColor textColor,outlineColor)
Renders bitmap text with an outline of the given pixel thickness.
voidxDrawBitmapTextAlpha(TFont*, float x,y, const char* text, float alpha)
Renders bitmap text with an alpha transparency value (0.0–1.0).
intxGetBitmapTextWidth(TFont*, const char* text)
Returns the pixel width of the given text string using this font.
09

3D Engine — x3d.h

The core 3D rendering module. Built on the OpenGL 1.1 fixed-function pipeline. Encompasses camera control, lighting, mesh rendering, terrain, skybox, animated MD2 models, billboards, fog, and more.

Initialization

voidx3DInit(int width, int height)
Initializes the 3D subsystem. Sets up projection matrix and default OpenGL state. Must be called after xInit().
voidx3DBegin(void)
Switches to 3D rendering mode. Sets up the perspective projection and clears the depth buffer. Call before drawing any 3D geometry.
voidx3DEnd(void)
Ends 3D rendering mode and restores the 2D orthographic projection for UI/HUD rendering.
voidx3DSetViewport(int x, y, width, height)
Sets a custom viewport region for split-screen or picture-in-picture effects.
voidx3DUpdateAspectRatio(int width, int height)
Recalculates the aspect ratio after a resolution change. Call whenever the window size changes.
09a

Camera — x3d.h

TCamera Structure

TCamera struct
TVector3positionWorld-space position
TVector3targetLook-at target point
TVector3upWorld up vector (usually 0,1,0)
floatfovField of view in degrees
floatnearPlaneNear clip distance
floatfarPlaneFar clip distance (draw distance)
floatyawLeft-right rotation (degrees)
floatpitchUp-down tilt (degrees)
floatrollBank/tilt (degrees)
TVector3forward, rightCached direction vectors

Creation

voidx3DCreateCamera(TCamera* camera)
Initializes a camera with default values: position (0,0,0), FOV 60°, near 0.1, far 1000.
voidx3DCreateCameraEx(TCamera*, TVector3 pos, TVector3 target, float fov, near, far)
Full camera creation with explicit parameters.
voidx3DCreateCameraFPS(TCamera*, TVector3 pos, float yaw, float pitch)
Creates a first-person style camera initialized with yaw (horizontal) and pitch (vertical) angles.

Movement & Rotation

voidx3DMoveCameraZ(TCamera*, float distance)
Moves the camera forward (positive) or backward (negative) along its look direction.
voidx3DMoveCameraX(TCamera*, float distance)
Strafes the camera left (negative) or right (positive).
voidx3DMoveCameraY(TCamera*, float distance)
Moves the camera up or down along the world Y axis.
voidx3DRotateCamera(TCamera*, float yaw, pitch, roll)
Adds delta rotation angles to the camera (incremental, not absolute).
voidx3DSetCameraRotation(TCamera*, float yaw, pitch, roll)
Sets absolute rotation angles directly.
voidx3DCameraLookAt(TCamera*, TVector3 pos, target, up)
Positions the camera and points it at a target, similar to gluLookAt.
voidx3DSetCamera(TCamera* camera)
Applies the camera transform to the OpenGL modelview matrix. Call once per frame before drawing the 3D scene.

Global FOV & Draw Distance

voidx3DSetGlobalFOV(float fov)
Sets a global field-of-view (degrees) that affects the projection when using x3DBegin/x3DEnd.
voidx3DSetGlobalDrawDistance(float distance)
Sets the global far clip plane. Objects beyond this distance are not rendered.
voidx3DSetGlobalNearPlane(float distance)
Sets the global near clip plane. Very small values may cause z-fighting.
voidx3DUpdatePerspective(void)
Reapplies the projection matrix using the current global FOV, near, and far values.
09b

Lighting — x3d.h

Up to 8 simultaneous OpenGL lights (GL_LIGHT0–GL_LIGHT7). Supports directional, point, and spot lights with per-light attenuation.

LIGHT_DIRECTIONAL0Infinite light source (sun)
LIGHT_POINT1Omnidirectional point light
LIGHT_SPOT2Cone-shaped spotlight
MAX_LIGHTS8Maximum concurrent lights
voidx3DEnableLighting(void)
Enables the OpenGL lighting model (glEnable(GL_LIGHTING)).
voidx3DDisableLighting(void)
Disables lighting. Objects will render with full vertex colors.
voidx3DSetAmbientLight(TColor color)
Sets the global ambient light color applied to all lit surfaces.
voidx3DSetupDirectionalLight(int index, TVector3 direction, TColor diffuse, specular)
Configures a directional (sunlight-style) light at the given index (0–7).
voidx3DSetupPointLight(int index, TVector3 position, TColor diffuse, specular)
Configures a point light at the given world position.
voidx3DSetupSpotLight(int index, TVector3 pos, dir, float cutoff, TColor diffuse, specular)
Configures a spot light. cutoff is the half-angle of the cone in degrees (0–90).
voidx3DEnableLight(int index)
Activates the light at the given index.
voidx3DDisableLight(int index)
Deactivates the light at the given index.
voidx3DSetMaterialColor(TColor ambient, diffuse, specular, float shininess)
Sets the current OpenGL material properties for lit geometry. Shininess range is 0.0–128.0.
09c

Mesh & Primitives — x3d.h

Static 3D meshes and primitive shapes. Meshes can be compiled into OpenGL display lists for optimal performance.

Primitive Shapes

FunctionDescription
x3DDrawCube(size)Draws a unit cube centered at origin.
x3DDrawCubeEx(w,h,d)Draws a box with separate dimensions.
x3DDrawSphere(r, slices, stacks)Draws a tessellated sphere.
x3DDrawCylinder(r, h, slices)Draws a cylinder.
x3DDrawCone(r, h, slices)Draws a cone.
x3DDrawTorus(ir, or, sides, rings)Draws a torus (donut shape).
x3DDrawPlane(w, h, segX, segY)Draws a subdivided flat plane.

Custom Meshes (TMesh)

TMesh*x3DCreateMesh(int vertexCount, int indexCount)
Allocates a new mesh with space for the given number of vertices and indices. Returns NULL on failure.
voidx3DFreeMesh(TMesh* mesh)
Frees all mesh resources including the display list if compiled.
voidx3DSetMeshVertex(TMesh*, int index, float x,y,z)
Sets a vertex position by index.
voidx3DSetMeshNormal(TMesh*, int index, float nx,ny,nz)
Sets a vertex normal by index (required for lighting).
voidx3DSetMeshTexCoord(TMesh*, int index, float u,v)
Sets a UV texture coordinate by index.
voidx3DCompileMesh(TMesh* mesh)
Compiles the mesh into an OpenGL display list for faster rendering. Call once after building the mesh.
voidx3DDrawMesh(TMesh* mesh)
Renders the mesh. Uses the display list if compiled.
TMesh*x3DLoadOBJ(const char* filename)
Loads a Wavefront .OBJ model file and returns a new TMesh. Returns NULL on failure.

Texturing

intx3DLoadTexture(TBitmap* bitmap, const char* filename)
Loads a texture for use in 3D (sets GL_CLAMP where appropriate). Returns 1 on success.
voidx3DBindTexture(TBitmap* bitmap)
Binds the texture for rendering. Enables GL_TEXTURE_2D automatically.
voidx3DUnbindTexture(void)
Unbinds the current texture and disables GL_TEXTURE_2D.
voidx3DEnableBilinearFiltering(void)
Enables bilinear (GL_LINEAR) filtering for all subsequently loaded textures.
voidx3DDisableBilinearFiltering(void)
Disables bilinear filtering; textures will use nearest-neighbor (GL_NEAREST) — classic pixelated look.

Transforms

voidx3DSetPosition(float x, y, z)
Applies a translation transform (glTranslatef).
voidx3DRotate(float angle, float x, y, z)
Applies a rotation of angle degrees around the given axis (glRotatef).
voidx3DScale(float x, y, z)
Applies a scale transform (glScalef).
voidx3DResetView(void)
Pushes the current matrix stack (glPushMatrix). Use before positioning an object.
voidx3DRestoreView(void)
Pops the matrix stack (glPopMatrix). Use after rendering an object.

Render State Helpers

FunctionDescription
x3DEnableDepthTest()Enables depth testing (default: on).
x3DDisableDepthTest()Disables depth testing (for overlays, transparent objects).
x3DEnableCullFace()Enables back-face culling.
x3DDisableCullFace()Disables back-face culling (two-sided surfaces).
x3DEnableWireframe()Switches to wireframe polygon mode.
x3DDisableWireframe()Returns to filled polygon mode.
x3DEnableTexture()Enables GL_TEXTURE_2D.
x3DDisableTexture()Disables GL_TEXTURE_2D.

Fog

FOG_LINEAR0Linear distance falloff
FOG_EXP1Exponential falloff
FOG_EXP22Squared exponential falloff
voidx3DSetFog(int mode, TColor color, float density, start, end)
Configures fog. For FOG_LINEAR: start and end are distances. For FOG_EXP/FOG_EXP2: density controls falloff rate.
voidx3DEnableFog(void)
Activates fog rendering.
voidx3DDisableFog(void)
Deactivates fog rendering.
09d

Terrain / Heightmap — x3d.h

Generates a 3D terrain mesh from a grayscale heightmap image. Brighter pixels = higher terrain.

TTerrain*x3DCreateTerrain(const char* heightmapFile, float scaleXZ, float scaleY)
Loads a heightmap image and generates a terrain mesh. scaleXZ is the horizontal distance between vertices; scaleY multiplies the height values.
TTerrain*x3DCreateTerrainFromData(unsigned char* data, int w,h, float scaleXZ,scaleY, int step)
Creates terrain from raw byte data. step controls LOD resolution (1 = full detail, 2 = half, etc.).
voidx3DFreeTerrain(TTerrain* terrain)
Frees all terrain geometry and texture data.
voidx3DSetTerrainTexture(TTerrain*, const char* textureFile)
Applies a texture to the terrain surface.
voidx3DSetTerrainTextureScale(TTerrain*, float scaleU, scaleV)
Sets UV tiling scale for the terrain texture. Higher values = more repetitions.
voidx3DDrawTerrain(TTerrain* terrain)
Renders the terrain mesh with its texture (if set).
voidx3DDrawTerrainWireframe(TTerrain* terrain)
Renders the terrain in wireframe mode for debugging.
floatx3DGetTerrainHeight(TTerrain*, float x, float z)
Returns the interpolated terrain height (Y) at world position (x, z). Essential for keeping objects on the ground.
TVector3x3DGetTerrainNormal(TTerrain*, float x, float z)
Returns the surface normal at the given terrain position. Useful for aligning objects to slopes.
voidx3DCalculateTerrainNormals(TTerrain* terrain)
Recalculates per-vertex normals for correct lighting. Call after creating or modifying a terrain.
voidx3DSetTerrainLOD(TTerrain*, int lodLevel)
Sets the terrain level of detail. Higher values skip more vertices for better performance.
09e

Skybox — x3d.h

A six-sided textured cube rendered around the camera to simulate a distant environment.

SKYBOX_FRONT0
SKYBOX_BACK1
SKYBOX_LEFT2
SKYBOX_RIGHT3
SKYBOX_TOP4
SKYBOX_BOTTOM5
TSkybox*x3DCreateSkybox(float size)
Creates a skybox structure with the given box half-size.
intx3DLoadSkyboxTextures(TSkybox*, const char* front,back,left,right,top,bottom)
Loads all 6 textures at once by filename. Returns 1 if all loaded successfully.
intx3DLoadSkyboxTexturesPrefix(TSkybox*, const char* prefix, const char* extension)
Loads skybox textures using a naming convention: prefix_front.ext, prefix_back.ext, etc.
voidx3DCompileSkybox(TSkybox* skybox)
Compiles the skybox geometry into an OpenGL display list. Recommended for performance.
voidx3DDrawSkybox(TSkybox*, TCamera*)
Renders the skybox centered on the given camera position. Must be drawn before other 3D objects.
voidx3DDrawSkyboxRotated(TSkybox*, TCamera*, float angle)
Draws the skybox with an additional Y-axis rotation. Can simulate slowly drifting clouds.
voidx3DFreeSkybox(TSkybox* skybox)
Frees all skybox textures and the display list.
09f

MD2 Animated Models — x3d.h

Supports the Quake II MD2 model format, including per-vertex keyframe animation with smooth interpolation. The standard Quake II animation set is predefined.

Predefined Animation Types

0 MD2_ANIM_STAND
1 MD2_ANIM_RUN
2 MD2_ANIM_ATTACK
3 MD2_ANIM_PAIN
4 MD2_ANIM_JUMP
5 MD2_ANIM_FLIP
6 MD2_ANIM_SALUTE
7 MD2_ANIM_TAUNT
8 MD2_ANIM_WAVE
9 MD2_ANIM_POINT
10 MD2_ANIM_CROUCH_STAND
11 MD2_ANIM_CROUCH_WALK
12 MD2_ANIM_CROUCH_ATTACK
13 MD2_ANIM_CROUCH_PAIN
14 MD2_ANIM_CROUCH_DEATH
15 MD2_ANIM_DEATH1
16 MD2_ANIM_DEATH2
17 MD2_ANIM_DEATH3
TMD2Model*x3DLoadMD2(const char* filename)
Loads a Quake II .md2 file. Returns NULL on failure.
voidx3DFreeMD2(TMD2Model* model)
Frees all model data, skin texture, and animation buffers.
voidx3DSetMD2Skin(TMD2Model*, const char* skinFile)
Assigns a texture (skin) to the model by filename.
voidx3DDrawMD2(TMD2Model* model)
Renders the model at its current animation frame using smooth vertex interpolation.
voidx3DSetMD2Animation(TMD2Model*, int startFrame, int endFrame, int fps)
Sets a custom animation range and playback speed.
voidx3DSetMD2AnimationByType(TMD2Model*, int animType)
Sets the animation using a predefined type constant (e.g., MD2_ANIM_RUN).
voidx3DUpdateMD2Animation(TMD2Model*, float deltaTime)
Advances the animation by the given delta time (seconds). Call every frame with xGetDelta().
voidx3DSetMD2Alpha(TMD2Model*, float alpha)
Sets the model's overall transparency (0.0 = invisible, 1.0 = opaque). Requires model->useAlpha = 1.
09g

Billboards — x3d.h

Billboards are textured quads that automatically face the camera. Used for sprites, particles, trees, and HUD-in-3D elements.

BILLBOARD_SPHERICAL0Always faces camera (2-axis)
BILLBOARD_CYLINDRICAL1Rotates on Y only (trees)
BILLBOARD_SCREEN_ALIGNED2Parallel to screen plane
TBillboard*x3DCreateBillboard(float width, float height)
Allocates a new billboard structure of the given world-space size.
voidx3DFreeBillboard(TBillboard*)
Frees the billboard. Does not free the texture (managed separately).
intx3DSetBillboardTexture(TBillboard*, const char* filename)
Loads a texture for the billboard from a file.
voidx3DSetBillboardType(TBillboard*, int type)
Sets the billboard orientation mode.
voidx3DDrawBillboard(TBillboard*, TCamera*)
Renders the billboard, orienting it towards the given camera.
voidx3DDrawBillboardAt(TVector3 pos, float w,h, TBitmap*, TCamera*)
Quick one-call billboard draw without a TBillboard struct.
voidx3DBeginBillboards(TCamera*)
Begins a billboard batch. Call once, then draw multiple billboards with x3DDrawBillboardBatch, then call x3DEndBillboards. More efficient than drawing individually.
09h

Scrolling 2D Background — x3d.h

A parallax-scrolling background rendered as a full-screen quad. Scroll offset is automatically derived from the camera's yaw/pitch angles.

voidx3DInitBackground(T3DBackground* bg)
Zero-initializes a T3DBackground structure with default settings.
intx3DLoadBackground(T3DBackground*, const char* filename)
Loads the background texture.
voidx3DSetBackgroundScrollSpeed(T3DBackground*, float speed)
Sets the scroll speed multiplier. 1.0 = 1:1 with camera movement; 0.5 = half speed (parallax).
voidx3DSetBackgroundScrollMode(T3DBackground*, int enableH, int enableV)
Independently enables or disables horizontal and vertical scrolling.
voidx3DDrawBackground(T3DBackground*, TCamera*)
Draws the background using the camera orientation to calculate scroll offset. Call before drawing 3D geometry.
voidx3DDrawBackgroundStatic(T3DBackground*)
Draws a non-scrolling static background.
voidx3DSetBackgroundAlpha(T3DBackground*, float alpha)
Sets the transparency of the background (0.0–1.0).
09i

Blob Shadows — x3d.h

Fake soft shadows projected onto the terrain plane using an oval mesh (blob). Efficient for characters and objects.

voidx3DCreateBlobMesh(int segments)
Generates the shadow blob geometry. Call once at startup. More segments = rounder shadow.
voidx3DDestroyBlobMesh(void)
Frees the blob mesh memory. Call at shutdown.
voidx3DBeginBlobShadow(float posX,posY,posZ, float terrainHeight, float lightOffsetX,lightOffsetZ,lightHeight, float shadowAlpha, int useStaticShadow, float staticShadowRadius)
Begins rendering a blob shadow. Position is the caster's world position. terrainHeight is the Y position of the ground. lightOffsetX/Z/Height controls shadow direction. useStaticShadow = 1 draws a fixed-radius circle instead of a projected oval.
voidx3DEndBlobShadow(void)
Ends the shadow rendering block and restores render state.
i
Usage: Call x3DBeginBlobShadow, render geometry (or just let the system use the blob mesh), then call x3DEndBlobShadow. Shadows are drawn as dark transparent quads on the terrain.
10

Keyboard — xkeybrd.h

Polls the Windows keyboard state each frame. Provides both held-down and edge-detection (just pressed / just released) queries.

voidxKeyboardInit(void)
Initializes keyboard state arrays. Called automatically by xInit().
voidxKeyboardUpdate(void)
Samples current key states. Must be called once per frame before querying keys.
intxKeyDown(int keyCode)
Returns 1 while the key is held down.
intxKeyPressed(int keyCode)
Returns 1 only on the first frame the key is pressed (rising edge).
intxKeyReleased(int keyCode)
Returns 1 only on the first frame the key is released (falling edge).
intxAnyKeyPressed(void)
Returns 1 if any key was just pressed this frame.
voidxClearKeyStates(void)
Clears all key state history. Useful after menus or loading screens.

Key codes map to Windows virtual keys. Common constants:

ConstantDescription
KEY_ESCAPE, KEY_SPACE, KEY_RETURNEscape, Space, Enter
KEY_W, KEY_A, KEY_S, KEY_DWASD movement keys
KEY_UP, KEY_DOWN, KEY_LEFT, KEY_RIGHTArrow keys
KEY_F1 – KEY_F12Function keys
KEY_SHIFT, KEY_CONTROL, KEY_ALTModifier keys
KEY_NUMPAD0 – KEY_NUMPAD9Numeric keypad
KEY_0 – KEY_9Number row keys
11

Mouse — xmouse.h

Mouse position, delta movement, button state, scroll wheel, and cursor management including FPS-style capture mode.

voidxMouseUpdate(void)
Updates mouse state. Call once per frame.
intxMouseX(void)
Returns the mouse cursor X position in window pixels.
intxMouseY(void)
Returns the mouse cursor Y position in window pixels.
intxMouseDeltaX(void)
Returns the horizontal movement since the last frame. In capture mode, this is unbounded raw movement.
intxMouseDeltaY(void)
Returns the vertical movement since the last frame.
intxMouseButtonDown(int button)
Returns 1 while the button is held. Button codes: MOUSE_LEFT=0, MOUSE_RIGHT=1, MOUSE_MIDDLE=2.
intxMouseButtonPressed(int button)
Returns 1 only on the frame the button is first clicked.
intxMouseButtonReleased(int button)
Returns 1 only on the frame the button is released.
intxMouseWheel(void)
Returns the cumulative scroll wheel value.
intxMouseInRect(int x,y,w,h)
Returns 1 if the mouse is within the given rectangle. Useful for UI hit testing.
voidxMouseCapture(void)
Locks the cursor to the window center and hides it. xMouseDeltaX/Y return unlimited raw movement. Use for FPS camera control.
voidxMouseRelease(void)
Unlocks the cursor and makes it visible again.
intxMouseIsCaptured(void)
Returns 1 if the mouse is currently in capture mode.
12

Joystick — xjoy.h

DirectInput 8 joystick and gamepad support. Supports up to 4 simultaneous devices with full analog axes, POV (D-Pad), buttons, and force feedback.

JOY_MAX_DEVICES4Max simultaneous devices
JOY_AXIS_MIN / MAX-1000 / 1000Raw axis range
JOY_DEFAULT_DEADZONE200Default dead zone
JOY_MAX_BUTTONS32Max buttons per device

Button Mappings (Xbox / PlayStation)

ConstantXboxPlayStation
JOY_BTN_A (0)ACross
JOY_BTN_B (1)BCircle
JOY_BTN_X (2)XSquare
JOY_BTN_Y (3)YTriangle
JOY_BTN_LB (4)Left BumperL1
JOY_BTN_RB (5)Right BumperR1
JOY_BTN_START (7)StartStart
JOY_BTN_LSTICK (8)Left Stick ClickL3
JOY_BTN_RSTICK (9)Right Stick ClickR3
intxJoystickInit(HWND hwnd)
Initializes DirectInput and enumerates all connected joystick/gamepad devices.
voidxJoystickShutdown(void)
Releases all DirectInput devices and the DirectInput interface.
voidxJoystickUpdate(void)
Polls all joystick devices. Call once per frame.
intxJoyAxisX(int deviceIndex)
Raw left-stick X axis value (-1000 to +1000).
floatxJoyAxisXNormalized(int deviceIndex)
Left-stick X axis normalized to -1.0–+1.0, with deadzone applied.
intxJoyButtonDown(int device, int button)
Returns 1 while the button is held.
intxJoyButtonPressed(int device, int button)
Returns 1 on the first frame the button is pressed (edge detection).
intxJoyPOVUp(int deviceIndex)
Returns 1 if the D-Pad is pressed upward.
voidxJoySetDeadzone(int device, int deadzone)
Sets the dead zone threshold for a device. Axis values below this threshold are returned as zero.
voidxJoyPlayVibration(int device, int magnitude, int duration)
Triggers rumble on devices with force feedback. magnitude: 0–10000. duration: milliseconds.
13

Sound — xsound.h

DirectSound 8-based audio. Supports WAV sound effects (static buffers) and streaming WAV music. Up to 64 simultaneous sound buffers.

intxSoundInit(HWND hwnd)
Initializes DirectSound. Returns 1 on success. Requires a valid window handle.
voidxSoundShutdown(void)
Releases the DirectSound interface and all associated resources.

Sound Effects (TSound)

intxLoadSound(TSound*, const char* filename)
Loads a WAV file into a DirectSound buffer. Returns 1 on success.
intxLoadSoundFromMemory(TSound*, const unsigned char* wavData, int wavSize)
Loads a WAV sound directly from memory (e.g., from a package file).
voidxFreeSound(TSound*)
Releases the DirectSound buffer.
voidxPlaySound(TSound*)
Plays the sound once from the beginning.
voidxPlaySoundLooped(TSound*)
Plays the sound in a continuous loop.
voidxStopSound(TSound*)
Stops playback and rewinds to the beginning.
voidxSetSoundVolume(TSound*, int volume)
Sets volume. Range: 0 (silent) to 100 (full).
voidxSetSoundPan(TSound*, int pan)
Sets stereo panning. Range: -100 (full left) to 100 (full right), 0 = center.
voidxSetSoundFrequency(TSound*, int percentage)
Adjusts playback speed. 100 = normal speed, 200 = double speed (higher pitch), 50 = half speed.
voidxStopAllSounds(void)
Stops all active sound buffers.

Streaming Music (TMusic)

intxLoadMusic(TMusic*, const char* filename)
Opens a WAV file for streaming playback (not fully loaded into RAM).
voidxPlayMusic(TMusic*, int loop)
Starts streaming playback. Pass 1 to loop continuously.
voidxSetMusicVolume(TMusic*, int volume)
Sets music volume (0–100).
voidxSetMasterVolume(int volume)
Sets the master volume affecting all sounds and music (0–100).
14

CD Audio & MIDI — xmusic.h

MCI-based CD audio playback and MIDI file playback. Automatically links winmm.lib.

CD Audio (TCD)

intxOpenCD(TCD* cd)
Opens the default CD drive. Returns 1 on success.
intxOpenCDDrive(TCD*, char driveLetter)
Opens a specific CD drive by drive letter (e.g., 'D').
voidxPlayCDTrack(TCD*, int trackNumber)
Plays a specific track number (1-based).
voidxPlayCDRange(TCD*, int startTrack, int endTrack)
Plays a consecutive range of CD tracks.
voidxNextCDTrack(TCD*)
Advances to the next track.
voidxEjectCD(TCD*)
Opens the CD tray.
voidxUpdateCD(TCD*)
Updates the CD state. Call every frame to detect track end.
intxGetCDTrackCount(TCD*)
Returns the number of audio tracks on the disc.

MIDI (TMidi)

intxOpenMidi(TMidi*, const char* filename)
Opens a MIDI (.mid) file for playback. Returns 1 on success.
voidxPlayMidi(TMidi*)
Starts MIDI playback from the beginning.
voidxPlayMidiLoop(TMidi*)
Starts MIDI playback with looping enabled.
voidxPauseMidi(TMidi*)
Pauses playback at the current position.
voidxResumeMidi(TMidi*)
Resumes from the paused position.
voidxSetMidiVolume(TMidi*, int volume)
Sets MIDI volume. Range: 0–1000.
voidxSetMidiTempo(TMidi*, int tempo)
Sets the MIDI playback tempo. 1000 = 100% (normal speed).
voidxUpdateMidi(TMidi*)
Updates MIDI state. Required every frame for correct looping behavior.
voidxStopAllMidi(void)
Stops all active MIDI instances.
15

AVI Video — xavi.h

DirectShow-based AVI/video playback for cutscenes. Video is displayed in a child window and can be shown fullscreen or positioned over the game window.

!
OpenGL Conflict: AVI video cannot be played simultaneously with OpenGL rendering. Use xCanRenderOpenGL(avi) to check before calling x3DBegin(). Pause or stop the video before resuming 3D rendering.
intxAviInit(void)
Initializes DirectShow COM subsystem. Call once at startup. Returns 1 on success.
voidxAviShutdown(void)
Uninitializes DirectShow COM. Call at engine shutdown.
intxLoadAvi(TAvi*, HWND hwnd, const char* filename)
Loads an AVI/video file and creates a child video window. Returns 1 on success.
voidxFreeAvi(TAvi*)
Frees the DirectShow graph and the video window.
voidxPlayAvi(TAvi*)
Starts video playback (plays once).
voidxPlayAviLooped(TAvi*)
Starts video playback with looping.
voidxStopAvi(TAvi*)
Stops playback and rewinds to the start.
voidxPauseAvi(TAvi*)
Pauses playback at the current position.
voidxSetAviWindowPosition(TAvi*, int x,y,w,h)
Positions and sizes the video window within the parent window.
voidxSetAviFullscreen(TAvi*, int fullscreen)
Sets the video to cover the entire parent window.
voidxSetAviVolumePercent(TAvi*, int percent)
Sets video audio volume (0–100).
doublexGetAviPosition(TAvi*)
Returns the current playback position in seconds.
doublexGetAviDuration(TAvi*)
Returns the total video duration in seconds.
voidxUpdateAvi(TAvi*)
Updates video state — checks if playback has ended and handles looping. Call every frame.
intxIsAviFinished(TAvi*)
Returns 1 when the video has reached the end.
intxPlayAviBlocking(HWND, const char* filename, int canSkip)
Plays a video file and blocks until it finishes. If canSkip = 1, the user can press any key or click to skip. Returns 1 if played to completion, 0 if skipped.
intxPlayCutscene(HWND, const char* filename, int canSkip)
Plays a video fullscreen as a cutscene, blocking until done or skipped.
intxCanRenderOpenGL(TAvi*)
Returns 1 when it is safe to render OpenGL (no video is actively playing).
16

File Packages — xfiles.h

A custom binary archive format for bundling game assets. A package file contains a header (control number + file count), followed by a directory of file metadata, followed by the raw file data. The control number is 2903.

MAX_PACKAGE_FILES1024Max files per package
MAX_PACKAGES16Max open packages at once

Opening & Closing Packages

voidxPackageInit(void)
Initializes the package system. Call before any package operations.
TPackage*xPackageOpen(const char* filename)
Opens a package file (any extension: .pkg, .dat, .res, .pak). Returns NULL on failure. Reads the file directory into memory.
voidxPackageClose(TPackage*)
Closes the package file and releases its directory data.
voidxPackageSetDefault(TPackage*)
Sets a package as the global default used by all xLoad*FromPkg functions when no package is explicitly specified.

Finding & Loading Files

intxPackageFileExists(TPackage*, const char* filename)
Returns 1 if the named file exists within the package.
unsigned char*xPackageLoadFile(TPackage*, const char* filename, int* outSize)
Reads a file from the package into a newly allocated buffer. The caller is responsible for calling xPackageFreeData(). outSize receives the file size.
voidxPackageFreeData(unsigned char* data)
Frees memory returned by xPackageLoadFile.
char*xPackageLoadTextFile(TPackage*, const char* filename)
Reads a text file from the package, null-terminating it. Returns a pointer to the buffer (free with xPackageFreeData).
intxPackageExtractFile(TPackage*, const char* filename, const char* outputPath)
Extracts a file from the package to a location on disk.

Asset Loading Integration

Convenience functions that load engine assets directly from a package, bypassing the filesystem:

FunctionAsset Type
xLoadBitmapFromPkg(pkg, bitmap, file)2D bitmap texture
xLoadBitmapFromPkgColorKey(pkg, bitmap, file, r,g,b)Bitmap with color-key
x3DLoadTextureFromPkg(pkg, bitmap, file)3D model texture
x3DLoadSkyboxTextureFromPkg(pkg, skybox, side, file)Skybox face texture
xLoadSoundFromPkg(pkg, sound, file)WAV sound effect
xLoadMusicFromPkg(pkg, music, file)WAV music stream
xCreateBitmapFontFromPkg(pkg, font, metFile)Bitmap font (.met)
xLoadMD2FromPkg(pkg, file)Quake II MD2 model
xLoadOBJFromPkg(pkg, file)Wavefront OBJ model
x3DLoadBackgroundFromPkg(pkg, bg, file)2D scrolling background
/* Example: loading all assets from a package */
  TPackage* pkg = xPackageOpen("data/game.pkg");
  xPackageSetDefault(pkg);

  TBitmap hero;
  xLoadBitmapFromPkgColorKey(pkg, &hero, "hero.bmp", 255, 0, 255);

  TSound jump;
  xLoadSoundFromPkg(pkg, &jump, "jump.wav");

  TMD2Model* enemy = (TMD2Model*)xLoadMD2FromPkg(pkg, "enemy.md2");