Skip to content

perf(particlesys): Improve particle rendering performance using texture atlas - #3557

Open
stephanmeesters wants to merge 2 commits into
TheSuperHackers:mainfrom
stephanmeesters:perf/texture-atlas
Open

stephanmeesters wants to merge 2 commits into
TheSuperHackers:mainfrom
stephanmeesters:perf/texture-atlas

Conversation

@stephanmeesters

@stephanmeesters stephanmeesters commented Oct 18, 2026 •

Copy link
Copy Markdown

Merge by rebase

  • Adjust sorting renderer to draw multiple triangles in the same call if render state matches (same texture, same blending mode, etc).
  • Adjust ParticleSys to use the new texture atlas. Introduce a shared blending mode with which we can draw both alpha and additive particles. This requires a premultiplied alpha texture in the atlas.
  • The output UV data structure of the texture atlas was changed to RectClass as its a more natural fit.

Adds 77% performance to a busy scene. Number of draw calls reduced from 3161 to 717.

atlas

AI disclosure

Claude helped in review.

Background info

Background explanations about the new shared blending mode, courtesy of Claude:

Details

Background: one blend mode for alpha and additive particles

A particle batch ends whenever the texture or the blend mode changes. The texture atlas solves the texture part. The blend mode remains, because alpha and additive particles blend differently:

Particle type Blend Result
Alpha SRC_ALPHA, ONE_MINUS_SRC_ALPHA $C_s \alpha_s + C_d (1 - \alpha_s)$
Additive ONE, ONE $C_s + C_d$

Here $C_s$ and $\alpha_s$ are the particle's color and alpha, and $C_d$ is the color already on screen.

Both types now use the premultiplied-alpha blend mode, ONE, ONE_MINUS_SRC_ALPHA:

$$C_{out} = C_s + C_d (1 - \alpha_s)$$

This gives either result, depending on what the particle sends:

  • Alpha: send the color premultiplied by alpha, $(C\alpha, \alpha)$. The result is $C\alpha + C_d (1 - \alpha)$, which is alpha blending.
  • Additive: send alpha 0, $(C, 0)$. The result is $C + C_d$, which is additive blending.

The difference between the two types now lives in the per-particle data instead of the blend state, so both can be drawn in the same batch.

The GPU multiplies the texture color by the vertex color. To get $C\alpha$, the texture is premultiplied when it's packed into the atlas, and the vertex color is premultiplied on the CPU. Their product is the premultiplied result. Additive particles keep their texture as is and set the vertex alpha to 0.

flowchart LR
  subgraph Alpha particle
    TA["Atlas texture<br/>premultiplied"] --> MA(("×"))
    VA["Vertex color<br/>premultiplied"] --> MA
  end
  subgraph Additive particle
    TB["Atlas texture<br/>as is"] --> MB(("×"))
    VB["Vertex color<br/>alpha = 0"] --> MB
  end
  MA -- "(Cα, α)" --> B["ONE, ONE_MINUS_SRC_ALPHA<br/>out = src + dst·(1 − α)"]
  MB -- "(C, 0)" --> B
Loading

Todo

  • Add the pull ID to the commit titles
  • Clean up the commits after review

@coderabbitai

This comment was marked as spam.

@stephanmeesters stephanmeesters added Major Severity: Minor < Major < Critical < Blocker Performance Is a performance concern Gen Relates to Generals ZH Relates to Zero Hour labels Oct 18, 2026
coderabbitai[bot]

This comment was marked as off-topic.

coderabbitai[bot]

This comment was marked as off-topic.

Ronnin2011 pushed a commit to Ronnin2011/GeneralsGameCode that referenced this pull request Nov 8, 2026
…ngles in one call; particles share a premultiplied texture atlas (port of TSH TheSuperHackers#3557).

Port of TheSuperHackers TheSuperHackers#3557 (draft, stephanmeesters, head 343008d). The pool's draw loop extends a draw while the
next triangle's node has the same render state (shader, material, textures, transforms; a lit material never merges):
nothing is reordered. Particle sprites go onto a texture atlas built at run time from the shipped textures (2304x2304
pages, 5 mips, padding by wrap / clamp, at most 4 pages, 2 packs a frame), and additive and alpha sprites share one
premultiplied blend (additive = alpha 0), so the depth-sorted stream stops alternating states.
Ours on it: <d3d9.h> in textureatlas.cpp; the depth-1 volume fix and the water-wake skip kept in W3DParticleSys.cpp;
the [DRAW] bucket tag on the merged draw.
A test with a 27-Comanche rocket salvo: sorted draws 5,199 -> ~2,700 | 86 -> ~111 fps.
@stephanmeesters
stephanmeesters marked this pull request as ready for review November 22, 2026 11:48
@greptile-apps

greptile-apps Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

Confidence Score: 5/5 · The PR appears safe to merge; no actionable defects were found.RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge; no actionable defects were found.

Summary

The PR packs regular particle textures into shared atlas pages and lets alpha and additive particles share a blend mode.

  • Particle systems share atlas textures and blend states.
  • The sorting renderer draws matching triangles together.

No actionable issues were found. Checks were limited to source code; the native game was not run.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Particle texture] --> B{Regular particle and not terrain-conforming?}
  B -->|No| C[Use original texture and blend mode]
  B -->|Yes| D{Atlas entry available?}
  D -->|No| C
  D -->|Yes| E[Use atlas page and particle UV rectangle]
  E --> F{Alpha or additive?}
  F -->|Yes| G[Use shared blend mode]
  F -->|No| H[Keep original blend mode]
  G --> I[Draw matching sorted triangles together]
  H --> I
Loading

Reviews (5) · Last reviewed commit: "perf(particlesys): Improve particle rend..." · Reviewed by Greptile

@stephanmeesters stephanmeesters added the Rendering Is Rendering related label Nov 23, 2026
@bobtista

Copy link
Copy Markdown

Since this rebases: both commit titles still end in (#) and need (#3557). The PR title also has a leading space, and the body has a typo, "strcture".

@CryoTheRenegade CryoTheRenegade left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Math looks good, what's the memory offset of TextureAtlasClass? By my napkin math, one page takes (4 × 2304² × 341/256) bytes, about 27 MiB. At MAX_PAGES = 4 that is about 108 MiB of video memory.

state->vertex_count);
// Draw the batch.
Apply_Render_State(start_node->sorting_state);
DX8Wrapper::Draw_Triangles((start - chunkOffset) * 3, end - start, 0, overlapping_vertex_count);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This call now always passes 0 and overlapping_vertex_count, so the assignment state->min_vertex_index=vertex_array_offset; at line 534 looks dead. Nothing reads it before the nodes are released at the end of the flush. Can we remove it?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed.

for (end = start + 1; end < chunkEnd; ++end)
{
SortingNodeStruct* node = overlapping_nodes[tis[end].idx];
if (node != start_node && !Same_Render_State(start_node->sorting_state, node->sorting_state))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

After sorting, triangles often alternate between nodes (A B A B ...). That means Same_Render_State repeats the same matrix memcmps for the same pair of nodes on every triangle. Caching the last matching node skips the repeats:

SortingNodeStruct* last_match = start_node;
for (end = start + 1; end < chunkEnd; ++end)
{
    SortingNodeStruct* node = overlapping_nodes[tis[end].idx];
    if (node == last_match)
        continue;
    if (!Same_Render_State(start_node->sorting_state, node->sorting_state))
        break;
    last_match = node;
}

@stephanmeesters stephanmeesters Nov 25, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't opt for this one, it adds complexity, and Same_Render_State is actually pretty quick.

There is very little benefit: with the new batching (mauller/ronin stuff in w3dparticles + now the texture atlas) performs its work it will combine many particles into a single node, so then it doesn't even call Same_Render_State that often.

@stephanmeesters

Copy link
Copy Markdown
Author

Math looks good, what's the memory offset of TextureAtlasClass? By my napkin math, one page takes (4 × 2304² × 341/256) bytes, about 27 MiB. At MAX_PAGES = 4 that is about 108 MiB of video memory.

Correct, but for the particle textures in the retail data we only need a single page, so that's not too bad.

@stephanmeesters stephanmeesters changed the title perf(particlesys): Improve particle rendering performance using texture atlas perf(particlesys): Improve particle rendering performance using texture atlas Nov 25, 2026

@CryoTheRenegade CryoTheRenegade left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct, but for the particle textures in the retail data we only need a single page, so that's not too bad.

Okie, LGTM after nits are fixed

stephanmeesters added a commit to stephanmeesters/GeneralsGameCode that referenced this pull request Nov 27, 2026
stephanmeesters added a commit to stephanmeesters/GeneralsGameCode that referenced this pull request Nov 27, 2026
@stephanmeesters

Copy link
Copy Markdown
Author

Since this rebases: both commit titles still end in (#) and need (#3557). The PR title also has a leading space, and the body has a typo, "strcture".

Done, commits cleaned up. This one is good to go, I think.

@CryoTheRenegade

Copy link
Copy Markdown

Needs rebase

Ronnin2011 pushed a commit to Ronnin2011/GeneralsGameCode that referenced this pull request Nov 27, 2026
tintinhamans keeps ronin-dx9 on his fork for this build: go-merge as pushed on 24/11 (ba731ee), joined to Generals
Online's re-cut history by a bridge (08d4899: go-merge's tree, parents ba731ee and 775163c), then GO's main
merged on top (cbfbb1d). From now on GO reaches go-merge through ronin-dx9. This merge has no conflicts.
New from GO (74 commits):
- the online game setup's options as a fixed grid that fits 1080p, the lobby's name, access and password edited from
  a pencil in the setup header, the map preview and lobby icons drawn as soft lit solids, the ban renamed keep out;
- the communicator reworked into a dock: a name pill, conversation tabs, lobby invites, unread counts;
- network hardening: out-of-range lobby slots, wrapped commands, disconnect votes and run-ahead rates are ignored or
  dropped instead of crashing the match;
- crash dumps go to the GenOnline folder (full dumps only in debug mode); the VC++ runtime check at launch is gone
  (the launcher installs it); deprecated online code removed, GenOnline names used, logout off the main thread;
- GO's changes in upstream-owned files sit behind GENONLINE, and upstream text and line endings are restored where
  they differed without a purpose.
New from upstream (9): the texture atlas in its final form (TheSuperHackers#3562), slim function comments in place of Westwood's
blocks (TheSuperHackers#3697), retail compatibility of the cliff state and version 4 polygon triggers (TheSuperHackers#3634), WorldBuilder null
checks (TheSuperHackers#3383), the unused ATL includes removed (TheSuperHackers#3711), MinGW-w64 and ccache CI (TheSuperHackers#3675, TheSuperHackers#3710, TheSuperHackers#3701).
tintinhamans' own: D3DX9 from the vcpkg port dxsdk-d3dx with its DLL copied next to the games (the June 2010 SDK is
the fallback); our RmlUi welcome and options screens follow GO's API (TearDownGenOnline; the last working route and
the local disconnect file are gone).
Checked before merging: every line go-merge added over GO's base is in the result (1,011 files), apart from GO's own
removals and the slimmed comment blocks. Our texture atlas, a port of upstream's TheSuperHackers#3557 from 08/11, stays as it was
plus TheSuperHackers#3562's guard that disables the atlas when a page cannot be made; streaks keep their atlas cells. Nine files now
hold a few of our lines inside GENONLINE branches, which a GO build compiles as before. The frame-rate fix 6995aac
stays: the menu cap and the per-frame limit remain removed.
GO renamed its data from GeneralsOnline to GenOnline, so this exe needs the data pack built from this tree
(GenOnline/tools/pack_genonline_data.py zerohour 2026.11.0); the launcher's 2026.11.0-rc.1-81 pack stops it at init.
Built and run in game through the GO launcher.
Ronnin2011 pushed a commit to Ronnin2011/GeneralsGameCode that referenced this pull request Nov 27, 2026
…rHackers#3562), so its particle half (TheSuperHackers#3557) merges cleanly.

Our atlas was a port of upstream's TheSuperHackers#3557 as it stood on 08/11; upstream finished the atlas itself as TheSuperHackers#3562. The two
atlas files are now TheSuperHackers#3562's text, with our one line kept: d3d9.h in place of d3d8.h. Find_Or_Insert, Pack_Texture and
Copy_To_Cell take the source texture by reference, the eviction check sits inline in Find_Or_Insert and the members
follow upstream's order; the behaviour is the same.
W3DParticleSys.cpp passes the texture by reference in its two Find_Or_Insert calls and keeps a particle system with no
texture off the atlas itself, the check the pointer form made inside the atlas. Streaks still take the atlas cell the
particle code hands them; streakRender.cpp and sortingrenderer.cpp are unchanged.
Upstream's TheSuperHackers#3557 (particles on the atlas, still open) calls Find_Or_Insert the same way.
Compiled with the build's Release settings before applying; built and run in game: particles, explosions and streaks
draw.
stephanmeesters added a commit to stephanmeesters/GeneralsGameCode that referenced this pull request Nov 28, 2026
@stephanmeesters

Copy link
Copy Markdown
Author

Rebased

@bobtista bobtista left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good to me. The blend math matches the old result for both particle types

Ronnin2011 pushed a commit to Ronnin2011/GeneralsGameCode that referenced this pull request Nov 29, 2026
…erHackers#3383)

Upstream TheSuperHackers/GeneralsGameCode up to 967a361 (9 commits, through TheSuperHackers#3383), the batch before bobtista's
renderer PRs TheSuperHackers#3421-TheSuperHackers#3424 (taken one at a time), with the DX9 side of their changes:
- The texture atlas in its final form (TheSuperHackers#3562): our port of the PR's earlier revision (TheSuperHackers#3557, 08/11) gives way to
  upstream's text with d3d9.h for d3d8.h, the same files as go-merge's 1d8306f. W3DParticleSys.cpp's two
  Find_Or_Insert calls pass the texture by reference and keep a particle system without a texture off the atlas.
  Dependencies/Utility lists the premultiply-alpha files as upstream does.
- Slim function comments in place of Westwood's blocks (TheSuperHackers#3697): hlod.cpp keeps the shadow pass's coarsest-LOD draw
  (s_ForceLowestLod); render2d.cpp keeps the fork's version and loses only the two header lines upstream removed.
- The unused ATL includes removed (TheSuperHackers#3711): atl_compat.h, pseh_compat.h, reactos-atl.cmake and PreRTS.h's include.
- Taken as they are: retail compatibility of the cliff state and version 4 polygon triggers (TheSuperHackers#3634), WorldBuilder
  null checks (TheSuperHackers#3383), MinGW-w64 and ccache CI (TheSuperHackers#3675, TheSuperHackers#3710, TheSuperHackers#3701).
Checked before merging: the merged tree configured and built in a scratch worktree (z_generals Release, 0 errors);
this commit's tree is that build's source.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Gen Relates to Generals Major Severity: Minor < Major < Critical < Blocker Performance Is a performance concern Rendering Is Rendering related ZH Relates to Zero Hour

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants