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(ww3d2): cheaper mesh draws and half the translucent draw calls

Olcay Seygane72281663a7c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 63235a361..d86fff95c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -455,6 +455,8 @@ found and fixed, EA's own, not port damage.**
- 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.
+- Faster drawing in big battles on the Direct3D 11 renderer: each unit and building draw costs about a quarter less CPU, smoke, fire and tracers go out in about half the draw calls with the translucent pass a third cheaper, and shadows and aura rings laid on the ground take less than half the CPU they did. The picture is identical to the bit.
+- Late in big matches each frame does less busywork: the mouse-over check and the visibility sweep look only at what is on screen.
- 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/GameEngineDevice/Include/W3DDevice/GameClient/W3DScene.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DScene.h
index fa7708c99..92226d365 100644
--- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DScene.h
+++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DScene.h
@@ -77,6 +77,10 @@ public:
virtual void Visibility_Check(CameraClass * camera);
virtual void Render(RenderInfoClass & rinfo);
+ virtual void Add_Render_Object(RenderObjClass * obj);
+ virtual void Remove_Render_Object(RenderObjClass * obj);
+ virtual void Remove_All_Render_Objects(void);
+
void setCustomPassMode (CustomScenePassModes mode) {m_customPassMode = mode;}
CustomScenePassModes getCustomPassMode (void) {return m_customPassMode;}
@@ -143,7 +147,8 @@ protected:
RenderObjClass **m_nonOccludersOrOccludees; ///<objects which are neither bockers or blockees (small rocks, shrubs, etc.).
Int m_numPotentialOccluders;
Int m_numPotentialOccludees;
- Int m_numNonOccluderOrOccludee;
+ Int m_numNonOccluderOrOccludee;
+ std::vector<RenderObjClass *> m_visibleObjects; ///< what the last Visibility_Check set visible, in RenderList order; a removed object is nulled
CameraClass *m_camera;
}; // end class RTS3DScene
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DProjectedShadow.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DProjectedShadow.cpp
index 5c2a1f80b..16f46b3db 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DProjectedShadow.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Shadow/W3DProjectedShadow.cpp
@@ -963,7 +963,7 @@ is an optimized system that only uses the render objects bounding box to determi
void W3DProjectedShadowManager::queueDecal(W3DProjectedShadow *shadow, Bool sunCast)
{
int i,j,k;
- Vector3 hmapVertex,objPos;
+ Vector3 objPos;
AABoxClass box;
Matrix3D objXform(1);
Real cx,cy,dx,dy;
@@ -1203,6 +1203,17 @@ void W3DProjectedShadowManager::queueDecal(W3DProjectedShadow *shadow, Bool sunC
endY = __max(endY,drawStartY);
endY = __min(endY,drawEdgeY);
+ /* The drawn extents are statics renderShadows sets, and the tree buffer queues its blobs from the
+ terrain draw before that: on the first frame of a map smaller than the last one they are the
+ last map's. The fill below reads heights and flip bits unchecked, so the cells are kept on this
+ map as well. The extents never go below nought (setDrawOrg), so only the top needs it. */
+ const Int lastX = hmap->getXExtent()-1;
+ const Int lastY = hmap->getYExtent()-1;
+ startX = __min(startX,lastX);
+ endX = __min(endX,lastX);
+ startY = __min(startY,lastY);
+ endY = __min(endY,lastY);
+
//Check if decal too large to fit inside 65536 index buffer.
//try clipping each direction to < 104 since that's more than
//enough to cover typical map.
@@ -1238,9 +1249,6 @@ void W3DProjectedShadowManager::queueDecal(W3DProjectedShadow *shadow, Bool sunC
nShadowDecalPolysInBatch*3 > (SHADOW_DECAL_INDEX_SIZE-numIndex))
flushDecals(shadow->m_shadowTexture[0], shadow->m_type);
- SHADOW_DECAL_VERTEX* pvVertices = decalStageVertices + nShadowDecalVertsInBatch;
- UnsignedShort *pvIndices = decalStageIndices + nShadowDecalPolysInBatch*3;
-
//code to deal with rotated shadows based on sun direction, fix this later. For now shadow rotates with object rotation.
//shadow->m_shadowTexture[0]->getDecalUVAxis(&uVector,&vVector);
//uVector *= 20.0f/dx;//shadow->m_decalRadius; //scale texture to fit object
@@ -1254,72 +1262,76 @@ void W3DProjectedShadowManager::queueDecal(W3DProjectedShadow *shadow, Bool sunC
*/
DEBUG_ASSERTCRASH(numVerts == ((endY-startY+1)*(endX-startX+1)), ("queueDecal VB size mismatch"));
- if(pvVertices)
+ /* Every decal's cells are laid again every pass. A cache of them per decal was tried on
+ 2026-10-27 and saved next to nothing: most of a late game's decals turn or drift every pass
+ (aura rings, the shade under smoke), and reading a cached copy back cost what the arithmetic
+ it skipped did. The fill is cheap instead. What the loops read is taken into locals first,
+ since a store through a vertex pointer otherwise makes the compiler fetch the members behind
+ getHeight and m_diffuse again for every vertex. */
+ const UnsignedInt diffuse=shadow->m_diffuse;
+ const Int firstVertex=nShadowDecalVertsInBatch;
+ const UnsignedByte *heights=hmap->getDataPtr();
+ const Int heightRow=hmap->getXExtent();
+ const Real lift=0.01f * MAP_XY_FACTOR;
+
+ /* A vertex's texture coordinates are its dot products with the decal's axes. The column's term
+ and the row's are taken once each and summed in Vector3::Dot_Product's order, so every bit
+ comes out as it did per vertex. */
+ Real columnX[104], columnU[104], columnV[104]; //the clip above keeps a row to 104 vertices
+ for (i=0; i<vertsPerRow; i++)
{
- if (layerHeight)
- for (j=startY; j <= endY; j++)
- {
- hmapVertex.Y=(float)(j-borderSize) * MAP_XY_FACTOR;
-
- for (i=startX; i <= endX; i++)
- {
- hmapVertex.X=(float)(i-borderSize)*MAP_XY_FACTOR;
- hmapVertex.Z=__max((float)hmap->getHeight(i,j)*MAP_HEIGHT_SCALE,layerHeight);
- pvVertices->x=hmapVertex.X;
- pvVertices->y=hmapVertex.Y;
- pvVertices->z=hmapVertex.Z;
- pvVertices->diffuse=shadow->m_diffuse;
- pvVertices->u=Vector3::Dot_Product(uVector, (hmapVertex-objPos))+uOffset;
- pvVertices->v=Vector3::Dot_Product(vVector, (hmapVertex-objPos))+vOffset;
- pvVertices++;
- }
- }
- else
- //insert each cell's bottom/left edge vertex
- for (j=startY; j <= endY; j++)
- {
- hmapVertex.Y=(float)(j-borderSize) * MAP_XY_FACTOR;
+ columnX[i]=(float)(startX+i-borderSize)*MAP_XY_FACTOR;
+ columnU[i]=uVector.X*(columnX[i]-objPos.X);
+ columnV[i]=vVector.X*(columnX[i]-objPos.X);
+ }
- for (i=startX; i <= endX; i++)
- {
- hmapVertex.X=(float)(i-borderSize)*MAP_XY_FACTOR;
- hmapVertex.Z=(float)hmap->getHeight(i,j)*MAP_HEIGHT_SCALE+0.01f * MAP_XY_FACTOR;
- pvVertices->x=hmapVertex.X;
- pvVertices->y=hmapVertex.Y;
- pvVertices->z=hmapVertex.Z;
- pvVertices->diffuse=shadow->m_diffuse;
- pvVertices->u=Vector3::Dot_Product(uVector, (hmapVertex-objPos))+uOffset;
- pvVertices->v=Vector3::Dot_Product(vVector, (hmapVertex-objPos))+vOffset;
- pvVertices++;
- }
+ //the clamp to the drawn terrain above keeps every cell inside the map, so heights and flip bits are read unchecked
+ SHADOW_DECAL_VERTEX *pvVertices = decalStageVertices + firstVertex;
+ for (j=startY; j <= endY; j++)
+ {
+ const Real y=(float)(j-borderSize) * MAP_XY_FACTOR;
+ const Real rowU=uVector.Y*(y-objPos.Y);
+ const Real rowV=vVector.Y*(y-objPos.Y);
+ const UnsignedByte *height=heights + j*heightRow + startX;
+ for (i=0; i<vertsPerRow; i++)
+ {
+ Real z=(float)height[i]*MAP_HEIGHT_SCALE;
+ z = layerHeight ? __max(z,layerHeight) : z+lift; //off a bridge, each cell's bottom/left edge vertex lifted off the ground
+ pvVertices->x=columnX[i];
+ pvVertices->y=y;
+ pvVertices->z=z;
+ pvVertices->diffuse=diffuse;
+ pvVertices->u=columnU[i]+rowU+uVector.Z*(z-objPos.Z)+uOffset;
+ pvVertices->v=columnV[i]+rowV+vVector.Z*(z-objPos.Z)+vOffset;
+ pvVertices++;
}
}
- { //fill each cell's vertex indices
- Int rowStart;
- for (j=startY,rowStart=0; j<endY; j++,rowStart+=vertsPerRow)
+ //fill each cell's vertex indices
+ UnsignedShort *pvIndices = decalStageIndices + nShadowDecalPolysInBatch*3;
+ Int rowStart;
+ for (j=startY,rowStart=firstVertex; j<endY; j++,rowStart+=vertsPerRow)
+ {
+ for (i=rowStart,k=startX; k<endX; i++,k++)
{
- for (i=rowStart,k=startX; k<endX; i++,k++)
- {
- ///@todo: fix the winding order in heightmap to be in strip order like above!
- if (hmap->getFlipState(k,j))
- { pvIndices[0]=i+1+nShadowDecalVertsInBatch;
- pvIndices[1]=i+vertsPerRow+nShadowDecalVertsInBatch;
- pvIndices[2]=i+nShadowDecalVertsInBatch;
- pvIndices[3]=i+1+nShadowDecalVertsInBatch;
- pvIndices[4]=i+1+vertsPerRow+nShadowDecalVertsInBatch;
- pvIndices[5]=i+vertsPerRow+nShadowDecalVertsInBatch;
- }
- else
- { pvIndices[0]=i+nShadowDecalVertsInBatch;
- pvIndices[1]=i+1+vertsPerRow+nShadowDecalVertsInBatch;
- pvIndices[2]=i+vertsPerRow+nShadowDecalVertsInBatch;
- pvIndices[3]=i+nShadowDecalVertsInBatch;
- pvIndices[4]=i+1+nShadowDecalVertsInBatch;
- pvIndices[5]=i+1+vertsPerRow+nShadowDecalVertsInBatch;
- }
- pvIndices += 6;
+ ///@todo: fix the winding order in heightmap to be in strip order like above!
+ if (hmap->getQuickFlipState(k,j))
+ { pvIndices[0]=i+1;
+ pvIndices[1]=i+vertsPerRow;
+ pvIndices[2]=i;
+ pvIndices[3]=i+1;
+ pvIndices[4]=i+1+vertsPerRow;
+ pvIndices[5]=i+vertsPerRow;
+ }
+ else
+ { pvIndices[0]=i;
+ pvIndices[1]=i+1+vertsPerRow;
+ pvIndices[2]=i+vertsPerRow;
+ pvIndices[3]=i;
+ pvIndices[4]=i+1;
+ pvIndices[5]=i+1+vertsPerRow;
}
+ pvIndices += 6;
}
}
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DScene.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DScene.cpp
index 655d44818..15372df3d 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DScene.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DScene.cpp
@@ -79,6 +79,21 @@
#include <algorithm>
#include <vector>
+
+/* A hint that a cache line is about to be read, as in PartitionManager.cpp: it reads nothing the
+ program sees, so no result depends on it. */
+#if defined(__GNUC__) || defined(__clang__)
+ #define SCENE_PREFETCH(addr) __builtin_prefetch(addr)
+#elif defined(_M_X64) || defined(_M_IX86)
+ #include <xmmintrin.h>
+ #define SCENE_PREFETCH(addr) _mm_prefetch((const char *)(addr), _MM_HINT_T0)
+#elif defined(_M_ARM64)
+ #include <intrin.h>
+ #define SCENE_PREFETCH(addr) __prefetch(addr)
+#else
+ #define SCENE_PREFETCH(addr) ((void)0)
+#endif
+
#ifdef _INTERNAL
// for occasional debugging...
//#pragma optimize("", off)
@@ -369,6 +384,27 @@ void RTS3DScene::flagOccludedObjects(CameraClass * camera)
}
}
+//=============================================================================
+/** One object of castRay's walk: a quick ray-sphere test (Graphics Gems I, p388), then the geometry.
+ * A hit shortens the ray to end on it, so a later object has to be nearer to count. */
+static Bool castRayAgainst(RenderObjClass *robj, RayCollisionTestClass &tempRayTest, RayCollisionTestClass &raytest)
+{
+ const SphereClass *sphere = &robj->Get_Bounding_Sphere();
+ Vector3 sphere_vector(sphere->Center - tempRayTest.Ray.Get_P0());
+ Real Alpha = Vector3::Dot_Product(sphere_vector, tempRayTest.Ray.Get_Dir());
+ Real Beta = sphere->Radius * sphere->Radius - (Vector3::Dot_Product(sphere_vector, sphere_vector) - Alpha * Alpha);
+ if (Beta < 0.0f || !robj->Cast_Ray(tempRayTest))
+ return FALSE;
+
+ raytest.CollidedRenderObj = robj;
+ Vector3 newEndPoint;
+ tempRayTest.Ray.Compute_Point(tempRayTest.Result->Fraction,&newEndPoint);
+ tempRayTest.Ray.Set(raytest.Ray.Get_P0(),newEndPoint);
+ //intersection point is at the end of shortened ray, so adjust fraction to 1.0
+ tempRayTest.Result->Fraction=1.0f;
+ return TRUE;
+}
+
//=============================================================================
// RTS3DScene::castRay
//=============================================================================
@@ -389,54 +425,32 @@ Bool RTS3DScene::castRay(RayCollisionTestClass & raytest, Bool testAll, Int coll
//temporary results for each object tested
CastResultStruct result;
RayCollisionTestClass tempRayTest(raytest.Ray,&result);
- Vector3 newEndPoint;
Bool hit=FALSE;
tempRayTest.CollisionType = COLL_TYPE_ALL;
//check if a mesh is translucent before colliding with it. Skips headlights, etc.
tempRayTest.CheckTranslucent = true;
- RefRenderObjListIterator it(&RenderList);
-
- // select the first object
- it.First();
-
- while (!it.Is_Done())
+ if (testAll)
{
- // get the render object
- RenderObjClass * robj = it.Peek_Obj();
- it.Next();
-
- // only intersect if it was visible or if we must test all
- if(robj->Get_Collision_Type() & collisionType && (testAll || robj->Is_Really_Visible()))
+ RefRenderObjListIterator it(&RenderList);
+ for (it.First(); !it.Is_Done(); it.Next())
{
- // Do a quick ray-sphere test (Graphics Gems I, p388)
- const SphereClass *sphere = &robj->Get_Bounding_Sphere();
-
- // make a vector from the ray origin to the sphere center
- Vector3 sphere_vector(sphere->Center - tempRayTest.Ray.Get_P0());
-
- // get the dot product between the sphere_vector and the ray vector
- Real Alpha = Vector3::Dot_Product(sphere_vector, tempRayTest.Ray.Get_Dir());
-
- Real Beta = sphere->Radius * sphere->Radius - (Vector3::Dot_Product(sphere_vector, sphere_vector) - Alpha * Alpha);
-
- if(Beta < 0.0f)
- continue; //no intersection
-
- //Do a more accurate test against object geometry
- if (robj->Cast_Ray(tempRayTest))
- {
- //Found an object closer than last closest object
- //Adjust our results and refine search
- raytest.CollidedRenderObj = robj;
- hit=TRUE;
- //Refine search by making ray shorter
- tempRayTest.Ray.Compute_Point(tempRayTest.Result->Fraction,&newEndPoint);
- tempRayTest.Ray.Set(raytest.Ray.Get_P0(),newEndPoint);
- //intersection point is at the end of shortened ray, so adjust fraction to 1.0
- tempRayTest.Result->Fraction=1.0f;
- }
+ RenderObjClass *robj = it.Peek_Obj();
+ if ((robj->Get_Collision_Type() & collisionType) && castRayAgainst(robj, tempRayTest, raytest))
+ hit = TRUE;
+ }
+ }
+ else
+ {
+ // The visible ones only (m_visibleObjects, see Add_Render_Object): about 145 of 900 render
+ // objects late in a 4-player match. The mouse-over pick runs once a client frame, undrawn
+ // frames included, and the walk past the other 750 was two thirds of its time.
+ for (size_t i = 0; i < m_visibleObjects.size(); ++i)
+ {
+ RenderObjClass *robj = m_visibleObjects[i];
+ if (robj && (robj->Get_Collision_Type() & collisionType) && robj->Is_Really_Visible() && castRayAgainst(robj, tempRayTest, raytest))
+ hit = TRUE;
}
}
@@ -445,6 +459,37 @@ Bool RTS3DScene::castRay(RayCollisionTestClass & raytest, Bool testAll, Int coll
return hit;
}
+//=============================================================================
+// RTS3DScene::Add_Render_Object / Remove_Render_Object / Remove_All_Render_Objects
+//=============================================================================
+/** m_visibleObjects holds every object in the scene whose visible bit is set, in RenderList order,
+ * so a walk over it that asks Is_Really_Visible meets what a walk over RenderList would. An
+ * object joins the scene without the bit (DEFAULT_BITS) and only Visibility_Check sets it, so the
+ * list is what that check left, plus an object that comes back still carrying the bit from an
+ * earlier stay. A removed object is nulled rather than erased, keeping the order, which is the
+ * tie-break of castRay and the order the render loop queues in; the scene's reference is what
+ * kept it alive. */
+//=============================================================================
+void RTS3DScene::Add_Render_Object(RenderObjClass * obj)
+{
+ const bool listed = RenderList.Contains(obj);
+ SimpleSceneClass::Add_Render_Object(obj);
+ if (!listed && obj->Is_Visible())
+ m_visibleObjects.push_back(obj);
+}
+
+void RTS3DScene::Remove_Render_Object(RenderObjClass * obj)
+{
+ std::replace(m_visibleObjects.begin(), m_visibleObjects.end(), obj, (RenderObjClass *)NULL);
+ SimpleSceneClass::Remove_Render_Object(obj);
+}
+
+void RTS3DScene::Remove_All_Render_Objects(void)
+{
+ m_visibleObjects.clear();
+ SimpleSceneClass::Remove_All_Render_Objects();
+}
+
//=============================================================================
// posedPartsInView
//=============================================================================
@@ -457,6 +502,23 @@ static Bool posedPartsInView(RenderObjClass *robj, CameraClass *camera)
return W3DModelDraw::getPosedBoundingSphere(robj, posed) && !camera->Cull_Sphere(posed);
}
+/** Visibility_Check's walk is a linked list of objects scattered over the heap, most of them off the
+ * screen and done with in a few tests, so the walk is mostly waiting for each one to arrive. This
+ * asks for the one two ahead: its vtable pointer and bits at the start, its cached bounding sphere
+ * about 100 bytes in. A layout change only makes the second hint miss. */
+static inline void prefetchAhead(RefRenderObjListIterator it)
+{
+ it.Next();
+ if (it.Is_Done())
+ return;
+ it.Next();
+ if (it.Is_Done())
+ return;
+ const char *obj = (const char *)it.Peek_Obj();
+ SCENE_PREFETCH(obj);
+ SCENE_PREFETCH(obj + 100);
+}
+
//=============================================================================
// RTS3DScene::Visibility_Check
//=============================================================================
@@ -478,6 +540,7 @@ void RTS3DScene::Visibility_Check(CameraClass * camera)
m_numPotentialOccludees=0;
m_translucentObjectsCount=0;
m_numNonOccluderOrOccludee=0;
+ m_visibleObjects.clear();
Int currentFrame=0;
if (TheGameLogic) currentFrame = TheGameLogic->getFrame();
@@ -494,6 +557,7 @@ void RTS3DScene::Visibility_Check(CameraClass * camera)
for (it.First(); !it.Is_Done(); it.Next()) {
robj = it.Peek_Obj();
+ prefetchAhead(it);
draw=NULL;
drawInfo = (DrawableInfo *)robj->Get_User_Data();
@@ -523,6 +587,8 @@ void RTS3DScene::Visibility_Check(CameraClass * camera)
robj->Set_Visible(!camera->Cull_Sphere(robj->Get_Bounding_Sphere()));
}
}
+ if (robj->Is_Visible())
+ m_visibleObjects.push_back(robj);
}
}
else
@@ -533,6 +599,7 @@ void RTS3DScene::Visibility_Check(CameraClass * camera)
for (it.First(); !it.Is_Done(); it.Next()) {
robj = it.Peek_Obj();
+ prefetchAhead(it);
if (robj->Is_Force_Visible()) {
robj->Set_Visible(true);
@@ -605,6 +672,8 @@ void RTS3DScene::Visibility_Check(CameraClass * camera)
robj->Set_Visible(isVisible);
}
+ if (robj->Is_Visible())
+ m_visibleObjects.push_back(robj);
///@todo: We're not using LOD yet so I disabled this code. MW
// Also, should check how multiple passes (reflections) get along
@@ -1441,15 +1510,13 @@ void RTS3DScene::Customized_Render( RenderInfoClass &rinfo )
}
#endif
- // loop through all render objects in the list:
- for (it.First(&RenderList); !it.Is_Done();)
+ // loop through the visible render objects: m_visibleObjects is RenderList's visible ones in its
+ // order (Add_Render_Object), and the ~85% of the list off the screen cost this walk most of its
+ // time. By index, so an object removed during renderOneObject() only leaves a null behind.
+ for (size_t v = 0; v < m_visibleObjects.size(); ++v)
{
-
- // get the render object
- robj = it.Peek_Obj();
- it.Next(); //advance to next object in case this one gets deleted during renderOneObject().
-
- if (robj->Class_ID() == RenderObjClass::CLASSID_TILEMAP)
+ robj = m_visibleObjects[v];
+ if (robj == NULL || robj->Class_ID() == RenderObjClass::CLASSID_TILEMAP)
continue; //we already rendered terrain
if (robj->Is_Really_Visible()) {
@@ -1711,7 +1778,7 @@ void RTS3DScene::flushOccludedObjectsIntoStencil(RenderInfoClass & rinfo)
{
DrawableInfo *drawInfo=((DrawableInfo *)(*renderList)->Get_User_Data());
if (drawInfo->m_flags & DrawableInfo::ERF_IS_TRANSLUCENT)
- {
+ {
TheDX8MeshRenderer.Flush(); //render all the submitted meshes using current stencil function
SHD_FLUSH;
//Disable writing to color buffer since translucent objects are rendered at end of frame.
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp
index 2114ea9c1..03a862d30 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp
@@ -34,6 +34,7 @@
#if defined(_M_X64) || defined(_M_IX86) || defined(__SSE__)
#include <xmmintrin.h>
#endif
+#include <cstddef>
typedef HRESULT (WINAPI *D3DCompileFunction)(LPCVOID source_data, SIZE_T source_size,
LPCSTR source_name, const D3D_SHADER_MACRO * defines, ID3DInclude * include,
@@ -290,6 +291,8 @@ DX11BackendClass::DX11BackendClass()
Forget_Last_State_Objects();
memset(&HeldVertexConstants, 0, sizeof(HeldVertexConstants));
memset(&HeldPixelConstants, 0, sizeof(HeldPixelConstants));
+ memset(RecentPixelDiscards, 0, sizeof(RecentPixelDiscards)); // no ring is at nought once made
+ NextRecentPixel = 0;
memset(HeldEngineConstants, 0, sizeof(HeldEngineConstants));
VertexConstantsHeld = false;
PixelConstantsHeld = false;
@@ -297,6 +300,9 @@ DX11BackendClass::DX11BackendClass()
ConstantsChanged = true;
VertexConstantsChanged = false;
PixelConstantsChanged = false;
+ PixelBlendChanged = false;
+ HeldPixelBlendKey = 0;
+ WorldChanged = false;
TexturesChanged = true;
PipelineChanged = true;
StateObjectsChanged = true;
@@ -461,6 +467,7 @@ bool DX11BackendClass::Create_Constant_Ring(ConstantRing & ring, unsigned block_
// Full, so the first write discards: the buffer has never been mapped.
ring.Next = ring.Bytes;
ring.Current = 0;
+ ++ring.Discards;
D3D11_BUFFER_DESC description;
memset(&description, 0, sizeof(description));
@@ -491,6 +498,7 @@ bool DX11BackendClass::Write_Constants(ConstantRing & ring, const void * block,
++FrameConstantWrites;
if (wraps) {
++FrameConstantRenames;
+ ++ring.Discards;
}
return true;
}
@@ -500,7 +508,9 @@ void DX11BackendClass::Release_Constant_Ring(ConstantRing & ring)
if (ring.Buffer != NULL) {
ring.Buffer->Release();
}
+ const unsigned discards = ring.Discards;
memset(&ring, 0, sizeof(ring));
+ ring.Discards = discards + 1;
}
void DX11BackendClass::Release_Cached()
@@ -2269,20 +2279,28 @@ void DX11BackendClass::Set_Render_State(D3DRENDERSTATETYPE state, DWORD value)
// Upload_Pixel_Constants. The blend switch is there because the caster pass's alpha
// reference depends on it. A blend, depth or cull change used to rebuild and compare both
// blocks to find the same bytes.
+ // The first two groups are read by a constant block and by nothing else: no description and
+ // no state object is built from them, so they leave both alone. Every object sets its own
+ // ambient, and a scaled one turns NORMALIZENORMALS, which nothing here reads, on and off
+ // around its draws; each of those sent the next draw down the whole Resolve.
switch (state) {
case D3DRS_AMBIENT:
case D3DRS_FOGSTART:
case D3DRS_FOGEND:
case D3DRS_FOGDENSITY:
VertexConstantsChanged = true;
- break;
+ return;
case D3DRS_FOGCOLOR:
case D3DRS_TEXTUREFACTOR:
case D3DRS_ALPHAREF:
+ PixelConstantsChanged = true;
+ return;
+ case D3DRS_NORMALIZENORMALS:
+ return;
case D3DRS_ALPHABLENDENABLE:
case D3DRS_SRCBLEND: // a multiply pass takes no blast light (Upload_Pixel_Constants)
case D3DRS_DESTBLEND:
- PixelConstantsChanged = true;
+ PixelBlendChanged = true;
break;
default:
break;
@@ -2466,6 +2484,8 @@ void DX11BackendClass::Set_Transform(D3DTRANSFORMSTATETYPE state, const float ma
// are the vertex block's alone.
if (held == View || held == Projection) {
ConstantsChanged = true;
+ } else if (held == World) {
+ WorldChanged = true;
} else {
VertexConstantsChanged = true;
}
@@ -2522,7 +2542,8 @@ void DX11BackendClass::Set_Light(unsigned index, DWORD type, const float positio
memcpy(light.Attenuation, attenuation, sizeof(light.Attenuation));
memcpy(light.Spot, spot, sizeof(light.Spot));
memcpy(light.Ambient, ambient, sizeof(light.Ambient));
- ConstantsChanged = true;
+ // The lights are the vertex block's alone; the pixel block's lamps and blasts are its own.
+ VertexConstantsChanged = true;
if (pipeline_changed) {
PipelineChanged = true;
}
@@ -2532,7 +2553,7 @@ void DX11BackendClass::Disable_Light(unsigned index)
{
if (index < MAXIMUM_VERTEX_LIGHTS && Lights[index].Enabled) {
Lights[index].Enabled = false;
- ConstantsChanged = true;
+ VertexConstantsChanged = true;
PipelineChanged = true;
}
}
@@ -3505,18 +3526,46 @@ void DX11BackendClass::Upload_Constants()
// Each block is built only when something it is built from has been set since its buffer was
// last written.
const bool vertex_due = ConstantsChanged || VertexConstantsChanged || !VertexConstantsHeld;
- const bool pixel_due = ConstantsChanged || PixelConstantsChanged || !PixelConstantsHeld;
+ const bool world_due = !vertex_due && WorldChanged;
+ bool pixel_due = ConstantsChanged || PixelConstantsChanged || !PixelConstantsHeld;
+ // A blend change rebuilt the pixel block on every sorted run, and nearly always to the same
+ // bytes: the block reads the blend only through Pixel_Blend_Key.
+ if (!pixel_due && PixelBlendChanged) {
+ pixel_due = Pixel_Blend_Key() != HeldPixelBlendKey;
+ }
ConstantsChanged = false;
VertexConstantsChanged = false;
PixelConstantsChanged = false;
+ PixelBlendChanged = false;
+ WorldChanged = false;
if (vertex_due) {
Upload_Vertex_Constants();
+ } else if (world_due) {
+ Upload_World_Constants();
}
if (pixel_due) {
Upload_Pixel_Constants();
}
}
+// What the pixel block takes from the blend, and from the vertex format and the programs, which raise
+// no flag of their own: the look Draw_Effect picks, the multiply test that keeps the blast lights off
+// a pass multiplying what is under it, whether the program reads the scene's depth, and the alpha
+// reference, which the sun's caster pass answers by the blend switch. The same key is the same block.
+unsigned DX11BackendClass::Pixel_Blend_Key() const
+{
+ return Draw_Effect() | (Multiplies_Below() ? 0x100u : 0u)
+ | (EngineShader_Reads_Scene_Depth(PixelProgram) ? 0x200u : 0u)
+ | ((RenderStates.Get_Render_State(D3DRS_ALPHAREF) & 0xffu) << 10);
+}
+
+bool DX11BackendClass::Multiplies_Below() const
+{
+ return RenderStates.Get_Render_State(D3DRS_ALPHABLENDENABLE) != FALSE
+ && (RenderStates.Get_Render_State(D3DRS_SRCBLEND) == D3DBLEND_ZERO
+ || RenderStates.Get_Render_State(D3DRS_DESTBLEND) == D3DBLEND_SRCCOLOR);
+}
+
void DX11BackendClass::Upload_Vertex_Constants()
{
VertexConstantBlock vertex_block;
@@ -3583,8 +3632,31 @@ void DX11BackendClass::Upload_Vertex_Constants()
}
}
+// Everything but the world came from the same inputs as the held block (only WorldChanged is up),
+// so the held block with its three world products made again is what Upload_Vertex_Constants would
+// build, byte for byte, without its light transforms, colour conversions and kilobyte compare.
+void DX11BackendClass::Upload_World_Constants()
+{
+ float world[3][16];
+ multiply(World, View, world[1]);
+ multiply(world[1], Projection, world[0]);
+ inverse_transpose(world[1], world[2]);
+ // Set back to the matrices it holds, the block would be the one already in the buffer.
+ if (memcmp(HeldVertexConstants.WorldViewProjection, world, sizeof(world)) == 0) {
+ return;
+ }
+ static_assert(offsetof(VertexConstantBlock, WorldView) == sizeof(float) * 16
+ && offsetof(VertexConstantBlock, NormalTransform) == sizeof(float) * 32,
+ "the three world products lead the block");
+ memcpy(HeldVertexConstants.WorldViewProjection, world, sizeof(world));
+ VertexConstantsHeld = Write_Constants(VertexConstantRing, &HeldVertexConstants,
+ sizeof(HeldVertexConstants));
+}
+
void DX11BackendClass::Upload_Pixel_Constants()
{
+ // The held block is this one once the compare or the write below is done, or it is not held.
+ HeldPixelBlendKey = Pixel_Blend_Key();
PixelConstantBlock pixel_block;
memset(&pixel_block, 0, sizeof(pixel_block));
RenderStates.Get_Texture_Factor(pixel_block.TextureFactor);
@@ -3664,10 +3736,7 @@ void DX11BackendClass::Upload_Pixel_Constants()
// None for a particle: the smoke takes these lights on the CPU (BLAST_LIGHT_SAMPLING). None
// for a pass that multiplies what is under it (ZERO, SRCCOLOR): the base pass took the light
// already, and gained again the surface came out lit twice.
- const bool multiplies = RenderStates.Get_Render_State(D3DRS_ALPHABLENDENABLE) != FALSE
- && (RenderStates.Get_Render_State(D3DRS_SRCBLEND) == D3DBLEND_ZERO
- || RenderStates.Get_Render_State(D3DRS_DESTBLEND) == D3DBLEND_SRCCOLOR);
- const unsigned blasts = (camera_space || multiplies) ? 0 : BlastLightCount;
+ const unsigned blasts = (camera_space || Multiplies_Below()) ? 0 : BlastLightCount;
pixel_block.BlastLightParameters[0] = static_cast<float>(blasts);
for (unsigned slot = 0; slot < blasts; ++slot) {
memcpy(pixel_block.BlastLightPosition[slot], &BlastLights[slot][0], sizeof(float) * 4);
@@ -3688,14 +3757,43 @@ void DX11BackendClass::Upload_Pixel_Constants()
if (!PixelConstantsHeld
|| memcmp(&HeldPixelConstants, &pixel_block, sizeof(pixel_block)) != 0) {
+ if (Rebind_Recent_Pixel_Constants(pixel_block)) {
+ return;
+ }
PixelConstantsHeld = false;
if (Write_Constants(PixelConstantRing, &pixel_block, sizeof(pixel_block))) {
HeldPixelConstants = pixel_block;
PixelConstantsHeld = true;
+ RecentPixelConstants[NextRecentPixel] = pixel_block;
+ RecentPixelOffset[NextRecentPixel] = PixelConstantRing.Current;
+ RecentPixelDiscards[NextRecentPixel] = PixelConstantRing.Discards;
+ NextRecentPixel = (NextRecentPixel + 1) % RECENT_PIXEL_BLOCKS;
}
}
}
+// A block one of the last few writes left in the ring, in the buffer as it is now, bound again where
+// it lies: the draws read the same bytes from an older entry. The tail first, where a billboard
+// run's block and a streak's differ, so a block that is not there costs a short compare.
+bool DX11BackendClass::Rebind_Recent_Pixel_Constants(const PixelConstantBlock & block)
+{
+ const size_t tail = offsetof(PixelConstantBlock, SoftParticleDepth);
+ const unsigned char * const wanted = reinterpret_cast<const unsigned char *>(&block);
+ for (unsigned index = 0; index < RECENT_PIXEL_BLOCKS; ++index) {
+ const unsigned char * const recent =
+ reinterpret_cast<const unsigned char *>(&RecentPixelConstants[index]);
+ if (RecentPixelDiscards[index] == PixelConstantRing.Discards
+ && memcmp(recent + tail, wanted + tail, sizeof(block) - tail) == 0
+ && memcmp(recent, wanted, tail) == 0) {
+ PixelConstantRing.Current = RecentPixelOffset[index];
+ HeldPixelConstants = block;
+ PixelConstantsHeld = true;
+ return true;
+ }
+ }
+ return false;
+}
+
void DX11BackendClass::Forget_Last_State_Objects()
{
memset(&LastBlendDescription, 0, sizeof(LastBlendDescription));
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h
index 1cf64182b..0f9a423b9 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h
@@ -112,6 +112,13 @@ public:
// frame. While they are, the engine leaves the dynamic lights out of its own vertex lighting.
bool Lights_Per_Pixel() const { return ShadowReceiving && ShadowMapTexture != NULL; }
+ // How many blast lights the pixel block the last draw went up with carries. A pass multiplying
+ // what is under it carries none (Upload_Pixel_Constants).
+ unsigned Pixel_Block_Blast_Lights() const
+ {
+ return static_cast<unsigned>(HeldPixelConstants.BlastLightParameters[0]);
+ }
+
// The draws that follow are sorted particle billboards, which fade where they meet the scene's
// depth (SOFT_PARTICLE_SAMPLING). Only the sorting pool sets it, around the billboards' runs.
void Set_Soft_Particles(bool soft);
@@ -586,6 +593,7 @@ private:
bool Build_Combiner_Description(CombinerDescription & description) const;
void Upload_Constants();
void Upload_Vertex_Constants();
+ void Upload_World_Constants();
void Upload_Pixel_Constants();
// Both indexed draws land here; only the topology differs.
@@ -606,6 +614,7 @@ private:
unsigned Bytes; ///< the whole buffer, a whole number of entries
unsigned Next; ///< where the next write goes; Bytes makes it discard
unsigned Current; ///< where the last write went, which is what the draws read
+ unsigned Discards; ///< every discard and every new buffer: an entry written since is still there
};
bool Create_Constant_Ring(ConstantRing & ring, unsigned block_bytes);
bool Write_Constants(ConstantRing & ring, const void * block, unsigned bytes);
@@ -865,6 +874,17 @@ private:
PixelConstantBlock HeldPixelConstants;
float HeldEngineConstants[ENGINE_SHADER_CONSTANTS][4];
+ // The last few pixel blocks written, with the entry each went to and the ring's discard count
+ // then. The sorted flush goes back and forth between a few of them, a billboard run's soft
+ // particle depth and a streak's none, and one still in the buffer is bound where it lies instead
+ // of written again (Rebind_Recent_Pixel_Constants).
+ enum { RECENT_PIXEL_BLOCKS = 4 };
+ PixelConstantBlock RecentPixelConstants[RECENT_PIXEL_BLOCKS];
+ unsigned RecentPixelOffset[RECENT_PIXEL_BLOCKS];
+ unsigned RecentPixelDiscards[RECENT_PIXEL_BLOCKS];
+ unsigned NextRecentPixel;
+ bool Rebind_Recent_Pixel_Constants(const PixelConstantBlock & block);
+
// A freshly created dynamic buffer holds nothing in particular, and a Map can fail, so a copy
// above only stands for what is in its buffer once a write has actually gone through. One flag
// each rather than one between them: the engine bank is skipped on every draw that takes no
@@ -888,6 +908,19 @@ private:
// whose bytes always matched. ConstantsChanged stands for both.
bool VertexConstantsChanged;
bool PixelConstantsChanged;
+ // The blend switch or either factor, which the pixel block reads only through Pixel_Blend_Key:
+ // the block is built again only when the key moved from the one it was last built with. The
+ // sorted flush flips the blend at nearly every run, and each flip rebuilt and compared the
+ // whole block to find the same bytes.
+ bool PixelBlendChanged;
+ unsigned HeldPixelBlendKey;
+ unsigned Pixel_Blend_Key() const;
+ // A blend that multiplies what is under it: it takes no blast light.
+ bool Multiplies_Below() const;
+ // The world transform alone, which is every mesh draw: with nothing else flagged the held block
+ // is the rest of the next one, and only its three world products are made again
+ // (Upload_World_Constants).
+ bool WorldChanged;
bool PipelineChanged;
bool SamplerChanged[DX11_BACKEND_TEXTURE_STAGES];
// A stage's texture changed, or the last draw sampled the current target and so needs a fresh
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp
index 1ba8408f4..5af436539 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp
@@ -2820,10 +2820,12 @@ void DX8Wrapper::Draw(
Apply_Render_State_Changes();
- // -ffprobe only: the fixed-function inventory phase 2 has to write as HLSL, counted off the
- // device rather than off this wrapper's cache. Under D3D11 the device is behind that cache, so
- // the sample flushes the wrapper's cached values to it first; only the draws it samples pay.
- if (FixedFunctionProbe_Samples_Draw()) {
+ // The fixed-function inventory phase 2 had to write as HLSL, counted off the device rather than
+ // off this wrapper's cache. Under D3D11 the device is behind that cache, so a sample sent every
+ // deferred state to it and read forty-odd back, an eighth of the mesh pass's draw time for a
+ // device nothing presents; the D3D11 frame has its own count of what it drew (-dx11 drew), and
+ // -d3d9 still takes the inventory.
+ if (!Direct3D11_Present_Is_Enabled() && FixedFunctionProbe_Samples_Draw()) {
Flush_Deferred_D3D9_State();
FixedFunctionProbe_Record(D3DDevice);
}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/render2dsentence.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/render2dsentence.cpp
index ca439274b..4768a6d8d 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/render2dsentence.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/render2dsentence.cpp
@@ -141,6 +141,20 @@ Render2DSentenceClass::Reset_Polys (void)
////////////////////////////////////////////////////////////////////////////////////
void
Render2DSentenceClass::Reset (void)
+{
+ Reset_Keeping_Textures ();
+ Release_Spare_Textures ();
+ return ;
+}
+
+
+////////////////////////////////////////////////////////////////////////////////////
+//
+// Reset_Keeping_Textures
+//
+////////////////////////////////////////////////////////////////////////////////////
+void
+Render2DSentenceClass::Reset_Keeping_Textures (void)
{
//
// Make sure we unlock the current surface (if necessary)
@@ -156,9 +170,18 @@ Render2DSentenceClass::Reset (void)
REF_PTR_RELEASE (CurSurface);
//
- // Free each renderer
+ // Free each renderer, keeping its texture. Text set again (a clock, a counter, the corner
+ // readout's frame number every logic frame) mostly wants textures of the same size, and
+ // Build_Textures fills one of these rather than making a new one: a made one was a Direct3D 9
+ // texture and, on the Direct3D 11 frame, a new copy of it, most of what drawing a string cost.
+ // Each surface has its own renderer and texture, so none is kept twice.
//
while (Renderers.Count () > 0) {
+ TextureClass *texture = Renderers[0].Renderer->Peek_Texture ();
+ if (texture != NULL) {
+ texture->Add_Ref ();
+ SpareTextures.Add (texture);
+ }
delete Renderers[0].Renderer;
Renderers.Delete(0);
}
@@ -384,17 +407,26 @@ Render2DSentenceClass::Build_Textures (void)
curr_surface->Get_Description (desc);
//
- // Create the new texture
+ // A texture the sentence's last text left (Reset) when one is this size, or a new one. The
+ // copy below writes the whole of it, so nothing of the old text survives.
//
- TextureClass *new_texture = W3DNEW TextureClass (desc.Width, desc.Width, WW3D_FORMAT_A4R4G4B4, MIP_LEVELS_1);
+ TextureClass *new_texture = NULL;
+ for (int spare = 0; spare < SpareTextures.Count () && new_texture == NULL; spare ++) {
+ if (SpareTextures[spare]->Get_Width () == (int)desc.Width) {
+ new_texture = SpareTextures[spare];
+ SpareTextures.Delete (spare);
+ }
+ }
+ if (new_texture == NULL) {
+ new_texture = W3DNEW TextureClass (desc.Width, desc.Width, WW3D_FORMAT_A4R4G4B4, MIP_LEVELS_1);
+ new_texture->Get_Filter().Set_U_Addr_Mode(TextureFilterClass::TEXTURE_ADDRESS_CLAMP);
+ new_texture->Get_Filter().Set_V_Addr_Mode(TextureFilterClass::TEXTURE_ADDRESS_CLAMP);
+ new_texture->Get_Filter().Set_Min_Filter(TextureFilterClass::FILTER_TYPE_NONE);
+ new_texture->Get_Filter().Set_Mag_Filter(TextureFilterClass::FILTER_TYPE_NONE);
+ new_texture->Get_Filter().Set_Mip_Mapping(TextureFilterClass::FILTER_TYPE_NONE);
+ }
SurfaceClass *texture_surface = new_texture->Get_Surface_Level ();
- new_texture->Get_Filter().Set_U_Addr_Mode(TextureFilterClass::TEXTURE_ADDRESS_CLAMP);
- new_texture->Get_Filter().Set_V_Addr_Mode(TextureFilterClass::TEXTURE_ADDRESS_CLAMP);
- new_texture->Get_Filter().Set_Min_Filter(TextureFilterClass::FILTER_TYPE_NONE);
- new_texture->Get_Filter().Set_Mag_Filter(TextureFilterClass::FILTER_TYPE_NONE);
- new_texture->Get_Filter().Set_Mip_Mapping(TextureFilterClass::FILTER_TYPE_NONE);
-
//
// Copy the contents of the texture from the surface
//
@@ -422,6 +454,26 @@ Render2DSentenceClass::Build_Textures (void)
if (PendingSurfaces.Count()>0) {
PendingSurfaces.Delete_All ();
}
+
+ // what the new text had no use for
+ Release_Spare_Textures ();
+ return ;
+}
+
+
+////////////////////////////////////////////////////////////////////////////////////
+//
+// Release_Spare_Textures
+//
+////////////////////////////////////////////////////////////////////////////////////
+void
+Render2DSentenceClass::Release_Spare_Textures (void)
+{
+ for (int index = 0; index < SpareTextures.Count (); index ++) {
+ REF_PTR_RELEASE (SpareTextures[index]);
+ }
+
+ if (SpareTextures.Count()>0) SpareTextures.Delete_All ();
return ;
}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/render2dsentence.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/render2dsentence.h
index 82da99853..c515e09ed 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/render2dsentence.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/render2dsentence.h
@@ -164,6 +164,7 @@ public:
void Render (void);
virtual void Reset (void);
+ void Reset_Keeping_Textures (void); ///< Reset, but the next Build_Textures fills the old text's textures again
void Reset_Polys (void);
FontCharsClass * Peek_Font( void ) { return Font; }
@@ -256,6 +257,7 @@ private:
void Record_Sentence_Chunk (void);
void Allocate_New_Surface (const WideChar *text, bool justCalcExtents = false);
void Release_Pending_Surfaces (void);
+ void Release_Spare_Textures (void);
void Build_Sentence_Centered (const WideChar *text, int *hkX, int *hkY);
Vector2 Build_Sentence_Not_Centered (const WideChar *text, int *hkX, int *hkY,bool justCalcExtents = false );
//
@@ -264,6 +266,7 @@ private:
DynamicVectorClass<SentenceDataStruct> SentenceData;
DynamicVectorClass<PendingSurfaceStruct> PendingSurfaces;
DynamicVectorClass<RendererDataStruct> Renderers;
+ DynamicVectorClass<TextureClass *> SpareTextures; ///< the last text's, for Build_Textures to fill again (Reset)
FontCharsClass * Font;
Vector2 BaseLocation;
Vector2 Location;
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/sortingrenderer.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/sortingrenderer.cpp
index 0d6792ace..4ae74c567 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/sortingrenderer.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/sortingrenderer.cpp
@@ -572,6 +572,85 @@ static bool Same_Draw_State(const RenderStateStruct& a, const RenderStateStruct&
return true;
}
+// Whether two nodes draw in one run: the device state above and every look the flush sets per run.
+// A billboard run fades into the depth behind it and a mesh run does not, so the two never share one.
+static bool Same_Run_State(const SortingNodeStruct* a,const SortingNodeStruct* b)
+{
+ return a->glow==b->glow && a->fire==b->fire && a->emissive==b->emissive && a->quads==b->quads
+ && Same_Draw_Effect(a,b) && a->excludeSunReceivers==b->excludeSunReceivers
+ && a->casterEffect==b->casterEffect && Same_Draw_State(a->sorting_state,b->sorting_state);
+}
+
+// ----------------------------------------------------------------------------
+// Each pooled node's run state, named by the first node in pool order that has it, so a run break
+// is one compare and not Same_Run_State's matrices and lights. The hash covers only fields that
+// Same_Run_State compares byte for byte, so equal states always hash alike.
+
+static unsigned short overlapping_node_class[MAX_OVERLAPPING_NODES];
+static const unsigned CLASS_TABLE_SIZE=2*MAX_OVERLAPPING_NODES;
+static unsigned short class_table[CLASS_TABLE_SIZE]; // a class's node plus one; nought is empty
+static unsigned class_table_hash[CLASS_TABLE_SIZE];
+
+static unsigned Hash_Words(unsigned hash,const void* bytes,unsigned byte_count)
+{
+ const unsigned char* at=(const unsigned char*)bytes;
+ for (unsigned offset=0;offset+sizeof(unsigned)<=byte_count;offset+=sizeof(unsigned)) {
+ unsigned word;
+ memcpy(&word,at+offset,sizeof(word));
+ hash=(hash^word)*16777619u;
+ }
+ return hash;
+}
+
+static unsigned Run_State_Hash(const SortingNodeStruct* node,int textures)
+{
+ const RenderStateStruct& state=node->sorting_state;
+ const unsigned fields[3]={
+ state.shader.Get_Bits(),
+ node->draw_effect,
+ (node->glow?1u:0u)|(node->fire?2u:0u)|(node->emissive?4u:0u)|(node->quads?8u:0u)|(node->excludeSunReceivers?16u:0u) };
+ unsigned hash=Hash_Words(2166136261u,fields,sizeof(fields));
+ hash=Hash_Words(hash,&state.material,sizeof(state.material));
+ hash=Hash_Words(hash,state.Textures,sizeof(state.Textures[0])*textures);
+ hash=Hash_Words(hash,&state.world,sizeof(state.world));
+ return Hash_Words(hash,&state.view,sizeof(state.view));
+}
+
+// A node nothing may pass, nor it anything: a look that reads the scene's copy, a sun caster
+// effect, or a texture in the default pool, which is where every render target lives and so where a
+// draw sampling the picture under it would find it.
+static bool Run_Stays_In_Order(const SortingNodeStruct* node,int textures)
+{
+ if (node->draw_effect!=0 || node->casterEffect.Effect!=0) return true;
+ for (int i=0;i<textures;++i) {
+ const TextureBaseClass* texture=node->sorting_state.Textures[i];
+ if (texture && texture->Get_Pool()==TextureBaseClass::POOL_DEFAULT) return true;
+ }
+ return false;
+}
+
+static void Classify_Nodes(unsigned node_count,unsigned short* states)
+{
+ const int textures=DX8Wrapper::Get_Current_Caps()->Get_Max_Textures_Per_Pass();
+ memset(class_table,0,sizeof(class_table));
+ for (unsigned node=0;node<node_count;++node) {
+ const SortingNodeStruct* state=overlapping_nodes[node];
+ const unsigned hash=Run_State_Hash(state,textures);
+ unsigned slot=hash&(CLASS_TABLE_SIZE-1);
+ while (class_table[slot]!=0
+ && (class_table_hash[slot]!=hash || !Same_Run_State(overlapping_nodes[class_table[slot]-1],state))) {
+ slot=(slot+1)&(CLASS_TABLE_SIZE-1);
+ }
+ if (class_table[slot]==0) {
+ class_table[slot]=(unsigned short)(node+1);
+ class_table_hash[slot]=hash;
+ }
+ overlapping_node_class[node]=(unsigned short)(class_table[slot]-1);
+ states[node]=overlapping_node_class[node]
+ | (Run_Stays_In_Order(state,textures) ? (unsigned short)SortingRendererClass::SORT_STATE_FIXED : 0);
+ }
+}
+
// ----------------------------------------------------------------------------
static inline bool Entry_Is_Quad(const TempIndexStruct& entry)
@@ -682,17 +761,241 @@ static void Write_Batch_Indices(int chunk,void* context)
}
}
-// Draw one batch of the sorted entries, in that order.
+// ----------------------------------------------------------------------------
+// Runs. Nearly every sorted entry was a draw of its own in a big battle: two fires a screen apart
+// burn at the same depths, the sort interleaves their quads, and the state flipped at every one.
+// Blending orders only the draws that land on one pixel, so an entry may move back past entries
+// that share no pixel with it and join the last run of its own state; every pixel still blends the
+// same draws in the same order, so the picture is the same to the bit. Where an entry can reach is
+// worked out on SORT_TILE_GRID by SORT_TILE_GRID tiles of the viewport: an entry's tiles hold every
+// pixel it can touch, found from its corners through the projection with a margin, and anything
+// whose corners cannot be put on the screen that way covers all of it.
+
+static const unsigned TILE_GRID=SortingRendererClass::SORT_TILE_GRID;
+// How many runs back an entry looks for its own state.
+static const unsigned RUN_LOOK_BACK=64;
+// Past the rasterizer's snapping (a 256th of a pixel) and the CPU's rounding of the corners against
+// the GPU's (a millionth of the width), in the viewport's own units, two across: 1.3 pixels at 1280.
+static const float TILE_MARGIN=0.002f;
+// A corner this close to the eye, or behind it, puts the entry on the whole screen.
+static const float TILE_NEAREST_W=1.0e-3f;
+
+// Each pooled node's world, view and projection in one, for its entries' tiles.
+static D3DXMATRIX overlapping_node_clip[MAX_OVERLAPPING_NODES];
+static D3DXMATRIX sort_projection;
+static unsigned short overlapping_node_state[MAX_OVERLAPPING_NODES];
+
+// The arrays only grow, and only on the render thread.
+static unsigned short* entry_states;
+static SortingRendererClass::SortTiles* entry_tiles;
+static unsigned* entry_order;
+static unsigned entry_arrays_count;
+static unsigned* group_entry_run;
+static unsigned* group_run_start;
+static unsigned group_arrays_count;
+
+static void Reserve_Entry_Arrays(unsigned count)
+{
+ if (count<=entry_arrays_count) return;
+ delete[] entry_states;
+ delete[] entry_tiles;
+ delete[] entry_order;
+ entry_states=W3DNEWARRAY unsigned short[count];
+ entry_tiles=W3DNEWARRAY SortingRendererClass::SortTiles[count];
+ entry_order=W3DNEWARRAY unsigned[count];
+ entry_arrays_count=count;
+}
+
+static void Release_Entry_Arrays()
+{
+ delete[] entry_states;
+ delete[] entry_tiles;
+ delete[] entry_order;
+ delete[] group_entry_run;
+ delete[] group_run_start;
+ entry_states=NULL;
+ entry_tiles=NULL;
+ entry_order=NULL;
+ group_entry_run=NULL;
+ group_run_start=NULL;
+ entry_arrays_count=0;
+ group_arrays_count=0;
+}
+
+// NaN goes to the screen's edge on either side, so a broken corner widens the range.
+static inline unsigned char Low_Tile(float ndc)
+{
+ const float tile=(ndc-TILE_MARGIN+1.0f)*(0.5f*TILE_GRID);
+ if (!(tile>0.0f)) return 0;
+ return (tile<(float)(TILE_GRID-1)) ? (unsigned char)tile : (unsigned char)(TILE_GRID-1);
+}
+
+static inline unsigned char High_Tile(float ndc)
+{
+ const float tile=(ndc+TILE_MARGIN+1.0f)*(0.5f*TILE_GRID);
+ if (!(tile<(float)(TILE_GRID-1))) return (unsigned char)(TILE_GRID-1);
+ return (tile>0.0f) ? (unsigned char)tile : 0;
+}
+
+static SortingRendererClass::SortTiles Whole_Grid()
+{
+ SortingRendererClass::SortTiles tiles;
+ tiles.x0=0;
+ tiles.x1=(unsigned char)(TILE_GRID-1);
+ tiles.y0=0;
+ tiles.y1=(unsigned char)(TILE_GRID-1);
+ return tiles;
+}
+
+// The corners go through the same three matrices the draw's vertex program multiplies them by. With
+// every corner in front of the eye a triangle's picture is the triangle of its corners' pictures, and
+// clipping only takes from it.
+SortingRendererClass::SortTiles SortingRendererClass::_Entry_Tiles(const float* const* corners,
+ unsigned corner_count,const float* clip)
+{
+ float min_x=1.0e30f,max_x=-1.0e30f,min_y=1.0e30f,max_y=-1.0e30f;
+ for (unsigned c=0;c<corner_count;++c) {
+ const float x=corners[c][0],y=corners[c][1],z=corners[c][2];
+ const float w=x*clip[3]+y*clip[7]+z*clip[11]+clip[15];
+ if (!(w>TILE_NEAREST_W)) return Whole_Grid();
+ const float screen_x=(x*clip[0]+y*clip[4]+z*clip[8]+clip[12])/w;
+ const float screen_y=(x*clip[1]+y*clip[5]+z*clip[9]+clip[13])/w;
+ if (!(screen_x==screen_x) || !(screen_y==screen_y)) return Whole_Grid();
+ min_x=MIN(min_x,screen_x);
+ max_x=MAX(max_x,screen_x);
+ min_y=MIN(min_y,screen_y);
+ max_y=MAX(max_y,screen_y);
+ }
+ SortTiles tiles;
+ tiles.x0=Low_Tile(min_x);
+ tiles.x1=High_Tile(max_x);
+ tiles.y0=Low_Tile(min_y);
+ tiles.y1=High_Tile(max_y);
+ return tiles;
+}
+
+struct EntryTileJob
+{
+ const TempIndexStruct* entries;
+ unsigned entry_count;
+};
+
+static void Find_Entry_Tiles(int chunk,void* context)
+{
+ const EntryTileJob* job=(const EntryTileJob*)context;
+ const unsigned first=(unsigned)chunk*ENTRIES_PER_COPY_CHUNK;
+ const unsigned last=MIN(first+ENTRIES_PER_COPY_CHUNK,job->entry_count);
+ for (unsigned e=first;e<last;++e) {
+ const TempIndexStruct& entry=job->entries[e];
+ const VertexFormatXYZNDUV2* src_verts=overlapping_node_vertices[entry.idx];
+ const float* corners[4];
+ unsigned corner_count=3;
+ if (Entry_Is_Quad(entry)) {
+ for (unsigned c=0;c<4;++c) {
+ corners[c]=&src_verts[entry.tri.i+c].x;
+ }
+ corner_count=4;
+ }
+ else {
+ corners[0]=&src_verts[entry.tri.i].x;
+ corners[1]=&src_verts[entry.tri.j].x;
+ corners[2]=&src_verts[entry.tri.k].x;
+ }
+ entry_tiles[e]=SortingRendererClass::_Entry_Tiles(corners,corner_count,&overlapping_node_clip[entry.idx]._11);
+ entry_states[e]=overlapping_node_state[entry.idx];
+ }
+}
+
+struct OpenRun
+{
+ unsigned short state;
+ unsigned long long rows[TILE_GRID]; // the tiles its entries cover, a bit a column
+};
+
+unsigned SortingRendererClass::_Group_Runs(const unsigned short* states,const SortTiles* tiles,
+ unsigned count,unsigned* order)
+{
+ if (count>group_arrays_count) {
+ delete[] group_entry_run;
+ delete[] group_run_start;
+ group_entry_run=W3DNEWARRAY unsigned[count];
+ group_run_start=W3DNEWARRAY unsigned[count];
+ group_arrays_count=count;
+ }
+ static OpenRun open_runs[RUN_LOOK_BACK];
+ unsigned runs=0;
+ for (unsigned e=0;e<count;++e) {
+ const unsigned short state=states[e];
+ const SortTiles& at=tiles[e];
+ const unsigned long long columns=(2ull<<at.x1)-(1ull<<at.x0);
+ unsigned run=runs;
+ const unsigned oldest=(runs>RUN_LOOK_BACK) ? runs-RUN_LOOK_BACK : 0;
+ for (unsigned r=runs;r-->oldest;) {
+ const OpenRun& open=open_runs[r%RUN_LOOK_BACK];
+ if (open.state==state) {
+ run=r;
+ break;
+ }
+ if ((state|open.state)&SORT_STATE_FIXED) break;
+ bool shared=false;
+ for (unsigned y=at.y0;y<=at.y1 && !shared;++y) {
+ shared=(open.rows[y]&columns)!=0;
+ }
+ if (shared) break;
+ }
+ OpenRun& target=open_runs[run%RUN_LOOK_BACK];
+ if (run==runs) {
+ target.state=state;
+ memset(target.rows,0,sizeof(target.rows));
+ group_run_start[run]=0;
+ ++runs;
+ }
+ for (unsigned y=at.y0;y<=at.y1;++y) {
+ target.rows[y]|=columns;
+ }
+ group_entry_run[e]=run;
+ ++group_run_start[run];
+ }
+
+ // Each run's entries in the order the sort gave them, the runs in the order they opened.
+ unsigned start=0;
+ for (unsigned r=0;r<runs;++r) {
+ const unsigned entries_in_run=group_run_start[r];
+ group_run_start[r]=start;
+ start+=entries_in_run;
+ }
+ for (unsigned e=0;e<count;++e) {
+ order[group_run_start[group_entry_run[e]]++]=e;
+ }
+ return runs;
+}
+
+// The run's state is any of its nodes': they are all one class.
+static void Draw_Run(SortingNodeStruct* state,unsigned first_index,unsigned triangles,
+ unsigned first_vertex,unsigned vertex_count)
+{
+ Apply_Render_State(state->sorting_state);
+ SunShadow::SetSmokeGlow(DX8Wrapper::_Get_D3D_Device(),state->glow);
+ Direct3D11_Set_Fire_Look(state->fire);
+ Direct3D11_Set_Emissive(state->emissive);
+ Direct3D11_Set_Soft_Particles(state->quads);
+ Direct3D11_Set_Draw_Effect(state->draw_effect,state->draw_effect_parameters);
+ SunShadow::ReceiverExclusion sunReceivers(DX8Wrapper::_Get_D3D_Device(), state->excludeSunReceivers);
+ SunShadow::CasterEffectScope casterEffect(DX8Wrapper::_Get_D3D_Device(), state->casterEffect);
+ DX8Wrapper::Draw_Triangles(first_index,triangles,first_vertex,vertex_count);
+}
+
+// Draw one batch of the entries, in the order _Group_Runs gave them.
//
// Each entry's vertices are copied out of its node on their own - three for a triangle, four for a
// quad - so a run of entries covers one contiguous stretch of the batch's vertices and indices. A
// quad's indices are the pattern PointGroupClass's own quad index buffers use.
//
-// A run ends where the sorted entries move to another node, and it used to be drawn there even
-// when the next node draws with exactly the same state - thirty inferno cannons each with its own
-// fire system on the same texture, interleaved in depth, were a draw every few triangles. A run
-// carries on across nodes whose state matches. The order of the entries does not change, so
-// neither does the picture.
+// A run carries on across nodes of one class and ends where the class changes. Thirty inferno
+// cannons each with its own fire system on the same texture, interleaved in depth, used to be a
+// draw every few triangles; _Group_Runs has already moved each entry back past the entries in
+// other tiles to the last run of its class, so every pixel blends the same draws in the depth
+// sort's order and the picture does not change.
static void Flush_Sorting_Batch(const TempIndexStruct* entries,unsigned entry_count,unsigned vertex_count,unsigned index_count)
{
BatchCopyJob job;
@@ -743,50 +1046,21 @@ static void Flush_Sorting_Batch(const TempIndexStruct* entries,unsigned entry_co
unsigned run_triangles=0;
unsigned index_cursor=0;
unsigned vertex_cursor=0;
- unsigned node_id=entries[0].idx;
+ unsigned run_class=overlapping_node_class[entries[0].idx];
for (unsigned e=0;e<entry_count;++e) {
- const unsigned entry_node=entries[e].idx;
- if (entry_node!=node_id) {
- SortingNodeStruct* state=overlapping_nodes[node_id];
- SortingNodeStruct* next=overlapping_nodes[entry_node];
- // A run of billboards fades into the depth behind it and a run of meshes does not, so the
- // two never share a draw even in one state.
- if (state->glow!=next->glow || state->fire!=next->fire || state->emissive!=next->emissive ||
- state->quads!=next->quads || !Same_Draw_Effect(state,next) ||
- state->excludeSunReceivers!=next->excludeSunReceivers ||
- !(state->casterEffect==next->casterEffect) ||
- !Same_Draw_State(state->sorting_state,next->sorting_state)) {
- Apply_Render_State(state->sorting_state);
- SunShadow::SetSmokeGlow(DX8Wrapper::_Get_D3D_Device(),state->glow);
- Direct3D11_Set_Fire_Look(state->fire);
- Direct3D11_Set_Emissive(state->emissive);
- Direct3D11_Set_Soft_Particles(state->quads);
- Direct3D11_Set_Draw_Effect(state->draw_effect,state->draw_effect_parameters);
- SunShadow::ReceiverExclusion sunReceivers(DX8Wrapper::_Get_D3D_Device(), state->excludeSunReceivers);
- SunShadow::CasterEffectScope casterEffect(DX8Wrapper::_Get_D3D_Device(), state->casterEffect);
- DX8Wrapper::Draw_Triangles(run_first_index,run_triangles,run_first_vertex,vertex_cursor-run_first_vertex);
- run_first_index=index_cursor;
- run_first_vertex=vertex_cursor;
- run_triangles=0;
- }
- node_id=entry_node;
+ const unsigned entry_class=overlapping_node_class[entries[e].idx];
+ if (entry_class!=run_class) {
+ Draw_Run(overlapping_nodes[run_class],run_first_index,run_triangles,run_first_vertex,vertex_cursor-run_first_vertex);
+ run_first_index=index_cursor;
+ run_first_vertex=vertex_cursor;
+ run_triangles=0;
+ run_class=entry_class;
}
run_triangles+=Entry_Is_Quad(entries[e]) ? 2 : 1;
index_cursor+=Entry_Index_Count(entries[e]);
vertex_cursor+=Entry_Vertex_Count(entries[e]);
}
-
- Apply_Render_State(overlapping_nodes[node_id]->sorting_state);
- SunShadow::SetSmokeGlow(DX8Wrapper::_Get_D3D_Device(),overlapping_nodes[node_id]->glow);
- Direct3D11_Set_Fire_Look(overlapping_nodes[node_id]->fire);
- Direct3D11_Set_Emissive(overlapping_nodes[node_id]->emissive);
- Direct3D11_Set_Soft_Particles(overlapping_nodes[node_id]->quads);
- Direct3D11_Set_Draw_Effect(overlapping_nodes[node_id]->draw_effect,overlapping_nodes[node_id]->draw_effect_parameters);
- {
- SunShadow::ReceiverExclusion sunReceivers(DX8Wrapper::_Get_D3D_Device(), overlapping_nodes[node_id]->excludeSunReceivers);
- SunShadow::CasterEffectScope casterEffect(DX8Wrapper::_Get_D3D_Device(), overlapping_nodes[node_id]->casterEffect);
- DX8Wrapper::Draw_Triangles(run_first_index,run_triangles,run_first_vertex,vertex_cursor-run_first_vertex);
- }
+ Draw_Run(overlapping_nodes[run_class],run_first_index,run_triangles,run_first_vertex,vertex_cursor-run_first_vertex);
SunShadow::SetSmokeGlow(DX8Wrapper::_Get_D3D_Device(),false);
Direct3D11_Set_Fire_Look(false);
Direct3D11_Set_Emissive(false);
@@ -814,6 +1088,11 @@ void SortingRendererClass::Flush_Sorting_Pool()
SNAPSHOT_SAY(("SortingSystem - Flush \n"));
+ // The draws' projection, which no run sets, for the entries' tiles.
+ Matrix4x4 projection;
+ DX8Wrapper::_Get_DX8_Transform(D3DTS_PROJECTION,projection);
+ sort_projection=(D3DXMATRIX&)projection;
+
// Before any run resolves its program: the soft particles fade into this copy of the depth, and
// a sorted mesh writing depth between two of their runs costs no second one. A pool with no
// billboards in it takes none.
@@ -842,6 +1121,7 @@ void SortingRendererClass::Flush_Sorting_Pool()
D3DXMATRIX d3d_mtx=(D3DXMATRIX&)state->sorting_state.world*(D3DXMATRIX&)state->sorting_state.view;
const Matrix4x4& mtx=(const Matrix4x4&)d3d_mtx;
const bool camera_space=(mtx[0][2] == 0.0f && mtx[1][2] == 0.0f && mtx[3][2] == 0.0f && mtx[2][2] == 1.0f);
+ overlapping_node_clip[node_id]=d3d_mtx*sort_projection;
if (state->quads) {
const int quad_count=state->polygon_count/2;
@@ -939,6 +1219,19 @@ void SortingRendererClass::Flush_Sorting_Pool()
const TempIndexStruct* sorted=Sort_By_Depth(tis,temp_sort_scratch_array,overlapping_entry_count);
+ // The runs, drawn from the radix sort's other buffer.
+ Classify_Nodes(overlapping_node_count,overlapping_node_state);
+ Reserve_Entry_Arrays(overlapping_entry_count);
+ EntryTileJob tile_job;
+ tile_job.entries=sorted;
+ tile_job.entry_count=overlapping_entry_count;
+ Run_Parallel((int)((overlapping_entry_count+ENTRIES_PER_COPY_CHUNK-1)/ENTRIES_PER_COPY_CHUNK),1,Find_Entry_Tiles,&tile_job);
+ _Group_Runs(entry_states,entry_tiles,overlapping_entry_count,entry_order);
+ TempIndexStruct* grouped=(sorted==temp_index_array) ? temp_sort_scratch_array : temp_index_array;
+ for (unsigned e=0;e<overlapping_entry_count;++e) {
+ grouped[e]=sorted[entry_order[e]];
+ }
+
tSortEnd = Clock_Ticks();
flush_profile_sort_ms += flushProfileElapsedMS(tSortStart, tSortEnd);
@@ -948,8 +1241,8 @@ void SortingRendererClass::Flush_Sorting_Pool()
unsigned batch_vertices=0;
unsigned batch_indices=0;
while (batch_end<overlapping_entry_count) {
- const unsigned vertices=Entry_Vertex_Count(sorted[batch_end]);
- const unsigned indices=Entry_Index_Count(sorted[batch_end]);
+ const unsigned vertices=Entry_Vertex_Count(grouped[batch_end]);
+ const unsigned indices=Entry_Index_Count(grouped[batch_end]);
if (batch_vertices+vertices>MAX_BATCH_VERTICES || batch_indices+indices>MAX_BATCH_INDICES) {
break;
}
@@ -957,7 +1250,7 @@ void SortingRendererClass::Flush_Sorting_Pool()
batch_indices+=indices;
++batch_end;
}
- Flush_Sorting_Batch(sorted+batch_start,batch_end-batch_start,batch_vertices,batch_indices);
+ Flush_Sorting_Batch(grouped+batch_start,batch_end-batch_start,batch_vertices,batch_indices);
batch_start=batch_end;
}
@@ -1074,6 +1367,7 @@ void SortingRendererClass::Deinit()
delete[] batch_offsets;
batch_offsets=NULL;
batch_offsets_count=0;
+ Release_Entry_Arrays();
}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/sortingrenderer.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/sortingrenderer.h
index 34a3dc936..a1aa415ca 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/sortingrenderer.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/sortingrenderer.h
@@ -104,6 +104,25 @@ public:
return (bits&0x80000000u) ? 0x7FFFFFFFu-magnitude : 0x80000000u+magnitude;
}
+ /// The pixels a sorted entry can touch, as an inclusive range of the SORT_TILE_GRID by
+ /// SORT_TILE_GRID tiles the viewport is cut into. Two entries in no common tile share no pixel.
+ enum { SORT_TILE_GRID = 64 };
+ struct SortTiles { unsigned char x0, x1, y0, y1; };
+ /// The tiles an entry's corners reach through clip, the world, view and projection its draw
+ /// multiplies them by as sixteen floats in D3DX order. Each corner points at its x, y and z:
+ /// three are a triangle, four a quad. The range is widened by a margin past the rasterizer's
+ /// snapping, and a corner at or behind the eye, or one that comes out NaN, covers the whole grid.
+ static SortTiles _Entry_Tiles(const float* const* corners, unsigned corner_count, const float* clip);
+ /// An entry's draw state for _Group_Runs with this bit set is one nothing may pass and that
+ /// joins no earlier run: it stays exactly where the depth sort put it.
+ enum { SORT_STATE_FIXED = 0x8000 };
+ /// The order a flush draws its depth sorted entries in. An entry joins the latest earlier run of
+ /// its own draw state when every entry it would pass lies in other tiles, so each pixel still
+ /// blends the same draws in the same order; otherwise it stays where the sort put it. Writes the
+ /// drawing order, entry indices, into order[] and returns how many runs that makes.
+ static unsigned _Group_Runs(const unsigned short* states, const SortTiles* tiles, unsigned count,
+ unsigned* order);
+
static void _Enable_Triangle_Draw(bool enable) { _EnableTriangleDraw=enable; }
static bool _Is_Triangle_Draw_Enabled() { return _EnableTriangleDraw; }
};
diff --git a/GeneralsMD/Code/Tests/test_dx11backend.cpp b/GeneralsMD/Code/Tests/test_dx11backend.cpp
index 259e9acbc..97820a1ee 100644
--- a/GeneralsMD/Code/Tests/test_dx11backend.cpp
+++ b/GeneralsMD/Code/Tests/test_dx11backend.cpp
@@ -603,6 +603,178 @@ TEST(dx11backend_a_wrapped_constant_ring_draws_with_the_latest_block)
backend.Shutdown();
}
+// The sorted runs flip between a few pixel blocks, so a block still in the ring is bound again at
+// the entry it was written to rather than written again (Rebind_Recent_Pixel_Constants). Two texture
+// factors alternate with two fresh ones after each pair, which takes both out of the four the
+// backend remembers every other round, and the rounds go on until the ring has wrapped more than
+// once. A block bound again from before a wrap, where later writes have gone since, draws another
+// colour.
+TEST(dx11backend_a_pixel_block_bound_again_draws_its_own_colour_across_a_ring_wrap)
+{
+ const unsigned ROUNDS = 1500;
+ const DWORD FACTORS[2] = { 0xff112233, 0xff445566 };
+ const DWORD FRESH_FACTOR = 0xff800000;
+
+ DX11DeviceClass device;
+ CHECK(device.Create_Offscreen());
+ ID3D11Device * d3d = device.Get_Device();
+
+ DX11BackendClass backend;
+ CHECK(backend.Initialise(&device));
+
+ D3D11_TEXTURE2D_DESC target_description;
+ memset(&target_description, 0, sizeof(target_description));
+ target_description.Width = TARGET_SIZE;
+ target_description.Height = TARGET_SIZE;
+ target_description.MipLevels = 1;
+ target_description.ArraySize = 1;
+ target_description.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
+ target_description.SampleDesc.Count = 1;
+ target_description.Usage = D3D11_USAGE_DEFAULT;
+ target_description.BindFlags = D3D11_BIND_RENDER_TARGET;
+
+ ID3D11Texture2D * target = NULL;
+ CHECK(SUCCEEDED(d3d->CreateTexture2D(&target_description, NULL, &target)));
+
+ D3D11_TEXTURE2D_DESC staging_description = target_description;
+ staging_description.Usage = D3D11_USAGE_STAGING;
+ staging_description.BindFlags = 0;
+ staging_description.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
+
+ ID3D11Texture2D * staging = NULL;
+ CHECK(SUCCEEDED(d3d->CreateTexture2D(&staging_description, NULL, &staging)));
+
+ ID3D11RenderTargetView * target_view = NULL;
+ CHECK(SUCCEEDED(d3d->CreateRenderTargetView(target, NULL, &target_view)));
+ device.Get_Context()->OMSetRenderTargets(1, &target_view, NULL);
+
+ backend.Set_Viewport(0, 0, TARGET_SIZE, TARGET_SIZE);
+ configure_unlit_pass_through(backend);
+ backend.Set_Texture_Stage_State(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
+ backend.Set_Texture_Stage_State(0, D3DTSS_ALPHAARG1, D3DTA_TFACTOR);
+
+ ID3D11Buffer * vertices = NULL;
+ CHECK(DX11Resource_Create_Vertex_Buffer(d3d, sizeof(QUAD_VERTICES), D3DPOOL_MANAGED, 0,
+ QUAD_VERTICES, &vertices));
+ ID3D11Buffer * indices = NULL;
+ CHECK(DX11Resource_Create_Index_Buffer(d3d, sizeof(QUAD_INDICES), D3DPOOL_MANAGED, 0,
+ QUAD_INDICES, &indices));
+ backend.Set_Stream_Source(vertices, sizeof(BackendVertex), 0);
+ backend.Set_Indices(indices, DXGI_FORMAT_R16_UINT);
+
+ unsigned wrong = 0;
+ for (unsigned round = 0; round < ROUNDS; ++round) {
+ for (unsigned pick = 0; pick < 2; ++pick) {
+ backend.Set_Render_State(D3DRS_TEXTUREFACTOR, FACTORS[pick]);
+ CHECK(backend.Draw_Indexed_Triangles(6, 0, 0));
+
+ device.Get_Context()->CopyResource(staging, target);
+ D3D11_MAPPED_SUBRESOURCE mapped;
+ CHECK(SUCCEEDED(device.Get_Context()->Map(staging, 0, D3D11_MAP_READ, 0, &mapped)));
+ const unsigned char * centre = static_cast<const unsigned char *>(mapped.pData)
+ + mapped.RowPitch * (TARGET_SIZE / 2) + (TARGET_SIZE / 2) * 4;
+ const DWORD drawn = (static_cast<DWORD>(centre[3]) << 24) | (centre[2] << 16)
+ | (centre[1] << 8) | centre[0];
+ if (drawn != FACTORS[pick]) {
+ if (wrong == 0) {
+ printf(" round %u factor %08x drew %08x\n", round, FACTORS[pick], drawn);
+ }
+ ++wrong;
+ }
+ device.Get_Context()->Unmap(staging, 0);
+ }
+ for (unsigned fresh = 0; fresh < 2; ++fresh) {
+ backend.Set_Render_State(D3DRS_TEXTUREFACTOR, FRESH_FACTOR | (round * 2 + fresh));
+ CHECK(backend.Draw_Indexed_Triangles(6, 0, 0));
+ }
+ }
+ CHECK_EQ(wrong, 0u);
+
+ // Fewer pixel blocks written than drawn, so the two were bound again, and the vertex ring's
+ // first write and the pixel ring's first write and two wraps at least.
+ unsigned writes = 0;
+ unsigned renames = 0;
+ backend.Take_Frame_Constant_Writes(writes, renames);
+ printf(" %u constant writes, %u renames over %u draws\n", writes, renames, ROUNDS * 4);
+ if (backend.Constant_Offsets()) {
+ CHECK(writes < ROUNDS * 4);
+ CHECK(renames >= 4u);
+ }
+
+ indices->Release();
+ vertices->Release();
+ target_view->Release();
+ staging->Release();
+ target->Release();
+ backend.Shutdown();
+}
+
+// A pass multiplying what is under it goes up without the blast lights: the pass under it took
+// them, and the multiply would light the surface twice. A blend change raises no constant flag of
+// its own, so the pixel block is built again only when Pixel_Blend_Key moves, and the multiply test
+// is part of it. Read through the block the draw went up with: the multiply passes that read the
+// lights are the terrain's programs, and a generated multiply program samples none.
+TEST(dx11backend_a_multiply_pass_goes_up_without_the_blast_lights)
+{
+ DX11DeviceClass device;
+ CHECK(device.Create_Offscreen());
+ ID3D11Device * d3d = device.Get_Device();
+
+ DX11BackendClass backend;
+ CHECK(backend.Initialise(&device));
+
+ D3D11_TEXTURE2D_DESC target_description;
+ memset(&target_description, 0, sizeof(target_description));
+ target_description.Width = TARGET_SIZE;
+ target_description.Height = TARGET_SIZE;
+ target_description.MipLevels = 1;
+ target_description.ArraySize = 1;
+ target_description.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
+ target_description.SampleDesc.Count = 1;
+ target_description.Usage = D3D11_USAGE_DEFAULT;
+ target_description.BindFlags = D3D11_BIND_RENDER_TARGET;
+
+ ID3D11Texture2D * target = NULL;
+ CHECK(SUCCEEDED(d3d->CreateTexture2D(&target_description, NULL, &target)));
+ ID3D11RenderTargetView * target_view = NULL;
+ CHECK(SUCCEEDED(d3d->CreateRenderTargetView(target, NULL, &target_view)));
+
+ configure_unlit_pass_through(backend);
+ CHECK(backend.Begin_Shadow_Map(64));
+ backend.End_Shadow_Map();
+ backend.Set_Shadow_Parameters(0.001f, 0.5f, 2.0f, 1.0f, 1.0f, 1.0f, 0.0f);
+ const float blast[BLAST_LIGHT_FLOATS] = {
+ 0.0f, 0.0f, 0.5f, 10.0f, 1.0f, 0.5f, 0.25f, 1.0f, 0.1f, 0.1f, 0.1f, 0.0f };
+ backend.Set_Blast_Lights(blast, 1);
+
+ device.Get_Context()->OMSetRenderTargets(1, &target_view, NULL);
+ backend.Set_Viewport(0, 0, TARGET_SIZE, TARGET_SIZE);
+
+ ID3D11Buffer * vertices = NULL;
+ CHECK(DX11Resource_Create_Vertex_Buffer(d3d, sizeof(QUAD_VERTICES), D3DPOOL_MANAGED, 0,
+ QUAD_VERTICES, &vertices));
+ ID3D11Buffer * indices = NULL;
+ CHECK(DX11Resource_Create_Index_Buffer(d3d, sizeof(QUAD_INDICES), D3DPOOL_MANAGED, 0,
+ QUAD_INDICES, &indices));
+ backend.Set_Stream_Source(vertices, sizeof(BackendVertex), 0);
+ backend.Set_Indices(indices, DXGI_FORMAT_R16_UINT);
+
+ backend.Set_Render_State(D3DRS_ALPHABLENDENABLE, TRUE);
+ for (unsigned pass = 0; pass < 3; ++pass) {
+ const bool multiply = pass == 1;
+ backend.Set_Render_State(D3DRS_SRCBLEND, multiply ? D3DBLEND_ZERO : D3DBLEND_SRCALPHA);
+ backend.Set_Render_State(D3DRS_DESTBLEND, multiply ? D3DBLEND_SRCCOLOR : D3DBLEND_INVSRCALPHA);
+ CHECK(backend.Draw_Indexed_Triangles(6, 0, 0));
+ CHECK_EQ(backend.Pixel_Block_Blast_Lights(), multiply ? 0u : 1u);
+ }
+
+ indices->Release();
+ vertices->Release();
+ target_view->Release();
+ target->Release();
+ backend.Shutdown();
+}
+
// The sorted smoke billboards carry a fire's glow in their normals, and the backend adds it to what
// the stages made. The quad's normal is (0, 0, 1), so with the glow on the blue channel goes to full
// and the other two keep the vertex colour; the glow is its own pipeline and turning it off goes
diff --git a/GeneralsMD/Code/Tests/test_ww3d2.cpp b/GeneralsMD/Code/Tests/test_ww3d2.cpp
index beb1d4ed0..0fce7d14c 100644
--- a/GeneralsMD/Code/Tests/test_ww3d2.cpp
+++ b/GeneralsMD/Code/Tests/test_ww3d2.cpp
@@ -1767,6 +1767,7 @@ TEST(surface_draw_h_line_fills_the_run_inclusive_at_both_ends)
// and nothing on screen would say why, so the ordering is pinned here across the sign.
// ---------------------------------------------------------------------------------------------
#include "sortingrenderer.h"
+#include <limits>
TEST(sorting_depth_key_orders_the_way_the_depths_do)
{
@@ -1779,3 +1780,187 @@ TEST(sorting_depth_key_orders_the_way_the_depths_do)
/* the same depth twice is the same key, which is what keeps equal depths in pooled order */
CHECK_EQ( SortingRendererClass::_Depth_Sort_Key( 3.25f ), SortingRendererClass::_Depth_Sort_Key( 3.25f ) );
}
+
+// ---------------------------------------------------------------------------------------------
+// The flush draws its sorted entries in runs, and an entry moves back past entries in other tiles
+// to join the last run of its own state. The picture holds because two entries sharing a tile are
+// drawn in the order the sort gave them, and nothing passes a fixed entry or is passed by one. Two
+// fires on either side of the screen interleaved in depth are what it is for: two runs, not eight.
+// ---------------------------------------------------------------------------------------------
+static bool sort_tiles_meet( const SortingRendererClass::SortTiles & a, const SortingRendererClass::SortTiles & b )
+{
+ return a.x0 <= b.x1 && b.x0 <= a.x1 && a.y0 <= b.y1 && b.y0 <= a.y1;
+}
+
+static void set_sort_tiles( SortingRendererClass::SortTiles & tiles, unsigned x0, unsigned x1, unsigned y0, unsigned y1 )
+{
+ tiles.x0 = (unsigned char)x0;
+ tiles.x1 = (unsigned char)x1;
+ tiles.y0 = (unsigned char)y0;
+ tiles.y1 = (unsigned char)y1;
+}
+
+TEST(sorting_runs_join_only_past_entries_in_other_tiles)
+{
+ enum { MOST = 400 };
+ unsigned short states[ MOST ];
+ SortingRendererClass::SortTiles tiles[ MOST ];
+ unsigned order[ MOST ];
+ unsigned position[ MOST ];
+
+ /* two fires a screen apart, interleaved in depth */
+ for( unsigned e = 0; e < 8; ++e ) {
+ states[ e ] = (unsigned short)( e & 1 );
+ const unsigned x = ( e & 1 ) ? 28 : 2;
+ set_sort_tiles( tiles[ e ], x, x + 1, 10, 12 );
+ }
+ CHECK_EQ( SortingRendererClass::_Group_Runs( states, tiles, 8, order ), 2u );
+ for( unsigned k = 0; k < 4; ++k ) {
+ CHECK_EQ( order[ k ], 2 * k );
+ CHECK_EQ( order[ 4 + k ], 2 * k + 1 );
+ }
+
+ /* the same two over one another stay where the sort put them */
+ for( unsigned e = 0; e < 8; ++e )
+ set_sort_tiles( tiles[ e ], 10, 12, 10, 12 );
+ CHECK_EQ( SortingRendererClass::_Group_Runs( states, tiles, 8, order ), 8u );
+ for( unsigned k = 0; k < 8; ++k )
+ CHECK_EQ( order[ k ], k );
+
+ /* random pools of six states, the last of them fixed */
+ unsigned seed = 20261027u;
+ for( int pool = 0; pool < 300; ++pool ) {
+ seed = seed * 1664525u + 1013904223u;
+ const unsigned count = 1 + ( seed >> 8 ) % MOST;
+ for( unsigned e = 0; e < count; ++e ) {
+ seed = seed * 1664525u + 1013904223u;
+ const unsigned state = ( seed >> 8 ) % 6;
+ states[ e ] = (unsigned short)( state == 5 ? ( state | SortingRendererClass::SORT_STATE_FIXED ) : state );
+ const unsigned last = SortingRendererClass::SORT_TILE_GRID - 1;
+ const unsigned x = ( seed >> 12 ) % ( last + 1 ), y = ( seed >> 18 ) % ( last + 1 );
+ const unsigned span = ( ( seed >> 24 ) % 16 == 0 ) ? last : ( seed >> 28 ) % 6;
+ set_sort_tiles( tiles[ e ], x, x + span > last ? last : x + span, y, y + span > last ? last : y + span );
+ }
+ const unsigned runs = SortingRendererClass::_Group_Runs( states, tiles, count, order );
+
+ for( unsigned e = 0; e < count; ++e )
+ position[ e ] = MOST;
+ for( unsigned k = 0; k < count; ++k ) {
+ CHECK( order[ k ] < count );
+ CHECK_EQ( position[ order[ k ] ], (unsigned)MOST ); /* each entry once */
+ position[ order[ k ] ] = k;
+ }
+ unsigned changes = 0;
+ for( unsigned k = 1; k < count; ++k )
+ changes += states[ order[ k ] ] != states[ order[ k - 1 ] ];
+ CHECK_EQ( changes + 1, runs );
+
+ for( unsigned i = 0; i < count; ++i ) {
+ for( unsigned j = i + 1; j < count; ++j ) {
+ const bool held = sort_tiles_meet( tiles[ i ], tiles[ j ] )
+ || ( ( states[ i ] | states[ j ] ) & SortingRendererClass::SORT_STATE_FIXED );
+ if( held )
+ CHECK( position[ i ] < position[ j ] );
+ }
+ }
+ }
+}
+
+// ---------------------------------------------------------------------------------------------
+// An entry looks RUN_LOOK_BACK (64) runs back for its own state and no further, through a ring of
+// that many open runs. Seventy states each in a tile of its own, cycled twice, put every second
+// entry's run seventy runs back: out of reach, so nothing joins, and no entry takes a ring slot a
+// later run has reused for its old run. Sixty states cycled twice are in reach and pair up.
+// ---------------------------------------------------------------------------------------------
+static void set_state_tile( SortingRendererClass::SortTiles & tiles, unsigned state )
+{
+ const unsigned x = ( state % 32 ) * 2, y = ( state / 32 ) * 2;
+ set_sort_tiles( tiles, x, x, y, y );
+}
+
+TEST(sorting_runs_look_back_no_further_than_the_window)
+{
+ enum { PAST_REACH = 70, IN_REACH = 60 };
+ unsigned short states[ 2 * PAST_REACH ];
+ SortingRendererClass::SortTiles tiles[ 2 * PAST_REACH ];
+ unsigned order[ 2 * PAST_REACH ];
+
+ for( unsigned e = 0; e < 2 * PAST_REACH; ++e ) {
+ states[ e ] = (unsigned short)( e % PAST_REACH );
+ set_state_tile( tiles[ e ], e % PAST_REACH );
+ }
+ CHECK_EQ( SortingRendererClass::_Group_Runs( states, tiles, 2 * PAST_REACH, order ), 2u * PAST_REACH );
+ for( unsigned k = 0; k < 2 * PAST_REACH; ++k )
+ CHECK_EQ( order[ k ], k );
+
+ for( unsigned e = 0; e < 2 * IN_REACH; ++e ) {
+ states[ e ] = (unsigned short)( e % IN_REACH );
+ set_state_tile( tiles[ e ], e % IN_REACH );
+ }
+ CHECK_EQ( SortingRendererClass::_Group_Runs( states, tiles, 2 * IN_REACH, order ), (unsigned)IN_REACH );
+ for( unsigned state = 0; state < IN_REACH; ++state ) {
+ CHECK_EQ( order[ 2 * state ], state );
+ CHECK_EQ( order[ 2 * state + 1 ], state + IN_REACH );
+ }
+}
+
+// ---------------------------------------------------------------------------------------------
+// An entry's tiles are its corners taken through the matrix its draw uses, widened past the
+// rasterizer's snapping. Two triangles a thousandth either side of a tile's edge share a tile,
+// since a pixel on the edge can go to either; two a screen apart share none; a quad reaches its
+// fourth corner; and a corner the projection cannot put on the screen covers the whole grid.
+// ---------------------------------------------------------------------------------------------
+static SortingRendererClass::SortTiles sort_tiles_of( const float corners[][ 3 ], unsigned count, const float clip[ 16 ] )
+{
+ const float * pointers[ 4 ];
+ for( unsigned c = 0; c < count; ++c )
+ pointers[ c ] = corners[ c ];
+ return SortingRendererClass::_Entry_Tiles( pointers, count, clip );
+}
+
+static bool sort_tiles_whole( const SortingRendererClass::SortTiles & tiles )
+{
+ const unsigned last = SortingRendererClass::SORT_TILE_GRID - 1;
+ return tiles.x0 == 0 && tiles.x1 == last && tiles.y0 == 0 && tiles.y1 == last;
+}
+
+TEST(sorting_entry_tiles_come_from_the_corners_with_a_margin)
+{
+ /* w is the corner's z, so a corner at z 1 lands where its x and y say */
+ const float clip[ 16 ] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 };
+
+ /* x 0 is the edge between tiles 31 and 32 */
+ const float left[ 3 ][ 3 ] = { { -0.3f, -0.1f, 1.0f }, { -0.001f, -0.1f, 1.0f }, { -0.001f, 0.1f, 1.0f } };
+ const float right[ 3 ][ 3 ] = { { 0.001f, -0.1f, 1.0f }, { 0.3f, -0.1f, 1.0f }, { 0.001f, 0.1f, 1.0f } };
+ const SortingRendererClass::SortTiles left_tiles = sort_tiles_of( left, 3, clip );
+ const SortingRendererClass::SortTiles right_tiles = sort_tiles_of( right, 3, clip );
+ CHECK( sort_tiles_meet( left_tiles, right_tiles ) );
+ CHECK( !sort_tiles_whole( left_tiles ) );
+ CHECK( !sort_tiles_whole( right_tiles ) );
+
+ const float far_left[ 3 ][ 3 ] = { { -0.9f, -0.1f, 1.0f }, { -0.8f, -0.1f, 1.0f }, { -0.8f, 0.1f, 1.0f } };
+ const float far_right[ 3 ][ 3 ] = { { 0.8f, -0.1f, 1.0f }, { 0.9f, -0.1f, 1.0f }, { 0.8f, 0.1f, 1.0f } };
+ const SortingRendererClass::SortTiles far_right_tiles = sort_tiles_of( far_right, 3, clip );
+ CHECK( !sort_tiles_meet( sort_tiles_of( far_left, 3, clip ), far_right_tiles ) );
+
+ /* the same far right triangle twice as deep and twice as wide lands on the same tiles */
+ const float deeper[ 3 ][ 3 ] = { { 1.6f, -0.2f, 2.0f }, { 1.8f, -0.2f, 2.0f }, { 1.6f, 0.2f, 2.0f } };
+ const SortingRendererClass::SortTiles deeper_tiles = sort_tiles_of( deeper, 3, clip );
+ CHECK_EQ( deeper_tiles.x0, far_right_tiles.x0 );
+ CHECK_EQ( deeper_tiles.x1, far_right_tiles.x1 );
+ CHECK_EQ( deeper_tiles.y0, far_right_tiles.y0 );
+ CHECK_EQ( deeper_tiles.y1, far_right_tiles.y1 );
+
+ /* a quad: the far left triangle with a fourth corner out on the right */
+ const float quad[ 4 ][ 3 ] = { { -0.9f, -0.1f, 1.0f }, { -0.8f, -0.1f, 1.0f }, { -0.8f, 0.1f, 1.0f }, { 0.85f, 0.1f, 1.0f } };
+ CHECK( sort_tiles_meet( sort_tiles_of( quad, 4, clip ), far_right_tiles ) );
+
+ /* a corner on the eye's plane, a corner that is not a number, and a matrix that makes one */
+ const float nan = std::numeric_limits< float >::quiet_NaN();
+ const float at_eye[ 3 ][ 3 ] = { { 0.1f, 0.1f, 1.0f }, { 0.2f, 0.1f, 0.0f }, { 0.2f, 0.2f, 1.0f } };
+ const float broken[ 3 ][ 3 ] = { { 0.1f, 0.1f, 1.0f }, { nan, 0.1f, 1.0f }, { 0.2f, 0.2f, 1.0f } };
+ const float broken_clip[ 16 ] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, nan, 0, 0, 0 };
+ CHECK( sort_tiles_whole( sort_tiles_of( at_eye, 3, clip ) ) );
+ CHECK( sort_tiles_whole( sort_tiles_of( broken, 3, clip ) ) );
+ CHECK( sort_tiles_whole( sort_tiles_of( far_right, 3, broken_clip ) ) );
+}