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.
C++ cmakecnccommand-and-conquercppdirectx11game-enginegame-preservationgeneralsrtssage-enginex64zero-hour
feat(w3ddevice): gpu particle overflow, a million particles on d3d11
Olcay Seygan8302fecd9700
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7dc3e1a61..791d214f3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -369,6 +369,8 @@ found and fixed — EA's own, not port damage.**- Ground painted with a third texture, the dirt over grass and the rock over sand, cost a trip to the memory manager for every corner of every such patch on screen, every frame, only to light that corner. Nearly a tenth of the game's time went to taking and releasing the memory manager's lock for it. Lighting a corner asks for nothing now: the same Twilight Flame match went from 1.88ms a frame to 1.71ms as an observer and from 2.56ms to 2.26ms from a player's seat, and eight views over five maps came out the same as before.- The command bar stopped throwing its own layout away every frame. The few hundred positions and sizes it hands its page were written into a fresh list each frame, copied twice for the frames in front of the buttons, and thrown out, and every price and build time on a button was looked up by copying the text of every figure the bar was already showing. The list is written over in place now, nothing is copied, and the graphics card settings that did not change between two draws are not looked up again. The same Twilight Flame match from a player's seat went from 2.29ms a frame to 1.96ms, and as an observer from 1.64ms to 1.58ms. The picture is the same one.- Raise the particle limit as far as you like and every puff gets drawn. Past about sixteen thousand smoke and fire sprites on screen the game quietly stopped drawing the rest: a test with 68,000 of them showed barely a fifth. A test with 101,000 now draws all of them at 8.3ms a frame, and in 1,200 frames not one fell below 60 a second. The first version that drew them all took 22.4ms; the rest came from sorting and copying them far less and from sharing the work across every core of the processor.+- Smoke no longer vanishes mid-air when the particle limit is hit, and a million particles cost about four milliseconds. At the limit the game used to delete the oldest puffs to make room, so a plume simply stopped in the sky. On Direct3D 11 the particles past the limit now go to the graphics card, which works out where each one is every frame from its birth alone and keeps it until it fades. Below the limit nothing changes. Alpine Assault with 3,350 snow systems and about 1.05 million flakes in the air took 108.6 milliseconds a frame on the old path, 224 at the slowest one in a hundred, and 83% of its frames ran over 33. The new path takes 4.42 on average, 9.25 at the slowest one in a hundred, 14.0 at the worst, and not one frame in the run fell under 60 a second. Particles that bounce or must not sink into the hill are held on the terrain by the card as well.+- Only the particles past the limit move to the card; everything under it is drawn exactly as before, with its shadows, its place in the smoke map and its sorting. The old path stays on `-d3d9`, on the Classic graphics setting, in headless runs and on macOS and Linux, and `-gpuparticles 0` turns the new one off.- Big fights no longer drag the picture down into the twenties. Every moving tank and soldier, and every puff of smoke, goes to the graphics card through one shared scratch area, and it was so small that a big fight on Bombardment Beach filled it about fifty times a frame. Each refill made the processor wait for the card, 8 to 12ms of every frame, while the card sat two thirds idle. The area is made full size once now and refills about seven times a frame, in 0.02ms. The same 16,000-frame battle, fast-forwarded, finishes in 226 seconds where it took between 263 and 325, and the seconds that fell under 50 frames a second went from 125 or more to 4.- 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.@@ -2427,4 +2429,5 @@ The whole HUD is on the hardware. Four colours carry it, and they mean the same## Not there yet- Internet play. LAN works: two separate PCs have played each other on one network. Matches over the internet wait on Reforged's own lobby server, which is still on paper.- A frame through Direct3D 11 still costs a little more than it does through the old renderer: 7.6ms against 6.3ms in a screen full of inferno cannon fire. `-d3d9` on the command line puts the old renderer back on its own.+- Smoke past the particle limit is drawn by the graphics card without the sun's shadow: it does not receive one and casts none into the smoke map. Its see-through puffs are not sorted against each other, and a saved game forgets them. Very large puffs, 200,000 of them in a test, are limited by how many pixels the card fills: about 68 frames a second there, the worst at 26.6 milliseconds.- You need to own the game; no game data ships here.diff --git a/GeneralsMD/Code/BuildFingerprint.manifest b/GeneralsMD/Code/BuildFingerprint.manifestindex 8c6d806b9..669b2b76f 100644--- a/GeneralsMD/Code/BuildFingerprint.manifest+++ b/GeneralsMD/Code/BuildFingerprint.manifest@@ -335,6 +335,9 @@ Data/Scenarios/overlordlong.txtData/Scenarios/overlordrush.txtData/Scenarios/parade.txtData/Scenarios/particles100k.txt+Data/Scenarios/particles1m.txt+Data/Scenarios/particles1m_mixed.txt+Data/Scenarios/particles1m_smoke.txtData/Scenarios/rankaura.txtData/Scenarios/rankauramaresal.txtData/Scenarios/rankauranight.txt@@ -694,6 +697,7 @@ GameEngine/Include/GameClient/Module/SwayClientUpdate.hGameEngine/Include/GameClient/Mouse.hGameEngine/Include/GameClient/ObserverCamera.hGameEngine/Include/GameClient/ParabolicEase.h+GameEngine/Include/GameClient/ParticleClosedForm.hGameEngine/Include/GameClient/ParticleSys.hGameEngine/Include/GameClient/PlaceEventTranslator.hGameEngine/Include/GameClient/PlayerColorScheme.h@@ -1718,6 +1722,7 @@ GameEngineDevice/Include/W3DDevice/Common/W3DRadar.hGameEngineDevice/Include/W3DDevice/Common/W3DThingFactory.hGameEngineDevice/Include/W3DDevice/GameClient/BaseHeightMap.hGameEngineDevice/Include/W3DDevice/GameClient/FlatHeightMap.h+GameEngineDevice/Include/W3DDevice/GameClient/GpuParticles.hGameEngineDevice/Include/W3DDevice/GameClient/HeightMap.hGameEngineDevice/Include/W3DDevice/GameClient/Module/W3DDebrisDraw.hGameEngineDevice/Include/W3DDevice/GameClient/Module/W3DDefaultDraw.h@@ -1866,6 +1871,7 @@ GameEngineDevice/Source/W3DDevice/Common/Thing/W3DModuleFactory.cppGameEngineDevice/Source/W3DDevice/Common/Thing/W3DThingFactory.cppGameEngineDevice/Source/W3DDevice/Common/W3DConvert.cppGameEngineDevice/Source/W3DDevice/GameClient/BaseHeightMap.cpp+GameEngineDevice/Source/W3DDevice/GameClient/DX11GpuParticles.cppGameEngineDevice/Source/W3DDevice/GameClient/DX11HazardCloud.cppGameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DDebrisDraw.cppGameEngineDevice/Source/W3DDevice/GameClient/Drawable/Draw/W3DDefaultDraw.cpp@@ -1904,6 +1910,7 @@ GameEngineDevice/Source/W3DDevice/GameClient/GUI/Gadget/W3DVerticalSlider.cppGameEngineDevice/Source/W3DDevice/GameClient/GUI/W3DGameFont.cppGameEngineDevice/Source/W3DDevice/GameClient/GUI/W3DGameWindow.cppGameEngineDevice/Source/W3DDevice/GameClient/GUI/W3DGameWindowManager.cpp+GameEngineDevice/Source/W3DDevice/GameClient/GpuParticlesUnsupported.cppGameEngineDevice/Source/W3DDevice/GameClient/HazardCloud.cppGameEngineDevice/Source/W3DDevice/GameClient/HazardCloudCore.cppGameEngineDevice/Source/W3DDevice/GameClient/HazardCloudFlow.cppdiff --git a/GeneralsMD/Code/CMakeLists.txt b/GeneralsMD/Code/CMakeLists.txtindex 42666a4ec..f75fbb0c7 100644--- a/GeneralsMD/Code/CMakeLists.txt+++ b/GeneralsMD/Code/CMakeLists.txt@@ -1518,6 +1518,8 @@ if(ZH_PLATFORM_POSIX)# POSIX factory below; the no-backend factory is compiled only without it, and# the Direct3D 11 backend only on Windows.list(FILTER W3DDEVICE_SOURCES EXCLUDE REGEX "/(HazardCloudUnsupported|DX11HazardCloud)\\.cpp$")+ # The GPU particles have only a Direct3D 11 backend; GpuParticlesUnsupported answers for SDL3.+ list(FILTER W3DDEVICE_SOURCES EXCLUDE REGEX "/DX11GpuParticles\\.cpp$")# ---- the movies (V1): Windows' Bink player and its Bink API on FFmpeg, the same two files -------------# FFmpeg is built from the tarball Tools/vendor.sh keeps, into the build tree, with the Bink demuxer@@ -1693,6 +1695,8 @@ list(FILTER GAMEENGINEDEVICE_SOURCES EXCLUDE REGEX "/Source/SdlDevice/")# The hazard clouds' backend here is Direct3D 11's (DX11HazardCloud.cpp); the no-backend entry points# are for the tests that link no device.list(FILTER GAMEENGINEDEVICE_SOURCES EXCLUDE REGEX "/HazardCloudUnsupported\\.cpp$")+# The same for the GPU particles (DX11GpuParticles.cpp here, GpuParticlesUnsupported.cpp elsewhere).+list(FILTER GAMEENGINEDEVICE_SOURCES EXCLUDE REGEX "/GpuParticlesUnsupported\\.cpp$")# Sound and video are the game's own. Miles and Bink were binary-only, and the DLLs the retail# game ships are 32-bit, so there is nothing for a 64-bit exe to bind to: what it links instead is# those two APIs written over XAudio2 and FFmpeg. FFmpeg decodes binkvideo and binkaudio natively,diff --git a/GeneralsMD/Code/Data/Scenarios/particles1m.txt b/GeneralsMD/Code/Data/Scenarios/particles1m.txtnew file mode 100644index 000000000..ba484a8f1--- /dev/null+++ b/GeneralsMD/Code/Data/Scenarios/particles1m.txt@@ -0,0 +1,29 @@+# A million small additive particles on one screen, the load the GPU particle path is measured on.+#+# 3350 copies of the shipped Snow system in a 58 by 58 block. Snow is a billboard ADDITIVE system+# with no wind, no attached system and no flipbook, so it is GPU eligible. Each copy emits 2 to 4+# flakes every second retail frame and a flake lives 300 retail frames (10 s); measured, a copy+# settles at about 315 rather than the 450 that suggests, so the block holds about 1,055,000.+# Snow emits above the ground only, so a slope under a copy loses a few. The flakes fade in from+# black over the first 4 s and the additive invisibility test does not retire them early. Gravity+# pulls them under the emitter after about 4 s, so half of each flake's life is behind the terrain+# (with ParticleBounce on, the GPU rests them on it instead): vertex and sort cost, little fill.+# particles1m_smoke is the fill-bound half.+#+# The count climbs for 600 logic frames after the spawn and holds from about frame 660.+#+# generals.exe -win -xres 1280 -yres 720 -quickstart -noshellmap -multiInstance -noFPSLimit+# -msaa 0 -noDynamicLOD -map "Maps\Alpine Assault\Alpine Assault.map" -autoskirmish 2+# -takeover -seed 1 -maxframes 2400 -gpuparticles+# -scenario particles1m -camera 760 850 -logPrefix p1m_+#+# With -gpuparticles the CPU keeps its usual cap and every eligible spawn past it goes to the GPU+# ring, so the CPU draws the first few thousand and the GPU the rest. The CPU baseline drops+# -gpuparticles and adds -particlecap 1100000 to hold the same count. Grep the log for HEADLESS+# FRAMETIME, PARTICLECOST and GPUPARTICLES. -noDynamicLOD keeps the LOD manager from dropping+# WEAPON_EXPLOSION priority particles as the frame rate falls, which would make the two runs draw+# different scenes.+#+# <frame> particles <slot> <particle system> <count> <x> <y> [spacing]++30 particles 0 Snow 3350 760 850 15diff --git a/GeneralsMD/Code/Data/Scenarios/particles1m_mixed.txt b/GeneralsMD/Code/Data/Scenarios/particles1m_mixed.txtnew file mode 100644index 000000000..bb91c27d8--- /dev/null+++ b/GeneralsMD/Code/Data/Scenarios/particles1m_mixed.txt@@ -0,0 +1,22 @@+# particles1m with smoke in it, the mix a match draws: a million additive flakes on the GPU and+# smoke on both paths.+#+# The 3350 Snow copies of particles1m, and 100 copies of BurningBridgeBeam (particles1m_smoke's+# puffs) in a 10 by 10 block, 60 apart, over the middle of the snow. At the CPU cap a freed CPU+# slot goes to whichever system spawns next, so a few hundred puffs stay on the CPU and the rest+# go to the GPU ring. Those CPU puffs are what the smoke's fire light is gathered for: every Snow+# copy is an additive system, so each one's GPU samples are aged in closed form once a particle+# update to light them. particles1m alone draws no CPU smoke and skips that gather.+#+# generals.exe -win -xres 1280 -yres 720 -quickstart -noshellmap -multiInstance -noFPSLimit+# -msaa 0 -noDynamicLOD -map "Maps\Alpine Assault\Alpine Assault.map" -autoskirmish 2+# -takeover -seed 1 -maxframes 2400 -gpuparticles+# -scenario particles1m_mixed -camera 760 850 -logPrefix p1mx_+#+# Grep the log for HEADLESS FRAMETIME, PARTICLECOST and GPUPARTICLES; the live count holds at+# about 1,012,000 from frame 700.+#+# <frame> particles <slot> <particle system> <count> <x> <y> [spacing]++30 particles 0 Snow 3350 760 850 15+30 particles 0 BurningBridgeBeam 100 760 850 60diff --git a/GeneralsMD/Code/Data/Scenarios/particles1m_smoke.txt b/GeneralsMD/Code/Data/Scenarios/particles1m_smoke.txtnew file mode 100644index 000000000..c5fb550e8--- /dev/null+++ b/GeneralsMD/Code/Data/Scenarios/particles1m_smoke.txt@@ -0,0 +1,25 @@+# Big alpha smoke puffs filling the screen, the fill-bound load for the GPU particle path.+#+# 1000 copies of BurningBridgeBeam in a 32 by 32 block, 25 apart. It is a billboard ALPHA system+# with no wind, no ground collision and no attached system, so it is GPU eligible, and its puffs+# start 4 to 7 units across and grow to about 38 over a 100 retail frame (3.3 s) life, rising 10+# units. Two a retail frame make about 200 live a copy and 200,000 in the block. The columns are+# wider than the spacing, so the block is one overlapping sheet of smoke at 0.1 to 0.2 alpha.+# A million puffs this size is far past any card's fill rate, so the count is lower than the+# additive scene's on purpose; change the 1000 to move it.+#+# The copies start 3 to 60 retail frames apart (InitialDelay) and the count holds from about+# frame 400. 200 is under the CPU renderer's 512 a system.+#+# generals.exe -win -xres 1280 -yres 720 -quickstart -noshellmap -multiInstance -noFPSLimit+# -msaa 0 -noDynamicLOD -map "Maps\Alpine Assault\Alpine Assault.map" -autoskirmish 2+# -takeover -seed 1 -maxframes 2400 -gpuparticles+# -scenario particles1m_smoke -camera 760 850 -logPrefix p1ms_+#+# With -gpuparticles the CPU keeps its usual cap and every eligible puff past it goes to the GPU+# ring. The CPU baseline drops -gpuparticles and adds -particlecap 1100000 to hold the same count.+# Grep the log for HEADLESS FRAMETIME, PARTICLECOST, the DX11 GPU line and GPUPARTICLES.+#+# <frame> particles <slot> <particle system> <count> <x> <y> [spacing]++30 particles 0 BurningBridgeBeam 1000 760 850 25diff --git a/GeneralsMD/Code/GameEngine/Include/Common/GameLOD.h b/GeneralsMD/Code/GameEngine/Include/Common/GameLOD.hindex 068eb9498..b3884a84c 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/GameLOD.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/GameLOD.h@@ -105,6 +105,7 @@ struct StaticGameLODInfoInt m_sampleCount3D; ///<How many 3-D (World) samples should we allow simultaneously (Note: Hardware may support less than the desired number)Int m_streamCount; ///<How many streaming audio things should we allow simultaneously (Note: Hardware may support less than the desired number)Int m_maxParticleCount; ///<maximum number of particles that can exist+ Int m_gpuParticleCapacity; ///<Direct3D 11 particle ring slots for what goes past m_maxParticleCount, 0 for noneBool m_useShadowVolumes; ///<use volumetric shadows if available.Bool m_useShadowDecals; ///<use 2D Decal shadows.Bool m_useCloudMap; ///<use cloud shadows scrolling over terrain.diff --git a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.hindex 7595258d3..003fecaae 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h@@ -252,6 +252,8 @@ public:Bool isDynamicLODEnabled() const { return m_enableDynamicLOD && !m_noDynamicLODOverride; }/// The particle ceiling in force: -particlecap's, or the options slider's MaxParticleCount.Int getEffectiveParticleCap() const { return (m_particleCapOverride > 0) ? m_particleCapOverride : m_maxParticleCount; }+ /// The Direct3D 11 particle ring in force: -gpuparticles' (0 included, which is off), or the detail preset's.+ Int getEffectiveGpuParticleCapacity() const { return (m_gpuParticleCapacityOverride >= 0) ? m_gpuParticleCapacityOverride : m_gpuParticleCapacity; }static void parseGameDataDefinition( INI* ini );static void parseVeterancyDefinition( INI* ini ); ///< the Veterancy block, m_veterancy*@@ -339,6 +341,9 @@ public:Bool m_particleGroundBounce; // "-particlebounce": terrain collision on for every particle systemReal m_smokeThickness; // "-smoke": how much longer and thicker every smoke system runs, 0 for shipped behaviourInt m_particleCapOverride; // "-particlecap": stand in for the options slider's MaxParticleCount, 0 to use it+ Int m_gpuParticleCapacity; // spawn-record slots in the Direct3D 11 particle ring, the detail preset's GpuParticleCapacity; 0 keeps every particle on the CPU+ Int m_gpuParticleCapacityOverride; // "-gpuparticles": stand in for the preset's ring for one run, -1 to use it+ Bool m_gpuParticleCheck; // "-gpuparticlecheck": run the CPU path beside the GPU one and log the closed form's largest errorInt m_textureReductionFactor; //how much to cut texture resolution: 2 is half, 3 is quarter, etc.Bool m_enableBehindBuildingMarkers;Real m_waterPositionX;diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleClosedForm.h b/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleClosedForm.hnew file mode 100644index 000000000..8ba7ca274--- /dev/null+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleClosedForm.h@@ -0,0 +1,477 @@+/*+** Command & Conquer Generals Zero Hour(tm)+** Copyright 2025 Electronic Arts Inc.+**+** This program is free software: you can redistribute it and/or modify+** it under the terms of the GNU General Public License as published by+** the Free Software Foundation, either version 3 of the License, or+** (at your option) any later version.+**+** This program is distributed in the hope that it will be useful,+** but WITHOUT ANY WARRANTY; without even the implied warranty of+** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+** GNU General Public License for more details.+**+** You should have received a copy of the GNU General Public License+** along with this program. If not, see <http://www.gnu.org/licenses/>.+*/++// ParticleClosedForm.h ///////////////////////////////////////////////////////////////////////////+// A particle's state after k updates without running the k updates, and the two records the GPU+// particle path keeps: one per particle, written once at birth, and one per system.+///////////////////////////////////////////////////////////////////////////////////////////////////++#pragma once++#ifndef _PARTICLE_CLOSED_FORM_H_+#define _PARTICLE_CLOSED_FORM_H_++#include <math.h>+#include <stddef.h>+#include <string.h>+#include "Common/GameCommon.h"+#include "GameClient/ParticleSys.h"++/**+ * Particle::update's fade window (ParticleSys.cpp, PARTICLE_FADE_*): the last quarter of the+ * lifetime, at most eight retail frames, at least one. Own names, so ParticleSys.cpp can include+ * this header next to its own copies.+ */+enum+{+ PARTICLE_CLOSED_FORM_FADE_MAX_FRAMES = 8 * LOGICFRAMES_PER_RETAIL_FRAME,+ PARTICLE_CLOSED_FORM_FADE_LIFETIME_DIVISOR = 4+};++/// a damping below this is taken as this, because HLSL's pow(0, 0) is NaN where C's is 1+static const Real PARTICLE_CLOSED_FORM_MIN_DAMPING = 1.0e-6f;++/**+ * One particle as the GPU sees it, written at birth and never again. Floats and uints only, every+ * float3 followed by a scalar, so an HLSL StructuredBuffer of the same field order mirrors it.+ *+ * m_systemSlotSeed: the system entry's slot in the low 16 bits, a per-particle seed in the high 16.+ * m_alphaKeys: the eight alpha key values as bytes over 0..255, key i in byte (i & 3) of word i >> 2.+ * The key frames are the system's and live in its entry; only the values are drawn per particle.+ */+struct ParticleGpuSpawn+{+ Real m_pos[ 3 ];+ UnsignedInt m_birthFrame; ///< client frame of the update that made it, k = now - birth + 1+ Real m_vel[ 3 ];+ Real m_lifetime; ///< whole frames, 0 = never ages+ Real m_size;+ Real m_sizeRate;+ Real m_sizeRateDamping;+ Real m_velDamping;+ Real m_angleZ;+ Real m_angularRateZ;+ Real m_angularDamping;+ Real m_colorScale;+ UnsignedInt m_systemSlotSeed;+ UnsignedInt m_alphaKeys[ 2 ];+ UnsignedInt m_pad;+};++static_assert( sizeof( ParticleGpuSpawn ) == 80, "ParticleGpuSpawn is mirrored by an HLSL struct" );+static_assert( offsetof( ParticleGpuSpawn, m_birthFrame ) == 12, "ParticleGpuSpawn layout" );+static_assert( offsetof( ParticleGpuSpawn, m_vel ) == 16, "ParticleGpuSpawn layout" );+static_assert( offsetof( ParticleGpuSpawn, m_lifetime ) == 28, "ParticleGpuSpawn layout" );+static_assert( offsetof( ParticleGpuSpawn, m_size ) == 32, "ParticleGpuSpawn layout" );+static_assert( offsetof( ParticleGpuSpawn, m_velDamping ) == 44, "ParticleGpuSpawn layout" );+static_assert( offsetof( ParticleGpuSpawn, m_angleZ ) == 48, "ParticleGpuSpawn layout" );+static_assert( offsetof( ParticleGpuSpawn, m_colorScale ) == 60, "ParticleGpuSpawn layout" );+static_assert( offsetof( ParticleGpuSpawn, m_systemSlotSeed ) == 64, "ParticleGpuSpawn layout" );+static_assert( offsetof( ParticleGpuSpawn, m_alphaKeys ) == 68, "ParticleGpuSpawn layout" );+static_assert( offsetof( ParticleGpuSpawn, m_pad ) == 76, "ParticleGpuSpawn layout" );++/**+ * Segment i runs from alpha key i to key i + 1. m_time is the rate's divisor exactly as+ * computeAlphaRate takes it, the unsigned frame difference as a float, so a key earlier than the+ * one before it gives a near-zero rate rather than a negative one. m_end is the update count at+ * which key i + 1 is snapped to.+ */+struct ParticleGpuAlphaSegment+{+ Real m_time;+ UnsignedInt m_end;+};++/// segment i runs from colour key i to key i + 1, its rate taken on every update up to m_end+struct ParticleGpuColorSegment+{+ Real m_rate[ 3 ];+ UnsignedInt m_end;+};++/**+ * One particle system as the GPU sees it. Rebuilt when the system's keys change. The texture+ * slice and the flags belong to the renderer; particleGpuSystemEntryBuild leaves them zero.+ * m_shaderType holds ParticleSystemInfo::ParticleShaderType (ADDITIVE 1, ALPHA 2, ALPHA_TEST 3,+ * MULTIPLY 4).+ */+struct ParticleGpuSystemEntry+{+ Real m_drift[ 3 ];+ Real m_gravity;+ Real m_color[ 3 ]; ///< colour key 0+ UnsignedInt m_textureSlice;+ UnsignedInt m_shaderType;+ UnsignedInt m_flags;+ UnsignedInt m_alphaSegmentCount; ///< 0..7+ UnsignedInt m_colorSegmentCount; ///< 0..7+ ParticleGpuAlphaSegment m_alphaSegment[ MAX_KEYFRAMES ];+ ParticleGpuColorSegment m_colorSegment[ MAX_KEYFRAMES ];+};++static_assert( sizeof( ParticleGpuAlphaSegment ) == 8, "ParticleGpuAlphaSegment is mirrored by an HLSL struct" );+static_assert( sizeof( ParticleGpuColorSegment ) == 16, "ParticleGpuColorSegment is mirrored by an HLSL struct" );+static_assert( sizeof( ParticleGpuSystemEntry ) == 240, "ParticleGpuSystemEntry is mirrored by an HLSL struct" );+static_assert( offsetof( ParticleGpuSystemEntry, m_gravity ) == 12, "ParticleGpuSystemEntry layout" );+static_assert( offsetof( ParticleGpuSystemEntry, m_color ) == 16, "ParticleGpuSystemEntry layout" );+static_assert( offsetof( ParticleGpuSystemEntry, m_textureSlice ) == 28, "ParticleGpuSystemEntry layout" );+static_assert( offsetof( ParticleGpuSystemEntry, m_shaderType ) == 32, "ParticleGpuSystemEntry layout" );+static_assert( offsetof( ParticleGpuSystemEntry, m_colorSegmentCount ) == 44, "ParticleGpuSystemEntry layout" );+static_assert( offsetof( ParticleGpuSystemEntry, m_alphaSegment ) == 48, "ParticleGpuSystemEntry layout" );+static_assert( offsetof( ParticleGpuSystemEntry, m_colorSegment ) == 112, "ParticleGpuSystemEntry layout" );++/// What Particle::update would leave in a particle after k updates.+struct ParticleClosedFormState+{+ Coord3D m_pos;+ Coord3D m_vel;+ Real m_size;+ Real m_angleZ;+ Real m_alpha;+ RGBColor m_color;+ Bool m_dead; ///< update would have returned false by update k, of age or of invisibility+};++// ------------------------------------------------------------------------------------------------+/// Particle::update's clamp, which leaves a NaN alone just as its two comparisons do+// ------------------------------------------------------------------------------------------------+inline Real particleClosedFormClamp01( Real value )+{+ if (value < 0.0f)+ return 0.0f;+ if (value > 1.0f)+ return 1.0f;+ return value;+}++// ------------------------------------------------------------------------------------------------+inline Real particleGpuSpawnAlphaKey( const ParticleGpuSpawn &spawn, UnsignedInt key )+{+ return (Real)( ( spawn.m_alphaKeys[ key >> 2 ] >> ( ( key & 3 ) * 8 ) ) & 0xFF ) / 255.0f;+}++// ------------------------------------------------------------------------------------------------+/** The birth record of a particle made from info. An alpha key outside 0..1 is clamped into a+ * byte, which only moves the rate toward it; the value itself is clamped on every update anyway. */+// ------------------------------------------------------------------------------------------------+inline void particleGpuSpawnPack( const ParticleInfo &info, UnsignedInt birthFrame, UnsignedInt systemSlot,+ UnsignedInt seed, ParticleGpuSpawn *spawn )+{+ spawn->m_pos[ 0 ] = info.m_pos.x;+ spawn->m_pos[ 1 ] = info.m_pos.y;+ spawn->m_pos[ 2 ] = info.m_pos.z;+ spawn->m_birthFrame = birthFrame;+ spawn->m_vel[ 0 ] = info.m_vel.x;+ spawn->m_vel[ 1 ] = info.m_vel.y;+ spawn->m_vel[ 2 ] = info.m_vel.z;+ spawn->m_lifetime = (Real)info.m_lifetime;+ spawn->m_size = info.m_size;+ spawn->m_sizeRate = info.m_sizeRate;+ spawn->m_sizeRateDamping = info.m_sizeRateDamping;+ spawn->m_velDamping = info.m_velDamping;+ spawn->m_angleZ = info.m_angleZ;+ spawn->m_angularRateZ = info.m_angularRateZ;+ spawn->m_angularDamping = info.m_angularDamping;+ spawn->m_colorScale = info.m_colorScale;+ spawn->m_systemSlotSeed = ( systemSlot & 0xFFFF ) | ( ( seed & 0xFFFF ) << 16 );+ spawn->m_alphaKeys[ 0 ] = 0;+ spawn->m_alphaKeys[ 1 ] = 0;+ for( UnsignedInt i = 0; i < MAX_KEYFRAMES; ++i )+ {+ const UnsignedInt byte = (UnsignedInt)( particleClosedFormClamp01( info.m_alphaKey[ i ].value ) * 255.0f + 0.5f );+ spawn->m_alphaKeys[ i >> 2 ] |= byte << ( ( i & 3 ) * 8 );+ }+ spawn->m_pad = 0;+}++// ------------------------------------------------------------------------------------------------+/** The update on which each key after key 0 takes over. Particle::update moves to key j on the+ * first update k after the last switch with k - 1 >= frame j, at most one key an update, and stops+ * at the first key whose frame is zero. Keys out of order therefore last one update each.+ * Returns the number of segments. */+// ------------------------------------------------------------------------------------------------+inline UnsignedInt particleClosedFormSwitchUpdates( const UnsignedInt frame[ MAX_KEYFRAMES ], UnsignedInt end[ MAX_KEYFRAMES ] )+{+ UnsignedInt count = 0;+ UnsignedInt last = 0;+ for( UnsignedInt key = 1; key < MAX_KEYFRAMES && frame[ key ] != 0; ++key )+ {+ last = ( frame[ key ] + 1 > last + 1 ) ? frame[ key ] + 1 : last + 1;+ end[ count++ ] = last;+ }+ return count;+}++// ------------------------------------------------------------------------------------------------+/** The system's half of every particle it makes: drift, gravity, colour key 0 and the alpha and+ * colour segment tables, with the rates divided exactly as computeAlphaRate and computeColorRate+ * divide them. Past the eighth key the real code reads one key beyond the array for one update;+ * here that rate is zero. */+// ------------------------------------------------------------------------------------------------+inline void particleGpuSystemEntryBuild( const ParticleSystemInfo &system, ParticleGpuSystemEntry *entry )+{+ memset( entry, 0, sizeof( *entry ) );++ entry->m_drift[ 0 ] = system.m_driftVelocity.x;+ entry->m_drift[ 1 ] = system.m_driftVelocity.y;+ entry->m_drift[ 2 ] = system.m_driftVelocity.z;+ entry->m_gravity = system.m_gravity;+ entry->m_color[ 0 ] = system.m_colorKey[ 0 ].color.red;+ entry->m_color[ 1 ] = system.m_colorKey[ 0 ].color.green;+ entry->m_color[ 2 ] = system.m_colorKey[ 0 ].color.blue;+ entry->m_shaderType = (UnsignedInt)system.m_shaderType;++ UnsignedInt frame[ MAX_KEYFRAMES ];+ UnsignedInt end[ MAX_KEYFRAMES ];++ for( UnsignedInt i = 0; i < MAX_KEYFRAMES; ++i )+ frame[ i ] = system.m_alphaKey[ i ].frame;+ entry->m_alphaSegmentCount = particleClosedFormSwitchUpdates( frame, end );+ for( UnsignedInt i = 0; i < entry->m_alphaSegmentCount; ++i )+ {+ const UnsignedInt time = frame[ i + 1 ] - frame[ i ];+ entry->m_alphaSegment[ i ].m_time = (Real)time;+ entry->m_alphaSegment[ i ].m_end = end[ i ];+ }++ for( UnsignedInt i = 0; i < MAX_KEYFRAMES; ++i )+ frame[ i ] = system.m_colorKey[ i ].frame;+ entry->m_colorSegmentCount = particleClosedFormSwitchUpdates( frame, end );+ for( UnsignedInt i = 0; i < entry->m_colorSegmentCount; ++i )+ {+ const UnsignedInt time = frame[ i + 1 ] - frame[ i ];+ const RGBColor &from = system.m_colorKey[ i ].color;+ const RGBColor &to = system.m_colorKey[ i + 1 ].color;+ entry->m_colorSegment[ i ].m_rate[ 0 ] = ( to.red - from.red ) / time;+ entry->m_colorSegment[ i ].m_rate[ 1 ] = ( to.green - from.green ) / time;+ entry->m_colorSegment[ i ].m_rate[ 2 ] = ( to.blue - from.blue ) / time;+ entry->m_colorSegment[ i ].m_end = end[ i ];+ }+}++// ------------------------------------------------------------------------------------------------+/** For a damping d and a real k >= 1: power = d^k, sum = d^0 + ... + d^(k-1), and nested = the sum+ * of sum(i) over i = 1..k. A rate damped by d moves its value by rate * sum in k updates.+ *+ * The quotients (1 - d^k) / (1 - d) cancel to noise as d approaches 1, so while (1 - d) k < 0.1+ * the binomial series takes over: sum = C(k,1) - e C(k,2) + e^2 C(k,3) - e^3 C(k,4) with e = 1 - d,+ * nested the same over C(k+1, j+2). It is exact for d = 1 and for k <= 4, and the first term+ * dropped is under 1e-6 of the value. */+// ------------------------------------------------------------------------------------------------+inline void particleClosedFormSums( Real damping, Real k, Real *power, Real *sum, Real *nested )+{+ const Real d = ( damping < PARTICLE_CLOSED_FORM_MIN_DAMPING ) ? PARTICLE_CLOSED_FORM_MIN_DAMPING : damping;+ const Real e = 1.0f - d;+ *power = powf( d, k );++ if (fabsf( e ) * k < 0.1f)+ {+ *sum = k * ( 1.0f - e * ( k - 1.0f ) / 2.0f * ( 1.0f - e * ( k - 2.0f ) / 3.0f * ( 1.0f - e * ( k - 3.0f ) / 4.0f ) ) );+ *nested = k * ( k + 1.0f ) / 2.0f+ * ( 1.0f - e * ( k - 1.0f ) / 3.0f * ( 1.0f - e * ( k - 2.0f ) / 4.0f * ( 1.0f - e * ( k - 3.0f ) / 5.0f ) ) );+ return;+ }++ *sum = ( 1.0f - *power ) / e;+ *nested = ( k - d * *sum ) / e;+}++// ------------------------------------------------------------------------------------------------+/** Alpha after update k. Within a segment the rate is constant and the value is clamped every+ * update, so n updates in is clamp(start + n rate) exactly; a segment starts at its key's value,+ * snapped on the update that reaches it. Past the last key alpha stays where the last snap put it.+ * ADDITIVE never touches alpha. */+// ------------------------------------------------------------------------------------------------+inline Real particleClosedFormAlpha( const ParticleGpuSpawn &spawn, const ParticleGpuSystemEntry &entry, Real k )+{+ if (entry.m_shaderType == (UnsignedInt)ParticleSystemInfo::ADDITIVE)+ return particleGpuSpawnAlphaKey( spawn, 0 );++ UnsignedInt start = 0;+ UnsignedInt key = 0;+ for( ; key < entry.m_alphaSegmentCount; ++key )+ {+ const ParticleGpuAlphaSegment &segment = entry.m_alphaSegment[ key ];+ if (k < (Real)segment.m_end)+ {+ const Real from = particleGpuSpawnAlphaKey( spawn, key );+ const Real rate = ( particleGpuSpawnAlphaKey( spawn, key + 1 ) - from ) / segment.m_time;+ return particleClosedFormClamp01( from + ( k - (Real)start ) * rate );+ }+ start = segment.m_end;+ }+ return particleClosedFormClamp01( particleGpuSpawnAlphaKey( spawn, key ) );+}++// ------------------------------------------------------------------------------------------------+/** Colour after update k, before the fade. Every update adds the segment's rate and the+ * particle's colorScale and clamps; the rate is taken on the update that switches too, so each+ * segment overshoots its key by one rate. Past the last key only colorScale moves it. */+// ------------------------------------------------------------------------------------------------+inline void particleClosedFormColor( const ParticleGpuSpawn &spawn, const ParticleGpuSystemEntry &entry, Real k, Real color[ 3 ] )+{+ const Real scale = spawn.m_colorScale;+ color[ 0 ] = entry.m_color[ 0 ];+ color[ 1 ] = entry.m_color[ 1 ];+ color[ 2 ] = entry.m_color[ 2 ];++ Real done = 0.0f;+ for( UnsignedInt i = 0; i < entry.m_colorSegmentCount && done < k; ++i )+ {+ const ParticleGpuColorSegment &segment = entry.m_colorSegment[ i ];+ const Real end = ( k < (Real)segment.m_end ) ? k : (Real)segment.m_end;+ const Real updates = end - done;+ for( Int c = 0; c < 3; ++c )+ color[ c ] = particleClosedFormClamp01( color[ c ] + updates * ( segment.m_rate[ c ] + scale ) );+ done = end;+ }++ if (done < k)+ {+ for( Int c = 0; c < 3; ++c )+ color[ c ] = particleClosedFormClamp01( color[ c ] + ( k - done ) * scale );+ }+}++// ------------------------------------------------------------------------------------------------+/** The fade over the last frames of a life, capping alpha (ALPHA, ALPHA_TEST) or the brightest+ * channel (ADDITIVE) at an envelope falling to zero. Particle::update writes the cap into the+ * particle and keeps integrating from there, so this is exact only until the cap first bites; the+ * difference lives inside the window. */+// ------------------------------------------------------------------------------------------------+inline void particleClosedFormFade( const ParticleGpuSpawn &spawn, const ParticleGpuSystemEntry &entry, Real k,+ Real *alpha, Real color[ 3 ] )+{+ const UnsignedInt lifetime = (UnsignedInt)spawn.m_lifetime;+ if (lifetime == 0)+ return;++ UnsignedInt fadeFrames = lifetime / PARTICLE_CLOSED_FORM_FADE_LIFETIME_DIVISOR;+ if (fadeFrames > PARTICLE_CLOSED_FORM_FADE_MAX_FRAMES)+ fadeFrames = PARTICLE_CLOSED_FORM_FADE_MAX_FRAMES;+ else if (fadeFrames == 0)+ fadeFrames = 1;++ const Real left = spawn.m_lifetime - k;+ if (left > (Real)fadeFrames)+ return;++ const Real envelope = ( left - 1.0f ) / (Real)fadeFrames;+ switch (entry.m_shaderType)+ {+ case ParticleSystemInfo::ALPHA:+ case ParticleSystemInfo::ALPHA_TEST:+ if (*alpha > envelope)+ *alpha = envelope;+ break;++ case ParticleSystemInfo::ADDITIVE:+ {+ Real brightest = color[ 0 ];+ if (color[ 1 ] > brightest)+ brightest = color[ 1 ];+ if (color[ 2 ] > brightest)+ brightest = color[ 2 ];+ if (brightest > envelope)+ {+ const Real scale = envelope / brightest;+ color[ 0 ] *= scale;+ color[ 1 ] *= scale;+ color[ 2 ] *= scale;+ }+ break;+ }+ }+}++// ------------------------------------------------------------------------------------------------+/** A particle of a system without wind, ground collision or upTowardsEmitter, k updates after+ * birth (k >= 1, fractional for a frame drawn between two updates). MULTIPLY is not modelled:+ * no fade and never invisible.+ *+ * With v_k = d (v_{k-1} + g) and p_k = p_{k-1} + v_k + drift: v_k = d^k v0 + g d sum(k) and+ * p_k = p0 + k drift + v0 d sum(k) + g d nested(k). Angle and size are a0 + r0 sum(k) in their+ * own dampings. */+// ------------------------------------------------------------------------------------------------+inline void particleClosedFormEvaluate( const ParticleGpuSpawn &spawn, const ParticleGpuSystemEntry &entry, Real k,+ ParticleClosedFormState *state )+{+ Real power, sum, nested;++ particleClosedFormSums( spawn.m_velDamping, k, &power, &sum, &nested );+ const Real d = ( spawn.m_velDamping < PARTICLE_CLOSED_FORM_MIN_DAMPING ) ? PARTICLE_CLOSED_FORM_MIN_DAMPING : spawn.m_velDamping;+ const Real velocitySum = d * sum;+ state->m_vel.x = power * spawn.m_vel[ 0 ];+ state->m_vel.y = power * spawn.m_vel[ 1 ];+ state->m_vel.z = power * spawn.m_vel[ 2 ] + entry.m_gravity * velocitySum;+ state->m_pos.x = spawn.m_pos[ 0 ] + k * entry.m_drift[ 0 ] + spawn.m_vel[ 0 ] * velocitySum;+ state->m_pos.y = spawn.m_pos[ 1 ] + k * entry.m_drift[ 1 ] + spawn.m_vel[ 1 ] * velocitySum;+ state->m_pos.z = spawn.m_pos[ 2 ] + k * entry.m_drift[ 2 ] + spawn.m_vel[ 2 ] * velocitySum+ + entry.m_gravity * d * nested;++ particleClosedFormSums( spawn.m_angularDamping, k, &power, &sum, &nested );+ state->m_angleZ = spawn.m_angleZ + spawn.m_angularRateZ * sum;++ particleClosedFormSums( spawn.m_sizeRateDamping, k, &power, &sum, &nested );+ state->m_size = spawn.m_size + spawn.m_sizeRate * sum;++ Real color[ 3 ];+ Real alpha = particleClosedFormAlpha( spawn, entry, k );+ particleClosedFormColor( spawn, entry, k, color );+ particleClosedFormFade( spawn, entry, k, &alpha, color );+ state->m_alpha = alpha;+ state->m_color.red = color[ 0 ];+ state->m_color.green = color[ 1 ];+ state->m_color.blue = color[ 2 ];++ // isInvisible: only once past the last key, and it kills, so a particle that was invisible on+ // any update since is gone. Past the last key alpha only falls; colour moves by colorScale on+ // every channel alike, so the dimmest update is the first one past the key or this one.+ Bool invisible = FALSE;+ switch (entry.m_shaderType)+ {+ case ParticleSystemInfo::ALPHA:+ {+ const UnsignedInt last = entry.m_alphaSegmentCount ? entry.m_alphaSegment[ entry.m_alphaSegmentCount - 1 ].m_end : 0;+ invisible = k >= (Real)last && alpha < 0.02f;+ break;+ }++ case ParticleSystemInfo::ADDITIVE:+ {+ const UnsignedInt last = entry.m_colorSegmentCount ? entry.m_colorSegment[ entry.m_colorSegmentCount - 1 ].m_end : 0;+ if (k < (Real)last)+ break;+ invisible = ( color[ 0 ] + color[ 1 ] + color[ 2 ] ) <= 0.06f;+ const Real first = last ? (Real)last : 1.0f;+ if (!invisible && first < k)+ {+ Real firstAlpha = alpha;+ Real firstColor[ 3 ];+ particleClosedFormColor( spawn, entry, first, firstColor );+ particleClosedFormFade( spawn, entry, first, &firstAlpha, firstColor );+ invisible = ( firstColor[ 0 ] + firstColor[ 1 ] + firstColor[ 2 ] ) <= 0.06f;+ }+ break;+ }+ }++ state->m_dead = invisible || ( spawn.m_lifetime != 0.0f && k >= spawn.m_lifetime );+}++#endif // _PARTICLE_CLOSED_FORM_H_diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleSys.h b/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleSys.hindex 50ec11cd1..dd00b15ad 100644--- a/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleSys.h+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleSys.h@@ -642,6 +642,11 @@ public:UnsignedInt getFlipbookGridLog2( void ) const { return m_flipbookGridLog2; }Real getFlipbookRate( void ) const { return m_flipbookRate; }++ /// Whether the GPU path's closed form can draw this template's particles (ParticleSys.cpp says why+ /// each test is there); the manager still has to accept GPU particles at all.+ Bool isGpuEligible( void ) const;+ const AsciiString &getParticleTypeName( void ) const { return m_particleTypeName; }Bool isFlipbookRandomStart( void ) const { return m_flipbookRandomStart; }// This function was made const because of update modules' module data being all const.@@ -845,6 +850,29 @@ public:/// How much of this system the local player sees, for the stealth of what it is attached to.Real getStealthFade( void ) const;+ /** The GPU particle path (docs/plans/GPU-PARTICLES.md). An eligible system hands each spawn to+ * the manager's spawnGpuParticle, which keeps it as a spawn record the vertex shader ages in+ * closed form; no Particle is made and nothing on the CPU touches it again. The system keeps+ * the last few spawns so the client can still estimate what the cloud does (ground blob, fire+ * light) without reading the device's ring back. */+ struct GpuSpawnSample+ {+ ParticleInfo m_info; ///< the spawn exactly as spawnGpuParticle was handed it+ UnsignedInt m_birthFrame; ///< ParticleSystemManager::getParticleFrame() at the spawn+ };+ enum { GPU_SPAWN_SAMPLES = 16 };++ Bool isGpuEligible( void ) const { return m_gpuEligible; } ///< decided once, in the constructor+ UnsignedInt getGpuSpawnTotal( void ) const { return m_gpuSpawnTotal; } ///< spawns the GPU took, ever; 0 for a CPU-only system+ UnsignedInt getGpuLastDeathFrame( void ) const { return m_gpuLastDeathFrame; } ///< the update its last GPU particle to go dies in, as a CPU twin would+ UnsignedInt getGpuLifetimeLeft( void ) const; ///< frames until the last GPU particle dies, as Particle::getLifetimeLeft counts; 0 when none is alive+ UnsignedInt getGpuSampleCount( void ) const { return m_gpuSpawnTotal < (UnsignedInt)GPU_SPAWN_SAMPLES ? m_gpuSpawnTotal : (UnsignedInt)GPU_SPAWN_SAMPLES; }+ /// 0 is the newest spawn, getGpuSampleCount() - 1 the oldest kept+ const GpuSpawnSample &getGpuSample( UnsignedInt newestFirst ) const { return m_gpuSamples[ ( m_gpuSpawnTotal - 1 - newestFirst ) % GPU_SPAWN_SAMPLES ]; }+ /// The template asked for terrain collision (its INI, or -particlebounce and the ParticleBounce+ /// option forcing it): the device rests GPU particles on the terrain, without the bounce.+ Bool isGpuGroundClamped( void ) const { return m_template->m_groundCollision; }+protected:// snapshot methods@@ -869,6 +897,8 @@ protected:void makeUpdateContext( ParticleUpdateContext *context ) const;Bool finishUpdate( const ParticleShadowBlob *blob ); ///< the ground blob and the lifetime, after the particles+ void addGpuSamplesToShadowBlob( ParticleShadowBlob *blob ) const; ///< the GPU particles' share of the ground blob, from the samples+ Bool spawnOnGpu( const ParticleInfo *info ); ///< hand one spawn to the manager's GPU path; TRUE if it took itParticleShadowBlob m_pendingShadowBlob; ///< the survivors' footprint, gathered by updateParticlesMarkBool m_pendingCastsGroundShadow; ///< decided by updateEmission, where update() always decided it@@ -931,6 +961,11 @@ protected:Bool m_isShell; ///< made inside a tick and not yet built (buildClientPart)Bool m_initialDelaySet; ///< setInitialDelay was called, so the build keeps it over the template's+ Bool m_gpuEligible; ///< spawns go to the manager's GPU path; client-only, never xfered+ UnsignedInt m_gpuSpawnTotal; ///< spawns the GPU took; indexes m_gpuSamples+ UnsignedInt m_gpuLastDeathFrame; ///< the latest frame a GPU spawn of this system dies in+ std::vector<GpuSpawnSample> m_gpuSamples; ///< ring of the last GPU_SPAWN_SAMPLES spawns, sized on the first+// the actual particle system data is inherited from ParticleSystemInfo@@ -1015,7 +1050,21 @@ public:virtual void doParticles(RenderInfoClass &rinfo) = 0;virtual void queueParticleRender() = 0;-++ /** The GPU particle path (docs/plans/GPU-PARTICLES.md); a device that has one overrides all three.+ * acceptsGpuParticles is asked once per system, in its constructor. spawnGpuParticle takes one+ * spawn of an eligible system whole or answers FALSE, and the system then makes a CPU Particle.+ * releaseGpuSystem is called from every eligible system's destructor; one destroyed by the+ * manager's own destructor reaches this base no-op, the device's part being gone already. */+ virtual Bool acceptsGpuParticles( void ) const { return FALSE; }+ virtual Bool spawnGpuParticle( ParticleSystem *system, const ParticleInfo *info ) { return FALSE; }+ virtual void releaseGpuSystem( ParticleSystem *system ) {}++ /// The GPU particles' clock: one tick for each update() that runs the systems, which is exactly+ /// how often a CPU Particle ages, where the logic frame runs two or three ahead in a catch-up+ /// pass. Spawn records stamp their birthFrame from it and age against it.+ static UnsignedInt getParticleFrame( void );+virtual void preloadAssets( TimeOfDay timeOfDay );// these are only for use by partcle systems to link and unlink themselves@@ -1048,6 +1097,7 @@ protected:UnsignedInt m_particleSystemCount;Int m_onScreenParticleCount; ///< number of particles displayed on screen per frameUnsignedInt m_lastLogicFrameUpdate;+ UnsignedInt m_particleFrame; ///< getParticleFrame; client-only, never xferedInt m_localPlayerIndex; ///<used to tell particle systems which particles can be skipped due to player shroud statusstd::vector<ParticleSystem *> m_independentUpdates; ///< this update's systems whose particles go to the job pool; kept so it does not reallocatestd::vector<ParticleSystem *> m_shells; ///< made inside this tick, built after it; reset() deletes any a cleared game leftdiff --git a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cppindex 65f641006..60ad48d9f 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp@@ -966,6 +966,38 @@ Int parseParticleCap(char *args[], int num)return 2;}+/* -gpuparticles [slots]: how many spawn records the Direct3D 11 particle ring holds this run, over the+ detail preset's (Ultra 1 << 20 down to Low 1 << 17). The preset is applied after the command line,+ so this is a field of its own, read through getEffectiveGpuParticleCapacity, as -particlecap is.+ Bare is Ultra's 1 << 20; 0 keeps every particle on the CPU path with its cap. The number is+ optional, so only a word that starts with a digit is taken. -d3d9, Classic and the SDL3 builds+ never draw on the GPU whatever this says. GPU-PARTICLES.md. */+Int parseGpuParticles(char *args[], int num)+{+ if (TheWritableGlobalData)+ {+ if (num > 1 && args[1] && args[1][0] >= '0' && args[1][0] <= '9')+ {+ TheWritableGlobalData->m_gpuParticleCapacityOverride = atoi(args[1]);+ return 2;+ }+ TheWritableGlobalData->m_gpuParticleCapacityOverride = 1 << 20;+ }+ return 1;+}++/* -gpuparticlecheck: every GPU-eligible particle also runs the CPU update, and the log carries the+ largest difference between the closed form and the real Particle state. For proving the shader's+ maths, not for playing: it costs both paths at once. */+Int parseGpuParticleCheck(char *args[], int num)+{+ if (TheWritableGlobalData)+ {+ TheWritableGlobalData->m_gpuParticleCheck = TRUE;+ }+ return 1;+}+/* The sun's shadow map is how this game draws shadows, and there is no switch for it. It fillsevery frame and the stencil volumes stand down behind it; a machine with no Direct3D 11 devicefills no map and keeps the volumes on its own, which is the whole of the fallback. What is@@ -2808,6 +2840,8 @@ static CommandLineParam params[] ={ "-particlebounce", parseParticleBounce },{ "-smoke", parseSmoke },{ "-particlecap", parseParticleCap },+ { "-gpuparticles", parseGpuParticles },+ { "-gpuparticlecheck", parseGpuParticleCheck },{ "-noDynamicLOD", parseNoDynamicLOD },{ "-nochroma", parseNoChroma },{ "-shadowmapreport", parseShadowMapReport },diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GameLOD.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GameLOD.cppindex 56fdc2f50..aa5598e5d 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/GameLOD.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/GameLOD.cpp@@ -65,6 +65,7 @@ static const FieldParse TheStaticGameLODFieldParseTable[] ={ "SampleCount3D", INI::parseInt, NULL, offsetof( StaticGameLODInfo, m_sampleCount3D ) },{ "StreamCount", INI::parseInt, NULL, offsetof( StaticGameLODInfo, m_streamCount ) },{ "MaxParticleCount", INI::parseInt, NULL, offsetof( StaticGameLODInfo, m_maxParticleCount ) },+ { "GpuParticleCapacity", INI::parseInt, NULL, offsetof( StaticGameLODInfo, m_gpuParticleCapacity ) },{ "UseShadowVolumes", INI::parseBool, NULL, offsetof( StaticGameLODInfo, m_useShadowVolumes ) },{ "UseShadowDecals", INI::parseBool, NULL, offsetof( StaticGameLODInfo, m_useShadowDecals ) },{ "UseCloudMap", INI::parseBool, NULL, offsetof( StaticGameLODInfo, m_useCloudMap ) },@@ -90,6 +91,11 @@ static const char *StaticGameLODNames[]="Custom"};+// The Direct3D 11 particle ring each level asks for, Low to Ultra. Ultra's is the million slots the+// ring was measured at (GPU-PARTICLES.md) and each level below halves it. The shipped GameLOD.ini+// has no GpuParticleCapacity line, so these stand unless a modder's copy names one.+static const Int TheGpuParticleCapacities[STATIC_GAME_LOD_CUSTOM] = { 1 << 17, 1 << 18, 1 << 19, 1 << 20 };+StaticGameLODInfo::StaticGameLODInfo(void){m_minFPS=0;@@ -98,6 +104,7 @@ StaticGameLODInfo::StaticGameLODInfo(void)m_sampleCount3D=24;m_streamCount=2;m_maxParticleCount=2500;+ m_gpuParticleCapacity=TheGpuParticleCapacities[STATIC_GAME_LOD_HIGH];m_useShadowVolumes=TRUE;m_useShadowDecals=TRUE;@@ -239,7 +246,10 @@ GameLODManager::GameLODManager(void)m_reallyLowMHz = 400;for (Int i=0; i<STATIC_GAME_LOD_CUSTOM; i++)+ {m_numLevelPresets[i]=0;+ m_staticGameLODInfo[i].m_gpuParticleCapacity=TheGpuParticleCapacities[i]; //before GameLOD.ini, which may name its own+ }};GameLODManager::~GameLODManager()@@ -382,6 +392,7 @@ void GameLODManager::refreshCustomStaticLODLevel(void)StaticGameLODInfo *lodInfo=&m_staticGameLODInfo[STATIC_GAME_LOD_CUSTOM];lodInfo->m_maxParticleCount=TheGlobalData->m_maxParticleCount;+ lodInfo->m_gpuParticleCapacity=TheGlobalData->m_gpuParticleCapacity;lodInfo->m_useShadowVolumes=TheGlobalData->m_useShadowVolumes;lodInfo->m_useShadowDecals=TheGlobalData->m_useShadowDecals;lodInfo->m_useCloudMap=TheGlobalData->m_useCloudMap;@@ -561,6 +572,7 @@ void GameLODManager::applyStaticLODLevel(StaticGameLODLevel level)if (TheGlobalData){TheWritableGlobalData->m_maxParticleCount=lodInfo->m_maxParticleCount;+ TheWritableGlobalData->m_gpuParticleCapacity=lodInfo->m_gpuParticleCapacity;TheWritableGlobalData->m_useShadowVolumes=lodInfo->m_useShadowVolumes;TheWritableGlobalData->m_useShadowDecals=lodInfo->m_useShadowDecals;@@ -729,6 +741,7 @@ StaticGameLODInfo makeUltraStaticGameLOD( const StaticGameLODInfo &high ){StaticGameLODInfo ultra = high;ultra.m_maxParticleCount = ULTRA_MAX_PARTICLE_COUNT;+ ultra.m_gpuParticleCapacity = TheGpuParticleCapacities[STATIC_GAME_LOD_ULTRA];ultra.m_useShadowVolumes = TRUE;ultra.m_useShadowDecals = TRUE;ultra.m_useCloudMap = TRUE;diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cppindex cd14fa3ff..0a95718d7 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp@@ -1239,6 +1239,9 @@ GlobalData::GlobalData()m_particleGroundBounce = FALSE;m_smokeThickness = 0.0f;m_particleCapOverride = 0;+ m_gpuParticleCapacity = 1 << 20;+ m_gpuParticleCapacityOverride = -1;+ m_gpuParticleCheck = FALSE;m_noDynamicLODOverride = FALSE;m_maxFieldParticleCount = 30;diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cppindex 86a95ffcd..c995cdd11 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp@@ -8041,8 +8041,10 @@ void InGameUI::updateSignalMarks( void )continue;}+ // puffs the GPU took have no Particle, and their system says how long the last of them livesconst Particle *youngest = smoke->getLastParticle();- const UnsignedInt left = smoke->getSystemLifetimeLeft() + ( youngest ? youngest->getLifetimeLeft() : 0 );+ const UnsignedInt puffLeft = max( youngest ? youngest->getLifetimeLeft() : 0, smoke->getGpuLifetimeLeft() );+ const UnsignedInt left = smoke->getSystemLifetimeLeft() + puffLeft;const UnsignedInt opacity = min( (UnsignedInt)SIGNAL_MARK_OPACITY, left * SIGNAL_MARK_OPACITY / SIGNAL_MARK_FADE_OUT_FRAMES );mark.decal->setOpacity( shown ? (Int)opacity : 0 );index++;diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cppindex f588f4e24..1077d42c4 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp@@ -1587,6 +1587,10 @@ ParticleSystem::ParticleSystem( const ParticleSystemTemplate *sysTemplate,m_groundShadow = NULL;m_inSunMap = FALSE;+ m_gpuEligible = TheParticleSystemManager->acceptsGpuParticles() && sysTemplate->isGpuEligible();+ m_gpuSpawnTotal = 0;+ m_gpuLastDeathFrame = 0;+// A system logic makes inside a tick is built after it (LOGIC-THREAD.md M5). The load path's// systems have no id yet and are never made in a tick.if (m_systemID != INVALID_PARTICLE_SYSTEM_ID && LogicThread::defersEffects())@@ -1684,6 +1688,10 @@ ParticleSystem::~ParticleSystem()// give the ground blob back before the particles it was measured from go awayreleaseGroundShadow();+ // and the device's slot, with every GPU particle still in the air+ if (m_gpuEligible)+ TheParticleSystemManager->releaseGpuSystem( this );+// destroy all particles "in the air"while (m_systemParticlesHead)m_systemParticlesHead->deleteInstance();@@ -2183,7 +2191,7 @@ Particle *ParticleSystem::createParticle( const ParticleInfo *info,if ( getParticleCount() > 0 && priority == AREA_EFFECT && m_isGroundAligned && TheParticleSystemManager->getFieldParticleCount() > (UnsignedInt)TheGlobalData->m_maxFieldParticleCount )return NULL;-+// ALWAYS_RENDER particles are exempt from all count limits, and are always created, regardless of LOD issues.if (priority != ALWAYS_RENDER){@@ -2194,6 +2202,13 @@ Particle *ParticleSystem::createParticle( const ParticleInfo *info,int numInExcess = TheParticleSystemManager->getParticleCount() - (UnsignedInt)particleCap;if ( numInExcess > 0){+ // At the cap an eligible spawn goes to the GPU pool rather than evicting the oldest, so+ // below it the picture is the CPU's exactly. No Particle comes back; the caller tells+ // this NULL from a refusal by getGpuSpawnTotal. A player who set no particles at all+ // gets none there either.+ if (m_gpuEligible && TheGlobalData->m_maxParticleCount != 0 && spawnOnGpu( info ))+ return NULL;+if( TheParticleSystemManager->removeOldestParticles((UnsignedInt) numInExcess, priority) != numInExcess )return NULL; // could not remove enough particles, don't create new stuff}@@ -2209,6 +2224,30 @@ Particle *ParticleSystem::createParticle( const ParticleInfo *info,}+// ------------------------------------------------------------------------------------------------+/** One spawn to the manager's GPU path, kept in the sample ring if it takes it. */+// ------------------------------------------------------------------------------------------------+Bool ParticleSystem::spawnOnGpu( const ParticleInfo *info )+{+ if (info->m_lifetime == 0 || !TheParticleSystemManager->spawnGpuParticle( this, info ))+ return FALSE;++ const UnsignedInt birth = ParticleSystemManager::getParticleFrame();+ if (m_gpuSamples.empty())+ m_gpuSamples.resize( GPU_SPAWN_SAMPLES );+ GpuSpawnSample &sample = m_gpuSamples[ m_gpuSpawnTotal % GPU_SPAWN_SAMPLES ];+ sample.m_info = *info;+ sample.m_birthFrame = birth;+ ++m_gpuSpawnTotal;++ // a CPU twin is updated in the pass it is born in too, and dies in the update that takes its+ // lifetime to zero+ const UnsignedInt death = birth + info->m_lifetime - 1;+ if (death > m_gpuLastDeathFrame)+ m_gpuLastDeathFrame = death;+ return TRUE;+}+// ------------------------------------------------------------------------------------------------/** Generate a new, random set of ParticleInfo* particleNum and particleCount are used to get 'tween frame particles emitted in the correct@@ -2494,9 +2533,12 @@ Bool ParticleSystem::updateEmission( Int localPlayerIndex, Bool *keepSystem )const ParticleInfo *info = generateParticleInfo(i, count);if (!m_isEmitAboveGroundOnly || (info->m_pos.z >= TheTerrainLogic->getGroundHeight(info->m_pos.x, info->m_pos.y))){- // actually create a particle+ // actually create a particle. One the GPU took has no Particle but still feeds+ // the slave and the chain below; its system has no attached system to make+ // (m_gpuEligible), so p is never NULL there.+ const UnsignedInt gpuSpawnsBefore = m_gpuSpawnTotal;Particle *p = createParticle( info, priority );- if (p == NULL)+ if (p == NULL && m_gpuSpawnTotal == gpuSpawnsBefore)continue;if (m_attachedSystemName.isEmpty() == false)@@ -2696,10 +2738,17 @@ Bool ParticleSystem::reapAndFinishUpdate( void )Bool ParticleSystem::finishUpdate( const ParticleShadowBlob *blob ){if (m_pendingCastsGroundShadow)- updateGroundShadow( blob );+ {+ ParticleShadowBlob footprint = *blob;+ addGpuSamplesToShadowBlob( &footprint );+ updateGroundShadow( &footprint );+ }elsereleaseGroundShadow();+ // GPU particles still in the air hold the system exactly as CPU ones do+ const Bool gpuAlive = getGpuLifetimeLeft() != 0;+//// If we have been "destroyed", wait for all of our particles to die off,// then destroy ourselves (return false).@@ -2707,7 +2756,7 @@ Bool ParticleSystem::finishUpdate( const ParticleShadowBlob *blob )// A finite slave outlives its master by its own lifetime. Going away first nulls the slave's// master, and a slave with no master emits at the world origin and is cut short, so the master// stays in the list, destroyed and drawing nothing, until the slave is done.- if (m_isDestroyed && !m_systemParticlesHead)+ if (m_isDestroyed && !m_systemParticlesHead && !gpuAlive)return m_slaveSystem != NULL && !m_slaveSystem->isSystemForever();// monitor particle system lifetime@@ -2718,7 +2767,7 @@ Bool ParticleSystem::finishUpdate( const ParticleShadowBlob *blob )m_systemLifetimeLeft--;// if there are still particles "in the air", don't destroy yet- if (getParticleCount())+ if (getParticleCount() || gpuAlive)return true;// check if time is up@@ -2741,6 +2790,74 @@ Bool ParticleSystem::finishUpdate( const ParticleShadowBlob *blob )return true;}+// ------------------------------------------------------------------------------------------------+UnsignedInt ParticleSystemManager::getParticleFrame( void )+{+ return TheParticleSystemManager->m_particleFrame;+}++// ------------------------------------------------------------------------------------------------+/** Counted as a CPU particle's getLifetimeLeft is after this frame's update: zero in the update it+ * dies in. */+// ------------------------------------------------------------------------------------------------+UnsignedInt ParticleSystem::getGpuLifetimeLeft( void ) const+{+ const UnsignedInt now = ParticleSystemManager::getParticleFrame();+ return m_gpuLastDeathFrame > now ? m_gpuLastDeathFrame - now : 0;+}++// ------------------------------------------------------------------------------------------------+/** 1 + r + ... + r^(k-1), the sum a damped rate adds up to over k updates. */+// ------------------------------------------------------------------------------------------------+static Real particleDampedSum( Real r, UnsignedInt k )+{+ if (fabsf( 1.0f - r ) < 1e-4f)+ return (Real)k;+ return ( 1.0f - powf( r, (Real)k ) ) / ( 1.0f - r );+}++// ------------------------------------------------------------------------------------------------+/** The GPU particles' share of the ground blob. Each kept spawn is aged over what the blob reads+ * of Particle::update: the ground plane only, where gravity does not reach, so position is the+ * damped velocity plus the drift; size the damped rate; alpha the straight line between its keys.+ * ponytail: GPU_SPAWN_SAMPLES spawns stand in for the whole cloud and alpha skips the key snap+ * and the fade envelope; ParticleClosedForm.h's evaluator replaces this once it lands. */+// ------------------------------------------------------------------------------------------------+void ParticleSystem::addGpuSamplesToShadowBlob( ParticleShadowBlob *blob ) const+{+ const UnsignedInt now = ParticleSystemManager::getParticleFrame();+ const UnsignedInt samples = getGpuSampleCount();+ for (UnsignedInt i = 0; i < samples; ++i)+ {+ const GpuSpawnSample &sample = getGpuSample( i );+ const ParticleInfo &info = sample.m_info;+ const UnsignedInt k = now - sample.m_birthFrame + 1; // updates since birth+ if (k >= info.m_lifetime)+ continue;++ const Real travel = info.m_velDamping * particleDampedSum( info.m_velDamping, k );+ const Real x = info.m_pos.x + k * m_driftVelocity.x + info.m_vel.x * travel;+ const Real y = info.m_pos.y + k * m_driftVelocity.y + info.m_vel.y * travel;+ const Real size = info.m_size + info.m_sizeRate * particleDampedSum( info.m_sizeRateDamping, k );++ Real alpha = info.m_alphaKey[ 0 ].value;+ for (Int j = 1; j < MAX_KEYFRAMES && info.m_alphaKey[ j ].frame; ++j)+ {+ const Keyframe &from = info.m_alphaKey[ j - 1 ];+ const Keyframe &to = info.m_alphaKey[ j ];+ if (k >= to.frame)+ {+ alpha = to.value;+ continue;+ }+ alpha = from.value + ( to.value - from.value ) * (Real)( k - from.frame ) / (Real)( to.frame - from.frame );+ break;+ }++ particleShadowBlobAdd( blob, x, y, size, alpha );+ }+}+// ------------------------------------------------------------------------------------------------/** Give the ground blob back. The decal's manager lives inside TheGameClient, and shutdownAll* runs in reverse init order, so TheGameClient - and with it every decal it was holding - is gone@@ -3653,6 +3770,30 @@ void ParticleSystemTemplate::forceSmokeBoost( const SmokeBoost &boost )m_priority = PRIORITY_FLOOR;}+// ------------------------------------------------------------------------------------------------+/** The GPU path takes only what its closed form evaluates (GPU-PARTICLES.md, split point). Wind,+ * the up-towards-emitter turn and a system on every particle need CPU state each frame; a+ * drawable, a streak, a volume particle, a smudge and the SMUD heat haze are drawn by other code;+ * the fire look and the flipbook read a particle's age in the CPU renderer; ALPHA_TEST and+ * MULTIPLY stay in the CPU's sorted pool. Ground collision does not refuse a system, as the+ * ParticleBounce option forces it on all of them: the device rests those on the terrain instead+ * (isGpuGroundClamped). A lifetime of 0 (forever) is refused per spawn. Slaves and controlled+ * children qualify, being on their own after birth. A system copies every field read here from+ * its template unchanged, so the template answers for all its systems. */+// ------------------------------------------------------------------------------------------------+Bool ParticleSystemTemplate::isGpuEligible( void ) const+{+ return m_particleType == PARTICLE+ && !m_particleTypeName.startsWith( "SMUD" )+ && !m_isGroundAligned+ && m_windMotion == WIND_MOTION_NOT_USED+ && m_attachedSystemName.isEmpty()+ && ( m_shaderType == ALPHA || m_shaderType == ADDITIVE )+ && !m_fireLook+ && m_flipbookGridLog2 == 0+ && !m_isParticleUpTowardsEmitter;+}+// ------------------------------------------------------------------------------------------------/** If returns non-NULL, it is a slave system for use ... the create slaves parameter* tells *this* slave system whether or not it should create any slaves itself@@ -3687,6 +3828,7 @@ ParticleSystemManager::ParticleSystemManager( void )//Added By Sadullah Nader//Initializations insertedm_lastLogicFrameUpdate = 0;+ m_particleFrame = 0;m_particleCount = 0;m_fieldParticleCount = 0;m_groundShadowCount = 0;@@ -3861,6 +4003,8 @@ void ParticleSystemManager::update( void )// update the last logic frame.m_lastLogicFrameUpdate = TheGameLogic->getFrame();+ // before the systems, so a spawn of this pass is born on it and aged once by it, like a Particle+ ++m_particleFrame;USE_PERF_TIMER(ParticleSystemManager)ParticleSystem *sys;diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/GpuParticles.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/GpuParticles.hnew file mode 100644index 000000000..7575f6f71--- /dev/null+++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/GpuParticles.h@@ -0,0 +1,101 @@+/*+** Command & Conquer Generals Zero Hour(tm)+** Copyright 2025 Electronic Arts Inc.+**+** This program is free software: you can redistribute it and/or modify+** it under the terms of the GNU General Public License as published by+** the Free Software Foundation, either version 3 of the License, or+** (at your option) any later version.+**+** This program is distributed in the hope that it will be useful,+** but WITHOUT ANY WARRANTY; without even the implied warranty of+** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+** GNU General Public License for more details.+**+** You should have received a copy of the GNU General Public License+** along with this program. If not, see <http://www.gnu.org/licenses/>.+*/++// GpuParticles.h /////////////////////////////////////////////////////////////////////////////////+// The device half of the GPU particle path (docs/plans/GPU-PARTICLES.md in the wrapper): a ring of+// spawn records written once at birth, a table of system entries, one texture array for every+// particle texture, and the passes that age the ring in closed form and draw it. The bookkeeping+// (which slot a system has, where the ring's head and tail are, what died) is the particle+// manager's, in W3DParticleSys.cpp; this only holds what the device holds.+//+// DX11GpuParticles.cpp is the Direct3D 11 answer. GpuParticlesUnsupported.cpp answers for every+// build without one, where Supported is false and the particle manager never asks for the rest.+///////////////////////////////////////////////////////////////////////////////////////////////////++#pragma once++#ifndef GPU_PARTICLES_H+#define GPU_PARTICLES_H++struct IDirect3DBaseTexture9;+struct ParticleGpuSpawn;+struct ParticleGpuSystemEntry;++namespace GpuParticles+{++/// System entry slots, the low 16 bits of a spawn record's m_systemSlotSeed.+enum { SYSTEM_SLOTS = 16384 };++/// Particle texture slices: one 128 square RGBA8 layer with mips each. Past this a system with a+/// new texture stays on the CPU (W3DParticleSys.cpp says so once in the log).+enum { TEXTURE_SLICES = 256 };++/// The frame's camera in the device's layout, row vectors: clip = world * view * projection.+struct Camera+{+ float view[ 16 ];+ float projection[ 16 ];+};++/// Direct3D 11 presents on a feature level 11 device. False under -d3d9, the SDL3 builds and+/// -headless; the caller adds the Classic setting and the pool size.+bool Supported();++/** Make, or find still there, the ring of capacity records, the system table, the texture array and+ * the programs. False when the device refused any of them; nothing is kept then. fresh comes back+ * true when what the device held before is gone (first call, a new device, a new capacity, a+ * release): the ring is empty and every entry and slice has to be written again. */+bool Prepare( unsigned capacity, bool *fresh );++/// count records into the ring from ring index first; first + count never passes the capacity.+void Write_Spawns( unsigned first, const ParticleGpuSpawn *spawns, unsigned count );++/// count system entries from slot first.+void Write_Systems( unsigned first, const ParticleGpuSystemEntry *entries, unsigned count );++/// The stealth fade of slots 0 .. count - 1, zero for a system the local player does not see.+void Write_Fades( const float *fades, unsigned count );++/** The terrain's height at each of width by height vertices, row by row, for the systems that rest+ * on the ground (an entry's flag 2). mapping takes world x and y to the texture's coordinates:+ * u = x * mapping[0] + mapping[2], v = y * mapping[1] + mapping[3]. */+void Set_Ground( const float *heights, unsigned width, unsigned height, const float mapping[ 4 ] );++/** The picture of texture slice slice: drawn into the array again, at the next Evaluate, when+ * texture's Direct3D 11 view is not the one drawn last time (a texture finishing its background+ * load swaps it), and left as it is otherwise. A null texture leaves the slice clear; every slice+ * starts clear. */+void Set_Slice_Texture( unsigned slice, IDirect3DBaseTexture9 *texture );++/** Age the count records from ring index first (wrapping) to the frame now plus smooth, a fraction+ * of an update, in closed form, once a frame before either pass draws. Nothing is aged again when+ * neither the range, the time nor any record changed since the last call. */+void Evaluate( unsigned first, unsigned count, unsigned now, float smooth );++/** Draw what Evaluate aged with this ParticleSystemInfo::ParticleShaderType, ALPHA newest first and+ * ADDITIVE in any order, depth read and not written. Into the scene, soft where the backend allows+ * it; into a mirror's own target and depth with no fade; nothing into the sun's map. */+void Draw( unsigned shaderType, const Camera &camera );++/// Before the device goes or is reset: everything above is made again by the next Prepare.+void ReleaseDevice();++} // namespace GpuParticles++#endif // GPU_PARTICLES_Hdiff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DParticleSys.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DParticleSys.hindex bd08969df..358572285 100644--- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DParticleSys.h+++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DParticleSys.h@@ -33,14 +33,21 @@#define __W3DParticleSys_H_#include "GameClient/ParticleSys.h"+#include "GameClient/ParticleClosedForm.h"+#include "W3DDevice/GameClient/GpuParticles.h"#include "WW3D2/pointgr.h"#include "WW3D2/streak.h"#include "WW3D2/rinfo.h"#include "WWLib/bittype.h"#include "Platform/ModernWaterBuild.h"+#include <deque>+#include <map>+#include <unordered_map>#include <vector>+class TextureClass;+//=============================================================================/** W3D implementation of the game display which is responsible for creating* all interaction with the screen and updating the display@@ -65,6 +72,17 @@ public:/// at the render's sync point: the systems' stealth fades and the fields' fades, which read the logicvoid takeReadsForRender( void );+ /// The GPU particle path (GpuParticles.h, GPU-PARTICLES.md): on a Direct3D 11 frame with the pool+ /// on and Classic off, an eligible system's spawns become records in the device's ring.+ virtual Bool acceptsGpuParticles( void ) const;+ virtual Bool spawnGpuParticle( ParticleSystem *system, const ParticleInfo *info );+ virtual void releaseGpuSystem( ParticleSystem *system );+ /// The textures as the base does, then the GPU path's ring, programs, slices and ground, so the+ /// match does not make them on its first frames.+ virtual void preloadAssets( TimeOfDay timeOfDay );+ /// Before the Direct3D 11 device goes: the ring, the table and the texture array.+ static void releaseGpuResources( void );+private:enum { MAX_POINTS_PER_GROUP = 512 };@@ -140,6 +158,66 @@ private:UnsignedInt m_frameViewParticles;UnsignedInt m_frameViewSystems;ParticleSystemID m_frameViewNextID;++ /// One system entry slot of the GPU path. A released slot is free again from reuseFrame, when+ /// the last record that names it has died.+ struct GpuSlot+ {+ ParticleSystem * system; ///< NULL while free+ UnsignedInt slice; ///< its texture's slice in the device's array+ UnsignedInt reuseFrame;+ };+ /// An additive or Emissive GPU system the fire light is taken from, seen at the sync point.+ struct GpuFireSystem+ {+ ParticleSystem * system;+ Real fade;+ UnsignedInt slot;+ };+ enum { GPU_NO_SLOT = 0xFFFFFFFF };+ /// Death frames are counted in a ring of this many frames, so the live count needs no walk.+ enum { GPU_DEATH_FRAMES = 0x10000 };++ UnsignedInt gpuSlotFor( ParticleSystem *system );+ UnsignedInt gpuTextureSlice( const AsciiString &name );+ void markGpuSlotDirty( UnsignedInt slot );+ void drainGpuDeaths( UnsignedInt now );+ Bool prepareGpu( void ); ///< the device's half made, or found; false if it refused+ void sendGpuGround( void );+ void drawGpuSlices( void );+ void refreshGpuSystems( void ); ///< entries and fades, with the frame view+ void drawGpuParticles( RenderInfoClass &rinfo ); ///< upload, age, and both passes+ void resetGpuParticles( void );++ Bool m_gpuSupported; ///< GpuParticles::Supported, asked on the main thread only+ UnsignedInt m_gpuCapacity; ///< ring records, fixed by the first spawn; 0 before it+ Bool m_gpuRefused; ///< the device refused the ring: CPU from here on+ UnsignedInt64 m_gpuWritten; ///< records ever written; the next goes at m_gpuWritten % capacity+ UnsignedInt64 m_gpuTail; ///< the oldest record that may be alive+ UnsignedInt64 m_gpuPendingFirst; ///< the record m_gpuPending[0] is+ std::vector<UnsignedInt> m_gpuDeath; ///< per ring record, the first frame it is surely dead+ std::vector<UnsignedInt> m_gpuDeathCounts; ///< records alive that die on each frame, by frame % GPU_DEATH_FRAMES+ UnsignedInt m_gpuLive; ///< records alive+ UnsignedInt m_gpuDrainedFrame; ///< m_gpuDeathCounts is taken off m_gpuLive up to this frame+ std::vector<ParticleGpuSpawn> m_gpuPending; ///< written since the last upload+ std::vector<GpuSlot> m_gpuSlots;+ std::vector<ParticleGpuSystemEntry> m_gpuEntries; ///< as the device has them, one a slot+ std::vector<Real> m_gpuFades;+ Bool m_gpuFadesDirty; ///< m_gpuFades differs from the device's copy+ std::deque<UnsignedInt> m_gpuFreeSlots; ///< in release order, so the front is the first to come free+ UnsignedInt m_gpuDirtyFirst, m_gpuDirtyEnd; ///< entries the device lacks+ std::unordered_map<ParticleSystem *, UnsignedInt> m_gpuSlotOf; ///< GPU_NO_SLOT for a system refused for good+ ParticleSystem * m_gpuLastSystem; ///< one spawn after another is mostly the same system+ UnsignedInt m_gpuLastSlot;+ std::vector<TextureClass *> m_gpuTextures; ///< by slice, a reference held on each+ std::map<TextureClass *, UnsignedInt> m_gpuTextureSlices;+ std::deque<UnsignedInt> m_gpuSliceQueue; ///< slices whose picture the device has not drawn yet+ UnsignedInt m_gpuSliceCursor; ///< the next slice checked for a view that changed+ Bool m_gpuTexturesFullTold;+ std::vector<GpuFireSystem> m_gpuFireSystems;+ UnsignedInt m_gpuSpawned; ///< since the last GPUPARTICLES line+ UnsignedInt m_gpuEvicted;+ UnsignedInt m_gpuLogFrame;};#endif // end __W3DParticleSys_H_diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/DX11GpuParticles.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/DX11GpuParticles.cppnew file mode 100644index 000000000..733877877--- /dev/null+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/DX11GpuParticles.cpp@@ -0,0 +1,938 @@+// Direct3D 11 backend for the GPU particle path (GpuParticles.h, GPU-PARTICLES.md in the wrapper):+// the spawn ring, the system table, the texture array and the three passes, drawn on the context+// between two of the backend's draws. Distributed under the repository's GPL-3.0 terms; see+// LICENSE.md.+//+// A frame runs one compute pass and two draws. The compute pass ages every record in the ring's+// live range once, in closed form, into a buffer of drawable particles (position, size, angle,+// colour, slice); doing it in the vertex shader instead would evaluate each particle six times a+// pass and twice over for the two passes. Both draws go in from doParticles, ADDITIVE then ALPHA,+// so smoke darkens the fire under it as the sorted pool's order does, and before the CPU's sorted+// billboards land over them. Each is one Draw of six vertices a particle with no vertex buffer,+// every particle texture in one Texture2DArray, so a frame is three calls whatever the number of+// systems or textures.+//+// The HLSL below mirrors ParticleClosedForm.h line for line: that header is the reference the tests+// hold, and a change to one is a change to both.+#include "W3DDevice/GameClient/GpuParticles.h"+#include "Common/Debug.h"+#include "dx11backend.h"+#include "dx11device.h"+#include "dx11runtime.h"+#include "dx11resource.h"+#include "dx11texture.h"++#include <d3d11.h>+#include <cmath>+#include <cstring>+#include <string>++namespace {++// ParticleClosedForm.h's records; W3DParticleSys.cpp asserts the sizes against the structs.+const unsigned SpawnStride = 80;+const unsigned EntryStride = 240;+// The compute pass's output: float3 position, size, four half colour channels, angle, kind.+const unsigned ParticleStride = 32;+const unsigned SliceTexels = 128;+const unsigned SliceMips = 8; // 128 down to 1+const unsigned GroupSize = 64;+// The backend's own fade length for the sorted billboards (SOFT_PARTICLE_FADE_UNITS, dx11backend.cpp).+const float SoftFadeUnits = 12.0f;+const unsigned Additive = 1; // ParticleSystemInfo::ADDITIVE+const unsigned Alpha = 2; // ParticleSystemInfo::ALPHA++// The records, field for field as ParticleClosedForm.h lays them out. A StructuredBuffer packs+// its elements at four bytes, so a float3 followed by a scalar is the C struct's sixteen bytes.+#define GPU_PARTICLE_RECORDS \+ "struct Spawn\n" \+ "{\n" \+ " float3 Position;\n" \+ " uint Birth;\n" \+ " float3 Velocity;\n" \+ " float Lifetime;\n" \+ " float Size;\n" \+ " float SizeRate;\n" \+ " float SizeDamping;\n" \+ " float VelocityDamping;\n" \+ " float Angle;\n" \+ " float AngularRate;\n" \+ " float AngularDamping;\n" \+ " float ColorScale;\n" \+ " uint SlotSeed;\n" \+ " uint2 AlphaKeys;\n" \+ " uint Pad;\n" \+ "};\n" \+ "struct AlphaSegment\n" \+ "{\n" \+ " float Time;\n" \+ " uint End;\n" \+ "};\n" \+ "struct ColorSegment\n" \+ "{\n" \+ " float3 Rate;\n" \+ " uint End;\n" \+ "};\n" \+ "struct SystemEntry\n" \+ "{\n" \+ " float3 Drift;\n" \+ " float Gravity;\n" \+ " float3 Color;\n" \+ " uint Slice;\n" \+ " uint ShaderType;\n" \+ " uint Flags;\n" \+ " uint AlphaCount;\n" \+ " uint ColorCount;\n" \+ " AlphaSegment Alpha[8];\n" \+ " ColorSegment Colour[8];\n" \+ "};\n" \+ "struct Particle\n" \+ "{\n" \+ " float3 Position;\n" \+ " float Size;\n" \+ " uint2 Colour;\n" /* red and green, blue and alpha, as halves */ \+ " float Angle;\n" \+ " uint Kind;\n" /* the slice in the low 16 bits, the shader type above; 0 is dead */ \+ "};\n" \+ "\n"++// One thread a record. The system entry is read from the buffer where it is indexed by a key, not+// copied: a copied entry is an indexable temporary of sixty registers.+static const char EVALUATE_PROGRAM[] =+ GPU_PARTICLE_RECORDS+ "cbuffer Frame : register(b0)\n"+ "{\n"+ " uint First;\n"+ " uint Count;\n"+ " uint Capacity;\n"+ " uint Now;\n"+ " float Smooth;\n"+ " float3 Unused;\n"+ " float4 GroundMap;\n" // world x and y to the height texture's coordinates: scale x, y, offset x, y+ "};\n"+ "StructuredBuffer<Spawn> Spawns : register(t0);\n"+ "StructuredBuffer<SystemEntry> Systems : register(t1);\n"+ "StructuredBuffer<float> Fades : register(t2);\n"+ "Texture2D<float> Ground : register(t3);\n"+ "SamplerState Linear : register(s0);\n"+ "RWStructuredBuffer<Particle> Particles : register(u0);\n"+ "\n"+ "static const uint ADDITIVE = 1;\n"+ "static const uint ALPHA = 2;\n"+ "static const uint ALPHA_TEST = 3;\n"+ "\n"+ "float alpha_key(Spawn spawn, uint key)\n"+ "{\n"+ " uint word = (key < 4) ? spawn.AlphaKeys.x : spawn.AlphaKeys.y;\n"+ " return float((word >> ((key & 3) * 8)) & 0xFF) / 255.0;\n"+ "}\n"+ "\n"+ // particleClosedFormSums+ "void damped_sums(float damping, float k, out float power, out float sum, out float nested)\n"+ "{\n"+ " float d = (damping < 1.0e-6) ? 1.0e-6 : damping;\n"+ " float e = 1.0 - d;\n"+ " power = pow(abs(d), k);\n" // d is at least 1e-6 already; abs only tells FXC so+ " if (abs(e) * k < 0.1)\n"+ " {\n"+ " sum = k * (1.0 - e * (k - 1.0) / 2.0 * (1.0 - e * (k - 2.0) / 3.0 * (1.0 - e * (k - 3.0) / 4.0)));\n"+ " nested = k * (k + 1.0) / 2.0\n"+ " * (1.0 - e * (k - 1.0) / 3.0 * (1.0 - e * (k - 2.0) / 4.0 * (1.0 - e * (k - 3.0) / 5.0)));\n"+ " return;\n"+ " }\n"+ " sum = (1.0 - power) / e;\n"+ " nested = (k - d * sum) / e;\n"+ "}\n"+ "\n"+ // particleClosedFormAlpha+ "float closed_alpha(Spawn spawn, uint slot, float k)\n"+ "{\n"+ " if (Systems[slot].ShaderType == ADDITIVE)\n"+ " return alpha_key(spawn, 0);\n"+ " uint start = 0;\n"+ " uint key = 0;\n"+ " uint count = Systems[slot].AlphaCount;\n"+ " [loop] for (; key < count; ++key)\n"+ " {\n"+ " uint end = Systems[slot].Alpha[key].End;\n"+ " if (k < float(end))\n"+ " {\n"+ " float from = alpha_key(spawn, key);\n"+ " float rate = (alpha_key(spawn, key + 1) - from) / Systems[slot].Alpha[key].Time;\n"+ " return saturate(from + (k - float(start)) * rate);\n"+ " }\n"+ " start = end;\n"+ " }\n"+ " return saturate(alpha_key(spawn, key));\n"+ "}\n"+ "\n"+ // particleClosedFormColor. Two colour keys on one frame divide by nought: the CPU carries the+ // infinity into a clamp, which is what this does too, but nought over nought is a NaN that a+ // blend would spread through the bloom, so a NaN rate is no change, which is what equal keys mean.+ "float3 closed_colour(Spawn spawn, uint slot, float k)\n"+ "{\n"+ " float scale = spawn.ColorScale;\n"+ " float3 colour = Systems[slot].Color;\n"+ " float done = 0.0;\n"+ " uint count = Systems[slot].ColorCount;\n"+ " [loop] for (uint i = 0; i < count && done < k; ++i)\n"+ " {\n"+ " float end = min(k, float(Systems[slot].Colour[i].End));\n"+ " float3 rate = Systems[slot].Colour[i].Rate;\n"+ " bool3 undefined = (asuint(rate) & 0x7FFFFFFFu) > 0x7F800000u;\n"+ " rate = undefined ? float3(0.0, 0.0, 0.0) : rate;\n"+ " colour = saturate(colour + (end - done) * (rate + scale));\n"+ " done = end;\n"+ " }\n"+ " if (done < k)\n"+ " colour = saturate(colour + (k - done) * scale);\n"+ " return colour;\n"+ "}\n"+ "\n"+ // particleClosedFormFade. An additive particle as black as nought under a falling envelope+ // scales by a negative over nought; it is invisible either way, so it is left black.+ "void closed_fade(Spawn spawn, uint shader, float k, inout float alpha, inout float3 colour)\n"+ "{\n"+ " uint lifetime = (uint)spawn.Lifetime;\n"+ " if (lifetime == 0u)\n"+ " return;\n"+ " uint frames = lifetime / 4u;\n"+ " frames = (frames > 16u) ? 16u : ((frames == 0u) ? 1u : frames);\n"+ " float left = spawn.Lifetime - k;\n"+ " if (left > float(frames))\n"+ " return;\n"+ " float envelope = (left - 1.0) / float(frames);\n"+ " if (shader == ALPHA || shader == ALPHA_TEST)\n"+ " {\n"+ " if (alpha > envelope)\n"+ " alpha = envelope;\n"+ " }\n"+ " else if (shader == ADDITIVE)\n"+ " {\n"+ " float brightest = max(colour.r, max(colour.g, colour.b));\n"+ " if (brightest > envelope && brightest > 0.0)\n"+ " colour *= envelope / brightest;\n"+ " }\n"+ "}\n"+ "\n"+ "[numthreads(64, 1, 1)]\n"+ "void main(uint3 thread : SV_DispatchThreadID)\n"+ "{\n"+ " uint index = thread.x;\n"+ " if (index >= Count)\n"+ " return;\n"+ " Spawn spawn = Spawns[(First + index) % Capacity];\n"+ " uint slot = spawn.SlotSeed & 0xFFFF;\n"+ " uint shader = Systems[slot].ShaderType;\n"+ " float fade = Fades[slot];\n"+ " Particle particle;\n"+ " particle.Position = float3(0.0, 0.0, 0.0);\n"+ " particle.Size = 0.0;\n"+ " particle.Colour = uint2(0, 0);\n"+ " particle.Angle = 0.0;\n"+ " particle.Kind = 0;\n"+ // a released system's records, and a system the local player does not see+ " if ((Systems[slot].Flags & 1) == 0 || fade <= 0.0)\n"+ " {\n"+ " Particles[index] = particle;\n"+ " return;\n"+ " }\n"+ // a newborn is updated on its birth frame, so k is one there; the picture lags a fraction of an+ // update the way the models' smooth motion does+ " float k = max(float(Now - spawn.Birth) + Smooth, 1.0);\n"+ "\n"+ // particleClosedFormEvaluate+ " float power, sum, nested;\n"+ " damped_sums(spawn.VelocityDamping, k, power, sum, nested);\n"+ " float d = (spawn.VelocityDamping < 1.0e-6) ? 1.0e-6 : spawn.VelocityDamping;\n"+ " float travel = d * sum;\n"+ " float3 position = spawn.Position + k * Systems[slot].Drift + spawn.Velocity * travel;\n"+ " position.z += Systems[slot].Gravity * d * nested;\n"+ // A system that would collide with the terrain on the CPU (ParticleBounce) rests on it here: the+ // closed form cannot bounce, so a particle below the ground is put on it and stays as it falls.+ " if ((Systems[slot].Flags & 2) != 0)\n"+ " position.z = max(position.z, Ground.SampleLevel(Linear, position.xy * GroundMap.xy + GroundMap.zw, 0.0));\n"+ " damped_sums(spawn.AngularDamping, k, power, sum, nested);\n"+ " float angle = spawn.Angle + spawn.AngularRate * sum;\n"+ " damped_sums(spawn.SizeDamping, k, power, sum, nested);\n"+ " float size = spawn.Size + spawn.SizeRate * sum;\n"+ "\n"+ " float alpha = closed_alpha(spawn, slot, k);\n"+ " float3 colour = closed_colour(spawn, slot, k);\n"+ " closed_fade(spawn, shader, k, alpha, colour);\n"+ "\n"+ " bool invisible = false;\n"+ " if (shader == ALPHA)\n"+ " {\n"+ " uint last = 0;\n"+ " uint count = Systems[slot].AlphaCount;\n"+ " if (count > 0)\n"+ " last = Systems[slot].Alpha[count - 1].End;\n"+ " invisible = k >= float(last) && alpha < 0.02;\n"+ " }\n"+ " else if (shader == ADDITIVE)\n"+ " {\n"+ " uint last = 0;\n"+ " uint count = Systems[slot].ColorCount;\n"+ " if (count > 0)\n"+ " last = Systems[slot].Colour[count - 1].End;\n"+ " if (k >= float(last))\n"+ " {\n"+ " invisible = (colour.r + colour.g + colour.b) <= 0.06;\n"+ " float first = (last != 0) ? float(last) : 1.0;\n"+ " if (!invisible && first < k)\n"+ " {\n"+ " float firstAlpha = alpha;\n"+ " float3 firstColour = closed_colour(spawn, slot, first);\n"+ " closed_fade(spawn, shader, first, firstAlpha, firstColour);\n"+ " invisible = (firstColour.r + firstColour.g + firstColour.b) <= 0.06;\n"+ " }\n"+ " }\n"+ " }\n"+ " if (invisible || (spawn.Lifetime != 0.0 && k >= spawn.Lifetime))\n"+ " {\n"+ " Particles[index] = particle;\n"+ " return;\n"+ " }\n"+ "\n"+ // stealthFadeParticle, then the vertex colour's clamp (Convert_Color_Clamp)+ " if (shader == ADDITIVE)\n"+ " colour *= fade;\n"+ " else\n"+ " alpha *= fade;\n"+ " colour = saturate(colour);\n"+ " alpha = saturate(alpha);\n"+ " particle.Position = position;\n"+ " particle.Size = size;\n"+ " particle.Colour = uint2(f32tof16(colour.r) | (f32tof16(colour.g) << 16),\n"+ " f32tof16(colour.b) | (f32tof16(alpha) << 16));\n"+ " particle.Angle = angle;\n"+ " particle.Kind = (shader << 16) | (Systems[slot].Slice & 0xFFFF);\n"+ " Particles[index] = particle;\n"+ "}\n";++#define GPU_PARTICLE_PASS_CONSTANTS \+ "cbuffer DrawPass : register(b0)\n" \+ "{\n" \+ " row_major float4x4 View;\n" \+ " row_major float4x4 Projection;\n" \+ " float4 SoftParticleDepth;\n" \+ " uint Count;\n" \+ " uint ShaderType;\n" \+ " uint NewestFirst;\n" \+ " uint Soft;\n" \+ " float Gain;\n" \+ " float3 Unused;\n" \+ "};\n" \+ "struct Corner\n" \+ "{\n" \+ " float4 Position : SV_Position;\n" \+ " float4 Colour : COLOR0;\n" \+ " float3 Coord : TEXCOORD0;\n" \+ " float HalfWidth : TEXCOORD1;\n" \+ "};\n" \+ "\n"++// Six vertices a particle, two triangles over PointGroupClass's quad corners in its order (0 1 2,+// 0 2 3), turned by its orientation table: the angle cut to a byte over a turn as MSVC casts it,+// then that byte over 256. The quad is offset in the camera's space, as Write_Billboard does.+static const char DRAW_VERTEX_PROGRAM[] =+ GPU_PARTICLE_RECORDS+ GPU_PARTICLE_PASS_CONSTANTS+ "StructuredBuffer<Particle> Particles : register(t0);\n"+ "\n"+ "Corner main(uint vertex : SV_VertexID)\n"+ "{\n"+ " uint quad = vertex / 6;\n"+ " uint index = (NewestFirst != 0) ? Count - 1 - quad : quad;\n"+ " Particle particle = Particles[index];\n"+ " Corner corner;\n"+ " corner.Colour = float4(f16tof32(particle.Colour.x & 0xFFFF), f16tof32(particle.Colour.x >> 16),\n"+ " f16tof32(particle.Colour.y & 0xFFFF), f16tof32(particle.Colour.y >> 16));\n"+ " corner.Coord = float3(0.0, 0.0, 0.0);\n"+ " corner.HalfWidth = 1.0;\n"+ // the other pass's particle, or a dead one: all six on one point, which draws nothing+ " if ((particle.Kind >> 16) != ShaderType)\n"+ " {\n"+ " corner.Position = float4(0.0, 0.0, -2.0, 1.0);\n"+ " return corner;\n"+ " }\n"+ " uint which = (0x320210u >> ((vertex - quad * 6) * 4)) & 0xF;\n"+ " float2 local = float2((which >= 2) ? 0.5 : -0.5, (which == 0 || which == 3) ? 0.5 : -0.5);\n"+ " float turn = float(uint(int(particle.Angle * (255.0 / 6.28318531))) & 255u) * (6.28318531 / 256.0);\n"+ " float c = cos(turn);\n"+ " float s = sin(turn);\n"+ " float2 offset = float2(local.x * c - local.y * s, local.x * s + local.y * c) * particle.Size;\n"+ " float4 eye = mul(float4(particle.Position, 1.0), View);\n"+ " eye.xy += offset;\n"+ " corner.Position = mul(eye, Projection);\n"+ " corner.Coord = float3(local.x + 0.5, 0.5 - local.y, float(particle.Kind & 0xFFFF));\n"+ " corner.HalfWidth = max(abs(particle.Size) * 0.5, 1.0e-3);\n"+ " return corner;\n"+ "}\n";++// The sprite modulated by the colour, as the sprite presets' GRADIENT_MODULATE stage does, faded where+// it meets the world through the backend's own soft particle text, and the additive pass brightened+// by the Glow option's gain the way Additive_Glow's blend factor brightens the sorted ones.+static const char DRAW_PIXEL_PROGRAM[] =+ GPU_PARTICLE_PASS_CONSTANTS+ "Texture2DArray Sprites : register(t0);\n"+ "SamplerState Linear : register(s0);\n"+ SOFT_PARTICLE_SAMPLING+ "float4 main(Corner corner) : SV_Target\n"+ "{\n"+ " float4 colour = Sprites.Sample(Linear, corner.Coord) * corner.Colour;\n"+ " if (Soft != 0)\n"+ " {\n"+ " float fade = soft_particle_fade(corner.Position, corner.HalfWidth);\n"+ " if (ShaderType == 1)\n"+ " colour *= fade;\n"+ " else\n"+ " colour.a *= fade;\n"+ " }\n"+ " colour.rgb *= Gain;\n"+ " return colour;\n"+ "}\n";++// A particle texture into its slice: one triangle over the 128 square, read at the level nearest that+// size, so a 256 texture is copied from its own 128 mip.+static const char BLIT_VERTEX_PROGRAM[] =+ "float4 main(uint vertex : SV_VertexID) : SV_Position\n"+ "{\n"+ " float2 corner = float2((vertex << 1) & 2, vertex & 2);\n"+ " return float4(corner.x * 2.0 - 1.0, 1.0 - corner.y * 2.0, 0.0, 1.0);\n"+ "}\n";++static const char BLIT_PIXEL_PROGRAM[] =+ "cbuffer Blit : register(b0)\n"+ "{\n"+ " float Level;\n"+ " float3 Unused;\n"+ "};\n"+ "Texture2D Source : register(t0);\n"+ "SamplerState Linear : register(s0);\n"+ "float4 main(float4 position : SV_Position) : SV_Target\n"+ "{\n"+ " return Source.SampleLevel(Linear, position.xy / 128.0, Level);\n"+ "}\n";++struct FrameBlock {+ unsigned first, count, capacity, now;+ float smooth;+ float unused[3];+ float groundMap[4];+};++struct PassBlock {+ float view[16];+ float projection[16];+ float softParticleDepth[4];+ unsigned count, shaderType, newestFirst, soft;+ float gain;+ float unused[3];+};++struct BlitBlock {+ float level;+ float unused[3];+};++template <class T> void drop(T *&object)+{+ if (object) {+ object->Release();+ object = nullptr;+ }+}++struct State {+ ID3D11Device *device = nullptr;+ unsigned capacity = 0;+ bool refused = false;+ ID3D11Buffer *spawns = nullptr;+ ID3D11ShaderResourceView *spawnView = nullptr;+ ID3D11Buffer *systems = nullptr;+ ID3D11ShaderResourceView *systemView = nullptr;+ ID3D11Buffer *fades = nullptr;+ ID3D11ShaderResourceView *fadeView = nullptr;+ ID3D11Buffer *particles = nullptr;+ ID3D11ShaderResourceView *particleView = nullptr;+ ID3D11UnorderedAccessView *particleWrite = nullptr;+ ID3D11Texture2D *sprites = nullptr;+ ID3D11ShaderResourceView *spriteView = nullptr;+ ID3D11RenderTargetView *sliceTargets[GpuParticles::TEXTURE_SLICES] = {};+ // The view each slice was drawn from, a reference held so no later view can come back at its+ // address and pass for it; null is a cleared slice.+ ID3D11ShaderResourceView *sliceSources[GpuParticles::TEXTURE_SLICES] = {};+ // Set_Slice_Texture's asks since the last Evaluate, drawn there in one go.+ ID3D11ShaderResourceView *slicePending[GpuParticles::TEXTURE_SLICES] = {};+ bool sliceAsked[GpuParticles::TEXTURE_SLICES] = {};+ unsigned slicesAsked = 0;+ ID3D11Texture2D *ground = nullptr;+ ID3D11ShaderResourceView *groundView = nullptr;+ float groundMap[4] = {};+ // What the last Evaluate aged and from what, so a pass drawn again before anything moved (a+ // paused game, a frame faster than the logic) does not age the ring again.+ bool inputsChanged = true;+ unsigned lastFirst = 0, lastCount = 0, lastNow = 0;+ float lastSmooth = -1.0f;+ ID3D11ComputeShader *evaluate = nullptr;+ ID3D11VertexShader *drawVertex = nullptr;+ ID3D11PixelShader *drawPixel = nullptr;+ ID3D11VertexShader *blitVertex = nullptr;+ ID3D11PixelShader *blitPixel = nullptr;+ ID3D11SamplerState *linear = nullptr;+ ID3D11BlendState *alphaBlend = nullptr;+ ID3D11BlendState *additiveBlend = nullptr;+ ID3D11DepthStencilState *depthRead = nullptr;+ ID3D11RasterizerState *rasterizer = nullptr;+ ID3D11Buffer *frameConstants = nullptr;+ ID3D11Buffer *passConstants = nullptr;+ ID3D11Buffer *blitConstants = nullptr;+ unsigned evaluated = 0; // particles the last Evaluate wrote+};+State state;++void release()+{+ drop(state.spawnView);+ drop(state.spawns);+ drop(state.systemView);+ drop(state.systems);+ drop(state.fadeView);+ drop(state.fades);+ drop(state.particleWrite);+ drop(state.particleView);+ drop(state.particles);+ for (ID3D11RenderTargetView *&target : state.sliceTargets) drop(target);+ for (ID3D11ShaderResourceView *&source : state.sliceSources) drop(source);+ drop(state.groundView);+ drop(state.ground);+ drop(state.spriteView);+ drop(state.sprites);+ drop(state.evaluate);+ drop(state.drawVertex);+ drop(state.drawPixel);+ drop(state.blitVertex);+ drop(state.blitPixel);+ drop(state.linear);+ drop(state.alphaBlend);+ drop(state.additiveBlend);+ drop(state.depthRead);+ drop(state.rasterizer);+ drop(state.frameConstants);+ drop(state.passConstants);+ drop(state.blitConstants);+ state = State();+}++bool compile(DX11BackendClass *backend, ID3D11Device *device, const char *source, const char *name,+ const char *profile, void **program)+{+ std::vector<unsigned char> code;+ if (!backend->Compile_Program(source, name, profile, code)) {+ DEBUG_LOG(("GPUPARTICLES: %s did not compile: %s\n", name, backend->First_Compiler_Error()));+ return false;+ }+ switch (profile[0]) {+ case 'c': return SUCCEEDED(device->CreateComputeShader(code.data(), code.size(), nullptr, (ID3D11ComputeShader **)program));+ case 'v': return SUCCEEDED(device->CreateVertexShader(code.data(), code.size(), nullptr, (ID3D11VertexShader **)program));+ default: return SUCCEEDED(device->CreatePixelShader(code.data(), code.size(), nullptr, (ID3D11PixelShader **)program));+ }+}++bool makeStructured(ID3D11Device *device, unsigned count, unsigned stride, bool writable, ID3D11Buffer **buffer,+ ID3D11ShaderResourceView **view, ID3D11UnorderedAccessView **write)+{+ D3D11_BUFFER_DESC description = {};+ description.ByteWidth = count * stride;+ description.Usage = D3D11_USAGE_DEFAULT;+ description.BindFlags = D3D11_BIND_SHADER_RESOURCE | (writable ? D3D11_BIND_UNORDERED_ACCESS : 0);+ description.MiscFlags = D3D11_RESOURCE_MISC_BUFFER_STRUCTURED;+ description.StructureByteStride = stride;+ D3D11_SHADER_RESOURCE_VIEW_DESC read = {};+ read.Format = DXGI_FORMAT_UNKNOWN;+ read.ViewDimension = D3D11_SRV_DIMENSION_BUFFER;+ read.Buffer.FirstElement = 0;+ read.Buffer.NumElements = count;+ if (FAILED(device->CreateBuffer(&description, nullptr, buffer))+ || FAILED(device->CreateShaderResourceView(*buffer, &read, view)))+ return false;+ if (!writable) return true;+ D3D11_UNORDERED_ACCESS_VIEW_DESC written = {};+ written.Format = DXGI_FORMAT_UNKNOWN;+ written.ViewDimension = D3D11_UAV_DIMENSION_BUFFER;+ written.Buffer.FirstElement = 0;+ written.Buffer.NumElements = count;+ return SUCCEEDED(device->CreateUnorderedAccessView(*buffer, &written, write));+}++bool makeConstants(ID3D11Device *device, unsigned bytes, ID3D11Buffer **buffer)+{+ D3D11_BUFFER_DESC description = {};+ description.ByteWidth = bytes;+ description.Usage = D3D11_USAGE_DYNAMIC;+ description.BindFlags = D3D11_BIND_CONSTANT_BUFFER;+ description.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;+ return SUCCEEDED(device->CreateBuffer(&description, nullptr, buffer));+}++void upload(ID3D11DeviceContext *context, ID3D11Buffer *buffer, const void *data, size_t bytes)+{+ D3D11_MAPPED_SUBRESOURCE mapped;+ if (FAILED(context->Map(buffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped))) return;+ std::memcpy(mapped.pData, data, bytes);+ context->Unmap(buffer, 0);+}++bool makeAll(DX11BackendClass *backend, ID3D11Device *device, unsigned capacity)+{+ bool made = makeStructured(device, capacity, SpawnStride, false, &state.spawns, &state.spawnView, nullptr)+ && makeStructured(device, GpuParticles::SYSTEM_SLOTS, EntryStride, false, &state.systems, &state.systemView, nullptr)+ && makeStructured(device, GpuParticles::SYSTEM_SLOTS, sizeof(float), false, &state.fades, &state.fadeView, nullptr)+ && makeStructured(device, capacity, ParticleStride, true, &state.particles, &state.particleView, &state.particleWrite)+ && makeConstants(device, sizeof(FrameBlock), &state.frameConstants)+ && makeConstants(device, sizeof(PassBlock), &state.passConstants)+ && makeConstants(device, sizeof(BlitBlock), &state.blitConstants)+ && compile(backend, device, EVALUATE_PROGRAM, "gpuparticles evaluate", "cs_5_0", (void **)&state.evaluate)+ && compile(backend, device, DRAW_VERTEX_PROGRAM, "gpuparticles draw", "vs_5_0", (void **)&state.drawVertex)+ && compile(backend, device, DRAW_PIXEL_PROGRAM, "gpuparticles draw", "ps_5_0", (void **)&state.drawPixel)+ && compile(backend, device, BLIT_VERTEX_PROGRAM, "gpuparticles slice", "vs_5_0", (void **)&state.blitVertex)+ && compile(backend, device, BLIT_PIXEL_PROGRAM, "gpuparticles slice", "ps_5_0", (void **)&state.blitPixel);++ D3D11_TEXTURE2D_DESC sprites = {};+ sprites.Width = sprites.Height = SliceTexels;+ sprites.MipLevels = SliceMips;+ sprites.ArraySize = GpuParticles::TEXTURE_SLICES;+ sprites.Format = DXGI_FORMAT_R8G8B8A8_UNORM;+ sprites.SampleDesc.Count = 1;+ sprites.Usage = D3D11_USAGE_DEFAULT;+ sprites.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET;+ sprites.MiscFlags = D3D11_RESOURCE_MISC_GENERATE_MIPS;+ made = made && SUCCEEDED(device->CreateTexture2D(&sprites, nullptr, &state.sprites))+ && SUCCEEDED(device->CreateShaderResourceView(state.sprites, nullptr, &state.spriteView));++ D3D11_SAMPLER_DESC sampler = {};+ sampler.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;+ sampler.AddressU = sampler.AddressV = sampler.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;+ sampler.ComparisonFunc = D3D11_COMPARISON_NEVER;+ sampler.MaxLOD = D3D11_FLOAT32_MAX;+ made = made && SUCCEEDED(device->CreateSamplerState(&sampler, &state.linear));++ // The sprite presets' blends: SRCALPHA, INVSRCALPHA and ONE, ONE, the alpha channel taking the+ // same factors as Direct3D 9 gives it with no separate alpha blend.+ D3D11_BLEND_DESC blend = {};+ D3D11_RENDER_TARGET_BLEND_DESC &target = blend.RenderTarget[0];+ target.BlendEnable = TRUE;+ target.SrcBlend = target.SrcBlendAlpha = D3D11_BLEND_SRC_ALPHA;+ target.DestBlend = target.DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;+ target.BlendOp = target.BlendOpAlpha = D3D11_BLEND_OP_ADD;+ target.RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;+ made = made && SUCCEEDED(device->CreateBlendState(&blend, &state.alphaBlend));+ target.SrcBlend = target.SrcBlendAlpha = D3D11_BLEND_ONE;+ target.DestBlend = target.DestBlendAlpha = D3D11_BLEND_ONE;+ made = made && SUCCEEDED(device->CreateBlendState(&blend, &state.additiveBlend));++ // PASS_LEQUAL with no depth write, as both sprite presets+ D3D11_DEPTH_STENCIL_DESC depth = {};+ depth.DepthEnable = TRUE;+ depth.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ZERO;+ depth.DepthFunc = D3D11_COMPARISON_LESS_EQUAL;+ made = made && SUCCEEDED(device->CreateDepthStencilState(&depth, &state.depthRead));++ D3D11_RASTERIZER_DESC rasterizer = {};+ rasterizer.FillMode = D3D11_FILL_SOLID;+ rasterizer.CullMode = D3D11_CULL_NONE;+ rasterizer.DepthClipEnable = TRUE;+ made = made && SUCCEEDED(device->CreateRasterizerState(&rasterizer, &state.rasterizer));++ // A target on every slice, made here with the rest so the first frame that needs one does not.+ for (unsigned slice = 0; made && slice < GpuParticles::TEXTURE_SLICES; ++slice) {+ D3D11_RENDER_TARGET_VIEW_DESC description = {};+ description.Format = DXGI_FORMAT_R8G8B8A8_UNORM;+ description.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DARRAY;+ description.Texture2DArray.MipSlice = 0;+ description.Texture2DArray.FirstArraySlice = slice;+ description.Texture2DArray.ArraySize = 1;+ made = SUCCEEDED(device->CreateRenderTargetView(state.sprites, &description, &state.sliceTargets[slice]));+ }+ return made;+}++// Every slice cleared and the mips made once, at the Prepare that made them (a map's load), so no+// layer is ever undefined and the driver's first GenerateMips is not paid mid-match.+void clearSlices(ID3D11DeviceContext *context)+{+ const float clear[4] = {};+ for (ID3D11RenderTargetView *target : state.sliceTargets) context->ClearRenderTargetView(target, clear);+ context->GenerateMips(state.spriteView);+}++// The asked slices drawn from their textures, then every mip of the array again. Binds on the+// context behind the backend's back, so the caller forgets the backend's bindings afterwards.+void drawSlices(ID3D11DeviceContext *context)+{+ ID3D11RenderTargetView *savedTarget = nullptr;+ ID3D11DepthStencilView *savedDepth = nullptr;+ context->OMGetRenderTargets(1, &savedTarget, &savedDepth);+ D3D11_VIEWPORT savedViewport;+ UINT viewportCount = 1;+ context->RSGetViewports(&viewportCount, &savedViewport);++ const D3D11_VIEWPORT viewport = { 0.0f, 0.0f, float(SliceTexels), float(SliceTexels), 0.0f, 1.0f };+ const float clear[4] = {};+ context->RSSetViewports(1, &viewport);+ context->RSSetState(state.rasterizer);+ context->OMSetBlendState(nullptr, nullptr, 0xffffffff);+ context->OMSetDepthStencilState(nullptr, 0);+ context->IASetInputLayout(nullptr);+ context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);+ context->VSSetShader(state.blitVertex, nullptr, 0);+ context->PSSetShader(state.blitPixel, nullptr, 0);+ context->PSSetSamplers(0, 1, &state.linear);+ context->PSSetConstantBuffers(0, 1, &state.blitConstants);++ ID3D11ShaderResourceView *const none = nullptr;+ for (unsigned slice = 0; slice < GpuParticles::TEXTURE_SLICES; ++slice) {+ if (!state.sliceAsked[slice]) continue;+ state.sliceAsked[slice] = false;+ ID3D11ShaderResourceView *source = state.slicePending[slice];+ drop(state.sliceSources[slice]);+ state.sliceSources[slice] = source;+ if (source) source->AddRef();+ // The texture is read only through its own two dimensional view; anything else leaves the+ // slice clear, which draws nothing in either blend.+ D3D11_SHADER_RESOURCE_VIEW_DESC view = {};+ if (source) source->GetDesc(&view);+ context->PSSetShaderResources(0, 1, &none);+ context->OMSetRenderTargets(1, &state.sliceTargets[slice], nullptr);+ context->ClearRenderTargetView(state.sliceTargets[slice], clear);+ if (!source || view.ViewDimension != D3D11_SRV_DIMENSION_TEXTURE2D) continue;++ ID3D11Resource *resource = nullptr;+ source->GetResource(&resource);+ D3D11_TEXTURE2D_DESC texture;+ static_cast<ID3D11Texture2D *>(resource)->GetDesc(&texture);+ resource->Release();+ // SampleLevel counts from the view's most detailed mip, which a reduced texture setting moves+ const unsigned levels = view.Texture2D.MipLevels ? view.Texture2D.MipLevels : 1;+ const unsigned width = texture.Width >> view.Texture2D.MostDetailedMip;+ float level = std::log2(float(width ? width : 1) / float(SliceTexels));+ level = level < 0.0f ? 0.0f : (level > float(levels - 1) ? float(levels - 1) : level);+ const BlitBlock block = { level, { 0.0f, 0.0f, 0.0f } };+ upload(context, state.blitConstants, &block, sizeof(block));+ context->PSSetShaderResources(0, 1, &source);+ context->Draw(3, 0);+ }+ context->PSSetShaderResources(0, 1, &none);+ context->OMSetRenderTargets(1, &savedTarget, savedDepth);+ context->RSSetViewports(viewportCount, &savedViewport);+ if (savedTarget) savedTarget->Release();+ if (savedDepth) savedDepth->Release();+ context->GenerateMips(state.spriteView);+ state.slicesAsked = 0;+}++} // namespace++namespace GpuParticles {++bool Supported()+{+ DX11DeviceClass *device = Direct3D11_Device();+ return Direct3D11_Present_Is_Enabled() && Direct3D11_Backend() && device && device->Get_Device()+ && device->Get_Device()->GetFeatureLevel() >= D3D_FEATURE_LEVEL_11_0;+}++bool Prepare(unsigned capacity, bool *fresh)+{+ ID3D11Device *device = Direct3D11_Device()->Get_Device();+ *fresh = false;+ if (state.device == device && state.capacity == capacity) return !state.refused;+ const double started = DX11Resource_Milliseconds_Now();+ release();+ state.device = device;+ state.capacity = capacity;+ *fresh = true;+ if (!makeAll(Direct3D11_Backend(), device, capacity)) {+ DEBUG_LOG(("GPUPARTICLES: the Direct3D 11 device refused a ring of %u; every particle stays on the CPU\n", capacity));+ release();+ state.device = device;+ state.capacity = capacity;+ state.refused = true;+ return false;+ }+ clearSlices(Direct3D11_Device()->Get_Context());+ DEBUG_LOG(("GPUPARTICLES: ring of %u records (%u MB with the aged copy) made in %.1f ms\n", capacity,+ unsigned((unsigned long long)capacity * (SpawnStride + ParticleStride) >> 20),+ DX11Resource_Milliseconds_Now() - started));+ return true;+}++void Write_Spawns(unsigned first, const ParticleGpuSpawn *spawns, unsigned count)+{+ const D3D11_BOX box = { first * SpawnStride, 0, 0, (first + count) * SpawnStride, 1, 1 };+ Direct3D11_Device()->Get_Context()->UpdateSubresource(state.spawns, 0, &box, spawns, 0, 0);+ state.inputsChanged = true;+}++void Write_Systems(unsigned first, const ParticleGpuSystemEntry *entries, unsigned count)+{+ const D3D11_BOX box = { first * EntryStride, 0, 0, (first + count) * EntryStride, 1, 1 };+ Direct3D11_Device()->Get_Context()->UpdateSubresource(state.systems, 0, &box, entries, 0, 0);+ state.inputsChanged = true;+}++void Write_Fades(const float *fades, unsigned count)+{+ const D3D11_BOX box = { 0, 0, 0, count * unsigned(sizeof(float)), 1, 1 };+ Direct3D11_Device()->Get_Context()->UpdateSubresource(state.fades, 0, &box, fades, 0, 0);+ state.inputsChanged = true;+}++void Set_Ground(const float *heights, unsigned width, unsigned height, const float mapping[4])+{+ drop(state.groundView);+ drop(state.ground);+ D3D11_TEXTURE2D_DESC description = {};+ description.Width = width;+ description.Height = height;+ description.MipLevels = 1;+ description.ArraySize = 1;+ description.Format = DXGI_FORMAT_R32_FLOAT;+ description.SampleDesc.Count = 1;+ description.Usage = D3D11_USAGE_IMMUTABLE;+ description.BindFlags = D3D11_BIND_SHADER_RESOURCE;+ const D3D11_SUBRESOURCE_DATA data = { heights, width * unsigned(sizeof(float)), 0 };+ ID3D11Device *device = Direct3D11_Device()->Get_Device();+ // no ground leaves the clamp on zero, the height of a map with none drawn+ if (FAILED(device->CreateTexture2D(&description, &data, &state.ground))+ || FAILED(device->CreateShaderResourceView(state.ground, nullptr, &state.groundView)))+ DEBUG_LOG(("GPUPARTICLES: the Direct3D 11 device refused a %ux%u ground\n", width, height));+ std::memcpy(state.groundMap, mapping, sizeof(state.groundMap));+ state.inputsChanged = true;+}++void Set_Slice_Texture(unsigned slice, IDirect3DBaseTexture9 *texture)+{+ DX11DeviceClass *device = Direct3D11_Device();+ ID3D11ShaderResourceView *view = texture+ ? DX11Texture_Mirror(device->Get_Device(), device->Get_Context(), texture) : nullptr;+ // The held reference keeps the drawn view alive, so a match on it is that same view and not a+ // later one made at a freed address.+ if (view == state.sliceSources[slice]) return;+ state.slicePending[slice] = view;+ if (!state.sliceAsked[slice]) {+ state.sliceAsked[slice] = true;+ ++state.slicesAsked;+ }+}++void Evaluate(unsigned first, unsigned count, unsigned now, float smooth)+{+ ID3D11DeviceContext *context = Direct3D11_Device()->Get_Context();+ if (state.slicesAsked) {+ drawSlices(context);+ Direct3D11_Backend()->Forget_Bindings();+ }+ state.evaluated = count;+ if (count == 0) return;+ const bool same = !state.inputsChanged && first == state.lastFirst && count == state.lastCount+ && now == state.lastNow && smooth == state.lastSmooth;+ if (same) return;+ state.inputsChanged = false;+ state.lastFirst = first;+ state.lastCount = count;+ state.lastNow = now;+ state.lastSmooth = smooth;++ FrameBlock block = { first, count, state.capacity, now, smooth, { 0.0f, 0.0f, 0.0f }, {} };+ std::memcpy(block.groundMap, state.groundMap, sizeof(block.groundMap));+ upload(context, state.frameConstants, &block, sizeof(block));+ ID3D11ShaderResourceView *const views[4] = { state.spawnView, state.systemView, state.fadeView, state.groundView };+ context->CSSetShader(state.evaluate, nullptr, 0);+ context->CSSetConstantBuffers(0, 1, &state.frameConstants);+ context->CSSetShaderResources(0, 4, views);+ context->CSSetSamplers(0, 1, &state.linear);+ context->CSSetUnorderedAccessViews(0, 1, &state.particleWrite, nullptr);+ context->Dispatch((count + GroupSize - 1) / GroupSize, 1, 1);++ // the backend runs no compute, so nothing of its own is bound here to forget+ ID3D11ShaderResourceView *const noViews[4] = {};+ ID3D11UnorderedAccessView *const noWrite = nullptr;+ context->CSSetUnorderedAccessViews(0, 1, &noWrite, nullptr);+ context->CSSetShaderResources(0, 4, noViews);+ context->CSSetShader(nullptr, nullptr, 0);+}++void Draw(unsigned shaderType, const Camera &camera)+{+ DX11BackendClass *backend = Direct3D11_Backend();+ // the sun's depth map takes no particle, GPU or sorted+ if (state.evaluated == 0 || backend->Shadow_Map_Bound()) return;+ DX11DeviceClass *device = Direct3D11_Device();+ ID3D11DeviceContext *context = device->Get_Context();+ // A mirror draws into a target and depth of its own: the particles go there as they are, with no+ // fade, since the depth copy is the scene's and not the mirror's.+ ID3D11RenderTargetView *target = backend->Scene_Target();+ ID3D11DepthStencilView *targetDepth = device->Get_Depth_Stencil_View();+ ID3D11RenderTargetView *heldTarget = nullptr;+ ID3D11DepthStencilView *heldDepth = nullptr;+ ID3D11ShaderResourceView *depth = nullptr;+ if (target) {+ backend->Take_Scene_Depth();+ depth = backend->Soft_Particles_Allowed() ? backend->Scene_Depth_Copy() : nullptr;+ } else {+ context->OMGetRenderTargets(1, &heldTarget, &heldDepth);+ target = heldTarget;+ targetDepth = heldDepth;+ }+ if (!target) {+ if (heldDepth) heldDepth->Release();+ return;+ }++ PassBlock block;+ std::memcpy(block.view, camera.view, sizeof(block.view));+ std::memcpy(block.projection, camera.projection, sizeof(block.projection));+ // SOFT_PARTICLE_SAMPLING's distance from a depth, out of the projection the world was drawn with+ block.softParticleDepth[0] = camera.projection[11] * camera.projection[14];+ block.softParticleDepth[1] = camera.projection[11];+ block.softParticleDepth[2] = camera.projection[10];+ block.softParticleDepth[3] = 1.0f / SoftFadeUnits;+ block.count = state.evaluated;+ block.shaderType = shaderType;+ block.newestFirst = shaderType == Alpha ? 1u : 0u;+ block.soft = depth ? 1u : 0u;+ block.gain = (shaderType == Additive && backend->Draws_Into_Scene()) ? backend->Additive_Gain() : 1.0f;+ block.unused[0] = block.unused[1] = block.unused[2] = 0.0f;+ upload(context, state.passConstants, &block, sizeof(block));++ context->OMSetRenderTargets(1, &target, targetDepth);+ context->IASetInputLayout(nullptr);+ context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);+ context->VSSetShader(state.drawVertex, nullptr, 0);+ context->VSSetConstantBuffers(0, 1, &state.passConstants);+ context->VSSetShaderResources(0, 1, &state.particleView);+ context->PSSetShader(state.drawPixel, nullptr, 0);+ context->PSSetConstantBuffers(0, 1, &state.passConstants);+ context->PSSetShaderResources(0, 1, &state.spriteView);+ context->PSSetShaderResources(7, 1, &depth);+ context->PSSetSamplers(0, 1, &state.linear);+ context->RSSetState(state.rasterizer);+ context->OMSetDepthStencilState(state.depthRead, 0);+ context->OMSetBlendState(shaderType == Additive ? state.additiveBlend : state.alphaBlend, nullptr, 0xffffffff);+ context->Draw(state.evaluated * 6, 0);++ ID3D11ShaderResourceView *const none = nullptr;+ context->VSSetShaderResources(0, 1, &none);+ context->PSSetShaderResources(0, 1, &none);+ context->PSSetShaderResources(7, 1, &none);+ if (heldTarget) heldTarget->Release();+ if (heldDepth) heldDepth->Release();+ backend->Forget_Bindings();+}++void ReleaseDevice() { release(); }++} // namespace GpuParticlesdiff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GpuParticlesUnsupported.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GpuParticlesUnsupported.cppnew file mode 100644index 000000000..d5ee3fd08--- /dev/null+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/GpuParticlesUnsupported.cpp@@ -0,0 +1,19 @@+// The GPU particle path's entry points for a build with no Direct3D 11 backend: nothing is+// supported, so the particle manager keeps every particle on the CPU and never asks for the rest.+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.+#include "W3DDevice/GameClient/GpuParticles.h"++namespace GpuParticles {++bool Supported() { return false; }+bool Prepare(unsigned, bool *fresh) { *fresh = false; return false; }+void Write_Spawns(unsigned, const ParticleGpuSpawn *, unsigned) {}+void Write_Systems(unsigned, const ParticleGpuSystemEntry *, unsigned) {}+void Write_Fades(const float *, unsigned) {}+void Set_Ground(const float *, unsigned, unsigned, const float[4]) {}+void Set_Slice_Texture(unsigned, IDirect3DBaseTexture9 *) {}+void Evaluate(unsigned, unsigned, unsigned, float) {}+void Draw(unsigned, const Camera &) {}+void ReleaseDevice() {}++} // namespace GpuParticlesdiff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cppindex 3e440e558..3ad39f867 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp@@ -487,6 +487,7 @@ static unsigned long long s_smoothPasses = 0;W3DDisplay::~W3DDisplay(){W3DParticleSystemManager::releaseCloudResources();+ W3DParticleSystemManager::releaseGpuResources();// R1: how each captured model was treated per tick, for the snap rules' tuning.{const unsigned long long *counts = SmoothMotion_Counts();diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cppindex 30c47334b..b07cbb485 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp@@ -81,6 +81,31 @@#include "Common/QuickTrig.h"#include "Platform/MsvcFloatCasts.h"+#include "Common/MapObject.h"++// DX11GpuParticles.cpp reads the records at these strides and writes the fade window's numbers into+// its HLSL; a change here is a change there.+static_assert( sizeof( ParticleGpuSpawn ) == 80 && sizeof( ParticleGpuSystemEntry ) == 240,+ "DX11GpuParticles.cpp's SpawnStride and EntryStride" );+static_assert( PARTICLE_CLOSED_FORM_FADE_MAX_FRAMES == 16 && PARTICLE_CLOSED_FORM_FADE_LIFETIME_DIVISOR == 4,+ "DX11GpuParticles.cpp's closed_fade" );+static_assert( GpuParticles::SYSTEM_SLOTS <= 0x10000, "a spawn record holds its slot in 16 bits" );+static_assert( MAX_KEYFRAMES == 8, "DX11GpuParticles.cpp's SystemEntry holds eight segments of each" );++/// The ring's largest size: Evaluate dispatches a group of 64 a record, and a dispatch takes 65535.+static const UnsignedInt GPU_PARTICLE_MOST_RECORDS = 64u * 65535u;++/// The ring the detail preset or -gpuparticles asks for, held to what one dispatch can age.+static UnsignedInt gpuCapacityAsked( void )+{+ const UnsignedInt asked = (UnsignedInt)TheGlobalData->getEffectiveGpuParticleCapacity();+ return asked < GPU_PARTICLE_MOST_RECORDS ? asked : GPU_PARTICLE_MOST_RECORDS;+}++/// A system entry's m_flags as DX11GpuParticles.cpp's compute pass reads them: the system is there,+/// and its particles rest on the terrain (ParticleBounce) instead of falling through it.+static const UnsignedInt PARTICLE_GPU_ALIVE = 1;+static const UnsignedInt PARTICLE_GPU_GROUND_CLAMPED = 2;#ifdef DEBUG_LOGGINGextern Real TheParticleFillMS;@@ -203,31 +228,13 @@ static UnsignedInt s_fireLightsFrame; ///< the particle update they werestatic UnsignedInt s_fireLightsParticles;static UnsignedInt s_fireLightsSystems;-/** One additive or Emissive system as a point light, if it is bright enough. An Emissive body's- * colour stays white while its flipbook cools to soot, so its weight falls with the life left. */-static void gatherFireLight( ParticleSystem *sys, Real fade )+/** One fire's light from its particles' weighted sums: w the weight, x, y and z the weighted+ * position, sq the weighted square of it. FALSE when it is not bright enough. */+static Bool makeFireLight( Real w, Real x, Real y, Real z, Real sq, Real fade, FireLight &fire ){- const Bool emissive = sys->getTemplate()->isEmissive();- Real w = 0.0f, x = 0.0f, y = 0.0f, z = 0.0f, sq = 0.0f;- for (Particle *p = sys->getFirstParticle(); p; p = p->m_systemNext)- {- const RGBColor *c = p->getColor();- Real pw = (c->red + c->green + c->blue) * (1.0f / 3.0f) * p->getSize();- if (emissive && p->m_lifetime)- pw *= (Real)p->getLifetimeLeft() / (Real)p->m_lifetime;- if (pw <= 0.0f)- continue;- const Coord3D *pos = p->getPosition();- w += pw;- x += pw * pos->x;- y += pw * pos->y;- z += pw * pos->z;- sq += pw * (pos->x * pos->x + pos->y * pos->y + pos->z * pos->z);- }if (w < FIRE_LIGHT_MIN_WEIGHT)- return;+ return FALSE;- FireLight fire;SmokeLight &light = fire.light;const Real inv = 1.0f / w;light.x = x * inv;@@ -253,7 +260,93 @@ static void gatherFireLight( ParticleSystem *sys, Real fade )light.invHeight = 1.0f / height;light.invBelow = 1.0f / (radius * FIRE_LIGHT_BELOW_SHARE);light.reachSq = reach * reach;- s_fireLights.push_back( fire );+ return TRUE;+}++static void addFireLight( Real w, Real x, Real y, Real z, Real sq, Real fade )+{+ FireLight fire;+ if (makeFireLight( w, x, y, z, sq, fade, fire ))+ s_fireLights.push_back( fire );+}++/** One additive or Emissive system as a point light, if it is bright enough. An Emissive body's+ * colour stays white while its flipbook cools to soot, so its weight falls with the life left. */+static void gatherFireLight( ParticleSystem *sys, Real fade )+{+ const Bool emissive = sys->getTemplate()->isEmissive();+ Real w = 0.0f, x = 0.0f, y = 0.0f, z = 0.0f, sq = 0.0f;+ for (Particle *p = sys->getFirstParticle(); p; p = p->m_systemNext)+ {+ const RGBColor *c = p->getColor();+ Real pw = (c->red + c->green + c->blue) * (1.0f / 3.0f) * p->getSize();+ if (emissive && p->m_lifetime)+ pw *= (Real)p->getLifetimeLeft() / (Real)p->m_lifetime;+ if (pw <= 0.0f)+ continue;+ const Coord3D *pos = p->getPosition();+ w += pw;+ x += pw * pos->x;+ y += pw * pos->y;+ z += pw * pos->z;+ sq += pw * (pos->x * pos->x + pos->y * pos->y + pos->z * pos->z);+ }+ addFireLight( w, x, y, z, sq, fade );+}++/** The same for a GPU system, from the spawns it keeps (ParticleSystem::getGpuSample) aged in closed+ * form to the last particle update, as a CPU particle stands then.+ * ponytail: GPU_SPAWN_SAMPLES spawns stand in for the whole fire, so a big one weighs as a small+ * one would; scale by a live count per slot if fires under smoke look too dim.+ * A million particles can be thousands of such systems at sixteen closed forms each, eight+ * milliseconds on one thread, so the systems go to the job pool, one item each, and the lit ones+ * join s_fireLights afterwards in the order the walk found them. */+struct GpuFireLight+{+ ParticleSystem * system;+ Real fade;+ UnsignedInt slot;+ const ParticleGpuSystemEntry * entry;+ FireLight light;+ Bool lit;+};++static std::vector<GpuFireLight> s_gpuFireLights; ///< kept across updates so the gather does not allocate++static const Int GPU_FIRE_LIGHTS_PER_CLAIM = 16;++static void gatherGpuFireLight( Int index, void *context )+{+ GpuFireLight &fire = ( (GpuFireLight *)context )[ index ];+ ParticleSystem *sys = fire.system;+ const UnsignedInt slot = fire.slot;+ const ParticleGpuSystemEntry &entry = *fire.entry;+ const Bool emissive = sys->getTemplate()->isEmissive();+ const UnsignedInt now = ParticleSystemManager::getParticleFrame();+ Real w = 0.0f, x = 0.0f, y = 0.0f, z = 0.0f, sq = 0.0f;+ for (UnsignedInt i = 0; i < sys->getGpuSampleCount(); ++i)+ {+ const ParticleSystem::GpuSpawnSample &sample = sys->getGpuSample( i );+ ParticleGpuSpawn spawn;+ particleGpuSpawnPack( sample.m_info, sample.m_birthFrame, slot, 0, &spawn );+ const Real k = (Real)( now - sample.m_birthFrame + 1 );+ ParticleClosedFormState state;+ particleClosedFormEvaluate( spawn, entry, k, &state );+ if (state.m_dead)+ continue;+ Real pw = (state.m_color.red + state.m_color.green + state.m_color.blue) * (1.0f / 3.0f) * state.m_size;+ if (emissive)+ pw *= ( spawn.m_lifetime - k ) / spawn.m_lifetime;+ if (pw <= 0.0f)+ continue;+ const Coord3D &pos = state.m_pos;+ w += pw;+ x += pw * pos.x;+ y += pw * pos.y;+ z += pw * pos.z;+ sq += pw * (pos.x * pos.x + pos.y * pos.y + pos.z * pos.z);+ }+ fire.lit = makeFireLight( w, x, y, z, sq, fire.fade, fire.light );}/** The scene's enabled light pulses, which FX lists put on explosions. */@@ -1678,6 +1771,26 @@ W3DParticleSystemManager::W3DParticleSystemManager()m_frameViewSystems = 0;m_frameViewNextID = INVALID_PARTICLE_SYSTEM_ID;+ // asked again on the main thread at each map's load and each draw; this may run on the logic's+ m_gpuSupported = FALSE;+ m_gpuCapacity = 0;+ m_gpuRefused = FALSE;+ m_gpuWritten = 0;+ m_gpuTail = 0;+ m_gpuPendingFirst = 0;+ m_gpuLive = 0;+ m_gpuDrainedFrame = 0;+ m_gpuFadesDirty = FALSE;+ m_gpuDirtyFirst = 0;+ m_gpuDirtyEnd = 0;+ m_gpuLastSystem = NULL;+ m_gpuLastSlot = GPU_NO_SLOT;+ m_gpuSliceCursor = 0;+ m_gpuTexturesFullTold = FALSE;+ m_gpuSpawned = 0;+ m_gpuEvicted = 0;+ m_gpuLogFrame = 0;+m_pointGroup = NEW PointGroupClass();//m_streakLine = NULL;m_streakLine = NEW StreakLineClass();@@ -1706,6 +1819,8 @@ W3DParticleSystemManager::~W3DParticleSystemManager()REF_PTR_RELEASE(m_sizeBuffer);REF_PTR_RELEASE(m_angleBuffer);REF_PTR_RELEASE(m_frameBuffer);++ resetGpuParticles(); // the texture references it holds}/** A reset can be followed by an update on the same logic frame, so the fires' frame alone would@@ -1719,6 +1834,7 @@ void W3DParticleSystemManager::reset()m_fieldSystems.clear();m_sunMapCasters.clear();invalidateGroundFields(); // the object IDs it holds belong to the game that ended+ resetGpuParticles(); // the client frame starts again, and every system is gone}void W3DParticleSystemManager::invalidateGroundFields(bool fadeIn)@@ -1744,6 +1860,13 @@ void W3DParticleSystemManager::releaseCloudResources()s_fieldCloudCapabilityKnown = false;}+/** Only for the device going: a mode change keeps the device, and with it the ring's particles,+ * where releaseCloudResources drops the clouds' screen sized targets. */+void W3DParticleSystemManager::releaseGpuResources()+{+ GpuParticles::ReleaseDevice();+}+/** LOGIC-THREAD.md phase 3. A system's stealth fade asks its object's drawable, and a field asks for* its object, its life and the fog, so the frame view and the fields are taken here, before the* render; the render's own refreshFrameView finds the view still valid. */@@ -1792,6 +1915,7 @@ void W3DParticleSystemManager::refreshFrameView( void )#endifm_frameView.push_back( view );}+ refreshGpuSystems();m_frameViewValid = TRUE;m_sunMapCastersValid = FALSE;@@ -2022,7 +2146,13 @@ void W3DParticleSystemManager::doParticles(RenderInfoClass &rinfo)fillJob.extentY = beY;fillJob.extentZ = beZ;fillJob.lightCount = 0;- if (TheGlobalData->m_smokeFireLighting)+ // Only a CPU drawn smoke system takes a light (pickSmokeLights); with none, the walk over every+ // fire, a GPU one's samples aged in closed form, is a third of a frame thrown away.+ Bool smokeDrawn = FALSE;+ for (size_t v = 0; v < m_frameView.size() && !smokeDrawn; ++v)+ smokeDrawn = m_frameView[ v ].system->getShaderType() == ParticleSystemInfo::ALPHA+ && !m_frameView[ v ].system->getTemplate()->isEmissive();+ if (TheGlobalData->m_smokeFireLighting && smokeDrawn){// Between two particle updates nothing moves a particle; a system made in between has none// yet, and the counts catch a load or anything else that adds or takes some away.@@ -2035,6 +2165,21 @@ void W3DParticleSystemManager::doParticles(RenderInfoClass &rinfo)if (m_frameView[ v ].system->getShaderType() == ParticleSystemInfo::ADDITIVE|| m_frameView[ v ].system->getTemplate()->isEmissive())gatherFireLight( m_frameView[ v ].system, m_frameView[ v ].fade );+ s_gpuFireLights.resize( m_gpuFireSystems.size() );+ for (size_t g = 0; g < m_gpuFireSystems.size(); ++g)+ {+ const GpuFireSystem &fire = m_gpuFireSystems[ g ];+ GpuFireLight &item = s_gpuFireLights[ g ];+ item.system = fire.system;+ item.fade = fire.fade;+ item.slot = fire.slot;+ item.entry = &m_gpuEntries[ fire.slot ];+ }+ if (!s_gpuFireLights.empty())+ JobSystem::parallel_for( (Int)s_gpuFireLights.size(), GPU_FIRE_LIGHTS_PER_CLAIM, gatherGpuFireLight, &s_gpuFireLights[ 0 ] );+ for (size_t g = 0; g < s_gpuFireLights.size(); ++g)+ if (s_gpuFireLights[ g ].lit)+ s_fireLights.push_back( s_gpuFireLights[ g ].light );s_fireLightsValid = TRUE;s_fireLightsFrame = m_lastLogicFrameUpdate;s_fireLightsParticles = m_particleCount;@@ -2336,6 +2481,10 @@ void W3DParticleSystemManager::doParticles(RenderInfoClass &rinfo)}#endif+ // The GPU particles' two passes, under the sorted billboards this loop put in the sorting pool,+ // which land over them when the pool flushes.+ drawGpuParticles( rinfo );+//Draw any particles belonging to weather effectsif (TheSnowManager)((W3DSnowManager *)TheSnowManager)->render(rinfo);@@ -2348,3 +2497,458 @@ void W3DParticleSystemManager::doParticles(RenderInfoClass &rinfo)TheSmudgeManager->setSmudgeCountLastFrame(visibleSmudgeCount);}}++//-------------------------------------------------------------------------------------------------+// The GPU particle path's bookkeeping (GPU-PARTICLES.md in the wrapper; GpuParticles.h is the device+// half). A spawn is packed into a record at the ring's head and kept on the CPU only as the frame+// it is surely dead on, which is what the live range and the eviction count read, and counted by+// that frame for the log line's live count. A system gets an entry slot at its first spawn and+// gives it back when it goes; the slot is not handed out again until the last record naming it has+// died. Everything goes up to the device in drawGpuParticles: the frame's records in at most two+// pieces, the entries and fades that changed, and a few texture slices a frame.+//-------------------------------------------------------------------------------------------------++/// A particle texture's first picture, drawn into its slice: at most this many a frame.+static const UnsignedInt GPU_SLICES_DRAWN_A_FRAME = 4;+/// Slices looked at again a frame for a view that changed (a texture's background load finishing).+static const UnsignedInt GPU_SLICES_CHECKED_A_FRAME = 8;++/** Asked by every system's constructor, which may run on the logic thread, so it reads only what the+ * main thread cached and calls nothing on the device. */+Bool W3DParticleSystemManager::acceptsGpuParticles( void ) const+{+ return m_gpuSupported && !m_gpuRefused && TheGlobalData->getEffectiveGpuParticleCapacity() > 0+ && !TheGlobalData->m_headless && !TheGlobalData->m_classicGraphics;+}++void W3DParticleSystemManager::markGpuSlotDirty( UnsignedInt slot )+{+ if (m_gpuDirtyFirst == m_gpuDirtyEnd)+ {+ m_gpuDirtyFirst = slot;+ m_gpuDirtyEnd = slot + 1;+ return;+ }+ if (slot < m_gpuDirtyFirst)+ m_gpuDirtyFirst = slot;+ if (slot + 1 > m_gpuDirtyEnd)+ m_gpuDirtyEnd = slot + 1;+}++/** The array slice of a particle texture, given one on its first use and queued for its picture. A+ * reference is held on each texture until the match ends, so its slice stays its own. GPU_NO_SLOT+ * once the array is full. */+UnsignedInt W3DParticleSystemManager::gpuTextureSlice( const AsciiString &name )+{+ TextureClass *texture = W3DDisplay::m_assetManager->Get_Texture( name.str() );+ std::map<TextureClass *, UnsignedInt>::const_iterator known = m_gpuTextureSlices.find( texture );+ if (known != m_gpuTextureSlices.end())+ {+ texture->Release_Ref();+ return known->second;+ }+ if (m_gpuTextures.size() == (size_t)GpuParticles::TEXTURE_SLICES)+ {+ if (!m_gpuTexturesFullTold)+ DEBUG_LOG(( "GPUPARTICLES: the texture array is full at %d slices; %s and every texture after it stays on the CPU\n",+ (Int)GpuParticles::TEXTURE_SLICES, name.str() ));+ m_gpuTexturesFullTold = TRUE;+ texture->Release_Ref();+ return GPU_NO_SLOT;+ }+ const UnsignedInt slice = (UnsignedInt)m_gpuTextures.size();+ m_gpuTextures.push_back( texture );+ m_gpuTextureSlices[ texture ] = slice;+ m_gpuSliceQueue.push_back( slice );+ return slice;+}++/** The entry slot of a system, given one at its first spawn: the longest released slot if its records+ * have all died, else a new one. GPU_NO_SLOT when all SYSTEM_SLOTS are taken or the texture array+ * is full, and the CPU takes the spawn; the texture refusal is kept, the slot one asked again. */+UnsignedInt W3DParticleSystemManager::gpuSlotFor( ParticleSystem *system )+{+ if (system == m_gpuLastSystem)+ return m_gpuLastSlot;++ UnsignedInt slot = GPU_NO_SLOT;+ std::unordered_map<ParticleSystem *, UnsignedInt>::const_iterator known = m_gpuSlotOf.find( system );+ if (known != m_gpuSlotOf.end())+ slot = known->second;+ else+ {+ const UnsignedInt slice = gpuTextureSlice( system->getParticleTypeName() );+ if (slice == GPU_NO_SLOT)+ {+ m_gpuSlotOf[ system ] = GPU_NO_SLOT;+ return GPU_NO_SLOT;+ }+ // ponytail: only the front is looked at; a slot released later that comes free sooner waits its turn+ if (!m_gpuFreeSlots.empty() && m_gpuSlots[ m_gpuFreeSlots.front() ].reuseFrame <= getParticleFrame())+ {+ slot = m_gpuFreeSlots.front();+ m_gpuFreeSlots.pop_front();+ }+ else+ {+ if (m_gpuSlots.size() == (size_t)GpuParticles::SYSTEM_SLOTS)+ return GPU_NO_SLOT;+ slot = (UnsignedInt)m_gpuSlots.size();+ m_gpuSlots.resize( slot + 1 );+ m_gpuEntries.resize( slot + 1 );+ m_gpuFades.resize( slot + 1 );+ }++ GpuSlot &taken = m_gpuSlots[ slot ];+ taken.system = system;+ taken.slice = slice;+ taken.reuseFrame = 0;+ ParticleGpuSystemEntry &entry = m_gpuEntries[ slot ];+ particleGpuSystemEntryBuild( *system, &entry );+ entry.m_textureSlice = slice;+ entry.m_flags = PARTICLE_GPU_ALIVE | ( system->isGpuGroundClamped() ? PARTICLE_GPU_GROUND_CLAMPED : 0u );+ // the fade is taken at the sync point (refreshGpuSystems), which runs before the next draw+ m_gpuFades[ slot ] = 1.0f;+ m_gpuFadesDirty = TRUE;+ markGpuSlotDirty( slot );+ m_gpuSlotOf[ system ] = slot;+ }++ m_gpuLastSystem = system;+ m_gpuLastSlot = slot;+ return slot;+}++/** The records that died since the last call off the live count. The particle frame only goes up+ * (a reset clears the counts); a gap of a whole ring of frames with no call means no spawn in it+ * either, so everything counted has died. */+void W3DParticleSystemManager::drainGpuDeaths( UnsignedInt now )+{+ if (now <= m_gpuDrainedFrame)+ return;+ if (now - m_gpuDrainedFrame >= (UnsignedInt)GPU_DEATH_FRAMES)+ {+ std::fill( m_gpuDeathCounts.begin(), m_gpuDeathCounts.end(), 0u );+ m_gpuLive = 0;+ m_gpuDrainedFrame = now;+ return;+ }+ while (m_gpuDrainedFrame < now)+ {+ UnsignedInt &dying = m_gpuDeathCounts[ ++m_gpuDrainedFrame % GPU_DEATH_FRAMES ];+ m_gpuLive -= dying;+ dying = 0;+ }+}++Bool W3DParticleSystemManager::spawnGpuParticle( ParticleSystem *system, const ParticleInfo *info )+{+ // Classic can come on mid-match, after the system was made eligible; its spawns go to the CPU+ if (m_gpuRefused || TheGlobalData->m_classicGraphics)+ return FALSE;+ const UnsignedInt slot = gpuSlotFor( system );+ if (slot == GPU_NO_SLOT)+ return FALSE;++ // k = now - birth + smooth reaches the lifetime one update after a CPU twin's last+ const UnsignedInt now = getParticleFrame();+ drainGpuDeaths( now );+ UnsignedInt &death = m_gpuDeath[ (size_t)( m_gpuWritten % m_gpuCapacity ) ];+ if (death > now)+ {+ ++m_gpuEvicted;+ --m_gpuDeathCounts[ death % GPU_DEATH_FRAMES ];+ --m_gpuLive;+ }+ // ponytail: the death count's ring is 65535 frames (18 minutes), so a longer life is cut to that+ // for the tail and the count; the compute pass still ages it by its own lifetime while it is drawn+ const UnsignedInt life = info->m_lifetime < (UnsignedInt)GPU_DEATH_FRAMES ? info->m_lifetime : (UnsignedInt)GPU_DEATH_FRAMES - 1;+ death = now + life;+ ++m_gpuDeathCounts[ death % GPU_DEATH_FRAMES ];+ ++m_gpuLive;++ // A window drawing nothing (minimised) still spawns; past two rings of records only the newest+ // ring could ever be drawn.+ if (m_gpuPending.size() == 2 * (size_t)m_gpuCapacity)+ {+ m_gpuPending.erase( m_gpuPending.begin(), m_gpuPending.begin() + m_gpuCapacity );+ m_gpuPendingFirst += m_gpuCapacity;+ }+ m_gpuPending.resize( m_gpuPending.size() + 1 );+ particleGpuSpawnPack( *info, now, slot, (UnsignedInt)( m_gpuWritten * 2654435761u ) >> 16, &m_gpuPending.back() );+ ++m_gpuWritten;+ ++m_gpuSpawned;+ return TRUE;+}++void W3DParticleSystemManager::releaseGpuSystem( ParticleSystem *system )+{+ std::unordered_map<ParticleSystem *, UnsignedInt>::iterator known = m_gpuSlotOf.find( system );+ if (known == m_gpuSlotOf.end())+ return; // an eligible system that never spawned on the GPU+ const UnsignedInt slot = known->second;+ m_gpuSlotOf.erase( known );+ if (m_gpuLastSystem == system)+ m_gpuLastSystem = NULL;+ if (slot == GPU_NO_SLOT)+ return; // refused for its texture, it never held one++ // its records stay in the ring until they die; until then the entry culls them, and the slot waits+ GpuSlot &freed = m_gpuSlots[ slot ];+ freed.system = NULL;+ freed.reuseFrame = system->getGpuLastDeathFrame() + 1;+ m_gpuEntries[ slot ].m_flags = 0;+ m_gpuFades[ slot ] = 0.0f;+ m_gpuFadesDirty = TRUE;+ markGpuSlotDirty( slot );+ m_gpuFreeSlots.push_back( slot );+}++/** With the frame view, at the sync point: each system's stealth fade, and the fires among them for+ * the smoke's light. The entry is not built again here: gpuSlotFor builds it at the system's first+ * GPU spawn, and the only writers of the keys it reads (tintAllColors from the beacon and the signal+ * smoke, which also sets two keys of its own) run right after createParticleSystem, before any spawn;+ * a slave's merge works on a copy. Rebuilding and comparing every entry every update cost 0.65 ms+ * at 3450 systems.+ * ponytail: a key changed on a system already spawning on the GPU is not seen; give+ * ParticleSystemInfo a key version and rebuild on a new one if anything ever does that. */+void W3DParticleSystemManager::refreshGpuSystems( void )+{+ m_gpuFireSystems.clear();+ for (UnsignedInt slot = 0; slot < (UnsignedInt)m_gpuSlots.size(); ++slot)+ {+ ParticleSystem *sys = m_gpuSlots[ slot ].system;+ if (sys == NULL)+ continue;+ const Real fade = sys->getStealthFade();+ const Real shown = fade > 0.0f ? fade : 0.0f;+ if (m_gpuFades[ slot ] != shown)+ {+ m_gpuFades[ slot ] = shown;+ m_gpuFadesDirty = TRUE;+ }+ if (fade > 0.0f && sys->getGpuSampleCount() != 0+ && ( sys->getShaderType() == ParticleSystemInfo::ADDITIVE || sys->getTemplate()->isEmissive() ))+ {+ const GpuFireSystem fire = { sys, fade, slot };+ m_gpuFireSystems.push_back( fire );+ }+ }+}++/** At a map's load, after the base has loaded the particle textures: everything the device makes+ * for the GPU path is made here, so the match's first frames pay none of it. */+void W3DParticleSystemManager::preloadAssets( TimeOfDay timeOfDay )+{+ ParticleSystemManager::preloadAssets( timeOfDay );+ // a detail preset changed since the last match asks for another ring: made again here, between+ // matches, never in one, and a size the device refused before may be one it takes now+ if (m_gpuCapacity != 0 && TheGlobalData->getEffectiveGpuParticleCapacity() > 0 && gpuCapacityAsked() != m_gpuCapacity)+ {+ m_gpuCapacity = 0;+ m_gpuRefused = FALSE;+ }+ if (!prepareGpu())+ return;+ sendGpuGround(); // a new map: the old ground is not this one's++ // Every texture an eligible template names gets its slice and picture now, drawn in one go.+ // ponytail: the slices go in template order, so past TEXTURE_SLICES the textures left out are+ // whichever came last, not the least used; count spawns per texture if that ever bites.+ for (TemplateMap::const_iterator it = beginParticleSystemTemplate(); it != endParticleSystemTemplate(); ++it)+ {+ const ParticleSystemTemplate *tmplate = it->second;+ if (tmplate->isGpuEligible() && !tmplate->getParticleTypeName().isEmpty()+ && gpuTextureSlice( tmplate->getParticleTypeName() ) == GPU_NO_SLOT)+ break;+ }+ while (!m_gpuSliceQueue.empty())+ {+ const UnsignedInt slice = m_gpuSliceQueue.front();+ m_gpuSliceQueue.pop_front();+ m_gpuTextures[ slice ]->Init();+ GpuParticles::Set_Slice_Texture( slice, m_gpuTextures[ slice ]->Peek_D3D_Base_Texture() );+ }+ GpuParticles::Evaluate( 0, 0, getParticleFrame(), 0.0f ); // draws the slices asked; ages nothing+ DEBUG_LOG(( "GPUPARTICLES: %u texture slices drawn at load\n", (UnsignedInt)m_gpuTextures.size() ));+}++/** On the main thread, at a map's load and at each draw. A device made again (a reset, a new+ * capacity) holds nothing of what went up before: those records are lost, and every entry, fade,+ * slice and the ground go up again. */+Bool W3DParticleSystemManager::prepareGpu( void )+{+ m_gpuSupported = GpuParticles::Supported();+ if (!m_gpuSupported || m_gpuRefused || TheGlobalData->getEffectiveGpuParticleCapacity() <= 0)+ return FALSE;+ if (m_gpuCapacity == 0)+ {+ m_gpuCapacity = gpuCapacityAsked();+ m_gpuDeath.assign( m_gpuCapacity, 0 );+ m_gpuDeathCounts.assign( GPU_DEATH_FRAMES, 0 );+ }++ bool fresh = false;+ if (!GpuParticles::Prepare( m_gpuCapacity, &fresh ))+ {+ m_gpuRefused = TRUE;+ m_gpuPending.clear();+ m_gpuPendingFirst = m_gpuWritten;+ m_gpuTail = m_gpuWritten;+ return FALSE;+ }+ if (fresh)+ {+ if (m_gpuTail < m_gpuPendingFirst)+ m_gpuTail = m_gpuPendingFirst;+ m_gpuDirtyFirst = 0;+ m_gpuDirtyEnd = (UnsignedInt)m_gpuSlots.size();+ m_gpuFadesDirty = TRUE;+ m_gpuSliceQueue.clear();+ for (UnsignedInt slice = 0; slice < (UnsignedInt)m_gpuTextures.size(); ++slice)+ m_gpuSliceQueue.push_back( slice );+ sendGpuGround();+ }+ return TRUE;+}++/** The drawn terrain's heights (BaseHeightMapRenderObjClass::getDrawHeight's map) for the systems+ * that rest on it, one texel a height map vertex so the device's bilinear read lands on the vertices+ * as the CPU's does.+ * ponytail: taken once a map and at a device's reset, so a crater dug in the match is not in it;+ * send it again from the terrain's own change if a resting particle is seen floating over one. */+void W3DParticleSystemManager::sendGpuGround( void )+{+ WorldHeightMap *map = TheTerrainRenderObject->getMap();+ if (map == NULL)+ return; // no map loaded: a menu drawn with no shell map+ const UnsignedInt width = (UnsignedInt)map->getXExtent();+ const UnsignedInt height = (UnsignedInt)map->getYExtent();+ const UnsignedByte *data = map->getDataPtr();+ std::vector<float> heights( (size_t)width * height );+ for (size_t i = 0; i < heights.size(); ++i)+ heights[ i ] = data[ i ] * MAP_HEIGHT_SCALE;+ // vertex i is at world (i - border) * MAP_XY_FACTOR, its texel's centre at (i + 0.5) / extent+ const Real border = (Real)map->getBorderSizeInline();+ const float mapping[ 4 ] = { 1.0f / ( MAP_XY_FACTOR * width ), 1.0f / ( MAP_XY_FACTOR * height ),+ ( border + 0.5f ) / width, ( border + 0.5f ) / height };+ GpuParticles::Set_Ground( &heights[ 0 ], width, height, mapping );+}++/** A few queued slices' first pictures a frame, and a few drawn ones looked at again in turn, so a+ * burst of new textures is spread over frames instead of landing in one. */+void W3DParticleSystemManager::drawGpuSlices( void )+{+ const auto send = [this]( UnsignedInt slice )+ {+ TextureClass *texture = m_gpuTextures[ slice ];+ texture->Init(); // as Apply would, for a texture no CPU draw has bound+ GpuParticles::Set_Slice_Texture( slice, texture->Peek_D3D_Base_Texture() );+ };+ for (UnsignedInt drawn = 0; drawn < GPU_SLICES_DRAWN_A_FRAME && !m_gpuSliceQueue.empty(); ++drawn)+ {+ send( m_gpuSliceQueue.front() );+ m_gpuSliceQueue.pop_front();+ }+ const UnsignedInt count = (UnsignedInt)m_gpuTextures.size();+ for (UnsignedInt checked = 0; checked < GPU_SLICES_CHECKED_A_FRAME && checked < count; ++checked)+ {+ m_gpuSliceCursor = ( m_gpuSliceCursor + 1 ) % count;+ send( m_gpuSliceCursor );+ }+}++/** Both passes, from doParticles before the sorted billboards: ADDITIVE first so the smoke drawn in+ * the ALPHA pass darkens the fire under it, as the sorting pool's back to front order mostly does. */+void W3DParticleSystemManager::drawGpuParticles( RenderInfoClass &rinfo )+{+ // Classic may have come on mid-match: what is in the ring waits, undrawn, until it goes off+ if (TheGlobalData->m_classicGraphics || !prepareGpu())+ return;++ const UnsignedInt now = getParticleFrame();+ drainGpuDeaths( now );++ // the records spawned since the last draw, the newest ring of them at most, in at most two pieces+ const size_t pending = m_gpuPending.size();+ if (pending != 0)+ {+ const UnsignedInt keep = pending < (size_t)m_gpuCapacity ? (UnsignedInt)pending : m_gpuCapacity;+ const ParticleGpuSpawn *from = &m_gpuPending[ pending - keep ];+ const UnsignedInt ring = (UnsignedInt)( ( m_gpuWritten - keep ) % m_gpuCapacity );+ const UnsignedInt first = keep < m_gpuCapacity - ring ? keep : m_gpuCapacity - ring;+ GpuParticles::Write_Spawns( ring, from, first );+ if (first < keep)+ GpuParticles::Write_Spawns( 0, from + first, keep - first );+ m_gpuPending.clear();+ }+ m_gpuPendingFirst = m_gpuWritten;++ if (m_gpuDirtyFirst != m_gpuDirtyEnd)+ {+ GpuParticles::Write_Systems( m_gpuDirtyFirst, &m_gpuEntries[ m_gpuDirtyFirst ], m_gpuDirtyEnd - m_gpuDirtyFirst );+ m_gpuDirtyFirst = m_gpuDirtyEnd = 0;+ }+ if (m_gpuFadesDirty && !m_gpuFades.empty())+ GpuParticles::Write_Fades( &m_gpuFades[ 0 ], (UnsignedInt)m_gpuFades.size() );+ m_gpuFadesDirty = FALSE;+ drawGpuSlices();++ // the oldest record that may still be alive: past every overwritten one, then past the dead+ if (m_gpuWritten - m_gpuTail > m_gpuCapacity)+ m_gpuTail = m_gpuWritten - m_gpuCapacity;+ while (m_gpuTail < m_gpuWritten && m_gpuDeath[ (size_t)( m_gpuTail % m_gpuCapacity ) ] <= now)+ ++m_gpuTail;+ const UnsignedInt range = (UnsignedInt)( m_gpuWritten - m_gpuTail );++ GpuParticles::Evaluate( (UnsignedInt)( m_gpuTail % m_gpuCapacity ), range, now, TheSmoothMotionAlpha );++ const HazardCloud::Camera cloud = cloudCamera( rinfo.Camera );+ GpuParticles::Camera camera;+ memcpy( camera.view, cloud.view, sizeof( camera.view ) );+ memcpy( camera.projection, cloud.projection, sizeof( camera.projection ) );+ GpuParticles::Draw( ParticleSystemInfo::ADDITIVE, camera );+ GpuParticles::Draw( ParticleSystemInfo::ALPHA, camera );++#ifdef DEBUG_LOGGING+ // GPU-PARTICLES.md's measurement line, beside PARTICLES every 100 particle updates: the records+ // alive, those spawned and those overwritten alive since the last line, the range the passes+ // draw, and the systems holding a slot.+ if (m_lastLogicFrameUpdate % 100 == 0 && m_lastLogicFrameUpdate != m_gpuLogFrame)+ {+ m_gpuLogFrame = m_lastLogicFrameUpdate;+ DEBUG_LOG(( "GPUPARTICLES frame %d: live %u spawned %u ring %u evicted %u systems %u\n",+ m_lastLogicFrameUpdate, m_gpuLive, m_gpuSpawned, range, m_gpuEvicted, (UnsignedInt)m_gpuSlotOf.size() ));+ m_gpuSpawned = 0;+ m_gpuEvicted = 0;+ }+#endif+}++/** After a reset every system is gone, so nothing in the ring is drawn again, no slot waits, and the+ * match's textures are let go for the next one's. */+void W3DParticleSystemManager::resetGpuParticles( void )+{+ m_gpuTail = m_gpuWritten;+ m_gpuPendingFirst = m_gpuWritten;+ m_gpuPending.clear();+ std::fill( m_gpuDeath.begin(), m_gpuDeath.end(), 0u );+ std::fill( m_gpuDeathCounts.begin(), m_gpuDeathCounts.end(), 0u );+ m_gpuLive = 0;+ m_gpuSlots.clear();+ m_gpuEntries.clear();+ m_gpuFades.clear();+ m_gpuFadesDirty = FALSE;+ m_gpuFreeSlots.clear();+ m_gpuSlotOf.clear();+ m_gpuLastSystem = NULL;+ m_gpuDirtyFirst = m_gpuDirtyEnd = 0;+ m_gpuFireSystems.clear();+ for (size_t i = 0; i < m_gpuTextures.size(); ++i)+ m_gpuTextures[ i ]->Release_Ref();+ m_gpuTextures.clear();+ m_gpuTextureSlices.clear();+ m_gpuSliceQueue.clear();+ m_gpuSliceCursor = 0;+ m_gpuTexturesFullTold = FALSE;+}diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.hindex 850df4839..2f9c4b9ab 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h@@ -119,6 +119,9 @@ public:// Copy the scene's depth for the soft particles if anything wrote it since the last copy. The// sorting pool calls it at the top of each flush, before any particle run resolves its program.void Take_Scene_Depth();+ // The copy Take_Scene_Depth keeps, for a pass drawn behind the backend's back that fades where+ // it meets the world (the GPU particles). Null before the first copy and under Classic.+ ID3D11ShaderResourceView * Scene_Depth_Copy() const { return SceneDepthCopyView; }// How many depth copies Take_Scene_Depth made since the last call. Taking it resets it.unsigned Take_Frame_Depth_Copies();// Off under the Classic graphics setting, whose picture is -d3d9's: no draw fades, no copy.@@ -129,6 +132,7 @@ public:PipelineChanged = true;}}+ bool Soft_Particles_Allowed() const { return SoftParticlesAllowed; }// The engine bound a texture at this stage that has no D3D11 copy - a render target it drew// into, most often. Sampling white there paints a full screen quad over the frame, so a drawdiff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cppindex 7cc8b4828..621b122ed 100644--- a/GeneralsMD/Code/Tests/test_gameengine.cpp+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp@@ -3148,6 +3148,454 @@ TEST(particle_already_leaving_the_surface_is_only_lifted_clear)CHECK_NEAR(vel.x, 1.0f, 1e-5f);}+//////////////////////////////////////////////////////////////////////////////+// Particle closed form+//+// ParticleClosedForm.h says where Particle::update leaves a particle after k+// updates without running them. A real Particle needs a live system and the+// manager, so the replica below is Particle::update's arithmetic copied line+// for line (no wind, no ground, no upTowardsEmitter). A change to that+// function has to be made here as well.+//////////////////////////////////////////////////////////////////////////////++#include "GameClient/ParticleClosedForm.h"++struct ParticleReplica+{+ Coord3D pos, vel, accel;+ Real velDamping, angleZ, angularRateZ, angularDamping, size, sizeRate, sizeRateDamping;+ Keyframe alphaKey[ MAX_KEYFRAMES ];+ RGBColorKeyframe colorKey[ MAX_KEYFRAMES ];+ Real alpha, alphaRate;+ Int alphaTargetKey;+ RGBColor color, colorRate;+ Int colorTargetKey;+ Real colorScale;+ UnsignedInt lifetime, lifetimeLeft, createTimestamp;++ void computeAlphaRate()+ {+ if (alphaKey[ alphaTargetKey ].frame == 0)+ {+ alphaRate = 0.0f;+ return;+ }+ Real delta = alphaKey[ alphaTargetKey ].value - alphaKey[ alphaTargetKey - 1 ].value;+ UnsignedInt time = alphaKey[ alphaTargetKey ].frame - alphaKey[ alphaTargetKey - 1 ].frame;+ alphaRate = delta / time;+ }++ void computeColorRate()+ {+ if (colorKey[ colorTargetKey ].frame == 0)+ {+ colorRate.red = colorRate.green = colorRate.blue = 0.0f;+ return;+ }+ UnsignedInt time = colorKey[ colorTargetKey ].frame - colorKey[ colorTargetKey - 1 ].frame;+ colorRate.red = ( colorKey[ colorTargetKey ].color.red - colorKey[ colorTargetKey - 1 ].color.red ) / time;+ colorRate.green = ( colorKey[ colorTargetKey ].color.green - colorKey[ colorTargetKey - 1 ].color.green ) / time;+ colorRate.blue = ( colorKey[ colorTargetKey ].color.blue - colorKey[ colorTargetKey - 1 ].color.blue ) / time;+ }++ Bool isInvisible( const ParticleUpdateContext &context )+ {+ switch (context.shaderType)+ {+ case ParticleSystemInfo::ADDITIVE:+ if (colorTargetKey >= MAX_KEYFRAMES || colorKey[ colorTargetKey ].frame == 0)+ return ( color.red + color.green + color.blue ) <= 0.06f;+ return false;+ case ParticleSystemInfo::ALPHA:+ if (alphaTargetKey >= MAX_KEYFRAMES || alphaKey[ alphaTargetKey ].frame == 0)+ return alpha < 0.02f;+ return false;+ default:+ return false;+ }+ }++ Bool update( const ParticleUpdateContext &context )+ {+ if (context.gravity != 0.0f)+ accel.z += context.gravity;+ vel.x += accel.x;+ vel.y += accel.y;+ vel.z += accel.z;+ vel.x *= velDamping;+ vel.y *= velDamping;+ vel.z *= velDamping;+ pos.x += vel.x + context.driftVelocity.x;+ pos.y += vel.y + context.driftVelocity.y;+ pos.z += vel.z + context.driftVelocity.z;++ angleZ += angularRateZ;+ angularRateZ *= angularDamping;+ size += sizeRate;+ sizeRate *= sizeRateDamping;++ if (context.shaderType != ParticleSystemInfo::ADDITIVE)+ {+ alpha += alphaRate;+ if (alphaTargetKey < MAX_KEYFRAMES && alphaKey[ alphaTargetKey ].frame)+ {+ if (context.clientFrame - createTimestamp >= alphaKey[ alphaTargetKey ].frame)+ {+ alpha = alphaKey[ alphaTargetKey ].value;+ alphaTargetKey++;+ computeAlphaRate();+ }+ }+ else+ alphaRate = 0.0f;+ alpha = particleClosedFormClamp01( alpha );+ }++ color.red += colorRate.red;+ color.green += colorRate.green;+ color.blue += colorRate.blue;+ if (colorTargetKey < MAX_KEYFRAMES && colorKey[ colorTargetKey ].frame)+ {+ if (context.clientFrame - createTimestamp >= colorKey[ colorTargetKey ].frame)+ {+ colorTargetKey++;+ computeColorRate();+ }+ }+ else+ colorRate.red = colorRate.green = colorRate.blue = 0.0f;+ color.red = particleClosedFormClamp01( color.red + colorScale );+ color.green = particleClosedFormClamp01( color.green + colorScale );+ color.blue = particleClosedFormClamp01( color.blue + colorScale );++ accel.z = accel.y = accel.x = 0.0f;++ if (lifetimeLeft)+ {+ if (--lifetimeLeft == 0)+ return false;+ UnsignedInt fadeFrames = lifetime / PARTICLE_CLOSED_FORM_FADE_LIFETIME_DIVISOR;+ if (fadeFrames > PARTICLE_CLOSED_FORM_FADE_MAX_FRAMES)+ fadeFrames = PARTICLE_CLOSED_FORM_FADE_MAX_FRAMES;+ else if (fadeFrames == 0)+ fadeFrames = 1;+ if (lifetimeLeft <= fadeFrames)+ {+ const Real envelope = (Real)( lifetimeLeft - 1 ) / (Real)fadeFrames;+ if (context.shaderType == ParticleSystemInfo::ALPHA && alpha > envelope)+ alpha = envelope;+ if (context.shaderType == ParticleSystemInfo::ADDITIVE)+ {+ Real brightest = color.red > color.green ? color.red : color.green;+ brightest = brightest > color.blue ? brightest : color.blue;+ if (brightest > envelope)+ {+ const Real scale = envelope / brightest;+ color.red *= scale;+ color.green *= scale;+ color.blue *= scale;+ }+ }+ }+ }+ return !isInvisible( context );+ }+};++/// a system and a particle of it the closed-form tests start from; keys all off+static void closedFormSetup( ParticleSystemInfo *system, ParticleInfo *info,+ ParticleSystemInfo::ParticleShaderType shader, UnsignedInt lifetime )+{+ system->m_shaderType = shader;+ system->m_driftVelocity.set( 0.25f, -0.5f, 0.125f );+ system->m_gravity = -0.05f;+ for( Int i = 0; i < MAX_KEYFRAMES; ++i )+ {+ system->m_alphaKey[ i ].frame = 0;+ system->m_colorKey[ i ].frame = 0;+ system->m_colorKey[ i ].color.red = system->m_colorKey[ i ].color.green = system->m_colorKey[ i ].color.blue = 0.0f;+ info->m_alphaKey[ i ].value = 0.0f;+ }+ info->m_pos.set( 10.0f, 20.0f, 30.0f );+ info->m_vel.set( 1.5f, -0.75f, 2.0f );+ info->m_velDamping = 0.95f;+ info->m_angleZ = 0.3f;+ info->m_angularRateZ = 0.05f;+ info->m_angularDamping = 0.9f;+ info->m_size = 2.0f;+ info->m_sizeRate = 0.4f;+ info->m_sizeRateDamping = 0.98f;+ info->m_colorScale = 0.0f;+ info->m_lifetime = lifetime;+}++static void closedFormColorKey( ParticleSystemInfo *system, Int key, Real red, Real green, Real blue, UnsignedInt frame )+{+ system->m_colorKey[ key ].color.red = red;+ system->m_colorKey[ key ].color.green = green;+ system->m_colorKey[ key ].color.blue = blue;+ system->m_colorKey[ key ].frame = frame;+}++static void closedFormAlphaKey( ParticleSystemInfo *system, ParticleInfo *info, Int key, Real value, UnsignedInt frame )+{+ system->m_alphaKey[ key ].frame = frame;+ info->m_alphaKey[ key ].value = value;+}++struct ClosedFormRun+{+ Real kinematic; ///< worst relative error over position, velocity, size and angle+ Real alpha; ///< worst alpha error before the fade window+ Real color; ///< worst colour error before the fade window+ Real overEnvelope; ///< how far above the envelope the closed form sat inside the window+ Int deathMismatches;+ UnsignedInt diedAt; ///< the update the replica returned false on+};++static Real closedFormRelative( Real a, Real b )+{+ return fabsf( a - b ) / ( 1.0f + fabsf( b ) );+}++static void closedFormWorst( Real *worst, Real error )+{+ if (!( error <= *worst ))+ *worst = error;+}++static ClosedFormRun closedFormAgainstUpdate( const ParticleSystemInfo &system, ParticleInfo info )+{+ for( Int i = 0; i < MAX_KEYFRAMES; ++i )+ {+ info.m_alphaKey[ i ].frame = system.m_alphaKey[ i ].frame;+ info.m_colorKey[ i ] = system.m_colorKey[ i ];+ }++ const UnsignedInt birth = 1000;+ ParticleGpuSpawn spawn;+ ParticleGpuSystemEntry entry;+ particleGpuSpawnPack( info, birth, 3, 7, &spawn );+ particleGpuSystemEntryBuild( system, &entry );++ // the replica takes the alpha values the spawn record kept, so quantising is not counted as error+ ParticleReplica p;+ p.pos = info.m_pos;+ p.vel = info.m_vel;+ p.accel.zero();+ p.velDamping = info.m_velDamping;+ p.angleZ = info.m_angleZ;+ p.angularRateZ = info.m_angularRateZ;+ p.angularDamping = info.m_angularDamping;+ p.size = info.m_size;+ p.sizeRate = info.m_sizeRate;+ p.sizeRateDamping = info.m_sizeRateDamping;+ for( Int i = 0; i < MAX_KEYFRAMES; ++i )+ {+ p.alphaKey[ i ].value = particleGpuSpawnAlphaKey( spawn, i );+ p.alphaKey[ i ].frame = info.m_alphaKey[ i ].frame;+ p.colorKey[ i ] = info.m_colorKey[ i ];+ }+ p.alpha = p.alphaKey[ 0 ].value;+ p.alphaTargetKey = 1;+ p.computeAlphaRate();+ p.color = p.colorKey[ 0 ].color;+ p.colorTargetKey = 1;+ p.computeColorRate();+ p.colorScale = info.m_colorScale;+ p.lifetime = p.lifetimeLeft = info.m_lifetime;+ p.createTimestamp = birth;++ ParticleUpdateContext context;+ context.driftVelocity = system.m_driftVelocity;+ context.gravity = system.m_gravity;+ context.shaderType = system.m_shaderType;+ context.windMotion = ParticleSystemInfo::WIND_MOTION_NOT_USED;+ context.groundCollision = FALSE;+ context.groundBounce = 0.0f;+ context.groundFriction = 0.0f;++ UnsignedInt fadeFrames = info.m_lifetime / PARTICLE_CLOSED_FORM_FADE_LIFETIME_DIVISOR;+ if (fadeFrames > PARTICLE_CLOSED_FORM_FADE_MAX_FRAMES)+ fadeFrames = PARTICLE_CLOSED_FORM_FADE_MAX_FRAMES;+ else if (fadeFrames == 0)+ fadeFrames = 1;++ ClosedFormRun run = {};+ for( UnsignedInt k = 1; k <= info.m_lifetime; ++k )+ {+ context.clientFrame = birth + k - 1;+ const Bool alive = p.update( context );++ ParticleClosedFormState s;+ particleClosedFormEvaluate( spawn, entry, (Real)k, &s );+ if (s.m_dead == alive)+ ++run.deathMismatches;+ if (!alive)+ {+ run.diedAt = k;+ break;+ }++ closedFormWorst( &run.kinematic, closedFormRelative( s.m_pos.x, p.pos.x ) );+ closedFormWorst( &run.kinematic, closedFormRelative( s.m_pos.y, p.pos.y ) );+ closedFormWorst( &run.kinematic, closedFormRelative( s.m_pos.z, p.pos.z ) );+ closedFormWorst( &run.kinematic, closedFormRelative( s.m_vel.x, p.vel.x ) );+ closedFormWorst( &run.kinematic, closedFormRelative( s.m_vel.y, p.vel.y ) );+ closedFormWorst( &run.kinematic, closedFormRelative( s.m_vel.z, p.vel.z ) );+ closedFormWorst( &run.kinematic, closedFormRelative( s.m_size, p.size ) );+ closedFormWorst( &run.kinematic, closedFormRelative( s.m_angleZ, p.angleZ ) );++ const UnsignedInt left = info.m_lifetime - k;+ if (left > fadeFrames)+ {+ closedFormWorst( &run.alpha, fabsf( s.m_alpha - p.alpha ) );+ closedFormWorst( &run.color, fabsf( s.m_color.red - p.color.red ) );+ closedFormWorst( &run.color, fabsf( s.m_color.green - p.color.green ) );+ closedFormWorst( &run.color, fabsf( s.m_color.blue - p.color.blue ) );+ }+ else+ {+ const Real envelope = (Real)( left - 1 ) / (Real)fadeFrames;+ Real strength = s.m_alpha;+ if (system.m_shaderType == ParticleSystemInfo::ADDITIVE)+ {+ strength = s.m_color.red > s.m_color.green ? s.m_color.red : s.m_color.green;+ strength = strength > s.m_color.blue ? strength : s.m_color.blue;+ }+ closedFormWorst( &run.overEnvelope, strength - envelope );+ }+ }+ return run;+}++static void closedFormCheckRun( const ClosedFormRun &run, UnsignedInt diedAt )+{+ CHECK( run.kinematic < 5e-4f );+ CHECK( run.alpha < 1e-4f );+ CHECK( run.color < 1e-4f );+ CHECK( run.overEnvelope < 1e-5f );+ CHECK_EQ( run.deathMismatches, 0 );+ CHECK_EQ( run.diedAt, diedAt );+}++// VelocityDamping 0 is in the shipped data (jet exhaust): the velocity is gone after the first+// update and only the drift moves it. Alpha snaps to 0 at its last key and isInvisible kills it.+TEST(particle_closed_form_follows_update_with_zero_damping)+{+ ParticleSystemInfo system;+ ParticleInfo info;+ closedFormSetup( &system, &info, ParticleSystemInfo::ALPHA, 90 );+ info.m_velDamping = 0.0f;+ info.m_angularDamping = 0.0f;+ info.m_sizeRateDamping = 0.0f;+ closedFormAlphaKey( &system, &info, 0, 0.25f, 0 );+ closedFormAlphaKey( &system, &info, 1, 1.0f, 20 );+ closedFormAlphaKey( &system, &info, 2, 0.0f, 60 );+ closedFormColorKey( &system, 0, 1.0f, 0.5f, 0.0f, 0 );+ closedFormColorKey( &system, 1, 0.0f, 0.5f, 1.0f, 40 );++ closedFormCheckRun( closedFormAgainstUpdate( system, info ), 61 );+}++// d = 1 takes the series branch, which is exact there. ADDITIVE leaves alpha at key 0 whatever+// the alpha keys say; the colour overshoots each key by one rate and dies black past the last.+TEST(particle_closed_form_follows_update_with_unit_damping)+{+ ParticleSystemInfo system;+ ParticleInfo info;+ closedFormSetup( &system, &info, ParticleSystemInfo::ADDITIVE, 200 );+ info.m_velDamping = 1.0f;+ info.m_angularDamping = 1.0f;+ info.m_sizeRateDamping = 1.0f;+ closedFormAlphaKey( &system, &info, 0, 0.6f, 0 );+ closedFormAlphaKey( &system, &info, 1, 0.1f, 10 );+ closedFormColorKey( &system, 0, 1.0f, 1.0f, 1.0f, 0 );+ closedFormColorKey( &system, 1, 1.0f, 0.5f, 0.25f, 30 );+ closedFormColorKey( &system, 2, 0.0f, 0.0f, 0.0f, 50 );++ closedFormCheckRun( closedFormAgainstUpdate( system, info ), 51 );++ // a constant colour is capped by the envelope and goes black on the last update before its age+ closedFormSetup( &system, &info, ParticleSystemInfo::ADDITIVE, 60 );+ closedFormColorKey( &system, 0, 0.8f, 0.4f, 0.2f, 0 );+ closedFormCheckRun( closedFormAgainstUpdate( system, info ), 59 );+}++// The usual case. colorScale pushes red into the clamp at 1 before its key and the next segment+// brings it down from there, not from where an unclamped sum would have been.+TEST(particle_closed_form_follows_update_with_damping_and_clamps)+{+ ParticleSystemInfo system;+ ParticleInfo info;+ closedFormSetup( &system, &info, ParticleSystemInfo::ALPHA, 300 );+ info.m_colorScale = 0.01f;+ closedFormAlphaKey( &system, &info, 0, 0.0f, 0 );+ closedFormAlphaKey( &system, &info, 1, 0.8f, 30 );+ closedFormAlphaKey( &system, &info, 2, 0.8f, 200 );+ closedFormColorKey( &system, 0, 0.5f, 0.5f, 0.5f, 0 );+ closedFormColorKey( &system, 1, 1.0f, 0.2f, 0.9f, 40 );+ closedFormColorKey( &system, 2, 0.1f, 0.9f, 0.0f, 100 );++ closedFormCheckRun( closedFormAgainstUpdate( system, info ), 299 );++ info.m_colorScale = -0.02f;+ closedFormCheckRun( closedFormAgainstUpdate( system, info ), 299 );+}++// Dampings a hair either side of 1 over a long life: the velocity's (1 - d) k stays in the series+// branch, the angle's crosses into the quotient branch, and the size grows by d > 1.+TEST(particle_closed_form_follows_update_with_damping_near_one)+{+ ParticleSystemInfo system;+ ParticleInfo info;+ closedFormSetup( &system, &info, ParticleSystemInfo::ALPHA, 1200 );+ info.m_velDamping = 0.99995f;+ info.m_angularDamping = 0.9999f;+ info.m_sizeRateDamping = 1.00002f;+ info.m_colorScale = -0.0005f;+ closedFormAlphaKey( &system, &info, 0, 0.5f, 0 );+ closedFormColorKey( &system, 0, 0.9f, 0.6f, 0.3f, 0 );++ closedFormCheckRun( closedFormAgainstUpdate( system, info ), 1199 );+}++// A key earlier than the one before it is taken on the very next update, its rate divided by an+// unsigned difference that wrapped. A key with frame 0 ends the table.+TEST(particle_closed_form_takes_keys_out_of_order_one_update_each)+{+ ParticleSystemInfo system;+ ParticleInfo info;+ closedFormSetup( &system, &info, ParticleSystemInfo::ALPHA, 120 );+ closedFormAlphaKey( &system, &info, 0, 0.0f, 0 );+ closedFormAlphaKey( &system, &info, 1, 1.0f, 20 );+ closedFormAlphaKey( &system, &info, 2, 0.2f, 8 );+ closedFormAlphaKey( &system, &info, 3, 0.6f, 40 );+ closedFormColorKey( &system, 0, 0.0f, 0.0f, 0.0f, 0 );+ closedFormColorKey( &system, 1, 1.0f, 0.5f, 0.0f, 16 );+ closedFormColorKey( &system, 2, 0.0f, 1.0f, 0.5f, 4 );+ closedFormColorKey( &system, 3, 0.5f, 0.5f, 1.0f, 30 );++ ParticleGpuSystemEntry entry;+ particleGpuSystemEntryBuild( system, &entry );+ CHECK_EQ( entry.m_alphaSegmentCount, 3u );+ CHECK_EQ( entry.m_alphaSegment[ 0 ].m_end, 21u );+ CHECK_EQ( entry.m_alphaSegment[ 1 ].m_end, 22u );+ CHECK_EQ( entry.m_alphaSegment[ 2 ].m_end, 41u );+ CHECK( entry.m_alphaSegment[ 1 ].m_time > 4.0e9f );+ CHECK_EQ( entry.m_colorSegmentCount, 3u );+ CHECK_EQ( entry.m_colorSegment[ 0 ].m_end, 17u );+ CHECK_EQ( entry.m_colorSegment[ 1 ].m_end, 18u );+ CHECK_EQ( entry.m_colorSegment[ 2 ].m_end, 31u );++ closedFormCheckRun( closedFormAgainstUpdate( system, info ), 119 );++ closedFormAlphaKey( &system, &info, 2, 0.2f, 0 );+ particleGpuSystemEntryBuild( system, &entry );+ CHECK_EQ( entry.m_alphaSegmentCount, 1u );+ closedFormCheckRun( closedFormAgainstUpdate( system, info ), 119 );+}+//////////////////////////////////////////////////////////////////////////////// The ground blob under a particle system//@@ -18611,6 +19059,37 @@ TEST(particle_cap_in_force_is_the_switch_else_the_slider)TheWritableGlobalData = saved;}+/* The GPU particle ring is the detail preset's, a million slots on Ultra halving down to Low, and+ -gpuparticles beats it, 0 (off) included; Custom keeps whatever ring was in force. */+TEST(gpu_particle_ring_in_force_is_the_switch_else_the_preset)+{+ GlobalData *saved = TheWritableGlobalData;+ GlobalData *scratch = NEW GlobalData;+ TheWritableGlobalData = scratch;+ {+ GameLODManager lod;+ CHECK( lod.setStaticLODLevel( STATIC_GAME_LOD_ULTRA ) );+ CHECK_EQ( scratch->getEffectiveGpuParticleCapacity(), 1 << 20 );+ CHECK( lod.setStaticLODLevel( STATIC_GAME_LOD_HIGH ) );+ CHECK_EQ( scratch->getEffectiveGpuParticleCapacity(), 1 << 19 );+ CHECK( lod.setStaticLODLevel( STATIC_GAME_LOD_MEDIUM ) );+ CHECK_EQ( scratch->getEffectiveGpuParticleCapacity(), 1 << 18 );+ CHECK( lod.setStaticLODLevel( STATIC_GAME_LOD_LOW ) );+ CHECK_EQ( scratch->getEffectiveGpuParticleCapacity(), 1 << 17 );+ CHECK( lod.setStaticLODLevel( STATIC_GAME_LOD_CUSTOM ) );+ CHECK_EQ( scratch->getEffectiveGpuParticleCapacity(), 1 << 17 );++ scratch->m_gpuParticleCapacityOverride = 4096;+ CHECK( lod.setStaticLODLevel( STATIC_GAME_LOD_ULTRA ) );+ CHECK_EQ( scratch->m_gpuParticleCapacity, 1 << 20 );+ CHECK_EQ( scratch->getEffectiveGpuParticleCapacity(), 4096 );+ scratch->m_gpuParticleCapacityOverride = 0;+ CHECK_EQ( scratch->getEffectiveGpuParticleCapacity(), 0 );+ }+ delete scratch; // while it is the current one: ~GlobalData reads TheWritableGlobalData+ TheWritableGlobalData = saved;+}+/** The Reforged lighting style keeps what a sunlit surface receives and takes it out of the shade:on an ordinary afternoon (ambient half the sun, a fill on each side) the lit side of flat groundlands within a few percent of where it was, the shadow side loses a quarter, the sun turns warmer