Zero Hour rebuilt from EA's source: x64, Direct3D 11, VS2022/CMake, ~60 original bugs fixed, an AI that builds a base. Bring your own game.
C++ cmakecnccommand-and-conquercppdirectx11game-enginegame-preservationgeneralsrtssage-enginex64zero-hour
perf(w3ddevice): reuse static water mesh and shoreline work
Olcay Seyganfcd05658ffac
diff --git a/GeneralsMD/Code/BuildFingerprint.manifest b/GeneralsMD/Code/BuildFingerprint.manifestindex 82c8a1cbe..bf8fed92a 100644--- a/GeneralsMD/Code/BuildFingerprint.manifest+++ b/GeneralsMD/Code/BuildFingerprint.manifest@@ -2304,13 +2304,18 @@ Libraries/Include/Platform/WaterObstacleIndex.hLibraries/Include/Platform/WaterOpticalContext.hLibraries/Include/Platform/WaterOpticalModel.hLibraries/Include/Platform/WaterPerformanceSettings.h+Libraries/Include/Platform/WaterPreparedMeshCache.hLibraries/Include/Platform/WaterProjectedMesh.h+Libraries/Include/Platform/WaterProjectedMeshCache.h+Libraries/Include/Platform/WaterProjectedSampleCache.h+Libraries/Include/Platform/WaterRenderCaches.hLibraries/Include/Platform/WaterScreenReflection.hLibraries/Include/Platform/WaterShoreFoam.hLibraries/Include/Platform/WaterShoreHistory.hLibraries/Include/Platform/WaterShoreOverlay.hLibraries/Include/Platform/WaterShoreSource.hLibraries/Include/Platform/WaterShoreSupport.h+Libraries/Include/Platform/WaterStaticSampleCache.hLibraries/Include/Platform/WaterSurfaceModel.hLibraries/Include/Platform/WaterTerrainCulling.hLibraries/Include/Platform/WaterVesselMotion.h@@ -3330,7 +3335,17 @@ RTS.dswStubs/NullAudioManager.hTests/WaterBowShoulderTest.hTests/WaterHullContactFoamTest.h+Tests/WaterPreparedViewTest.h+Tests/WaterProjectedSampleCacheTest.h+Tests/WaterShoreHistoryReference.h+Tests/WaterShorePreparedTest.h+Tests/WaterShoreSourcePerfTest.h+Tests/WaterShoreSourceReference.h+Tests/WaterTerrainCullingReference.hTests/WaterTerrainCullingTest.h+Tests/WaterTerrainProofCacheTest.h+Tests/WaterWaveCageCopyTest.h+Tests/WaterWaveCageMeshReference.hTests/WaterWaveCageTest.hTests/arch_diff/arch_probe.cppTests/arch_diff/known_differences.txtdiff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/TerrainVisual.h b/GeneralsMD/Code/GameEngine/Include/GameClient/TerrainVisual.hindex 6e8a504e9..7c1dc7777 100644--- a/GeneralsMD/Code/GameEngine/Include/GameClient/TerrainVisual.h+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/TerrainVisual.h@@ -224,6 +224,8 @@ public:virtual void update( void );virtual Bool load( AsciiString filename );+ // Called after final map/save inputs are installed, before gameplay presentation.+ virtual void prewarmMapRenderData( void ) {}/// get color of texture on the terrain at location specifiedvirtual void getTerrainColorAt( Real x, Real y, RGBColor *pColor ) = 0;diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameState.cppindex 8fc627637..4bdfc793e 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/SaveGame/GameState.cpp@@ -1725,6 +1725,9 @@ void GameState::gameStatePostProcessLoad( void )ThePartitionManager->update();ThePartitionManager->stopKeepingCellsFromSave();+ // Prepare immutable presentation data after every saved map input is final.+ if (TheTerrainVisual) TheTerrainVisual->prewarmMapRenderData();+// last, so nothing the load did can draw from the stream after it is put backTheGameLogic->restoreLoadedRandomState();diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cppindex fe7b710e1..05e74acf4 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp@@ -2389,6 +2389,9 @@ void GameLogic::startNewGame( Bool loadingSaveGame )}}+ // Saved terrain and triggers arrive later; saves prepare at postprocess load.+ if (!loadingSaveGame && TheTerrainVisual) TheTerrainVisual->prewarmMapRenderData();+updateLoadProgress(LOAD_PROGRESS_END);if(isInMultiplayerGame() && TheNetwork)diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DTerrainVisual.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DTerrainVisual.hindex ea94ff88c..c539ec1c0 100644--- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DTerrainVisual.h+++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DTerrainVisual.h@@ -64,6 +64,7 @@ public:virtual void update( void );virtual Bool load( AsciiString filename );+ virtual void prewarmMapRenderData( void );void getTerrainColorAt( Real x, Real y, RGBColor *pColor );diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DWater.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DWater.hindex 6a248fe55..24318870c 100644--- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DWater.h+++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DWater.h@@ -56,6 +56,7 @@#include "Platform/WaterObstacleIndex.h"#include "Platform/WaterHullModel.h"#include "Platform/WaterHullPoseCache.h"+#include "Platform/WaterRenderCaches.h"#include "Platform/WaterVesselMotion.h"#include "Platform/WaterFoamHistory.h"#include "Platform/WaterShoreSource.h"@@ -129,6 +130,7 @@ public:void update( void ); ///< update phase of the water#if ZH_MODERN_WATERvoid takeReadsForRender(void);+ void prewarmStaticMapData(void);#endifvoid enableWaterGrid(Bool state); ///< used to active custom water for special maps. (i.e DAM). The grid is TerrainLogic's WaterGrid; this builds its buffersvoid updateMapOverrides(void); ///< used to update any map specific map overrides for water appearance.@@ -237,6 +239,7 @@ protected:Bool m_modernProjectedCacheEnabled=TRUE;struct ModernProjectedSample { Real height,damping,obstacle,hullFreeObstacle,offshore,fftDamping,exposure; };std::unordered_map<WaterProjectedMesh::WorldKey,ModernProjectedSample,WaterProjectedMesh::WorldHash> m_modernProjectedSamples;+ WaterRenderCaches::Cache<ModernProjectedSample> m_modernRenderCaches;Vector3 m_modernCamera;CameraClass *m_modernRenderCamera = NULL;struct ModernWaterObstacle {@@ -299,6 +302,12 @@ protected:WaterShoreSource::Batch m_modernShoreSource;uint64_t m_modernShoreRevision=1, m_modernShoreAttempted=0;Bool m_modernShoreReady=FALSE;+ struct ModernShorePreparation {+ uint64_t revision=0;+ WaterShoreHistory::BuildResult result=WaterShoreHistory::BuildResult::Invalid;+ WaterShoreSource::Batch source;+ WaterShoreHistory::Topology topology;+ } m_modernShorePreparation;unsigned m_modernFoamDrawFrame=~0u;std::vector<UnsignedInt> m_modernFoamDrawObjectIDs;struct ModernFoamTexture {@@ -308,6 +317,9 @@ protected:unsigned channels=0; // bit0 vessel RGB, bit1 coast A, bit2 second direction tileunsigned textureWidth=0,textureHeight=0;Bool valid=FALSE;+ WaterShoreHistory::RasterLookup shoreLookup;+ std::vector<float> shoreBreakup;+ uint64_t shoreBreakupBuild=0;};std::vector<ModernFoamTexture> m_modernFoamTextures;@@ -390,13 +402,15 @@ protected:void bindModernWaterFoam(Real level,Bool river);void invalidateModernWaterShore(void);void updateModernWaterShore(void);+ void prepareModernWaterShore(void);+ void clearModernWaterRenderCaches(void);Real modernHullDamping(Real x,Real y,Real level) const;Bool modernHasHull(UnsignedInt objectID) const;void clearModernWaterOpticalTextures(void);void refreshModernWaterOpticalPolygons(void);TextureClass *modernWaterOpticalTexture(Real level);void drawModernWaterPatch(const Vector3 points[4], Bool river, Real riverStart = 0, Real riverEnd = 1);- Real modernWaterDamping(Real x, Real y, Real z, Real offshore=0.0f, Real *obstacleAttenuation=NULL, Real *terrainDepth=NULL, Real *hullFreeDamping=NULL, Real *hullFreeObstacle=NULL) const;+ Real modernWaterDamping(Real x, Real y, Real z, Real offshore=0.0f, Real *obstacleAttenuation=NULL, Real *terrainDepth=NULL, Real *hullFreeDamping=NULL, Real *hullFreeObstacle=NULL, const Real *cachedTerrain=NULL) const;Bool m_renderingMirror = FALSE; ///< prevents a water draw sampling the mirror being writtenvoid cleanupJbaWaterShader(void);diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlPipelineCache.cpp b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlPipelineCache.cppindex 35f28a4a9..a6f575045 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlPipelineCache.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlPipelineCache.cpp@@ -491,10 +491,8 @@ bool Sdl_Sampler_Description(const RenderUInt32 ss[14], void *create_info, std::SdlSamplerCache::SdlSamplerCache(SDL_GPUDevice *device) :Device(device),- LastSampler(NULL),- HaveLast(false)+ RecentSize(0), LastRecent(0), NextRecent(0), TableLookups(0){- memset(&LastKey, 0, sizeof(LastKey));}SdlSamplerCache::~SdlSamplerCache()@@ -508,27 +506,41 @@ SdlSamplerCache::~SdlSamplerCache()size_t SdlSamplerCache::KeyHash::operator()(const Key &key) const{- // FNV-1a over the bytes, as SdlProgramCache's ByBytes does.- const unsigned char *bytes = reinterpret_cast<const unsigned char *>(key.States);+ // This is an in-process hash, not a persisted identifier. Mix whole state words+ // instead of a 56-byte multiply chain; equality still checks every state bit.uint64_t hash = 1469598103934665603ull;- for (size_t i = 0; i < sizeof(key.States); ++i) {- hash = (hash ^ bytes[i]) * 1099511628211ull;+ for (RenderUInt32 state : key.States) {+ hash = (hash ^ state) * 1099511628211ull;}return (size_t)hash;}+void SdlSamplerCache::Remember(const Key &key, SDL_GPUSampler *sampler)+{+ Recent[NextRecent] = {key, sampler};+ LastRecent = NextRecent;+ NextRecent = (NextRecent + 1) % RecentCount;+ if (RecentSize < RecentCount)+ ++RecentSize;+}+SDL_GPUSampler *SdlSamplerCache::Sampler(const RenderUInt32 sampler_states[14]){Key key;memcpy(key.States, sampler_states, sizeof(key.States));- if (HaveLast && key == LastKey) {- return LastSampler;+ if (RecentSize && key == Recent[LastRecent].key) {+ return Recent[LastRecent].sampler;}+ for (unsigned i = 0; i < RecentSize; ++i) {+ if (i != LastRecent && key == Recent[i].key) {+ LastRecent = i;+ return Recent[i].sampler;+ }+ }+ ++TableLookups;auto existing = Samplers.find(key);if (existing != Samplers.end()) {- LastKey = key;- LastSampler = existing->second;- HaveLast = true;+ Remember(key, existing->second);return existing->second;}SDL_GPUSamplerCreateInfo info;@@ -549,8 +561,6 @@ SDL_GPUSampler *SdlSamplerCache::Sampler(const RenderUInt32 sampler_states[14])fprintf(stderr, "SdlSamplerCache: a sampler refused: %s\n", refusal.c_str());}Samplers[key] = sampler;- LastKey = key;- LastSampler = sampler;- HaveLast = true;+ Remember(key, sampler);return sampler;}diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlPipelineCache.h b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlPipelineCache.hindex 752190757..d72cfa6b7 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlPipelineCache.h+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlPipelineCache.h@@ -133,9 +133,12 @@ public:/// Null for a refusal (Refusal() says why) or when the device refuses it.SDL_GPUSampler *Sampler(const RenderUInt32 sampler_states[14]);const std::string &Refusal() const { return LastRefusal; }+ size_t Table_Lookups() const {+ return TableLookups;+ }private:- /// A stage's 14 sampler states, compared and hashed by their bytes: PERF1 found the std::string key+ /// A stage's 14 sampler states, compared exactly: PERF1 found the std::string key/// this replaced (56 bytes, past the string's inline buffer) allocating on every lookup, 8 slots a draw.struct Key{@@ -148,9 +151,17 @@ private:};SDL_GPUDevice *Device;std::unordered_map<Key, SDL_GPUSampler *, KeyHash> Samplers;- Key LastKey; ///< the last lookup's, for a draw that samples as the one before did- SDL_GPUSampler *LastSampler;- bool HaveLast;+ // Consecutive stages often alternate a few settings. Retain the last-hit shortcut,+ // with a bounded ring for the other recent keys, including cached refusals.+ static constexpr unsigned RecentCount = 4;+ struct RecentEntry {+ Key key;+ SDL_GPUSampler *sampler;+ };+ RecentEntry Recent[RecentCount];+ unsigned RecentSize, LastRecent, NextRecent;+ size_t TableLookups;+ void Remember(const Key &key, SDL_GPUSampler *sampler);std::string LastRefusal;};diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainVisual.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainVisual.cppindex 7b3c5c446..dd39f024b 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainVisual.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainVisual.cpp@@ -708,6 +708,14 @@ Bool W3DTerrainVisual::load( AsciiString filename )} // end load+// Final terrain and authored/saved water are available at this hook.+void W3DTerrainVisual::prewarmMapRenderData( void )+{+ if (!TheGlobalData || TheGlobalData->m_noRenderDevice || !m_waterRenderObject ||+ !TheGameLogic || TheGameLogic->isInShellGame()) return;+ m_waterRenderObject->prewarmStaticMapData();+}+// ------------------------------------------------------------------------------------------------// ------------------------------------------------------------------------------------------------void W3DTerrainVisual::enableWaterGrid( Bool enable )diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cppindex 8ed945ae3..d7a1883c9 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp@@ -884,10 +884,51 @@ void WaterRenderObjClass::invalidateModernWaterShore(void){m_modernShoreHistory.Clear();m_modernShoreSource.Clear();+ m_modernShorePreparation=ModernShorePreparation();m_modernShoreReady = FALSE;if (++m_modernShoreRevision == 0) m_modernShoreRevision = 1;m_modernShoreAttempted = 0;- for (ModernFoamTexture &field : m_modernFoamTextures) field.valid = FALSE;+ for (ModernFoamTexture &field : m_modernFoamTextures) {+ field.valid=FALSE;+ field.shoreLookup.Clear();+ field.shoreBreakup.clear();+ field.shoreBreakupBuild=0;+ }+}++void WaterRenderObjClass::prepareModernWaterShore(void)+{+#if ZH_MODERN_WATER+ if (m_modernShorePreparation.revision==m_modernShoreRevision) return;+ ModernShorePreparation prepared;+ prepared.revision=m_modernShoreRevision;+ std::vector<double> levels;+ for (const auto &polygon : m_modernOpticalPolygons) {+ if (polygon.points.size() < 3) continue;+ const double level = polygon.points[0].z;+ Bool flat = TRUE;+ for (const auto &p : polygon.points) flat = flat && fabs(double(p.z) - level) < .01;+ if (flat && std::find(levels.begin(), levels.end(), level) == levels.end()) levels.push_back(level);+ }+ std::sort(levels.begin(), levels.end());++ if (m_modernOpticalPolygonsValid && !m_modernHeights.empty() && levels.size() <= WaterShoreHistory::MaxLevels) {+ // Complete every level before collecting pointers: texture-vector reallocation cannot+ // invalidate a source field, and camera order cannot choose the retained history levels.+ for (double level : levels) modernWaterOpticalTexture(Real(level));+ std::vector<WaterShoreSource::Level> fields;+ for (double level : levels) for (const auto &field : m_modernOpticalTextures)+ if (field.level == level) {+ fields.push_back({level, &field.shoreContext});+ break;+ }+ if (fields.size() == levels.size()) prepared.result = prepared.source.Build(m_modernHeights.data(), m_modernHeightWidth,+ m_modernHeightHeight, m_modernHeightBorder, MAP_XY_FACTOR, MAP_HEIGHT_SCALE, m_modernOpticalPolygons, fields);+ if (prepared.result==WaterShoreHistory::BuildResult::Ready)+ prepared.result=prepared.topology.Build(prepared.source.Grid(),prepared.source.Cells());+ }+ m_modernShorePreparation=std::move(prepared);+#endif}void WaterRenderObjClass::updateModernWaterShore(void)@@ -896,40 +937,54 @@ void WaterRenderObjClass::updateModernWaterShore(void)if (m_modernShoreAttempted != m_modernShoreRevision) {m_modernShoreAttempted = m_modernShoreRevision;m_modernShoreReady = FALSE;- std::vector<double> levels;- for (const auto &polygon : m_modernOpticalPolygons) {- if (polygon.points.size() < 3) continue;- const double level = polygon.points[0].z;- Bool flat = TRUE;- for (const auto &p : polygon.points) flat = flat && fabs(double(p.z) - level) < .01;- if (flat && std::find(levels.begin(), levels.end(), level) == levels.end()) levels.push_back(level);- }- std::sort(levels.begin(), levels.end());- WaterShoreHistory::BuildResult result = WaterShoreHistory::BuildResult::Invalid;- if (m_modernOpticalPolygonsValid && !m_modernHeights.empty() && levels.size() <= WaterShoreHistory::MaxLevels) {- // Complete every level before collecting pointers: texture-vector reallocation cannot- // invalidate a source field, and camera order cannot choose the retained history levels.- for (double level : levels) modernWaterOpticalTexture(Real(level));- std::vector<WaterShoreSource::Level> fields;- for (double level : levels) for (const auto &field : m_modernOpticalTextures)- if (field.level == level) {- fields.push_back({level, &field.shoreContext});- break;- }- WaterShoreSource::Batch candidate;- if (fields.size() == levels.size()) result = candidate.Build(m_modernHeights.data(), m_modernHeightWidth,- m_modernHeightHeight, m_modernHeightBorder, MAP_XY_FACTOR, MAP_HEIGHT_SCALE, m_modernOpticalPolygons, fields);- if (result == WaterShoreHistory::BuildResult::Ready) {+ if (WaterScreenReflection::Supported()) {+ prepareModernWaterShore();+ ModernShorePreparation &prepared=m_modernShorePreparation;+ if (prepared.result==WaterShoreHistory::BuildResult::Ready) {WaterShoreHistory::Parameters settings;- settings.maximumRate = WaterShoreFoam::MaximumRate;- result = m_modernShoreHistory.Install(candidate.Grid(), candidate.Cells(), m_modernShoreRevision, m_modernWaveTime, settings);+ settings.maximumRate=WaterShoreFoam::MaximumRate;+ if (m_modernShoreHistory.InstallPrepared(std::move(prepared.topology),m_modernShoreRevision,+ m_modernWaveTime,settings)==WaterShoreHistory::BuildResult::Ready) {+ m_modernShoreSource=std::move(prepared.source);+ m_modernShoreReady=TRUE;+ }+ }+ m_modernShorePreparation=ModernShorePreparation();+ } else {+ std::vector<double> levels;+ for (const auto &polygon : m_modernOpticalPolygons) {+ if (polygon.points.size() < 3) continue;+ const double level = polygon.points[0].z;+ Bool flat = TRUE;+ for (const auto &p : polygon.points) flat = flat && fabs(double(p.z) - level) < .01;+ if (flat && std::find(levels.begin(), levels.end(), level) == levels.end()) levels.push_back(level);+ }+ std::sort(levels.begin(), levels.end());+ WaterShoreHistory::BuildResult result = WaterShoreHistory::BuildResult::Invalid;+ if (m_modernOpticalPolygonsValid && !m_modernHeights.empty() && levels.size() <= WaterShoreHistory::MaxLevels) {+ // Complete every level before collecting pointers: texture-vector reallocation cannot+ // invalidate a source field, and camera order cannot choose the retained history levels.+ for (double level : levels) modernWaterOpticalTexture(Real(level));+ std::vector<WaterShoreSource::Level> fields;+ for (double level : levels) for (const auto &field : m_modernOpticalTextures)+ if (field.level == level) {+ fields.push_back({level, &field.shoreContext});+ break;+ }+ WaterShoreSource::Batch candidate;+ if (fields.size() == levels.size()) result = candidate.Build(m_modernHeights.data(), m_modernHeightWidth,+ m_modernHeightHeight, m_modernHeightBorder, MAP_XY_FACTOR, MAP_HEIGHT_SCALE, m_modernOpticalPolygons, fields);if (result == WaterShoreHistory::BuildResult::Ready) {- m_modernShoreSource = std::move(candidate);- m_modernShoreReady = TRUE;+ WaterShoreHistory::Parameters settings;+ settings.maximumRate = WaterShoreFoam::MaximumRate;+ result = m_modernShoreHistory.Install(candidate.Grid(), candidate.Cells(), m_modernShoreRevision, m_modernWaveTime, settings);+ if (result == WaterShoreHistory::BuildResult::Ready) {+ m_modernShoreSource = std::move(candidate);+ m_modernShoreReady = TRUE;+ }}}}-}if (m_modernShoreReady && m_modernShoreHistory.ValidFor(m_modernShoreRevision)) {const auto result = m_modernShoreHistory.Advance(m_modernWaveTime, m_modernShoreSource);@@ -1031,9 +1086,26 @@ void WaterRenderObjClass::bindModernWaterFoam(Real level, Bool river)const auto &states = m_modernShoreHistory.Preview(m_modernShoreSource);const WaterShoreHistory::Mapping shoreMap = {map.originX, map.originY, map.widthWorld, map.heightWorld,map.widthPixels, map.heightPixels};- auto coverage = WaterShoreSource::Coverage;- atlas = WaterShoreHistory::RasterizeAlpha(m_modernShoreHistory.Domain(), states, shoreMap, level, m_modernWaveTime,- coverage, pixels, m_modernShoreSource.Support());+ if (WaterScreenReflection::Supported()) {+ atlas=field.shoreLookup.Prepare(m_modernShoreHistory.Domain(),shoreMap,level,m_modernShoreRevision,m_modernShoreSource.Support());+ if (atlas) {+ if (field.shoreBreakupBuild!=field.shoreLookup.BuildCount()) {+ field.shoreBreakup.assign(pixels.size(),0);+ field.shoreLookup.ForEachSample([&](size_t n,double x,double y) {+ field.shoreBreakup[n]=float(WaterShoreSource::SpatialBreakup(x,y));+ });+ field.shoreBreakupBuild=field.shoreLookup.BuildCount();+ }+ auto coverage=[&](const WaterShoreHistory::State &state,double,double,double,size_t n) {+ return WaterShoreSource::CoverageFromBreakup(state,field.shoreBreakup[n]);+ };+ atlas=field.shoreLookup.Rasterize(states,m_modernWaveTime,coverage,pixels);+ }+ } else {+ auto coverage = WaterShoreSource::Coverage;+ atlas = WaterShoreHistory::RasterizeAlpha(m_modernShoreHistory.Domain(), states, shoreMap, level, m_modernWaveTime,+ coverage, pixels, m_modernShoreSource.Support());+ }}if (atlas) {// Merge coastal alpha before appending the direction tile: its rasterizer@@ -1108,6 +1180,7 @@ void WaterRenderObjClass::synchronizeWaterStyle(void)// Apply before any reflected or main-scene water draw. Existing recorded draws keep// their immutable GPU programs; both styles have separate program/pipeline cache keys.m_useModernWater = modern;+ clearModernWaterRenderCaches();registerWaterStyleShaders();clearModernWaterFoam();clearModernWaterHulls();@@ -1346,8 +1419,58 @@ void WaterRenderObjClass::updateModernWaterTextures(void)#endif}+void WaterRenderObjClass::prewarmStaticMapData(void)+{+#if ZH_MODERN_WATER+ if (!WaterScreenReflection::Supported() || !TheGlobalData || TheGlobalData->m_noRenderDevice ||+ !TheGameLogic || TheGameLogic->isInShellGame() || !DX8Wrapper::_Get_D3D_Device() ||+ !m_trapezoidWaterPixelShader || !wantsModernWater()) return;+ WorldHeightMap *map=TheTerrainRenderObject?TheTerrainRenderObject->getMap():NULL;+ if (!map || !map->getDataPtr() || map->getXExtent()<2 || map->getYExtent()<2 ||+ map->getXExtent()>2048 || map->getYExtent()>2048 || map->getBorderSize()<0 ||+ map->getBorderSize()>(map->getXExtent()-2)/2 || map->getBorderSize()>(map->getYExtent()-2)/2) return;+ // Prepare immutable data only. History activation retains its first live timestamp.+ synchronizeWaterStyle();+ takeWaterPolygonsForDraw();+ if (m_waterPolygonsForDraw.empty()) return;+ updateModernWaterTextures();+ refreshModernWaterOpticalPolygons();+ std::vector<double> flatLevels,exactLevels;+ if (m_modernOpticalPolygonsValid) for (const auto &polygon:m_modernOpticalPolygons) {+ if (polygon.points.size()<3) continue;+ const double level=polygon.points[0].z;+ bool flat=true,exact=true;+ for (const auto &point:polygon.points) {+ flat=flat && fabs(double(point.z)-level)<.01;+ exact=exact && double(point.z)==level;+ }+ if (flat && std::find(flatLevels.begin(),flatLevels.end(),level)==flatLevels.end()) flatLevels.push_back(level);+ if (exact && std::find(exactLevels.begin(),exactLevels.end(),level)==exactLevels.end()) exactLevels.push_back(level);+ }+ std::sort(flatLevels.begin(),flatLevels.end());+ if (m_modernOpticalPolygonsValid && !m_modernHeights.empty() && flatLevels.size()<=WaterShoreHistory::MaxLevels)+ for (double level:flatLevels) modernWaterOpticalTexture(Real(level));+ // Overflow and nonflat levels keep the original authored admission order.+ if (m_modernOpticalPolygonsValid) for (const auto &polygon:m_modernOpticalPolygons)+ if (!polygon.points.empty()) modernWaterOpticalTexture(polygon.points[0].z);+ if (exactLevels.size()<=WaterTerrainCulling::WetNodeCache::MaxEntries) for (double level:exactLevels) {+ double ceiling;+ if (WaterTerrainCulling::ProofCeiling(MAP_HEIGHT_SCALE,level,WaterSurfaceModel::MaxDisplacement+.01f,ceiling))+ m_modernRenderCaches.terrain.Prewarm(m_modernHeights.data(),m_modernHeightWidth,m_modernHeightHeight,+ MAP_HEIGHT_SCALE,ceiling);+ }+ if (m_modernShoreAttempted!=m_modernShoreRevision) prepareModernWaterShore();+#endif+}++void WaterRenderObjClass::clearModernWaterRenderCaches(void)+{+ m_modernRenderCaches.Clear();+}+void WaterRenderObjClass::clearModernWaterOpticalTextures(void){+ clearModernWaterRenderCaches();m_modernProjectedSamples.clear();m_modernObstacleIndex.Clear();for (size_t i=0;i<m_modernOpticalTextures.size();++i) {@@ -3071,6 +3194,18 @@ void WaterRenderObjClass::Render(RenderInfoClass & rinfo)// Per-frame reuse shares lattice vertices across flat patches/levels, while never keeping// stale terrain, moving hulls, wave time or camera state from a previous render.m_modernProjectedSamples.clear();+ if (WaterScreenReflection::Supported()) {+ const auto &quality=WaterPerformanceSettings::Applied();+ WaterRenderCaches::Settings settings;+ settings.reflectionMode=m_waterReflectionMode;+ settings.refraction=quality.refraction;+ settings.reflectionDetail=quality.reflectionDetail;+ settings.requestedFftResolution=quality.requestedFftResolution;+ settings.activeFftResolution=quality.activeFftResolution;+ settings.sceneReflections=quality.sceneReflections;+ settings.width=targetWidth;settings.height=targetHeight;+ m_modernRenderCaches.BeginRender(settings);+ }m_modernObstacleIndex.Clear();m_modernProjectedCacheEnabled=visibleFlatPatches>1;@@ -4081,7 +4216,7 @@ Real WaterRenderObjClass::getWaterHeight(Real x, Real y)}// Scene geometry attenuates the render mesh only. It never changes the simulation water grid.-Real WaterRenderObjClass::modernWaterDamping(Real x, Real y, Real z, Real offshore, Real *obstacleAttenuation, Real *terrainDepth, Real *hullFreeDamping, Real *hullFreeObstacle) const+Real WaterRenderObjClass::modernWaterDamping(Real x, Real y, Real z, Real offshore, Real *obstacleAttenuation, Real *terrainDepth, Real *hullFreeDamping, Real *hullFreeObstacle, const Real *cachedTerrain) const{if (obstacleAttenuation) *obstacleAttenuation=1.0f;if (hullFreeObstacle) *hullFreeObstacle=1.0f;@@ -4090,7 +4225,11 @@ Real WaterRenderObjClass::modernWaterDamping(Real x, Real y, Real z, Real offshoif (hullFreeDamping) *hullFreeDamping=0.0f;WorldHeightMap *map=TheTerrainRenderObject?TheTerrainRenderObject->getMap():NULL;Real damping=1.0f;- if (map && map->getXExtent()>1 && map->getYExtent()>1) {+ if (cachedTerrain) {+ if (terrainDepth) *terrainDepth=cachedTerrain[0];+ damping=cachedTerrain[1];+ if (damping<=0.0f && !hullFreeObstacle) return 0.0f;+ } else if (map && map->getXExtent()>1 && map->getYExtent()>1) {const Real depth=WaterTerrainDepth(map,x,y,z);if (terrainDepth) *terrainDepth=depth;damping=WaterSurfaceModel::TerrainDamping(depth,offshore);@@ -4260,6 +4399,9 @@ void WaterRenderObjClass::drawModernWaterPatch(const Vector3 points[4], Bool rivdiffuse |= m_settings[m_tod].waterDiffuse & 0xff000000; //copy alpha/opacity from ini settingWaterProjectedMesh::Mesh projectedMesh;+ WaterPreparedMeshCache::Cache::View preparedView;+ const WaterProjectedMesh::Mesh *preparedMesh=&projectedMesh;+ const Bool reuseWater=WaterScreenReflection::Supported();WaterFftGeometry::SeamFade fftSeam;Bool projected = FALSE;@@ -4312,9 +4454,14 @@ void WaterRenderObjClass::drawModernWaterPatch(const Vector3 points[4], Bool rivboundaryKnots.push_back({{a.x + dx * t, a.y + dy * t}, edge, i, t});}}- if (separation > WaterSurfaceModel::MaxDisplacement*2 && projection.Prepare() &&- WaterProjectedMesh::Build(polygon, projection, {m_modernProjectedColumns, m_modernProjectedRows}, projectedMesh,- m_modernProjectedBudget, boundaryKnots)) {+ Bool built=FALSE;+ if (separation > WaterSurfaceModel::MaxDisplacement*2 && projection.Prepare()) {+ if (reuseWater) built=m_modernRenderCaches.topology.Build(polygon,projection,+ {m_modernProjectedColumns,m_modernProjectedRows},projectedMesh,m_modernProjectedBudget,boundaryKnots);+ else built=WaterProjectedMesh::Build(polygon,projection,{m_modernProjectedColumns,m_modernProjectedRows},+ projectedMesh,m_modernProjectedBudget,boundaryKnots);+ }+ if (built) {projected = TRUE;vertexCount = (Int) projectedMesh.vertices.size();fftSeam.Prepare(polygon, projection, {m_modernProjectedColumns, m_modernProjectedRows});@@ -4376,53 +4523,55 @@ void WaterRenderObjClass::drawModernWaterPatch(const Vector3 points[4], Bool rivm_modernBowVertices += bowStats.addedVertices;m_modernBowTriangles += bowStats.addedTriangles;}- // Authored ocean polygons often extend beneath the entire land mass. The- // projected lattice covers that hidden area too; discard only triangles- // whose complete displaced footprint is buried, before evaluating waves,- // obstacles or uploading their vertices. Endpoint depths alone can miss a- // small pond inside a triangle, so inspect every overlapping terrain cell.- // Keep the original mesh for an underwater/below-terrain free camera.- if (m_modernCamera.Z > points[0].Z + WaterSurfaceModel::MaxDisplacement + 0.01f &&+ const Bool cullTerrain=(m_modernCamera.Z > points[0].Z + WaterSurfaceModel::MaxDisplacement + 0.01f &&WaterTerrainCulling::CameraAboveTerrain(m_modernHeights.data(), m_modernHeightWidth, m_modernHeightHeight,m_modernHeightBorder, MAP_XY_FACTOR, MAP_HEIGHT_SCALE,- m_modernCamera.X, m_modernCamera.Y, m_modernCamera.Z))- {- WaterTerrainCulling::CullDryTriangles(- projectedMesh, m_modernHeights.data(), m_modernHeightWidth, m_modernHeightHeight,- m_modernHeightBorder, MAP_XY_FACTOR, MAP_HEIGHT_SCALE, points[0].Z,- WaterSurfaceModel::MaxDisplacement + 0.01f,- WaterFftGeometry::MaxHorizontalDisplacement + 0.01f);- }-- if (waveCageAvailable)- {- const auto depth = [&](const WaterProjectedMesh::Point &p)+ m_modernCamera.X, m_modernCamera.Y, m_modernCamera.Z));+ auto prepareSurface=[&](WaterProjectedMesh::Mesh &mesh) {+ if (cullTerrain){- return points[0].Z - WaterWaveCage::Height(- m_modernHeights.data(), m_modernHeightWidth, m_modernHeightHeight,- m_modernHeightBorder, MAP_XY_FACTOR, MAP_HEIGHT_SCALE, float(p.x), float(p.y));- };- const auto supported = [&](const WaterProjectedMesh::Point &p)- {- return WaterSurfaceModel::SampleOffshore(- oceanContext->waveCageSupport.data(), m_modernHeightWidth, m_modernHeightHeight,- float(p.x) / MAP_XY_FACTOR + m_modernHeightBorder,- float(p.y) / MAP_XY_FACTOR + m_modernHeightBorder, MAP_XY_FACTOR).height > 0.0f;- };+ WaterTerrainCulling::CullDryTriangles(+ mesh, m_modernHeights.data(), m_modernHeightWidth, m_modernHeightHeight,+ m_modernHeightBorder, MAP_XY_FACTOR, MAP_HEIGHT_SCALE, points[0].Z,+ WaterSurfaceModel::MaxDisplacement + 0.01f,+ WaterFftGeometry::MaxHorizontalDisplacement + 0.01f, reuseWater?&m_modernRenderCaches.terrain:NULL);+ }- // Split only supported interior triangles at the rest waterline. The helper- // retains authored seams and leaves the original mesh intact if its budget fails.- WaterWaveCageMesh::ClipRestWaterline(projectedMesh, depth, supported);- }+ if (waveCageAvailable)+ {+ const auto depth = [&](const WaterProjectedMesh::Point &p)+ {+ return points[0].Z - WaterWaveCage::Height(+ m_modernHeights.data(), m_modernHeightWidth, m_modernHeightHeight,+ m_modernHeightBorder, MAP_XY_FACTOR, MAP_HEIGHT_SCALE, float(p.x), float(p.y));+ };+ const auto supported = [&](const WaterProjectedMesh::Point &p)+ {+ return WaterSurfaceModel::SampleOffshore(+ oceanContext->waveCageSupport.data(), m_modernHeightWidth, m_modernHeightHeight,+ float(p.x) / MAP_XY_FACTOR + m_modernHeightBorder,+ float(p.y) / MAP_XY_FACTOR + m_modernHeightBorder, MAP_XY_FACTOR).height > 0.0f;+ };++ // Split only supported interior triangles at the rest waterline. The helper+ // retains authored seams and leaves the original mesh intact if its budget fails.+ WaterWaveCageMesh::ClipRestWaterline(mesh, depth, supported);+ }- // Waterline clipping also leaves unreferenced dry vertices behind.- WaterTerrainCulling::CompactVertices(projectedMesh);- vertexCount = (Int) projectedMesh.vertices.size();+ // Waterline clipping also leaves unreferenced dry vertices behind.+ WaterTerrainCulling::CompactVertices(mesh);+ };+ if (reuseWater) {+ preparedView=m_modernRenderCaches.prepared.ProcessView(projectedMesh,points[0].Z,cullTerrain,waveCageAvailable,prepareSurface);+ preparedMesh=&preparedView.Get();+ } else prepareSurface(projectedMesh);+ vertexCount = (Int) preparedMesh->vertices.size();}}- if (projected && projectedMesh.indices.empty()) return;+ const WaterProjectedMesh::Mesh &drawMesh=*preparedMesh;+ if (projected && drawMesh.indices.empty()) return;const Bool waveCage = projected && waveCageAvailable;DynamicVBAccessClass vertices(BUFFER_TYPE_DYNAMIC_DX8, dynamic_fvf_type, vertexCount);{@@ -4434,26 +4583,49 @@ void WaterRenderObjClass::drawModernWaterPatch(const Vector3 points[4], Bool rivauto makeBaseVertex = [&](const WaterSurfaceModel::Point &p, Bool boundarySample = FALSE) {const Bool share = m_modernProjectedCacheEnabled || boundarySample;const WaterProjectedMesh::WorldKey key = WaterProjectedMesh::SampleKey(p.x, p.y, p.z);- auto cached = share ? m_modernProjectedSamples.find(key) : m_modernProjectedSamples.end();+ const ModernProjectedSample *cached=NULL;+ if (share) {+ if (reuseWater) cached=m_modernRenderCaches.samples.Find(key);+ else {+ const auto found=m_modernProjectedSamples.find(key);+ if (found!=m_modernProjectedSamples.end()) cached=&found->second;+ }+ }ModernProjectedSample sample;- if (cached != m_modernProjectedSamples.end()) {- sample = cached->second;+ if (cached) {+ sample = *cached;} else {- const WaterSurfaceModel::Sample offshore = WaterSurfaceModel::SampleOffshore(oceanContext->ocean.data(),+ WaterStaticSampleCache::Sample fields;+ if (reuseWater) fields=m_modernRenderCaches.staticSamples.Get(p.x,p.y,p.z,[&]() {+ WaterStaticSampleCache::Sample value;+ value.offshore=WaterSurfaceModel::SampleOffshore(oceanContext->ocean.data(),m_modernHeightWidth,m_modernHeightHeight,+ p.x/MAP_XY_FACTOR+m_modernHeightBorder,p.y/MAP_XY_FACTOR+m_modernHeightBorder,MAP_XY_FACTOR);+ value.exposure=WaterSurfaceModel::SampleOffshore(oceanContext->shoreContext.exposure.data(),m_modernHeightWidth,+ m_modernHeightHeight,p.x/MAP_XY_FACTOR+m_modernHeightBorder,p.y/MAP_XY_FACTOR+m_modernHeightBorder,MAP_XY_FACTOR).height;+ value.terrainDepth=WaterStaticSampleCache::TerrainDepth(m_modernHeights.data(),m_modernHeightWidth,m_modernHeightHeight,+ m_modernHeightBorder,MAP_XY_FACTOR,MAP_HEIGHT_SCALE,p.x,p.y,p.z);+ value.terrainDamping=WaterSurfaceModel::TerrainDamping(value.terrainDepth,value.offshore.height);+ return value;+ });+ const WaterSurfaceModel::Sample offshore = reuseWater?fields.offshore: WaterSurfaceModel::SampleOffshore(oceanContext->ocean.data(),m_modernHeightWidth, m_modernHeightHeight, p.x / MAP_XY_FACTOR + m_modernHeightBorder,p.y / MAP_XY_FACTOR + m_modernHeightBorder, MAP_XY_FACTOR);sample.obstacle = sample.hullFreeObstacle = 1;Real terrainDepth = 0, hullFreeDamping = 0;+ const Real terrain[2]={reuseWater?fields.terrainDepth:0,reuseWater?fields.terrainDamping:1};sample.damping = modernWaterDamping(p.x, p.y, p.z, offshore.height, &sample.obstacle, &terrainDepth, &hullFreeDamping,- waveCage ? &sample.hullFreeObstacle : NULL);+ waveCage ? &sample.hullFreeObstacle : NULL,reuseWater?terrain:NULL);sample.offshore = offshore.height;- sample.exposure = WaterSurfaceModel::SampleOffshore(oceanContext->shoreContext.exposure.data(),+ sample.exposure = reuseWater?fields.exposure:WaterSurfaceModel::SampleOffshore(oceanContext->shoreContext.exposure.data(),m_modernHeightWidth, m_modernHeightHeight, p.x / MAP_XY_FACTOR + m_modernHeightBorder,p.y / MAP_XY_FACTOR + m_modernHeightBorder, MAP_XY_FACTOR).height;sample.fftDamping = WaterFftGeometry::SafeDamping(hullFreeDamping, terrainDepth);sample.height = sample.damping > 0 ? WaterSurfaceModel::EvaluateBlendedHeight(p.x, p.y, m_modernWaveTime,offshore) * sample.damping : 0;- if (share && m_modernProjectedSamples.size() < WaterSurfaceModel::VertexBudget) m_modernProjectedSamples.emplace(key, sample);+ if (share) {+ if (reuseWater) m_modernRenderCaches.samples.Store(key,sample);+ else if (m_modernProjectedSamples.size()<WaterSurfaceModel::VertexBudget) m_modernProjectedSamples.emplace(key,sample);+ }}VertexFormatXYZNDUV2 result;result.x = p.x;@@ -4553,13 +4725,13 @@ void WaterRenderObjClass::drawModernWaterPatch(const Vector3 points[4], Bool rivresult.z += result.u1;return result;};- for (size_t n = 0; n < projectedMesh.vertices.size(); ++n) {- const WaterProjectedMesh::Vertex &p = projectedMesh.vertices[n];+ for (size_t n = 0; n < drawMesh.vertices.size(); ++n) {+ const WaterProjectedMesh::Vertex &p = drawMesh.vertices[n];if (p.boundary < 0) {grid[n] = p.collar >= 0 ? correctedVertex(p.world,- projectedMesh.collars[p.collar]) : makeBaseVertex({Real(p.world.x), Real(p.world.y), points[0].Z});+ drawMesh.collars[p.collar]) : makeBaseVertex({Real(p.world.x), Real(p.world.y), points[0].Z});if (p.transition >= 0) {- const WaterProjectedMesh::CentreTransition &transition = projectedMesh.transitions[p.transition];+ const WaterProjectedMesh::CentreTransition &transition = drawMesh.transitions[p.transition];VertexFormatXYZNDUV2 source[3];for (Int i = 0; i < 3; ++i) source[i] = correctedVertex(transition.source[i],WaterProjectedMesh::CollarAt(authored, transition.source[i]), TRUE);@@ -4676,12 +4848,12 @@ void WaterRenderObjClass::drawModernWaterPatch(const Vector3 points[4], Bool riv// Legacy dynamic index buffers store their count in 16 bits. Keep a shared vertex grid and// submit bounded row batches; even a 128-cell ocean patch cannot truncate its index count.if (projected) {- for (size_t first = 0; first < projectedMesh.indices.size(); first += 65532) {- const size_t count = min(size_t(65532), projectedMesh.indices.size() - first);+ for (size_t first = 0; first < drawMesh.indices.size(); first += 65532) {+ const size_t count = min(size_t(65532), drawMesh.indices.size() - first);DynamicIBAccessClass indices(BUFFER_TYPE_DYNAMIC_DX8, (Int) count);{DynamicIBAccessClass::WriteLockClass lock(&indices);- memcpy(lock.Get_Index_Array(), projectedMesh.indices.data() + first, count * sizeof(UnsignedShort));+ memcpy(lock.Get_Index_Array(), drawMesh.indices.data() + first, count * sizeof(UnsignedShort));}DX8Wrapper::Set_Index_Buffer(indices, 0);DX8Wrapper::Draw_Triangles(0, (Int) count / 3, 0, vertexCount);diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterPreparedMeshCache.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterPreparedMeshCache.hnew file mode 100644index 000000000..53155ca9f--- /dev/null+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterPreparedMeshCache.h@@ -0,0 +1,216 @@+/* Exact reuse of terrain-culled, rest-waterline-clipped projected water meshes, one per patch. */+#pragma once+#include "WaterProjectedMesh.h"+#include <deque>+#include <memory>++namespace WaterPreparedMeshCache {+class Cache {+public:+ class View {+ friend class Cache;+ std::shared_ptr<const WaterProjectedMesh::Mesh> pinned_;+ const WaterProjectedMesh::Mesh *fallback_ = nullptr;+ explicit View(std::shared_ptr<const WaterProjectedMesh::Mesh> mesh) : pinned_(std::move(mesh)) {}+ explicit View(const WaterProjectedMesh::Mesh &mesh) : fallback_(&mesh) {}+ public:+ View() = default;+ const WaterProjectedMesh::Mesh &Get() const {+ return pinned_ ? *pinned_ : *fallback_;+ }+ const WaterProjectedMesh::Mesh &operator*() const {+ return Get();+ }+ const WaterProjectedMesh::Mesh *operator->() const {+ return &Get();+ }+ };+ explicit Cache(size_t maxBytes=32u*1024u*1024u,size_t maxEntries=8):maxBytes_(maxBytes),maxEntries_(maxEntries) {}++ // The owner clears this cache when terrain, optical support or processing rules change.+ // Dynamic bow refinement is part of the complete input mesh, never an implicit key.+ template <class Compute>+ void Process(WaterProjectedMesh::Mesh &mesh, float level, bool cullTerrain, bool waveCage,+ const Compute &compute, bool *reused = nullptr) {+ if (reused) *reused=false;+ size_t inputBytes=0;+ const bool cacheable = maxBytes_ && maxEntries_ && std::isfinite(level) && Measure(mesh, maxBytes_,+ inputBytes);+ if (!cacheable) {+ compute(mesh);+ return;+ }+ for (const Entry &entry : entries_) {+ if (!(Same(level, entry.level) && cullTerrain == entry.cullTerrain &&+ waveCage == entry.waveCage && Same(mesh, entry.input)))+ continue;+ mesh = *entry.output;+ if (reused) *reused=true;+ return;+ }+ const bool validInput = Valid(mesh);+ if (!validInput) {+ compute(mesh);+ return;+ }+ WaterProjectedMesh::Mesh before=mesh;+ compute(mesh);+ size_t outputBytes=0;+ // Bypasses preserve the existing entries. Neither an oversized output nor invalid+ // callback result can displace a valid earlier input/output pair.+ const bool validOutput = Measure(mesh, maxBytes_ - inputBytes, outputBytes) && Valid(mesh);+ if (!validOutput)+ return;+ WaterProjectedMesh::Mesh after=mesh;+ const bool fits = Measure(before, maxBytes_, inputBytes, true) && Measure(after, maxBytes_ - inputBytes,+ outputBytes, true);+ if (!fits)+ return;+ const size_t bytes=inputBytes+outputBytes;+ // FIFO keeps eviction independent of frame timing, as the topology cache does.+ while (!entries_.empty() && (entries_.size()>=maxEntries_ || cachedBytes_>maxBytes_-bytes)) {+ cachedBytes_-=entries_.front().bytes;entries_.pop_front();+ }+ entries_.emplace_back();+ Entry &entry=entries_.back();+ std::swap(entry.input, before);+ entry.output = std::make_shared<const WaterProjectedMesh::Mesh>(std::move(after));+ entry.level = level;+ entry.cullTerrain = cullTerrain;+ entry.waveCage = waveCage;+ entry.bytes = bytes;+ cachedBytes_ += bytes;+ }++ // Pin a read-only cached result through this draw, including cache Clear or+ // eviction during shader setup. Cacheable misses consume mesh's buffers;+ // bypass views borrow the computed caller mesh, which must outlive the view.+ // CachedBytes covers cache-owned entries; release each view after its draw.+ // Never cast away a view's const and pass its mesh back as mutable input.+ template <class Compute>+ View ProcessView(WaterProjectedMesh::Mesh &mesh, float level, bool cullTerrain, bool waveCage,+ const Compute &compute, bool *reused = nullptr) {+ if (reused)+ *reused = false;+ size_t inputBytes = 0;+ const bool cacheable = maxBytes_ && maxEntries_ && std::isfinite(level) && Measure(mesh, maxBytes_,+ inputBytes);+ if (!cacheable) {+ compute(mesh);+ return View(mesh);+ }+ for (const Entry &entry : entries_) {+ if (!(Same(level, entry.level) && cullTerrain == entry.cullTerrain && waveCage == entry.waveCage+ && Same(mesh, entry.input)))+ continue;+ if (reused)+ *reused = true;+ return View(entry.output);+ }+ const bool validInput = Valid(mesh);+ if (!validInput) {+ compute(mesh);+ return View(mesh);+ }+ WaterProjectedMesh::Mesh before = mesh;+ compute(mesh);+ size_t outputBytes = 0;+ const bool validOutput = Measure(mesh, maxBytes_ - inputBytes, outputBytes) && Valid(mesh);+ if (!validOutput)+ return View(mesh);+ const bool inputFits = Measure(before, maxBytes_, inputBytes, true);+ bool outputFits = inputFits && Measure(mesh, maxBytes_ - inputBytes, outputBytes, true);+ if (!inputFits)+ return View(mesh);+ if (!outputFits) {+ // Match Process's compact-copy admission when spare caller capacity+ // alone exceeds the budget; never retain unaccounted moved buffers.+ WaterProjectedMesh::Mesh compact = mesh;+ outputFits = Measure(compact, maxBytes_ - inputBytes, outputBytes, true);+ if (!outputFits)+ return View(mesh);+ std::swap(mesh, compact);+ }+ const size_t bytes = inputBytes + outputBytes;+ while (!entries_.empty() && (entries_.size() >= maxEntries_ || cachedBytes_ > maxBytes_ - bytes)) {+ cachedBytes_ -= entries_.front().bytes;+ entries_.pop_front();+ }+ entries_.emplace_back();+ Entry &entry = entries_.back();+ std::swap(entry.input, before);+ entry.output = std::make_shared<const WaterProjectedMesh::Mesh>(std::move(mesh));+ entry.level=level;entry.cullTerrain=cullTerrain;entry.waveCage=waveCage;entry.bytes=bytes;+ cachedBytes_+=bytes;+ return View(entry.output);+ }+ void Clear() { entries_.clear();cachedBytes_=0; }+ size_t CachedBytes() const { return cachedBytes_; }+ size_t EntryCount() const { return entries_.size(); }++private:+ static bool Same(double a,double b) {+ uint64_t aa,bb;std::memcpy(&aa,&a,sizeof(aa));std::memcpy(&bb,&b,sizeof(bb));return aa==bb;+ }+ static bool Same(float a,float b) {+ uint32_t aa,bb;std::memcpy(&aa,&a,sizeof(aa));std::memcpy(&bb,&b,sizeof(bb));return aa==bb;+ }+ static bool Same(WaterProjectedMesh::Point a,WaterProjectedMesh::Point b) { return Same(a.x,b.x) && Same(a.y,b.y); }+ static bool Same(const WaterProjectedMesh::Mesh &a,const WaterProjectedMesh::Mesh &b) {+ if (a.cells!=b.cells || a.indices!=b.indices || a.vertices.size()!=b.vertices.size() ||+ a.collars.size()!=b.collars.size() || a.transitions.size()!=b.transitions.size()) return false;+ for (size_t i=0;i<a.vertices.size();++i) {+ const auto &x=a.vertices[i],&y=b.vertices[i];+ if (!Same(x.world,y.world) || x.boundary!=y.boundary || !Same(x.edgeParameter,y.edgeParameter) ||+ x.knot!=y.knot || x.transition!=y.transition || x.collar!=y.collar || x.lattice!=y.lattice) return false;+ }+ for (size_t i=0;i<a.transitions.size();++i) {+ const auto &x=a.transitions[i],&y=b.transitions[i];+ if (!Same(x.analytic,y.analytic)) return false;+ for (int j=0;j<3;++j) if (!Same(x.source[j],y.source[j]) || !Same(x.weight[j],y.weight[j])) return false;+ }+ for (size_t i=0;i<a.collars.size();++i) {+ const auto &x=a.collars[i],&y=b.collars[i];+ if (x.count!=y.count || !Same(x.fade,y.fade)) return false;+ // Build leaves unused slots uninitialized. Only active slots have meaning.+ for (int j=0;j<x.count;++j) if (x.edge[j]!=y.edge[j] || !Same(x.parameter[j],y.parameter[j]) || !Same(x.weight[j],y.weight[j])) return false;+ }+ return true;+ }+ static bool Measure(const WaterProjectedMesh::Mesh &mesh,size_t limit,size_t &bytes,bool allocated=false) {+ bytes=0;+ const size_t counts[]={allocated?mesh.vertices.capacity():mesh.vertices.size(),allocated?mesh.indices.capacity():mesh.indices.size(),+ allocated?mesh.transitions.capacity():mesh.transitions.size(),allocated?mesh.collars.capacity():mesh.collars.size()};+ const size_t widths[]={sizeof(WaterProjectedMesh::Vertex),sizeof(uint16_t),sizeof(WaterProjectedMesh::CentreTransition),sizeof(WaterProjectedMesh::BoundaryCollar)};+ for (int i=0;i<4;++i) {+ if (counts[i]>(limit-bytes)/widths[i]) return false;+ bytes+=counts[i]*widths[i];+ }+ return mesh.vertices.size()<=65536 && mesh.indices.size()%3==0;+ }+ static bool Valid(const WaterProjectedMesh::Mesh &mesh) {+ for (const auto &v:mesh.vertices) if (!std::isfinite(v.world.x) || !std::isfinite(v.world.y) || !std::isfinite(v.edgeParameter) ||+ v.boundary < -1 || v.boundary>3 || v.transition < -1 || v.collar < -1 ||+ (v.transition>=0 && size_t(v.transition)>=mesh.transitions.size()) || (v.collar>=0 && size_t(v.collar)>=mesh.collars.size())) return false;+ for (uint16_t i:mesh.indices) if (i>=mesh.vertices.size()) return false;+ for (const auto &t:mesh.transitions) {+ if (!std::isfinite(t.analytic)) return false;+ for (int i=0;i<3;++i) if (!std::isfinite(t.source[i].x) || !std::isfinite(t.source[i].y) || !std::isfinite(t.weight[i])) return false;+ }+ for (const auto &c:mesh.collars) {+ if (c.count<0 || c.count>4 || !std::isfinite(c.fade)) return false;+ for (int i=0;i<c.count;++i) if (!std::isfinite(c.parameter[i]) || !std::isfinite(c.weight[i])) return false;+ }+ return true;+ }+ struct Entry {+ WaterProjectedMesh::Mesh input;+ std::shared_ptr<const WaterProjectedMesh::Mesh> output;+ float level=0;+ bool cullTerrain=false,waveCage=false;+ size_t bytes=0;+ };+ size_t maxBytes_,maxEntries_,cachedBytes_=0;+ std::deque<Entry> entries_;+};+}diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterProjectedMeshCache.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterProjectedMeshCache.hnew file mode 100644index 000000000..f53fd62fa--- /dev/null+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterProjectedMeshCache.h@@ -0,0 +1,76 @@+/* Exact, bounded reuse of the projected base lattice before dynamic water edits. */+#pragma once+#include "WaterProjectedMesh.h"+#include <deque>++namespace WaterProjectedMeshCache {+class Cache {+public:+ explicit Cache(size_t maxVertices=262144,size_t maxEntries=32)+ : maxVertices_(maxVertices),maxEntries_(maxEntries) {}++ bool Build(const WaterProjectedMesh::Point corners[4], const WaterProjectedMesh::Projection &projection,+ WaterProjectedMesh::Resolution resolution, WaterProjectedMesh::Mesh &out, size_t vertexBudget = 60000,+ const std::vector<WaterProjectedMesh::BoundaryKnot> &knots = {}, bool *reused = nullptr) {+ if (reused) *reused=false;+ for (const Entry &entry : entries_) {+ if (!entry.Matches(corners, projection, resolution, vertexBudget, knots))+ continue;+ // Callers refine, cull and clip their copy. None of those edits can enter the cache.+ out=entry.mesh;+ if (reused) *reused=true;+ return true;+ }+ // Preserve Build's result, including a partially built mesh on failure. A failed or+ // oversized request must not evict useful entries or masquerade as an earlier success.+ const bool built = WaterProjectedMesh::Build(corners, projection, resolution, out, vertexBudget, knots);+ if (!built)+ return false;+ if (!maxEntries_ || out.vertices.size()>maxVertices_) return true;+ while (!entries_.empty() && (entries_.size()>=maxEntries_ ||+ cachedVertices_>maxVertices_-out.vertices.size())) {+ cachedVertices_-=entries_.front().mesh.vertices.size();entries_.pop_front();+ }+ entries_.emplace_back(corners,projection,resolution,vertexBudget,knots,out);+ cachedVertices_+=out.vertices.size();+ return true;+ }+ void Clear() { entries_.clear();cachedVertices_=0; }+ size_t EntryCount() const { return entries_.size(); }+ size_t CachedVertices() const { return cachedVertices_; }++private:+ static bool Same(double a,double b) {+ uint64_t aa,bb;std::memcpy(&aa,&a,sizeof(aa));std::memcpy(&bb,&b,sizeof(bb));return aa==bb;+ }+ static bool Same(WaterProjectedMesh::Point a,WaterProjectedMesh::Point b) {+ return Same(a.x,b.x) && Same(a.y,b.y);+ }+ struct Entry {+ WaterProjectedMesh::Point corners[4];+ WaterProjectedMesh::Projection projection;+ WaterProjectedMesh::Resolution resolution;+ size_t vertexBudget;+ std::vector<WaterProjectedMesh::BoundaryKnot> knots;+ WaterProjectedMesh::Mesh mesh;+ Entry(const WaterProjectedMesh::Point c[4],const WaterProjectedMesh::Projection &p,+ WaterProjectedMesh::Resolution r,size_t budget,const std::vector<WaterProjectedMesh::BoundaryKnot> &k,+ const WaterProjectedMesh::Mesh &m):projection(p),resolution(r),vertexBudget(budget),knots(k),mesh(m) {+ std::copy(c,c+4,corners);+ }+ bool Matches(const WaterProjectedMesh::Point c[4],const WaterProjectedMesh::Projection &p,+ WaterProjectedMesh::Resolution r,size_t budget,const std::vector<WaterProjectedMesh::BoundaryKnot> &k) const {+ if (r.columns!=resolution.columns || r.rows!=resolution.rows || budget!=vertexBudget || k.size()!=knots.size()) return false;+ for (int i=0;i<4;++i) if (!Same(c[i],corners[i])) return false;+ for (int i=0;i<9;++i) if (!Same(p.matrix[i],projection.matrix[i]) || !Same(p.inverse[i],projection.inverse[i])) return false;+ if (!Same(p.depth.a,projection.depth.a) || !Same(p.depth.b,projection.depth.b) || !Same(p.depth.c,projection.depth.c) ||+ !Same(p.nearDistance,projection.nearDistance) || !Same(p.farDistance,projection.farDistance) || !Same(p.margin,projection.margin)) return false;+ for (size_t i=0;i<k.size();++i) if (!Same(k[i].world,knots[i].world) || k[i].boundary!=knots[i].boundary ||+ k[i].index!=knots[i].index || !Same(k[i].edgeParameter,knots[i].edgeParameter)) return false;+ return true;+ }+ };+ size_t maxVertices_,maxEntries_,cachedVertices_=0;+ std::deque<Entry> entries_; // FIFO keeps capacity and eviction independent of frame timing.+};+}diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterProjectedSampleCache.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterProjectedSampleCache.hnew file mode 100644index 000000000..6c6b177c4--- /dev/null+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterProjectedSampleCache.h@@ -0,0 +1,80 @@+/* Reuse hash nodes across renders, never animated projected-surface values. */+#pragma once++#include "WaterProjectedMesh.h"+#include "WaterSurfaceModel.h"+#include <limits>+#include <type_traits>+#include <unordered_map>++namespace WaterProjectedSampleCache {+template <class Value, class Epoch = uint32_t>+class Cache {+ static_assert(std::is_integral<Epoch>::value && std::is_unsigned<Epoch>::value,+ "The render epoch must be an unsigned integer");+ struct Entry {+ Value value;+ Epoch epoch;+ };+ std::unordered_map<WaterProjectedMesh::WorldKey, Entry, WaterProjectedMesh::WorldHash> entries;+ Epoch epoch = 0;+ size_t live = 0;+ const size_t limit;+public:+ explicit Cache(size_t maximum = WaterSurfaceModel::VertexBudget)+ : limit((std::min)(maximum, size_t(WaterSurfaceModel::VertexBudget))) {}++ void Clear() {+ entries.clear();+ epoch = 0;+ live = 0;+ }+ void BeginRender() {+ // Camera movement may leave old coordinates behind. Amortize their removal;+ // a stable view neither walks stale entries nor allocates/frees hash nodes.+ const size_t allowance = (std::max)((std::min)(size_t(4096), limit),+ live > limit / 2 ? limit : live * 2);+ if (entries.size() > allowance || epoch == (std::numeric_limits<Epoch>::max)())+ Clear();+ ++epoch;+ live = 0;+ }+ size_t Size() const {+ return entries.size();+ }+ size_t LiveSize() const {+ return live;+ }++ const Value *Find(const WaterProjectedMesh::WorldKey &key) const {+ const auto found = entries.find(key);+ return found != entries.end() && found->second.epoch == epoch ? &found->second.value : nullptr;+ }+ void Store(const WaterProjectedMesh::WorldKey &key, const Value &value) {+ if (live >= limit)+ return;+ const auto found = entries.find(key);+ if (found != entries.end()) {+ if (found->second.epoch != epoch) {+ found->second.value = value;+ found->second.epoch = epoch;+ ++live;+ }+ } else {+ // Preserve the old current-render admission order even after a camera+ // move fills resident storage. This pressure-only sweep occurs at most+ // once per render; ordinary BeginRender never scans the table.+ if (entries.size() == limit) {+ for (auto stale = entries.begin(); stale != entries.end();) {+ if (stale->second.epoch != epoch)+ stale = entries.erase(stale);+ else+ ++stale;+ }+ }+ entries.emplace(key, Entry{value, epoch});+ ++live;+ }+ }+};+}diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterRenderCaches.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterRenderCaches.hnew file mode 100644index 000000000..e60d38c00--- /dev/null+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterRenderCaches.h@@ -0,0 +1,54 @@+// Distributed under the repository's GPL-3.0 terms; see LICENSE.md.+#pragma once++#include "WaterPreparedMeshCache.h"+#include "WaterProjectedMeshCache.h"+#include "WaterProjectedSampleCache.h"+#include "WaterStaticSampleCache.h"+#include "WaterTerrainCulling.h"++namespace WaterRenderCaches {+// Camera matrices, patch geometry, level, mesh resolution and bow refinement are+// exact keys in the mesh caches. These other preferences invalidate the set.+struct Settings {+ int reflectionMode=0, refraction=0, reflectionDetail=1;+ unsigned requestedFftResolution=256, activeFftResolution=256;+ int width=0, height=0;+ bool sceneReflections=true;+ bool operator==(const Settings &other) const {+ return reflectionMode==other.reflectionMode && refraction==other.refraction &&+ reflectionDetail==other.reflectionDetail && requestedFftResolution==other.requestedFftResolution &&+ activeFftResolution==other.activeFftResolution && width==other.width && height==other.height &&+ sceneReflections==other.sceneReflections;+ }+};++template<class Sample> class Cache {+ Settings settings;+ bool configured=false;+public:+ WaterProjectedMeshCache::Cache topology;+ WaterPreparedMeshCache::Cache prepared;+ WaterProjectedSampleCache::Cache<Sample> samples;+ WaterStaticSampleCache::Cache staticSamples;+ WaterTerrainCulling::WetNodeCache terrain;++ // Style, terrain, polygon, map and device lifecycle boundaries call Clear.+ void Clear() {+ topology.Clear();+ prepared.Clear();+ samples.Clear();+ staticSamples.Clear();+ terrain.Clear();+ configured=false;+ }+ void BeginRender(const Settings &next) {+ if (configured && !(settings==next)) Clear();+ settings=next;+ configured=true;+ // The first view must retain static data prepared during loading.+ samples.BeginRender();+ staticSamples.BeginRender();+ }+};+}diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterShoreHistory.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterShoreHistory.hindex 981fc3ecd..e2ae6b4e3 100644--- a/GeneralsMD/Code/Libraries/Include/Platform/WaterShoreHistory.h+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterShoreHistory.h@@ -204,11 +204,25 @@ public:Parameters settings=Parameters()) {if(!ValidTime(time)||!ValidGrid(grid)||!ValidParameters(settings,grid))return BuildResult::Invalid;Topology candidate;const BuildResult result=candidate.Build(grid,cells);if(result!=BuildResult::Ready)return result;+ return InstallPrepared(std::move(candidate), mapRevision, time, settings);+ }+ // The caller supplies a successfully built immutable topology. Its construction+ // may run during loading; only this call establishes the live history epoch.+ BuildResult InstallPrepared(Topology &&candidate, uint64_t mapRevision, double time,+ Parameters settings = Parameters()) {+ if (!ValidTime(time) || !ValidGrid(candidate.Geometry()) || !ValidParameters(settings, candidate.Geometry()))+ return BuildResult::Invalid;+ const size_t count = candidate.Cells().size();const bool reuse=installed&&revision==mapRevision&&topology.SameGeometry(candidate)&&settings.lifetime==parameters.lifetime&&settings.diffusivity==parameters.diffusivity&&settings.maximumRate==parameters.maximumRate;topology=std::move(candidate);parameters=settings;revision=mapRevision;installed=true;if(!reuse) {- committed.assign(cells.size(),{});preview.resize(cells.size());decayed.resize(cells.size());next.resize(cells.size());rates.resize(cells.size());ClearDynamic(time);+ committed.assign(count, {});+ preview.resize(count);+ decayed.resize(count);+ next.resize(count);+ rates.resize(count);+ ClearDynamic(time);}return BuildResult::Ready;}@@ -348,4 +362,200 @@ template<class Coverage> inline bool RasterizeAlpha(const Topology&topology,consreturn RasterizeAlpha(topology,states,mapping,level,time,coverage,vesselARGB,UnrestrictedSupport{});}+// One bounded camera mapping. The dependency revision must change whenever the+// topology or support geometry changes; neither density/age nor time is cached.+// Support::At/Allows must be pure within that immutable revision.+class RasterLookup {+ struct Axis {+ double world = 0, fraction = 0;+ int64_t key = 0;+ };+ struct TileRange {+ uint32_t tile = 0;+ uint16_t x0 = 0, x1 = 0, y0 = 0, y1 = 0;+ };+ std::array<Axis, 512> horizontal{}, vertical{};+ std::vector<TileRange> ranges;+ std::vector<uint8_t> masks;+ const Topology *owner = nullptr;+ const void *supportOwner = nullptr;+ Mapping mapping;+ double level = 0;+ uint64_t revision = 0, builds = 0;+ size_t sampleCount = 0;+ static bool Same(double a, double b) {+ return a == b && (a != 0 || std::signbit(a) == std::signbit(b));+ }+ static bool Valid(const Mapping &m, double l) {+ return std::isfinite(m.originX) && std::isfinite(m.originY) && std::isfinite(m.widthWorld)+ && std::isfinite(m.heightWorld) && m.widthWorld > 0 && m.heightWorld > 0+ && std::isfinite(m.originX + m.widthWorld) && std::isfinite(m.originY + m.heightWorld)+ && m.widthPixels && m.heightPixels && m.widthPixels <= 512 && m.heightPixels <= 512 && std::isfinite(l);+ }+public:+ static constexpr size_t MaximumPixels = 512 * 512;+ void Clear() {+ *this = RasterLookup();+ }+ uint64_t BuildCount() const {+ return builds;+ }+ size_t SampleCount() const {+ return sampleCount;+ }+ size_t TileCount() const {+ return ranges.size();+ }+ size_t MemoryBytes() const {+ return sizeof(*this) + ranges.capacity() * sizeof(TileRange) + masks.capacity();+ }+ bool Matches(const Topology &t, const Mapping &m, double l, uint64_t dependency, const void *support) const {+ return owner == &t && supportOwner == support && revision == dependency && revision != 0 && Same(level, l)+ && Same(mapping.originX, m.originX) && Same(mapping.originY, m.originY)+ && Same(mapping.widthWorld, m.widthWorld) && Same(mapping.heightWorld, m.heightWorld)+ && mapping.widthPixels == m.widthPixels && mapping.heightPixels == m.heightPixels;+ }+ template <class Support> bool Prepare(const Topology &t, const Mapping &m, double l, uint64_t dependency,+ const Support &support) {+ if (!dependency || !Valid(m, l))+ return false;+ if (Matches(t, m, l, dependency, &support))+ return true;+ RasterLookup next;+ next.owner = &t;+ next.supportOwner = &support;+ next.mapping = m;+ next.level = l;+ next.revision = dependency;+ next.builds = builds + 1;+ if (!next.builds)+ next.builds = 1;+ const Grid &g = t.Geometry();+ auto axis = [](std::array<Axis, 512> &out, unsigned count, double origin, double extent,+ double gridOrigin, double spacing) {+ for (unsigned i = 0; i < count; ++i) {+ Axis &a = out[i];+ a.world = origin + (double(i) + .5) * extent / count;+ const double p = (a.world - gridOrigin) / spacing;+ if (!std::isfinite(p) || p < (std::numeric_limits<int32_t>::min)()+ || p >= (std::numeric_limits<int32_t>::max)())+ a.key = p < (std::numeric_limits<int32_t>::min)() ? (std::numeric_limits<int64_t>::min)() : (std::numeric_limits<int64_t>::max)();+ else {+ a.key = int32_t(std::floor(p));+ a.fraction = p - double(a.key);+ }+ }+ };+ axis(next.horizontal, m.widthPixels, m.originX, m.widthWorld, g.originX, g.spacing);+ axis(next.vertical, m.heightPixels, m.originY, m.heightWorld, g.originY, g.spacing);+ auto first = [](const std::array<Axis, 512> &a, unsigned count, int64_t key) {+ return unsigned(std::lower_bound(a.begin(), a.begin() + count, key, [](const Axis &v, int64_t k) {+ return v.key < k;+ }) - a.begin());+ };+ auto after = [](const std::array<Axis, 512> &a, unsigned count, int64_t key) {+ return unsigned(std::upper_bound(a.begin(), a.begin() + count, key, [](int64_t k, const Axis &v) {+ return k < v.key;+ }) - a.begin());+ };+ next.masks.assign(size_t(m.widthPixels) * m.heightPixels, 0);+ next.ranges.reserve((std::min)(t.RasterTiles().size(), next.masks.size()));+ for (size_t i = 0; i < t.RasterTiles().size(); ++i) {+ const RasterTile &tile = t.RasterTiles()[i];+ if (tile.level != l || tile.x < next.horizontal[0].key || tile.x > next.horizontal[m.widthPixels - 1].key+ || tile.y < next.vertical[0].key || tile.y > next.vertical[m.heightPixels - 1].key)+ continue;+ const unsigned x0 = first(next.horizontal, m.widthPixels, tile.x), x1 = after(next.horizontal,+ m.widthPixels, tile.x);+ if (x0 == x1)+ continue;+ const unsigned y0 = first(next.vertical, m.heightPixels, tile.y), y1 = after(next.vertical,+ m.heightPixels, tile.y);+ if (y0 == y1)+ continue;+ next.ranges.push_back({uint32_t(i), uint16_t(x0), uint16_t(x1), uint16_t(y0), uint16_t(y1)});+ for (unsigned y = y0; y < y1; ++y)+ for (unsigned x = x0; x < x1; ++x) {+ const double fx = next.horizontal[x].fraction, fy = next.vertical[y].fraction;+ const auto stencil = support.At(tile.x, tile.y, l, fx, fy);+ uint8_t mask = 0;+ for (unsigned dy = 0; dy < 2; ++dy)+ for (unsigned dx = 0; dx < 2; ++dx) {+ const unsigned corner = dy * 2 + dx;+ if (tile.nodes[corner] < 0)+ continue;+ const double weight = (dx ? fx : 1 - fx) * (dy ? fy : 1 - fy);+ if (weight > 0 && stencil.Allows(dx, dy))+ mask |= uint8_t(1u << corner);+ }+ next.masks[size_t(y) * m.widthPixels + x] = mask;+ ++next.sampleCount;+ }+ }+ * this = std::move(next);+ return true;+ }+ // Prepare camera-fixed caller data, e.g. shoreline spatial breakup, once+ // per BuildCount. Pixel ownership is unique and follows the original order.+ template <class Function> void ForEachSample(Function function) const {+ for (const TileRange &r : ranges)+ for (unsigned y = r.y0; y < r.y1; ++y)+ for (unsigned x = r.x0; x < r.x1; ++x)+ function(size_t(y) * mapping.widthPixels + x, horizontal[x].world, vertical[y].world);+ }++ template <class Coverage> bool Rasterize(const std::vector<State> &states, double time,+ Coverage &coverage, std::vector<uint32_t> &pixels) const {+ if (!owner || !std::isfinite(time) || states.size() != owner->Cells().size() || pixels.size() != masks.size())+ return false;+ for (uint32_t &pixel : pixels)+ pixel &= 0x00ffffffu;+ for (const TileRange &r : ranges) {+ const RasterTile &tile = owner->RasterTiles()[r.tile];+ bool active = false;+ for (int32_t node : tile.nodes)+ if (node >= 0 && states[size_t(node)].density > 0) {+ active = true;+ break;+ }+ if (!active)+ continue;+ for (unsigned y = r.y0; y < r.y1; ++y)+ for (unsigned x = r.x0; x < r.x1; ++x) {+ const double fx = horizontal[x].fraction, fy = vertical[y].fraction;+ State state;+ const size_t n = size_t(y) * mapping.widthPixels + x;+ const uint8_t mask = masks[n];+ for (unsigned dy = 0; dy < 2; ++dy)+ for (unsigned dx = 0; dx < 2; ++dx) {+ const unsigned corner = dy * 2 + dx;+ if (!(mask & (1u << corner)))+ continue;+ const double weight = (dx ? fx : 1 - fx) * (dy ? fy : 1 - fy);+ state.density += states[size_t(tile.nodes[corner])].density * weight;+ state.ageMoment += states[size_t(tile.nodes[corner])].ageMoment * weight;+ }+ const double value = state.density > 0 ? coverage(state, horizontal[x].world, vertical[y].world, time, n) : 0;+ pixels[n] = WithAlpha(pixels[n], value);+ }+ }+ return true;+ }+};++template <class Coverage, class Support> inline bool RasterizeAlphaCached(const Topology &topology,+ const std::vector<State> &states,+ const Mapping &mapping, double level, double time, Coverage &coverage, std::vector<uint32_t> &pixels,+ const Support &support,+ RasterLookup &lookup, uint64_t dependencyRevision) {+ if (!std::isfinite(time) || states.size() != topology.Cells().size()+ || pixels.size() != size_t(mapping.widthPixels) * mapping.heightPixels+ || !lookup.Prepare(topology, mapping, level, dependencyRevision, support))+ return false;+ auto material = [&](const State &s, double x, double y, double t, size_t) {+ return coverage(s, x, y, t);+ };+ return lookup.Rasterize(states, time, material, pixels);+}+}diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterShoreSource.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterShoreSource.hindex b0e9e3c61..c2947dfb7 100644--- a/GeneralsMD/Code/Libraries/Include/Platform/WaterShoreSource.h+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterShoreSource.h@@ -8,9 +8,54 @@namespace WaterShoreSource {struct Level {double level=0;const WaterOpticalContext::Field *field=nullptr;};+// Terrain-only terms of WaterShoreFoam::Rate, immutable for one source batch.+// Keep the original division and left-associated multiplication order at sample time.+struct RateContext {+ float normalX = 0, normalY = 0, depthDivisor = 0, attenuation = 0;+ float rock = 0, steep = 0, prefix = 0, exposure = 0;+};++inline RateContext PrepareRate(const WaterShoreFoam::Context &c) {+ using namespace WaterShoreFoam;+ RateContext out;+ if (!std::isfinite(c.depth) || !std::isfinite(c.shore) || !std::isfinite(c.nx) || !std::isfinite(c.ny)+ || !std::isfinite(c.slope) || !std::isfinite(c.exposure) || !std::isfinite(c.support)+ || c.depth <= MinDepth || c.support <= 0)+ return out;+ const float normalLength = std::hypot(c.nx, c.ny);+ if (!std::isfinite(normalLength) || normalLength <= 1e-8f)+ return out;+ out.normalX = c.nx / normalLength;+ out.normalY = c.ny / normalLength;+ out.depthDivisor = (std::max)(c.depth + 0.5f, 1.0f);+ const float attenuation = WaterSurfaceModel::ShoreDamping(c.depth);+ out.attenuation = 1 - attenuation * attenuation;+ out.rock = 1 - Smooth(0, RockDistance, (std::max)(0.0f, c.shore));+ out.steep = Smooth(SlopeStart, SlopeFull, c.slope);+ out.prefix = MaximumRate *Clamp(c.support, 0, 1) * Smooth(MinDepth, WetDepth, c.depth);+ out.exposure = ShelteredScale + (1 - ShelteredScale) * Clamp(c.exposure, 0, 1);+ return out;+}++inline float PreparedRate(const RateContext &c, const WaterShoreFoam::Wave &w) {+ using namespace WaterShoreFoam;+ if (c.prefix <= 0 || !std::isfinite(w.height) || !std::isfinite(w.dx) || !std::isfinite(w.dy)+ || !std::isfinite(w.dt) || w.height <= 0)+ return 0;+ const float waveSlope = std::hypot(w.dx, w.dy);+ if (!std::isfinite(waveSlope) || waveSlope <= 1e-8f || std::abs(w.dt) <= 1e-8f)+ return 0;+ const float cosine = (w.dt > 0 ? 1.0f : -1.0f) * ((w.dx / waveSlope) * c.normalX+ + (w.dy / waveSlope) * c.normalY);+ const float incoming = Smooth(0, IncomingCosine, cosine);+ const float beach = Smooth(BreakStart, BreakFull, 2 * w.height / c.depthDivisor) * c.attenuation;+ return c.prefix * incoming * c.exposure * Clamp(beach + (c.rock - beach) * c.steep, 0, 1) * Smooth(0,+ CrestHeight, w.height);+}struct SampleContext {WaterShoreFoam::Context coast;WaterShoreFoam::FrontWeights frontWeights;+ RateContext rate;std::array<float,WaterShoreFoam::ModeCount> sine{},cosine{};};struct Context : SampleContext {std::array<SampleContext,4> quadrature;};@@ -82,6 +127,7 @@ public:context.coast.support=FieldSample(f.coast,width,ix,iy,fx,fy);context.coast.exposure=FieldSample(f.exposure,width,ix,iy,fx,fy);context.frontWeights=WaterShoreFoam::IncomingWeights(context.coast.nx,context.coast.ny);+ context.rate = PrepareRate(context.coast);const double worldX=next.grid.originX+px*spacing,worldY=next.grid.originY+py*spacing;for(unsigned mode=0;mode<WaterShoreFoam::ModeCount;++mode) {const auto&m=WaterShoreFoam::Modes[mode];@@ -151,7 +197,11 @@ public:rates[i]=0;if(nodes[i].sourceIndex>=contexts.size())continue;const Context&node=contexts[nodes[i].sourceIndex];for(const SampleContext&context:node.quadrature) {- if(context.coast.support<=0)continue;+ // Both conditions prove a zero final source for every phase;+ // retain the original wave/front accumulation for active quads.+ if (context.rate.prefix <= 0 || (context.frontWeights.value[0] == 0+ && context.frontWeights.value[1] == 0 && context.frontWeights.value[2] == 0))+ continue;WaterShoreFoam::Wave wave;float front=0;for(unsigned mode=0;mode<WaterShoreFoam::ModeCount;++mode) {const auto&m=WaterShoreFoam::Modes[mode];@@ -163,7 +213,7 @@ public:}// A phase-locked birth mask only removes old-source support. No new// per-cell trigonometry, graph cells, upload work or time state is added.- rates[i]+=.25*WaterShoreFoam::Rate(context.coast,wave)*WaterShoreFoam::Clamp(front,0,1);+ rates[i] += .25 * PreparedRate(context.rate, wave) * WaterShoreFoam::Clamp(front, 0, 1);}}}@@ -182,13 +232,23 @@ inline double Noise(double x,double y) {double fx=x-ix,fy=y-iy;fx=fx*fx*(3-2*fx);fy=fy*fy*(3-2*fy);return (hash(ix,iy)*(1-fx)+hash(ix+1,iy)*fx)*(1-fy)+(hash(ix,iy+1)*(1-fx)+hash(ix+1,iy+1)*fx)*fy;}-inline double Coverage(const WaterShoreHistory::State&s,double x,double y,double) {++inline double SpatialBreakup(double x, double y) {+ const double texture = Noise(x / 7, y / 7) * .7 + Noise(x / 2.3, y / 2.3) * .3;+ return WaterShoreFoam::Smooth(.25f, .7f, float(texture));+}++inline double CoverageFromBreakup(const WaterShoreHistory::State &s, double breakup) {if(!(s.density>0)||!std::isfinite(s.density)||!std::isfinite(s.ageMoment))return 0;const double age=s.ageMoment/s.density;- const double texture=Noise(x/7,y/7)*.7+Noise(x/2.3,y/2.3)*.3;- const double breakup=WaterShoreFoam::Smooth(.25f,.7f,float(texture));const double aged=WaterShoreFoam::Smooth(.4f,3.0f,float(age));const double terminal=1-WaterShoreFoam::Smooth(8,14,float(age));return -std::expm1(-s.density)*(1-aged+aged*breakup)*terminal;}++inline double Coverage(const WaterShoreHistory::State &s, double x, double y, double) {+ if (!(s.density > 0) || !std::isfinite(s.density) || !std::isfinite(s.ageMoment))+ return 0;+ return CoverageFromBreakup(s, SpatialBreakup(x, y));+}}diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterStaticSampleCache.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterStaticSampleCache.hnew file mode 100644index 000000000..d7cfc5b3b--- /dev/null+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterStaticSampleCache.h@@ -0,0 +1,64 @@+/* Exact static field reuse for consecutive water draws. Animated inputs stay outside this cache. */+#pragma once++#include "WaterProjectedMesh.h"+#include "WaterSurfaceModel.h"++namespace WaterStaticSampleCache {+// Preserve WaterTerrainDepth's clamp(lo, value, hi) argument order and+// WorldHeightMapData's flattened-index bounds, including samples beyond an edge.+// The caller owns a width*height immutable draw snapshot.+inline float TerrainDepth(const uint8_t *heights,int width,int height,int border,+ float spacing,float heightScale,float x,float y,float level) {+ if (!heights || width<2 || height<2) return 0.0f;+ const float gx=x/spacing+border,gy=y/spacing+border;+ const float mx=0.0f<gx?gx:0.0f,my=0.0f<gy?gy:0.0f;+ const int ix=int(mx),iy=int(my);const float fx=mx-ix,fy=my-iy;+ const auto at=[&](int column,int row) {+ const int64_t index=int64_t(row)*width+column;+ return index>=0 && index<int64_t(width)*height?heights[size_t(index)]:uint8_t(0);+ };+ const float a=at(ix,iy)*(1-fx)+at(ix+1,iy)*fx;+ const float b=at(ix,iy+1)*(1-fx)+at(ix+1,iy+1)*fx;+ return level-(a*(1-fy)+b*fy)*heightScale;+}++struct Sample {+ WaterSurfaceModel::Sample offshore;+ float exposure;+ float terrainDepth;+ float terrainDamping;+};++// A stable projected mesh visits the same coordinates in the same order. A sequence+// cache avoids a hash lookup per vertex; changed order/coordinates are ordinary misses.+// The owner must Clear when terrain, optical polygons, or field interpretation changes.+class Cache {+ struct Entry { WaterProjectedMesh::WorldKey key; Sample value; };+ std::vector<Entry> entries;+ size_t cursor = 0;+ const size_t limit;+public:+ explicit Cache(size_t maximum = WaterSurfaceModel::VertexBudget) : limit(maximum) {}+ void BeginRender() { cursor = 0; }+ void Clear() { entries.clear(); cursor = 0; }+ size_t Size() const { return entries.size(); }++ template<class Compute>+ Sample Get(float x, float y, float level, const Compute &compute, bool *reused = nullptr) {+ if (reused) *reused = false;+ if (!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(level) || cursor >= limit)+ return compute();+ const auto key = WaterProjectedMesh::SampleKey(x, y, level);+ const size_t index = cursor++;+ if (index < entries.size() && entries[index].key == key) {+ if (reused) *reused = true;+ return entries[index].value;+ }+ const Sample value = compute();+ if (index < entries.size()) entries[index] = {key, value};+ else entries.push_back({key, value});+ return value;+ }+};+}diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterSurfaceModel.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterSurfaceModel.hindex 3bc110b87..50f7e2da5 100644--- a/GeneralsMD/Code/Libraries/Include/Platform/WaterSurfaceModel.h+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterSurfaceModel.h@@ -46,6 +46,18 @@ inline Sample Evaluate(float x, float y, float seconds) {#undef WATER_MODE_EVALreturn value;}+// Displacement uses exactly the same height arithmetic without retaining the outlined+// full evaluator's slope accumulation on the release compiler.+inline float EvaluateHeight(float x, float y, float seconds) {+ float height=0;+#define WATER_MODE_HEIGHT_EVAL(kx,ky,amplitude,omega,phase) { \+ const float p = x*kx+y*ky-seconds*omega+phase; \+ const float s = std::sin(p), c = std::cos(p); \+ height += amplitude*(s+0.13f*2.0f*s*c); }+ WATER_SURFACE_MODES(WATER_MODE_HEIGHT_EVAL)+#undef WATER_MODE_HEIGHT_EVAL+ return height;+}// Open water has its own spectrum. Height energy is shared by several crossing swells rather// than concentrated into the old river's first two directions. A slowly evolving coordinate// warp bends the crests, and a bounded packet envelope breaks their uniform strength.@@ -72,6 +84,15 @@ inline Sample Evaluate(float x, float y, float seconds) {X( 0.6200f, 3.3400f,0.016f,6.02f,4.07f)struct OceanSurface { float height,dx,dy,laplacian; };+// The height-only evaluator retains the full model's warp and envelope arithmetic.+struct OceanWarp { float q0,q1,s0,s1,px,py; };+inline OceanWarp OceanWarpAt(float x,float y,float seconds) {+ const float q0=x*0.0241f+y*0.0157f-seconds*0.23f+0.4f;+ const float q1=x*-0.0173f+y*0.0299f-seconds*0.19f+2.1f;+ const float s0=std::sin(q0),s1=std::sin(q1);+ return {q0,q1,s0,s1,x+5.0f*s0,y+4.0f*s1};+}+inline float OceanEnvelope(float s0,float s1) { return 0.86f+0.14f*s0*s1; }template<bool Curvature,bool Slopes=true,bool SwellOnly=false> inline OceanSurface EvaluateOceanInternal(float x,float y,float seconds) {const float q0=x*0.0241f+y*0.0157f-seconds*0.23f+0.4f;const float q1=x*-0.0173f+y*0.0299f-seconds*0.19f+2.1f;@@ -112,11 +133,19 @@ inline Sample EvaluateOcean(float x,float y,float seconds) {const OceanSurface value=EvaluateOceanInternal<false>(x,y,seconds);return {value.height,value.dx,value.dy};}-// The fixed, unlit mesh vertex path does not consume ocean normals. Keep the same height-// arithmetic while instantiating away derivatives; merely reading EvaluateOcean(...).height-// still invokes its outlined full evaluator on the release compiler.+// The fixed, unlit mesh vertex path does not consume ocean normals. A scalar return also+// avoids the release compiler's spills when returning the height-only OceanSurface struct.+// The mode accumulation, warp and envelope match the full model.inline float EvaluateOceanHeight(float x,float y,float seconds) {- return EvaluateOceanInternal<false,false>(x,y,seconds).height;+ const OceanWarp warp=OceanWarpAt(x,y,seconds);+ float height=0;+#define WATER_OCEAN_HEIGHT_EVAL(kx,ky,amplitude,omega,phase) { \+ const float p=warp.px*kx+warp.py*ky-seconds*omega+phase; \+ const float s=std::sin(p),c=std::cos(p); \+ height+=amplitude*(s+0.16f*s*c); }+ WATER_OCEAN_MODES(WATER_OCEAN_HEIGHT_EVAL)+#undef WATER_OCEAN_HEIGHT_EVAL+ return height*OceanEnvelope(warp.s0,warp.s1);}inline Sample BlendSamples(const Sample &river,const Sample &ocean,const Sample &offshore) {const float blend=offshore.height<0?0:(offshore.height>1?1:offshore.height);@@ -131,9 +160,9 @@ inline Sample EvaluateBlended(float x,float y,float seconds,const Sample &offshoreturn BlendSamples(Evaluate(x,y,seconds),EvaluateOcean(x,y,seconds),offshore);}inline float EvaluateBlendedHeight(float x,float y,float seconds,const Sample &offshore) {- if (offshore.height<=0 && offshore.dx==0 && offshore.dy==0) return Evaluate(x,y,seconds).height;+ if (offshore.height<=0 && offshore.dx==0 && offshore.dy==0) return EvaluateHeight(x,y,seconds);if (offshore.height>=1 && offshore.dx==0 && offshore.dy==0) return EvaluateOceanHeight(x,y,seconds);- const float river=Evaluate(x,y,seconds).height,ocean=EvaluateOceanHeight(x,y,seconds);+ const float river=EvaluateHeight(x,y,seconds),ocean=EvaluateOceanHeight(x,y,seconds);const float blend=offshore.height<0?0:(offshore.height>1?1:offshore.height);return river+(ocean-river)*blend;}diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterTerrainCulling.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterTerrainCulling.hindex ae279ed1d..5f7c7c26b 100644--- a/GeneralsMD/Code/Libraries/Include/Platform/WaterTerrainCulling.h+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterTerrainCulling.h@@ -2,6 +2,7 @@#pragma once#include "Platform/WaterProjectedMesh.h"+#include <deque>#include <limits>namespace WaterTerrainCulling@@ -9,6 +10,151 @@ namespace WaterTerrainCullingconstexpr size_t MaxTriangleSamples = 1024;constexpr size_t MaxMeshSamples = 4u * 1024u * 1024u;+// Shared by loading preparation and the live proof, including float displacement+// rounding. Never replace this multiplication predicate with division/floor.+inline bool ProofCeiling(double heightScale, double level, double verticalBound, double &ceiling)+{+ if (!std::isfinite(heightScale) || heightScale <= 0 || !std::isfinite(level) ||+ !std::isfinite(verticalBound) || verticalBound < 0)+ return false;+ const double top = level + verticalBound;+ if (!std::isfinite(top) || !std::isfinite(255 * heightScale))+ return false;+ const double epsilon = 8 * std::numeric_limits<float>::epsilon();+ ceiling = top + epsilon * (std::max)(1.0, (std::max)(std::abs(top), 255 * heightScale));+ return std::isfinite(ceiling);+}++// The owner supplies an immutable height snapshot and clears this with its terrain+// caches when bytes change. Equal byte cutoffs share a table across water levels.+// At most eight (2049 * 2049 * sizeof(uint32_t)) tables can be retained.+class WetNodeCache+{+ struct Entry {+ int cutoff;+ std::vector<uint32_t> prefix;+ };+public:+ static constexpr size_t MaxEntries = 8;+ class Query+ {+ friend class WetNodeCache;+ WetNodeCache *owner = nullptr;+ Entry *entry = nullptr;+ int cutoff = 0;+ public:+ bool HasWet(int firstX, int lastX, int firstY, int lastY, bool &wet);+ };+ explicit WetNodeCache(size_t maxEntries = MaxEntries)+ : maxEntries_((std::min)(maxEntries, MaxEntries)) {}++ // Consume the query before the next Prepare/Clear; eviction may replace it.+ Query Prepare(const uint8_t *heights, int width, int height, double heightScale, double ceiling)+ {+ Query query;+ if (!maxEntries_ || !heights || width < 2 || height < 2 || width > 2048 || height > 2048 ||+ !std::isfinite(heightScale) || heightScale <= 0 || !std::isfinite(ceiling))+ return query;+ if (heights != heights_ || width != width_ || height != height_) {+ Clear();+ heights_ = heights;+ width_ = width;+ height_ = height;+ }+ // Use the scalar predicate itself: division/floor can round a boundary+ // differently from the multiplication used by the original proof.+ int cutoff = -1;+ while (cutoff < 255 && double(cutoff + 1) * heightScale <= ceiling)+ ++cutoff;+ query.owner = this;+ query.cutoff = cutoff;+ if (cutoff < 0 || cutoff == 255)+ return query;+ for (Entry &entry : entries_)+ if (entry.cutoff == cutoff) {+ query.entry = &entry;+ return query;+ }+ if (entries_.size() == maxEntries_) {+ bytes_ -= entries_.front().prefix.capacity() * sizeof(uint32_t);+ entries_.pop_front();+ }+ entries_.push_back(Entry{cutoff, {}});+ query.entry = &entries_.back();+ return query;+ }+ // Build immutable map data during loading without counting a render query.+ // Trivial all-wet/all-dry cutoffs need no prefix allocation.+ bool Prewarm(const uint8_t *heights, int width, int height, double heightScale, double ceiling)+ {+ Query query = Prepare(heights, width, height, heightScale, ceiling);+ if (!query.owner)+ return false;+ if (query.entry && query.entry->prefix.empty())+ Build(*query.entry);+ return true;+ }+ void Clear()+ {+ entries_.clear();+ heights_ = nullptr;+ width_ = height_ = 0;+ bytes_ = builds_ = queryHits_ = 0;+ }+ size_t CachedBytes() const {+ return bytes_;+ }+ size_t EntryCount() const {+ return entries_.size();+ }+ size_t BuildCount() const {+ return builds_;+ }+ size_t QueryHits() const {+ return queryHits_;+ }+private:+ void Build(Entry &entry)+ {+ const size_t stride = size_t(width_) + 1;+ entry.prefix.assign(stride * (size_t(height_) + 1), 0);+ for (int y = 0; y < height_; ++y) {+ uint32_t row = 0;+ for (int x = 0; x < width_; ++x) {+ row += heights_[size_t(y) * width_ + x] <= entry.cutoff;+ entry.prefix[size_t(y + 1) * stride + x + 1] =+ entry.prefix[size_t(y) * stride + x + 1] + row;+ }+ }+ bytes_ += entry.prefix.capacity() * sizeof(uint32_t);+ ++builds_;+ }+ const uint8_t *heights_ = nullptr;+ int width_ = 0, height_ = 0;+ size_t maxEntries_, bytes_ = 0, builds_ = 0, queryHits_ = 0;+ std::deque<Entry> entries_;+};++inline bool WetNodeCache::Query::HasWet(int firstX, int lastX, int firstY, int lastY, bool &wet)+{+ if (!owner || firstX < 0 || firstY < 0 || lastX < firstX || lastY < firstY ||+ lastX >= owner->width_ || lastY >= owner->height_)+ return false;+ ++owner->queryHits_;+ if (cutoff < 0 || cutoff == 255) {+ wet = cutoff == 255;+ return true;+ }+ if (entry->prefix.empty())+ owner->Build(*entry);+ const size_t stride = size_t(owner->width_) + 1;+ const auto &p = entry->prefix;+ const uint32_t right = p[size_t(lastY + 1) * stride + lastX + 1] - p[size_t(firstY) * stride + lastX + 1];+ const uint32_t left = p[size_t(lastY + 1) * stride + firstX] - p[size_t(firstY) * stride + firstX];+ wet = right != left;+ return true;+}+// The terrain renderer triangulates each heightmap cell. Its surface can be above// the bilinear sample on a saddle, so require clearance over every cell corner.// Callers can use this to disable terrain occlusion proofs from below the ground.@@ -84,14 +230,16 @@ inline void Install(WaterProjectedMesh::Mesh &mesh, std::vector<uint16_t> &indicremap[index] = 0;}- std::vector<WaterProjectedMesh::Vertex> vertices;- vertices.reserve(mesh.vertices.size());+ size_t retained = 0;for (size_t i = 0; i < remap.size(); ++i){if (remap[i] == 0){- remap[i] = int(vertices.size());- vertices.push_back(mesh.vertices[i]);+ remap[i] = int(retained);+ // Stable old-index order means the destination never passes unread input.+ if (retained != i)+ mesh.vertices[retained] = mesh.vertices[i];+ ++retained;}}@@ -100,7 +248,7 @@ inline void Install(WaterProjectedMesh::Mesh &mesh, std::vector<uint16_t> &indicindex = uint16_t(remap[index]);}- mesh.vertices.swap(vertices);+ mesh.vertices.resize(retained);mesh.indices.swap(indices);}@@ -111,8 +259,7 @@ inline bool CompactVertices(WaterProjectedMesh::Mesh &mesh)return false;}- std::vector<uint16_t> indices = mesh.indices;- Install(mesh, indices);+ Install(mesh, mesh.indices);return true;}@@ -125,7 +272,7 @@ inline bool CompactVertices(WaterProjectedMesh::Mesh &mesh)inline bool CullDryTriangles(WaterProjectedMesh::Mesh &mesh, const uint8_t *heights,int width, int height, int border, double spacing, double heightScale,- double level, double verticalBound, double horizontalBound)+ double level, double verticalBound, double horizontalBound, WetNodeCache *cache = nullptr){if (!heights || width < 2 || height < 2 || width > 2048 || height > 2048 ||border < 0 || border > (width - 2) / 2 || border > (height - 2) / 2 ||@@ -137,22 +284,17 @@ inline bool CullDryTriangles(return false;}- const double top = level + verticalBound;- if (!std::isfinite(top) || !std::isfinite(255 * heightScale))- {- return false;- }-// Vertices and shader displacement ultimately use float; include their rounding// before converting bounds to grid cells and comparing terrain/water elevations.const double epsilon = 8 * std::numeric_limits<float>::epsilon();- const double ceiling = top + epsilon *- (std::max)(1.0, (std::max)(std::abs(top), 255 * heightScale));- if (!std::isfinite(ceiling))+ double ceiling;+ if (!ProofCeiling(heightScale, level, verticalBound, ceiling)){return false;}+ auto proof = cache ? cache->Prepare(heights, width, height, heightScale, ceiling) : WetNodeCache::Query();+std::vector<uint16_t> indices;indices.reserve(mesh.indices.size());size_t work = 0;@@ -191,15 +333,20 @@ inline bool CullDryTriangles({work += samples;dry = true;-- for (int y = firstY; y <= lastY && dry; ++y)- {- for (int x = firstX; x <= lastX; ++x)- {- if (heights[size_t(y) * width + x] * heightScale <= ceiling)- {- dry = false;- break;+ // Most ocean triangles encounter wet terrain immediately. Keep+ // that scalar early exit before lazily building/querying a table.+ bool wet = false;+ if (cache && heights[size_t(firstY) * width + firstX] * heightScale <= ceiling)+ dry = false;+ else if (cache && proof.HasWet(firstX, lastX, firstY, lastY, wet))+ dry = !wet;+ else {+ for (int y = firstY; y <= lastY && dry; ++y) {+ for (int x = firstX; x <= lastX; ++x) {+ if (heights[size_t(y) * width + x] * heightScale <= ceiling) {+ dry = false;+ break;+ }}}}diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterWaveCageMesh.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterWaveCageMesh.hindex 21128ea85..683b13fa3 100644--- a/GeneralsMD/Code/Libraries/Include/Platform/WaterWaveCageMesh.h+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterWaveCageMesh.h@@ -33,28 +33,42 @@ inline bool ClipRestWaterline(WaterProjectedMesh::Mesh&mesh,DepthSampler depthSaconstexpr uint32_t None=0xffffffffu;std::vector<std::array<uint32_t,3>> crossings(triangleCount,std::array<uint32_t,3>{{None,None,None}});std::vector<uint8_t> eligible(triangleCount,1);std::vector<size_t> queue;+ size_t affectedTriangles=0;const auto key=[](uint16_t a,uint16_t b){return (uint32_t((std::min)(a,b))<<16)|uint32_t((std::max)(a,b));};for(size_t t=0;t<triangleCount;++t){+ bool negative=false;for(int corner=0;corner<3;++corner){const uint16_t a=mesh.indices[t*3+corner],b=mesh.indices[t*3+(corner+1)%3];if(a>=mesh.vertices.size()||b>=mesh.vertices.size()||a==b)return false;eligible[t]=eligible[t]&&eligibleVertex[a];+ negative=negative||depths[a]<0;if((depths[a]<0&&depths[b]>0)||(depths[b]<0&&depths[a]>0)){const auto k=key(a,b);crossings[t][corner]=k;auto&e=edges[k];if(e.count>=2)return false;e.owner[e.count++]=t;}}+ if(eligible[t]&&negative)++affectedTriangles;if(!eligible[t])queue.push_back(t);}for(size_t head=0;head<queue.size();++head){for(auto k:crossings[queue[head]])if(k!=None){const auto&e=edges.find(k)->second;for(unsigned owner=0;owner<e.count;++owner)if(eligible[e.owner[owner]]){- eligible[e.owner[owner]]=0;queue.push_back(e.owner[owner]);+ const size_t t=e.owner[owner];+ if(depths[mesh.indices[t*3]]<0||depths[mesh.indices[t*3+1]]<0||depths[mesh.indices[t*3+2]]<0)+ --affectedTriangles;+ eligible[t]=0;queue.push_back(t);}}}- auto vertices=mesh.vertices;std::vector<uint16_t> indices;indices.reserve(mesh.indices.size());bool valid=true;+ // Validate and propagate crossing chains before accepting an unchanged mesh.+ if(!affectedTriangles)return true;+ // Stage only intersections; original vertices stay untouched until success.+ const size_t originalVertices=mesh.vertices.size();+ std::vector<Vertex> added;std::vector<uint16_t> indices;indices.reserve(mesh.indices.size());bool valid=true;+ const auto world=[&](uint16_t index){+ return index<originalVertices?mesh.vertices[index].world:added[size_t(index)-originalVertices].world;+ };const auto intersection=[&](uint16_t a,uint16_t b)->uint16_t{if(depths[a]==0)return a;if(depths[b]==0)return b;auto found=edges.find(key(a,b));if(found==edges.end()){valid=false;return 0;}@@ -70,13 +84,13 @@ inline bool ClipRestWaterline(WaterProjectedMesh::Mesh&mesh,DepthSampler depthSaif((depth>=0)==(lowDepth>=0)){low=mid;lowDepth=depth;}else high=mid;}const double parameter=lowDepth>=0?low:high; // round toward the wet side- if(vertices.size()>=maxVertices){valid=false;return 0;}+ if(originalVertices+added.size()>=maxVertices){valid=false;return 0;}Vertex v;v.world={p.x+(q.x-p.x)*parameter,p.y+(q.y-p.y)*parameter};- e.vertex=int(vertices.size());vertices.push_back(v);return uint16_t(e.vertex);+ e.vertex=int(originalVertices+added.size());added.push_back(v);return uint16_t(e.vertex);};const auto triangle=[&](uint16_t a,uint16_t b,uint16_t c){if(a==b||b==c||c==a)return;- const Point pa=vertices[a].world,pb=vertices[b].world,pc=vertices[c].world;+ const Point pa=world(a),pb=world(b),pc=world(c);if(std::abs((pb.x-pa.x)*(pc.y-pa.y)-(pb.y-pa.y)*(pc.x-pa.x))<1e-16)return;indices.insert(indices.end(),{a,b,c});};@@ -95,6 +109,6 @@ inline bool ClipRestWaterline(WaterProjectedMesh::Mesh&mesh,DepthSampler depthSa}for(unsigned i=1;i+1<count;++i)triangle(polygon[0],polygon[i],polygon[i+1]);}- mesh.vertices.swap(vertices);mesh.indices.swap(indices);return true;+ mesh.vertices.insert(mesh.vertices.end(),added.begin(),added.end());mesh.indices.swap(indices);return true;}}diff --git a/GeneralsMD/Code/Tests/WaterPreparedViewTest.h b/GeneralsMD/Code/Tests/WaterPreparedViewTest.hnew file mode 100644index 000000000..352c8a4ea--- /dev/null+++ b/GeneralsMD/Code/Tests/WaterPreparedViewTest.h@@ -0,0 +1,174 @@+#pragma once++// Included after the prepared-cache fixtures in test_water_grid.cpp.++TEST(water_prepared_view_matches_copy_pipeline_without_output_copy)+{+ using namespace WaterProjectedMesh;+ const Mesh input = preparedCacheInput();+ const auto terrain = preparedCacheTerrain();+ WaterPreparedMeshCache::Cache copied, borrowed;+ const Vertex *computedVertices = nullptr;+ int computes = 0;+ bool reused = true;+ auto compute = [&](Mesh &mesh) {+ ++computes;+ preparedCachePipeline(mesh, terrain, 5, true, true);+ computedVertices = mesh.vertices.data();+ };+ Mesh expected = input;+ copied.Process(expected, 5, true, true, [&](Mesh &mesh) {+ preparedCachePipeline(mesh, terrain, 5, true, true);+ });+ Mesh caller = input;+ const auto first = borrowed.ProcessView(caller, 5, true, true, compute, &reused);+ CHECK(!reused && computes == 1 && projectedCacheSameMesh(first.Get(), expected));+ CHECK(first->vertices.data() == computedVertices && caller.vertices.empty());+ const Mesh *address = &first.Get();+ // Returned data belongs to the cache, including on the miss. Editing the+ // separate caller mesh cannot alter it, and each later hit borrows it again.+ caller = input;+ caller.vertices[0].world.x = -100;+ CHECK(projectedCacheSameMesh(first.Get(), expected));+ for (int frame = 0; frame < 3; ++frame) {+ caller = input;+ const auto hit = borrowed.ProcessView(caller, 5, true, true, compute, &reused);+ CHECK(reused && computes == 1 && &hit.Get() == address && projectedCacheSameMesh(hit.Get(), expected));+ CHECK(projectedCacheSameMesh(caller, input));+ }+}++TEST(water_prepared_view_bypasses_preserve_computed_output_and_prior_entry)+{+ using namespace WaterProjectedMesh;+ const Mesh input = preparedCacheInput();+ WaterPreparedMeshCache::Cache cache;+ auto identity = [](Mesh &) {};+ bool reused = true;+ Mesh initial = input;+ cache.ProcessView(initial, 5, false, false, identity);+ const size_t retained = cache.CachedBytes();+ for (int invalid = 0; invalid < 5; ++invalid) {+ Mesh caller = input;+ ++caller.cells;+ float level = 5;+ if (invalid == 0)+ caller.indices[0] = 65535;+ if (invalid == 1)+ caller.vertices[0].world.x = NAN;+ if (invalid == 2)+ level = INFINITY;+ const auto result = cache.ProcessView(caller, level, false, false, [&](Mesh &mesh) {+ if (invalid == 3)+ mesh.collars[0].count = -1;+ if (invalid == 4)+ mesh.vertices.resize(65537);+ }, &reused);+ CHECK(!reused && &result.Get() == &caller && cache.CachedBytes() == retained && cache.EntryCount() == 1);+ Mesh probe = input;+ const auto hit = cache.ProcessView(probe, 5, false, false, identity, &reused);+ CHECK(reused && projectedCacheSameMesh(hit.Get(), input));+ }+ for (bool bytesDisabled :{false, true}) {+ WaterPreparedMeshCache::Cache disabled(bytesDisabled ? 0 : 32u * 1024u * 1024u, bytesDisabled ? 8 : 0);+ Mesh caller = input;+ const auto result = disabled.ProcessView(caller, 5, false, false, identity, &reused);+ CHECK(!reused && &result.Get() == &caller && projectedCacheSameMesh(result.Get(),+ input) && disabled.CachedBytes() == 0);+ }+}++TEST(water_prepared_view_accounts_retained_capacity_and_normalizes_only_if_needed)+{+ using namespace WaterProjectedMesh;+ const Mesh input = preparedCacheInput();+ const size_t budget = preparedCacheBytes(input) * 2;+ WaterPreparedMeshCache::Cache cache(budget);+ Mesh caller = input;+ caller.vertices.reserve(1000);+ const Vertex *large = caller.vertices.data();+ bool reused = true;+ const auto result = cache.ProcessView(caller, 5, false, false, [](Mesh &) {}, &reused);+ CHECK(!reused && projectedCacheSameMesh(result.Get(), input) && result->vertices.data() != large);+ CHECK(cache.EntryCount() == 1 && cache.CachedBytes() <= budget);+ caller = input;+ const auto hit = cache.ProcessView(caller, 5, false, false, [](Mesh &) {}, &reused);+ CHECK(reused && projectedCacheSameMesh(hit.Get(), input));++ // Spare capacities that do fit are retained and included in the byte count.+ WaterPreparedMeshCache::Cache roomy;+ caller = input;+ caller.vertices.reserve(1000);+ large = caller.vertices.data();+ const size_t actualOutput = caller.vertices.capacity() * sizeof(Vertex)+ + caller.indices.capacity() * sizeof(uint16_t)+ + caller.transitions.capacity() * sizeof(CentreTransition)+ + caller.collars.capacity() * sizeof(BoundaryCollar);+ const auto moved = roomy.ProcessView(caller, 5, false, false, [](Mesh &) {});+ CHECK(moved->vertices.data() == large && roomy.CachedBytes() == preparedCacheBytes(input) + actualOutput);+}++TEST(water_prepared_view_preserves_fifo_and_interoperates_with_copy_api)+{+ using namespace WaterProjectedMesh;+ const Mesh input = preparedCacheInput();+ WaterPreparedMeshCache::Cache copied(32u * 1024u * 1024u, 2), borrowed(32u * 1024u * 1024u, 2);+ auto compute = [](Mesh &mesh) {+ mesh.vertices[0].world.x += mesh.cells;+ };+ for (int key :{0, 1, 0, 2, 1, 2, 0}) {+ Mesh expected = input, caller = input;+ expected.cells += key;+ caller.cells += key;+ bool a = false, b = false;+ copied.Process(expected, 5, false, false, compute, &a);+ const auto view = borrowed.ProcessView(caller, 5, false, false, compute, &b);+ CHECK(a == b && projectedCacheSameMesh(view.Get(), expected) && borrowed.EntryCount() == copied.EntryCount());+ // Legacy Process must still produce an independently editable output.+ Mesh own = input;+ own.cells += key;+ borrowed.Process(own, 5, false, false, compute, &b);+ CHECK(b && projectedCacheSameMesh(own, expected));+ own.vertices[0].world.x = -100;+ caller = input;+ caller.cells += key;+ const auto again = borrowed.ProcessView(caller, 5, false, false, compute, &b);+ CHECK(b && projectedCacheSameMesh(again.Get(), expected));+ }+ borrowed.Clear();+ CHECK(borrowed.EntryCount() == 0 && borrowed.CachedBytes() == 0);+ Mesh caller = input;+ bool reused = true;+ borrowed.ProcessView(caller, 5, false, false, compute, &reused);+ CHECK(!reused);+}++TEST(water_prepared_view_pins_output_across_clear_and_fifo_eviction)+{+ using namespace WaterProjectedMesh;+ const Mesh input = preparedCacheInput();+ WaterPreparedMeshCache::Cache cache(32u * 1024u * 1024u, 1);+ auto compute = [](Mesh &mesh) {+ mesh.vertices[0].world.x += mesh.cells;+ };+ Mesh expected = input;+ compute(expected);+ Mesh caller = input;+ const auto pinned = cache.ProcessView(caller, 5, false, false, compute);+ const Vertex *address = pinned->vertices.data();+ cache.Clear();+ CHECK(cache.CachedBytes() == 0 && cache.EntryCount() == 0);+ CHECK(pinned->vertices.data() == address && projectedCacheSameMesh(pinned.Get(), expected));+ for (int key :{1, 2, 3}) {+ caller = input;+ caller.cells += key;+ const auto current = cache.ProcessView(caller, 5, false, false, compute);+ CHECK(cache.EntryCount() == 1 && pinned->vertices.data() == address);+ CHECK(projectedCacheSameMesh(pinned.Get(), expected));+ }+ // A copied View pins the same immutable buffers without a deep mesh copy.+ const auto second = pinned;+ CHECK(&second.Get() == &pinned.Get());+ cache.Clear();+ CHECK(projectedCacheSameMesh(second.Get(), expected));+}diff --git a/GeneralsMD/Code/Tests/WaterProjectedSampleCacheTest.h b/GeneralsMD/Code/Tests/WaterProjectedSampleCacheTest.hnew file mode 100644index 000000000..0915bf4ba--- /dev/null+++ b/GeneralsMD/Code/Tests/WaterProjectedSampleCacheTest.h@@ -0,0 +1,160 @@+#pragma once+#include "Platform/WaterProjectedSampleCache.h"+#include <array>+#include <cstring>++namespace WaterProjectedSampleCacheTest {+using Sample = std::array<float, 7>;+inline bool Same(const Sample &a, const Sample &b) {+ return std::memcmp(a.data(), b.data(), sizeof(a)) == 0;+}++inline Sample Evaluate(float x, float y, float level, float time, float hull, float terrain) {+ return {{std::sin(x + time) + hull, terrain - level, hull * y, 1 - hull,+ x * y + terrain, time * .125f, level - terrain}};+}++inline void CheckDynamic() {+ WaterProjectedSampleCache::Cache<Sample> cache;+ std::array<const Sample *, 23> nodes = {{}};+ int computed = 0;+ for (int frame = 0; frame < 80; ++frame) {+ cache.BeginRender();+ for (int visit = 0; visit < 4; ++visit)+ for (int n = 0; n < 23; ++n) {+ const int i = (n * 7 + visit) % 23;+ const float x = float(i) * .5f, y = float(i % 5), level = float(i % 3);+ const auto key = WaterProjectedMesh::SampleKey(x, y, level);+ const Sample reference = Evaluate(x, y, level, frame * .125f, frame * .01f, float(frame % 7));+ const Sample *found = cache.Find(key);+ if (visit == 0)+ CHECK(!found);+ else+ CHECK(found);+ if (!found) {+ ++computed;+ cache.Store(key, reference);+ found = cache.Find(key);+ }+ CHECK(found && Same(*found, reference));+ // The stable camera reuses the node, but its payload is new each render.+ if (frame)+ CHECK(found == nodes[i]);+ nodes[i] = found;+ }+ CHECK(cache.Size() == 23 && cache.LiveSize() == 23 && computed == (frame + 1) * 23);+ }+ cache.Clear();+ CHECK(cache.Size() == 0 && cache.LiveSize() == 0);+ CHECK(!cache.Find(WaterProjectedMesh::SampleKey(0, 0, 0)));+}++inline void CheckOracle() {+ WaterProjectedSampleCache::Cache<Sample> cache(17);+ std::unordered_map<WaterProjectedMesh::WorldKey, Sample, WaterProjectedMesh::WorldHash> original;+ for (int frame = 0; frame < 60; ++frame) {+ original.clear();+ cache.BeginRender();+ for (int request = 0; request < 100; ++request) {+ const int n = (request * 7 + frame * 3) % 29;+ const float x = float(n), y = float(n % 4), level = float(n % 3);+ const auto key = WaterProjectedMesh::SampleKey(x, y, level);+ const bool share = request % 5 != 0;+ auto old = share ? original.find(key) : original.end();+ const bool oldHit = old != original.end();+ const Sample *found = share ? cache.Find(key) : nullptr;+ Sample expected, actual;+ auto evaluate = [&]() {+ auto s = Evaluate(x, y, level, frame * .2f, frame * .01f, frame % 5);+ return s;+ };+ if (oldHit)+ expected = old->second;+ else {+ expected = evaluate();+ if (share && original.size() < 17)+ original.emplace(key, expected);+ }+ if (found)+ actual = *found;+ else {+ actual = evaluate();+ if (share)+ cache.Store(key, actual);+ }+ CHECK((found != nullptr) == oldHit);+ CHECK(Same(actual, expected));+ CHECK(cache.Size() <= 17 && cache.LiveSize() <= 17);+ }+ }+ // A later request at the same XYZ must receive the complete sample.+ cache.Clear();+ cache.BeginRender();+ const auto key = WaterProjectedMesh::SampleKey(1, 2, 3);+ CHECK(!cache.Find(key));+ const auto complete = Evaluate(1, 2, 3, 4, .2f, 7);+ cache.Store(key, complete);+ CHECK(cache.Find(key) && Same(*cache.Find(key), complete));+ Sample replacement = complete;+ replacement[0] = -100;+ cache.Store(key, replacement);+ CHECK(Same(*cache.Find(key), complete));+}++inline void CheckBoundsAndWrap() {+ const Sample value = {{1, 2, 3, 4, 5, 6, 7}};+ WaterProjectedSampleCache::Cache<Sample> full(3);+ for (int frame = 0; frame < 3; ++frame) {+ full.BeginRender();+ for (int i = 0; i < 3; ++i) {+ const auto key = WaterProjectedMesh::SampleKey(float(frame * 3 + i), 0, 0);+ CHECK(!full.Find(key));+ full.Store(key, value);+ CHECK(full.Find(key) && Same(*full.Find(key), value));+ }+ CHECK(full.Size() == 3 && full.LiveSize() == 3);+ const auto denied = WaterProjectedMesh::SampleKey(float(frame * 3 + 3), 0, 0);+ full.Store(denied, value);+ CHECK(!full.Find(denied));+ for (int i = 0; i < 3; ++i) {+ const auto found = full.Find(WaterProjectedMesh::SampleKey(float(frame * 3 + i), 0, 0));+ CHECK(found && Same(*found, value));+ }+ }+ WaterProjectedSampleCache::Cache<Sample> cache(10000);+ cache.BeginRender();+ for (int i = 0; i < 9000; ++i)+ cache.Store(WaterProjectedMesh::SampleKey(float(i), 0, 0), value);+ cache.BeginRender();+ CHECK(cache.Size() == 9000 && cache.LiveSize() == 0);+ cache.Store(WaterProjectedMesh::SampleKey(0, 0, 0), value);+ cache.BeginRender();+ CHECK(cache.Size() == 0); // Large old view versus one live point.+ WaterProjectedSampleCache::Cache<Sample> disabled(0);+ disabled.BeginRender();+ disabled.Store(WaterProjectedMesh::SampleKey(0, 0, 0), value);+ CHECK(disabled.Size() == 0 && !disabled.Find(WaterProjectedMesh::SampleKey(0, 0, 0)));+ WaterProjectedSampleCache::Cache<Sample, uint8_t> wrapping(10);+ const auto anchor = WaterProjectedMesh::SampleKey(1, 2, 3), current = WaterProjectedMesh::SampleKey(4, 5, 6);+ wrapping.BeginRender();+ wrapping.Store(anchor, value);+ for (int frame = 2; frame <= 256; ++frame) {+ wrapping.BeginRender();+ CHECK(!wrapping.Find(anchor));+ CHECK(!wrapping.Find(current));+ wrapping.Store(current, value);+ CHECK(wrapping.Find(current));+ }+ CHECK(wrapping.Size() == 1); // Wrap discarded the old epoch-one anchor.+}+}++TEST(water_projected_sample_cache_refreshes_dynamic_inputs_once_per_render_and_reuses_nodes) {+ WaterProjectedSampleCacheTest::CheckDynamic();+}+TEST(water_projected_sample_cache_matches_per_render_map_and_keeps_partial_samples_unpublished) {+ WaterProjectedSampleCacheTest::CheckOracle();+}+TEST(water_projected_sample_cache_bounds_camera_history_invalidates_and_handles_epoch_wrap) {+ WaterProjectedSampleCacheTest::CheckBoundsAndWrap();+}diff --git a/GeneralsMD/Code/Tests/WaterShoreHistoryReference.h b/GeneralsMD/Code/Tests/WaterShoreHistoryReference.hnew file mode 100644index 000000000..0a923646a--- /dev/null+++ b/GeneralsMD/Code/Tests/WaterShoreHistoryReference.h@@ -0,0 +1,469 @@+// Frozen HEAD 3c1f8285 shore history oracle; only namespace renamed.+/* Render-only, fixed-world coastal foam history. Source physics is supplied by the caller. */+#pragma once+#include <algorithm>+#include <array>+#include <cmath>+#include <cstdint>+#include <limits>+#include <utility>+#include <vector>++namespace WaterShoreHistoryFrozenReference {+constexpr size_t MaxCells=65536,MaxLevels=8,MaxEdges=2*MaxCells;+constexpr double Tick=0.1;+constexpr uint64_t MaxCatchupTicks=8,MaxTickIndex=uint64_t(1)<<48;+// Keep absolute double clock resolution well below a fixed tick.+inline bool ValidTime(double time){return std::isfinite(time)&&std::abs(time)<=Tick*double(MaxTickIndex);}+struct Parameters {double lifetime=5,diffusivity=2,maximumRate=16;};+struct Grid {double originX=0,originY=0,spacing=5;};+// The caller only supplies actual wet terrain cells within its bounded coastal domain.+// Domain includes a wet-only spread margin around source cells, not dry validity-mask cells.+struct Cell {+ int32_t x=0,y=0;double level=0;+ uint32_t sourceIndex=0; // opaque index into the caller's immutable, per-revision source context+ uint8_t connections=3; // positive X/Y edges; builder proves each segment stays in the polygon union+};+struct State {double density=0,ageMoment=0;};+struct Edge {uint32_t a=0,b=0;};+inline bool Less(const Cell&a,const Cell&b) {+ if(a.level!=b.level)return a.level<b.level;+ if(a.y!=b.y)return a.y<b.y;+ return a.x<b.x;+}+inline bool SameKey(const Cell&a,const Cell&b){return a.level==b.level&&a.x==b.x&&a.y==b.y;}+inline double Clamp(double x,double low,double high){return (std::max)(low,(std::min)(high,x));}+inline bool ValidGrid(const Grid&g) {+ return std::isfinite(g.originX)&&std::isfinite(g.originY)&&std::isfinite(g.spacing)+ &&g.spacing>=1&&g.spacing<=1024;+}+inline bool ValidParameters(const Parameters&p,const Grid&g) {+ // Four-neighbour diffusion is a convex combination with >=1/2 self weight.+ return std::isfinite(p.lifetime)&&p.lifetime>=.1&&p.lifetime<=3600+ &&std::isfinite(p.diffusivity)&&p.diffusivity>=0&&4*p.diffusivity*Tick/(g.spacing*g.spacing)<=.5+ &&std::isfinite(p.maximumRate)&&p.maximumRate>=0&&p.maximumRate<=1000;+}+struct Decay {+ double q=1,elapsed=0,sourceDensity=0,sourceAge=0;+ static Decay Make(double seconds,double lifetime) {+ Decay d;d.elapsed=seconds;const double x=seconds/lifetime;+ if(x>700){d.q=0;d.sourceDensity=lifetime;d.sourceAge=lifetime*lifetime;return d;}+ d.q=std::exp(-x);const double oneMinus=-std::expm1(-x);+ // Stable integral of age*exp(-age/lifetime); no cancellation at small partial dt.+ const double moment=x<.05?x*x*(.5+x*(-1.0/3+x*(1.0/8+x*(-1.0/30+x*(1.0/144+x*(-1.0/840+x/5760))))))+ :oneMinus-x*d.q;+ d.sourceDensity=lifetime*oneMinus;d.sourceAge=lifetime*lifetime*moment;return d;+ }+ State Apply(const State&s,double rate)const {+ // The early q==0 case also avoids 0*(large elapsed*density) becoming NaN.+ if(q==0)return {rate*sourceDensity,rate*sourceAge};+ return {q*s.density+rate*sourceDensity,q*(s.ageMoment+elapsed*s.density)+rate*sourceAge};+ }+};+enum class BuildResult {Ready,TooManyCells,TooManyLevels,Invalid};+// Cached interpolation ownership. Every raster sample belongs to one half-open grid+// tile; indices retain the original dy/dx summation order and absent nodes stay -1.+struct RasterTile {+ int32_t x=0,y=0;double level=0;+ std::array<int32_t,4> nodes{{-1,-1,-1,-1}};+};+inline bool RasterLess(const RasterTile&a,const RasterTile&b) {+ if(a.level!=b.level)return a.level<b.level;+ if(a.y!=b.y)return a.y<b.y;return a.x<b.x;+}+class Topology {+ Grid grid;std::vector<Cell> cells;std::vector<Edge> edges;+ std::vector<RasterTile> rasterTiles;+ // Fixed open-address lookup: at most 1/2 occupancy, bounded allocations and no frame-time writes.+ std::vector<uint32_t> table;static constexpr uint32_t Empty=~uint32_t(0);+ static uint64_t Mix(uint64_t v){v^=v>>30;v*=0xbf58476d1ce4e5b9ULL;v^=v>>27;v*=0x94d049bb133111ebULL;return v^(v>>31);}+ uint64_t Hash(int32_t x,int32_t y,double level)const {+ // Level is located in a tiny sorted list, avoiding host-endian double byte hashing.+ const auto at=std::lower_bound(levels.begin(),levels.end(),level);+ const uint64_t l=uint64_t(at-levels.begin());+ return Mix(uint64_t(uint32_t(x))|(uint64_t(uint32_t(y))<<32))^Mix(l+0x9e3779b97f4a7c15ULL);+ }+ std::vector<double> levels;+public:+ BuildResult Build(const Grid&inputGrid,const std::vector<Cell>&input) {+ if(input.size()>MaxCells)return BuildResult::TooManyCells;+ if(!ValidGrid(inputGrid))return BuildResult::Invalid;+ Topology next;next.grid=inputGrid;next.cells=input;+ for(Cell&c:next.cells) {+ if(!std::isfinite(c.level)||!std::isfinite(inputGrid.originX+double(c.x)*inputGrid.spacing)+ ||!std::isfinite(inputGrid.originY+double(c.y)*inputGrid.spacing))return BuildResult::Invalid;+ if(c.level==0)c.level=0; // canonical positive zero+ }+ std::sort(next.cells.begin(),next.cells.end(),Less);+ for(size_t i=0;i<next.cells.size();++i) {+ if(i&&SameKey(next.cells[i-1],next.cells[i]))return BuildResult::Invalid;+ if(next.levels.empty()||next.levels.back()!=next.cells[i].level)next.levels.push_back(next.cells[i].level);+ }+ if(next.levels.size()>MaxLevels)return BuildResult::TooManyLevels;+ size_t size=2;while(size<2*next.cells.size())size*=2;+ next.table.assign(size,Empty);next.edges.reserve(2*next.cells.size());+ for(uint32_t i=0;i<next.cells.size();++i) {+ const Cell&c=next.cells[i];size_t slot=next.Hash(c.x,c.y,c.level)&(size-1);+ while(next.table[slot]!=Empty)slot=(slot+1)&(size-1);+ next.table[slot]=i;+ }+ for(uint32_t i=0;i<next.cells.size();++i) {+ const Cell&c=next.cells[i];int neighbour=-1;+ if((c.connections&1)&&c.x<(std::numeric_limits<int32_t>::max)())neighbour=next.Find(c.x+1,c.y,c.level);+ if(neighbour>=0)next.edges.push_back({i,uint32_t(neighbour)});+ if((c.connections&2)&&c.y<(std::numeric_limits<int32_t>::max)())neighbour=next.Find(c.x,c.y+1,c.level);else neighbour=-1;+ if(neighbour>=0)next.edges.push_back({i,uint32_t(neighbour)});+ }+ if(next.edges.size()>MaxEdges)return BuildResult::Invalid;+ // Build at most four contributions per node once per geometry revision, not+ // four hash lookups per atlas texel on every history upload.+ next.rasterTiles.reserve(4*next.cells.size());+ for(uint32_t i=0;i<next.cells.size();++i) {+ const Cell&c=next.cells[i];+ for(unsigned dy=0;dy<2;++dy)for(unsigned dx=0;dx<2;++dx) {+ const int64_t x=int64_t(c.x)-dx,y=int64_t(c.y)-dy;+ // Sample permits floor indices [INT_MIN,INT_MAX), with +1 neighbours.+ if(x<(std::numeric_limits<int32_t>::min)()||y<(std::numeric_limits<int32_t>::min)()+ ||x>=(std::numeric_limits<int32_t>::max)()||y>=(std::numeric_limits<int32_t>::max)())continue;+ RasterTile tile;tile.x=int32_t(x);tile.y=int32_t(y);tile.level=c.level;tile.nodes[dy*2+dx]=int32_t(i);+ next.rasterTiles.push_back(tile);+ }+ }+ std::sort(next.rasterTiles.begin(),next.rasterTiles.end(),RasterLess);+ size_t kept=0;+ for(size_t read=0;read<next.rasterTiles.size();++read) {+ const RasterTile tile=next.rasterTiles[read];+ if(kept&&next.rasterTiles[kept-1].x==tile.x&&next.rasterTiles[kept-1].y==tile.y&&next.rasterTiles[kept-1].level==tile.level) {+ for(unsigned n=0;n<4;++n)if(tile.nodes[n]>=0)next.rasterTiles[kept-1].nodes[n]=tile.nodes[n];+ } else next.rasterTiles[kept++]=tile;+ }+ next.rasterTiles.resize(kept);+ *this=std::move(next);return BuildResult::Ready;+ }+ int Find(int32_t x,int32_t y,double level)const {+ if(table.empty()||!std::isfinite(level))return -1;+ size_t slot=Hash(x,y,level)&(table.size()-1);+ for(size_t attempts=0;attempts<table.size();++attempts) {+ const uint32_t index=table[slot];if(index==Empty)return -1;+ const Cell&c=cells[index];if(c.x==x&&c.y==y&&c.level==level)return int(index);+ slot=(slot+1)&(table.size()-1);+ }+ return -1;+ }+ bool SameGeometry(const Topology&o)const {+ if(grid.originX!=o.grid.originX||grid.originY!=o.grid.originY||grid.spacing!=o.grid.spacing||cells.size()!=o.cells.size())return false;+ for(size_t i=0;i<cells.size();++i)if(!SameKey(cells[i],o.cells[i])||cells[i].connections!=o.cells[i].connections)return false;+ return true;+ }+ const Grid& Geometry()const{return grid;}+ const std::vector<Cell>& Cells()const{return cells;}+ const std::vector<Edge>& Edges()const{return edges;}+ const std::vector<RasterTile>& RasterTiles()const{return rasterTiles;}+};+// One full operator: exact source/decay/age integration for constant rate over dt, followed+// by conservative reciprocal wet-neighbour diffusion. The latter is first-order in time,+// not claimed to be an exact heat solver. Fixed global ticks make render schedules irrelevant.+inline bool Step(const Topology&topology,const Parameters¶meters,const std::vector<State>&input,+ const std::vector<double>&rates,double dt,std::vector<State>&decayed,std::vector<State>&output) {+ const size_t count=topology.Cells().size();+ if(input.size()!=count||rates.size()!=count||&input==&decayed||&input==&output||&decayed==&output+ ||!std::isfinite(dt)||dt<0||dt>Tick+1e-12||!ValidParameters(parameters,topology.Geometry()))return false;+ for(const State&s:input)if(!std::isfinite(s.density)||!std::isfinite(s.ageMoment)||s.density<0||s.ageMoment<0)return false;+ const Decay decay=Decay::Make(dt,parameters.lifetime);+ decayed.resize(count);output.resize(count);+ for(size_t i=0;i<count;++i) {+ const double rate=std::isfinite(rates[i])?Clamp(rates[i],0,parameters.maximumRate):0;+ output[i]=decayed[i]=decay.Apply(input[i],rate);+ }+ const double amount=parameters.diffusivity*dt/(topology.Geometry().spacing*topology.Geometry().spacing);+ for(const Edge&e:topology.Edges()) {+ const double density=amount*(decayed[e.b].density-decayed[e.a].density);+ const double age=amount*(decayed[e.b].ageMoment-decayed[e.a].ageMoment);+ output[e.a].density+=density;output[e.b].density-=density;+ output[e.a].ageMoment+=age;output[e.b].ageMoment-=age;+ }+ return true;+}+enum class AdvanceResult {Advanced,Unchanged,Rewound,GapDecayed,Invalid};+class History {+ Topology topology;Parameters parameters;std::vector<State> committed,preview,decayed,next;+ std::vector<double> rates;uint64_t revision=0,completed=0;double epoch=0,observed=0;+ bool installed=false,previewDirty=false;+ void ClearDynamic(double time) {+ std::fill(committed.begin(),committed.end(),State{});preview=committed;+ epoch=observed=time;completed=0;previewDirty=false;+ }+ template<class Source> void Fill(Source&source,double time) {+ std::fill(rates.begin(),rates.end(),0.0);+ // Batch callback permits three shared temporal sin/cos pairs, not per-cell transcendental work.+ source(time,topology.Cells().data(),topology.Cells().size(),rates.data());+ }+public:+ // Exact keys + revision preserve dynamic state through device refresh and reordered source tables.+ // A new map/terrain/polygon revision clears history even when coordinates happen to match.+ BuildResult Install(const Grid&grid,const std::vector<Cell>&cells,uint64_t mapRevision,double time,+ Parameters settings=Parameters()) {+ if(!ValidTime(time)||!ValidGrid(grid)||!ValidParameters(settings,grid))return BuildResult::Invalid;+ Topology candidate;const BuildResult result=candidate.Build(grid,cells);if(result!=BuildResult::Ready)return result;+ const bool reuse=installed&&revision==mapRevision&&topology.SameGeometry(candidate)+ &&settings.lifetime==parameters.lifetime&&settings.diffusivity==parameters.diffusivity&&settings.maximumRate==parameters.maximumRate;+ topology=std::move(candidate);parameters=settings;revision=mapRevision;installed=true;+ if(!reuse) {+ committed.assign(cells.size(),{});preview.resize(cells.size());decayed.resize(cells.size());next.resize(cells.size());rates.resize(cells.size());ClearDynamic(time);+ }+ return BuildResult::Ready;+ }+ void Clear(){*this=History();}+ bool ValidFor(uint64_t mapRevision)const{return installed&&mapRevision==revision;}+ template<class Source> AdvanceResult Advance(double time,Source&source) {+ if(!installed||!ValidTime(time))return AdvanceResult::Invalid;+ if(time==observed)return AdvanceResult::Unchanged;+ if(time<observed){ClearDynamic(time);return AdvanceResult::Rewound;}+ const double ratio=(time-epoch)/Tick;+ if(!std::isfinite(ratio)||ratio>double(MaxTickIndex))return AdvanceResult::Invalid;+ uint64_t wanted=uint64_t(std::floor(ratio));+ // Compare the actual fixed-clock boundaries, correcting representational division noise.+ while(epoch+double(wanted)*Tick>time)--wanted;+ while(wanted<MaxTickIndex&&epoch+double(wanted+1)*Tick<=time)++wanted;+ if(wanted-completed>MaxCatchupTicks) {+ // Preserve the last observed partial field, even if no atlas requested it yet.+ // Only the genuinely unseen interval suppresses births and diffusion.+ committed=Preview(source);+ const Decay decay=Decay::Make(time-observed,parameters.lifetime);+ for(State&s:committed)s=decay.Apply(s,0);+ preview=committed;epoch=observed=time;completed=0;previewDirty=false;+ return AdvanceResult::GapDecayed; // no invented births during an unseen large gap+ }+ while(completed<wanted) {+ Fill(source,epoch+(double(completed)+.5)*Tick);+ // The mathematical fixed step is Tick; subtracting large absolute timestamps+ // would introduce an age/diffusion error and can exceed Tick by roundoff.+ if(!Step(topology,parameters,committed,rates,Tick,decayed,next))return AdvanceResult::Invalid;+ committed.swap(next);++completed;+ }+ observed=time;previewDirty=true;return AdvanceResult::Advanced;+ }+ template<class Source> const std::vector<State>& Preview(Source&source) {+ if(!previewDirty)return preview;+ const double anchor=epoch+double(completed)*Tick,partial=Clamp(observed-anchor,0,Tick);+ if(partial<=0)preview=committed;+ else {+ Fill(source,(anchor+observed)*.5);+ if(!Step(topology,parameters,committed,rates,partial,decayed,preview))preview=committed;+ }+ previewDirty=false;return preview;+ }+ const std::vector<State>& Committed()const{return committed;}+ const Topology& Domain()const{return topology;}+ double Time()const{return observed;}+ double CommittedTime()const{return epoch+double(completed)*Tick;}+};+// Bilinear interpolation of density and age MOMENTS, never unweighted average age.+struct UnrestrictedSupport {+ struct Stencil {bool Allows(unsigned,unsigned)const{return true;}};+ Stencil At(int32_t,int32_t,double,double,double)const{return {};}+};+template<class Support> inline State Sample(const Topology&topology,const std::vector<State>&states,double x,double y,double level,const Support&support) {+ if(states.size()!=topology.Cells().size()||!std::isfinite(x)||!std::isfinite(y)||!std::isfinite(level))return {};+ const Grid&g=topology.Geometry();const double px=(x-g.originX)/g.spacing,py=(y-g.originY)/g.spacing;+ if(!std::isfinite(px)||!std::isfinite(py)||px<(std::numeric_limits<int32_t>::min)()||py<(std::numeric_limits<int32_t>::min)()+ ||px>=(std::numeric_limits<int32_t>::max)()||py>=(std::numeric_limits<int32_t>::max)())return {};+ const int32_t ix=int32_t(std::floor(px)),iy=int32_t(std::floor(py));const double fx=px-ix,fy=py-iy;State out;+ const auto stencil=support.At(ix,iy,level,fx,fy);+ for(int dy=0;dy<2;++dy)for(int dx=0;dx<2;++dx) {+ const int index=topology.Find(ix+dx,iy+dy,level);if(index<0)continue;+ const double weight=(dx?fx:1-fx)*(dy?fy:1-fy);+ // Zero rejected contributions without redistributing their weight to another shore.+ if(weight<=0 || !stencil.Allows(unsigned(dx),unsigned(dy)))continue;+ out.density+=states[size_t(index)].density*weight;out.ageMoment+=states[size_t(index)].ageMoment*weight;+ }+ return out;+}+inline State Sample(const Topology&topology,const std::vector<State>&states,double x,double y,double level) {+ return Sample(topology,states,x,y,level,UnrestrictedSupport{});+}+inline uint32_t WithAlpha(uint32_t vesselARGB,double coverage) {+ const uint32_t alpha=std::isfinite(coverage)?uint32_t(Clamp(coverage,0,1)*255+.5):0;+ return (vesselARGB&0x00ffffffu)|(alpha<<24);+}+struct Mapping {double originX=0,originY=0,widthWorld=0,heightWorld=0;unsigned widthPixels=0,heightPixels=0;};+template<class Coverage,class Support> inline bool RasterizeAlpha(const Topology&topology,const std::vector<State>&states,+ const Mapping&mapping,double level,double time,Coverage&coverage,std::vector<uint32_t>&vesselARGB,const Support&support) {+ if(!std::isfinite(mapping.originX)||!std::isfinite(mapping.originY)||!std::isfinite(mapping.widthWorld)+ ||!std::isfinite(mapping.heightWorld)||mapping.widthWorld<=0||mapping.heightWorld<=0+ ||!std::isfinite(mapping.originX+mapping.widthWorld)||!std::isfinite(mapping.originY+mapping.heightWorld)+ ||!mapping.widthPixels||!mapping.heightPixels||mapping.widthPixels>512||mapping.heightPixels>512+ ||!std::isfinite(level)||!std::isfinite(time)||states.size()!=topology.Cells().size()+ ||vesselARGB.size()!=size_t(mapping.widthPixels)*mapping.heightPixels)return false;+ // Clear stale coast alpha everywhere without changing vessel RGB. Empty or offscreen+ // history then costs only this linear write, not per-pixel support and hash searches.+ for(uint32_t&pixel:vesselARGB)pixel&=0x00ffffffu;+ struct Axis {double world=0,fraction=0;int64_t key=0;};+ std::array<Axis,512> horizontal,vertical;+ const Grid&g=topology.Geometry();+ auto axis=[](std::array<Axis,512>&out,unsigned count,double origin,double extent,double gridOrigin,double spacing) {+ for(unsigned i=0;i<count;++i) {+ Axis&a=out[i];+ // Preserve Sample's arithmetic, including overflow/out-of-grid rejection.+ a.world=origin+(double(i)+.5)*extent/count;+ const double p=(a.world-gridOrigin)/spacing;+ if(!std::isfinite(p)||p<(std::numeric_limits<int32_t>::min)()||p>=(std::numeric_limits<int32_t>::max)()) {+ a.key=p<(std::numeric_limits<int32_t>::min)()?(std::numeric_limits<int64_t>::min)():(std::numeric_limits<int64_t>::max)();+ } else {a.key=int32_t(std::floor(p));a.fraction=p-double(a.key);}+ }+ };+ axis(horizontal,mapping.widthPixels,mapping.originX,mapping.widthWorld,g.originX,g.spacing);+ axis(vertical,mapping.heightPixels,mapping.originY,mapping.heightWorld,g.originY,g.spacing);+ auto first=[](const std::array<Axis,512>&a,unsigned count,int64_t key) {+ return unsigned(std::lower_bound(a.begin(),a.begin()+count,key,[](const Axis&v,int64_t k){return v.key<k;})-a.begin());+ };+ auto after=[](const std::array<Axis,512>&a,unsigned count,int64_t key) {+ return unsigned(std::upper_bound(a.begin(),a.begin()+count,key,[](int64_t k,const Axis&v){return k<v.key;})-a.begin());+ };+ for(const RasterTile&tile:topology.RasterTiles()) {+ if(tile.level!=level||tile.x<horizontal[0].key||tile.x>horizontal[mapping.widthPixels-1].key+ ||tile.y<vertical[0].key||tile.y>vertical[mapping.heightPixels-1].key)continue;+ bool active=false;for(int32_t node:tile.nodes)if(node>=0&&states[size_t(node)].density>0){active=true;break;}+ if(!active)continue;+ const unsigned x0=first(horizontal,mapping.widthPixels,tile.x),x1=after(horizontal,mapping.widthPixels,tile.x);+ if(x0==x1)continue;+ const unsigned y0=first(vertical,mapping.heightPixels,tile.y),y1=after(vertical,mapping.heightPixels,tile.y);+ for(unsigned y=y0;y<y1;++y)for(unsigned x=x0;x<x1;++x) {+ const double fx=horizontal[x].fraction,fy=vertical[y].fraction;State state;+ const auto stencil=support.At(tile.x,tile.y,level,fx,fy);+ for(unsigned dy=0;dy<2;++dy)for(unsigned dx=0;dx<2;++dx) {+ const int32_t node=tile.nodes[dy*2+dx];if(node<0)continue;+ const double weight=(dx?fx:1-fx)*(dy?fy:1-fy);+ if(weight<=0||!stencil.Allows(dx,dy))continue;+ state.density+=states[size_t(node)].density*weight;state.ageMoment+=states[size_t(node)].ageMoment*weight;+ }+ const double value=state.density>0?coverage(state,horizontal[x].world,vertical[y].world,time):0;+ const size_t n=size_t(y)*mapping.widthPixels+x;vesselARGB[n]=WithAlpha(vesselARGB[n],value);+ }+ }+ return true;+}++template<class Coverage> inline bool RasterizeAlpha(const Topology&topology,const std::vector<State>&states,+ const Mapping&mapping,double level,double time,Coverage&coverage,std::vector<uint32_t>&vesselARGB) {+ return RasterizeAlpha(topology,states,mapping,level,time,coverage,vesselARGB,UnrestrictedSupport{});+}++// One bounded camera mapping. The dependency revision must change whenever the+// topology or support geometry changes; neither density/age nor time is cached.+// Support::At/Allows must be pure within that immutable revision.+class RasterLookup {+ struct Axis {double world=0,fraction=0;int64_t key=0;};+ struct TileRange {uint32_t tile=0;uint16_t x0=0,x1=0,y0=0,y1=0;};+ std::array<Axis,512> horizontal{},vertical{};+ std::vector<TileRange> ranges;+ std::vector<uint8_t> masks;+ const Topology *owner=nullptr;const void *supportOwner=nullptr;+ Mapping mapping;double level=0;uint64_t revision=0,builds=0;+ size_t sampleCount=0;+ static bool Same(double a,double b){return a==b&&(a!=0||std::signbit(a)==std::signbit(b));}+ static bool Valid(const Mapping&m,double l) {+ return std::isfinite(m.originX)&&std::isfinite(m.originY)&&std::isfinite(m.widthWorld)+ &&std::isfinite(m.heightWorld)&&m.widthWorld>0&&m.heightWorld>0+ &&std::isfinite(m.originX+m.widthWorld)&&std::isfinite(m.originY+m.heightWorld)+ &&m.widthPixels&&m.heightPixels&&m.widthPixels<=512&&m.heightPixels<=512&&std::isfinite(l);+ }+public:+ static constexpr size_t MaximumPixels=512*512;+ void Clear(){*this=RasterLookup();}+ uint64_t BuildCount()const{return builds;}+ size_t SampleCount()const{return sampleCount;}+ size_t TileCount()const{return ranges.size();}+ size_t MemoryBytes()const{return sizeof(*this)+ranges.capacity()*sizeof(TileRange)+masks.capacity();}+ bool Matches(const Topology&t,const Mapping&m,double l,uint64_t dependency,const void *support)const {+ return owner==&t&&supportOwner==support&&revision==dependency&&revision!=0&&Same(level,l)+ &&Same(mapping.originX,m.originX)&&Same(mapping.originY,m.originY)+ &&Same(mapping.widthWorld,m.widthWorld)&&Same(mapping.heightWorld,m.heightWorld)+ &&mapping.widthPixels==m.widthPixels&&mapping.heightPixels==m.heightPixels;+ }+ template<class Support> bool Prepare(const Topology&t,const Mapping&m,double l,uint64_t dependency,const Support&support) {+ if(!dependency||!Valid(m,l))return false;+ if(Matches(t,m,l,dependency,&support))return true;+ RasterLookup next;next.owner=&t;next.supportOwner=&support;next.mapping=m;next.level=l;next.revision=dependency;+ next.builds=builds+1;if(!next.builds)next.builds=1;+ const Grid&g=t.Geometry();+ auto axis=[](std::array<Axis,512>&out,unsigned count,double origin,double extent,double gridOrigin,double spacing) {+ for(unsigned i=0;i<count;++i) {+ Axis&a=out[i];a.world=origin+(double(i)+.5)*extent/count;+ const double p=(a.world-gridOrigin)/spacing;+ if(!std::isfinite(p)||p<(std::numeric_limits<int32_t>::min)()||p>=(std::numeric_limits<int32_t>::max)())+ a.key=p<(std::numeric_limits<int32_t>::min)()?(std::numeric_limits<int64_t>::min)():(std::numeric_limits<int64_t>::max)();+ else {a.key=int32_t(std::floor(p));a.fraction=p-double(a.key);}+ }+ };+ axis(next.horizontal,m.widthPixels,m.originX,m.widthWorld,g.originX,g.spacing);+ axis(next.vertical,m.heightPixels,m.originY,m.heightWorld,g.originY,g.spacing);+ auto first=[](const std::array<Axis,512>&a,unsigned count,int64_t key) {+ return unsigned(std::lower_bound(a.begin(),a.begin()+count,key,[](const Axis&v,int64_t k){return v.key<k;})-a.begin());+ };+ auto after=[](const std::array<Axis,512>&a,unsigned count,int64_t key) {+ return unsigned(std::upper_bound(a.begin(),a.begin()+count,key,[](int64_t k,const Axis&v){return k<v.key;})-a.begin());+ };+ next.masks.assign(size_t(m.widthPixels)*m.heightPixels,0);+ next.ranges.reserve((std::min)(t.RasterTiles().size(),next.masks.size()));+ for(size_t i=0;i<t.RasterTiles().size();++i) {+ const RasterTile&tile=t.RasterTiles()[i];+ if(tile.level!=l||tile.x<next.horizontal[0].key||tile.x>next.horizontal[m.widthPixels-1].key+ ||tile.y<next.vertical[0].key||tile.y>next.vertical[m.heightPixels-1].key)continue;+ const unsigned x0=first(next.horizontal,m.widthPixels,tile.x),x1=after(next.horizontal,m.widthPixels,tile.x);+ if(x0==x1)continue;+ const unsigned y0=first(next.vertical,m.heightPixels,tile.y),y1=after(next.vertical,m.heightPixels,tile.y);+ if(y0==y1)continue;+ next.ranges.push_back({uint32_t(i),uint16_t(x0),uint16_t(x1),uint16_t(y0),uint16_t(y1)});+ for(unsigned y=y0;y<y1;++y)for(unsigned x=x0;x<x1;++x) {+ const double fx=next.horizontal[x].fraction,fy=next.vertical[y].fraction;+ const auto stencil=support.At(tile.x,tile.y,l,fx,fy);uint8_t mask=0;+ for(unsigned dy=0;dy<2;++dy)for(unsigned dx=0;dx<2;++dx) {+ const unsigned corner=dy*2+dx;if(tile.nodes[corner]<0)continue;+ const double weight=(dx?fx:1-fx)*(dy?fy:1-fy);+ if(weight>0&&stencil.Allows(dx,dy))mask|=uint8_t(1u<<corner);+ }+ next.masks[size_t(y)*m.widthPixels+x]=mask;++next.sampleCount;+ }+ }+ *this=std::move(next);return true;+ }+ // Prepare camera-fixed caller data, e.g. shoreline spatial breakup, once+ // per BuildCount. Pixel ownership is unique and follows the original order.+ template<class Function> void ForEachSample(Function function)const {+ for(const TileRange&r:ranges)for(unsigned y=r.y0;y<r.y1;++y)for(unsigned x=r.x0;x<r.x1;++x)+ function(size_t(y)*mapping.widthPixels+x,horizontal[x].world,vertical[y].world);+ }+ template<class Coverage> bool Rasterize(const std::vector<State>&states,double time,Coverage&coverage,std::vector<uint32_t>&pixels)const {+ if(!owner||!std::isfinite(time)||states.size()!=owner->Cells().size()||pixels.size()!=masks.size())return false;+ for(uint32_t&pixel:pixels)pixel&=0x00ffffffu;+ for(const TileRange&r:ranges) {+ const RasterTile&tile=owner->RasterTiles()[r.tile];+ bool active=false;for(int32_t node:tile.nodes)if(node>=0&&states[size_t(node)].density>0){active=true;break;}+ if(!active)continue;+ for(unsigned y=r.y0;y<r.y1;++y)for(unsigned x=r.x0;x<r.x1;++x) {+ const double fx=horizontal[x].fraction,fy=vertical[y].fraction;State state;+ const size_t n=size_t(y)*mapping.widthPixels+x;const uint8_t mask=masks[n];+ for(unsigned dy=0;dy<2;++dy)for(unsigned dx=0;dx<2;++dx) {+ const unsigned corner=dy*2+dx;if(!(mask&(1u<<corner)))continue;+ const double weight=(dx?fx:1-fx)*(dy?fy:1-fy);+ state.density+=states[size_t(tile.nodes[corner])].density*weight;+ state.ageMoment+=states[size_t(tile.nodes[corner])].ageMoment*weight;+ }+ const double value=state.density>0?coverage(state,horizontal[x].world,vertical[y].world,time,n):0;+ pixels[n]=WithAlpha(pixels[n],value);+ }+ }+ return true;+ }+};+template<class Coverage,class Support> inline bool RasterizeAlphaCached(const Topology&topology,const std::vector<State>&states,+ const Mapping&mapping,double level,double time,Coverage&coverage,std::vector<uint32_t>&pixels,const Support&support,+ RasterLookup&lookup,uint64_t dependencyRevision) {+ if(!std::isfinite(time)||states.size()!=topology.Cells().size()||pixels.size()!=size_t(mapping.widthPixels)*mapping.heightPixels+ ||!lookup.Prepare(topology,mapping,level,dependencyRevision,support))return false;+ auto material=[&](const State&s,double x,double y,double t,size_t){return coverage(s,x,y,t);};+ return lookup.Rasterize(states,time,material,pixels);+}++}diff --git a/GeneralsMD/Code/Tests/WaterShorePreparedTest.h b/GeneralsMD/Code/Tests/WaterShorePreparedTest.hnew file mode 100644index 000000000..8f8304faa--- /dev/null+++ b/GeneralsMD/Code/Tests/WaterShorePreparedTest.h@@ -0,0 +1,178 @@+#pragma once+#include "WaterShoreHistoryReference.h"+#include "Platform/WaterShoreHistory.h"++namespace WaterShorePreparedTest {+namespace Old = WaterShoreHistoryFrozenReference;+namespace New = WaterShoreHistory;++struct Source {+ std::vector<double> times;+ std::vector<uint32_t> indices;+ template <class Cell> void operator()(double time, const Cell *cells, size_t count, double *rates) {+ times.push_back(time);+ for (size_t i = 0; i < count; ++i) {+ indices.push_back(cells[i].sourceIndex);+ rates[i] = (1 + cells[i].sourceIndex % 7) * (.4 + .1 * std::sin(time * 1.7 + cells[i].x * .2+ + cells[i].y * .4));+ }+ }+};++inline std::vector<New::Cell> Cells() {+ std::vector<New::Cell> out;+ for (double level :{8., 11.})+ for (int y = -2; y <= 2; ++y)+ for (int x = -2; x <= 2; ++x)+ if (x || y)+ out.push_back({x, y, level, uint32_t(out.size()), uint8_t((x == 1 ? 0 : 1) | (y == 1 ? 0 : 2))});+ return out;+}++inline std::vector<Old::Cell> OldCells(const std::vector<New::Cell> &cells) {+ std::vector<Old::Cell> out;+ for (const auto &c : cells)+ out.push_back({c.x, c.y, c.level, c.sourceIndex, c.connections});+ return out;+}++template <class A, class B> inline void States(const A &a, const B &b) {+ CHECK(a.size() == b.size());+ if (a.size() != b.size())+ return;+ for (size_t i = 0; i < a.size(); ++i) {+ CHECK(projectedCacheSameDouble(a[i].density, b[i].density));+ CHECK(projectedCacheSameDouble(a[i].ageMoment, b[i].ageMoment));+ }+}+struct Fixture {+ Old::History old;+ New::History normal, prepared;+ Source oldSource, normalSource, preparedSource;+ void Check() {+ CHECK(projectedCacheSameDouble(old.Time(), normal.Time()));+ CHECK(projectedCacheSameDouble(old.Time(), prepared.Time()));+ CHECK(projectedCacheSameDouble(old.CommittedTime(), normal.CommittedTime()));+ CHECK(projectedCacheSameDouble(old.CommittedTime(), prepared.CommittedTime()));+ States(old.Committed(), normal.Committed());+ States(old.Committed(), prepared.Committed());+ States(old.Preview(oldSource), normal.Preview(normalSource));+ States(old.Preview(oldSource), prepared.Preview(preparedSource));+ CHECK(oldSource.times == normalSource.times && oldSource.times == preparedSource.times);+ CHECK(oldSource.indices == normalSource.indices && oldSource.indices == preparedSource.indices);+ const auto &a = old.Domain();+ const auto &b = normal.Domain();+ const auto &c = prepared.Domain();+ CHECK(a.Cells().size() == b.Cells().size() && a.Cells().size() == c.Cells().size());+ if (a.Cells().size() == c.Cells().size())+ for (size_t i = 0; i < a.Cells().size(); ++i) {+ CHECK(a.Cells()[i].x == c.Cells()[i].x && a.Cells()[i].y == c.Cells()[i].y &&+ projectedCacheSameDouble(a.Cells()[i].level, c.Cells()[i].level) &&+ a.Cells()[i].sourceIndex == c.Cells()[i].sourceIndex && a.Cells()[i].connections == c.Cells()[i].connections);+ }+ CHECK(a.Edges().size() == b.Edges().size() && a.Edges().size() == c.Edges().size());+ if (a.Edges().size() == c.Edges().size())+ for (size_t i = 0; i < a.Edges().size(); ++i)+ CHECK(a.Edges()[i].a == c.Edges()[i].a && a.Edges()[i].b == c.Edges()[i].b);+ CHECK(a.RasterTiles().size() == b.RasterTiles().size() && a.RasterTiles().size() == c.RasterTiles().size());+ if (a.RasterTiles().size() == c.RasterTiles().size())+ for (size_t i = 0; i < a.RasterTiles().size(); ++i) {+ const auto &x = a.RasterTiles()[i];+ const auto &y = c.RasterTiles()[i];+ CHECK(x.x == y.x && x.y == y.y && projectedCacheSameDouble(x.level, y.level) && x.nodes == y.nodes);+ }+ }+ void Install(const std::vector<New::Cell> &cells, uint64_t revision, double time,+ New::Parameters settings = New::Parameters(),+ New::Topology *prebuilt = nullptr) {+ const New::Grid grid{-13, 17, 5};+ const Old::Grid oldGrid{grid.originX, grid.originY, grid.spacing};+ const Old::Parameters oldSettings{settings.lifetime, settings.diffusivity, settings.maximumRate};+ New::Topology topology;+ New::BuildResult built;+ if (prebuilt) {+ topology = std::move(*prebuilt);+ built = New::BuildResult::Ready;+ }+ else+ built = topology.Build(grid, cells); // No history timestamp or source sample is touched here.+ const auto expected = old.Install(oldGrid, OldCells(cells), revision, time, oldSettings);+ const auto ordinary = normal.Install(grid, cells, revision, time, settings);+ const auto result = built == New::BuildResult::Ready ? prepared.InstallPrepared(std::move(topology),+ revision, time, settings) : built;+ CHECK(unsigned(expected) == unsigned(ordinary) && unsigned(expected) == unsigned(result));+ if (built == New::BuildResult::Ready &&result == New::BuildResult::Invalid)+ CHECK(topology.Cells().size() == cells.size()); // Invalid activation must not consume its candidate.+ CHECK(old.ValidFor(revision) == normal.ValidFor(revision)+ && old.ValidFor(revision) == prepared.ValidFor(revision));+ Check();+ }+ void Advance(double time) {+ const auto a = old.Advance(time, oldSource);+ const auto b = normal.Advance(time, normalSource);+ const auto c = prepared.Advance(time, preparedSource);+ CHECK(unsigned(a) == unsigned(b) && unsigned(a) == unsigned(c));+ Check();+ }+ void Clear() {+ old.Clear();+ normal.Clear();+ prepared.Clear();+ Check();+ }+};++inline void Check() {+ for (double start :{-3.271, 0., 12345.678}) {+ Fixture f;+ auto cells = Cells();+ // Static construction precedes the first nonzero live timestamp. It must+ // neither install history nor sample any temporal source during loading.+ New::Topology pending;+ CHECK(pending.Build({-13, 17, 5}, cells) == New::BuildResult::Ready);+ CHECK(!f.prepared.ValidFor(7) && f.prepared.Time() == 0 && f.prepared.Committed().empty());+ CHECK(f.preparedSource.times.empty());+ f.Install(cells, 7, start, New::Parameters(), &pending);+ f.Advance(start);+ for (double delta :{.037, .1, .117, .267, .8, 4.3, 4.3, 4.1, 4.16, 4.6})+ f.Advance(start + delta);+ std::reverse(cells.begin(), cells.end());+ for (auto &cell : cells)+ cell.sourceIndex += 101;+ // Same geometry retains both moments AND the original epoch, even when+ // the caller supplies a different timestamp and reordered source indices.+ f.Install(cells, 7, start + 50);+ f.Advance(start + 4.7);+ f.Install(cells, 8, start + 6.123);+ f.Advance(start + 6.17);+ New::Parameters changed;+ changed.lifetime = 2.4;+ changed.diffusivity = .5;+ changed.maximumRate = 7;+ f.Install(cells, 8, start + 7.29, changed);+ f.Advance(start + 7.347);+ f.Install(cells, 9, NAN); // Failure leaves the previous history untouched.+ f.Install(cells, 9, INFINITY);+ New::Parameters invalid;+ invalid.lifetime = 0;+ f.Install(cells, 9, start + 8, invalid);+ invalid = New::Parameters();+ invalid.diffusivity = 1e9;+ f.Install(cells, 9, start + 8, invalid);+ auto duplicate = cells;+ duplicate.push_back(cells.front());+ f.Install(duplicate, 9, start + 8);+ auto excessive = cells;+ excessive.resize(New::MaxCells + 1);+ f.Install(excessive, 9, start + 8);+ f.Clear();+ CHECK(!f.prepared.ValidFor(8));+ // Invalidation discards the prior live phase; rebuilding the same map+ // still starts at its next ORIGINAL live timestamp, never loading time.+ f.Install(cells, 10, start + 10.731);+ f.Advance(start + 10.768);+ f.Install({}, 11, start + 12.123);+ f.Advance(start + 12.16); // Successfully built empty topology.+ }+}+}diff --git a/GeneralsMD/Code/Tests/WaterShoreSourcePerfTest.h b/GeneralsMD/Code/Tests/WaterShoreSourcePerfTest.hnew file mode 100644index 000000000..21cea2a72--- /dev/null+++ b/GeneralsMD/Code/Tests/WaterShoreSourcePerfTest.h@@ -0,0 +1,131 @@+#pragma once+#include "Platform/WaterShoreSource.h"+#include "WaterShoreSourceReference.h"+#include <cstring>+#include <limits>+namespace WaterShoreSourcePerfTest {+struct Fixture {+ int width = 65, height = 49;+ std::vector<uint8_t> heights;+ std::vector<WaterOpticalContext::Polygon> polygons;+ WaterOpticalContext::Field field;+ Fixture() {+ heights.resize(size_t(width) * height);+ for (int y = 0; y < height; ++y)+ for (int x = 0; x < width; ++x)+ heights[size_t(y) * width + x] = uint8_t((std::max)(0, 20 - std::abs(x - width / 2)));+ WaterOpticalContext::Polygon polygon;+ polygon.points = {{0, 0, 10}, {640, 0, 10}, {640, 480, 10}, {0, 480, 10}};+ polygons.push_back(polygon);+ CHECK(WaterOpticalContext::Build(heights.data(), width, height, 0, 10, 1, 10, polygons, field));+ }+};++template <class T> bool SameBits(T a, T b) {+ return std::memcmp(&a, &b, sizeof(T)) == 0;+}++inline void CheckRate() {+ uint32_t random = 0x78563412;+ auto next = [&]() {+ random = random * 1664525u + 1013904223u;+ return float(random >> 8) / 16777215.0f;+ };+ for (unsigned i = 0; i < 10000; ++i) {+ WaterShoreFoam::Context c = {next() * 18 - 1, next() * 14 - 2, next() * 2 - 1, next() * 2 - 1,+ next() * 2 - .1f, next() * 1.8f - .4f, next() * 1.4f - .2f};+ WaterShoreFoam::Wave w = {next() * 7 - 3, next() * 4 - 2, next() * 4 - 2, next() * 8 - 4};+ if (i % 31 == 0)+ c.depth = WaterShoreFoam::MinDepth;+ if (i % 37 == 0)+ c.nx = c.ny = 0;+ if (i % 41 == 0)+ w.dt = 0;+ if (i % 43 == 0)+ w.dx = w.dy = 0;+ CHECK(SameBits(WaterShoreFoam::Rate(c, w),+ WaterShoreSource::PreparedRate(WaterShoreSource::PrepareRate(c), w)));+ }+ for (float invalid :{std::numeric_limits<float>::quiet_NaN(), std::numeric_limits<float>::infinity(),+ -std::numeric_limits<float>::infinity()}) {+ for (unsigned field = 0; field < 7; ++field) {+ WaterShoreFoam::Context c = {1, 2, -.8f, .1f, .5f, .7f, .8f};+ float *at[] = {&c.depth, &c.shore, &c.nx, &c.ny, &c.slope, &c.exposure, &c.support};+ *at[field] = invalid;+ const WaterShoreFoam::Wave w = {1, .2f, .3f, -.7f};+ CHECK(SameBits(WaterShoreFoam::Rate(c, w),+ WaterShoreSource::PreparedRate(WaterShoreSource::PrepareRate(c), w)));+ }+ }+}++inline void CheckBatch() {+ Fixture fixture;+ WaterShoreSource::Batch actual;+ WaterShoreSourceReference::Batch original;+ CHECK(actual.Build(fixture.heights.data(), fixture.width, fixture.height, 0, 10, 1, fixture.polygons,+ {{10, &fixture.field}}) == WaterShoreHistory::BuildResult::Ready);+ CHECK(original.Build(fixture.heights.data(), fixture.width, fixture.height, 0, 10, 1, fixture.polygons,+ {{10, &fixture.field}}) == WaterShoreHistory::BuildResult::Ready);+ CHECK(!actual.Cells().empty() && actual.Cells().size() == original.Cells().size());+ std::vector<double> a(actual.Cells().size()), b(a.size());+ unsigned active = 0, zeroFront = 0, liveFront = 0;+ for (const auto &node : actual.Contexts())+ for (const auto &q : node.quadrature)+ if (q.coast.support > 0) {+ if (q.frontWeights.value[0] == 0 && q.frontWeights.value[1] == 0 && q.frontWeights.value[2] == 0)+ ++zeroFront;+ else+ ++liveFront;+ }+ CHECK(zeroFront > 0 && liveFront > 0);+ for (double time :{0.0, .05, .1, .4, 1.7, 6.3, 17.0, 60.0, 600.0, 3600.0, 100000.0, -3.0}) {+ actual(time, actual.Cells().data(), a.size(), a.data());+ original(time, original.Cells().data(), b.size(), b.data());+ CHECK(std::memcmp(a.data(), b.data(), a.size() * sizeof(double)) == 0);+ for (double v : a)+ active += v > 0;+ }+ CHECK(active > 0);+ // Fill receives topology-sorted/reordered cells, not necessarily source order.+ auto reordered = actual.Cells();+ std::reverse(reordered.begin(), reordered.end());+ actual(1.3, reordered.data(), a.size(), a.data());+ original(1.3, reordered.data(), b.size(), b.data());+ CHECK(std::memcmp(a.data(), b.data(), a.size() * sizeof(double)) == 0);+ // Preserve malformed source-slot rejection without accessing a context.+ auto bad = reordered;+ bad[0].sourceIndex = uint32_t(actual.Contexts().size());+ actual(1.3, bad.data(), a.size(), a.data());+ original(1.3, bad.data(), b.size(), b.data());+ CHECK(std::memcmp(a.data(), b.data(), a.size() * sizeof(double)) == 0);+}++inline void CheckCoverage() {+ for (double x :{-10241.3, -1.0, 0.0, .5, 13.0, 10240.0})+ for (double y :{-991.7, 0.0, 7.0, 333.75}) {+ const double breakup = WaterShoreSource::SpatialBreakup(x, y);+ const float stored = float(breakup);+ CHECK(double(stored) == breakup);+ for (double density :{0.0, 1e-20, .1, 1.0, 10.0})+ for (double age :{0.0, .4, 1.7, 3.0, 8.0, 14.0, 15.0}) {+ const WaterShoreHistory::State state = {density, density * age};+ const double original = WaterShoreSourceReference::Coverage(state, x, y, 0);+ CHECK(SameBits(original, WaterShoreSource::Coverage(state, x, y, 123)));+ CHECK(SameBits(original, WaterShoreSource::CoverageFromBreakup(state, double(stored))));+ }+ }+ for (auto invalid :{WaterShoreHistory::State{-1, 0}, WaterShoreHistory::State{NAN, 0},+ WaterShoreHistory::State{1, NAN}, WaterShoreHistory::State{INFINITY, 0}})+ CHECK(WaterShoreSource::CoverageFromBreakup(invalid, .5) == 0);+}+}+TEST(water_shore_source_prepared_rate_matches_original_float_bits) {+ WaterShoreSourcePerfTest::CheckRate();+}+TEST(water_shore_source_precomputed_coast_matches_frozen_batch_bits) {+ WaterShoreSourcePerfTest::CheckBatch();+}+TEST(water_shore_source_spatial_breakup_preserves_coverage_double_bits) {+ WaterShoreSourcePerfTest::CheckCoverage();+}diff --git a/GeneralsMD/Code/Tests/WaterShoreSourceReference.h b/GeneralsMD/Code/Tests/WaterShoreSourceReference.hnew file mode 100644index 000000000..b50edcb78--- /dev/null+++ b/GeneralsMD/Code/Tests/WaterShoreSourceReference.h@@ -0,0 +1,195 @@+// Frozen before the spatial-rate/coverage cache; keep the original formulas/order.+/* Fixed-world, bounded coastal source contexts. No camera, vessel or gameplay state. */+#pragma once+#include "Platform/WaterShoreFoam.h"+#include "Platform/WaterShoreHistory.h"+#include "Platform/WaterShoreSupport.h"+#include "Platform/WaterOpticalContext.h"+#include <array>++namespace WaterShoreSourceReference {+struct Level {double level=0;const WaterOpticalContext::Field *field=nullptr;};+struct SampleContext {+ WaterShoreFoam::Context coast;+ WaterShoreFoam::FrontWeights frontWeights;+ std::array<float,WaterShoreFoam::ModeCount> sine{},cosine{};+};+struct Context : SampleContext {std::array<SampleContext,4> quadrature;};+using Interval=WaterOpticalContext::Interval;+// Exact scanline union, including authored edges. Every accepted diffusion segment+// lies entirely inside a union interval, rather than testing only its endpoints.+using WaterOpticalContext::Intervals;+inline bool Covered(const std::vector<Interval>&spans,double a,double b) {+ const auto at=std::upper_bound(spans.begin(),spans.end(),a,+ [](double x,const Interval&i){return x<i.first;});+ return at!=spans.begin()&&(at-1)->second>=b;+}+inline float Height(const uint8_t*heights,int width,int height,double x,double y,double scale) {+ x=WaterShoreHistory::Clamp(x,0,width-1.000001);y=WaterShoreHistory::Clamp(y,0,height-1.000001);+ const int ix=int(x),iy=int(y);const double fx=x-ix,fy=y-iy;const size_t n=size_t(iy)*width+ix;+ return float(((heights[n]*(1-fx)+heights[n+1]*fx)*(1-fy)+ +(heights[n+width]*(1-fx)+heights[n+width+1]*fx)*fy)*scale);+}+inline float FieldSample(const std::vector<uint8_t>&field,int width,int x,int y,float fx,float fy) {+ const size_t n=size_t(y)*width+x;+ return ((field[n]*(1-fx)+field[n+1]*fx)*(1-fy)+ +(field[n+width]*(1-fx)+field[n+width+1]*fx)*fy)/255.0f;+}+class Batch {+ WaterShoreHistory::Grid grid;+ std::vector<WaterShoreHistory::Cell> cells;+ std::vector<Context> contexts;+ WaterShoreSupport::Domain support;+public:+ WaterShoreHistory::BuildResult Build(const uint8_t*heights,int width,int height,int border,+ double spacing,double heightScale,const std::vector<WaterOpticalContext::Polygon>&polygons,+ const std::vector<Level>&levels) {+ using namespace WaterShoreHistory;+ if(!heights||width<2||height<2||width>WaterOpticalContext::MaxDimension||height>WaterOpticalContext::MaxDimension+ ||size_t(width)*height>WaterOpticalContext::MaxCells||border<0||border>(width-2)/2||border>(height-2)/2+ ||!std::isfinite(spacing)||spacing<2||spacing>2048||!std::isfinite(heightScale)||heightScale<=0)+ return BuildResult::Invalid;+ if(levels.size()>MaxLevels)return BuildResult::TooManyLevels;+ size_t points=0;+ for(const auto&polygon:polygons) {+ if(polygon.points.size()>WaterOpticalContext::MaxPoints-points)return BuildResult::Invalid;+ points+=polygon.points.size();+ for(const auto&p:polygon.points)if(!std::isfinite(p.x)||!std::isfinite(p.y)||!std::isfinite(p.z))return BuildResult::Invalid;+ }+ Batch next;next.grid={-border*spacing,-border*spacing,spacing*.5};+ std::vector<double> seen;+ for(const Level&entry:levels) {+ if(!entry.field||!std::isfinite(entry.level))return BuildResult::Invalid;+ if(std::find(seen.begin(),seen.end(),entry.level)!=seen.end())return BuildResult::Invalid;+ seen.push_back(entry.level);+ const auto&f=*entry.field;const size_t count=size_t(width)*height;+ if(f.ocean.size()!=count||f.shore.size()!=count||f.exposure.size()!=count||f.coast.size()!=count)return BuildResult::Invalid;+ const size_t first=next.cells.size();+ auto sample=[&](double px,double py) {+ SampleContext context;+ if(px<0||py<0||px>=width-1||py>=height-1)return context;+ const int ix=int(px),iy=int(py);const float fx=float(px-ix),fy=float(py-iy);+ const float terrain=Height(heights,width,height,px,py,heightScale);+ if(!(terrain<entry.level)||FieldSample(f.ocean,width,ix,iy,fx,fy)>0)return context;+ const double offset=5.0/spacing;+ const float gx=(Height(heights,width,height,px+offset,py,heightScale)+ -Height(heights,width,height,px-offset,py,heightScale))*.1f;+ const float gy=(Height(heights,width,height,px,py+offset,heightScale)+ -Height(heights,width,height,px,py-offset,heightScale))*.1f;+ context.coast.depth=float(entry.level)-terrain;+ context.coast.nx=-gx;context.coast.ny=-gy;context.coast.slope=std::hypot(gx,gy);+ context.coast.shore=(std::min)(FieldSample(f.shore,width,ix,iy,fx,fy)*100,+ context.coast.depth/(std::max)(context.coast.slope,.01f));+ context.coast.support=FieldSample(f.coast,width,ix,iy,fx,fy);+ context.coast.exposure=FieldSample(f.exposure,width,ix,iy,fx,fy);+ context.frontWeights=WaterShoreFoam::IncomingWeights(context.coast.nx,context.coast.ny);+ const double worldX=next.grid.originX+px*spacing,worldY=next.grid.originY+py*spacing;+ for(unsigned mode=0;mode<WaterShoreFoam::ModeCount;++mode) {+ const auto&m=WaterShoreFoam::Modes[mode];+ const float phase=float(worldX)*m.kx+float(worldY)*m.ky+m.phase;+ context.sine[mode]=std::sin(phase);context.cosine[mode]=std::cos(phase);+ }+ return context;+ };+ for(int y=0;y<2*(height-1);++y) {+ const double worldY=next.grid.originY+y*next.grid.spacing;+ const auto row=Intervals(polygons,entry.level,worldY,true);+ if(row.empty())continue;+ const std::array<std::vector<Interval>,2> quadratureRows={+ Intervals(polygons,entry.level,worldY-next.grid.spacing*.25,true),+ Intervals(polygons,entry.level,worldY+next.grid.spacing*.25,true)};+ for(int x=0;x<2*(width-1);++x) {+ const int ix=x/2,iy=y/2;const float fx=(x%2)*.5f,fy=(y%2)*.5f;+ // Include a one-terrain-cell margin around support for wet-only spreading.+ bool nearCoast=false;+ for(int yy=(std::max)(0,iy-1);yy<=(std::min)(height-1,iy+2)&&!nearCoast;++yy)+ for(int xx=(std::max)(0,ix-1);xx<=(std::min)(width-1,ix+2);++xx)+ nearCoast=nearCoast||f.coast[size_t(yy)*width+xx]!=0;+ if(!nearCoast||FieldSample(f.ocean,width,ix,iy,fx,fy)>0)continue;+ const double worldX=next.grid.originX+x*next.grid.spacing;+ if(!Covered(row,worldX,worldX))continue;+ const float terrain=Height(heights,width,height,x*.5,y*.5,heightScale);+ if(!(terrain<entry.level))continue;+ if(next.cells.size()>=MaxCells)return BuildResult::TooManyCells;+ Context context;static_cast<SampleContext&>(context)=sample(x*.5,y*.5);+ // Fixed2x2 area quadrature captures narrow wet source bands and the+ // nonlinear crest/incoming gates; dry/outside subnodes contribute zero.+ // It does not expand the wet graph or connect across polygon gaps.+ for(unsigned sy=0;sy<2;++sy)for(unsigned sx=0;sx<2;++sx) {+ const double px=x*.5+(sx?.125:-.125),py=y*.5+(sy?.125:-.125);+ const double qx=next.grid.originX+px*spacing;+ if(Covered(quadratureRows[sy],qx,qx))context.quadrature[sy*2+sx]=sample(px,py);+ }+ const uint8_t connections=Covered(row,worldX,worldX+next.grid.spacing)?1:0;+ next.cells.push_back({x,y,entry.level,uint32_t(next.contexts.size()),connections});+ next.contexts.push_back(context);+ }+ }+ // Cache one vertical scanline at a time, using bounded cell indices rather than+ // scanning polygon edges once for every history node.+ std::vector<size_t> columnOrder;+ for(size_t i=first;i<next.cells.size();++i)columnOrder.push_back(i);+ std::sort(columnOrder.begin(),columnOrder.end(),[&](size_t a,size_t b){return next.cells[a].x<next.cells[b].x;});+ int previous=-1;std::vector<Interval> column;+ for(size_t i:columnOrder) {+ auto&cell=next.cells[i];+ if(cell.x!=previous){previous=cell.x;column=Intervals(polygons,entry.level,next.grid.originX+cell.x*next.grid.spacing,false);}+ const double worldY=next.grid.originY+cell.y*next.grid.spacing;+ if(Covered(column,worldY,worldY+next.grid.spacing))cell.connections|=2;+ }+ }+ auto terrain=[&](double x,double y){return Height(heights,width,height,x,y,heightScale);};+ if(!next.support.Build(next.grid,next.cells,width,height,polygons,terrain))return BuildResult::Invalid;+ *this=std::move(next);return BuildResult::Ready;+ }+ void operator()(double time,const WaterShoreHistory::Cell*nodes,size_t count,double*rates) const {+ std::array<float,WaterShoreFoam::ModeCount> sine{},cosine{};+ for(unsigned mode=0;mode<WaterShoreFoam::ModeCount;++mode) {+ const float phase=-float(time)*WaterShoreFoam::Modes[mode].omega;+ sine[mode]=std::sin(phase);cosine[mode]=std::cos(phase);+ }+ for(size_t i=0;i<count;++i) {+ rates[i]=0;if(nodes[i].sourceIndex>=contexts.size())continue;+ const Context&node=contexts[nodes[i].sourceIndex];+ for(const SampleContext&context:node.quadrature) {+ if(context.coast.support<=0)continue;+ WaterShoreFoam::Wave wave;float front=0;+ for(unsigned mode=0;mode<WaterShoreFoam::ModeCount;++mode) {+ const auto&m=WaterShoreFoam::Modes[mode];+ const float s=context.sine[mode]*cosine[mode]+context.cosine[mode]*sine[mode];+ const float c=context.cosine[mode]*cosine[mode]-context.sine[mode]*sine[mode];+ const float derivative=m.amplitude*(c+.26f*(c*c-s*s));+ wave.height+=m.amplitude*(s+.26f*s*c);wave.dx+=derivative*m.kx;wave.dy+=derivative*m.ky;wave.dt-=derivative*m.omega;+ front+=context.frontWeights.value[mode]*WaterShoreFoam::FrontKernel(s,c);+ }+ // A phase-locked birth mask only removes old-source support. No new+ // per-cell trigonometry, graph cells, upload work or time state is added.+ rates[i]+=.25*WaterShoreFoam::Rate(context.coast,wave)*WaterShoreFoam::Clamp(front,0,1);+ }+ }+ }+ const WaterShoreHistory::Grid&Grid()const{return grid;}+ const std::vector<WaterShoreHistory::Cell>&Cells()const{return cells;}+ const std::vector<Context>&Contexts()const{return contexts;}+ const WaterShoreSupport::Domain&Support()const{return support;}+ void Clear(){*this=Batch();}+};+// Density and its age moment become a porous, world-anchored surface coverage.+// The material has no dependence on vessel heading, render count or atlas mapping.+inline double Noise(double x,double y) {+ auto hash=[](int64_t x,int64_t y){uint64_t h=uint64_t(x)*0x9e3779b97f4a7c15ULL^uint64_t(y)*0xbf58476d1ce4e5b9ULL;+ h=(h^(h>>30))*0xbf58476d1ce4e5b9ULL;h=(h^(h>>27))*0x94d049bb133111ebULL;return double((h^(h>>31))&0xffffffu)/16777215.0;};+ const int64_t ix=int64_t(std::floor(x)),iy=int64_t(std::floor(y));+ double fx=x-ix,fy=y-iy;fx=fx*fx*(3-2*fx);fy=fy*fy*(3-2*fy);+ return (hash(ix,iy)*(1-fx)+hash(ix+1,iy)*fx)*(1-fy)+(hash(ix,iy+1)*(1-fx)+hash(ix+1,iy+1)*fx)*fy;+}+inline double Coverage(const WaterShoreHistory::State&s,double x,double y,double) {+ if(!(s.density>0)||!std::isfinite(s.density)||!std::isfinite(s.ageMoment))return 0;+ const double age=s.ageMoment/s.density;+ const double texture=Noise(x/7,y/7)*.7+Noise(x/2.3,y/2.3)*.3;+ const double breakup=WaterShoreFoam::Smooth(.25f,.7f,float(texture));+ const double aged=WaterShoreFoam::Smooth(.4f,3.0f,float(age));+ const double terminal=1-WaterShoreFoam::Smooth(8,14,float(age));+ return -std::expm1(-s.density)*(1-aged+aged*breakup)*terminal;+}+}diff --git a/GeneralsMD/Code/Tests/WaterTerrainCullingReference.h b/GeneralsMD/Code/Tests/WaterTerrainCullingReference.hnew file mode 100644index 000000000..b8657e9d8--- /dev/null+++ b/GeneralsMD/Code/Tests/WaterTerrainCullingReference.h@@ -0,0 +1,220 @@+// Frozen HEAD 3c1f8285 terrain culling oracle; only namespace renamed.+/* Render-only rejection of water triangles proven to be entirely below terrain. */+#pragma once++#include "Platform/WaterProjectedMesh.h"+#include <limits>++namespace WaterTerrainCullingFrozenReference+{+constexpr size_t MaxTriangleSamples = 1024;+constexpr size_t MaxMeshSamples = 4u * 1024u * 1024u;++// The terrain renderer triangulates each heightmap cell. Its surface can be above+// the bilinear sample on a saddle, so require clearance over every cell corner.+// Callers can use this to disable terrain occlusion proofs from below the ground.+inline bool CameraAboveTerrain(+ const uint8_t *heights, int width, int height, int border,+ double spacing, double heightScale,+ double cameraX, double cameraY, double cameraZ)+{+ if (!heights || width < 2 || height < 2 || width > 2048 || height > 2048 ||+ border < 0 || border > (width - 2) / 2 || border > (height - 2) / 2 ||+ !std::isfinite(spacing) || spacing <= 0 ||+ !std::isfinite(heightScale) || heightScale <= 0 ||+ !std::isfinite(cameraX) || !std::isfinite(cameraY) || !std::isfinite(cameraZ))+ {+ return false;+ }++ const double x = cameraX / spacing + border;+ const double y = cameraY / spacing + border;+ if (!std::isfinite(x) || !std::isfinite(y) ||+ x < 0 || y < 0 || x > width - 1 || y > height - 1)+ {+ return false;+ }++ const int x0 = int(x);+ const int y0 = int(y);+ const int x1 = (std::min)(x0 + 1, width - 1);+ const int y1 = (std::min)(y0 + 1, height - 1);+ const uint8_t maximum = (std::max)(+ (std::max)(heights[size_t(y0) * width + x0], heights[size_t(y0) * width + x1]),+ (std::max)(heights[size_t(y1) * width + x0], heights[size_t(y1) * width + x1]));+ const double ceiling = maximum * heightScale;+ const double epsilon = 8 * std::numeric_limits<float>::epsilon() *+ (std::max)(1.0, (std::max)(std::abs(ceiling), std::abs(cameraZ)));++ return std::isfinite(ceiling) && cameraZ > ceiling + epsilon;+}++inline bool ValidMesh(const WaterProjectedMesh::Mesh &mesh)+{+ if (mesh.vertices.size() > 65536 || mesh.indices.size() % 3)+ {+ return false;+ }++ for (const auto &vertex : mesh.vertices)+ {+ if (!std::isfinite(vertex.world.x) || !std::isfinite(vertex.world.y))+ {+ return false;+ }+ }++ for (uint16_t index : mesh.indices)+ {+ if (index >= mesh.vertices.size())+ {+ return false;+ }+ }++ return true;+}++// All references in collars/transitions are world coordinates or authored edge IDs,+// not mesh vertex indices. Retain those tables and each surviving vertex verbatim.+inline void Install(WaterProjectedMesh::Mesh &mesh, std::vector<uint16_t> &indices)+{+ std::vector<int> remap(mesh.vertices.size(), -1);+ for (uint16_t index : indices)+ {+ remap[index] = 0;+ }++ std::vector<WaterProjectedMesh::Vertex> vertices;+ vertices.reserve(mesh.vertices.size());+ for (size_t i = 0; i < remap.size(); ++i)+ {+ if (remap[i] == 0)+ {+ remap[i] = int(vertices.size());+ vertices.push_back(mesh.vertices[i]);+ }+ }++ for (uint16_t &index : indices)+ {+ index = uint16_t(remap[index]);+ }++ mesh.vertices.swap(vertices);+ mesh.indices.swap(indices);+}++inline bool CompactVertices(WaterProjectedMesh::Mesh &mesh)+{+ if (!ValidMesh(mesh))+ {+ return false;+ }++ std::vector<uint16_t> indices = mesh.indices;+ Install(mesh, indices);+ return true;+}++// A bilinear terrain cell and either triangulation of that cell never fall below+// their lowest corner. Inspect ALL corners of ALL cells overlapped by the displaced+// triangle's bounds; sampling only the triangle endpoints can hide an interior pond.+// The supplied displacement bounds must include every enabled surface effect.+// Unknown/outside terrain and queries exceeding the work budget retain the triangle.+// Invalid inputs leave the entire mesh unchanged. No partial geometry is removed.+inline bool CullDryTriangles(+ WaterProjectedMesh::Mesh &mesh, const uint8_t *heights,+ int width, int height, int border, double spacing, double heightScale,+ double level, double verticalBound, double horizontalBound)+{+ if (!heights || width < 2 || height < 2 || width > 2048 || height > 2048 ||+ border < 0 || border > (width - 2) / 2 || border > (height - 2) / 2 ||+ !std::isfinite(spacing) || spacing <= 0 ||+ !std::isfinite(heightScale) || heightScale <= 0 || !std::isfinite(level) ||+ !std::isfinite(verticalBound) || verticalBound < 0 ||+ !std::isfinite(horizontalBound) || horizontalBound < 0 || !ValidMesh(mesh))+ {+ return false;+ }++ const double top = level + verticalBound;+ if (!std::isfinite(top) || !std::isfinite(255 * heightScale))+ {+ return false;+ }++ // Vertices and shader displacement ultimately use float; include their rounding+ // before converting bounds to grid cells and comparing terrain/water elevations.+ const double epsilon = 8 * std::numeric_limits<float>::epsilon();+ const double ceiling = top + epsilon *+ (std::max)(1.0, (std::max)(std::abs(top), 255 * heightScale));+ if (!std::isfinite(ceiling))+ {+ return false;+ }++ std::vector<uint16_t> indices;+ indices.reserve(mesh.indices.size());+ size_t work = 0;++ for (size_t triangle = 0; triangle < mesh.indices.size(); triangle += 3)+ {+ const auto a = mesh.vertices[mesh.indices[triangle]].world;+ const auto b = mesh.vertices[mesh.indices[triangle + 1]].world;+ const auto c = mesh.vertices[mesh.indices[triangle + 2]].world;+ double minX = (std::min)(a.x, (std::min)(b.x, c.x));+ double maxX = (std::max)(a.x, (std::max)(b.x, c.x));+ double minY = (std::min)(a.y, (std::min)(b.y, c.y));+ double maxY = (std::max)(a.y, (std::max)(b.y, c.y));+ const double magnitude = (std::max)(1.0, (std::max)(+ (std::max)(std::abs(minX), std::abs(maxX)),+ (std::max)(std::abs(minY), std::abs(maxY))));+ const double margin = horizontalBound + epsilon * (magnitude + horizontalBound);++ minX = (minX - margin) / spacing + border;+ maxX = (maxX + margin) / spacing + border;+ minY = (minY - margin) / spacing + border;+ maxY = (maxY + margin) / spacing + border;++ bool dry = false;+ if (std::isfinite(minX) && std::isfinite(maxX) &&+ std::isfinite(minY) && std::isfinite(maxY) &&+ minX >= 0 && minY >= 0 && maxX <= width - 1 && maxY <= height - 1)+ {+ const int firstX = int(std::floor(minX));+ const int lastX = int(std::ceil(maxX));+ const int firstY = int(std::floor(minY));+ const int lastY = int(std::ceil(maxY));+ const size_t samples = size_t(lastX - firstX + 1) * size_t(lastY - firstY + 1);++ if (samples <= MaxTriangleSamples && samples <= MaxMeshSamples - work)+ {+ work += samples;+ dry = true;++ for (int y = firstY; y <= lastY && dry; ++y)+ {+ for (int x = firstX; x <= lastX; ++x)+ {+ if (heights[size_t(y) * width + x] * heightScale <= ceiling)+ {+ dry = false;+ break;+ }+ }+ }+ }+ }++ if (!dry)+ {+ indices.insert(+ indices.end(), mesh.indices.begin() + triangle, mesh.indices.begin() + triangle + 3);+ }+ }++ Install(mesh, indices);+ return true;+}+}diff --git a/GeneralsMD/Code/Tests/WaterTerrainProofCacheTest.h b/GeneralsMD/Code/Tests/WaterTerrainProofCacheTest.hnew file mode 100644index 000000000..8b0ac36f6--- /dev/null+++ b/GeneralsMD/Code/Tests/WaterTerrainProofCacheTest.h@@ -0,0 +1,408 @@+#pragma once++#include "WaterTerrainCullingReference.h"+#include "Platform/WaterTerrainCulling.h"+#include "Platform/WaterWaveCage.h"+#include "Platform/WaterWaveCageMesh.h"+#include <limits>++// Compare active semantic fields, never padding or allocation capacity. The frozen+// implementation also supplies the original copying Install/CompactVertices path.+namespace WaterTerrainProofCacheTest {+using WaterProjectedMesh::Mesh;+using WaterProjectedMesh::Point;++inline Mesh Triangle(Point a = {1.25, 1.25}, Point b = {6.25, 1.25}, Point c = {1.25, 6.25}) {+ Mesh mesh;+ for (Point p :{a, b, c}) {+ WaterProjectedMesh::Vertex v;+ v.world = p;+ mesh.vertices.push_back(v);+ }+ mesh.indices = {0, 1, 2};+ mesh.cells = 37;+ return mesh;+}++inline void Compare(const Mesh &input, const uint8_t *heights, int width, int height, int border,+ double spacing, double scale, double level, double vertical, double horizontal,+ WaterTerrainCulling::WetNodeCache *cache, bool clip = false) {+ Mesh reference = input, actual = input, scalar = input;+ const bool expected = WaterTerrainCullingFrozenReference::CullDryTriangles(+ reference, heights, width, height, border, spacing, scale, level, vertical, horizontal);+ const bool result = WaterTerrainCulling::CullDryTriangles(+ actual, heights, width, height, border, spacing, scale, level, vertical, horizontal, cache);+ const bool scalarResult = WaterTerrainCulling::CullDryTriangles(+ scalar, heights, width, height, border, spacing, scale, level, vertical, horizontal);+ CHECK(result == expected && scalarResult == expected);+ CHECK(projectedCacheSameMesh(reference, actual));+ CHECK(projectedCacheSameMesh(reference, scalar));+ if (!expected) {+ CHECK(projectedCacheSameMesh(input, actual));+ return;+ }+ if (clip) {+ const auto depth = [&](Point p) {+ return level - WaterWaveCage::Height(heights, width, height, border, spacing, scale, float(p.x), float(p.y));+ };+ const auto supported = [](Point p) {+ return p.x + p.y > 1;+ };+ const bool oldClip = WaterWaveCageMesh::ClipRestWaterline(reference, depth, supported);+ const bool newClip = WaterWaveCageMesh::ClipRestWaterline(actual, depth, supported);+ CHECK(oldClip == newClip);+ }+ const bool oldCompact = WaterTerrainCullingFrozenReference::CompactVertices(reference);+ const bool newCompact = WaterTerrainCulling::CompactVertices(actual);+ CHECK(oldCompact == newCompact && projectedCacheSameMesh(reference, actual));+}++inline uint32_t Random(uint32_t &seed) {+ seed = seed * 1664525u + 1013904223u;+ return seed;+}++inline void ExtremesAndThresholds() {+ WaterTerrainCulling::WetNodeCache cache;+ Mesh input = Triangle();+ std::vector<uint8_t> heights(81, 30);+ for (int wet = -1; wet < 81; ++wet) {+ std::fill(heights.begin(), heights.end(), 30);+ if (wet >= 0)+ heights[wet] = 0; // A one-node pond anywhere, including dry row boundaries.+ cache.Clear();+ Compare(input, heights.data(), 9, 9, 0, 1, 1, 10, 0, 0, &cache, true);+ Compare(input, heights.data(), 9, 9, 0, 1, 1, 10, 0, 0, &cache, true);+ }+ for (uint8_t h :{uint8_t(0), uint8_t(10), uint8_t(11), uint8_t(255)}) {+ heights.assign(81, h);+ cache.Clear();+ for (double scale :{.25, 1.0, 3.0})+ for (double level :{-0.0, 0.0, 10.0,+ std::nextafter(10.0, -INFINITY), std::nextafter(10.0, INFINITY), 255.0}) {+ Compare(input, heights.data(), 9, 9, 0, 1, scale, level, 0, 0, &cache, true);+ Compare(input, heights.data(), 9, 9, 0, 1, scale, level, .5, 1, &cache, true);+ }+ }+ heights.assign(81, 30);+ cache.Clear();+ for (Mesh edge :{Triangle({-1, 1}, {1, 1}, {1, 2}), Triangle({7.9, 7.9}, {8, 7.9}, {7.9, 8}),+ Triangle({0, 0}, {0, 0}, {0, 0}), Triangle({-0.0, 0}, {.1, 0}, {0, .1})})+ Compare(edge, heights.data(), 9, 9, 0, 1, 1, 10, 0, 0, &cache, true);+ Compare(input, heights.data(), 9, 9, 2, 2, 2, 10, 0, 0, &cache, true);+}++inline void MovingProjectedPipeline() {+ const int width = 64, height = 48;+ uint32_t seed = 0x57a31c9u;+ WaterTerrainCulling::WetNodeCache cache;+ for (int terrain = 0; terrain < 4; ++terrain) {+ std::vector<uint8_t> heights(width * height);+ for (int y = 0; y < height; ++y)+ for (int x = 0; x < width; ++x) {+ const uint32_t noise = Random(seed);+ heights[y * width + x] = terrain == 0 ? uint8_t(noise >> 24) : terrain == 1 ? uint8_t(x < 30 ? 0 : 40) :+ terrain == 2 ? uint8_t((x / 7 + y / 9) % 2 ? 0 : 40) : uint8_t(40);+ }+ if (terrain == 3)+ heights[23 * width + 31] = 0;+ cache.Clear();+ for (int frame = 0; frame < 24; ++frame) {+ const double extent = 220 + frame * 3.5, cx = 245 + frame * 2.25, cy = 210 - frame * .75;+ WaterProjectedMesh::Projection projection = {{2 / extent, 0, -cx * 2 / extent,+ 0, 2 / extent, -cy * 2 / extent, frame * .000001, -frame * .0000005, 1}, {0}, {0, 0, 1}, .1, 10, .12};+ CHECK(projection.Prepare());+ WaterProjectedMesh::Point patch[4] = {{0, 0}, {630, 0}, {630, 470}, {0, 470}};+ if (frame % 3 == 1)+ std::reverse(patch, patch + 4);+ std::vector<WaterProjectedMesh::BoundaryKnot> knots;+ for (int edge = 0; edge < 4; ++edge)+ for (int k = 0; k <= 16; ++k) {+ Point a = patch[edge], b = patch[(edge + 1) % 4];+ if (a.x > b.x || (a.x == b.x && a.y > b.y))+ std::swap(a, b);+ const double t = k / 16.;+ knots.push_back({{a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t}, edge, k, t});+ }+ Mesh mesh;+ CHECK(WaterProjectedMesh::Build(patch, projection, {41, 27}, mesh, 60000, knots));+ WaterProjectedMesh::Vertex unused;+ unused.world = {700, 700};+ mesh.vertices.push_back(unused);+ Compare(mesh, heights.data(), width, height, 0, 10, 1, 15, 4.01, 3.01, &cache, true);+ }+ }+}++inline void BudgetAndIndexLimits() {+ WaterTerrainCulling::WetNodeCache cache;+ std::vector<uint8_t> heights(65 * 65, 30);+ Mesh repeated = Triangle({1.25, 1.25}, {30.25, 1.25}, {1.25, 30.25});+ repeated.indices.clear();+ for (int i = 0; i < 5000; ++i)+ repeated.indices.insert(repeated.indices.end(), {0, 1, 2});+ // Each legal rectangle charges 31*31 samples, even though SAT is O(1).+ // Later identical dry triangles must remain after the mesh budget is exhausted.+ Compare(repeated, heights.data(), 65, 65, 0, 1, 1, 10, 0, 0, &cache);+ Mesh expected = repeated;+ CHECK(WaterTerrainCullingFrozenReference::CullDryTriangles(expected, heights.data(), 65, 65, 0, 1, 1, 10,+ 0, 0));+ CHECK(!expected.indices.empty() && expected.indices.size() < repeated.indices.size());+ Mesh wetBudget = repeated;+ // 4,364 charges of 961 leave 500 samples. Larger requests then bypass+ // without charging, so consume the remainder with a 20*25 first-wet query.+ const size_t rectangleCharge = 31u * 31u, remainderCharge = 20u * 25u;+ CHECK(WaterTerrainCullingFrozenReference::MaxMeshSamples % rectangleCharge == remainderCharge);+ for (Point p :{Point{1.25, 1.25}, Point{19.25, 1.25}, Point{1.25, 24.25},+ Point{40.25, 40.25}, Point{45.25, 40.25}, Point{40.25, 45.25}}) {+ WaterProjectedMesh::Vertex v;+ v.world = p;+ wetBudget.vertices.push_back(v);+ }+ wetBudget.indices.insert(wetBudget.indices.end(), {3, 4, 5});+ wetBudget.indices.insert(wetBudget.indices.end(), {6, 7, 8});+ heights[1 * 65 + 1] = 0;+ cache.Clear();+ // Even immediate first-node wet exits consume their complete logical sample+ // charge. The final dry triangle must therefore remain beyond the budget.+ Compare(wetBudget, heights.data(), 65, 65, 0, 1, 1, 10, 0, 0, &cache);+ Mesh charged = wetBudget;+ CHECK(WaterTerrainCullingFrozenReference::CullDryTriangles(charged, heights.data(), 65, 65, 0, 1, 1, 10,+ 0, 0));+ CHECK(charged.indices.size() == wetBudget.indices.size());+ Compare(Triangle({1, 1}, {63, 1}, {1, 63}), heights.data(), 65, 65, 0, 1, 1, 10, 0, 0, &cache);++ Mesh high = Triangle();+ high.vertices.resize(65536, high.vertices[0]);+ high.vertices[65533].world = {2, 2};+ high.vertices[65534].world = {3, 2};+ high.vertices[65535].world = {2, 3};+ high.indices = {65535, 65533, 65534};+ heights.assign(65 * 65, 0);+ cache.Clear();+ Compare(high, heights.data(), 65, 65, 0, 1, 1, 10, 0, 0, &cache);+ high.vertices.push_back(high.vertices[0]);+ Compare(high, heights.data(), 65, 65, 0, 1, 1, 10, 0, 0, &cache);+}++inline void InvalidAndCompaction() {+ WaterTerrainCulling::WetNodeCache cache;+ std::vector<uint8_t> heights(81, 30);+ const Mesh base = Triangle();+ for (int failure = 0; failure < 21; ++failure) {+ Mesh mesh = base;+ const uint8_t *data = heights.data();+ int width = 9, height = 9, border = 0;+ double spacing = 1, scale = 1, level = 10, vertical = 0, horizontal = 0;+ switch (failure) {+ case 0 : data = nullptr;+ break;+ case 1 : width = 1;+ break;+ case 2 : height = 2049;+ break;+ case 3 : border = -1;+ break;+ case 4 : border = 5;+ break;+ case 5 : spacing = 0;+ break;+ case 6 : spacing = -0.0;+ break;+ case 7 : spacing = INFINITY;+ break;+ case 8 : scale = 0;+ break;+ case 9 : scale = NAN;+ break;+ case 10 : level = NAN;+ break;+ case 11 : level = INFINITY;+ break;+ case 12 : vertical = -1;+ break;+ case 13 : horizontal = -1;+ break;+ case 14 : horizontal = INFINITY;+ break;+ case 15 : mesh.indices.push_back(0);+ break;+ case 16 : mesh.indices[2] = 65535;+ break;+ case 17 : mesh.vertices[1].world.x = NAN;+ break;+ case 18 : mesh.vertices[2].world.y = INFINITY;+ break;+ case 19 : scale = std::numeric_limits<double>::max();+ break;+ case 20 : level = std::numeric_limits<double>::max();+ vertical = level;+ break;+ }+ Compare(mesh, data, width, height, border, spacing, scale, level, vertical, horizontal, &cache);+ }+ Mesh input = base;+ for (int i = 0; i < 12; ++i) {+ WaterProjectedMesh::Vertex v;+ v.world = {double(i), double(i + 1)};+ v.boundary = i % 5 - 1;+ v.edgeParameter = i * .03125;+ v.knot = i;+ v.lattice = 53 - i;+ input.vertices.push_back(v);+ }+ input.indices = {14, 3, 8, 8, 3, 5, 5, 14, 8};+ input.transitions.resize(1);+ input.transitions[0] = {};+ input.transitions[0].analytic = .75;+ input.collars.resize(1);+ input.collars[0].count = 1;+ input.collars[0].fade = .5;+ input.collars[0].edge[0] = 2;+ input.collars[0].parameter[0] = .3;+ input.collars[0].weight[0] = .5;+ input.vertices[8].collar = 0;+ input.vertices[14].transition = 0;+ for (int variant = 0; variant < 4; ++variant) {+ Mesh old = input, actual = input;+ if (variant == 1) {+ old.indices.clear();+ actual.indices.clear();+ }+ if (variant == 2) {+ old.indices[2] = 65535;+ actual.indices[2] = 65535;+ }+ if (variant == 3) {+ old.vertices[0].world.x = NAN;+ actual.vertices[0].world.x = NAN;+ }+ const bool a = WaterTerrainCullingFrozenReference::CompactVertices(old);+ const bool b = WaterTerrainCulling::CompactVertices(actual);+ CHECK(a == b && projectedCacheSameMesh(old, actual));+ }+}++inline void LifetimeAndCapacity() {+ std::vector<uint8_t> heights(81, 30);+ const Mesh mesh = Triangle();+ WaterTerrainCulling::WetNodeCache cache(1);+ Compare(mesh, heights.data(), 9, 9, 0, 1, 1, 10, 0, 0, &cache);+ const size_t builds = cache.BuildCount();+ CHECK(builds > 0 && cache.EntryCount() == 1 && cache.CachedBytes() > 0);+ Compare(mesh, heights.data(), 9, 9, 0, 1, 1, 10.1, 0, 0, &cache);+ CHECK(cache.BuildCount() == builds && cache.EntryCount() == 1); // Same encoded wet/dry cutoff.+ Compare(mesh, heights.data(), 9, 9, 0, 1, 1, 20, 0, 0, &cache);+ CHECK(cache.EntryCount() == 1 && cache.BuildCount() > builds);+ Compare(mesh, heights.data(), 9, 9, 0, 1, 1, 10, 0, 0, &cache);+ CHECK(cache.EntryCount() == 1);+ heights[3 * 9 + 3] = 0;+ cache.Clear();+ CHECK(cache.EntryCount() == 0 && cache.CachedBytes() == 0);+ Compare(mesh, heights.data(), 9, 9, 0, 1, 1, 10, 0, 0, &cache, true);+ std::vector<uint8_t> other(81, 30);+ Compare(mesh, other.data(), 9, 9, 0, 1, 1, 10, 0, 0, &cache);+ WaterTerrainCulling::WetNodeCache disabled(0);+ Compare(mesh, other.data(), 9, 9, 0, 1, 1, 10, 0, 0, &disabled, true);+ CHECK(disabled.EntryCount() == 0 && disabled.CachedBytes() == 0 && disabled.BuildCount() == 0);++ WaterTerrainCulling::WetNodeCache warmed;+ double ceiling = 0;+ CHECK(WaterTerrainCulling::ProofCeiling(1, 10, .5, ceiling));+ const double expectedTop = 10 + .5;+ const double expectedCeiling = expectedTop + 8 * std::numeric_limits<float>::epsilon() *+ (std::max)(1.0, (std::max)(std::abs(expectedTop), 255.0));+ CHECK(projectedCacheSameDouble(ceiling, expectedCeiling));+ CHECK(warmed.Prewarm(other.data(), 9, 9, 1, ceiling));+ CHECK(warmed.BuildCount() == 1 && warmed.EntryCount() == 1 && warmed.CachedBytes() > 0+ && warmed.QueryHits() == 0);+ CHECK(warmed.Prewarm(other.data(), 9, 9, 1, ceiling) && warmed.BuildCount() == 1 && warmed.QueryHits() == 0);+ Compare(mesh, other.data(), 9, 9, 0, 1, 1, 10, .5, 0, &warmed, true);+ CHECK(warmed.BuildCount() == 1); // First gameplay proof consumes the loading-built table.+ CHECK(!disabled.Prewarm(other.data(), 9, 9, 1, ceiling));+ CHECK(!warmed.Prewarm(nullptr, 9, 9, 1, ceiling) && warmed.BuildCount() == 1);+ WaterTerrainCulling::WetNodeCache trivial;+ CHECK(trivial.Prewarm(other.data(), 9, 9, 1, -1) && trivial.Prewarm(other.data(), 9, 9, 1, 255));+ CHECK(trivial.BuildCount() == 0 && trivial.EntryCount() == 0 && trivial.CachedBytes() == 0+ && trivial.QueryHits() == 0);+ CHECK(!WaterTerrainCulling::ProofCeiling(0, 10, 0, ceiling));+ CHECK(!WaterTerrainCulling::ProofCeiling(1, INFINITY, 0, ceiling));+ CHECK(!WaterTerrainCulling::ProofCeiling(1, 10, -1, ceiling));+ CHECK(!WaterTerrainCulling::ProofCeiling(std::numeric_limits<double>::max(), 10, 0, ceiling));+}++inline void RectangleQueries() {+ const int width = 13, height = 11;+ uint32_t seed = 0x9d125ad3u;+ std::vector<uint8_t> heights(width * height);+ for (auto &h : heights)+ h = uint8_t(Random(seed) >> 24);+ heights[0] = 0;+ heights[width - 1] = 255;+ heights[(height - 1) * width] = 127;+ heights.back() = 128;+ WaterTerrainCulling::WetNodeCache cache(3);+ for (double scale :{.25, 1.0, 2.75})+ for (int cutoff = -1; cutoff <= 256; ++cutoff) {+ const double equal = cutoff * scale;+ for (double ceiling :{std::nextafter(equal, -INFINITY), equal, std::nextafter(equal, INFINITY)}) {+ auto query = cache.Prepare(heights.data(), width, height, scale, ceiling);+ for (int sample = 0; sample < 12; ++sample) {+ int x0 = int(Random(seed) % width), x1 = int(Random(seed) % width);+ int y0 = int(Random(seed) % height), y1 = int(Random(seed) % height);+ if (x0 > x1)+ std::swap(x0, x1);+ if (y0 > y1)+ std::swap(y0, y1);+ if (sample < 4) {+ y0 = y1 = sample % 2 ? height - 1 : 0;+ x0 = x1 = sample / 2 ? width - 1 : 0;+ }+ bool expected = false;+ for (int y = y0; y <= y1; ++y)+ for (int x = x0; x <= x1; ++x)+ expected = expected || heights[y * width + x] * scale <= ceiling;+ bool wet = !expected;+ CHECK(query.HasWet(x0, x1, y0, y1, wet));+ CHECK(wet == expected);+ }+ }+ CHECK(cache.EntryCount() <= 3);+ }+ CHECK(cache.QueryHits() > 0 && cache.BuildCount() > 0);+ auto query = cache.Prepare(heights.data(), width, height, 1, 10);+ const size_t hits = cache.QueryHits(), builds = cache.BuildCount();+ for (std::array<int, 4> bounds :{std::array<int, 4>{{-1, 2, 0, 1}}, {{0, width, 0, 1}},+ {{0, 1, -1, 1}}, {{0, 1, 0, height}}, {{2, 1, 0, 1}}, {{0, 1, 2, 1}}}) {+ bool wet = true;+ CHECK(!query.HasWet(bounds[0], bounds[1], bounds[2], bounds[3], wet));+ CHECK(wet);+ }+ CHECK(cache.QueryHits() == hits && cache.BuildCount() == builds);+ for (int invalid = 0; invalid < 7; ++invalid) {+ const uint8_t *data = heights.data();+ int w = width, h = height;+ double scale = 1, ceiling = 10;+ switch (invalid) {+ case 0 : data = nullptr;+ break;+ case 1 : w = 1;+ break;+ case 2 : h = 2049;+ break;+ case 3 : scale = -0.0;+ break;+ case 4 : scale = INFINITY;+ break;+ case 5 : ceiling = NAN;+ break;+ case 6 : ceiling = INFINITY;+ break;+ }+ auto invalidQuery = cache.Prepare(data, w, h, scale, ceiling);+ bool wet = false;+ CHECK(!invalidQuery.HasWet(0, 1, 0, 1, wet));+ CHECK(!wet);+ }+}+}diff --git a/GeneralsMD/Code/Tests/WaterWaveCageCopyTest.h b/GeneralsMD/Code/Tests/WaterWaveCageCopyTest.hnew file mode 100644index 000000000..d6219503c--- /dev/null+++ b/GeneralsMD/Code/Tests/WaterWaveCageCopyTest.h@@ -0,0 +1,227 @@+#pragma once++#include "WaterWaveCageMeshReference.h"+#include "Platform/WaterWaveCageMesh.h"+#include <limits>+#include <utility>++namespace WaterWaveCageCopyTest {+using WaterProjectedMesh::Mesh;+using WaterProjectedMesh::Point;++inline Mesh Grid(int columns = 5, int rows = 4) {+ Mesh mesh;+ mesh.cells = columns * rows;+ for (int y = 0; y <= rows; ++y)+ for (int x = 0; x <= columns; ++x) {+ WaterProjectedMesh::Vertex v;+ v.world = {double(x), double(y)};+ v.edgeParameter = (x + y) * .03125;+ v.knot = x - y;+ v.lattice = y * (columns + 1) + x;+ mesh.vertices.push_back(v);+ }+ for (int y = 0; y < rows; ++y)+ for (int x = 0; x < columns; ++x) {+ const uint16_t a = uint16_t(y * (columns + 1) + x), b = uint16_t(a + 1);+ const uint16_t c = uint16_t(a + columns + 2), d = uint16_t(a + columns + 1);+ mesh.indices.insert(mesh.indices.end(), {a, b, c, a, c, d});+ }+ WaterProjectedMesh::CentreTransition transition = {};+ transition.source[0] = {1, 2};+ transition.source[1] = {3, 4};+ transition.source[2] = {5, 6};+ transition.weight[0] = .25;+ transition.weight[1] = .5;+ transition.weight[2] = .25;+ transition.analytic = .75;+ mesh.transitions.push_back(transition);+ WaterProjectedMesh::BoundaryCollar collar;+ collar.count = 2;+ collar.fade = .625;+ collar.edge[0] = 1;+ collar.parameter[0] = .25;+ collar.weight[0] = .75;+ collar.edge[1] = 3;+ collar.parameter[1] = .5;+ collar.weight[1] = .25;+ mesh.collars.push_back(collar);+ return mesh;+}++template <class Depth, class Support>+inline bool Compare(const Mesh &input, const Depth &depth, const Support &support, size_t budget = 65535) {+ Mesh reference = input, actual = input;+ std::vector<Point> oldDepth, newDepth, oldSupport, newSupport;+ const bool expected = WaterWaveCageMeshFrozenReference::ClipRestWaterline(reference,+ [&](Point p) {+ oldDepth.push_back(p);+ return depth(p);+ },+ [&](Point p) {+ oldSupport.push_back(p);+ return support(p);+ }, budget);+ const bool result = WaterWaveCageMesh::ClipRestWaterline(actual,+ [&](Point p) {+ newDepth.push_back(p);+ return depth(p);+ },+ [&](Point p) {+ newSupport.push_back(p);+ return support(p);+ }, budget);+ CHECK(result == expected && projectedCacheSameMesh(reference, actual));+ if (!expected)+ CHECK(projectedCacheSameMesh(input, actual));+ // Preserve callback order and every bisection coordinate, including early failure.+ for (const auto pair :{std::make_pair(&oldDepth, &newDepth), std::make_pair(&oldSupport, &newSupport)}) {+ CHECK(pair.first->size() == pair.second->size());+ if (pair.first->size() != pair.second->size())+ continue;+ for (size_t i = 0; i < pair.first->size(); ++i) {+ CHECK(projectedCacheSameDouble((*pair.first)[i].x, (*pair.second)[i].x));+ CHECK(projectedCacheSameDouble((*pair.first)[i].y, (*pair.second)[i].y));+ }+ }+ return result;+}++inline void NoopsAndChains() {+ // Equal output alone does not prove copy elision. Wet no-ops must retain+ // both buffers, and clipping must append into available vertex capacity.+ Mesh stable=Grid();+ const auto *vertices=stable.vertices.data();+ const auto *indices=stable.indices.data();+ CHECK(WaterWaveCageMesh::ClipRestWaterline(stable,[](Point) { return 1.; },[](Point) { return true; }));+ CHECK(stable.vertices.data()==vertices && stable.indices.data()==indices);+ Mesh clipped=Grid();clipped.vertices.reserve(1000);+ vertices=clipped.vertices.data();+ CHECK(WaterWaveCageMesh::ClipRestWaterline(clipped,[](Point p) { return p.x-.37; },[](Point) { return true; }));+ CHECK(clipped.vertices.data()==vertices);+ const auto supported = [](Point) {+ return true;+ };+ Mesh mesh = Grid();+ CHECK(Compare(mesh, [](Point) {+ return 1.;+ }, supported));+ CHECK(Compare(mesh, [](Point) {+ return -0.;+ }, supported));+ CHECK(Compare(mesh, [](Point) {+ return -1.;+ }, supported));+ CHECK(Compare(mesh, [](Point p) {+ return p.x - 2.;+ }, [](Point) {+ return false;+ }));+ // Crossing propagation disables both owners and their connected chain.+ for (int protection = 0; protection < 3; ++protection) {+ Mesh chain = Grid(1, 1);+ if (protection == 0)+ chain.vertices[2].boundary = 2;+ if (protection == 1)+ chain.vertices[2].collar = 0;+ if (protection == 2)+ chain.vertices[2].transition = 0;+ CHECK(Compare(chain, [](Point p) {+ return p.x - .5;+ }, supported));+ }+ mesh.indices.clear();+ CHECK(Compare(mesh, [](Point) {+ return -1.;+ }, supported));+ Mesh empty;+ CHECK(Compare(empty, [](Point) {+ return 1.;+ }, supported));+}++inline void CrossingsAndBudgets() {+ const auto supported = [](Point) {+ return true;+ };+ for (int frame = 0; frame < 24; ++frame) {+ Mesh mesh = Grid(9, 7);+ if (frame % 3 == 1)+ for (size_t t = 0; t < mesh.indices.size(); t += 3)+ std::swap(mesh.indices[t], mesh.indices[t + 2]);+ if (frame % 4 == 0) {+ mesh.vertices[0].boundary = 0;+ mesh.vertices[19].collar = 0;+ mesh.vertices[58].transition = 0;+ }+ const auto depth = [&](Point p) {+ return p.x * p.x * .075 - p.y * .21 - 1.7 + frame * .037;+ };+ CHECK(Compare(mesh, depth, [&](Point p) {+ return frame % 2 == 0 || p.x + p.y > 2.;+ }));+ }+ const Mesh mesh = Grid(1, 1);+ for (size_t budget = 0; budget <= 9; ++budget)+ Compare(mesh, [](Point p) {+ return p.x - .37;+ }, supported, budget);+ CHECK(Compare(Grid(2, 1), [](Point p) {+ return p.x - 1.;+ }, supported)); // Exact zero endpoint.+ Mesh high = mesh;+ high.vertices.resize(65532, mesh.vertices[0]);+ CHECK(Compare(high, [](Point p) {+ return p.x - .37;+ }, supported));+ high.vertices.push_back(mesh.vertices[0]);+ CHECK(!Compare(high, [](Point p) {+ return p.x - .37;+ }, supported)); // Partial split rolls back.+ high.vertices.resize(65536, mesh.vertices[0]);+ CHECK(!Compare(high, [](Point) {+ return 1.;+ }, supported));+}++inline void InvalidRollback() {+ const auto supported = [](Point) {+ return true;+ };+ const Mesh base = Grid(1, 1);+ for (int failure = 0; failure < 6; ++failure) {+ Mesh mesh = base;+ if (failure == 0)+ mesh.indices.push_back(0);+ if (failure == 1)+ mesh.indices[1] = 65535;+ if (failure == 2)+ mesh.indices[1] = mesh.indices[0];+ if (failure == 3)+ mesh.vertices[0].world.x = std::numeric_limits<double>::quiet_NaN();+ if (failure == 4)+ mesh.vertices[0].world.y = std::numeric_limits<double>::infinity();+ if (failure == 5)+ mesh.indices.insert(mesh.indices.end(), {0, 1, 2});+ // Constant wet depth must still reject invalid edges before the no-op return.+ const bool result = Compare(mesh, [](Point) {+ return 1.;+ }, supported);+ CHECK(result == (failure == 5));+ }+ Mesh nonmanifold = base;+ nonmanifold.indices.insert(nonmanifold.indices.end(), {0, 1, 3});+ CHECK(!Compare(nonmanifold, [](Point p) {+ return p.x - .5;+ }, supported));+ CHECK(!Compare(base, [](Point) {+ return std::numeric_limits<double>::quiet_NaN();+ }, supported));+ CHECK(!Compare(base, [](Point p) {+ return p.x == .5 ? std::numeric_limits<double>::infinity() : p.x - .5;+ }, supported));+ CHECK(!Compare(base, [](Point) {+ return 1.;+ }, supported, 65536));+}+}diff --git a/GeneralsMD/Code/Tests/WaterWaveCageMeshReference.h b/GeneralsMD/Code/Tests/WaterWaveCageMeshReference.hnew file mode 100644index 000000000..e79d16180--- /dev/null+++ b/GeneralsMD/Code/Tests/WaterWaveCageMeshReference.h@@ -0,0 +1,101 @@+// Frozen HEAD 3c1f8285 rest-waterline oracle; only namespace renamed.+/* Copyright 2026. SPDX-License-Identifier: GPL-3.0-or-later */+#pragma once+#include "Platform/WaterProjectedMesh.h"+#include <array>+#include <unordered_map>++namespace WaterWaveCageMeshFrozenReference {+constexpr unsigned WaterlineIterations=16;+// Section 8 of Jeschke et al. (2020): insert rest-waterline vertices before+// evaluating the cage map. Samplers take a WaterProjectedMesh::Point; depth is+// water level minus bilinear terrain height, and eligible selects cage support.+// Authored edges, collars and transition fans are deliberately preserved. If a+// crossed edge touches an ineligible triangle, preserve its whole connected+// crossing chain: partially clipping that chain would introduce a T junction.+// A chain that reaches an authored seam can therefore remain untessellated.+// Failure is atomic. This clips sign-changing triangle edges, not sub-triangle+// islands or multiple terrain crossings with equal-sign edge endpoints.+template<class DepthSampler,class EligibleSampler>+inline bool ClipRestWaterline(WaterProjectedMesh::Mesh&mesh,DepthSampler depthSampler,+ EligibleSampler eligibleSampler,size_t maxVertices=65535){+ using namespace WaterProjectedMesh;+ if(maxVertices>65535||mesh.vertices.size()>maxVertices||mesh.indices.size()%3)return false;+ const size_t triangleCount=mesh.indices.size()/3;+ std::vector<double> depths(mesh.vertices.size());std::vector<uint8_t> eligibleVertex(mesh.vertices.size());+ for(size_t i=0;i<mesh.vertices.size();++i){+ const auto&v=mesh.vertices[i];+ if(!std::isfinite(v.world.x)||!std::isfinite(v.world.y))return false;+ depths[i]=depthSampler(v.world);if(!std::isfinite(depths[i]))return false;+ eligibleVertex[i]=v.boundary<0&&v.collar<0&&v.transition<0&&eligibleSampler(v.world);+ }+ struct Edge {size_t owner[2]={0,0};unsigned count=0;int vertex=-1;};+ std::unordered_map<uint32_t,Edge> edges;+ constexpr uint32_t None=0xffffffffu;+ std::vector<std::array<uint32_t,3>> crossings(triangleCount,std::array<uint32_t,3>{{None,None,None}});+ std::vector<uint8_t> eligible(triangleCount,1);std::vector<size_t> queue;+ const auto key=[](uint16_t a,uint16_t b){return (uint32_t((std::min)(a,b))<<16)|uint32_t((std::max)(a,b));};+ for(size_t t=0;t<triangleCount;++t){+ for(int corner=0;corner<3;++corner){+ const uint16_t a=mesh.indices[t*3+corner],b=mesh.indices[t*3+(corner+1)%3];+ if(a>=mesh.vertices.size()||b>=mesh.vertices.size()||a==b)return false;+ eligible[t]=eligible[t]&&eligibleVertex[a];+ if((depths[a]<0&&depths[b]>0)||(depths[b]<0&&depths[a]>0)){+ const auto k=key(a,b);crossings[t][corner]=k;auto&e=edges[k];+ if(e.count>=2)return false;e.owner[e.count++]=t;+ }+ }+ if(!eligible[t])queue.push_back(t);+ }+ for(size_t head=0;head<queue.size();++head){+ for(auto k:crossings[queue[head]])if(k!=None){+ const auto&e=edges.find(k)->second;+ for(unsigned owner=0;owner<e.count;++owner)if(eligible[e.owner[owner]]){+ eligible[e.owner[owner]]=0;queue.push_back(e.owner[owner]);+ }+ }+ }+ auto vertices=mesh.vertices;std::vector<uint16_t> indices;indices.reserve(mesh.indices.size());bool valid=true;+ const auto intersection=[&](uint16_t a,uint16_t b)->uint16_t{+ if(depths[a]==0)return a;if(depths[b]==0)return b;+ auto found=edges.find(key(a,b));if(found==edges.end()){valid=false;return 0;}+ auto&e=found->second;if(e.vertex>=0)return uint16_t(e.vertex);+ // Always evaluate in canonical endpoint order, independently of winding.+ const uint16_t first=(std::min)(a,b),second=(std::max)(a,b);+ const Point p=mesh.vertices[first].world,q=mesh.vertices[second].world;+ double low=0,high=1,lowDepth=depths[first];+ for(unsigned step=0;step<WaterlineIterations;++step){+ const double mid=(low+high)*.5;const Point point{p.x+(q.x-p.x)*mid,p.y+(q.y-p.y)*mid};+ const double depth=depthSampler(point);if(!std::isfinite(depth)){valid=false;return 0;}+ if(depth==0){low=high=mid;lowDepth=0;break;}+ if((depth>=0)==(lowDepth>=0)){low=mid;lowDepth=depth;}else high=mid;+ }+ const double parameter=lowDepth>=0?low:high; // round toward the wet side+ if(vertices.size()>=maxVertices){valid=false;return 0;}+ Vertex v;v.world={p.x+(q.x-p.x)*parameter,p.y+(q.y-p.y)*parameter};+ e.vertex=int(vertices.size());vertices.push_back(v);return uint16_t(e.vertex);+ };+ const auto triangle=[&](uint16_t a,uint16_t b,uint16_t c){+ if(a==b||b==c||c==a)return;+ const Point pa=vertices[a].world,pb=vertices[b].world,pc=vertices[c].world;+ if(std::abs((pb.x-pa.x)*(pc.y-pa.y)-(pb.y-pa.y)*(pc.x-pa.x))<1e-16)return;+ indices.insert(indices.end(),{a,b,c});+ };+ for(size_t t=0;t<triangleCount;++t){+ const uint16_t a=mesh.indices[t*3],b=mesh.indices[t*3+1],c=mesh.indices[t*3+2];+ if(!eligible[t]||(depths[a]>=0&&depths[b]>=0&&depths[c]>=0)){+ indices.insert(indices.end(),{a,b,c});continue;+ }+ if(depths[a]<0&&depths[b]<0&&depths[c]<0)continue;+ uint16_t polygon[6];unsigned count=0;uint16_t previous=c;+ for(uint16_t current:{a,b,c}){+ const bool before=depths[previous]>=0,after=depths[current]>=0;+ if(before!=after){polygon[count++]=intersection(previous,current);if(!valid)return false;}+ if(after)polygon[count++]=current;+ previous=current;+ }+ for(unsigned i=1;i+1<count;++i)triangle(polygon[0],polygon[i],polygon[i+1]);+ }+ mesh.vertices.swap(vertices);mesh.indices.swap(indices);return true;+}+}diff --git a/GeneralsMD/Code/Tests/test_sdl_pipeline_state.cpp b/GeneralsMD/Code/Tests/test_sdl_pipeline_state.cppindex 13b7c5f70..5c407c9da 100644--- a/GeneralsMD/Code/Tests/test_sdl_pipeline_state.cpp+++ b/GeneralsMD/Code/Tests/test_sdl_pipeline_state.cpp@@ -289,6 +289,41 @@ int main()CHECK(sampler != NULL && samplers->Sampler(sampler_states) == sampler);sampler_states[D3DSAMP_ADDRESSU] = D3DTADDRESS_BORDER;CHECK(samplers->Sampler(sampler_states) == NULL && !samplers->Refusal().empty());+ // Alternating stage settings must reuse the exact sampler (or refusal) without+ // hashing every call. Eviction only drops this shortcut, never the owned entry.+ RenderUInt32 recent_states[4][14];+ SDL_GPUSampler *recent_samplers[4];+ for (unsigned i = 0; i < 4; ++i) {+ memcpy(recent_states[i], sampler_states, sizeof(sampler_states));+ recent_states[i][D3DSAMP_ADDRESSU] = i == 3 ? D3DTADDRESS_BORDER : D3DTADDRESS_WRAP;+ recent_states[i][D3DSAMP_MAXMIPLEVEL] = i;+ recent_samplers[i] = samplers->Sampler(recent_states[i]);+ CHECK((recent_samplers[i] != NULL) == (i != 3));+ }+ // Settle the ring after the unrelated keys used above (hits do not change its+ // insertion order), then a four-key working set no longer needs the table.+ for (unsigned i = 0; i < 4; ++i)+ CHECK(samplers->Sampler(recent_states[i]) == recent_samplers[i]);+ const size_t populated = samplers->Table_Lookups();+ for (unsigned round = 0; round < 16; ++round)+ for (unsigned i = 0; i < 4; ++i)+ CHECK(samplers->Sampler(recent_states[i]) == recent_samplers[i]);+ CHECK(samplers->Table_Lookups() == populated);+ for (unsigned i = 4; i < 12; ++i) {+ recent_states[0][D3DSAMP_MAXMIPLEVEL] = i;+ CHECK(samplers->Sampler(recent_states[0]) != NULL);+ }+ recent_states[0][D3DSAMP_MAXMIPLEVEL] = 0;+ const size_t evicted = samplers->Table_Lookups();+ CHECK(samplers->Sampler(recent_states[0]) == recent_samplers[0]);+ CHECK(samplers->Table_Lookups() == evicted + 1);+ // Include high bits (float-valued sampler state) in the exact cache identity.+ recent_states[0][D3DSAMP_MIPMAPLODBIAS] = 0x3f000000u;+ CHECK(samplers->Sampler(recent_states[0]) != NULL);+ CHECK(samplers->Table_Lookups() == evicted + 2);+ recent_states[0][D3DSAMP_MIPMAPLODBIAS] = 0;+ CHECK(samplers->Sampler(recent_states[0]) == recent_samplers[0]);+ CHECK(samplers->Table_Lookups() == evicted + 2);printf("sdl_pipeline_state_selfcheck: %s: %u pipelines built\n", SDL_GetGPUDeviceDriver(frame->Device()),pipelines->Pipelines_Built());diff --git a/GeneralsMD/Code/Tests/test_water_grid.cpp b/GeneralsMD/Code/Tests/test_water_grid.cppindex b87e09231..2751ab1a0 100644--- a/GeneralsMD/Code/Tests/test_water_grid.cpp+++ b/GeneralsMD/Code/Tests/test_water_grid.cpp@@ -2509,14 +2509,33 @@ TEST(water_ocean_blended_displaced_shared_edges_are_exact_through_all_morphs)TEST(water_ocean_height_only_evaluation_is_bit_identical_to_the_full_model){using namespace WaterSurfaceModel;- for (float time:{0.0f,3.17f,97.5f,1220.3f}) for (int i=0;i<1200;++i) {+ for (float time:{-17.3f,0.0f,3.17f,97.5f,1220.3f}) for (int i=0;i<1200;++i) {const float x=-4395.0f+i*7.731f,y=3526.0f-i*5.377f;- CHECK(EvaluateOceanHeight(x,y,time)==EvaluateOcean(x,y,time).height);+ const float height=EvaluateOceanHeight(x,y,time),fullHeight=EvaluateOcean(x,y,time).height;+ const float templateHeight=EvaluateOceanInternal<false,false>(x,y,time).height;+ CHECK(memcmp(&height,&fullHeight,sizeof(height))==0);+ CHECK(memcmp(&height,&templateHeight,sizeof(height))==0);for (const Sample offshore: {Sample{0,0,0},Sample{0.25f,0.01f,-0.005f},Sample{1,0,0},Sample{1,0.001f,0}})CHECK(EvaluateBlendedHeight(x,y,time,offshore)==EvaluateBlended(x,y,time,offshore).height);}}+TEST(water_river_height_only_evaluation_is_bit_identical_to_the_full_model)+{+ using namespace WaterSurfaceModel;+ for (float time:{-17.3f,0.0f,3.17f,97.5f,1220.3f}) for (int i=0;i<1200;++i) {+ const float x=-4395.0f+i*7.731f,y=3526.0f-i*5.377f;+ const float height=EvaluateHeight(x,y,time),fullHeight=Evaluate(x,y,time).height;+ CHECK(memcmp(&height,&fullHeight,sizeof(height))==0);+ for (const Sample offshore: {Sample{-0.2f,0,0},Sample{0,0,0},Sample{0,0.01f,0},+ Sample{0.25f,0.01f,-0.005f},Sample{0.5f,0,0},Sample{1,0,0},Sample{1.2f,0.001f,0}}) {+ const float blended=EvaluateBlendedHeight(x,y,time,offshore);+ const float fullBlended=EvaluateBlended(x,y,time,offshore).height;+ CHECK(memcmp(&blended,&fullBlended,sizeof(blended))==0);+ }+ }+}+TEST(water_ocean_obstacle_broadphase_only_rejects_fully_unattenuated_samples){using namespace WaterSurfaceModel;@@ -5063,6 +5082,63 @@ TEST(water_style_changes_at_render_boundary_without_advancing_paused_time_or_relTheWaterTransparency=savedTransparency;delete scratch;TheWritableGlobalData=saved;}+namespace {+class WaterRenderCacheProbe : public WaterRenderObjClass {+public:+ void seedCaches() {+ using namespace WaterProjectedMesh;+ const Point corners[4]={{-95,-170},{81,-110},{120,92},{-64,170}};+ Mesh mesh;+ CHECK(m_modernRenderCaches.topology.Build(corners,testWaterProjection(),{16,12},mesh));+ m_modernRenderCaches.prepared.Process(mesh,5,false,false,[](Mesh &) {});+ m_modernRenderCaches.staticSamples.Get(1,2,3,[]() {+ return WaterStaticSampleCache::Sample{{.2f,.1f,0},.4f,5,1};+ });+ m_modernHeights.assign(81,30);+ CHECK(m_modernRenderCaches.terrain.Prewarm(m_modernHeights.data(),9,9,1,10));+ m_modernRenderCaches.samples.Store(SampleKey(1,2,3),{});+ CHECK(m_modernRenderCaches.topology.EntryCount()>0 && m_modernRenderCaches.prepared.EntryCount()>0);+ CHECK(m_modernRenderCaches.staticSamples.Size()>0 && m_modernRenderCaches.terrain.EntryCount()>0);+ CHECK(m_modernRenderCaches.samples.Size()>0);+ m_modernShorePreparation.revision=m_modernShoreRevision;+ }+ void checkCleared() {+ CHECK(m_modernRenderCaches.topology.EntryCount()==0 && m_modernRenderCaches.prepared.EntryCount()==0);+ CHECK(m_modernRenderCaches.staticSamples.Size()==0 && m_modernRenderCaches.terrain.EntryCount()==0);+ CHECK(m_modernRenderCaches.samples.Size()==0);+ }+ void changeStyle() { m_useModernWater=TRUE;synchronizeWaterStyle(); }+ void changeWaterPolygons() {+ m_modernOpticalPolygonsValid=TRUE;+ WaterOpticalContext::Polygon polygon;+ polygon.points={{0,0,4},{80,0,4},{80,60,4},{0,60,4}};+ m_modernOpticalPolygons={polygon};+ // The sync snapshot now has no polygons: an authored water area was removed.+ m_waterPolygonsForDraw.clear();+ refreshModernWaterOpticalPolygons();+ }+ void checkPreparationCleared() { CHECK(m_modernShorePreparation.revision==0); }+};+}++TEST(water_render_caches_clear_at_real_style_water_edit_map_and_device_boundaries)+{+ boot();+ const Int savedStyle=TheGlobalData->m_waterStyle;+ TheWritableGlobalData->m_waterStyle=0;+ WaterTransparencySetting *saved=(WaterTransparencySetting*)TheWaterTransparency.getNonOverloadedPointer();+ TheWaterTransparency=newInstance(WaterTransparencySetting);+ {+ WaterRenderCacheProbe water;+ water.seedCaches();water.changeStyle();water.checkCleared();water.checkPreparationCleared();+ water.seedCaches();water.changeWaterPolygons();water.checkCleared();water.checkPreparationCleared();+ water.seedCaches();water.reset();water.checkCleared();water.checkPreparationCleared();+ water.seedCaches();water.ReleaseResources();water.checkCleared();+ }+ TheWaterTransparency=saved;+ TheWritableGlobalData->m_waterStyle=savedStyle;+}+#endifTEST(water_quality_keeps_scene_depth_independent_of_colour_demand)@@ -5079,3 +5155,741 @@ TEST(water_quality_keeps_scene_depth_independent_of_colour_demand)CHECK(Applied().sceneReflections && Applied().requestedFftResolution == 256);Applied() = saved;}++#include "Platform/WaterProjectedMeshCache.h"++#include "Platform/WaterStaticSampleCache.h"++#include "Platform/WaterPreparedMeshCache.h"+#include "Platform/WaterTerrainCulling.h"+#include "Platform/WaterWaveCageMesh.h"++namespace {+bool projectedCacheSameDouble(double a,double b)+{+ uint64_t aa,bb;std::memcpy(&aa,&a,sizeof(aa));std::memcpy(&bb,&b,sizeof(bb));return aa==bb;+}+bool projectedCacheSameMesh(const WaterProjectedMesh::Mesh &a,const WaterProjectedMesh::Mesh &b)+{+ if (a.cells!=b.cells || a.indices!=b.indices || a.vertices.size()!=b.vertices.size() ||+ a.transitions.size()!=b.transitions.size() || a.collars.size()!=b.collars.size()) return false;+ for (size_t i=0;i<a.vertices.size();++i) {+ const auto &x=a.vertices[i],&y=b.vertices[i];+ if (!projectedCacheSameDouble(x.world.x,y.world.x) || !projectedCacheSameDouble(x.world.y,y.world.y) ||+ !projectedCacheSameDouble(x.edgeParameter,y.edgeParameter) || x.boundary!=y.boundary || x.knot!=y.knot ||+ x.transition!=y.transition || x.collar!=y.collar || x.lattice!=y.lattice) return false;+ }+ for (size_t i=0;i<a.transitions.size();++i) {+ const auto &x=a.transitions[i],&y=b.transitions[i];+ if (!projectedCacheSameDouble(x.analytic,y.analytic)) return false;+ for (int j=0;j<3;++j) if (!projectedCacheSameDouble(x.source[j].x,y.source[j].x) ||+ !projectedCacheSameDouble(x.source[j].y,y.source[j].y) || !projectedCacheSameDouble(x.weight[j],y.weight[j])) return false;+ }+ for (size_t i=0;i<a.collars.size();++i) {+ const auto &x=a.collars[i],&y=b.collars[i];+ if (x.count!=y.count || !projectedCacheSameDouble(x.fade,y.fade)) return false;+ for (int j=0;j<x.count;++j) if (x.edge[j]!=y.edge[j] || !projectedCacheSameDouble(x.parameter[j],y.parameter[j]) ||+ !projectedCacheSameDouble(x.weight[j],y.weight[j])) return false;+ }+ return true;+}+std::vector<WaterProjectedMesh::BoundaryKnot> projectedCacheKnots(const WaterProjectedMesh::Point corners[4])+{+ using namespace WaterProjectedMesh;std::vector<BoundaryKnot> knots;+ for (int edge=0;edge<4;++edge) {+ Point a=corners[edge],b=corners[(edge+1)%4];if (a.x>b.x || (a.x==b.x && a.y>b.y)) std::swap(a,b);+ for (int i=0;i<=8;++i) { const double t=i/8.;knots.push_back({{a.x+(b.x-a.x)*t,a.y+(b.y-a.y)*t},edge,i,t}); }+ }+ return knots;+}+}++TEST(water_projected_topology_cache_copies_every_base_mesh_field_before_dynamic_edits)+{+ using namespace WaterProjectedMesh;WaterProjectedMeshCache::Cache cache;+ const Point corners[4]={{-95,-170},{81,-110},{120,92},{-64,170}};+ const auto projection=testWaterProjection();const auto knots=projectedCacheKnots(corners);+ Mesh reference,actual;bool reused=true;+ CHECK(Build(corners,projection,{18,12},reference,60000,knots));+ CHECK(!reference.vertices.empty() && !reference.indices.empty() && !reference.transitions.empty() && !reference.collars.empty());+ CHECK(cache.Build(corners,projection,{18,12},actual,60000,knots,&reused));CHECK(!reused);+ CHECK(projectedCacheSameMesh(reference,actual));+ for (int frame=0;frame<3;++frame) {+ // Model downstream refinement, terrain culling and clipping changing every owned vector.+ actual.vertices.front().world.x+=100;actual.vertices.front().boundary=99;+ actual.indices.clear();actual.transitions.front().analytic=-1;actual.collars.front().fade=-1;actual.cells=0;+ actual.vertices.push_back(Vertex{});actual.transitions.push_back(CentreTransition{});actual.collars.push_back(BoundaryCollar{});+ CHECK(cache.Build(corners,projection,{18,12},actual,60000,knots,&reused));CHECK(reused);+ CHECK(projectedCacheSameMesh(reference,actual));+ }+ CHECK(cache.EntryCount()==1 && cache.CachedVertices()==reference.vertices.size());+ cache.Clear();CHECK(cache.EntryCount()==0 && cache.CachedVertices()==0);+ CHECK(cache.Build(corners,projection,{18,12},actual,60000,knots,&reused));CHECK(!reused);+ CHECK(projectedCacheSameMesh(reference,actual));+}++TEST(water_projected_topology_cache_keys_every_build_input_exactly)+{+ using namespace WaterProjectedMesh;WaterProjectedMeshCache::Cache cache(262144,128);+ const Point baseCorners[4]={{-95,-170},{81,-110},{120,92},{-64,170}};+ const Projection baseProjection=testWaterProjection();const auto baseKnots=projectedCacheKnots(baseCorners);+ Mesh baseline;CHECK(cache.Build(baseCorners,baseProjection,{18,12},baseline,60000,baseKnots));+ // Includes both dimensions selected from viewport size, every prepared projection scalar,+ // exact polygon coordinates, the caller's budget, and each ordered boundary-knot member.+ for (int input=0;input<43;++input) {+ Point corners[4];std::copy(baseCorners,baseCorners+4,corners);Projection projection=baseProjection;+ Resolution resolution={18,12};size_t budget=60000;auto knots=baseKnots;+ if (input<8) {+ double &coordinate=input%2?corners[input/2].y:corners[input/2].x;+ coordinate=std::nextafter(coordinate,INFINITY);+ } else if (input<17) {+ double &value=projection.matrix[input-8];value=std::nextafter(value,INFINITY);CHECK(projection.Prepare());+ } else if (input<26) {+ double &value=projection.inverse[input-17];value=std::nextafter(value,INFINITY);+ } else switch (input) {+ case 26: projection.depth.a=.0001;break;+ case 27: projection.depth.b=.0001;break;+ case 28: projection.depth.c=1.01;break;+ case 29: projection.nearDistance=.2;break;+ case 30: projection.farDistance=9;break;+ case 31: projection.margin=.13;break;+ case 32: ++resolution.columns;break;+ case 33: ++resolution.rows;break;+ case 34: --budget;break;+ case 35: knots[0].world.x=std::nextafter(knots[0].world.x,INFINITY);break;+ case 36: knots[0].world.y=std::nextafter(knots[0].world.y,INFINITY);break;+ case 37: ++knots[0].boundary;break;+ case 38: ++knots[0].index;break;+ case 39: knots[0].edgeParameter=.01;break;+ case 40: std::swap(knots[0],knots[1]);break;+ case 41: knots.pop_back();break;+ case 42: projection.matrix[1]=-0.0;break;+ }+ Mesh reference,actual;bool reused=true;+ CHECK(Build(corners,projection,resolution,reference,budget,knots));+ CHECK(cache.Build(corners,projection,resolution,actual,budget,knots,&reused));CHECK(!reused);+ CHECK(projectedCacheSameMesh(reference,actual));+ CHECK(cache.Build(corners,projection,resolution,actual,budget,knots,&reused));CHECK(reused);+ CHECK(projectedCacheSameMesh(reference,actual));+ }+}++TEST(water_projected_topology_cache_preserves_failed_and_empty_build_results)+{+ using namespace WaterProjectedMesh;WaterProjectedMeshCache::Cache cache;+ const Point corners[4]={{-500,-500},{500,-500},{500,500},{-500,500}};+ const auto projection=testWaterProjection();Mesh baseline;CHECK(cache.Build(corners,projection,{8,8},baseline));+ for (int failure=0;failure<3;++failure) {+ Point changed[4];std::copy(corners,corners+4,changed);auto p=projection;size_t budget=60000;+ if (failure==0) budget=1;+ if (failure==1) changed[2]={-500,0}; // Concave authored polygon.+ if (failure==2) { p.inverse[6]=1;p.inverse[8]=0; } // Failure after some appended vertices.+ Mesh reference=baseline,actual=baseline;bool reused=true;+ CHECK(!Build(changed,p,{8,8},reference,budget));+ CHECK(!cache.Build(changed,p,{8,8},actual,budget,{},&reused));CHECK(!reused);+ CHECK(projectedCacheSameMesh(reference,actual));+ CHECK(cache.EntryCount()==1 && cache.CachedVertices()==baseline.vertices.size());+ CHECK(cache.Build(corners,projection,{8,8},actual,60000,{},&reused));CHECK(reused);+ CHECK(projectedCacheSameMesh(baseline,actual));+ }+ Point invisible[4]={{1000,1000},{1100,1000},{1100,1100},{1000,1100}};Mesh empty,actual=baseline;bool reused=true;+ CHECK(Build(invisible,projection,{8,8},empty) && empty.vertices.empty());+ CHECK(cache.Build(invisible,projection,{8,8},actual,60000,{},&reused));CHECK(!reused);+ CHECK(projectedCacheSameMesh(empty,actual));+ CHECK(cache.Build(invisible,projection,{8,8},actual,60000,{},&reused));CHECK(reused);+ CHECK(projectedCacheSameMesh(empty,actual));+}++TEST(water_projected_topology_cache_bounds_multi_patch_storage_and_evicts_deterministically)+{+ using namespace WaterProjectedMesh;const auto projection=testWaterProjection();+ const Point corners[4]={{-500,-500},{500,-500},{500,500},{-500,500}};+ Mesh reference;CHECK(Build(corners,projection,{8,8},reference));const size_t count=reference.vertices.size();+ WaterProjectedMeshCache::Cache cache(count*2,8);Mesh actual;bool reused=true;+ // Distinct authored patches have identical visible meshes, but must retain separate exact keys.+ for (int patch=0;patch<3;++patch) {+ Point changed[4];std::copy(corners,corners+4,changed);changed[0].x-=patch;+ CHECK(cache.Build(changed,projection,{8,8},actual,60000,{},&reused));CHECK(!reused);+ CHECK(projectedCacheSameMesh(reference,actual));+ CHECK(cache.CachedVertices()<=count*2 && cache.EntryCount()<=2);+ }+ Point retained[4];std::copy(corners,corners+4,retained);retained[0].x-=1;+ CHECK(cache.Build(retained,projection,{8,8},actual,60000,{},&reused));CHECK(reused);+ CHECK(cache.Build(corners,projection,{8,8},actual,60000,{},&reused));CHECK(!reused); // FIFO oldest was evicted.+ WaterProjectedMeshCache::Cache tooSmall(count-1,8),disabled(262144,0);+ for (auto *uncached:{&tooSmall,&disabled}) for (int repeat=0;repeat<2;++repeat) {+ CHECK(uncached->Build(corners,projection,{8,8},actual,60000,{},&reused));CHECK(!reused);+ CHECK(projectedCacheSameMesh(reference,actual));CHECK(uncached->EntryCount()==0 && uncached->CachedVertices()==0);+ }+ WaterProjectedMeshCache::Cache emptyCache(0,2);+ for (int patch=0;patch<3;++patch) {+ const double x=1000+patch*100.;const Point invisible[4]={{x,1000},{x+10,1000},{x+10,1100},{x,1100}};+ CHECK(emptyCache.Build(invisible,projection,{8,8},actual));+ CHECK(actual.vertices.empty() && emptyCache.CachedVertices()==0 && emptyCache.EntryCount()<=2);+ }+}++namespace {+WaterStaticSampleCache::Sample staticCacheReference(const uint8_t field[9],float x,float y,float level,float terrainOffset=0)+{+ const auto offshore=WaterSurfaceModel::SampleOffshore(field,3,3,x/10,y/10,10);+ const float depth=level-(x*.2f+y*.3f+terrainOffset);+ return {offshore,offshore.height*.7f,depth,WaterSurfaceModel::TerrainDamping(depth,offshore.height)};+}+bool staticCacheSameSample(const WaterStaticSampleCache::Sample &a,const WaterStaticSampleCache::Sample &b)+{+ const float x[]={a.offshore.height,a.offshore.dx,a.offshore.dy,a.exposure,a.terrainDepth,a.terrainDamping};+ const float y[]={b.offshore.height,b.offshore.dx,b.offshore.dy,b.exposure,b.terrainDepth,b.terrainDamping};+ for (int i=0;i<6;++i) { uint32_t xx,yy;std::memcpy(&xx,&x[i],4);std::memcpy(&yy,&y[i],4);if (xx!=yy) return false; }+ return true;+}+}++TEST(water_static_sample_cache_reuses_exact_fields_and_keys_coordinates_order_and_level)+{+ const uint8_t field[9]={0,40,100,70,150,220,90,190,255};+ for (int change=0;change<4;++change) {+ WaterStaticSampleCache::Cache cache;int computed=0;+ const std::array<float,3> points[2]={{{1.25f,2.5f,7}},{{8,6,9}}};+ auto read=[&](const std::array<float,3> &p,bool expectedReuse) {+ const auto reference=staticCacheReference(field,p[0],p[1],p[2]);bool reused=!expectedReuse;+ auto value=cache.Get(p[0],p[1],p[2],[&]() { ++computed;return reference; },&reused);+ CHECK(reused==expectedReuse && staticCacheSameSample(value,reference));+ value.offshore.height=-100;value.terrainDamping=-100; // Returned copies are independently editable.+ };+ cache.BeginRender();for (const auto &p:points) read(p,false);CHECK(computed==2 && cache.Size()==2);+ for (int frame=0;frame<3;++frame) { cache.BeginRender();for (const auto &p:points) read(p,true); }+ CHECK(computed==2);+ auto changed=points[0];+ if (change<3) changed[change]=std::nextafter(changed[change],INFINITY);+ cache.BeginRender();+ if (change==3) { read(points[1],false);read(points[0],false);CHECK(computed==4); }+ else { read(changed,false);read(points[1],true);CHECK(computed==3); }+ }+}++TEST(water_static_sample_cache_clear_refreshes_changed_terrain_and_optical_context)+{+ uint8_t field[9]={0,40,100,70,150,220,90,190,255};WaterStaticSampleCache::Cache cache;+ int computed=0;float terrainOffset=0;auto compute=[&]() { ++computed;return staticCacheReference(field,8,6,7,terrainOffset); };+ bool reused=true;const auto original=cache.Get(8,6,7,compute,&reused);CHECK(!reused && computed==1);+ cache.BeginRender();CHECK(staticCacheSameSample(cache.Get(8,6,7,compute,&reused),original));CHECK(reused && computed==1);+ field[0]=255;field[1]=0;terrainOffset=3;+ const auto changed=staticCacheReference(field,8,6,7,terrainOffset);CHECK(!staticCacheSameSample(original,changed));+ cache.Clear();CHECK(cache.Size()==0);+ CHECK(staticCacheSameSample(cache.Get(8,6,7,compute,&reused),changed));CHECK(!reused && computed==2);+ cache.BeginRender();CHECK(staticCacheSameSample(cache.Get(8,6,7,compute,&reused),changed));CHECK(reused && computed==2);+}++TEST(water_static_sample_cache_bounds_storage_and_bypasses_nonfinite_coordinates)+{+ WaterStaticSampleCache::Cache cache(2);int computed=0;bool reused=true;+ const WaterStaticSampleCache::Sample reference={{.25f,.01f,-.02f},.4f,3,.8f};+ auto compute=[&]() { ++computed;return reference; };+ for (int render=0;render<2;++render) {+ cache.BeginRender();+ for (int i=0;i<3;++i) {+ CHECK(staticCacheSameSample(cache.Get(float(i),1,7,compute,&reused),reference));+ CHECK(reused==(render==1 && i<2));CHECK(cache.Size()<=2);+ }+ }+ CHECK(computed==4 && cache.Size()==2);+ cache.BeginRender();+ const float nan=std::numeric_limits<float>::quiet_NaN(),inf=std::numeric_limits<float>::infinity();+ for (auto p:{std::array<float,3>{{nan,1,7}},std::array<float,3>{{0,inf,7}},std::array<float,3>{{0,1,-inf}}}) {+ CHECK(staticCacheSameSample(cache.Get(p[0],p[1],p[2],compute,&reused),reference));CHECK(!reused && cache.Size()==2);+ }+ CHECK(computed==7);+ // Invalid requests do not consume sequence slots; signed zero uses the common world key.+ CHECK(staticCacheSameSample(cache.Get(-0.0f,1,7,compute,&reused),reference));CHECK(reused && computed==7);+ WaterStaticSampleCache::Cache disabled(0);+ for (int repeat=0;repeat<2;++repeat) {+ disabled.BeginRender();CHECK(staticCacheSameSample(disabled.Get(0,1,7,compute,&reused),reference));CHECK(!reused && disabled.Size()==0);+ }+}++namespace {+WaterProjectedMesh::Mesh preparedCacheInput()+{+ using namespace WaterProjectedMesh;Mesh mesh;mesh.cells=17;+ for (Point p:{Point{2,2},Point{8,2},Point{2,8},Point{22,22},Point{25,22},Point{22,25},Point{90,90}}) {+ Vertex v;v.world=p;mesh.vertices.push_back(v);+ }+ mesh.indices={0,1,2,3,4,5};+ for (int i=0;i<2;++i) {+ CentreTransition transition={};transition.analytic=.2+i*.1;+ for (int j=0;j<3;++j) { transition.source[j]={double(i+j),double(i-j)};transition.weight[j]=(j+1)/6.; }+ mesh.transitions.push_back(transition);+ BoundaryCollar collar={};collar.count=4;collar.fade=.6+i*.1;+ for (int j=0;j<4;++j) { collar.edge[j]=j;collar.parameter[j]=.1*j;collar.weight[j]=.1*(j+1); }+ mesh.collars.push_back(collar);+ }+ return mesh;+}+std::vector<uint8_t> preparedCacheTerrain()+{+ std::vector<uint8_t> heights;+ for (int y=0;y<4;++y) for (uint8_t h:{uint8_t(0),uint8_t(10),uint8_t(100),uint8_t(100)}) heights.push_back(h);+ return heights;+}+void preparedCachePipeline(WaterProjectedMesh::Mesh &mesh,const std::vector<uint8_t> &heights,float level,bool cull,bool cage)+{+ if (cull) CHECK(WaterTerrainCulling::CullDryTriangles(mesh,heights.data(),4,4,0,10,1,level,0,0));+ if (cage) CHECK(WaterWaveCageMesh::ClipRestWaterline(mesh,[&](WaterProjectedMesh::Point p) { return level-p.x; },+ [](WaterProjectedMesh::Point) { return true; }));+ CHECK(WaterTerrainCulling::CompactVertices(mesh));+}+size_t preparedCacheBytes(const WaterProjectedMesh::Mesh &mesh)+{+ return mesh.vertices.size()*sizeof(WaterProjectedMesh::Vertex)+mesh.indices.size()*sizeof(uint16_t)++ mesh.transitions.size()*sizeof(WaterProjectedMesh::CentreTransition)+mesh.collars.size()*sizeof(WaterProjectedMesh::BoundaryCollar);+}+}++TEST(water_prepared_mesh_cache_matches_actual_cull_clip_compact_and_isolates_output_edits)+{+ const auto input=preparedCacheInput();const auto terrain=preparedCacheTerrain();auto reference=input;+ preparedCachePipeline(reference,terrain,5,true,true);+ CHECK(reference.vertices.size()==4 && reference.indices.size()==6 && !projectedCacheSameMesh(reference,input));+ WaterPreparedMeshCache::Cache cache;int computed=0;bool reused=true;+ auto compute=[&](WaterProjectedMesh::Mesh &mesh) { ++computed;preparedCachePipeline(mesh,terrain,5,true,true); };+ auto actual=input;cache.Process(actual,5,true,true,compute,&reused);+ CHECK(!reused && computed==1 && projectedCacheSameMesh(actual,reference));+ // Each frame starts with the base/refined input; downstream draw preparation owns its result.+ actual.vertices[0].world.x=-100;actual.indices.clear();actual.collars[0].fade=-1;+ actual.transitions[0].analytic=-1;actual.cells=0;+ for (int frame=0;frame<3;++frame) {+ actual=input;cache.Process(actual,5,true,true,compute,&reused);+ CHECK(reused && computed==1 && projectedCacheSameMesh(actual,reference));+ }+ CHECK(cache.CachedBytes()==preparedCacheBytes(input)+preparedCacheBytes(reference));+}++TEST(water_prepared_mesh_cache_keys_every_semantic_field_without_uninitialized_collar_tails)+{+ using namespace WaterProjectedMesh;const Mesh input=preparedCacheInput();+ auto changedMisses=[&](Mesh changed,float level=5,bool cull=false,bool cage=false) {+ WaterPreparedMeshCache::Cache cache;int computed=0;bool reused=true;+ auto compute=[&](Mesh &) { ++computed; };Mesh initial=input;cache.Process(initial,5,false,false,compute);+ Mesh actual=changed;cache.Process(actual,level,cull,cage,compute,&reused);+ CHECK(!reused && computed==2 && projectedCacheSameMesh(actual,changed));+ actual=changed;cache.Process(actual,level,cull,cage,compute,&reused);+ CHECK(reused && computed==2 && projectedCacheSameMesh(actual,changed));+ };+ for (size_t i=0;i<input.vertices.size();++i) for (int field=0;field<8;++field) {+ Mesh changed=input;auto &v=changed.vertices[i];+ switch (field) {+ case 0: v.world.x=std::nextafter(v.world.x,INFINITY);break;+ case 1: v.world.y=std::nextafter(v.world.y,INFINITY);break;+ case 2: v.boundary=0;break;+ case 3: v.edgeParameter=std::nextafter(v.edgeParameter,INFINITY);break;+ case 4: v.knot=0;break;+ case 5: v.transition=0;break;+ case 6: v.collar=0;break;+ case 7: v.lattice=0;break;+ }+ changedMisses(changed);+ }+ for (size_t i=0;i<input.transitions.size();++i) for (int field=0;field<10;++field) {+ Mesh changed=input;auto &t=changed.transitions[i];+ double &value=field==9?t.analytic:field%3==0?t.source[field/3].x:field%3==1?t.source[field/3].y:t.weight[field/3];+ value=std::nextafter(value,INFINITY);changedMisses(changed);+ }+ for (size_t i=0;i<input.collars.size();++i) for (int field=0;field<14;++field) {+ Mesh changed=input;auto &c=changed.collars[i];+ if (field==0) --c.count;+ else if (field==1) c.fade=std::nextafter(c.fade,INFINITY);+ else {+ const int slot=(field-2)/3,member=(field-2)%3;+ if (!member) c.edge[slot]=(c.edge[slot]+1)%4;+ else { double &value=member==1?c.parameter[slot]:c.weight[slot];value=std::nextafter(value,INFINITY); }+ }+ changedMisses(changed);+ }+ for (size_t i=0;i<input.indices.size();++i) { Mesh changed=input;changed.indices[i]=(changed.indices[i]+1)%input.vertices.size();changedMisses(changed); }+ for (int field=0;field<9;++field) {+ Mesh changed=input;+ switch (field) {+ case 0: ++changed.cells;break;+ case 1: changed.vertices.pop_back();break;+ case 2: changed.vertices.push_back(input.vertices.back());break;+ case 3: changed.transitions.pop_back();break;+ case 4: changed.transitions.push_back(input.transitions.back());break;+ case 5: changed.collars.pop_back();break;+ case 6: changed.collars.push_back(input.collars.back());break;+ case 7: changed.indices.resize(3);break;+ case 8: std::swap(changed.indices[0],changed.indices[1]);break;+ }+ changedMisses(changed);+ }+ changedMisses(input,std::nextafter(5.f,INFINITY));changedMisses(input,5,true,false);changedMisses(input,5,false,true);+ WaterPreparedMeshCache::Cache cache;int computed=0;auto compute=[&](Mesh &) { ++computed; };+ Mesh initial=input;initial.collars[0].count=1;cache.Process(initial,0,false,false,compute);+ Mesh same=initial;for (int i=1;i<4;++i) { same.collars[0].edge[i]=100;same.collars[0].parameter[i]=NAN;same.collars[0].weight[i]=NAN; }+ bool reused=false;cache.Process(same,0,false,false,compute,&reused);CHECK(reused && computed==1);+ Mesh signedZero=initial;cache.Process(signedZero,-0.0f,false,false,compute,&reused);CHECK(!reused && computed==2);+}++TEST(water_prepared_mesh_cache_clear_refreshes_terrain_and_bounds_bypasses_preserve_entry)+{+ using namespace WaterProjectedMesh;const auto input=preparedCacheInput();auto terrain=preparedCacheTerrain();+ WaterPreparedMeshCache::Cache cache;int computed=0;bool reused=true;+ auto compute=[&](Mesh &mesh) { ++computed;preparedCachePipeline(mesh,terrain,5,true,false); };+ Mesh original=input;cache.Process(original,5,true,false,compute);CHECK(computed==1 && original.vertices.size()==3);+ std::fill(terrain.begin(),terrain.end(),0);cache.Clear();CHECK(cache.CachedBytes()==0);+ Mesh changed=input;cache.Process(changed,5,true,false,compute,&reused);+ CHECK(!reused && computed==2 && changed.vertices.size()==6 && !projectedCacheSameMesh(original,changed));+ const size_t bound=preparedCacheBytes(input)*2;WaterPreparedMeshCache::Cache bounded(bound);+ int calls=0;auto identity=[&](Mesh &) { ++calls; };Mesh actual=input;bounded.Process(actual,5,false,false,identity);+ CHECK(calls==1 && bounded.CachedBytes()<=bound);const size_t stored=bounded.CachedBytes();+ for (int invalid=0;invalid<6;++invalid) {+ Mesh request=input;float level=5;+ if (invalid==0) request.vertices.resize(1000);+ if (invalid==1) request.indices[0]=65535;+ if (invalid==2) request.collars[0].count=5;+ if (invalid==3) request.vertices[0].world.x=NAN;+ if (invalid==4) level=INFINITY;+ if (invalid==5) request.indices.pop_back();+ const int before=calls;bounded.Process(request,level,false,false,identity,&reused);+ CHECK(!reused && calls==before+1 && bounded.CachedBytes()==stored);+ actual=input;bounded.Process(actual,5,false,false,identity,&reused);CHECK(reused && calls==before+1);+ }+ for (bool invalidOutput:{false,true}) {+ Mesh request=input;++request.cells;const int before=calls;+ bounded.Process(request,5,false,false,[&](Mesh &mesh) { ++calls;if (invalidOutput) mesh.collars[0].count=-1;else mesh.vertices.resize(1000); },&reused);+ CHECK(!reused && calls==before+1 && bounded.CachedBytes()==stored);+ actual=input;bounded.Process(actual,5,false,false,identity,&reused);CHECK(reused && calls==before+1);+ }+ WaterPreparedMeshCache::Cache disabled(0);actual=input;disabled.Process(actual,5,false,false,identity,&reused);+ CHECK(!reused && disabled.CachedBytes()==0 && projectedCacheSameMesh(actual,input));+}++TEST(water_prepared_mesh_cache_keeps_one_entry_per_patch_and_evicts_fifo)+{+ using namespace WaterProjectedMesh;const auto input=preparedCacheInput();+ int computed=0;bool reused=true;auto compute=[&](Mesh &) { ++computed; };+ std::vector<Mesh> patches;+ for (int patch=0;patch<3;++patch) { Mesh changed=input;changed.cells+=patch;patches.push_back(changed); }+ WaterPreparedMeshCache::Cache cache(32u*1024u*1024u,2);+ // Two visible patches alternate every frame; neither may evict the other.+ for (int frame=0;frame<3;++frame) for (int patch=0;patch<2;++patch) {+ Mesh actual=patches[patch];cache.Process(actual,5,false,false,compute,&reused);+ CHECK(reused==(frame>0) && projectedCacheSameMesh(actual,patches[patch]));+ }+ CHECK(computed==2 && cache.EntryCount()==2);+ Mesh third=patches[2];cache.Process(third,5,false,false,compute,&reused);+ CHECK(!reused && computed==3 && cache.EntryCount()==2);+ Mesh oldest=patches[0];cache.Process(oldest,5,false,false,compute,&reused);CHECK(!reused);+ Mesh newest=patches[2];cache.Process(newest,5,false,false,compute,&reused);CHECK(reused);+ WaterPreparedMeshCache::Cache disabled(32u*1024u*1024u,0);+ for (int repeat=0;repeat<2;++repeat) {+ Mesh actual=input;disabled.Process(actual,5,false,false,compute,&reused);+ CHECK(!reused && disabled.EntryCount()==0 && disabled.CachedBytes()==0);+ }+}++#include "WaterPreparedViewTest.h"++#include "WaterShorePreparedTest.h"+TEST(water_shore_prepared_topology_matches_frozen_live_install_phase_and_history)+{+ WaterShorePreparedTest::Check();+}++namespace {+struct ShoreCountingSupport {+ unsigned mask = 15;+ mutable size_t lookups = 0, allows = 0;+ struct Stencil {+ const ShoreCountingSupport *owner;+ double x, y;+ bool Allows(unsigned dx, unsigned dy) const {+ ++owner->allows;+ return (owner->mask & (1u << (dy * 2 + dx))) && (dx ? x > .13 : x < .87) && (dy ? y > .17 : y < .83);+ }+ };+ Stencil At(int32_t, int32_t, double, double x, double y) const {+ ++lookups;+ return {this, x, y};+ }+};+}+TEST(water_shore_raster_lookup_reuses_only_static_work_and_invalidates_dependencies) {+ using namespace WaterShoreHistory;+ Topology topology;+ auto cells = shoreFourCorners();+ cells.push_back({0, 0, 20, 4});+ CHECK(topology.Build({}, cells) == BuildResult::Ready);+ std::vector<State> states(topology.Cells().size(), {1, 2});+ Mapping mapping = {-2.5, -2.5, 10, 10, 40, 32};+ ShoreCountingSupport support;+ RasterLookup lookup;+ uint64_t revision = 1;+ struct Material {+ std::vector<State> inputs;+ std::vector<double> coordinates;+ double operator()(const State &s, double x, double y, double time) {+ inputs.push_back(s);+ coordinates.insert(coordinates.end(), {x, y, time});+ return -std::expm1(-s.density) * (.6 + .2 * std::sin(x * .3 + y * .7 + time + s.ageMoment / (s.density+ + .01)));+ }+ };+ auto compare = [&](double level, double time) {+ std::vector<uint32_t> seed(size_t(mapping.widthPixels) * mapping.heightPixels);+ for (size_t i = 0; i < seed.size(); ++i)+ seed[i] = 0xff000000u | ((uint32_t(i) * 2654435761u) & 0xffffffu);+ auto expected = seed, actual = seed;+ Material a, b;+ CHECK(RasterizeAlpha(topology, states, mapping, level, time, a, expected, support));+ const auto before = support.lookups, allowBefore = support.allows, builds = lookup.BuildCount();+ CHECK(RasterizeAlphaCached(topology, states, mapping, level, time, b, actual, support, lookup, revision));+ CHECK(expected == actual);+ CHECK(a.coordinates == b.coordinates);+ CHECK(a.inputs.size() == b.inputs.size());+ for (size_t i = 0; i < a.inputs.size() && i < b.inputs.size(); ++i) {+ CHECK(a.inputs[i].density == b.inputs[i].density);+ CHECK(a.inputs[i].ageMoment == b.inputs[i].ageMoment);+ }+ if (lookup.BuildCount() == builds) {+ CHECK(support.lookups == before);+ CHECK(support.allows == allowBefore);+ }+ CHECK(lookup.SampleCount() <= RasterLookup::MaximumPixels &&lookup.TileCount() <= lookup.SampleCount());+ CHECK(lookup.MemoryBytes() <= sizeof(RasterLookup) + 13 * RasterLookup::MaximumPixels);+ };+ compare(10, 0);+ CHECK(lookup.BuildCount() == 1);+ for (unsigned frame = 1; frame <= 12; ++frame) {+ for (size_t i = 0; i < states.size(); ++i)+ states[i] = {frame % 3 ? double(i + frame) * .13 : 0, double(i + 2 * frame) * .7};+ compare(10, frame * .137);+ CHECK(lookup.BuildCount() == 1);+ }+ mapping.originX += .125;+ compare(10, 2);+ CHECK(lookup.BuildCount() == 2);+ mapping.originY -= .25;+ compare(10, 2);+ CHECK(lookup.BuildCount() == 3);+ mapping.widthWorld += .75;+ compare(10, 2);+ CHECK(lookup.BuildCount() == 4);+ mapping.heightWorld += .5;+ compare(10, 2);+ CHECK(lookup.BuildCount() == 5);+ mapping.widthPixels = 43;+ compare(10, 2);+ CHECK(lookup.BuildCount() == 6);+ mapping.heightPixels = 37;+ compare(10, 2);+ CHECK(lookup.BuildCount() == 7);+ compare(20, 2);+ CHECK(lookup.BuildCount() == 8);+ support.mask = 0;+ ++revision;+ compare(20, 2);+ CHECK(lookup.BuildCount() == 9);+ cells.push_back({1, 0, 20, 5});+ CHECK(topology.Build({.5, -.5, 5}, cells) == BuildResult::Ready);+ states.assign(topology.Cells().size(), {1.3, .7});+ support.mask = 15;+ ++revision;+ compare(20, 3);+ CHECK(lookup.BuildCount() == 10);+ ShoreCountingSupport other;+ auto material = [](const State &s, double, double, double) {+ return s.density;+ };+ std::vector<uint32_t> pixels(size_t(mapping.widthPixels) * mapping.heightPixels, 0xaabbccddu);+ CHECK(RasterizeAlphaCached(topology, states, mapping, 20, 3, material, pixels, other, lookup, revision));+ CHECK(lookup.BuildCount() == 11); // support object identity is part of the key+ const auto saved = pixels;+ const auto builds = lookup.BuildCount();+ Mapping invalid = mapping;+ invalid.widthPixels = 513;+ CHECK(!RasterizeAlphaCached(topology, states, invalid, 20, 3, material, pixels, other, lookup, revision));+ CHECK(!RasterizeAlphaCached(topology, states, mapping, 20, NAN, material, pixels, other, lookup, revision));+ CHECK(!RasterizeAlphaCached(topology, states, mapping, 20, 3, material, pixels, other, lookup, 0));+ CHECK(pixels == saved && lookup.BuildCount() == builds);+ lookup.Clear();+ CHECK(lookup.BuildCount() == 0 && lookup.SampleCount() == 0 && lookup.TileCount() == 0);+}+TEST(water_shore_raster_prepared_spatial_breakup_preserves_live_coverage_bytes) {+ using namespace WaterShoreHistory;+ const auto cells = shoreFourCorners();+ Topology topology;+ CHECK(topology.Build({}, cells) == BuildResult::Ready);+ WaterShoreSupport::Domain support;+ auto flat = [](double, double) {+ return 0.f;+ };+ CHECK(support.Build({}, cells, 3, 3, {shoreRect(0, 0, 2, 5), shoreRect(3, 0, 5, 5)}, flat));+ RasterLookup lookup;+ uint64_t prepared = 0;+ size_t preparations = 0;+ std::vector<float> breakup;+ for (unsigned camera = 0; camera < 4; ++camera) {+ Mapping mapping = {-1 + camera * .13, -.75 + camera * .21, 7.3, 6.7, 61 + camera, 57 - camera};+ for (unsigned frame = 0; frame < 16; ++frame) {+ std::vector<State> states;+ for (unsigned i = 0; i < 4; ++i)+ states.push_back({frame % 4 ? (.05 + double(frame + i) * .17) : 0, double(frame + 2 * i) * .31});+ const double time = frame * .137 + camera;+ std::vector<uint32_t> seed(size_t(mapping.widthPixels) * mapping.heightPixels, 0xa3abcdefu),+ expected = seed, actual = seed;+ auto coverage = WaterShoreSource::Coverage;+ CHECK(RasterizeAlpha(topology, states, mapping, 10, time, coverage, expected, support));+ CHECK(lookup.Prepare(topology, mapping, 10, 1, support));+ if (prepared != lookup.BuildCount()) {+ breakup.assign(seed.size(), 0);+ lookup.ForEachSample([&](size_t n, double x, double y) {+ const double value = WaterShoreSource::SpatialBreakup(x, y);+ breakup[n] = float(value);+ CHECK(double(breakup[n]) == value);+ ++preparations;+ });+ prepared = lookup.BuildCount();+ }+ const auto before = preparations;+ auto material = [&](const State &s, double, double, double, size_t n) {+ return WaterShoreSource::CoverageFromBreakup(s, breakup[n]);+ };+ CHECK(lookup.Rasterize(states, time, material, actual));+ CHECK(actual == expected);+ CHECK(preparations == before && lookup.BuildCount() == camera + 1);+ }+ }+ CHECK(preparations > 1000);+}+++#include "WaterWaveCageCopyTest.h"+TEST(water_wave_cage_copy_elision_matches_frozen_noops_and_crossing_chains)+{+ WaterWaveCageCopyTest::NoopsAndChains();+}+TEST(water_wave_cage_copy_elision_matches_frozen_crossings_and_vertex_budgets)+{+ WaterWaveCageCopyTest::CrossingsAndBudgets();+}+TEST(water_wave_cage_copy_elision_preserves_frozen_invalid_input_rollback)+{+ WaterWaveCageCopyTest::InvalidRollback();+}++++#include "WaterTerrainProofCacheTest.h"+TEST(water_terrain_proof_cache_matches_frozen_threshold_pond_and_boundary_outputs)+{+ WaterTerrainProofCacheTest::ExtremesAndThresholds();+}+TEST(water_terrain_proof_cache_matches_frozen_moving_projected_cull_clip_compact_pipeline)+{+ WaterTerrainProofCacheTest::MovingProjectedPipeline();+}+TEST(water_terrain_proof_cache_preserves_sample_budgets_and_65536_vertex_indices)+{+ WaterTerrainProofCacheTest::BudgetAndIndexLimits();+}+TEST(water_terrain_compaction_matches_frozen_metadata_order_and_invalid_rollback)+{+ WaterTerrainProofCacheTest::InvalidAndCompaction();+}+TEST(water_terrain_proof_cache_clear_cutoff_reuse_and_capacity_are_exact)+{+ WaterTerrainProofCacheTest::LifetimeAndCapacity();+}+TEST(water_terrain_proof_cache_rectangle_queries_match_encoded_predicate_at_thresholds)+{+ WaterTerrainProofCacheTest::RectangleQueries();+}++++#include "WaterShoreSourcePerfTest.h"+#include "WaterProjectedSampleCacheTest.h"++#include "Platform/WaterRenderCaches.h"+TEST(water_render_cache_preferences_preserve_loading_data_and_invalidate_every_setting)+{+ using namespace WaterProjectedMesh;+ WaterRenderCaches::Cache<float> cache;+ WaterRenderCaches::Settings settings;+ const Mesh input=preparedCacheInput();+ const Point corners[4]={{-95,-170},{81,-110},{120,92},{-64,170}};+ const auto projection=testWaterProjection();+ const auto knots=projectedCacheKnots(corners);+ const auto key=SampleKey(1,2,3);+ std::vector<uint8_t> heights(81,30);+ // Loading may fill static caches before the first view is known.+ uint8_t field[9]={0,40,100,70,150,220,90,190,255};+ auto populate=[&]() {+ Mesh mesh;+ CHECK(cache.topology.Build(corners,projection,{32,24},mesh,60000,knots));+ mesh=input;cache.prepared.Process(mesh,5,false,false,[](Mesh &) {});+ cache.staticSamples.BeginRender();+ cache.staticSamples.Get(1,2,3,[&]() { return staticCacheReference(field,1,2,3); });+ CHECK(cache.terrain.Prewarm(heights.data(),9,9,1,10));+ cache.samples.Store(key,7);+ };+ populate();+ cache.BeginRender(settings);+ auto retained=[&]() {+ CHECK(cache.topology.EntryCount()==1 && cache.prepared.EntryCount()==1);+ CHECK(cache.staticSamples.Size()==1 && cache.terrain.EntryCount()==1);+ };+ retained();+ CHECK(!cache.samples.Find(key)); // animated payloads never survive a render+ for (int change=0;change<8;++change) {+ populate();cache.BeginRender(settings);retained();+ auto next=settings;+ switch (change) {+ case 0: ++next.reflectionMode;break;+ case 1: ++next.refraction;break;+ case 2: --next.reflectionDetail;break;+ case 3: next.requestedFftResolution=128;break;+ case 4: next.activeFftResolution=128;break;+ case 5: next.sceneReflections=false;break;+ case 6: next.width=1920;break;+ case 7: next.height=1080;break;+ }+ cache.BeginRender(next);+ CHECK(cache.topology.EntryCount()==0 && cache.prepared.EntryCount()==0);+ CHECK(cache.staticSamples.Size()==0 && cache.terrain.EntryCount()==0 && !cache.samples.Find(key));+ cache.BeginRender(settings);+ }+ populate();cache.Clear();+ CHECK(cache.topology.EntryCount()==0 && cache.prepared.EntryCount()==0);+ CHECK(cache.staticSamples.Size()==0 && cache.terrain.EntryCount()==0 && !cache.samples.Find(key));+}++TEST(water_static_terrain_snapshot_preserves_original_render_map_interpolation)+{+ // Frozen WaterTerrainDepth argument order and WorldHeightMapData bounds.+ const int width=7,height=5;+ std::vector<uint8_t> heights(width*height);+ for (size_t i=0;i<heights.size();++i) heights[i]=uint8_t(i*37);+ auto original=[&](float x,float y,float level,int border,float spacing,float scale) {+ const float mx=clamp(x/spacing+border,0.0f,float(width)-1.001f);+ const float my=clamp(y/spacing+border,0.0f,float(height)-1.001f);+ const int ix=int(mx),iy=int(my);const float fx=mx-ix,fy=my-iy;+ auto getHeight=[&](int column,int row) {+ const int index=row*width+column;+ return index>=0 && index<int(heights.size())?heights[index]:uint8_t(0);+ };+ const float a=getHeight(ix,iy)*(1-fx)+getHeight(ix+1,iy)*fx;+ const float b=getHeight(ix,iy+1)*(1-fx)+getHeight(ix+1,iy+1)*fx;+ return level-(a*(1-fy)+b*fy)*scale;+ };+ for (int border:{0,1}) for (float spacing:{1.f,10.f}) for (float scale:{.625f,1.f})+ for (float level:{-0.f,0.f,7.25f,100.f})+ for (float x:{-100.f,0.f,.123f,3.f,49.99f,60.f,10000.f})+ for (float y:{-100.f,0.f,.456f,2.f,29.99f,40.f,10000.f}) {+ const float expected=original(x,y,level,border,spacing,scale);+ const float actual=WaterStaticSampleCache::TerrainDepth(heights.data(),width,height,border,spacing,scale,x,y,level);+ CHECK(std::memcmp(&actual,&expected,sizeof(actual))==0);+ }+ CHECK(WaterStaticSampleCache::TerrainDepth(nullptr,0,0,0,10,1,0,0,7)==0);+}