Skip to content

Zero Hour rebuilt from EA's source: x64, Direct3D 11, VS2022/CMake, ~60 original bugs fixed, an AI that builds a base. Bring your own game.

perf(w3ddevice): instanced depth-only sun shadow casters

Olcay Seygan7b0df7f816df
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f3c7bd2c4..24cc6a829 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -414,6 +414,7 @@ found and fixed, EA's own, not port damage.**
- Crowded battles run a good deal faster. At 1080p, thirty Inferno Cannons against twenty Crusaders went from 153 to 227 frames a second, and six Brutal computer players on one map from 146 to 240. The slowest one frame in twenty got 22 to 34% shorter, and the slowest one in a hundred 16 to 29%. The game stopped re-sending lights, materials, textures and card settings that had not changed, stopped relighting the terrain when no light had moved, stopped adding up the glow of every fire particle twice, and widened low-colour textures with a lookup instead of arithmetic on each pixel. The new renderer keeps the old one's settings back until something actually reads them, re-sends only the half of each draw's settings that changed, and remembers each patch of ground's colours, its blend coordinates and its tread marks between frames. Units whose shadow cannot reach the screen are no longer drawn into the shadow map, except on maps with reflecting water. The command bar and the console replay what they drew last frame when nothing under them moved, and the HUD checks for changes without rebuilding its text. The rules side runs 4% quicker too: locking, the lists of nearby units, the sleeping-unit schedule and text strings all got cheaper. The picture matches the old build in all eight test views on both renderers, and a recorded match plays back to the same checksum.
- A long match costs less late in the game. Four Hard computer players on Twilight Flame, well into the match, went from 111.6 to 136.2 frames a second, and the step that works out the battle from 5.59ms to 4.78ms. The computer left every group it had made and never filled in a list the game went through on every step until the match ended, and that list is cleared now. A unit looking for something to shoot passes over ground that holds nobody it could shoot at, sight is worked out with fewer lookups, and the smoke and fire are gone through once per step instead of once for every picture. Eight views over five maps came out the same as before.
- Every moving unit's skeleton was worked out three times a picture, once for its shadow, once for the scene and once more for the outline drawn when it stands behind a building. It is worked out once now, and late in the same match the animation costs 60% less. With the rules step finding the next unit due for an update a little faster, minutes 24 to 26 went from 119.8 to 123.7 frames a second, and the match still ends on the same checksum.
+- Shadows in a big battle cost about a third of what they did. With some 560 tanks, soldiers and buildings throwing a shadow on Twilight Flame, the sun's shadows took 0.90 ms of every picture and now take 0.36, never more than half a millisecond in any second of the fight. Every copy of the same model now goes to the graphics card in one batch, so the shadows that took 916 separate draws take 121, and the card itself spends half as long on them. The shadows land on the same pixels they did.
- Late in a match the picture caught less often. Every ten seconds each computer player looked over its economy, its spending and the enemy army all in one step, 8 to 10ms of work landing on a single picture. Those three now run a fifth of a second apart. With four Hard computer players on Twilight Flame at minutes 24 and 25, pictures slower than 16.7ms went from 29 a minute to 22, and the slowest one in a hundred from 14.7ms to 14.0ms. Two more hitches got smaller in the same match. The map of where units can drive is rebuilt whenever a building goes up or comes down, and that rebuild went from 9.9ms to 7.4ms, with the ones over 8ms halved (90 to 43). A Hard computer steering its Particle Cannon beam now weighs the ground around it in 0.9ms instead of 2.6ms. Neither changes a single move: the match ends on the same checksum.
- The game no longer freezes for seconds when your hard drive is busy. It writes a log of the match as it plays, and once a second the battle itself stopped to push that log to disk. On a drive already busy with something else, Windows can hold such a write back for seconds, and the whole game stood still behind it: a 2v2 against the computer froze for 7.8 seconds on a single step. The log is written on the side now and the battle never waits for it. Three matches played while another program kept the drive busy froze for 6.2 seconds in two of them before; with the change, the slowest step in all three took 48ms.
- The game's log no longer grows without limit. Players sent us logs of half a gigabyte up to 19 GB, enough to fill a disk, and the launcher could not open them to report a crash. Most of it was the network code writing a line for every order and every frame, which only a developer's build writes now: a 100-second two-player network match went from 10.9 MB of log to 175 KB, and a skirmish from 600 KB to 166 KB. Past 64 MB the log keeps its first 8 MB, which say how the game started and on what machine, and its most recent lines, so it stays under 64 MB however long you play.
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h
index b42ee3c5d..d8432a2b9 100644
--- a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h
+++ b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h
@@ -333,6 +333,7 @@ public:
Int m_lightingStyle; // "LightingStyle": LightingStyleType; the map's lights are rebalanced as each map loads
Bool m_shadowMap; // "-shadowmap": draw the casters into the sun's depth buffer as well
Bool m_shadowMapReport; // "-shadowmapreport": log what ended up in that buffer, once a second
+ Bool m_shadowMapOldCasters; // "-shadowmapoldcasters": every caster through the mesh renderer, none instanced
Bool m_shadowMapOnly; // "-shadowmaponly": the map's shadows with the stencil volumes' own darkening off
Real m_shadowMapPenumbra; // "-shadowtune": penumbra per world unit of gap under the caster, 0 for the built-in
Real m_shadowMapSkyFill; // how much of a wide shadow the sky fills back in
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/LogicThread.h b/GeneralsMD/Code/GameEngine/Include/Common/LogicThread.h
index 2686af56c..6abffc470 100644
--- a/GeneralsMD/Code/GameEngine/Include/Common/LogicThread.h
+++ b/GeneralsMD/Code/GameEngine/Include/Common/LogicThread.h
@@ -32,6 +32,7 @@
#include <atomic>
#include <functional>
+#include <mutex>
#include <vector>
class Drawable;
@@ -153,6 +154,27 @@ namespace LogicThread
Bool m_open;
};
+ /** Live render objects between the tick and a fork that poses them. The sun's shadow pass holds it
+ * on the main thread across its pose fork; the tick takes it (TickReachesLiveModels) wherever it
+ * reaches a live model through Drawable::getDrawModulesFlushed, which can set a model's state or
+ * pose its bones. Neither side waits for the other while holding it, so neither can deadlock, and
+ * a bone read lands at the same pose either side of the fork: posing is a function of the model
+ * and the frame's sync time alone. Recursive, because those reaches nest. */
+ extern std::recursive_mutex g_liveModelLock;
+
+ /** The tick's half of g_liveModelLock; nothing on any other thread, where the tick is not running
+ * beside a fork. */
+ class TickReachesLiveModels
+ {
+ public:
+ TickReachesLiveModels( void ) : m_locked( t_isLogicThread ) { if( m_locked ) g_liveModelLock.lock(); }
+ ~TickReachesLiveModels( void ) { if( m_locked ) g_liveModelLock.unlock(); }
+ private:
+ TickReachesLiveModels( const TickReachesLiveModels & );
+ TickReachesLiveModels &operator=( const TickReachesLiveModels & );
+ Bool m_locked;
+ };
+
/** LOGIC-THREAD.md phase 3, step 3b, the overlap. GameClient::update calls this in front of the
* draw: at 1 and 2 it asks GameEngine::planOverlappedTick, which runs the message stream and the
* pacer there in a single-player match, whether the pass's first tick is due. */
diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleSys.h b/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleSys.h
index 4284421b6..8ea9aeec3 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleSys.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleSys.h
@@ -786,8 +786,11 @@ public:
/// The renderer put at least one of this system's particles into the sun's smoke map on its
/// last frame, so the cloud shades the ground already and its blob would shade it twice.
/// Written by the shadow pass every frame it runs, read by shouldCastGroundShadow.
- void setInSunMap( Bool inSunMap ) { m_inSunMap = inSunMap; }
- Bool isInSunMap( void ) const { return m_inSunMap; }
+ /// A mark is the stamp of the fill that set it, so the next fill drops every mark at once with
+ /// forgetAllInSunMap rather than finding each system the last one marked.
+ void setInSunMap( Bool inSunMap ) { m_inSunMapStamp = inSunMap ? s_sunMapStamp : 0; }
+ Bool isInSunMap( void ) const { return m_inSunMapStamp == s_sunMapStamp; }
+ static void forgetAllInSunMap( void ) { if( ++s_sunMapStamp == 0 ) s_sunMapStamp = 1; }
Bool shouldBillboard( void ) { return !m_isGroundAligned; }
@@ -903,7 +906,8 @@ protected:
ParticleShadowBlob m_pendingShadowBlob; ///< the survivors' footprint, gathered by updateParticlesMark
Bool m_pendingCastsGroundShadow; ///< decided by updateEmission, where update() always decided it
UnsignedInt m_pendingDeaths; ///< particles updateParticlesMark marked; the reap stops once it has removed them
- Bool m_inSunMap; ///< setInSunMap: client-only, never xfered
+ UnsignedInt m_inSunMapStamp; ///< setInSunMap: client-only, never xfered; 0 is never a fill's stamp
+ static UnsignedInt s_sunMapStamp; ///< the current fill's, from 1
protected:
Particle * m_systemParticlesHead;
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp
index 157fefb4c..8fa2f6924 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp
@@ -1041,6 +1041,16 @@ Int parseShadowMapReport(char *args[], int num)
return 1;
}
+/* -shadowmapoldcasters: the sun's depth pass draws every caster through the mesh renderer one draw a
+ piece, as it did before the opaque rigid ones went into instanced depth-only draws. The other half
+ of any A/B of what that costs or of whether the map still holds the same depth. */
+Int parseShadowMapOldCasters(char *args[], int num)
+{
+ if (TheWritableGlobalData)
+ TheWritableGlobalData->m_shadowMapOldCasters = TRUE;
+ return 1;
+}
+
/* -noparticleshadows: take the soft blob back off the ground under every particle cloud.
ShadowsForParticles is on by default and the shipped INI has no entry for it, so without this
@@ -2860,6 +2870,7 @@ static CommandLineParam params[] =
{ "-noDynamicLOD", parseNoDynamicLOD },
{ "-nochroma", parseNoChroma },
{ "-shadowmapreport", parseShadowMapReport },
+ { "-shadowmapoldcasters", parseShadowMapOldCasters },
{ "-shadowmapboth", parseShadowMapBoth },
{ "-noparticleshadows", parseNoParticleShadows },
{ "-novolumetricsmoke", parseNoVolumetricSmoke },
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp
index 6d9e87e2e..a5862e881 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp
@@ -3320,6 +3320,15 @@ void GameEngine::update( void )
if( windowMS >= 1000 )
{
const Real fps = (Real)fpsFrames * 1000.0f / (Real)windowMS;
+ // The sun's depth pass every second of a match, fast or slow, so its cost can be read
+ // on a machine that never drops under the gate below. Under -shadowmapreport only.
+ if( TheGlobalData->m_shadowMapReport && TheGameLogic && TheGameLogic->isInGame()
+ && !TheGameLogic->isInShellGame() )
+ {
+ DEBUG_LOG(("SHADOW WINDOW frame %d: cpu %.2f ms, %.0f casters, %.0f draws a picture\n",
+ TheGameLogic->getFrame(), fpsShadowTotal / fpsFrames,
+ (Real)fpsCasterTotal / fpsFrames, (Real)fpsShadowDrawTotal / fpsFrames));
+ }
if( fps < 50.0f && TheGameLogic && TheGameLogic->isInGame() && !TheGameLogic->isInShellGame() )
{
// 'hz' is the rate the simulation actually achieved and 'catchup' how many render
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp
index d699262c8..3e14b2b42 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp
@@ -983,6 +983,7 @@ GlobalData::GlobalData()
m_shadowMap = TRUE; //the sun's own shadows are what the game draws with now
m_shadowMapOnly = TRUE; //and they replace the stencil volumes rather than joining them
m_shadowMapReport = FALSE;
+ m_shadowMapOldCasters = FALSE;
m_shadowMapPenumbra = 0.0f; //zero anywhere here means the built-in value stands
m_shadowMapSkyFill = 0.0f;
m_shadowMapStrength = 0.0f;
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/LogicThread.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/LogicThread.cpp
index 9f5de2b12..0ec6c4882 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/System/LogicThread.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/LogicThread.cpp
@@ -53,6 +53,7 @@
thread_local Bool LogicThread::t_isLogicThread = FALSE;
std::atomic<Int> LogicThread::g_windowOpen( 0 );
+std::recursive_mutex LogicThread::g_liveModelLock;
namespace
{
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp
index 188cb7843..cd95b7235 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable.cpp
@@ -1133,6 +1133,7 @@ Int Drawable::getCurrentClientBonePositions(const char* boneNamePrefix, Int star
Int count = 0;
// the bones as drawn; asked after the tick (the uplink cannon's raised antenna, FX at bones), where
// what the tick deferred on this drawable is applied first
+ LogicThread::TickReachesLiveModels liveModels; // a tick beside the render waits out the shadow pass's poses
for (DrawModule** dm = const_cast<Drawable*>(this)->getDrawModulesFlushed(); *dm; ++dm)
{
if (maxBones <= 0)
@@ -1164,6 +1165,7 @@ Int Drawable::getCurrentClientBonePositions(const char* boneNamePrefix, Int star
Bool Drawable::getCurrentWorldspaceClientBonePositions(const char* boneName, Matrix3D& transform) const
{
// a laser's client update and the attached models ask; the bones have to be where the tick left the drawable
+ LogicThread::TickReachesLiveModels liveModels;
for (DrawModule** dm = const_cast<Drawable*>(this)->getDrawModulesFlushed(); *dm; ++dm)
{
if (skipsForLogic(*dm))
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp
index 6a996c82b..a7394799d 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp
@@ -1441,10 +1441,12 @@ void ParticleSystemInfo::loadPostProcess( void )
// ParticleSystem /////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
+UnsignedInt ParticleSystem::s_sunMapStamp = 1;
+
// ------------------------------------------------------------------------------------------------
/** Read particle system properties from given file */
// ------------------------------------------------------------------------------------------------
-ParticleSystem::ParticleSystem( const ParticleSystemTemplate *sysTemplate,
+ParticleSystem::ParticleSystem( const ParticleSystemTemplate *sysTemplate,
ParticleSystemID id,
Bool createSlaves )
{
@@ -1586,7 +1588,7 @@ ParticleSystem::ParticleSystem( const ParticleSystemTemplate *sysTemplate,
m_personalityStore = 0;
m_controlParticle = NULL;
m_groundShadow = NULL;
- m_inSunMap = FALSE;
+ m_inSunMapStamp = 0;
m_gpuEligible = TheParticleSystemManager->acceptsGpuParticles() && sysTemplate->isGpuEligible();
m_gpuSpawnTotal = 0;
@@ -2900,7 +2902,7 @@ Bool ParticleSystem::shouldCastGroundShadow( void ) const
return FALSE;
// the sun's map holds this cloud already and shades the ground under it through its own density
- if (m_inSunMap)
+ if (isInSunMap())
return FALSE;
if (m_isGroundAligned)
diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DTreeBuffer.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DTreeBuffer.h
index d667d747e..cb2dd1b42 100644
--- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DTreeBuffer.h
+++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DTreeBuffer.h
@@ -132,7 +132,8 @@ typedef struct {
Int swayType; ///< Which sway array entry we are using.
Int firstIndex; ///< First index in the vertex buffer for this tree.
- Int bufferNdx; ///< Which vertex buffer this is in.
+ Int bufferNdx; ///< Which vertex buffer this is in, -1 when the last fill left it out.
+ Bool moved; ///< Its vertices changed since updateVertexBuffer last wrote them.
// Topple parameters. [7/7/2003]
Real m_angularVelocity; ///< Velocity in degrees per frame (or is it radians per frame?)
@@ -268,6 +269,15 @@ private:
std::vector<ShadowRange> m_shadowRanges[MAX_BUFFERS];
Bool m_lastShadowsForProps = FALSE;
Int m_sunCasterTrees = 0;
+ // What the last sun pass culled against: both views' frustum planes, the silhouette stretch and
+ // ShadowsForProps. The next pass with the same key and no tree changed keeps its visible flags
+ // rather than walking every tree again; any tree change or a screen-only cull drops the key.
+ enum { SUN_CULL_KEY = 2*6*4 + 4 };
+ Real m_sunCullKey[SUN_CULL_KEY];
+ Int m_sunCullTrees = 0;
+ Bool m_sunCullValid = FALSE;
+ Bool m_movedSinceCull = FALSE; ///< a tree moved since the last full cull (a sinking one's sort key moves)
+ std::vector<Int> m_movedTrees; ///< the trees with moved set, in the order stepTrees moved them
IDirect3DPixelShader9 * m_dwTreePixelShader; ///<D3D pixel shader
IDirect3DVertexShader9 * m_dwTreeVertexShader; ///<D3D vertex shader
IDirect3DVertexDeclaration9 * m_treeVertexDeclaration; ///<what D3D8 carried beside the shader
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DModelDraw.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DModelDraw.cpp
index ff040e84f..b0d40c039 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DModelDraw.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DModelDraw.cpp
@@ -3669,7 +3669,10 @@ void W3DModelDraw::setModelState(const ModelConditionInfo* newState)
//BONEPOS_LOG(("validateStuff() from within W3DModelDraw::setModelState()\n"));
//BONEPOS_DUMPREAL(draw->getScale());
- newState->validateStuff(m_renderObject, draw->getScale(), getW3DModelDrawModuleData()->m_extraPublicBones);
+ // inside a tick never the live model, as getPristineBonePositionsForConditionState asks: the render
+ // may be posing it beside the tick, and its captured turret bones would go into the shared cache
+ newState->validateStuff(TheGameLogic->isInGameLogicUpdate() ? NULL : m_renderObject, draw->getScale(),
+ getW3DModelDrawModuleData()->m_extraPublicBones);
// ensure that any muzzle flashes from the *new* state, start out hidden...
// hideAllMuzzleFlashes(newState, m_renderObject);//moved to above
rebuildWeaponRecoilInfo(newState);
@@ -3801,7 +3804,8 @@ void W3DModelDraw::setModelState(const ModelConditionInfo* newState)
//BONEPOS_LOG(("validateStuff() from within W3DModelDraw::setModelState()\n"));
//BONEPOS_DUMPREAL(getDrawable()->getScale());
- newState->validateStuff(m_renderObject, getDrawable()->getScale(), getW3DModelDrawModuleData()->m_extraPublicBones);
+ newState->validateStuff(TheGameLogic->isInGameLogicUpdate() ? NULL : m_renderObject, getDrawable()->getScale(),
+ getW3DModelDrawModuleData()->m_extraPublicBones); // the live model only outside a tick, as above
rebuildWeaponRecoilInfo(newState);
// ensure that any muzzle flashes from the *previous* state, are hidden...
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cpp
index 23b8a97ad..0d2b68716 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DVolumetricShadow.cpp
@@ -80,7 +80,10 @@
#include "GameClient/ParticleSys.h"
#include "W3DDevice/GameClient/W3DParticleSys.h"
#include "W3DDevice/GameClient/Module/W3DModelDraw.h"
+#include "Common/JobSystem.h"
+#include "Common/LogicThread.h"
#include <algorithm>
+#include <cstddef>
#include <vector>
#ifdef _INTERNAL
@@ -3889,22 +3892,11 @@ DECLARE_PERF_TIMER(stencilShadows)
DECLARE_PERF_TIMER(shadowVolumeUpdate)
DECLARE_PERF_TIMER(shadowVolumeSubmit)
-/// The systems the last fill marked, by id: a particle update since may have retired any of them.
-static std::vector<ParticleSystemID> s_systemsInSunMap;
-
-/** Nothing of this frame's smoke is in the map: every system keeps its blob. Only a system the last
- fill marked can be marked, so only those are looked up, not every system there is. */
+/** Nothing of this frame's smoke is in the map: every system keeps its blob. A new stamp drops every
+ mark at once; finding each system the last fill marked was a list walk and a map lookup apiece. */
static void forgetSmokeInSunMap( void )
{
- if (TheParticleSystemManager == NULL)
- return;
- for (size_t i = 0; i < s_systemsInSunMap.size(); ++i)
- {
- ParticleSystem *sys = TheParticleSystemManager->findParticleSystem( s_systemsInSunMap[ i ] );
- if (sys) // gone since, with its mark
- sys->setInSunMap( FALSE );
- }
- s_systemsInSunMap.clear();
+ ParticleSystem::forgetAllInSunMap();
}
/** One particle on its way into the smoke map, with the system it came from and how far it is from
@@ -3916,6 +3908,10 @@ struct SmokeCaster
ParticleSystem *system;
bool operator<( const SmokeCaster &other ) const { return distanceSqr < other.distanceSqr; }
};
+// the smoke cull copies the five floats the backend reads straight out of both
+static_assert( offsetof( SmokeCaster, opticalDepth ) == 4 * sizeof(Real), "SmokeCaster leads with the backend's five floats" );
+static_assert( offsetof( W3DParticleSystemManager::SunMapCaster, opticalDepth ) == 4 * sizeof(Real),
+ "SunMapCaster leads with the backend's five floats" );
/** The smoke into the sun's light: every alpha-blended billboard particle as a soft ball, its optical
depth the one its own alpha implies (particleSunMapOpticalDepth), handed to the backend's smoke
@@ -3925,42 +3921,153 @@ struct SmokeCaster
particles nearest the camera's focus win, so a new fire on screen is never starved by old smoke
at the edge. Every system with a particle in the map is marked, and those lose their blob;
with the option off, or the map refused, none is. */
-static void fillSmokeMap( const Matrix3D &sunTransform, const Vector3 &focus, Real halfWidth, Real farClip )
+struct SmokeMapJob
+{
+ const W3DParticleSystemManager::SunMapCaster *candidates;
+ size_t count;
+ Int chunks;
+ Matrix3D sunTransform;
+ Real halfWidth, farClip;
+ Real *packed; ///< five floats a candidate, each chunk at its own candidates' offset
+ ParticleSystem **runs; ///< each chunk's runs of one system, at its own candidates' offset
+ UnsignedInt *kept; ///< particles each chunk kept
+ UnsignedInt *noted; ///< runs each chunk noted
+};
+static SmokeMapJob s_smoke;
+static std::vector<Real> s_smokePacked; // kept, and never shrunk, so not filled again each frame
+static std::vector<ParticleSystem *> s_smokeRuns;
+static std::vector<UnsignedInt> s_smokeChunkCounts;
+#define SMOKE_CANDIDATES_PER_CHUNK 512 // short enough that no chunk is the fork's long pole
+
+/** The box the depth map covers, in the sun's own frame: it looks down its -Z. */
+static inline Bool inSunBox( const W3DParticleSystemManager::SunMapCaster &candidate )
+{
+ const Real radius = candidate.radius;
+ Vector3 inSun;
+ Matrix3D::Inverse_Transform_Vector( s_smoke.sunTransform, Vector3( candidate.x, candidate.y, candidate.z ), &inSun );
+ const Real reach = s_smoke.halfWidth + radius;
+ return !(inSun.X < -reach || inSun.X > reach || inSun.Y < -reach || inSun.Y > reach
+ || -inSun.Z < SHADOW_MAP_NEAR_CLIP - radius || -inSun.Z > s_smoke.farClip + radius);
+}
+
+/** The smoke map's CPU half, before the fork: the old marks dropped, the candidates taken and every
+ buffer the chunks write sized here, because a job does not allocate. The particles are walked
+ once a particle update (getSunMapCasters, its own fork); a pass drawn in between, half of them
+ late in a match and most of them early, only culls that list to its own sun. */
+static void beginSmokeMap( const Matrix3D &sunTransform, Real halfWidth, Real farClip )
+{
+ forgetSmokeInSunMap();
+ s_smoke.count = 0;
+ s_smoke.chunks = 0;
+ if (!TheGlobalData->m_volumetricSmokeShadows || TheParticleSystemManager == NULL)
+ return;
+ const std::vector<W3DParticleSystemManager::SunMapCaster> &candidates =
+ ((W3DParticleSystemManager *)TheParticleSystemManager)->getSunMapCasters();
+ if (candidates.empty())
+ return;
+ const size_t count = candidates.size();
+ const Int chunks = (Int)((count + SMOKE_CANDIDATES_PER_CHUNK - 1) / SMOKE_CANDIDATES_PER_CHUNK);
+ if (s_smokePacked.size() < count * 5)
+ s_smokePacked.resize( count * 5 );
+ if (s_smokeRuns.size() < count)
+ s_smokeRuns.resize( count );
+ if (s_smokeChunkCounts.size() < (size_t)chunks * 2)
+ s_smokeChunkCounts.resize( (size_t)chunks * 2 );
+ s_smoke.candidates = &candidates[ 0 ];
+ s_smoke.count = count;
+ s_smoke.chunks = chunks;
+ s_smoke.sunTransform = sunTransform;
+ s_smoke.halfWidth = halfWidth;
+ s_smoke.farClip = farClip;
+ s_smoke.packed = &s_smokePacked[ 0 ];
+ s_smoke.runs = &s_smokeRuns[ 0 ];
+ s_smoke.kept = &s_smokeChunkCounts[ 0 ];
+ s_smoke.noted = &s_smokeChunkCounts[ chunks ];
+}
+
+/** One chunk of the cull, on any thread: the in-box particles straight into what the backend reads
+ (x, y, z, radius and optical depth lead a SunMapCaster in that order), and a system noted when it
+ changes rather than with every particle, since a list's particles come a system at a time. The
+ distance to the focus only decides anything past the limit, which endSmokeMap handles. */
+static void cullSmokeChunk( Int chunk )
+{
+ const size_t first = (size_t)chunk * SMOKE_CANDIDATES_PER_CHUNK;
+ const size_t end = (std::min)( first + (size_t)SMOKE_CANDIDATES_PER_CHUNK, s_smoke.count );
+ Real *out = s_smoke.packed + first * 5;
+ ParticleSystem **runs = s_smoke.runs + first;
+ UnsignedInt kept = 0;
+ UnsignedInt noted = 0;
+ ParticleSystem *last = NULL;
+ for (size_t i = first; i < end; ++i)
+ {
+ const W3DParticleSystemManager::SunMapCaster &candidate = s_smoke.candidates[ i ];
+ if (!inSunBox( candidate ))
+ continue;
+ memcpy( out + kept * 5, &candidate.x, 5 * sizeof(Real) );
+ ++kept;
+ if (candidate.system != last)
+ {
+ last = candidate.system;
+ runs[ noted++ ] = last;
+ }
+ }
+ s_smoke.kept[ chunk ] = kept;
+ s_smoke.noted[ chunk ] = noted;
+}
+
+/** The smoke into the sun's light: every alpha-blended billboard particle as a soft ball, its optical
+ depth the one its own alpha implies (particleSunMapOpticalDepth), handed to the backend's smoke
+ map. The systems are read as the last client update left them, because the pass runs before
+ the frame's particles are drawn. Fire is additive and casts nothing; a ground-aligned system is
+ a decal already. Only what stands in the sun's box counts, and past the map's limit the
+ particles nearest the camera's focus win, so a new fire on screen is never starved by old smoke
+ at the edge. Every system with a particle in the map is marked, and those lose their blob;
+ with the option off, or the map refused, none is. The chunks culled beside the casters' poses;
+ here they close up in list order, which is the order one walk wrote, and go to the device. */
+static void endSmokeMap( const Vector3 &focus )
{
static std::vector<SmokeCaster> found; // kept: a burning base is thousands of particles every frame
- static std::vector<Real> packed;
static Bool reported = FALSE;
static UnsignedInt nextReportFrame = 0;
const size_t mostCasters = 16384; // the backend's own SMOKE_MOST_CASTERS
- forgetSmokeInSunMap();
- found.clear();
- packed.clear();
+ // a chunk's output never sits before where it closes up to, so both moves only go down
+ size_t inBox = 0;
+ size_t runCount = 0;
+ ParticleSystem *last = NULL;
+ for (Int chunk = 0; chunk < s_smoke.chunks; ++chunk)
+ {
+ const size_t first = (size_t)chunk * SMOKE_CANDIDATES_PER_CHUNK;
+ const UnsignedInt kept = s_smoke.kept[ chunk ];
+ if (kept != 0 && first != inBox)
+ memmove( s_smoke.packed + inBox * 5, s_smoke.packed + first * 5, kept * 5 * sizeof(Real) );
+ inBox += kept;
+ for (UnsignedInt r = 0; r < s_smoke.noted[ chunk ]; ++r)
+ {
+ ParticleSystem *system = s_smoke.runs[ first + r ];
+ if (system != last)
+ {
+ last = system;
+ s_smoke.runs[ runCount++ ] = system;
+ }
+ }
+ }
+ size_t casters = inBox;
- if (TheGlobalData->m_volumetricSmokeShadows && TheParticleSystemManager != NULL)
+ // past the limit the particles nearest the camera's focus win, picked as they always were
+ if (inBox > mostCasters)
{
- // The particles are walked once a particle update (getSunMapCasters); a pass drawn in between,
- // half of them late in a match and most of them early, only culls that list to its own sun.
- const std::vector<W3DParticleSystemManager::SunMapCaster> &candidates =
- ((W3DParticleSystemManager *)TheParticleSystemManager)->getSunMapCasters();
- for (size_t i = 0; i < candidates.size(); ++i)
+ found.clear();
+ for (size_t i = 0; i < s_smoke.count; ++i)
{
- const W3DParticleSystemManager::SunMapCaster &candidate = candidates[ i ];
- const Real radius = candidate.radius;
-
- // the box the depth map covers, in the sun's own frame: it looks down its -Z
- Vector3 inSun;
- Matrix3D::Inverse_Transform_Vector( sunTransform, Vector3( candidate.x, candidate.y, candidate.z ), &inSun );
- const Real reach = halfWidth + radius;
- if (inSun.X < -reach || inSun.X > reach || inSun.Y < -reach || inSun.Y > reach
- || -inSun.Z < SHADOW_MAP_NEAR_CLIP - radius || -inSun.Z > farClip + radius)
+ const W3DParticleSystemManager::SunMapCaster &candidate = s_smoke.candidates[ i ];
+ if (!inSunBox( candidate ))
continue;
-
SmokeCaster caster;
caster.x = candidate.x;
caster.y = candidate.y;
caster.z = candidate.z;
- caster.radius = radius;
+ caster.radius = candidate.radius;
caster.opticalDepth = candidate.opticalDepth;
const Real dx = candidate.x - focus.X;
const Real dy = candidate.y - focus.Y;
@@ -3968,37 +4075,34 @@ static void fillSmokeMap( const Matrix3D &sunTransform, const Vector3 &focus, Re
caster.system = candidate.system;
found.push_back( caster );
}
- }
-
- const size_t inBox = found.size();
- if (found.size() > mostCasters)
- {
std::nth_element( found.begin(), found.begin() + mostCasters, found.end() );
found.resize( mostCasters );
+ casters = mostCasters;
+ runCount = 0;
+ last = NULL;
+ for (size_t i = 0; i < casters; ++i)
+ {
+ memcpy( s_smoke.packed + i * 5, &found[ i ].x, 5 * sizeof(Real) );
+ if (found[ i ].system != last)
+ {
+ last = found[ i ].system;
+ s_smoke.runs[ runCount++ ] = last;
+ }
+ }
}
- packed.reserve( found.size() * 5 );
- for (size_t i = 0; i < found.size(); ++i)
- {
- packed.push_back( found[ i ].x );
- packed.push_back( found[ i ].y );
- packed.push_back( found[ i ].z );
- packed.push_back( found[ i ].radius );
- packed.push_back( found[ i ].opticalDepth );
- }
-
- const Bool held = SunShadow::FillSmoke(DX8Wrapper::_Get_D3D_Device(), packed.empty() ? NULL : &packed[ 0 ],
- (unsigned)found.size(), SMOKE_SHADOW_STRENGTH );
+ const Bool held = SunShadow::FillSmoke(DX8Wrapper::_Get_D3D_Device(), casters ? s_smoke.packed : NULL,
+ (unsigned)casters, SMOKE_SHADOW_STRENGTH );
if (!held)
return;
Int systemsHeld = 0;
- for (size_t i = 0; i < found.size(); ++i)
+ for (size_t i = 0; i < runCount; ++i)
{
- if (!found[ i ].system->isInSunMap())
+ ParticleSystem *system = s_smoke.runs[ i ];
+ if (!system->isInSunMap())
{
- found[ i ].system->setInSunMap( TRUE );
- s_systemsInSunMap.push_back( found[ i ].system->getSystemID() );
+ system->setInSunMap( TRUE );
++systemsHeld;
}
}
@@ -4006,13 +4110,13 @@ static void fillSmokeMap( const Matrix3D &sunTransform, const Vector3 &focus, Re
// A run's log says whether the smoke was in the map at all: the first frame it held any, and
// every ten seconds while it does.
const UnsignedInt frame = TheGameLogic ? TheGameLogic->getFrame() : 0;
- if (!found.empty() && (!reported || frame >= nextReportFrame))
+ if (casters && (!reported || frame >= nextReportFrame))
{
nextReportFrame = frame + 10 * LOGICFRAMES_PER_SECOND;
reported = TRUE;
DEBUG_LOG(("SMOKEMAP: frame %u, %d casters from %d systems in the sun's map, %d more past its limit;"
" fire light %s\n",
- frame, (Int)found.size(), systemsHeld, (Int)( inBox - found.size() ),
+ frame, (Int)casters, systemsHeld, (Int)( inBox - casters ),
TheGlobalData->m_smokeFireLighting ? "on" : "off"));
}
}
@@ -4092,6 +4196,79 @@ public:
}
};
+/** Every enabled caster in list order, and what the gather decided for each. Kept: five hundred
+ casters every frame in a fight. */
+enum CasterVerdict
+{
+ CASTER_OUT_OF_BOX, ///< not in the sun's box
+ CASTER_OUT_OF_VIEW, ///< in the box, its shadow reaching nothing drawn
+ CASTER_DRAWN,
+ CASTER_ON_MAIN, ///< a part of another model: gathered on the main thread after the fork
+};
+static std::vector<RenderObjClass *> s_casters;
+static std::vector<UnsignedByte> s_casterVerdicts;
+
+/** What goes into the map is what stands in the sun's box, not what the tactical camera can see.
+ Culling by the camera meant a tank just off the left of the screen stopped casting, so its shadow
+ blinked out while the shadow of the tank beside it stayed - and scrolling turned that into a row
+ of shadows flickering along the edge of the frame. That tank is still in the map, because its
+ shadow sweeps onto the screen. What can be left out is a caster whose shadow, followed downwind
+ to the lowest ground and widened by the filter, never meets the frame: no pixel drawn this frame
+ reads a texel it is nearest the sun in, so the map reads the same everywhere it is read. A
+ caster drawn is posed here as well (Render's own first half, the clock and the bones), so the
+ whole of a caster's CPU work is one job item. */
+static UnsignedByte gatherCaster( RenderObjClass *robj, const Matrix3D &sun, Real halfWidth,
+ const SunShadowCasterCull &casterCull )
+{
+ SphereClass bound = robj->Get_Bounding_Sphere();
+ const Bool posed = W3DModelDraw::getPosedBoundingSphere( robj, bound ); // see casterSphere
+ Vector3 inSun;
+ Matrix3D::Inverse_Transform_Vector( sun, posed ? bound.Center : robj->Get_Position(), &inSun );
+ const Real reach = halfWidth + bound.Radius;
+ if (inSun.X < -reach || inSun.X > reach || inSun.Y < -reach || inSun.Y > reach)
+ return CASTER_OUT_OF_BOX;
+ if (!casterCull.Visible(bound))
+ {
+ CasterAnimationClock::advance(robj);
+ return CASTER_OUT_OF_VIEW;
+ }
+ if (robj->Class_ID() == RenderObjClass::CLASSID_HLOD)
+ ((HLodClass *)robj)->Pose_For_Render();
+ return CASTER_DRAWN;
+}
+
+/** One fork for the pass's CPU work, so the main thread works through it with the pool instead of
+ waiting on it: the smoke cull's chunks first, the heaviest items, then one caster an item, so
+ no thread is left holding a long group at the end. A caster's gather reads it, its HTree and
+ the shared animation data, and writes only the caster and its sub-objects: the motion channels'
+ shared caches are safe across threads and decode the same values from any cache state
+ (motchan.cpp), the combo motions are peeked rather than counted, and an embedded animation sound
+ never plays because nothing hands AnimatedSoundMgrClass a sound library, so Trigger_Sound
+ returns its frame untouched. A part of another model is left to the main thread, since its
+ transform reaches up into a container a second caster may share. Each verdict goes to the
+ caster's own slot, and Render then draws in list order as before, the pose current. */
+struct ShadowPassJob
+{
+ Int smokeChunks;
+ const Matrix3D *sun;
+ Real halfWidth;
+ const SunShadowCasterCull *casterCull;
+};
+
+static void shadowPassItem( Int index, void *context )
+{
+ const ShadowPassJob &job = *(const ShadowPassJob *)context;
+ if (index < job.smokeChunks)
+ {
+ cullSmokeChunk( index );
+ return;
+ }
+ const Int c = index - job.smokeChunks;
+ RenderObjClass *robj = s_casters[ c ];
+ s_casterVerdicts[ c ] = robj->Get_Container() != NULL ? (UnsignedByte)CASTER_ON_MAIN
+ : gatherCaster( robj, *job.sun, job.halfWidth, *job.casterCull );
+}
+
/** Where an edge of the view crosses the level z, held to the stretch between its near and far
planes. */
static Vector3 viewEdgeAtHeight( const Vector3 &nearPoint, const Vector3 &farPoint, Real z )
@@ -4326,6 +4503,17 @@ void W3DVolumetricShadowManager::renderShadowMap( CameraClass &sceneCamera )
// MeshClass::Render leaves the light pieces (beams, glows) out under this hint.
sunInfo.Push_Override_Flags( RenderInfoClass::RINFO_OVERRIDE_SHADOW_RENDERING );
MeshClass::Shadow_Pass_Light_Meshes = 0;
+ /* On Direct3D 11 the opaque casters (rigid, alpha tested and skins, the last skinned on the GPU)
+ skip the texture categories and go into instanced depth-only draws, one a piece of a model
+ (DX8MeshRendererClass::Flush_Shadow_Casters). The SDL device has no such draw, and
+ -shadowmapoldcasters keeps the old way for an A/B. */
+#if defined(__linux__)
+ MeshClass::Shadow_Lean_Casters = false;
+#else
+ MeshClass::Shadow_Lean_Casters = Direct3D11_Shadow_Map_Bound() && !TheGlobalData->m_shadowMapOldCasters;
+#endif
+ DX8MeshRendererClass::Reset_Shadow_Caster_Counts();
+ const unsigned shadowOldDrawsBefore = DX8Wrapper::Get_Draw_Calls();
#ifndef DEBUG_LOGGING
Int castersCounted = 0;
#endif
@@ -4359,34 +4547,46 @@ void W3DVolumetricShadowManager::renderShadowMap( CameraClass &sceneCamera )
#else
W3DVolumetricShadow *firstCaster = m_shadowList;
#endif
+ beginSmokeMap( transform, halfWidth, farClip );
+ /* A tick running beside the render (-logicthread 1 and 2) can reach a live model through
+ getDrawModulesFlushed and set its state or read its bones, so it waits here from the casters'
+ gathering to the end of their poses (LogicThread::g_liveModelLock). */
+ std::unique_lock<std::recursive_mutex> liveModels( LogicThread::g_liveModelLock );
+ s_casters.clear();
for (W3DVolumetricShadow *shadow = firstCaster; shadow; shadow = shadow->m_next)
{
RenderObjClass *robj = shadow->getRenderObject();
- if (robj == NULL || !shadow->isRenderEnabled() || shadow->isInvisibleEnabled())
- continue;
+ if (robj != NULL && shadow->isRenderEnabled() && !shadow->isInvisibleEnabled())
+ s_casters.push_back( robj );
+ }
+ s_casterVerdicts.resize( s_casters.size() );
- /* What goes into the map is what stands in the sun's box, not what the tactical camera can
- see. Culling by the camera meant a tank just off the left of the screen stopped casting,
- so its shadow blinked out while the shadow of the tank beside it stayed - and scrolling
- turned that into a row of shadows flickering along the edge of the frame. */
- SphereClass bound = robj->Get_Bounding_Sphere();
- const Bool posed = W3DModelDraw::getPosedBoundingSphere( robj, bound ); // see casterSphere
- Vector3 inSun;
- Matrix3D::Inverse_Transform_Vector( transform, posed ? bound.Center : robj->Get_Position(), &inSun );
- const Real reach = halfWidth + bound.Radius;
- if (inSun.X < -reach || inSun.X > reach || inSun.Y < -reach || inSun.Y > reach)
- continue;
+ {
+ ShadowPassJob job;
+ job.smokeChunks = s_smoke.chunks;
+ job.sun = &transform;
+ job.halfWidth = halfWidth;
+ job.casterCull = &casterCull;
+ const Int items = job.smokeChunks + (Int)s_casters.size();
+ if (items > 0)
+ JobSystem::parallel_for( items, 1, shadowPassItem, &job );
+ }
- /* That tank is still in the map, because its shadow sweeps onto the screen. What can be left
- out is a caster whose shadow, followed downwind to the lowest ground and widened by the
- filter, never meets the frame: no pixel drawn this frame reads a texel it is nearest the
- sun in, so the map reads the same everywhere it is read. */
- if (!casterCull.Visible(bound))
- {
- CasterAnimationClock::advance(robj);
+ // the parts of other models, their containers posed by now
+ for (size_t c = 0; c < s_casters.size(); ++c)
+ {
+ if (s_casterVerdicts[ c ] == CASTER_ON_MAIN)
+ s_casterVerdicts[ c ] = gatherCaster( s_casters[ c ], transform, halfWidth, casterCull );
+ if (s_casterVerdicts[ c ] == CASTER_OUT_OF_VIEW)
++castersOutOfView;
+ }
+ liveModels.unlock();
+
+ for (size_t c = 0; c < s_casters.size(); ++c)
+ {
+ if (s_casterVerdicts[ c ] != CASTER_DRAWN)
continue;
- }
+ RenderObjClass *robj = s_casters[ c ];
/* An own stealthed unit casts only a share of its shadow, breathing with its fade, the way
the cloak lets the ground show through its body (effect_cloak_shadow in ffshader.h). A
@@ -4414,6 +4614,10 @@ void W3DVolumetricShadowManager::renderShadowMap( CameraClass &sceneCamera )
// and changing that preference does not remove trees from an already loaded map.
if (geometryShadows)
castersCounted += TheTerrainRenderObject->renderTreeShadowCasters(sunInfo, &sceneCamera, casterCull);
+ // Off before anything below renders a mesh: the sort lists' meshes come through Render again,
+ // after the instanced casters have gone.
+ TheDX8MeshRenderer.Flush_Shadow_Casters();
+ MeshClass::Shadow_Lean_Casters = false;
TheDX8MeshRenderer.Flush();
/* A mesh the material system calls translucent goes to the sort lists rather than to the mesh
renderer, and a helicopter's rotor disc is one of them: without this the map holds the
@@ -4458,16 +4662,17 @@ void W3DVolumetricShadowManager::renderShadowMap( CameraClass &sceneCamera )
// The smoke goes into a map of its own through the sun the casters were just drawn with.
// past the map's limit the smoke nearest the camera wins: the freecam's box is centred on the
// map's middle, which is not where it is looking from
+ // The cull ran beside the casters' poses (beginSmokeMap, cullSmokeChunk).
#if defined(__linux__)
if (captured)
- fillSmokeMap( transform, wholeMap ? sceneCamera.Get_Position() : focus, halfWidth, farClip );
+ endSmokeMap( wholeMap ? sceneCamera.Get_Position() : focus );
else {
SunShadow::FillSmoke(DX8Wrapper::_Get_D3D_Device(), NULL, 0, 0.0f );
forgetSmokeInSunMap();
}
#else
// Direct3D 11 fills the smoke map whether or not the depth capture bound, as it always has.
- fillSmokeMap( transform, wholeMap ? sceneCamera.Get_Position() : focus, halfWidth, farClip );
+ endSmokeMap( wholeMap ? sceneCamera.Get_Position() : focus );
#endif
// The frame's own camera, put back: the view, the projection and the viewport all went with the
@@ -4541,7 +4746,8 @@ void W3DVolumetricShadowManager::renderShadowMap( CameraClass &sceneCamera )
if( freq > 0 )
TheShadowMapMS += (Real)((double)(tShadowEnd - tShadowStart) * 1000.0 / (double)freq);
TheShadowMapCasters += castersCounted;
- TheShadowMapDraws += DX8Wrapper::Get_Draw_Calls() - shadowDrawsBefore;
+ // the instanced casters' draws went past the wrapper's count
+ TheShadowMapDraws += DX8Wrapper::Get_Draw_Calls() - shadowDrawsBefore + DX8MeshRendererClass::Shadow_Lean_Draws;
}
#endif
@@ -4562,8 +4768,24 @@ void W3DVolumetricShadowManager::renderShadowMap( CameraClass &sceneCamera )
if (frame >= nextReportFrame)
{
nextReportFrame = frame + LOGICFRAMES_PER_SECOND;
- DEBUG_LOG(("SHADOWMAP: %d casters, %d left out as reaching nothing in view, %d light meshes left out, %s\n",
+ // The meshes the lean path left to the old one, by the first reason each failed on.
+ AsciiString oldMeshes;
+ for (Int reason = 0; reason < DX8MeshRendererClass::SHADOW_OLD_REASON_COUNT; ++reason)
+ {
+ if (DX8MeshRendererClass::Shadow_Old_Meshes[reason] != 0)
+ {
+ AsciiString entry;
+ entry.format(" %s %d", DX8MeshRendererClass::Shadow_Old_Reason_Name(reason),
+ DX8MeshRendererClass::Shadow_Old_Meshes[reason]);
+ oldMeshes.concat(entry);
+ }
+ }
+ DEBUG_LOG(("SHADOWMAP: %d casters, %d left out as reaching nothing in view, %d light meshes left out, lean %d draws %d instances (%d alpha tested, %d skinned), old %u draws, old meshes:%s, %s\n",
castersCounted, castersOutOfView, MeshClass::Shadow_Pass_Light_Meshes,
+ DX8MeshRendererClass::Shadow_Lean_Draws, DX8MeshRendererClass::Shadow_Lean_Instances,
+ DX8MeshRendererClass::Shadow_Lean_Alpha_Tested, DX8MeshRendererClass::Shadow_Lean_Skinned,
+ DX8Wrapper::Get_Draw_Calls() - shadowOldDrawsBefore,
+ oldMeshes.isEmpty() ? " none" : oldMeshes.str(),
SunShadow::Report(DX8Wrapper::_Get_D3D_Device()).c_str()));
}
}
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTreeBuffer.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTreeBuffer.cpp
index 6168834f8..5ea95f69b 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTreeBuffer.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTreeBuffer.cpp
@@ -398,6 +398,29 @@ void W3DTreeBuffer::cull(const CameraClass * camera, const CameraClass *sunCamer
shadow can reach the view is in the batch too. It lies flat at the tree's base. */
Real stretchX, stretchY;
const Bool castsSilhouette = treeSilhouetteShadows(m_dwTreeVertexShader) && treeShadowStretch(stretchX, stretchY);
+ /* The sun pass culls every frame, and with the camera still the answer is the same flags, the same
+ keys and the same count as last time: every input is in the key, and every change to a tree's
+ bounds or type comes through m_anythingChanged or a new tree, which drop it. */
+ if (sunCamera) {
+ static_assert(sizeof(PlaneClass) == 4*sizeof(Real), "the key copies the frustum planes as floats");
+ Real key[SUN_CULL_KEY];
+ memcpy(key, camera->Get_Frustum_Planes(), 6*sizeof(PlaneClass));
+ memcpy(key+24, sunCamera->Get_Frustum_Planes(), 6*sizeof(PlaneClass));
+ key[48] = castsSilhouette ? 1.0f : 0.0f;
+ key[49] = castsSilhouette ? stretchX : 0.0f;
+ key[50] = castsSilhouette ? stretchY : 0.0f;
+ key[51] = TheGlobalData->m_shadowsForProps ? 1.0f : 0.0f;
+ if (m_sunCullValid && m_sunCullTrees == m_numTrees && memcmp(key, m_sunCullKey, sizeof(key)) == 0) {
+ m_updateAllKeys = false;
+ return;
+ }
+ memcpy(m_sunCullKey, key, sizeof(key));
+ m_sunCullTrees = m_numTrees;
+ m_sunCullValid = TRUE;
+ } else {
+ m_sunCullValid = FALSE;
+ }
+ m_movedSinceCull = FALSE;
/* The sun's box holds trees the screen does not, and they go into the same buffers the screen
draws from. The fill takes trees in index order and stops at MAX_BUFFERS, so a box over dense
woodland (the freecam's is the whole map) would push trees in plain view out. The screen's own
@@ -852,6 +875,15 @@ void W3DTreeBuffer::loadTreesInVertexAndIndexBuffers(RefRenderObjListIterator *p
Int curTree=0;
Int bNdx;
for (bNdx=0; bNdx<MAX_BUFFERS; ++bNdx) m_shadowRanges[bNdx].clear();
+ // A slot is only a tree's while this fill gives it one: updateVertexBuffer writes a moved tree
+ // into its slot alone, and a slot left over from an older fill now holds some other tree.
+ // The fill writes every tree it takes in as it stands, so nothing moved is left to write.
+ for (curTree=0; curTree<m_numTrees; curTree++) {
+ m_trees[curTree].bufferNdx = -1;
+ m_trees[curTree].moved = false;
+ }
+ m_movedTrees.clear();
+ curTree = 0;
const GlobalData::TerrainLighting *objectLighting = TheGlobalData->m_terrainObjectsLighting[TheGlobalData->m_timeOfDay];
for (bNdx=0; bNdx<MAX_BUFFERS; bNdx++) {
m_curNumTreeVertices[bNdx] = 0;
@@ -930,8 +962,6 @@ void W3DTreeBuffer::loadTreesInVertexAndIndexBuffers(RefRenderObjListIterator *p
Int startVertex = m_curNumTreeVertices[bNdx];
- m_trees[curTree].firstIndex = startVertex;
- m_trees[curTree].bufferNdx = bNdx;
Int i;
Int numVertex = m_treeTypes[type].m_mesh->Peek_Model()->Get_Vertex_Count();
Vector3 *pVert = m_treeTypes[type].m_mesh->Peek_Model()->Get_Vertex_Array();
@@ -951,6 +981,8 @@ void W3DTreeBuffer::loadTreesInVertexAndIndexBuffers(RefRenderObjListIterator *p
bNdx, m_curNumTreeIndices[bNdx], curTree, m_numTrees));
break;
}
+ m_trees[curTree].firstIndex = startVertex;
+ m_trees[curTree].bufferNdx = bNdx;
const Vector2*uvs=m_treeTypes[type].m_mesh->Peek_Model()->Get_UV_Array_By_Index(0);
@@ -1138,85 +1170,84 @@ void W3DTreeBuffer::loadTreesInVertexAndIndexBuffers(RefRenderObjListIterator *p
//=============================================================================
// W3DTreeBuffer::updateVertexBuffer
//=============================================================================
-/** Updates the push aside offset in vertex buffer. */
+/** Writes the trees stepTrees moved into their own slots and nothing else. It used to lock each
+whole buffer, and on Direct3D 11 a static buffer's unlock copies and uploads every byte it locked:
+about a megabyte a buffer, four buffers, for one bush a soldier walked through, and in a crowd that
+was most passes. stepTrees lists the trees it moved; each buffer takes one lock over the span its
+moved trees cover, so a move is written once, by whichever pass comes first. */
//=============================================================================
void W3DTreeBuffer::updateVertexBuffer(void)
{
if (!m_indexTree[0] || !m_vertexTree[0] || !m_initialized) {
return;
}
+ Int lo[MAX_BUFFERS], hi[MAX_BUFFERS];
Int bNdx;
- for (bNdx = 0; bNdx<MAX_BUFFERS; bNdx++) {
- if (m_curNumTreeIndices[bNdx]==0) {
- break;
+ for (bNdx=0; bNdx<MAX_BUFFERS; bNdx++) {
+ lo[bNdx] = MAX_TREE_VERTEX;
+ hi[bNdx] = 0;
+ }
+ Int kept = 0;
+ Int n;
+ for (n=0; n<(Int)m_movedTrees.size(); n++) {
+ TTree &tree = m_trees[m_movedTrees[n]];
+ // Deleted, culled out or left out of the fill: the fill that next takes it in writes it as it
+ // stands then.
+ if (tree.treeType<0 || !tree.visible || tree.bufferNdx<0) {
+ tree.moved = false;
+ continue;
}
- VertexFormatXYZNDUV1 *vb;
- // Lock the buffers.
- #ifdef USE_STATIC
- DX8VertexBufferClass::WriteLockClass lockVtxBuffer(m_vertexTree[bNdx], 0);
- #else
- DX8VertexBufferClass::WriteLockClass lockVtxBuffer(m_vertexTree[bNdx], D3DLOCK_DISCARD);
- #endif
- vb=(VertexFormatXYZNDUV1*)lockVtxBuffer.Get_Vertex_Array();
+ const Int end = tree.firstIndex + m_treeTypes[tree.treeType].m_mesh->Peek_Model()->Get_Vertex_Count();
+ if (tree.firstIndex < lo[tree.bufferNdx]) lo[tree.bufferNdx] = tree.firstIndex;
+ if (end > hi[tree.bufferNdx]) hi[tree.bufferNdx] = end;
+ m_movedTrees[kept++] = m_movedTrees[n];
+ }
+ m_movedTrees.resize(kept);
- //
- // The lock fails when the device has gone out from under us, and everything below writes
- // through this pointer without looking. Same shape as the tank tracks flush: give up on
- // this buffer, the next frame will push the trees aside again.
- //
+ for (bNdx=0; bNdx<MAX_BUFFERS; bNdx++) {
+ if (hi[bNdx] <= lo[bNdx]) {
+ continue;
+ }
+ DX8VertexBufferClass::AppendLockClass lockVtxBuffer(m_vertexTree[bNdx], lo[bNdx], hi[bNdx]-lo[bNdx]);
+ VertexFormatXYZNDUV1 *vb = (VertexFormatXYZNDUV1*)lockVtxBuffer.Get_Vertex_Array();
+ // The lock fails when the device has gone out from under us: its trees wait for the next pass.
if (vb == NULL) {
+ m_anyPushChanged = true;
continue;
}
-
- VertexFormatXYZNDUV1 *curVb;
-
- Int curTree;
- for (curTree=0; curTree<m_numTrees; curTree++) {
- if (m_trees[curTree].bufferNdx!=bNdx) {
+ for (n=0; n<(Int)m_movedTrees.size(); n++) {
+ TTree &tree = m_trees[m_movedTrees[n]];
+ if (tree.bufferNdx != bNdx) {
continue;
}
- Int type = m_trees[curTree].treeType;
- if (type<0) {
- continue; // Deleted tree. [6/9/2003]
- }
- if (m_trees[curTree].pushAsideDelta==0.0f && m_trees[curTree].m_toppleState == TOPPLE_UPRIGHT) {
- continue; // not toppling or pushed, no need to update. jba [7/11/2003]
- }
- m_anyPushChanged = true;
- if (!m_trees[curTree].visible) continue;
- Real scale = m_trees[curTree].scale;
- Vector3 loc = m_trees[curTree].location;
- Real theSin = m_trees[curTree].sin;
- Real theCos = m_trees[curTree].cos;
- if (type<0 || m_treeTypes[type].m_mesh == 0) {
- type = 0;
- }
-
- Int startVertex = m_trees[curTree].firstIndex;
- curVb = vb+startVertex;
- Int i;
- Int numVertex = m_treeTypes[type].m_mesh->Peek_Model()->Get_Vertex_Count();
- Vector3 *pVert = m_treeTypes[type].m_mesh->Peek_Model()->Get_Vertex_Array();
-
- for (i=0; i<numVertex; i++) {
+ tree.moved = false;
+ const Int type = tree.treeType;
+ const Int numVertex = m_treeTypes[type].m_mesh->Peek_Model()->Get_Vertex_Count();
+ const Vector3 *pVert = m_treeTypes[type].m_mesh->Peek_Model()->Get_Vertex_Array();
+ VertexFormatXYZNDUV1 *curVb = vb + (tree.firstIndex - lo[bNdx]);
+
+ const Real scale = tree.scale;
+ const Vector3 loc = tree.location;
+ const Real theSin = tree.sin;
+ const Real theCos = tree.cos;
+ for (Int i=0; i<numVertex; i++) {
Real x = pVert[i].X;
Real y = pVert[i].Y;
-
Vector3 vLoc;
x += m_treeTypes[type].m_offset.X;
y += m_treeTypes[type].m_offset.Y;
vLoc.X = x*scale*theCos - y*scale*theSin;
vLoc.Y = y*scale*theCos + x*scale*theSin;
- vLoc.Z = pVert[i].Z*scale;
+ vLoc.Z = pVert[i].Z*scale;
vLoc.Z += m_treeTypes[type].m_offset.Z;
- if (m_trees[curTree].m_toppleState != TOPPLE_UPRIGHT) {
- m_trees[curTree].m_mtx.Transform_Vector(m_trees[curTree].m_mtx, vLoc, &vLoc);
+ if (tree.m_toppleState != TOPPLE_UPRIGHT) {
+ tree.m_mtx.Transform_Vector(tree.m_mtx, vLoc, &vLoc);
} else {
- if (m_trees[curTree].pushAside>0.0f) {
- vLoc.X += pVert[i].Z * m_trees[curTree].pushAside * m_trees[curTree].pushAsideCos * m_treeTypes[type].m_data->m_maxOutwardMovement;
- vLoc.Y += pVert[i].Z * m_trees[curTree].pushAside * m_trees[curTree].pushAsideSin* m_treeTypes[type].m_data->m_maxOutwardMovement;
+ if (tree.pushAside>0.0f) {
+ vLoc.X += pVert[i].Z * tree.pushAside * tree.pushAsideCos * m_treeTypes[type].m_data->m_maxOutwardMovement;
+ vLoc.Y += pVert[i].Z * tree.pushAside * tree.pushAsideSin* m_treeTypes[type].m_data->m_maxOutwardMovement;
}
vLoc.X += loc.X;
vLoc.Y += loc.Y;
@@ -1226,11 +1257,20 @@ void W3DTreeBuffer::updateVertexBuffer(void)
curVb->x = vLoc.X;
curVb->y = vLoc.Y;
curVb->z = vLoc.Z;
- curVb->ny = 1.0f - m_treeTypes[type].m_data->m_darkening*m_trees[curTree].pushAside;
+ curVb->ny = 1.0f - m_treeTypes[type].m_data->m_darkening*tree.pushAside;
curVb++;
}
- }
+ }
+ }
+
+ // what a failed lock left stays listed
+ kept = 0;
+ for (n=0; n<(Int)m_movedTrees.size(); n++) {
+ if (m_trees[m_movedTrees[n]].moved) {
+ m_movedTrees[kept++] = m_movedTrees[n];
+ }
}
+ m_movedTrees.resize(kept);
}
//-----------------------------------------------------------------------------
@@ -1460,6 +1500,7 @@ void W3DTreeBuffer::clearAllTrees(void)
m_numShadowTextures = 0;
m_numTrees=0;
+ m_movedTrees.clear();
m_bounds.lo.x = m_bounds.lo.y = 0;
m_bounds.hi.x = m_bounds.hi.y = 1;
REF_PTR_RELEASE(m_treeTexture);
@@ -1666,6 +1707,7 @@ void W3DTreeBuffer::addTree(DrawableID id, Coord3D location, Real scale, Real an
m_trees[m_numTrees].firstIndex = 0;
m_trees[m_numTrees].bufferNdx = -1;
+ m_trees[m_numTrees].moved = false;
//
// swayType is a vertex shader constant index counted from c8, and c8 itself is the all-zero
@@ -2191,11 +2233,17 @@ void W3DTreeBuffer::stepTrees( void )
if (type<0) { // deleted.
continue;
}
+ // A tree whose vertices move this logic frame is marked, and only such a tree: one lying still
+ // on the ground, or held up in the fog, rewrites nothing.
+ Bool moved = false;
if(m_trees[curTree].m_toppleState == TOPPLE_FALLING ||
m_trees[curTree].m_toppleState == TOPPLE_FOGGED) {
+ const W3DToppleState before = m_trees[curTree].m_toppleState;
updateTopplingTree(m_trees+curTree);
+ moved = before != TOPPLE_FOGGED || m_trees[curTree].m_toppleState != TOPPLE_FOGGED;
} else if(m_trees[curTree].m_toppleState == TOPPLE_DOWN) {
if (m_treeTypes[type].m_data->m_killWhenToppled) {
+ moved = true;
if (m_trees[curTree].m_sinkFramesLeft==0) {
m_trees[curTree].treeType = DELETED_TREE_TYPE; // delete it. [7/11/2003]
m_anythingChanged = true; // need to regenerate trees. [7/11/2003]
@@ -2205,6 +2253,7 @@ void W3DTreeBuffer::stepTrees( void )
m_trees[curTree].m_mtx.Set_Translation(m_trees[curTree].location);
}
} else if (m_trees[curTree].pushAsideDelta!=0.0f) {
+ moved = true;
m_trees[curTree].pushAside += m_trees[curTree].pushAsideDelta;
if (m_trees[curTree].pushAside>=1.0f) {
m_trees[curTree].pushAsideDelta = -1.0/(Real)m_treeTypes[type].m_data->m_framesToMoveInward;
@@ -2213,6 +2262,14 @@ void W3DTreeBuffer::stepTrees( void )
m_trees[curTree].pushAside = 0.0f;
}
}
+ if (moved) {
+ if (!m_trees[curTree].moved) {
+ m_trees[curTree].moved = true;
+ m_movedTrees.push_back(curTree);
+ }
+ m_anyPushChanged = true;
+ m_movedSinceCull = true;
+ }
}
}
@@ -2284,6 +2341,12 @@ void W3DTreeBuffer::drawTrees(CameraClass * camera, RefRenderObjListIterator *pD
// culling them against its own frustum left the screen drawing the mirror's trees until the
// next cull, and with the mirror skipping frames the trees flickered between the two sets. The
// mirror draws what the screen culled, which is what stands near the water it lands on.
+ // A tree that came or went since the last cull drops the sun pass's key, whichever pass sees the
+ // change first. A moved one only matters to a cull asked to redo the sort keys: a sinking tree's
+ // key follows its height.
+ if (m_anythingChanged || (m_movedSinceCull && m_updateAllKeys)) {
+ m_sunCullValid = FALSE;
+ }
if (sunCamera || (m_updateAllKeys && !ShaderClass::Is_Backface_Culling_Inverted())) {
cull(camera, sunCamera);
}
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameLogic/W3DGhostObject.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameLogic/W3DGhostObject.cpp
index c87c131d3..c282557f3 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameLogic/W3DGhostObject.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameLogic/W3DGhostObject.cpp
@@ -368,7 +368,9 @@ void W3DGhostObject::snapShot(int playerIndex)
W3DRenderObjectSnapshot *snap=m_parentSnapshots[playerIndex],*prevSnap=NULL;
- //walk through all W3D render objects used by this object
+ //walk through all W3D render objects used by this object; a tick beside the render waits out
+ //the shadow pass's poses first
+ LogicThread::TickReachesLiveModels liveModels;
for (DrawModule ** dm = draw->getDrawModulesFlushed(); *dm; ++dm)
{
const ObjectDrawInterface* di = (*dm)->getObjectDrawInterface();
@@ -444,6 +446,7 @@ void W3DGhostObject::removeParentObject(void)
draw->setFullyObscuredByShroud(true);
//walk through all W3D render objects used by this object
+ LogicThread::TickReachesLiveModels liveModels;
for (DrawModule ** dm = draw->getDrawModulesFlushed(); *dm; ++dm)
{
const ObjectDrawInterface* di = (*dm)->getObjectDrawInterface();
@@ -480,6 +483,7 @@ void W3DGhostObject::restoreParentObject(void)
return;
//walk through all W3D render objects used by this object
+ LogicThread::TickReachesLiveModels liveModels;
for (DrawModule ** dm = draw->getDrawModulesFlushed(); *dm; ++dm)
{
const ObjectDrawInterface* di = (*dm)->getObjectDrawInterface();
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/animobj.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/animobj.cpp
index 8589425c5..0faf64ee4 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/animobj.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/animobj.cpp
@@ -15,6 +15,7 @@
** You should have received a copy of the GNU General Public License
** along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
+// Modified 2025-2026 by Olcay Seygan for Zero Hour Reforged; see the git history.
/***********************************************************************************************
*** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S ***
@@ -286,6 +287,11 @@ void Animatable3DObjClass::Release( void )
* 12/8/98 GTH : Created. *
*=============================================================================================*/
void Animatable3DObjClass::Render(RenderInfoClass & rinfo)
+{
+ Pose_For_Render();
+}
+
+void Animatable3DObjClass::Pose_For_Render(void)
{
if (HTree == NULL) return;
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/animobj.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/animobj.h
index b8bba817f..188410dc5 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/animobj.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/animobj.h
@@ -15,6 +15,7 @@
** You should have received a copy of the GNU General Public License
** along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
+// Modified 2025-2026 by Olcay Seygan for Zero Hour Reforged; see the git history.
/***********************************************************************************************
*** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S ***
@@ -75,6 +76,11 @@ public:
virtual void Render(RenderInfoClass & rinfo);
virtual void Special_Render(SpecialRenderInfoClass & rinfo);
+ // What Render does before anything is drawn: the clock moved on and the bones posed. It touches
+ // only this object and its sub-objects, so the sun's shadow pass runs it for many casters at once
+ // and Render then finds the pose current.
+ void Pose_For_Render(void);
+
/////////////////////////////////////////////////////////////////////////////
// Render Object Interface - "Scene Graph"
/////////////////////////////////////////////////////////////////////////////
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp
index ac93b5c24..4f0c491a2 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp
@@ -31,6 +31,9 @@
#include <stdio.h>
#include <string.h>
#include <windows.h>
+#if defined(_M_X64) || defined(_M_IX86) || defined(__SSE__)
+#include <xmmintrin.h>
+#endif
typedef HRESULT (WINAPI *D3DCompileFunction)(LPCVOID source_data, SIZE_T source_size,
LPCSTR source_name, const D3D_SHADER_MACRO * defines, ID3DInclude * include,
@@ -332,6 +335,19 @@ DX11BackendClass::DX11BackendClass()
SmokeMapRefused = false;
SmokeMapFilled = false;
SmokeStrength = 0.0f;
+ memset(ShadowCasterVertexShaders, 0, sizeof(ShadowCasterVertexShaders));
+ memset(ShadowCasterLayouts, 0, sizeof(ShadowCasterLayouts));
+ ShadowCasterAlphaTest = NULL;
+ ShadowCasterInstances = NULL;
+ ShadowCasterCapacity = 0;
+ ShadowCasterBones = NULL;
+ ShadowCasterBonesView = NULL;
+ ShadowCasterBonesCapacity = 0;
+ ShadowCasterRefused = false;
+ ShadowSkinSource = NULL;
+ ShadowSkinCapacity = 0;
+ ShadowSkinUsed = 0;
+ ShadowSkinGeneration = 1;
memset(Headlights, 0, sizeof(Headlights));
HeadlightCount = 0;
memset(HeadlightGain, 0, sizeof(HeadlightGain));
@@ -585,6 +601,7 @@ void DX11BackendClass::Shutdown()
ShadowMapSize = 0;
ShadowMapBound = false;
Release_Smoke_Map();
+ Release_Shadow_Casters();
Release_Scene_Depth();
Release_Scene_Colour();
RenderStates.Set_Shadow_Caster_Pass(false);
@@ -1036,6 +1053,482 @@ bool DX11BackendClass::Fill_Smoke_Map(const float * casters, unsigned count, flo
return true;
}
+// A caster's depth and nothing else. The position goes through the instance's product of world,
+// view and projection the way the generated vertex programs take it through theirs
+// (ffvertex.cpp: mul of the model position by a row major matrix), so the same vertex lands on the
+// same depth. No pixel program for an opaque caster: the pass writes no colour, and it discards
+// nothing.
+#define SHADOW_CASTER_INSTANCE_INPUT \
+ " float4 Row0 : WORLDVIEWPROJECTION0;\n" \
+ " float4 Row1 : WORLDVIEWPROJECTION1;\n" \
+ " float4 Row2 : WORLDVIEWPROJECTION2;\n" \
+ " float4 Row3 : WORLDVIEWPROJECTION3;\n"
+#define SHADOW_CASTER_PROJECT(position) \
+ " float4x4 world_view_projection = float4x4(caster.Row0, caster.Row1, caster.Row2, caster.Row3);\n" \
+ " return mul(float4(" position ", 1.0), world_view_projection);\n"
+
+static const char SHADOW_CASTER_VERTEX_PROGRAM[] =
+ "struct Caster\n"
+ "{\n"
+ " float3 Position : POSITION;\n"
+ SHADOW_CASTER_INSTANCE_INPUT
+ "};\n"
+ "float4 main(Caster caster) : SV_Position\n"
+ "{\n"
+ SHADOW_CASTER_PROJECT("caster.Position")
+ "}\n";
+
+// An alpha tested caster carries stage 0's coordinates to the pixel program, untransformed, as the
+// generated programs pass them for a stage without a mapper.
+static const char SHADOW_CASTER_ALPHA_VERTEX_PROGRAM[] =
+ "struct Caster\n"
+ "{\n"
+ " float3 Position : POSITION;\n"
+ " float2 TexCoord : TEXCOORD;\n"
+ SHADOW_CASTER_INSTANCE_INPUT
+ "};\n"
+ "struct Output\n"
+ "{\n"
+ " float4 Position : SV_Position;\n"
+ " float2 TexCoord : TEXCOORD0;\n"
+ "};\n"
+ "Output main(Caster caster)\n"
+ "{\n"
+ " Output output;\n"
+ " float4x4 world_view_projection = float4x4(caster.Row0, caster.Row1, caster.Row2, caster.Row3);\n"
+ " output.Position = mul(float4(caster.Position, 1.0), world_view_projection);\n"
+ " output.TexCoord = caster.TexCoord;\n"
+ " return output;\n"
+ "}\n";
+
+// A skin's vertex through its bone the way MeshGeometryClass::get_deformed_vertices takes it
+// (Matrix3D::Transform_Vector: each row's dot with the position plus its translation), then through
+// view and projection with the identity world the texture category's walk gives a skin. The
+// bones are three rows each, the pass's skins one after another.
+static const char SHADOW_CASTER_SKIN_VERTEX_PROGRAM[] =
+ "Buffer<float4> Bones : register(t0);\n"
+ "struct Caster\n"
+ "{\n"
+ " float3 Position : POSITION;\n"
+ " uint Bone : BONE;\n"
+ SHADOW_CASTER_INSTANCE_INPUT
+ " uint FirstBone : FIRSTBONE;\n"
+ "};\n"
+ "float4 main(Caster caster) : SV_Position\n"
+ "{\n"
+ " uint row = (caster.FirstBone + caster.Bone) * 3;\n"
+ " float4 x = Bones[row];\n"
+ " float4 y = Bones[row + 1];\n"
+ " float4 z = Bones[row + 2];\n"
+ " float3 p = caster.Position;\n"
+ " float3 skinned = float3(x.x * p.x + x.y * p.y + x.z * p.z + x.w,\n"
+ " y.x * p.x + y.y * p.y + y.z * p.z + y.w,\n"
+ " z.x * p.x + z.y * p.y + z.z * p.z + z.w);\n"
+ SHADOW_CASTER_PROJECT("skinned")
+ "}\n";
+
+// ShaderClass::Apply's test for an opaque material (reference 0x60, greater or equal) on stage 0's
+// alpha, rounded to a level first as ffshader.cpp's ALPHA_LEVEL does. The material's diffuse
+// alpha that stage 0 multiplies by is one for every caster taken (Add_Shadow_Caster).
+static const char SHADOW_CASTER_ALPHA_PIXEL_PROGRAM[] =
+ "Texture2D Texture0 : register(t0);\n"
+ "SamplerState Sampler0 : register(s0);\n"
+ "struct Input\n"
+ "{\n"
+ " float4 Position : SV_Position;\n"
+ " float2 TexCoord : TEXCOORD0;\n"
+ "};\n"
+ "void main(Input input)\n"
+ "{\n"
+ " float alpha_level = floor(Texture0.Sample(Sampler0, input.TexCoord).a * 255.0 + 0.5);\n"
+ " clip(alpha_level - 96.0);\n"
+ "}\n";
+
+#undef SHADOW_CASTER_INSTANCE_INPUT
+#undef SHADOW_CASTER_PROJECT
+
+static const unsigned SHADOW_CASTER_MATRIX_FLOATS = 16;
+// The matrix, the first bone and three floats of padding.
+static const unsigned SHADOW_CASTER_INSTANCE_FLOATS = 20;
+static const unsigned SHADOW_CASTER_FIRST_BONE_BYTES = SHADOW_CASTER_MATRIX_FLOATS * sizeof(float);
+static const unsigned SHADOW_CASTER_ROWS_A_BONE = 3;
+static const unsigned SHADOW_CASTER_FIRST_INSTANCES = 1024;
+static const unsigned SHADOW_CASTER_FIRST_BONE_ROWS = 4096;
+static const unsigned SHADOW_SKIN_FIRST_VERTICES = 65536;
+
+void DX11BackendClass::Release_Shadow_Casters()
+{
+ IUnknown ** const held[] = {
+ (IUnknown **)&ShadowCasterVertexShaders[0], (IUnknown **)&ShadowCasterVertexShaders[1],
+ (IUnknown **)&ShadowCasterVertexShaders[2], (IUnknown **)&ShadowCasterLayouts[0],
+ (IUnknown **)&ShadowCasterLayouts[1], (IUnknown **)&ShadowCasterLayouts[2],
+ (IUnknown **)&ShadowCasterAlphaTest, (IUnknown **)&ShadowCasterInstances,
+ (IUnknown **)&ShadowCasterBonesView, (IUnknown **)&ShadowCasterBones,
+ (IUnknown **)&ShadowSkinSource,
+ };
+ for (unsigned index = 0; index < sizeof(held) / sizeof(held[0]); ++index) {
+ if (*held[index] != NULL) {
+ (*held[index])->Release();
+ *held[index] = NULL;
+ }
+ }
+ ShadowCasterCapacity = 0;
+ ShadowCasterBonesCapacity = 0;
+ ShadowCasterRefused = false;
+ ShadowSkinCapacity = 0;
+ ShadowSkinUsed = 0;
+ ++ShadowSkinGeneration;
+}
+
+bool DX11BackendClass::Make_Shadow_Caster_Program()
+{
+ if (ShadowCasterAlphaTest != NULL) {
+ return true;
+ }
+ if (ShadowCasterRefused) {
+ return false;
+ }
+ const D3D11_INPUT_ELEMENT_DESC rigid[] = {
+ { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
+ { "WORLDVIEWPROJECTION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 0, D3D11_INPUT_PER_INSTANCE_DATA, 1 },
+ { "WORLDVIEWPROJECTION", 1, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 16, D3D11_INPUT_PER_INSTANCE_DATA, 1 },
+ { "WORLDVIEWPROJECTION", 2, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 32, D3D11_INPUT_PER_INSTANCE_DATA, 1 },
+ { "WORLDVIEWPROJECTION", 3, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 48, D3D11_INPUT_PER_INSTANCE_DATA, 1 },
+ };
+ // The coordinates come from the vertex buffer bound a second time at slot 2, its offset moved on
+ // to the stage's set, so one layout serves every vertex format.
+ const D3D11_INPUT_ELEMENT_DESC alpha_tested[] = {
+ rigid[0], rigid[1], rigid[2], rigid[3], rigid[4],
+ { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 2, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
+ };
+ const D3D11_INPUT_ELEMENT_DESC skinned[] = {
+ rigid[0], rigid[1], rigid[2], rigid[3], rigid[4],
+ { "BONE", 0, DXGI_FORMAT_R32_UINT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
+ { "FIRSTBONE", 0, DXGI_FORMAT_R32_UINT, 1, SHADOW_CASTER_FIRST_BONE_BYTES, D3D11_INPUT_PER_INSTANCE_DATA, 1 },
+ };
+ struct Program
+ {
+ const char * Source;
+ const char * Name;
+ const D3D11_INPUT_ELEMENT_DESC * Elements;
+ unsigned ElementCount;
+ };
+ const Program programs[3] = {
+ { SHADOW_CASTER_VERTEX_PROGRAM, "shadowcaster", rigid, sizeof(rigid) / sizeof(rigid[0]) },
+ { SHADOW_CASTER_ALPHA_VERTEX_PROGRAM, "shadowcasteralpha", alpha_tested,
+ sizeof(alpha_tested) / sizeof(alpha_tested[0]) },
+ { SHADOW_CASTER_SKIN_VERTEX_PROGRAM, "shadowcasterskin", skinned, sizeof(skinned) / sizeof(skinned[0]) },
+ };
+ ID3D11Device * device = Device->Get_Device();
+ std::vector<unsigned char> code;
+ bool made = true;
+ for (unsigned kind = 0; kind < 3 && made; ++kind) {
+ made = Compile_Program(programs[kind].Source, programs[kind].Name, VERTEX_PROFILE, code)
+ && SUCCEEDED(device->CreateVertexShader(&code[0], code.size(), NULL, &ShadowCasterVertexShaders[kind]))
+ && SUCCEEDED(device->CreateInputLayout(programs[kind].Elements, programs[kind].ElementCount,
+ &code[0], code.size(), &ShadowCasterLayouts[kind]));
+ }
+ made = made && Compile_Program(SHADOW_CASTER_ALPHA_PIXEL_PROGRAM, "shadowcasteralphatest", PIXEL_PROFILE, code)
+ && SUCCEEDED(device->CreatePixelShader(&code[0], code.size(), NULL, &ShadowCasterAlphaTest));
+ if (!made) {
+ Note_Refusal("the device would not make the instanced shadow caster programs");
+ Release_Shadow_Casters();
+ ShadowCasterRefused = true;
+ return false;
+ }
+ return true;
+}
+
+bool DX11BackendClass::Upload_Shadow_Skin(const ShadowSkinVertex * vertices, unsigned count,
+ unsigned & first_vertex)
+{
+ if (Device == NULL) {
+ return false;
+ }
+ ID3D11Device * device = Device->Get_Device();
+ if (ShadowSkinSource == NULL || ShadowSkinUsed + count > ShadowSkinCapacity) {
+ unsigned capacity = (ShadowSkinCapacity != 0) ? ShadowSkinCapacity * 2 : SHADOW_SKIN_FIRST_VERTICES;
+ while (capacity < count) {
+ capacity *= 2;
+ }
+ if (ShadowSkinSource != NULL) {
+ ShadowSkinSource->Release();
+ ShadowSkinSource = NULL;
+ }
+ ShadowSkinCapacity = 0;
+ ShadowSkinUsed = 0;
+ ++ShadowSkinGeneration;
+ D3D11_BUFFER_DESC buffer;
+ memset(&buffer, 0, sizeof(buffer));
+ buffer.ByteWidth = capacity * sizeof(ShadowSkinVertex);
+ buffer.Usage = D3D11_USAGE_DEFAULT;
+ buffer.BindFlags = D3D11_BIND_VERTEX_BUFFER;
+ if (FAILED(device->CreateBuffer(&buffer, NULL, &ShadowSkinSource))) {
+ Note_Refusal("the device refused the shadow skin source");
+ ShadowSkinSource = NULL;
+ return false;
+ }
+ ShadowSkinCapacity = capacity;
+ }
+ D3D11_BOX box;
+ box.left = ShadowSkinUsed * sizeof(ShadowSkinVertex);
+ box.right = (ShadowSkinUsed + count) * sizeof(ShadowSkinVertex);
+ box.top = 0;
+ box.bottom = 1;
+ box.front = 0;
+ box.back = 1;
+ Device->Get_Context()->UpdateSubresource(ShadowSkinSource, 0, &box, vertices, 0, 0);
+ first_vertex = ShadowSkinUsed;
+ ShadowSkinUsed += count;
+ return true;
+}
+
+// The world matrix the texture category's walk puts on the device for a Matrix3D's three rows:
+// Matrix4x4(Matrix3D).Transpose(), Direct3D 9's layout, the translation in the last row.
+static void world_from_rows(const float rows[12], float world[16])
+{
+ for (unsigned row = 0; row < 3; ++row) {
+ world[row * 4 + 0] = rows[0 * 4 + row];
+ world[row * 4 + 1] = rows[1 * 4 + row];
+ world[row * 4 + 2] = rows[2 * 4 + row];
+ world[row * 4 + 3] = 0.0f;
+ }
+ world[12] = rows[3];
+ world[13] = rows[7];
+ world[14] = rows[11];
+ world[15] = 1.0f;
+}
+
+#if defined(_M_X64) || defined(_M_IX86) || defined(__SSE__)
+// multiply()'s product a row of four columns at a time: every element still starts from nought
+// and adds its four products in index order, each a multiply and then an add, never a fused
+// multiply-add, so the floats are multiply()'s to the bit.
+static void multiply_rows(const float left[16], const float right[16], float result[16])
+{
+ const __m128 right0 = _mm_loadu_ps(right);
+ const __m128 right1 = _mm_loadu_ps(right + 4);
+ const __m128 right2 = _mm_loadu_ps(right + 8);
+ const __m128 right3 = _mm_loadu_ps(right + 12);
+ for (unsigned row = 0; row < 4; ++row) {
+ const float * const factors = left + row * 4;
+ __m128 sum = _mm_setzero_ps();
+ sum = _mm_add_ps(sum, _mm_mul_ps(_mm_set1_ps(factors[0]), right0));
+ sum = _mm_add_ps(sum, _mm_mul_ps(_mm_set1_ps(factors[1]), right1));
+ sum = _mm_add_ps(sum, _mm_mul_ps(_mm_set1_ps(factors[2]), right2));
+ sum = _mm_add_ps(sum, _mm_mul_ps(_mm_set1_ps(factors[3]), right3));
+ _mm_storeu_ps(result + row * 4, sum);
+ }
+}
+#else
+static void multiply_rows(const float left[16], const float right[16], float result[16])
+{
+ multiply(left, right, result);
+}
+#endif
+
+static const float IDENTITY_ROWS[12] ={ 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f };
+
+bool DX11BackendClass::Upload_Shadow_Casters(const float * const * worlds, const unsigned * first_bones,
+ unsigned instance_count, const float * const * bones, unsigned bone_count)
+{
+ if (Device == NULL || !ShadowMapBound || !Make_Shadow_Caster_Program()) {
+ return false;
+ }
+ if (instance_count == 0) {
+ return true;
+ }
+
+ ID3D11Device * device = Device->Get_Device();
+ ID3D11DeviceContext * context = Device->Get_Context();
+ if (ShadowCasterCapacity < instance_count) {
+ if (ShadowCasterInstances != NULL) {
+ ShadowCasterInstances->Release();
+ ShadowCasterInstances = NULL;
+ }
+ ShadowCasterCapacity = 0;
+ unsigned capacity = SHADOW_CASTER_FIRST_INSTANCES;
+ while (capacity < instance_count) {
+ capacity *= 2;
+ }
+ D3D11_BUFFER_DESC buffer;
+ memset(&buffer, 0, sizeof(buffer));
+ buffer.ByteWidth = capacity * SHADOW_CASTER_INSTANCE_FLOATS * sizeof(float);
+ buffer.Usage = D3D11_USAGE_DYNAMIC;
+ buffer.BindFlags = D3D11_BIND_VERTEX_BUFFER;
+ buffer.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
+ if (FAILED(device->CreateBuffer(&buffer, NULL, &ShadowCasterInstances))) {
+ Note_Refusal("the device refused the shadow casters' instance buffer");
+ ShadowCasterInstances = NULL;
+ return false;
+ }
+ ShadowCasterCapacity = capacity;
+ }
+ const unsigned row_count = bone_count * SHADOW_CASTER_ROWS_A_BONE;
+ if (ShadowCasterBonesCapacity < row_count) {
+ if (ShadowCasterBonesView != NULL) {
+ ShadowCasterBonesView->Release();
+ ShadowCasterBonesView = NULL;
+ }
+ if (ShadowCasterBones != NULL) {
+ ShadowCasterBones->Release();
+ ShadowCasterBones = NULL;
+ }
+ ShadowCasterBonesCapacity = 0;
+ unsigned capacity = SHADOW_CASTER_FIRST_BONE_ROWS;
+ while (capacity < row_count) {
+ capacity *= 2;
+ }
+ D3D11_BUFFER_DESC buffer;
+ memset(&buffer, 0, sizeof(buffer));
+ buffer.ByteWidth = capacity * 4 * sizeof(float);
+ buffer.Usage = D3D11_USAGE_DYNAMIC;
+ buffer.BindFlags = D3D11_BIND_SHADER_RESOURCE;
+ buffer.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
+ D3D11_SHADER_RESOURCE_VIEW_DESC view;
+ memset(&view, 0, sizeof(view));
+ view.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
+ view.ViewDimension = D3D11_SRV_DIMENSION_BUFFER;
+ view.Buffer.FirstElement = 0;
+ view.Buffer.NumElements = capacity;
+ if (FAILED(device->CreateBuffer(&buffer, NULL, &ShadowCasterBones))
+ || FAILED(device->CreateShaderResourceView(ShadowCasterBones, &view, &ShadowCasterBonesView))) {
+ Note_Refusal("the device refused the shadow casters' bone buffer");
+ if (ShadowCasterBones != NULL) {
+ ShadowCasterBones->Release();
+ ShadowCasterBones = NULL;
+ }
+ ShadowCasterBonesView = NULL;
+ return false;
+ }
+ ShadowCasterBonesCapacity = capacity;
+ }
+
+ /* Each instance's matrix as Upload_Vertex_Constants makes it, world times view, then times the
+ projection, written straight into the mapped buffer. The same two products in the same order
+ are the same floats. Every identity world (the skins, and meshes at the origin) has the same
+ product, made once. */
+ D3D11_MAPPED_SUBRESOURCE mapped;
+ if (FAILED(context->Map(ShadowCasterInstances, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped))) {
+ return false;
+ }
+ float identity[16];
+ world_from_rows(IDENTITY_ROWS, identity);
+ float identity_view[16];
+ float identity_product[16];
+ multiply(identity, View, identity_view);
+ multiply(identity_view, Projection, identity_product);
+ float * target = static_cast<float *>(mapped.pData);
+ for (unsigned instance = 0; instance < instance_count; ++instance, target += SHADOW_CASTER_INSTANCE_FLOATS) {
+ if (worlds[instance] == NULL) {
+ memcpy(target, identity_product, sizeof(identity_product));
+ } else {
+ float world[16];
+ float world_view[16];
+ world_from_rows(worlds[instance], world);
+ multiply_rows(world, View, world_view);
+ multiply_rows(world_view, Projection, target);
+ }
+ // The padding too: a write-combined buffer left with gaps goes out in pieces.
+ const unsigned tail[SHADOW_CASTER_INSTANCE_FLOATS - SHADOW_CASTER_MATRIX_FLOATS] ={ first_bones[instance], 0, 0, 0 };
+ memcpy(target + SHADOW_CASTER_MATRIX_FLOATS, tail, sizeof(tail));
+ }
+ context->Unmap(ShadowCasterInstances, 0);
+
+ if (row_count != 0) {
+ if (FAILED(context->Map(ShadowCasterBones, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped))) {
+ return false;
+ }
+ float * rows = static_cast<float *>(mapped.pData);
+ for (unsigned bone = 0; bone < bone_count; ++bone, rows += SHADOW_CASTER_ROWS_A_BONE * 4) {
+ memcpy(rows, bones[bone], SHADOW_CASTER_ROWS_A_BONE * 4 * sizeof(float));
+ }
+ context->Unmap(ShadowCasterBones, 0);
+ }
+ return true;
+}
+
+bool DX11BackendClass::Draw_Shadow_Casters(const ShadowCasterRun * runs, unsigned run_count)
+{
+ if (run_count == 0) {
+ return true;
+ }
+ ID3D11DeviceContext * context = Device->Get_Context();
+ bool alpha_tested = false;
+ for (unsigned index = 0; index < run_count && !alpha_tested; ++index) {
+ alpha_tested = runs[index].Kind == SHADOW_CASTER_ALPHA_TESTED;
+ }
+ if (alpha_tested) {
+ if (Textures[0] == NULL) {
+ return false;
+ }
+ ID3D11SamplerState * const sampler = Sampler_State(0);
+ context->PSSetShaderResources(0, 1, &Textures[0]);
+ context->PSSetSamplers(0, 1, &sampler);
+ }
+ context->VSSetShaderResources(0, 1, &ShadowCasterBonesView);
+
+ /* The cull and the depth test are each run's own, the rest of the rasterizer and depth state
+ (the bias, the clipping, the depth writes the caster pass forces) is what the pass holds, which
+ is what the mesh renderer's draws would have read. Built through the render states so a
+ state object is the one those draws would have been given; both go back as they were. */
+ const DWORD held_cull = RenderStates.Get_Stored_Render_State(D3DRS_CULLMODE);
+ const DWORD held_depth = RenderStates.Get_Stored_Render_State(D3DRS_ZFUNC);
+ ID3D11Buffer * bound_vertices = NULL;
+ unsigned bound_stride = 0;
+ unsigned bound_texture_offset = 0;
+ ID3D11Buffer * bound_indices = NULL;
+ bool bound_strip = false;
+ bool states_known = false;
+ ShadowCasterKind bound_kind = SHADOW_CASTER_RIGID;
+ for (unsigned index = 0; index < run_count; ++index) {
+ const ShadowCasterRun & run = runs[index];
+ if (!states_known || run.CullMode != RenderStates.Get_Stored_Render_State(D3DRS_CULLMODE)
+ || run.DepthFunction != RenderStates.Get_Stored_Render_State(D3DRS_ZFUNC)) {
+ Set_Render_State(D3DRS_CULLMODE, run.CullMode);
+ Set_Render_State(D3DRS_ZFUNC, run.DepthFunction);
+ context->RSSetState(Rasterizer_State());
+ context->OMSetDepthStencilState(Depth_Stencil_State(), RenderStates.Get_Stencil_Reference());
+ states_known = true;
+ }
+ if (index == 0 || run.Kind != bound_kind) {
+ context->IASetInputLayout(ShadowCasterLayouts[run.Kind]);
+ context->VSSetShader(ShadowCasterVertexShaders[run.Kind], NULL, 0);
+ context->PSSetShader((run.Kind == SHADOW_CASTER_ALPHA_TESTED) ? ShadowCasterAlphaTest : NULL, NULL, 0);
+ bound_kind = run.Kind;
+ bound_vertices = NULL;
+ }
+ ID3D11Buffer * const vertices = (run.Kind == SHADOW_CASTER_SKINNED) ? ShadowSkinSource : run.Vertices;
+ const unsigned stride = (run.Kind == SHADOW_CASTER_SKINNED) ? sizeof(ShadowSkinVertex) : run.Stride;
+ if (vertices != bound_vertices || stride != bound_stride || run.TextureOffset != bound_texture_offset) {
+ ID3D11Buffer * const buffers[3] = { vertices, ShadowCasterInstances, vertices };
+ const UINT strides[3] = { stride, SHADOW_CASTER_INSTANCE_FLOATS * sizeof(float), stride };
+ const UINT offsets[3] = { 0, 0, run.TextureOffset };
+ context->IASetVertexBuffers(0, 3, buffers, strides, offsets);
+ bound_vertices = vertices;
+ bound_stride = stride;
+ bound_texture_offset = run.TextureOffset;
+ }
+ if (index == 0 || run.Indices != bound_indices) {
+ context->IASetIndexBuffer(run.Indices, DXGI_FORMAT_R16_UINT, 0);
+ bound_indices = run.Indices;
+ }
+ if (index == 0 || run.Strip != bound_strip) {
+ context->IASetPrimitiveTopology(run.Strip
+ ? D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP : D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
+ bound_strip = run.Strip;
+ }
+ context->DrawIndexedInstanced(run.IndexCount, run.InstanceCount, run.StartIndex,
+ static_cast<INT>(run.BaseVertex), run.FirstInstance);
+ ++DrawsMade;
+ }
+ Set_Render_State(D3DRS_CULLMODE, held_cull);
+ Set_Render_State(D3DRS_ZFUNC, held_depth);
+ ID3D11ShaderResourceView * const no_view = NULL;
+ context->VSSetShaderResources(0, 1, &no_view);
+ Forget_Bindings();
+ return true;
+}
+
bool DX11BackendClass::Camera_Space_Draw() const
{
static const float IDENTITY[16] = {
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h
index 2f9c4b9ab..226eb920e 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h
@@ -244,6 +244,58 @@ public:
bool Fill_Smoke_Map(const float * casters, unsigned count, float strength);
ID3D11ShaderResourceView * Smoke_Map() const { return SmokeMapFilled ? SmokeMapTexture : NULL; }
+ // The opaque casters of the sun's depth pass, drawn depth only and instanced: one run is one
+ // piece of one mesh model (a buffer pair, an index range, a cull and a depth test), drawn once
+ // for each of its instances. Upload_Shadow_Casters takes the pass's instances, each a world as
+ // the three rows of a Matrix3D (NULL for an identity world) and the first bone of a skinned one,
+ // and the pass's bones, three rows of a Matrix3D each, and writes them straight into the mapped
+ // buffers; it is false, with nothing written, when the device refused a program or a buffer, and
+ // the caller draws them the old way. Each instance's world is the matrix the texture category's
+ // walk sets (the Matrix3D transposed into Direct3D 9's layout) and its position goes through the
+ // product Upload_Vertex_Constants builds, in the same order, so the map holds the depth the
+ // generated programs wrote. An alpha tested run samples the texture and
+ // sampler on stage 0 as they stand, so Draw_Shadow_Casters is handed the runs of one texture at
+ // a time, and is false, with nothing drawn, when alpha tested runs find no texture there. A
+ // skinned run's vertices are the shadow skin source. Only while the map is bound. Every run
+ // counts in Draws_Made.
+ enum ShadowCasterKind
+ {
+ SHADOW_CASTER_RIGID,
+ SHADOW_CASTER_ALPHA_TESTED,
+ SHADOW_CASTER_SKINNED
+ };
+ struct ShadowCasterRun
+ {
+ ShadowCasterKind Kind;
+ ID3D11Buffer * Vertices;
+ unsigned Stride;
+ unsigned TextureOffset; ///< bytes into a vertex to stage 0's coordinates, alpha tested only
+ ID3D11Buffer * Indices;
+ unsigned StartIndex;
+ unsigned IndexCount;
+ unsigned BaseVertex;
+ bool Strip;
+ DWORD CullMode; ///< D3DCULL
+ DWORD DepthFunction; ///< D3DCMPFUNC
+ unsigned FirstInstance;
+ unsigned InstanceCount;
+ };
+ struct ShadowSkinVertex
+ {
+ float Position[3]; ///< the bind pose, in its bone's space
+ unsigned Bone;
+ };
+ bool Upload_Shadow_Casters(const float * const * worlds, const unsigned * first_bones,
+ unsigned instance_count, const float * const * bones, unsigned bone_count);
+ bool Draw_Shadow_Casters(const ShadowCasterRun * runs, unsigned run_count);
+
+ // The bind poses of the skins the depth pass skins on the GPU, appended a model at a time and
+ // kept across passes. A model whose vertices do not fit starts a new, larger buffer, and so does
+ // a release of the device; either moves the generation on, and a model uploaded under an older
+ // generation uploads again. False when the device refused the buffer.
+ bool Upload_Shadow_Skin(const ShadowSkinVertex * vertices, unsigned count, unsigned & first_vertex);
+ unsigned Shadow_Skin_Generation() const { return ShadowSkinGeneration; }
+
// The scene camera's view, which a camera space draw's pixels go back to the world through: the
// sorted particles are written in camera space and drawn with an identity world and view
// (PointGroupClass::Insert_Sorted_Billboards), so the view the backend holds for them says
@@ -691,6 +743,24 @@ private:
bool SmokeMapRefused;
bool SmokeMapFilled;
float SmokeStrength;
+ // Draw_Shadow_Casters' programs and layouts a kind of run, the alpha test's pixel program, the
+ // instance buffer and the bones' buffer, both of which grow by doubling and are written once a
+ // pass, and the skin source. Made on the first pass.
+ bool Make_Shadow_Caster_Program();
+ void Release_Shadow_Casters();
+ ID3D11VertexShader * ShadowCasterVertexShaders[3];
+ ID3D11InputLayout * ShadowCasterLayouts[3];
+ ID3D11PixelShader * ShadowCasterAlphaTest;
+ ID3D11Buffer * ShadowCasterInstances;
+ unsigned ShadowCasterCapacity;
+ ID3D11Buffer * ShadowCasterBones;
+ ID3D11ShaderResourceView * ShadowCasterBonesView;
+ unsigned ShadowCasterBonesCapacity;
+ bool ShadowCasterRefused;
+ ID3D11Buffer * ShadowSkinSource;
+ unsigned ShadowSkinCapacity;
+ unsigned ShadowSkinUsed;
+ unsigned ShadowSkinGeneration;
// Set_Headlights' slots, eight floats each, how many are lit and the gain per channel.
float Headlights[HEADLIGHT_SLOTS][8];
unsigned HeadlightCount;
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp
index 5b8fa38fd..d06683025 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp
@@ -620,6 +620,51 @@ bool Direct3D11_Fill_Smoke_Map(const float * casters, unsigned count, float stre
return Active ? Backend.Fill_Smoke_Map(casters, count, strength) : false;
}
+bool Direct3D11_Upload_Shadow_Casters(const float * const * worlds, const unsigned * first_bones,
+ unsigned instance_count, const float * const * bones, unsigned bone_count)
+{
+ return Active && Backend.Upload_Shadow_Casters(worlds, first_bones, instance_count, bones, bone_count);
+}
+
+bool Direct3D11_Upload_Shadow_Skin(const DX11ShadowSkinVertex * vertices, unsigned count,
+ unsigned & first_vertex)
+{
+ return Active && Backend.Upload_Shadow_Skin(
+ reinterpret_cast<const DX11BackendClass::ShadowSkinVertex *>(vertices), count, first_vertex);
+}
+
+unsigned Direct3D11_Shadow_Skin_Generation()
+{
+ return Backend.Shadow_Skin_Generation();
+}
+
+bool Direct3D11_Draw_Shadow_Casters(const DX11ShadowCasterRun * runs, unsigned run_count)
+{
+ if (!Active) {
+ return false;
+ }
+ static std::vector<DX11BackendClass::ShadowCasterRun> backend_runs;
+ backend_runs.resize(run_count);
+ for (unsigned index = 0; index < run_count; ++index) {
+ const DX11ShadowCasterRun & run = runs[index];
+ DX11BackendClass::ShadowCasterRun & backend_run = backend_runs[index];
+ backend_run.Kind = static_cast<DX11BackendClass::ShadowCasterKind>(run.Kind);
+ backend_run.Vertices = (run.Vertices != NULL) ? run.Vertices->Buffer() : NULL;
+ backend_run.Stride = run.Stride;
+ backend_run.TextureOffset = run.TextureOffset;
+ backend_run.Indices = run.Indices->Buffer();
+ backend_run.StartIndex = run.StartIndex;
+ backend_run.IndexCount = run.IndexCount;
+ backend_run.BaseVertex = run.BaseVertex;
+ backend_run.Strip = run.Strip;
+ backend_run.CullMode = run.CullMode;
+ backend_run.DepthFunction = run.DepthFunction;
+ backend_run.FirstInstance = run.FirstInstance;
+ backend_run.InstanceCount = run.InstanceCount;
+ }
+ return Backend.Draw_Shadow_Casters(run_count ? &backend_runs[0] : NULL, run_count);
+}
+
void Direct3D11_Set_Scene_View(const float view[16])
{
if (Active) {
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h
index a09719a2b..15e37d870 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h
@@ -166,6 +166,52 @@ void Direct3D11_Clear_Shadow_Parameters();
// caller keeps its older shade under the clouds.
bool Direct3D11_Fill_Smoke_Map(const float * casters, unsigned count, float strength);
+// The sun's opaque casters, depth only and instanced, while the map is bound
+// (DX11BackendClass::Upload_Shadow_Casters and Draw_Shadow_Casters): the pass's instances go up
+// once, a world an instance as the three rows of its Matrix3D (NULL for an identity world) and the
+// first bone of a skinned one, with the pass's bones, three rows of a Matrix3D each. A run is
+// one piece of one mesh model drawn once for each of its instances. An alpha tested run samples
+// the texture set on stage 0, so the runs are drawn a texture at a time. False with nothing drawn
+// when there is no backend, it refused a program or a buffer, or alpha tested runs find no texture
+// on stage 0, and the caller draws those casters the old way.
+enum DX11ShadowCasterKind
+{
+ DX11_SHADOW_CASTER_RIGID,
+ DX11_SHADOW_CASTER_ALPHA_TESTED,
+ DX11_SHADOW_CASTER_SKINNED
+};
+struct DX11ShadowCasterRun
+{
+ DX11ShadowCasterKind Kind;
+ DX11BufferTwinClass * Vertices; ///< NULL for a skinned run, which reads the skin source
+ unsigned Stride;
+ unsigned TextureOffset; ///< bytes into a vertex to stage 0's coordinates
+ DX11BufferTwinClass * Indices;
+ unsigned StartIndex;
+ unsigned IndexCount;
+ unsigned BaseVertex;
+ bool Strip;
+ unsigned long CullMode; ///< D3DCULL
+ unsigned long DepthFunction; ///< D3DCMPFUNC
+ unsigned FirstInstance;
+ unsigned InstanceCount;
+};
+bool Direct3D11_Upload_Shadow_Casters(const float * const * worlds, const unsigned * first_bones,
+ unsigned instance_count, const float * const * bones, unsigned bone_count);
+bool Direct3D11_Draw_Shadow_Casters(const DX11ShadowCasterRun * runs, unsigned run_count);
+
+// A skin's bind pose for the depth pass to skin on the GPU (DX11BackendClass::Upload_Shadow_Skin):
+// a position in its bone's space and the bone, a vertex at a time. The first vertex comes back
+// with the generation it is good for; a model uploaded under an older one uploads again.
+struct DX11ShadowSkinVertex
+{
+ float Position[3];
+ unsigned Bone;
+};
+bool Direct3D11_Upload_Shadow_Skin(const DX11ShadowSkinVertex * vertices, unsigned count,
+ unsigned & first_vertex);
+unsigned Direct3D11_Shadow_Skin_Generation();
+
// The scene camera's view, in the device's layout, set by the shadow pass once the frame's camera is
// back. A draw made in camera space (identity view, perspective projection: the sorted particles)
// looks its shadow up through it.
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime_posix.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime_posix.cpp
index e9ecdfaaa..b57e77e4b 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime_posix.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime_posix.cpp
@@ -74,6 +74,10 @@ std::string Direct3D11_Shadow_Map_Report() { return std::string("no Direct3D 11
void Direct3D11_Set_Shadow_Parameters(float, float, float, float, float, float, float) {}
void Direct3D11_Clear_Shadow_Parameters() {}
bool Direct3D11_Fill_Smoke_Map(const float *, unsigned, float) { return false; }
+bool Direct3D11_Upload_Shadow_Casters(const float * const *, const unsigned *, unsigned, const float * const *, unsigned) { return false; }
+bool Direct3D11_Draw_Shadow_Casters(const DX11ShadowCasterRun *, unsigned) { return false; }
+bool Direct3D11_Upload_Shadow_Skin(const DX11ShadowSkinVertex *, unsigned, unsigned &) { return false; }
+unsigned Direct3D11_Shadow_Skin_Generation() { return 0; }
void Direct3D11_Set_Scene_View(const float [16]) {}
void Direct3D11_Set_Smoke_Glow(bool) {}
void Direct3D11_Set_Fire_Look(bool) {}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8polygonrenderer.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8polygonrenderer.h
index 0498d8216..b1d688709 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8polygonrenderer.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8polygonrenderer.h
@@ -92,6 +92,8 @@ public:
unsigned Get_Vertex_Offset(void) { return vertex_offset; }
unsigned Get_Index_Offset(void) { return index_offset; }
inline unsigned Get_Pass(void) { return pass; }
+ unsigned Get_Index_Count(void) { return index_count; }
+ bool Is_Strip(void) { return strip; }
MeshModelClass* Get_Mesh_Model_Class() { return mmc; }
DX8TextureCategoryClass* Get_Texture_Category() { return texture_category; }
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8renderer.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8renderer.cpp
index 7746956cb..e6ffcf4ab 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8renderer.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8renderer.cpp
@@ -65,6 +65,11 @@
#include "stripoptimizer.h"
#include "meshgeometry.h"
#include "sortingrenderer.h"
+#include "htree.h"
+
+#include <algorithm>
+#include <tuple>
+#include <vector>
/*
** Global Instance of the DX8MeshRender
@@ -2230,6 +2235,532 @@ static void Render_FVF_Category_Container_List_Delayed_Passes(FVFCategoryList& l
}
}
+// ---------------------------------------------------------------------------
+//
+// The sun's depth pass, instanced. A texture category's walk sets a texture, a material, lights,
+// a world matrix and a shader for every piece of every caster, and the backend then builds and
+// compares a constant block and resolves a pipeline for each, all for a draw whose only output is
+// depth. An opaque rigid caster's depth is its triangles through world, view and projection and
+// nothing else, so those are drawn here, one draw per piece of a model whatever the number of
+// copies in the sun's box. An alpha tested one adds its texture's alpha test, and a skin is
+// skinned in the vertex program from its bind pose, uploaded once, and the pass's bones, so its
+// vertices are not deformed on the CPU for the pass at all.
+//
+// ---------------------------------------------------------------------------
+
+int DX8MeshRendererClass::Shadow_Lean_Draws = 0;
+int DX8MeshRendererClass::Shadow_Lean_Instances = 0;
+int DX8MeshRendererClass::Shadow_Lean_Alpha_Tested = 0;
+int DX8MeshRendererClass::Shadow_Lean_Skinned = 0;
+int DX8MeshRendererClass::Shadow_Old_Meshes[DX8MeshRendererClass::SHADOW_OLD_REASON_COUNT] = { 0 };
+
+void DX8MeshRendererClass::Reset_Shadow_Caster_Counts()
+{
+ Shadow_Lean_Draws = 0;
+ Shadow_Lean_Instances = 0;
+ Shadow_Lean_Alpha_Tested = 0;
+ Shadow_Lean_Skinned = 0;
+ memset(Shadow_Old_Meshes, 0, sizeof(Shadow_Old_Meshes));
+}
+
+const char * DX8MeshRendererClass::Shadow_Old_Reason_Name(int reason)
+{
+ static const char * const names[SHADOW_OLD_REASON_COUNT] = {
+ "sorted", "camera-facing", "draw-effect", "fading", "debug", "streaming", "skin-passes", "blended",
+ "alpha-test", "skin-alpha-test", "format", "no-base-pass", "refused"
+ };
+ return names[reason];
+}
+
+/* A pass groups the casters by model: the first instance of a model this pass works its pieces
+ out (Describe_Shadow_Caster_Piece, its base pass pieces as runs) and every instance after it
+ only joins the model's group. Each piece of each model is then one run over the group's
+ instances, which a counting sort by group lays out one after another. */
+struct ShadowCasterPiece
+{
+ TextureClass * Texture; // stage 0 of an alpha tested piece, NULL otherwise
+ DX11ShadowCasterKind Kind;
+ DX11BufferTwinClass * Vertices; // NULL for a skin, which reads the skin source
+ unsigned Stride;
+ unsigned TextureOffset;
+ DX11BufferTwinClass * Indices;
+ unsigned StartIndex;
+ unsigned IndexCount;
+ bool Strip;
+ bool Culled;
+ unsigned long DepthFunction;
+ DX8PolygonRendererClass * Renderer;
+};
+
+struct ShadowCasterGroup
+{
+ MeshModelClass * Model;
+ unsigned FirstPiece;
+ unsigned PieceCount;
+ unsigned InstanceCount;
+ unsigned FirstInstance;
+ unsigned BaseVertex;
+};
+
+struct ShadowCasterInstance
+{
+ MeshClass * Mesh; // a reference each, as a render task holds
+ unsigned Group;
+ const float * World; // the Matrix3D's rows, NULL for an identity world
+ unsigned FirstBone;
+};
+
+struct ShadowCasterRunEntry
+{
+ TextureClass * Texture;
+ unsigned Piece;
+ DX11ShadowCasterRun Run;
+};
+
+static unsigned _ShadowCasterPass = 1;
+static std::vector<ShadowCasterPiece> _ShadowCasterPieces;
+static std::vector<ShadowCasterGroup> _ShadowCasterGroups;
+static std::vector<ShadowCasterInstance> _ShadowCasterInstances;
+static std::vector<MeshClass *> _ShadowCasterOrdered;
+static std::vector<const float *> _ShadowCasterWorlds;
+static std::vector<unsigned> _ShadowCasterFirstBones;
+static std::vector<const float *> _ShadowCasterBones;
+static std::vector<DX11ShadowCasterRun> _ShadowCasterRuns;
+static std::vector<unsigned> _ShadowCasterRunPieces;
+static std::vector<ShadowCasterRunEntry> _ShadowCasterRunEntries;
+// The skeleton whose bones went in last, which the next skin of the same model reuses.
+static const HTreeClass * _ShadowCasterLastTree = NULL;
+static unsigned _ShadowCasterLastFirstBone = 0;
+static std::vector<DX11ShadowSkinVertex> _ShadowSkinVertices;
+
+static DX11BufferTwinClass * Shadow_Caster_Vertex_Twin(VertexBufferClass * buffer)
+{
+ if (buffer == NULL || buffer->Type() != BUFFER_TYPE_DX8) {
+ return NULL;
+ }
+ DX8VertexBufferClass * vertices = static_cast<DX8VertexBufferClass *>(buffer);
+ return (vertices->Get_DX8_Vertex_Buffer() != NULL) ? vertices->Get_DX11_Twin() : NULL;
+}
+
+static DX11BufferTwinClass * Shadow_Caster_Index_Twin(IndexBufferClass * buffer)
+{
+ if (buffer == NULL || buffer->Type() != BUFFER_TYPE_DX8) {
+ return NULL;
+ }
+ DX8IndexBufferClass * indices = static_cast<DX8IndexBufferClass *>(buffer);
+ return (indices->Get_DX8_Index_Buffer() != NULL) ? indices->Get_DX11_Twin() : NULL;
+}
+
+/* Whether an alpha tested piece's test is stage 0's texel alpha alone, which is all the lean pixel
+ program reads: a plain texture through the material's own coordinates (no mapper), an alpha the
+ stages take from the texture and the diffuse colour only, and a diffuse alpha of one, which is
+ the material's opacity when it is lit from the material and a vertex colour's alpha otherwise,
+ so a vertex colour has to stay out of it. */
+static bool Shadow_Caster_Alpha_Is_Texture(DX8TextureCategoryClass * category, const ShaderClass & shader,
+ unsigned fvf, unsigned & uv_set)
+{
+ VertexMaterialClass * material = const_cast<VertexMaterialClass *>(category->Peek_Material());
+ const ShaderClass::PriGradientType gradient = shader.Get_Primary_Gradient();
+ if (category->Peek_Texture(0) == NULL || shader.Get_Texturing() != ShaderClass::TEXTURING_ENABLE
+ || (gradient != ShaderClass::GRADIENT_DISABLE && gradient != ShaderClass::GRADIENT_MODULATE
+ && gradient != ShaderClass::GRADIENT_ADD && gradient != ShaderClass::GRADIENT_MODULATE2X)
+ || shader.Get_Post_Detail_Alpha_Func() != ShaderClass::DETAILALPHA_DISABLE
+ || (material != NULL && material->Peek_Mapper(0) != NULL)) {
+ return false;
+ }
+ // Lit, the diffuse alpha is the material's whenever the vertex has no colour to take it from,
+ // whatever source the material names (ffvertex.cpp falls back to MaterialDiffuse).
+ const bool lit = material != NULL && material->Get_Lighting() && !WW3D::Is_Coloring_Enabled();
+ const bool lit_from_material = lit && material->Get_Diffuse_Color_Source() == VertexMaterialClass::MATERIAL;
+ if ((lit && material->Get_Opacity() != 1.0f)
+ || ((fvf & D3DFVF_DIFFUSE) != 0 && !lit_from_material)) {
+ return false;
+ }
+ uv_set = (material != NULL) ? (unsigned)material->Get_UV_Source(0) : 0;
+ const unsigned uv_sets = (fvf & D3DFVF_TEXCOUNT_MASK) >> D3DFVF_TEXCOUNT_SHIFT;
+ const unsigned uv_format = (fvf >> (16 + uv_set * 2)) & 3;
+ return uv_set < uv_sets && uv_format == D3DFVF_TEXTUREFORMAT2;
+}
+
+/* One base pass piece of a model as a run, or the reason the model goes the old way. */
+static int Describe_Shadow_Caster_Piece(DX8PolygonRendererClass * renderer, bool skin,
+ ShadowCasterPiece & record)
+{
+ DX8TextureCategoryClass * category = renderer->Get_Texture_Category();
+ const ShaderClass shader = category->Get_Shader();
+ DX8FVFCategoryContainer * container = category->Get_Container();
+ if (shader.Get_Src_Blend_Func() != ShaderClass::SRCBLEND_ONE
+ || shader.Get_Dst_Blend_Func() != ShaderClass::DSTBLEND_ZERO) {
+ return DX8MeshRendererClass::SHADOW_OLD_BLENDED;
+ }
+ const bool alpha_tested = shader.Get_Alpha_Test() != ShaderClass::ALPHATEST_DISABLE;
+ if (alpha_tested && skin) {
+ return DX8MeshRendererClass::SHADOW_OLD_SKIN_ALPHA_TEST;
+ }
+ record.Indices = Shadow_Caster_Index_Twin(container->Peek_Index_Buffer());
+ record.Texture = NULL;
+ record.TextureOffset = 0;
+ if (skin) {
+ // The skin source's vertices, which Flush_Shadow_Casters places; the indices are the
+ // model's own, the container having put every skin at vertex offset 0 (Add_Mesh).
+ record.Kind = DX11_SHADOW_CASTER_SKINNED;
+ record.Vertices = NULL;
+ record.Stride = 0;
+ if (record.Indices == NULL) {
+ return DX8MeshRendererClass::SHADOW_OLD_FORMAT;
+ }
+ } else {
+ VertexBufferClass * buffer = static_cast<DX8RigidFVFCategoryContainer *>(container)->Peek_Vertex_Buffer();
+ record.Kind = DX11_SHADOW_CASTER_RIGID;
+ record.Vertices = Shadow_Caster_Vertex_Twin(buffer);
+ if ((container->Get_FVF() & D3DFVF_POSITION_MASK) != D3DFVF_XYZ || record.Vertices == NULL
+ || record.Indices == NULL) {
+ return DX8MeshRendererClass::SHADOW_OLD_FORMAT;
+ }
+ record.Stride = buffer->FVF_Info().Get_FVF_Size();
+ if (alpha_tested) {
+ unsigned uv_set = 0;
+ if (!Shadow_Caster_Alpha_Is_Texture(category, shader, container->Get_FVF(), uv_set)) {
+ return DX8MeshRendererClass::SHADOW_OLD_ALPHA_TEST;
+ }
+ record.Kind = DX11_SHADOW_CASTER_ALPHA_TESTED;
+ record.Texture = category->Peek_Texture(0);
+ record.TextureOffset = buffer->FVF_Info().Get_Tex_Offset(uv_set);
+ }
+ }
+
+ record.StartIndex = (unsigned short)renderer->Get_Index_Offset();
+ record.Strip = renderer->Is_Strip();
+ record.IndexCount = record.Strip
+ ? (unsigned)(unsigned short)(renderer->Get_Index_Count() - 2) + 2
+ : (unsigned)(unsigned short)(renderer->Get_Index_Count() / 3) * 3;
+ // ShaderClass::Apply's cull and depth test; which way the cull faces is read when the run is made.
+ record.Culled = shader.Get_Cull_Mode() != 0;
+ record.DepthFunction = (unsigned long)(int(shader.Get_Depth_Compare()) + 1);
+ record.Renderer = renderer;
+ return -1;
+}
+
+/* A model's pieces from the given one on, merged where they can be one draw: a model's base pass
+ pieces sit one after another in the container's index buffer, a texture category each
+ (Generate_Texture_Categories hands the indices out in order), and the depth pass draws two
+ opaque pieces in the same buffers with the same cull and test alike. Only an order-free test
+ (less or less-equal, so the nearest surface wins whichever is drawn first) is merged, and only
+ lists. */
+static void Merge_Shadow_Caster_Pieces(size_t first)
+{
+ std::sort(_ShadowCasterPieces.begin() + first, _ShadowCasterPieces.end(),
+ [](const ShadowCasterPiece & left, const ShadowCasterPiece & right) { return left.StartIndex < right.StartIndex; });
+ size_t kept = first;
+ for (size_t index = first + 1; index < _ShadowCasterPieces.size(); ++index) {
+ ShadowCasterPiece & last = _ShadowCasterPieces[kept];
+ const ShadowCasterPiece & next = _ShadowCasterPieces[index];
+ const bool order_free = last.DepthFunction == D3DCMP_LESSEQUAL || last.DepthFunction == D3DCMP_LESS;
+ if (last.Kind != DX11_SHADOW_CASTER_ALPHA_TESTED && next.Kind == last.Kind && !last.Strip && !next.Strip
+ && next.Vertices == last.Vertices && next.Stride == last.Stride && next.Indices == last.Indices
+ && next.Culled == last.Culled && next.DepthFunction == last.DepthFunction && order_free
+ && last.StartIndex + last.IndexCount == next.StartIndex) {
+ last.IndexCount += next.IndexCount;
+ } else {
+ _ShadowCasterPieces[++kept] = next;
+ }
+ }
+ _ShadowCasterPieces.resize(kept + 1);
+}
+
+// The pass's records gone, their storage kept for the next pass, and a new pass begun.
+static void Clear_Shadow_Casters()
+{
+ _ShadowCasterInstances.clear();
+ _ShadowCasterPieces.clear();
+ _ShadowCasterGroups.clear();
+ _ShadowCasterBones.clear();
+ _ShadowCasterLastTree = NULL;
+ ++_ShadowCasterPass;
+}
+
+bool DX8MeshRendererClass::Add_Shadow_Caster(MeshClass * mesh, bool has_material_passes)
+{
+ /* What the texture category's walk would do differently for this mesh, each a reason to leave
+ it there: a sorted or camera facing model, a look (the cloak's shadow), a fading opacity, a
+ mesh the debugger hides, the forced multiply that blends opaque
+ materials, a rigid model still waiting for room in a streaming buffer (a skin's offset is the
+ last fill's and means nothing here), and a skin whose material passes need its vertices
+ deformed into the container anyway. */
+ MeshModelClass * model = mesh->Peek_Model();
+ const bool skin = model->Get_Flag(MeshGeometryClass::SKIN) != 0;
+ /* A material override (a tread's scrolling coordinates) only moves the coordinates of a stage 0
+ linear offset mapper, and no piece taken reads those: an opaque piece writes depth alone and an
+ alpha tested one is taken only without a mapper. Fading swaps in a blending shader, which the
+ pass turns into its own alpha test on the faded alpha, and stays the old way. */
+ int reason = -1;
+ if (mesh->Get_Draw_Effect() != 0) {
+ reason = SHADOW_OLD_DRAW_EFFECT;
+ } else if (mesh->Get_Alpha_Override() != 1.0f) {
+ reason = SHADOW_OLD_FADING;
+ } else if (DX8RendererDebugger::Is_Enabled() || DX8TextureCategoryClass::Is_Force_Multiply()) {
+ reason = SHADOW_OLD_DEBUG;
+ } else if (!skin && mesh->Get_Base_Vertex_Offset() != 0) {
+ // A rigid mesh's offset is nought (only a skin's fill sets one) unless it is waiting for room.
+ reason = SHADOW_OLD_STREAMING;
+ } else if (skin && has_material_passes) {
+ reason = SHADOW_OLD_SKIN_PASSES;
+ }
+ if (reason >= 0) {
+ ++Shadow_Old_Meshes[reason];
+ return false;
+ }
+
+ if (model->ShadowCasterPass != _ShadowCasterPass) {
+ /* The model's first instance this pass. Every base pass piece has to be taken, or the model
+ goes the old way whole. Only pass 0 is drawn: a later pass is the same triangles again and
+ adds no depth the first did not write. */
+ model->ShadowCasterPass = _ShadowCasterPass;
+ if (model->Get_Flag(MeshGeometryClass::SORT)) {
+ reason = SHADOW_OLD_SORTED;
+ } else if (model->Get_Flag(MeshModelClass::ALIGNED) || model->Get_Flag(MeshModelClass::ORIENTED)) {
+ reason = SHADOW_OLD_CAMERA_FACING;
+ }
+ const size_t first = _ShadowCasterPieces.size();
+ DX8PolygonRendererListIterator it(&(model->PolygonRendererList));
+ for (; reason < 0 && !it.Is_Done(); it.Next()) {
+ DX8PolygonRendererClass * renderer = it.Peek_Obj();
+ if (renderer->Get_Pass() != 0) {
+ continue;
+ }
+ ShadowCasterPiece piece;
+ reason = Describe_Shadow_Caster_Piece(renderer, skin, piece);
+ if (reason < 0) {
+ _ShadowCasterPieces.push_back(piece);
+ }
+ }
+ if (reason < 0 && _ShadowCasterPieces.size() == first) {
+ reason = SHADOW_OLD_NO_BASE_PASS;
+ }
+ if (reason >= 0) {
+ _ShadowCasterPieces.resize(first);
+ model->ShadowCasterGroup = -1 - reason;
+ } else {
+ Merge_Shadow_Caster_Pieces(first);
+ ShadowCasterGroup group;
+ group.Model = model;
+ group.FirstPiece = (unsigned)first;
+ group.PieceCount = (unsigned)(_ShadowCasterPieces.size() - first);
+ group.InstanceCount = 0;
+ group.FirstInstance = 0;
+ group.BaseVertex = 0;
+ model->ShadowCasterGroup = (int)_ShadowCasterGroups.size();
+ _ShadowCasterGroups.push_back(group);
+ }
+ }
+ if (model->ShadowCasterGroup < 0) {
+ ++Shadow_Old_Meshes[-1 - model->ShadowCasterGroup];
+ return false;
+ }
+
+ /* Each instance's world, as the rows of its Matrix3D, NULL where the texture category's walk sets
+ an identity world (an identity transform, and every skin); each skeleton's bones in the pose
+ the skin container's fill would read them in (MeshClass::Get_Deformed_Vertices), and each
+ skin's first bone among them. A model's skins are rendered one after another, so they share
+ one copy of the skeleton; a skeleton met again later only costs a second copy. */
+ mesh->Add_Ref();
+ ShadowCasterInstance instance;
+ instance.Mesh = mesh;
+ instance.Group = (unsigned)model->ShadowCasterGroup;
+ instance.World = NULL;
+ instance.FirstBone = 0;
+ if (!skin) {
+ if (!mesh->Is_Transform_Identity()) {
+ instance.World = reinterpret_cast<const float *>(&mesh->Get_Transform());
+ }
+ } else {
+ const HTreeClass * tree = mesh->Get_Container()->Get_HTree();
+ if (tree != _ShadowCasterLastTree) {
+ _ShadowCasterLastTree = tree;
+ _ShadowCasterLastFirstBone = (unsigned)_ShadowCasterBones.size();
+ const int pivots = tree->Num_Pivots();
+ for (int pivot = 0; pivot < pivots; ++pivot) {
+ _ShadowCasterBones.push_back(reinterpret_cast<const float *>(&tree->Get_Transform(pivot)));
+ }
+ }
+ instance.FirstBone = _ShadowCasterLastFirstBone;
+ }
+ _ShadowCasterInstances.push_back(instance);
+ ++_ShadowCasterGroups[instance.Group].InstanceCount;
+ return true;
+}
+
+void DX8MeshRendererClass::Flush_Shadow_Casters()
+{
+ if (_ShadowCasterInstances.empty()) {
+ Clear_Shadow_Casters();
+ return;
+ }
+ WWPROFILE("DX8MeshRenderer::Flush_Shadow_Casters");
+
+ // The sun's view is set but waits in the wrapper for the next draw; the backend reads it here.
+ DX8Wrapper::Apply_Render_State_Changes();
+
+ /* The skins' bind poses into the skin source, a model the first time it is seen under the
+ source's generation. A model that does not fit starts a new source, which every model uploaded
+ before it has to go into again, this pass's included, so the walk starts over. */
+ bool uploaded = true;
+ bool placed = false;
+ while (uploaded && !placed) {
+ placed = true;
+ const unsigned generation = Direct3D11_Shadow_Skin_Generation();
+ for (size_t index = 0; index < _ShadowCasterGroups.size() && placed && uploaded; ++index) {
+ ShadowCasterGroup & group = _ShadowCasterGroups[index];
+ if (_ShadowCasterPieces[group.FirstPiece].Kind != DX11_SHADOW_CASTER_SKINNED) {
+ continue;
+ }
+ MeshModelClass * model = group.Model;
+ if (model->ShadowSkinSourceOffset < 0 || model->ShadowSkinSourceGeneration != generation) {
+ const int vertex_count = model->Get_Vertex_Count();
+ const Vector3 * positions = model->Get_Vertex_Array();
+ const uint16 * bones = model->Get_Vertex_Bone_Links();
+ _ShadowSkinVertices.resize(vertex_count);
+ for (int vertex = 0; vertex < vertex_count; ++vertex) {
+ _ShadowSkinVertices[vertex].Position[0] = positions[vertex].X;
+ _ShadowSkinVertices[vertex].Position[1] = positions[vertex].Y;
+ _ShadowSkinVertices[vertex].Position[2] = positions[vertex].Z;
+ _ShadowSkinVertices[vertex].Bone = bones[vertex];
+ }
+ unsigned first_vertex = 0;
+ uploaded = Direct3D11_Upload_Shadow_Skin(&_ShadowSkinVertices[0], (unsigned)vertex_count, first_vertex);
+ model->ShadowSkinSourceOffset = uploaded ? (int)first_vertex : -1;
+ model->ShadowSkinSourceGeneration = Direct3D11_Shadow_Skin_Generation();
+ placed = model->ShadowSkinSourceGeneration == generation;
+ }
+ group.BaseVertex = (unsigned)model->ShadowSkinSourceOffset;
+ }
+ }
+
+ // The instances one group after another, a counting sort by group.
+ const unsigned count = (unsigned)_ShadowCasterInstances.size();
+ unsigned next = 0;
+ for (size_t index = 0; index < _ShadowCasterGroups.size(); ++index) {
+ ShadowCasterGroup & group = _ShadowCasterGroups[index];
+ group.FirstInstance = next;
+ next += group.InstanceCount;
+ group.InstanceCount = 0;
+ }
+ _ShadowCasterOrdered.resize(count);
+ _ShadowCasterWorlds.resize(count);
+ _ShadowCasterFirstBones.resize(count);
+ for (unsigned index = 0; index < count; ++index) {
+ const ShadowCasterInstance & instance = _ShadowCasterInstances[index];
+ ShadowCasterGroup & group = _ShadowCasterGroups[instance.Group];
+ const unsigned slot = group.FirstInstance + group.InstanceCount++;
+ _ShadowCasterOrdered[slot] = instance.Mesh;
+ _ShadowCasterWorlds[slot] = instance.World;
+ _ShadowCasterFirstBones[slot] = instance.FirstBone;
+ }
+
+ /* A run a piece of a model over all its instances, ordered by the texture an alpha tested one
+ tests against (none first), then by kind, cull, depth test and vertex buffer so the binds and
+ states change least. */
+ const unsigned long cull = ShaderClass::Is_Backface_Culling_Inverted() ? D3DCULL_CCW : D3DCULL_CW;
+ _ShadowCasterRunEntries.clear();
+ for (size_t index = 0; index < _ShadowCasterGroups.size(); ++index) {
+ const ShadowCasterGroup & group = _ShadowCasterGroups[index];
+ for (unsigned piece_index = group.FirstPiece; piece_index < group.FirstPiece + group.PieceCount; ++piece_index) {
+ const ShadowCasterPiece & piece = _ShadowCasterPieces[piece_index];
+ ShadowCasterRunEntry entry;
+ entry.Texture = piece.Texture;
+ entry.Piece = piece_index;
+ DX11ShadowCasterRun & run = entry.Run;
+ run.Kind = piece.Kind;
+ run.Vertices = piece.Vertices;
+ run.Stride = piece.Stride;
+ run.TextureOffset = piece.TextureOffset;
+ run.Indices = piece.Indices;
+ run.StartIndex = piece.StartIndex;
+ run.IndexCount = piece.IndexCount;
+ run.BaseVertex = group.BaseVertex;
+ run.Strip = piece.Strip;
+ run.CullMode = piece.Culled ? cull : D3DCULL_NONE;
+ run.DepthFunction = piece.DepthFunction;
+ run.FirstInstance = group.FirstInstance;
+ run.InstanceCount = group.InstanceCount;
+ _ShadowCasterRunEntries.push_back(entry);
+ }
+ }
+ std::sort(_ShadowCasterRunEntries.begin(), _ShadowCasterRunEntries.end(),
+ [](const ShadowCasterRunEntry & left, const ShadowCasterRunEntry & right) {
+ return std::make_tuple(left.Texture, (int)left.Run.Kind, left.Run.CullMode, left.Run.DepthFunction, left.Run.Vertices)
+ < std::make_tuple(right.Texture, (int)right.Run.Kind, right.Run.CullMode, right.Run.DepthFunction, right.Run.Vertices);
+ });
+ _ShadowCasterRuns.resize(_ShadowCasterRunEntries.size());
+ _ShadowCasterRunPieces.resize(_ShadowCasterRunEntries.size());
+ for (size_t index = 0; index < _ShadowCasterRunEntries.size(); ++index) {
+ _ShadowCasterRuns[index] = _ShadowCasterRunEntries[index].Run;
+ _ShadowCasterRunPieces[index] = _ShadowCasterRunEntries[index].Piece;
+ }
+
+ if (uploaded && Direct3D11_Upload_Shadow_Casters(&_ShadowCasterWorlds[0], &_ShadowCasterFirstBones[0], count,
+ _ShadowCasterBones.empty() ? NULL : &_ShadowCasterBones[0], (unsigned)_ShadowCasterBones.size())) {
+ // A texture's runs at a time, the opaque and skinned ones (no texture) first: an alpha tested
+ // run's texture goes on stage 0 through the wrapper, as the texture category's walk sets it,
+ // so the backend samples it with the filter and addressing that walk would have given it.
+ size_t begin = 0;
+ while (begin < _ShadowCasterRuns.size()) {
+ TextureClass * texture = _ShadowCasterRunEntries[begin].Texture;
+ size_t end = begin + 1;
+ while (end < _ShadowCasterRuns.size() && _ShadowCasterRunEntries[end].Texture == texture) {
+ ++end;
+ }
+ if (texture != NULL) {
+ DX8Wrapper::Set_Texture(0, texture);
+ DX8Wrapper::Apply_Render_State_Changes();
+ }
+ if (Direct3D11_Draw_Shadow_Casters(&_ShadowCasterRuns[begin], (unsigned)(end - begin))) {
+ for (size_t run = begin; run < end; ++run) {
+ const DX11ShadowCasterRun & drawn = _ShadowCasterRuns[run];
+ ++Shadow_Lean_Draws;
+ Shadow_Lean_Instances += (int)drawn.InstanceCount;
+ Shadow_Lean_Alpha_Tested += (drawn.Kind == DX11_SHADOW_CASTER_ALPHA_TESTED) ? (int)drawn.InstanceCount : 0;
+ Shadow_Lean_Skinned += (drawn.Kind == DX11_SHADOW_CASTER_SKINNED) ? (int)drawn.InstanceCount : 0;
+ }
+ } else {
+ // No texture to test against on stage 0: those pieces go to their texture category.
+ for (size_t run = begin; run < end; ++run) {
+ const DX11ShadowCasterRun & refused = _ShadowCasterRuns[run];
+ DX8PolygonRendererClass * renderer = _ShadowCasterPieces[_ShadowCasterRunPieces[run]].Renderer;
+ for (unsigned instance = 0; instance < refused.InstanceCount; ++instance) {
+ renderer->Get_Texture_Category()->Add_Render_Task(renderer,
+ _ShadowCasterOrdered[refused.FirstInstance + instance]);
+ ++Shadow_Old_Meshes[SHADOW_OLD_REFUSED];
+ }
+ }
+ }
+ begin = end;
+ }
+ } else {
+ // The backend would not draw them (a program or a buffer refused): every piece of every mesh
+ // taken goes to its texture category, and a skin to its container's fill, as it would have
+ // without this.
+ for (size_t index = 0; index < _ShadowCasterInstances.size(); ++index) {
+ MeshClass * mesh = _ShadowCasterInstances[index].Mesh;
+ MeshModelClass * model = mesh->Peek_Model();
+ DX8PolygonRendererListIterator it(&(model->PolygonRendererList));
+ for (; !it.Is_Done(); it.Next()) {
+ it.Peek_Obj()->Get_Texture_Category()->Add_Render_Task(it.Peek_Obj(), mesh);
+ }
+ if (model->Get_Flag(MeshGeometryClass::SKIN)) {
+ DX8FVFCategoryContainer * container = model->PolygonRendererList.Peek_Head()->Get_Texture_Category()->Get_Container();
+ static_cast<DX8SkinFVFCategoryContainer *>(container)->Add_Visible_Skin(mesh);
+ }
+ ++Shadow_Old_Meshes[SHADOW_OLD_REFUSED];
+ }
+ }
+
+ for (size_t index = 0; index < _ShadowCasterInstances.size(); ++index) {
+ _ShadowCasterInstances[index].Mesh->Release_Ref();
+ }
+ Clear_Shadow_Casters();
+}
+
void DX8MeshRendererClass::Flush(void)
{
int i;
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8renderer.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8renderer.h
index db6f60ec8..ab718c49f 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8renderer.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8renderer.h
@@ -126,6 +126,7 @@ public:
// Force multiply blend on all objects inserted from now on. (Doesn't affect the objects that are already in the lists)
static void SetForceMultiply(bool multiply) { m_gForceMultiply=multiply; }
+ static bool Is_Force_Multiply() { return m_gForceMultiply; }
};
@@ -212,7 +213,8 @@ public:
virtual bool Check_If_Mesh_Fits(MeshModelClass* mmc)=0;
inline unsigned Get_FVF() const { return FVF; }
-
+ IndexBufferClass * Peek_Index_Buffer() const { return index_buffer; }
+
inline void Add_Visible_Texture_Category(DX8TextureCategoryClass * tex_category,int pass)
{
WWASSERT(pass<MAX_PASSES);
@@ -258,6 +260,8 @@ public:
virtual void Add_Delayed_Visible_Material_Pass(MaterialPassClass * pass, MeshClass * mesh);
virtual void Render_Delayed_Procedural_Material_Passes(void);
+ VertexBufferClass * Peek_Vertex_Buffer() const { return vertex_buffer; }
+
protected:
@@ -341,6 +345,41 @@ public:
// This should be called at the beginning of a game or menu or after a major modifications to the scene...
void Invalidate(bool shutdown=false); // Added flag so it doesn't allocate more mem when shutting down. -MW
+ /* The sun's depth pass on Direct3D 11 (MeshClass::Shadow_Lean_Casters). Add_Shadow_Caster takes
+ an opaque mesh's base pass (rigid, alpha tested or a skin, which is skinned on the GPU) for an
+ instanced depth-only draw and answers true, or answers false having taken nothing, and the
+ mesh goes to its texture categories as before; a skin with material passes to draw stays
+ there. Flush_Shadow_Casters draws what was taken, sorted so each piece of each model is one
+ draw however many of it stand in the sun's box; it runs before Flush. The counts are the
+ pass's, zeroed by Reset_Shadow_Caster_Counts: draws and instances of each kind, and the
+ meshes left to the old way by the first reason each failed on. */
+ enum ShadowOldReason
+ {
+ SHADOW_OLD_SORTED,
+ SHADOW_OLD_CAMERA_FACING,
+ SHADOW_OLD_DRAW_EFFECT,
+ SHADOW_OLD_FADING,
+ SHADOW_OLD_DEBUG,
+ SHADOW_OLD_STREAMING,
+ SHADOW_OLD_SKIN_PASSES,
+ SHADOW_OLD_BLENDED,
+ SHADOW_OLD_ALPHA_TEST,
+ SHADOW_OLD_SKIN_ALPHA_TEST,
+ SHADOW_OLD_FORMAT,
+ SHADOW_OLD_NO_BASE_PASS,
+ SHADOW_OLD_REFUSED,
+ SHADOW_OLD_REASON_COUNT
+ };
+ bool Add_Shadow_Caster(MeshClass * mesh, bool has_material_passes);
+ void Flush_Shadow_Casters();
+ static void Reset_Shadow_Caster_Counts();
+ static const char * Shadow_Old_Reason_Name(int reason);
+ static int Shadow_Lean_Draws;
+ static int Shadow_Lean_Instances;
+ static int Shadow_Lean_Alpha_Tested;
+ static int Shadow_Lean_Skinned;
+ static int Shadow_Old_Meshes[SHADOW_OLD_REASON_COUNT];
+
protected:
void Render_Decal_Meshes(void);
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hlod.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hlod.cpp
index 1310c9095..dd898455f 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hlod.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hlod.cpp
@@ -2224,7 +2224,14 @@ void HLodClass::Special_Render(SpecialRenderInfoClass & rinfo)
*=============================================================================================*/
void HLodClass::Set_Transform(const Matrix3D &m)
{
- Animatable3DObjClass::Set_Transform(m);
+ // W3DModelDraw hands every model its drawable's transform each draw, and a building standing in its
+ // base pose got the same bits back and posed its whole skeleton again: Base_Update writes the same
+ // bones from the same root, so a pose still current is kept. Bitwise, so not even a zero's sign
+ // differs. An animated model always takes the call, since its clock moves at the next pose.
+ if (CurMotionMode == BASE_POSE && Is_Hierarchy_Valid() && !Are_Sub_Object_Transforms_Dirty()
+ && memcmp(&m, &Transform, sizeof(Matrix3D)) == 0)
+ return;
+ Animatable3DObjClass::Set_Transform(m);
Set_Sub_Object_Transforms_Dirty(true);
}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hmorphanim.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hmorphanim.cpp
index ee132d544..b767be45a 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hmorphanim.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hmorphanim.cpp
@@ -121,33 +121,37 @@ void TimeCodedMorphKeysClass::Get_Morph_Info(float morph_frame,int * pose_frame0
uint32 TimeCodedMorphKeysClass::get_index(float frame)
{
- assert(CachedIdx <= (uint32)Keys.Count ()-1);
+ // the hint is read once and written whole: any index it holds finds the same interval
+ uint32 idx = CachedIdx.load(std::memory_order_relaxed);
+ assert(idx <= (uint32)Keys.Count ()-1);
- float cached_frame = Keys[CachedIdx].MorphFrame;
+ float cached_frame = Keys[idx].MorphFrame;
// check if the requested time is in the cached interval or the following one
if (frame >= cached_frame) {
// special case for end packets
- if (CachedIdx == (uint32)Keys.Count ()-1) return(CachedIdx);
-
+ if (idx == (uint32)Keys.Count ()-1) return(idx);
+
// check if the requested time is still in the cached interval
- if (frame < Keys[CachedIdx + 1].MorphFrame) return(CachedIdx);
+ if (frame < Keys[idx + 1].MorphFrame) return(idx);
// do one time look-ahead before reverting to a search
- CachedIdx++;
-
+ idx++;
+ CachedIdx.store(idx, std::memory_order_relaxed);
+
// again, special case the end interval
- if (CachedIdx == (uint32)Keys.Count ()-1) return(CachedIdx);
+ if (idx == (uint32)Keys.Count ()-1) return(idx);
// check if requested time is in this interval
- if (frame < Keys[CachedIdx + 1].MorphFrame) return(CachedIdx);
+ if (frame < Keys[idx + 1].MorphFrame) return(idx);
}
// nope, fall back to a binary search for the requested interval
- CachedIdx = binary_search_index(frame);
+ idx = binary_search_index(frame);
+ CachedIdx.store(idx, std::memory_order_relaxed);
- return(CachedIdx);
+ return(idx);
}
uint32 TimeCodedMorphKeysClass::binary_search_index(float req_frame)
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hmorphanim.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hmorphanim.h
index f6ae698b9..79872ec40 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hmorphanim.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/hmorphanim.h
@@ -15,6 +15,7 @@
** You should have received a copy of the GNU General Public License
** along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
+// Modified 2025-2026 by Olcay Seygan for Zero Hour Reforged; see the git history.
/***********************************************************************************************
*** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S ***
@@ -46,6 +47,7 @@
#include "always.h"
#include "hanim.h"
#include "simplevec.h"
+#include <atomic>
class TimeCodedMorphKeysClass;
class ChunkLoadClass;
@@ -175,7 +177,7 @@ private:
};
SimpleDynVecClass<MorphKeyStruct> Keys; // morph key data
- uint32 CachedIdx; // last accessed index
+ std::atomic<uint32> CachedIdx; // last accessed index: a hint shared across threads, as in motchan.h
void Free(void);
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/htree.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/htree.cpp
index b085e8df9..d11248f71 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/htree.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/htree.cpp
@@ -815,13 +815,16 @@ void HTreeClass::Combo_Update
int anim_num;
for ( anim_num = 0; anim_num < anim->Get_Num_Anims(); anim_num++ ) {
- HAnimClass *motion = anim->Get_Motion( anim_num );
+ // Peeked, not got: the motion and the map are shared by every object playing them, and
+ // their reference counts are plain ints the sun's shadow pass would race on while it
+ // poses casters on several threads.
+ HAnimClass *motion = anim->Peek_Motion( anim_num );
if ( motion != NULL ) {
float frame_num = anim->Get_Frame( anim_num );
- PivotMapClass * pivot_map = anim->Get_Pivot_Weight_Map( anim_num );
+ PivotMapClass * pivot_map = anim->Peek_Pivot_Weight_Map( anim_num );
//float *pivot_map = anim->Get_Pivot_Weight_Map( anim_num );
@@ -829,9 +832,6 @@ void HTreeClass::Combo_Update
if ( pivot_map != NULL ) {
weight *= (*pivot_map)[piv_idx];
- // GREG - Pivot maps are ref counted so shouldn't we
- // release the rivot map here?
- pivot_map->Release_Ref();
}
if ( weight != 0.0 ) {
@@ -856,8 +856,6 @@ void HTreeClass::Combo_Update
#endif
}
- motion->Release_Ref();
-
}
}
@@ -892,13 +890,11 @@ void HTreeClass::Combo_Update
pivot->IsVisible = false;
for ( anim_num = 0; (anim_num < anim->Get_Num_Anims()) && (!pivot->IsVisible); anim_num++ ) {
- HAnimClass *motion = anim->Get_Motion( anim_num );
+ HAnimClass *motion = anim->Peek_Motion( anim_num );
if ( motion != NULL ) {
float frame_num = anim->Get_Frame( anim_num );
pivot->IsVisible |= motion->Get_Visibility(piv_idx,frame_num);
-
- motion->Release_Ref();
}
}
}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/mesh.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/mesh.cpp
index a99e99c60..8aa79404e 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/mesh.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/mesh.cpp
@@ -126,6 +126,7 @@ static unsigned MeshDebugIdCount;
bool MeshClass::Legacy_Meshes_Fogged = true;
int MeshClass::Shadow_Pass_Light_Meshes = 0;
+bool MeshClass::Shadow_Lean_Casters = false;
static SimpleDynVecClass<uint32> temp_apt;
/*
@@ -662,6 +663,13 @@ int MeshClass::Get_Num_Polys(void) const
* HISTORY: *
* 12/10/98 GTH : Created. *
*=============================================================================================*/
+/* The FVF container a mesh's model is in, looked up only where it is used: a caster the sun's depth
+ pass takes never reads it, and the walk to it is three loads a mesh. */
+static DX8FVFCategoryContainer * Peek_FVF_Container(DX8PolygonRendererList & renderers)
+{
+ return renderers.Peek_Head()->Get_Texture_Category()->Get_Container();
+}
+
void MeshClass::Render(RenderInfoClass & rinfo)
{
WWPROFILE("Mesh::Render");
@@ -707,8 +715,14 @@ void MeshClass::Render(RenderInfoClass & rinfo)
const FrustumClass & frustum=rinfo.Camera.Get_Frustum();
- if ( Model->Get_Flag(MeshGeometryClass::SKIN) ||
- CollisionMath::Overlap_Test(frustum,Get_Bounding_Box())!=CollisionMath::OUTSIDE )
+ /*
+ ** The sun's depth pass puts the frustum test off until it knows the mesh goes the old way: a
+ ** lean caster is drawn whole and the clipping drops what lies outside the sun's box, the
+ ** same depth the test would have left, without bringing its bounds up to date after every
+ ** pose.
+ */
+ if ( Model->Get_Flag(MeshGeometryClass::SKIN) || Shadow_Lean_Casters ||
+ CollisionMath::Overlap_Test(frustum,Get_Bounding_Box())!=CollisionMath::OUTSIDE )
{
bool rendered_something = false;
@@ -738,11 +752,6 @@ void MeshClass::Render(RenderInfoClass & rinfo)
*/
// Model->Process_Texture_Reduction();
- /*
- ** Look up the FVF container that this mesh is in
- */
- DX8FVFCategoryContainer * fvf_container = Model->PolygonRendererList.Peek_Head()->Get_Texture_Category()->Get_Container();
-
/*
** Check if we should render the base passes. One special case here: if
** the mesh is translucent (alpha) and the base passes are disabled but we
@@ -759,16 +768,26 @@ void MeshClass::Render(RenderInfoClass & rinfo)
render_base_passes = true;
}
+ const bool lean_caster = render_base_passes && Shadow_Lean_Casters
+ && TheDX8MeshRenderer.Add_Shadow_Caster(this, rinfo.Additional_Pass_Count() != 0);
+ if (Shadow_Lean_Casters && !lean_caster && !Model->Get_Flag(MeshGeometryClass::SKIN)
+ && CollisionMath::Overlap_Test(frustum,Get_Bounding_Box())==CollisionMath::OUTSIDE) {
+ return;
+ }
+
if (render_base_passes) {
/*
- ** Link each polygon renderer for this mesh into the visible list
+ ** Link each polygon renderer for this mesh into the visible list, unless the sun's
+ ** depth pass takes the mesh as an instanced caster.
*/
- DX8PolygonRendererListIterator it(&(Model->PolygonRendererList));
- while (!it.Is_Done()) {
- DX8PolygonRendererClass* polygon_renderer=it.Peek_Obj();
- polygon_renderer->Get_Texture_Category()->Add_Render_Task(polygon_renderer,this);
- it.Next();
+ if (!lean_caster) {
+ DX8PolygonRendererListIterator it(&(Model->PolygonRendererList));
+ while (!it.Is_Done()) {
+ DX8PolygonRendererClass* polygon_renderer=it.Peek_Obj();
+ polygon_renderer->Get_Texture_Category()->Add_Render_Task(polygon_renderer,this);
+ it.Next();
+ }
}
rendered_something = true;
@@ -780,8 +799,9 @@ void MeshClass::Render(RenderInfoClass & rinfo)
** for rendering
*/
for (int i=0; i<rinfo.Additional_Pass_Count(); i++) {
-
+
MaterialPassClass * matpass = rinfo.Peek_Additional_Pass(i);
+ DX8FVFCategoryContainer * fvf_container = Peek_FVF_Container(Model->PolygonRendererList);
if ((!Is_Translucent()) || (matpass->Is_Enabled_On_Translucent_Meshes())) {
@@ -800,11 +820,12 @@ void MeshClass::Render(RenderInfoClass & rinfo)
/*
** If we rendered any base or procedural passes and this is a skin, we need
- ** to tell the mesh rendering system to process this skin
+ ** to tell the mesh rendering system to process this skin. A skin the sun's depth pass
+ ** took is skinned on the GPU and has nothing in the container to fill.
*/
- if (rendered_something && Model->Get_Flag(MeshGeometryClass::SKIN)) {
+ if (rendered_something && !lean_caster && Model->Get_Flag(MeshGeometryClass::SKIN)) {
//WWASSERT(dynamic_cast<DX8SkinFVFCategoryContainer *>(fvf_container) != NULL);
- static_cast<DX8SkinFVFCategoryContainer*>(fvf_container)->Add_Visible_Skin(this);
+ static_cast<DX8SkinFVFCategoryContainer*>(Peek_FVF_Container(Model->PolygonRendererList))->Add_Visible_Skin(this);
}
/*
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/mesh.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/mesh.h
index 578ec7794..dc2686419 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/mesh.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/mesh.h
@@ -162,6 +162,10 @@ public:
// Meshes a shadow pass left out as light rather than matter, counted until the caller resets it.
static int Shadow_Pass_Light_Meshes;
+ // Set by the sun's depth pass while a Direct3D 11 map is bound: an opaque rigid mesh's base
+ // pass goes to DX8MeshRendererClass::Add_Shadow_Caster rather than to its texture categories.
+ static bool Shadow_Lean_Casters;
+
void Replace_Texture(TextureClass* texture,TextureClass* new_texture);
void Replace_VertexMaterial(VertexMaterialClass* vmat,VertexMaterialClass* new_vmat);
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/meshmdl.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/meshmdl.cpp
index 73adcc622..cf7d26dc9 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/meshmdl.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/meshmdl.cpp
@@ -74,7 +74,11 @@ MeshModelClass::MeshModelClass(void) :
AlternateMatDesc(NULL),
CurMatDesc(NULL),
MatInfo(NULL),
- GapFiller(NULL)
+ GapFiller(NULL),
+ ShadowSkinSourceOffset(-1),
+ ShadowSkinSourceGeneration(0),
+ ShadowCasterPass(0),
+ ShadowCasterGroup(-1)
{
Set_Flag(DIRTY_BOUNDS,true);
@@ -93,7 +97,11 @@ MeshModelClass::MeshModelClass(const MeshModelClass & that) :
CurMatDesc(NULL),
MatInfo(NULL),
GapFiller(NULL),
- HasBeenInUse(false)
+ HasBeenInUse(false),
+ ShadowSkinSourceOffset(-1),
+ ShadowSkinSourceGeneration(0),
+ ShadowCasterPass(0),
+ ShadowCasterGroup(-1)
{
DefMatDesc = W3DNEW MeshMatDescClass(*(that.DefMatDesc));
if (that.AlternateMatDesc != NULL) {
@@ -151,6 +159,7 @@ MeshModelClass & MeshModelClass::operator = (const MeshModelClass & that)
GapFiller=NULL;
}
if (that.GapFiller) GapFiller=W3DNEW GapFillerClass(*that.GapFiller);
+ ShadowSkinSourceOffset=-1;
}
return * this;
}
@@ -167,6 +176,7 @@ void MeshModelClass::Reset(int polycount,int vertcount,int passcount)
// Release everything we have and reset to initial state
TheDX8MeshRenderer.Unregister_Mesh_Type(this);
+ ShadowSkinSourceOffset=-1;
MatInfo->Reset();
DefMatDesc->Reset(polycount,vertcount,passcount);
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/meshmdl.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/meshmdl.h
index 3ceec6fbe..a3e3282f5 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/meshmdl.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/meshmdl.h
@@ -339,6 +339,17 @@ protected:
GapFillerClass * GapFiller;
bool HasBeenInUse; // For debugging purposes!
+ // A skin's bind pose and bone links in the Direct3D 11 backend's shadow skin source, for the
+ // sun's depth pass to skin on the GPU: the first vertex there, -1 before an upload, and the
+ // generation of the buffer it went into (the backend starts a new one when it fills or is reset).
+ int ShadowSkinSourceOffset;
+ unsigned ShadowSkinSourceGeneration;
+ // The depth pass this model's pieces were last worked out in (DX8MeshRendererClass::
+ // Add_Shadow_Caster), and the result: its group of instances in that pass, or -1 less the reason
+ // it goes the old way. Worked out again every pass, so nothing about the model can go stale.
+ unsigned ShadowCasterPass;
+ int ShadowCasterGroup;
+
friend class MeshClass;
friend class MeshDeformSetClass;
friend class MeshDeformClass;
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/motchan.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/motchan.cpp
index ba32b31b8..0204a3d04 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/motchan.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/motchan.cpp
@@ -624,31 +624,34 @@ uint32 TimeCodedMotionChannelClass::binary_search_index(uint32 timecode)
* 01/27/2000 JGA : Created. *
*=============================================================================================*/
uint32 TimeCodedMotionChannelClass::get_index(uint32 timecode)
-{
- assert(CachedIdx <= LastTimeCodeIdx);
+{
+ uint32 idx = CachedIdx.load( std::memory_order_relaxed );
+ assert(idx <= LastTimeCodeIdx);
uint32 time;
- time = Data[CachedIdx] & ~W3D_TIMECODED_BINARY_MOVEMENT_FLAG;
+ time = Data[idx] & ~W3D_TIMECODED_BINARY_MOVEMENT_FLAG;
if (timecode >= time) {
// possibly in the current packet
// special case for end packets
- if (CachedIdx == LastTimeCodeIdx) return(CachedIdx);
- time = Data[CachedIdx + PacketSize] & ~W3D_TIMECODED_BINARY_MOVEMENT_FLAG;
- if (timecode < time) return(CachedIdx);
+ if (idx == LastTimeCodeIdx) return(idx);
+ time = Data[idx + PacketSize] & ~W3D_TIMECODED_BINARY_MOVEMENT_FLAG;
+ if (timecode < time) return(idx);
// Do one time look-ahead before reverting to a search
- CachedIdx+=PacketSize;
- if (CachedIdx == LastTimeCodeIdx) return(CachedIdx);
- time = Data[CachedIdx + PacketSize] & ~W3D_TIMECODED_BINARY_MOVEMENT_FLAG;
- if (timecode < time) return(CachedIdx);
+ idx+=PacketSize;
+ CachedIdx.store( idx, std::memory_order_relaxed );
+ if (idx == LastTimeCodeIdx) return(idx);
+ time = Data[idx + PacketSize] & ~W3D_TIMECODED_BINARY_MOVEMENT_FLAG;
+ if (timecode < time) return(idx);
}
- CachedIdx = binary_search_index( timecode );
+ idx = binary_search_index( timecode );
+ CachedIdx.store( idx, std::memory_order_relaxed );
- return(CachedIdx);
+ return(idx);
} // get_index
@@ -804,19 +807,20 @@ bool TimeCodedBitChannelClass::Load_W3D(ChunkLoadClass & cload)
*=============================================================================================*/
int TimeCodedBitChannelClass::Get_Bit(int frame)
{
- assert(frame >= 0);
- assert(CachedIdx < NumTimeCodes);
+ assert(frame >= 0);
+ const uint32 cached = CachedIdx.load( std::memory_order_relaxed );
+ assert(cached < NumTimeCodes);
int time;
int idx=0;
- time = Bits[CachedIdx] & ~W3D_TIMECODED_BIT_MASK;
+ time = Bits[cached] & ~W3D_TIMECODED_BIT_MASK;
+
-
if (frame >= time) {
-
+
// start from here
- idx = CachedIdx+1;
+ idx = cached+1;
}
@@ -832,7 +836,7 @@ int TimeCodedBitChannelClass::Get_Bit(int frame)
if (idx < 0) idx = 0;
- CachedIdx = idx;
+ CachedIdx.store( (uint32)idx, std::memory_order_relaxed );
return (((Bits[idx] & W3D_TIMECODED_BIT_MASK) == W3D_TIMECODED_BIT_MASK));
@@ -988,9 +992,11 @@ void AdaptiveDeltaMotionChannelClass::decompress(uint32 frame_idx, float *outdat
// Start Over from the beginning
float *base = (float *) &Data[0]; // pointer to our true know beginning values
- bool done = false;
-
for(int vi=0; vi<VectorLen; vi++) {
+ // Per component: set once for the whole vector, it stopped every component after the first at
+ // the end of its first packet, so a quaternion past frame 16 came out of whichever way the
+ // shared cache last reached it
+ bool done = false;
// Decompress all the vector indices, since they will probably all be needed
unsigned char *pPacket = (unsigned char *) Data; // pointer to current packet
pPacket+= (sizeof(float) * VectorLen); // skip non-compressed header information
@@ -1065,9 +1071,8 @@ void AdaptiveDeltaMotionChannelClass::decompress(uint32 src_idx, float *srcdata,
float *base = (float *) &Data[0]; // pointer to our true know beginning values
base += VectorLen; // skip header information
- bool done = false;
-
for(int vi=0; vi<VectorLen; vi++) {
+ bool done = false; // per component, as in the decompress above
// Decompress all the vector indices, since they will probably all be needed
unsigned char *pPacket = (unsigned char *) base; // pointer to current packet
pPacket+= PACKET_SIZE * vi; // skip to the appropriate packet start
@@ -1201,8 +1206,10 @@ float AdaptiveDeltaMotionChannelClass::getframe(uint32 frame_idx, uint32 vector_
float temp[4];
memcpy(&temp[0], &CacheData[VectorLen], VectorLen * sizeof(float));
-
- decompress(CacheFrame, &temp[0], frame_idx, &CacheData[0]);
+
+ // temp holds CacheFrame+1, so the deltas start after it: from CacheFrame they added that frame's
+ // twice, and the answer depended on where the shared cache last stood
+ decompress(CacheFrame + 1, &temp[0], frame_idx, &CacheData[0]);
CacheFrame = frame_idx;
if (frame_idx != (NumFrames - 1)) {
@@ -1229,9 +1236,10 @@ void AdaptiveDeltaMotionChannelClass::Get_Vector(float32 frame,float * setvec)
{
uint32 frame1 = frame;
-
+
float ratio = frame - frame1;
+ FastCriticalSectionClass::LockClass lock( CacheLock );
float value1 = getframe(frame1);
float value2 = getframe(frame1 + 1);
@@ -1251,6 +1259,7 @@ Quaternion AdaptiveDeltaMotionChannelClass::Get_QuatVector(float32 frame)
uint32 frame2 = frame1+1;
float ratio = frame - frame1;
+ FastCriticalSectionClass::LockClass lock( CacheLock );
Quaternion q1(1);
q1.Set( getframe(frame1, 0),
getframe(frame1, 1),
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/motchan.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/motchan.h
index a1982baa5..93c3435e2 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/motchan.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/motchan.h
@@ -15,6 +15,7 @@
** You should have received a copy of the GNU General Public License
** along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
+// Modified 2025-2026 by Olcay Seygan for Zero Hour Reforged; see the git history.
/* $Header: /Commando/Code/ww3d2/motchan.h 5 11/29/01 1:07p Jani_p $ */
/***********************************************************************************************
@@ -47,6 +48,8 @@
#include "bittype.h"
#include "w3d_file.h"
#include "quat.h"
+#include "mutex.h"
+#include <atomic>
class ChunkLoadClass;
class Quaternion;
@@ -240,7 +243,10 @@ private:
uint32 NumTimeCodes; // Number of packets
uint32 LastTimeCodeIdx; // absolute index to last time code
- uint32 CachedIdx; // Last Index Used
+ // Last index used: a hint where the search starts, shared by every object playing this
+ // animation, which the sun's shadow pass poses on several threads. Any packet index it holds
+ // finds the same packet, so it is read once and written whole.
+ std::atomic<uint32> CachedIdx;
uint32 * Data; // pointer to packet data
@@ -282,6 +288,7 @@ private:
uint32 CacheFrame;
float *CacheData; // the data for CachedFrame, and CachedFrame+1, x VectorLen
+ FastCriticalSectionClass CacheLock; // the cache is shared by every object playing this animation
void Free(void);
@@ -322,7 +329,7 @@ private:
int DefaultVal;
uint32 NumTimeCodes;
- uint32 CachedIdx;
+ std::atomic<uint32> CachedIdx; // a shared hint, as TimeCodedMotionChannelClass's
uint32 *Bits;
diff --git a/GeneralsMD/Code/Tests/test_dx11backend.cpp b/GeneralsMD/Code/Tests/test_dx11backend.cpp
index 8a1350c2a..5f4f49749 100644
--- a/GeneralsMD/Code/Tests/test_dx11backend.cpp
+++ b/GeneralsMD/Code/Tests/test_dx11backend.cpp
@@ -1261,6 +1261,330 @@ TEST(dx11backend_the_smoke_map_holds_each_casters_three_sums)
backend.Shutdown();
}
+// The sun's depth map read back as its 24-bit depths, one a texel.
+static void read_shadow_depths(DX11DeviceClass & device, DX11BackendClass & backend,
+ std::vector<unsigned> & depths)
+{
+ ID3D11Resource * resource = NULL;
+ backend.Shadow_Map()->GetResource(&resource);
+ ID3D11Texture2D * texture = static_cast<ID3D11Texture2D *>(resource);
+ D3D11_TEXTURE2D_DESC description;
+ texture->GetDesc(&description);
+ description.Usage = D3D11_USAGE_STAGING;
+ description.BindFlags = 0;
+ description.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
+ ID3D11Texture2D * staging = NULL;
+ CHECK(SUCCEEDED(device.Get_Device()->CreateTexture2D(&description, NULL, &staging)));
+ device.Get_Context()->CopyResource(staging, texture);
+ D3D11_MAPPED_SUBRESOURCE mapped;
+ CHECK(SUCCEEDED(device.Get_Context()->Map(staging, 0, D3D11_MAP_READ, 0, &mapped)));
+ depths.resize(description.Width * description.Height);
+ for (unsigned y = 0; y < description.Height; ++y) {
+ const unsigned * row = reinterpret_cast<const unsigned *>(
+ static_cast<const unsigned char *>(mapped.pData) + mapped.RowPitch * y);
+ for (unsigned x = 0; x < description.Width; ++x) {
+ depths[y * description.Width + x] = row[x] & 0x00ffffff;
+ }
+ }
+ device.Get_Context()->Unmap(staging, 0);
+ staging->Release();
+ resource->Release();
+}
+
+// The instanced depth-only casters (Draw_Shadow_Casters) have to leave the sun's map holding the
+// depth the generated programs leave in it for the same mesh drawn once a copy, to the bit: a
+// mesh drawn twice, turned and moved, and tilted in depth so every texel's value is its own.
+TEST(dx11backend_instanced_shadow_casters_write_the_depth_the_old_draws_write)
+{
+ DX11DeviceClass device;
+ CHECK(device.Create_Offscreen());
+ ID3D11Device * d3d = device.Get_Device();
+
+ DX11BackendClass backend;
+ CHECK(backend.Initialise(&device));
+ configure_unlit_pass_through(backend);
+
+ // The sun's box: x and y across four units, depth over ten.
+ float sun[16];
+ set_identity(sun);
+ sun[0] = 0.5f;
+ sun[5] = 0.5f;
+ sun[10] = 0.1f;
+ backend.Set_Transform(D3DTS_PROJECTION, sun);
+
+ // Two copies of the mesh, turned by different angles and moved, in Direct3D 9's layout.
+ float worlds[2][16];
+ const float angles[2] = { 0.5236f, -1.1f };
+ const float moves[2][3] = { { 0.3f, -0.2f, 2.75f }, { -0.45f, 0.35f, 3.1f } };
+ for (unsigned copy = 0; copy < 2; ++copy) {
+ set_identity(worlds[copy]);
+ worlds[copy][0] = cosf(angles[copy]);
+ worlds[copy][1] = sinf(angles[copy]);
+ worlds[copy][4] = -sinf(angles[copy]);
+ worlds[copy][5] = cosf(angles[copy]);
+ worlds[copy][12] = moves[copy][0];
+ worlds[copy][13] = moves[copy][1];
+ worlds[copy][14] = moves[copy][2];
+ }
+
+ // The quad, tilted from front to back.
+ BackendVertex vertices_data[4];
+ memcpy(vertices_data, QUAD_VERTICES, sizeof(vertices_data));
+ const float depths_at[4] = { 0.37f, 1.91f, 4.13f, 2.59f };
+ for (unsigned index = 0; index < 4; ++index) {
+ vertices_data[index].Position[0] *= 1.3f;
+ vertices_data[index].Position[1] *= 0.9f;
+ vertices_data[index].Position[2] = depths_at[index];
+ }
+ ID3D11Buffer * vertices = NULL;
+ CHECK(DX11Resource_Create_Vertex_Buffer(d3d, sizeof(vertices_data), D3DPOOL_MANAGED, 0,
+ vertices_data, &vertices));
+ ID3D11Buffer * indices = NULL;
+ CHECK(DX11Resource_Create_Index_Buffer(d3d, sizeof(QUAD_INDICES), D3DPOOL_MANAGED, 0,
+ QUAD_INDICES, &indices));
+
+ // What renderShadowMap sets for the pass, and an opaque mesh's shader: both faces, so the
+ // cull cannot hide a difference.
+ backend.Set_Render_State(D3DRS_COLORWRITEENABLE, 0);
+ backend.Set_Render_State(D3DRS_ZENABLE, D3DZB_TRUE);
+ backend.Set_Render_State(D3DRS_ZWRITEENABLE, TRUE);
+ backend.Set_Render_State(D3DRS_ZFUNC, D3DCMP_LESSEQUAL);
+ backend.Set_Render_State(D3DRS_CULLMODE, D3DCULL_NONE);
+
+ CHECK(backend.Begin_Shadow_Map(64));
+ backend.Set_Stream_Source(vertices, sizeof(BackendVertex), 0);
+ backend.Set_Indices(indices, DXGI_FORMAT_R16_UINT);
+ for (unsigned copy = 0; copy < 2; ++copy) {
+ backend.Set_Transform(D3DTS_WORLD, worlds[copy]);
+ CHECK(backend.Draw_Indexed_Triangles(6, 0, 0));
+ }
+ backend.End_Shadow_Map();
+ std::vector<unsigned> old_depths;
+ read_shadow_depths(device, backend, old_depths);
+
+ // The pass before the instanced one has to have drawn something, or the comparison proves
+ // nothing: some texels near, some still at the far plane.
+ unsigned covered = 0;
+ for (size_t texel = 0; texel < old_depths.size(); ++texel) {
+ if (old_depths[texel] != 0x00ffffff) {
+ ++covered;
+ }
+ }
+ printf(" %u of %u texels covered\n", covered, (unsigned)old_depths.size());
+ CHECK(covered > 0);
+ CHECK(covered < old_depths.size());
+
+ // The instanced draw, with the cull and depth test left somewhere else first: the run's own
+ // have to be the ones it draws with.
+ backend.Set_Render_State(D3DRS_CULLMODE, D3DCULL_CW);
+ backend.Set_Render_State(D3DRS_ZFUNC, D3DCMP_ALWAYS);
+ CHECK(backend.Begin_Shadow_Map(64));
+ DX11BackendClass::ShadowCasterRun run;
+ run.Kind = DX11BackendClass::SHADOW_CASTER_RIGID;
+ run.Vertices = vertices;
+ run.Stride = sizeof(BackendVertex);
+ run.TextureOffset = 0;
+ run.Indices = indices;
+ run.StartIndex = 0;
+ run.IndexCount = 6;
+ run.BaseVertex = 0;
+ run.Strip = false;
+ run.CullMode = D3DCULL_NONE;
+ run.DepthFunction = D3DCMP_LESSEQUAL;
+ run.FirstInstance = 0;
+ run.InstanceCount = 2;
+ // The same worlds as the rows of a Matrix3D, which is what the mesh renderer hands over.
+ float rows[2][12];
+ for (unsigned copy = 0; copy < 2; ++copy) {
+ for (unsigned row = 0; row < 3; ++row) {
+ for (unsigned column = 0; column < 4; ++column) {
+ rows[copy][row * 4 + column] = worlds[copy][column * 4 + row];
+ }
+ }
+ }
+ const float * const instance_rows[2] = { rows[0], rows[1] };
+ const unsigned first_bones[2] = { 0, 0 };
+ CHECK(backend.Upload_Shadow_Casters(instance_rows, first_bones, 2, NULL, 0));
+ CHECK(backend.Draw_Shadow_Casters(&run, 1));
+ backend.End_Shadow_Map();
+ std::vector<unsigned> lean_depths;
+ read_shadow_depths(device, backend, lean_depths);
+
+ CHECK_EQ(lean_depths.size(), old_depths.size());
+ unsigned differing = 0;
+ for (size_t texel = 0; texel < old_depths.size() && texel < lean_depths.size(); ++texel) {
+ if (old_depths[texel] != lean_depths[texel]) {
+ ++differing;
+ }
+ }
+ if (differing != 0) {
+ printf(" %u texels differ\n", differing);
+ }
+ CHECK_EQ(differing, 0u);
+
+ indices->Release();
+ vertices->Release();
+ backend.Shutdown();
+}
+
+// A skin skinned in the depth pass's vertex program has to leave the depth the CPU fill leaves
+// (Matrix3D::Transform_Vector per vertex, then drawn with an identity world), within a level or
+// two of a 24-bit depth for the order the GPU adds the products in: two copies of a quad whose
+// halves hang on two bones, each copy on its own pair of bones.
+TEST(dx11backend_skinned_shadow_casters_write_the_depth_the_cpu_skinned_draws_write)
+{
+ static const unsigned BONES = 4;
+ static const unsigned DEPTH_LEVELS_ALLOWED = 2;
+ static const unsigned EDGE_TEXELS_ALLOWED = 4;
+
+ DX11DeviceClass device;
+ CHECK(device.Create_Offscreen());
+ ID3D11Device * d3d = device.Get_Device();
+
+ DX11BackendClass backend;
+ CHECK(backend.Initialise(&device));
+ configure_unlit_pass_through(backend);
+
+ float sun[16];
+ set_identity(sun);
+ sun[0] = 0.5f;
+ sun[5] = 0.5f;
+ sun[10] = 0.1f;
+ backend.Set_Transform(D3DTS_PROJECTION, sun);
+
+ // Four bones, three rows of a Matrix3D each: turned about z, tipped about x, moved.
+ float bone_rows[BONES][12];
+ const float turns[BONES] = { 0.4f, -0.7f, 1.3f, 0.15f };
+ const float tips[BONES] = { 0.2f, -0.35f, 0.1f, 0.45f };
+ const float moves[BONES][3] = {
+ { 0.2f, -0.1f, 3.0f }, { -0.3f, 0.25f, 2.2f }, { 0.35f, 0.3f, 4.1f }, { -0.2f, -0.4f, 1.7f } };
+ for (unsigned bone = 0; bone < BONES; ++bone) {
+ const float c = cosf(turns[bone]);
+ const float s = sinf(turns[bone]);
+ const float ct = cosf(tips[bone]);
+ const float st = sinf(tips[bone]);
+ // The turn about z, then the tip about x: rows of tip * turn.
+ const float rows[3][4] = {
+ { c, -s, 0.0f, moves[bone][0] },
+ { ct * s, ct * c, -st, moves[bone][1] },
+ { st * s, st * c, ct, moves[bone][2] } };
+ memcpy(bone_rows[bone], rows, sizeof(rows));
+ }
+
+ // The bind pose: the quad, its first two corners on one bone and the other two on the next.
+ DX11BackendClass::ShadowSkinVertex bind[4];
+ for (unsigned index = 0; index < 4; ++index) {
+ bind[index].Position[0] = QUAD_VERTICES[index].Position[0] * 0.8f;
+ bind[index].Position[1] = QUAD_VERTICES[index].Position[1] * 0.6f;
+ bind[index].Position[2] = 0.25f * (float)index - 0.3f;
+ bind[index].Bone = (index < 2) ? 0 : 1;
+ }
+
+ // The CPU fill's result for each copy, drawn the old way with an identity world.
+ BackendVertex deformed[2][4];
+ for (unsigned copy = 0; copy < 2; ++copy) {
+ for (unsigned index = 0; index < 4; ++index) {
+ const float * row = bone_rows[copy * 2 + bind[index].Bone];
+ const float * p = bind[index].Position;
+ deformed[copy][index] = QUAD_VERTICES[index];
+ for (unsigned axis = 0; axis < 3; ++axis) {
+ const float * r = row + axis * 4;
+ deformed[copy][index].Position[axis] = r[0] * p[0] + r[1] * p[1] + r[2] * p[2] + r[3];
+ }
+ }
+ }
+ ID3D11Buffer * vertices = NULL;
+ CHECK(DX11Resource_Create_Vertex_Buffer(d3d, sizeof(deformed), D3DPOOL_MANAGED, 0, deformed, &vertices));
+ ID3D11Buffer * indices = NULL;
+ CHECK(DX11Resource_Create_Index_Buffer(d3d, sizeof(QUAD_INDICES), D3DPOOL_MANAGED, 0,
+ QUAD_INDICES, &indices));
+
+ backend.Set_Render_State(D3DRS_COLORWRITEENABLE, 0);
+ backend.Set_Render_State(D3DRS_ZENABLE, D3DZB_TRUE);
+ backend.Set_Render_State(D3DRS_ZWRITEENABLE, TRUE);
+ backend.Set_Render_State(D3DRS_ZFUNC, D3DCMP_LESSEQUAL);
+ backend.Set_Render_State(D3DRS_CULLMODE, D3DCULL_NONE);
+
+ float identity[16];
+ set_identity(identity);
+ CHECK(backend.Begin_Shadow_Map(64));
+ backend.Set_Transform(D3DTS_WORLD, identity);
+ backend.Set_Stream_Source(vertices, sizeof(BackendVertex), 0);
+ backend.Set_Indices(indices, DXGI_FORMAT_R16_UINT);
+ for (unsigned copy = 0; copy < 2; ++copy) {
+ CHECK(backend.Draw_Indexed_Triangles(6, 0, copy * 4));
+ }
+ backend.End_Shadow_Map();
+ std::vector<unsigned> old_depths;
+ read_shadow_depths(device, backend, old_depths);
+
+ unsigned covered = 0;
+ for (size_t texel = 0; texel < old_depths.size(); ++texel) {
+ if (old_depths[texel] != 0x00ffffff) {
+ ++covered;
+ }
+ }
+ printf(" %u of %u texels covered\n", covered, (unsigned)old_depths.size());
+ CHECK(covered > 0);
+ CHECK(covered < old_depths.size());
+
+ // Uploaded behind a few vertices of another model, so the base vertex is not nought.
+ DX11BackendClass::ShadowSkinVertex padding[3];
+ memset(padding, 0, sizeof(padding));
+ unsigned padding_first = 0;
+ CHECK(backend.Upload_Shadow_Skin(padding, 3, padding_first));
+ unsigned first_vertex = 0;
+ CHECK(backend.Upload_Shadow_Skin(bind, 4, first_vertex));
+ CHECK_EQ(first_vertex, padding_first + 3);
+
+ CHECK(backend.Begin_Shadow_Map(64));
+ DX11BackendClass::ShadowCasterRun run;
+ run.Kind = DX11BackendClass::SHADOW_CASTER_SKINNED;
+ run.Vertices = NULL;
+ run.Stride = 0;
+ run.TextureOffset = 0;
+ run.Indices = indices;
+ run.StartIndex = 0;
+ run.IndexCount = 6;
+ run.BaseVertex = first_vertex;
+ run.Strip = false;
+ run.CullMode = D3DCULL_NONE;
+ run.DepthFunction = D3DCMP_LESSEQUAL;
+ run.FirstInstance = 0;
+ run.InstanceCount = 2;
+ // Identity worlds, as a skin's always is.
+ const float * const worlds[2] = { NULL, NULL };
+ const unsigned first_bones[2] = { 0, 2 };
+ const float * const bones[BONES] = { bone_rows[0], bone_rows[1], bone_rows[2], bone_rows[3] };
+ CHECK(backend.Upload_Shadow_Casters(worlds, first_bones, 2, bones, BONES));
+ CHECK(backend.Draw_Shadow_Casters(&run, 1));
+ backend.End_Shadow_Map();
+ std::vector<unsigned> lean_depths;
+ read_shadow_depths(device, backend, lean_depths);
+
+ CHECK_EQ(lean_depths.size(), old_depths.size());
+ unsigned edge = 0;
+ unsigned widest = 0;
+ for (size_t texel = 0; texel < old_depths.size() && texel < lean_depths.size(); ++texel) {
+ const bool old_covered = old_depths[texel] != 0x00ffffff;
+ const bool lean_covered = lean_depths[texel] != 0x00ffffff;
+ if (old_covered != lean_covered) {
+ ++edge;
+ } else {
+ const unsigned gap = (old_depths[texel] > lean_depths[texel])
+ ? old_depths[texel] - lean_depths[texel] : lean_depths[texel] - old_depths[texel];
+ widest = (gap > widest) ? gap : widest;
+ }
+ }
+ printf(" %u edge texels differ, widest depth gap %u\n", edge, widest);
+ CHECK(edge <= EDGE_TEXELS_ALLOWED);
+ CHECK(widest <= DEPTH_LEVELS_ALLOWED);
+
+ indices->Release();
+ vertices->Release();
+ backend.Shutdown();
+}
+
// The volumetric hazard clouds' text is the SDL GPU backend's too, written for DXC. Every pass of
// it has to go through the compiler this backend uses at shader model 5, and the device has to take
// what comes out, or the clouds go Classic on the first hazard of the match.