Repository navigation
feat(ww3d2): Implement texture atlas - #3562
Conversation
This comment was marked as spam.
This comment was marked as spam.
There was a problem hiding this comment.
Actionable comments posted: 4
ℹ️ Review info
⚙️ Run configuration
- Configuration used: Organization UI
- Review profile: CHILL
- Plan: Advanced
- Run ID:
292e8ca8-2b91-4248-b7a7-465257875006
📒 Files selected for processing: 15
Core/Libraries/Source/WWVegas/WW3D2/CMakeLists.txtCore/Libraries/Source/WWVegas/WW3D2/textureatlas.cppCore/Libraries/Source/WWVegas/WW3D2/textureatlas.hDependencies/Utility/CMakeLists.txtDependencies/Utility/Utility/premultiply_alpha.hDependencies/Utility/Utility/premultiply_alpha.inlDependencies/Utility/Utility/premultiply_alpha_sse2.inlDependencies/Utility/Utility/premultiply_alpha_x86asm.inlTests/Google/Core/CMakeLists.txtTests/Google/Core/Libraries/WWVegas/WW3D2/TextureAtlasTest.cppTests/Google/Dependencies/CMakeLists.txtTests/Google/Dependencies/Utility/premultiply_alpha_common.hTests/Google/Dependencies/Utility/premultiply_alpha_portable_test.cppTests/Google/Dependencies/Utility/premultiply_alpha_sse2_test.cppTests/Google/Dependencies/Utility/premultiply_alpha_x86asm_test.cpp
Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 2 remain after this review.
[Low impact] The latest changes appear safe to merge; they preserve eviction timing.
|
|
Is this a framework, or already applied in the game? |
Not yet applied, this is planned in #3557 for which this atlas is a prerequisite. 77% performance gain for the scene I tested. |
|
Is this meant to be titled as chore? |
Yes, in the end I went with chore because it adds the infrastructure needed for a follow-up |
| , PacksThisFrame(0) | ||
| {} | ||
|
|
||
| TextureClass* Find_Or_Insert(TextureClass* source, bool premultiply, Vector4& rect); // Gets the page holding the texture and its uv rectangle, packing the texture first if needed. |
There was a problem hiding this comment.
Do we also need a function for removing a texture class or do we only ever need to add? Do we throw away the atlas and rebuild it if one texture is no longer needed?
There was a problem hiding this comment.
For the use case of rendering particles the focus is on lazily packing all of the textures. All of these particle textures (84 textures according to a .big scan) combined can fit on a single texture atlas page, which is great for performance. One 2048x2048 page with mips is only 21.25 MiB vram so we could also bump up the resolution when needed.
We could do something like a LRU cache when the atlas is full, but practically the multiple pages should be able to fit anything, perhaps this can be done when there is ever a need for it.
There was a problem hiding this comment.
When will the Atlas be purged? On level unload or also when particles with some textures are no longer drawn? If the Atlas is never purging during level runtime, then Mods with many new particles textures can accumulate into the Atlas until it is full? What happens after it is full? And how can new textures kick out old ones?
There was a problem hiding this comment.
When will the Atlas be purged? On level unload or also when particles with some textures are no longer drawn?
This will be controlled by the owner of the atlas. For the particles I am using W3DParticleSystemManager::reset() to purge the atlas, so this happens on engine reset after each level, through GameEngine::resetSubsystems().
If the Atlas is never purging during level runtime, then Mods with many new particles textures can accumulate into the Atlas until it is full? What happens after it is full?
Correct, but in the worse case you would only miss out on the performance benefits for some of the particles. And we do have some leeway with the multiple pages that can be used.
And how can new textures kick out old ones?
Not possible right now, I suppose it could be situation-dependent so we could let the owner of the atlas control it, by purging the atlas when required?
I can take a stab at implementing some system for kicking out old textures. Right now, the code can be simple because textures can only be added at the end of a row, or added to a new row, or a new page. In this new situation it would have to look for holes on the page, and if a big texture comes in may need to purge multiple textures, and perhaps we then also need a defragmentation feature.
There was a problem hiding this comment.
My main concern here is that the accumulation of big amount of particles would leave them permanently in the Atlas during the level runtime. It is cool that all retail particles fit in one Atlas page, but we should at least anticipate and handle extreme excess so it causes no unexpected degradations in Mods that use higher numbers of particle textures.
There was a problem hiding this comment.
OK worked with Claude on this. The solution that was landed on: purge the oldest page in the atlas when it reaches the limit. This keeps the code simple (no looking for gaps, or defragmentation) and addresses the concern that some textures remain forever.
…age size for efficient packing
When a texture does not fit, the first lookup of the next frame empties the oldest page and reuses it as the newest one. Textures still drawn from it are packed again. Failed textures get another try. Co-Authored-By: Claude Opus 5.5 <[email protected]>
091bb67 to
0b74010
Compare
This should be a |
This comment was marked as resolved.
This comment was marked as resolved.
There was a problem hiding this comment.
There are suprisingly few tests for the atlas. Does this cover everything?
There was a problem hiding this comment.
No the trouble is that we need a graphics adapter to do a full test, but it is possible after merging #3597.
…442) * fix(targa): Validate header sizes when loading Targa images (TheSuperHackers#3572) * fix(dx8wrapper): Prevent undefined behavior when converting Vector4 colors (TheSuperHackers#3655) * fix(ww3d2): Prevent undefined behavior when writing dynamic vertices and reading screenshot pixels (TheSuperHackers#3671) * refactor(pathutil): Add ensureTrailingSeparatorInPath helper (TheSuperHackers#3444) * bugfix(max2w3d): Let the timecoded animation compression drop keys of slow rotations (TheSuperHackers#3679) The compression tests whether a rotation key can be rebuilt from its neighbours with Slerp and measures the angle to the original. Slerp interpolated linearly without normalizing when the neighbours were less than about 5.1 degrees apart. The shortened quaternion read as an error of about half that span, so with the default tolerance of 0.05 degrees, keys of bones rotating between about 0.05 and 2.5 degrees per frame were never dropped, while faster bones compressed normally. Slerp now interpolates linearly only below the threshold that WWMath's Slerp and the game's Fast_Slerp use. Measured with VC6 on 61-frame test tracks, a constant rotation of 0.1 to 2.5 degrees per frame now keeps 2 keys instead of 61, and an ease in/out over 30 degrees keeps 15 instead of 59. Fast rotations are unchanged. The compression checks a removed key only against its neighbours at the time of removal, as it does for translations. Slow rotations now reach that limit too: on the test tracks, the largest error at removed frames is about 0.1 to 0.16 degrees. * refactor(maxsdk): Read max.h and maxscrpt.h through wrappers that restore the clashing macros (TheSuperHackers#3679) The force included max_undef.h removed the VC6 override shim and PI for the whole file, so no header read after the Max SDK could use the shim. max_sdk.h and maxscrpt_sdk.h now hide both macros only while the Max SDK headers are read, and restore them afterwards. max_undef.h keeps WIN32_LEAN_AND_MEAN, which must be undone before any header includes Windows.h. The wrappers have no include guard, because max.h has none: each time it is read, it redefines assert through assert1.h as an assert that also checks in release builds, and the plugin relies on that. Both PI values are the same float. * bugfix(rawfile): Return the file position from RawFileClass::Raw_Seek again (TheSuperHackers#3679) Since the switch of RawFileClass to the C stdio API, Raw_Seek returned the result of fseek, which is 0 on success, instead of the position that SetFilePointer returned. Seek and Tell of RawFileClass and of the classes derived from it returned 0 as well. ChunkSaveClass keeps these positions to go back to a chunk header and to continue writing behind the chunk, so files it wrote through these classes were overwritten from the start. This broke W3DView's saves of emitters, LODs, aggregates and animations. ChunkLoadClass::Seek always failed, and WWAudio passed 0 to the seek callback of Miles, which W3DView uses to play sounds. Raw_Seek now returns the position after the seek again, or -1 on failure. The game reads its files through GameFileClass, which already returns the position, and does not use the result when it writes files through RawFileClass. * refactor(max2w3d): Replace pluglib's copies of WWLib and WWMath with WWLib and WWMath (TheSuperHackers#3679) max2w3d and pluglib now include the WWLib and WWMath headers and link core_wwvegas, plus core_wwstub for the memory pool and operator new hooks that WWLib's always.h declares. pluglib keeps only its 3ds Max helpers and the Max matrix variant of EulerAnglesClass. The returning forms of Slerp and Vector3::Cross_Product only exist in WWMath with ALLOW_TEMPORARIES, so their callers use the forms with an output parameter. The AABTree builder no longer needs its own WWASSERT. WWMath normalizes vectors with Inv_Sqrt_Legacy instead of 1/sqrt. Measured with VC6 over a million random vectors, 87% of the exported normals stay bit-identical and the others differ by 1 or 2 ulp. Slerp computes with WWMath::Acos and Sinf_Legacy, which changes the components of its results by at most 2.4e-7, measured over a million random pairs. The abstract classes of the plugin now take _purecall from WWLib instead of the C library, as in the other tools that use WWLib. It pulls in the CPU detection and the system timer, so loading the plugin detects the CPU and calls timeBeginPeriod(1). * refactor(max2w3d): Use WWMath's EulerAnglesClass (TheSuperHackers#3679) pluglib's EulerAnglesClass was WWMath's adapted to take a Max matrix. The two callers now convert the Max matrix into a Matrix3D with the new Convert_Max_Matrix, which keeps the layout the adapted class used, and use WWMath's EulerAnglesClass. WWMath computes the angles in float instead of double. Measured with VC6 over a million random rotations, 98.7% of the exported pivot Euler angles stay bit-identical, and none differs by more than 5e-10 radians. The game does not read them. * refactor(max2w3d): Replace the Targa class with WWLib's (TheSuperHackers#3679) max2w3d's copy of TARGA differed from WWLib's only in writing through the C runtime file functions instead of WWLib's file factory, and in fixes that WWLib has since received. The exporter writes its 16x16 texture of material colors through WWLib's class now, with the same bytes. * refactor(max2w3d): Use w3d_file.h and w3d_obsolete.h from WW3D2 (TheSuperHackers#3679) max2w3d's copies of the W3D format headers were older versions of the WW3D2 ones. The newer w3d_file.h adds chunks, structs and enum values and swaps the values of SORT_LEVEL_BIN1 and SORT_LEVEL_BIN3, none of which max2w3d uses, apart from five surface types that the material dialog now also offers: Water Permeable, Tiberium Water, Tiberium Water Permeable, Underwater Dirt and Underwater Tiberium Dirt. * refactor(max2w3d): Move the remaining pluglib files into max2w3d (TheSuperHackers#3679) Only max2w3d used pluglib's 3ds Max helpers, so they move into max2w3d unchanged and the core_pluglib target is removed. * fix: Fix map cache path slashes for non-Windows (TheSuperHackers#3107) * bugfix(specialpower): Fix special powers never becoming ready on constructed structures (TheSuperHackers#3666) Non-retail builds started every special power of an object that is created under construction with a ready frame of 0xFFFFFFFF, so that it could not be used before the construction was finished. Only a SpecialPowerCreate module started the recharge on build completion, so the powers of structures without one, such as the Battle Plans and the CIA Intelligence of the America Strategy Center, never became ready. The ready frame now starts at 0 as in retail. The new SpecialPowerModule::canDoSpecialPower() tells whether the object can use its special power now, regardless of the timer. In non-retail builds it is false while the object is disabled, the power is paused, or the object is under construction, and isReady() requires it. This keeps shared powers unavailable on a structure that cannot use them, and stops the skirmish AI from firing a superweapon from a structure that is still being built. getPercentReady() now reports 1 only when isReady() is true, so that ActionManager no longer accepts a command that the special power then refuses. A power under construction reports 0, a paused power keeps the percent it was paused at, and any other power that is not ready stays below 1. * bugfix(specialpower): Prevent special powers from executing on structures under construction (TheSuperHackers#3666) Scripts and forced command button commands execute a special power without asking isReady(), so they could still use the special power of a structure under construction. In Zero Hour this dereferenced the special power module of MissileLauncherBuildingUpdate before its first update had looked it up. The special power entry points of SpecialPowerModule now refuse when canDoSpecialPower() is false. The powers that can sit on a structure and act after the base class call check it as well: OCLSpecialPower, SpyVisionSpecialPower, BaikonurLaunchPower, CashHackSpecialPower, DefectorSpecialPower and, in Zero Hour, FireWeaponPower. In non-retail builds this also stops these powers from creating their effect while the power is paused, for example the scan of a GLA Radar Van before its upgrade, which the base class already refused. MissileLauncherBuildingUpdate no longer crashes while it does not know its special power module yet. The retail escape path for an unready MissileLauncherBuildingUpdate now also stops OCLSpecialPower::doSpecialPower() from creating its object creation list, as it already did for doSpecialPowerAtLocation(). * bugfix(missilelauncherbuildingupdate): Look up the special power module when the object is created (TheSuperHackers#3666) MissileLauncherBuildingUpdate looked up its special power module only in its first update after construction. A special power fired before that, by a script on the frame the launcher is created or right after a save game is loaded, found no module. This no longer crashes, but in non-retail builds the missile was launched without the door sequence. In non-retail builds the module is now looked up in onObjectCreated(), once all modules of the object exist. Retail-compatible builds keep the lazy lookup in update() and the escape path that refuses the launch. * bugfix(watertracks): Restore shore waves when loading saved games (TheSuperHackers#3493) * refactor: Remove unused embedded web browser (TheSuperHackers#3691) * refactor(ww3d2): Route lights and fog via Renderer (TheSuperHackers#3420) * refactor(ww3d2): Remove the unused black and white shadow renderer (TheSuperHackers#3670) TexProjectClass only rendered with BWRenderClass inside an #if 0 block, so SpecialRenderInfoClass::BWRenderer was always null and MeshModelClass::Shadow_Render returned without drawing. * refactor(filesystem): Rename appendPathSeparator to ensureTrailingPathSeparatorInPath (TheSuperHackers#3694) * build(max2w3d): Fix the compile error from passing no image size to Targa::SetImage (TheSuperHackers#3696) * refactor: Replace _isnan and _finite with std::isnan and std::isfinite (TheSuperHackers#3686) _isnan and _finite are MSVC CRT functions from <float.h>. Use the standard functions instead. The new cmath_adapter.h gives VC6 std::isnan and std::isfinite built on _isnan and _finite, because neither VC6 nor STLport 4.5.3 has them. * ci(build): Keep precompiled headers when caching with ccache (TheSuperHackers#3701) * ci(build): Cache the MinGW-w64 toolchain packages (TheSuperHackers#3710) * feat(ww3d2): Implement texture atlas (TheSuperHackers#3562) * bugfix(worldheightmap): Restore Generals retail compatibility of the cliff state (TheSuperHackers#3634) Merging the Height Map code gave Generals the cliff state rows of Zero Hour, which have (width+7)/8 bytes. Retail Generals keeps them in rows of (width+1)/8 bytes, which are too short for the last cells of a row when the map width modulo 8 is 2 to 6. These cells share their bit with the first cells of the next row. Since the merge they read as no cliff instead, so the pathfinder classifies them differently and retail Generals replays on such maps mismatch. Retail Generals also reads the cliff bits of version 8 maps, which come from Zero Hour, in rows of (width+1)/8 bytes, while Zero Hour writes them in rows of (width+7)/8 bytes. When the map width modulo 8 is 1 to 6, each row in the file is one byte longer than the row retail reads, so retail reads each row one byte further off than the row before. A retail compatible Generals now restores the cliff state of retail after loading. For version 7 maps the last cells of a row take the stored bits of the first cells of the next row. For older maps, whose flags are computed from the heights column by column, the first cells of the next row take the flags of the last cells, which retail computes last. For version 8 maps the bits are regrouped into the rows that retail reads. Without retail compatibility, Generals and Zero Hour compute the flags of these cells from the heights for version 7 maps, because the file has no bits for them. Steep slopes in the last columns of such maps are no longer passable for ground units. Version 8 maps without retail compatibility and a retail compatible Zero Hour keep the cliff state as before. * bugfix(polygontrigger): Restore Generals retail compatibility of version 4 polygon triggers (TheSuperHackers#3634) Merging the map code gave Generals the layer name that Zero Hour stores in version 4 polygon triggers. Retail Generals does not know it and reads the following values of such triggers from the wrong bytes. With an empty layer name, the first trigger is never a water area, and reading its points runs past the end of the file, so no further triggers are read. Since the merge, Generals reads the water areas of Zero Hour maps correctly, so retail Generals replays on such maps mismatch. A retail compatible Generals now skips the layer name again and reads these triggers like retail. In debug builds this raises an assert for each value read past the end of the chunk. Without retail compatibility, and in Zero Hour, the layer name is read as before. * refactor: Replace Westwood function comment blocks with slim comments (TheSuperHackers#3697) The Westwood comment blocks above the functions are replaced by slim comments. Descriptions are kept where they add to the function name. INPUT and OUTPUT entries are dropped unless they say something the signature does not, such as units or valid ranges. History entries are dropped, except for notes on how a function behaves today and the TheSuperHackers entries, which keep their keyword. The Functions lists in the file headers are removed as well, since they repeat the function descriptions. * refactor: Remove the unused ATL includes (TheSuperHackers#3711) * ci(build): Remove the Wine and widl install step from MinGW-w64 jobs (TheSuperHackers#3675) * fix(worldbuilder): Prevent null dereferences and simplify name restore in object editing (TheSuperHackers#3383) * fix(build): restore winsock2 include in NetworkMesh and undef PAGE_SIZE in textureatlas * fix(build): use winsock2.h in udp.h for Windows compatibility * fix(build): include winsock2.h before windows.h in PreRTS.h * docs(worklog): remove leftover merge marker in 2026-11-DIARY.md --------- Co-authored-by: Bobby Battista <[email protected]> Co-authored-by: Jacob Lane Ledbetter <[email protected]> Co-authored-by: xezon <[email protected]> Co-authored-by: Omar Aglan <[email protected]> Co-authored-by: stm <[email protected]>
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.
…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.
…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.
TextureAtlasClassin WW3D2. (around 350 LoC)premultiply_alphain Dependencies. Multiple versions: portable, SSE2, VC6 compat.A texture atlas is implemented for speeding up rendering. It can be used with variably sized (but power of two) textures and supports mip-mapping. New textures are added using
Find_Or_Insert. Owners of the atlas are responsible for cleaning it up usingReset. Atlas pages are 2048x2048 and multiple pages can be created on demand.A special feature is to store the textures in premultiplied form which is necessary for rendering particles efficiently using this atlas. This will be done in #3557.
To keep stutters to a minimum, the number of textures that can be added per frame has a limiter, and the premultiply alpha step was optimized using SSE2. Cost measured using Tracy came out to around a maximum of 0.5ms per frame. It was investigated whether we can run the texture adding in a background thread but that does not appear to be feasible, the expensive D3DX copy calls (for DXT textures) are required to run on the render thread.
Unit tests for testing texture packing were created but these require a DX device and won't run on the CI so are omitted here. The tests added are for the helper functions.
AI was used during implementing and testing.
Example of filled atlas page (with premultiplied alpha variants of each for illustration)