A Delphi wrapper and object-oriented binding layer for the Jolt Physics high-performance rigid body physics engine.
Sample video: https://youtu.be/EaJqNMYcxJo
This project provides a clean VCL-friendly implementation that bridges the native Jolt Physics C API with Raylib for 3D rendering. It allows you to run a fully multi-threaded physics simulation directly inside a Delphi application.
The sandbox here is now frozen, since it gets a lil bit too large for a "sample" and had to get its own name...
Yutani https://github.com/LaMitaOne/Yutani-Building-better-worlds
Status: Work in Progress (Beta v0.61)
The original Jolt Physics C API contains over 3,000 lines of definitions. This wrapper currently covers approximately 85% of the API (over 1,500 lines of Delphi bindings).
While some highly specific low-level telemetry and niche constraints are still missing, the wrapper now includes comprehensive support for advanced game engine systems. This includes Ragdolls, Soft Body configuration, advanced Shape Casting (Sweep tests), Vehicles, and Table-based Collision Groups. The core simulation functionalityβrigid bodies, complex shapes, all standard constraints, collision callbacks, and queriesβis fully implemented and highly stable for practical use.
β¨ Features
Core Physics System (Jolt Physics)
World Creation: Initializes the physics system, sets up gravity, and optimizes the broadphase for efficient collision detection.
Rigid Bodies: Supports static, kinematic, and dynamic actors with full transform syncing for position and rotation.
Collision Shapes: Provides wrappers for Box, Sphere, Capsule, Cylinder, Tapered shapes, Convex Hulls, Compound shapes, Meshes, and Heightfields.
Physics Interactions: Allows the application of forces, impulses, and precise control over linear and angular velocities.
Advanced Collision & Queries
Raycasting: Offers built-in 3D raycasting to query the physics world from screen coordinates or specific origins.
Shape Casting (Sweeps): Implements advanced CastShape and CollideShape queries to sweep complex shapes across the world, which is essential for character movement and projectile collision.
Table-based Layers: Provides explicit, large-scale BroadPhase and ObjectLayer management for complex and highly customized collision filtering.
Collision Groups: Features advanced GroupFilter and SubGroupID management to define intricate collision rules, such as ignoring specific ragdoll limbs or attached objects.
Complex Game Systems
Ragdolls & Skeletons: Delivers full skeleton mapping, joint configuration (like Hinge and SwingTwist), and runtime ragdoll control for activation and deactivation.
Soft Bodies: Lays the foundation for deformable physics objects by allowing the creation of soft bodies from scratch using vertices and edges.
Vehicles: Implements a comprehensive vehicle setup, including engines, transmissions, anti-roll bars, tracks, and driver inputs for wheeled, tracked, and motorcycle controllers.
Advanced Constraints: Supports mechanical joints like Cone, SwingTwist, SixDOF, and Gear constraints for complex physics simulations.
Virtual Characters: Features an advanced CharacterVirtual implementation with contact listeners and extended update settings for smooth stair walking and stepping down.
Engine Utilities & Safety
Safe Editing: Uses a dynamic detach and reattach system that safely removes objects from the physics simulation during gizmo editing and cleanly re-attaches them upon mouse release to prevent crashes or jitter.
Dynamic Scaling: Safely rebuilds native Jolt shapes on the fly, including an automatic fallback to a 0.0 convex radius to support paper-thin walls.
Multi-threading: Utilizes Jolt's built-in thread pool and job system to distribute physics calculations across CPU cores for maximum performance.
Debug Rendering: Includes extensible DebugRenderer bindings, such as DrawSettings, wireframes, and bounding boxes, to easily visualize the physics world directly in the engine.
Rendering & Environment (Raylib + Custom GLSL)
VCL Integration: Includes a TRaylibSandbox component that embeds a Raylib 3D window inside a standard Delphi VCL form, running smoothly in a background thread without blocking the UI.
Pre-allocated Unit Meshes: Capsules, Pyramids, and Prisms are rendered using optimized, pre-loaded Unit Meshes, drastically reducing memory overhead.
Perfect Grounding: Geometric primitives are perfectly centered on the floor during scaling, preventing floating or sinking objects.
Advanced Lighting System: Custom GLSL shaders implementing ambient and diffuse shading. Lighting and shadows now correctly adapt to world-rotated shapes (cylinders/cones no longer have fixed lighting).
Dynamic Fake Shadows: Flat shadows drawn under objects that scale in size and opacity based on the object's height.
Procedural Skybox & Clouds: Custom GLSL shaders for a horizon-to-zenith gradient sky and a moving, dynamic cloud layer.
Day/Night Cycle: Manual or automatic time-of-day progression that dynamically shifts sun position, ambient lighting, and skybox gradients.
Optimization: Frustum & Distance Culling for actors outside the view frustum.
Editor & Tooling
Full Gizmo System: Translate, Rotate, and Scale Gizmos (toggled via CTRL). Gizmos align perfectly to the object's local rotation and dynamically resize to remain grabbable regardless of object dimensions.
Object Inspector (RTTI): Full property editing via RTTI. Edit Position, Scale, Rotation, Mass, Friction, and Restitution directly from a standard Delphi TStringGrid.
Brush & Ghost Preview: Place objects dynamically in the 3D world with a semi-transparent ghost preview that snaps to the floor or surface of other objects.
Context Menu & Selection: Right-click context menus, TreeView hierarchy sync, and actor duplication.
Shooting Mechanic: Fire blue cannonball projectiles with a cooldown to knock objects away.
Audio: Integrated MiniAudio4Delphi for spatial sound and engine test effects.
Controls:
Ctrl to switch move/rotate/size
Middle click camera rotation
WASD move camera
Mouse Wheel zoom in out
Ctrl q,e select prev, next
π¦ Project Structure
The repository consists of three main units:
JoltPhysics.pas - The low-level header translation mapping the JoltC.dll C API to Delphi types and records.
ModelEngine.pas - The Object-Oriented Delphi layer that manages the physics world and actors.
RaylibSandbox.pas - A VCL TWinControl that runs a threaded Raylib window, handling 3D rendering, camera input, and user interaction.
π οΈ What's Missing? (Roadmap)
Since the original C API is massive, there is still a lot to cover. Here is what is currently missing but planned for future updates:
Complete Locking BodyInterface: Full implementation of `BodyLockRead`, `BodyLockWrite`, and multi-lock interfaces for safe, manual multi-threaded access.
Advanced Shape Casting Collectors: Wrappers for `AllHit`, `ClosestHit`, and `AnyHit` collector types to easily gather multiple collision results from `CastShape` and `CollideShape`.
Vehicle Runtime Telemetry: Getting real-time data from vehicles (current RPM, gear, wheel contact normals) and implementing the remaining `MotorcycleController` steering setup.
Advanced Constraints: Adding the remaining niche joints (`PathConstraint`, `RackAndPinionConstraint`, `PulleyConstraint`).
Physics State Serialization: Implementing `SaveState` and `RestoreState` for saving and loading exact physics snapshots (useful for savegames).
Custom Memory Allocators: Currently relying on `JPH_TempAllocatorMalloc`; future updates will expose ways to hook in custom memory allocation strategies.
Missing Math Helpers: Expanding the math wrapper (Matrix inverses, quaternion to Euler angles, full vector arithmetic).
Exe and sample project included
Latest Changes:
v0.61:
Fixed spawn pos and ghost rotation of capsule, prism and pyramid
Fixed delete from treeview working now
Fixed delete from popup spawning empty cube after
Improved gizmos, better clickable from far distance
Raised Camera movement height and distance
Improved 3d model loading std sizes, not 1x1x1 anymore
Added spawn screens button and units for video injection
v0.60:
Implemented Advanced Collision Queries (CastShape/CollideShape) and Sweep tests.
Added full Ragdoll/Skeleton configuration (joint mapping, group filters, activation).
Exposed Soft Body creation APIs (adding vertices/edges, SoftBodyCreationSettings).
Expanded Vehicle system (engines, transmissions, tracks, anti-roll bars, driver inputs).
Added remaining constraints (Cone, SwingTwist, SixDOF, Gear).
Implemented Table-based BroadPhase/Layer filters and Collision Group management.
Extended Body Interface (MoveKinematic, PointVelocity, InverseInertia).
Added PhysicsStepListener vtables and expanded Debug Renderer bindings (DrawSettings).
v0.59:
Load now works with scenes including lot more objects.
We need give jolt little time after creating each object in its physical world, then it works fine.
Added Checkbox cbSpawnStatic for new spawned objects.
v0.58:
Scene Serialization (Save/Load): Implemented a custom, high-performance binary scene format (.d3dfm). Uses manual TFileStream and TWriter/TReader serialization to bypass VCL RTTI streaming crashes. Safely writes and restores object names, shape types, transforms (position, rotation, scale), colors, and physics properties. Still more to test but ...sometimes...works :D
Object Naming: TA3DComponent now explicitly declares and overrides the Name property (inheriting from TComponent). Names are assigned automatically on spawn (e.g., Cube_0, Sphere_1) and are fully serialized.
TreeView Synchronization: The VCL TTreeView is now fully bi-directionally linked with the 3D scene. Spawning an object adds a node, deleting removes it. Clicking a node selects the 3D object (and vice versa) via stored object pointers in Node.Data.
RTTI Object Inspector Enhancements: The TStringGrid inspector now correctly displays inherited properties (like Name) using GetPropList with the IncludeInherited flag. Editing the Name property in the grid instantly updates the TreeView.
Viewport Focus Guard: Implemented a bounds-check in HandleDesktopInput. The engine only processes 3D clicks/dragging if the mouse cursor is actively hovering over the Raylib viewport, preventing accidental deselections or background clicks while editing in the VCL UI.
v0.57:
Added Slow Motion Mode: Integrated a fully functional slow-motion system. When activated externally, the physics simulation (Jolt Physics), bomb timers, and projectile lifespans scale correctly to 20% speed, ensuring smooth and physically accurate time-lapse effects without breaking gravity or collision.
Added Spawn & Explosion Sounds: Implemented distinct audio feedback using MiniAudio. Newly spawned objects now play an impact sound, and the bomb explosion triggers a dedicated, heavy explosion sound effect.
Added 3D Button Spawner (btnSpawnButton): Added functionality to spawn fully interactive 3D buttons directly into the Raylib viewport. The buttons feature dynamic text rendering onto a texture, hover states, press-animations, and properly fire their assigned OnClick events thread-safe back to the VCL.
Fixed Pyramid Mesh Alignment: Resolved an issue where the visual mesh of the pyramid was offset from its actual physics center of mass. It now aligns perfectly, ensuring the geometry rests correctly on the ground β even when dynamically rotated sideways.
v0.56:
Added FIsStatic property and GetMotionType method to TA3DComponent for thread-safe state checking
Preserved original motion type in ReattachToPhysics to prevent dynamic objects from becoming static
Added TSpawnRequest record to enable thread-safe custom spawn queues from external modules
Added new VCL3D unit for high-level, ready-to-use spawning routines
Implemented SpawnSandbox to generate 4 solid, static boundary walls
Implemented SpawnDynamicWall to procedurally build a grid of physics blocks
Added parameters to toggle sequential dropping vs perfect placement for wall blocks
Implemented interactive Bomb Brush to place timed explosive spheres via mouse click
Added UpdateBomb and ExplodeBomb mechanics applying massive radial and upward impulses
Fixed Access Violation crash on application shutdown by removing redundant Jolt filter destruction
v0.55:
Converted basic primitives (Cube, Sphere) from direct vertex drawing to proper Raylib meshes. This ensures the custom GLSL lighting system calculates normals and shadows correctly for every object in the scene.
Implemented object cycling. Users can now quickly iterate through spawned objects using UI buttons or keyboard shortcuts (Ctrl+Q for previous, Ctrl+E for next).
Distance culling is no longer hardcoded. Exposed the MaxRenderDistance variable to the Object Inspector and linked it to a SpinEdit control on the VCL form, allowing real-time adjustments.
Identified and resolved a per-frame shader creation/destroy overhead in the RenderShadowMap routine by caching the default shader.
Exposed DayNightSpeed property to allow dynamic adjustment of the time-lapse speed via a UI SpinEdit (scaled 1-100).
v0.54:
Capsules, Pyramids, and Prisms now use pre-loaded Unit Meshes and are
perfectly grounded (centered on the floor) during scaling.
The lighting and shadow system has been fixed to correctly adapt to
world-rotated shapes (on 3d model, cube and sphere fine, others to do).
Actor colors are now directly injected into the GLSL shader via vec4.
v0.53:
Added stModel shape type to support rendering custom loaded 3D models (tried with glb from kenney.nl).
Implemented safe loading, assigning, and unloading of native Raylib TModel data into physics actors.
Added FMeshSize and FModelOffset properties to properly scale and align 3D models within their physics bounding boxes.
Added automatic memory management: Unloads the native Raylib model safely in the component's destructor to prevent memory leaks.
Updated SetScale to dynamically calculate box half-extents based on the original mesh dimensions multiplied by the current scale for stModel types.
Added a procedural Skybox with custom GLSL shaders for infinite background rendering.
Implemented a dynamic Day/Night cycle that dynamically updates lighting uniforms (sun position, ambient color, diffuse color).
Implemented real-time Shadow Mapping (Shadow Pass) using an orthographic light camera.
Added RenderShadowMap and DrawSceneShadows procedures to render scene depth from the sun's perspective.
Removed boundary walls and expanded the floor to 1000x1000 units to properly showcase the new skybox and environment.
Added DrawMeshBox and DrawMeshSphere helper functions to standardize primitive rendering.
Updated 3D rendering loop to apply lighting shaders consistently to primitives and skybox.
Integrated MiniAudio4Delphi for 3D audio engine support.
Added PlayTestSound procedure which triggers a sound effect when firing projectiles.
Exposed DayNightRhythmActive and DayNightTime as published properties, allowing control of the day/night cycle at runtime.
v0.52:
Fix: Pause Mode Spawn Position β Objects spawned via mouse click while the simulation was paused previously appeared at the world origin (0,0,0) and only "jumped" to their correct location when Play was pressed.
The transform matrix is now explicitly updated immediately upon creation.
Fix: Mass Spawn Overload β Clicking the mass spawn buttons in the HUD often spawned 120+ objects because the click was registered across multiple frames.
Added proper edge-detection (mouse down/up state tracking) so exactly the requested amount (30) is queued.
Add: Highlight Collision Option β Integrated a UI checkbox to toggle collision highlighting on and off.
Add: Live Engine Stats Dashboard β Prepared a TMemo as a live monitor.
A timer safely reads statistics from the background thread (like active physics bodies and physics update duration) and displays them without causing cross-thread UI conflicts.
v0.51:
Corrected spawn and phantom (ghost preview) positions for all shapes to rest accurately on the ground.
Added Prism shape (stPrism).
Implemented an icon bar at the top of the popup menu for quick spawning.
Added new right side pagecontrol with scene / engine tab.
Added checkboxes for Frustum/Distance Culling.
Added FPS Combobox.
v0.5:
Native Context Popup: Replaced VCL PopupMenu with a fully native Raylib 2D popup ("Delete" / "Duplicate") rendered directly inside the 3D viewport.
Click-Out Deselection: Left-clicking empty 3D space now immediately deselects the current actor and hides the gizmo.
Ghost-Cube Fix: Setting gmNone on scene clear prevents the bug where clicking a spawn button accidentally spawned an object at the button's location.
Perfect Local Rotation: Gizmos now calculate axis vectors directly from the actor's quaternion, ensuring they stay perfectly attached to the object's local faces regardless of its physical rotation or falling state.
Hover Highlighting: Gizmo axes now highlight yellow on mouse hover before clicking, showing exactly which axis will be grabbed.
Robust Hitboxes: Invisible bounding boxes for gizmo picking have been significantly enlarged, making axes much easier to grab without accidentally selecting the 3D object behind them.
Dynamic Sizing: Gizmo arrow thickness now scales dynamically based on the object's size, preventing them from becoming invisible on large actors.
Drag & Throw Tool: Reintroduced the Drag & Throw tool as a distinct mode (gmNone), allowing users to pull, push, and test physics interactions without the gizmo interfering.
Capsule Actor: Added Capsule as a new primitive shape, including UI button, rendering logic, and Jolt physics mapping.
v0.4:
Editor & Gizmo Update:
Gizmo System: Added Translate, Rotate, and Scale gizmos (toggleable via CTRL).
Object Inspector (RTTI): Live TStringGrid reading/writing all properties (Position, Rotation, Colors, Physics) directly to the object.
Scene Hierarchy: TreeView sync.
Brush System: Click-to-place mechanics with semi-transparent ghost preview.
Play/Pause Mode: Simulation can now be frozen for pure editing.
Safe Editing (Detach/Reattach): Objects are fully detached from Jolt while being edited (preventing crashes/jitter) and cleanly re-attached with new transforms on mouse release.
Tiny Scale Fix: SetScale automatically falls back to 0.0 convex radius for objects < 0.2m (allows paper-thin walls).
v0.3:
JoltPhysics:
Expanded Structs & Records: Added necessary records for advanced queries, including JPH_CollideShapeResult, JPH_ShapeCastResult, JPH_CollideShapeSettings, JPH_ShapeCastSettings, and JPH_RayCastSettings.
Constraint System: Implemented base structs (JPH_ConstraintSettings) and specific settings for Fixed, Point, Distance, Hinge, and Slider constraints. Added corresponding API functions for creation, destruction, and control (e.g., JPH_HingeConstraint_SetMotorState).
Complete Enum Constants: Added all missing enum values as constants (e.g., JPH_BodyType, JPH_ShapeSubType, JPH_AllowedDOFs, JPH_GroundState, JPH_MotorState, JPH_ConstraintSubType, etc.).
Listeners & Callbacks: Added vtable structs and API functions for JPH_ContactListener (collision events) and JPH_BodyActivationListener (sleep/wake events).
Extended Body Interface: Integrated many missing functions such as AddTorque, AddForce2 (with position parameter), AddAngularImpulse, combined getters/setters for velocities, and queries for Active-state, ObjectLayer, and UserData.
Additional Shapes: Added settings and creation functions for TaperedCapsule, TaperedCylinder, ConvexHull, StaticCompound, and MeshShape. Also added JPH_CompoundShapeSettings_AddShape for grouping shapes.
Math Helpers: Wrapped useful C-API math functions (JPH_Vec3_Cross, JPH_Vec3_Normalize, JPH_Quat_Rotate, JPH_Mat44_RotationTranslation, etc.).
Material System: Added functions to create and destroy JPH_PhysicsMaterial.
Miscellaneous: Added JPH_PhysicsSystem_Update (without TempAllocator) and included the {$A+} compiler directive to ensure exact C/C++ struct alignment.
RaylibSandbox:
Shooting Mechanic (Projectiles): Added the ability to shoot dynamic physics spheres by pressing SPACE. Projectiles use a 250ms cooldown to prevent machine-gun fire.
Dynamic Fake Shadows: Implemented custom flat shadows (DrawFlatShadow / DrawCylinderEx) for the floor, walls, and all actors. Shadow radius and alpha opacity scale dynamically based on the object's Y-height to simulate realistic light scattering.
Camera Panning & Bounds: Added WASD and Arrow Key panning. Camera movement is now clamped to world bounds (-80 to +80) to prevent the user from scrolling infinitely into the void.
Custom Lighting System: Implemented a custom GLSL shader for basic ambient and diffuse lighting that affects the floor, walls, and objects, giving the scene proper depth.
CCD (Continuous Collision Detection): Projectiles use JPH_MotionQuality_LinearCast to prevent fast-moving spheres from tunneling through walls or objects.
Z-Fighting Fix: Enabled rlEnableDepthTest() for custom shadow drawing to prevent them from flickering or being hidden behind the wallpaper texture.
Sphere Clipping Fix: Applied a manual Y-offset (+0.3 for spheres) during rendering to visually lift them out of the floor, bypassing Jolt's internal convex radius penetration.
Raylib DrawSphere Workaround: Implemented manual matrix scaling (rlScalef) because Raylib's DrawSphere ignores the radius parameter when drawing inside a manually pushed rotation matrix.
Memory Initialization: Used FillChar for TItemData upon spawn to prevent random memory garbage from causing projectiles to render incorrectly.
v0.2:
True 3D Rotation: Implemented proper quaternion-based rotation and transform matrices (Scale * Rotation * Translation) so objects now visually roll and tumble correctly.
Pyramid Shape: Added stPyramid (simulated via a 4-sided Jolt cylinder) with a slight spawn offset to prevent perfect balancing.
Frustum & Distance Culling: Optimized the 3D renderer to skip drawing objects that are out of camera view or beyond a set distance limit.
Custom Spawn Transforms: TModelActor.Create now accepts optional initial position (APos) and rotation (ARot) parameters for dynamic spawning.
Dynamic Glow State: Moved collision glow logic into a TealGlow property on the actor, triggered by velocity thresholds for cleaner rendering logic.
Selection Highlighting: Dynamically selected objects are now rendered with a yellow wireframe overlay for clear visual feedback.
Code Cleanup: Renamed cube-specific variables to generic item names (FItems, PItemData) to reflect support for multiple shape types.
JoltC Wrapper Based on JoltC from https://github.com/amerkoleci/joltc
ModelEngine based on https://github.com/GuvaCode/raylib-TPS-prototype
includes:
Raylib 3d https://github.com/LaMitaOne/r3d-delphi
MiniAudio4Delphi https://github.com/LaMitaOne/MiniAudio4Delphi
3D Test Models by https://kenney.nl/
Looking for more .glb / .gltf assets to test in the sandbox? Check out these awesome free resources: