Skip to content

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

feat(gameclient): flipbook fireballs and rising smoke for deaths

Olcay Seygancb83636f1eca
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 195d7d388..1238a3480 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1605,6 +1605,7 @@ The whole HUD is on the hardware. Four colours carry it, and they mean the same
- A bright cloud no longer shows what is behind it as a line drawing. Inside a nuke's white cloud, or a falling War Factory's fireball, every tree and wreck under it used to come out as a thin grey outline, and the picture's sharpening ringed each dark piece in white. Both stop where the frame is bright. A yellow or orange fireball still drew them, because the shading that darkens corners was laid over the finished picture and read the fire as dark: an Aurora's bomb on a War Factory showed its chimneys, its lattice and the trees beside it as dark outlines through the flames. Corners are now shaded before any fire or smoke is drawn, so a blast of any colour covers what is behind it.
- Smoke and fire no longer end on a straight line where they meet the ground or a building. A puff that sinks into a hillside or drifts against a wall thins out over its last few metres, softly enough that a nuke's haze and a Scud's grey smoke no longer come out as stacked, stair-stepped terraces, and a toxin cloud lying low over the ground keeps its body instead of breaking into hard-edged green islands. A China mine field blinks where you can see it again: its lights hang just off the ground, and the fade had eaten all but a thirtieth of their bright middle. No effect fades over more than its own size now, so a small spark close to the ground keeps its light. This is the default renderer; Classic and the old renderer keep the hard edge they had in 2003.
- Fire burns instead of fading. Every flame and fireball in the game, 182 kinds from a burning soldier to a nuke's mushroom, starts white-hot and cools through yellow, orange and red to a sooty dark as it dies, eats away from its thin edges in rather than going see-through all at once, and licks and flickers, so a fire that used to be a still picture getting dimmer now moves. Green toxin and anthrax fires keep their colour. Default renderer only; Classic and the old renderer draw fire as they did.
+- A tank shell landing, a tank dying and a mid-sized building going down now explode as a rolling fireball that swells and cools from yellow through deep orange to soot instead of a still picture of one, with a column of turning smoke climbing behind it. A building no longer goes down behind a white flare. Both are animated paintings, so they move on every renderer.
- Gunfire shows at the zoom you play at. A rifle's tracer was a third of a unit wide, about one pixel from the default camera, and a bullet hit nothing you could see. Tracers from rifles, Gattlings, Humvees, Technicals and Quad Cannons are now twice as wide and half again as long, the muzzle flash is half as big again, and every hit kicks up sparks and a puff of dirt where it lands. A tank shell burns a short hot streak behind it all the way to the target, where it used to be a grey sliver you could not pick out between the flash and the blast. A Crusader's, Battlemaster's, Scorpion's, Paladin's or Overlord's shot used to be a soft white glow drifting out in front of the gun, wider than the tank; it is now a short orange blast at the barrel tip, with a bigger flame and smoke puff behind it. A shell landing throws dirt and sparks around its blast. The colours are the ones the game always used, and no weapon does anything different.
- Blasts throw fragments that smoke. The bigger explosions fling hot sparks into the air, each drawing a thin dark line of smoke that climbs, fans around the blast and curves down. A Stinger, a rocket pod, a tank shell or a rocket used to throw them too, and a fight filled with them; they now show on a bomb, a heavy shell, a Scud or a building, five that climb several times a tank's length, and on a nuke, a MOAB, a Daisy Cutter or a large building, eight that arc over its own fireball and hang for a couple of seconds. A vehicle that blows up throws burning pieces that drag near-black smoke and bounce where they land, and the turret, wheels and plates it throws off trail smoke and flame too, then smoulder a moment on the ground. The fragments and their smoke are the first effects the particle limit and a lower detail setting drop, so a bigger fight keeps its explosions and loses some lines. What a weapon does is unchanged. Rather have the explosions as they always were? Explosion Debris Trails in the launcher's Options turns all of it off, for you alone: the other players in your match keep whatever they picked, and nobody's game falls out of step over it.
- A China mine field tells you what kind it is. EA's field had no model at all, only a soft white glint swelling and fading on each of its eight spots, so your own minefield looked like a patch of fireflies. Each mine is now marked by a small arming light that snaps on for a quarter of a second every second and a half, red on standard and cluster mines and blue on EMP mines, with a white-hot point and a dark rim that keep it readable on grass, sand or snow. No mine body is drawn on the ground, only the light. The enemy still sees nothing until he detects the field. A mine going off under a tank now throws a column of dark earth twice the tank's height, scatters clods round it and leaves a low black smoke and a scorch, with a short jolt of the screen; it used to puff a pale spray of specks that looked like dust kicked up. An EMP mine throws no earth, so you can tell which kind went off: it lights a blue ring across the ground, a crackle of blue sparks and a short blue flash at the spot; EA's flash grew until it washed the whole screen white for a fifth of a second. What a mine does is unchanged.
diff --git a/GeneralsMD/Code/BuildFingerprint.manifest b/GeneralsMD/Code/BuildFingerprint.manifest
index 49548d91e..751bb63ab 100644
--- a/GeneralsMD/Code/BuildFingerprint.manifest
+++ b/GeneralsMD/Code/BuildFingerprint.manifest
@@ -9,6 +9,8 @@ Data/Art/Textures/ReforgedBarChinaRight.tga
Data/Art/Textures/ReforgedBarGLACenter.tga
Data/Art/Textures/ReforgedBarGLALeft.tga
Data/Art/Textures/ReforgedBarGLARight.tga
+Data/Art/Textures/ReforgedExplosionFire.dds
+Data/Art/Textures/ReforgedExplosionSmoke.dds
Data/Art/Textures/ReforgedForceAttack.tga
Data/Art/Textures/ReforgedHudAmericaCommandBar.dds
Data/Art/Textures/ReforgedHudAmericaPowers.dds
@@ -45,6 +47,7 @@ Data/Cinema/debristrails3_nuke.txt
Data/Cinema/debristrails3_side.txt
Data/Cinema/demo.txt
Data/Cinema/drawlooks.txt
+Data/Cinema/explfx.txt
Data/Cinema/explreel.txt
Data/Cinema/filterblur.txt
Data/Cinema/filterbw.txt
@@ -223,6 +226,7 @@ Data/Scenarios/empfriendly.txt
Data/Scenarios/exitmovebuild.txt
Data/Scenarios/exitorders.txt
Data/Scenarios/expansionbunker.txt
+Data/Scenarios/explfx.txt
Data/Scenarios/explreel.txt
Data/Scenarios/firelook.txt
Data/Scenarios/fogleak.txt
@@ -3883,6 +3887,7 @@ Tools/china_beacon.py
Tools/control_client.py
Tools/d3d9posix_check.py
Tools/diplomacy_layout.py
+Tools/explosion_flipbook.py
Tools/ffmpeg-build-posix.sh
Tools/ffmpeg-build.bat
Tools/ffmpeg-build.sh
diff --git a/GeneralsMD/Code/Data/Art/Textures/ReforgedExplosionFire.dds b/GeneralsMD/Code/Data/Art/Textures/ReforgedExplosionFire.dds
new file mode 100644
index 000000000..99977b922
Binary files /dev/null and b/GeneralsMD/Code/Data/Art/Textures/ReforgedExplosionFire.dds differ
diff --git a/GeneralsMD/Code/Data/Art/Textures/ReforgedExplosionSmoke.dds b/GeneralsMD/Code/Data/Art/Textures/ReforgedExplosionSmoke.dds
new file mode 100644
index 000000000..4b2a9cdc7
Binary files /dev/null and b/GeneralsMD/Code/Data/Art/Textures/ReforgedExplosionSmoke.dds differ
diff --git a/GeneralsMD/Code/Data/Cinema/explfx.txt b/GeneralsMD/Code/Data/Cinema/explfx.txt
new file mode 100644
index 000000000..114af4db0
--- /dev/null
+++ b/GeneralsMD/Code/Data/Cinema/explfx.txt
@@ -0,0 +1,18 @@
+# Scenarios/explfx.txt filmed close, for the flipbook explosions (-video 120 1440). Three takes on
+# Twilight Flame round start 0 (537,3188): Battlemasters and Crusaders trading shells with the first
+# Crusaders dying, the barracks falling under Overlord fire, and the second Crusader wave meeting the
+# Battlemasters and the Overlords.
+
+2.0 cut 800 3090 0.55 60 -6
+2.1 zoom 0.45 6.5
+2.1 orbit 20 6.5
+
+8.0 cut 597 3470 0.75 90 -2
+8.1 zoom 0.65 6.8
+8.1 orbit -15 6.8
+
+15.0 cut 790 3140 0.6 80 -6
+15.1 zoom 0.48 8.5
+15.1 orbit 25 8.5
+
+24.0 end
diff --git a/GeneralsMD/Code/Data/INI/FXListReforged.ini b/GeneralsMD/Code/Data/INI/FXListReforged.ini
index d9977f0ae..1a8e8b8a6 100644
--- a/GeneralsMD/Code/Data/INI/FXListReforged.ini
+++ b/GeneralsMD/Code/Data/INI/FXListReforged.ini
@@ -83,12 +83,19 @@ FXList WeaponFX_GenericTankShellDetonation
Sound
Name = ExplosionRocketBuggyMissile
End
+ ; the flipbook fireball, its hot core and its smoke column in place of EA's BuggyMissileExplosion
+ ; and its smoke
ParticleSystem
- Name = BuggyMissileExplosion
- UseCallersRadius = Yes ; Override the radius with the damage radius of the weapon.
+ Name = ReforgedShellFireball
+ Offset = X:0.0 Y:0.0 Z:4.0
End
ParticleSystem
- Name = BuggyMissileExplosionSmoke
+ Name = ReforgedShellFireCore
+ Offset = X:0.0 Y:0.0 Z:4.0
+ End
+ ParticleSystem
+ Name = ReforgedShellSmoke
+ Offset = X:0.0 Y:0.0 Z:3.0
End
; a shell landing throws EA's dirt clods and sparks, which only a tank being struck used to show
ParticleSystem
@@ -222,14 +229,26 @@ FXList FX_GenericTankDeathExplosion
ParticleSystem
Name = ReforgedVehicleShrapnel
End
+ ; the flipbook fireball, two smaller ones after it and a smoke column, in place of EA's
+ ; MammothTankExplosionSmoke and MammothTankSubExplosionSmoke
ParticleSystem
- Name = MammothTankExplosionSmoke
+ Name = ReforgedTankFireball
+ Offset = X:0.0 Y:0.0 Z:8.0
End
ParticleSystem
- Name = MammothTankSubExplosionSmoke
- Radius = 15 30 UNIFORM
- Height = 0 20 UNIFORM
- InitialDelay = 167 667 UNIFORM
+ Name = ReforgedTankFireCore
+ Offset = X:0.0 Y:0.0 Z:8.0
+ End
+ ParticleSystem
+ Name = ReforgedShellFireball
+ Count = 2
+ Radius = 8 16 UNIFORM
+ Height = 4 16 UNIFORM
+ InitialDelay = 167 500 UNIFORM
+ End
+ ParticleSystem
+ Name = ReforgedTankSmoke
+ Offset = X:0.0 Y:0.0 Z:6.0
End
ParticleSystem
Name = MammothTankExplosionDebris
@@ -3142,14 +3161,30 @@ FXList FX_StructureMediumDeath
ParticleSystem
Name = StructureTransitionMediumSmoke
End
+ ; the flipbook fireball, two tank-sized ones after it and a smoke column, in place of EA's
+ ; StructureTransitionMediumExplosion; EA's StructureTransitionMediumFlare is left out, its white
+ ; flare and light streaks washed the fireball away
ParticleSystem
- Name = StructureTransitionMediumExplosion
+ Name = ReforgedStructureFireball
+ Offset = X:0.0 Y:0.0 Z:15.0
End
ParticleSystem
- Name = StructureTransitionMediumShockwave
+ Name = ReforgedStructureFireCore
+ Offset = X:0.0 Y:0.0 Z:15.0
End
ParticleSystem
- Name = StructureTransitionMediumFlare
+ Name = ReforgedTankFireball
+ Count = 2
+ Radius = 15 30 UNIFORM
+ Height = 10 30 UNIFORM
+ InitialDelay = 250 750 UNIFORM
+ End
+ ParticleSystem
+ Name = ReforgedStructureSmoke
+ Offset = X:0.0 Y:0.0 Z:10.0
+ End
+ ParticleSystem
+ Name = StructureTransitionMediumShockwave
End
Sound
Name = BuildingDie
diff --git a/GeneralsMD/Code/Data/INI/ParticleSystemReforged.ini b/GeneralsMD/Code/Data/INI/ParticleSystemReforged.ini
index 6e042dd9f..0b43c9c76 100644
--- a/GeneralsMD/Code/Data/INI/ParticleSystemReforged.ini
+++ b/GeneralsMD/Code/Data/INI/ParticleSystemReforged.ini
@@ -6474,6 +6474,538 @@ ParticleSystem UpgradeCarpetBombExplosion
FireLook = Yes
End
+; Flipbook explosions, three sizes: a tank shell landing, a tank dying, a medium building dying
+; (FXListReforged.ini). Each is a fireball, a small hot core and a smoke column. The fireball plays
+; the 64 frames of ReforgedExplosionFire once over its life, growing, rolling and cooling to soot, so
+; the card itself fades and the colour stays white. It is alpha blended and Emissive: drawn
+; additively the bodies stacked into cream and white, and as plain alpha the smoke's light and the
+; sun's smoke map would shade it. The core is EA's EXexplo03 card, small, brief and additive, the
+; only part that blooms. The column is puffs of ReforgedExplosionSmoke, each turning over at its own
+; pace from a random frame, two at a time, climbing and swelling. Both pictures come out of
+; Tools/explosion_flipbook.py.
+
+ParticleSystem ReforgedShellFireball
+ Priority = WEAPON_EXPLOSION
+ IsOneShot = No
+ Shader = ALPHA
+ Type = PARTICLE
+ ParticleName = ReforgedExplosionFire.tga
+ Emissive = Yes
+ FlipbookGrid = 8
+ AngleZ = 0.00 6.28
+ AngularRateZ = -0.01 0.01
+ AngularDamping = 0.98 0.99
+ VelocityDamping = 0.88 0.92
+ Gravity = 0.00
+ Lifetime = 40.00 50.00
+ SystemLifetime = 2
+ Size = 11.00 14.00
+ StartSizeRate = 0.00 0.00
+ SizeRate = 0.08 0.12
+ SizeRateDamping = 0.97 0.98
+ Alpha1 = 1.00 1.00 0
+ Alpha2 = 0.00 0.00 0
+ Alpha3 = 0.00 0.00 0
+ Alpha4 = 0.00 0.00 0
+ Alpha5 = 0.00 0.00 0
+ Alpha6 = 0.00 0.00 0
+ Alpha7 = 0.00 0.00 0
+ Alpha8 = 0.00 0.00 0
+ Color1 = R:255 G:255 B:255 0
+ Color2 = R:0 G:0 B:0 0
+ Color3 = R:0 G:0 B:0 0
+ Color4 = R:0 G:0 B:0 0
+ Color5 = R:0 G:0 B:0 0
+ Color6 = R:0 G:0 B:0 0
+ Color7 = R:0 G:0 B:0 0
+ Color8 = R:0 G:0 B:0 0
+ ColorScale = 0.00 0.00
+ BurstDelay = 99999.00 99999.00
+ BurstCount = 2.00 3.00
+ InitialDelay = 0.00 0.00
+ DriftVelocity = X:0.00 Y:0.00 Z:0.15
+ VelocityType = SPHERICAL
+ VelSpherical = 0.20 0.50
+ VolumeType = SPHERE
+ VolSphereRadius = 2.00
+ IsHollow = No
+ IsGroundAligned = No
+ IsEmitAboveGroundOnly = No
+ IsParticleUpTowardsEmitter = No
+ WindMotion = Unused
+ WindAngleChangeMin = 0.149924
+ WindAngleChangeMax = 0.449946
+ WindPingPongStartAngleMin = 0.000000
+ WindPingPongStartAngleMax = 0.785398
+ WindPingPongEndAngleMin = 5.497787
+ WindPingPongEndAngleMax = 6.283185
+End
+
+ParticleSystem ReforgedShellFireCore
+ Priority = WEAPON_EXPLOSION
+ IsOneShot = No
+ Shader = ADDITIVE
+ Type = PARTICLE
+ ParticleName = EXexplo03.tga
+ AngleZ = 0.00 6.28
+ AngularRateZ = 0.00 0.00
+ AngularDamping = 1.00 1.00
+ VelocityDamping = 1.00 1.00
+ Gravity = 0.00
+ Lifetime = 10.00 12.00
+ SystemLifetime = 2
+ Size = 5.00 6.00
+ StartSizeRate = 0.00 0.00
+ SizeRate = 0.20 0.25
+ SizeRateDamping = 0.95 0.95
+ Alpha1 = 1.00 1.00 0
+ Alpha2 = 0.00 0.00 0
+ Alpha3 = 0.00 0.00 0
+ Alpha4 = 0.00 0.00 0
+ Alpha5 = 0.00 0.00 0
+ Alpha6 = 0.00 0.00 0
+ Alpha7 = 0.00 0.00 0
+ Alpha8 = 0.00 0.00 0
+ Color1 = R:255 G:190 B:100 0
+ Color2 = R:190 G:80 B:15 5
+ Color3 = R:0 G:0 B:0 12
+ Color4 = R:0 G:0 B:0 0
+ Color5 = R:0 G:0 B:0 0
+ Color6 = R:0 G:0 B:0 0
+ Color7 = R:0 G:0 B:0 0
+ Color8 = R:0 G:0 B:0 0
+ ColorScale = 0.00 0.00
+ BurstDelay = 99999.00 99999.00
+ BurstCount = 1.00 1.00
+ InitialDelay = 0.00 0.00
+ DriftVelocity = X:0.00 Y:0.00 Z:0.00
+ VelocityType = ORTHO
+ VelOrthoX = 0.00 0.00
+ VelOrthoY = 0.00 0.00
+ VelOrthoZ = 0.00 0.00
+ VolumeType = POINT
+ IsHollow = No
+ IsGroundAligned = No
+ IsEmitAboveGroundOnly = No
+ IsParticleUpTowardsEmitter = No
+ WindMotion = Unused
+ WindAngleChangeMin = 0.149924
+ WindAngleChangeMax = 0.449946
+ WindPingPongStartAngleMin = 0.000000
+ WindPingPongStartAngleMax = 0.785398
+ WindPingPongEndAngleMin = 5.497787
+ WindPingPongEndAngleMax = 6.283185
+End
+
+ParticleSystem ReforgedShellSmoke
+ Priority = WEAPON_EXPLOSION
+ IsOneShot = No
+ Shader = ALPHA
+ Type = PARTICLE
+ ParticleName = ReforgedExplosionSmoke.tga
+ FlipbookGrid = 8
+ FlipbookRate = 10
+ FlipbookRandomStart = Yes
+ AngleZ = 0.00 6.28
+ AngularRateZ = -0.01 0.01
+ AngularDamping = 0.99 0.99
+ VelocityDamping = 0.95 0.96
+ Gravity = 0.00
+ Lifetime = 90.00 110.00
+ SystemLifetime = 20
+ Size = 8.00 11.00
+ StartSizeRate = 0.00 0.00
+ SizeRate = 0.35 0.45
+ SizeRateDamping = 0.985 0.99
+ Alpha1 = 0.00 0.00 0
+ Alpha2 = 0.75 0.85 8
+ Alpha3 = 0.50 0.60 40
+ Alpha4 = 0.00 0.00 90
+ Alpha5 = 0.00 0.00 0
+ Alpha6 = 0.00 0.00 0
+ Alpha7 = 0.00 0.00 0
+ Alpha8 = 0.00 0.00 0
+ Color1 = R:100 G:92 B:86 0
+ Color2 = R:150 G:142 B:134 80
+ Color3 = R:0 G:0 B:0 0
+ Color4 = R:0 G:0 B:0 0
+ Color5 = R:0 G:0 B:0 0
+ Color6 = R:0 G:0 B:0 0
+ Color7 = R:0 G:0 B:0 0
+ Color8 = R:0 G:0 B:0 0
+ ColorScale = 0.00 0.00
+ BurstDelay = 2.00 3.00
+ BurstCount = 2.00 2.00
+ InitialDelay = 3.00 3.00
+ DriftVelocity = X:0.04 Y:0.04 Z:0.45
+ VelocityType = ORTHO
+ VelOrthoX = -0.10 0.10
+ VelOrthoY = -0.10 0.10
+ VelOrthoZ = 0.90 1.40
+ VolumeType = CYLINDER
+ VolCylinderRadius = 2.00
+ VolCylinderLength = 0.00
+ IsHollow = No
+ IsGroundAligned = No
+ IsEmitAboveGroundOnly = No
+ IsParticleUpTowardsEmitter = No
+ WindMotion = Unused
+ WindAngleChangeMin = 0.149924
+ WindAngleChangeMax = 0.449946
+ WindPingPongStartAngleMin = 0.000000
+ WindPingPongStartAngleMax = 0.785398
+ WindPingPongEndAngleMin = 5.497787
+ WindPingPongEndAngleMax = 6.283185
+End
+
+ParticleSystem ReforgedTankFireball
+ Priority = DEATH_EXPLOSION
+ IsOneShot = No
+ Shader = ALPHA
+ Type = PARTICLE
+ ParticleName = ReforgedExplosionFire.tga
+ Emissive = Yes
+ FlipbookGrid = 8
+ AngleZ = 0.00 6.28
+ AngularRateZ = -0.01 0.01
+ AngularDamping = 0.98 0.99
+ VelocityDamping = 0.88 0.92
+ Gravity = 0.00
+ Lifetime = 50.00 60.00
+ SystemLifetime = 2
+ Size = 40.00 50.00
+ StartSizeRate = 0.00 0.00
+ SizeRate = 0.30 0.40
+ SizeRateDamping = 0.97 0.98
+ Alpha1 = 1.00 1.00 0
+ Alpha2 = 0.00 0.00 0
+ Alpha3 = 0.00 0.00 0
+ Alpha4 = 0.00 0.00 0
+ Alpha5 = 0.00 0.00 0
+ Alpha6 = 0.00 0.00 0
+ Alpha7 = 0.00 0.00 0
+ Alpha8 = 0.00 0.00 0
+ Color1 = R:255 G:255 B:255 0
+ Color2 = R:0 G:0 B:0 0
+ Color3 = R:0 G:0 B:0 0
+ Color4 = R:0 G:0 B:0 0
+ Color5 = R:0 G:0 B:0 0
+ Color6 = R:0 G:0 B:0 0
+ Color7 = R:0 G:0 B:0 0
+ Color8 = R:0 G:0 B:0 0
+ ColorScale = 0.00 0.00
+ BurstDelay = 99999.00 99999.00
+ BurstCount = 4.00 5.00
+ InitialDelay = 0.00 0.00
+ DriftVelocity = X:0.00 Y:0.00 Z:0.20
+ VelocityType = SPHERICAL
+ VelSpherical = 0.50 1.20
+ VolumeType = SPHERE
+ VolSphereRadius = 6.00
+ IsHollow = No
+ IsGroundAligned = No
+ IsEmitAboveGroundOnly = No
+ IsParticleUpTowardsEmitter = No
+ WindMotion = Unused
+ WindAngleChangeMin = 0.149924
+ WindAngleChangeMax = 0.449946
+ WindPingPongStartAngleMin = 0.000000
+ WindPingPongStartAngleMax = 0.785398
+ WindPingPongEndAngleMin = 5.497787
+ WindPingPongEndAngleMax = 6.283185
+End
+
+ParticleSystem ReforgedTankFireCore
+ Priority = DEATH_EXPLOSION
+ IsOneShot = No
+ Shader = ADDITIVE
+ Type = PARTICLE
+ ParticleName = EXexplo03.tga
+ AngleZ = 0.00 6.28
+ AngularRateZ = 0.00 0.00
+ AngularDamping = 1.00 1.00
+ VelocityDamping = 1.00 1.00
+ Gravity = 0.00
+ Lifetime = 14.00 16.00
+ SystemLifetime = 2
+ Size = 12.00 15.00
+ StartSizeRate = 0.00 0.00
+ SizeRate = 0.40 0.50
+ SizeRateDamping = 0.95 0.95
+ Alpha1 = 1.00 1.00 0
+ Alpha2 = 0.00 0.00 0
+ Alpha3 = 0.00 0.00 0
+ Alpha4 = 0.00 0.00 0
+ Alpha5 = 0.00 0.00 0
+ Alpha6 = 0.00 0.00 0
+ Alpha7 = 0.00 0.00 0
+ Alpha8 = 0.00 0.00 0
+ Color1 = R:255 G:190 B:100 0
+ Color2 = R:190 G:80 B:15 6
+ Color3 = R:0 G:0 B:0 16
+ Color4 = R:0 G:0 B:0 0
+ Color5 = R:0 G:0 B:0 0
+ Color6 = R:0 G:0 B:0 0
+ Color7 = R:0 G:0 B:0 0
+ Color8 = R:0 G:0 B:0 0
+ ColorScale = 0.00 0.00
+ BurstDelay = 99999.00 99999.00
+ BurstCount = 1.00 1.00
+ InitialDelay = 0.00 0.00
+ DriftVelocity = X:0.00 Y:0.00 Z:0.00
+ VelocityType = ORTHO
+ VelOrthoX = 0.00 0.00
+ VelOrthoY = 0.00 0.00
+ VelOrthoZ = 0.00 0.00
+ VolumeType = POINT
+ IsHollow = No
+ IsGroundAligned = No
+ IsEmitAboveGroundOnly = No
+ IsParticleUpTowardsEmitter = No
+ WindMotion = Unused
+ WindAngleChangeMin = 0.149924
+ WindAngleChangeMax = 0.449946
+ WindPingPongStartAngleMin = 0.000000
+ WindPingPongStartAngleMax = 0.785398
+ WindPingPongEndAngleMin = 5.497787
+ WindPingPongEndAngleMax = 6.283185
+End
+
+ParticleSystem ReforgedTankSmoke
+ Priority = DEATH_EXPLOSION
+ IsOneShot = No
+ Shader = ALPHA
+ Type = PARTICLE
+ ParticleName = ReforgedExplosionSmoke.tga
+ FlipbookGrid = 8
+ FlipbookRate = 10
+ FlipbookRandomStart = Yes
+ AngleZ = 0.00 6.28
+ AngularRateZ = -0.01 0.01
+ AngularDamping = 0.99 0.99
+ VelocityDamping = 0.94 0.96
+ Gravity = 0.00
+ Lifetime = 150.00 180.00
+ SystemLifetime = 45
+ Size = 14.00 18.00
+ StartSizeRate = 0.00 0.00
+ SizeRate = 0.45 0.60
+ SizeRateDamping = 0.985 0.99
+ Alpha1 = 0.00 0.00 0
+ Alpha2 = 0.80 0.90 10
+ Alpha3 = 0.55 0.65 70
+ Alpha4 = 0.00 0.00 150
+ Alpha5 = 0.00 0.00 0
+ Alpha6 = 0.00 0.00 0
+ Alpha7 = 0.00 0.00 0
+ Alpha8 = 0.00 0.00 0
+ Color1 = R:90 G:82 B:76 0
+ Color2 = R:145 G:138 B:130 120
+ Color3 = R:0 G:0 B:0 0
+ Color4 = R:0 G:0 B:0 0
+ Color5 = R:0 G:0 B:0 0
+ Color6 = R:0 G:0 B:0 0
+ Color7 = R:0 G:0 B:0 0
+ Color8 = R:0 G:0 B:0 0
+ ColorScale = 0.00 0.00
+ BurstDelay = 2.00 3.00
+ BurstCount = 2.00 2.00
+ InitialDelay = 5.00 5.00
+ DriftVelocity = X:0.05 Y:0.05 Z:0.55
+ VelocityType = ORTHO
+ VelOrthoX = -0.15 0.15
+ VelOrthoY = -0.15 0.15
+ VelOrthoZ = 1.10 1.60
+ VolumeType = CYLINDER
+ VolCylinderRadius = 4.00
+ VolCylinderLength = 0.00
+ IsHollow = No
+ IsGroundAligned = No
+ IsEmitAboveGroundOnly = No
+ IsParticleUpTowardsEmitter = No
+ WindMotion = Unused
+ WindAngleChangeMin = 0.149924
+ WindAngleChangeMax = 0.449946
+ WindPingPongStartAngleMin = 0.000000
+ WindPingPongStartAngleMax = 0.785398
+ WindPingPongEndAngleMin = 5.497787
+ WindPingPongEndAngleMax = 6.283185
+End
+
+ParticleSystem ReforgedStructureFireball
+ Priority = DEATH_EXPLOSION
+ IsOneShot = No
+ Shader = ALPHA
+ Type = PARTICLE
+ ParticleName = ReforgedExplosionFire.tga
+ Emissive = Yes
+ FlipbookGrid = 8
+ AngleZ = 0.00 6.28
+ AngularRateZ = -0.01 0.01
+ AngularDamping = 0.98 0.99
+ VelocityDamping = 0.88 0.92
+ Gravity = 0.00
+ Lifetime = 60.00 75.00
+ SystemLifetime = 2
+ Size = 80.00 100.00
+ StartSizeRate = 0.00 0.00
+ SizeRate = 0.40 0.60
+ SizeRateDamping = 0.97 0.98
+ Alpha1 = 1.00 1.00 0
+ Alpha2 = 0.00 0.00 0
+ Alpha3 = 0.00 0.00 0
+ Alpha4 = 0.00 0.00 0
+ Alpha5 = 0.00 0.00 0
+ Alpha6 = 0.00 0.00 0
+ Alpha7 = 0.00 0.00 0
+ Alpha8 = 0.00 0.00 0
+ Color1 = R:255 G:255 B:255 0
+ Color2 = R:0 G:0 B:0 0
+ Color3 = R:0 G:0 B:0 0
+ Color4 = R:0 G:0 B:0 0
+ Color5 = R:0 G:0 B:0 0
+ Color6 = R:0 G:0 B:0 0
+ Color7 = R:0 G:0 B:0 0
+ Color8 = R:0 G:0 B:0 0
+ ColorScale = 0.00 0.00
+ BurstDelay = 99999.00 99999.00
+ BurstCount = 6.00 8.00
+ InitialDelay = 0.00 0.00
+ DriftVelocity = X:0.00 Y:0.00 Z:0.30
+ VelocityType = SPHERICAL
+ VelSpherical = 0.80 1.60
+ VolumeType = SPHERE
+ VolSphereRadius = 14.00
+ IsHollow = No
+ IsGroundAligned = No
+ IsEmitAboveGroundOnly = No
+ IsParticleUpTowardsEmitter = No
+ WindMotion = Unused
+ WindAngleChangeMin = 0.149924
+ WindAngleChangeMax = 0.449946
+ WindPingPongStartAngleMin = 0.000000
+ WindPingPongStartAngleMax = 0.785398
+ WindPingPongEndAngleMin = 5.497787
+ WindPingPongEndAngleMax = 6.283185
+End
+
+ParticleSystem ReforgedStructureFireCore
+ Priority = DEATH_EXPLOSION
+ IsOneShot = No
+ Shader = ADDITIVE
+ Type = PARTICLE
+ ParticleName = EXexplo03.tga
+ AngleZ = 0.00 6.28
+ AngularRateZ = 0.00 0.00
+ AngularDamping = 1.00 1.00
+ VelocityDamping = 1.00 1.00
+ Gravity = 0.00
+ Lifetime = 18.00 20.00
+ SystemLifetime = 2
+ Size = 25.00 30.00
+ StartSizeRate = 0.00 0.00
+ SizeRate = 0.70 0.90
+ SizeRateDamping = 0.95 0.95
+ Alpha1 = 1.00 1.00 0
+ Alpha2 = 0.00 0.00 0
+ Alpha3 = 0.00 0.00 0
+ Alpha4 = 0.00 0.00 0
+ Alpha5 = 0.00 0.00 0
+ Alpha6 = 0.00 0.00 0
+ Alpha7 = 0.00 0.00 0
+ Alpha8 = 0.00 0.00 0
+ Color1 = R:255 G:190 B:100 0
+ Color2 = R:190 G:80 B:15 7
+ Color3 = R:0 G:0 B:0 20
+ Color4 = R:0 G:0 B:0 0
+ Color5 = R:0 G:0 B:0 0
+ Color6 = R:0 G:0 B:0 0
+ Color7 = R:0 G:0 B:0 0
+ Color8 = R:0 G:0 B:0 0
+ ColorScale = 0.00 0.00
+ BurstDelay = 99999.00 99999.00
+ BurstCount = 1.00 1.00
+ InitialDelay = 0.00 0.00
+ DriftVelocity = X:0.00 Y:0.00 Z:0.00
+ VelocityType = ORTHO
+ VelOrthoX = 0.00 0.00
+ VelOrthoY = 0.00 0.00
+ VelOrthoZ = 0.00 0.00
+ VolumeType = POINT
+ IsHollow = No
+ IsGroundAligned = No
+ IsEmitAboveGroundOnly = No
+ IsParticleUpTowardsEmitter = No
+ WindMotion = Unused
+ WindAngleChangeMin = 0.149924
+ WindAngleChangeMax = 0.449946
+ WindPingPongStartAngleMin = 0.000000
+ WindPingPongStartAngleMax = 0.785398
+ WindPingPongEndAngleMin = 5.497787
+ WindPingPongEndAngleMax = 6.283185
+End
+
+ParticleSystem ReforgedStructureSmoke
+ Priority = DEATH_EXPLOSION
+ IsOneShot = No
+ Shader = ALPHA
+ Type = PARTICLE
+ ParticleName = ReforgedExplosionSmoke.tga
+ FlipbookGrid = 8
+ FlipbookRate = 8
+ FlipbookRandomStart = Yes
+ AngleZ = 0.00 6.28
+ AngularRateZ = -0.01 0.01
+ AngularDamping = 0.99 0.99
+ VelocityDamping = 0.94 0.96
+ Gravity = 0.00
+ Lifetime = 220.00 260.00
+ SystemLifetime = 75
+ Size = 30.00 40.00
+ StartSizeRate = 0.00 0.00
+ SizeRate = 0.60 0.80
+ SizeRateDamping = 0.985 0.99
+ Alpha1 = 0.00 0.00 0
+ Alpha2 = 0.80 0.90 12
+ Alpha3 = 0.55 0.65 100
+ Alpha4 = 0.00 0.00 220
+ Alpha5 = 0.00 0.00 0
+ Alpha6 = 0.00 0.00 0
+ Alpha7 = 0.00 0.00 0
+ Alpha8 = 0.00 0.00 0
+ Color1 = R:90 G:82 B:76 0
+ Color2 = R:150 G:142 B:134 160
+ Color3 = R:0 G:0 B:0 0
+ Color4 = R:0 G:0 B:0 0
+ Color5 = R:0 G:0 B:0 0
+ Color6 = R:0 G:0 B:0 0
+ Color7 = R:0 G:0 B:0 0
+ Color8 = R:0 G:0 B:0 0
+ ColorScale = 0.00 0.00
+ BurstDelay = 2.00 3.00
+ BurstCount = 2.00 3.00
+ InitialDelay = 6.00 6.00
+ DriftVelocity = X:0.06 Y:0.06 Z:0.65
+ VelocityType = ORTHO
+ VelOrthoX = -0.25 0.25
+ VelOrthoY = -0.25 0.25
+ VelOrthoZ = 1.40 2.00
+ VolumeType = CYLINDER
+ VolCylinderRadius = 12.00
+ VolCylinderLength = 0.00
+ IsHollow = No
+ IsGroundAligned = No
+ IsEmitAboveGroundOnly = No
+ IsParticleUpTowardsEmitter = No
+ WindMotion = Unused
+ WindAngleChangeMin = 0.149924
+ WindAngleChangeMax = 0.449946
+ WindPingPongStartAngleMin = 0.000000
+ WindPingPongStartAngleMax = 0.785398
+ WindPingPongEndAngleMin = 5.497787
+ WindPingPongEndAngleMax = 6.283185
+End
+
; The wreck pieces a vehicle's death throws as models (turrets, wheels, doors, hull plates; the
; ParticleSystem line of their CreateDebris in ObjectCreationListReforged.ini) trail the same dark
; ribbon as the shrapnel above, with a small flame on each of its points that is gone in a quarter
diff --git a/GeneralsMD/Code/Data/Scenarios/explfx.txt b/GeneralsMD/Code/Data/Scenarios/explfx.txt
new file mode 100644
index 000000000..7a9d5c18e
--- /dev/null
+++ b/GeneralsMD/Code/Data/Scenarios/explfx.txt
@@ -0,0 +1,74 @@
+# Footage of the flipbook explosions (ReforgedExplosionFire/Smoke in ParticleSystemReforged.ini) on
+# Twilight Flame, close: tank shells bursting (WeaponFX_GenericTankShellDetonation), tanks dying
+# (FX_GenericTankDeathExplosion) and medium buildings falling (FX_StructureMediumDeath). An American
+# base at start 0 (537,3188) on the firelook spots; Crusaders and Paladins meet Battlemasters and
+# Overlords east of it, while a second Overlord group shells the barracks and the War Factory.
+# Seat 0 America, seat 1 China, everyone hostile, nothing thinks but this file.
+# Filmed with Cinema/explfx.txt:
+#
+# generals.exe -win -xres 1280 -yres 720 -msaa 0 -fps 120 -noFPSLimit -particlecap 2500
+# -quickstart -noshellmap -observer -multiInstance -map "Maps\Twilight Flame\Twilight Flame.map"
+# -autoskirmish 2 -takeover -side 0 FactionAmerica -side 1 FactionChina -seed 7
+# -scenario explfx -cinema explfx -video <from> <to> explfx -maxframes <to + 20>
+
+# the base round the command centre
+10 spawn 0 AmericaPowerPlant 1 start0:-240:160
+10 spawn 0 AmericaWarFactory 1 start0:40:-340
+10 spawn 0 AmericaBarracks 1 start0:60:320
+10 spawn 0 AmericaSupplyCenter 1 start0:-260:440
+
+# the tank fight east of the base: shells both ways, Crusaders and Paladins dying
+20 spawn 0 AmericaTankCrusader 6 start0:160:-120 45
+20 spawn 0 AmericaTankPaladin 2 start0:100:-40 45
+20 spawn 0 AmericaInfantryRanger 8 start0:180:60 20
+20 spawn 1 ChinaTankBattleMaster 12 start0:400:-100 40
+40 attackmove 0 AmericaTankCrusader start0:400:-100
+40 attackmove 0 AmericaTankPaladin start0:400:-100
+40 attackmove 0 AmericaInfantryRanger start0:400:0
+40 attack 1 ChinaTankBattleMaster 0 AmericaTankCrusader
+
+# the siege group: Overlords on the barracks, then the War Factory
+20 spawn 1 ChinaTankOverlord 5 start0:360:440 60
+40 attack 1 ChinaTankOverlord 0 AmericaBarracks
+
+300 attackmove 1 ChinaTankOverlord start0:200:-100
+
+# a second American wave so the fight keeps going
+300 spawn 0 AmericaTankCrusader 4 start0:120:-200 45
+315 attackmove 0 AmericaTankCrusader start0:460:-100
+
+30 tally 0 AmericaTankCrusader
+60 tally 0 AmericaTankCrusader
+90 tally 0 AmericaTankCrusader
+120 tally 0 AmericaTankCrusader
+150 tally 0 AmericaTankCrusader
+180 tally 0 AmericaTankCrusader
+210 tally 0 AmericaTankCrusader
+240 tally 0 AmericaTankCrusader
+270 tally 0 AmericaTankCrusader
+300 tally 0 AmericaTankCrusader
+360 tally 0 AmericaTankCrusader
+420 tally 0 AmericaTankCrusader
+480 tally 0 AmericaTankCrusader
+60 tally 0 AmericaTankPaladin
+120 tally 0 AmericaTankPaladin
+180 tally 0 AmericaTankPaladin
+240 tally 0 AmericaTankPaladin
+300 tally 0 AmericaTankPaladin
+60 tally 1 ChinaTankOverlord
+120 tally 1 ChinaTankBattleMaster
+180 tally 1 ChinaTankOverlord
+240 tally 1 ChinaTankBattleMaster
+300 tally 1 ChinaTankOverlord
+360 tally 1 ChinaTankBattleMaster
+60 tally 0 AmericaBarracks
+90 tally 0 AmericaBarracks
+120 tally 0 AmericaBarracks
+150 tally 0 AmericaBarracks
+180 tally 0 AmericaBarracks
+210 tally 0 AmericaBarracks
+240 tally 0 AmericaBarracks
+270 tally 0 AmericaBarracks
+300 tally 0 AmericaBarracks
+360 tally 0 AmericaBarracks
+420 tally 0 AmericaBarracks
diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleSys.h b/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleSys.h
index 5c11a527b..af04b8282 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleSys.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/ParticleSys.h
@@ -207,6 +207,10 @@ public:
UnsignedInt getPersonality(void) { return m_personality; };
void setPersonality(UnsignedInt p) { m_personality = p; };
+ /// The cell of its template's flipbook this particle shows now (ParticleSystemTemplate's Flipbook
+ /// fields), counted row by row from the top left; 0 for a card that is not a flipbook.
+ UnsignedInt getFlipbookFrame( void ) const;
+
protected:
// snapshot methods
@@ -244,6 +248,7 @@ protected:
Bool m_diesThisUpdate; ///< set on the job pool, read when the dead are removed; never saved
+ UnsignedByte m_flipbookStart; ///< the flipbook cell it starts on; drawing only, never saved
public:
Bool m_inSystemList;
Bool m_inOverallList;
@@ -624,6 +629,21 @@ public:
* (W3DParticleSys.cpp, FIRE_LOOK_SAMPLING in ffshader.h). Drawing only. */
Bool isFireLook( void ) const { return m_fireLook; }
+ /** "FlipbookGrid = 8": the card is a square atlas of 8 by 8 frames (2, 4, 8 or 16 a side), row by
+ * row from the top left, and each particle shows one at a time. "FlipbookRate" is frames a
+ * second, looping; 0 (the default) plays the frames once over the particle's life.
+ * "FlipbookRandomStart = Yes" starts each particle on a frame from the client's random stream,
+ * and a particle playing once then runs from there to the last. Drawing only, and only for
+ * billboards and the point group: a streak or a ground field still draws the whole atlas. */
+ /** "Emissive = Yes": an alpha blended system that gives light rather than takes it, a fireball's
+ * body: no glow from nearby fires and lights, and nothing cast into the sun's smoke map, so it
+ * neither shades itself nor darkens the ground under it. Drawing only. */
+ Bool isEmissive( void ) const { return m_emissive; }
+
+ UnsignedInt getFlipbookGridLog2( void ) const { return m_flipbookGridLog2; }
+ Real getFlipbookRate( void ) const { return m_flipbookRate; }
+ Bool isFlipbookRandomStart( void ) const { return m_flipbookRandomStart; }
+
// This function was made const because of update modules' module data being all const.
ParticleSystem *createSlaveSystem( Bool createSlaves = TRUE ) const ; ///< if returns non-NULL, it is a slave system for use
@@ -649,6 +669,10 @@ protected:
AsciiString m_name; ///< the name of this template
Bool m_explosionDebrisTrail; ///< switched off with the DebrisTrails option (client only)
Bool m_fireLook; ///< drawn with the Direct3D 11 fire look (client only)
+ Bool m_emissive; ///< alpha blended but takes no light and casts no smoke shadow (client only)
+ UnsignedByte m_flipbookGridLog2; ///< log2 of the flipbook's frames a side, 0 for a plain card (client only)
+ Real m_flipbookRate; ///< flipbook frames a second, looping; 0 plays once over the life (client only)
+ Bool m_flipbookRandomStart; ///< each particle starts on a random flipbook frame (client only)
// This has to be mutable because of the delayed initialization thing in createSlaveSystem
mutable const ParticleSystemTemplate *m_slaveTemplate; ///< if non-NULL, use this to create a slave system
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp
index 12328a0bc..f588f4e24 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/System/ParticleSys.cpp
@@ -123,6 +123,19 @@ static void parseRetailPerFrameFactorRandom( INI *ini, void *instance, void *sto
scaleRandomVariable( store, ConvertRetailPerFrameFactor );
}
+/// "FlipbookGrid": frames a side, kept as its log2 because the point group's frame tables are indexed
+/// that way. 1 is a plain card; anything but a power of two up to 16 stops the load.
+static void parseFlipbookGrid( INI *ini, void * /*instance*/, void *store, const void * /*userData*/ )
+{
+ const UnsignedInt side = INI::scanUnsignedInt( ini->getNextToken() );
+ UnsignedByte log2 = 0;
+ while (log2 < 4 && (1u << log2) < side)
+ ++log2;
+ if ((1u << log2) != side)
+ throw INI_INVALID_DATA;
+ *(UnsignedByte *)store = log2;
+}
+
static void parseRetailPerFrameSquaredReal( INI *ini, void *instance, void *store, const void *userData )
{
INI::parseReal( ini, instance, store, userData );
@@ -373,6 +386,13 @@ Particle::Particle( ParticleSystem *system, const ParticleInfo *info )
m_createTimestamp = TheGameClient->getFrame();
m_personality = 0;
+ // Drawn only when the system's template is a flipbook that asks for it, so every other system
+ // leaves the client's random stream as it was.
+ const ParticleSystemTemplate *flipbook = system->getTemplate();
+ m_flipbookStart = 0;
+ if (flipbook->getFlipbookGridLog2() != 0 && flipbook->isFlipbookRandomStart())
+ m_flipbookStart = (UnsignedByte)GameClientRandomValue( 0, ( 1 << ( 2 * flipbook->getFlipbookGridLog2() ) ) - 1 );
+
m_size = info->m_size;
m_sizeRate = info->m_sizeRate;
m_sizeRateDamping = info->m_sizeRateDamping;
@@ -431,6 +451,26 @@ Particle::~Particle()
//DEBUG_ASSERTLOG(!(totalParticleCount % 100 == 0), ( "TotalParticleCount = %d\n", m_totalParticleCount ));
}
+// ------------------------------------------------------------------------------------------------
+/** The age is the logic frames the particle has lived, so the frames run on the game's clock and stop
+ * with it. A particle with no lifetime never ages and keeps its first frame. Reads only the
+ * particle and its template, so the render's fill jobs may call it. */
+// ------------------------------------------------------------------------------------------------
+UnsignedInt Particle::getFlipbookFrame( void ) const
+{
+ const ParticleSystemTemplate *flipbook = m_system->getTemplate();
+ const UnsignedInt frames = 1u << ( 2 * flipbook->getFlipbookGridLog2() );
+ if (frames == 1 || m_lifetime == 0)
+ return m_flipbookStart;
+
+ const UnsignedInt age = m_lifetime - m_lifetimeLeft;
+ if (flipbook->getFlipbookRate() > 0.0f)
+ return ( m_flipbookStart + (UnsignedInt)( age * flipbook->getFlipbookRate() * SECONDS_PER_LOGICFRAME_REAL ) ) % frames;
+
+ const UnsignedInt frame = m_flipbookStart + (UnsignedInt)( (Real)age / (Real)m_lifetime * (Real)( frames - m_flipbookStart ) );
+ return frame < frames ? frame : frames - 1;
+}
+
// ------------------------------------------------------------------------------------------------
/** See ParticleSys.h. The density scales the optical depth the alpha implies and is untuned; a
* particle fainter than the thinnest casts nothing. */
@@ -2737,6 +2777,10 @@ Bool ParticleSystem::shouldCastGroundShadow( void ) const
if (m_shaderType != ALPHA && m_shaderType != ALPHA_TEST)
return FALSE;
+ // a fireball's body gives light and throws no shadow
+ if (m_template->isEmissive())
+ return FALSE;
+
// the sun's map holds this cloud already and shades the ground under it through its own density
if (m_inSunMap)
return FALSE;
@@ -3368,6 +3412,10 @@ const FieldParse ParticleSystemTemplate::m_fieldParseTable[] =
{ "PerParticleAttachedSystem", INI::parseAsciiString, NULL, offsetof( ParticleSystemTemplate, m_attachedSystemName ) },
{ "ExplosionDebrisTrail", INI::parseBool, NULL, offsetof( ParticleSystemTemplate, m_explosionDebrisTrail ) },
{ "FireLook", INI::parseBool, NULL, offsetof( ParticleSystemTemplate, m_fireLook ) },
+ { "Emissive", INI::parseBool, NULL, offsetof( ParticleSystemTemplate, m_emissive ) },
+ { "FlipbookGrid", parseFlipbookGrid, NULL, offsetof( ParticleSystemTemplate, m_flipbookGridLog2 ) },
+ { "FlipbookRate", INI::parseReal, NULL, offsetof( ParticleSystemTemplate, m_flipbookRate ) },
+ { "FlipbookRandomStart", INI::parseBool, NULL, offsetof( ParticleSystemTemplate, m_flipbookRandomStart ) },
{ "Lifetime", parseRetailFramesRandom, NULL, offsetof( ParticleSystemTemplate, m_lifetime ) },
{ "SystemLifetime", INI::parseRetailFramesUnsignedInt, NULL, offsetof( ParticleSystemTemplate, m_systemLifetime ) },
@@ -3542,6 +3590,10 @@ ParticleSystemTemplate::ParticleSystemTemplate( const AsciiString &name ) :
//
m_explosionDebrisTrail = FALSE;
m_fireLook = FALSE;
+ m_emissive = FALSE;
+ m_flipbookGridLog2 = 0;
+ m_flipbookRate = 0.0f;
+ m_flipbookRandomStart = FALSE;
}
// ------------------------------------------------------------------------------------------------
diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DParticleSys.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DParticleSys.h
index bd2cb3e47..59c4498ab 100644
--- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DParticleSys.h
+++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DParticleSys.h
@@ -68,6 +68,7 @@ private:
ShareBufferClass<Vector4> *m_RGBABuffer; ///< array of particle color and alpha
ShareBufferClass<float> *m_sizeBuffer; ///< array of particle sizes
ShareBufferClass<uint8> *m_angleBuffer; ///< array of particle orientations
+ ShareBufferClass<uint8> *m_frameBuffer; ///< array of particle flipbook frames
Bool m_readyToRender; ///< if true, it is OK to render
public:
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp
index 918cfc325..d9d5b4dce 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DParticleSys.cpp
@@ -167,14 +167,18 @@ static UnsignedInt s_fireLightsFrame; ///< the particle update they were
static UnsignedInt s_fireLightsParticles;
static UnsignedInt s_fireLightsSystems;
-/** One additive system as a point light, if it is bright enough. */
+/** 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();
- const Real pw = (c->red + c->green + c->blue) * (1.0f / 3.0f) * p->getSize();
+ 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();
@@ -292,7 +296,7 @@ static Int gatherSmokeLights( SmokeLight *lights, const AABoxClass &view )
* Any other system gets none. */
static Int pickSmokeLights( ParticleSystem *sys, const SmokeLight *lights, Int count, SmokeLight *picked )
{
- if (count == 0 || sys->getShaderType() != ParticleSystemInfo::ALPHA)
+ if (count == 0 || sys->getShaderType() != ParticleSystemInfo::ALPHA || sys->getTemplate()->isEmissive())
return 0;
Particle *p = sys->getFirstParticle();
@@ -425,6 +429,7 @@ static void fillBillboards( Int index, void *context )
SmokeLight lights[ SMOKE_LIGHTS_PER_SYSTEM ];
const Int lightCount = pickSmokeLights( fill.system, job->lights, job->lightCount, lights );
const ParticleSystemInfo::ParticleShaderType shaderType = fill.system->getShaderType();
+ const UnsignedInt flipbookLog2 = fill.system->getTemplate()->getFlipbookGridLog2();
for (Particle *p = fill.system->getFirstParticle(); p; p = p->m_systemNext)
{
@@ -462,14 +467,16 @@ static void fillBillboards( Int index, void *context )
// The orientation table's index wraps, as it did on Windows (Platform/MsvcFloatCasts.h).
const uint8 orientation = floatToByteAsMsvc( p->getAngle() * 255.0f / (2.0f * PI) );
PointGroupClass::Write_Billboard( quad, job->view, Vector3( pos->x, pos->y, pos->z ), psize,
- orientation, packed, glow );
+ orientation, packed, glow, flipbookLog2, flipbookLog2 ? p->getFlipbookFrame() : 0 );
if (fill.fire)
{
- // FIRE_LOOK_SAMPLING's packing: a whole seed below 256, then the age held off the whole
- // numbers on both sides, so the interpolated value never floors to the next seed.
- // Lifetime 0 is a particle that never dies (four retail systems), which stays young.
+ // FIRE_LOOK_SAMPLING's packing: a whole number below 256, the seed times eight plus the
+ // flipbook's log2 frames a side, so the noise bends a flipbook frame inside its own cell;
+ // then the age held off the whole numbers on both sides, so the interpolated value never
+ // floors to the next one. Lifetime 0 is a particle that never dies (four retail
+ // systems), which stays young.
const Real age = p->m_lifetime ? 1.0f - (Real)p->getLifetimeLeft() / (Real)p->m_lifetime : 0.0f;
- const Real fireAgeSeed = (Real)( ( p->getPersonality() * 97u ) & 255u ) + 0.01f + 0.98f * age;
+ const Real fireAgeSeed = (Real)( ( ( ( p->getPersonality() * 97u ) & 31u ) << 3 ) | flipbookLog2 ) + 0.01f + 0.98f * age;
for (Int k = 0; k < 4; ++k)
quad[ k ].v2 = fireAgeSeed;
}
@@ -1211,6 +1218,7 @@ W3DParticleSystemManager::W3DParticleSystemManager()
m_RGBABuffer = NULL;
m_sizeBuffer = NULL;
m_angleBuffer = NULL;
+ m_frameBuffer = NULL;
m_readyToRender = false;
m_onScreenParticleCount = 0;
@@ -1231,6 +1239,7 @@ W3DParticleSystemManager::W3DParticleSystemManager()
m_RGBABuffer = NEW_REF( ShareBufferClass<Vector4>, (MAX_POINTS_PER_GROUP, "W3DParticleSystemManager::m_RGBABuffer") );
m_sizeBuffer = NEW_REF( ShareBufferClass<float>, (MAX_POINTS_PER_GROUP, "W3DParticleSystemManager::m_sizeBuffer") );
m_angleBuffer = NEW_REF( ShareBufferClass<uint8>, (MAX_POINTS_PER_GROUP, "W3DParticleSystemManager::m_angleBuffer") );
+ m_frameBuffer = NEW_REF( ShareBufferClass<uint8>, (MAX_POINTS_PER_GROUP, "W3DParticleSystemManager::m_frameBuffer") );
}
W3DParticleSystemManager::~W3DParticleSystemManager()
@@ -1248,6 +1257,7 @@ W3DParticleSystemManager::~W3DParticleSystemManager()
REF_PTR_RELEASE(m_RGBABuffer);
REF_PTR_RELEASE(m_sizeBuffer);
REF_PTR_RELEASE(m_angleBuffer);
+ REF_PTR_RELEASE(m_frameBuffer);
}
/** A reset can be followed by an update on the same logic frame, so the fires' frame alone would
@@ -1380,7 +1390,7 @@ const std::vector<W3DParticleSystemManager::SunMapCaster> &W3DParticleSystemMana
{
ParticleSystem *sys = m_frameView[ v ].system;
if (sys->getShaderType() != ParticleSystemInfo::ALPHA || !sys->shouldBillboard()
- || sys->isUsingStreak() || sys->isUsingSmudge())
+ || sys->isUsingStreak() || sys->isUsingSmudge() || sys->getTemplate()->isEmissive())
continue;
if (*((UnsignedInt *)sys->getParticleTypeName().str()) == 0x44554D53)
continue;
@@ -1539,7 +1549,8 @@ void W3DParticleSystemManager::doParticles(RenderInfoClass &rinfo)
s_fireLights.clear();
// a hidden fire lights nothing, an own stealthed one only as much as it shows
for (size_t v = 0; v < m_frameView.size(); ++v)
- if (m_frameView[ v ].system->getShaderType() == ParticleSystemInfo::ADDITIVE)
+ if (m_frameView[ v ].system->getShaderType() == ParticleSystemInfo::ADDITIVE
+ || m_frameView[ v ].system->getTemplate()->isEmissive())
gatherFireLight( m_frameView[ v ].system, m_frameView[ v ].fade );
s_fireLightsValid = TRUE;
s_fireLightsFrame = m_lastLogicFrameUpdate;
@@ -1576,7 +1587,8 @@ void W3DParticleSystemManager::doParticles(RenderInfoClass &rinfo)
if (nextFill < m_billboardFills.size() && m_billboardFills[ nextFill ].system == sys)
{
BillboardFill &fill = m_billboardFills[ nextFill++ ];
- PointGroupClass::Insert_Sorted_Billboards( &fill.range, fill.drawn, fill.texture, fill.shader, fill.glow != FALSE, fill.fire != FALSE );
+ PointGroupClass::Insert_Sorted_Billboards( &fill.range, fill.drawn, fill.texture, fill.shader, fill.glow != FALSE, fill.fire != FALSE,
+ sys->getTemplate()->isEmissive() != FALSE );
fill.texture->Release_Ref(); // the draw state took its own reference
m_fieldParticleCount += fill.fieldIncrement * fill.drawn;
m_onScreenParticleCount += fill.drawn;
@@ -1633,6 +1645,8 @@ void W3DParticleSystemManager::doParticles(RenderInfoClass &rinfo)
Real *sizeArray = m_sizeBuffer->Get_Array();
Vector4 *RGBAArray = m_RGBABuffer->Get_Array();
uint8 *angleArray = m_angleBuffer->Get_Array();
+ uint8 *frameArray = m_frameBuffer->Get_Array();
+ const UnsignedInt flipbookLog2 = sys->getTemplate()->getFlipbookGridLog2();
const Coord3D *pos;
const RGBColor *color;
Real psize;
@@ -1671,6 +1685,8 @@ void W3DParticleSystemManager::doParticles(RenderInfoClass &rinfo)
posArray[count].Z = pos->z;
sizeArray[count] = psize;
+ if (flipbookLog2)
+ frameArray[count] = (uint8)p->getFlipbookFrame();
color = p->getColor();
RGBAArray[count].X = color->red;
@@ -1773,11 +1789,11 @@ void W3DParticleSystemManager::doParticles(RenderInfoClass &rinfo)
/// @todo Use both QUADS and TRIS for particles
m_pointGroup->Set_Point_Mode( PointGroupClass::QUADS );
- m_pointGroup->Set_Arrays( m_posBuffer, m_RGBABuffer, NULL, m_sizeBuffer, m_angleBuffer, NULL, count );
+ // A flipbook's frames go in the frame array; every other system draws the whole card.
+ m_pointGroup->Set_Arrays( m_posBuffer, m_RGBABuffer, NULL, m_sizeBuffer, m_angleBuffer,
+ flipbookLog2 ? m_frameBuffer : NULL, count );
+ m_pointGroup->Set_Frame_Row_Column_Count_Log2( (unsigned char)flipbookLog2 );
m_pointGroup->Set_Billboard(sys->shouldBillboard());
-
- /// @todo Support animated texture particles
- /// @todo lorenzen sez: unimplemented code wastes cpu cycles
m_pointGroup->Set_Point_Frame( 0 );
//RENDER IT!
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp
index d2eb123b0..8ba375c93 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp
@@ -246,6 +246,7 @@ DX11BackendClass::DX11BackendClass()
, ShadowReceiving(false)
, SmokeGlow(false)
, FireLook(false)
+ , Emissive(false)
, AdditiveGain(1.0f)
, GlowDraw(false)
, SceneStandIn(NULL)
@@ -1044,6 +1045,14 @@ void DX11BackendClass::Set_Fire_Look(bool fire)
}
}
+void DX11BackendClass::Set_Emissive(bool emissive)
+{
+ if (Emissive != emissive) {
+ Emissive = emissive;
+ PipelineChanged = true;
+ }
+}
+
/** Which way a fire billboard wears its look: through the colour for a blend that adds it
unweighted, through the alpha otherwise. Off under Classic, whose picture is -d3d9's
(SoftParticlesAllowed carries that setting), and off for anything but a one-stage fixed-function
@@ -2189,6 +2198,9 @@ bool DX11BackendClass::Shadow_Receiving() const
if (!ShadowReceiving || ShadowMapBound || ShadowMapTexture == NULL) {
return false;
}
+ if (Emissive) {
+ return false; // a fireball's body blended over the frame: it gives light, it takes no shade
+ }
// A transcribed terrain or road program takes one too: the ground is where a shadow is seen,
// and those programs carry the sampling whether a frame has a map or not. The water and the
// trees keep their own shadows for now.
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h
index a08f1ae03..82003ef3b 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h
@@ -239,6 +239,11 @@ public:
// pool sets it, around those systems' runs. A draw it does not suit takes none (Fire_Look).
void Set_Fire_Look(bool fire);
+ // The draws that follow are an Emissive particle system's billboards, a fireball's alpha blended
+ // body: they give light, so they take neither the sun's shadow nor the smoke's shade. Only the
+ // sorting pool sets it, around those systems' runs.
+ void Set_Emissive(bool emissive);
+
// The look the draws that follow are dressed in (a DRAW_EFFECT_* value, ffshader.h) and its
// four numbers: wall clock seconds, strength, a per-object seed and the object's opacity. The
// mesh renderer sets it around one object's draws and puts DRAW_EFFECT_NONE back after them.
@@ -557,6 +562,8 @@ private:
// Set_Fire_Look, and which way the current draw wears it (a FIRE_LOOK_* value).
bool FireLook;
unsigned Fire_Look() const;
+ // Set_Emissive: the current draws take no shadow and no smoke shade (Shadow_Receiving).
+ bool Emissive;
// Set_Draw_Effect's look and numbers, and the look the current draw takes after the checks.
unsigned DrawEffect;
float DrawEffectNumbers[4];
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp
index c9fedef44..73fb2de91 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp
@@ -629,6 +629,13 @@ void Direct3D11_Set_Fire_Look(bool fire)
}
}
+void Direct3D11_Set_Emissive(bool emissive)
+{
+ if (Active) {
+ Backend.Set_Emissive(emissive);
+ }
+}
+
static bool DrawEffectsAllowed = true;
void Direct3D11_Set_Draw_Effect(unsigned effect, const float parameters[4])
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h
index 37ed5157a..eb4b0f314 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h
@@ -175,6 +175,10 @@ void Direct3D11_Set_Smoke_Glow(bool glow);
// seed in the second coordinate set (DX11BackendClass::Set_Fire_Look). The sorting pool sets it.
void Direct3D11_Set_Fire_Look(bool fire);
+// The draws that follow are an Emissive particle system's billboards, which take no shadow and no
+// smoke shade (DX11BackendClass::Set_Emissive). The sorting pool sets it.
+void Direct3D11_Set_Emissive(bool emissive);
+
// The look one object's draws are dressed in (DRAW_EFFECT_* in ffshader.h) and its four numbers
// (DX11BackendClass::Set_Draw_Effect). The mesh renderer sets it around a mesh's draws and puts
// zero back after them. -d3d9, -headless and the SDL3 port draw the object as they always did.
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime_posix.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime_posix.cpp
index 1b5cb0c20..fc96e672d 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime_posix.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime_posix.cpp
@@ -76,6 +76,7 @@ bool Direct3D11_Fill_Smoke_Map(const float *, unsigned, float) { return false; }
void Direct3D11_Set_Scene_View(const float [16]) {}
void Direct3D11_Set_Smoke_Glow(bool) {}
void Direct3D11_Set_Fire_Look(bool) {}
+void Direct3D11_Set_Emissive(bool) {}
void Direct3D11_Set_Draw_Effect(unsigned, const float [4]) {}
bool Direct3D11_Draw_Effects() { return false; }
void Direct3D11_Allow_Draw_Effects(bool) {}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.h
index c0f52fcdf..27f1e4dd0 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.h
@@ -466,7 +466,8 @@ const unsigned NORMAL_MAPPED_LIGHTS = 4;
// A fire or explosion billboard on Direct3D 11 (CombinerDescription::FireLook). Nothing in the
// constant block: the particle's age and a seed ride in the second coordinate set's v, packed as
-// seed + 0.01 + 0.98 * age with the seed a whole number below 256 (W3DParticleSys.cpp,
+// seed + 0.01 + 0.98 * age with the seed a whole number below 256, eight times a random number below
+// 32 plus the flipbook's log2 frames a side (W3DParticleSys.cpp,
// fillBillboards), and the vertex half hands the set on (VertexPipelineDescription::FireLook). The
// margins keep the interpolated value off a whole number, where floor would flip the seed.
//
@@ -502,12 +503,21 @@ const unsigned NORMAL_MAPPED_LIGHTS = 4;
"}\n" \
"\n"
+// The whole number's low three bits are the flipbook's log2 frames a side (ParticleSystemTemplate's
+// FlipbookGrid, 0 for a plain card), and the bend works in the frame's own coordinates and stays
+// inside its cell, so a flipbook frame flickers like a whole card and never reaches into the next
+// frame. The cell comes from the interpolated coordinate itself: only a pixel on a cell's very edge
+// can land in the neighbour, and every frame's edge is empty.
#define FIRE_LOOK_BEND \
" float fire_age = saturate((frac(input.TexCoord1.y) - 0.01) / 0.98);\n" \
- " float2 fire_at = input.TexCoord0 * 3.0 + floor(input.TexCoord1.y) * float2(0.37, 0.61);\n" \
+ " float fire_seed = floor(input.TexCoord1.y);\n" \
+ " float fire_cells = (float)(1u << ((uint)fire_seed & 7u));\n" \
+ " float2 fire_cell = min(floor(input.TexCoord0 * fire_cells), fire_cells - 1.0);\n" \
+ " float2 fire_local = input.TexCoord0 * fire_cells - fire_cell;\n" \
+ " float2 fire_at = fire_local * 3.0 + fire_seed * float2(0.37, 0.61);\n" \
" float2 fire_bend = float2(fire_noise(fire_at + float2(0.0, fire_age * 5.0)),\n" \
" fire_noise(fire_at * 1.7 + float2(4.1, fire_age * 7.0))) - 0.5;\n" \
- " input.TexCoord0 = saturate(input.TexCoord0 + fire_bend * (0.06 + 0.06 * fire_age));\n"
+ " input.TexCoord0 = (fire_cell + saturate(fire_local + fire_bend * (0.06 + 0.06 * fire_age))) / fire_cells;\n"
// After the stages, with the shape read from the last stage's texel into fire_shape, by one of the
// two expressions below; the caller applies fire_keep to the alpha or to the whole colour.
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/pointgr.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/pointgr.cpp
index b392143c0..1184a3580 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/pointgr.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/pointgr.cpp
@@ -1071,7 +1071,7 @@ void PointGroupClass::Reserve_Sorted_Billboards(int quads, SortingBillboardRange
* the same Insert_Quads, from a range the jobs have already written. *
*========================================================================*/
void PointGroupClass::Insert_Sorted_Billboards(SortingBillboardRange *range, int quads,
- TextureClass *texture, const ShaderClass &shader, bool glow, bool fire)
+ TextureClass *texture, const ShaderClass &shader, bool glow, bool fire, bool emissive)
{
if (quads > 0)
{
@@ -1095,7 +1095,7 @@ void PointGroupClass::Insert_Sorted_Billboards(SortingBillboardRange *range, int
const unsigned short vertices=(unsigned short)(quads*4);
DX8Wrapper::Set_Index_Buffer(SortingQuads, 0);
DX8Wrapper::Set_Sorting_Vertex_Range(range->Array, range->Offset, vertices);
- SortingRendererClass::Insert_Quads((unsigned short)quads, 0, vertices, glow, fire);
+ SortingRendererClass::Insert_Quads((unsigned short)quads, 0, vertices, glow, fire, emissive);
DX8Wrapper::Set_Transform(D3DTS_VIEW,view);
}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/pointgr.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/pointgr.h
index 44bb82f9d..744970ceb 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/pointgr.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/pointgr.h
@@ -237,25 +237,27 @@ public:
/// shader has to be one Would_Sort_Billboards accepts. glow: the quads' normals hold the glow
/// Write_Billboard was given, for the Direct3D 11 backend to add after the shade. fire: the
/// caller wrote each particle's age and seed into v2 for the fire look (ffshader.h,
- /// FIRE_LOOK_SAMPLING). Render thread only.
+ /// FIRE_LOOK_SAMPLING). emissive: an Emissive system's quads, which take no shadow and no
+ /// smoke shade (Direct3D11_Set_Emissive). Render thread only.
static void Insert_Sorted_Billboards(SortingBillboardRange *range, int quads,
TextureClass *texture, const ShaderClass &shader, bool glow = false,
- bool fire = false);
+ bool fire = false, bool emissive = false);
- /// One billboard's four vertices: the transform, corner table and single-frame UVs Render uses
- /// for a billboarded QUADS group with per-point sizes, orientations and colours, written the
+ /// One billboard's four vertices: the transform, corner table and frame UVs Render uses for a
+ /// billboarded QUADS group with per-point sizes, orientations, colours and frames, written the
/// same way so the vertices come out bit for bit the same. color is packed already
/// (DX8Wrapper::Convert_Color_Clamp). glow goes in the normal, which an unlit billboard does not
- /// otherwise read. Touches nothing but its arguments and the static tables, so any thread may
- /// call it.
+ /// otherwise read. frame_log2 and frame pick one cell of a square atlas, as
+ /// Set_Frame_Row_Column_Count_Log2 and the frame array do; 0 and 0 are the whole texture.
+ /// Touches nothing but its arguments and the static tables, so any thread may call it.
static inline void Write_Billboard(VertexFormatXYZNDUV2 *quad, const Matrix4x4 &view,
const Vector3 &world, float size, unsigned char orientation, unsigned color,
- const Vector3 &glow)
+ const Vector3 &glow, unsigned frame_log2=0, unsigned frame=0)
{
const Vector4 result=view*world;
const Vector3 point(result.X,result.Y,result.Z);
const Vector3 *corners=_QuadVertexLocationOrientationTable[orientation];
- const Vector2 *uv=_QuadVertexUVFrameTable[0];
+ const Vector2 *uv=_QuadVertexUVFrameTable[frame_log2] + frame*4;
for (int k=0;k<4;++k)
{
const Vector3 location=point + corners[k] * size;
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/sortingrenderer.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/sortingrenderer.cpp
index bb9f9d176..143d78c75 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/sortingrenderer.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/sortingrenderer.cpp
@@ -150,6 +150,7 @@ public:
bool quads; // four vertices a quad, in order from min_vertex_index; the ib is not read
bool glow; // the normals hold a fire's glow (Insert_Quads)
bool fire; // a fire system's quads, age and seed in v2 (Insert_Quads)
+ bool emissive; // an Emissive system's quads: no shadow, no smoke shade (Insert_Quads)
// The object's Direct3D 11 look (RTS3DScene::renderOneObject) as the mesh renderer had it set
// when a sorted mesh queued its triangles; its draws come later, after the look is put back.
unsigned draw_effect;
@@ -254,6 +255,7 @@ void SortingRendererClass::Insert_Triangles(
state->quads=false;
state->glow=false;
state->fire=false;
+ state->emissive=false;
state->draw_effect=Direct3D11_Requested_Draw_Effect(state->draw_effect_parameters);
SortingVertexBufferClass* vertex_buffer=static_cast<SortingVertexBufferClass*>(state->sorting_state.vertex_buffers[0]);
@@ -342,7 +344,8 @@ void SortingRendererClass::Insert_Quads(
unsigned short min_vertex_index,
unsigned short vertex_count,
bool glow,
- bool fire)
+ bool fire,
+ bool emissive)
{
const unsigned short polygon_count=quad_count*2;
if (!WW3D::Is_Sorting_Enabled()) {
@@ -368,6 +371,7 @@ void SortingRendererClass::Insert_Quads(
state->quads=true;
state->glow=glow;
state->fire=fire;
+ state->emissive=emissive;
No_Draw_Effect(state);
state->transformed_center=Vector3(0.0f,0.0f,0.0f);
unsorted_list.Add_Tail(state);
@@ -740,11 +744,13 @@ static void Flush_Sorting_Batch(const TempIndexStruct* entries,unsigned entry_co
SortingNodeStruct* next=overlapping_nodes[entry_node];
// A run of billboards fades into the depth behind it and a run of meshes does not, so the
// two never share a draw even in one state.
- if (state->glow!=next->glow || state->fire!=next->fire || state->quads!=next->quads || !Same_Draw_Effect(state,next) ||
+ if (state->glow!=next->glow || state->fire!=next->fire || state->emissive!=next->emissive ||
+ state->quads!=next->quads || !Same_Draw_Effect(state,next) ||
!Same_Draw_State(state->sorting_state,next->sorting_state)) {
Apply_Render_State(state->sorting_state);
Direct3D11_Set_Smoke_Glow(state->glow);
Direct3D11_Set_Fire_Look(state->fire);
+ Direct3D11_Set_Emissive(state->emissive);
Direct3D11_Set_Soft_Particles(state->quads);
Direct3D11_Set_Draw_Effect(state->draw_effect,state->draw_effect_parameters);
DX8Wrapper::Draw_Triangles(run_first_index,run_triangles,run_first_vertex,vertex_cursor-run_first_vertex);
@@ -762,11 +768,13 @@ static void Flush_Sorting_Batch(const TempIndexStruct* entries,unsigned entry_co
Apply_Render_State(overlapping_nodes[node_id]->sorting_state);
Direct3D11_Set_Smoke_Glow(overlapping_nodes[node_id]->glow);
Direct3D11_Set_Fire_Look(overlapping_nodes[node_id]->fire);
+ Direct3D11_Set_Emissive(overlapping_nodes[node_id]->emissive);
Direct3D11_Set_Soft_Particles(overlapping_nodes[node_id]->quads);
Direct3D11_Set_Draw_Effect(overlapping_nodes[node_id]->draw_effect,overlapping_nodes[node_id]->draw_effect_parameters);
DX8Wrapper::Draw_Triangles(run_first_index,run_triangles,run_first_vertex,vertex_cursor-run_first_vertex);
Direct3D11_Set_Smoke_Glow(false);
Direct3D11_Set_Fire_Look(false);
+ Direct3D11_Set_Emissive(false);
Direct3D11_Set_Soft_Particles(false);
static const float no_effect[4]={0.0f,0.0f,0.0f,0.0f};
Direct3D11_Set_Draw_Effect(0,no_effect);
@@ -1090,6 +1098,7 @@ void SortingRendererClass::Insert_VolumeParticle(
state->quads=false;
state->glow=false;
state->fire=false;
+ state->emissive=false;
No_Draw_Effect(state);
SortingVertexBufferClass* vertex_buffer=static_cast<SortingVertexBufferClass*>(state->sorting_state.vertex_buffers[0]);
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/sortingrenderer.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/sortingrenderer.h
index bd214740d..34a3dc936 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/sortingrenderer.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/sortingrenderer.h
@@ -55,12 +55,14 @@ public:
/// a quad and does not read the index buffer. glow: the quads' normals hold a fire's glow, which
/// the Direct3D 11 backend adds after the shade (Direct3D11_Set_Smoke_Glow). fire: a fire or
/// explosion system's quads, each particle's age and seed in v2 (Direct3D11_Set_Fire_Look).
+ /// emissive: quads that take no shadow and no smoke shade (Direct3D11_Set_Emissive).
static void Insert_Quads(
unsigned short quad_count,
unsigned short min_vertex_index,
unsigned short vertex_count,
bool glow = false,
- bool fire = false);
+ bool fire = false,
+ bool emissive = false);
static void Insert_VolumeParticle(
const SphereClass& bounding_sphere,
diff --git a/GeneralsMD/Code/Tests/test_ffshadercompile.cpp b/GeneralsMD/Code/Tests/test_ffshadercompile.cpp
index 34fd8d26b..e1d1864e6 100644
--- a/GeneralsMD/Code/Tests/test_ffshadercompile.cpp
+++ b/GeneralsMD/Code/Tests/test_ffshadercompile.cpp
@@ -399,7 +399,7 @@ TEST(ffshadercompile_a_fire_billboard_burns_on_d3d11_only)
CHECK(CombinerShader_Key(description) == plain_key + ":B2");
std::string flame;
CHECK(CombinerShader_Generate(description, COMBINER_SHADER_TARGET_D3D11, flame));
- const size_t bend = flame.find("input.TexCoord0 = saturate(");
+ const size_t bend = flame.find("input.TexCoord0 = (fire_cell + saturate(");
const size_t sample = flame.find("Texture0.Sample(");
const size_t burn = flame.find("current *= fire_keep;");
const size_t fog = flame.find("FogColour.rgb, current.rgb");
diff --git a/GeneralsMD/Code/Tools/explosion_flipbook.py b/GeneralsMD/Code/Tools/explosion_flipbook.py
new file mode 100644
index 000000000..86e194dd3
--- /dev/null
+++ b/GeneralsMD/Code/Tools/explosion_flipbook.py
@@ -0,0 +1,392 @@
+"""The two flipbooks the Reforged explosions play (ParticleSystemReforged.ini, FlipbookGrid): a
+fireball that grows, rolls and cools over its 64 frames, and a dark smoke puff that turns over once
+in 64 frames, so it loops without a seam.
+
+Both are raymarched through a noise volume. The fireball is a sphere whose surface is pushed out by
+billowed noise (the sum of folded octaves, which gives round lobes with creases between them) that
+rises and swells with the sphere; a temperature falls from the core outwards and with time, and runs
+a ramp from yellow through saturated deep orange and red to soot. It is alpha blended (stacked
+additively it went to cream and white), so its colour is the ramp itself, never past it, and the late
+frames turn to dark soot as the alpha thins. The smoke is the same kind of sphere rotated rigidly
+about a horizontal axis and lit from above by three density reads towards the light. Both are DXT5
+with straight alpha.
+
+ python Tools/explosion_flipbook.py
+ writes Data/Art/Textures/ReforgedExplosionFire.dds (8 by 8 frames of 256 pixels) and
+ Data/Art/Textures/ReforgedExplosionSmoke.dds (8 by 8 frames of 128 pixels).
+ python Tools/explosion_flipbook.py preview <folder>
+ also writes both atlases as PNG there, the fireball on black and the smoke on grey.
+ python Tools/explosion_flipbook.py selfcheck
+
+Same bytes on every run: the noise comes from a seeded generator and nothing else varies. Nothing is
+drawn past REACH of a frame's half width, a margin of 13 pixels at 128, and every mip level has the
+outermost texel ring of each frame cleared to nothing. The chain runs two levels past 8-pixel frames
+because DDSFileClass drops a file's two smallest levels, so the game's own chain ends there. So neither
+the bilinear filter nor a small mip pulls the neighbouring frame onto a quad's edge, which drew hard
+lines round the smoke in game."""
+import os
+import struct
+import sys
+
+import numpy as np
+from scipy import ndimage
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+OUT_FOLDER = os.path.join(HERE, "..", "Data", "Art", "Textures")
+FIRE_NAME = "ReforgedExplosionFire.dds"
+SMOKE_NAME = "ReforgedExplosionSmoke.dds"
+
+GRID = 8 # frames a side: ParticleSystemReforged.ini's FlipbookGrid
+FRAMES = GRID * GRID
+FIRE_CELL = 256
+SMOKE_CELL = 128
+STEPS = 64 # samples along each ray through the unit cube
+SEED = 1987
+REACH = 0.80 # nothing is drawn past this radius, which keeps every frame's border empty
+SMALLEST_CELL = 8 # the smallest mip the game loads has frames this many pixels a side
+THROWAWAY_LEVELS = 2 # levels below it, which DDSFileClass drops on load (ddsfile.cpp)
+
+NOISE_SIZE = 128 # the noise volume's side, periodic
+NOISE_OCTAVES = (4, 8, 16, 32, 64) # lattice cells a side for each octave
+VOXELS_PER_UNIT = 30.0 # how much noise one unit of the cube spans
+
+# The fireball. Radii are in the cube's half width, so 1 touches the frame's edge.
+FIRE_RADIUS_START = 0.25
+FIRE_RADIUS_END = 0.46
+FIRE_BILLOW = 0.70 # how far the billows push the surface, as a share of the radius
+FIRE_LOBE_SCALE = 0.75 # below 1 makes the billows bigger
+FIRE_CREASE = 0.9 # how much cooler the creases between billows burn than the lobes
+FIRE_RISE = 0.9 # noise units the billows climb over the life
+FIRE_SWIRL = 0.6 # radians the billows turn about the vertical over the life
+FIRE_ABSORB = 16.0 # optical depth of one unit of full density
+# Yellow, orange, saturated deep orange, red, soot: (temperature, linear colour). No white: the
+# hottest is a yellow, so the body never reads cream however it is lit.
+FIRE_RAMP = (
+ (0.00, (0.035, 0.025, 0.020)),
+ (0.20, (0.22, 0.05, 0.015)),
+ (0.40, (0.70, 0.17, 0.020)),
+ (0.60, (0.98, 0.38, 0.035)),
+ (0.80, (1.00, 0.60, 0.090)),
+ (1.00, (1.00, 0.80, 0.280)),
+)
+
+SMOKE_RADIUS = 0.48
+SMOKE_BILLOW = 0.65
+SMOKE_SOFT = 0.35 # the depth over which the edge thickens to full, as a share of the radius
+SMOKE_ABSORB = 14.0
+SMOKE_DARK = 0.04 # linear grey on the shadowed side
+SMOKE_LIT = 0.62 # linear grey on the side towards the light
+SMOKE_LIGHT_STEP = 0.08 # spacing of the three reads towards the light
+SMOKE_LIGHT_ABSORB = 1.6 # how much those reads darken the sample
+
+
+def noise_volumes():
+ """Two periodic noise volumes, both NOISE_SIZE a side: billowed (the shape) and plain fBm (the
+ temperature and the domain warp)."""
+ rng = np.random.default_rng(SEED)
+ billow = np.zeros((NOISE_SIZE,) * 3, np.float32)
+ smooth = np.zeros((NOISE_SIZE,) * 3, np.float32)
+ amplitude = 1.0
+ total = 0.0
+ for cells in NOISE_OCTAVES:
+ for target, fold in ((billow, True), (smooth, False)):
+ lattice = rng.random((cells,) * 3, dtype=np.float32)
+ octave = ndimage.zoom(lattice, NOISE_SIZE / cells, order=3, mode="grid-wrap", grid_mode=True)
+ target += amplitude * (np.abs(octave * 2.0 - 1.0) if fold else octave)
+ total += amplitude
+ amplitude *= 0.5
+ return billow / total, smooth / total
+
+
+def sample(volume, points):
+ """The volume at points (n, 3) in noise units, trilinear and wrapping."""
+ coordinates = (points * VOXELS_PER_UNIT).T
+ return ndimage.map_coordinates(volume, coordinates, order=1, mode="grid-wrap", prefilter=False)
+
+
+def cube_points(cell):
+ """Every sample of an orthographic view down -z through the cube [-1, 1]^3: (cell, cell, STEPS, 3),
+ row 0 at the top (y = 1), the first step nearest the eye (z = 1)."""
+ axis = (np.arange(cell, dtype=np.float32) + 0.5) / cell * 2.0 - 1.0
+ depth = 1.0 - (np.arange(STEPS, dtype=np.float32) + 0.5) / STEPS * 2.0
+ y, x, z = np.meshgrid(-axis, axis, depth, indexing="ij")
+ return np.stack((x, y, z), axis=-1)
+
+
+def ramp(temperature):
+ keys = np.array([key for key, _ in FIRE_RAMP], np.float32)
+ colours = np.array([colour for _, colour in FIRE_RAMP], np.float32)
+ return np.stack([np.interp(temperature, keys, colours[:, c]) for c in range(3)], axis=-1)
+
+
+def composite(density, emission):
+ """Front to back along the steps: density (h, w, s) as optical depth a step, emission (h, w, s, 3).
+ Returns the premultiplied colour and the alpha."""
+ colour = np.zeros(density.shape[:2] + (3,), np.float32)
+ transmit = np.ones(density.shape[:2], np.float32)
+ for step in range(density.shape[2]):
+ absorbed = 1.0 - np.exp(-density[:, :, step])
+ colour += (transmit * absorbed)[..., None] * emission[:, :, step]
+ transmit *= 1.0 - absorbed
+ return colour, 1.0 - transmit
+
+
+def fire_frame(index, points, radius_of_point, billow, smooth):
+ t = index / (FRAMES - 1.0)
+ radius = FIRE_RADIUS_START + (FIRE_RADIUS_END - FIRE_RADIUS_START) * (1.0 - (1.0 - t) ** 2.5)
+ reach = min(radius * (1.0 + FIRE_BILLOW), REACH)
+ inside = radius_of_point < reach
+ p = points[inside]
+ # The billows swell with the sphere, climb and turn slowly about the vertical.
+ angle = FIRE_SWIRL * t
+ cos, sin = np.cos(angle), np.sin(angle)
+ q = p / np.float32(radius ** 0.6)
+ q = np.stack((q[:, 0] * cos - q[:, 2] * sin, q[:, 1] - FIRE_RISE * t, q[:, 0] * sin + q[:, 2] * cos), axis=-1)
+ warp = sample(smooth, q * 0.7 + 11.0) - 0.5
+ q = q + warp[:, None] * 0.6
+ shape = sample(billow, q * FIRE_LOBE_SCALE)
+ r = radius_of_point[inside]
+ surface = radius * (1.0 - FIRE_BILLOW * 0.55 + FIRE_BILLOW * shape * 1.6)
+ # Late in the life the cloud thins from the inside out and the last frames empty.
+ thin = np.clip((t - 0.55) / 0.45, 0.0, 1.0)
+ solid = np.clip((surface - r) / (0.06 * radius), 0.0, 1.0) * (1.0 - thin * thin)
+ solid *= np.clip(1.0 - thin * 1.2 + shape * 1.2 * thin, 0.0, 1.0)
+ # Hot in the core and early; the creases between billows run cooler than the lobes.
+ heat = 1.25 - 1.2 * t ** 0.8
+ temperature = heat * (0.45 + 0.55 * np.clip(1.0 - r / surface, 0.0, 1.0) ** 0.5)
+ temperature += (shape - 0.5) * FIRE_CREASE + (sample(smooth, q * 1.9 + 37.0) - 0.5) * 0.4
+ temperature = np.clip(temperature, 0.0, 1.0)
+ # The glow dies with the cloud: what is left late is soot.
+ temperature *= (1.0 - thin) ** 1.5
+
+ density = np.zeros(points.shape[:3], np.float32)
+ emission = np.zeros(points.shape[:3] + (3,), np.float32)
+ density[inside] = solid * (FIRE_ABSORB * 2.0 / STEPS)
+ emission[inside] = ramp(temperature)
+ colour, alpha = composite(density, emission)
+ # Straight alpha, black where nothing is, so the filter darkens the edge a little and never
+ # brightens it; then the gamma the game's textures are painted in.
+ straight = np.where(alpha[..., None] > 1e-3, colour / np.maximum(alpha[..., None], 1e-3), 0.0)
+ straight = np.clip(straight, 0.0, 1.0) ** (1.0 / 2.2)
+ return np.concatenate((straight, alpha[..., None]), axis=-1)
+
+
+def smoke_frame(index, points, radius_of_point, billow, smooth):
+ angle = 2.0 * np.pi * index / FRAMES
+ cos, sin = np.cos(angle), np.sin(angle)
+ reach = min(SMOKE_RADIUS * (1.0 + SMOKE_BILLOW), REACH)
+ inside = radius_of_point < reach
+ p = points[inside]
+
+ def solid_at(at):
+ # Turned rigidly about the x axis: a whole turn in FRAMES, so frame FRAMES is frame 0.
+ q = np.stack((at[:, 0], at[:, 1] * cos - at[:, 2] * sin, at[:, 1] * sin + at[:, 2] * cos), axis=-1)
+ warp = sample(smooth, q * 0.7 + 23.0) - 0.5
+ shape = sample(billow, q * 1.3 + warp[:, None] * 0.5 + 5.0)
+ r = np.sqrt((at * at).sum(axis=-1))
+ surface = SMOKE_RADIUS * (1.0 - SMOKE_BILLOW * 0.55 + SMOKE_BILLOW * shape * 1.6)
+ return np.clip((surface - r) / (SMOKE_SOFT * SMOKE_RADIUS), 0.0, 1.0) ** 1.5
+
+ solid = solid_at(p)
+ # Lit from above and a little from the front: the smoke between the sample and the light shades
+ # it, so the top of each billow is pale and the underside and the creases go dark.
+ toward = np.array([0.25, 0.9, 0.35], np.float32)
+ toward /= np.sqrt((toward * toward).sum())
+ blocked = sum(solid_at(p + toward * (SMOKE_LIGHT_STEP * k)) for k in (1, 2, 3))
+ light = np.exp(-SMOKE_LIGHT_ABSORB * blocked)
+ grey = SMOKE_DARK + (SMOKE_LIT - SMOKE_DARK) * light
+
+ density = np.zeros(points.shape[:3], np.float32)
+ emission = np.zeros(points.shape[:3] + (3,), np.float32)
+ density[inside] = solid * (SMOKE_ABSORB * 2.0 / STEPS)
+ emission[inside] = np.repeat(grey[:, None], 3, axis=1)
+ colour, alpha = composite(density, emission)
+ # Straight alpha; where nothing is, the colour the edge would have, so the filter brings no fringe.
+ straight = np.where(alpha[..., None] > 1e-3, colour / np.maximum(alpha[..., None], 1e-3), SMOKE_DARK)
+ straight = np.clip(straight, 0.0, 1.0) ** (1.0 / 2.2)
+ return np.concatenate((straight, alpha[..., None]), axis=-1)
+
+
+def atlas(render, cell, channels, billow, smooth):
+ points = cube_points(cell)
+ radius_of_point = np.sqrt((points * points).sum(axis=-1))
+ image = np.zeros((GRID * cell, GRID * cell, channels), np.float32)
+ for index in range(FRAMES):
+ row, column = divmod(index, GRID)
+ image[row * cell:(row + 1) * cell, column * cell:(column + 1) * cell] = render(index, points, radius_of_point, billow, smooth)
+ return image
+
+
+# ---------------------------------------------------------------------------------------------
+# DDS, DXT5. Colour endpoints on each block's principal axis, inset by a sixteenth, indices to the
+# nearest palette entry. Plain, but enough for soft fire and smoke.
+
+def to565(rgb):
+ r = np.round(rgb[..., 0] * 31.0 / 255.0).astype(np.uint32)
+ g = np.round(rgb[..., 1] * 63.0 / 255.0).astype(np.uint32)
+ b = np.round(rgb[..., 2] * 31.0 / 255.0).astype(np.uint32)
+ return (r << 11) | (g << 5) | b
+
+
+def from565(c):
+ r = (c >> 11) & 31
+ g = (c >> 5) & 63
+ b = c & 31
+ return np.stack(((r << 3) | (r >> 2), (g << 2) | (g >> 4), (b << 3) | (b >> 2)), axis=-1).astype(np.float32)
+
+
+def blocks(image):
+ h, w, c = image.shape
+ return image.reshape(h // 4, 4, w // 4, 4, c).transpose(0, 2, 1, 3, 4).reshape(-1, 16, c)
+
+
+def colour_blocks(rgb):
+ """rgb (n, 16, 3) in 0..255: n DXT colour blocks, always in four colour mode."""
+ # Endpoints on the block's principal axis, which the box corners miss when the channels run
+ # opposite ways.
+ mean = rgb.mean(axis=1, keepdims=True)
+ centred = rgb - mean
+ axis = np.linalg.eigh(np.einsum("nki,nkj->nij", centred, centred))[1][:, :, 2]
+ along = np.einsum("nki,ni->nk", centred, axis)
+ low = np.clip(mean[:, 0] + axis * along.min(axis=1, keepdims=True), 0.0, 255.0)
+ high = np.clip(mean[:, 0] + axis * along.max(axis=1, keepdims=True), 0.0, 255.0)
+ inset = (high - low) / 16.0
+ c0 = to565(high - inset)
+ c1 = to565(low + inset)
+ swap = c0 < c1
+ c0, c1 = np.where(swap, c1, c0), np.where(swap, c0, c1)
+ p0 = from565(c0)
+ p1 = from565(c1)
+ palette = np.stack((p0, p1, (2.0 * p0 + p1) / 3.0, (p0 + 2.0 * p1) / 3.0), axis=1)
+ distance = ((rgb[:, :, None, :] - palette[:, None, :, :]) ** 2).sum(axis=-1)
+ index = distance.argmin(axis=-1).astype(np.uint32)
+ index[c0 == c1] = 0
+ bits = (index << (2 * np.arange(16, dtype=np.uint32))).sum(axis=1, dtype=np.uint64).astype(np.uint32)
+ out = np.zeros((rgb.shape[0], 8), np.uint8)
+ out[:, 0:2] = c0.astype("<u2").view(np.uint8).reshape(-1, 2)
+ out[:, 2:4] = c1.astype("<u2").view(np.uint8).reshape(-1, 2)
+ out[:, 4:8] = bits.astype("<u4").view(np.uint8).reshape(-1, 4)
+ return out
+
+
+def alpha_blocks(alpha):
+ """alpha (n, 16) in 0..255: n DXT5 alpha blocks, in eight value mode."""
+ a0 = alpha.max(axis=1).round().astype(np.uint32)
+ a1 = alpha.min(axis=1).round().astype(np.uint32)
+ weights = np.array([0, 7, 1, 2, 3, 4, 5, 6], np.float32) # palette entry i is a0 + (a1 - a0) * weight / 7
+ palette = a0[:, None] + (a1[:, None].astype(np.float32) - a0[:, None]) * weights / 7.0
+ palette = np.floor(palette + 0.5)
+ index = np.abs(alpha[:, :, None] - palette[:, None, :]).argmin(axis=-1).astype(np.uint64)
+ index[a0 == a1] = 0
+ bits = (index << (3 * np.arange(16, dtype=np.uint64))).sum(axis=1, dtype=np.uint64)
+ out = np.zeros((alpha.shape[0], 8), np.uint8)
+ out[:, 0] = a0
+ out[:, 1] = a1
+ out[:, 2:8] = bits.astype("<u8").view(np.uint8).reshape(-1, 8)[:, :6]
+ return out
+
+
+def clear_cell_rings(level, cell):
+ """Every frame's outermost ring of texels emptied, so a quad's edge samples nothing."""
+ alpha = level[..., 3]
+ for edge in range(0, level.shape[0], cell):
+ alpha[edge, :] = alpha[edge + cell - 1, :] = 0.0
+ alpha[:, edge] = alpha[:, edge + cell - 1] = 0.0
+ return level
+
+
+def mips(image, cell):
+ """The chain down to frames SMALLEST_CELL pixels a side and THROWAWAY_LEVELS more for the loader
+ to drop, each level the box average of the one above with the colour weighted by its alpha, and
+ every level's frame rings cleared."""
+ levels = [clear_cell_rings(image.copy(), cell)]
+ while cell > SMALLEST_CELL >> THROWAWAY_LEVELS:
+ top = levels[-1]
+ weighted = np.concatenate((top[..., :3] * top[..., 3:], top[..., 3:]), axis=-1)
+ h, w, c = weighted.shape
+ level = weighted.reshape(h // 2, 2, w // 2, 2, c).mean(axis=(1, 3))
+ alpha = level[..., 3:]
+ level = np.concatenate((np.where(alpha > 1e-4, level[..., :3] / np.maximum(alpha, 1e-4), 0.0), alpha), axis=-1)
+ cell //= 2
+ levels.append(clear_cell_rings(level, cell))
+ return levels
+
+
+def dds(image, cell):
+ """image (h, w, 4) in 0..1, straight alpha, frames cell pixels a side, as a DXT5 DDS file's bytes
+ with its mips."""
+ levels = mips(image, cell)
+ payload = []
+ for level in levels:
+ if level.shape[0] < 4: # a level under one block is stored as a whole block
+ level = np.pad(level, ((0, 4 - level.shape[0]), (0, 4 - level.shape[1]), (0, 0)), mode="edge")
+ texels = blocks(np.clip(np.round(level * 255.0), 0.0, 255.0))
+ payload.append(np.concatenate((alpha_blocks(texels[:, :, 3]), colour_blocks(texels[:, :, :3])), axis=1).tobytes())
+ h, w = image.shape[:2]
+ flags = 0x1 | 0x2 | 0x4 | 0x1000 | 0x20000 | 0x80000 # caps, height, width, pixel format, mip count, linear size
+ header = b"DDS " + struct.pack("<7I", 124, flags, h, w, len(payload[0]), 0, len(levels)) + bytes(44)
+ header += struct.pack("<2I4s5I", 32, 0x4, b"DXT5", 0, 0, 0, 0, 0)
+ header += struct.pack("<5I", 0x8 | 0x1000 | 0x400000, 0, 0, 0, 0) # complex, texture, mipmap
+ assert len(header) == 128
+ return header + b"".join(payload)
+
+
+def decode_colour_block(block):
+ c0, c1, bits = struct.unpack("<HHI", bytes(block))
+ p0 = from565(np.uint32(c0))
+ p1 = from565(np.uint32(c1))
+ palette = (p0, p1, (2 * p0 + p1) / 3, (p0 + 2 * p1) / 3)
+ return np.array([palette[(bits >> (2 * i)) & 3] for i in range(16)])
+
+
+def selfcheck():
+ # A block on one line between two colours, the case DXT is built for, comes back close.
+ rng = np.random.default_rng(3)
+ ends = rng.random((5, 2, 3)) * 255.0
+ along = np.linspace(0.0, 1.0, 16)[None, :, None]
+ rgb = ends[:, :1] * (1.0 - along) + ends[:, 1:] * along
+ rgb[0] = 128.0 # a flat block takes index 0 throughout
+ encoded = colour_blocks(rgb)
+ for block, source in zip(encoded, rgb):
+ assert np.abs(decode_colour_block(block) - source).max() < 32.0
+ assert struct.unpack("<I", bytes(encoded[0][4:8]))[0] == 0
+ alpha = np.tile(np.linspace(0.0, 255.0, 16), (2, 1))
+ alpha[1] = 77.0
+ coded = alpha_blocks(alpha)
+ assert coded[0][0] == 255 and coded[0][1] == 0 and coded[1][0] == coded[1][1] == 77
+ assert not coded[1][2:].any()
+ tiny = dds(np.zeros((8, 8, 4), np.float32), 8)
+ assert len(tiny) == 128 + 4 * 16 + 16 + 16 and tiny[:4] == b"DDS "
+ # A solid atlas: the chain runs to 8-pixel frames plus two levels for the loader to drop, and
+ # every level it keeps has its frames' rings empty and their insides full.
+ levels = mips(np.ones((64, 64, 4), np.float32), 32)
+ assert [level.shape[0] for level in levels] == [64, 32, 16, 8, 4]
+ for level, cell in zip(levels[:-THROWAWAY_LEVELS], (32, 16, 8)):
+ assert not level[::cell, :, 3].any() and not level[cell - 1::cell, :, 3].any()
+ assert level[cell // 2, cell // 2, 3] > 0.0
+
+
+def main():
+ selfcheck()
+ if sys.argv[1:2] == ["selfcheck"]:
+ return
+ billow, smooth = noise_volumes()
+ fire = atlas(fire_frame, FIRE_CELL, 4, billow, smooth)
+ smoke = atlas(smoke_frame, SMOKE_CELL, 4, billow, smooth)
+ for name, image, cell in ((FIRE_NAME, fire, FIRE_CELL), (SMOKE_NAME, smoke, SMOKE_CELL)):
+ path = os.path.normpath(os.path.join(OUT_FOLDER, name))
+ with open(path, "wb") as out:
+ out.write(dds(image, cell))
+ print(path)
+ if sys.argv[1:2] == ["preview"]:
+ from PIL import Image
+ folder = sys.argv[2]
+ # Both over a desert sand, the ground they are mostly seen against.
+ sand = np.array([0.62, 0.50, 0.33], np.float32)
+ for name, image in (("fire.png", fire), ("smoke.png", smoke)):
+ over = image[..., :3] * image[..., 3:] + sand * (1.0 - image[..., 3:])
+ Image.fromarray(np.uint8(over * 255.0 + 0.5)).save(os.path.join(folder, name))
+
+
+if __name__ == "__main__":
+ main()