VR-Forces Developer's Guide
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
exampleBallistics

Table of Contents

Overview

This example demonstrates the VR-Vantage ballistics system in isolation. It creates a plug-in driver, DtExampleBallisticsDriver, that fires bursts of GPU tracer rounds in response to key presses, removes them again, and previews the predicted trajectory of each shot. The example shows no platform or vehicle: the only things drawn are the GPU tracers and the trajectory-preview arcs.

Expected Result

exampleBallistics.png
Tracer bursts and predicted trajectory arcs

When you press one of the fire keys, a burst of tracer rounds is fired from a fixed muzzle position and travels along a ballistic trajectory under the influence of gravity and wind. Each fire key produces a differently coloured tracer burst. As a tracer passes near the observer, the "Bullet Flyby" proximity sound plays.

When you press Shift together with a fire key, nothing is fired. Instead, the driver draws the predicted trajectory of that same shot as three coloured arcs: green for wind plus gravity, yellow for gravity only, and red for no forces. Comparing the arcs shows how much wind and gravity bend the path. The arcs remain visible for 10 seconds, and if you change the wind while they are displayed the green wind-and-gravity arc re-bends immediately to match.

Example details

The example is built around the DtBallisticManager singleton, which owns the GPU ballistics simulation. The driver installs a DtEventProcessorInterface to watch for key presses. On a fire key it fills in a DtBallisticManager::BallisticData record and calls DtBallisticManager::createProjectiles(). On a Shift+key it runs the CPU-side DtTrajectoryPredictor instead and renders the result with DtDebugShapes.

Both the fire path and the preview path read the same per-key parameters from a single shot table, so the previewed arc always matches the burst that would be fired. Each entry describes a burst: the muzzle position and velocity, maximum range, the number of rounds, the rate of fire, how often a round is a visible tracer (the tracer interval), and the tracer appearance (DtTracerDefinition). The proximity sound group is always "Bullet Flyby".

The driver demonstrates several capabilities of the ballistics system:

The Example

The entry point exampleBallistics.cxx registers the plug-in and creates the DtExampleBallisticsDriver. The driver's onStart() loads the terrain, connects the wind signals, and installs the key event processor. onTick() polls the per-key fire and preview flags each frame, calling fireShot() to launch a tracer burst and predictShot() to draw a trajectory preview, both reading the shared shot table.

Building the Example

VR-Vantage includes pre-built versions of the example plug-in. To build it yourself, follow the instructions at Building VR-Vantage Examples, Applications, and Plug-ins.

Running the Example

This example is a plug-in. You can run it by running vrvStealth.exe –plugin ../examples/plugins/release/exampleBallistics.dll (on Windows) or vrvStealth.exe –plugin ../examples/plugins/release/libexampleBallistics.so (on Linux) from the command prompt. Once running, press 'B', 'N', or 'M' to fire a tracer burst, hold Shift with 'B', 'N', or 'M' to preview a trajectory, and press 'R' to remove everything. For more information about running examples, please see Running Applications and Examples.

Example Source Files


exampleBallistics.cxx

/*****************************************************************************
* Copyright (c) 2026 MAK Technologies, Inc.
* All rights reserved.
*****************************************************************************/
#include <vrvCore/DtDe.h>
#include <QtCore/QObject>
#include <QtCore/QString>
#include <QtWidgets/QToolBar>
// Use the VR-Vantage namespace.
// All classes in VR-Vantage are in this namespace.
using namespace makVrv;
static vrvSignalsLib::connection postInitializeConnection;
class DtExampleBallisticsToolbar : public DtToolbar
{
public:
DtExampleBallisticsToolbar( DtDe& de )
: DtToolbar( de, "DtExampleBallisticsToolbar" )
{
}
virtual ~DtExampleBallisticsToolbar() {}
virtual QToolBar* createToolbar( DtDe& de, QWidget* parent )
{
QString title = QObject::tr("Ballistics Example Toolbar");
QToolBar* tb = new QToolBar( parent );
tb->setWindowTitle( title );
tb->setObjectName( title );
return tb;
}
};
void initializeMinimalUI( DtDeInitializer&, DtDe&,
{
// Create DtExampleDriver.
// The driver is now owned by the display engine. Do not delete it.
de.driverManager().addDriver(driver);
// Start the driver, creating the agent.
de.driverManager().startDriver(driver);
// Disconnect now that the one-time post-initialize setup is complete.
postInitializeConnection.disconnect();
}
void init(DtDe& de)
{
// Ensure that init only gets called once
// (not strictly necessary here, but this is good practice in general)
// We only want to create the driver if we are running in master mode.
if (de.isInMasterMode())
{
//DtVrvApplication* app = DtVrvApplication::findFromDe(de);
//if (app)
//{
// DtVrvApplication::ApplicationTransform functor = boost::bind(&initializeMinimalUI, boost::placeholders::_1, boost::placeholders::_2, boost::placeholders::_3);
// app->installPostPluginTransform(functor, "MinimalUIPostPluginTransform");
//}
// The accessory must be created after the DE's initialization is
// finished, to make sure all the objects it uses exist.
postInitializeConnection = de.signal_postInitialize.connect(boost::bind(
&installDriver, std::ref(de)));
}
}
{
// Setup the plug-in. Normally, the init function and functionality
// should be in its own library.
init(*de);
return true;
}
void initializeMinimalUI( DtDeInitializer& deInit, DtDe& de,
{
// Register the toolbar so it can be added to the gui.
new DtExampleBallisticsToolbar(de) );
// Register the toolbar menuitem so it can be added to the toolbar.
// Add the example's toolbar with the FireDetonateLines toggle button.
toolbar.addToolbarPath( DtToolbarPath::toolbar("DtExampleBallisticsToolbar") );
toolbar.addToolbarPath( DtToolbarPath::toolbar("DtExampleBallisticsToolbar").item("DtFireDetonateLinesItem") );
// Tell the De not to show the startup screen. This must be done here
// because it will be overwritten if set with the rest of the configs.
}

DtExampleBallisticsDriver.cxx

/*****************************************************************************
* Copyright (c) 2026 MAK Technologies, Inc.
* All rights reserved.
*****************************************************************************/
#include <vrvCore/DtDe.h>
#include <algorithm>
#include <vector>
// Use the VR-Vantage namespace.
// All classes in VR-Vantage are in this namespace.
using namespace makVrv;
//#define USE_GEOCENTRIC_TERRAIN
#define SHOW_GRAVITY_ONLY
#define SHOW_NO_FORCES
struct DtBallisticShotDefinition
{
DtVector myPosition;
DtVector myVelocity;
double myMaxDistance;
int myCount;
double myRateOfFire;
int myTracerInterval;
DtTracerDefinition myTracerDefinition;
std::string myArcLabel;
};
namespace
{
// Scales a raw muzzle velocity by the shared velocity scale factor
// (1.0 keeps the original speed; 0.25 fires four times slower).
DtVector DtScaledMuzzleVelocity(const DtVector& rawVelocity)
{
const double velocityScale = 0.25;
DtVector scaled;
DtVecScale(rawVelocity, velocityScale, scaled);
return scaled;
}
// Returns the three per-key shot definitions, built once. The muzzle
// position, velocity, and range vary by terrain type, selected at compile
// time by USE_GEOCENTRIC_TERRAIN.
const std::vector<DtBallisticShotDefinition>& DtBallisticShotDefinitions()
{
static const std::vector<DtBallisticShotDefinition> theDefinitions = []()
{
std::vector<DtBallisticShotDefinition> definitions;
#ifdef USE_GEOCENTRIC_TERRAIN
// Near Ala Moana, Honolulu, Hawaii (geocentric ECEF coordinates).
definitions.push_back({
DtVector(-5506817.128206, -2240932.121720, 2301773.052875),
DtScaledMuzzleVelocity(DtVector(-365.649048, 761.991699, -115.231880)),
258.1192626953, 15, 750.0 / 60.0, 5,
definitions.push_back({
DtVector(-5506976.325637, -2240559.782043, 2301862.716279),
DtScaledMuzzleVelocity(DtVector(218.335922, -614.219727, -550.156860)),
198.2325134277, 3, 550.0 / 60.0, 1,
DtTracerDefinition::red(), "Shot N" });
definitions.push_back({
DtVector(-5506878.107655, -2240862.760257, 2301961.459429),
DtScaledMuzzleVelocity(DtVector(-132.207169, 511.155518, -669.962891)),
272.3383483887, 3, 550.0 / 60.0, 2,
DtTracerDefinition::green(), "Shot M" });
#else
// Ground_DB II ECEF coordinates (from DIS fire PDUs).
definitions.push_back({
DtVector(-521.924, -845.68, 61.8551),
DtScaledMuzzleVelocity(DtVector(789.674, 302.878, -110.854)),
318.4730529785, 15, 750.0 / 60.0, 5,
definitions.push_back({
DtVector(-164.228, -268.048, 36.5075),
DtScaledMuzzleVelocity(DtVector(-128.745, -938.665, -32.1992)),
470.5762329102, 3, 550.0 / 60.0, 1,
DtTracerDefinition::red(), "Shot N" });
definitions.push_back({
DtVector(-153.321, -270.162, 36.5229),
DtScaledMuzzleVelocity(DtVector(-135.452, -841.676, -29.0304)),
469.6385498047, 3, 550.0 / 60.0, 2,
DtTracerDefinition::green(), "Shot M" });
#endif
return definitions;
}();
return theDefinitions;
}
}
class DtBallisticFireEventProcessor : public DtEventProcessorInterface
{
public:
DtBallisticFireEventProcessor(bool& fireRequestedB, bool& fireRequestedN, bool& fireRequestedM,
bool& previewRequestedB, bool& previewRequestedN, bool& previewRequestedM,
bool& removeRequested)
: myFireRequestedB(fireRequestedB)
, myFireRequestedN(fireRequestedN)
, myFireRequestedM(fireRequestedM)
, myPreviewRequestedB(previewRequestedB)
, myPreviewRequestedN(previewRequestedN)
, myPreviewRequestedM(previewRequestedM)
, myRemoveRequested(removeRequested)
, myClassName("DtBallisticFireEventProcessor")
{
}
virtual ~DtBallisticFireEventProcessor() {}
virtual bool processMouseEvent(const DtMouseEvent& ev, DtChannel& channel) { return false; }
virtual bool processKeyboardEvent(const DtKeyEvent& ev, DtChannel& channel)
{
{
return false;
}
if (modifiers == DtKeyState::NO_MODIFIER)
{
if (key == DtKeyState::KEY_B)
{
myFireRequestedB = true;
return true;
}
if (key == DtKeyState::KEY_N)
{
myFireRequestedN = true;
return true;
}
if (key == DtKeyState::KEY_M)
{
myFireRequestedM = true;
return true;
}
if (key == DtKeyState::KEY_R)
{
myRemoveRequested = true;
return true;
}
}
else if (modifiers == DtKeyState::SHIFT_MODIFIER)
{
if (key == DtKeyState::KEY_B)
{
myPreviewRequestedB = true;
return true;
}
if (key == DtKeyState::KEY_N)
{
myPreviewRequestedN = true;
return true;
}
if (key == DtKeyState::KEY_M)
{
myPreviewRequestedM = true;
return true;
}
}
return false;
}
virtual const std::string& className() { return myClassName; }
protected:
bool& myFireRequestedB;
bool& myFireRequestedN;
bool& myFireRequestedM;
bool& myPreviewRequestedB;
bool& myPreviewRequestedN;
bool& myPreviewRequestedM;
bool& myRemoveRequested;
std::string myClassName;
};
: makVrv::DtDriver( am, "DtExampleBallisticsDriver" )
, myCoordinateSystem( nullptr )
, myWindSpeed( 0.0f )
, myWindDirection( 0.0f )
, myFireRequestedB( false )
, myFireRequestedN( false )
, myFireRequestedM( false )
, myPreviewRequestedB( false )
, myPreviewRequestedN( false )
, myPreviewRequestedM( false )
, myRemoveRequested( false )
, myEventProcessor( nullptr )
{
// Going forward we recommend locally cloning and keeping the coordinate system in sync
// with signals for ensuring thread safe operations on client side
myCoordinateSystem = am.de().sharedState().coordinateSystem().clone();
if (myCoordinateSystem == nullptr)
{
DtTHROW_NEW(DtCorruptedState, "myDe.sharedState().coordinateSystem().clone() failed.");
}
myConnections += DtDeSharedStateSignaler::instance( am.de() ).signal_coordinateSystemChanged.connect(
slot_coordinateSystemChanged();
}
{
}
const std::string& DtExampleBallisticsDriver::className() const
{
static std::string name = "DtExampleBallisticsDriver";
return name;
}
{
#ifdef USE_GEOCENTRIC_TERRAIN
// Load the geocentric terrain programatically.
DtScene& sceneDriver = myAgentManager.de().scene();
std::string groundDbPath = myAgentManager.de().dePathConfiguration().sharedDataPath();
groundDbPath += "/TerrainData/TerrainConfiguration/Ala Moana.mtf";
sceneDriver.loadTerrain( groundDbPath );
#else
// Load Ground_DB II programatically.
DtScene& sceneDriver = myAgentManager.de().scene();
std::string groundDbPath = myAgentManager.de().dePathConfiguration().sharedDataPath();
groundDbPath += "/TerrainData/TerrainConfiguration/Ground_DB II.mtf";
sceneDriver.loadTerrain( groundDbPath );
#endif
DtSkyObjectSignaler& skySignal = DtSkyObjectSignaler::instance(myAgentManager.de());
skySignal.signal_windSpeedChanged.connect(
this, boost::placeholders::_1)));
skySignal.signal_windDirectionChanged.connect(
this, boost::placeholders::_1)));
// Register key bindings: 'B'/'N'/'M' fire tracer bursts, Shift+'B'/'N'/'M'
// preview the predicted trajectory, and 'R' removes everything.
myEventProcessor = new DtBallisticFireEventProcessor(
return true;
}
{
{
myEventProcessor = nullptr;
}
// Remove any predicted trajectory arcs still being displayed.
return true;
}
{
const std::vector<DtBallisticShotDefinition>& definitions = DtBallisticShotDefinitions();
// Fire a tracer burst for each fire key pressed this frame. The B/N/M keys
// map to shot indices 0/1/2; guard each access on the table size so a future
// change to the shot table cannot index out of range.
{
if (definitions.size() > 0)
{
fireShot(definitions[0]);
}
}
{
if (definitions.size() > 1)
{
fireShot(definitions[1]);
}
}
{
if (definitions.size() > 2)
{
fireShot(definitions[2]);
}
}
// Preview the predicted trajectory for each Shift+key pressed this frame.
{
if (definitions.size() > 0)
{
predictShot(definitions[0]);
}
}
{
if (definitions.size() > 1)
{
predictShot(definitions[1]);
}
}
{
if (definitions.size() > 2)
{
predictShot(definitions[2]);
}
}
// Remove all fired bursts and predicted arcs when 'R' is pressed.
{
if (!myFiredIdentifiers.empty())
{
DtBallisticManager& ballisticManager = DtBallisticManager::instance(myAgentManager.de());
for (const auto& identifier : myFiredIdentifiers)
{
ballisticManager.removeProjectiles(identifier);
}
myFiredIdentifiers.clear();
}
}
return true;
}
{
myWindSpeed = metersPerSecond;
}
{
myWindDirection = radians;
}
DtVector position, DtVector& east, DtVector& north, DtVector& up)
{
{
return;
}
if (!converter)
{
return;
}
converter->setupTopoFrame(position);
converter->enuToCig_vecTrans(DtVector(1.0, 0.0, 0.0), east);
converter->enuToCig_vecTrans(DtVector(0.0, 1.0, 0.0), north);
converter->enuToCig_vecTrans(DtVector(0.0, 0.0, 1.0), up);
}
{
}
void DtExampleBallisticsDriver::predictShot(const DtBallisticShotDefinition& def)
{
// Remove any existing arcs for this shot so a re-preview (for example after
// a wind change) replaces rather than duplicates them.
double muzzleVelocity = std::sqrt(def.myVelocity.magnitudeSquared());
if (muzzleVelocity <= 0.0)
{
return;
}
double lifeTime = (def.myMaxDistance / muzzleVelocity) * 2.0;
double timeStep = lifeTime / 100.0;
// Build the bullet from the same parameters used to fire the burst.
DtBulletDefinition bulletDef;
bulletDef.setMuzzleVelocity(muzzleVelocity);
bulletDef.setMaxDistance(def.myMaxDistance);
bulletDef.setMaxLifetime(lifeTime);
bulletDef.setMass(0.01);
bulletDef.setCaliber(5.56);
// Build the local ENU frame at the muzzle position.
DtVector east(1.0, 0.0, 0.0);
DtVector north(0.0, 1.0, 0.0);
DtVector up(0.0, 0.0, 1.0);
computeDirectionVectors(def.myPosition, east, north, up);
dvec3(east.x(), east.y(), east.z()),
dvec3(north.x(), north.y(), north.z()),
dvec3(up.x(), up.y(), up.z()));
// Start the prediction at the exact muzzle position so the previewed arc
// lines up with the fired tracers, which launch from def.myPosition.
dvec3 origin = dvec3(def.myPosition.x(), def.myPosition.y(), def.myPosition.z());
dvec3 velocity = dvec3(def.myVelocity.x(), def.myVelocity.y(), def.myVelocity.z());
velocity.normalize();
velocity *= bulletDef.muzzleVelocity();
// How long a previewed arc stays on screen, in seconds, before it
// self-expires. The 'R' key still clears arcs on demand before this elapses.
const float previewAliveTime = 10.0f;
// Predicts one trajectory and stitches it into a coloured multi-line shape.
auto drawArc = [&](const std::string& label, double red, double green, double blue,
const DtBallisticEnvironment& environment)
{
DtTrajectoryPredictor trajectoryPredictor;
std::vector<DtTrajectoryPoint> trajectory =
trajectoryPredictor.predictTrajectory(origin, velocity, bulletDef, environment, lifeTime, timeStep);
if (trajectory.empty())
{
return;
}
DtGeom3dLinesComponent* multiLine = de.renderer().debugShapes().addMultiLine(label, previewAliveTime);
if (!multiLine)
{
return;
}
multiLine->setCurrentColor(red, green, blue, 1.0);
multiLine->setCurrentStartColor(red, green, blue, 1.0);
multiLine->setCurrentEndColor(red, green, blue, 1.0);
DtVector pointA(0.0, 0.0, 0.0);
DtVector pointB(0.0, 0.0, 0.0);
int index = -1;
for (const DtTrajectoryPoint& point : trajectory)
{
pointB = pointA;
pointA = DtVector(point.position().x, point.position().y, point.position().z);
if (index == -1)
{
index = 0;
continue;
}
multiLine->setLine(pointA, pointB, index);
++index;
}
};
// Wind and gravity (green).
{
dvec3 windVelocityEnu(
0.0);
dvec3 windVelocityInFrame =
frame.right() * windVelocityEnu.x +
frame.forward() * windVelocityEnu.y +
frame.up() * windVelocityEnu.z;
environment.setCoordinateFrame(frame);
environment.setGravity(frame.up() * -9.81);
environment.setWindVelocity(windVelocityInFrame);
drawArc(def.myArcLabel + " Wind+Gravity", 0.0, 1.0, 0.0, environment);
}
#ifdef SHOW_GRAVITY_ONLY
// Gravity only (yellow).
{
environment.setGravity(frame.up() * -9.81);
environment.setWindVelocity(dvec3(0.0, 0.0, 0.0));
drawArc(def.myArcLabel + " Gravity", 1.0, 1.0, 0.0, environment);
}
#endif
#ifdef SHOW_NO_FORCES
// No forces (red).
{
environment.setGravity(dvec3(0.0, 0.0, 0.0));
environment.setWindVelocity(dvec3(0.0, 0.0, 0.0));
drawArc(def.myArcLabel + " No Forces", 1.0, 0.0, 0.0, environment);
}
#endif
// Remember this shot so its arcs can be re-predicted when the wind changes.
if (std::find(myActivePreviews.begin(), myActivePreviews.end(), &def) == myActivePreviews.end())
{
myActivePreviews.push_back(&def);
}
}
void DtExampleBallisticsDriver::fireShot(const DtBallisticShotDefinition& def)
{
ballisticData.myPosition = def.myPosition;
ballisticData.myVelocity = def.myVelocity;
ballisticData.myMuzzleVelocity = std::sqrt(def.myVelocity.magnitudeSquared());
ballisticData.myMaxDistance = def.myMaxDistance;
ballisticData.myMaxLifetime = (def.myMaxDistance / ballisticData.myMuzzleVelocity) * 2.0;
ballisticData.myMass = 0.01;
ballisticData.myCaliber = 5.56;
ballisticData.myCount = def.myCount;
ballisticData.myRateOfFire = def.myRateOfFire;
ballisticData.myTracerInterval = def.myTracerInterval;
ballisticData.myTracerDefinition = def.myTracerDefinition;
ballisticData.myProximitySoundGroup = "Bullet Flyby";
identifier.mySourceId = std::to_string(myAgentManager.createNewUniqueId());
myFiredIdentifiers.push_back(identifier);
DtBallisticManager& ballisticManager = DtBallisticManager::instance(myAgentManager.de());
ballisticManager.createProjectiles(identifier, ballisticData);
}
void DtExampleBallisticsDriver::removeArcsFor(const DtBallisticShotDefinition& def)
{
de.renderer().debugShapes().removeMultiLine(def.myArcLabel + " Wind+Gravity");
de.renderer().debugShapes().removeMultiLine(def.myArcLabel + " Gravity");
de.renderer().debugShapes().removeMultiLine(def.myArcLabel + " No Forces");
}
{
// Copy the active list first because predictShot() appends to it; re-predict
// each displayed shot so the arcs reflect the latest wind speed/direction.
std::vector<const DtBallisticShotDefinition*> active = myActivePreviews;
for (const DtBallisticShotDefinition* def : active)
{
predictShot(*def);
}
}
{
for (const DtBallisticShotDefinition& def : DtBallisticShotDefinitions())
{
}
}

DtExampleBallisticsDriver.h

/*****************************************************************************
* Copyright (c) 2026 MAK Technologies, Inc.
* All rights reserved.
*****************************************************************************/
#pragma once
#include <deque>
#include <vector>
#include <matrix/vlVector.h>
#include <boost/bind/bind.hpp>
#include <boost/bind/placeholders.hpp>
namespace makVrv
{
class DtCoordinateSystem;
class DtEventProcessorInterface;
}
struct DtBallisticShotDefinition;
{
public:
virtual const std::string& className() const;
virtual bool onStart();
virtual bool onStop();
virtual bool onTick();
protected:
virtual void computeDirectionVectors(DtVector position, DtVector& east, DtVector& north, DtVector& up);
void fireShot(const DtBallisticShotDefinition& def);
void predictShot(const DtBallisticShotDefinition& def);
void removeArcsFor(const DtBallisticShotDefinition& def);
virtual void slot_windSpeedChanged(float metersPerSecond);
virtual void slot_windDirectionChanged(float radians);
protected:
float myWindSpeed;
std::deque<makVrv::DtBallisticManager::BallisticIdentifier> myFiredIdentifiers;
std::vector<const DtBallisticShotDefinition*> myActivePreviews;
};

[<< Examples] [Home] [Top of Page]


Document ID: Generated on Thu Oct 15 21:27:02 EDT 2026 from SVN revision 296421
Copyright © 2005-2026 MAK Technologies. All Rights Reserved (www.mak.com)