Skip to content

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

refactor(water): remove environment knobs and render tracing

Richard Louie Orilla12634423b9bc
diff --git a/GeneralsMD/Code/BuildFingerprint.manifest b/GeneralsMD/Code/BuildFingerprint.manifest
index 619688a9a..6e1b1a7b7 100644
--- a/GeneralsMD/Code/BuildFingerprint.manifest
+++ b/GeneralsMD/Code/BuildFingerprint.manifest
@@ -1981,13 +1981,6 @@ Libraries/Include/Platform/WaterBedMaterial.h
Libraries/Include/Platform/WaterBowLift.h
Libraries/Include/Platform/WaterBowRefinement.h
Libraries/Include/Platform/WaterBowShoulder.h
-Libraries/Include/Platform/WaterCoastalCrest.h
-Libraries/Include/Platform/WaterCoastalDomain.h
-Libraries/Include/Platform/WaterCoastalIncident.h
-Libraries/Include/Platform/WaterCoastalPresentation.h
-Libraries/Include/Platform/WaterCoastalRender.h
-Libraries/Include/Platform/WaterCoastalSurf.h
-Libraries/Include/Platform/WaterCoastalView.h
Libraries/Include/Platform/WaterFftFiltering.h
Libraries/Include/Platform/WaterFftGeometry.h
Libraries/Include/Platform/WaterFftSampling.h
@@ -3026,10 +3019,6 @@ RTS.dsp
RTS.dsw
Stubs/NullAudioManager.h
Tests/WaterBowShoulderTest.h
-Tests/WaterCoastalCapacityTest.h
-Tests/WaterCoastalDomainTest.h
-Tests/WaterCoastalFootprintTest.h
-Tests/WaterCoastalViewTest.h
Tests/WaterHullContactFoamTest.h
Tests/WaterTerrainCullingTest.h
Tests/WaterWaveCageTest.h
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Water.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/Water.cpp
index 73a52877a..83593ff4c 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/Water.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/Water.cpp
@@ -36,7 +36,6 @@
#include "Common/file.h"
#include "Platform/ModernWaterConfig.h"
-#include <cstdio>
// GLOBALS ////////////////////////////////////////////////////////////////////////////////////////
WaterSetting WaterSettings[ TIME_OF_DAY_COUNT ];
@@ -66,13 +65,11 @@ void loadModernWaterSettings()
const char *path = "Data\\INI\\ModernWater.ini";
File *file = TheFileSystem->openFile(path, File::READ | File::BINARY);
if (!file) {
- fprintf(stderr, "ModernWater: %s is absent; using built-in material rules\n", path);
return;
}
const Int size = file->size();
if (size < 0 || size > 1024 * 1024) {
file->close();
- fprintf(stderr, "ModernWater: invalid configuration size; using built-in material rules\n");
return;
}
std::string contents(size, '\0');
@@ -80,11 +77,8 @@ void loadModernWaterSettings()
file->close();
std::string error;
if (!complete || !ModernWaterConfig::Parse(contents, settings.rules, error)) {
- fprintf(stderr, "ModernWater: %s: %s; using built-in material rules\n", path,
- complete ? error.c_str() : "incomplete read");
return;
}
- fprintf(stderr, "ModernWater: loaded %u material rules from %s\n", unsigned(settings.rules.size()), path);
}
void getModernWaterMaterial(Real color[4], Real parameters[4])
diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DWater.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DWater.h
index c458be2e2..1d81e2a93 100644
--- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DWater.h
+++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DWater.h
@@ -57,7 +57,6 @@
#include "Platform/WaterVesselMotion.h"
#include "Platform/WaterFoamHistory.h"
#include "Platform/WaterShoreSource.h"
-#include "Platform/WaterCoastalRender.h"
class Drawable;
class MeshModelClass;
@@ -227,17 +226,9 @@ protected:
WaterBowRefinement::Admissions m_modernBowAdmissions;
uintptr_t m_modernBowPatchOwner=0;
unsigned m_modernBowPatchPart=0;
- size_t m_modernBowVertices=0,m_modernBowTriangles=0,m_modernBowRegions=0,m_modernBowDenied=0,m_modernBowRejected=0;
- size_t m_modernProjectedVertices=0,m_modernProjectedTriangles=0,m_modernProjectedFallbacks=0,m_modernRetainedVertices=0;
- size_t m_modernProjectedBudget=60000,m_modernProjectedEvaluations=0;
+ size_t m_modernBowVertices=0,m_modernBowTriangles=0;
+ size_t m_modernProjectedBudget=60000;
Bool m_modernProjectedCacheEnabled=TRUE;
- Bool m_modernProfileEnabled=FALSE;
- struct ModernWaterProfile {
- double render=0,setup=0,hulls=0,obstacles=0,mesh=0,fill=0,submit=0;
- double fieldSample=0,dampingSample=0,waveSample=0,cacheSample=0;
- size_t frames=0,vertices=0,triangles=0,patches=0,patchObstacles=0;
- size_t attempts=0,hits=0,misses=0,samples=0,wavePoints=0;
- } m_modernProfile;
struct ModernProjectedSample { Real height,damping,obstacle,hullFreeObstacle,offshore,fftDamping,exposure; };
std::unordered_map<WaterProjectedMesh::WorldKey,ModernProjectedSample,WaterProjectedMesh::WorldHash> m_modernProjectedSamples;
Vector3 m_modernCamera;
@@ -287,7 +278,6 @@ protected:
WaterHullPoseCache::Cache visualPoses;
std::vector<MeshModelClass*> visualModels;
WaterHullVisual::Packet visual={};
- UnsignedInt visualTraceFrame=~0u;
WaterHullModel::Polygon polygon,contact;
Real forwardSign=1.0f;
WaterVesselMotion::State motion;
@@ -297,20 +287,11 @@ protected:
std::vector<WaterHullVisual::Packet> m_modernVisualHulls;
std::vector<UnsignedInt> m_modernHullObjectIDs;
UnsignedInt m_modernHullSerial=0;
- UnsignedInt m_modernHullTraceLines=0;
- UnsignedInt m_modernVisualHullTraceLines=0;
- UnsignedInt m_modernVesselStateTraceFrame=~0u, m_modernVesselStateTraceLines=0;
WaterFoamHistory::History m_modernFoamHistory;
WaterShoreHistory::History m_modernShoreHistory;
WaterShoreSource::Batch m_modernShoreSource;
uint64_t m_modernShoreRevision=1, m_modernShoreAttempted=0;
Bool m_modernShoreReady=FALSE;
- WaterCoastalDomain::Domain m_modernCoastalDomain;
- uint64_t m_modernCoastalRevision=0;
- Bool m_modernCoastalReady=FALSE,m_modernCoastalViewReady=FALSE;
- WaterShoreHistory::Mapping m_modernCoastalMapping={};
- Real m_modernCoastalViewLevel=0;
- std::vector<WaterCoastalSurf::Lookup> m_modernCoastalLookup;
unsigned m_modernFoamDrawFrame=~0u;
std::vector<UnsignedInt> m_modernFoamDrawObjectIDs;
struct ModernFoamTexture {
@@ -396,7 +377,6 @@ protected:
void clearModernWaterHulls(Bool admissions=TRUE);
void clearModernWaterFoam(Bool history=TRUE);
void bindModernWaterFoam(Real level,Bool river);
- void bindModernWaterCoastal(Real level,Bool river);
void invalidateModernWaterShore(void);
void updateModernWaterShore(void);
Real modernHullDamping(Real x,Real y,Real level) const;
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/PosixDevice9.h b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/PosixDevice9.h
index 9d9f4584b..a540a2589 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/PosixDevice9.h
+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/PosixDevice9.h
@@ -47,7 +47,6 @@
#include "Platform/RenderTypes.h"
#include "Platform/D3D9Posix.h"
#include "Platform/WaterShoreOverlay.h"
-#include "Platform/WaterCoastalRender.h"
#include "Platform/WaterHullVisualLayout.h"
#include <memory>
@@ -173,9 +172,6 @@ public:
PosixDevice9(PosixDirect3D9 *adapter, RenderWindow window, const D3DPRESENT_PARAMETERS &parameters);
// Render-only explicit metadata: never infers .wak ownership from texture names.
- bool Coastal_Bind(uint64_t revision,const WaterCoastalDomain::Domain &domain,
- const WaterShoreHistory::Mapping &mapping,double level,const std::vector<WaterCoastalSurf::Lookup> &lookup);
- void Coastal_End() { CoastalActive=false; }
void Shore_Begin(bool enabled);
void Shore_End();
void Shore_Patch(const WaterShoreOverlay::Quad *patch);
@@ -346,10 +342,6 @@ public:
RenderResult SetPixelShaderConstantF(unsigned int start, const float *data, unsigned int count) override;
protected:
- bool CoastalActive=false;
- uint64_t CoastalRevision=0,CoastalViewRevision=0;
- WaterShoreHistory::Mapping CoastalMapping={};
- double CoastalLevel=0;
struct ShoreRegion {
WaterShoreOverlay::Quad patch;
WaterShoreOverlay::View view;
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/PosixDevice9Draw.cpp b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/PosixDevice9Draw.cpp
index 0c2be34b3..d7cfc3689 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/PosixDevice9Draw.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/PosixDevice9Draw.cpp
@@ -46,40 +46,13 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
-#if defined(__linux__)
-#include <execinfo.h> // bounded opt-in CPU attribution; no GPU queries/readbacks
-#endif
-
-bool PosixDevice9::Coastal_Bind(uint64_t revision,const WaterCoastalDomain::Domain &domain,
- const WaterShoreHistory::Mapping &mapping,double level,const std::vector<WaterCoastalSurf::Lookup> &lookup)
-{
- Coastal_End();
- const char *option=getenv("ZH_WATER_SURF_GPU");
- if(!Gpu || !option || strcmp(option,"1")!=0 || !revision || domain.Nodes().empty())return false;
- if(CoastalRevision!=revision || !Gpu->Coastal_Surf_Domain(0,revision)) {
- if(!Gpu->Install_Coastal_Surf(revision,domain.Nodes(),domain.Grid().spacing))return false;
- CoastalRevision=revision;CoastalViewRevision=0;
- }
- if(CoastalViewRevision!=revision || CoastalLevel!=level || !WaterCoastalView::SameMapping(mapping,CoastalMapping)) {
- if(!Gpu->Set_Coastal_Surf_View(revision,mapping,level,lookup))return false;
- CoastalViewRevision=revision;CoastalMapping=mapping;CoastalLevel=level;
- }
- CoastalActive=true;return true;
-}
-bool PosixWaterCoastalBind(IDirect3DDevice9 *d,uint64_t r,const WaterCoastalDomain::Domain &domain,
- const WaterShoreHistory::Mapping &mapping,double level,const std::vector<WaterCoastalSurf::Lookup> &lookup)
-{return d && static_cast<PosixDevice9*>(d)->Coastal_Bind(r,domain,mapping,level,lookup);}
-void PosixWaterCoastalEnd(IDirect3DDevice9 *d){if(d)static_cast<PosixDevice9*>(d)->Coastal_End();}
-
void PosixDevice9::Shore_Begin(bool enabled)
{
Shore_End();
- const char *option=getenv("ZH_WATER_SHORE_FOAM");
- ShoreActive=enabled && (!option || strcmp(option,"0")!=0);
+ ShoreActive=enabled;
}
void PosixDevice9::Shore_End()
{
- Coastal_End();
ShoreActive=ShoreHasPatch=ShoreHasTrack=false;ShoreRegions.clear();
}
void PosixDevice9::Shore_Patch(const WaterShoreOverlay::Quad *patch)
@@ -981,8 +954,7 @@ RenderResult PosixDevice9::Gpu_Draw(const DrawCall &call)
// pairing. Only this path may bind native FFT textures to the vertex stage.
const bool fft_requested = pixel_engine == ENGINE_SHADER_WATER_TRAPEZOID
&& vertex_engine == ENGINE_SHADER_NONE && !vertex.LightingEnabled
- && PixelShaderConstants[6][2] > 0.5f && PixelShaderConstants[6][3] > 0.5f
- && WaterFftSampling::Enabled();
+ && PixelShaderConstants[6][2] > 0.5f && PixelShaderConstants[6][3] > 0.5f;
bool fft_water = fft_requested && Gpu->Prepare_Ocean(PixelShaderConstants[1][0]*WaterFftSampling::TimeScale);
const SdlProgram *fft_vertex = fft_water ? &Programs->Water_Vertex_Program(vertex) : NULL;
if (fft_vertex && fft_vertex->Shader == NULL) fft_water = false;
@@ -1097,14 +1069,6 @@ RenderResult PosixDevice9::Gpu_Draw(const DrawCall &call)
SDL_GPUTexture *water_background = water_draw ? Gpu->Water_Background(target) : NULL;
SDL_GPUTexture *water_depth = water_draw ? Gpu->Water_Depth(target) : NULL;
bool water_history = water_draw && Water_Foam_History_Available();
- bool coastal_view=water_draw && fft_water && CoastalActive && water_depth
- && PixelShaderConstants[1][1]<.5f && PixelShaderConstants[6][3]>.5f
- && Gpu->Prepare_Coastal_Surf_From_Ocean(CoastalRevision,PixelShaderConstants[1][0])
- && Gpu->Prepare_Coastal_Surf_View(CoastalRevision);
- SDL_GPUTexture *coastal_texture=coastal_view?Gpu->Coastal_Surf_View(CoastalRevision,CoastalLevel):NULL;
- SDL_GPUSampler *coastal_sampler=coastal_view?Gpu->Coastal_Surf_View_Sampler(CoastalRevision,CoastalLevel):NULL;
- coastal_view=coastal_view && coastal_texture && coastal_sampler
- && coastal_texture!=target.Colour && coastal_texture!=target.Depth;
draw.VertexSamplerCount = vertex_program.SamplerSlots;
for (unsigned int slot = 0; slot < draw.VertexSamplerCount && slot < 3; ++slot) {
draw.VertexTextures[slot] = Gpu->Ocean_Map(slot * 2);
@@ -1120,12 +1084,6 @@ RenderResult PosixDevice9::Gpu_Draw(const DrawCall &call)
for (unsigned int slot = 0; slot < pixel_program->SamplerSlots; ++slot) {
const int texture_stage = pixel_program->SlotTexture[slot];
const int sampler_stage = pixel_program->SlotSampler[slot];
- if (water_draw && texture_stage==15) {
- draw.Textures[slot]=coastal_view?coastal_texture:Mirrors->White();
- draw.Samplers[slot]=coastal_view?coastal_sampler:Samplers->Sampler(SamplerStates[0]);
- if(!draw.Textures[slot] || !draw.Samplers[slot])return D3D_OK;
- continue;
- }
if (water_draw && texture_stage >= 8 && texture_stage < 14) {
draw.Textures[slot] = fft_water ? Gpu->Ocean_Map(texture_stage - 8) : Mirrors->White();
draw.Samplers[slot] = fft_water ? Gpu->Ocean_Sampler() : Samplers->Sampler(SamplerStates[0]);
@@ -1159,50 +1117,6 @@ RenderResult PosixDevice9::Gpu_Draw(const DrawCall &call)
shore_overlay=false;draw.Textures[slot]=Mirrors->White();
}
if (draw.Textures[slot] != NULL && (draw.Textures[slot] == target.Colour || draw.Textures[slot] == target.Depth)) {
- // Metadata only, at the rejected draw; the refusal remains in force.
- // Four events/process maximum. Never use this evidence run for performance comparisons.
- const char *aliasTrace=getenv("ZH_GPU_TARGET_ALIAS_TRACE");
- static unsigned aliasTraceCount=0;
- if(aliasTrace && strcmp(aliasTrace,"1")==0 && aliasTraceCount<4) {
- ++aliasTraceCount;
- D3DSURFACE_DESC td={},rt={},ds={};
- if(texture && texture->GetType()==D3DRTYPE_TEXTURE)
- static_cast<IDirect3DTexture9*>(texture)->GetLevelDesc(0,&td);
- if(RenderTargets[0]) RenderTargets[0]->GetDesc(&rt);
- if(DepthStencil) DepthStencil->GetDesc(&ds);
- IDirect3DTexture9 *targetContainer=NULL;
- if(RenderTargets[0]) RenderTargets[0]->GetContainer(IID_IDirect3DTexture9,(void**)&targetContainer);
- fprintf(stderr,"target-alias: event=%u present=%u recorded=%u batch=%llu round=%d role=%s slot=%u texture_stage=%d sampler_stage=%d fvf=0x%x primitive_type=%u primitives=%u indexed=%d user_vertices=%d stride=%u\n",
- aliasTraceCount,PresentCount,DrawsRecorded,(unsigned long long)Gpu->Batch(),round,
- water_draw?"water":(shore_overlay?"shore-overlay":"ordinary"),slot,texture_stage,sampler_stage,
- (unsigned)FVF,(unsigned)call.Type,call.PrimitiveCount,(int)call.Indexed,(int)user,stride);
- fprintf(stderr,"target-alias-program: vs=%.*s ps=%.*s vertex_engine=%d pixel_engine=%d fft=%d shore=%d\n",
- 256,vertex_program.Key.c_str(),256,pixel_program->Key.c_str(),vertex_engine,pixel_engine,(int)fft_water,(int)shore_overlay);
- fprintf(stderr,"target-alias-gpu: sample=%p colour=%p depth=%p aliases_colour=%d aliases_depth=%d target_size=%ux%u background=%p water_depth=%p shore_depth=%p\n",
- (void*)draw.Textures[slot],(void*)target.Colour,(void*)target.Depth,
- (int)(draw.Textures[slot]==target.Colour),(int)(draw.Textures[slot]==target.Depth),target.Width,target.Height,
- (void*)water_background,(void*)water_depth,(void*)shore_depth);
- fprintf(stderr,"target-alias-d3d: texture=%p target=%p target_container=%p container_is_texture=%d backbuffer=%d depth_surface=%p texture_desc=%ux%u/%u/0x%x target_desc=%ux%u/%u/0x%x depth_desc=%ux%u/%u/0x%x\n",
- (void*)texture,(void*)RenderTargets[0],(void*)targetContainer,(int)(targetContainer && targetContainer==texture),
- (int)(RenderTargets[0]==BackBuffer),(void*)DepthStencil,
- td.Width,td.Height,(unsigned)td.Format,(unsigned)td.Usage,rt.Width,rt.Height,(unsigned)rt.Format,(unsigned)rt.Usage,
- ds.Width,ds.Height,(unsigned)ds.Format,(unsigned)ds.Usage);
- if(targetContainer) targetContainer->Release();
- const RenderUInt32 noStage[TEXTURE_STAGE_STATE_COUNT]={};
- const RenderUInt32 *ts=texture_stage<TEXTURE_STAGE_COUNT ? TextureStageStates[texture_stage] : noStage;
- fprintf(stderr,"target-alias-state: colour_op=%u args=%u,%u,%u alpha_op=%u args=%u,%u,%u z=%u/%u blend=%u/%u/%u colour_write=0x%x shadow=%d soft_particle=%d draw_effect=%d smoke_glow=%d\n",
- (unsigned)ts[D3DTSS_COLOROP],(unsigned)ts[D3DTSS_COLORARG0],(unsigned)ts[D3DTSS_COLORARG1],(unsigned)ts[D3DTSS_COLORARG2],
- (unsigned)ts[D3DTSS_ALPHAOP],(unsigned)ts[D3DTSS_ALPHAARG0],(unsigned)ts[D3DTSS_ALPHAARG1],(unsigned)ts[D3DTSS_ALPHAARG2],
- (unsigned)states[D3DRS_ZENABLE],(unsigned)states[D3DRS_ZWRITEENABLE],(unsigned)states[D3DRS_ALPHABLENDENABLE],
- (unsigned)states[D3DRS_SRCBLEND],(unsigned)states[D3DRS_DESTBLEND],(unsigned)states[D3DRS_COLORWRITEENABLE],
- (int)combiner.ShadowReceiving,(int)combiner.SoftParticle,(int)combiner.DrawEffect,(int)combiner.SmokeGlow);
-#if defined(__linux__)
- void *stack[16];const int count=backtrace(stack,16);
- fprintf(stderr,"target-alias-stack: begin event=%u frames=%d\n",aliasTraceCount,count);fflush(stderr);
- backtrace_symbols_fd(stack,count,2);
- fprintf(stderr,"target-alias-stack: end event=%u\n",aliasTraceCount);
-#endif
- }
// Undefined in D3D9, and an error on SDL3 GPU: the pass would read what it writes.
Refuse_Draw("sampling the render target it draws into");
return D3D_OK;
@@ -1432,26 +1346,7 @@ RenderResult PosixDevice9::Gpu_Draw(const DrawCall &call)
water.SceneParameters[2] = 1.0f / (float)target.Height;
water.SceneParameters[3] = water_depth ? 1.0f : 0.0f;
water.FftParameters[0] = fft_water ? 1.0f : 0.0f;
- water.FftParameters[1] = fft_water && WaterVesselWaves::Enabled() ? 1.0f : 0.0f;
if (!water_history) water.FoamHistoryParameters[0] = 0.0f;
- if(coastal_view) {
- water.CoastalArea[0]=float(CoastalMapping.originX);water.CoastalArea[1]=float(CoastalMapping.originY);
- water.CoastalArea[2]=float(CoastalMapping.widthWorld);water.CoastalArea[3]=float(CoastalMapping.heightWorld);
- water.CoastalParams[0]=1;water.CoastalParams[1]=float(CoastalLevel);
- water.CoastalParams[2]=float(Gpu->Coastal_Surf_View_Time(CoastalRevision,CoastalLevel));
- water.CoastalParams[3]=PixelShaderConstants[1][0];
- if(getenv("ZH_WATER_SURF_TRACE")) {
- static double last=-1;
- if(floor(last)!=floor(water.CoastalParams[3])) {
- last=water.CoastalParams[3];
- fprintf(stderr,"water-surf-draw: time=%.3f sampled=%.3f revision=%llu nodes=%u history=%llu views=%llu sets=%llu level=%.3f area=(%.1f,%.1f,%.1f,%.1f)\n",
- last,water.CoastalParams[2],(unsigned long long)CoastalRevision,Gpu->Coastal_Surf_Nodes(CoastalRevision),
- (unsigned long long)Gpu->Coastal_Surf_Updates(),(unsigned long long)Gpu->Coastal_Surf_View_Updates(),
- (unsigned long long)Gpu->Coastal_Surf_View_Sets(),CoastalLevel,CoastalMapping.originX,CoastalMapping.originY,
- CoastalMapping.widthWorld,CoastalMapping.heightWorld);
- }
- }
- }
if(pixel_program->UniformBuffers==4) {
SdlWaterVisualPixelConstants visual;
Build_Water_Visual_Constants(water,visual);
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlConstants.h b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlConstants.h
index 52f2ae089..b415ef3e8 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlConstants.h
+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlConstants.h
@@ -97,15 +97,13 @@ struct SdlWaterPixelConstants
float FoamHistoryParameters[4]; // available, water level, cell world size, simulation time of atlas
float ContactHullData[80][4]; // optional foam-only contours; count < 3 falls back to the matching mean hull
float FoamFillLights[4][4]; // two direction/colour pairs; first direction.w enables the main light for foam
- float CoastalArea[4]; // lower world origin XY and extent XY of the independent coastal view
- float CoastalParams[4]; // valid, exact level, successful history sample time, current water time
#define MODERN_WATER_CPP_UNIFORM(name) float name[4];
MODERN_WATER_MATERIAL_UNIFORMS(MODERN_WATER_CPP_UNIFORM)
#undef MODERN_WATER_CPP_UNIFORM
};
static_assert(sizeof(SdlWaterPixelConstants) == WaterHullVisualLayout::VertexCommonRegisters * 16, "water uniform packing");
-static_assert(offsetof(SdlWaterPixelConstants,MaterialColor)==186*16
- && offsetof(SdlWaterPixelConstants,MaterialParameters)==187*16,"water material tail packing");
+static_assert(offsetof(SdlWaterPixelConstants,MaterialColor)==184*16
+ && offsetof(SdlWaterPixelConstants,MaterialParameters)==185*16,"water material tail packing");
// Fragment-only extension after the shared water vertex/pixel prefix.
struct SdlWaterVisualPixelConstants
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrame.cpp b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrame.cpp
index 1b6efccb0..4e6bc98ee 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrame.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrame.cpp
@@ -21,10 +21,6 @@
#include "SdlGpuFrame.h"
#include "sdl3shadercompile.h"
#include "Platform/WaterFftSpectrum.h"
-#include "Platform/WaterCoastalSurf.h"
-#include "Platform/WaterCoastalIncident.h"
-#include "Platform/WaterCoastalView.h"
-#include <memory>
#include <SDL3/SDL.h>
@@ -232,7 +228,6 @@ SdlGpuFrame::~SdlGpuFrame()
SDL_ReleaseGPUFence(GpuDevice, FlushFences[i]);
}
FlushFences.clear();
- Release_Coastal_Surf();
Release_Ocean();
Release_Targets();
Commands.clear();
@@ -491,543 +486,6 @@ SDL_GPUSampler *SdlGpuFrame::Ocean_Sampler() const
return OceanReady && Ocean?Ocean->Linear:NULL;
}
-// Compact, camera-independent coastal history. Every native texture has fixed format
-// and extent owned here; callers cannot substitute an unverified sampler attachment.
-struct SdlGpuFrame::CoastalSurfResources
-{
- SDL_GPUDevice *Device;
- SDL_GPUTexture *Domain[5]={}, *State[3]={}, *Input=NULL;
- SDL_GPUShader *Vertex=NULL, *Pixels[2]={};
- SDL_GPUGraphicsPipeline *Pipelines[2]={},*IncidentPipeline=NULL;
- SDL_GPUShader *IncidentPixel=NULL;
- SDL_GPUSampler *Point=NULL;
- WaterCoastalSurf::Clock Clock;
- std::vector<float> Payload;
- uint64_t Revision=0;
- unsigned Count=0,Active=0;
- double Spacing=0;
- bool Ready=false;
-
- explicit CoastalSurfResources(SDL_GPUDevice *device):Device(device) {}
- ~CoastalSurfResources() {
- if(IncidentPipeline) SDL_ReleaseGPUGraphicsPipeline(Device,IncidentPipeline);
- if(IncidentPixel) SDL_ReleaseGPUShader(Device,IncidentPixel);
- for(auto *pipeline:Pipelines) if(pipeline) SDL_ReleaseGPUGraphicsPipeline(Device,pipeline);
- for(auto *pixel:Pixels) if(pixel) SDL_ReleaseGPUShader(Device,pixel);
- if(Vertex) SDL_ReleaseGPUShader(Device,Vertex);
- if(Point) SDL_ReleaseGPUSampler(Device,Point);
- for(auto *texture:Domain) if(texture) SDL_ReleaseGPUTexture(Device,texture);
- for(auto *texture:State) if(texture) SDL_ReleaseGPUTexture(Device,texture);
- if(Input) SDL_ReleaseGPUTexture(Device,Input);
- }
- bool CreateIncident() {
- if(IncidentPipeline) return true;
- std::string source,error;std::vector<unsigned char> spirv;
- if(!WaterCoastalIncident::PixelSource(source)
- || !SDL3_Compile_HLSL_To_SPIRV(source,false,spirv,error)) return false;
- unsigned samplers=0,uniforms=0;SDL3_Shader_Slots(spirv,false,samplers,uniforms);
- if(samplers!=WaterCoastalIncident::SamplerCount || uniforms!=1) return false;
- SDL_GPUShader *pixel=SDL3_Create_Shader(Device,spirv,false,error);if(!pixel) return false;
- SDL_GPUColorTargetDescription target={};target.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
- SDL_GPUGraphicsPipelineCreateInfo info={};info.vertex_shader=Vertex;info.fragment_shader=pixel;
- info.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;info.rasterizer_state.cull_mode=SDL_GPU_CULLMODE_NONE;
- info.rasterizer_state.fill_mode=SDL_GPU_FILLMODE_FILL;
- info.target_info.color_target_descriptions=&target;info.target_info.num_color_targets=1;
- SDL_GPUGraphicsPipeline *pipeline=SDL_CreateGPUGraphicsPipeline(Device,&info);
- if(!pipeline){SDL_ReleaseGPUShader(Device,pixel);return false;}
- IncidentPixel=pixel;IncidentPipeline=pipeline;return true;
- }
- bool IncidentPass(SDL_GPUCommandBuffer *commands,SDL_GPUTexture *const *ocean,
- SDL_GPUSampler *oceanSampler,float time) {
- if(!commands || !Input || !IncidentPipeline || !oceanSampler) return false;
- SDL_GPUTextureSamplerBinding bindings[WaterCoastalIncident::SamplerCount]={};
- for(unsigned i=0;i<4;++i) {
- if(!Domain[i] || !ocean[i] || Domain[i]==Input || ocean[i]==Input) return false;
- bindings[i].texture=Domain[i];bindings[i].sampler=Point;
- bindings[4+i].texture=ocean[i];bindings[4+i].sampler=oceanSampler;
- }
- SDL_GPUColorTargetInfo target={};target.texture=Input;
- target.load_op=SDL_GPU_LOADOP_DONT_CARE;target.store_op=SDL_GPU_STOREOP_STORE;
- SDL_GPURenderPass *pass=SDL_BeginGPURenderPass(commands,&target,1,NULL);if(!pass) return false;
- SDL_BindGPUGraphicsPipeline(pass,IncidentPipeline);
- SDL_BindGPUFragmentSamplers(pass,0,bindings,WaterCoastalIncident::SamplerCount);
- const SDL_GPUViewport viewport={0,0,float(WaterCoastalSurf::AtlasSide),float(WaterCoastalSurf::AtlasSide),0,1};
- SDL_SetGPUViewport(pass,&viewport);
- const WaterCoastalIncident::Parameters parameters{time,float(Count),0,0};
- SDL_PushGPUFragmentUniformData(commands,0,&parameters,sizeof(parameters));
- SDL_DrawGPUPrimitives(pass,3,1,0,0);SDL_EndGPURenderPass(pass);return true;
- }
- bool Pass(SDL_GPUCommandBuffer *commands,unsigned which,SDL_GPUTexture *destination,
- SDL_GPUTexture **sources,unsigned count,const float parameters[4]) {
- if(!commands || which>=2 || !destination || count!=(which?2u:5u)) return false;
- for(unsigned i=0;i<count;++i) if(!sources[i] || sources[i]==destination) return false;
- SDL_GPUColorTargetInfo target={};target.texture=destination;
- target.load_op=SDL_GPU_LOADOP_DONT_CARE;target.store_op=SDL_GPU_STOREOP_STORE;
- // No cycling: all older readers have already been submitted before this update.
- SDL_GPURenderPass *pass=SDL_BeginGPURenderPass(commands,&target,1,NULL);
- if(!pass) return false;
- SDL_BindGPUGraphicsPipeline(pass,Pipelines[which]);
- SDL_GPUTextureSamplerBinding bindings[5]={};
- for(unsigned i=0;i<count;++i){bindings[i].texture=sources[i];bindings[i].sampler=Point;}
- SDL_BindGPUFragmentSamplers(pass,0,bindings,count);
- const SDL_GPUViewport viewport={0,0,float(WaterCoastalSurf::AtlasSide),float(WaterCoastalSurf::AtlasSide),0,1};
- SDL_SetGPUViewport(pass,&viewport);
- SDL_PushGPUFragmentUniformData(commands,0,parameters,4*sizeof(float));
- SDL_DrawGPUPrimitives(pass,3,1,0,0);
- SDL_EndGPURenderPass(pass);return true;
- }
-};
-
-static std::string Coastal_Surf_Pixel_Source(bool diffusion)
-{
- std::string source;
- const unsigned count=diffusion?2:5;
- for(unsigned i=0;i<count;++i) source+="Texture2D<float4> T"+std::to_string(i)+" : register(t"+std::to_string(i)+", space2);\n";
- source+="cbuffer SurfParameters : register(b0, space3) { float4 Parameters; };\n";
- source+=WaterCoastalSurf::Source();
- if(diffusion) source+=R"SURF(
-float4 surfNeighbour(float id) {
- if(!isfinite(id)||id<1||id>Parameters.x||id!=floor(id)) return float4(-1,0,0,-1);
- uint at=(uint)id-1;return T0.Load(int3(at%256,at/256,0));
-}
-float4 main(float4 position:SV_Position):SV_Target0 {
- uint2 pixel=(uint2)position.xy;uint index=pixel.y*256+pixel.x;
- if(index>=(uint)Parameters.x) return float4(0,0,0,-1);
- float4 centre=T0.Load(int3(pixel,0)),ids=T1.Load(int3(pixel,0));
- uint mask=0;float4 a=0,b=0,c=0,d=0;
- if(ids.x!=0){mask|=1;a=surfNeighbour(ids.x);}
- if(ids.y!=0){mask|=2;b=surfNeighbour(ids.y);}
- if(ids.z!=0){mask|=4;c=surfNeighbour(ids.z);}
- if(ids.w!=0){mask|=8;d=surfNeighbour(ids.w);}
- return waterSurfDiffuse(centre,a,b,c,d,mask,Parameters.z,Parameters.y);
-}
-)SURF";
- else source+=R"SURF(
-float4 main(float4 position:SV_Position):SV_Target0 {
- uint2 pixel=(uint2)position.xy;uint index=pixel.y*256+pixel.x;
- if(index>=(uint)Parameters.x || Parameters.w>1.5) return float4(0,0,0,-1);
- WaterSurfContext context;
- context.coast=T2.Load(int3(pixel,0));context.surface=T3.Load(int3(pixel,0));
- context.admission=T4.Load(int3(pixel,0));
- return waterSurfAdvance(context,T1.Load(int3(pixel,0)),T0.Load(int3(pixel,0)),
- Parameters.y,Parameters.w<.5);
-}
-)SURF";
- return source;
-}
-
-void SdlGpuFrame::Release_Coastal_Surf()
-{
- Release_Coastal_Surf_View();
- if(!CoastalSurf) return;
- // Set_Target does not retain a resource. Do not leave an owned attachment as
- // the implicit destination of a later clear after revision replacement/clear.
- bool owned=CurrentTarget.Colour==CoastalSurf->Input;
- for(auto *texture:CoastalSurf->Domain) owned|=CurrentTarget.Colour==texture;
- for(auto *texture:CoastalSurf->State) owned|=CurrentTarget.Colour==texture;
- if(TargetSet && owned){TargetSet=false;CurrentTarget={};}
- delete CoastalSurf;CoastalSurf=NULL;
-}
-
-bool SdlGpuFrame::Clear_Coastal_Surf()
-{
- // A recorded draw may still reference any exposed state or domain texture.
- if((!Commands.empty() || !Uploads.empty()) && !Flush()) return false;
- Release_Coastal_Surf();return true;
-}
-
-bool SdlGpuFrame::Install_Coastal_Surf(uint64_t revision,
- const std::vector<WaterCoastalSurf::Node> &nodes,double spacing)
-{
- using namespace WaterCoastalSurf;
- if(!revision || !ValidGraph(nodes,spacing)) return false;
- if(nodes.empty()) return Clear_Coastal_Surf();
- const size_t plane=size_t(MaxNodes)*4;
- std::vector<float> payload(plane*5,0);
- for(size_t i=0;i<nodes.size();++i) {
- const Node &node=nodes[i];const Context &c=node.context;
- float *world=payload.data()+i*4,*coast=payload.data()+plane+i*4;
- float *surface=payload.data()+plane*2+i*4,*admission=payload.data()+plane*3+i*4;
- float *neighbours=payload.data()+plane*4+i*4;
- world[0]=node.world[0];world[1]=node.world[1];world[2]=node.world[2];
- coast[0]=c.depth;coast[1]=c.distance;coast[2]=c.outwardX;coast[3]=c.outwardY;
- surface[0]=c.exposure;surface[1]=c.offshore;surface[2]=c.analyticDamping;surface[3]=c.spectralDamping;
- admission[0]=c.wet;admission[1]=c.admitted;
- for(unsigned side=0;side<4;++side) neighbours[side]=float(node.neighbour[side]);
- }
- if(CoastalSurf && CoastalSurf->Revision==revision) {
- // Revision is an immutable domain identity. Repeated binds neither clear history
- // nor silently accept changed bytes under a stale revision.
- return CoastalSurf->Count==nodes.size() && CoastalSurf->Spacing==spacing
- && CoastalSurf->Payload.size()==payload.size()
- && memcmp(CoastalSurf->Payload.data(),payload.data(),payload.size()*sizeof(float))==0;
- }
- const SDL_GPUTextureUsageFlags usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET|SDL_GPU_TEXTUREUSAGE_SAMPLER;
- if(!SDL_GPUTextureSupportsFormat(GpuDevice,SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT,
- SDL_GPU_TEXTURETYPE_2D,usage)) return false; // retain the existing water fallback
- std::unique_ptr<CoastalSurfResources> next(new CoastalSurfResources(GpuDevice));
- next->Revision=revision;next->Count=unsigned(nodes.size());next->Spacing=spacing;next->Payload=std::move(payload);
- SDL_GPUTextureCreateInfo info={};info.type=SDL_GPU_TEXTURETYPE_2D;
- info.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;info.usage=usage;
- info.width=info.height=AtlasSide;info.layer_count_or_depth=info.num_levels=1;
- for(auto *&texture:next->Domain) texture=SDL_CreateGPUTexture(GpuDevice,&info);
- for(auto *&texture:next->State) texture=SDL_CreateGPUTexture(GpuDevice,&info);
- next->Input=SDL_CreateGPUTexture(GpuDevice,&info);
- for(auto *texture:next->Domain) if(!texture) return false;
- for(auto *texture:next->State) if(!texture) return false;
- if(!next->Input) return false;
- SDL_GPUSamplerCreateInfo sampler={};
- sampler.address_mode_u=sampler.address_mode_v=sampler.address_mode_w=SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
- sampler.min_filter=sampler.mag_filter=SDL_GPU_FILTER_NEAREST;sampler.mipmap_mode=SDL_GPU_SAMPLERMIPMAPMODE_NEAREST;
- next->Point=SDL_CreateGPUSampler(GpuDevice,&sampler);if(!next->Point) return false;
- std::vector<unsigned char> spirv;std::string error;
- if(!SDL3_Compile_HLSL_To_SPIRV(WaterFftSpectrum::VertexHlsl(),true,spirv,error)
- || !(next->Vertex=SDL3_Create_Shader(GpuDevice,spirv,true,error))) return false;
- for(unsigned which=0;which<2;++which) {
- if(!SDL3_Compile_HLSL_To_SPIRV(Coastal_Surf_Pixel_Source(which!=0),false,spirv,error)) return false;
- unsigned samplers=0,uniforms=0;SDL3_Shader_Slots(spirv,false,samplers,uniforms);
- if(samplers!=(which?2u:5u) || uniforms!=1) return false;
- next->Pixels[which]=SDL3_Create_Shader(GpuDevice,spirv,false,error);if(!next->Pixels[which]) return false;
- SDL_GPUColorTargetDescription target={};target.format=info.format;
- SDL_GPUGraphicsPipelineCreateInfo pipeline={};pipeline.vertex_shader=next->Vertex;
- pipeline.fragment_shader=next->Pixels[which];pipeline.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;
- pipeline.rasterizer_state.cull_mode=SDL_GPU_CULLMODE_NONE;pipeline.rasterizer_state.fill_mode=SDL_GPU_FILLMODE_FILL;
- pipeline.target_info.color_target_descriptions=&target;pipeline.target_info.num_color_targets=1;
- next->Pipelines[which]=SDL_CreateGPUGraphicsPipeline(GpuDevice,&pipeline);
- if(!next->Pipelines[which]) return false;
- }
- const Uint32 bytes=Uint32(plane*sizeof(float));
- SDL_GPUTransferBufferCreateInfo transferInfo={};transferInfo.usage=SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD;
- transferInfo.size=bytes*9; // five domain, three state, one incident texture: 9 MiB maximum
- SDL_GPUTransferBuffer *transfer=SDL_CreateGPUTransferBuffer(GpuDevice,&transferInfo);
- if(!transfer) return false;
- float *mapped=static_cast<float *>(SDL_MapGPUTransferBuffer(GpuDevice,transfer,false));
- if(!mapped){SDL_ReleaseGPUTransferBuffer(GpuDevice,transfer);return false;}
- memcpy(mapped,next->Payload.data(),bytes*5);
- memset(mapped+plane*5,0,bytes*4);
- for(unsigned state=0;state<3;++state) for(unsigned i=0;i<MaxNodes;++i) mapped[plane*(5+state)+i*4+3]=-1;
- // Until the producer writes a real incident field, this valid still field cannot emit.
- for(unsigned i=0;i<MaxNodes;++i) mapped[plane*8+i*4+3]=1;
- SDL_UnmapGPUTransferBuffer(GpuDevice,transfer);
- // The old resources remain intact on every allocation/compile/upload-recording failure.
- if((!Commands.empty() || !Uploads.empty()) && !Flush()) {
- SDL_ReleaseGPUTransferBuffer(GpuDevice,transfer);return false;
- }
- SDL_GPUCommandBuffer *commands=SDL_AcquireGPUCommandBuffer(GpuDevice);
- if(!commands){SDL_ReleaseGPUTransferBuffer(GpuDevice,transfer);return false;}
- SDL_GPUCopyPass *copy=SDL_BeginGPUCopyPass(commands);
- if(!copy){SDL_CancelGPUCommandBuffer(commands);SDL_ReleaseGPUTransferBuffer(GpuDevice,transfer);return false;}
- for(unsigned i=0;i<9;++i) {
- SDL_GPUTextureTransferInfo upload={};upload.transfer_buffer=transfer;upload.offset=i*bytes;
- upload.pixels_per_row=upload.rows_per_layer=AtlasSide;
- SDL_GPUTextureRegion region={};region.texture=i<5?next->Domain[i]:i<8?next->State[i-5]:next->Input;
- region.w=region.h=AtlasSide;region.d=1;SDL_UploadToGPUTexture(copy,&upload,&region,false);
- }
- SDL_EndGPUCopyPass(copy);
- const bool submitted=SerializeSubmits?Submit(commands):Submit_Flush(commands);
- SDL_ReleaseGPUTransferBuffer(GpuDevice,transfer);
- if(!submitted) return false;
- Release_Coastal_Surf();CoastalSurf=next.release();++CoastalSurfInstalls;
- return true;
-}
-
-SdlTarget SdlGpuFrame::Coastal_Surf_Field_Target(uint64_t revision) const
-{
- SdlTarget target={};
- if(CoastalSurf && CoastalSurf->Revision==revision) {
- target.Colour=CoastalSurf->Input;target.Width=target.Height=WaterCoastalSurf::AtlasSide;
- }
- return target;
-}
-
-bool SdlGpuFrame::Coastal_Surf_Field_Due(uint64_t revision,double time) const
-{
- if(!CoastalSurf || CoastalSurf->Revision!=revision) return false;
- const auto action=CoastalSurf->Clock.Inspect(revision,time).action;
- return action==WaterCoastalSurf::Action::Sample || action==WaterCoastalSurf::Action::GapDecay;
-}
-
-bool SdlGpuFrame::Prepare_Coastal_Surf(uint64_t revision,double time,const SdlTarget &field)
-{
- return Prepare_Coastal_Surf_Impl(revision,time,field,false);
-}
-
-bool SdlGpuFrame::Prepare_Coastal_Surf_From_Ocean(uint64_t revision,double time)
-{
- return Prepare_Coastal_Surf_Impl(revision,time,Coastal_Surf_Field_Target(revision),true);
-}
-
-bool SdlGpuFrame::Prepare_Coastal_Surf_Impl(uint64_t revision,double time,const SdlTarget &field,bool fromOcean)
-{
- using namespace WaterCoastalSurf;
- if(!CoastalSurf || !revision || CoastalSurf->Revision!=revision
- || field.Colour!=CoastalSurf->Input || field.Depth || field.Width!=AtlasSide || field.Height!=AtlasSide) return false;
- const Plan plan=CoastalSurf->Clock.Inspect(revision,time);
- if(plan.action==Action::Invalid) return false;
- if(plan.action==Action::None) return CoastalSurf->Clock.Commit(revision,plan);
- const bool incident=fromOcean && (plan.action==Action::Sample || plan.action==Action::GapDecay);
- if(incident) {
- // This is the same float multiply used by the ordinary water draw. A stale,
- // missing, or differently phased ocean must not advance source history.
- const float phase=float(time)*WaterFftSampling::TimeScale;
- if(!std::isfinite(phase) || !OceanReady || !Ocean || OceanTime!=phase
- || !Ocean->Linear || !CoastalSurf->CreateIncident()) return false;
- for(unsigned i=0;i<4;++i) if(!Ocean->Maps[i]) return false;
- }
- // Includes caller writes into Input and any earlier draws sampling the current State.
- if((!Commands.empty() || !Uploads.empty()) && !Flush()) return false;
- SDL_GPUCommandBuffer *commands=SDL_AcquireGPUCommandBuffer(GpuDevice);if(!commands) return false;
- const unsigned reaction=(CoastalSurf->Active+1)%3,final=(CoastalSurf->Active+2)%3;
- SDL_GPUTexture *inputs[5]={CoastalSurf->State[CoastalSurf->Active],CoastalSurf->Input,
- CoastalSurf->Domain[1],CoastalSurf->Domain[2],CoastalSurf->Domain[3]};
- const float parameters[4]={float(CoastalSurf->Count),float(plan.elapsed),float(CoastalSurf->Spacing),
- plan.action==Action::Reset?2.0f:plan.action==Action::GapDecay?1.0f:0.0f};
- // The producer output is sampled only after ending its attachment pass. Keeping
- // all three passes in this command buffer makes failure/clock commitment atomic.
- bool ok=!incident || CoastalSurf->IncidentPass(commands,Ocean->Maps,Ocean->Linear,float(time));
- if(ok) ok=CoastalSurf->Pass(commands,0,CoastalSurf->State[reaction],inputs,5,parameters);
- unsigned next=reaction;
- if(ok && plan.action==Action::Sample) {
- SDL_GPUTexture *sources[2]={CoastalSurf->State[reaction],CoastalSurf->Domain[4]};
- ok=CoastalSurf->Pass(commands,1,CoastalSurf->State[final],sources,2,parameters);next=final;
- }
- if(!ok){SDL_CancelGPUCommandBuffer(commands);return false;}
- const Uint64 started=SDL_GetTicksNS();
- ok=SerializeSubmits?Submit(commands):Submit_Flush(commands);
- FlushMs+=double(SDL_GetTicksNS()-started)/1.0e6;++Flushes;++FlushesTotal;
- if(!ok) return false;
- // Commit only after every GPU write is accepted. Earlier state stays addressable on failure.
- if(!CoastalSurf->Clock.Commit(revision,plan)){CoastalSurf->Ready=false;return false;}
- CoastalSurf->Active=next;CoastalSurf->Ready=true;++CoastalSurfUpdates;return true;
-}
-
-SDL_GPUTexture *SdlGpuFrame::Coastal_Surf_State(uint64_t revision) const
-{
- return CoastalSurf && CoastalSurf->Ready && CoastalSurf->Revision==revision
- ?CoastalSurf->State[CoastalSurf->Active]:NULL;
-}
-SDL_GPUTexture *SdlGpuFrame::Coastal_Surf_Domain(unsigned index,uint64_t revision) const
-{
- return CoastalSurf && CoastalSurf->Revision==revision && index<5?CoastalSurf->Domain[index]:NULL;
-}
-SDL_GPUSampler *SdlGpuFrame::Coastal_Surf_Sampler(uint64_t revision) const
-{
- return CoastalSurf && CoastalSurf->Revision==revision?CoastalSurf->Point:NULL;
-}
-double SdlGpuFrame::Coastal_Surf_Time(uint64_t revision) const
-{
- return CoastalSurf && CoastalSurf->Ready && CoastalSurf->Revision==revision?CoastalSurf->Clock.SampledTime():0;
-}
-unsigned SdlGpuFrame::Coastal_Surf_Nodes(uint64_t revision) const
-{
- return CoastalSurf && CoastalSurf->Revision==revision?CoastalSurf->Count:0;
-}
-
-// One global view allocation set, independent of the fixed-world history atlas.
-struct SdlGpuFrame::CoastalSurfViewResources
-{
- SDL_GPUDevice *Device;
- SDL_GPUTexture *Ids=NULL,*Weights=NULL,*Output=NULL;
- SDL_GPUShader *Pixel=NULL;
- SDL_GPUGraphicsPipeline *Pipeline=NULL;
- SDL_GPUSampler *Linear=NULL;
- WaterCoastalView::Mapping Mapping={};
- std::vector<WaterCoastalSurf::Lookup> Lookups;
- uint64_t Revision=0,HistoryUpdate=0;
- double Level=0,Time=0;
- bool Pending=true,Ready=false;
- explicit CoastalSurfViewResources(SDL_GPUDevice *device):Device(device) {}
- ~CoastalSurfViewResources() {
- if(Pipeline)SDL_ReleaseGPUGraphicsPipeline(Device,Pipeline);
- if(Pixel)SDL_ReleaseGPUShader(Device,Pixel);
- if(Linear)SDL_ReleaseGPUSampler(Device,Linear);
- if(Ids)SDL_ReleaseGPUTexture(Device,Ids);
- if(Weights)SDL_ReleaseGPUTexture(Device,Weights);
- if(Output)SDL_ReleaseGPUTexture(Device,Output);
- }
-};
-
-static const char *Coastal_Surf_View_Pixel_Source()
-{
- return R"VIEW(
-Texture2D<float4> Ids:register(t0,space2);
-Texture2D<float4> Weights:register(t1,space2);
-Texture2D<float4> State:register(t2,space2);
-Texture2D<float4> World:register(t3,space2);
-cbuffer ViewParameters:register(b0,space3){float4 Parameters;};
-float4 main(float4 position:SV_Position):SV_Target0 {
- uint2 pixel=(uint2)position.xy;
- float4 ids=Ids.Load(int3(pixel,0)),weights=Weights.Load(int3(pixel,0));
- if(!all(isfinite(ids))||!all(isfinite(weights))||any(weights<0)||any(weights>1)
- ||dot(weights,float4(1,1,1,1))>1.000001)return 0;
- float2 moments=0;
- [unroll]for(uint i=0;i<4;++i) {
- float id=ids[i],weight=weights[i];
- if(weight<=0)continue;
- if(id<1||id>Parameters.x||id!=floor(id))continue;
- uint at=(uint)id-1;int3 cell=int3(at%256,at/256,0);
- float4 world=World.Load(cell),state=State.Load(cell);
- if(!all(isfinite(world))||world.z!=Parameters.y||!all(isfinite(state))
- ||state.x<0||state.x>16||state.y<0||state.y>1024
- ||abs(state.z)>64||state.w< -1||state.w>1.2)continue;
- // Missing, invalid and wrong-level contributions remain zero. Never
- // normalize surviving weights or convert density into coverage here.
- moments+=weight*state.xy;
- }
- return float4(moments,0,0);
-}
-)VIEW";
-}
-
-void SdlGpuFrame::Release_Coastal_Surf_View()
-{
- if(!CoastalSurfView)return;
- if(TargetSet && (CurrentTarget.Colour==CoastalSurfView->Ids
- ||CurrentTarget.Colour==CoastalSurfView->Weights||CurrentTarget.Colour==CoastalSurfView->Output)) {
- TargetSet=false;CurrentTarget={};
- }
- delete CoastalSurfView;CoastalSurfView=NULL;
-}
-
-bool SdlGpuFrame::Clear_Coastal_Surf_View()
-{
- if((!Commands.empty()||!Uploads.empty())&&!Flush())return false;
- Release_Coastal_Surf_View();return true;
-}
-
-bool SdlGpuFrame::Set_Coastal_Surf_View(uint64_t revision,const WaterShoreHistory::Mapping &mapping,
- double level,const std::vector<WaterCoastalSurf::Lookup> &lookups)
-{
- using namespace WaterCoastalSurf;
- auto fail=[&](){if(CoastalSurfView)CoastalSurfView->Ready=false;return false;};
- if(!CoastalSurf||!revision||CoastalSurf->Revision!=revision||!WaterCoastalView::ValidMapping(mapping)
- ||!WaterCoastalView::ValidLevel(level)
- ||lookups.size()!=size_t(mapping.widthPixels)*mapping.heightPixels)return fail();
- for(const Lookup &lookup:lookups) {
- if(!ValidLookup(lookup,CoastalSurf->Count))return fail();
- for(unsigned i=0;i<4;++i)if(lookup.node[i]) {
- // Validate against immutable serialized domain identity, not caller labels.
- if(CoastalSurf->Payload[(lookup.node[i]-1)*4+2]!=float(level))return fail();
- }
- }
- static_assert(sizeof(Lookup)==8*sizeof(uint32_t),"lookup has exactly eight scalar channels");
- if(CoastalSurfView && CoastalSurfView->Revision==revision && CoastalSurfView->Level==level
- && WaterCoastalView::SameMapping(CoastalSurfView->Mapping,mapping)
- && CoastalSurfView->Lookups.size()==lookups.size()
- && memcmp(CoastalSurfView->Lookups.data(),lookups.data(),lookups.size()*sizeof(Lookup))==0)return true;
- // Allocate the accepted CPU copy before changing any existing cache metadata.
- std::vector<Lookup> accepted=lookups;
- const bool replace=!CoastalSurfView
- ||CoastalSurfView->Mapping.widthPixels!=mapping.widthPixels
- ||CoastalSurfView->Mapping.heightPixels!=mapping.heightPixels;
- std::unique_ptr<CoastalSurfViewResources> next;
- CoastalSurfViewResources *view=CoastalSurfView;
- if(replace) {
- next.reset(new CoastalSurfViewResources(GpuDevice));view=next.get();
- SDL_GPUTextureCreateInfo ti={};ti.type=SDL_GPU_TEXTURETYPE_2D;
- ti.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
- ti.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET|SDL_GPU_TEXTUREUSAGE_SAMPLER;
- ti.width=mapping.widthPixels;ti.height=mapping.heightPixels;ti.layer_count_or_depth=ti.num_levels=1;
- view->Ids=SDL_CreateGPUTexture(GpuDevice,&ti);view->Weights=SDL_CreateGPUTexture(GpuDevice,&ti);
- view->Output=SDL_CreateGPUTexture(GpuDevice,&ti);
- if(!view->Ids||!view->Weights||!view->Output)return fail();
- SDL_GPUSamplerCreateInfo si={};si.min_filter=si.mag_filter=SDL_GPU_FILTER_LINEAR;
- si.mipmap_mode=SDL_GPU_SAMPLERMIPMAPMODE_NEAREST;
- si.address_mode_u=si.address_mode_v=si.address_mode_w=SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
- view->Linear=SDL_CreateGPUSampler(GpuDevice,&si);if(!view->Linear)return fail();
- std::string error;std::vector<unsigned char> spirv;
- if(!SDL3_Compile_HLSL_To_SPIRV(Coastal_Surf_View_Pixel_Source(),false,spirv,error))return fail();
- unsigned samplers=0,uniforms=0;SDL3_Shader_Slots(spirv,false,samplers,uniforms);
- if(samplers!=4||uniforms!=1)return fail();
- view->Pixel=SDL3_Create_Shader(GpuDevice,spirv,false,error);if(!view->Pixel)return fail();
- SDL_GPUColorTargetDescription colour={};colour.format=ti.format;
- SDL_GPUGraphicsPipelineCreateInfo pi={};pi.vertex_shader=CoastalSurf->Vertex;pi.fragment_shader=view->Pixel;
- pi.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;pi.rasterizer_state.cull_mode=SDL_GPU_CULLMODE_NONE;
- pi.rasterizer_state.fill_mode=SDL_GPU_FILLMODE_FILL;
- pi.target_info.color_target_descriptions=&colour;pi.target_info.num_color_targets=1;
- view->Pipeline=SDL_CreateGPUGraphicsPipeline(GpuDevice,&pi);if(!view->Pipeline)return fail();
- // Old CPU draws must retain the old view until submitted before its release.
- if((!Commands.empty()||!Uploads.empty())&&!Flush())return fail();
- }
- view->Revision=revision;view->Level=level;view->Mapping=mapping;
- view->Lookups.swap(accepted);view->Pending=true;view->Ready=false;
- if(replace){Release_Coastal_Surf_View();CoastalSurfView=next.release();}
- ++CoastalSurfViewSets;return true;
-}
-
-bool SdlGpuFrame::Prepare_Coastal_Surf_View(uint64_t revision)
-{
- auto fail=[&](){if(CoastalSurfView)CoastalSurfView->Ready=false;return false;};
- if(!CoastalSurfView||!CoastalSurf||!CoastalSurf->Ready||CoastalSurfView->Revision!=revision
- ||CoastalSurf->Revision!=revision)return fail();
- CoastalSurfViewResources &view=*CoastalSurfView;
- if(view.Ready&&!view.Pending&&view.HistoryUpdate==CoastalSurfUpdates)return true;
- if((!Commands.empty()||!Uploads.empty())&&!Flush())return fail();
- SDL_GPUTexture *state=CoastalSurf->State[CoastalSurf->Active],*world=CoastalSurf->Domain[0];
- if(!state||!world||view.Output==state||view.Output==world||view.Output==view.Ids||view.Output==view.Weights)return fail();
- SDL_GPUTransferBuffer *transfer=NULL;
- const Uint32 bytes=Uint32(view.Lookups.size()*4*sizeof(float));
- if(view.Pending) {
- SDL_GPUTransferBufferCreateInfo ti={};ti.usage=SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD;ti.size=bytes*2;
- transfer=SDL_CreateGPUTransferBuffer(GpuDevice,&ti);if(!transfer)return fail();
- float *mapped=static_cast<float *>(SDL_MapGPUTransferBuffer(GpuDevice,transfer,false));
- if(!mapped){SDL_ReleaseGPUTransferBuffer(GpuDevice,transfer);return fail();}
- for(size_t n=0;n<view.Lookups.size();++n)for(unsigned c=0;c<4;++c) {
- mapped[n*4+c]=float(view.Lookups[n].node[c]);
- mapped[view.Lookups.size()*4+n*4+c]=view.Lookups[n].weight[c];
- }
- SDL_UnmapGPUTransferBuffer(GpuDevice,transfer);
- }
- SDL_GPUCommandBuffer *commands=SDL_AcquireGPUCommandBuffer(GpuDevice);
- auto cancel=[&](){if(commands)SDL_CancelGPUCommandBuffer(commands);if(transfer)SDL_ReleaseGPUTransferBuffer(GpuDevice,transfer);return fail();};
- if(!commands)return cancel();
- if(view.Pending) {
- SDL_GPUCopyPass *copy=SDL_BeginGPUCopyPass(commands);if(!copy)return cancel();
- for(unsigned i=0;i<2;++i) {
- SDL_GPUTextureTransferInfo upload={};upload.transfer_buffer=transfer;upload.offset=i*bytes;
- upload.pixels_per_row=view.Mapping.widthPixels;upload.rows_per_layer=view.Mapping.heightPixels;
- SDL_GPUTextureRegion region={};region.texture=i?view.Weights:view.Ids;
- region.w=view.Mapping.widthPixels;region.h=view.Mapping.heightPixels;region.d=1;
- SDL_UploadToGPUTexture(copy,&upload,&region,false);
- }
- SDL_EndGPUCopyPass(copy);
- }
- SDL_GPUColorTargetInfo target={};target.texture=view.Output;
- target.load_op=SDL_GPU_LOADOP_DONT_CARE;target.store_op=SDL_GPU_STOREOP_STORE;
- SDL_GPURenderPass *pass=SDL_BeginGPURenderPass(commands,&target,1,NULL);if(!pass)return cancel();
- SDL_BindGPUGraphicsPipeline(pass,view.Pipeline);
- SDL_GPUTextureSamplerBinding bindings[4]={{view.Ids,CoastalSurf->Point},{view.Weights,CoastalSurf->Point},
- {state,CoastalSurf->Point},{world,CoastalSurf->Point}};
- SDL_BindGPUFragmentSamplers(pass,0,bindings,4);
- const SDL_GPUViewport viewport={0,0,float(view.Mapping.widthPixels),float(view.Mapping.heightPixels),0,1};
- SDL_SetGPUViewport(pass,&viewport);
- const float parameters[4]={float(CoastalSurf->Count),float(view.Level),0,0};
- SDL_PushGPUFragmentUniformData(commands,0,parameters,sizeof(parameters));
- SDL_DrawGPUPrimitives(pass,3,1,0,0);SDL_EndGPURenderPass(pass);
- const Uint64 started=SDL_GetTicksNS();
- const bool submitted=SerializeSubmits?Submit(commands):Submit_Flush(commands);
- FlushMs+=double(SDL_GetTicksNS()-started)/1.0e6;++Flushes;++FlushesTotal;
- if(transfer)SDL_ReleaseGPUTransferBuffer(GpuDevice,transfer);
- if(!submitted)return fail();
- view.Pending=false;view.Ready=true;view.HistoryUpdate=CoastalSurfUpdates;
- view.Time=CoastalSurf->Clock.SampledTime();++CoastalSurfViewUpdates;return true;
-}
-
-SDL_GPUTexture *SdlGpuFrame::Coastal_Surf_View(uint64_t revision,double level) const
-{
- return CoastalSurfView&&CoastalSurf&&CoastalSurf->Ready&&CoastalSurf->Revision==revision
- &&CoastalSurfView->Ready&&!CoastalSurfView->Pending&&CoastalSurfView->Revision==revision
- &&CoastalSurfView->Level==level&&CoastalSurfView->HistoryUpdate==CoastalSurfUpdates?CoastalSurfView->Output:NULL;
-}
-SDL_GPUSampler *SdlGpuFrame::Coastal_Surf_View_Sampler(uint64_t revision,double level) const
-{
- return Coastal_Surf_View(revision,level)?CoastalSurfView->Linear:NULL;
-}
-double SdlGpuFrame::Coastal_Surf_View_Time(uint64_t revision,double level) const
-{
- return Coastal_Surf_View(revision,level)?CoastalSurfView->Time:0;
-}
-
void SdlGpuFrame::Invalidate_Water_Snapshots(SDL_GPUTexture *colour, SDL_GPUTexture *depth)
{
for (size_t i = 0; i < WaterSnapshots.size(); ++i) {
@@ -1141,7 +599,11 @@ bool SdlGpuFrame::Create_Water_Depth_Pipeline()
std::vector<unsigned char> spirv;
if (!SDL3_Compile_HLSL_To_SPIRV(GAMMA_VERTEX_HLSL, true, spirv, log)
|| !(WaterDepthVertex = SDL3_Create_Shader(GpuDevice, spirv, true, log))) {
- fprintf(stderr, "SdlGpuFrame: water depth vertex: %s\n", log.c_str());
+ static bool reported = false;
+ if (!reported) {
+ reported = true;
+ fprintf(stderr, "SdlGpuFrame: water depth vertex: %s\n", log.c_str());
+ }
return false;
}
}
@@ -1149,7 +611,11 @@ bool SdlGpuFrame::Create_Water_Depth_Pipeline()
std::vector<unsigned char> spirv;
if (!SDL3_Compile_HLSL_To_SPIRV(WATER_DEPTH_PIXEL_HLSL, false, spirv, log)
|| !(WaterDepthPixel = SDL3_Create_Shader(GpuDevice, spirv, false, log))) {
- fprintf(stderr, "SdlGpuFrame: water depth pixel: %s\n", log.c_str());
+ static bool reported = false;
+ if (!reported) {
+ reported = true;
+ fprintf(stderr, "SdlGpuFrame: water depth pixel: %s\n", log.c_str());
+ }
return false;
}
}
@@ -1173,8 +639,13 @@ bool SdlGpuFrame::Create_Water_Depth_Pipeline()
sampler.address_mode_u = sampler.address_mode_v = sampler.address_mode_w = SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
WaterDepthSampler = SDL_CreateGPUSampler(GpuDevice, &sampler);
}
- if (!WaterDepthPipeline || !WaterDepthSampler)
- fprintf(stderr, "SdlGpuFrame: water depth resolve: %s\n", SDL_GetError());
+ if (!WaterDepthPipeline || !WaterDepthSampler) {
+ static bool reported = false;
+ if (!reported) {
+ reported = true;
+ fprintf(stderr, "SdlGpuFrame: water depth resolve: %s\n", SDL_GetError());
+ }
+ }
return WaterDepthPipeline && WaterDepthSampler;
}
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrame.h b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrame.h
index e5ca7a67c..145172e3a 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrame.h
+++ b/GeneralsMD/Code/GameEngineDevice/Source/PosixDevice/Render/SdlGpuFrame.h
@@ -48,8 +48,6 @@ struct SDL_GPUSampler;
struct SDL_GPUShader;
struct SDL_GPUTexture;
struct SDL_Window;
-namespace WaterCoastalSurf { struct Node; struct Lookup; }
-namespace WaterShoreHistory { struct Mapping; }
/// Where a pass draws: a colour texture of Target_Format() and a depth-stencil of Depth_Format(), the
/// same size. The back buffer is one; a render-target surface's GPU texture is another (A3d).
@@ -232,47 +230,6 @@ public:
SDL_GPUSampler * Ocean_Sampler() const;
uint64_t Ocean_Updates() const { return OceanUpdates; }
- /// Bounded GPU coastal history; callers install one immutable graph across all levels.
- /// Same revision with changed bytes is rejected. Empty graphs clear the feature.
- bool Install_Coastal_Surf(uint64_t revision,const std::vector<WaterCoastalSurf::Node> &nodes,double spacing);
- /// Known-format RGBA32F 256x256 target owned by this frame. The caller renders the current
- /// incident Field here, then supplies this exact target to Prepare. No arbitrary native
- /// texture metadata is trusted; SDL offers no public texture format/dimension query.
- SdlTarget Coastal_Surf_Field_Target(uint64_t revision) const;
- /// Render the incident Field only for Sample/GapDecay. First/reset Prepare clears to
- /// density=age=height=0, rate=-1; it consumes no field. Call Prepare even when not due
- /// to observe clock advances/rewinds without repeating GPU work at paused times.
- bool Coastal_Surf_Field_Due(uint64_t revision,double water_time) const;
- bool Prepare_Coastal_Surf(uint64_t revision,double water_time,const SdlTarget &field);
- /// Production path: when due, sample only an already prepared matching-phase ocean,
- /// then record incident/reaction/diffusion atomically. Never updates the FFT itself.
- /// On false, caller must disable coastal composition for this draw, not use stale data.
- bool Prepare_Coastal_Surf_From_Ocean(uint64_t revision,double water_time);
- bool Clear_Coastal_Surf();
- /// Borrowed handles remain valid until Clear or a different successful Install. Prepare
- /// can rotate the state handle; resolve it after Prepare for each immutable recorded draw.
- SDL_GPUTexture * Coastal_Surf_State(uint64_t revision) const;
- /// Domain indices: 0 world,1 coast,2 surface,3 admission,4 neighbour IDs (index+1).
- SDL_GPUTexture * Coastal_Surf_Domain(unsigned index,uint64_t revision) const;
- SDL_GPUSampler * Coastal_Surf_Sampler(uint64_t revision) const;
- double Coastal_Surf_Time(uint64_t revision) const;
- unsigned Coastal_Surf_Nodes(uint64_t revision) const;
- uint64_t Coastal_Surf_Updates() const { return CoastalSurfUpdates; }
- uint64_t Coastal_Surf_Installs() const { return CoastalSurfInstalls; }
- /// One active camera-view lookup across all water levels. Set caches/validates CPU
- /// IDs and weights; Prepare uploads changed lookup and composes density/age moments
- /// from the current history in one submission. Missing weights stay zero.
- bool Set_Coastal_Surf_View(uint64_t revision,const WaterShoreHistory::Mapping &mapping,
- double level,const std::vector<WaterCoastalSurf::Lookup> &lookups);
- bool Prepare_Coastal_Surf_View(uint64_t revision);
- bool Clear_Coastal_Surf_View();
- /// Only current-state, successfully submitted output is exposed; B/A are zero.
- SDL_GPUTexture *Coastal_Surf_View(uint64_t revision,double level) const;
- SDL_GPUSampler *Coastal_Surf_View_Sampler(uint64_t revision,double level) const;
- double Coastal_Surf_View_Time(uint64_t revision,double level) const;
- uint64_t Coastal_Surf_View_Sets() const { return CoastalSurfViewSets; }
- uint64_t Coastal_Surf_View_Updates() const { return CoastalSurfViewUpdates; }
-
unsigned int Width() const { return BackWidth; }
unsigned int Height() const { return BackHeight; }
/// The back buffer's format, and so what a Present_To target has to be.
@@ -359,16 +316,6 @@ private:
void Release_Ocean();
bool Fail_Ocean(const char *reason);
- struct CoastalSurfResources;
- CoastalSurfResources *CoastalSurf=NULL;
- uint64_t CoastalSurfUpdates=0,CoastalSurfInstalls=0;
- void Release_Coastal_Surf();
- bool Prepare_Coastal_Surf_Impl(uint64_t revision,double time,const SdlTarget &field,bool from_ocean);
- struct CoastalSurfViewResources;
- CoastalSurfViewResources *CoastalSurfView=NULL;
- uint64_t CoastalSurfViewSets=0,CoastalSurfViewUpdates=0;
- void Release_Coastal_Surf_View();
-
WaterSnapshot *Water_Snapshot(const SdlTarget &source);
void Invalidate_Water_Snapshots(SDL_GPUTexture *colour, SDL_GPUTexture *depth);
void Refresh_Water_Snapshots();
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp
index f804e8c2c..f85259ddf 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWater.cpp
@@ -31,15 +31,12 @@
///////////////////////////////////////////////////////////////////////////////////////////////////
#define SCROLL_UV
-
+
// INCLUDES ///////////////////////////////////////////////////////////////////////////////////////
#include "stdio.h"
-#include <cstdlib>
-#include <chrono>
#include "Lib/Clock.h"
#include "Platform/WaterSurfaceModel.h"
#include "Platform/ModernWaterMaterial.h"
-#include "Platform/WaterCoastalCrest.h"
#include "Platform/WaterShoreOverlay.h"
#include "Platform/WaterFoamWindow.h"
#include "Platform/WaterFoamParticlePolicy.h"
@@ -93,7 +90,6 @@
#include "W3DDevice/GameClient/W3DScene.h"
#include "W3DDevice/GameClient/W3DCustomScene.h"
-
#ifdef _INTERNAL
// for occasional debugging...
//#pragma optimize("", off)
@@ -225,7 +221,6 @@ void doSkyBoxSet(Bool startDraw)
TheWritableGlobalData->m_drawSkyBox = startDraw;
}
-
#define DONUT_SIDES 90
#define INNER_RADIUS 200.0f
#define OUTER_RADIUS 250.0f
@@ -241,7 +236,6 @@ void doSkyBoxSet(Bool startDraw)
static const Real WATER_SCROLL_SPEED = 0.2f;
static const Real AUTHORED_FPS = 30.0f;
-
static Bool wireframeForDebug = 0;
//
@@ -291,10 +285,8 @@ void WaterRenderObjClass::setupJbaWaterShader(void)
m_riverTexture->Get_Filter().Set_Min_Filter(TextureFilterClass::FILTER_TYPE_BEST);
m_riverTexture->Get_Filter().Set_Mip_Mapping(TextureFilterClass::FILTER_TYPE_BEST);
-
// Setting *setting=&m_settings[m_tod];
-
DX8Wrapper::Apply_Render_State_Changes(); //force update of view and projection matrices
DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_ALPHAOP, D3DTOP_ADD );
if (!m_riverAlphaEdge->Is_Initialized())
@@ -305,7 +297,7 @@ void WaterRenderObjClass::setupJbaWaterShader(void)
DX8Wrapper::Set_DX8_Texture_Stage_State(0, D3DTSS_TEXCOORDINDEX, 0);
DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DTSS_TEXCOORDINDEX, 0);
DX8Wrapper::Set_DX8_Texture_Stage_State(3, D3DTSS_TEXCOORDINDEX, 1);
-
+
Bool doSparkles = true;
if (m_riverWaterPixelShader && doSparkles) {
@@ -319,7 +311,7 @@ void WaterRenderObjClass::setupJbaWaterShader(void)
DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DSAMP_ADDRESSU, D3DTADDRESS_WRAP);
DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DSAMP_ADDRESSV, D3DTADDRESS_WRAP);
-
+
DX8Wrapper::Set_DX8_Texture_Stage_State(2, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_CAMERASPACEPOSITION);
// Two output coordinates are used.
DX8Wrapper::Set_DX8_Texture_Stage_State(2, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT2);
@@ -338,7 +330,7 @@ void WaterRenderObjClass::setupJbaWaterShader(void)
D3DXMatrixTranslation(&scale, m_riverVOrigin, m_riverVOrigin,0);
destMatrix = destMatrix*scale;
DX8Wrapper::_Set_DX8_Transform(D3DTS_TEXTURE2, *(Matrix4x4*)&destMatrix);
-
+
}
DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR );
DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR );
@@ -455,10 +447,6 @@ void WaterRenderObjClass::clearModernWaterHulls(Bool admissions)
m_modernVisualHulls.clear();
m_modernHullObjectIDs.clear();
m_modernHullSerial = 0;
- m_modernHullTraceLines = 0;
- m_modernVesselStateTraceFrame = ~0u;
- m_modernVesselStateTraceLines = 0;
- m_modernVisualHullTraceLines = 0;
}
Bool WaterRenderObjClass::modernHasHull(UnsignedInt objectID) const
@@ -592,16 +580,8 @@ void WaterRenderObjClass::updateModernWaterHulls(void)
clearModernWaterHulls();clearModernWaterFoam();return;
}
++m_modernHullSerial;
- const Bool visualContact=WaterHullVisual::Enabled();
const UnsignedInt motionFrame=m_modernMotionFrame;
const Bool motionFrozen=m_modernMotionFrozen;
- // Opt-in evidence of the actual displayed transform; never drives water or simulation.
- const char *stateTraceOption=getenv("ZH_WATER_VESSEL_STATE_TRACE");
- const UnsignedInt renderFrame=WW3D::Get_Frame_Count();
- const Bool traceVesselState=stateTraceOption && stateTraceOption[0]=='1' && stateTraceOption[1]=='\0' &&
- !m_renderingMirror && m_modernVesselStateTraceLines<4096 && m_modernVesselStateTraceFrame!=renderFrame;
- if(traceVesselState) m_modernVesselStateTraceFrame=renderFrame;
- unsigned stateTraceRows=0;
struct Candidate { UnsignedInt objectID; const ModernWaterObject *object; RenderObjClass *model; Real level,score,samplePhase,crestRise; Bool influenceVisible; };
m_modernFoamHistory.Advance(m_modernWaveTime);
std::vector<Candidate> candidates;
@@ -715,24 +695,7 @@ void WaterRenderObjClass::updateModernWaterHulls(void)
if(cache.slicedModels.capacity()<meshes.size()) cache.slicedModels.reserve(meshes.size());
for(const WaterHullMesh &mesh:meshes) { mesh.model->Add_Ref();cache.slicedModels.push_back(mesh.model); }
cache.poses.Store(meshes,candidate.crestRise);
- if (getenv("ZH_WATER_HULL_TRACE") && m_modernHullTraceLines<64) {
- if(m_modernHullTraceLines==0) {
- const Coord3D &sun=TheGlobalData->m_terrainLightPos[0];const RGBColor &colour=TheGlobalData->m_terrainDiffuse[0];
- const RGBColor &ambient=TheGlobalData->m_terrainAmbient[0];
- fprintf(stderr,"water-hull-light: sun=(%.5f,%.5f,%.5f) colour=(%.5f,%.5f,%.5f) ambient=(%.5f,%.5f,%.5f) camera=(%.2f,%.2f,%.2f)\n",
- -sun.x,-sun.y,-sun.z,colour.red,colour.green,colour.blue,ambient.red,ambient.green,ambient.blue,m_modernCamera.X,m_modernCamera.Y,m_modernCamera.Z);
- for(Int lightIndex=1;lightIndex<min(3,TheGlobalData->m_numGlobalLights);++lightIndex) {
- const Coord3D &fill=TheGlobalData->m_terrainLightPos[lightIndex];
- const RGBColor &diffuse=TheGlobalData->m_terrainDiffuse[lightIndex];
- fprintf(stderr,"water-hull-fill: index=%d count=%d direction=(%.5f,%.5f,%.5f) colour=(%.5f,%.5f,%.5f)\n",
- lightIndex,TheGlobalData->m_numGlobalLights,-fill.x,-fill.y,-fill.z,diffuse.red,diffuse.green,diffuse.blue);
- }
- }
- fprintf(stderr,"water-hull: object=%u model=%s meshes=%u triangles=%u vertices=%u error=%.4f level=%.3f origin=(%.2f,%.2f,%.2f)\n",
- unsigned(candidate.objectID),candidate.model->Get_Name(),unsigned(meshes.size()),triangles,
- cache.polygon.count,cache.polygon.error,candidate.level,origin.X,origin.Y,origin.Z);
- ++m_modernHullTraceLines;
- }
+
cache.forwardSign=1.0f;
const int bow=candidate.model->Get_Bone_Index("BOWWAKE"),stern=candidate.model->Get_Bone_Index("PROPELLERWAKE");
if(bow>0 && stern>0) {
@@ -752,28 +715,7 @@ void WaterRenderObjClass::updateModernWaterHulls(void)
if(leftMax-leftMin<rightMax-rightMin) cache.forwardSign=-1.0f;
}
}
- if(traceVesselState && stateTraceRows<8 && m_modernVesselStateTraceLines<4096) {
- const AABoxClass &bounds=candidate.model->Get_Bounding_Box();
- // Model names normally contain only asset identifiers. Bound and sanitize the
- // diagnostic string so malformed names cannot create JSON/log injection.
- char modelName[129];unsigned nameLength=0;const char *sourceName=candidate.model->Get_Name();
- while(sourceName && nameLength<128 && sourceName[nameLength]) {
- const unsigned char c=(unsigned char)sourceName[nameLength];
- modelName[nameLength++]=(c>=32 && c<127 && c!='"' && c!='\\')?char(c):'_';
- }
- modelName[nameLength]='\0';
- fprintf(stderr,"water-vessel-state: {\"render\":%u,\"frame\":%u,\"object\":%u,\"model\":\"%s\",\"level\":%.6g,\"origin\":[%.6g,%.6g,%.6g],\"bounds\":[[%.6g,%.6g,%.6g],[%.6g,%.6g,%.6g]],\"axis\":[%.6g,%.6g],\"mean\":[",
- unsigned(renderFrame),unsigned(motionFrame),unsigned(candidate.objectID),modelName,candidate.level,
- origin.X,origin.Y,origin.Z,bounds.Center.X-bounds.Extent.X,bounds.Center.Y-bounds.Extent.Y,bounds.Center.Z-bounds.Extent.Z,
- bounds.Center.X+bounds.Extent.X,bounds.Center.Y+bounds.Extent.Y,bounds.Center.Z+bounds.Extent.Z,axisX,axisY);
- for(unsigned i=0;i<cache.polygon.count && i<WaterHullModel::MaxVertices;++i)
- fprintf(stderr,"%s[%.6g,%.6g]",i?",":"",cache.polygon.points[i].x,cache.polygon.points[i].y);
- fprintf(stderr,"],\"contact\":[");
- for(unsigned i=0;i<cache.contact.count && i<WaterHullModel::MaxVertices;++i)
- fprintf(stderr,"%s[%.6g,%.6g]",i?",":"",cache.contact.points[i].x,cache.contact.points[i].y);
- fprintf(stderr,"]}\n");
- ++stateTraceRows;++m_modernVesselStateTraceLines;
- }
+
if(cache.polygon.count<3) continue;
const WaterVesselMotion::Point initialVelocity=candidate.object->initialVelocity;
const WaterVesselMotion::State previousMotion=cache.motion;
@@ -826,7 +768,7 @@ void WaterRenderObjClass::updateModernWaterHulls(void)
m_modernFoamHistory.Observe((UnsignedInt)candidate.objectID,contactHull,m_modernWaveTime,TRUE,resetMotion,&motionPosition);
if(candidate.influenceVisible && m_modernHulls.size()<WaterHullModel::MaxHulls) {
WaterHullVisual::Packet visualPacket={};
- if(visualContact) {
+ {
// A separate cache keeps the mean-water clearance, pressure and history unchanged.
// Only the eight admitted shader hulls collect full reachable visual geometry.
const float bound=WaterFftGeometry::MaxVerticalDisplacement;
@@ -871,134 +813,10 @@ void WaterRenderObjClass::updateModernWaterHulls(void)
const float deltaX=contactHull.data[0][0]-origin.X,deltaY=contactHull.data[0][1]-origin.Y;
WaterHullVisual::Reframe(cache.visual,deltaX*axisX+deltaY*axisY,
-deltaX*axisY+deltaY*axisX,visualPacket);
- if(getenv("ZH_WATER_HULL_TRACE") && !m_renderingMirror && m_modernVisualHullTraceLines<128 &&
- cache.visualTraceFrame!=motionFrame && (m_modernVisualHullTraceLines<8 || motionFrame%30==0)) {
- fprintf(stderr,"water-hull-visual: frame=%u object=%u slot=%u complete=%d reused=%d vertices=%.0f triangles=%.0f radius=%.5f valid=%.0f\n",
- unsigned(motionFrame),unsigned(candidate.objectID),unsigned(m_modernHulls.size()),int(complete),int(reusable),
- visualPacket.metadata[0],visualPacket.metadata[1],visualPacket.metadata[2],visualPacket.metadata[3]);
- ++m_modernVisualHullTraceLines;
- cache.visualTraceFrame=motionFrame;
- }
- }
- if(visualContact) m_modernVisualHulls.push_back(visualPacket);
- // Diagnostic only. Insert inside the selected-hull branch, before m_modernHulls.push_back.
- // Every traversal and output is opt-in and bounded. No rendering/simulation data is mutated.
- const char *meshTraceOption=getenv("ZH_WATER_CONTACT_MESH_DUMP");
- if(meshTraceOption && meshTraceOption[0]=='1' && meshTraceOption[1]=='\0' && !m_renderingMirror) {
- auto auditUnsigned=[](const char *&s,unsigned &value)->bool {
- if(!s || *s<'0' || *s>'9') return false;
- value=0;
- while(*s>='0' && *s<='9') {
- if(value>100000000U) return false;
- value=value*10+unsigned(*s++-'0');
- }
- return true;
- };
- const char *frameList=getenv("ZH_WATER_CONTACT_MESH_FRAMES");
- if(!frameList) frameList="201,381";
- bool wantedFrame=false,validOptions=true;unsigned frameCount=0;
- while(*frameList && validOptions) {
- unsigned requested=0;
- validOptions=++frameCount<=8 && auditUnsigned(frameList,requested);
- wantedFrame=wantedFrame || (validOptions && requested==motionFrame);
- if(validOptions && *frameList==',') { ++frameList;if(!*frameList) validOptions=false; }
- else if(*frameList) validOptions=false;
- }
- const char *objectOption=getenv("ZH_WATER_CONTACT_MESH_OBJECT");
- unsigned requestedObject=0;bool wantedObject=true;
- if(objectOption) {
- validOptions=validOptions && auditUnsigned(objectOption,requestedObject) && !*objectOption;
- wantedObject=requestedObject==unsigned(candidate.objectID);
- }
- struct AuditKey { unsigned frame,object; };
- static AuditKey emitted[64];static unsigned emittedCount=0;
- bool seen=false;
- for(unsigned i=0;i<emittedCount;++i)
- seen=seen || (emitted[i].frame==motionFrame && emitted[i].object==unsigned(candidate.objectID));
- if(validOptions && wantedFrame && wantedObject && !seen && emittedCount<64) {
- emitted[emittedCount++]={unsigned(motionFrame),unsigned(candidate.objectID)};
- // This diagnostic collector's temporary Z origin is mean-V. Restore mean-relative Z
- // explicitly below. The existing cached collector and every production packet stay intact.
- const float auditV=WaterFftGeometry::MaxVerticalDisplacement;
- std::vector<WaterHullMesh> auditMeshes;unsigned auditVisited=0;
- bool complete=CollectWaterHullMeshes(candidate.model,origin,axisX,axisY,
- candidate.level-auditV,2.0f*auditV,auditMeshes,auditVisited);
- const char *reason=complete?"ok":"collector_limit_or_invalid_pose";
- struct AuditTriangle { WaterHullModel::Point3 p[3]; };
- std::vector<AuditTriangle> auditTriangles;
- if(complete) for(const WaterHullMesh &mesh:auditMeshes) {
- const unsigned count=mesh.model->Get_Polygon_Count();
- if(count>WaterHullModel::MaxSliceTriangles-auditTriangles.size()) {
- complete=false;reason="triangle_limit";break;
- }
- const Vector3 *vertices=mesh.model->Get_Vertex_Array();
- const TriIndex *indices=mesh.model->Get_Polygon_Array();
- if(!vertices || !indices) { complete=false;reason="missing_arrays";break; }
- for(unsigned ti=0;ti<count;++ti) {
- AuditTriangle triangle;
- for(unsigned vi=0;vi<3;++vi) {
- if(indices[ti][vi]>=mesh.model->Get_Vertex_Count()) {
- complete=false;reason="invalid_index";break;
- }
- triangle.p[vi]=WaterHullPoint(mesh,vertices[indices[ti][vi]]);
- triangle.p[vi].z-=auditV;
- const auto &p=triangle.p[vi];
- if(!std::isfinite(p.x)||!std::isfinite(p.y)||!std::isfinite(p.z)||
- fabs(p.x)>1.0e6f||fabs(p.y)>1.0e6f||fabs(p.z)>1.0e6f) {
- complete=false;reason="invalid_vertex";break;
- }
- }
- if(!complete) break;
- auditTriangles.push_back(triangle);
- }
- if(!complete) break;
- }
- if(!complete) auditTriangles.clear(); // never present a partial soup as complete
- char auditName[129];unsigned auditNameLength=0;const char *auditSourceName=candidate.model->Get_Name();
- while(auditSourceName && auditNameLength<128 && auditSourceName[auditNameLength]) {
- const unsigned char c=(unsigned char)auditSourceName[auditNameLength];
- auditName[auditNameLength++]=(c>=32 && c<127 && c!='"' && c!='\\')?char(c):'_';
- }
- auditName[auditNameLength]='\0';
- fprintf(stderr,"water-contact-mesh: {\"version\":1,\"frame\":%u,\"render\":%u,\"time\":%.9g,\"object\":%u,\"model\":\"%s\",\"complete\":%s,\"reason\":\"%s\",\"level\":%.9g,\"range\":[%.9g,%.9g],\"origin\":[%.9g,%.9g,%.9g],\"axis\":[%.9g,%.9g],\"crestCap\":%.9g,\"meshes\":%u,\"visited\":%u,\"frameSize\":[%d,%d],\"contactFrame\":[%.9g,%.9g,%.9g,%.9g],\"mean\":[",
- unsigned(motionFrame),unsigned(renderFrame),double(m_modernWaveTime),unsigned(candidate.objectID),auditName,
- complete?"true":"false",reason,double(candidate.level),double(-auditV),double(auditV),
- double(origin.X),double(origin.Y),double(origin.Z),double(axisX),double(axisY),double(candidate.crestRise),
- unsigned(auditMeshes.size()),auditVisited,m_modernProjectedWidth,m_modernProjectedHeight,
- double((contactHull.data[0][0]-origin.X)*axisX+(contactHull.data[0][1]-origin.Y)*axisY),
- double(-(contactHull.data[0][0]-origin.X)*axisY+(contactHull.data[0][1]-origin.Y)*axisX),
- double(contactHull.data[1][2]),double(contactHull.data[1][3]));
- for(unsigned i=0;i<cache.polygon.count;++i)
- fprintf(stderr,"%s[%.9g,%.9g]",i?",":"",double(cache.polygon.points[i].x),double(cache.polygon.points[i].y));
- fprintf(stderr,"],\"slab\":[");
- for(unsigned i=0;i<cache.contact.count;++i)
- fprintf(stderr,"%s[%.9g,%.9g]",i?",":"",double(cache.contact.points[i].x),double(cache.contact.points[i].y));
- fprintf(stderr,"],\"camera\":");
- if(m_modernRenderCamera) {
- Matrix3D auditView;m_modernRenderCamera->Get_View_Matrix(&auditView);
- const Matrix4x4 &auditProjection=m_modernRenderCamera->Get_Projection_Matrix();
- Vector2 auditViewportMin,auditViewportMax;m_modernRenderCamera->Get_Viewport(auditViewportMin,auditViewportMax);
- fprintf(stderr,"{\"convention\":\"column_vector\",\"viewport\":[%.9g,%.9g,%.9g,%.9g],\"view\":[",
- double(auditViewportMin.X),double(auditViewportMin.Y),double(auditViewportMax.X),double(auditViewportMax.Y));
- for(unsigned r=0;r<3;++r) for(unsigned c=0;c<4;++c)
- fprintf(stderr,"%s%.9g",r||c?",":"",double(auditView[r][c]));
- fprintf(stderr,"],\"projection\":[");
- for(unsigned r=0;r<4;++r) for(unsigned c=0;c<4;++c)
- fprintf(stderr,"%s%.9g",r||c?",":"",double(auditProjection[r][c]));
- fprintf(stderr,"]}");
- } else fprintf(stderr,"null");
- fprintf(stderr,",\"triangles\":[");
- for(size_t ti=0;ti<auditTriangles.size();++ti) {
- fprintf(stderr,"%s[",ti?",":"");
- for(unsigned vi=0;vi<3;++vi) {
- const auto &p=auditTriangles[ti].p[vi];
- fprintf(stderr,"%s[%.9g,%.9g,%.9g]",vi?",":"",double(p.x),double(p.y),double(p.z));
- }
- fprintf(stderr,"]");
- }
- fprintf(stderr,"]}\n");
- }
+
}
+ m_modernVisualHulls.push_back(visualPacket);
+
m_modernHulls.push_back(hull);
m_modernContactHulls.push_back(contactHull);
m_modernHullObjectIDs.push_back((UnsignedInt)candidate.objectID);
@@ -1023,10 +841,6 @@ void WaterRenderObjClass::invalidateModernWaterShore(void)
m_modernShoreHistory.Clear();
m_modernShoreSource.Clear();
m_modernShoreReady = FALSE;
- m_modernCoastalDomain = WaterCoastalDomain::Domain();
- m_modernCoastalRevision = 0;
- m_modernCoastalReady = m_modernCoastalViewReady = FALSE;
- m_modernCoastalLookup.clear();
if (++m_modernShoreRevision == 0) m_modernShoreRevision = 1;
m_modernShoreAttempted = 0;
for (ModernFoamTexture &field : m_modernFoamTextures) field.valid = FALSE;
@@ -1058,25 +872,6 @@ void WaterRenderObjClass::updateModernWaterShore(void)
fields.push_back({level, &field.shoreContext});
break;
}
- // The broader physical coast is independent of the old authored rim alpha.
- const char *surf = getenv("ZH_WATER_SURF_GPU");
- if (surf && strcmp(surf, "1") == 0 && fields.size() == levels.size()) {
- WaterCoastalDomain::Domain coastal;
- const auto status = coastal.Build(m_modernHeights.data(), m_modernHeightWidth, m_modernHeightHeight,
- m_modernHeightBorder, MAP_XY_FACTOR, MAP_HEIGHT_SCALE, m_modernOpticalPolygons, fields);
- if (status == WaterShoreHistory::BuildResult::Ready && !coastal.Nodes().empty()) {
- // Process-wide identity prevents a new map/object reusing an immutable GPU revision.
- static uint64_t nextCoastalRevision = 0;
- if (++nextCoastalRevision == 0) ++nextCoastalRevision;
- m_modernCoastalRevision = nextCoastalRevision;
- m_modernCoastalDomain = std::move(coastal);
- m_modernCoastalReady = TRUE;
- m_modernCoastalViewReady = FALSE;
- }
- fprintf(stderr, "water-surf-domain: revision=%llu result=%u nodes=%u levels=%u spacing=%.3f\n",
- (unsigned long long) m_modernCoastalRevision, unsigned(status), unsigned(m_modernCoastalDomain.Nodes().size()),
- unsigned(fields.size()), m_modernCoastalDomain.Grid().spacing);
- }
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);
@@ -1089,13 +884,8 @@ void WaterRenderObjClass::updateModernWaterShore(void)
m_modernShoreReady = TRUE;
}
}
- } else if (levels.size() > WaterShoreHistory::MaxLevels) result = WaterShoreHistory::BuildResult::TooManyLevels;
- if (getenv("ZH_WATER_SHORE_TRACE") || !m_modernShoreReady)
- fprintf(stderr, "water-shore-domain: revision=%llu result=%u cells=%u edges=%u levels=%u tiles=%u support_vertices=%u support_work=%u\n",
- (unsigned long long) m_modernShoreRevision, unsigned(result), unsigned(m_modernShoreHistory.Domain().Cells().size()),
- unsigned(m_modernShoreHistory.Domain().Edges().size()), unsigned(levels.size()),
- unsigned(m_modernShoreSource.Support().TileCount()), unsigned(m_modernShoreSource.Support().VertexCount()),
- unsigned(m_modernShoreSource.Support().Work()));
+ }
+
}
if (m_modernShoreReady && m_modernShoreHistory.ValidFor(m_modernShoreRevision)) {
const auto result = m_modernShoreHistory.Advance(m_modernWaveTime, m_modernShoreSource);
@@ -1111,11 +901,8 @@ void WaterRenderObjClass::bindModernWaterFoam(Real level, Bool river)
#if defined(__linux__)
D3DXVECTOR4 area(0, 0, 0, 0), parameters(0, level, 0, m_modernWaveTime);
TextureClass *texture = NULL;
- const char *enabled = getenv("ZH_WATER_FOAM_HISTORY");
- const char *shoreEnabled = getenv("ZH_WATER_SHORE_HISTORY"), *shoreSource = getenv("ZH_WATER_SHORE_FOAM");
- const Bool vessel = (!enabled || strcmp(enabled, "0") != 0) && m_modernFoamHistory.HasFoam();
- const Bool coast = (!shoreEnabled || strcmp(shoreEnabled, "0") != 0) && (!shoreSource || strcmp(shoreSource, "0") != 0)
- && m_modernShoreReady && m_modernShoreHistory.ValidFor(m_modernShoreRevision)
+ const Bool vessel = m_modernFoamHistory.HasFoam();
+ const Bool coast = m_modernShoreReady && m_modernShoreHistory.ValidFor(m_modernShoreRevision)
&& !m_modernShoreHistory.Domain().Cells().empty();
const unsigned channels = ((vessel ? 1 : 0)|(coast ? 2 : 0))|((vessel || coast) ? 4 : 0);
if (!river && channels && m_modernRenderCamera) {
@@ -1159,32 +946,6 @@ void WaterRenderObjClass::bindModernWaterFoam(Real level, Bool river)
coverage, pixels, m_modernShoreSource.Support());
}
if (atlas) {
- // Optional native capture evidence: report elapsed water time and the actual
- // uploaded coverage, without reading any GPU resource back to the CPU.
- if (getenv("ZH_WATER_FOAM_TRACE") && floor(field.timestamp) != floor(m_modernWaveTime)) {
- unsigned covered = 0, peak = 0;
- double total = 0;
- for (std::uint32_t pixel : pixels) {
- const unsigned r = (pixel >> 16) & 255;
- covered += r > 0;
- peak = max(peak, r);
- total += r;
- }
- fprintf(stderr, "water-foam: time=%.3f level=%.3f segments=%u emitters=%u covered=%u peak=%u sum=%.0f area=(%.1f,%.1f,%.1f,%.1f)\n",
- m_modernWaveTime, level, unsigned(m_modernFoamHistory.SegmentCount()), unsigned(m_modernFoamHistory.TrackedCount()),
- covered, peak, total, map.originX, map.originY, map.widthWorld, map.heightWorld);
- for (size_t h = 0; h < m_modernHulls.size(); ++h) {
- const WaterHullModel::Hull &hull = m_modernHulls[h];
- fprintf(stderr, "water-foam-hull: time=%.3f object=%u center=(%.2f,%.2f) half-size=(%.2f,%.2f) velocity=(%.2f,%.2f) ends=(%.2f,%.2f,%.2f,%.2f)\n",
- m_modernWaveTime, m_modernHullObjectIDs[h], hull.data[0][0], hull.data[0][1], hull.data[1][2], hull.data[1][3],
- hull.data[2][0], hull.data[2][1], hull.data[3][0], hull.data[3][1], hull.data[3][2], hull.data[3][3]);
- const WaterHullModel::Hull &contact = m_modernContactHulls[h];
- fprintf(stderr, "water-foam-contact: time=%.3f object=%u center=(%.2f,%.2f) half-size=(%.2f,%.2f) ends=(%.2f,%.2f,%.2f,%.2f)\n",
- m_modernWaveTime, m_modernHullObjectIDs[h], contact.data[0][0], contact.data[0][1], contact.data[1][2],
- contact.data[1][3],
- contact.data[3][0], contact.data[3][1], contact.data[3][2], contact.data[3][3]);
- }
- }
// Merge coastal alpha before appending the direction tile: its rasterizer
// owns exactly the original logical window. Both tiles share one upload/lifetime.
pixels.insert(pixels.end(), direction.begin(), direction.end());
@@ -1231,48 +992,6 @@ void WaterRenderObjClass::bindModernWaterFoam(Real level, Bool river)
#endif
}
-void WaterRenderObjClass::bindModernWaterCoastal(Real level, Bool river)
-{
-#if defined(__linux__)
- auto *device = DX8Wrapper::_Get_D3D_Device();
- PosixWaterCoastalEnd(device);
- const char *option = getenv("ZH_WATER_SURF_GPU");
- if (river || !option || strcmp(option, "1") != 0
- || !m_modernCoastalReady || !m_modernRenderCamera)
- return;
-
- const Vector2 ndc[5] = {
- Vector2(0, 0), Vector2(-1, -1), Vector2(1, -1), Vector2(1, 1), Vector2(-1, 1)
- };
- WaterFoamWindow::Point rays[5];
- for (unsigned i = 0; i < 5; ++i) {
- Vector3 target;
- m_modernRenderCamera->Un_Project(target, ndc[i]);
- const Vector3 direction = target - m_modernCamera;
- rays[i] = {direction.X, direction.Y, direction.Z};
- }
- const auto window = WaterFoamWindow::Choose(
- {
- m_modernCamera.X, m_modernCamera.Y, m_modernCamera.Z
- }, rays, level);
- const WaterShoreHistory::Mapping mapping = {
- window.originX, window.originY, window.widthWorld, window.heightWorld,
- window.widthPixels, window.heightPixels
- };
- if (!m_modernCoastalViewReady || m_modernCoastalViewLevel != level
- || !WaterCoastalView::SameMapping(mapping, m_modernCoastalMapping)) {
- m_modernCoastalViewReady = WaterCoastalView::Build(
- m_modernCoastalDomain, mapping, level, m_modernCoastalLookup);
- if (m_modernCoastalViewReady) {
- m_modernCoastalMapping = mapping;
- m_modernCoastalViewLevel = level;
- }
- }
- if (m_modernCoastalViewReady)
- PosixWaterCoastalBind(device, m_modernCoastalRevision, m_modernCoastalDomain,
- m_modernCoastalMapping, level, m_modernCoastalLookup);
-#endif
-}
void WaterRenderObjClass::registerWaterStyleShaders(void)
{
@@ -1310,8 +1029,6 @@ void WaterRenderObjClass::synchronizeWaterStyle(void)
m_modernObstacles.clear();
m_modernPatchObstacles.clear();
m_modernObstacleIndex.Clear();
- m_modernProfile = ModernWaterProfile();
- m_modernProfileEnabled = FALSE;
// Classic clears the mirror to white; Modern clears it transparent. Bypass the
// stationary-camera reuse once, so neither style samples the other's background.
@@ -1385,7 +1102,7 @@ void WaterRenderObjClass::setupModernWaterShader(Bool river, Bool heightCorrecti
DX8Wrapper::_Get_D3D_Device()->SetPixelShaderConstantF(96, &m_modernContactHulls[0].data[0][0],
m_modernContactHulls.size() * WaterHullModel::RegistersPerHull);
}
- if (WaterHullVisual::Enabled()) {
+ {
// Every slot is initialized, including absent hulls and river draws. The backend takes
// immutable draw snapshots before a different surface can replace these registers.
float metadata[WaterHullVisualLayout::MaxHulls][4] = {};
@@ -1401,7 +1118,6 @@ void WaterRenderObjClass::setupModernWaterShader(Bool river, Bool heightCorrecti
}
DX8Wrapper::Set_DX8_Texture(4, optical ? optical->Peek_D3D_Texture() : NULL);
bindModernWaterFoam(m_modernOpticalLevel, river);
- bindModernWaterCoastal(m_modernOpticalLevel, river);
TextureClass *heightTexture = m_modernHeightTexture;
if (waveCage && !river && heightCorrection)
for (const ModernOpticalTexture &cached : m_modernOpticalTextures)
@@ -1575,8 +1291,7 @@ TextureClass *WaterRenderObjClass::modernWaterOpticalTexture(Real level)
if (!bits) { REF_PTR_RELEASE(texture); return NULL; }
ModernOpticalTexture &cached=m_modernOpticalTextures.back();
cached.texture=texture;
- const char *waveCageOption=getenv("ZH_WATER_WAVE_CAGES");
- if(WaterFftSampling::Enabled() && (!waveCageOption || strcmp(waveCageOption,"0")!=0)) {
+ {
WaterWaveCage::Field cage;
if(WaterWaveCage::Build(m_modernHeights.data(),m_modernHeightWidth,m_modernHeightHeight,
m_modernHeightBorder,MAP_XY_FACTOR,MAP_HEIGHT_SCALE,level,field,cage)) {
@@ -1615,7 +1330,6 @@ TextureClass *WaterRenderObjClass::modernWaterOpticalTexture(Real level)
-
//-------------------------------------------------------------------------------------------------
/** Destructor. Releases w3d assets. */
//-------------------------------------------------------------------------------------------------
@@ -1791,7 +1505,7 @@ RenderResult WaterRenderObjClass::initBumpMap(LPDIRECT3DTEXTURE9 *pTex, TextureC
// DEBUG_CRASH(("WaterRenderObjClass::Invalid BumpMap format - Was it compressed?") );
return D3D_OK;
}
-
+
if (pBumpSource->Peek_D3D_Texture())
{
numLevels=pBumpSource->Peek_D3D_Texture()->GetLevelCount();
@@ -2126,7 +1840,6 @@ RenderResult WaterRenderObjClass::generateIndexBuffer(Int sizeX, Int sizeY)
m_numIndices=psize*((psize+1)*2)+(psize*2)-2;
-
Int x,z,s_toggle=1;
for (z=step; z<size; z+=step)
{
@@ -2201,7 +1914,7 @@ void WaterRenderObjClass::ReleaseResources(void)
{ m_waveVertexDeclaration->Release();
m_waveVertexDeclaration=NULL;
}
-
+
if (m_waterPixelShader)
m_waterPixelShader->Release();
@@ -2497,7 +2210,6 @@ Int WaterRenderObjClass::init(Real waterLevel, Real dx, Real dy, SceneClass *par
//Setup material for regular water
m_vertexMaterialClass=VertexMaterialClass::Get_Preset(VertexMaterialClass::PRELIT_DIFFUSE);
-
m_shaderClass = zFillAlphaShader;//ShaderClass::_PresetAlphaShader;ShaderClass::_PresetOpaqueShader;//detailOpaqueShader;
@@ -2743,7 +2455,6 @@ void WaterRenderObjClass::update( void )
} // end update
-
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
void WaterRenderObjClass::replaceSkyboxTexture(const AsciiString& oldTexName, const AsciiString& newTextName)
@@ -2790,7 +2501,7 @@ void WaterRenderObjClass::loadSetting( Setting *setting, TimeOfDay timeOfDay )
// sanity
DEBUG_ASSERTCRASH( setting, ("WaterRenderObjClass::loadSetting, NULL setting\n") );
-
+
// textures
setting->skyTexture = WW3DAssetManager::Get_Instance()->Get_Texture( WaterSettings[ timeOfDay ].m_skyTextureFile.str() );
setting->waterTexture = WW3DAssetManager::Get_Instance()->Get_Texture( WaterSettings[ timeOfDay ].m_waterTextureFile.str() );
@@ -2976,7 +2687,6 @@ void WaterRenderObjClass::renderMirror(CameraClass *cam, Real level)
//generate a new camera matrix from reflected vectors
Matrix3D reflectedTransform(rRight,rUp,rN,rPos);
-
DX8Wrapper::Set_Render_Target_With_Z((TextureClass*)m_pReflectionTexture);
// Clear the backbuffer
@@ -3059,12 +2769,6 @@ void WaterRenderObjClass::renderMirror(CameraClass *cam, Real level)
* This algorithm doesn't apply to translucent water, which is rendered into a
* texture and rendered at end of scene. */
//-------------------------------------------------------------------------------------------------
-#if defined(__linux__)
-static double modernWaterProfileMilliseconds()
-{
- return std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now().time_since_epoch()).count();
-}
-#endif
DECLARE_PERF_TIMER(Water)
void WaterRenderObjClass::Render(RenderInfoClass & rinfo)
{
@@ -3102,9 +2806,7 @@ void WaterRenderObjClass::Render(RenderInfoClass & rinfo)
WaterShoreOverlay::Scope shoreScope(DX8Wrapper::_Get_D3D_Device(),
m_useModernWater && m_waterType==WATER_TYPE_0_TRANSLUCENT && m_trapezoidWaterPixelShader &&
!TheGlobalData->m_isWorldBuilder && !TheGlobalData->m_usingWaterTrackEditor);
- m_modernProfileEnabled=m_useModernWater && std::getenv("ZH_WATER_PROFILE")!=NULL;
m_modernFoamDrawFrame=~0u;m_modernFoamDrawObjectIDs.clear();
- const double profileRenderStart=m_modernProfileEnabled?modernWaterProfileMilliseconds():0;
RenderUInt32 oldModernCoordIndex=0,oldModernTransformFlags=0;
RenderUInt32 oldModernBaseCoordIndex=0,oldModernBaseTransformFlags=0;
IDirect3DBaseTexture9 *oldModernBed=NULL,*oldModernOptical=NULL,*oldModernFoam=NULL;
@@ -3179,22 +2881,16 @@ void WaterRenderObjClass::Render(RenderInfoClass & rinfo)
// stale terrain, moving hulls, wave time or camera state from a previous render.
m_modernProjectedSamples.clear();
m_modernObstacleIndex.Clear();
- m_modernProjectedVertices=m_modernProjectedTriangles=m_modernProjectedFallbacks=m_modernRetainedVertices=m_modernProjectedEvaluations=0;
+
m_modernProjectedCacheEnabled=visibleFlatPatches>1;
- m_modernBowVertices=m_modernBowTriangles=m_modernBowRegions=m_modernBowDenied=m_modernBowRejected=0;
+ m_modernBowVertices=m_modernBowTriangles=0;
m_modernBowAdmissions.Begin(m_modernWaveTime);
- double profilePhaseStart=0;
- if (m_modernProfileEnabled) {
- profilePhaseStart=modernWaterProfileMilliseconds();
- m_modernProfile.setup+=profilePhaseStart-profileRenderStart;
- }
+
updateModernWaterHulls();
- if (m_modernProfileEnabled) {
- const double now=modernWaterProfileMilliseconds();m_modernProfile.hulls+=now-profilePhaseStart;profilePhaseStart=now;
- }
+
for (size_t i=0;i<m_modernObstacles.size();++i)
m_modernObstacles[i].hasHull=modernHasHull(m_modernObstacleObjectIDs[i]);
- if (m_modernProfileEnabled) m_modernProfile.obstacles+=modernWaterProfileMilliseconds()-profilePhaseStart;
+
}
#endif
@@ -3353,13 +3049,7 @@ void WaterRenderObjClass::Render(RenderInfoClass & rinfo)
DX8Wrapper::Set_DX8_Texture(14,oldModernFoam);
if(oldModernFoam) oldModernFoam->Release();
m_modernBowAdmissions.End();
- if (std::getenv("ZH_WATER_MESH_STATS")) {
- static UnsignedInt reports=0;
- if ((reports++%120)==0) fprintf(stderr,"[water-mesh] lattice=%dx%d projected_vertices=%zu evaluated_samples=%zu triangles=%zu retained_vertices=%zu fallbacks=%zu bow_vertices=%zu bow_triangles=%zu bow_regions=%zu bow_denied=%zu bow_rejected=%zu\n",
- m_modernProjectedColumns,m_modernProjectedRows,m_modernProjectedVertices,m_modernProjectedEvaluations,
- m_modernProjectedTriangles,m_modernRetainedVertices,m_modernProjectedFallbacks,
- m_modernBowVertices,m_modernBowTriangles,m_modernBowRegions,m_modernBowDenied,m_modernBowRejected);
- }
+
m_modernRenderCamera=NULL;
}
#endif
@@ -3380,26 +3070,7 @@ void WaterRenderObjClass::Render(RenderInfoClass & rinfo)
if (m_waterTrackSystem)
m_waterTrackSystem->flush(rinfo);
#if defined(__linux__)
- if (m_modernProfileEnabled) {
- m_modernProfile.render+=modernWaterProfileMilliseconds()-profileRenderStart;
- m_modernProfile.vertices+=m_modernProjectedVertices+m_modernRetainedVertices;
- m_modernProfile.triangles+=m_modernProjectedTriangles;
- if (++m_modernProfile.frames>=120) {
- const double frames=double(m_modernProfile.frames);
- fprintf(stderr,"[water-profile] frames=%zu render_ms=%.4f setup_ms=%.4f hulls_ms=%.4f obstacles_ms=%.4f projected_mesh_ms=%.4f vertex_fill_ms=%.4f submit_ms=%.4f vertices=%.1f projected_triangles=%.1f patches=%.1f\n",
- m_modernProfile.frames,m_modernProfile.render/frames,m_modernProfile.setup/frames,
- m_modernProfile.hulls/frames,m_modernProfile.obstacles/frames,m_modernProfile.mesh/frames,
- m_modernProfile.fill/frames,m_modernProfile.submit/frames,m_modernProfile.vertices/frames,
- m_modernProfile.triangles/frames,m_modernProfile.patches/frames);
- const double scale=m_modernProfile.samples?double(m_modernProfile.attempts)/(m_modernProfile.samples*frames):0;
- fprintf(stderr,"[water-profile-sampled] samples=%zu field_ms=%.4f damping_ms=%.4f wave_ms=%.4f cache_ms=%.4f patch_obstacles=%.1f misses=%.1f hits=%.1f wave_points=%.1f\n",
- m_modernProfile.samples,m_modernProfile.fieldSample*scale,m_modernProfile.dampingSample*scale,
- m_modernProfile.waveSample*scale,m_modernProfile.cacheSample*scale,
- m_modernProfile.patches?double(m_modernProfile.patchObstacles)/m_modernProfile.patches:0,
- m_modernProfile.misses/frames,m_modernProfile.hits/frames,m_modernProfile.wavePoints/frames);
- m_modernProfile=ModernWaterProfile();
- }
- }
+
#endif
// renderWaterMesh();
@@ -3472,7 +3143,6 @@ void WaterRenderObjClass::drawSea(RenderInfoClass & rinfo)
DX8Wrapper::Set_Texture(0,NULL); //we'll be setting our own textures, so reset W3D
DX8Wrapper::Set_Texture(1,NULL); //we'll be setting our own textures, so reset W3D
-
DX8Wrapper::Apply_Render_State_Changes(); //force update of view and projection matrices
Vector3 camTran;
@@ -3663,7 +3333,6 @@ void WaterRenderObjClass::drawSea(RenderInfoClass & rinfo)
}
-
#define FEATHER_LAYER_COUNT (5.0f)
#define FEATHER_THICKNESS (4.0f)
@@ -3722,7 +3391,6 @@ void WaterRenderObjClass::renderWater(void)
else
drawTrapezoidWater(points);
-
}
}
}
@@ -3756,7 +3424,6 @@ void WaterRenderObjClass::renderSky(void)
fu= m_uOffset + (SKYPLANE_SIZE * 2) * setting->skyTexelsPerUnit;
fv= m_vOffset + (SKYPLANE_SIZE * 2) * setting->skyTexelsPerUnit;
-
VertexMaterialClass *vmat=VertexMaterialClass::Get_Preset(VertexMaterialClass::PRELIT_DIFFUSE);
DX8Wrapper::Set_Material(vmat);
REF_PTR_RELEASE(vmat);
@@ -3783,21 +3450,21 @@ void WaterRenderObjClass::renderSky(void)
verts[0].u1=m_uOffset;
verts[0].v1=fv;
verts[0].diffuse=setting->vertex01Diffuse;
-
+
verts[1].x=SKYPLANE_SIZE;
verts[1].y=SKYPLANE_SIZE;
verts[1].z=SKYPLANE_HEIGHT;
verts[1].u1=fu;
verts[1].v1=fv;
verts[1].diffuse=setting->vertex11Diffuse;
-
+
verts[2].x=SKYPLANE_SIZE;
verts[2].y=-SKYPLANE_SIZE;
verts[2].z=SKYPLANE_HEIGHT;
verts[2].u1=fu;
verts[2].v1=m_vOffset;
verts[2].diffuse=setting->vertex10Diffuse;
-
+
verts[3].x=-SKYPLANE_SIZE;
verts[3].y=-SKYPLANE_SIZE;
verts[3].z=SKYPLANE_HEIGHT;
@@ -3848,15 +3515,12 @@ void WaterRenderObjClass::renderSkyBody(Matrix3D *mat)
angle = acos(angle);
-
Matrix3D tm(1);
tm.Set(rotAxis,angle);
tm.Adjust_Translation(Vector3(SKYBODY_X,SKYBODY_Y,SKYBODY_HEIGHT));
-
DX8Wrapper::Set_Transform(D3DTS_WORLD,tm);
-
VertexMaterialClass *vmat=VertexMaterialClass::Get_Preset(VertexMaterialClass::PRELIT_DIFFUSE);
DX8Wrapper::Set_Material(vmat);
REF_PTR_RELEASE(vmat);
@@ -3868,7 +3532,6 @@ void WaterRenderObjClass::renderSkyBody(Matrix3D *mat)
DX8Wrapper::Set_Shader(m_shader2);
-
// DX8Wrapper::Set_Shader(ShaderClass::/*_PresetAdditiveShader*//*_PresetOpaqueShader*/_PresetAlphaShader);
// DX8Wrapper::Set_Texture(0,setting->skyBodyTexture);
@@ -3887,21 +3550,21 @@ void WaterRenderObjClass::renderSkyBody(Matrix3D *mat)
verts[0].u2=0;
verts[0].v2=1;
verts[0].diffuse=0xffffffff;
-
+
verts[1].x=SKYBODY_SIZE;
verts[1].y=SKYBODY_SIZE;
verts[1].z=0;
verts[1].u2=1;
verts[1].v2=1;
verts[1].diffuse=0xffffffff;
-
+
verts[2].x=SKYBODY_SIZE;
verts[2].y=-SKYBODY_SIZE;
verts[2].z=0;
verts[2].u2=1;
verts[2].v2=0;
verts[2].diffuse=0xffffffff;
-
+
verts[3].x=-SKYBODY_SIZE;
verts[3].y=-SKYBODY_SIZE;
verts[3].z=0;
@@ -4115,7 +3778,6 @@ void WaterRenderObjClass::renderWaterMesh(void)
DX8Wrapper::Apply_Render_State_Changes(); //force update of view and projection matrices
#endif
-
// DX8Wrapper::Set_DX8_Render_State(D3DRS_ZFUNC,D3DCMP_ALWAYS); //used to display grid under map.
// D3D9 takes the base vertex index on the draw call, not here.
@@ -4126,7 +3788,6 @@ void WaterRenderObjClass::renderWaterMesh(void)
Direct3D11_Mirror_Stream_Source(waterVertexTwin,sizeof(MaterMeshVertexFormat),0);
Direct3D11_Mirror_Indices(waterIndexTwin);
-
if (TheTerrainRenderObject->getShroud() && !m_trapezoidWaterPixelShader)
{ //we have a shroud to apply and can't do it inside the pixel shader.
//so do it in stage1
@@ -4155,7 +3816,6 @@ void WaterRenderObjClass::renderWaterMesh(void)
Direct3D11_Draw_Indexed_Strip(m_numIndices,0,m_vertexBufferD3DOffset);
}
-
Debug_Statistics::Record_DX8_Polys_And_Vertices(m_numIndices-2,mx*my,ShaderClass::_PresetOpaqueShader);
// DX8Wrapper::Set_DX8_Render_State(D3DRS_FILLMODE,D3DFILL_SOLID);
@@ -4224,7 +3884,6 @@ Real WaterRenderObjClass::getWaterHeight(Real x, Real y)
return INVALID_WATER_HEIGHT; //point not underwater
}
-
// 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
{
@@ -4317,28 +3976,7 @@ void WaterRenderObjClass::drawModernWaterPatch(const Vector3 points[4], Bool riv
oceanContext = &m_modernOpticalTextures[field];
break;
}
- const char *waveCageOption = getenv("ZH_WATER_WAVE_CAGES");
- const Bool waveCageAvailable = oceanContext && oceanContext->waveCage && WaterFftSampling::Enabled()
- && (!waveCageOption || strcmp(waveCageOption, "0") != 0);
- const char *coastalCrestOption = getenv("ZH_WATER_COAST_CREST");
- const Bool coastalCrestEnabled = coastalCrestOption && strcmp(coastalCrestOption, "1") == 0;
- // Only actual exposed terrain coast in the analytic R0 region participates. No new
- // texture/resource or gameplay height is introduced; this reuses the uploaded field bytes.
- auto coastalCrestHeight = [&](Real x, Real y, Real offshore, Real depth, Real obstacle, Real damping) {
- if (!coastalCrestEnabled || !WaterCoastalCrest::Eligible(river, oceanContext != NULL, offshore)
- || depth <= WaterShoreFoam::MinDepth) return 0.0f;
- const auto &field = oceanContext->shoreContext;
- if (field.coast.size() != oceanContext->ocean.size() || field.exposure.size() != field.coast.size()) return 0.0f;
- const Real gx = x / MAP_XY_FACTOR + m_modernHeightBorder, gy = y / MAP_XY_FACTOR + m_modernHeightBorder;
- const Real support = WaterSurfaceModel::SampleOffshore(field.coast.data(), m_modernHeightWidth, m_modernHeightHeight, gx, gy,
- MAP_XY_FACTOR).height;
- const Real exposure = WaterSurfaceModel::SampleOffshore(field.exposure.data(), m_modernHeightWidth, m_modernHeightHeight, gx,
- gy, MAP_XY_FACTOR).height;
- const Real encodedObstacle = WaterCoastalCrest::EncodeObstacle(obstacle);
- if (support <= 0 || exposure <= 0 || encodedObstacle - 0.5f / 255.0f <= damping) return 0.0f;
- return WaterCoastalCrest::Height(WaterShoreFoam::Evaluate(x, y, m_modernWaveTime).height,
- depth, support, exposure, encodedObstacle, damping);
- };
+ const Bool waveCageAvailable = oceanContext && oceanContext->waveCage;
const Int cells = m_modernMeshCells, side = cells + 1;
Int vertexCount = side * side;
WaterSurfaceModel::Point corners[4];
@@ -4427,11 +4065,7 @@ void WaterRenderObjClass::drawModernWaterPatch(const Vector3 points[4], Bool riv
WaterProjectedMesh::Mesh projectedMesh;
WaterFftGeometry::SeamFade fftSeam;
- const double profileMeshStart = m_modernProfileEnabled ? modernWaterProfileMilliseconds() : 0;
- if (m_modernProfileEnabled) {
- ++m_modernProfile.patches;
- m_modernProfile.patchObstacles += m_modernPatchObstacles.size();
- }
+
Bool projected = FALSE;
const float levels[4] = {points[0].Z, points[1].Z, points[2].Z, points[3].Z};
// Homography is defined on one plane. Authored sloped patches retain every original Z.
@@ -4490,8 +4124,7 @@ void WaterRenderObjClass::drawModernWaterPatch(const Vector3 points[4], Bool riv
fftSeam.Prepare(polygon, projection, {m_modernProjectedColumns, m_modernProjectedRows});
// Optional bow detail only replaces fresh interior triangles. The same submitted
// contact contours drive the shader packet and its projected geometric demand.
- // Explicit wave opt-outs must also omit work for their absent displacement field.
- if (WaterFftSampling::Enabled() && WaterVesselWaves::Enabled()) {
+ {
WaterBowRefinement::View bowView;
bowView.projection = projection;
bowView.resolution = {m_modernProjectedColumns, m_modernProjectedRows};
@@ -4532,7 +4165,7 @@ void WaterRenderObjClass::drawModernWaterPatch(const Vector3 points[4], Bool riv
prepared.cell.x > m_modernProjectedColumns + WaterBowRefinement::WindowRadius ||
prepared.cell.y > m_modernProjectedRows + WaterBowRefinement::WindowRadius) continue;
if (!WaterBowRefinement::HasRefinableDemand(projectedMesh, bowView, polygon, prepared)) continue;
- if (!m_modernBowAdmissions.Request(patchKey, bow, m_modernProjectedBudget)) ++m_modernBowDenied;
+ m_modernBowAdmissions.Request(patchKey, bow, m_modernProjectedBudget);
}
std::vector<WaterBowRefinement::Active> active;
active.reserve(WaterBowRefinement::MaxRegions);
@@ -4546,8 +4179,6 @@ void WaterRenderObjClass::drawModernWaterPatch(const Vector3 points[4], Bool riv
WaterBowRefinement::MaxAddedVertices - m_modernBowVertices, WaterBowRefinement::MaxAddedTriangles - m_modernBowTriangles);
m_modernBowVertices += bowStats.addedVertices;
m_modernBowTriangles += bowStats.addedTriangles;
- m_modernBowRegions += bowStats.regions;
- m_modernBowRejected += bowStats.rejected ? 1 : 0;
}
// Authored ocean polygons often extend beneath the entire land mass. The
// projected lattice covers that hidden area too; discard only triangles
@@ -4592,16 +4223,11 @@ void WaterRenderObjClass::drawModernWaterPatch(const Vector3 points[4], Bool riv
// Waterline clipping also leaves unreferenced dry vertices behind.
WaterTerrainCulling::CompactVertices(projectedMesh);
vertexCount = (Int) projectedMesh.vertices.size();
- m_modernProjectedVertices += vertexCount;
- m_modernProjectedTriangles += projectedMesh.indices.size() / 3;
- } else ++m_modernProjectedFallbacks; // Retain complete original coverage if projection is singular.
+ }
}
- if (m_modernProfileEnabled) m_modernProfile.mesh += modernWaterProfileMilliseconds() - profileMeshStart;
if (projected && projectedMesh.indices.empty()) return;
- if (!projected) m_modernRetainedVertices += vertexCount;
const Bool waveCage = projected && waveCageAvailable;
- const double profileFillStart = m_modernProfileEnabled ? modernWaterProfileMilliseconds() : 0;
DynamicVBAccessClass vertices(BUFFER_TYPE_DYNAMIC_DX8, dynamic_fvf_type, vertexCount);
{
DynamicVBAccessClass::WriteLockClass lock(&vertices);
@@ -4610,34 +4236,16 @@ void WaterRenderObjClass::drawModernWaterPatch(const Vector3 points[4], Bool riv
W3DShroud *shroud = TheTerrainRenderObject ? TheTerrainRenderObject->getShroud() : NULL;
if (projected) {
auto makeBaseVertex = [&](const WaterSurfaceModel::Point &p, Bool boundarySample = FALSE) {
- // Sample one in 64 vertices, with the phase rotating each render. Clock reads are
- // absent from normal runs and sparse enough not to dominate the measured work.
- const Bool sampled = m_modernProfileEnabled && ((m_modernProfile.attempts++ + m_modernProfile.frames) & 63) == 0;
- double stamp = sampled ? modernWaterProfileMilliseconds() : 0;
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();
- if (sampled) {
- const double now = modernWaterProfileMilliseconds();
- m_modernProfile.cacheSample += now - stamp;
- stamp = now;
- ++m_modernProfile.samples;
- }
ModernProjectedSample sample;
if (cached != m_modernProjectedSamples.end()) {
sample = cached->second;
- if (m_modernProfileEnabled) ++m_modernProfile.hits;
} else {
- ++m_modernProjectedEvaluations;
- if (m_modernProfileEnabled) ++m_modernProfile.misses;
const WaterSurfaceModel::Sample 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);
- if (sampled) {
- const double now = modernWaterProfileMilliseconds();
- m_modernProfile.fieldSample += now - stamp;
- stamp = now;
- }
sample.obstacle = sample.hullFreeObstacle = 1;
Real terrainDepth = 0, hullFreeDamping = 0;
sample.damping = modernWaterDamping(p.x, p.y, p.z, offshore.height, &sample.obstacle, &terrainDepth, &hullFreeDamping,
@@ -4647,22 +4255,9 @@ void WaterRenderObjClass::drawModernWaterPatch(const Vector3 points[4], Bool riv
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);
- if (sampled) {
- const double now = modernWaterProfileMilliseconds();
- m_modernProfile.dampingSample += now - stamp;
- stamp = now;
- }
sample.height = sample.damping > 0 ? WaterSurfaceModel::EvaluateBlendedHeight(p.x, p.y, m_modernWaveTime,
offshore) * sample.damping : 0;
- sample.height += coastalCrestHeight(p.x, p.y, offshore.height, terrainDepth, sample.obstacle, sample.damping);
- if (sampled) {
- const double now = modernWaterProfileMilliseconds();
- m_modernProfile.waveSample += now - stamp;
- stamp = now;
- }
- if (m_modernProfileEnabled && sample.damping > 0) ++m_modernProfile.wavePoints;
if (share && m_modernProjectedSamples.size() < WaterSurfaceModel::VertexBudget) m_modernProjectedSamples.emplace(key, sample);
- if (sampled) m_modernProfile.cacheSample += modernWaterProfileMilliseconds() - stamp;
}
VertexFormatXYZNDUV2 result;
result.x = p.x;
@@ -4818,8 +4413,7 @@ void WaterRenderObjClass::drawModernWaterPatch(const Vector3 points[4], Bool riv
}
vertex->x = p.x;
vertex->y = p.y;
- vertex->z = p.z + damping * wave.height
- + coastalCrestHeight(p.x, p.y, offshore.height, terrainDepth, obstacleAttenuation, damping);
+ vertex->z = p.z + damping * wave.height;
// The flat modern shader uses only alpha for colour/shroud. PRELIT_DIFFUSE passes RGB
// through unchanged, so red carries the obstacle profile independently of terrain.
vertex->diffuse = river ? applyShroudToRiverDiffuse(shroud, p.x, p.y, diffuse) :
@@ -4861,11 +4455,7 @@ void WaterRenderObjClass::drawModernWaterPatch(const Vector3 points[4], Bool riv
}
}
}
- double profileSubmitStart = 0;
- if (m_modernProfileEnabled) {
- profileSubmitStart = modernWaterProfileMilliseconds();
- m_modernProfile.fill += profileSubmitStart - profileFillStart;
- }
+
Matrix3D transform(1);
DX8Wrapper::Set_Transform(D3DTS_WORLD, transform);
DX8Wrapper::Set_Vertex_Buffer(vertices);
@@ -4876,8 +4466,7 @@ void WaterRenderObjClass::drawModernWaterPatch(const Vector3 points[4], Bool riv
DX8Wrapper::_Get_D3D_Device()->GetRenderState(D3DRS_CULLMODE, &cull);
DX8Wrapper::Set_DX8_Render_State(D3DRS_CULLMODE, D3DCULL_NONE);
if (TheWaterTransparency->m_additiveBlend) DX8Wrapper::Set_DX8_Render_State(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
- const char *debug = std::getenv("ZH_WATER_DEBUG");
- const Bool meshDebug = wireframeForDebug || (debug && strcmp(debug, "wireframe") == 0);
+ const Bool meshDebug = wireframeForDebug;
if (meshDebug) DX8Wrapper::Set_DX8_Render_State(D3DRS_FILLMODE, D3DFILL_WIREFRAME);
WaterShoreOverlay::Quad shorePatch;
shorePatch.level = points[0].Z;
@@ -4942,7 +4531,7 @@ void WaterRenderObjClass::drawModernWaterPatch(const Vector3 points[4], Bool riv
DX8Wrapper::Set_DX8_Render_State(D3DRS_ZFUNC, D3DCMP_EQUAL);
}
DX8Wrapper::Set_DX8_Render_State(D3DRS_CULLMODE, cull);
- if (m_modernProfileEnabled) m_modernProfile.submit += modernWaterProfileMilliseconds() - profileSubmitStart;
+
#endif
}
@@ -5179,7 +4768,6 @@ void WaterRenderObjClass::drawRiverWater(PolygonTrigger *pTrig)
DX8Wrapper::Set_DX8_Render_State(D3DRS_CULLMODE, D3DCULL_NONE);
-
if (wireframeForDebug) {
DX8Wrapper::Set_DX8_Render_State(D3DRS_FILLMODE,D3DFILL_WIREFRAME);
}
@@ -5200,7 +4788,6 @@ void WaterRenderObjClass::drawRiverWater(PolygonTrigger *pTrig)
// used to apply it here darkened the banks twice.
DX8Wrapper::Set_DX8_Render_State(D3DRS_CULLMODE, cull);
-
}
//-------------------------------------------------------------------------------------------------
@@ -5314,7 +4901,7 @@ void WaterRenderObjClass::setupFlatWaterShader(Bool heightCorrection,Bool waveCa
DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DTSS_ALPHAOP, D3DTOP_ADD );
DX8Wrapper::Set_DX8_Texture_Stage_State(0, D3DTSS_TEXCOORDINDEX, 0);
DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DTSS_TEXCOORDINDEX, 0);
-
+
Bool doSparkles = true;
if (m_trapezoidWaterPixelShader && doSparkles) {
@@ -5331,7 +4918,7 @@ void WaterRenderObjClass::setupFlatWaterShader(Bool heightCorrection,Bool waveCa
DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DSAMP_ADDRESSU, D3DTADDRESS_WRAP);
DX8Wrapper::Set_DX8_Texture_Stage_State(1, D3DSAMP_ADDRESSV, D3DTADDRESS_WRAP);
-
+
DX8Wrapper::Set_DX8_Texture_Stage_State(2, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_CAMERASPACEPOSITION);
// Two output coordinates are used.
DX8Wrapper::Set_DX8_Texture_Stage_State(2, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT2);
@@ -5499,7 +5086,6 @@ void WaterRenderObjClass::drawTrapezoidWater(Vector3 points[4])
// It needs to be set proportional to the number of feather layers
// this comes from TheGlobalData->m_featherWater, which is a count of layers
-
Int Alpha = 0;
if ( TheGlobalData->m_featherWater == 5) Alpha = 80;
if ( TheGlobalData->m_featherWater == 4) Alpha = 110;
@@ -5596,7 +5182,6 @@ void WaterRenderObjClass::drawTrapezoidWater(Vector3 points[4])
//#endif // OLD VS NEW WATER
-
Matrix3D tm(1);
DX8Wrapper::Set_Transform(D3DTS_WORLD,tm); //position the water surface
@@ -5612,13 +5197,11 @@ void WaterRenderObjClass::drawTrapezoidWater(Vector3 points[4])
DX8Wrapper::Set_DX8_Render_State(D3DRS_DESTBLEND, D3DBLEND_INVDESTALPHA );
}
-
RenderUInt32 cull;
DX8Wrapper::_Get_D3D_Device()->GetRenderState(D3DRS_CULLMODE, &cull);
DX8Wrapper::Set_DX8_Render_State(D3DRS_CULLMODE, D3DCULL_NONE);
-
//#ifdef FEATHER_WATER // the NEW WATER a'la LORENZEN
// int layer = 0;//LORENZEN
@@ -5642,7 +5225,6 @@ void WaterRenderObjClass::drawTrapezoidWater(Vector3 points[4])
-
if (false) {
DX8Wrapper::Set_DX8_Render_State(D3DRS_FILLMODE,D3DFILL_WIREFRAME);
DX8Wrapper::Set_DX8_Render_State(D3DRS_ALPHABLENDENABLE , false);
@@ -5691,7 +5273,6 @@ void WaterRenderObjClass::drawTrapezoidWater(Vector3 points[4])
}
-
//-------------------------------------------------------------------------------------------------
//debug version where moon rotates with the camera (always upright on screen)
//-------------------------------------------------------------------------------------------------
@@ -5735,21 +5316,21 @@ void WaterRenderObjClass::renderSkyBody(Matrix3D *mat)
verts[0].u2=0;
verts[0].v2=1;
verts[0].diffuse=0xffffffff;
-
+
verts[1].x=SKYBODY_SIZE*V1.X;
verts[1].y=SKYBODY_SIZE*V1.Y;
verts[1].z=SKYBODY_SIZE*V1.Z;
verts[1].u2=1;
verts[1].v2=1;
verts[1].diffuse=0xffffffff;
-
+
verts[2].x=SKYBODY_SIZE*V2.X;
verts[2].y=SKYBODY_SIZE*V2.Y;
verts[2].z=SKYBODY_SIZE*V2.Z;
verts[2].u2=1;
verts[2].v2=0;
verts[2].diffuse=0xffffffff;
-
+
verts[3].x=SKYBODY_SIZE*V3.X;
verts[3].y=SKYBODY_SIZE*V3.Y;
verts[3].z=SKYBODY_SIZE*V3.Z;
@@ -5774,4 +5355,3 @@ void WaterRenderObjClass::renderSkyBody(Matrix3D *mat)
/* The save's grid data (the snapshot that was here) is WaterGrid::xfer's; W3DTerrainVisual::xfer
still writes it in the same place. */
-
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWaterTracks.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWaterTracks.cpp
index dd740e6e7..0396ef330 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWaterTracks.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/Water/W3DWaterTracks.cpp
@@ -68,7 +68,6 @@
#if defined(__linux__)
#include "Platform/WaterShoreOverlay.h"
#endif
-#include <cstdlib>
#include <cstring>
//#pragma optimize("", off)
@@ -970,9 +969,7 @@ void setFPMode( void );
#if defined(__linux__)
void WaterTracksRenderSystem::takeReadsForRender(void)
{
- const char *legacySurf=std::getenv("ZH_WATER_LEGACY_SURF");
- if ((legacySurf && std::strcmp(legacySurf,"0")==0) || !TheGlobalData->m_showSoftWaterEdge ||
- TheWaterTransparency->m_transparentWaterDepth==0) return;
+ if (!TheGlobalData->m_showSoftWaterEdge || TheWaterTransparency->m_transparentWaterDepth==0) return;
if (TheGlobalData->m_usingWaterTrackEditor) TestWaterUpdate();
update();
for (WaterTracksObj *mod=m_usedModules;mod;mod=mod->m_nextSystem) {
@@ -992,12 +989,6 @@ void WaterTracksRenderSystem::takeReadsForRender(void)
//=============================================================================
void WaterTracksRenderSystem::flush(RenderInfoClass & rinfo)
{
-#if defined(__linux__)
- // Developer comparison only: isolate the water-surface surf from the authored .wak
- // overlay. Normal play keeps the overlay until its per-fragment replacement is valid.
- const char *legacySurf=std::getenv("ZH_WATER_LEGACY_SURF");
- if (legacySurf && std::strcmp(legacySurf,"0")==0) return;
-#endif
/** @todo: Optimize system by drawing tracks as triangle strips and use dynamic vertex buffer access.
May also try rendering all tracks with one call to W3D/D3D by grouping them by texture.
Try improving the fit to vertical surfaces like cliffs.
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterBowLift.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterBowLift.h
index 3ef837e2b..38e973f4b 100644
--- a/GeneralsMD/Code/Libraries/Include/Platform/WaterBowLift.h
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterBowLift.h
@@ -2,16 +2,9 @@
#pragma once
#include <cmath>
#include <algorithm>
-#include <cstdlib>
-#include <cstring>
#include <string>
#include "Platform/WaterFftGeometry.h"
namespace WaterBowLift {
-inline bool Enabled() {
- const char *value=std::getenv("ZH_WATER_BOW_LIFT");
- // Enabled for ordinary launches; explicit non-matching values retain the diagnostic fallback.
- return !value || std::strcmp(value,"floor")==0;
-}
struct Field { double value=0,dx=0,dy=0; };
// Contract: B>=0, 0<=D<=F<=1. F retains terrain/floor/obstacle clearance;
// D also contains mean-hull clearance. Gradients are with respect to mesh parameters.
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterBowRefinement.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterBowRefinement.h
index e79e858d1..28ceef75f 100644
--- a/GeneralsMD/Code/Libraries/Include/Platform/WaterBowRefinement.h
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterBowRefinement.h
@@ -86,37 +86,27 @@ template<class Weight> bool Subdivide(const Topology &input,const WaterProjected
struct Bow {
unsigned id=0;double level=0;
- bool shoulder=false;WaterBowShoulder::Contour contour{};
- // origin is the real contact endpoint; centre is a floor/visibility probe at the end
- // of the clearance ramp, never a second displacement anchor in front of the vessel.
+ WaterBowShoulder::Contour contour{};
+ // origin follows the contact contour support; centre probes the exterior ridge
+ // for floor clearance and visibility.
Point origin{},centre{},forward{},hullCentre{};
- double sigmaAlong=0,sigmaAcross=0,amplitude=0,moving=0,reach=0;
+ double sigmaAlong=0,sigmaAcross=0,reach=0;
};
-inline bool MakeBow(unsigned id,const WaterHullModel::Hull &mean,const WaterHullModel::Hull &contact,double level,Bow &out,bool shoulder=WaterBowShoulder::Enabled()) {
+inline bool MakeBow(unsigned id,const WaterHullModel::Hull &mean,const WaterHullModel::Hull &contact,double level,Bow &out) {
if(!std::isfinite(level)) return false;
const auto &h=contact.data[0][3]>=3&&contact.data[0][3]<=12?contact:mean;
- for(unsigned row=0;row<4;++row) for(float value:h.data[row]) if(!std::isfinite(value)) return false;
- if(h.data[0][3]<3||h.data[0][3]>12||std::abs(level-h.data[0][2])>.1) return false;
const double speed=std::hypot(h.data[2][0],h.data[2][1]);if(!(speed>double(.3f))) return false;
- Bow b;b.id=id;b.level=level;b.hullCentre={h.data[0][0],h.data[0][1]};
- b.forward={h.data[2][0]/speed,h.data[2][1]/speed};
- const double blend=Smooth(-.25,.25,b.forward.x*h.data[1][0]+b.forward.y*h.data[1][1]);
- const double x=h.data[3][0]+(h.data[3][2]-h.data[3][0])*blend,y=h.data[3][1]+(h.data[3][3]-h.data[3][1])*blend;
- b.origin={b.hullCentre.x+x*h.data[1][0]-y*h.data[1][1],b.hullCentre.y+x*h.data[1][1]+y*h.data[1][0]};
- b.centre={b.origin.x+WaterHullModel::FadeDistance*b.forward.x,b.origin.y+WaterHullModel::FadeDistance*b.forward.y};
const auto pressure=WaterVesselWaves::BowPressure(h.data[1][3],float(speed));
- b.sigmaAlong=pressure.along;b.sigmaAcross=pressure.across;b.amplitude=pressure.amplitude;
- b.moving=Smooth(.3,14,speed);b.reach=h.data[2][3]+110;
- if(shoulder) {
- if(!WaterBowShoulder::Prepare(h,level,pressure.along,pressure.amplitude,b.contour))return false;
- b.shoulder=true;
- const auto origin=WaterBowShoulder::ToWorld(b.contour,b.contour.supportCentre);
- b.origin={origin.x,origin.y};
- // Narrowest ridge scale in every orientation, including turning/broadside motion.
- b.sigmaAlong=b.sigmaAcross=b.contour.width;
- b.centre={b.origin.x+WaterBowShoulder::ShoulderOffset*b.contour.width*b.forward.x,
- b.origin.y+WaterBowShoulder::ShoulderOffset*b.contour.width*b.forward.y};
- }
+ Bow b;b.id=id;b.level=level;
+ if(!WaterBowShoulder::Prepare(h,level,pressure.along,pressure.amplitude,b.contour))return false;
+ b.hullCentre={b.contour.centre.x,b.contour.centre.y};
+ b.forward={h.data[2][0]/speed,h.data[2][1]/speed};
+ const auto origin=WaterBowShoulder::ToWorld(b.contour,b.contour.supportCentre);
+ b.origin={origin.x,origin.y};
+ // Narrowest ridge scale in every orientation, including turning/broadside motion.
+ b.sigmaAlong=b.sigmaAcross=b.contour.width;b.reach=b.contour.reach;
+ b.centre={b.origin.x+WaterBowShoulder::ShoulderOffset*b.contour.width*b.forward.x,
+ b.origin.y+WaterBowShoulder::ShoulderOffset*b.contour.width*b.forward.y};
if(!Finite(b.centre)||b.sigmaAlong<=0||b.sigmaAcross<=0||b.reach<=0) return false;
out=b;return true;
}
@@ -128,8 +118,7 @@ inline bool PrepareBow(const Bow &bow,const View &view,Prepared &out,double safe
!Finite(bow.origin)||!Finite(bow.centre)||!Finite(bow.forward)||!Finite(bow.hullCentre)||
!std::isfinite(bow.reach)||bow.reach<=0||
!std::isfinite(bow.sigmaAlong)||bow.sigmaAlong<=0||!std::isfinite(bow.sigmaAcross)||bow.sigmaAcross<=0||
- !std::isfinite(bow.amplitude)||bow.amplitude<0||
- !std::isfinite(bow.moving)||bow.moving<0||bow.moving>1) return false;
+ !std::isfinite(bow.contour.amplitude)||bow.contour.amplitude<0) return false;
Prepared p;p.bow=bow;if(!view.projection.Transform(bow.centre,p.screen)) return false;
const double *m=view.projection.matrix,w=m[6]*bow.centre.x+m[7]*bow.centre.y+m[8];if(w<=1e-9) return false;
const double j[4]={(m[0]-p.screen.x*m[6])/w*view.width*.5,(m[1]-p.screen.x*m[7])/w*view.width*.5,
@@ -143,14 +132,12 @@ inline bool PrepareBow(const Bow &bow,const View &view,Prepared &out,double safe
p.desiredDepth=(std::max)(0.0,(std::min)(2.0,std::log2(3*step/(std::max)(1.665109222*minor,1e-9))));
const double vzx=(view.verticalClip[0]-p.screen.x*view.verticalClip[2])/w*view.width*.5;
const double vzy=(view.verticalClip[1]-p.screen.y*view.verticalClip[2])/w*view.height*.5;
- const auto probe=WaterVesselWaves::EvaluateBowPressure(
- {float(bow.sigmaAlong),float(bow.sigmaAcross),float(bow.amplitude)},WaterHullModel::FadeDistance,0);
const double bound=WaterFftGeometry::MaxVerticalDisplacement;
- const double rawProbe=bow.shoulder?WaterBowShoulder::Evaluate(bow.contour,{bow.centre.x,bow.centre.y}).value:probe.height;
+ const double rawProbe=WaterBowShoulder::Evaluate(bow.contour,{bow.centre.x,bow.centre.y}).value;
const double height=bound*std::tanh(rawProbe/bound)*Saturate(safeAmplitude);
p.heightGate=Smooth(.25,1,std::hypot(vzx,vzy)*height);
- // Keep the floor/visibility probe at +9, but center the fixed detail window on
- // the world pressure anchor. Its inverse horizontal map can lie on either side.
+ // Center the fixed detail window on the contour support. Its inverse
+ // horizontal map can lie on either side of that anchor.
Point anchorScreen;if(!view.projection.Transform(bow.origin,anchorScreen)) return false;
p.cell={(anchorScreen.x/limit+1)*view.resolution.columns*.5,(anchorScreen.y/limit+1)*view.resolution.rows*.5};
if(!Finite(p.cell)||!std::isfinite(p.desiredDepth)||!std::isfinite(p.heightGate)) return false;
@@ -158,26 +145,14 @@ inline bool PrepareBow(const Bow &bow,const View &view,Prepared &out,double safe
}
inline double Demand(const Prepared &p,unsigned level,Logical at,Point world,double admission=1) {
if(level<1||level>2||!Finite(world)) return 0;
- const double dx=world.x-p.bow.origin.x,dy=world.y-p.bow.origin.y;
- const double across=(-dx*p.bow.forward.y+dy*p.bow.forward.x)/p.bow.sigmaAcross;
- const double along=(dx*p.bow.forward.x+dy*p.bow.forward.y)/p.bow.sigmaAlong+
- WaterVesselWaves::BowCurvature*(std::sqrt(1+across*across)-1);
- // Bound the inverse image of the registered bow field without CPU FFT sampling.
- // The curved normalized profile has a global Jacobian Frobenius bound L; moving
- // by at most R can reduce its profile distance by at most R*L. Radial support
- // expands by R as well. The existing cell crop and topology budgets stay fixed.
+ // Signed distance and support-plane retreat are 1-Lipschitz. Expand the
+ // inverse image by the bounded FFT displacement without sampling it on the CPU.
const double radius=WaterFftGeometry::MaxHorizontalDisplacement;
- const double lipschitz=std::sqrt(1/(p.bow.sigmaAlong*p.bow.sigmaAlong)+
- (1+WaterVesselWaves::BowCurvature*WaterVesselWaves::BowCurvature)/(p.bow.sigmaAcross*p.bow.sigmaAcross));
- const double profile=(std::max)(0.0,std::hypot(along,across)-radius*lipschitz);
const double radial=(std::max)(0.0,std::hypot(world.x-p.bow.hullCentre.x,world.y-p.bow.hullCentre.y)-radius);
- double physical=(1-Smooth(1.5,3,profile))*(1-Smooth(p.bow.reach-30,p.bow.reach,radial));
- if(p.bow.shoulder) {
- const auto lower=WaterBowShoulder::InverseProfileLowerBounds(p.bow.contour,{world.x,world.y},radius);
- physical=(1-Smooth(WaterBowShoulder::ShoulderFadeStart,WaterBowShoulder::ShoulderFadeEnd,lower.x))*
- (1-Smooth(WaterBowShoulder::ShoulderFadeStart,WaterBowShoulder::ShoulderFadeEnd,lower.y))*
- (1-Smooth(p.bow.reach-30,p.bow.reach,radial));
- }
+ const auto lower=WaterBowShoulder::InverseProfileLowerBounds(p.bow.contour,{world.x,world.y},radius);
+ const double physical=(1-Smooth(WaterBowShoulder::ShoulderFadeStart,WaterBowShoulder::ShoulderFadeEnd,lower.x))*
+ (1-Smooth(WaterBowShoulder::ShoulderFadeStart,WaterBowShoulder::ShoulderFadeEnd,lower.y))*
+ (1-Smooth(p.bow.reach-30,p.bow.reach,radial));
const double cellDistance=(std::max)(std::abs(at.x*.25-p.cell.x),std::abs(at.y*.25-p.cell.y));
const double window=1-Smooth(3,CoreRadius,cellDistance);
return Smooth(0,1,p.desiredDepth-double(level-1))*p.heightGate*physical*window*Saturate(admission);
@@ -338,7 +313,7 @@ inline bool Refine(WaterProjectedMesh::Mesh &mesh,const View &view,const Point c
!std::isfinite(p.heightGate)||p.heightGate<0||p.heightGate>1||
!Finite(p.bow.origin)||!Finite(p.bow.centre)||!Finite(p.bow.forward)||
!std::isfinite(p.bow.sigmaAlong)||p.bow.sigmaAlong<=0||!std::isfinite(p.bow.sigmaAcross)||p.bow.sigmaAcross<=0||
- !std::isfinite(p.bow.amplitude)||p.bow.amplitude<0||!Finite(p.bow.hullCentre)||!std::isfinite(p.bow.reach)||p.bow.reach<=0) {
+ !std::isfinite(p.bow.contour.amplitude)||p.bow.contour.amplitude<0||!Finite(p.bow.hullCentre)||!std::isfinite(p.bow.reach)||p.bow.reach<=0) {
stats.rejected=true;return false;
}
}
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterBowShoulder.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterBowShoulder.h
index 40b6f761c..9956360b4 100644
--- a/GeneralsMD/Code/Libraries/Include/Platform/WaterBowShoulder.h
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterBowShoulder.h
@@ -1,11 +1,8 @@
/* Render-only exterior bow shoulder. No gameplay/transport state. */
#pragma once
#include "Platform/WaterHullModel.h"
-#include <cstdlib>
-#include <cstring>
#include <string>
namespace WaterBowShoulder {
-inline bool Enabled() { const char *v=std::getenv("ZH_WATER_BOW_SHOULDER");return !v||std::strcmp(v,"contour")==0; }
#define WATER_BOW_SHOULDER_CONSTANTS(X) \
X(ShoulderWidthBeam,.45f) X(ShoulderWidthMin,3.0f) X(ShoulderWidthMax,12.0f) \
X(ShoulderOffset,.5f) X(ShoulderFadeStart,1.5f) X(ShoulderFadeEnd,3.0f)
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterCoastalCrest.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterCoastalCrest.h
deleted file mode 100644
index 39440648b..000000000
--- a/GeneralsMD/Code/Libraries/Include/Platform/WaterCoastalCrest.h
+++ /dev/null
@@ -1,65 +0,0 @@
-/* Bounded render-only nonlinear coastal crest restoration. Positive temporal mean is intentional
- * in this experimental approximation; it is not a mass-conserving shallow-water solver. */
-#pragma once
-#include "Platform/WaterShoreFoam.h"
-namespace WaterCoastalCrest {
-using Field=WaterSurfaceModel::Sample; // value, d/dx, d/dy
-inline bool Eligible(bool river,bool context,float offshore) {return !river&&context&&offshore==0;}
-inline float EncodeObstacle(float obstacle) {
- return float((WaterSurfaceModel::EncodeObstacleAttenuation(0,obstacle)>>16)&255)/255.0f;
-}
-inline bool Finite(const Field& f) {return std::isfinite(f.height)&&std::isfinite(f.dx)&&std::isfinite(f.dy);}
-inline Field Unit(Field f) {
- if(f.height<=0)return {0,0,0};if(f.height>=1)return {1,0,0};return f;
-}
-inline Field Product(const Field&a,const Field&b) {
- return {a.height*b.height,a.dx*b.height+a.height*b.dx,a.dy*b.height+a.height*b.dy};
-}
-inline Field Smooth(float a,float b,Field f) {
- if(f.height<=a)return {0,0,0};if(f.height>=b)return {1,0,0};
- const float t=(f.height-a)/(b-a),derivative=6*t*(1-t)/(b-a);
- return {t*t*(3-2*t),derivative*f.dx,derivative*f.dy};
-}
-// Caller must preserve river/offshore/missing-context identity. Terrain clearance is evaluated
-// at the same point as the original envelope; this addition never lowers that original mesh.
-inline Field Correction(Field broad,Field depth,Field support,Field exposure,Field obstacle,Field damping) {
- if(!Finite(broad)||!Finite(depth)||!Finite(support)||!Finite(exposure)||!Finite(obstacle)||!Finite(damping)
- ||broad.height<=0||depth.height<=WaterShoreFoam::MinDepth)return {0,0,0};
- support=Unit(support);exposure=Unit(exposure);obstacle=Unit(obstacle);damping=Unit(damping);
- // Diffuse red is UNORM8 rounded by the existing vertex encoder. Remove half a code
- // so restoration can never exceed the original unquantized obstacle envelope.
- obstacle.height-=0.5f/255.0f;if(obstacle.height<=0)obstacle={0,0,0};
- const Field gain={obstacle.height-damping.height,obstacle.dx-damping.dx,obstacle.dy-damping.dy};
- if(gain.height<=0||support.height<=0||exposure.height<=0)return {0,0,0};
- const float clearance=depth.height-WaterShoreFoam::MinDepth,ratio=broad.height/clearance;
- const float q=std::tanh(ratio),dq=1-q*q,depthDerivative=q-ratio*dq;
- const Field limited={clearance*q,dq*broad.dx+depthDerivative*depth.dx,dq*broad.dy+depthDerivative*depth.dy};
- const Field wet=Smooth(WaterShoreFoam::MinDepth,WaterShoreFoam::WetDepth,depth);
- const Field crest=Smooth(0,WaterShoreFoam::CrestHeight,broad);
- return Product(Product(Product(support,exposure),Product(wet,gain)),Product(limited,crest));
-}
-inline float Height(float broad,float depth,float support,float exposure,float obstacle,float damping) {
- return Correction({broad,0,0},{depth,0,0},{support,0,0},{exposure,0,0},{obstacle,0,0},{damping,0,0}).height;
-}
-inline std::string Source() {return R"COAST(
-float3 waterCoastUnit(float3 f) {if(f.x<=0)return 0;if(f.x>=1)return float3(1,0,0);return f;}
-float3 waterCoastProduct(float3 a,float3 b) {return float3(a.x*b.x,a.yz*b.x+a.x*b.yz);}
-float3 waterCoastSmooth(float a,float b,float3 f) {
- if(f.x<=a)return 0;if(f.x>=b)return float3(1,0,0);
- float t=(f.x-a)/(b-a);return float3(t*t*(3-2*t),(6*t*(1-t)/(b-a))*f.yz);
-}
-float3 waterCoastalCrest(float3 broad,float3 depth,float3 support,float3 exposure,float3 obstacle,float3 damping) {
- if(!all(isfinite(broad))||!all(isfinite(depth))||!all(isfinite(support))||!all(isfinite(exposure))
- ||!all(isfinite(obstacle))||!all(isfinite(damping))||broad.x<=0||depth.x<=ShoreMinDepth)return 0;
- support=waterCoastUnit(support);exposure=waterCoastUnit(exposure);
- obstacle=waterCoastUnit(obstacle);damping=waterCoastUnit(damping);
- obstacle.x-=0.5/255.0;if(obstacle.x<=0)obstacle=0;
- float3 gain=obstacle-damping;if(gain.x<=0||support.x<=0||exposure.x<=0)return 0;
- float clearance=depth.x-ShoreMinDepth,ratio=broad.x/clearance,q=tanh(ratio),dq=1-q*q;
- float3 limited=float3(clearance*q,dq*broad.yz+(q-ratio*dq)*depth.yz);
- float3 wet=waterCoastSmooth(ShoreMinDepth,ShoreWetDepth,depth),crest=waterCoastSmooth(0,ShoreCrestHeight,broad);
- return waterCoastProduct(waterCoastProduct(waterCoastProduct(support,exposure),waterCoastProduct(wet,gain)),
- waterCoastProduct(limited,crest));
-}
-)COAST";}
-}
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterCoastalDomain.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterCoastalDomain.h
deleted file mode 100644
index ba503c668..000000000
--- a/GeneralsMD/Code/Libraries/Include/Platform/WaterCoastalDomain.h
+++ /dev/null
@@ -1,202 +0,0 @@
-/* Immutable physical coastal domain. No camera, simulation or map mutation. */
-#pragma once
-#include "Platform/WaterCoastalSurf.h"
-#include "Platform/WaterShoreSource.h"
-
-namespace WaterCoastalDomain {
-using Result=WaterShoreHistory::BuildResult;
-using Level=WaterShoreSource::Level;
-constexpr size_t MaxWetCells=4*WaterOpticalContext::MaxCells;
-// Conservative scan/sort, lattice and flood work units, shared across all levels.
-// A caller may supply a smaller allowance; no caller can exceed this fixed cap.
-constexpr size_t MaxBuildWork=128u*1024u*1024u;
-class Domain {
- WaterShoreHistory::Grid grid;
- WaterShoreHistory::Topology topology;
- WaterShoreSupport::Domain support;
- std::vector<WaterShoreHistory::Cell> cells;
- std::vector<WaterCoastalSurf::Node> nodes;
-public:
- Result 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>&inputLevels,
- size_t workAllowance=MaxBuildWork) {
- 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<8||spacing>128||!std::isfinite(heightScale)||heightScale<=0
- ||polygons.size()>WaterOpticalContext::MaxPoints/3)
- return Result::Invalid;
- if(inputLevels.size()>WaterCoastalSurf::MaxLevels)return Result::TooManyLevels;
- size_t points=0;
- for(const auto &p:polygons) {
- if(p.points.size()>WaterOpticalContext::MaxPoints-points)return Result::Invalid;
- points+=p.points.size();
- for(const auto &v:p.points)if(!std::isfinite(v.x)||!std::isfinite(v.y)||!std::isfinite(v.z))return Result::Invalid;
- }
- std::vector<Level> levels=inputLevels;
- const size_t terrainCount=size_t(width)*height;
- for(const auto &l:levels) {
- if(!l.field||!std::isfinite(l.level)||double(float(l.level))!=l.level)return Result::Invalid;
- const auto &f=*l.field;
- if(f.ocean.size()!=terrainCount||f.shore.size()!=terrainCount||f.coast.size()!=terrainCount
- ||f.exposure.size()!=terrainCount||f.physicalShore.size()!=terrainCount)return Result::Invalid;
- }
- std::sort(levels.begin(),levels.end(),[](const Level&a,const Level&b){return a.level<b.level;});
- for(size_t i=1;i<levels.size();++i)if(levels[i-1].level==levels[i].level)return Result::Invalid;
- size_t remaining=(std::min)(workAllowance,MaxBuildWork);
- auto spend=[&](size_t amount){if(amount>remaining)return false;remaining-=amount;return true;};
- // Intervals has at most three spans per input vertex. Charge its bounded sorting
- // as well as point visits before performing a scanline, including empty polygons.
- size_t sortPasses=0;for(size_t n=3*points+1;n>1;n=(n+1)/2)++sortPasses;
- const size_t lineWork=1+polygons.size()+points*(4+3*sortPasses);
- const size_t coveredWork=sortPasses+1; // upper_bound on at most three spans per vertex
- // Build at most two bounded candidates from the same completed fine flood.
- // Stride2 is exactly the original terrain grid, so support rectangles remain
- // bilinear. Larger strides would cross terrain-cell boundaries and need a
- // different support proof; they are deliberately not attempted here.
- Domain fine,coarse;fine.grid={-border*spacing,-border*spacing,spacing*.5};
- coarse.grid={fine.grid.originX,fine.grid.originY,spacing};
- // Keep the existing GPU graph spacing contract; no stride2 candidate is
- // possible when its spacing would exceed64 world units.
- bool fineOverflow=false,coarseOverflow=spacing>64;
- auto append=[&](Domain &candidate,bool &overflow,int x,int y,double level,
- const WaterCoastalSurf::Node &node,uint8_t connections){
- if(overflow)return;
- if(candidate.cells.size()>=WaterCoastalSurf::MaxNodes){
- overflow=true;candidate.cells.clear();candidate.nodes.clear();return;
- }
- candidate.cells.push_back({x,y,level,uint32_t(candidate.nodes.size()),connections});
- candidate.nodes.push_back(node);
- };
- // Unlike the legacy width-epsilon sampler, exact final-row vertices remain exact.
- // Cardinal half-cell segments stay within one bilinear terrain cell, so their
- // height is linear: wet endpoints prove the entire cardinal segment is wet.
- auto terrain=[&](double x,double y){
- x=Clamp(x,0,width-1);y=Clamp(y,0,height-1);
- const int ix=(std::min)(int(x),width-2),iy=(std::min)(int(y),height-2);
- 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)*heightScale);
- };
- const int nx=2*width-1,ny=2*height-1;
- const size_t wetCount=size_t(nx)*ny;
- if(wetCount>MaxWetCells)return Result::Invalid;
- enum : uint8_t {Wet=1,PositiveX=2,PositiveY=4,Connected=8};
- for(const Level &entry:levels) {
- const auto &f=*entry.field;
- // Full wet connectivity precedes shallow/distance pruning: an island coast
- // remains exposed when its only path to the playable boundary is deep ocean.
- // Memory is reused one level at a time; optical exposure cannot establish connectivity.
- std::vector<uint8_t> wet(wetCount,0),columnWet(size_t(nx),0);
- for(int y=0;y<ny;++y) {
- if(!spend(lineWork+size_t(nx)*(1+2*coveredWork)))return Result::Invalid;
- const double wy=fine.grid.originY+y*fine.grid.spacing;
- const auto row=WaterShoreSource::Intervals(polygons,entry.level,wy,true);
- if(row.empty())continue;
- for(int x=0;x<nx;++x) {
- const double wx=fine.grid.originX+x*fine.grid.spacing;
- if(!WaterShoreSource::Covered(row,wx,wx)||!(terrain(x*.5,y*.5)<entry.level))continue;
- uint8_t flags=Wet;
- if(x+1<nx&&WaterShoreSource::Covered(row,wx,wx+fine.grid.spacing))flags|=PositiveX;
- wet[size_t(y)*nx+x]=flags;columnWet[size_t(x)]=1;
- }
- }
- for(int x=0;x<nx;++x)if(columnWet[size_t(x)]) {
- if(!spend(lineWork+size_t(ny)*(1+coveredWork)))return Result::Invalid;
- const auto column=WaterShoreSource::Intervals(polygons,entry.level,
- fine.grid.originX+x*fine.grid.spacing,false);
- for(int y=0;y+1<ny;++y) {
- auto &flags=wet[size_t(y)*nx+x];if(!(flags&Wet))continue;
- const double wy=fine.grid.originY+y*fine.grid.spacing;
- if(WaterShoreSource::Covered(column,wy,wy+fine.grid.spacing))flags|=PositiveY;
- }
- }
- std::vector<uint32_t> queue;queue.reserve(wetCount);
- auto seed=[&](size_t index){
- auto &flags=wet[index];if((flags&(Wet|Connected))!=Wet)return;
- flags|=Connected;queue.push_back(uint32_t(index));
- };
- const int left=2*border,right=2*(width-border-1),top=2*border,bottom=2*(height-border-1);
- for(int x=left;x<=right;++x){seed(size_t(top)*nx+x);seed(size_t(bottom)*nx+x);}
- for(int y=top;y<=bottom;++y){seed(size_t(y)*nx+left);seed(size_t(y)*nx+right);}
- for(size_t q=0;q<queue.size();++q) {
- if(!spend(4))return Result::Invalid;
- const size_t i=queue[q];const int x=int(i%nx),y=int(i/nx);
- if(x+1<nx&&(wet[i]&PositiveX))seed(i+1);
- if(x>0&&(wet[i-1]&PositiveX))seed(i-1);
- if(y+1<ny&&(wet[i]&PositiveY))seed(i+nx);
- if(y>0&&(wet[i-nx]&PositiveY))seed(i-nx);
- }
- if(!spend(wetCount))return Result::Invalid;
- // Final-row/column source knots remain excluded to retain the existing
- // support-tile contract. They participated in the full wet connectivity.
- for(int y=0;y+1<ny;++y)for(int x=0;x+1<nx;++x) {
- const uint8_t flags=wet[size_t(y)*nx+x];if(!(flags&Connected))continue;
- const float gx=x*.5f,gy=y*.5f;
- const float depth=float(entry.level)-terrain(gx,gy);
- if(!(depth>.15f)||depth>=12)continue;
- const auto distance=WaterSurfaceModel::SampleOffshore(f.physicalShore.data(),width,height,gx,gy,float(spacing));
- // The saturated code means at least160, not exactly160. It cannot
- // prove membership in a collar when spacing makes that collar wider.
- if(distance.height>=1)continue;
- const float physical=distance.height*WaterOpticalContext::PhysicalShoreRange;
- if(physical>WaterCoastalSurf::PhysicalCoastEnd+spacing+WaterOpticalContext::PhysicalShoreRange/510)continue;
- const auto ocean=WaterSurfaceModel::SampleOffshore(f.ocean.data(),width,height,gx,gy,float(spacing));
- const auto exposure=WaterSurfaceModel::SampleOffshore(f.exposure.data(),width,height,gx,gy,float(spacing));
- // Physical connectivity above remains mandatory. Within that domain,
- // match the actual spectral support used by geometry and presentation.
- if(exposure.height<=0)continue;
- WaterCoastalSurf::Node node;
- node.world[0]=float(fine.grid.originX+x*fine.grid.spacing);
- node.world[1]=float(fine.grid.originY+y*fine.grid.spacing);node.world[2]=float(entry.level);
- auto &c=node.context;c.depth=depth;c.distance=physical;
- c.outwardX=distance.dx*WaterOpticalContext::PhysicalShoreRange;
- c.outwardY=distance.dy*WaterOpticalContext::PhysicalShoreRange;
- c.exposure=exposure.height;c.offshore=ocean.height;
- c.analyticDamping=WaterSurfaceModel::TerrainDamping(depth,ocean.height);
- c.spectralDamping=WaterFftGeometry::SafeDamping(c.analyticDamping,depth);
- c.wet=c.admitted=1;
- const uint8_t connections=uint8_t((flags&PositiveX?1:0)|(flags&PositiveY?2:0));
- append(fine,fineOverflow,x,y,entry.level,node,connections);
- if((x&1)==0&&(y&1)==0&&!coarseOverflow){
- if(!spend(4))return Result::Invalid;
- auto linked=[&](bool vertical){
- const int ex=x+(vertical?0:2),ey=y+(vertical?2:0);
- if(ex>=nx||ey>=ny)return false;
- const size_t step=vertical?size_t(nx):1,start=size_t(y)*nx+x;
- const uint8_t direction=vertical?PositiveY:PositiveX;
- for(unsigned k=0;k<2;++k){
- const uint8_t a=wet[start+k*step],b=wet[start+(k+1)*step];
- if((a&(Wet|Connected|direction))!=(Wet|Connected|direction)
- ||(b&(Wet|Connected))!=(Wet|Connected))return false;
- }
- return true;
- };
- const uint8_t links=uint8_t((linked(false)?1:0)|(linked(true)?2:0));
- append(coarse,coarseOverflow,x/2,y/2,entry.level,node,links);
- }
- if(fineOverflow&&coarseOverflow)return Result::TooManyCells;
- }
- }
- const unsigned selectedStride=fineOverflow?2u:1u;
- Domain next=std::move(fineOverflow?coarse:fine);
- const auto built=next.topology.Build(next.grid,next.cells);if(built!=Result::Ready)return built;
- // Sorted level/y/x insertion preserves the immutable node IDs after Topology.Build.
- if(next.topology.Cells().size()!=next.nodes.size())return Result::Invalid;
- for(const auto &edge:next.topology.Edges()) {
- const auto &a=next.cells[edge.a],&b=next.cells[edge.b];
- const unsigned side=a.y==b.y?1:3,opposite=side-1;
- next.nodes[edge.a].neighbour[side]=edge.b+1;next.nodes[edge.b].neighbour[opposite]=edge.a+1;
- }
- if(!WaterCoastalSurf::ValidGraph(next.nodes,next.grid.spacing))return Result::Invalid;
- auto supportTerrain=[&](double x,double y){return terrain(x*selectedStride,y*selectedStride);};
- if(!next.support.Build(next.grid,next.cells,width,height,polygons,supportTerrain))return Result::Invalid;
- *this=std::move(next);return Result::Ready;
- }
- const WaterShoreHistory::Grid& Grid()const{return grid;}
- const WaterShoreHistory::Topology& Topology()const{return topology;}
- const std::vector<WaterShoreHistory::Cell>& Cells()const{return cells;}
- const std::vector<WaterCoastalSurf::Node>& Nodes()const{return nodes;}
- const WaterShoreSupport::Domain& Support()const{return support;}
-};
-}
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterCoastalIncident.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterCoastalIncident.h
deleted file mode 100644
index 1b575a68c..000000000
--- a/GeneralsMD/Code/Libraries/Include/Platform/WaterCoastalIncident.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/* GPU-only production-field sampler for the optional coastal history atlas. */
-#pragma once
-#include "Platform/WaterCoastalSurf.h"
-#include "Platform/WaterFftSpectrum.h"
-#include "Platform/WaterShoreFoam.h"
-#include "Platform/WaterSurfaceModel.h"
-#include <string>
-
-namespace WaterCoastalIncident {
-// Domain slots 0..3: world, coast, surface, admission. Slots 4..7 are the existing
-// ocean maps 0..3 (broad/medium displacement+derivatives), with the ocean sampler.
-// Ocean maps 4/5 are fine ripples and deliberately have no source binding.
-constexpr unsigned SamplerCount=8,UniformBytes=16;
-struct Parameters {float waterTime=0,nodeCount=0,padding0=0,padding1=0;};
-static_assert(sizeof(Parameters)==UniformBytes,"Incident uniform is one float4");
-inline const char *VertexSource(){return WaterFftSpectrum::VertexHlsl();}
-inline bool Slice(const std::string &source,const char *begin,const char *end,std::string &out){
- const size_t a=source.find(begin),b=a==std::string::npos?std::string::npos:source.find(end,a);
- if(a==std::string::npos||b==std::string::npos||b<=a)return false;
- out=source.substr(a,b-a);return true;
-}
-inline bool ReplaceOnce(std::string &text,const std::string &old,const std::string &replacement){
- const size_t at=text.find(old);if(at==std::string::npos||text.find(old,at+old.size())!=std::string::npos)return false;
- text.replace(at,old.size(),replacement);return true;
-}
-inline bool PixelSource(std::string &result){
- result.clear();
- // Extract the actual production decoder and map-coordinate convention. A changed
- // source contract fails optional creation; it cannot silently invent another ocean.
- const std::string production=WaterFftSampling::PixelSource(false,false);
- std::string structure,sampling,decode,legacy;
- if(!Slice(production,"struct FftSurface {","struct FftMapSamples",structure)
- ||!Slice(production,"struct FftMapSamples","FftSurface fftDecodeSamples(",sampling)
- ||!Slice(production,"FftSurface fftDecodeSamples(","FftSurface fftRawSurface(",decode)
- ||!Slice(WaterShoreFoam::Source(),"float4 waterShoreWave(","float waterShoreRate(",legacy))return false;
- if(!ReplaceOnce(sampling,"samples.c=Texture12.SampleLevel(Sampler12,p/(13.0*fftWorldScale),lod[2]);","samples.c=0;")
- ||!ReplaceOnce(sampling,"samples.cd=Texture13.SampleLevel(Sampler13,p/(13.0*fftWorldScale),lod[2]);","samples.cd=0;"))return false;
- for(unsigned i=0;i<4;++i){
- if(!ReplaceOnce(sampling,"Texture"+std::to_string(8+i),"IncidentTexture"+std::to_string(4+i))
- ||!ReplaceOnce(sampling,"Sampler"+std::to_string(8+i),"IncidentSampler"+std::to_string(4+i)))return false;
- }
- std::string source;
- for(unsigned i=0;i<SamplerCount;++i){const std::string n=std::to_string(i);
- source+="Texture2D<float4> IncidentTexture"+n+" : register(t"+n+",space2);\n"
- +"SamplerState IncidentSampler"+n+" : register(s"+n+",space2);\n";}
- source+="cbuffer IncidentParameters:register(b0,space3){float4 Parameters;};\n";
- source+=WaterFftSampling::CommonSource()+structure+sampling+decode
- +WaterCoastalSurf::IncidentSource()+WaterCoastalSurf::Source()+legacy
- +WaterSurfaceModel::OceanShaderSource();
- source+=R"HLSL(
-float4 main(float4 pixel:SV_Position):SV_Target0 {
- uint2 cell=(uint2)pixel.xy;uint index=cell.y*256+cell.x;
- if(!all(isfinite(Parameters))||Parameters.y<0||Parameters.y>65536
- ||floor(Parameters.y)!=Parameters.y||index>=(uint)Parameters.y)return float4(0,0,0,1);
- float2 uv=(float2(cell)+.5)/256.0;
- float4 world=IncidentTexture0.SampleLevel(IncidentSampler0,uv,0);
- WaterSurfContext context;
- context.coast=IncidentTexture1.SampleLevel(IncidentSampler1,uv,0);
- context.surface=IncidentTexture2.SampleLevel(IncidentSampler2,uv,0);
- context.admission=IncidentTexture3.SampleLevel(IncidentSampler3,uv,0);
- if(!all(isfinite(world))||!waterSurfContextFinite(context)||context.admission.x<.5
- ||context.admission.y<.5||context.surface.x<=0||context.coast.x<=.15)return float4(0,0,0,1);
- float offshore=context.surface.y,weight=context.surface.x;
- // Exactly the existing selected analytic components; the ocean helper retains
- // its original warp and packet envelope. Exposed shallow water shares the FFT
- // phase even at zero optical R. No second TimeScale, blend-weight gradient,
- // damping derivative, vessel pressure or decorative swell enters this source.
- float3 legacy=waterShoreWave(world.xy,Parameters.x).xyz;
- float4 oceanSwell;waterOceanSurface(world.xy,Parameters.x,oceanSwell);
- float4 analytic=float4(lerp(legacy,oceanSwell.xyz,offshore),1);
- float4 spectral=waterSurfIncident(fftMapSamples(world.xy,float3(0,0,0)));
- float4 incident=waterSurfBlend(analytic,spectral,weight);
- // Horizontal chop still fades with optical R; a zero-chop shore must not
- // acquire a compression breaker just because its vertical wave is spectral.
- incident.w=lerp(1.0,spectral.w,saturate(weight*offshore));
- return incident;
-}
-)HLSL";
- result.swap(source);return true;
-}
-} // namespace WaterCoastalIncident
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterCoastalPresentation.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterCoastalPresentation.h
deleted file mode 100644
index dee147a70..000000000
--- a/GeneralsMD/Code/Libraries/Include/Platform/WaterCoastalPresentation.h
+++ /dev/null
@@ -1,73 +0,0 @@
-/* Optional coastal history presentation; no source births or gameplay state. */
-#pragma once
-#include "Platform/WaterCoastalSurf.h"
-#include <cmath>
-
-namespace WaterCoastalPresentation {
-struct Moments {float density=0,age=0;};
-inline Moments AtTime(float density,float ageMoment,float elapsed){
- if(!std::isfinite(density)||!std::isfinite(ageMoment)||!std::isfinite(elapsed)
- ||density<=0||density>16||ageMoment<0||ageMoment>1024||elapsed<0||elapsed>=14)return {};
- const float age=ageMoment/density+elapsed;
- if(!std::isfinite(age)||age>=14)return {};
- return {float(density*std::exp(-double(elapsed)/5)),age};
-}
-inline float ModelGate(float actual,float canonical,float correction,float gx,float gy){
- using WaterCoastalSurf::Smooth;
- if(!std::isfinite(actual)||!std::isfinite(canonical)||!std::isfinite(correction)
- ||!std::isfinite(gx)||!std::isfinite(gy)||actual<0||actual>1||canonical<0||canonical>1)return 0;
- return (1-Smooth(.015f,.06f,std::abs(actual-canonical)))
- *(1-Smooth(.02f,.15f,std::abs(correction)))*(1-Smooth(.002f,.02f,std::hypot(gx,gy)));
-}
-inline const char *Source(){return R"HLSL(
-bool waterCoastalViewValid(float4 area,float4 params,float2 position,float level,float time) {
- if(!all(isfinite(area))||!all(isfinite(params))||!all(isfinite(position))||!isfinite(level)||!isfinite(time)
- ||params.x<.5||any(area.zw<=0)||abs(params.y-level)>.01||abs(params.w-time)>.0001
- ||params.z>params.w||params.z<0)return false;
- float2 uv=(position-area.xy)/area.zw;
- return all(uv>=0)&&all(uv<=1);
-}
-float2 waterCoastalAtTime(float2 moments,float elapsed) {
- if(!all(isfinite(moments))||!isfinite(elapsed)||moments.x<=0||moments.x>16
- ||moments.y<0||moments.y>1024||elapsed<0||elapsed>=14)return 0;
- float age=moments.y/moments.x+elapsed;
- if(!isfinite(age)||age>=14)return 0;
- return float2(moments.x*exp(-elapsed/5.0),age);
-}
-float waterCoastalModelGate(float actual,float canonical,float correction,float2 correctionSlope) {
- if(!all(isfinite(float4(actual,canonical,correction,0)))||!all(isfinite(correctionSlope))
- ||actual<0||actual>1||canonical<0||canonical>1)return 0;
- // Canonical exposure is camera independent; the vertex metadata includes the
- // actual patch/camera FFT fade. Optical R does not select the wave family.
- // Corrections are representation deltas, not a new breaking-wave source.
- return (1-smoothstep(.015,.06,abs(actual-canonical)))
- *(1-smoothstep(.02,.15,abs(correction)))*(1-smoothstep(.002,.02,length(correctionSlope)));
-}
-float waterCoastalWetGate(float rawDepth,float3 hit,float3 world,float3 view,float level,
- float worldTerrain,float parameterTerrain,float hitTerrain,float obstacle,float hull) {
- if(!isfinite(rawDepth)||rawDepth<0||rawDepth>=.999999||!all(isfinite(hit))
- ||!all(isfinite(world))||!all(isfinite(view))||!isfinite(level)
- ||!all(isfinite(float4(worldTerrain,parameterTerrain,hitTerrain,obstacle)))||!isfinite(hull))return 0;
- // Real original raster depth only. Both the current chop location and fixed
- // parameter must remain wet; a background sample or an above-water face cannot
- // borrow terrain metadata as evidence of water. Keep original ordinary rims.
- if(hit.z>min(world.z,level)-.08||dot(hit-world,view)>=-.01
- ||worldTerrain>=min(world.z-.08,level-.15)||parameterTerrain>=level-.15)return 0;
- // Terrain agreement is a bounded heuristic, not an object-ID reconstruction.
- // Known moving hulls and interpolated structure damping independently reject
- // their footprint; thin unregistered objects still require native inspection.
- float terrainMatch=1-smoothstep(.5,1.5,abs(hit.z-hitTerrain));
- float solid=smoothstep(.001,.1,min(saturate(obstacle),saturate(hull)));
- return smoothstep(0,.8,world.z-hit.z)*smoothstep(.15,.8,level-worldTerrain)*terrainMatch*solid;
-}
-float waterCoastalPorousCoverage(float2 position,float footprint,float2 densityAge) {
- if(densityAge.x<=0)return 0;
- float coverage=waterFoamOpticalCoverage(densityAge.x);
- // Existing static world-anchored pore material: aging changes its area, not its
- // phase. No scrolling texture or independent oscillator impersonates a front.
- float aged=smoothstep(.4,3.0,densityAge.y);
- float porous=waterFoamOldCoverage(position,coverage,footprint,1.0);
- return lerp(coverage,porous,aged)*(1-smoothstep(8,14,densityAge.y));
-}
-)HLSL";}
-} // namespace WaterCoastalPresentation
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterCoastalRender.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterCoastalRender.h
deleted file mode 100644
index 08f5a0207..000000000
--- a/GeneralsMD/Code/Libraries/Include/Platform/WaterCoastalRender.h
+++ /dev/null
@@ -1,9 +0,0 @@
-// Render-only bridge. The device caches immutable domain/view identities; no map mutation.
-#pragma once
-#include "Platform/WaterCoastalView.h"
-#ifndef _WIN32
-class IDirect3DDevice9;
-bool PosixWaterCoastalBind(IDirect3DDevice9 *,uint64_t,const WaterCoastalDomain::Domain &,
- const WaterShoreHistory::Mapping &,double,const std::vector<WaterCoastalSurf::Lookup> &);
-void PosixWaterCoastalEnd(IDirect3DDevice9 *);
-#endif
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterCoastalSurf.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterCoastalSurf.h
deleted file mode 100644
index 7f9596698..000000000
--- a/GeneralsMD/Code/Libraries/Include/Platform/WaterCoastalSurf.h
+++ /dev/null
@@ -1,275 +0,0 @@
-/* Bounded render-only coastal source/history core. GPU transport is a separate owner. */
-#pragma once
-#include "Platform/WaterFftSampling.h"
-#include "Platform/WaterShoreHistory.h"
-#include <array>
-#include <cmath>
-#include <cstdint>
-#include <string>
-#include <vector>
-
-namespace WaterCoastalSurf {
-constexpr unsigned AtlasSide=256,MaxNodes=AtlasSide*AtlasSide,MaxLevels=8,MaxViewSide=512;
-constexpr double SourceTick=.1,MaximumSourceInterval=.25,Lifetime=5,Diffusivity=2;
-constexpr float MaximumRate=1.2f,PhysicalCoastFull=96,PhysicalCoastEnd=128;
-// Coordinates/heights are game world units. dt is elapsed modern-water seconds, not
-// FFT time (the native maps already contain the WaterFftSampling::TimeScale phase).
-// The field excludes fine ripples and generated vessel waves. It is a component
-// of the existing geometry, not an additional independent surf oscillator.
-struct Field {float height=0,dx=0,dy=0,compression=1;};
-struct Context {
- float depth=0,distance=0,outwardX=0,outwardY=0;
- float exposure=0,offshore=0,analyticDamping=0,spectralDamping=0;
- float wet=0,admitted=0;
-};
-// Four float channels on the GPU. rate=-1 means no valid previous source sample.
-// History itself stays in the fixed mean-water parameter/world chart. Sampling
-// it at the corresponding parameter makes it follow the actual horizontal chop.
-struct State {float density=0,ageMoment=0,height=0,rate=-1;};
-inline float Clamp(float x,float a,float b){return (std::max)(a,(std::min)(b,x));}
-inline float Smooth(float a,float b,float x){const float t=Clamp((x-a)/(b-a),0,1);return t*t*(3-2*t);}
-inline bool Finite(const Field &f){return std::isfinite(f.height)&&std::isfinite(f.dx)&&std::isfinite(f.dy)&&std::isfinite(f.compression)
- &&std::abs(f.height)<=64&&std::abs(f.dx)<=1024&&std::abs(f.dy)<=1024&&std::abs(f.compression)<=1048576;}
-inline bool Finite(const Context &c){return std::isfinite(c.depth)&&std::isfinite(c.distance)&&std::isfinite(c.outwardX)&&std::isfinite(c.outwardY)
- &&std::isfinite(c.exposure)&&std::isfinite(c.offshore)&&std::isfinite(c.analyticDamping)&&std::isfinite(c.spectralDamping)
- &&std::isfinite(c.wet)&&std::isfinite(c.admitted)&&std::abs(c.depth)<=1048576&&std::abs(c.distance)<=1048576
- &&std::abs(c.outwardX)<=1024&&std::abs(c.outwardY)<=1024&&c.exposure>=0&&c.exposure<=1
- &&c.offshore>=0&&c.offshore<=1&&c.analyticDamping>=0&&c.analyticDamping<=1
- &&c.spectralDamping>=0&&c.spectralDamping<=1&&c.wet>=0&&c.wet<=1&&c.admitted>=0&&c.admitted<=1;}
-inline bool Finite(const State &s){return std::isfinite(s.density)&&std::isfinite(s.ageMoment)&&std::isfinite(s.height)&&std::isfinite(s.rate)
- &&s.density>=0&&s.density<=16&&s.ageMoment>=0&&s.ageMoment<=1024&&std::abs(s.height)<=64&&s.rate>=-1&&s.rate<=MaximumRate;}
-// Incident-component indicators at fixed blend weight, excluding its gradient.
-// This is not the final mixed geometric normal/Jacobian: a static coastal transition
-// must not create a breaker from two different but spatially constant input heights.
-inline Field Blend(const Field &analytic,const Field &spectral,float weight){
- if(!Finite(analytic)||!Finite(spectral)||!std::isfinite(weight))return {};
- const float w=Clamp(weight,0,1);
- return {analytic.height+(spectral.height-analytic.height)*w,
- analytic.dx+(spectral.dx-analytic.dx)*w,analytic.dy+(spectral.dy-analytic.dy)*w,
- 1+(spectral.compression-1)*w};
-}
-inline float Domain(const Context &c){
- if(!Finite(c)||c.wet<.5f||c.admitted<.5f||c.exposure<=0||c.depth<=.15f||c.distance<0)return 0;
- // This physical source domain is independent of optical A replacement validity.
- // The depth bound makes the 128-unit distance limit a work bound, not a uniform ribbon.
- return Smooth(.15f,.8f,c.depth)*(1-Smooth(8,12,c.depth))
- *(1-Smooth(PhysicalCoastFull,PhysicalCoastEnd,c.distance))*Clamp(c.exposure,0,1);
-}
-inline float Rate(const Context &c,const Field &f,const State &previous,double elapsed){
- const float domain=Domain(c);
- if(domain<=0||!Finite(f)||!Finite(previous)||previous.rate<0||!std::isfinite(elapsed)
- ||elapsed<=1e-6||elapsed>MaximumSourceInterval||f.height<=0)return 0;
- const float normal=std::hypot(c.outwardX,c.outwardY),slope=std::hypot(f.dx,f.dy);
- if(normal<=1e-8f||slope<=1e-8f)return 0;
- const float ht=float((double(f.height)-previous.height)/elapsed);
- // Backward temporal difference of the same broad field, on the fixed parameter
- // chart. This is a bounded phase-direction approximation, not Eulerian fluid velocity.
- // Positive h_t selects the growing face; the outward gradient then identifies arrival.
- if(!(ht>0))return 0;
- if(!std::isfinite(ht))return 0;
- const float incoming=Smooth(0,.25f,(f.dx/slope)*(c.outwardX/normal)+(f.dy/slope)*(c.outwardY/normal));
- const float heightBreak=Smooth(.4f,.85f,2*f.height/(std::max)(c.depth+.5f,1.0f));
- const float compressionBreak=Smooth(.04f,.30f,1-f.compression);
- const float breaking=(std::max)(heightBreak,compressionBreak);
- const float damping=Clamp(c.analyticDamping+(c.spectralDamping-c.analyticDamping)*Clamp(c.exposure,0,1),0,1);
- // Dissipation is already implied by the actual shallow-water damping. No constant
- // source floor, camera derivative, artificial crest, or fine-ripple trigger is added.
- const float lostEnergy=1-damping*damping;
- return MaximumRate*domain*incoming*breaking*lostEnergy*Smooth(0,.5f,f.height)*Smooth(0,.08f,ht);
-}
-// Factored integrals S_n(x)=integral_0^1 u^n exp(-x*u) du, x<=.05;
-// the series avoids cancellation and division by tiny x in the linear-rate update.
-inline double IntegralSeries(unsigned n,double x){
- double sum=0,term=1;
- for(unsigned k=0;k<10;++k){sum+=term/double(n+k+1);term*=-x/double(k+1);}
- return sum;
-}
-inline State Integrate(const State &previous,float height,float rate,double elapsed,bool source){
- if(!Finite(previous)||!std::isfinite(height)||!std::isfinite(rate)||!std::isfinite(elapsed)||elapsed<0)return {};
- if(elapsed<=1e-6)return previous;
- const double x=elapsed/Lifetime,q=std::exp(-x);
- double density=q*previous.density,age=q*(previous.ageMoment+elapsed*previous.density);
- if(source&&elapsed<=MaximumSourceInterval){
- const double a=Clamp(previous.rate,0,MaximumRate),b=Clamp(rate,0,MaximumRate);
- const double j0=IntegralSeries(0,x),j1=IntegralSeries(1,x),j2=IntegralSeries(2,x);
- const double w0=elapsed*j1,w1=elapsed*(j0-j1);
- const double m0=elapsed*elapsed*j2,m1=elapsed*elapsed*(j1-j2);
- density+=a*w0+b*w1;age+=a*m0+b*m1;
- }
- // Underflow explicitly produces zero; never evaluate inf*0 after an enormous gap.
- if(q==0){density=0;age=0;}
- return {float(density),float(age),height,source?Clamp(rate,0,MaximumRate):0};
-}
-inline State Advance(const Context &c,const Field &field,const State &previous,double elapsed,bool allowSource=true){
- if(elapsed>=0&&elapsed<=1e-6&&Finite(previous))return previous;
- if(!Finite(c)||!Finite(field)||c.wet<.5f||c.admitted<.5f||c.exposure<=0||c.depth<=.15f)return {};
- const float rate=allowSource?Rate(c,field,previous,elapsed):0;
- return Integrate(previous,field.height,rate,elapsed,allowSource&&elapsed<=MaximumSourceInterval);
-}
-inline float Coverage(const State &s,float porous){
- if(!Finite(s)||!std::isfinite(porous)||s.density<=0)return 0;
- const float age=s.ageMoment/s.density;
- const float old=Smooth(.4f,3,age),terminal=1-Smooth(8,14,age);
- return float(-std::expm1(-double(s.density)))*(1-old+old*Clamp(porous,0,1))*terminal;
-}
-// Immutable graph payload. Node identity is its exact level and fixed world-grid key.
-// Zero neighbour IDs mean no connection; IDs are otherwise index+1 (exact in float32).
-struct Node {
- float world[4]={}; // mean-water x,y,exact level,unused
- Context context;
- uint32_t neighbour[4]={}; // -X,+X,-Y,+Y, reciprocal same-level wet segments only
-};
-inline bool ValidGraph(const std::vector<Node> &nodes,double spacing){
- if(nodes.size()>MaxNodes||!std::isfinite(spacing)||spacing<4||spacing>64)return false;
- std::vector<float> levels;std::vector<std::array<float,3>> keys;keys.reserve(nodes.size());
- const unsigned opposite[4]={1,0,3,2};
- for(unsigned i=0;i<nodes.size();++i){const Node &n=nodes[i];
- for(float v:n.world)if(!std::isfinite(v))return false;
- // Every installed slot is valid wet history support, including the no-birth
- // spread margin. Otherwise diffusion could refill a slot Advance just cleared.
- if(!Finite(n.context)||n.context.wet<.5f||n.context.admitted<.5f
- ||n.context.exposure<=0||n.context.depth<=.15f)return false;
- keys.push_back({n.world[2],n.world[1],n.world[0]});
- if(std::find(levels.begin(),levels.end(),n.world[2])==levels.end())levels.push_back(n.world[2]);
- if(levels.size()>MaxLevels)return false;
- for(unsigned side=0;side<4;++side){const uint32_t id=n.neighbour[side];if(!id)continue;
- if(id>nodes.size()||id==i+1)return false;
- const Node &other=nodes[id-1];
- if(other.world[2]!=n.world[2]||other.neighbour[opposite[side]]!=i+1)return false;
- const double dx=other.world[0]-n.world[0],dy=other.world[1]-n.world[1];
- const double expectedX=side==0?-spacing:side==1?spacing:0;
- const double expectedY=side==2?-spacing:side==3?spacing:0;
- if(std::abs(dx-expectedX)>1e-5||std::abs(dy-expectedY)>1e-5)return false;
- }
- }
- std::sort(keys.begin(),keys.end());
- if(std::adjacent_find(keys.begin(),keys.end())!=keys.end())return false;
- return true;
-}
-inline State Diffuse(const State &centre,const std::array<State,4> &neighbours,unsigned mask,double spacing,double elapsed){
- if(!Finite(centre)||!std::isfinite(spacing)||spacing<4||!std::isfinite(elapsed)||elapsed<0||elapsed>MaximumSourceInterval)return {};
- const double a=Diffusivity*elapsed/(spacing*spacing);State out=centre;
- double density=centre.density,age=centre.ageMoment;
- for(unsigned i=0;i<4;++i)if(mask&(1u<<i)){
- if(!Finite(neighbours[i]))return {};
- density+=a*(neighbours[i].density-centre.density);age+=a*(neighbours[i].ageMoment-centre.ageMoment);
- }
- out.density=float(density);out.ageMoment=float(age);return out;
-}
-// Camera-view composition stores source indices/weights, not copied history. Rejected
-// contributions have zero weight; weights are never renormalized across a dry gap.
-struct Lookup {uint32_t node[4]={};float weight[4]={};};
-inline bool ValidLookup(const Lookup &lookup,unsigned count){
- if(count>MaxNodes)return false;double total=0;
- for(unsigned i=0;i<4;++i){if(lookup.node[i]>count||!std::isfinite(lookup.weight[i])||lookup.weight[i]<0
- ||lookup.weight[i]>1||(!lookup.node[i]&&lookup.weight[i]!=0))return false;total+=lookup.weight[i];}
- return total<=1.000001;
-}
-enum class Action {None,Reset,Sample,GapDecay,Invalid};
-struct Plan {Action action=Action::None;double time=0,elapsed=0;uint64_t tick=0;};
-class Clock {
- bool ready=false;uint64_t revision=0,completed=0;double epoch=0,sampled=0,observed=0;
-public:
- // Planning never advances state: commit only after all GPU writes were submitted.
- Plan Inspect(uint64_t rev,double time)const{
- if(!rev||!WaterShoreHistory::ValidTime(time))return {Action::Invalid};
- if(!ready||rev!=revision||time<observed)return {Action::Reset,time,0,0};
- const uint64_t tick=uint64_t((std::max)(0.0,std::floor((time-epoch)/SourceTick+1e-9)));
- if(tick<=completed)return {Action::None,time,0,tick};
- const double elapsed=time-sampled;
- return {elapsed>MaximumSourceInterval?Action::GapDecay:Action::Sample,time,elapsed,tick};
- }
- bool Commit(uint64_t rev,const Plan &plan){
- if(plan.action==Action::Invalid||!rev||!WaterShoreHistory::ValidTime(plan.time))return false;
- const Plan expected=Inspect(rev,plan.time);
- if(expected.action!=plan.action||expected.elapsed!=plan.elapsed||expected.tick!=plan.tick)return false;
- observed=plan.time;
- if(plan.action==Action::None)return true;
- if(plan.action==Action::Reset){ready=true;revision=rev;epoch=sampled=plan.time;completed=0;}
- else {sampled=plan.time;completed=plan.tick;}
- return true;
- }
- double SampledTime()const{return sampled;}
- void Clear(){*this=Clock();}
-};
-
-// Called after the real fftDecodeSamples/fftLimit helpers. Zeroing the fine sample
-// excludes its phase/derivatives while retaining the production broad/medium decode
-// and limiter; no duplicate Phillips equations or differently seeded spectrum exist.
-inline const char *IncidentSource(){return R"HLSL(
-float4 waterSurfIncident(FftMapSamples samples) {
- samples.c=0;samples.cd=0;
- FftSurface field=fftDecodeSamples(samples);
- float3 derivative=fftLimitDerivative(field.displacement);
- return float4(fftLimit(field.displacement).z,
- field.derivativeX.z*derivative.z,field.derivativeY.z*derivative.z,field.incidentCompression);
-}
-)HLSL";}
-inline const char *Source(){return R"HLSL(
-struct WaterSurfContext {float4 coast;float4 surface;float4 admission;};
-// coast=(depth,physicalDistance,outwardX,outwardY)
-// surface=(exposure/spectral support,optical offshore,analyticDamping,spectralDamping)
-// admission=(wet,admitted,0,0); optical A is deliberately absent.
-bool waterSurfContextFinite(WaterSurfContext c){return all(isfinite(c.coast))&&all(isfinite(c.surface))&&all(isfinite(c.admission))
- &&all(abs(c.coast.xy)<=1048576)&&all(abs(c.coast.zw)<=1024)&&all(c.surface>=0)&&all(c.surface<=1)
- &&all(c.admission.xy>=0)&&all(c.admission.xy<=1);}
-bool waterSurfFieldFinite(float4 f){return all(isfinite(f))&&abs(f.x)<=64&&all(abs(f.yz)<=1024)&&abs(f.w)<=1048576;}
-float waterSurfDomain(WaterSurfContext c){
- if(!waterSurfContextFinite(c)||c.admission.x<.5||c.admission.y<.5||c.surface.x<=0||c.coast.x<=.15||c.coast.y<0)return 0;
- return smoothstep(.15,.8,c.coast.x)*(1-smoothstep(8,12,c.coast.x))
- *(1-smoothstep(96,128,c.coast.y))*saturate(c.surface.x);
-}
-bool waterSurfStateFinite(float4 s){return all(isfinite(s))&&s.x>=0&&s.x<=16&&s.y>=0&&s.y<=1024&&abs(s.z)<=64&&s.w>=-1&&s.w<=1.2;}
-float4 waterSurfBlend(float4 analytic,float4 spectral,float weight){
- if(!waterSurfFieldFinite(analytic)||!waterSurfFieldFinite(spectral)||!isfinite(weight))return float4(0,0,0,1);
- float w=saturate(weight);return float4(analytic.xyz+(spectral.xyz-analytic.xyz)*w,1+(spectral.w-1)*w);
-}
-float waterSurfRate(WaterSurfContext c,float4 field,float4 previous,float dt){
- float domain=waterSurfDomain(c);
- if(domain<=0||!waterSurfFieldFinite(field)||!waterSurfStateFinite(previous)||previous.w<0||!isfinite(dt)||dt<=.000001||dt>.25||field.x<=0)return 0;
- float n=length(c.coast.zw),slope=length(field.yz);if(n<=.00000001||slope<=.00000001)return 0;
- float ht=(field.x-previous.z)/dt;if(!isfinite(ht)||!(ht>0))return 0;
- float incoming=smoothstep(0,.25,dot(field.yz/slope,c.coast.zw/n));
- float breaking=max(smoothstep(.4,.85,2*field.x/max(c.coast.x+.5,1)),smoothstep(.04,.30,1-field.w));
- float damping=saturate(lerp(c.surface.z,c.surface.w,saturate(c.surface.x)));
- return 1.2*domain*incoming*breaking*(1-damping*damping)*smoothstep(0,.5,field.x)*smoothstep(0,.08,ht);
-}
-float3 waterSurfIntegrals(float x){
- float3 sum=0;float term=1;
- [unroll]for(int k=0;k<10;++k){sum+=term/float3(k+1,k+2,k+3);term*=-x/(k+1);}
- return sum;
-}
-float4 waterSurfIntegrate(float4 previous,float height,float rate,float dt,bool source){
- if(!waterSurfStateFinite(previous)||!isfinite(height)||!isfinite(rate)||!isfinite(dt)||dt<0)return float4(0,0,0,-1);
- if(dt<=.000001)return previous;
- float x=dt/5,q=exp(-x);float density=q*previous.x,age=q*(previous.y+dt*previous.x);
- if(source&&dt<=.25){
- float a=clamp(previous.w,0,1.2),b=clamp(rate,0,1.2);float3 j=waterSurfIntegrals(x);
- float w0=dt*j.y,w1=dt*(j.x-j.y),m0=dt*dt*j.z,m1=dt*dt*(j.y-j.z);
- density+=a*w0+b*w1;age+=a*m0+b*m1;
- }
- if(q==0){density=0;age=0;}
- return float4(density,age,height,source?clamp(rate,0,1.2):0);
-}
-float4 waterSurfAdvance(WaterSurfContext c,float4 field,float4 previous,float dt,bool allowSource){
- if(dt>=0&&dt<=.000001&&waterSurfStateFinite(previous))return previous;
- if(!waterSurfContextFinite(c)||!waterSurfFieldFinite(field)||c.admission.x<.5||c.admission.y<.5||c.surface.x<=0||c.coast.x<=.15)return float4(0,0,0,-1);
- float rate=allowSource?waterSurfRate(c,field,previous,dt):0;
- return waterSurfIntegrate(previous,field.x,rate,dt,allowSource&&dt<=.25);
-}
-float4 waterSurfDiffuse(float4 centre,float4 a,float4 b,float4 c,float4 d,uint mask,float spacing,float dt){
- if(!waterSurfStateFinite(centre)||!isfinite(spacing)||spacing<4||!isfinite(dt)||dt<0||dt>.25)return float4(0,0,0,-1);
- float amount=2*dt/(spacing*spacing);float2 value=centre.xy;
- if(mask&1){if(!waterSurfStateFinite(a))return float4(0,0,0,-1);value+=amount*(a.xy-centre.xy);}
- if(mask&2){if(!waterSurfStateFinite(b))return float4(0,0,0,-1);value+=amount*(b.xy-centre.xy);}
- if(mask&4){if(!waterSurfStateFinite(c))return float4(0,0,0,-1);value+=amount*(c.xy-centre.xy);}
- if(mask&8){if(!waterSurfStateFinite(d))return float4(0,0,0,-1);value+=amount*(d.xy-centre.xy);}
- return float4(value,centre.zw);
-}
-float waterSurfCoverage(float4 state,float porous){
- if(!waterSurfStateFinite(state)||!isfinite(porous)||state.x<=0)return 0;
- float age=state.y/state.x,old=smoothstep(.4,3,age);
- return (1-exp(-state.x))*lerp(1,saturate(porous),old)*(1-smoothstep(8,14,age));
-}
-)HLSL";}
-} // namespace WaterCoastalSurf
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterCoastalView.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterCoastalView.h
deleted file mode 100644
index f2581afbd..000000000
--- a/GeneralsMD/Code/Libraries/Include/Platform/WaterCoastalView.h
+++ /dev/null
@@ -1,112 +0,0 @@
-/* Bounded view-to-physical-coast interpolation. No state copying or GPU access. */
-#pragma once
-#include "Platform/WaterCoastalDomain.h"
-#include <limits>
-
-namespace WaterCoastalView {
-using Mapping=WaterShoreHistory::Mapping;
-using Lookup=WaterCoastalSurf::Lookup;
-constexpr unsigned MaxSide=WaterCoastalSurf::MaxViewSide;
-constexpr size_t MaxPixels=size_t(MaxSide)*MaxSide;
-// Helper-call allowance, not a CPU-instruction budget: one texel setup/At unit
-// plus at most four bounded Topology::Find and four Support::Allows calls. At
-// has a bounded binary search; Find/Allows bound probes or clipped vertices.
-constexpr size_t WorkPerPixel=9,MaxBuildWork=WorkPerPixel*MaxPixels;
-// Separate bounded coverage work: tile searches/corner checks/polygon edge visits.
-constexpr size_t MaxFootprintTiles=49,MaxFootprintBuildWork=64*MaxPixels;
-inline bool FitsFloat(double value){
- const double limit=(std::numeric_limits<float>::max)();
- return std::isfinite(value)&&value>=-limit&&value<=limit;
-}
-inline bool ExactFloat(double value){return FitsFloat(value)&&double(float(value))==value;}
-inline bool ValidLevel(double level){return ExactFloat(level);}
-inline bool ValidMapping(const Mapping&m){
- return m.widthPixels>0&&m.heightPixels>0&&m.widthPixels<=MaxSide&&m.heightPixels<=MaxSide
- &&ExactFloat(m.originX)&&ExactFloat(m.originY)&&ExactFloat(m.widthWorld)&&ExactFloat(m.heightWorld)
- &&m.widthWorld>0&&m.heightWorld>0&&FitsFloat(m.originX+m.widthWorld)
- &&FitsFloat(m.originY+m.heightWorld)&&std::isfinite(1.f/float(m.widthWorld))
- &&std::isfinite(1.f/float(m.heightWorld));
-}
-inline bool SameMapping(const Mapping&a,const Mapping&b){
- return a.originX==b.originX&&a.originY==b.originY&&a.widthWorld==b.widthWorld
- &&a.heightWorld==b.heightWorld&&a.widthPixels==b.widthPixels&&a.heightPixels==b.heightPixels;
-}
-inline WaterShoreSupport::AreaResult FilterFootprint(const WaterCoastalDomain::Domain&domain,
- const Mapping&m,double level,unsigned x,unsigned y,size_t &remaining){
- using Result=WaterShoreSupport::AreaResult;const auto &g=domain.Grid();
- const double dx=m.widthWorld/m.widthPixels,dy=m.heightWorld/m.heightPixels;
- // The exact bilinear tent is centre +/- one texel spacing. Its enclosing 3x3
- // pixel cells add half a texel of coordinate/filter margin. Clip to the chart:
- // the presentation rejects UV outside it, and clamp only extends boundary cells.
- const double x0=(m.originX+(x?double(x-1):0)*dx-g.originX)/g.spacing;
- const double y0=(m.originY+(y?double(y-1):0)*dy-g.originY)/g.spacing;
- const double x1=(m.originX+(std::min)(double(x)+2,double(m.widthPixels))*dx-g.originX)/g.spacing;
- const double y1=(m.originY+(std::min)(double(y)+2,double(m.heightPixels))*dy-g.originY)/g.spacing;
- if(!std::isfinite(x0)||!std::isfinite(y0)||!std::isfinite(x1)||!std::isfinite(y1)
- ||x0<(std::numeric_limits<int32_t>::min)()||y0<(std::numeric_limits<int32_t>::min)()
- ||x1>=(std::numeric_limits<int32_t>::max)()||y1>=(std::numeric_limits<int32_t>::max)()
- ||x1<=x0||y1<=y0)return Result::Unsupported;
- const int32_t loX=int32_t(std::floor(x0)),loY=int32_t(std::floor(y0));
- const int32_t hiX=int32_t(std::ceil(x1)-1),hiY=int32_t(std::ceil(y1)-1);
- const uint64_t nx=uint64_t(int64_t(hiX)-loX+1),ny=uint64_t(int64_t(hiY)-loY+1);
- if(nx>MaxFootprintTiles||ny>MaxFootprintTiles||nx*ny>MaxFootprintTiles)return Result::OverBudget;
- for(int32_t iy=loY;iy<=hiY;++iy)for(int32_t ix=loX;ix<=hiX;++ix){
- if(!remaining)return Result::OverBudget;--remaining;
- const auto tile=domain.Support().At(ix,iy,level,0,0);
- const Result result=tile.CoversRectangle((std::max)(0.,x0-ix),(std::max)(0.,y0-iy),
- (std::min)(1.,x1-ix),(std::min)(1.,y1-iy),remaining);
- if(result!=Result::Covered)return result;
- }
- return Result::Covered;
-}
-// Texel centres use world=origin+(pixel+.5)*extent/count. The later shader uses
-// UV=(world-origin)/extent, with NO extra half-texel offset or flipped Y axis.
-// Float-exact metadata prevents a second rounded origin/extent in those uniforms.
-inline bool Build(const WaterCoastalDomain::Domain&domain,const Mapping&mapping,double level,
- std::vector<Lookup>&output,size_t workAllowance=MaxBuildWork,
- size_t footprintAllowance=MaxFootprintBuildWork){
- if(!ValidMapping(mapping)||!ValidLevel(level))return false;
- const size_t count=size_t(mapping.widthPixels)*mapping.heightPixels;
- if(count*WorkPerPixel>(std::min)(workAllowance,MaxBuildWork))return false;
- const auto &topology=domain.Topology();const auto &grid=domain.Grid();
- const size_t nodes=domain.Nodes().size();
- if(nodes>WaterCoastalSurf::MaxNodes||topology.Cells().size()!=nodes||!WaterShoreHistory::ValidGrid(grid))return false;
- size_t remainingFootprint=(std::min)(footprintAllowance,MaxFootprintBuildWork);
- std::vector<Lookup> next(count);
- for(unsigned y=0;y<mapping.heightPixels;++y)for(unsigned x=0;x<mapping.widthPixels;++x){
- const double wx=mapping.originX+(double(x)+.5)*mapping.widthWorld/mapping.widthPixels;
- const double wy=mapping.originY+(double(y)+.5)*mapping.heightWorld/mapping.heightPixels;
- const double px=(wx-grid.originX)/grid.spacing,py=(wy-grid.originY)/grid.spacing;
- // An entirely off-domain view remains a valid empty lookup. Clamp neither
- // coordinates nor indices: either would smear an outer row into distant water.
- 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)())continue;
- const int32_t ix=int32_t(std::floor(px)),iy=int32_t(std::floor(py));
- const double fx=px-ix,fy=py-iy;
- const auto support=domain.Support().At(ix,iy,level,fx,fy);
- Lookup &lookup=next[size_t(y)*mapping.widthPixels+x];
- for(unsigned dy=0;dy<2;++dy)for(unsigned dx=0;dx<2;++dx){
- const double weight=(dx?fx:1-fx)*(dy?fy:1-fy);
- if(weight<=0)continue;
- const int index=topology.Find(ix+int32_t(dx),iy+int32_t(dy),level);
- if(index<0)continue;
- if(size_t(index)>=nodes)return false;
- if(!support.Allows(dx,dy))continue;
- const float stored=float(weight);if(stored<=0)continue;
- const unsigned corner=dy*2+dx;
- lookup.node[corner]=uint32_t(index)+1;lookup.weight[corner]=stored;
- }
- // Missing/dry/wrong-level/gap contributions stay exactly zero. There is no
- // normalization of retained weights and no nearest-node ownership shortcut.
- if(!WaterCoastalSurf::ValidLookup(lookup,unsigned(nodes)))return false;
- bool nonzero=false;for(unsigned c=0;c<4;++c)nonzero=nonzero||lookup.weight[c]>0;
- if(nonzero){
- const auto area=FilterFootprint(domain,mapping,level,x,y,remainingFootprint);
- if(area==WaterShoreSupport::AreaResult::OverBudget)return false;
- if(area!=WaterShoreSupport::AreaResult::Covered)lookup={};
- }
- }
- output.swap(next);return true;
-}
-} // namespace WaterCoastalView
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterFftSampling.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterFftSampling.h
index d3254a6ab..8aea914cf 100644
--- a/GeneralsMD/Code/Libraries/Include/Platform/WaterFftSampling.h
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterFftSampling.h
@@ -3,8 +3,6 @@
#pragma once
#include <string>
#include <cstdio>
-#include <cstdlib>
-#include <cstring>
#include "Platform/WaterFftGeometry.h"
#include "Platform/WaterVesselWaves.h"
#include "Platform/WaterFftFiltering.h"
@@ -13,10 +11,6 @@
#include "Platform/ModernWaterMaterial.h"
namespace WaterFftSampling {
-inline bool Enabled() {
- const char *value=std::getenv("ZH_WATER_FFT");
- return !value || std::strcmp(value,"0")!=0;
-}
// The reference's close water-level camera uses metre-sized waves. Generals' RTS camera
// requires a larger render scale; scale wavelength and displacement together, not normals.
constexpr float WorldScale=WaterFftSpectrum::WorldScale;
@@ -46,8 +40,6 @@ inline std::string UniformSource(const char *name,unsigned slot,bool visual_hull
float4 FoamHistoryParameters;
float4 ContactHullData[80];
float4 FoamFillLights[4];
- float4 CoastalArea;
- float4 CoastalParams;
)HLSL";
#define MODERN_WATER_HLSL_UNIFORM(name) " float4 " #name ";\n"
source+=MODERN_WATER_MATERIAL_UNIFORMS(MODERN_WATER_HLSL_UNIFORM);
@@ -95,7 +87,7 @@ FftHorizontalRegistration fftHorizontalRegistration(float2 p,float3 raw,float3 r
}
)HLSL";
}
-inline std::string VertexSource(bool bowLift=false,bool bowShoulder=WaterBowShoulder::Enabled())
+inline std::string VertexSource()
{
return std::string(R"HLSL(
Texture2D FftDisplacement0 : register(t0);
@@ -104,7 +96,7 @@ Texture2D FftDisplacement1 : register(t1);
SamplerState FftSampler1 : register(s1);
Texture2D FftDisplacement2 : register(t2);
SamplerState FftSampler2 : register(s2);
-)HLSL")+CommonSource()+(bowLift?WaterBowLift::Source():std::string())+WaterVesselWaves::Source(true,bowShoulder)+R"HLSL(
+)HLSL")+CommonSource()+WaterBowLift::Source()+WaterVesselWaves::Source()+R"HLSL(
float3 fftRawDisplacement(float2 p) {
float3 a=FftDisplacement0.SampleLevel(FftSampler0,p/(450.0*fftWorldScale),0).xyz;
float3 b=FftDisplacement1.SampleLevel(FftSampler1,p/(103.0*fftWorldScale),0).xyz;
@@ -112,10 +104,10 @@ float3 fftRawDisplacement(float2 p) {
return (a.xzy*float3(-1.2,-1.2,1)+b.xzy*float3(-1.5,-1.5,1)
+c.xzy*float3(-1.5,-1.5,1))*fftWorldScale;
}
-)HLSL"+(bowLift?R"HLSL(float3 fftVertexBowDisplacement(float2 p,float level,float horizontalScale,out float bowHeight) {
- bowHeight=0;)HLSL":R"HLSL(float3 fftVertexDisplacement(float2 p,float level,float horizontalScale) {)HLSL")+R"HLSL(
+float3 fftVertexBowDisplacement(float2 p,float level,float horizontalScale,out float bowHeight) {
+ bowHeight=0;
float3 displacement=fftRawDisplacement(p);
- if(FftParameters.y>0.5) {
+ {
int count=clamp((int)HullParameters.x,0,8);
float3 oldBow[8];
for(int h=0;h<count;++h) {
@@ -124,30 +116,25 @@ float3 fftRawDisplacement(float2 p) {
displacement+=vesselReflectedValue(fftRawDisplacement(reflected.samplePosition),reflected);
displacement.z+=vesselGeneratedWave(p,level,WaterParameters.x,h,oldBow[h]).x;
}
- if()HLSL"+(bowShoulder?std::string("true"):std::string("horizontalScale!=0.0"))+R"HLSL() {
+ {
float2 position=fftHorizontalPosition(p,displacement,horizontalScale);
for(int h=0;h<count;++h)
-)HLSL"+(bowLift?R"HLSL( {float currentBow=vesselGeneratedBow(position,level,h).x;
- displacement.z+=currentBow-oldBow[h].x;bowHeight+=currentBow;})HLSL":R"HLSL( displacement.z+=vesselGeneratedBow(position,level,h).x-oldBow[h].x;)HLSL")+R"HLSL(
-)HLSL"+(bowLift?R"HLSL( } else {for(int h=0;h<count;++h)bowHeight+=oldBow[h].x;}
+ {float currentBow=vesselGeneratedBow(position,level,h).x;
+ displacement.z+=currentBow-oldBow[h].x;bowHeight+=currentBow;}
+ }
}
return fftLimit(displacement);
}
float3 fftVertexDisplacement(float2 p,float level,float horizontalScale) {
float ignored;return fftVertexBowDisplacement(p,level,horizontalScale,ignored);
}
-// Compatibility callers without mesh metadata retain their unregistered model.)HLSL":R"HLSL( }
- }
- return fftLimit(displacement);
-}
-// Compatibility callers without mesh metadata retain their unregistered model.)HLSL")+R"HLSL(
float3 fftVertexDisplacement(float2 p,float level) {return fftVertexDisplacement(p,level,0.0);}
float3 fftVertexDisplacement(float2 p) {return fftVertexDisplacement(p,WaterParameters.w);}
)HLSL";
}
// Add a water-only wrapper to the generated fixed vertex program. It retains the engine's
// original projection, shroud coordinate generation and fog after moving the actual vertex.
-inline bool WrapVertex(std::string &hlsl,bool bowLift=WaterBowLift::Enabled(),bool bowShoulder=WaterBowShoulder::Enabled())
+inline bool WrapVertex(std::string &hlsl)
{
const std::string entry="Output main(Input input)";
const size_t at=hlsl.find(entry);
@@ -155,9 +142,9 @@ inline bool WrapVertex(std::string &hlsl,bool bowLift=WaterBowLift::Enabled(),bo
|| hlsl.find("float2 TexCoord1")==std::string::npos) return false;
hlsl.replace(at,entry.size(),"Output waterFixedVertex(Input input)");
hlsl+=UniformSource("WaterVertexParameters",1);
- hlsl+=VertexSource(bowLift,bowShoulder);
+ hlsl+=VertexSource();
hlsl+=WaterWaveCageShader::Source(true);
- hlsl+=std::string(R"HLSL(
+ hlsl+=R"HLSL(
Output main(Input input)
{
float2 parameter=input.Position.xy;
@@ -170,9 +157,9 @@ Output main(Input input)
if(weight>0.0) {
float damping=vesselApplyHullDamping(parameter,input.TexCoord1.y,
float3(freeDamping,0,0),float3(offshore,0,0)).x;
-)HLSL")+(bowLift?R"HLSL( float bowHeight;
+ float bowHeight;
float3 displacement=fftVertexBowDisplacement(parameter,input.TexCoord1.y,horizontalWeight*damping,bowHeight);
- float lifted=fftBowLift(float3(bowHeight,0,0),float3(freeDamping,0,0),float3(damping,0,0)).x;)HLSL":R"HLSL( float3 displacement=fftVertexDisplacement(parameter,input.TexCoord1.y,horizontalWeight*damping);)HLSL")+R"HLSL(
+ float lifted=fftBowLift(float3(bowHeight,0,0),float3(freeDamping,0,0),float3(damping,0,0)).x;
WaveCage cage=waveCage(parameter,input.TexCoord1.y);
float cageAmount=cage.support;
float3 cageDisplacement=0;
@@ -183,7 +170,7 @@ Output main(Input input)
cageDisplacement=waveCageFloor(parameter,input.TexCoord1.y,waveCageMap(cage,displacement)*cageObstacle);
}
input.Position.xy+=lerp(displacement.xy*(horizontalWeight*damping),cageDisplacement.xy*weight,cageAmount);
- input.Position.z=input.TexCoord1.y+)HLSL"+(bowLift?R"HLSL(lerp(originalHeight,displacement.z*damping+lifted,weight))HLSL":R"HLSL(lerp(originalHeight,displacement.z*damping,weight))HLSL")+R"HLSL(;
+ input.Position.z=input.TexCoord1.y+lerp(originalHeight,displacement.z*damping+lifted,weight);
input.Position.z=lerp(input.Position.z,input.TexCoord1.y+lerp(originalHeight,cageDisplacement.z,weight),cageAmount);
}
input.Normal=float3(0,0,1);
@@ -196,25 +183,17 @@ Output main(Input input)
)HLSL";
return true;
}
-inline std::string PixelSource(bool bowLift=false,bool bowShoulder=WaterBowShoulder::Enabled(),bool textureArray=false)
+inline std::string PixelSource()
{
- std::string source=CommonSource()+(bowLift?WaterBowLift::Source():std::string())+WaterVesselWaves::Source(true,bowShoulder)+WaterFftFiltering::Source()+R"HLSL(
-)HLSL"+(bowLift?R"HLSL(struct FftSurface {
+ std::string source=CommonSource()+WaterBowLift::Source()+WaterVesselWaves::Source()+WaterFftFiltering::Source()+R"HLSL(
+struct FftSurface {
float3 bow;
- float bowLimitedDelta;
- float3 displacement;)HLSL":R"HLSL(struct FftSurface {
- float3 displacement;)HLSL")+R"HLSL(
+ float3 displacement;
float3 derivativeX;
float3 derivativeY;
- float compression;
float incidentCompression;
float3 contactIncident;
- float vesselHeight;
float vesselCrest;
- // Diagnostic-only outputs. Unused normal rendering removes this accumulator and the
- // second limiter through dead-code elimination; no displacement/normal inputs change.
- float generatedRaw;
- float generatedHeight;
float3 shadingDisplacement;
float3 shadingDerivativeX;
float3 shadingDerivativeY;
@@ -296,13 +275,12 @@ FftSurface fftSurface(float2 p,float level,float footprint,float3 horizontalScal
FftSurface value,shading;
fftRawAndShadingSurface(p,shadingLod,value,shading);
float reflectionVariance=1.0;
- float oldHeight=fftLimit(value.displacement).z;
// Mirroring a field around a hull changes its parameterization; a compressed mirror
// Jacobian alone is not a breaking wave. Preserve incident whitecaps and add only the
// restrained bow/wake crest signal below, while using full derivatives for the normals.
// fftDecodeSamples already retained the broad/medium incident compression before
// any hull reflection or generated vessel packet changes this full surface.
- if(FftParameters.y>0.5) {
+ {
int count=clamp((int)HullParameters.x,0,8);
float3 oldBow[8];float oldGenerated[8];
for(int h=0;h<count;++h) {
@@ -325,8 +303,7 @@ FftSurface fftSurface(float2 p,float level,float footprint,float3 horizontalScal
incident.derivativeY,float2(0,1),reflected);
}
float3 generated=vesselGeneratedWave(p,level,WaterParameters.x,h,oldBow[h]);
-)HLSL"+(bowLift?R"HLSL( oldGenerated[h]=generated.x;
- if()HLSL"+(bowShoulder?std::string("false"):std::string("!any(horizontalScale!=0.0)"))+R"HLSL()value.bow+=oldBow[h];)HLSL":R"HLSL( oldGenerated[h]=generated.x;)HLSL")+R"HLSL(
+ oldGenerated[h]=generated.x;
if(filtered) {
shading.displacement.z+=generated.x;
shading.derivativeX.z+=generated.y;
@@ -336,19 +313,18 @@ FftSurface fftSurface(float2 p,float level,float footprint,float3 horizontalScal
value.derivativeX.z+=generated.y;
value.derivativeY.z+=generated.z;
value.vesselCrest+=max(generated.x,0.0)*0.32;
- value.generatedRaw+=generated.x;
}
- if()HLSL"+(bowShoulder?std::string("true"):std::string("any(horizontalScale!=0.0)"))+R"HLSL() {
+ {
// The physical mip-zero map is shared even when reflected lighting is filtered.
// Retaining the original loop above preserves stern/history accumulation and
// permits an exact zero-chop difference, without another FFT texture sample.
FftHorizontalRegistration map=fftHorizontalRegistration(p,value.displacement,
value.derivativeX,value.derivativeY,horizontalScale);
for(int h=0;h<count;++h) {
- )HLSL"+(bowLift?R"HLSL(float3 bow=vesselGeneratedBow(map.position,level,h);
+ float3 bow=vesselGeneratedBow(map.position,level,h);
bow.yz=float2(dot(bow.yz,map.derivativeX),dot(bow.yz,map.derivativeY));
value.bow+=bow;
- float3 correction=bow-oldBow[h];)HLSL":R"HLSL(float3 correction=vesselRegisteredBowDifference(map.position,map.derivativeX,map.derivativeY,level,h,oldBow[h]);)HLSL")+R"HLSL(
+ float3 correction=bow-oldBow[h];
if(filtered) {
shading.displacement.z+=correction.x;
shading.derivativeX.z+=correction.y;
@@ -358,20 +334,11 @@ FftSurface fftSurface(float2 p,float level,float footprint,float3 horizontalScal
value.derivativeX.z+=correction.y;
value.derivativeY.z+=correction.z;
value.vesselCrest+=(max(oldGenerated[h]+correction.x,0.0)-max(oldGenerated[h],0.0))*0.32;
- value.generatedRaw+=correction.x;
}
}
}
float3 derivative=fftLimitDerivative(value.displacement);
- float withoutGenerated=fftVerticalBound*tanh((value.displacement.z-value.generatedRaw)/fftVerticalBound);
-)HLSL"+(bowLift?R"HLSL( // Same physical sample and phase, removing only the registered bow contribution.
- // This diagnostic excludes the extra floor lift, which is applied with mesh damping below.
- float withoutBow=fftVerticalBound*tanh((value.displacement.z-value.bow.x)/fftVerticalBound);
-)HLSL":std::string())+R"HLSL(
value.displacement=fftLimit(value.displacement);
-)HLSL"+(bowLift?R"HLSL( value.bowLimitedDelta=value.displacement.z-withoutBow;
-)HLSL":std::string())+R"HLSL(
- value.generatedHeight=value.displacement.z-withoutGenerated;
value.derivativeX*=derivative;
value.derivativeY*=derivative;
if(filtered) {
@@ -387,57 +354,18 @@ FftSurface fftSurface(float2 p,float level,float footprint,float3 horizontalScal
value.shadingDerivativeX=value.derivativeX;
value.shadingDerivativeY=value.derivativeY;
}
- value.vesselHeight=value.displacement.z-oldHeight;
value.vesselCrest=saturate(value.vesselCrest);
- value.compression=(1+value.derivativeX.x)*(1+value.derivativeY.y)
- -value.derivativeX.y*value.derivativeY.x;
return value;
}
-// Compatibility callers without mesh metadata retain their unregistered model.
FftSurface fftSurface(float2 p,float level,float footprint) {return fftSurface(p,level,footprint,float3(0,0,0));}
FftSurface fftSurface(float2 p,float level) {return fftSurface(p,level,0.0);}
FftSurface fftSurface(float2 p) {return fftSurface(p,WaterParameters.w);}
-float3 fftPressureDebug(FftSurface surface,float weight,float damping,float generatedFoam) {
- return float3(max(surface.generatedRaw,0.0)/8.0,
- max(surface.generatedHeight,0.0)*weight*damping/3.85,generatedFoam);
-}
-float3 fftPressureRetentionDebug(FftSurface surface,float weight,float damping,float generatedFoam) {
- // Gaussian tails smaller than this raw height are below meaningful float subtraction
- // resolution at the limiter. Do not mislabel their cancellation as a large red footprint.
- if(surface.generatedRaw<=0.0001) return 0;
- float isolated=fftVerticalBound*tanh(surface.generatedRaw/fftVerticalBound);
- return float3(1.0-saturate(surface.generatedHeight/max(isolated,0.000001)),
- weight*damping,generatedFoam);
-}
-)HLSL"+(bowLift?R"HLSL(float3 fftBowRetentionDebug(FftSurface surface,float weight,float freeDamping,float damping) {
- // R: registered bow / 8 world units. G: its actual marginal final rise / V.
- // B: available mesh envelope. Keep stern/reflected/incident height in the same limiter;
- // an isolated tanh(bow/V) cannot measure the loss at the current FFT phase.
- float lifted=fftBowLift(surface.bow,float3(freeDamping,0,0),float3(damping,0,0)).x;
- return float3(max(surface.bow.x,0.0)/8.0,
- max(damping*surface.bowLimitedDelta+lifted,0.0)*weight/fftVerticalBound,
- weight*freeDamping);
-}
-)HLSL":std::string())+R"HLSL(
float2 fftParameterGradient(float value,float2 px,float2 py) {
float det=px.x*py.y-px.y*py.x;
float inverse=abs(det)>0.000001?1.0/det:0.0;
return float2(ddx(value)*py.y-ddy(value)*px.y,ddy(value)*px.x-ddx(value)*py.x)*inverse;
}
)HLSL";
- if(textureArray) {
- // Preserve the independent-map source contract used by the coastal decoder and
- // numerical fixtures; only the material's native binding changes.
- std::string sampling;
- for(unsigned layer=0;layer<6;++layer) {
- const std::string i=std::to_string(layer),stage=std::to_string(layer+8);
- const std::string from="Texture"+stage+".SampleLevel(Sampler"+stage+",",to="fftMap"+i+"(";
- for(size_t at=source.find(from);at!=std::string::npos;at=source.find(from,at+to.size()))
- source.replace(at,from.size(),to);
- sampling+="float4 fftMap"+i+"(float2 uv,float lod) { return OceanMaps.SampleLevel(OceanSampler,float3(uv,"+i+"),lod); }\n";
- }
- source=sampling+source;
- }
return source;
}
} // namespace WaterFftSampling
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterHullModel.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterHullModel.h
index 3e0336383..780314490 100644
--- a/GeneralsMD/Code/Libraries/Include/Platform/WaterHullModel.h
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterHullModel.h
@@ -125,15 +125,12 @@ float WaterHullSignedDistance(float2 p,int baseIndex,int count) {
// Depends on the production oceanNoise function and HullParameters/HullData declarations.
// Tests call this same emitted shader, so contact and moving-wake behavior cannot drift.
-inline std::string GetEffectsHlslSource(bool contactContours=false,bool visualContact=false) {
- // Isolated legacy fixtures can omit the optional contact block. Production always uses
- // it, with an invalid/empty contact falling back to the exact mean-waterline contour.
- std::string source=contactContours?R"HLSL(
+inline std::string GetEffectsHlslSource() {
+ // An invalid or empty contact packet falls back to the exact mean-waterline contour.
+ std::string source=R"HLSL(
float4 WaterContactRegister(int index) {
return ContactHullData[(index/10)*10].w>=3.0?ContactHullData[index]:HullData[index];
}
-)HLSL":R"HLSL(
-float4 WaterContactRegister(int index) { return HullData[index]; }
)HLSL";
source=std::string(WaterHullContactFoam::Source())+source;
source+=R"HLSL(
@@ -204,11 +201,11 @@ float3 oceanHullEffects(float2 world,float level,float time,float offshore,float
float bowContact=exposed*(1.0-smoothstep(bowWidth,bowWidth+aa,distance))*bowRegion
*moving*(0.45+0.55*smoothstep(0.25,0.7,flecks));
)HLSL";
- if(visualContact) source+=" if(VisualHullMeta[h].w<0.5) {\n";
+ source+=" if(VisualHullMeta[h].w<0.5) {\n";
source+=R"HLSL( foam=max(foam,max(contact,bowContact*0.82));
turbulence=max(turbulence,exposed*outer*(collision*0.18+moving*0.25)+bowContact*0.4);
)HLSL";
- if(visualContact) source+=" }\n";
+ source+=" }\n";
source+=R"HLSL( }
if(speed>0.3) {
float2 wakePoint=local-stern;
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterHullVisual.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterHullVisual.h
index 8dae7831c..1d2f4ab4d 100644
--- a/GeneralsMD/Code/Libraries/Include/Platform/WaterHullVisual.h
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterHullVisual.h
@@ -3,17 +3,9 @@
#include <algorithm>
#include <cmath>
#include <cstddef>
-#include <cstdlib>
-#include <cstring>
#include <limits>
namespace WaterHullVisual {
-// One launch-time policy for mesh collection, packet upload and shader generation.
-// Unset selects the validated mesh path; explicit values such as 0 disable it.
-inline bool Enabled() {
- const char *value=std::getenv("ZH_WATER_HULL_CONTACT");
- return !value || std::strcmp(value,"mesh")==0;
-}
constexpr unsigned MaxVertices=64, MaxTriangles=96, RegistersPerHull=88;
constexpr unsigned MaxSourceTriangles=8192;
// Keep every intermediate float product finite. Native vessel local coordinates
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterHullVisualLayout.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterHullVisualLayout.h
index 21079d4a5..c964f88f1 100644
--- a/GeneralsMD/Code/Libraries/Include/Platform/WaterHullVisualLayout.h
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterHullVisualLayout.h
@@ -6,7 +6,7 @@ enum : unsigned {
MaxHulls=8, MaxVertices=64, MaxTriangles=96, RegistersPerHull=88,
PacketRegisters=MaxHulls*RegistersPerHull,
MetadataRegister=176, PacketRegister=192, PixelRegisterCount=896,
- FragmentCommonRegisters=196, VertexCommonRegisters=188,
+ FragmentCommonRegisters=194, VertexCommonRegisters=186,
BlockCount=3, Block0Registers=256, Block1Registers=256, Block2Registers=192
};
constexpr unsigned BlockRegisters(unsigned block) {
diff --git a/GeneralsMD/Code/Libraries/Include/Platform/WaterVesselWaves.h b/GeneralsMD/Code/Libraries/Include/Platform/WaterVesselWaves.h
index 55c482dc4..1e92c901a 100644
--- a/GeneralsMD/Code/Libraries/Include/Platform/WaterVesselWaves.h
+++ b/GeneralsMD/Code/Libraries/Include/Platform/WaterVesselWaves.h
@@ -3,15 +3,9 @@
#include <string>
#include <algorithm>
#include <cmath>
-#include <cstdlib>
-#include <cstring>
#include "Platform/WaterBowShoulder.h"
namespace WaterVesselWaves {
-inline bool Enabled() {
- const char *value=std::getenv("ZH_WATER_VESSEL_WAVES");
- return !value || std::strcmp(value,"0")!=0;
-}
// Render-only pressure response uses measured contact half-beam and velocity. Keeping these
// constants in one list makes the CPU refinement estimate and both shader stages agree.
#define WATER_VESSEL_BOW_CONSTANTS(X) \
@@ -23,7 +17,6 @@ inline bool Enabled() {
WATER_VESSEL_BOW_CONSTANTS(WATER_VESSEL_BOW_CONSTANT)
#undef WATER_VESSEL_BOW_CONSTANT
struct BowPressureParameters { float along=0,across=0,amplitude=0; };
-struct BowPressureSample { float height=0,dAlong=0,dAcross=0; };
inline BowPressureParameters BowPressure(float halfBeam,float speed) {
if(!std::isfinite(halfBeam)||!std::isfinite(speed)||halfBeam<0||speed<0) return {};
const float u=(std::max)(0.0f,(std::min)(speed,BowSpeedMax)-BowRestSpeed);
@@ -34,16 +27,6 @@ inline BowPressureParameters BowPressure(float halfBeam,float speed) {
p.amplitude=(std::max)(BowHeadMin,(std::min)(BowHeadMax,BowHeadBeam*std::sqrt(halfBeam)))*response;
return p;
}
-inline BowPressureSample EvaluateBowPressure(const BowPressureParameters &p,float along,float across) {
- if(!std::isfinite(p.along)||!std::isfinite(p.across)||!std::isfinite(p.amplitude)||
- !std::isfinite(along)||!std::isfinite(across)||p.along<=0||p.across<=0||p.amplitude<=0) return {};
- const float q=across/p.across,r=std::sqrt(1.0f+q*q);
- const float shifted=along/p.along+BowCurvature*(r-1.0f);
- const float h=p.amplitude*std::exp(-shifted*shifted-q*q);
- if(h==0) return {}; // Avoid an underflowed Gaussian multiplying an extreme coordinate.
- return {h,-2.0f*h*shifted/p.along,
- -2.0f*h*(q+shifted*BowCurvature*q/r)/p.across};
-}
inline std::string BowPressureSource() {
std::string source;
#define WATER_VESSEL_BOW_HLSL(name,value) source+="static const float " #name "=" #value ";\n";
@@ -63,18 +46,16 @@ float3 vesselBowPressure(float halfBeam,float speed) {
#undef WATER_VESSEL_BOW_CONSTANTS
// Reflection reaches at most 90 units from a contour; generated wakes end within 110 units.
// The collector's existing hull-radius + 122 culling margin therefore still contains the field.
-inline std::string Source(bool contactContours=false,bool bowShoulder=WaterBowShoulder::Enabled()) {
+inline std::string Source() {
// A pitching shallow keel can move a mean-slice endpoint by several world units
// in one frame. Generated packets follow the current reachable contact envelope;
// exact mean-waterline clearance and reflection below remain independent.
- std::string source=contactContours?R"HLSL(
+ std::string source=R"HLSL(
float4 vesselPacketRegister(int index) {
int base=(index/10)*10;
float count=ContactHullData[base].w;
return count>=3.0 && count<=12.0?ContactHullData[index]:HullData[index];
}
-)HLSL":R"HLSL(
-float4 vesselPacketRegister(int index) { return HullData[index]; }
)HLSL";
return BowPressureSource()+source+R"HLSL(
// Match WaterHullModel::Damping at the undisplaced surface parameter. The smooth nine-unit
@@ -222,7 +203,7 @@ float3 vesselBowPressureField(float3 along,float3 across,float3 parameters) {
(vwSqrt(vwConstant(1.0)+vwMul(q,q))-vwConstant(1.0))*BowCurvature;
return vwExp(-vwMul(shifted,shifted)-vwMul(q,q))*parameters.z;
}
-)HLSL"+(bowShoulder?WaterBowShoulder::Source():std::string())+R"HLSL(// Generated crest coverage follows the physical packet and its usable displacement.
+)HLSL"+WaterBowShoulder::Source()+R"HLSL(// Generated crest coverage follows the physical packet and its usable displacement.
// Illumination belongs to the diffuse foam material, not to the amount of emitted foam.
// The caller retains the solid-hull mask and uses the same microcoverage as hull/history foam.
float vesselGeneratedFoam(float crest,float weight,float damping) {
@@ -275,31 +256,7 @@ float3 vesselGeneratedWave(float2 p,float level,float time,int h) {
// Bow-only world field. Keep the stern packet and its parameterization above unchanged.
// The caller supplies the final horizontal position after every reflected XY contribution.
float3 vesselGeneratedBow(float2 p,float level,int h) {
-)HLSL"+(bowShoulder?R"HLSL( return vesselContourBow(p,level,h);
-)HLSL":std::string())+R"HLSL( int base=h*10;
- float4 position=vesselPacketRegister(base),axis=vesselPacketRegister(base+1),motion=vesselPacketRegister(base+2);
- float speed=length(motion.xy);
- if(position.w<3 || abs(level-position.z)>0.1 || speed<=0.3) return 0;
- float2 delta=p-position.xy;
- float radius=length(delta),reach=motion.w+110.0;
- if(radius>=reach) return 0;
- float2 forward=motion.xy/max(speed,0.001),side=float2(-forward.y,forward.x);
- float2 localVelocity=float2(dot(forward,axis.xy),dot(forward,float2(-axis.y,axis.x)));
- float4 endpoints=vesselPacketRegister(base+3);
- float forwardBlend=smoothstep(-0.25,0.25,localVelocity.x);
- float2 bowLocal=lerp(endpoints.xy,endpoints.zw,forwardBlend);
- float2 bow=position.xy+float2(axis.x*bowLocal.x-axis.y*bowLocal.y,axis.y*bowLocal.x+axis.x*bowLocal.y);
- float3 bowForward=float3(dot(p-bow,forward),forward),bowAcross=float3(dot(p-bow,side),side);
- float3 bowCrest=vesselBowPressureField(bowForward,bowAcross,vesselBowPressure(axis.w,speed));
- float3 radial=float3(radius,delta/max(radius,0.001));
- float3 support=vwConstant(1.0)-vwSmooth(motion.w+80.0,reach,radial);
- return vwMul(bowCrest,support);
-}
-float3 vesselRegisteredBowDifference(float2 position,float2 derivativeX,float2 derivativeY,
- float level,int h,float3 oldBow) {
- float3 bow=vesselGeneratedBow(position,level,h);
- bow.yz=float2(dot(bow.yz,derivativeX),dot(bow.yz,derivativeY));
- return bow-oldBow;
+ return vesselContourBow(p,level,h);
}
)HLSL";
}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.cpp
index 2d689aea3..66a102bac 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.cpp
@@ -21,7 +21,6 @@
#include "ffvertex.h"
#include "sdl3target.h"
#include "Platform/WaterSurfaceModel.h"
-#include "Platform/WaterCoastalPresentation.h"
#include "Platform/WaterOpticalModel.h"
#include "Platform/ModernWaterMaterial.h"
#include "Platform/WaterHullModel.h"
@@ -30,7 +29,6 @@
#include "Platform/WaterFoamShading.h"
#include "Platform/WaterFoamEnvironment.h"
#include "Platform/WaterShoreFoam.h"
-#include "Platform/WaterCoastalCrest.h"
#include <stdio.h>
#include <stdlib.h>
@@ -497,20 +495,13 @@ static bool write_engine_pixel_program(EngineShaderProgram program,
// are composed before the existing shore/shroud alpha blend. No additional assets are required.
static void write_modern_water(std::string &hlsl, bool river)
{
- const char *coastalSurfOption=getenv("ZH_WATER_SURF_GPU");
- const bool coastalSurf=!river && coastalSurfOption && strcmp(coastalSurfOption,"1")==0;
- const bool bowLift=WaterBowLift::Enabled();
- const bool visualContact=WaterHullVisual::Enabled();
- const char *visualDebugOption=getenv("ZH_WATER_DEBUG");
- const bool visualDiagnostic=visualContact && visualDebugOption &&
- (strcmp(visualDebugOption,"contact-mesh-query")==0 || strcmp(visualDebugOption,"contact-mesh-sources")==0);
hlsl.clear();
- for (unsigned stage = 0; stage < (coastalSurf?16u:15u); ++stage) {
+ for (unsigned stage = 0; stage < 15u; ++stage) {
char line[128];
snprintf(line, sizeof(line), "Texture2D Texture%u : register(t%u);\nSamplerState Sampler%u : register(s%u);\n", stage, stage, stage, stage);
hlsl += line;
}
- hlsl += WaterFftSampling::UniformSource("CombinerConstants",0,visualContact);
+ hlsl += WaterFftSampling::UniformSource("CombinerConstants",0,true);
hlsl += R"HLSL(struct Input
{
float4 Position : SV_Position;
@@ -736,7 +727,7 @@ WaterRefractionSample waterRefractedScene(float2 originalPixel, float2 offset,
hlsl += ModernWaterMaterial::OpticalSource();
hlsl += ModernWaterMaterial::BubbleSource();
hlsl += WaterHullModel::GetHlslSource();
- hlsl += WaterFftSampling::PixelSource(bowLift);
+ hlsl += WaterFftSampling::PixelSource();
hlsl += WaterWaveCageShader::Source(false);
char oceanBound[96];
snprintf(oceanBound, sizeof(oceanBound), "static const float oceanDisplacementBound = %.9g;\n",
@@ -750,12 +741,12 @@ float terrainWaveAttenuation(float depth, float offshore)
return lerp(shore, saturate((depth-0.15)/oceanDisplacementBound), offshore);
}
)HLSL";
- if(visualContact) hlsl += WaterHullVisual::Source();
- hlsl += WaterHullModel::GetEffectsHlslSource(true,visualContact);
- if(visualContact) hlsl += R"HLSL(
+ hlsl += WaterHullVisual::Source();
+ hlsl += WaterHullModel::GetEffectsHlslSource();
+ hlsl += R"HLSL(
// Fresh visible contact uses the posed triangle slice at the raster surface, including
// horizontal chop and geometric interpolation. It does not alter pressure or old wakes.
-// Shared contact material for normal shading and source-attribution diagnostics.
+// Contact material for the current posed triangle slice.
// Query admission and hull accumulation remain with each caller.
float3 oceanMeshContactFoam(WaterVisualResult contact,float2 local,float4 motion,float2 axis,
float speed,float moving,float collision,float time,float incomingHeight,float footprint,float waveImpact)
@@ -810,57 +801,13 @@ float2 oceanMeshHullEffects(float3 world,float level,float time,float offshore,
}
return saturate(float2(foam,turbulence))*offshore;
}
-)HLSL";
- if(visualDiagnostic) hlsl += R"HLSL(
-// Diagnostic only: geometry is queried before optical eligibility. Normal effects are unchanged.
-// A nonzero red tag proves a valid source-band slice. All channels use one nearest hull.
-float4 oceanMeshHullDiagnostic(float3 world,float level,float time,float offshore,
- float incomingHeight,float footprint,float waveImpact,int sourceMode)
-{
- float nearestDistance=1.0e6;
- float4 result=float4(0,0,0,1);
- if(abs(world.z-level)>fftVerticalBound) return result;
- for(int h=0;h<clamp((int)HullParameters.x,0,8);++h) {
- float4 meta=VisualHullMeta[h];
- if(meta.w<0.5 || meta.y<1.0) continue;
- int index=h*10;
- float4 position=WaterContactRegister(index),axis=WaterContactRegister(index+1);
- if(position.w<3.0 || abs(level-position.z)>0.1) continue;
- float2 delta=world.xy-position.xy;
- if(dot(delta,delta)>(meta.z+12.0)*(meta.z+12.0)) continue;
- float2 local=float2(dot(delta,axis.xy),dot(delta,float2(-axis.y,axis.x)));
- WaterVisualResult contact=WaterVisualQuery(h,float3(local,world.z-level));
- if(contact.hasSegment<0.5 || contact.distance>12.0) continue;
- // Strict distance tie keeps the lower hull slot; all channels describe this same query.
- if(contact.distance>=nearestDistance) continue;
- float4 motion=WaterContactRegister(index+2);
- float speed=length(motion.xy),moving=smoothstep(0.3,18.0,speed);
- float collision=waterHullContactResponse(incomingHeight,waveImpact);
- float3 effects=oceanMeshContactFoam(contact,local,motion,axis.xy,
- speed,moving,collision,time,incomingHeight,footprint,waveImpact);
- nearestDistance=contact.distance;
- float taggedDistance=0.25+0.75*(1.0-saturate(contact.distance/12.0));
- float rawSide=saturate(effects.x),rawBow=saturate(effects.y);
- result=sourceMode==0 ? float4(taggedDistance,offshore,max(rawSide,rawBow),1.0)
- : float4(taggedDistance,rawSide,rawBow,1.0);
- }
- return result;
-}
)HLSL";
hlsl += WaterFoamShading::HistorySamplingSource();
hlsl += WaterFoamShading::Source();
hlsl += WaterFoamShading::MaterialSource();
hlsl += WaterFoamEnvironment::HlslSource();
hlsl += WaterShoreFoam::Source();
- const char *coastalCrestOption=getenv("ZH_WATER_COAST_CREST");
- const bool coastalCrest=coastalCrestOption && strcmp(coastalCrestOption,"1")==0;
- if(coastalCrest) hlsl+=WaterCoastalCrest::Source();
hlsl += WaterShoreFoam::HistorySource();
- if(coastalSurf) hlsl+=WaterCoastalPresentation::Source();
- // Comparison switch is resolved at shader generation, never per pixel/frame.
- const char *shoreOption=getenv("ZH_WATER_SHORE_FOAM");
- hlsl += (!shoreOption || strcmp(shoreOption,"0")!=0)
- ? "static const bool shoreFoamEnabled=true;\n" : "static const bool shoreFoamEnabled=false;\n";
hlsl += R"HLSL(
float4 main(Input input) : SV_Target
{
@@ -897,8 +844,7 @@ float4 main(Input input) : SV_Target
float3 wave = lerp(legacyWave, oceanWave, offshore);
FftSurface spectral=(FftSurface)0;
)HLSL";
- if(bowLift) hlsl+=R"HLSL(float3 bowLiftField=0;float3 fftDampingField=float3(0,0,0);float2 fftWeightSlope=0;)HLSL";
- else hlsl+=R"HLSL(float3 fftDampingField=float3(0,0,0);float2 fftWeightSlope=0;)HLSL";
+ hlsl+=R"HLSL(float3 bowLiftField=0;float3 fftDampingField=float3(0,0,0);float2 fftWeightSlope=0;)HLSL";
hlsl+=R"HLSL(
float fftHorizontalWeight=0.0;
float2 fftHorizontalWeightSlope=0;
@@ -914,9 +860,8 @@ float4 main(Input input) : SV_Target
float3 horizontalScale=float3(fftHorizontalWeight*fftDampingField.x,
fftHorizontalWeightSlope*fftDampingField.x+fftDampingField.yz*fftHorizontalWeight);
)HLSL";
- if(bowLift) hlsl+=R"HLSL(spectral=fftSurface(wavePosition,baseLevel,max(length(parameterDx),length(parameterDy)),horizontalScale);
+ hlsl+=R"HLSL(spectral=fftSurface(wavePosition,baseLevel,max(length(parameterDx),length(parameterDy)),horizontalScale);
bowLiftField=fftBowLift(spectral.bow,float3(freeDamping,fftParameterGradient(freeDamping,parameterDx,parameterDy)),fftDampingField);)HLSL";
- else hlsl+=R"HLSL(spectral=fftSurface(wavePosition,baseLevel,max(length(parameterDx),length(parameterDy)),horizontalScale);)HLSL";
hlsl+=R"HLSL(
}
float footprint=max(length(dx),length(dy));
@@ -926,7 +871,7 @@ float4 main(Input input) : SV_Target
float3 hullEffects=oceanHullEffects(wavePosition,baseLevel,time,offshore,hullWave,foamFootprint,waveImpact);
hullEffects.x=waterFoamContactPatches(wavePosition,hullEffects.x,foamFootprint,time);
)HLSL";
- if(visualContact) hlsl += R"HLSL(
+ hlsl += R"HLSL(
float2 meshHullEffects=oceanMeshHullEffects(world,baseLevel,time,offshore,hullWave,footprint,waveImpact);
meshHullEffects.x=waterFoamContactPatches(wavePosition,meshHullEffects.x,foamFootprint,time);
hullEffects.y=max(hullEffects.y,meshHullEffects.y);
@@ -955,21 +900,6 @@ float4 main(Input input) : SV_Target
float2 correctionSlope=float2(cu*parameterDy.y-cv*parameterDx.y,cv*parameterDx.x-cu*parameterDy.x)*invDet;
float2 slope = baseSlope + wave.yz * attenuation + wave.x * attenuationSlope + correctionSlope;
)HLSL";
- if(coastalCrest) hlsl += R"COAST( // All screen derivatives are evaluated before the eligibility branch. The
- // helper then differentiates every product and the same depth-limited crest as CPU.
- float2 coastSupportGradient=fftParameterGradient(opticalContext.a,parameterDx,parameterDy);
- float2 coastExposureGradient=fftParameterGradient(opticalContext.b,parameterDx,parameterDy);
- float2 coastObstacleGradient=fftParameterGradient(input.Diffuse.r,parameterDx,parameterDy);
- float2 coastDepthGradient=baseSlope-fftParameterGradient(surfaceTerrainHeight,parameterDx,parameterDy);
- if(OpticalParameters.z>0.5 && TerrainParameters.w>0.5 && WaterParameters.y<0.5
- && offshore==0.0 && opticalContext.a>0.0 && opticalContext.b>0.0) {
- float3 coastalCorrection=waterCoastalCrest(waterShoreWave(wavePosition,time).xyz,
- float3(baseLevel-surfaceTerrainHeight,coastDepthGradient),
- float3(opticalContext.a,coastSupportGradient),float3(opticalContext.b,coastExposureGradient),
- float3(input.Diffuse.r,coastObstacleGradient),float3(attenuation,attenuationSlope));
- slope+=coastalCorrection.yz;meshCorrection+=coastalCorrection.x;
- }
-)COAST";
hlsl += R"HLSL( float3 normal = normalize(float3(-slope, 1.0));
float continuousHeight=baseLevel+wave.x*attenuation+meshCorrection;
WaveCage cage=waveCage(wavePosition,baseLevel);
@@ -994,13 +924,11 @@ float4 main(Input input) : SV_Target
float2 horizontalSlope=fftHorizontalWeightSlope*fftDamping+dampingSlope*fftHorizontalWeight;
float oldHeight=continuousHeight-baseLevel;
)HLSL";
- if(bowLift) hlsl+=R"HLSL(float newHeight=spectral.displacement.z*fftDamping+bowLiftField.x;)HLSL";
- else hlsl+=R"HLSL(float newHeight=spectral.displacement.z*fftDamping;)HLSL";
+ hlsl+=R"HLSL(float newHeight=spectral.displacement.z*fftDamping+bowLiftField.x;)HLSL";
hlsl+=R"HLSL(
float2 newSlope=float2(spectral.derivativeX.z,spectral.derivativeY.z)*fftDamping
)HLSL";
- if(bowLift) hlsl+=R"HLSL(+spectral.displacement.z*dampingSlope+bowLiftField.yz;)HLSL";
- else hlsl+=R"HLSL(+spectral.displacement.z*dampingSlope;)HLSL";
+ hlsl+=R"HLSL(+spectral.displacement.z*dampingSlope+bowLiftField.yz;)HLSL";
hlsl+=R"HLSL(
float2 heightSlope=baseSlope+lerp(slope-baseSlope,newSlope,fftWeight)
+(newHeight-oldHeight)*weightSlope;
@@ -1022,13 +950,11 @@ float4 main(Input input) : SV_Target
// Filter the same displacement derivatives for reflected/direct light only. Keep
// level-zero geometry, refraction, contact and optical path reconstruction intact.
)HLSL";
- if(bowLift) hlsl+=R"HLSL(float shadedHeight=spectral.shadingDisplacement.z*fftDamping+bowLiftField.x;)HLSL";
- else hlsl+=R"HLSL(float shadedHeight=spectral.shadingDisplacement.z*fftDamping;)HLSL";
+ hlsl+=R"HLSL(float shadedHeight=spectral.shadingDisplacement.z*fftDamping+bowLiftField.x;)HLSL";
hlsl+=R"HLSL(
float2 shadedSlope=float2(spectral.shadingDerivativeX.z,spectral.shadingDerivativeY.z)*fftDamping
)HLSL";
- if(bowLift) hlsl+=R"HLSL(+spectral.shadingDisplacement.z*dampingSlope+bowLiftField.yz;)HLSL";
- else hlsl+=R"HLSL(+spectral.shadingDisplacement.z*dampingSlope;)HLSL";
+ hlsl+=R"HLSL(+spectral.shadingDisplacement.z*dampingSlope+bowLiftField.yz;)HLSL";
hlsl+=R"HLSL(
float2 shadedHeightSlope=baseSlope+lerp(slope-baseSlope,shadedSlope,fftWeight)
+(shadedHeight-oldHeight)*weightSlope;
@@ -1228,42 +1154,8 @@ float4 main(Input input) : SV_Target
cageWash=cageAmount*fftWeight*cageWet*cageContact*cageCrest*lerp(0.45,1.0,cagePores);
foam=max(foam*(1.0-cageAmount*fftWeight*cageTerrainMatch),cageWash*0.72);
)HLSL";
- if(coastalSurf) hlsl+=R"COAST(
- float gpuCoastFoam=0.0,gpuCoastRaw=0.0,gpuCoastGate=0.0;
- float2 gpuCoastDensityAge=0.0;
- if(WaterParameters.y<0.5 && OpticalParameters.z>0.5 && OpticalParameters.w>0.5
- && TerrainParameters.w>0.5 && SceneParameters.w>0.5
- && all(isfinite(SceneParameters.yz)) && all(SceneParameters.yz>0)
- && waterCoastalViewValid(CoastalArea,CoastalParams,wavePosition,baseLevel,time)) {
- float2 coastUV=(wavePosition-CoastalArea.xy)/CoastalArea.zw;
- float2 coastMoments=Texture15.SampleLevel(Sampler15,coastUV,0).rg;
- float2 coastDensityAge=waterCoastalAtTime(coastMoments,CoastalParams.w-CoastalParams.z);
- gpuCoastDensityAge=coastDensityAge;
- if(coastDensityAge.x>0.0) {
- // Source and lookup live on the original parameter chart, not chopped XY.
- float2 parameterContextUV=(wavePosition+TerrainParameters.xx+5.0)/max(TerrainParameters.y,1.0);
- float canonicalSupport=Texture4.SampleLevel(Sampler4,parameterContextUV,0).b;
- float coastModelGate=waterCoastalModelGate(fftWeight,canonicalSupport,input.TexCoord0.x,correctionSlope);
- gpuCoastRaw=waterCoastalPorousCoverage(wavePosition,foamFootprint,coastDensityAge);
- if(coastModelGate>0.0 && gpuCoastRaw>0.0) {
- // Reconstruct the original actual scene sample. A refracted hit or the
- // terrain fallback cannot justify surf on an object or dry fragment.
- float2 coastPixel=waterScenePixel(floor(input.Position.xy)+0.5);
- float coastRawDepth=Texture6.SampleLevel(Sampler6,coastPixel*SceneParameters.yz,0).r;
- if(waterShoreSceneDepth(SceneParameters.w,coastRawDepth)) {
- float3 coastHit=scenePosition(coastPixel,coastRawDepth);
- float coastHullGuard=vesselHullDamping(world.xy,baseLevel).x;
- float coastWetGate=waterCoastalWetGate(coastRawDepth,coastHit,world,view,baseLevel,
- surfaceTerrainHeight,terrainHeight(wavePosition),terrainHeight(coastHit.xy),input.Diffuse.r,coastHullGuard);
- gpuCoastGate=coastModelGate*coastWetGate;
- gpuCoastFoam=gpuCoastRaw*gpuCoastGate;
- }
- }
- }
- }
-)COAST";
hlsl+=R"HLSL(
- if(shoreFoamEnabled && WaterParameters.y<0.5 && OpticalParameters.z>0.5
+ if(WaterParameters.y<0.5 && OpticalParameters.z>0.5
&& TerrainParameters.w>0.5 && SceneParameters.w>0.5
&& opticalContext.r==0.0 && (opticalContext.a>0.0 || shoreHistory>0.0)) {
// Test the original raster pixel, not the refracted candidate or bottomPosition's
@@ -1330,7 +1222,7 @@ float4 main(Input input) : SV_Target
// Current solid hulls mask old trails if they cross another vessel's waterline.
vesselFoam*=smoothstep(0.0,0.006,hullEffects.z);
)HLSL";
- if(visualContact) hlsl += R"HLSL(
+ hlsl += R"HLSL(
// Actual triangle contact may meet the visible hull inside the mean footprint.
// Keep the old mask for trails and pressure foam, and merge fresh contact after it.
if(meshHullEffects.x>0.0) {
@@ -1341,7 +1233,7 @@ float4 main(Input input) : SV_Target
}
)HLSL";
hlsl += R"HLSL()HLSL";
- if(bowLift) hlsl+=R"HLSL( // This is foam on the additional displaced bow shoulder, not mean-plane hull wash.
+ hlsl+=R"HLSL( // This is foam on the additional displaced bow shoulder, not mean-plane hull wash.
// Its height already includes F-D; the unchanged opaque scene depth hides solid hulls.
float liftedBowFoam=fftBowLiftFoam(bowLiftField.x,fftWeight);
if(liftedBowFoam>0.0) {
@@ -1350,12 +1242,10 @@ float4 main(Input input) : SV_Target
foamAge=historyFoam.y*24.0*(1.0-smoothstep(0.25,1.0,freshFoam/max(historyFoam.x,0.0001)));
}
vesselFoam=waterFoamMicroCoverage(wavePosition,vesselFoam,foamFootprint,foamAge,time);)HLSL";
- else hlsl+=R"HLSL( vesselFoam=waterFoamMicroCoverage(wavePosition,vesselFoam,foamFootprint,foamAge,time);)HLSL";
hlsl+=R"HLSL(
foam=max(foam,vesselFoam);
foamWithoutShore=max(foamWithoutShore,vesselFoam);
)HLSL";
- if(coastalSurf) hlsl+=" float gpuCoastPrevious=foam;\n foam=max(foam,gpuCoastFoam);\n";
hlsl+=R"HLSL(
float shoreMaterialWeight=waterFoamCoastWeight(foam,foamWithoutShore,vesselFoam);
// Analytic fine normals can face away from the eye between geometric vertices. Fresnel alone
@@ -1385,20 +1275,11 @@ float4 main(Input input) : SV_Target
sunVisible*FoamFillLights[0].w,FoamFillLights[0].xyz,FoamFillLights[1].rgb,
FoamFillLights[2].xyz,FoamFillLights[3].rgb);
)HLSL";
- if(coastalSurf) hlsl+=" float3 coastAuthoredIrradiance=vesselIrradiance;\n";
hlsl+=R"HLSL(
if(vesselFoam>0.0 && offshore>0.0)
vesselIrradiance=waterFoamReplaceAmbient(vesselIrradiance,HullParameters.yzw,
waterFoamSkyIrradiance(normal,light,daylight),offshore);
)HLSL";
- if(coastalSurf) hlsl+=R"COAST(
- // Coast has its own ambient replacement, independent of vessel presence. Keep
- // the exact previous lighting when this optional source contributes nothing.
- float3 coastIrradiance=vesselIrradiance;
- if(gpuCoastFoam>0.0 && offshore>0.0)
- coastIrradiance=waterFoamReplaceAmbient(coastAuthoredIrradiance,HullParameters.yzw,
- waterFoamSkyIrradiance(normal,light,daylight),offshore);
-)COAST";
hlsl+=R"HLSL(
float3 vesselDiffuse=waterLinear(vesselAlbedo)*vesselIrradiance;
float3 vesselRadiance=vesselDiffuse;
@@ -1420,9 +1301,7 @@ float4 main(Input input) : SV_Target
// Share the filtered incident reflection; exchange Fresnel only once.
if(shoreMaterialWeight>0.0)
)HLSL";
- hlsl+=coastalSurf
- ? " shoreRadiance=waterFoamRoughMaterial(waterLinear(foamAlbedo)*coastIrradiance,\n"
- : " shoreRadiance=waterFoamRoughMaterial(waterLinear(foamAlbedo)*vesselIrradiance,\n";
+ hlsl+=" shoreRadiance=waterFoamRoughMaterial(waterLinear(foamAlbedo)*vesselIrradiance,\n";
hlsl+=R"HLSL( foamReflection,environmentFresnel,oceanViewCosine,foamRoughness);
}
// Mix the lit surface contributions; independently mixing albedo and irradiance
@@ -1442,220 +1321,6 @@ float4 main(Input input) : SV_Target
hlsl += " float4 edge = Texture3.Sample(Sampler3, input.TexCoord3);\n";
hlsl += " current = float4(saturate(surface) * edge.rgb, saturate(depth * 2.0) * lerp(input.Diffuse.a * base.a, step(0.001, input.Diffuse.a * base.a), SceneParameters.x));\n";
}
- // Developer captures isolate the actual water inputs; normal game output is unaffected.
- const char *debug = getenv("ZH_WATER_DEBUG");
- if(coastalSurf && debug && strcmp(debug,"coastal-surf")==0)
- hlsl+="current=float4(gpuCoastRaw,gpuCoastGate,gpuCoastFoam,1.0);\n";
- if(coastalSurf && debug && strcmp(debug,"coastal-density")==0)
- hlsl+="current=float4(waterFoamOpticalCoverage(gpuCoastDensityAge.x),gpuCoastDensityAge.y/14.0,gpuCoastRaw,1.0);\n";
- if(coastalSurf && debug && strcmp(debug,"coastal-material")==0)
- hlsl+="current=float4(gpuCoastPrevious,max(0.0,foam-gpuCoastPrevious),shoreMaterialWeight,1.0);\n";
- if (debug && strcmp(debug, "depth") == 0) hlsl += "current.rgb = (1.0-exp(-depth*0.04)).xxx;\n";
- if (debug && strcmp(debug, "bed") == 0) hlsl += "current.rgb = waterDisplay(scene);\n";
- if (debug && strcmp(debug, "reflection") == 0) hlsl += "current.rgb = waterDisplay(reflection);\n";
- if (debug && strcmp(debug, "normal") == 0) hlsl += "current.rgb = normal*0.5+0.5;\n";
- if (debug && strcmp(debug, "highlight") == 0) hlsl += "current.rgb = waterDisplay(highlight);\n";
- if (debug && strcmp(debug, "offshore") == 0) hlsl += "current.rgb = offshore.xxx;\n";
- if (debug && strcmp(debug, "wave-cage") == 0) hlsl += "current = float4(cageAmount,cage.radii.x/fftVerticalBound,cage.radii.y/fftVerticalBound,1.0);\n";
- if (debug && strcmp(debug, "cage-wash") == 0) hlsl += "current = float4(cageWash,cageContact*cageAmount,cageCrest*cageAmount,1.0);\n";
- if (debug && strcmp(debug, "shore-history") == 0) hlsl += "current = float4(shoreHistory,shoreRate/ShoreMaximumRate,shoreSupport,1.0);\n";
- if (debug && strcmp(debug, "shore-history-terms") == 0) hlsl += "current = float4(shoreHistory,shoreRetained,current.a,1.0);\n";
- if (debug && strcmp(debug, "shore") == 0) hlsl += "current.rgb = float3(shoreRate/ShoreMaximumRate,shoreSupport,opticalContext.b);\n";
- // Opaque diagnostic removes thin-water alpha compositing from source attribution.
- if (debug && strcmp(debug, "shore-raw") == 0) hlsl += "current = float4(shoreRate/ShoreMaximumRate,shoreSupport,opticalContext.b,1.0);\n";
- if (debug && strcmp(debug, "shore-source-terms") == 0) hlsl += R"HLSL(
- // Shore source attribution (M5i): R actual admitted front rate / maximum rate;
- // G same model with a fixed-world terrain derivative / maximum rate;
- // B fresh-front coverage after scene wetness/terrain match, in raw [0,1] units.
- // B excludes retained history and later hull/max/material operations. It is not
- // divided by the old .35-second cap. This code is absent from normal shaders.
- float2 sourceTermsFront;
- float4 sourceTermsWave=waterShoreWaveFront(wavePosition,time,-terrainGradient,
- parameterDx,parameterDy,sourceTermsFront);
- float2 fixedShoreGradient=float2(terrainHeight(world.xy+float2(5,0))-terrainHeight(world.xy-float2(5,0)),
- terrainHeight(world.xy+float2(0,5))-terrainHeight(world.xy-float2(0,5)))*0.1;
- float fixedShoreDepth=max(0.0,baseLevel-surfaceTerrainHeight),fixedShoreSlope=length(fixedShoreGradient);
- float2 fixedShoreFront;
- float4 fixedShoreWave=waterShoreWaveFront(wavePosition,time,-fixedShoreGradient,
- parameterDx,parameterDy,fixedShoreFront);
- float fixedShoreRate=waterShoreRate(fixedShoreWave,fixedShoreDepth,
- min(opticalContext.g*100.0,fixedShoreDepth/max(fixedShoreSlope,0.01)),
- -fixedShoreGradient,fixedShoreSlope,opticalContext.b,shoreSupport)*fixedShoreFront.x;
- float finalShoreCoverage=waterShoreFrontFresh(shoreRate,sourceTermsFront.y)*smoothstep(0.0,0.8,depth)
- *(1.0-smoothstep(0.5,1.5,abs(shoreSceneBottom.z-terrainHeight(shoreSceneBottom.xy))));
- current=float4(shoreRate/ShoreMaximumRate,fixedShoreRate/ShoreMaximumRate,finalShoreCoverage,1.0);
- // End shore source attribution. Only the opt-in diagnostic recomputes residence.
-)HLSL";
- if (debug && strcmp(debug, "foam") == 0) hlsl += "current.rgb = float3(historyFoam.x,hullEffects.x,historyFoam.y*historyFoam.x);\n";
- if (debug && strcmp(debug, "vessel") == 0) hlsl += "current.rgb = float3(max(0.0,-spectral.vesselHeight),max(0.0,spectral.vesselHeight),spectral.vesselCrest)*fftWeight;\n";
- if (debug && strcmp(debug, "pressure") == 0) hlsl += "current.rgb = fftPressureDebug(spectral,fftWeight,fftDamping,generatedFoam);\n";
- if (debug && strcmp(debug, "resolved-normal") == 0) hlsl += "current.rgb = resolvedNormal*0.5+0.5;\n";
- if (debug && strcmp(debug, "roughness") == 0) hlsl += "current.rgb = float3(roughness,environmentRoughness,sqrt(unresolvedSlopeVariance));\n";
- if (debug && strcmp(debug, "pressure-retention") == 0) hlsl += "current.rgb = fftPressureRetentionDebug(spectral,fftWeight,fftDamping,generatedFoam);\n";
- // Diagnostics evaluate old and current rules at the same fragment/phase/snapshot.
- // No extra code is emitted for normal water or any unrelated debug mode.
- if (debug && (strcmp(debug,"footprint")==0 || strcmp(debug,"footprint-path")==0 ||
- strcmp(debug,"footprint-colour")==0 || strcmp(debug,"footprint-reasons")==0 || strcmp(debug,"footprint-overlay")==0)) {
- hlsl += R"HLSL(
-float2 auditOrigin=waterScenePixel(input.Position.xy);
-float2 auditCandidate=waterScenePixel(input.Position.xy+refractionPixels);
-float3 auditOriginalBottom=bottomPosition(input.Position.xy,world,baseLevel);
-float3 auditOldHit=bottomPosition(auditCandidate,world,baseLevel);
-// Exact previous M4B/M4A nearest-only selection, including its terrain fallback policy.
-float auditOldAccepted=step(auditOldHit.z,min(world.z,opticalWorld.z)-0.08)
- *step(0.0,min(dot(auditOldHit-world,-view),dot(auditOldHit-opticalWorld,-view)));
-float2 auditOldPixel=lerp(auditOrigin,auditCandidate,auditOldAccepted);
-float3 auditOldBottom=lerp(auditOriginalBottom,auditOldHit,auditOldAccepted);
-float auditOriginalDepth=Texture6.SampleLevel(Sampler6,
- waterScenePixel(floor(input.Position.xy)+0.5)*SceneParameters.yz,0).r;
-float auditOriginalRealHit=(SceneParameters.w>0.5 && auditOriginalDepth>=0.0 && auditOriginalDepth<0.999999)?1.0:0.0;
-float auditNewPath=length(refractedScene.bottom-opticalWorld);
-float auditOldPath=length(auditOldBottom-opticalWorld);
-)HLSL";
- if(strcmp(debug,"footprint-overlay")==0)
- hlsl += "current.rgb=lerp(current.rgb,float3(1,0,1),0.7*auditOldAccepted*(1.0-refractedScene.accepted));\n";
- if(strcmp(debug,"footprint")==0)
- hlsl += "current.rgb=float3(refractedScene.accepted,auditOldAccepted,auditOriginalRealHit);\n";
- if(strcmp(debug,"footprint-path")==0)
- hlsl += "current.rgb=float3(saturate((auditNewPath-auditOldPath)/16.0),saturate((auditOldPath-auditNewPath)/16.0),1.0-auditOriginalRealHit);\n";
- if(strcmp(debug,"footprint-colour")==0)
- hlsl += "float3 auditOldColour=Texture5.SampleLevel(Sampler5,auditOldPixel*SceneParameters.yz,0).rgb;\n"
- "current.rgb=saturate(abs(refractedScene.colour-auditOldColour)*4.0);\n";
- if(strcmp(debug,"footprint-reasons")==0) {
- hlsl += R"HLSL(
-// Classify every positive-weight tap. R=unavailable/clear/invalid depth,
-// G=not below one/both water surfaces, B=not behind one/both forward planes.
-// Multiple channels may be set; they are causes present, not a guessed primary cause.
-float3 auditReasons=float3(SceneParameters.w>0.5?0.0:1.0,0,0);
-if(SceneParameters.w>0.5) {
- float2 auditLower=floor(auditCandidate-0.5)+0.5;
- float2 auditFraction=frac(auditCandidate-0.5);
- float4 auditWeights=float4((1-auditFraction.x)*(1-auditFraction.y),
- auditFraction.x*(1-auditFraction.y),(1-auditFraction.x)*auditFraction.y,
- auditFraction.x*auditFraction.y);
- [unroll] for(int auditTap=0;auditTap<4;++auditTap) {
- [branch] if(auditWeights[auditTap]>0.0) {
- float2 auditTexel=waterScenePixel(auditLower+float2(auditTap&1,(auditTap>>1)&1));
- float auditDepth=Texture6.SampleLevel(Sampler6,auditTexel*SceneParameters.yz,0).r;
- if(!(auditDepth>=0.0 && auditDepth<0.999999)) auditReasons.r=1.0;
- else {
- float3 auditHit=scenePosition(auditTexel,auditDepth);
- if(!(auditHit.z<=min(world.z,opticalWorld.z)-0.08)) auditReasons.g=1.0;
- if(!(dot(auditHit-world,-view)>=0.0 && dot(auditHit-opticalWorld,-view)>=0.0)) auditReasons.b=1.0;
- }
- }
- }
-}
-current.rgb=auditReasons;
-)HLSL";
- }
- }
-}
-
-// Opt-in original-scene-depth attribution. Normal shader text remains unchanged.
-static int water_hull_depth_diagnostic()
-{
- const char *mode=getenv("ZH_WATER_DEBUG");
- if(mode && strcmp(mode,"contact-depth")==0) return 1;
- if(mode && strcmp(mode,"contact-depth-masks")==0) return 2;
- if(mode && strcmp(mode,"contact-depth-height")==0) return 3;
- return 0;
-}
-
-static void write_water_hull_depth_diagnostic(std::string &hlsl)
-{
- hlsl+=R"HLSL(
-// These are measurements, not new foam emission or a claim of scene object identity.
-// Read the original scene pixel once, without bottomPosition's terrain fallback and
-// without the later refraction offset. All quantities use actual raster world.xyz.
-float hullDepthValid=0.0,hullDepthWetProximity=0.0,hullDepthSupport=0.0,hullDepthRegion=0.0;
-float3 hullDepthHit=float3(0,0,0);
-if(SceneParameters.w>0.5 && all(isfinite(SceneParameters.yz))
- && all(SceneParameters.yz>0.0) && all(isfinite(world))) {
- float2 hullDepthPixel=waterScenePixel(floor(input.Position.xy)+0.5);
- float hullDepthRaw=Texture6.SampleLevel(Sampler6,hullDepthPixel*SceneParameters.yz,0).r;
- if(isfinite(hullDepthRaw) && hullDepthRaw>=0.0 && hullDepthRaw<0.999999) {
- hullDepthHit=scenePosition(hullDepthPixel,hullDepthRaw);
- if(all(isfinite(hullDepthHit))) {
- hullDepthValid=1.0;
- if(hullDepthHit.z<=world.z && dot(hullDepthHit-world,-view)>=0.0)
- hullDepthWetProximity=saturate(1.0-length(hullDepthHit-world)/8.0);
- }
- }
-}
-// Known-vessel context is deliberately conservative: the union of the current mean
-// and reachable-slab footprints. It is NOT an instantaneous cross-section or hull ID.
-// A 12-unit expanded rectangle only bounds diagnostic work/display; it emits no foam.
-for(int hullDepthHull=0;hullDepthHull<clamp((int)HullParameters.x,0,8);++hullDepthHull) {
- int hullDepthIndex=hullDepthHull*10;
- float4 hullDepthMean=HullData[hullDepthIndex],hullDepthMeanAxis=HullData[hullDepthIndex+1];
- float4 hullDepthSlab=WaterContactRegister(hullDepthIndex),hullDepthSlabAxis=WaterContactRegister(hullDepthIndex+1);
- if(hullDepthMean.w<3.0 || hullDepthMean.w>12.0 || abs(baseLevel-hullDepthMean.z)>0.1) continue;
- float2 hullDepthMeanDelta=world.xy-hullDepthMean.xy;
- float2 hullDepthMeanLocal=float2(dot(hullDepthMeanDelta,hullDepthMeanAxis.xy),
- dot(hullDepthMeanDelta,float2(-hullDepthMeanAxis.y,hullDepthMeanAxis.x)));
- float2 hullDepthSlabDelta=world.xy-hullDepthSlab.xy;
- float2 hullDepthSlabLocal=float2(dot(hullDepthSlabDelta,hullDepthSlabAxis.xy),
- dot(hullDepthSlabDelta,float2(-hullDepthSlabAxis.y,hullDepthSlabAxis.x)));
- bool hullDepthSlabValid=hullDepthSlab.w>=3.0 && hullDepthSlab.w<=12.0 && abs(baseLevel-hullDepthSlab.z)<=0.1;
- bool hullDepthInMean=all(abs(hullDepthMeanLocal)<hullDepthMeanAxis.zw+12.0);
- bool hullDepthInSlab=hullDepthSlabValid && all(abs(hullDepthSlabLocal)<hullDepthSlabAxis.zw+12.0);
- if(!hullDepthInMean && !hullDepthInSlab) continue;
- hullDepthRegion=1.0;
- if(hullDepthValid>0.5) {
- float2 hullDepthMeanHitDelta=hullDepthHit.xy-hullDepthMean.xy;
- float2 hullDepthMeanHit=float2(dot(hullDepthMeanHitDelta,hullDepthMeanAxis.xy),
- dot(hullDepthMeanHitDelta,float2(-hullDepthMeanAxis.y,hullDepthMeanAxis.x)));
- float hullDepthDistance=WaterHullSignedDistance(hullDepthMeanHit,hullDepthIndex,(int)hullDepthMean.w);
- if(hullDepthSlabValid) {
- float2 hullDepthSlabHitDelta=hullDepthHit.xy-hullDepthSlab.xy;
- float2 hullDepthSlabHit=float2(dot(hullDepthSlabHitDelta,hullDepthSlabAxis.xy),
- dot(hullDepthSlabHitDelta,float2(-hullDepthSlabAxis.y,hullDepthSlabAxis.x)));
- hullDepthDistance=min(hullDepthDistance,WaterContactDistance(hullDepthSlabHit,hullDepthIndex,(int)hullDepthSlab.w));
- }
- hullDepthSupport=max(hullDepthSupport,1.0-smoothstep(0.0,4.0,max(hullDepthDistance,0.0)));
- }
-}
-// Separate likely bed hits from a surface standing above/below terrain. This is an
-// attribution heuristic: submerged rocks/other objects can pass it, so it is not ID.
-float hullDepthOffTerrain=0.0;
-if(hullDepthValid>0.5 && TerrainParameters.w>0.5) {
- float hullDepthTerrain=terrainHeight(hullDepthHit.xy);
- if(isfinite(hullDepthTerrain))
- hullDepthOffTerrain=smoothstep(0.5,1.5,abs(hullDepthHit.z-hullDepthTerrain));
-}
-float hullDepthKnownConfidence=hullDepthRegion*hullDepthSupport*hullDepthOffTerrain;
-float hullDepthCandidate=hullDepthWetProximity*hullDepthKnownConfidence;
-)HLSL";
-}
-
-static void finish_water_hull_depth_diagnostic(std::string &hlsl,int mode)
-{
- // Normal fog/alpha test has already executed. Encode raw measurements afterwards,
- // opaque for byte attribution, without changing ordinary clipping or any normal mode.
- if(mode==1) hlsl+=R"HLSL(
-// R: original finite real scene hit in the selected known-hull diagnostic region.
-// G: behind/below-water hit proximity, max(0,1-worldRayGap/8), in that region.
-// B: same hit agrees with conservative hull footprint and is separated from terrain.
-current=float4(hullDepthRegion*hullDepthValid,hullDepthRegion*hullDepthWetProximity,
- hullDepthKnownConfidence,1.0);
-)HLSL";
- else if(mode==2) hlsl+=R"HLSL(
-// R: G*B from contact-depth (a possible visible contact, NOT emitted foam).
-// G: that candidate after the old generic-rim mean-hull suppression.
-// B: that candidate after the old vessel-foam mean-solid mask, independently of G.
-current=float4(hullDepthCandidate,hullDepthCandidate*lerp(1.0,hullEffects.z,offshore),
- hullDepthCandidate*smoothstep(0.0,0.006,hullEffects.z),1.0);
-)HLSL";
- else hlsl+=R"HLSL(
-// R/G: actual raster-water / original valid scene-hit height relative to mean level,
-// each encoded saturate(0.5+0.5*(z-baseLevel)/fftVerticalBound). Endpoints are censored.
-// B: the same wet, near-surface, footprint/nonterrain candidate from the other modes.
-// Invalid original hits have G=0; outside the known-hull display region RGB is zero.
-current=float4(hullDepthRegion*saturate(0.5+0.5*(world.z-baseLevel)/fftVerticalBound),
- hullDepthRegion*hullDepthValid*saturate(0.5+0.5*(hullDepthHit.z-baseLevel)/fftVerticalBound),
- hullDepthCandidate,1.0);
-)HLSL";
}
bool EngineShader_Pixel_Program(EngineShaderProgram program,
@@ -1671,30 +1336,7 @@ bool EngineShader_Pixel_Program(EngineShaderProgram program,
#if defined(__linux__)
if (program == ENGINE_SHADER_WATER_TRAPEZOID || program == ENGINE_SHADER_WATER_RIVER) {
write_modern_water(hlsl, program == ENGINE_SHADER_WATER_RIVER);
- const int hullDepthDiagnostic=water_hull_depth_diagnostic();
- if(hullDepthDiagnostic) write_water_hull_depth_diagnostic(hlsl);
if (!CombinerShader_Append_Pixel_Pipeline(pipeline, hlsl)) return false;
- if(hullDepthDiagnostic) finish_water_hull_depth_diagnostic(hlsl,hullDepthDiagnostic);
- const bool visualContact=WaterHullVisual::Enabled();
- const char *waterDebug=getenv("ZH_WATER_DEBUG");
- if(WaterBowLift::Enabled() && waterDebug && strcmp(waterDebug,"bow-retention")==0)
- hlsl += "// Encode raw bow measurements after ordinary clipping/fog/alpha test.\n"
- "current=float4(fftBowRetentionDebug(spectral,fftWeight,saturate(input.Specular.y),fftDamping),1.0);\n";
- if(visualContact && waterDebug && strcmp(waterDebug,"contact-mesh")==0)
- hlsl += "// Raw actual-height source, combined fresh source, and final material coverage.\ncurrent=float4(meshHullEffects.x,freshFoam,vesselFoam,1.0);\n";
- if(visualContact && waterDebug && strcmp(waterDebug,"contact-mesh-alpha")==0)
- hlsl += "// Raw actual-height source, final material coverage, and original compositing alpha.\ncurrent=float4(meshHullEffects.x,vesselFoam,current.a,1.0);\n";
- if(visualContact && waterDebug && strcmp(waterDebug,"contact-material")==0)
- hlsl += "// Lit vessel material before coverage and legacy fog/shroud composition.\ncurrent=float4(waterDisplay(vesselRadiance),1.0);\n";
- if(visualContact && waterDebug && strcmp(waterDebug,"contact-lighting")==0)
- hlsl += "// Surface sun cosine, actual direct-light visibility, and original fog visibility.\ncurrent=float4(saturate(dot(normal,light)),sunVisible*FoamFillLights[0].w,saturate(input.Fog),1.0);\n";
- if(visualContact && waterDebug &&
- (strcmp(waterDebug,"contact-mesh-query")==0 || strcmp(waterDebug,"contact-mesh-sources")==0)) {
- // Evaluate and encode after the ordinary pipeline; no diagnostic changes normal water.
- hlsl += strcmp(waterDebug,"contact-mesh-query")==0
- ? "current=oceanMeshHullDiagnostic(world,baseLevel,time,offshore,hullWave,footprint,waveImpact,0);\n"
- : "current=oceanMeshHullDiagnostic(world,baseLevel,time,offshore,hullWave,footprint,waveImpact,1);\n";
- }
hlsl += " return current;\n}\n";
return SDL3_Shader_Retarget(hlsl, false);
}
diff --git a/GeneralsMD/Code/Tests/WaterCoastalCapacityTest.h b/GeneralsMD/Code/Tests/WaterCoastalCapacityTest.h
deleted file mode 100644
index e22c54935..000000000
--- a/GeneralsMD/Code/Tests/WaterCoastalCapacityTest.h
+++ /dev/null
@@ -1,79 +0,0 @@
-#pragma once
-#include "WaterCoastalDomainTest.h"
-#include "Platform/WaterCoastalView.h"
-namespace WaterCoastalCapacityTest {
-using WaterCoastalDomainTest::Map;
-using WaterCoastalDomainTest::Domain;
-using WaterCoastalDomainTest::Result;
-inline void Ridges(Map &m){
- m.level=4;m.Full();for(int y=0;y<m.height;++y)for(int x=4;x<m.width;x+=8)m.heights[size_t(y)*m.width+x]=12;
-}
-inline void Check(){
- // Actual physical coast throughout the map, not a narrowed collar or a forced
- // optical exposure bit. Every channel reaches a playable boundary in the fine flood.
- Map large(260,260);Ridges(large);
- large.heights[40*260+40]=large.heights[41*260+41]=1;
- large.heights[40*260+41]=large.heights[41*260+40]=9;
- // A one-unit polygon gap lies in the SECOND fine link of coarse 640->650.
- large.polygons={Map::Rect(0,0,647,2590,4),Map::Rect(648,0,2590,2590,4)};
- if(!large.Build())return;Domain coast;CHECK(large.Install(coast)==Result::Ready);
- CHECK(coast.Grid().spacing==10&&coast.Nodes().size()<=65536&&coast.Nodes().size()>50000);
- CHECK(WaterCoastalSurf::ValidGraph(coast.Nodes(),10));
- CHECK(coast.Cells().size()==coast.Nodes().size());if(coast.Cells().size()!=coast.Nodes().size())return;
- for(size_t i=0;i<coast.Cells().size();++i){
- const auto&c=coast.Cells()[i];const auto&n=coast.Nodes()[i];
- CHECK(c.x>=0&&c.y>=0&&c.x<259&&c.y<259);if(c.x<0||c.y<0||c.x>=259||c.y>=259)return;
- CHECK(n.world[0]==c.x*10&&n.world[1]==c.y*10&&n.world[2]==4);
- CHECK(n.context.depth==4-large.heights[size_t(c.y)*260+c.x]);
- CHECK(n.context.depth>.15&&n.context.depth<12&&n.context.distance<139);
- }
- const int a=coast.Topology().Find(64,80,4),b=coast.Topology().Find(65,80,4);
- CHECK(a>=0&&b>=0);if(a<0||b<0)return;
- CHECK((coast.Cells()[size_t(a)].connections&1)==0);
- CHECK(coast.Nodes()[size_t(a)].neighbour[1]==0&&coast.Nodes()[size_t(b)].neighbour[0]==0);
- CHECK(!coast.Support().At(64,80,4,1,0).Allows(0,0));
- const auto intervals=WaterShoreSource::Intervals(large.polygons,4,800,true);
- CHECK(WaterShoreSource::Covered(intervals,640,645));
- CHECK(!WaterShoreSource::Covered(intervals,645,650)); // armed second-link control
- const auto saddle=coast.Support().At(40,40,4,1,1);
- CHECK(saddle.tile);if(!saddle.tile)return;
- const float actual[4]={1,9,9,1};for(unsigned i=0;i<4;++i)CHECK(saddle.tile->heights[i]==actual[i]);
- CHECK(coast.Topology().Find(40,40,4)>=0&&coast.Topology().Find(41,41,4)>=0);
- CHECK(!saddle.Allows(0,0)); // exact terrain-cell saddle; endpoint-only coarse check fails
- size_t work=10000;CHECK(saddle.CoversRectangle(.9,.9,1,1,work)==WaterShoreSupport::AreaResult::Covered);
- work=10000;CHECK(saddle.CoversRectangle(0,0,1,1,work)==WaterShoreSupport::AreaResult::Unsupported);
- for(const auto&e:coast.Topology().Edges()){
- const auto&ca=coast.Cells()[e.a],&cb=coast.Cells()[e.b];
- const double ha=large.heights[size_t(ca.y)*260+ca.x],hb=large.heights[size_t(cb.y)*260+cb.x];
- CHECK(ha<4&&hb<4&&(ha+hb)*.5<4);
- CHECK(!(ca.x==64&&cb.x==65&&ca.y==cb.y));
- }
- const auto signature=WaterCoastalDomainTest::Signature(coast);Domain repeat;
- CHECK(large.Install(repeat)==Result::Ready&&WaterCoastalDomainTest::Signature(repeat)==signature);
- CHECK(large.Install(coast,1)==Result::Invalid&&WaterCoastalDomainTest::Signature(coast)==signature);
-
- Map widest(130,130);widest.spacing=128;widest.level=6;widest.Full();if(!widest.Build())return;
- widest.field.physicalShore.assign(widest.field.physicalShore.size(),1); // capacity-only armed metadata
- CHECK(widest.Install(coast)==Result::TooManyCells&&WaterCoastalDomainTest::Signature(coast)==signature);
-
- // Count all levels together and use one deterministic stride, preserving exact
- // level keys rather than consuming the capacity with whichever level arrived first.
- Map multi(130,130);Ridges(multi);multi.polygons.push_back(Map::Rect(0,0,1290,1290,5));
- if(!multi.Build())return;WaterOpticalContext::Field upper;
- CHECK(WaterOpticalContext::Build(multi.heights.data(),130,130,0,10,1,5,multi.polygons,upper));
- Domain levels;CHECK(levels.Build(multi.heights.data(),130,130,0,10,1,multi.polygons,{{5,&upper},{4,&multi.field}})==Result::Ready);
- CHECK(levels.Grid().spacing==10&&levels.Nodes().size()<65536&&WaterCoastalSurf::ValidGraph(levels.Nodes(),10));
- const int low=levels.Topology().Find(1,1,4),high=levels.Topology().Find(1,1,5);
- CHECK(low>=0&&high>=0&&low!=high);
- if(low>=0&&high>=0){CHECK(levels.Nodes()[size_t(low)].context.depth==4&&levels.Nodes()[size_t(high)].context.depth==5);}
- Domain sorted;CHECK(sorted.Build(multi.heights.data(),130,130,0,10,1,multi.polygons,{{4,&multi.field},{5,&upper}})==Result::Ready);
- CHECK(WaterCoastalDomainTest::Signature(sorted)==WaterCoastalDomainTest::Signature(levels));
-
- // Fine maps keep their original lattice; an entirely wet sea still has no
- // physical coast and must not gain source nodes merely to fill the atlas.
- Map small(11,11);Ridges(small);if(!small.Build())return;Domain fine;
- CHECK(small.Install(fine)==Result::Ready&&fine.Grid().spacing==5);
- Map sea(260,260);sea.level=4;sea.Full();if(!sea.Build())return;Domain empty;
- CHECK(sea.Install(empty)==Result::Ready&&empty.Nodes().empty()&&empty.Grid().spacing==5);
-}
-}
diff --git a/GeneralsMD/Code/Tests/WaterCoastalDomainTest.h b/GeneralsMD/Code/Tests/WaterCoastalDomainTest.h
deleted file mode 100644
index 3351b3349..000000000
--- a/GeneralsMD/Code/Tests/WaterCoastalDomainTest.h
+++ /dev/null
@@ -1,123 +0,0 @@
-#pragma once
-// Physical-domain regressions use armed optical controls and actual map geometry.
-// Included after test_harness.h; no custom runner or process exit.
-#include "Platform/WaterCoastalDomain.h"
-namespace WaterCoastalDomainTest {
-using Domain=WaterCoastalDomain::Domain;
-using Result=WaterCoastalDomain::Result;
-namespace Opt=WaterOpticalContext;
-struct Map {
- int width,height,border=0;double spacing=10,scale=1;float level=10;
- std::vector<uint8_t> heights;std::vector<Opt::Polygon> polygons;Opt::Field field;
- Map(int w,int h):width(w),height(h),heights(size_t(w)*h,0){Full();}
- static Opt::Polygon Rect(float x0,float y0,float x1,float y1,float z){return {{{x0,y0,z},{x1,y0,z},{x1,y1,z},{x0,y1,z}}};}
- void Full(){polygons={Rect(float(-border*spacing),float(-border*spacing),float((width-border-1)*spacing),float((height-border-1)*spacing),level)};}
- bool Build(){const bool ok=Opt::Build(heights.data(),width,height,border,float(spacing),float(scale),level,polygons,field);CHECK(ok);return ok;}
- Result Install(Domain&d,size_t budget=WaterCoastalDomain::MaxBuildWork)const{return d.Build(heights.data(),width,height,border,spacing,scale,polygons,{{level,&field}},budget);}
-};
-inline std::vector<double> Signature(const Domain &d){
- std::vector<double> s{d.Grid().originX,d.Grid().originY,d.Grid().spacing,double(d.Support().TileCount()),double(d.Support().VertexCount()),double(d.Support().Work())};
- for(const auto&c:d.Cells())s.insert(s.end(),{double(c.x),double(c.y),c.level,double(c.sourceIndex),double(c.connections)});
- for(const auto&n:d.Nodes()){
- for(float v:n.world)s.push_back(v);
- const auto&c=n.context;s.insert(s.end(),{c.depth,c.distance,c.outwardX,c.outwardY,c.exposure,c.offshore,c.analyticDamping,c.spectralDamping,c.wet,c.admitted});
- for(auto id:n.neighbour)s.push_back(id);
- }
- for(const auto&e:d.Topology().Edges())s.insert(s.end(),{double(e.a),double(e.b)});
- return s;
-}
-inline void Graph(const Domain &d){
- CHECK(WaterCoastalSurf::ValidGraph(d.Nodes(),d.Grid().spacing));
- CHECK(d.Cells().size()==d.Nodes().size()&&d.Topology().Cells().size()==d.Nodes().size());
- if(d.Cells().size()!=d.Nodes().size()||d.Topology().Cells().size()!=d.Nodes().size())return;
- for(size_t i=0;i<d.Cells().size();++i){
- const auto &c=d.Cells()[i],&sorted=d.Topology().Cells()[i];
- CHECK(c.sourceIndex==i&&sorted.sourceIndex==i&&WaterShoreHistory::SameKey(c,sorted));
- CHECK(i==0||WaterShoreHistory::Less(d.Cells()[i-1],c));
- const auto &n=d.Nodes()[i];CHECK(n.context.exposure>0&&n.context.exposure<=1&&n.context.wet==1&&n.context.admitted==1);
- CHECK(n.world[0]==float(d.Grid().originX+c.x*d.Grid().spacing)&&n.world[1]==float(d.Grid().originY+c.y*d.Grid().spacing)&&n.world[2]==float(c.level));
- CHECK(n.context.analyticDamping==WaterSurfaceModel::TerrainDamping(n.context.depth,n.context.offshore)&&n.context.spectralDamping==WaterFftGeometry::SafeDamping(n.context.analyticDamping,n.context.depth));
- }
-}
-
-inline void Check(){
- Map ridge(11,11);
- for(int y=3;y<=7;++y)for(int x=3;x<=7;++x)if(x==3||x==7||y==3||y==7)ridge.heights[size_t(y)*11+x]=12;
- if(!ridge.Build())return;Domain kept;CHECK(ridge.Install(kept)==Result::Ready);Graph(kept);
- const auto enclosed=WaterSurfaceModel::SampleOffshore(ridge.field.exposure.data(),11,11,3.5f,5,10);
- const auto oceanFacing=WaterSurfaceModel::SampleOffshore(ridge.field.exposure.data(),11,11,2.5f,5,10);
- CHECK(enclosed.height==0);
- CHECK(oceanFacing.height>.49f&&oceanFacing.height<.51f);
- CHECK(kept.Topology().Find(7,10,10)<0);
- CHECK(kept.Topology().Find(5,10,10)>=0);
- CHECK(kept.Topology().Find(4,10,10)>=0);
- for(const auto&c:kept.Cells())CHECK(!(c.x>6&&c.x<14&&c.y>6&&c.y<14));
- for(const auto&n:kept.Nodes())CHECK(n.context.exposure==WaterSurfaceModel::SampleOffshore(
- ridge.field.exposure.data(),11,11,n.world[0]/10,n.world[1]/10,10).height);
-
-
- Map gap(11,11);gap.heights[5*11+6]=12;
- gap.polygons={Map::Rect(0,0,43,100,10),Map::Rect(44,20,76,80,10)};if(!gap.Build())return;Domain separated;
- CHECK(gap.field.exposure[4*11+5]==0);
- for(int y=2;y<=8;++y)for(int x=5;x<=7;++x)
- if(gap.heights[size_t(y)*11+x]<gap.level)CHECK(gap.field.exposure[size_t(y)*11+x]==0);
- CHECK(gap.Install(separated)==Result::Ready);Graph(separated);
- CHECK(separated.Topology().Find(10,8,10)<0);
- CHECK(separated.Topology().Find(8,8,10)>=0);
- for(const auto&n:separated.Nodes())CHECK(n.world[0]<=43);
- // The union must connect when two polygons overlap BETWEEN native samples:
- // neither polygon alone covers the complete native edge from x=40 to x=50.
- gap.polygons={Map::Rect(0,0,46,100,10),Map::Rect(45,20,76,80,10)};
- if(!gap.Build())return;Domain joined;CHECK(gap.field.exposure[4*11+5]==255);
- CHECK(gap.Install(joined)==Result::Ready);Graph(joined);
- CHECK(joined.Topology().Find(10,8,10)>=0);
-
-
- Map island(17,17);island.level=20;island.Full();
- for(int y=7;y<=9;++y)for(int x=7;x<=9;++x)island.heights[size_t(y)*17+x]=24;
- if(!island.Build())return;Domain coast;CHECK(island.Install(coast)==Result::Ready);Graph(coast);
- CHECK(coast.Topology().Find(13,16,20)>=0);
- CHECK(!coast.Cells().empty());
- for(const auto&c:coast.Cells())CHECK(c.x>0&&c.y>0&&c.x<32&&c.y<32);
-
- auto layeredPolygons=island.polygons;layeredPolygons.push_back(Map::Rect(0,0,160,160,10));Opt::Field lower;
- CHECK(Opt::Build(island.heights.data(),17,17,0,10,1,10,layeredPolygons,lower));
- Domain layered;CHECK(layered.Build(island.heights.data(),17,17,0,10,1,layeredPolygons,{{20,&island.field},{10,&lower}})==Result::Ready);Graph(layered);
- CHECK(std::any_of(layered.Cells().begin(),layered.Cells().end(),[](const auto&c){return c.level==10;})&&std::any_of(layered.Cells().begin(),layered.Cells().end(),[](const auto&c){return c.level==20;}));
-
- for(double spacing:{32.,64.,128.}){
- Map sea(130,130);sea.level=6;sea.spacing=spacing;sea.Full();if(!sea.Build())return;
- CHECK(std::all_of(sea.field.physicalShore.begin(),sea.field.physicalShore.end(),[](uint8_t v){return v==255;}));
- Domain empty;CHECK(sea.Install(empty)==Result::Ready&&empty.Nodes().empty());Graph(empty);
- }
-
-
- // Playable boundary, not the padded terrain extent, is the exposure seed.
- Map boundary(5,5);boundary.border=1;boundary.level=10;boundary.Full();boundary.heights.assign(25,12);
- for(int y=1;y<=3;++y)boundary.heights[size_t(y)*5+2]=0;
- if(!boundary.Build())return;Domain boundaryDomain;CHECK(boundary.Install(boundaryDomain)==Result::Ready);
- CHECK(boundaryDomain.Topology().Find(4,4,10)>=0);Graph(boundaryDomain);
- Map lastRow(5,5);lastRow.heights.assign(25,12);lastRow.heights[4*5+2]=0;if(!lastRow.Build())return;Domain lastDomain;
- CHECK(lastRow.Install(lastDomain)==Result::Ready&&lastDomain.Topology().Find(4,7,10)>=0);Graph(lastDomain);
- Map dryEdge(5,5);dryEdge.heights.assign(25,12);dryEdge.heights[3*5+2]=0;dryEdge.heights[4*5+2]=10;if(!dryEdge.Build())return;Domain dryDomain;
- CHECK(dryEdge.Install(dryDomain)==Result::Ready&&dryDomain.Nodes().empty());
-
-
- // Diagonal wet endpoints in one half-cell can still straddle a dry saddle.
- Map saddle(3,3);saddle.level=14;saddle.Full();saddle.heights={13,17,17,17,5,5,17,5,5};if(!saddle.Build())return;Domain saddleDomain;
- CHECK(saddle.Install(saddleDomain)==Result::Ready);
- CHECK(saddleDomain.Topology().Find(0,0,14)>=0&&saddleDomain.Topology().Find(1,1,14)>=0);
- auto stencil=saddleDomain.Support().At(0,0,14,1,1);CHECK(!stencil.Allows(0,0));Graph(saddleDomain);
-
- const auto before=Signature(kept);
- CHECK(ridge.Install(kept,1)==Result::Invalid&&Signature(kept)==before);
- auto bad=ridge.field;bad.physicalShore.pop_back();
- CHECK(kept.Build(ridge.heights.data(),11,11,0,10,1,ridge.polygons,{{10,&bad}})==Result::Invalid&&Signature(kept)==before);
- std::vector<Opt::Polygon> tooMany(Opt::MaxPoints/3+1);
- CHECK(kept.Build(ridge.heights.data(),11,11,0,10,1,tooMany,{{10,&ridge.field}})==Result::Invalid&&Signature(kept)==before);
- CHECK(kept.Build(ridge.heights.data(),11,11,0,10,1,ridge.polygons,{{10,&ridge.field},{10,&ridge.field}})==Result::Invalid&&Signature(kept)==before);
- Map capped(260,260);capped.level=6;capped.Full();if(!capped.Build())return;capped.field.physicalShore.assign(capped.field.physicalShore.size(),1);
- CHECK(capped.Install(kept)==Result::TooManyCells&&Signature(kept)==before);
-
-}
-}
diff --git a/GeneralsMD/Code/Tests/WaterCoastalFootprintTest.h b/GeneralsMD/Code/Tests/WaterCoastalFootprintTest.h
deleted file mode 100644
index a15a3ef39..000000000
--- a/GeneralsMD/Code/Tests/WaterCoastalFootprintTest.h
+++ /dev/null
@@ -1,72 +0,0 @@
-#pragma once
-#include "Platform/WaterCoastalView.h"
-#include "WaterCoastalDomainTest.h"
-namespace WaterCoastalFootprintTest {
-using WaterCoastalDomainTest::Map;
-using WaterCoastalDomainTest::Domain;
-using WaterCoastalDomainTest::Result;
-using WaterCoastalView::Lookup;
-using Area=WaterShoreSupport::AreaResult;
-inline double Weight(const Lookup &v){double r=0;for(float w:v.weight)r+=w;return r;}
-inline bool PointIn(const WaterOpticalContext::Polygon&p,double x,double y){
- bool in=false;for(size_t i=0,j=p.points.size()-1;i<p.points.size();j=i++){
- const auto&a=p.points[j],&b=p.points[i];if((a.y>y)!=(b.y>y))in=in^(x<a.x+(y-a.y)*(b.x-a.x)/(b.y-a.y));
- }return in;
-}
-inline void Check(){
- Map gap(11,11);gap.heights[5*11+6]=12;
- gap.polygons={Map::Rect(0,0,43,100,10),Map::Rect(44,20,76,80,10)};
- if(!gap.Build())return;Domain domain;CHECK(gap.Install(domain)==Result::Ready);
- const auto point=domain.Support().At(8,8,10,.6,.2);
- CHECK(point.Allows(0,0)&&point.Allows(0,1));
- CHECK(domain.Topology().Find(8,8,10)>=0&&domain.Topology().Find(9,8,10)<0);
- // The centre-only lookup at (43,41) keeps original weight .4. Linear sampling
- // at (44.25,41) then borrows .375*.4=.15 across the gap into the rejected pool.
- const double oldBorrow=((1-.6)*(1-.2)+(1-.6)*.2)*.375;
- CHECK(std::abs(oldBorrow-.15)<1e-14&&gap.field.exposure[4*11+5]==0);
- std::vector<Lookup> output;
- CHECK(WaterCoastalView::Build(domain,{20,30,48,20,24,10},10,output));CHECK(output.size()==240);
- if(output.size()!=240)return;
- const size_t row=5*24;
- CHECK(std::abs(Weight(output[row+9])-1)<1e-7); // (39,41): complete wet footprint
- CHECK(Weight(output[row+10])==0&&Weight(output[row+11])==0&&Weight(output[row+12])==0);
- CHECK(.375*Weight(output[row+11])+.625*Weight(output[row+12])==0);
- unsigned retained=0;for(const auto&v:output)retained+=Weight(v)>0;CHECK(retained>20);
- const auto &retainedLookup=output[row+9];const double fx=.8,fy=.2;
- for(unsigned dy=0;dy<2;++dy)for(unsigned dx=0;dx<2;++dx)
- CHECK(std::abs(retainedLookup.weight[dy*2+dx]-(dx?fx:1-fx)*(dy?fy:1-fy))<3e-8);
-
- // A thin notch has no polygon vertex inside the queried rectangle; its corners
- // AND centre are inside the polygon. Full segment/rectangle intersection is essential.
- WaterOpticalContext::Polygon notch{{{0,0,10},{10,0,10},{10,10,10},{2.25f,10,10},
- {2.25f,1,10},{2.125f,1,10},{2.125f,10,10},{0,10,10}}};
- for(double x:{2.,3.})for(double y:{2.,4.})CHECK(PointIn(notch,x,y));CHECK(PointIn(notch,2.5,3));
- for(const auto&p:notch.points)CHECK(!(p.x>2&&p.x<3&&p.y>2&&p.y<4));
- WaterShoreSupport::Domain support;
- const WaterShoreHistory::Grid grid{0,0,5};
- const std::vector<WaterShoreHistory::Cell> cells{{0,0,10,0,0}};
- CHECK(support.Build(grid,cells,2,2,{notch},[](double,double){return 0.f;}));
- size_t work=10000;CHECK(support.At(0,0,10,0,0).CoversRectangle(.4,.4,.6,.8,work)==Area::Unsupported);
- work=10000;CHECK(support.At(0,0,10,0,0).CoversRectangle(.6,.4,.8,.8,work)==Area::Covered);
- work=10000;CHECK(support.At(0,0,11,0,0).CoversRectangle(.6,.4,.8,.8,work)==Area::Unsupported);
- // Union-only seams are explicitly conservative: no single polygon covers this
- // rectangle even though the union does. No accidental acceptance through parity.
- CHECK(support.Build(grid,cells,2,2,{Map::Rect(0,0,2.5,10,10),Map::Rect(2.5,0,10,10,10)},[](double,double){return 0.f;}));
- work=10000;CHECK(support.At(0,0,10,0,0).CoversRectangle(.4,.4,.6,.8,work)==Area::Unsupported);
-
- Map ridge(11,11);for(int y=0;y<11;++y)ridge.heights[size_t(y)*11+5]=12;
- if(!ridge.Build())return;Domain rd;CHECK(ridge.Install(rd)==Result::Ready);
- CHECK(rd.Topology().Find(9,8,10)>=0&&rd.Topology().Find(11,8,10)>=0); // both centres wet
- CHECK(WaterCoastalView::Build(rd,{40,35,20,10,2,1},10,output));CHECK(output.size()==2);
- if(output.size()!=2)return;CHECK(Weight(output[0])==0&&Weight(output[1])==0); // dry ridge between them
-
- Map full(11,11);for(int y=0;y<11;++y)full.heights[size_t(y)*11]=12;
- if(!full.Build())return;Domain fd;CHECK(full.Install(fd)==Result::Ready);
- output.assign(1,Lookup{});output[0].node[0]=17;output[0].weight[0]=.75f;
- auto preserved=[&](){return output.size()==1&&output[0].node[0]==17&&output[0].weight[0]==.75f;};
- CHECK(!WaterCoastalView::Build(fd,{20,20,20,20,8,8},10,output,WaterCoastalView::MaxBuildWork,0)&&preserved());
- CHECK(!WaterCoastalView::Build(fd,{-32,-32,128,128,1,1},10,output)&&preserved()); // per-footprint tile cap
- CHECK(WaterCoastalView::Build(fd,{20,20,20,20,8,8},10,output));CHECK(output.size()==64);
- for(const auto&v:output)CHECK(std::abs(Weight(v)-1)<1e-7);
-}
-}
diff --git a/GeneralsMD/Code/Tests/WaterCoastalViewTest.h b/GeneralsMD/Code/Tests/WaterCoastalViewTest.h
deleted file mode 100644
index 904ed11b9..000000000
--- a/GeneralsMD/Code/Tests/WaterCoastalViewTest.h
+++ /dev/null
@@ -1,139 +0,0 @@
-#pragma once
-// Existing test_harness.h supplies CHECK. These fixtures use real physical domains,
-// with separate expected coordinates/weights and armed rejected contributions.
-#include "Platform/WaterCoastalView.h"
-#include "WaterCoastalDomainTest.h"
-namespace WaterCoastalViewTest {
-using WaterCoastalDomainTest::Map;
-using WaterCoastalDomainTest::Domain;
-using WaterCoastalDomainTest::Result;
-using WaterCoastalView::Mapping;
-using WaterCoastalView::Lookup;
-inline double Weight(const Lookup&v){double sum=0;for(float w:v.weight)sum+=w;return sum;}
-inline bool Same(const std::vector<Lookup>&a,const std::vector<Lookup>&b){
- if(a.size()!=b.size())return false;
- for(size_t i=0;i<a.size();++i)for(unsigned c=0;c<4;++c)
- if(a[i].node[c]!=b[i].node[c]||a[i].weight[c]!=b[i].weight[c])return false;
- return true;
-}
-inline void ConstantAndCoordinates(){
- Map map(11,11);for(int y=0;y<11;++y)map.heights[size_t(y)*11]=12;
- if(!map.Build())return;Domain domain;CHECK(map.Install(domain)==Result::Ready);
- // Non-square pixel/world extents expose a transposed or half-texel-shifted chart.
- const Mapping mapping{20,20,20,30,7,9};std::vector<Lookup> lookup;
- CHECK(WaterCoastalView::Build(domain,mapping,10,lookup));CHECK(lookup.size()==63);
- if(lookup.size()!=63)return;
- for(unsigned y=0;y<9;++y)for(unsigned x=0;x<7;++x){
- const double wx=20+(x+.5)*20/7,wy=20+(y+.5)*30/9;
- const double gx=wx/5,gy=wy/5;const int ix=int(std::floor(gx)),iy=int(std::floor(gy));
- const double fx=gx-ix,fy=gy-iy;const auto&v=lookup[size_t(y)*7+x];
- CHECK(std::abs((wx-20)/20-(x+.5)/7)<1e-14);
- CHECK(std::abs((wy-20)/30-(y+.5)/9)<1e-14);
- double density=0,ageMoment=0;
- for(unsigned dy=0;dy<2;++dy)for(unsigned dx=0;dx<2;++dx){
- const unsigned c=dy*2+dx;const int id=domain.Topology().Find(ix+int(dx),iy+int(dy),10);
- const double expected=(dx?fx:1-fx)*(dy?fy:1-fy);
- CHECK(id>=0);CHECK(v.node[c]==(expected>0&&id>=0?unsigned(id)+1:0));
- CHECK(std::abs(v.weight[c]-expected)<3e-8);
- density+=v.weight[c]*3.25;ageMoment+=v.weight[c]*7.5;
- }
- CHECK(std::abs(Weight(v)-1)<8e-8);
- CHECK(std::abs(density-3.25)<3e-7&&std::abs(ageMoment-7.5)<6e-7);
- }
-}
-inline void GapAndSaddle(){
- Map map(11,11);map.heights[5*11+6]=12;
- map.polygons={Map::Rect(0,0,43,100,10),Map::Rect(44,20,76,80,10)};
- if(!map.Build())return;Domain domain;CHECK(map.Install(domain)==Result::Ready);
- CHECK(map.field.exposure[4*11+5]==0); // optical connectivity also respects the authored gap
- CHECK(domain.Topology().Find(8,8,10)>=0&&domain.Topology().Find(9,8,10)<0);
- std::vector<Lookup> lookup;
- // In connected polygon: retain its original half-weight, never normalize to one.
- CHECK(WaterCoastalView::Build(domain,{42,39.5,1,1,1,1},10,lookup));
- CHECK(lookup.size()==1);if(lookup.size()!=1)return;
- CHECK(lookup[0].node[0]==unsigned(domain.Topology().Find(8,8,10))+1);
- CHECK(lookup[0].weight[0]==.5f&&Weight(lookup[0])==.5);
- for(double ox:{43.,44.}){ // target in polygon gap, then inside disconnected pool
- CHECK(WaterCoastalView::Build(domain,{ox,39.5,1,1,1,1},10,lookup));
- CHECK(lookup.size()==1&&Weight(lookup[0])==0);
- }
- Map saddle(3,3);saddle.level=14;saddle.Full();saddle.heights={13,17,17,17,5,5,17,5,5};
- if(!saddle.Build())return;Domain sd;CHECK(saddle.Install(sd)==Result::Ready);
- CHECK(sd.Topology().Find(0,0,14)>=0&&sd.Topology().Find(1,1,14)>=0);
- CHECK(!sd.Support().At(0,0,14,.9,.9).Allows(0,0)); // wet endpoints, dry interior
- CHECK(WaterCoastalView::Build(sd,{4,4,1,1,1,1},14,lookup));
- CHECK(lookup.size()==1);if(lookup.size()!=1)return;
- CHECK(lookup[0].node[0]==0&&lookup[0].weight[0]==0);
- CHECK(lookup[0].node[3]==unsigned(sd.Topology().Find(1,1,14))+1);
- CHECK(std::abs(lookup[0].weight[3]-.81)<3e-8&&std::abs(Weight(lookup[0])-.81)<3e-8);
-}
-inline void BordersAndLevels(){
- Map map(11,11);map.border=2;map.Full();map.heights[5*11+2]=12;
- if(!map.Build())return;Domain domain;CHECK(map.Install(domain)==Result::Ready);
- CHECK(domain.Grid().originX==-20&&domain.Grid().originY==-20);
- std::vector<Lookup> lookup;
- CHECK(WaterCoastalView::Build(domain,{-20,0,10,10,4,4},10,lookup));CHECK(lookup.size()==16);
- if(lookup.size()!=16)return;
- for(unsigned y=0;y<4;++y)for(unsigned x=0;x<4;++x){
- const double gx=(x+.5)*.5,gy=4+(y+.5)*.5;
- const int ix=int(std::floor(gx)),iy=int(std::floor(gy));const auto&v=lookup[size_t(y)*4+x];
- CHECK(std::abs(Weight(v)-1)<8e-8);
- CHECK(v.node[0]==unsigned(domain.Topology().Find(ix,iy,10))+1);
- }
- CHECK(WaterCoastalView::Build(domain,{-30,0,10,10,2,2},10,lookup));
- CHECK(lookup.size()==4);for(const auto&v:lookup)CHECK(Weight(v)==0); // no edge clamp
- CHECK(WaterCoastalView::Build(domain,{1099511627776.,0,64,64,2,2},10,lookup));
- for(const auto&v:lookup)CHECK(Weight(v)==0); // valid float chart, out of int32 lattice
-
- Map levels(11,11);for(int y=0;y<11;++y)levels.heights[size_t(y)*11+3]=12;
- levels.heights[5*11+8]=20;levels.polygons.push_back(Map::Rect(0,0,100,100,14));
- if(!levels.Build())return;WaterOpticalContext::Field upper;
- CHECK(WaterOpticalContext::Build(levels.heights.data(),11,11,0,10,1,14,levels.polygons,upper));
- Domain layered;CHECK(layered.Build(levels.heights.data(),11,11,0,10,1,levels.polygons,{{14,&upper},{10,&levels.field}})==Result::Ready);
- const int lowerId=layered.Topology().Find(5,8,10),upperId=layered.Topology().Find(5,8,14);
- CHECK(lowerId>=0&&upperId>=0&&lowerId!=upperId);
- const Mapping centred{24.5,39.5,1,1,1,1};
- for(double level:{10.,14.}){
- CHECK(WaterCoastalView::Build(layered,centred,level,lookup));CHECK(lookup.size()==1);
- if(lookup.size()!=1)return;
- CHECK(lookup[0].node[0]==unsigned(level==10?lowerId:upperId)+1&&lookup[0].weight[0]==1);
- CHECK(Weight(lookup[0])==1);
- }
- CHECK(WaterCoastalView::Build(layered,centred,11,lookup));CHECK(lookup.size()==1&&Weight(lookup[0])==0);
-}
-inline void BoundsAndAtomicity(){
- Domain empty;const Mapping good{0,0,64,64,1,1};
- std::vector<Lookup> output(2);output[0].node[0]=17;output[0].weight[0]=.75f;output[1].node[3]=29;output[1].weight[3]=.25f;
- const auto original=output;
- CHECK(WaterCoastalView::SameMapping(good,good));
- for(unsigned field=0;field<6;++field){Mapping changed=good;
- if(field==0)changed.originX=1;if(field==1)changed.originY=1;if(field==2)changed.widthWorld=32;
- if(field==3)changed.heightWorld=32;if(field==4)changed.widthPixels=2;if(field==5)changed.heightPixels=2;
- CHECK(!WaterCoastalView::SameMapping(good,changed));
- }
- for(unsigned kind=0;kind<11;++kind){Mapping bad=good;
- if(kind==0)bad.widthPixels=0;if(kind==1)bad.heightPixels=0;
- if(kind==2)bad.widthPixels=513;if(kind==3)bad.heightPixels=513;
- if(kind==4)bad.widthWorld=0;if(kind==5)bad.heightWorld=-1;
- if(kind==6)bad.originX=std::numeric_limits<double>::quiet_NaN();
- if(kind==7)bad.originY=.1; // cannot represent exact shader metadata
- if(kind==8)bad.widthWorld=double((std::numeric_limits<float>::denorm_min)());
- if(kind==9){bad.originX=double((std::numeric_limits<float>::max)());bad.widthWorld=bad.originX;}
- if(kind==10)bad.heightWorld=std::numeric_limits<double>::infinity();
- CHECK(!WaterCoastalView::ValidMapping(bad));
- CHECK(!WaterCoastalView::Build(empty,bad,10,output)&&Same(output,original));
- }
- for(double badLevel:{.1,std::numeric_limits<double>::quiet_NaN(),std::numeric_limits<double>::infinity()})
- CHECK(!WaterCoastalView::Build(empty,good,badLevel,output)&&Same(output,original));
- CHECK(!WaterCoastalView::Build(empty,good,10,output,WaterCoastalView::WorkPerPixel-1)&&Same(output,original));
- CHECK(WaterCoastalView::Build(empty,good,10,output,WaterCoastalView::WorkPerPixel));
- CHECK(output.size()==1&&Weight(output[0])==0);
- const Mapping largest{-256,-256,512,512,512,512};
- const auto one=output;
- CHECK(!WaterCoastalView::Build(empty,largest,10,output,WaterCoastalView::MaxBuildWork-1)&&Same(output,one));
- CHECK(WaterCoastalView::Build(empty,largest,10,output));CHECK(output.size()==512u*512u);
- bool allZero=true;for(const auto&v:output)for(unsigned c=0;c<4;++c)allZero=allZero&&v.node[c]==0&&v.weight[c]==0;
- CHECK(allZero);
-}
-inline void Check(){ConstantAndCoordinates();GapAndSaddle();BordersAndLevels();BoundsAndAtomicity();}
-}
diff --git a/GeneralsMD/Code/Tests/test_posix_draw_resolve.cpp b/GeneralsMD/Code/Tests/test_posix_draw_resolve.cpp
index cb39e34ab..f174510de 100644
--- a/GeneralsMD/Code/Tests/test_posix_draw_resolve.cpp
+++ b/GeneralsMD/Code/Tests/test_posix_draw_resolve.cpp
@@ -329,8 +329,7 @@ static void check_constants(PosixDevice9 *device)
CHECK(memcmp(water.HullData,hull_registers[1],sizeof(water.HullData))==0);
// The optional foam contour is a distinct tail, never a replacement for the mean hull used
// by displacement. Exercise every register, including the twelfth vertex of hull eight.
- CHECK(sizeof(water)==188*16 && offsetof(SdlWaterPixelConstants,ContactHullData)==100*16);
- CHECK(offsetof(SdlWaterPixelConstants,CoastalArea)==184*16 && offsetof(SdlWaterPixelConstants,CoastalParams)==185*16);
+ CHECK(sizeof(water)==186*16 && offsetof(SdlWaterPixelConstants,ContactHullData)==100*16);
float contact_registers[80][4]={};
for(int r=0;r<80;++r)for(int c=0;c<4;++c)contact_registers[r][c]=-float(r*4+c)-0.75f;
CHECK(device->SetPixelShaderConstantF(96,&contact_registers[0][0],80)==D3D_OK);
@@ -366,11 +365,11 @@ static void check_constants(PosixDevice9 *device)
CHECK(device->SetPixelShaderConstantF(175,contact_registers[79],1)==D3D_OK);
CHECK(device->SetPixelShaderConstantF(WaterHullVisualLayout::PixelRegisterCount,contact_registers[79],1)==D3DERR_INVALIDCALL);
// Exact mesh transport extends the emulated bank deliberately, without moving the old
- // 188-register native vertex prefix or copying the reserved engine-register gap into metadata.
+ // 186-register native vertex prefix or copying the reserved engine-register gap into metadata.
using namespace WaterHullVisualLayout;
CHECK(PosixDevice9::PIXEL_SHADER_CONSTANT_COUNT==896);
- CHECK(sizeof(SdlWaterVisualPixelConstants)==196*16 && offsetof(SdlWaterVisualPixelConstants,VisualHullMeta)==188*16);
- CHECK(VertexCommonRegisters==188 && FragmentCommonRegisters==196);
+ CHECK(sizeof(SdlWaterVisualPixelConstants)==194*16 && offsetof(SdlWaterVisualPixelConstants,VisualHullMeta)==186*16);
+ CHECK(VertexCommonRegisters==186 && FragmentCommonRegisters==194);
CHECK(BlockOffset(0)==0 && BlockOffset(1)==256 && BlockOffset(2)==512);
CHECK(BlockRegisters(0)==256 && BlockRegisters(1)==256 && BlockRegisters(2)==192);
float visualMeta[8][4]={};float visualPacket[704][4]={};float reserved[8][4]={};
@@ -383,18 +382,9 @@ static void check_constants(PosixDevice9 *device)
CHECK(device->SetPixelShaderConstantF(895,visualPacket[703],2)==D3DERR_INVALIDCALL);
CHECK(device->SetPixelShaderConstantF(896,visualPacket[703],1)==D3DERR_INVALIDCALL);
SdlWaterVisualPixelConstants visual;
- // The scene-owned native coastal tail is independent of emulated c184..191 above.
- // Reusing a populated CPU block must clear it until a successful draw explicitly binds a view.
- const float coastArea[4]={-32,48,256,128},coastParams[4]={1,7,24.25f,24.375f},zeroCoast[4]={};
- memcpy(water.CoastalArea,coastArea,sizeof(coastArea));memcpy(water.CoastalParams,coastParams,sizeof(coastParams));
- device->Build_Water_Constants(pixel,water);
- CHECK(memcmp(water.CoastalArea,zeroCoast,sizeof(zeroCoast))==0 && memcmp(water.CoastalParams,zeroCoast,sizeof(zeroCoast))==0);
- // A successful scene binding fills this native tail before the visual wrapper copies it.
- memcpy(water.CoastalArea,coastArea,sizeof(coastArea));memcpy(water.CoastalParams,coastParams,sizeof(coastParams));
device->Build_Water_Visual_Constants(water,visual);
CHECK(memcmp(&visual.Water,&water,sizeof(water))==0);
CHECK(memcmp(visual.VisualHullMeta,visualMeta,sizeof(visualMeta))==0);
- CHECK(memcmp(visual.Water.CoastalArea,coastArea,sizeof(coastArea))==0 && memcmp(visual.Water.CoastalParams,coastParams,sizeof(coastParams))==0);
// After an ocean, missing/zero metadata must replace every previously populated slot.
memset(visualMeta,0,sizeof(visualMeta));CHECK(device->SetPixelShaderConstantF(176,visualMeta[0],8)==D3D_OK);
device->Build_Water_Visual_Constants(water,visual);CHECK(memcmp(visual.VisualHullMeta,visualMeta,sizeof(visualMeta))==0);
diff --git a/GeneralsMD/Code/Tests/test_sdl_gpu_frame.cpp b/GeneralsMD/Code/Tests/test_sdl_gpu_frame.cpp
index c5341caf8..e5c5b7ed9 100644
--- a/GeneralsMD/Code/Tests/test_sdl_gpu_frame.cpp
+++ b/GeneralsMD/Code/Tests/test_sdl_gpu_frame.cpp
@@ -46,15 +46,11 @@
#include "Platform/WaterFoamShading.h"
#include "Platform/WaterFoamEnvironment.h"
#include "Platform/WaterShoreFoam.h"
-#include "Platform/WaterCoastalCrest.h"
-#include "Platform/WaterCoastalSurf.h"
-#include "Platform/WaterCoastalPresentation.h"
-#include "Platform/WaterCoastalView.h"
-#include "Platform/WaterCoastalIncident.h"
#include "Platform/WaterShoreOverlay.h"
#include "../Libraries/Source/WWVegas/WW3D2/ffshader.h"
#include "Platform/WaterBowRefinement.h"
#include <complex>
+#include <sstream>
#include <SDL3/SDL.h>
@@ -72,9 +68,6 @@ static int failures = 0;
// Bind the production fragment layout even when a normal-only fixture has no mesh hulls.
static void push_empty_visual_water(SDL_GPUCommandBuffer *commands,const SdlWaterPixelConstants &water)
{
- if(!WaterHullVisual::Enabled()) {
- SDL_PushGPUFragmentUniformData(commands,0,&water,sizeof(water));return;
- }
SdlWaterVisualPixelConstants common={};common.Water=water;
SDL_PushGPUFragmentUniformData(commands,0,&common,sizeof(common));
const float packets[WaterHullVisualLayout::PacketRegisters][4]={};
@@ -83,6 +76,48 @@ static void push_empty_visual_water(SDL_GPUCommandBuffer *commands,const SdlWate
WaterHullVisualLayout::BlockRegisters(block)*16);
}
+// Observe the production normal without a runtime shader variant or environment switch.
+static bool observe_water_normal(std::string &source)
+{
+ const std::string output=" return current;\n}";
+ const size_t at=source.rfind(output);
+ CHECK(at!=std::string::npos);
+ if(at==std::string::npos)return false;
+ source.insert(at," current.rgb = normal*0.5+0.5;\n");
+ return true;
+}
+
+// Compile the exact production refraction helpers with fixture inputs. Unrelated mesh-hull
+// buffers occupy b1..b3 in the complete material shader; these helpers need only its b0.
+static bool water_refraction_fixture_source(const std::string &production,std::string &source)
+{
+ const size_t input=production.find("struct Input");
+ const size_t terrain=production.find("float terrainHeight("),terrainEnd=production.find("float terrainSun(",terrain);
+ const size_t first=production.find("float2 pixelOffset("),last=production.find("WaterRefractionSample waterRefractedScene(",first);
+ const size_t opening=production.find('{',last);
+ CHECK(input!=std::string::npos && terrain<terrainEnd && terrainEnd!=std::string::npos
+ && first<last && last<opening && opening!=std::string::npos);
+ if(input==std::string::npos || terrain>=terrainEnd || terrainEnd==std::string::npos
+ || first>=last || last>=opening || opening==std::string::npos)return false;
+ size_t end=opening+1;int depth=1;
+ for(;end<production.size() && depth;++end) {
+ if(production[end]=='{')++depth;
+ else if(production[end]=='}')--depth;
+ }
+ CHECK(depth==0);if(depth)return false;
+ std::istringstream prefix(production.substr(0,input));std::string line;
+ source.clear();
+ while(std::getline(prefix,line)) {
+ if(line.find("cbuffer WaterVisualBlock")!=std::string::npos
+ || line.find("float4 VisualHullMeta[")!=std::string::npos)continue;
+ source+=line+'\n';
+ }
+ source+=production.substr(terrain,terrainEnd-terrain);
+ source+=production.substr(first,end-first);
+ source+=WaterOpticalModel::GetHlslSource();
+ return true;
+}
+
static const unsigned int WIDTH = 64;
static const unsigned int HEIGHT = 48;
@@ -575,21 +610,16 @@ static void check_gpu_water_mesh_correction(SdlGpuFrame *frame)
}
} resources;
resources.device=frame->Device();
- const char *previous=getenv("ZH_WATER_DEBUG");
- const bool hadDebug=previous!=NULL;
- const std::string previousDebug=previous?previous:"";
- CHECK(setenv("ZH_WATER_DEBUG","normal",1)==0);
PixelPipelineDescription pixelDescription={};std::string pixelSource;
const bool generated=EngineShader_Pixel_Program(ENGINE_SHADER_WATER_TRAPEZOID,pixelDescription,
pixelSource,COMBINER_SHADER_TARGET_SDL3_GPU);
- if(hadDebug) CHECK(setenv("ZH_WATER_DEBUG",previousDebug.c_str(),1)==0);
- else CHECK(unsetenv("ZH_WATER_DEBUG")==0);
CHECK(generated);if(!generated) return;
+ if(!observe_water_normal(pixelSource)) return;
std::vector<unsigned char> spirv;std::string error;
bool compiled=SDL3_Compile_HLSL_To_SPIRV(pixelSource,false,spirv,error);CHECK(compiled);
if(!compiled) {printf("water correction pixel compile: %s\n",error.c_str());return;}
unsigned samplers=0,pixelUniforms=0;SDL3_Shader_Slots(spirv,false,samplers,pixelUniforms);
- const unsigned expectedUniforms=WaterHullVisual::Enabled()?4u:1u;
+ const unsigned expectedUniforms=4u;
CHECK(samplers<=16 && pixelUniforms==expectedUniforms);if(samplers>16 || pixelUniforms!=expectedUniforms) return;
resources.pixel=SDL3_Create_Shader(resources.device,spirv,false,error);CHECK(resources.pixel);
if(!resources.pixel) return;
@@ -1010,7 +1040,8 @@ static void check_gpu_water_hull_effects(SdlGpuFrame *frame)
const char *vertexSource="float4 main(uint id : SV_VertexID) : SV_Position {return float4(id==1?3.0:-1.0,id==2?3.0:-1.0,0,1);}";
std::string pixelSource="cbuffer Samples : register(b0, space3) { float4 HullParameters; float4 HullData[80]; float4 Query; float4 TestBasis; float4 WaveInput; float4 ContactHullData[80]; };\n";
pixelSource+=waterSource.substr(noiseStart,noiseEnd-noiseStart);
- pixelSource+=GetHlslSource();pixelSource+=GetEffectsHlslSource(true);
+ pixelSource+="static const float4 VisualHullMeta[8]={0,0,0,0,0,0,0,0};\n";
+ pixelSource+=GetHlslSource();pixelSource+=GetEffectsHlslSource();
pixelSource+="float main(float4 pixel : SV_Position) : SV_Target { "
"uint column=(uint)pixel.x, channel=column%3; float2 local=float2((int)(column/3)-150,(int)pixel.y-40); "
"float2 world=TestBasis.xy+local.x*TestBasis.zw+local.y*float2(-TestBasis.w,TestBasis.z); "
@@ -1254,23 +1285,11 @@ static void check_gpu_water_refraction_footprint(SdlGpuFrame *frame)
} r;
r.device=frame->Device();
PixelPipelineDescription pd={};std::string ps;
- const char *oldDebug=getenv("ZH_WATER_DEBUG");const bool hadDebug=oldDebug!=NULL;
- const std::string savedDebug=oldDebug?oldDebug:"";
- // This isolated optical probe reserves b1 for its cases, with no hull packets.
- const char *oldContact=getenv("ZH_WATER_HULL_CONTACT");const bool hadContact=oldContact!=NULL;
- const std::string savedContact=oldContact?oldContact:"";
- CHECK(setenv("ZH_WATER_HULL_CONTACT","0",1)==0);
- CHECK(unsetenv("ZH_WATER_DEBUG")==0);
const bool generated=EngineShader_Pixel_Program(ENGINE_SHADER_WATER_TRAPEZOID,pd,ps,
COMBINER_SHADER_TARGET_SDL3_GPU);
- if(hadDebug)CHECK(setenv("ZH_WATER_DEBUG",savedDebug.c_str(),1)==0);
- else CHECK(unsetenv("ZH_WATER_DEBUG")==0);
- if(hadContact)CHECK(setenv("ZH_WATER_HULL_CONTACT",savedContact.c_str(),1)==0);
- else CHECK(unsetenv("ZH_WATER_HULL_CONTACT")==0);
CHECK(generated);if(!generated)return;
- const std::string entry="float4 main(Input input)";
- const size_t at=ps.find(entry);CHECK(at!=std::string::npos);if(at==std::string::npos)return;
- ps.replace(at,entry.size(),"float4 unusedWaterMain(Input input)");
+ std::string production;production.swap(ps);
+ if(!water_refraction_fixture_source(production,ps))return;
ps+=R"M4C(
cbuffer M4cCases : register(b1, space3) { float4 M4cFixtures[27 * 3]; };
// Armed M4A nearest-only control, retaining its corrected sign/shared viewport behaviour.
@@ -1547,27 +1566,14 @@ static void check_gpu_water_refraction_coordinates(SdlGpuFrame *frame)
} r;
r.device=frame->Device();
PixelPipelineDescription pd={};std::string ps;
- const char *oldDebug=getenv("ZH_WATER_DEBUG");const bool hadDebug=oldDebug!=NULL;
- const std::string savedDebug=oldDebug?oldDebug:"";
- // This isolated optical probe reserves b1 for its cases, with no hull packets.
- const char *oldContact=getenv("ZH_WATER_HULL_CONTACT");const bool hadContact=oldContact!=NULL;
- const std::string savedContact=oldContact?oldContact:"";
- CHECK(setenv("ZH_WATER_HULL_CONTACT","0",1)==0);
- CHECK(unsetenv("ZH_WATER_DEBUG")==0);
const bool generated=EngineShader_Pixel_Program(ENGINE_SHADER_WATER_TRAPEZOID,pd,ps,
COMBINER_SHADER_TARGET_SDL3_GPU);
- if(hadDebug)CHECK(setenv("ZH_WATER_DEBUG",savedDebug.c_str(),1)==0);
- else CHECK(unsetenv("ZH_WATER_DEBUG")==0);
- if(hadContact)CHECK(setenv("ZH_WATER_HULL_CONTACT",savedContact.c_str(),1)==0);
- else CHECK(unsetenv("ZH_WATER_HULL_CONTACT")==0);
CHECK(generated);if(!generated)return;
- const std::string entry="float4 main(Input input)";
- const size_t at=ps.find(entry);CHECK(at!=std::string::npos);if(at==std::string::npos)return;
- ps.replace(at,entry.size(),"float4 unusedWaterMain(Input input)");
+ std::string production;production.swap(ps);
+ if(!water_refraction_fixture_source(production,ps))return;
ps+="\n#define M4aCaseCount 10\n";
ps+=R"M4A(
-// Test-only wrapper appended to the exact generated production water pixel shader after
-// renaming its main to unusedWaterMain. This invokes the same helpers used by production main.
+// Test-only entry point invokes the exact helpers extracted from the production shader.
// Set M4aCaseCount when constructing this shader; each case occupies four float4s.
cbuffer M4aCases : register(b1, space3) { float4 M4aFixtures[M4aCaseCount * 4]; };
@@ -2054,10 +2060,7 @@ static void check_gpu_water_vertex_uniform_order(SdlGpuFrame *frame)
const unsigned contactRegister=offsetof(SdlWaterPixelConstants,ContactHullData)/16;
const unsigned lastContactRegister=contactRegister+79;
const unsigned fillRegister=offsetof(SdlWaterPixelConstants,FoamFillLights)/16;
- const unsigned coastalAreaRegister=offsetof(SdlWaterPixelConstants,CoastalArea)/16;
- const unsigned coastalParamsRegister=offsetof(SdlWaterPixelConstants,CoastalParams)/16;
- CHECK(contactRegister==100 && fillRegister==180 && coastalAreaRegister==184 && coastalParamsRegister==185
- && sizeof(SdlWaterPixelConstants)==188*16);
+ CHECK(contactRegister==100 && fillRegister==180 && sizeof(SdlWaterPixelConstants)==186*16);
std::string block="cbuffer WaterBlock : register(b1,space1) { float4 Water[";
block+=std::to_string(sizeof(SdlWaterPixelConstants)/16)+"]; };\n";
const std::string output="struct Output { float4 Position:SV_Position; [[vk::location(0)]] float4 Value:TEXCOORD0; };\n";
@@ -2065,26 +2068,25 @@ static void check_gpu_water_vertex_uniform_order(SdlGpuFrame *frame)
std::string waterVertex="cbuffer FixedBlock : register(b0,space1) { float4 Fixed; };\n"+block+output;
waterVertex+="Output main(uint id:SV_VertexID) {"+position+
"o.Value=float4(Fixed.x,Water["+std::to_string(timeRegister)+"].x,Water["+
- std::to_string(lastHullRegister)+"].w,Water["+std::to_string(fftRegister)+"].y);"
+ std::to_string(lastHullRegister)+"].w,Water["+std::to_string(fftRegister)+"].x);"
"o.Value.x+=Water["+std::to_string(historyAreaRegister)+"].x;"
"o.Value.z+=Water["+std::to_string(historyRegister)+"].w;"
"o.Value.x+=Water["+std::to_string(contactRegister)+"].w;"
"o.Value.y+=Water["+std::to_string(lastContactRegister)+"].w;"
"o.Value.x+=Water["+std::to_string(fillRegister)+"].w+Water["+std::to_string(fillRegister+1)+"].x;"
- "o.Value+=Water["+std::to_string(coastalAreaRegister)+"]+Water["+std::to_string(coastalParamsRegister)+"];return o;}\n";
+ "return o;}\n";
std::string waterPixel="cbuffer WaterBlock : register(b0,space3) { float4 Water["+
std::to_string(sizeof(SdlWaterPixelConstants)/16)+"]; };\n";
waterPixel+="float4 main([[vk::location(0)]] float4 value:TEXCOORD0):SV_Target0 {\n"
"value.w+=abs(value.y-Water["+std::to_string(timeRegister)+"].x-Water["+
- std::to_string(lastContactRegister)+"].w-Water["+std::to_string(coastalAreaRegister)+"].y-Water["+
- std::to_string(coastalParamsRegister)+"].y)*100.0;"
+ std::to_string(lastContactRegister)+"].w)*100.0;"
"value.x-=Water["+std::to_string(historyAreaRegister)+"].x;"
"value.z+=Water["+std::to_string(historyAreaRegister)+"].w;"
"value.w+=Water["+std::to_string(historyRegister)+"].w;"
"value.z+=Water["+std::to_string(lastContactRegister)+"].z;"
"value.y+=Water["+std::to_string(fillRegister+3)+"].z;"
"value.z+=Water["+std::to_string(fillRegister+2)+"].z;"
- "value+=2*Water["+std::to_string(coastalAreaRegister)+"]+3*Water["+std::to_string(coastalParamsRegister)+"];return value;}\n";
+ "return value;}\n";
const std::string plainVertex="cbuffer FixedBlock : register(b0,space1) { float4 Fixed; };\n"+output+
"Output main(uint id:SV_VertexID) {"+position+"o.Value=float4(9,8,7,6)*Fixed.x;return o;}\n";
const char *plainPixel="float4 main([[vk::location(0)]] float4 value:TEXCOORD0):SV_Target0 {return value;}\n";
@@ -2127,10 +2129,6 @@ static void check_gpu_water_vertex_uniform_order(SdlGpuFrame *frame)
const float historyTail[2][3]={{-128,.25f,24.25f},{192,.125f,26.0f}};
const float contactTail[2][3]={{12,-175.25f,91.5f},{0,0,0}};
const float fillTail[2][4]={{1,2.25f,-.875f,5.125f},{0,0,0,0}};
- // Every native tail component is read in both stages. State 1 is explicit invalid/zero,
- // including after non-water; state 0 returns immediately after a rectangle clear.
- const float coastalArea[2][4]={{-32,48,256,128},{0,0,0,0}};
- const float coastalParams[2][4]={{1,7,24.25f,24.375f},{0,0,0,0}};
for(unsigned row=0;row<rows;++row) {
if(row==3) {
// Engine rectangle-clear pipelines target its native UNORM scene format.
@@ -2144,7 +2142,7 @@ static void check_gpu_water_vertex_uniform_order(SdlGpuFrame *frame)
draw.VertexConstants=frame->Constants(0,fixed,sizeof(fixed));draw.VertexConstantsSize=sizeof(fixed);
if(waterRows[row]) {
SdlWaterPixelConstants water={};water.WaterParameters[0]=expectedWater[state[row]][1];
- water.HullData[79][3]=expectedWater[state[row]][2];water.FftParameters[0]=1;water.FftParameters[1]=expectedWater[state[row]][3];
+ water.HullData[79][3]=expectedWater[state[row]][2];water.FftParameters[0]=expectedWater[state[row]][3];
water.FoamHistoryArea[0]=historyTail[state[row]][0];water.FoamHistoryArea[3]=historyTail[state[row]][1];
water.FoamHistoryParameters[3]=historyTail[state[row]][2];
water.ContactHullData[0][3]=contactTail[state[row]][0];
@@ -2152,8 +2150,6 @@ static void check_gpu_water_vertex_uniform_order(SdlGpuFrame *frame)
water.ContactHullData[79][2]=contactTail[state[row]][2];
water.FoamFillLights[0][3]=fillTail[state[row]][0];water.FoamFillLights[1][0]=fillTail[state[row]][1];
water.FoamFillLights[2][2]=fillTail[state[row]][2];water.FoamFillLights[3][2]=fillTail[state[row]][3];
- memcpy(water.CoastalArea,coastalArea[state[row]],sizeof(water.CoastalArea));
- memcpy(water.CoastalParams,coastalParams[state[row]],sizeof(water.CoastalParams));
draw.PixelConstants=frame->Constants(1,&water,sizeof(water));draw.PixelConstantsSize=sizeof(water);
draw.VertexWaterConstants=draw.PixelConstants;draw.VertexWaterConstantsSize=draw.PixelConstantsSize;
// Poison the source after recording: deferred execution must read its copied snapshot.
@@ -2170,11 +2166,10 @@ static void check_gpu_water_vertex_uniform_order(SdlGpuFrame *frame)
if(waterRows[row] && c>=2)expected+=historyTail[state[row]][2]+(c==2?historyTail[state[row]][1]:0);
if(waterRows[row] && c<3)expected+=contactTail[state[row]][c];
if(waterRows[row] && c<3)expected+=c==0?fillTail[state[row]][0]+fillTail[state[row]][1]:fillTail[state[row]][c==1?3:2];
- if(waterRows[row])expected+=3*coastalArea[state[row]][c]+4*coastalParams[state[row]][c];
matched &= std::isfinite(values[(row*width+x)*4+c]) && std::abs(values[(row*width+x)*4+c]-expected)<0.00001f;
}
CHECK(matched);
- printf("sdl_gpu_frame_selfcheck: GPU water VS slot1: %u queued draws, shared 188-float4 pixel snapshot, mean/FFT/history/contact/fill-light/coastal tails in both stages, explicit zero contact/light/coastal fallback, intervening non-water and rectangle clear checked\n",rows);
+ printf("sdl_gpu_frame_selfcheck: GPU water VS slot1: %u queued draws, shared 186-float4 pixel snapshot, mean/FFT/history/contact/fill-light tails in both stages, explicit zero contact/light fallback, intervening non-water and rectangle clear checked\n",rows);
}
static void check_gpu_water_visual_uniform_order(SdlGpuFrame *frame)
@@ -2188,11 +2183,10 @@ static void check_gpu_water_visual_uniform_order(SdlGpuFrame *frame)
std::string vs=std::string(output)+WaterFftSampling::UniformSource("WaterVertex",1)+
"cbuffer FixedBlock:register(b0){float4 Fixed;};\n"+
"Output main(uint id:SV_VertexID){"+position+
- "o.Value=float4(WaterParameters.x,ContactHullData[79].w,FoamFillLights[3].z,1)+Fixed+CoastalArea+CoastalParams;return o;}\n";
+ "o.Value=float4(WaterParameters.x,ContactHullData[79].w,FoamFillLights[3].z,1)+Fixed;return o;}\n";
std::string ps=WaterFftSampling::UniformSource("WaterFragment",0,true)+R"HLSL(
float4 main(float4 position:SV_Position,[[vk::location(0)]] float4 value:TEXCOORD0):SV_Target0 {
int x=(int)position.x;
- value+=2*CoastalArea+3*CoastalParams;
if(x<704) {
float4 packet;
if(x<256) packet=VisualHullBlock0[x];
@@ -2266,10 +2260,6 @@ float4 main(float4 position:SV_Position,[[vk::location(0)]] float4 value:TEXCOOR
draw.VertexConstants=frame->Constants(0,fixed,sizeof(fixed));draw.VertexConstantsSize=sizeof(fixed);
water.Water.WaterParameters[0]=state+.125f;water.Water.ContactHullData[79][3]=state*2+.25f;
water.Water.FoamFillLights[3][2]=state*3+.5f;
- for(unsigned c=0;c<4;++c) {
- water.Water.CoastalArea[c]=state?float(state*8+c)+.25f:0;
- water.Water.CoastalParams[c]=state?float(state*4+c)+.125f:0;
- }
for(unsigned h=0;h<MaxHulls;++h)for(unsigned c=0;c<4;++c)
water.VisualHullMeta[h][c]=state?float(state*100+h*4+c)+.5f:0;
for(unsigned r=0;r<PacketRegisters;++r)for(unsigned c=0;c<4;++c)
@@ -2300,7 +2290,6 @@ float4 main(float4 position:SV_Position,[[vk::location(0)]] float4 value:TEXCOOR
if(waterRows[row]) {
const double prefix=c==0?state+.125:c==1?state*2+.25:c==2?state*3+.5:1;
expected=prefix+(c+1)*.0625+(state?state*100+h*4+c+.5:0);
- if(state)expected+=3*(state*8+c+.25)+4*(state*4+c+.125);
if(x<PacketRegisters)expected+=state?state*10000+x*4+c+.25:0;
}
const double actual=values[(row*width+x)*4+c],error=std::abs(actual-expected);maxError=std::max(maxError,error);
@@ -2309,7 +2298,7 @@ float4 main(float4 position:SV_Position,[[vk::location(0)]] float4 value:TEXCOOR
if(waterRows[row] && state && (x==256 || x==512))armedBoundary+=std::abs(actual-(expected-1024))>100;
}
CHECK(matched && armedLatest>0 && armedBoundary>0);
- printf("sdl_gpu_frame_selfcheck: visual hull transport: all704 packet float4s +8 metadata, PS slots0..3, 188-register VS alias and 196-register PS common, both coastal float4s in both stages, queued A/B/zero, non-water, clear, new batch, resize; max error %.9g, armed %u/%u\n",maxError,armedLatest,armedBoundary);
+ printf("sdl_gpu_frame_selfcheck: visual hull transport: all704 packet float4s +8 metadata, PS slots0..3, 186-register VS alias and 194-register PS common, queued A/B/zero, non-water, clear, new batch, resize; max error %.9g, armed %u/%u\n",maxError,armedLatest,armedBoundary);
}
static void check_gpu_water_visual_query(SdlGpuFrame *frame)
@@ -2450,15 +2439,8 @@ static void check_gpu_water_visual_zero_effect_skip(SdlGpuFrame *frame)
// contact response in the same fragment. Only the optimized body may skip a zero-effect query.
// The only test instrumentation is a counter immediately before each geometry query.
using namespace WaterHullVisualLayout;
- const char *oldContact=getenv("ZH_WATER_HULL_CONTACT"),*oldDebug=getenv("ZH_WATER_DEBUG");
- const bool hadContact=oldContact!=NULL,hadDebug=oldDebug!=NULL;
- const std::string savedContact=oldContact?oldContact:"",savedDebug=oldDebug?oldDebug:"";
- CHECK(unsetenv("ZH_WATER_HULL_CONTACT")==0); // Exercise the ordinary launch default.
- CHECK(unsetenv("ZH_WATER_DEBUG")==0);
PixelPipelineDescription description={};std::string production;
const bool generated=EngineShader_Pixel_Program(ENGINE_SHADER_WATER_TRAPEZOID,description,production,COMBINER_SHADER_TARGET_SDL3_GPU);
- if(hadContact)CHECK(setenv("ZH_WATER_HULL_CONTACT",savedContact.c_str(),1)==0);else CHECK(unsetenv("ZH_WATER_HULL_CONTACT")==0);
- if(hadDebug)CHECK(setenv("ZH_WATER_DEBUG",savedDebug.c_str(),1)==0);else CHECK(unsetenv("ZH_WATER_DEBUG")==0);
CHECK(generated);if(!generated)return;
auto extract=[&](const char *signature) {
const size_t start=production.find(signature),opening=start==std::string::npos?start:production.find('{',start);
@@ -2676,409 +2658,6 @@ float4 main(float4 pixel:SV_Position):SV_Target0 {
}
#endif // __linux__
-// Append after read_float_targets; include Platform/WaterCoastalSurf.h once and call
-// check_gpu_coastal_surf_owner(frame) in the GPU selfcheck after core math fixtures.
-// Runtime owner performs no readbacks; every readback below is test-only.
-// Insert after read_float_targets; invoke after check_gpu_fft_ocean and the
-// independent WaterCoastalIncident fixture so FFT initial-owner assertions remain valid.
-static void check_gpu_coastal_surf_from_ocean(SdlGpuFrame *frame)
-{
- using namespace WaterCoastalSurf;
- const uint64_t revision=0xc0a571;
- struct Cleanup {SdlGpuFrame *frame;~Cleanup(){CHECK(frame->Clear_Coastal_Surf());frame->Set_Target(frame->Back_Buffer_Target());}} cleanup{frame};
- CHECK(frame->Clear_Coastal_Surf());
- std::vector<Node> nodes(3);
- for(unsigned i=0;i<3;++i) {
- nodes[i].world[0]=-137.25f+83*i;nodes[i].world[1]=91.5f;nodes[i].world[2]=7+4*i;
- nodes[i].context={4,32,1,0,1,float(i)*.5f,.4f,.5f,1,1};
- }
- const bool installed=frame->Install_Coastal_Surf(revision,nodes,8);CHECK(installed);if(!installed)return;
- const SdlTarget input=frame->Coastal_Surf_Field_Target(revision);CHECK(input.Colour);if(!input.Colour)return;
- const uint64_t fftBefore=frame->Ocean_Updates();
- CHECK(frame->Prepare_Coastal_Surf_From_Ocean(revision,2.25)); // reset needs no field/FFT phase
- SDL_GPUTexture *initialState=frame->Coastal_Surf_State(revision);CHECK(initialState);if(!initialState)return;
- CHECK(frame->Ocean_Updates()==fftBefore && !frame->Coastal_Surf_Field_Due(revision,2.25));
- const auto initial=read_float_targets(frame,&initialState,1,256,256);
- CHECK(initial.size()==MaxNodes*4);if(initial.size()!=MaxNodes*4)return;
- auto field=[&](){return read_float_targets(frame,&input.Colour,1,256,256);};
- const auto untouched=field();
- const uint64_t resetUpdates=frame->Coastal_Surf_Updates();
- CHECK(frame->Prepare_Ocean(9.0f)); // deliberately wrong phase for next source tick
- const uint64_t wrongFft=frame->Ocean_Updates();
- CHECK(!frame->Prepare_Coastal_Surf_From_Ocean(revision,2.35));
- CHECK(frame->Coastal_Surf_Updates()==resetUpdates && frame->Ocean_Updates()==wrongFft);
- CHECK(frame->Coastal_Surf_State(revision)==initialState && frame->Coastal_Surf_Time(revision)==2.25);
- CHECK(field()==untouched);
- CHECK(read_float_targets(frame,&initialState,1,256,256)==initial);
-
- // An armed queued stale field must be overwritten by the real producer before
- // Advance samples it in the same command buffer; caller input upload comes first.
- uint32_t offset=0;float *poison=reinterpret_cast<float *>(frame->Upload_Space(MaxNodes*4*sizeof(float),offset));
- CHECK(poison);if(!poison)return;
- for(unsigned i=0;i<MaxNodes;++i){poison[i*4]=63;poison[i*4+1]=poison[i*4+2]=0;poison[i*4+3]=1;}
- frame->Queue_Texture_Upload(input.Colour,0,256,256,offset);
- CHECK(frame->Prepare_Ocean(float(2.35)*WaterFftSampling::TimeScale));
- const uint64_t correctFft=frame->Ocean_Updates();
- CHECK(frame->Prepare_Coastal_Surf_From_Ocean(revision,2.35));
- CHECK(frame->Ocean_Updates()==correctFft && frame->Coastal_Surf_Updates()==resetUpdates+1);
- SDL_GPUTexture *warmState=frame->Coastal_Surf_State(revision);CHECK(warmState);if(!warmState)return;
- const auto generated=field(),warm=read_float_targets(frame,&warmState,1,256,256);
- CHECK(generated.size()==MaxNodes*4 && warm.size()==MaxNodes*4);
- if(generated.size()!=MaxNodes*4 || warm.size()!=MaxNodes*4)return;
- bool finite=true,nonzero=false,tail=true;
- for(unsigned i=0;i<MaxNodes;++i)for(unsigned c=0;c<4;++c)finite &= std::isfinite(generated[i*4+c])&&std::isfinite(warm[i*4+c]);
- for(unsigned i=0;i<nodes.size();++i) {
- CHECK(generated[i*4]!=63 && warm[i*4+2]==generated[i*4]);
- CHECK(warm[i*4]==0 && warm[i*4+1]==0 && warm[i*4+3]==0);
- nonzero |= std::abs(generated[i*4])>.001f || std::abs(generated[i*4+1])>.001f;
- }
- for(unsigned i=unsigned(nodes.size());i<MaxNodes;++i) {
- tail &= generated[i*4]==0 && generated[i*4+1]==0 && generated[i*4+2]==0 && generated[i*4+3]==1;
- tail &= warm[i*4]==0 && warm[i*4+1]==0 && warm[i*4+2]==0 && warm[i*4+3]==-1;
- }
- CHECK(finite && nonzero && tail);
- CHECK(!frame->Coastal_Surf_Field_Due(revision,2.35));
- CHECK(frame->Prepare_Coastal_Surf_From_Ocean(revision,2.35));
- CHECK(frame->Coastal_Surf_Updates()==resetUpdates+1 && frame->Ocean_Updates()==correctFft);
- CHECK(frame->Coastal_Surf_State(revision)==warmState && field()==generated);
- CHECK(read_float_targets(frame,&warmState,1,256,256)==warm);
-
- // Failed due-time phase checks leave the clock uncommitted, so a corrected
- // existing FFT can retry that exact tick without losing or duplicating it.
- CHECK(!frame->Prepare_Coastal_Surf_From_Ocean(revision,2.45));
- CHECK(frame->Coastal_Surf_Time(revision)==2.35 && frame->Coastal_Surf_Updates()==resetUpdates+1);
- CHECK(field()==generated);
- CHECK(frame->Prepare_Ocean(float(2.45)*WaterFftSampling::TimeScale));
- const uint64_t nextFft=frame->Ocean_Updates();
- CHECK(frame->Prepare_Coastal_Surf_From_Ocean(revision,2.45));
- CHECK(frame->Ocean_Updates()==nextFft && frame->Coastal_Surf_Updates()==resetUpdates+2);
- SDL_GPUTexture *advancedState=frame->Coastal_Surf_State(revision);CHECK(advancedState);if(!advancedState)return;
- const auto advanced=read_float_targets(frame,&advancedState,1,256,256),changedField=field();
- CHECK(changedField!=generated);
- for(unsigned i=0;i<nodes.size();++i)CHECK(advanced[i*4+2]==changedField[i*4]);
- CHECK(!frame->Prepare_Coastal_Surf_From_Ocean(revision+1,2.55));
- CHECK(!frame->Prepare_Coastal_Surf_From_Ocean(revision,NAN));
- CHECK(frame->Coastal_Surf_Time(revision)==2.45 && frame->Coastal_Surf_Updates()==resetUpdates+2);
- CHECK(frame->Prepare_Coastal_Surf_From_Ocean(revision,2.25)); // rewind: clear, do not force FFT backwards
- CHECK(frame->Ocean_Updates()==nextFft);
- SDL_GPUTexture *rewound=frame->Coastal_Surf_State(revision);CHECK(rewound);
- if(rewound)CHECK(read_float_targets(frame,&rewound,1,256,256)==initial);
- printf("sdl_gpu_frame_selfcheck: coastal production wrapper: same-phase existing FFT required, wrong-phase retry atomic, queued stale input replaced, actual field consumed by history, all atlas channels/tail, pause/rewind and no extra FFT updates checked\n");
-}
-
-// Insert after read_float_targets and invoke after the coastal owner fixture.
-static void check_gpu_coastal_surf_view(SdlGpuFrame *frame)
-{
- using namespace WaterCoastalSurf;
- const uint64_t revision=0xc051e;
- const unsigned oldWidth=frame->Width(),oldHeight=frame->Height();
- struct Cleanup {SdlGpuFrame *f;unsigned w,h;~Cleanup(){CHECK(f->Clear_Coastal_Surf());CHECK(f->Resize(w,h));f->Set_Target(f->Back_Buffer_Target());}} cleanup{frame,oldWidth,oldHeight};
- CHECK(frame->Clear_Coastal_Surf());
- std::vector<Node> nodes(257);
- for(unsigned i=0;i<nodes.size();++i){nodes[i].world[0]=float(i*8);nodes[i].world[2]=7;nodes[i].context={4,32,1,0,1,1,.4f,.5f,1,1};}
- nodes[2].world[2]=11;
- const bool installed=frame->Install_Coastal_Surf(revision,nodes,8);CHECK(installed);if(!installed)return;
- WaterCoastalView::Mapping mapping={-16,24,48,32,3,2};
- std::vector<Lookup> lookups(6);
- lookups[1].node[0]=1;lookups[1].weight[0]=1;
- lookups[2].node[0]=2;lookups[2].weight[0]=1;
- lookups[3].node[0]=1;lookups[3].node[1]=2;lookups[3].node[2]=257;
- lookups[3].weight[0]=.25f;lookups[3].weight[1]=.5f;lookups[3].weight[2]=.125f;
- lookups[4].node[0]=257;lookups[4].weight[0]=.25f;
- lookups[5].node[0]=lookups[5].node[1]=1;lookups[5].weight[0]=lookups[5].weight[1]=.25f;
- const uint64_t sets=frame->Coastal_Surf_View_Sets(),updates=frame->Coastal_Surf_View_Updates();
- CHECK(frame->Set_Coastal_Surf_View(revision,mapping,7,lookups));
- CHECK(!frame->Prepare_Coastal_Surf_View(revision) && !frame->Coastal_Surf_View(revision,7)); // history not ready
- const SdlTarget input=frame->Coastal_Surf_Field_Target(revision);
- CHECK(frame->Prepare_Coastal_Surf(revision,0,input));
- SDL_GPUTexture *state=frame->Coastal_Surf_State(revision);CHECK(state);if(!state)return;
- // Seed exact finite moments through a test-only GPU upload. The composition
- // oracle is closed form and deliberately uses densities above coverage's range.
- uint32_t offset=0;float *seed=reinterpret_cast<float *>(frame->Upload_Space(MaxNodes*4*sizeof(float),offset));
- CHECK(seed);if(!seed)return;memset(seed,0,MaxNodes*4*sizeof(float));
- for(unsigned i=0;i<MaxNodes;++i)seed[i*4+3]=i<nodes.size()?0:-1;
- seed[0]=2;seed[1]=10;seed[4]=6;seed[5]=6;seed[8]=5;seed[9]=20;seed[256*4]=8;seed[256*4+1]=24;
- frame->Queue_Texture_Upload(state,0,256,256,offset);
- CHECK(frame->Prepare_Coastal_Surf_View(revision));
- SDL_GPUTexture *view=frame->Coastal_Surf_View(revision,7);CHECK(view);if(!view)return;
- CHECK(frame->Coastal_Surf_View_Sampler(revision,7));
- CHECK(!frame->Coastal_Surf_View(revision,11) && !frame->Coastal_Surf_View(revision+1,7));
- CHECK(frame->Coastal_Surf_View_Time(revision,7)==0);
- CHECK(frame->Coastal_Surf_View_Sets()==sets+1 && frame->Coastal_Surf_View_Updates()==updates+1);
- const double expected[6][2]={{0,0},{2,10},{6,6},{4.5,8.5},{2,6},{1,5}};
- auto verify=[&](const std::vector<float>&values,double elapsed){
- CHECK(values.size()==24);if(values.size()!=24)return;
- const double q=std::exp(-elapsed/Lifetime);
- for(unsigned i=0;i<6;++i){
- CHECK(std::abs(values[i*4]-expected[i][0]*q)<2e-5);
- CHECK(std::abs(values[i*4+1]-(expected[i][1]+elapsed*expected[i][0])*q)<2e-5);
- CHECK(values[i*4+2]==0 && values[i*4+3]==0);
- }
- };
- const auto first=read_float_targets(frame,&view,1,3,2);CHECK(first.size()==24);if(first.size()!=24)return;verify(first,0);
- CHECK(first[4]>1 && first[4*4]==2); // raw density, quarter weight remains quarter
- CHECK(frame->Set_Coastal_Surf_View(revision,mapping,7,lookups));CHECK(frame->Prepare_Coastal_Surf_View(revision));
- CHECK(frame->Coastal_Surf_View_Updates()==updates+1 && frame->Coastal_Surf_View_Sets()==sets+1);
- CHECK(read_float_targets(frame,&view,1,3,2)==first);
- auto invalid=lookups;invalid[1].node[0]=3; // valid atlas index, wrong exact level
- CHECK(!frame->Set_Coastal_Surf_View(revision,mapping,7,invalid));
- CHECK(!frame->Coastal_Surf_View(revision,7) && !frame->Coastal_Surf_View_Sampler(revision,7));
- invalid=lookups;invalid[1].weight[0]=NAN;CHECK(!frame->Set_Coastal_Surf_View(revision,mapping,7,invalid));
- invalid=lookups;invalid[1].node[1]=2;invalid[1].weight[1]=.25f;CHECK(!frame->Set_Coastal_Surf_View(revision,mapping,7,invalid));
- invalid=lookups;invalid[1].node[0]=258;CHECK(!frame->Set_Coastal_Surf_View(revision,mapping,7,invalid));
- auto badMapping=mapping;badMapping.widthPixels=513;CHECK(!frame->Set_Coastal_Surf_View(revision,badMapping,7,lookups));
- CHECK(!frame->Set_Coastal_Surf_View(revision,mapping,7.1,lookups));
- CHECK(!frame->Set_Coastal_Surf_View(revision+1,mapping,7,lookups));
- CHECK(frame->Set_Coastal_Surf_View(revision,mapping,7,lookups));CHECK(frame->Prepare_Coastal_Surf_View(revision));
- CHECK(frame->Coastal_Surf_View(revision,7)==view);
- CHECK(frame->Prepare_Coastal_Surf(revision,.1,input)); // pure decay; initial incident field is still zero
- CHECK(!frame->Coastal_Surf_View(revision,7)); // stale composed moments may not be exposed
- const uint64_t beforeCompose=frame->Coastal_Surf_View_Updates();
- CHECK(frame->Prepare_Coastal_Surf_View(revision));CHECK(frame->Coastal_Surf_View_Updates()==beforeCompose+1);
- CHECK(frame->Coastal_Surf_View(revision,7)==view && frame->Coastal_Surf_View_Time(revision,7)==.1);
- const auto decayed=read_float_targets(frame,&view,1,3,2);CHECK(decayed.size()==24);if(decayed.size()!=24)return;verify(decayed,.1);
- CHECK(frame->Resize(oldWidth+7,oldHeight+5));
- CHECK(frame->Coastal_Surf_View(revision,7)==view && frame->Coastal_Surf_State(revision));
- CHECK(frame->Prepare_Coastal_Surf_View(revision) && frame->Coastal_Surf_View_Updates()==beforeCompose+1);
- CHECK(read_float_targets(frame,&view,1,3,2)==decayed);
- mapping.originX+=8;CHECK(frame->Set_Coastal_Surf_View(revision,mapping,7,lookups));
- CHECK(!frame->Coastal_Surf_View(revision,7));CHECK(frame->Prepare_Coastal_Surf_View(revision));
- CHECK(frame->Coastal_Surf_View(revision,7)==view);verify(read_float_targets(frame,&view,1,3,2),.1);
-
- // A recorded ordinary draw must read the old composition before the same
- // output texture is reused, and before a different-sized view releases it.
- struct Reader {
- SdlGpuFrame *f;SDL_GPUShader *vs=NULL,*ps=NULL;SDL_GPUGraphicsPipeline *pipeline=NULL;SDL_GPUTexture *target=NULL;
- ~Reader(){CHECK(f->Flush());f->Set_Target(f->Back_Buffer_Target());if(target)SDL_ReleaseGPUTexture(f->Device(),target);
- if(pipeline)SDL_ReleaseGPUGraphicsPipeline(f->Device(),pipeline);if(vs)SDL_ReleaseGPUShader(f->Device(),vs);if(ps)SDL_ReleaseGPUShader(f->Device(),ps);}
- } reader{frame};
- std::string error;std::vector<unsigned char> spirv;
- bool ok=SDL3_Compile_HLSL_To_SPIRV(WaterFftSpectrum::VertexHlsl(),true,spirv,error);CHECK(ok);
- if(ok)reader.vs=SDL3_Create_Shader(frame->Device(),spirv,true,error);
- const char *ps="Texture2D<float4> View:register(t0,space2);float4 main(float4 p:SV_Position):SV_Target0{return View.Load(int3((int2)p.xy,0));}";
- ok=SDL3_Compile_HLSL_To_SPIRV(ps,false,spirv,error);CHECK(ok);
- if(ok){unsigned samplers=0,uniforms=0;SDL3_Shader_Slots(spirv,false,samplers,uniforms);CHECK(samplers==1&&uniforms==0);
- if(samplers==1&&uniforms==0)reader.ps=SDL3_Create_Shader(frame->Device(),spirv,false,error);}
- CHECK(reader.vs&&reader.ps);if(!reader.vs||!reader.ps)return;
- SDL_GPUColorTargetDescription colour={};colour.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
- SDL_GPUGraphicsPipelineCreateInfo pi={};pi.vertex_shader=reader.vs;pi.fragment_shader=reader.ps;pi.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;
- pi.target_info.color_target_descriptions=&colour;pi.target_info.num_color_targets=1;pi.target_info.has_depth_stencil_target=true;
- pi.target_info.depth_stencil_format=(SDL_GPUTextureFormat)frame->Depth_Format();reader.pipeline=SDL_CreateGPUGraphicsPipeline(frame->Device(),&pi);
- SDL_GPUTextureCreateInfo ti={};ti.type=SDL_GPU_TEXTURETYPE_2D;ti.format=colour.format;ti.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;
- ti.width=3;ti.height=2;ti.layer_count_or_depth=ti.num_levels=1;reader.target=SDL_CreateGPUTexture(frame->Device(),&ti);
- CHECK(reader.pipeline&&reader.target);if(!reader.pipeline||!reader.target)return;
- auto record=[&]()->bool{frame->Set_Target({reader.target,frame->Depth_For(3,2),3,2});SdlRecordedDraw draw={};
- draw.Pipeline=reader.pipeline;draw.Count=3;draw.SamplerCount=1;
- void *staged=frame->Stage(16,draw.VertexOffset);CHECK(staged);if(!staged)return false;memset(staged,0,16);
- draw.Textures[0]=frame->Coastal_Surf_View(revision,7);draw.Samplers[0]=frame->Coastal_Surf_View_Sampler(revision,7);
- CHECK(draw.Textures[0]&&draw.Samplers[0]);if(!draw.Textures[0]||!draw.Samplers[0])return false;
- draw.Viewport[2]=3;draw.Viewport[3]=2;draw.Viewport[5]=1;draw.Scissor[2]=3;draw.Scissor[3]=2;frame->Record_Draw(draw);return true;};
- if(!record())return;const uint64_t batch=frame->Batch();
- auto changed=lookups;changed[1].weight[0]=.25f;changed[2].node[0]=1;
- CHECK(frame->Set_Coastal_Surf_View(revision,mapping,7,changed));CHECK(frame->Prepare_Coastal_Surf_View(revision));
- CHECK(frame->Batch()>batch && frame->Coastal_Surf_View(revision,7)==view);
- CHECK(read_float_targets(frame,&reader.target,1,3,2)==decayed);
- const auto changedValues=read_float_targets(frame,&view,1,3,2);CHECK(changedValues.size()==24);if(changedValues.size()!=24)return;
- CHECK(std::abs(changedValues[4]-.25f*decayed[4])<1e-6 && changedValues[8]==decayed[4]);
- if(!record())return;WaterCoastalView::Mapping narrow=mapping;narrow.widthPixels=4;narrow.heightPixels=1;
- std::vector<Lookup> single(4);for(auto &l:single){l.node[0]=1;l.weight[0]=1;}
- CHECK(frame->Set_Coastal_Surf_View(revision,narrow,7,single));CHECK(!frame->Coastal_Surf_View(revision,7));
- CHECK(frame->Prepare_Coastal_Surf_View(revision));SDL_GPUTexture *newView=frame->Coastal_Surf_View(revision,7);
- CHECK(newView&&newView!=view);if(!newView)return;
- CHECK(read_float_targets(frame,&reader.target,1,3,2)==changedValues);
- for(auto &l:single)l.node[0]=3;
- CHECK(frame->Set_Coastal_Surf_View(revision,narrow,11,single));CHECK(frame->Prepare_Coastal_Surf_View(revision));
- CHECK(!frame->Coastal_Surf_View(revision,7) && frame->Coastal_Surf_View(revision,11)==newView);
- const auto level=read_float_targets(frame,&newView,1,4,1);CHECK(level.size()==16);if(level.size()!=16)return;const double q=std::exp(-.1/Lifetime);
- for(unsigned i=0;i<4;++i){CHECK(std::abs(level[i*4]-5*q)<2e-5);CHECK(std::abs(level[i*4+1]-20.5*q)<2e-5);}
- frame->Set_Target({newView,NULL,4,1});CHECK(frame->Clear_Coastal_Surf_View());
- CHECK(!frame->Coastal_Surf_View(revision,11) && frame->Coastal_Surf_State(revision));
- frame->Clear_Back_Buffer(true,false,false,0xFF102030,1,0);CHECK(frame->Flush()); // released current target invalidated
- CHECK(frame->Set_Coastal_Surf_View(revision,mapping,7,lookups));CHECK(frame->Prepare_Coastal_Surf_View(revision));
- CHECK(frame->Install_Coastal_Surf(revision+1,nodes,8));CHECK(!frame->Coastal_Surf_View(revision,7));
- CHECK(!frame->Prepare_Coastal_Surf_View(revision+1));
- printf("sdl_gpu_frame_selfcheck: coastal view: raw density/age, quarter/missing weights without renormalization, row-crossing IDs, exact levels, invalid input, cache/state refresh, resize/remap, queued reuse/release and independent history lifetime checked\n");
-}
-
-static void check_gpu_coastal_surf_owner(SdlGpuFrame *frame)
-{
- using namespace WaterCoastalSurf;
- const unsigned oldWidth=frame->Width(),oldHeight=frame->Height();
- CHECK(frame->Clear_Coastal_Surf());
- CHECK(!frame->Coastal_Surf_State(71) && !frame->Coastal_Surf_Field_Target(71).Colour);
- CHECK(!frame->Coastal_Surf_Field_Due(71,0));
- const SDL_GPUTextureUsageFlags usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET|SDL_GPU_TEXTUREUSAGE_SAMPLER;
- if(!SDL_GPUTextureSupportsFormat(frame->Device(),SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT,
- SDL_GPU_TEXTURETYPE_2D,usage)) {
- std::vector<Node> probe(1);probe[0].context={1,8,1,0,1,1,0,0,1,1};
- CHECK(!frame->Install_Coastal_Surf(71,probe,8));
- CHECK(!frame->Coastal_Surf_State(71));
- printf("sdl_gpu_frame_selfcheck: coastal owner RGBA32F unsupported: safe fallback checked\n");return;
- }
- // Only nodes 0 and 256 exchange. Their IDs cross an atlas row. Isolated node 1
- // occupies the same XY as node 0 at a distinct exact level and must stay empty.
- std::vector<Node> nodes(257);
- for(unsigned i=0;i<nodes.size();++i) {
- nodes[i].world[0]=float(100+i*8);nodes[i].world[1]=16;nodes[i].world[2]=7;
- nodes[i].context={1,200,1,0,1,1,0,0,1,1}; // valid wet no-birth spread support
- }
- nodes[0].world[0]=nodes[0].world[1]=0;nodes[0].context.distance=8;
- nodes[1].world[0]=nodes[1].world[1]=0;nodes[1].world[2]=11;
- nodes[256].world[0]=8;nodes[256].world[1]=0;nodes[256].context.distance=8;
- nodes[0].neighbour[1]=257;nodes[256].neighbour[0]=1;
- CHECK(ValidGraph(nodes,8));
- const uint64_t installs=frame->Coastal_Surf_Installs(),updates=frame->Coastal_Surf_Updates();
- CHECK(frame->Install_Coastal_Surf(71,nodes,8));
- SdlTarget input=frame->Coastal_Surf_Field_Target(71);
- CHECK(input.Colour && !input.Depth && input.Width==256 && input.Height==256);
- if(!input.Colour) return;
- CHECK(frame->Coastal_Surf_Installs()==installs+1 && frame->Coastal_Surf_Nodes(71)==257);
- CHECK(!frame->Coastal_Surf_State(71) && !frame->Coastal_Surf_State(72));
- CHECK(frame->Coastal_Surf_Sampler(71) && !frame->Coastal_Surf_Sampler(72));
- for(unsigned i=0;i<5;++i)CHECK(frame->Coastal_Surf_Domain(i,71));
- CHECK(!frame->Coastal_Surf_Domain(5,71) && !frame->Coastal_Surf_Domain(0,72));
- CHECK(!frame->Coastal_Surf_Field_Due(71,0));
- CHECK(frame->Prepare_Coastal_Surf(71,0,input));
- CHECK(frame->Coastal_Surf_Updates()==updates+1 && frame->Coastal_Surf_Time(71)==0);
- auto state=[&]() {
- SDL_GPUTexture *texture=frame->Coastal_Surf_State(71);CHECK(texture);
- return texture?read_float_targets(frame,&texture,1,256,256)
- :std::vector<float>(MaxNodes*4,std::numeric_limits<float>::quiet_NaN());
- };
- auto sentinel=[&](const std::vector<float>&v,unsigned start) {
- bool ok=v.size()==MaxNodes*4;
- if(ok)for(unsigned i=start;i<MaxNodes;++i) {
- ok &= v[i*4]==0 && v[i*4+1]==0 && v[i*4+2]==0 && v[i*4+3]==-1;
- }
- CHECK(ok);
- };
- const auto reset=state();sentinel(reset,0);
- auto field=[&](float height) {
- uint32_t offset=0;float *p=reinterpret_cast<float *>(frame->Upload_Space(MaxNodes*4*sizeof(float),offset));
- CHECK(p);if(!p)return;
- for(unsigned i=0;i<MaxNodes;++i) {
- p[i*4]=height;p[i*4+1]=i==256?-.4f:.4f;p[i*4+2]=0;p[i*4+3]=.5f;
- }
- frame->Queue_Texture_Upload(input.Colour,0,256,256,offset);
- };
- CHECK(frame->Coastal_Surf_Field_Due(71,.1));
- field(.5f); // Deliberately no Flush: Prepare must submit this upload first.
- CHECK(frame->Prepare_Coastal_Surf(71,.1,input));
- const auto warm=state();sentinel(warm,257);
- CHECK(warm[0]==0 && warm[2]==.5f && warm[3]==0);
- CHECK(warm[256*4]==0 && warm[256*4+2]==.5f && warm[256*4+3]==0);
- field(1.5f);CHECK(frame->Prepare_Coastal_Surf(71,.2,input));
- const auto born=state();sentinel(born,257);
- CHECK(born[3]>.99f*MaximumRate && born[256*4+3]==0);
- // Independent Simpson integration of a linear 0 -> 1.2 source, with age
- // measured from the source time. It does not call Integrate/Advance/Diffuse.
- double mass=0,moment=0;const unsigned steps=1000;const double dt=.1;
- for(unsigned i=0;i<=steps;++i) {
- const double u=dt*i/steps,weight=i==0||i==steps?1:i%2?4:2;
- const double value=MaximumRate*(u/dt)*std::exp(-(dt-u)/Lifetime);
- mass+=weight*value;moment+=weight*value*(dt-u);
- }
- mass*=dt/(3*steps);moment*=dt/(3*steps);
- const double alpha=Diffusivity*dt/64;
- CHECK(std::abs(born[0]-mass*(1-alpha))<2e-6 && std::abs(born[1]-moment*(1-alpha))<2e-6);
- CHECK(std::abs(born[256*4]-mass*alpha)<2e-6 && std::abs(born[256*4+1]-moment*alpha)<2e-6);
- CHECK(born[4]==0 && born[5]==0); // exact-level isolation
- CHECK(born[0]>.05f && born[256*4]>0.0001f); // armed, non-vacuous source and diffusion
-
- const uint64_t pausedUpdates=frame->Coastal_Surf_Updates();
- SDL_GPUTexture *paused=frame->Coastal_Surf_State(71);
- CHECK(!frame->Coastal_Surf_Field_Due(71,.2));
- CHECK(frame->Prepare_Coastal_Surf(71,.2,input));
- CHECK(frame->Coastal_Surf_Updates()==pausedUpdates && frame->Coastal_Surf_State(71)==paused);
- CHECK(state()==born);
- CHECK(frame->Install_Coastal_Surf(71,nodes,8));
- CHECK(frame->Coastal_Surf_Installs()==installs+1 && frame->Coastal_Surf_State(71)==paused);
- auto badNodes=nodes;badNodes[0].context.depth=2;
- CHECK(!frame->Install_Coastal_Surf(71,badNodes,8)); // same revision, changed payload
- badNodes=nodes;badNodes[256].context.wet=0;
- CHECK(!frame->Install_Coastal_Surf(72,badNodes,8)); // dry graph endpoint
- badNodes=nodes;badNodes[0].neighbour[1]=MaxNodes+1;
- CHECK(!frame->Install_Coastal_Surf(72,badNodes,8));
- CHECK(!frame->Install_Coastal_Surf(0,nodes,8));
- SdlTarget wrong=input;wrong.Width=255;CHECK(!frame->Prepare_Coastal_Surf(71,.3,wrong));
- wrong=input;wrong.Depth=frame->Back_Buffer_Target().Depth;CHECK(!frame->Prepare_Coastal_Surf(71,.3,wrong));
- wrong=input;wrong.Colour=frame->Coastal_Surf_State(71);CHECK(!frame->Prepare_Coastal_Surf(71,.3,wrong));
- wrong=input;wrong.Colour=frame->Coastal_Surf_Domain(0,71);CHECK(!frame->Prepare_Coastal_Surf(71,.3,wrong));
- CHECK(!frame->Prepare_Coastal_Surf(72,.3,input) && !frame->Prepare_Coastal_Surf(71,NAN,input));
- CHECK(frame->Coastal_Surf_State(71)==paused && frame->Coastal_Surf_Updates()==pausedUpdates && state()==born);
- CHECK(frame->Resize(oldWidth+5,oldHeight+3));
- CHECK(frame->Coastal_Surf_Field_Target(71).Colour==input.Colour && frame->Coastal_Surf_State(71)==paused);
- CHECK(state()==born && !frame->Coastal_Surf_Field_Due(71,.2));
-
- // Queue an ordinary draw reading the old state, then advance far enough to
- // recycle that exact physical state texture. The unsubmitted reader must
- // retain the old values instead of observing the overwritten ping-pong slot.
- struct Reader {
- SDL_GPUDevice *device;SDL_GPUShader *vs=NULL,*ps=NULL;SDL_GPUGraphicsPipeline *pipeline=NULL;
- SDL_GPUTexture *target=NULL;
- ~Reader(){if(target)SDL_ReleaseGPUTexture(device,target);if(pipeline)SDL_ReleaseGPUGraphicsPipeline(device,pipeline);
- if(vs)SDL_ReleaseGPUShader(device,vs);if(ps)SDL_ReleaseGPUShader(device,ps);}
- } reader;reader.device=frame->Device();
- std::vector<unsigned char> spirv;std::string error;
- const char *vs="float4 main(uint id:SV_VertexID):SV_Position{return float4(id==1?3.0:-1.0,id==2?3.0:-1.0,0,1);}";
- const char *ps="Texture2D<float4> State:register(t0,space2);float4 main(float4 p:SV_Position):SV_Target0{return State.Load(int3(0,(uint)p.x==0?0:1,0));}";
- bool ok=SDL3_Compile_HLSL_To_SPIRV(vs,true,spirv,error);CHECK(ok);
- if(ok)reader.vs=SDL3_Create_Shader(reader.device,spirv,true,error);
- ok=SDL3_Compile_HLSL_To_SPIRV(ps,false,spirv,error);CHECK(ok);
- if(ok) {
- unsigned samplers=0,uniforms=0;SDL3_Shader_Slots(spirv,false,samplers,uniforms);
- CHECK(samplers==1 && uniforms==0);
- if(samplers==1 && uniforms==0)reader.ps=SDL3_Create_Shader(reader.device,spirv,false,error);
- }
- CHECK(reader.vs && reader.ps);
- if(reader.vs && reader.ps) {
- SDL_GPUColorTargetDescription colour={};colour.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
- SDL_GPUGraphicsPipelineCreateInfo pi={};pi.vertex_shader=reader.vs;pi.fragment_shader=reader.ps;
- pi.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;pi.target_info.color_target_descriptions=&colour;pi.target_info.num_color_targets=1;
- pi.target_info.has_depth_stencil_target=true;pi.target_info.depth_stencil_format=(SDL_GPUTextureFormat)frame->Depth_Format();
- reader.pipeline=SDL_CreateGPUGraphicsPipeline(reader.device,&pi);
- SDL_GPUTextureCreateInfo ti={};ti.type=SDL_GPU_TEXTURETYPE_2D;ti.format=colour.format;ti.usage=usage;
- ti.width=2;ti.height=1;ti.layer_count_or_depth=ti.num_levels=1;
- reader.target=SDL_CreateGPUTexture(reader.device,&ti);CHECK(reader.pipeline && reader.target);
- if(reader.pipeline && reader.target) {
- frame->Set_Target({reader.target,frame->Depth_For(2,1),2,1});
- SdlRecordedDraw draw={};draw.Pipeline=reader.pipeline;draw.Count=3;draw.SamplerCount=1;
- memset(frame->Stage(16,draw.VertexOffset),0,16);draw.Textures[0]=paused;draw.Samplers[0]=frame->Coastal_Surf_Sampler(71);
- draw.Viewport[2]=2;draw.Viewport[3]=1;draw.Viewport[5]=1;draw.Scissor[2]=2;draw.Scissor[3]=1;
- frame->Record_Draw(draw);const uint64_t batch=frame->Batch();
- field(2.5f);CHECK(frame->Prepare_Coastal_Surf(71,.3,input));CHECK(frame->Batch()>batch);
- field(3.5f);CHECK(frame->Prepare_Coastal_Surf(71,.4,input));
- const auto saved=read_float_targets(frame,&reader.target,1,2,1);
- for(unsigned c=0;c<4;++c) {
- CHECK(std::abs(saved[c]-born[c])<1e-6);
- CHECK(std::abs(saved[4+c]-born[256*4+c])<1e-6);
- }
- const auto current=state();CHECK(current[0]>born[0]+.1f);
- }
- }
- CHECK(frame->Flush());frame->Set_Target(frame->Back_Buffer_Target());
- const auto beforeGap=state();const double beforeGapTime=frame->Coastal_Surf_Time(71);field(4.5f);
- CHECK(frame->Coastal_Surf_Field_Due(71,1.4));CHECK(frame->Prepare_Coastal_Surf(71,1.4,input));
- const auto gap=state();const double elapsed=1.4-beforeGapTime;
- // Gap performs pure decay, no diffusion/birth, and commits the fresh height.
- CHECK(elapsed>MaximumSourceInterval);
- CHECK(std::abs(gap[0]-beforeGap[0]*std::exp(-elapsed/Lifetime))<2e-6);
- CHECK(gap[2]==4.5f && gap[3]==0);
- CHECK(frame->Prepare_Coastal_Surf(71,1.3,input));sentinel(state(),0); // rewind reset
- CHECK(!frame->Coastal_Surf_Field_Due(71,1.3));
- CHECK(frame->Install_Coastal_Surf(72,nodes,8));
- CHECK(!frame->Coastal_Surf_State(71) && !frame->Coastal_Surf_State(72));
- CHECK(!frame->Prepare_Coastal_Surf(72,0,input)); // stale pointer rejected
- input=frame->Coastal_Surf_Field_Target(72);CHECK(input.Colour);
- CHECK(frame->Prepare_Coastal_Surf(72,0,input) && frame->Coastal_Surf_State(72));
- frame->Set_Target(input);CHECK(frame->Clear_Coastal_Surf());
- CHECK(!frame->Coastal_Surf_State(72) && !frame->Coastal_Surf_Field_Target(72).Colour);
- // Release invalidates an owned CurrentTarget. A subsequent ordinary clear is safe.
- frame->Clear_Back_Buffer(true,false,false,0xFF102030,1,0);CHECK(frame->Flush());
- CHECK(frame->Resize(oldWidth,oldHeight));frame->Set_Target(frame->Back_Buffer_Target());
- printf("sdl_gpu_frame_selfcheck: coastal owner: source ordering, independent linear-source integral, reciprocal row-crossing diffusion, level isolation, inactive tail, pause, queued old reader, gap/rewind, immutable revision, input/alias guards, resize and clear checked\n");
-}
-
static void check_gpu_foam_history_upload(SdlGpuFrame *frame)
{
// Exercise the same versioned CPU texture mirror as the runtime atlas. Reading via slot14
@@ -4790,28 +4369,11 @@ static void check_gpu_coastal_material(SdlGpuFrame *frame)
}
#endif // __linux__
-// Independent scalar pressure reference: intentionally does not call the production parameter
-// builder, constants, dual arithmetic, or derivative expressions. GPU slopes use differences
-// of this double-precision height, so a shared CPU/HLSL derivative mistake cannot self-confirm.
-static void vessel_test_pressure_parameters(double beam,double speed,double result[3])
-{
- result[0]=result[1]=result[2]=0;
- if(!std::isfinite(beam)||!std::isfinite(speed)||beam<0||speed<0)return;
- const double u=(std::max)(0.0,(std::min)(speed,250.0)-.3);
- result[0]=(std::max)(9.0,(std::min)(32.0,6+1.2*beam));
- result[1]=(std::max)(4.0,(std::min)(60.0,1.5+.95*beam));
- result[2]=(std::max)(3.0,(std::min)(8.0,1.8*std::sqrt(beam)))*u*u/(u*u+26*26);
-}
-static double vessel_test_pressure(double along,double across,double beam,double speed)
-{
- double p[3];vessel_test_pressure_parameters(beam,speed,p);if(p[2]<=0)return 0;
- const double q=across/p[1],s=along/p[0]+.6*(std::sqrt(1+q*q)-1);
- return p[2]*std::exp(-s*s-q*q);
-}
+// Independent scalar stern reference. The contour bow has its own closed-form oracle.
static double vessel_test_packet(const WaterHullModel::Hull &h,double x,double y,double level,double time,
- double *sternOut=NULL,double *bowOut=NULL)
+ double *sternOut=NULL)
{
- if(sternOut)*sternOut=0;if(bowOut)*bowOut=0;
+ if(sternOut)*sternOut=0;
const double speed=std::hypot(h.data[2][0],h.data[2][1]);
if(h.data[0][3]<3||std::abs(level-h.data[0][2])>.1||speed<=double(.3f))return 0;
auto smooth=[](double a,double b,double v){const double t=(std::max)(0.0,(std::min)(1.0,(v-a)/(b-a)));return t*t*(3-2*t);};
@@ -4819,7 +4381,6 @@ static double vessel_test_packet(const WaterHullModel::Hull &h,double x,double y
const double fx=h.data[2][0]/speed,fy=h.data[2][1]/speed,ax=h.data[1][0],ay=h.data[1][1],beam=h.data[1][3];
const double blend=smooth(-.25,.25,fx*ax+fy*ay);
const double sx=h.data[3][2]+(h.data[3][0]-h.data[3][2])*blend,sy=h.data[3][3]+(h.data[3][1]-h.data[3][3])*blend;
- const double bx=h.data[3][0]+(h.data[3][2]-h.data[3][0])*blend,by=h.data[3][1]+(h.data[3][3]-h.data[3][1])*blend;
const double dx=x-h.data[0][0]-(ax*sx-ay*sy),dy=y-h.data[0][1]-(ay*sx+ax*sy);
const double along=-dx*fx-dy*fy,across=-dx*fy+dy*fx;
const double length=(std::max)(30.0,(std::min)(110.0,speed*3.2+beam*2));
@@ -4829,334 +4390,7 @@ static double vessel_test_packet(const WaterHullModel::Hull &h,double x,double y
const double radial=std::hypot(x-h.data[0][0],y-h.data[0][1]);
const double support=1-smooth(h.data[2][3]+80,h.data[2][3]+110,radial);
const double stern=(arms*1.35+churn)*smooth(0,10,along)*(1-smooth(length*.5,length,along))*smooth(.3,14,speed)*support;
- const double dbx=x-h.data[0][0]-(ax*bx-ay*by),dby=y-h.data[0][1]-(ay*bx+ax*by);
- const double bow=vessel_test_pressure(dbx*fx+dby*fy,-dbx*fy+dby*fx,beam,speed)*support;
- if(sternOut)*sternOut=stern;if(bowOut)*bowOut=bow;return stern+bow;
-}
-
-static void check_gpu_vessel_wave_model(SdlGpuFrame *frame)
-{
- using WaterHullModel::Hull;
- Hull hulls[8];
- auto rectangle=[](Hull &h,float velocity) {
- h.data[0][2]=7;h.data[0][3]=4;h.data[1][0]=1;h.data[1][2]=20;h.data[1][3]=6;
- h.data[2][0]=velocity;h.data[2][2]=.23f;h.data[2][3]=sqrtf(436.0f);
- h.data[3][0]=-20;h.data[3][2]=20;
- const float points[8]={-20,-6,20,-6,20,6,-20,6};memcpy(h.data[4],points,sizeof(points));
- };
- rectangle(hulls[0],0);rectangle(hulls[1],12);rectangle(hulls[2],-12);rectangle(hulls[4],.3f);
- hulls[3]=hulls[1];const float cosine=cosf(.63f),sine=sinf(.63f);
- hulls[3].data[0][0]=137;hulls[3].data[0][1]=-83;hulls[3].data[1][0]=cosine;hulls[3].data[1][1]=sine;
- hulls[3].data[2][0]=12*cosine;hulls[3].data[2][1]=12*sine;
- hulls[5]=hulls[1];hulls[5].data[0][3]=2;hulls[7]=hulls[1];
- rectangle(hulls[6],.00001f);hulls[6].data[2][1]=12;
- struct Fixture { float point[4],other[4]; };
- std::vector<Fixture> fixtures;
- auto add=[&](float x,float y,unsigned h,float time=4,float level=7) {
- Fixture f={{x,y,level,time},{float(h),0,0,0}};fixtures.push_back(f);return unsigned(fixtures.size()-1);
- };
- const unsigned edge=add(0,8,0),corner=add(23,10,0),inside=add(0,0,0),far=add(90,70,0);
- const unsigned wrong=add(0,8,0,4,8),fade=add(0,34,0),leftCorner=add(19.999f,10,0),rightCorner=add(20.001f,10,0);
- const unsigned wake=add(-40,9,1),bow=add(28,0,1),stationary=add(-40,9,0),reverse=add(40,-9,2);
- const unsigned rotated=add(137-40*cosine-9*sine,-83-40*sine+9*cosine,3);
- const unsigned slow=add(-40,9,4),bad=add(-40,9,5),last=add(-40,9,7);
- const unsigned repeat=add(-40,9,1),churn=add(-40,0,1),later=add(-40,0,1,5),wakeEnd=add(-140,0,1),bowFar=add(100,0,1);
- // Keep the broadside endpoint control inside the corner region: x==20 is
- // an edge/corner derivative crease, so a central difference is not valid there.
- const unsigned sideBow=add(0,8,6),sideSwitch=add(20.1f,8,6),sideStern=add(0,-20,6),sideWing=add(9,-20,6);
- add(-24,-10,0);add(-15,-7,0);add(8,19,0);add(137+23*cosine-10*sine,-83+23*sine+10*cosine,3);
- const double horizontalBound=8/std::sqrt(2.0);
- const unsigned translatedPeak=add(float(20-.5*horizontalBound*std::tanh(4/horizontalBound)),
- float(.5*horizontalBound*std::tanh(3/horizontalBound)),1);
- const unsigned packetCount=unsigned(fixtures.size());
- const float beams[4]={6,9,30,80},speeds[7]={0,5,14,25,40,60,250};
- unsigned pressureRows[4][7];
- for(unsigned b=0;b<4;++b)for(unsigned v=0;v<7;++v) {
- double p[3];vessel_test_pressure_parameters(beams[b],speeds[v],p);
- Fixture f={{float(p[0]*.45),float(p[1]*.65),0,0},{0,beams[b],speeds[v],1}};
- pressureRows[b][v]=unsigned(fixtures.size());fixtures.push_back(f);
- }
- const float invalidInputs[][2]={{-1,40},{9,-1},{NAN,40},{9,INFINITY}};
- for(const auto &invalid:invalidInputs) {
- Fixture f={{2,3,0,0},{0,invalid[0],invalid[1],1}};fixtures.push_back(f);
- }
- const unsigned columns=24,count=unsigned(fixtures.size());
- std::string ps="cbuffer FixturesBlock : register(b0,space3) { float4 HullData[80]; float4 Fixtures[";
- ps+=std::to_string(count*2)+"]; };\nstatic const float4 HullParameters=float4(0,0,0,0);\n";
- ps+=WaterFftSampling::CommonSource()+WaterVesselWaves::Source(false,false); // Independent Gaussian fallback oracle below.
- ps+=R"HLSL(
-float3 incident(float2 p) {return float3(2.0*sin(.07*p.x+.025*p.y),1.5*cos(.035*p.x-.045*p.y),3.0*sin(.055*p.x-.08*p.y));}
-float3 incidentX(float2 p) {return float3(.14*cos(.07*p.x+.025*p.y),-.0525*sin(.035*p.x-.045*p.y),.165*cos(.055*p.x-.08*p.y));}
-float3 incidentY(float2 p) {return float3(.05*cos(.07*p.x+.025*p.y),.0675*sin(.035*p.x-.045*p.y),-.24*cos(.055*p.x-.08*p.y));}
-float4 main(float4 pixel:SV_Position):SV_Target0 {
- uint row=(uint)pixel.y,col=(uint)pixel.x;float4 f=Fixtures[row*2];int h=(int)Fixtures[row*2+1].x;
- float4 mode=Fixtures[row*2+1];
- if(mode.w>0.5) {
- float3 parameters=vesselBowPressure(mode.y,mode.z);
- if(col==0) return float4(parameters,0);
- float2 queryPoint=f.xy;
- if(col>=2 && col<=5) queryPoint+=col==2?float2(.03125,0):col==3?float2(-.03125,0):col==4?float2(0,.03125):float2(0,-.03125);
- if(col==6) queryPoint=0;
- float halfCoordinate=sqrt(log(2.0));
- if(col==7) queryPoint=float2(parameters.x*halfCoordinate,0);
- if(col==8) queryPoint=float2(-.6*parameters.x*(sqrt(1.0+halfCoordinate*halfCoordinate)-1.0),parameters.y*halfCoordinate);
- return float4(vesselBowPressureField(float3(queryPoint.x,1,0),float3(queryPoint.y,0,1),parameters),0);
- }
- if(col>=20) {
- // All four asymptotic component-limit corners. This fails if the emitter
- // accidentally uses radial8 as each component's bound instead of 8/sqrt(2).
- float2 sign=float2((col&1)!=0?1.0:-1.0,(col&2)!=0?1.0:-1.0);
- float2 shifted=fftHorizontalPosition(float2(0,0),float3(sign*1000.0,0),1.0);
- return float4(shifted,length(shifted),0);
- }
- if(col>=10) {
- float2 p=f.xy;
- if(col>=11 && col<=14) p+=col==11?float2(.03125,0):col==12?float2(-.03125,0):col==13?float2(0,.03125):float2(0,-.03125);
- float3 oldBow;
- float3 oldGenerated=vesselGeneratedWave(p,f.z,f.w,h,oldBow);
- float3 raw=incident(p),rawX=incidentX(p),rawY=incidentY(p);
- float phase=.013*p.x-.017*p.y;
- float3 scale=float3(.5+.1*sin(phase),.0013*cos(phase),-.0017*cos(phase));
- if(col==15) {raw=0;rawX=0;rawY=0;scale=float3(.5,0,0);}
- if(col==18) {raw=float3(4,-3,0);rawX=0;rawY=0;scale=float3(.5,0,0);}
- FftHorizontalRegistration map=fftHorizontalRegistration(p,raw,rawX,rawY,scale);
- float3 correction=vesselRegisteredBowDifference(map.position,map.derivativeX,map.derivativeY,f.z,h,oldBow);
- float3 registered=oldGenerated+correction;
- if(col==15) return float4(registered-oldGenerated,0);
- if(col==16) return float4(map.position,scale.x,0);
- if(col==17) {
- float3 mapped=vesselGeneratedBow(map.position,f.z,h);
- mapped.yz=float2(dot(mapped.yz,map.derivativeX),dot(mapped.yz,map.derivativeY));
- return float4((registered-mapped)-(oldGenerated-oldBow),0);
- }
- if(col==19) return float4(oldGenerated,0);
- return float4(registered,0);
- }
- float2 p=f.xy;
- if(col>=6) p+=col==6?float2(.03125,0):col==7?float2(-.03125,0):col==8?float2(0,.03125):float2(0,-.03125);
- VesselReflection v=vesselReflection(p,f.z,h);float3 d=incident(v.samplePosition);
- float3 value=vesselReflectedValue(d,v),generated=vesselGeneratedWave(p,f.z,f.w,h);
- if(col==0 || col>=6) return float4(value,generated.x);
- if(col==1) return float4(vesselReflectedDerivative(d,incidentX(v.samplePosition),incidentY(v.samplePosition),float2(1,0),v),0);
- if(col==2) return float4(vesselReflectedDerivative(d,incidentX(v.samplePosition),incidentY(v.samplePosition),float2(0,1),v),0);
- if(col==3) return float4(v.samplePosition,v.weight,v.corner);
- if(col==4) return float4(v.weightGradient,v.normal);
- return float4(generated,0);
-}
-
-)HLSL";
- const char *vs="float4 main(uint id:SV_VertexID):SV_Position {return float4(id==1?3.0:-1.0,id==2?3.0:-1.0,0,1);}";
- std::vector<unsigned char> spirv;std::string error;
- bool compiled=SDL3_Compile_HLSL_To_SPIRV(vs,true,spirv,error);CHECK(compiled);if(!compiled) return;
- SDL_GPUShader *vertex=SDL3_Create_Shader(frame->Device(),spirv,true,error);CHECK(vertex);
- compiled=SDL3_Compile_HLSL_To_SPIRV(ps,false,spirv,error);CHECK(compiled);
- if(!compiled) {printf("vessel wave model: %s\n",error.c_str());if(vertex) SDL_ReleaseGPUShader(frame->Device(),vertex);return;}
- SDL_GPUShader *pixel=SDL3_Create_Shader(frame->Device(),spirv,false,error);CHECK(pixel);
- SDL_GPUColorTargetDescription colour={};colour.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
- SDL_GPUGraphicsPipelineCreateInfo info={};info.vertex_shader=vertex;info.fragment_shader=pixel;
- info.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;info.target_info.color_target_descriptions=&colour;info.target_info.num_color_targets=1;
- SDL_GPUGraphicsPipeline *pipeline=vertex&&pixel?SDL_CreateGPUGraphicsPipeline(frame->Device(),&info):NULL;CHECK(pipeline);
- SDL_GPUTextureCreateInfo texture={};texture.type=SDL_GPU_TEXTURETYPE_2D;texture.format=colour.format;
- texture.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;texture.width=columns;texture.height=count;texture.layer_count_or_depth=texture.num_levels=1;
- SDL_GPUTexture *target=SDL_CreateGPUTexture(frame->Device(),&texture);CHECK(target);
- if(pipeline && target) {
- std::vector<float> uniforms(80*4+count*8);memcpy(uniforms.data(),hulls,sizeof(hulls));
- CHECK(uniforms.size()*sizeof(float)<=4096); // bundled Vulkan uniform section limit
- memcpy(uniforms.data()+80*4,fixtures.data(),fixtures.size()*sizeof(Fixture));
- auto render=[&]() {
- CHECK(frame->Flush());SDL_GPUCommandBuffer *commands=SDL_AcquireGPUCommandBuffer(frame->Device());CHECK(commands);
- SDL_GPUColorTargetInfo attachment={};attachment.texture=target;attachment.load_op=SDL_GPU_LOADOP_DONT_CARE;attachment.store_op=SDL_GPU_STOREOP_STORE;
- SDL_GPURenderPass *pass=SDL_BeginGPURenderPass(commands,&attachment,1,NULL);CHECK(pass);
- SDL_BindGPUGraphicsPipeline(pass,pipeline);SDL_PushGPUFragmentUniformData(commands,0,uniforms.data(),uniforms.size()*sizeof(float));
- SDL_DrawGPUPrimitives(pass,3,1,0,0);SDL_EndGPURenderPass(pass);CHECK(SDL_SubmitGPUCommandBuffer(commands));
- return read_float_targets(frame,&target,1,columns,count);
- };
- const auto values=render();
- auto value=[&](unsigned row,unsigned col,unsigned component){return double(values[(row*columns+col)*4+component]);};
- // Independent CPU geometry: clamp to a rectangle, then mirror about that closest point.
- // This does not call the production closest-edge, mirror-Jacobian, or derivative helpers.
- auto reflected=[&](unsigned row,double x,double y,double result[3]) {
- const Fixture &f=fixtures[row];const Hull &h=hulls[unsigned(f.other[0])];
- result[0]=result[1]=result[2]=0;
- if(h.data[0][3]<3 || std::abs(f.point[2]-h.data[0][2])>.1) return;
- const double ax=h.data[1][0],ay=h.data[1][1],dx=x-h.data[0][0],dy=y-h.data[0][1];
- const double lx=dx*ax+dy*ay,ly=-dx*ay+dy*ax;
- if(std::abs(lx)<=20 && std::abs(ly)<=6) return;
- const double qx=(std::max)(-20.0,(std::min)(20.0,lx)),qy=(std::max)(-6.0,(std::min)(6.0,ly));
- const double distance=std::hypot(lx-qx,ly-qy);if(distance>=28 || distance<.0001) return;
- const double nx=(ax*(lx-qx)-ay*(ly-qy))/distance,ny=(ay*(lx-qx)+ax*(ly-qy))/distance;
- const double mx=x-2*distance*nx,my=y-2*distance*ny,t=distance/28,fade=1-t*t*(3-2*t),weight=.68*fade*fade;
- const double d[3]={2*std::sin(.07*mx+.025*my),1.5*std::cos(.035*mx-.045*my),3*std::sin(.055*mx-.08*my)};
- const double normal=nx*d[0]+ny*d[1];result[0]=(d[0]-2*nx*normal)*weight;result[1]=(d[1]-2*ny*normal)*weight;result[2]=d[2]*weight;
- };
- double maxValue=0,maxDerivative=0,maxPacketDerivative=0,maxPacketValue=0,maxScalarPacketDerivative=0,maxSternError=0;
- for(unsigned row=0;row<packetCount;++row) {
- const double x=fixtures[row].point[0],y=fixtures[row].point[1];double expected[3];reflected(row,x,y,expected);
- const auto &h=hulls[unsigned(fixtures[row].other[0])];double sternValue=0,bowValue=0;
- const double packet=vessel_test_packet(h,x,y,fixtures[row].point[2],fixtures[row].point[3],&sternValue,&bowValue);
- maxPacketValue=(std::max)(maxPacketValue,std::abs(value(row,5,0)-packet));CHECK(std::abs(value(row,5,0)-packet)<.00002);
- const double sternError=std::abs((value(row,5,0)-bowValue)-sternValue);
- maxSternError=(std::max)(maxSternError,sternError);CHECK(sternError<.00002);
- for(unsigned c=0;c<3;++c) {maxValue=(std::max)(maxValue,std::abs(value(row,0,c)-expected[c]));CHECK(std::abs(value(row,0,c)-expected[c])<.00002);}
- for(unsigned axis=0;axis<2;++axis) {
- double plus[3],minus[3];const double step=.0001;
- reflected(row,x+(axis==0?step:0),y+(axis==1?step:0),plus);
- reflected(row,x-(axis==0?step:0),y-(axis==1?step:0),minus);
- for(unsigned c=0;c<3;++c) {
- const double difference=std::abs(value(row,1+axis,c)-(plus[c]-minus[c])/(2*step));
- maxDerivative=(std::max)(maxDerivative,difference);CHECK(difference<.0002);
- }
- const double numeric=(value(row,6+axis*2,3)-value(row,7+axis*2,3))/.0625;
- const double difference=std::abs(numeric-value(row,5,axis+1));
- maxPacketDerivative=(std::max)(maxPacketDerivative,difference);CHECK(difference<.0003);
- const double packetPlus=vessel_test_packet(h,x+(axis==0?.0001:0),y+(axis==1?.0001:0),fixtures[row].point[2],fixtures[row].point[3]);
- const double packetMinus=vessel_test_packet(h,x-(axis==0?.0001:0),y-(axis==1?.0001:0),fixtures[row].point[2],fixtures[row].point[3]);
- const double scalarError=std::abs(value(row,5,axis+1)-(packetPlus-packetMinus)/.0002);
- maxScalarPacketDerivative=(std::max)(maxScalarPacketDerivative,scalarError);CHECK(scalarError<.00003);
- }
- for(unsigned col=0;col<columns;++col) for(unsigned c=0;c<4;++c) CHECK(std::isfinite(value(row,col,c)));
- }
- // The reference maps scalar query positions and separately evaluates the original
- // stern and mapped bow. It never calls the production Jacobian or dual helpers.
- auto registeredScalar=[&](unsigned row,double x,double y,bool constant=false) {
- const Fixture &f=fixtures[row];const Hull &h=hulls[unsigned(f.other[0])];
- double stern=0;vessel_test_packet(h,x,y,f.point[2],f.point[3],&stern);
- const double scale=constant?.5:.5+.1*std::sin(.013*x-.017*y);
- const double rawX=constant?4:2*std::sin(.07*x+.025*y),rawY=constant?-3:1.5*std::cos(.035*x-.045*y);
- const double mappedX=x+scale*horizontalBound*std::tanh(rawX/horizontalBound);
- const double mappedY=y+scale*horizontalBound*std::tanh(rawY/horizontalBound);
- double bow=0;vessel_test_packet(h,mappedX,mappedY,f.point[2],f.point[3],NULL,&bow);
- return stern+bow;
- };
- double registrationValueError=0,registrationDerivativeError=0,registrationDifferenceError=0,registrationOldControl=0;
- for(unsigned row=0;row<packetCount;++row) {
- const double x=fixtures[row].point[0],y=fixtures[row].point[1];
- const double error=std::abs(value(row,10,0)-registeredScalar(row,x,y));
- registrationValueError=(std::max)(registrationValueError,error);CHECK(error<.00003);
- registrationOldControl=(std::max)(registrationOldControl,std::abs(value(row,10,0)-value(row,19,0)));
- for(unsigned axis=0;axis<2;++axis) {
- const double step=.0001;
- const double plus=registeredScalar(row,x+(axis==0?step:0),y+(axis==1?step:0));
- const double minus=registeredScalar(row,x-(axis==0?step:0),y-(axis==1?step:0));
- const double error=std::abs(value(row,10,1+axis)-(plus-minus)/(2*step));
- registrationDerivativeError=(std::max)(registrationDerivativeError,error);CHECK(error<.00005);
- const double gpuDifference=(value(row,11+2*axis,0)-value(row,12+2*axis,0))/.0625;
- const double gpuError=std::abs(value(row,10,1+axis)-gpuDifference);
- registrationDifferenceError=(std::max)(registrationDifferenceError,gpuError);CHECK(gpuError<.0004);
- }
- for(unsigned c=0;c<3;++c) {CHECK(value(row,15,c)==0);CHECK(std::abs(value(row,17,c))<.000002);}
- CHECK(std::abs(value(row,18,0)-registeredScalar(row,x,y,true))<.00003);
- const double horizontal=std::hypot(value(row,16,0)-x,value(row,16,1)-y);
- CHECK(horizontal<=8*value(row,16,2)+.00002);
- for(unsigned col=20;col<24;++col) {
- CHECK(std::abs(value(row,col,0)-((col&1)?1:-1)*horizontalBound)<.000002);
- CHECK(std::abs(value(row,col,1)-((col&2)?1:-1)*horizontalBound)<.000002);
- CHECK(value(row,col,2)<=8.000002 && value(row,col,2)>7.999998);
- }
- }
- double peakParameters[3];vessel_test_pressure_parameters(6,12,peakParameters);
- CHECK(std::abs(value(translatedPeak,18,0)-peakParameters[2])<.000003);
- CHECK(registrationOldControl>.005);
- printf("sdl_gpu_frame_selfcheck: registered bow %u scalar fixtures: value %.8g, derivative %.8g, GPU finite difference %.8g; old-coordinate control %.8g; translated world peak, exact zero-chop and stern preservation checked\n",
- packetCount,registrationValueError,registrationDerivativeError,registrationDifferenceError,registrationOldControl);
- double maxPressureParameter=0,maxPressureValue=0,maxPressureDerivative=0,maxPressureCpu=0,maxPressureDifference=0;
- for(unsigned row=packetCount;row<count;++row) {
- const Fixture &f=fixtures[row];double expected[3];vessel_test_pressure_parameters(f.other[1],f.other[2],expected);
- const auto cpu=WaterVesselWaves::BowPressure(f.other[1],f.other[2]);const float cpuParameters[3]={cpu.along,cpu.across,cpu.amplitude};
- for(unsigned c=0;c<3;++c) {
- maxPressureParameter=(std::max)(maxPressureParameter,std::abs(value(row,0,c)-expected[c]));
- CHECK(std::abs(value(row,0,c)-expected[c])<.00001 && std::abs(value(row,0,c)-cpuParameters[c])<.00001);
- }
- const double scalar=vessel_test_pressure(f.point[0],f.point[1],f.other[1],f.other[2]);
- maxPressureValue=(std::max)(maxPressureValue,std::abs(value(row,1,0)-scalar));CHECK(std::abs(value(row,1,0)-scalar)<.00001);
- const auto cpuValue=WaterVesselWaves::EvaluateBowPressure(cpu,f.point[0],f.point[1]);
- const float cpuSample[3]={cpuValue.height,cpuValue.dAlong,cpuValue.dAcross};
- for(unsigned c=0;c<3;++c) {
- maxPressureCpu=(std::max)(maxPressureCpu,std::abs(value(row,1,c)-cpuSample[c]));CHECK(std::abs(value(row,1,c)-cpuSample[c])<.00002);
- }
- for(unsigned axis=0;axis<2;++axis) {
- const double plus=vessel_test_pressure(f.point[0]+(axis==0?.0001:0),f.point[1]+(axis==1?.0001:0),f.other[1],f.other[2]);
- const double minus=vessel_test_pressure(f.point[0]-(axis==0?.0001:0),f.point[1]-(axis==1?.0001:0),f.other[1],f.other[2]);
- const double derivativeError=std::abs(value(row,1,axis+1)-(plus-minus)/.0002);
- maxPressureDerivative=(std::max)(maxPressureDerivative,derivativeError);CHECK(derivativeError<.00002);
- const double differenceError=std::abs(value(row,1,axis+1)-(value(row,2+axis*2,0)-value(row,3+axis*2,0))/.0625);
- maxPressureDifference=(std::max)(maxPressureDifference,differenceError);CHECK(differenceError<.00003);
- }
- CHECK(std::abs(value(row,6,0)-expected[2])<.000003);
- CHECK(std::abs(value(row,7,0)-expected[2]*.5)<.000003 && std::abs(value(row,8,0)-expected[2]*.5)<.000003);
- for(unsigned col=0;col<columns;++col)for(unsigned c=0;c<4;++c)CHECK(std::isfinite(value(row,col,c)));
- }
- for(unsigned b=0;b<4;++b) {
- CHECK(value(pressureRows[b][0],6,0)==0);
- for(unsigned v=1;v<7;++v)CHECK(value(pressureRows[b][v],6,0)>value(pressureRows[b][v-1],6,0));
- CHECK(value(pressureRows[b][4],6,0)>value(pressureRows[b][2],6,0)*3);
- }
- CHECK(value(pressureRows[3][4],0,1)>value(pressureRows[0][4],0,1)*8 && value(pressureRows[3][4],6,0)>value(pressureRows[0][4],6,0));
- CHECK(std::abs(value(edge,3,0))<.00001 && std::abs(value(edge,3,1)-4)<.00001 && value(edge,3,3)==0);
- CHECK(std::abs(value(corner,3,0)-17)<.00001 && std::abs(value(corner,3,1)-2)<.00001 && value(corner,3,3)==1);
- for(unsigned row:{inside,far,wrong,fade}) CHECK(value(row,3,2)==0);
- for(unsigned c=0;c<3;++c) CHECK(std::abs(value(leftCorner,0,c)-value(rightCorner,0,c))<.001);
- CHECK(value(wake,5,0)>.05 && value(bow,5,0)>.5);
- for(unsigned row:{stationary,slow,bad,wakeEnd,bowFar}) CHECK(std::abs(value(row,5,0))<.00001);
- CHECK(std::abs(value(reverse,5,0)-value(wake,5,0))<.00002);
- CHECK(std::abs(value(reverse,5,1)+value(wake,5,1))<.00002 && std::abs(value(reverse,5,2)+value(wake,5,2))<.00002);
- CHECK(std::abs(value(rotated,5,0)-value(wake,5,0))<.00002);
- CHECK(std::abs(value(rotated,5,1)-(value(wake,5,1)*cosine-value(wake,5,2)*sine))<.00002);
- CHECK(std::abs(value(rotated,5,2)-(value(wake,5,1)*sine+value(wake,5,2)*cosine))<.00002);
- for(unsigned c=0;c<3;++c) CHECK(value(repeat,5,c)==value(wake,5,c) && value(last,5,c)==value(wake,5,c));
- // The divergent crests are steady in the boat frame. Animate the centre churn instead:
- // at along=20/across=0 both spatial envelopes are one, so its expected temporal delta
- // is independently just the scalar sinusoid times the measured-speed gate.
- const double speedT=(12.0-.3)/(14.0-.3),speedGate=speedT*speedT*(3-2*speedT);
- const double phase=6.0+double(hulls[1].data[2][2])*6.2831853;
- const double expectedDelta=.24*speedGate*(std::sin(phase-5*1.15)-std::sin(phase-4*1.15));
- CHECK(expectedDelta>.15 && std::abs((value(later,5,0)-value(churn,5,0))-expectedDelta)<.00002);
- // The travel direction crosses sideways by only 0.00000167 radians. Heights and slopes
- // must not jump from one end of a forty-unit hull to the other. Check active bow/churn and
- // both old endpoint regions; the armed endpoint-forcing control proves this catches a snap.
- hulls[6].data[2][0]=-.00001f;memcpy(uniforms.data()+6*40,&hulls[6],sizeof(Hull));
- const auto oppositeSide=render();double maxSideChange=0;
- CHECK(value(sideBow,5,0)>.5);
- for(unsigned row:{sideBow,sideSwitch,sideStern,sideWing}) for(unsigned c=0;c<3;++c) {
- const double change=std::abs(value(row,5,c)-oppositeSide[(row*columns+5)*4+c]);
- maxSideChange=(std::max)(maxSideChange,change);CHECK(change<.0003);
- }
- hulls[6].data[2][0]=.00001f;hulls[6].data[3][0]=hulls[6].data[3][2]=20;
- memcpy(uniforms.data()+6*40,&hulls[6],sizeof(Hull));const auto forcedRight=render();
- const double forcedRightExpected=vessel_test_packet(hulls[6],fixtures[sideSwitch].point[0],fixtures[sideSwitch].point[1],7,4);
- hulls[6].data[2][0]=-.00001f;hulls[6].data[3][0]=hulls[6].data[3][2]=-20;
- memcpy(uniforms.data()+6*40,&hulls[6],sizeof(Hull));const auto forcedLeft=render();
- const double forcedLeftExpected=vessel_test_packet(hulls[6],fixtures[sideSwitch].point[0],fixtures[sideSwitch].point[1],7,4);
- const double forcedDelta=forcedRight[(sideSwitch*columns+5)*4]-forcedLeft[(sideSwitch*columns+5)*4];
- CHECK(std::abs(forcedDelta)>.4 && std::abs(forcedDelta-(forcedRightExpected-forcedLeftExpected))<.00002);
- // This armed old-model control catches accidental retention of the detached fixed8/1.9
- // bump; it is separate from numerical error tolerances, which remain tight.
- CHECK(std::abs(value(bow,5,0)-1.9*speedGate)>.5);
- double maxScaledPacket=0;
- for(float beam:beams) {
- double previousHeight=0;
- for(float speed:{14.0f,40.0f}) {
- Hull large;rectangle(large,speed);large.data[1][2]=beam*3;large.data[1][3]=beam;
- large.data[2][3]=std::hypot(beam*3,beam);large.data[3][0]=-beam*3;large.data[3][2]=beam*3;
- const float points[8]={-beam*3,-beam,beam*3,-beam,beam*3,beam,-beam*3,beam};memcpy(large.data[4],points,sizeof(points));
- memcpy(uniforms.data()+7*40,&large,sizeof(large));
- Fixture sample=fixtures[last];sample.point[0]=beam*3+9;sample.point[1]=beam*.5f;
- memcpy(uniforms.data()+80*4+last*8,&sample,sizeof(sample));const auto scaled=render();
- const double observed=scaled[(last*columns+5)*4],expected=vessel_test_packet(large,sample.point[0],sample.point[1],7,4);
- maxScaledPacket=(std::max)(maxScaledPacket,std::abs(observed-expected));CHECK(std::abs(observed-expected)<.00002);
- for(unsigned axis=0;axis<2;++axis) {
- const double plus=vessel_test_packet(large,sample.point[0]+(axis==0?.0001:0),sample.point[1]+(axis==1?.0001:0),7,4);
- const double minus=vessel_test_packet(large,sample.point[0]-(axis==0?.0001:0),sample.point[1]-(axis==1?.0001:0),7,4);
- CHECK(std::abs(scaled[(last*columns+5)*4+axis+1]-(plus-minus)/.0002)<.00003);
- }
- if(previousHeight>0)CHECK(observed>previousHeight*3);previousHeight=observed;
- }
- }
- printf("sdl_gpu_frame_selfcheck: GPU bow pressure: %u beam/speed/invalid fixtures, independent parameters %.8f/value %.8f/gradient %.8f, CPU agreement %.8f, GPU height differences %.8f, full scaled packet %.8f; actual bow anchor, curved half-height widths, monotonic speed beyond14 and beam-dependent extent checked\n",count-packetCount,maxPressureParameter,maxPressureValue,maxPressureDerivative,maxPressureCpu,maxPressureDifference,maxScaledPacket);
- printf("sdl_gpu_frame_selfcheck: GPU physical vessel waves: %u fixtures, independent reflection value %.8f/gradient %.8f, packet value %.8f/scalar gradient %.8f/GPU finite-difference %.8f, unchanged stern %.8f, sideways height/slope change %.8f; stationary/corners/reverse/rotation/level/speed/pause/support/final hull and armed endpoint snap checked\n",packetCount,maxValue,maxDerivative,maxPacketValue,maxScalarPacketDerivative,maxPacketDerivative,maxSternError,maxSideChange);
- }
- if(target) SDL_ReleaseGPUTexture(frame->Device(),target);if(pipeline) SDL_ReleaseGPUGraphicsPipeline(frame->Device(),pipeline);
- if(vertex) SDL_ReleaseGPUShader(frame->Device(),vertex);if(pixel) SDL_ReleaseGPUShader(frame->Device(),pixel);
+ if(sternOut)*sternOut=stern;return stern;
}
static void check_gpu_vessel_hull_damping(SdlGpuFrame *frame)
@@ -5299,7 +4533,7 @@ static void check_gpu_water_wave_cage(SdlGpuFrame *frame)
} r;r.device=frame->Device();
VertexPipelineDescription vd={};vd.FVF=FF_FVF_XYZ|FF_FVF_NORMAL|FF_FVF_DIFFUSE|FF_FVF_TEX2;vd.StageCount=4;
vd.Stages[0].TextureCoordinateIndex=0;vd.Stages[1].TextureCoordinateIndex=1;
- std::string vs;CHECK(VertexShader_Generate(vd,VERTEX_SHADER_TARGET_D3D11,vs));CHECK(WaterFftSampling::WrapVertex(vs,false,false));
+ std::string vs;CHECK(VertexShader_Generate(vd,VERTEX_SHADER_TARGET_D3D11,vs));CHECK(WaterFftSampling::WrapVertex(vs));
CHECK(SDL3_Shader_Retarget(vs,true));
const std::string entry="Output main(Input input)";const size_t at=vs.find(entry);CHECK(at!=std::string::npos);if(at==std::string::npos)return;
vs.replace(at,entry.size(),"Output cageWaterVertex(Input input)");
@@ -5453,7 +4687,7 @@ Result main(CageProbe input) {
static void check_gpu_water_hull_normal(SdlGpuFrame *frame)
{
// A constant spectral height has zero spectral slope. Its production normal is therefore
- // independently the derivative of the analytic hull envelope. Changing a coarse quad's
+ // independently the derivative of its reflected height and clearance envelopes. A coarse quad's
// diagonal must not change that normal; the old interpolated-envelope control must change it.
const unsigned width=96,height=32;
struct Resources {
@@ -5464,11 +4698,9 @@ static void check_gpu_water_hull_normal(SdlGpuFrame *frame)
if(sampler)SDL_ReleaseGPUSampler(device,sampler);}
} resources;
resources.device=frame->Device();
- const char *previous=getenv("ZH_WATER_DEBUG");const bool hadDebug=previous!=NULL;const std::string oldDebug=previous?previous:"";
- CHECK(setenv("ZH_WATER_DEBUG","normal",1)==0);
PixelPipelineDescription pd={};std::string ps;const bool generated=EngineShader_Pixel_Program(ENGINE_SHADER_WATER_TRAPEZOID,pd,ps,COMBINER_SHADER_TARGET_SDL3_GPU);
- if(hadDebug)CHECK(setenv("ZH_WATER_DEBUG",oldDebug.c_str(),1)==0);else CHECK(unsetenv("ZH_WATER_DEBUG")==0);
CHECK(generated);if(!generated)return;
+ if(!observe_water_normal(ps)) return;
VertexPipelineDescription vd={};vd.FVF=FF_FVF_XYZ|FF_FVF_NORMAL|FF_FVF_DIFFUSE|FF_FVF_TEX2;vd.StageCount=4;
vd.Stages[0].TextureCoordinateIndex=0;vd.Stages[1].TextureCoordinateIndex=1;
std::string vs;CHECK(VertexShader_Generate(vd,VERTEX_SHADER_TARGET_D3D11,vs));CHECK(WaterFftSampling::WrapVertex(vs));
@@ -5504,7 +4736,7 @@ Output main(uint id:SV_VertexID) {
resources.vertex=SDL3_Create_Shader(resources.device,spirv,true,error);CHECK(resources.vertex);
compiled=SDL3_Compile_HLSL_To_SPIRV(ps,false,spirv,error);CHECK(compiled);
if(!compiled){printf("hull normal PS: %s\n",error.c_str());return;}
- unsigned samplers=0,uniforms=0;SDL3_Shader_Slots(spirv,false,samplers,uniforms);CHECK(samplers<=16 && uniforms==(WaterHullVisual::Enabled()?4u:1u));
+ unsigned samplers=0,uniforms=0;SDL3_Shader_Slots(spirv,false,samplers,uniforms);CHECK(samplers<=16 && uniforms==(4u));
resources.pixel=SDL3_Create_Shader(resources.device,spirv,false,error);CHECK(resources.pixel);
SDL_GPUColorTargetDescription colour={};colour.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
SDL_GPUGraphicsPipelineCreateInfo pi={};pi.vertex_shader=resources.vertex;pi.fragment_shader=resources.pixel;
@@ -5527,7 +4759,7 @@ Output main(uint id:SV_VertexID) {
water.SunDirection[2]=1;water.SunColour[0]=water.SunColour[1]=water.SunColour[2]=1;
water.TerrainParameters[1]=100;water.SceneParameters[1]=water.SceneParameters[2]=1;
water.OpticalParameters[0]=3;water.OpticalParameters[1]=water.OpticalParameters[2]=1;
- water.FftParameters[0]=1;water.FftParameters[1]=0; // isolate clearance from optional reflected/generated waves
+ water.FftParameters[0]=1;
water.HullParameters[0]=1;water.HullData[0][2]=.5f;water.HullData[0][3]=4;
water.HullData[1][0]=1;water.HullData[1][2]=20;water.HullData[1][3]=6;
const float outline[8]={-20,-6,20,-6,20,6,-20,6};memcpy(water.HullData[4],outline,sizeof(outline));
@@ -5559,30 +4791,44 @@ Output main(uint id:SV_VertexID) {
const auto seam=render(0,false,0,1),floor=render(1,false,1,WaterFftGeometry::SafeDamping(1,2.25f));
CHECK(first.size()==width*height*4 && second.size()==first.size() && coarseFirst.size()==first.size() && coarseSecond.size()==first.size() && seam.size()==first.size() && floor.size()==first.size());
if(first.size()!=width*height*4 || second.size()!=first.size() || coarseFirst.size()!=first.size() || coarseSecond.size()!=first.size() || seam.size()!=first.size() || floor.size()!=first.size())return;
- const double waveHeight=WaterFftGeometry::MaxVerticalDisplacement*std::tanh(1.0/WaterFftGeometry::MaxVerticalDisplacement);
+ auto surfaceHeight=[](double x,double y,double freeDamping) {
+ const double dx=x<-20?x+20:x>20?x-20:0,dy=y>6?y-6:y<-6?y+6:0;
+ const double distance=std::hypot(dx,dy),t=std::min(1.0,distance/9);
+ const double damping=std::min(freeDamping,t*t*(3-2*t));
+ double reflected=0;
+ if(distance>.0001 && distance<28) {
+ const double r=distance/28,fade=1-r*r*(3-2*r);
+ reflected=.68*fade*fade;
+ }
+ const double bound=WaterFftGeometry::MaxVerticalDisplacement;
+ return bound*std::tanh((1+reflected)/bound)*damping;
+ };
+ auto scalarNormal=[&](double x,double y,double freeDamping) {
+ const double step=.0001;
+ const double gx=(surfaceHeight(x+step,y,freeDamping)-surfaceHeight(x-step,y,freeDamping))/(2*step);
+ const double gy=(surfaceHeight(x,y+step,freeDamping)-surfaceHeight(x,y-step,freeDamping))/(2*step);
+ const double length=std::sqrt(1+gx*gx+gy*gy);
+ return std::array<double,3>{-gx/length,-gy/length,1/length};
+ };
double maximumError=0,maximumDiagonal=0,maximumControl=0,maximumSeam=0,maximumFloor=0;unsigned controls=0,active=0;
for(unsigned y=1;y<height-1;++y)for(unsigned x=1;x<width-1;++x) {
const double px=-24+52*(x+.5)/width,py=17-13*(y+.5)/height;
- const double sx=px<-20?px+20:px>20?px-20:0,sy=py>6?py-6:py<-6?py+6:0,distance=std::hypot(sx,sy);
- const double t=(std::min)(1.0,distance/9),damping=t*t*(3-2*t),slope=6*t*(1-t)/9;
- const double gx=distance>0?slope*sx/distance:0,gy=distance>0?slope*sy/distance:0;
- const double normalLength=std::sqrt(1+waveHeight*waveHeight*(gx*gx+gy*gy));
- const double normal[3]={-waveHeight*gx/normalLength,-waveHeight*gy/normalLength,1/normalLength};
- const bool floorWins=WaterFftGeometry::SafeDamping(1,2.25f)<=damping;
+ const auto normal=scalarNormal(px,py,1);
+ const auto floorNormal=scalarNormal(px,py,WaterFftGeometry::SafeDamping(1,2.25f));
for(unsigned c=0;c<3;++c) {
const unsigned offset=(y*width+x)*4+c;
const double error=std::abs(first[offset]-(.5+.5*normal[c]));maximumError=(std::max)(maximumError,error);
maximumDiagonal=(std::max)(maximumDiagonal,double(std::abs(first[offset]-second[offset])));
const double control=std::abs(coarseFirst[offset]-coarseSecond[offset]);maximumControl=(std::max)(maximumControl,control);controls+=control>.005;
maximumSeam=(std::max)(maximumSeam,std::abs(seam[offset]-(c==2?1.0:.5)));
- const double expected=floorWins?(c==2?1.0:.5):(.5+.5*normal[c]);maximumFloor=(std::max)(maximumFloor,std::abs(floor[offset]-expected));
+ const double expected=.5+.5*floorNormal[c];maximumFloor=(std::max)(maximumFloor,std::abs(floor[offset]-expected));
}
active+=std::abs(normal[0])+std::abs(normal[1])>.08;
}
for(const auto *image:{&first,&second,&coarseFirst,&coarseSecond,&seam,&floor})for(float v:*image)CHECK(std::isfinite(v));
CHECK(maximumError<.0001 && maximumDiagonal<.0001 && maximumFloor<.0001 && maximumSeam<.0001);
CHECK(active>200 && maximumControl>.01 && controls>100);
- printf("sdl_gpu_frame_selfcheck: GPU production hull normal: %u renders, independent normal %.8f/diagonal %.8f/floor %.8f/zero-weight %.8f; armed interpolated damping diagonal error %.8f (%u components), disabled vessel-wave gate checked\n",renders,maximumError,maximumDiagonal,maximumFloor,maximumSeam,maximumControl,controls);
+ printf("sdl_gpu_frame_selfcheck: GPU production hull normal: %u renders, independent normal %.8f/diagonal %.8f/floor %.8f/zero-weight %.8f; armed interpolated damping diagonal error %.8f (%u components), composed reflected-wave clearance checked\n",renders,maximumError,maximumDiagonal,maximumFloor,maximumSeam,maximumControl,controls);
}
#endif // __linux__
@@ -5604,7 +4850,8 @@ static void check_gpu_water_bow_shoulder(SdlGpuFrame *frame)
add(7,286,0);add(7,292,0);add(7,298,0);add(7,322,0); // carrier cap/wing/derivative/compact
const unsigned rows=unsigned(fixtures.size()),columns=12;
std::string common="cbuffer BowShoulderFixtures : register(b0) {float4 HullData[80];float4 Fixture["+std::to_string(rows)+"];};\nstatic const float4 HullParameters=float4(8,0,0,0);\n";
- common+=WaterFftSampling::CommonSource()+WaterVesselWaves::Source(false,true);
+ common+="static const float4 ContactHullData[80]={0};\n";
+ common+=WaterFftSampling::CommonSource()+WaterVesselWaves::Source();
common+=R"HLSL(
float3 shoulderEval(uint row,uint col) {
float4 f=Fixture[row];int h=(int)f.w;float2 p=f.xy;
@@ -5885,12 +5132,12 @@ Result main(ProbeOutput input) {Result o;o.Parameter=input.Parameter;o.Metadata=
printf("sdl_gpu_frame_selfcheck: GPU production bow refinement: %u meshes/%u stable pixels, raster world-coordinate error %.8f; fresh metadata/depth errors %.8f/%.8f (bounds .00003/.00003), pixel XY errors %.8f/%.8f (independent bounds %.8f/%.8f), coarse collapse %.8f/near-limit %.8f, full-change %u, stale metadata control %.8f, exact locked-boundary coverage, bounded height %.5f\n",renders,totalStable,maxCoordinateError,maxMetadataError,maxDepthError,maxPixelErrorX,maxPixelErrorY,coverageBoundX,coverageBoundY,zeroError,nearError,changed,staleDifference,maxBound);
}
-static void check_gpu_fft_vessel_composition(SdlGpuFrame *frame,bool bowLift=false,bool bowShoulder=false)
+static void check_gpu_fft_vessel_composition(SdlGpuFrame *frame)
{
// Known Fourier modes, independently packed into the six real field maps, make a numerical
// derivative meaningful: the random full-band spectrum is too close to texture Nyquist for a
// small finite difference of bilinear samples to approximate its stored spectral derivative.
- const unsigned side=256,rows=10,columns=bowLift?51:40,plane=side*side*4;
+ const unsigned side=256,rows=10,columns=41,plane=side*side*4;
const double amplitude[3]={.13,.17,.32},phase[3]={.31,-.42,.71},chop[3]={-1.2,-1.5,-1.5};
const int modes[3][2]={{1,1},{1,-1},{1,0}};
const float points[rows][4]={{0,8,7,0},{23,10,7,.5f},{-24,-10,7,1.5f},{12,18,7,3},{28,0,7,8},
@@ -5953,33 +5200,33 @@ static void check_gpu_fft_vessel_composition(SdlGpuFrame *frame,bool bowLift=fal
};
CHECK(frame->Flush());if(!upload()) return;
const std::string basicVS="float4 main(uint id:SV_VertexID):SV_Position {return float4(id==1?3.0:-1.0,id==2?3.0:-1.0,0,1);}";
- std::string sampleVS=WaterFftSampling::UniformSource("WaterBlock",0)+WaterFftSampling::VertexSource(bowLift,bowShoulder)+R"HLSL(
+ std::string sampleVS=WaterFftSampling::UniformSource("WaterBlock",0)+WaterFftSampling::VertexSource()+R"HLSL(
cbuffer PointBlock:register(b1) {float4 PointData;};
struct Output {float4 Position:SV_Position;[[vk::location(0)]] float4 Value:TEXCOORD0;[[vk::location(1)]] nointerpolation float4 Registered:TEXCOORD1;};
Output main(uint id:SV_VertexID) {Output o;o.Position=float4(id==1?3.0:-1.0,id==2?3.0:-1.0,0,1);
o.Value=float4(fftVertexDisplacement(PointData.xy,PointData.z),1);
o.Registered=float4(fftVertexDisplacement(PointData.xy,PointData.z,.559713426),1);return o;}
)HLSL";
- std::string samplePS="float4 main(float4 pixel:SV_Position,[[vk::location(0)]] float4 value:TEXCOORD0,[[vk::location(1)]] nointerpolation float4 registered:TEXCOORD1):SV_Target0 {return pixel.x>=36.0?registered:value;}";
+ std::string samplePS="float4 main(float4 pixel:SV_Position,[[vk::location(0)]] float4 value:TEXCOORD0,[[vk::location(1)]] nointerpolation float4 registered:TEXCOORD1):SV_Target0 {return pixel.x>=30.0?registered:value;}";
std::string surfacePS=WaterFftSampling::UniformSource("WaterBlock",0);
for(unsigned i=0;i<6;++i) surfacePS+="Texture2D Texture"+std::to_string(8+i)+":register(t"+std::to_string(i)+");SamplerState Sampler"+std::to_string(8+i)+":register(s"+std::to_string(i)+");\n";
surfacePS+="cbuffer PointBlock:register(b1) {float4 Points["+std::to_string(rows)+"];};\n";
- surfacePS+=WaterFftSampling::PixelSource(bowLift,bowShoulder);
+ surfacePS+=WaterFftSampling::PixelSource();
surfacePS+=R"HLSL(
-float4 main(float4 pixel:SV_Position):SV_Target0 {uint col=(uint)pixel.x;float4 p=Points[(uint)pixel.y];
+float4 main(float4 pixel:SV_Position):SV_Target0 {uint col=(uint)pixel.x;if(col>=6)col+=6;if(col>=45)col+=4;float4 p=Points[(uint)pixel.y];
FftSurface s=fftSurface(p.xy,p.z);
if(col>=36) {
FftSurface registered=fftSurface(p.xy,p.z,p.w,float3(.559713426,0,0));
if(col==36)return float4(registered.displacement,registered.vesselCrest);
- if(col==37)return float4(registered.derivativeX,registered.generatedRaw);
- if(col==38)return float4(registered.derivativeY,registered.generatedHeight);
+ if(col==37)return float4(registered.derivativeX,0);
+ if(col==38)return float4(registered.derivativeY,0);
FftSurface unfiltered=fftSurface(p.xy,p.z,0.0,float3(.559713426,0,0));
return float4(max(abs(registered.displacement-unfiltered.displacement),
max(abs(registered.derivativeX-unfiltered.derivativeX),abs(registered.derivativeY-unfiltered.derivativeY))),
- abs(registered.generatedRaw-unfiltered.generatedRaw));
+ 0);
}
-if(col==0) return float4(s.displacement,s.compression);
-if(col==1) return float4(s.derivativeX,s.vesselHeight);
+if(col==0) return float4(s.displacement,0);
+if(col==1) return float4(s.derivativeX,0);
if(col==2) return float4(s.derivativeY,s.vesselCrest);
if(col==3) return float4(normalize(cross(float3(1,0,0)+s.derivativeX,float3(0,1,0)+s.derivativeY)),s.incidentCompression);
if(col==4) return float4(vesselGeneratedFoam(s.vesselCrest,1,saturate((4.0-0.15)/fftVerticalBound)),
@@ -5987,18 +5234,6 @@ if(col==4) return float4(vesselGeneratedFoam(s.vesselCrest,1,saturate((4.0-0.15)
vesselGeneratedFoam(s.vesselCrest,0,1),vesselGeneratedFoam(s.vesselCrest,1,0));
if(col==5) return float4(vesselGeneratedFoam(-1,1,1),vesselGeneratedFoam(2,1,2),
vesselGeneratedFoam(1,-2,1),vesselGeneratedFoam(1,2,1));
-float damping=saturate((4.0-0.15)/fftVerticalBound);
-float coverage=vesselGeneratedFoam(s.vesselCrest,1,damping);
-if(col==6) return float4(s.generatedRaw,s.generatedHeight,fftVerticalBound*tanh(s.generatedRaw/fftVerticalBound),s.vesselHeight);
-if(col==7) return float4(fftPressureDebug(s,1,damping,coverage),0);
-if(col==8) return float4(fftPressureRetentionDebug(s,1,damping,coverage),0);
-if(col==9) return float4(fftPressureDebug(s,0,damping,0),0);
-if(col==10) return float4(fftPressureDebug(s,1,0,0),0);
-if(col==11) {
- FftSurface masked=s;uint maskCase=(uint)pixel.y%3;
- masked.generatedRaw=maskCase==0?0.0:maskCase==1?-1.0:0.000001;
- return float4(fftPressureRetentionDebug(masked,1,1,1),0);
-}
float3 lod=fftShadingLod(p.w);
if(col==19)return Texture8.SampleLevel(Sampler8,p.xy/(450.0*fftWorldScale),lod.x);
if(col==20)return Texture9.SampleLevel(Sampler9,p.xy/(450.0*fftWorldScale),lod.x);
@@ -6030,7 +5265,7 @@ if(col>=25) {
// Actual mirrored positions whenever this hull contributes; otherwise several
// negative/positive world-period wraps exercise arbitrary signed coordinates.
queryPosition+=float2(-18000.25,4120.5);
- if(FftParameters.y>0.5 && HullParameters.x>0.5) {
+ if(HullParameters.x>0.5) {
int hullIndex=(int)HullParameters.x-1;
VesselReflection reflected=vesselReflection(p.xy,p.z,hullIndex);
if(reflected.weight>0.0)queryPosition=reflected.samplePosition;
@@ -6054,15 +5289,14 @@ if(col==12) return float4(filtered.shadingDisplacement,filtered.unresolvedSlopeV
if(col==13) return float4(filtered.shadingDerivativeX,filtered.vesselCrest);
if(col==14) return float4(filtered.shadingDerivativeY,filtered.incidentCompression);
if(col==15) return float4(normalize(cross(float3(1,0,0)+filtered.shadingDerivativeX,
- float3(0,1,0)+filtered.shadingDerivativeY)),filtered.compression);
+ float3(0,1,0)+filtered.shadingDerivativeY)),0);
if(col==16) return float4(lod,fftShadingVariance(lod));
if(col==17) return float4(max(abs(filtered.displacement-s.displacement),
max(abs(filtered.derivativeX-s.derivativeX),abs(filtered.derivativeY-s.derivativeY))),
- abs(filtered.compression-s.compression)+abs(filtered.incidentCompression-s.incidentCompression));
-return float4(abs(filtered.generatedRaw-s.generatedRaw),abs(filtered.generatedHeight-s.generatedHeight),
- abs(filtered.vesselHeight-s.vesselHeight),abs(filtered.vesselCrest-s.vesselCrest));}
+ abs(filtered.incidentCompression-s.incidentCompression));
+return float4(0,0,0,abs(filtered.vesselCrest-s.vesselCrest));}
)HLSL";
- if(bowLift) {
+ {
const std::string oldStruct="nointerpolation float4 Registered:TEXCOORD1;";
sampleVS.replace(sampleVS.find(oldStruct),oldStruct.size(),oldStruct+"[[vk::location(2)]] nointerpolation float4 Lifted:TEXCOORD2;");
const std::string oldReturn="return o;}";
@@ -6075,8 +5309,8 @@ o.Lifted=float4(v.xy*(w*d),(v.z*d+added)*w,fftBowLiftFoam(added,w));return o;}
const std::string oldArgument="nointerpolation float4 registered:TEXCOORD1)";
samplePS.replace(samplePS.find(oldArgument),oldArgument.size(),
"nointerpolation float4 registered:TEXCOORD1,[[vk::location(2)]] nointerpolation float4 lifted:TEXCOORD2)");
- const std::string oldChoice="return pixel.x>=36.0?registered:value;";
- samplePS.replace(samplePS.find(oldChoice),oldChoice.size(),"return pixel.x>=40.0?lifted:pixel.x>=36.0?registered:value;");
+ const std::string oldChoice="return pixel.x>=30.0?registered:value;";
+ samplePS.replace(samplePS.find(oldChoice),oldChoice.size(),"return pixel.x>=34.0?lifted:pixel.x>=30.0?registered:value;");
const std::string before="if(col>=36) {";
surfacePS.insert(surfacePS.find(before),R"HLSL(
if(col>=40) {
@@ -6096,7 +5330,7 @@ if(col>=40) {
)HLSL");
}
- if(bowLift) {
+ {
surfacePS.insert(surfacePS.find("if(col>=40) {"),R"HLSL(
if(col==49) return float4(s.contactIncident,0);
if(col==50) {
@@ -6107,39 +5341,10 @@ if(col==50) {
return float4(max(abs(s.contactIncident-incident.contactIncident),abs(ripples.contactIncident)),
length(filtered.contactIncident-s.contactIncident));
}
-)HLSL");
- // Same-fragment bow attribution: actual physical raw composition is checked
- // independently below. The synthetic column only isolates the display helper.
- const std::string before="if(col>=40) {";
- surfacePS.insert(surfacePS.find(before),R"HLSL(
-if(col>=45) {
- float f=.559713426,d=f*saturate(abs(p.x)/28.0),w=.65+.002*p.y;
- float3 df=float3(d,abs(p.x)>0.0 && abs(p.x)<28.0?f/28.0*sign(p.x):0.0,0);
- float3 scale=float3(w*d,w*df.y,.002*d);
- FftSurface q=fftSurface(p.xy,p.z,p.w,scale);
- if(col==45)return float4(fftBowRetentionDebug(q,w,f,d),q.bowLimitedDelta);
- if(col==46) {
- FftSurface noBow=q;noBow.bow=0;noBow.bowLimitedDelta=0;
- return float4(fftBowRetentionDebug(q,w,f,0).y,fftBowRetentionDebug(q,w,d,d).y,
- fftBowRetentionDebug(q,0,f,d).y,fftBowRetentionDebug(noBow,w,f,d).y);
- }
- if(col==47) {
- const float background[10]={-32,-10,-1,0,1,10,32,0,0,0};
- const float bow[10]={64,8,.2,3,8,8,64,0,.000001,8};
- uint row=(uint)pixel.y;float a=background[row],b=bow[row];
- FftSurface synthetic=(FftSurface)0;synthetic.bow=float3(b,0,0);
- synthetic.bowLimitedDelta=fftVerticalBound*(tanh((a+b)/fftVerticalBound)-tanh(a/fftVerticalBound));
- return float4(fftBowRetentionDebug(synthetic,row==0?1.0:.7,1.0,row==0?1.0:.6),synthetic.bowLimitedDelta);
- }
- FftSurface zero=fftSurface(p.xy,p.z,0.0,scale);
- return float4(abs(fftBowRetentionDebug(q,w,f,d)-fftBowRetentionDebug(zero,w,f,d)),
- abs(q.bowLimitedDelta-zero.bowLimitedDelta));
-}
)HLSL");
}
- if(bowShoulder) {
- CHECK(bowLift);
+ {
// Full emitted fftSurface integration. Remove only the incident/reflected field
// difference between physical and filtered maps; generated bow/stern corrections
// must be common to both. The scalar field itself has separate independent CPU
@@ -6156,7 +5361,7 @@ if(col==44) {
FftSurface incident,filtered;
fftRawAndShadingSurface(p.xy,lod,incident,filtered);
float oldBowTotal=0;
- if(FftParameters.y>0.5)for(int h=0;h<clamp((int)HullParameters.x,0,8);++h) {
+ for(int h=0;h<clamp((int)HullParameters.x,0,8);++h) {
VesselReflection r=vesselReflection(p.xy,p.z,h);
if(r.weight>0.0) {
FftSurface a,b;fftRawAndShadingSurface(r.samplePosition,lod,a,b);
@@ -6199,7 +5404,7 @@ if(col==44) {
info.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;info.target_info.color_target_descriptions=&colour;info.target_info.num_color_targets=1;
resources.pipelines[stage]=SDL_CreateGPUGraphicsPipeline(resources.device,&info);CHECK(resources.pipelines[stage]);if(!resources.pipelines[stage]) return;
}
- SdlWaterPixelConstants water={};water.FftParameters[0]=water.FftParameters[1]=1;water.WaterParameters[0]=4;
+ SdlWaterPixelConstants water={};water.FftParameters[0]=1;water.WaterParameters[0]=4;
WaterHullModel::Hull hull;hull.data[0][2]=7;hull.data[0][3]=4;hull.data[1][0]=1;hull.data[1][2]=20;hull.data[1][3]=6;
hull.data[2][2]=.23f;hull.data[2][3]=sqrtf(436.0f);hull.data[3][0]=-20;hull.data[3][2]=20;
const float outline[8]={-20,-6,20,-6,20,6,-20,6};memcpy(hull.data[4],outline,sizeof(outline));
@@ -6207,7 +5412,7 @@ if(col==44) {
// not from copying the production derivative/Jacobian expressions.
auto smooth=[](double a,double b,double x) {const double t=(std::max)(0.0,(std::min)(1.0,(x-a)/(b-a)));return t*t*(3-2*t);};
// Separate scalar contour oracle from WaterBowShoulderTest: no production query,
- // gradient or registration helper. Keep the first two legacy invocations unchanged.
+ // gradient or registration helper.
auto shoulderScalar=[&](double x,double y,double halfLength) {
WaterHullModel::Hull selected=hull;selected.data[0][2]=7;selected.data[0][3]=4;
selected.data[1][2]=float(halfLength);selected.data[2][3]=float(std::hypot(halfLength,6.0));
@@ -6222,23 +5427,18 @@ if(col==44) {
const double arms=gaussian(across-width,strip)*std::cos((across-width)*.40)+gaussian(across+width,strip)*std::cos((across+width)*.40);
const double churn=gaussian(across,3.3)*std::sin(along*.30-4*1.15+.23*6.2831853)*.24;
const double trail=smooth(0,10,along)*(1-smooth(length*.5,length,along));
- const double bow=bowShoulder?0.0:vessel_test_pressure(x-halfLength,y,6,12);
const double radius=std::sqrt(halfLength*halfLength+36);
- return (trail*(arms*1.35+churn)*smooth(.3,14,12)+bow)*(1-smooth(radius+80,radius+110,std::hypot(x,y)))+
- (bowShoulder?shoulderScalar(x,y,halfLength):0.0);
+ return (trail*(arms*1.35+churn)*smooth(.3,14,12))*(1-smooth(radius+80,radius+110,std::hypot(x,y)))+
+ shoulderScalar(x,y,halfLength);
};
double maxValue=0,maxDerivative=0,maxNormal=0,maxVertex=0,maxIncident=0;
double registeredStageError=0,registeredChanged=0,registeredPhysicalError=0;
double liftStageError=0,liftHeightError=0,liftGradientError=0,liftBowError=0;
- double bowRetentionError=0,bowLimitedError=0,bowFilterError=0,bowSyntheticError=0;
double contactIncidentError=0;
- unsigned bowCrestControls=0,bowTroughControls=0,bowWithoutLiftControls=0,bowIsolatedControls=0,bowOverEnvelopeControls=0;
double shoulderFilteredError=0,shoulderMissingCorrection=0;unsigned shoulderFilteredControls=0;unsigned liftActive=0,liftZero=0,liftNonconstant=0;
unsigned registeredPhysicalDifferences=0;
- unsigned changedStationary=0,changedMoving=0,changedGradient=0,changedCompression=0;
+ unsigned changedStationary=0,changedMoving=0,changedGradient=0;
unsigned visibleShallowCrests=0;double maxGeneratedFoam=0;
- double maxGeneratedRaw=0,maxGeneratedDelta=0,maxPressureDebug=0,maxRetentionDebug=0;
- unsigned positiveIncidentCases=0,negativeIncidentCases=0,maskedDiagnostics=0;
std::vector<float> baseline,generatedBaseline,flatBaseline,contactBaseline;
double idealSamplerError=0;
double armedAnchorChange=0,maxShadingValue=0,maxShadingDerivative=0,maxShadingNormal=0,maxLod=0,maxVariance=0;
@@ -6247,8 +5447,9 @@ if(col==44) {
double maxSelectedCompression=0,maxFineValue=0,maxFineDerivative=0;
const auto &varianceTable=WaterFftFiltering::SpectrumVariance();
for(unsigned scenario=0;scenario<18;++scenario) {
- const bool enabled=scenario!=3,hasHull=scenario!=0,moving=scenario==2 || scenario==3 || scenario==5 || scenario>=6;
- const bool applicable=hasHull && enabled && scenario!=4,flat=scenario>=6;
+ if(scenario==3)continue; // former vessel-wave disable mode was removed
+ const bool hasHull=scenario!=0,moving=scenario==2 || scenario==5 || scenario>=6;
+ const bool applicable=hasHull && scenario!=4,flat=scenario>=6;
const bool contact=scenario==7 || scenario==8 || scenario==10 || scenario==11 || scenario==12;
const bool lastSlot=scenario==5 || scenario==11;
if(scenario==6) {std::fill(fields.begin(),fields.end(),0);if(!upload()) return;}
@@ -6257,14 +5458,14 @@ if(col==44) {
for(unsigned pixel=0;pixel<side*side;++pixel)fields[pixel*4+1]=scenario==16?.5f:-.5f;
if(!upload())return; // exactly +10/-10 world-unit incident height, zero derivatives
}
- water.FftParameters[1]=enabled?1:0;water.HullParameters[0]=hasHull?(lastSlot?8:1):0;
+ water.HullParameters[0]=hasHull?(lastSlot?8:1):0;
water.SunColour[0]=water.SunColour[1]=water.SunColour[2]=scenario==8?1.0f:0.0f;
memset(water.HullData,0,sizeof(water.HullData));hull.data[2][0]=moving?12:0;hull.data[0][2]=scenario==4?8:7;
memset(water.ContactHullData,0,sizeof(water.ContactHullData));
const float meanLength=scenario==8 || scenario==9?11.0f:20.0f;
hull.data[1][2]=meanLength;hull.data[2][3]=sqrtf(meanLength*meanLength+36);
hull.data[3][0]=-meanLength;hull.data[3][2]=meanLength;
- if(bowShoulder) {
+ {
const float contour[8]={-meanLength,-6,meanLength,-6,meanLength,6,-meanLength,6};
memcpy(hull.data[4],contour,sizeof(contour));
}
@@ -6272,7 +5473,7 @@ if(col==44) {
if(contact || (scenario>=13 && scenario<=15)) {
WaterHullModel::Hull stable=hull;stable.data[1][2]=28;stable.data[2][3]=sqrtf(820.0f);
stable.data[3][0]=-28;stable.data[3][2]=28;
- if(bowShoulder) {const float contour[8]={-28,-6,28,-6,28,6,-28,6};memcpy(stable.data[4],contour,sizeof(contour));}
+ {const float contour[8]={-28,-6,28,-6,28,6,-28,6};memcpy(stable.data[4],contour,sizeof(contour));}
stable.data[0][2]=scenario==10?8:7;stable.data[0][3]=scenario==13?2:scenario==14?13:scenario==15?0:4;
memcpy(water.ContactHullData+(lastSlot?70:0),&stable,sizeof(stable));
}
@@ -6298,7 +5499,8 @@ if(col==44) {
SDL_EndGPURenderPass(pass);
}
CHECK(SDL_SubmitGPUCommandBuffer(commands));const auto values=read_float_targets(frame,resources.targets,2,columns,rows);
- auto gpu=[&](unsigned row,unsigned col,unsigned c){return double(values[(row*columns+col)*4+c]);};
+ auto columnIndex=[](unsigned column){return column>=49?column-10:column>=12?column-6:column;};
+ auto gpu=[&](unsigned row,unsigned col,unsigned c){return double(values[(row*columns+columnIndex(col))*4+c]);};
auto raw=[&](double x,double y,double out[3],unsigned cascades=3) {
out[0]=out[1]=out[2]=0;if(scenario>=16) {out[2]=scenario==16?10:-10;return;}if(flat) return;
for(unsigned c=0;c<cascades;++c) {
@@ -6308,7 +5510,7 @@ if(col==44) {
out[1]+=20*chop[c]*amplitude[c]*modes[c][1]/length*std::sin(a);out[2]+=20*amplitude[c]*std::cos(a);
}
};
- auto surface=[&](double x,double y,double out[3],bool includeGenerated=true,bool limited=true) {
+ auto surface=[&](double x,double y,double out[3]) {
raw(x,y,out);
if(applicable) {
const double qx=(std::max)(-20.0,(std::min)(20.0,x)),qy=(std::max)(-6.0,(std::min)(6.0,y));
@@ -6318,14 +5520,14 @@ if(col==44) {
double d[3];raw(2*qx-x,2*qy-y,d);const double dot=d[0]*nx+d[1]*ny;
out[0]+=(d[0]-2*nx*dot)*weight;out[1]+=(d[1]-2*ny*dot)*weight;out[2]+=d[2]*weight;
}
- if(includeGenerated && moving && scenario!=10) out[2]+=packet(x,y,contact?28.0:double(meanLength));
+ if(moving && scenario!=10) out[2]+=packet(x,y,contact?28.0:double(meanLength));
}
const double bounds[3]={8/std::sqrt(2.0),8/std::sqrt(2.0),WaterFftGeometry::MaxVerticalDisplacement};
- if(limited)for(unsigned c=0;c<3;++c) out[c]=bounds[c]*std::tanh(out[c]/bounds[c]);
+ for(unsigned c=0;c<3;++c) out[c]=bounds[c]*std::tanh(out[c]/bounds[c]);
};
for(unsigned row=0;row<rows;++row) {
const double x=points[row][0],y=points[row][1];double expected[3],gradient[2][3];surface(x,y,expected);
- if(bowLift) {
+ {
// Columns30/32/33 independently expose the already-verified broad/medium
// raw field. Contact uses its own vertical limiter before vessel additions.
const double v=WaterFftGeometry::MaxVerticalDisplacement;
@@ -6340,10 +5542,10 @@ if(col==44) {
CHECK(gpu(row,50,c)<.000002);
}
if(scenario>0 && !flat) for(unsigned c=0;c<3;++c)
- CHECK(gpu(row,49,c)==baseline[(row*columns+49)*4+c]);
+ CHECK(gpu(row,49,c)==baseline[(row*columns+columnIndex(49))*4+c]);
}
for(unsigned c=0;c<3;++c) {
- const double vertex=values[rows*columns*4+(row*columns+36)*4+c];
+ const double vertex=values[rows*columns*4+(row*columns+columnIndex(36))*4+c];
const double error=std::abs(vertex-gpu(row,36,c));
registeredStageError=(std::max)(registeredStageError,error);CHECK(error<.00002);
registeredPhysicalError=(std::max)(registeredPhysicalError,double(gpu(row,39,c)));
@@ -6353,11 +5555,11 @@ if(col==44) {
}
CHECK(gpu(row,39,3)==0);
registeredChanged=(std::max)(registeredChanged,std::abs(gpu(row,36,2)-gpu(row,0,2)));
- if(bowLift) {
+ {
const double free=.559713426,mean=free*(std::min)(1.0,std::abs(x)/28.0),weight=.65+.002*y;
const double bound=WaterFftGeometry::MaxVerticalDisplacement;
for(unsigned c=0;c<4;++c) {
- const double vertex=values[rows*columns*4+(row*columns+40)*4+c];
+ const double vertex=values[rows*columns*4+(row*columns+columnIndex(40))*4+c];
const double error=std::abs(vertex-gpu(row,40,c));liftStageError=(std::max)(liftStageError,error);CHECK(error<.00003);
}
CHECK(std::abs(gpu(row,40,2))<=free*weight*bound+.000003);
@@ -6377,8 +5579,8 @@ if(col==44) {
// derivative, registration helper or production lift helper is reused.
auto bow=[&](double px,double py) {
if(!applicable || !moving || scenario==10)return 0.0;
- const double length=contact?28.0:double(meanLength),radius=std::hypot(length,6.0);
- return bowShoulder?shoulderScalar(px,py,length):vessel_test_pressure(px-length,py,6,12)*(1-smooth(radius+80,radius+110,std::hypot(px,py)));
+ const double length=contact?28.0:double(meanLength);
+ return shoulderScalar(px,py,length);
};
auto composed=[&](double px,double py) {
double current[3];surface(px,py,current);
@@ -6391,47 +5593,6 @@ if(col==44) {
double independent[3];surface(x,y,independent);
const double expectedBow=bow(x+independent[0]*weight*mean,y+independent[1]*weight*mean);
const double expectedHeight=composed(x,y);
- // Independently reconstruct RAW incident + reflection + stern + old
- // bow from known modes, then replace only the bow at registered XY.
- // Do not invert the limited GPU result or reuse its bow accumulator.
- double rawTotal[3];surface(x,y,rawTotal,true,false);
- const double background=rawTotal[2]-bow(x,y);
- const double limitedDelta=bound*(std::tanh((background+expectedBow)/bound)-std::tanh(background/bound));
- const double marginal=weight*(mean*limitedDelta+(free-mean)*bound*std::tanh(expectedBow/bound));
- const double expectedRGB[3]={expectedBow/8,marginal/bound,weight*free};
- const double tolerance=flat?.00003:.004; // existing independent known-map precision
- bowLimitedError=(std::max)(bowLimitedError,std::abs(limitedDelta-gpu(row,45,3)));
- CHECK(std::abs(limitedDelta-gpu(row,45,3))<tolerance);
- for(unsigned c=0;c<3;++c) {
- const double error=std::abs(expectedRGB[c]-gpu(row,45,c));
- bowRetentionError=(std::max)(bowRetentionError,error);CHECK(error<tolerance);
- }
- CHECK(gpu(row,45,1)>=0 && gpu(row,45,1)<=weight*(free+mean)+.000003);
- const double dZero=weight*free*std::tanh(expectedBow/bound);
- const double freeEqualsD=weight*mean*limitedDelta/bound;
- CHECK(std::abs(gpu(row,46,0)-dZero)<tolerance);
- CHECK(std::abs(gpu(row,46,1)-freeEqualsD)<tolerance);
- CHECK(gpu(row,46,2)==0 && gpu(row,46,3)==0);
- for(unsigned c=0;c<4;++c) {
- bowFilterError=(std::max)(bowFilterError,gpu(row,48,c));CHECK(gpu(row,48,c)<.000001);
- }
- if(expectedBow>.01) {
- bowCrestControls+=scenario==16;bowTroughControls+=scenario==17;
- bowWithoutLiftControls+=std::abs(marginal-weight*mean*limitedDelta)>.001;
- bowIsolatedControls+=std::abs(marginal-weight*free*bound*std::tanh(expectedBow/bound))>.001;
- }
- const double a[10]={-32,-10,-1,0,1,10,32,0,0,0};
- const double b[10]={64,8,.2,3,8,8,64,0,.000001,8};
- const double sw=row==0?1.:.7,sd=row==0?1.:.6;
- const double delta=bound*(std::tanh((a[row]+b[row])/bound)-std::tanh(a[row]/bound));
- const double synthetic[4]={b[row]/8,sw*(sd*delta/bound+(1-sd)*std::tanh(b[row]/bound)),sw,delta};
- for(unsigned c=0;c<4;++c) {
- const double error=std::abs(synthetic[c]-gpu(row,47,c));
- bowSyntheticError=(std::max)(bowSyntheticError,error);CHECK(error<.00001);
- }
- // The final total is bounded, but marginal trough-to-crest rise is
- // not bounded by the blue envelope (nor by 1 before display clamp).
- if(row==0) {CHECK(gpu(row,47,1)>1.9 && gpu(row,47,1)>gpu(row,47,2));++bowOverEnvelopeControls;}
liftBowError=(std::max)(liftBowError,std::abs(expectedBow-gpu(row,41,3)));
liftHeightError=(std::max)(liftHeightError,std::abs(expectedHeight-gpu(row,40,2)));
// Nonconstant ideal Fourier modes differ slightly from sampled
@@ -6449,7 +5610,7 @@ if(col==44) {
}
}
}
- if(bowShoulder) {
+ {
for(unsigned c=0;c<3;++c) {
shoulderFilteredError=(std::max)(shoulderFilteredError,gpu(row,44,c));
CHECK(gpu(row,44,c)<.00003);
@@ -6513,7 +5674,7 @@ if(col==44) {
pairedError=(std::max)(pairedError,std::abs(gpu(row,column,c)));CHECK(gpu(row,column,c)==0);
}
if(scenario==0) for(unsigned c=0;c<3;++c)armedReuse+=gpu(row,29,c)>.001;
- CHECK(gpu(row,13,3)==gpu(row,2,3) && gpu(row,14,3)==gpu(row,3,3) && gpu(row,15,3)==gpu(row,0,3));
+ CHECK(gpu(row,13,3)==gpu(row,2,3) && gpu(row,14,3)==gpu(row,3,3));
CHECK(gpu(row,12,3)>=0);
if(row<=1 || flat) {
for(unsigned c=0;c<3;++c) {
@@ -6544,32 +5705,6 @@ if(col==44) {
}
const double generated=applicable && moving && scenario!=10?packet(x,y,contact?28.0:double(meanLength)):0;
const double expectedCrest=(std::min)(1.0,(std::max)(0.0,generated)*.32);
- double without[3];surface(x,y,without,false);
- const double generatedDelta=expected[2]-without[2],bound=WaterFftGeometry::MaxVerticalDisplacement;
- const double isolated=bound*std::tanh(generated/bound),damping=WaterFftGeometry::SafeDamping(1,4);
- const double coverage=expectedCrest*.65*smooth(.15,.65,damping);
- const double rawError=std::abs(gpu(row,6,0)-generated),deltaError=std::abs(gpu(row,6,1)-generatedDelta);
- maxGeneratedRaw=(std::max)(maxGeneratedRaw,rawError);maxGeneratedDelta=(std::max)(maxGeneratedDelta,deltaError);
- CHECK(rawError<.00001 && deltaError<(flat?.00001:.0015));
- CHECK(std::abs(gpu(row,6,2)-isolated)<.00001);
- const double pressure[3]={(std::max)(0.0,generated)/8,(std::max)(0.0,generatedDelta)*damping/3.85,coverage};
- const bool mask=generated>.0001;
- const double retention[3]={mask?1-(std::max)(0.0,(std::min)(1.0,generatedDelta/(std::max)(isolated,.000001))):0,mask?damping:0,mask?coverage:0};
- for(unsigned c=0;c<3;++c) {
- const double pressureError=std::abs(gpu(row,7,c)-pressure[c]),retentionError=std::abs(gpu(row,8,c)-retention[c]);
- maxPressureDebug=(std::max)(maxPressureDebug,pressureError);maxRetentionDebug=(std::max)(maxRetentionDebug,retentionError);
- CHECK(pressureError<.0003 && retentionError<.003);
- CHECK(gpu(row,11,c)==0);++maskedDiagnostics;
- if(!mask)CHECK(gpu(row,8,c)==0);
- }
- for(unsigned col:{9u,10u}) {
- CHECK(std::abs(gpu(row,col,0)-pressure[0])<.00001);
- CHECK(gpu(row,col,1)==0 && gpu(row,col,2)==0);
- }
- if(scenario>=16 && generated>.01) {
- CHECK(generatedDelta>0 && generatedDelta<isolated*.6 && gpu(row,8,0)>.4);
- if(scenario==16)++positiveIncidentCases;else ++negativeIncidentCases;
- }
CHECK(std::abs(gpu(row,2,3)-expectedCrest)<.00001);
for(unsigned c=0;c<2;++c) {
const double damping=WaterFftGeometry::SafeDamping(1,c?2.25f:4.0f);
@@ -6615,30 +5750,24 @@ if(col==44) {
for(unsigned col=1;col<=2;++col) for(unsigned c=0;c<3;++c)
difference=(std::max)(difference,std::abs(gpu(row,col,c)-baseline[(row*columns+col)*4+c]));
changedGradient+=difference>.001;
- changedCompression+=std::abs(gpu(row,0,3)-gpu(row,3,3))>.001;
}
if(flat) changedMoving+=std::abs(gpu(row,0,2))>.01;
}
for(float v:values) CHECK(std::isfinite(v));
if(scenario==0) baseline=values;
if(scenario==2) generatedBaseline=values;
- if(scenario==3 || scenario==4) {
+ if(scenario==4) {
double previousMaximum=0,newMaximum=0;unsigned mismatches=0;
for(size_t i=0;i<values.size();++i)if(values[i]!=baseline[i]) {
const double error=std::abs(double(values[i])-baseline[i]);
- if(i/4%columns<36)previousMaximum=(std::max)(previousMaximum,error);else newMaximum=(std::max)(newMaximum,error);
+ if(i/4%columns<columnIndex(36))previousMaximum=(std::max)(previousMaximum,error);else newMaximum=(std::max)(newMaximum,error);
++mismatches;
}
printf("registered disabled scenario%u previous/new maxima %.9g / %.9g, mismatches%u\n",scenario,previousMaximum,newMaximum,mismatches);
- // Retain the previous 36-column exact contract. Registered evaluations
+ // Retain the physical-field exact contract. Registered evaluations
// permit <1e-6 world units for differently optimized uniform branches;
// observed maxima were 4.77e-7, not a change to their physical model.
- // The new shoulder shader's enabled/count-zero path and disabled/count-one
- // path have identical scalar fields but differ by 2.39e-7 on this GPU.
- // Preserve both old exact contracts and the wrong-level exact comparison;
- // bound only this new inactive-path comparison at registered-map precision.
- if(bowShoulder && scenario==3)CHECK(previousMaximum<.000001);
- else CHECK(previousMaximum==0);
+ CHECK(previousMaximum==0);
CHECK(newMaximum<.000001);
}
if(scenario==5) CHECK(values==generatedBaseline);
@@ -6648,22 +5777,20 @@ if(col==44) {
if(scenario==8) {
// Contact packet remains exact while the mean hull changes. Its incident
// reflection variance is allowed to follow that changed mean-hull bound.
- for(size_t i=0;i<values.size();++i)if(!(i/4%columns==12 && i%4==3))CHECK(values[i]==contactBaseline[i]);
+ for(size_t i=0;i<values.size();++i)if(!(i/4%columns==columnIndex(12) && i%4==3))CHECK(values[i]==contactBaseline[i]);
}
if(scenario==9)for(unsigned row=0;row<rows;++row)
armedAnchorChange=(std::max)(armedAnchorChange,std::abs(double(values[row*columns*4+2])-flatBaseline[row*columns*4+2]));
if(scenario>=13 && scenario<=15)CHECK(values==flatBaseline);
}
- if(bowLift) printf("contact incident: broad/medium limiter and gradients; fine/reflection/generated/footprint isolation maximum %.9g\n",contactIncidentError);
- if(bowShoulder) {
+ printf("contact incident: broad/medium limiter and gradients; fine/reflection/generated/footprint isolation maximum %.9g\n",contactIncidentError);
+ {
CHECK(shoulderFilteredControls>5 && shoulderMissingCorrection>.05);
- printf("sdl_gpu_frame_selfcheck: full contour shoulder FFT integration: physical/filtered generated correction %.9g, armed omitted-filter correction %.9g (%u cases); actual VertexSource(true,true)/PixelSource(true,true), known Fourier modes, varying weight/damping, zero chop, fallback/contact/last-slot and independent scalar/derivative/foam checks retained\n",shoulderFilteredError,shoulderMissingCorrection,shoulderFilteredControls);
+ printf("sdl_gpu_frame_selfcheck: full contour shoulder FFT integration: physical/filtered generated correction %.9g, armed omitted-filter correction %.9g (%u cases); actual production vertex/pixel source, known Fourier modes, varying weight/damping, zero chop, fallback/contact/last-slot and independent scalar/derivative/foam checks retained\n",shoulderFilteredError,shoulderMissingCorrection,shoulderFilteredControls);
}
- if(bowLift) {
+ {
CHECK(liftActive>5 && liftZero>20 && liftNonconstant>1);
- CHECK(bowCrestControls>0 && bowTroughControls>0 && bowWithoutLiftControls>0 && bowIsolatedControls>0 && bowOverEnvelopeControls==18);
- printf("sdl_gpu_frame_selfcheck: bow retention physical raw decomposition: RGB %.9g/limited marginal %.9g, helper %.9g, filtered identity %.9g; crest/trough %u/%u, omitted-lift %u, isolated-peak %u, G>envelope controls %u; zero bow/weight, F=D and D=0 checked\n",bowRetentionError,bowLimitedError,bowSyntheticError,bowFilterError,bowCrestControls,bowTroughControls,bowWithoutLiftControls,bowIsolatedControls,bowOverEnvelopeControls);
- printf("sdl_gpu_frame_selfcheck: optional bow lift actual FFT VS/PS %.9g, independent bow %.9g/height %.9g/finite-difference derivative %.9g; active %u, exact zero %u and nonconstant derivative controls %u, floor bound, physical filtering and actual-height foam checked\n",liftStageError,liftBowError,liftHeightError,liftGradientError,liftActive,liftZero,liftNonconstant);
+ printf("sdl_gpu_frame_selfcheck: bow lift actual FFT VS/PS %.9g, independent bow %.9g/height %.9g/finite-difference derivative %.9g; active %u, exact zero %u and nonconstant derivative controls %u, floor bound, physical filtering and actual-height foam checked\n",liftStageError,liftBowError,liftHeightError,liftGradientError,liftActive,liftZero,liftNonconstant);
}
CHECK(registeredChanged>.001);
printf("sdl_gpu_frame_selfcheck: registered physical footprint comparison max %.9g across %u nonzero values\n",registeredPhysicalError,registeredPhysicalDifferences);
@@ -6672,16 +5799,14 @@ if(col==44) {
// control; the observed maximum is 2.27e-7. Raw generated terms remain exact.
CHECK(registeredPhysicalError<.000001);
printf("sdl_gpu_frame_selfcheck: registered bow texture/stage parity %.8g, armed coordinate displacement %.8g; physical footprint agreement <1e-6, exact flat-chop identity and bounds checked\n",registeredStageError,registeredChanged);
- CHECK(changedStationary>=3 && changedGradient>=3 && changedCompression>=2 && changedMoving>=2 && armedAnchorChange>.2);
+ CHECK(changedStationary>=3 && changedGradient>=3 && changedMoving>=2 && armedAnchorChange>.2);
CHECK(visibleShallowCrests>10);CHECK(filteredChanged>=5 && preservedPacket>=20);CHECK(armedReuse>=5);
CHECK(armedFineBreaking>=5 && broadBreaking>=5 && mediumBreaking>=5 && physicalFineSamples>=5);
printf("sdl_gpu_frame_selfcheck: FFT breaking scale: coarse/medium limiter error %.9f; fine-only compression exactly1 with %u physical ripple samples, %u armed old fine-breaking controls and %u/%u broad/medium responses; independent fine value %.9f/derivative %.9f, full physical/vessel/reflection checks retained\n",maxSelectedCompression,physicalFineSamples,armedFineBreaking,broadBreaking,mediumBreaking,maxFineValue,maxFineDerivative);
printf("sdl_gpu_frame_selfcheck: FFT paired sampling reuse: bit-exact displacement/derivatives at arbitrary, negative-wrapped and real mirrored queries with zero/mixed/all positive LOD; maxdifference %.9f, armed missing-filter controls %u\n",pairedError,armedReuse);
- printf("sdl_gpu_frame_selfcheck: FFT footprint filtering: sampled-channel value %.9f/tangent %.9f/normal %.9f, LOD %.9f/variance %.9f; %u changed components, %u constant-field packet samples preserved, all physical/diagnostic outputs bit-exact across footprints0..8192; arbitrary-coordinate ideal sampler discrepancy %.9f reported separately\n",maxShadingValue,maxShadingDerivative,maxShadingNormal,maxLod,maxVariance,filteredChanged,preservedPacket,idealSamplerError);
- CHECK(positiveIncidentCases>=3 && negativeIncidentCases>=3 && maskedDiagnostics==18*rows*3);
- printf("sdl_gpu_frame_selfcheck: GPU pressure diagnostics: raw %.8f, generated-only limited delta %.8f, pressure RGB %.8f, retention RGB %.8f; independent with/without-generated composition, +10/-10 incident cases %u/%u, zero/negative/tiny-footprint masks %u and zero weight/damping checked\n",maxGeneratedRaw,maxGeneratedDelta,maxPressureDebug,maxRetentionDebug,positiveIncidentCases,negativeIncidentCases,maskedDiagnostics);
+ printf("sdl_gpu_frame_selfcheck: FFT footprint filtering: sampled-channel value %.9f/tangent %.9f/normal %.9f, LOD %.9f/variance %.9f; %u changed components, %u constant-field packet samples preserved, all physical outputs bit-exact across footprints0..8192; arbitrary-coordinate ideal sampler discrepancy %.9f reported separately\n",maxShadingValue,maxShadingDerivative,maxShadingNormal,maxLod,maxVariance,filteredChanged,preservedPacket,idealSamplerError);
printf("sdl_gpu_frame_selfcheck: GPU generated vessel foam: independent packet-crest/coverage error %.8f, %u active depth4/2.25 samples; rest/disabled/zero weight/zero hull damping, bounded inputs, unchanged coverage under changed sunlight checked\n",maxGeneratedFoam,visibleShallowCrests);
- printf("sdl_gpu_frame_selfcheck: GPU FFT-vessel composition: 18 known-mode/constant atlases, value %.8f/gradient %.8f/normal %.8f/VS-PS %.8f/incident compression %.8f; coarse+medium incident compression, stable contact packet despite changing mean slice, armed old-anchor height jump %.8f, independent curved-pressure/stern reference, contact level/pause/final-slot/count0/2/13 fallback, stationary reflection and bounds checked\n",maxValue,maxDerivative,maxNormal,maxVertex,maxIncident,armedAnchorChange);
+ printf("sdl_gpu_frame_selfcheck: GPU FFT-vessel composition: 17 known-mode/constant atlases, value %.8f/gradient %.8f/normal %.8f/VS-PS %.8f/incident compression %.8f; coarse+medium incident compression, stable contact packet despite changing mean slice, armed old-anchor height jump %.8f, independent contour-bow/stern reference, contact level/pause/final-slot/count0/2/13 fallback, stationary reflection and bounds checked\n",maxValue,maxDerivative,maxNormal,maxVertex,maxIncident,armedAnchorChange);
}
// Direct O(N^2) Fourier sum at a few points: deliberately independent of GPU butterfly ordering,
@@ -6902,272 +6027,6 @@ static unsigned int mismatches(const std::vector<uint8_t> &got, const uint16_t (
return bad;
}
-// Execute the actual generated integration, including UV0 residual and screen-to-world
-// derivatives. Field sampling is controlled here; native terrain/mesh sampling is separate.
-static void check_gpu_water_coastal_crest_injection(SdlGpuFrame *frame,const std::string &production)
-{
- auto block=[&](const char *first,const char *last) {
- const size_t a=production.find(first),b=a==std::string::npos?std::string::npos:production.find(last,a);
- CHECK(a!=std::string::npos && b!=std::string::npos);
- return a!=std::string::npos && b!=std::string::npos?production.substr(a,b-a):std::string();
- };
- const std::string composition=block(" float determinant = parameterDx.x", " WaveCage cage=waveCage(");
- const std::string gradient=block("float2 fftParameterGradient(", "\n}")+"\n}\n";
- const std::string metadata=block(" float meshCorrection=OpticalParameters.w", " float2 materialUV=");
- const std::string offshoreSource=block(" float offshore = opticalContext.r", " // The mesh and this derivative");
- CHECK(composition.find("slope+=coastalCorrection.yz;meshCorrection+=coastalCorrection.x;")!=std::string::npos);
- if(composition.empty() || metadata.empty() || offshoreSource.empty() || gradient.size()<10)return;
- const std::string shore=WaterShoreFoam::Source(),crest=WaterCoastalCrest::Source();
- CHECK(production.find(shore)!=std::string::npos && production.find(crest)!=std::string::npos);
- // Each scenario occupies four raster rows so every derivative quad stays in one case.
- // The two eight-pixel output tiles have identical parameter fields and return height/
- // slopes/residual and normal separately. All test fields vary in world, not screen, axes.
- struct Query {float f[8][4];};
- Query ordinary={{{1.7f,-2.3f,0,1},{20,.25f,.11f,.31f},{2,.75f,.65f,.9f},{1,1,0,0},
- {.013f,-.008f,.03f,-.025f},{.003f,-.002f,.021f,.017f},{.04f,-.03f,.005f,-.002f},{.004f,.003f,-.001f,.002f}}};
- auto broad=[](double x,double y,double time) {
- double value=0;
- for(unsigned i=0;i<WaterShoreFoam::ModeCount;++i) {
- const auto &m=WaterShoreFoam::Modes[i];
- const double phase=x*m.kx+y*m.ky-time*m.omega+m.phase;
- value+=m.amplitude*(std::sin(phase)+.13*std::sin(2*phase));
- }
- return value;
- };
- float crestTime=-1,troughTime=-1;
- for(unsigned i=0;i<600 && (crestTime<0 || troughTime<0);++i) {
- const double value=broad(ordinary.f[0][0],ordinary.f[0][1],i/30.);
- if(crestTime<0 && value>1)crestTime=float(i)/30;
- if(troughTime<0 && value<-1)troughTime=float(i)/30;
- }
- CHECK(crestTime>=0 && troughTime>=0);if(crestTime<0 || troughTime<0)return;
- ordinary.f[0][2]=crestTime;
- std::vector<Query> queries(14,ordinary);
- queries[1].f[1][3]=-.27f;queries[1].f[5][2]=-.019f;queries[1].f[5][3]=.029f; // signed collar residual
- queries[2].f[2][0]=.45f; // varying depth inside the wet gate
- queries[3].f[1][2]=.95f; // obstacle restoration gain closed
- queries[4].f[2][1]=0;queries[4].f[6][2]=queries[4].f[6][3]=0;
- queries[5].f[2][2]=0;queries[5].f[7][0]=queries[5].f[7][1]=0;
- queries[6].f[3][3]=.2f; // nonzero offshore
- queries[7].f[3][2]=1; // river
- queries[8].f[3][0]=0; // missing optical context
- queries[9].f[3][1]=0; // missing terrain texture
- queries[10].f[0][2]=troughTime;
- queries[11].f[2][0]=.1f;queries[11].f[6][0]=queries[11].f[6][1]=0;
- queries[12].f[0][3]=0; // metadata gate off; crest still active
- queries[13].f[1][3]=0;queries[13].f[5][2]=queries[13].f[5][3]=0;
- const unsigned width=16,height=unsigned(queries.size())*4;
- CHECK(queries.size()*sizeof(Query)<=4096);if(queries.size()*sizeof(Query)>4096)return;
- std::string ps="struct Query{float4 f[8];};cbuffer CoastComposition:register(b0){Query Queries["+std::to_string(queries.size())+"];};\n"
- "struct Input{float4 Diffuse;float2 TexCoord0;};\n"+shore+crest+gradient+R"COAST(
-float4 main(float4 pixel:SV_Position):SV_Target0 {
- uint row=(uint)pixel.y/4;Query q=Queries[row];
- float2 tile=float2((uint)pixel.x%8,(uint)pixel.y%4);
- float2 offset=tile.x*float2(.35,.11)+tile.y*float2(-.09,.29);
- float2 wavePosition=q.f[0].xy+offset;
- float2 parameterDx=ddx(wavePosition),parameterDy=ddy(wavePosition);
- float time=q.f[0].z;
- float4 OpticalParameters=float4(0,0,q.f[3].x,q.f[0].w);
- float4 TerrainParameters=float4(0,0,0,q.f[3].y);
- float4 WaterParameters=float4(time,q.f[3].z,0,0);
- float baseLevel=q.f[1].x+dot(q.f[4].xy,offset);
- float attenuation=q.f[1].z+dot(q.f[5].xy,offset);
- float surfaceTerrainHeight=baseLevel-(q.f[2].x+dot(q.f[6].xy,offset));
- float4 opticalContext=float4(q.f[3].w,0,q.f[2].z+dot(q.f[7].xy,offset),q.f[2].y+dot(q.f[6].zw,offset));
- Input input;input.Diffuse=float4(q.f[2].w+dot(q.f[7].zw,offset),0,0,1);
- input.TexCoord0=float2(q.f[1].w+dot(q.f[5].zw,offset),0);
- float3 wave=float3(q.f[1].y+dot(q.f[4].zw,offset),q.f[4].zw);
- float3 legacyWave=wave,oceanWave=wave;
-)COAST"+metadata+offshoreSource+composition+R"COAST(
- if(pixel.x<8)return float4(continuousHeight,slope,meshCorrection);
- return float4(normal,1);
-}
-)COAST";
- const bool placed=sdl3target_detail::place_registers(ps,false);CHECK(placed);if(!placed)return;
- const char *vs="float4 main(uint id:SV_VertexID):SV_Position{return float4(id==1?3.0:-1.0,id==2?3.0:-1.0,0,1);}";
- struct Resources {
- SDL_GPUDevice*device;SDL_GPUShader*vs=nullptr,*ps=nullptr;SDL_GPUGraphicsPipeline*pipeline=nullptr;SDL_GPUTexture*target=nullptr;
- ~Resources(){if(target)SDL_ReleaseGPUTexture(device,target);if(pipeline)SDL_ReleaseGPUGraphicsPipeline(device,pipeline);
- if(vs)SDL_ReleaseGPUShader(device,vs);if(ps)SDL_ReleaseGPUShader(device,ps);}
- }r;r.device=frame->Device();std::vector<unsigned char>spirv;std::string error;
- bool ok=SDL3_Compile_HLSL_To_SPIRV(vs,true,spirv,error);CHECK(ok);if(!ok)return;
- r.vs=SDL3_Create_Shader(r.device,spirv,true,error);CHECK(r.vs);if(!r.vs)return;
- ok=SDL3_Compile_HLSL_To_SPIRV(ps,false,spirv,error);CHECK(ok);if(!ok){printf("coastal injection PS: %s\n",error.c_str());return;}
- unsigned samplers=0,buffers=0;SDL3_Shader_Slots(spirv,false,samplers,buffers);CHECK(samplers==0&&buffers==1);if(samplers!=0||buffers!=1)return;
- r.ps=SDL3_Create_Shader(r.device,spirv,false,error);CHECK(r.ps);if(!r.ps)return;
- SDL_GPUColorTargetDescription colour={};colour.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
- SDL_GPUGraphicsPipelineCreateInfo pi={};pi.vertex_shader=r.vs;pi.fragment_shader=r.ps;pi.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;
- pi.target_info.color_target_descriptions=&colour;pi.target_info.num_color_targets=1;
- r.pipeline=SDL_CreateGPUGraphicsPipeline(r.device,&pi);CHECK(r.pipeline);if(!r.pipeline)return;
- SDL_GPUTextureCreateInfo ti={};ti.type=SDL_GPU_TEXTURETYPE_2D;ti.format=colour.format;ti.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;
- ti.width=width;ti.height=height;ti.layer_count_or_depth=ti.num_levels=1;r.target=SDL_CreateGPUTexture(r.device,&ti);CHECK(r.target);if(!r.target)return;
- CHECK(frame->Flush());
- auto render=[&](){SDL_GPUCommandBuffer*cmd=SDL_AcquireGPUCommandBuffer(r.device);CHECK(cmd);if(!cmd)return std::vector<float>();
- SDL_GPUColorTargetInfo target={};target.texture=r.target;target.load_op=SDL_GPU_LOADOP_DONT_CARE;target.store_op=SDL_GPU_STOREOP_STORE;
- SDL_GPURenderPass*pass=SDL_BeginGPURenderPass(cmd,&target,1,nullptr);CHECK(pass);if(!pass){SDL_CancelGPUCommandBuffer(cmd);return std::vector<float>();}
- SDL_BindGPUGraphicsPipeline(pass,r.pipeline);SDL_PushGPUFragmentUniformData(cmd,0,queries.data(),unsigned(queries.size()*sizeof(Query)));
- SDL_DrawGPUPrimitives(pass,3,1,0,0);SDL_EndGPURenderPass(pass);CHECK(SDL_SubmitGPUCommandBuffer(cmd));return read_float_targets(frame,&r.target,1,width,height);};
- const auto actual=render(),repeat=render();CHECK(actual==repeat&&actual.size()==width*height*4);if(actual.size()!=width*height*4)return;
- auto scalar=[&](const Query&q,double ox,double oy,double &addition,double &residual) {
- auto unit=[](double x){return (std::max)(0.,(std::min)(1.,x));};
- auto smooth=[&](double a,double b,double x){const double t=unit((x-a)/(b-a));return t*t*(3-2*t);};
- const double base=q.f[1][0]+q.f[4][0]*ox+q.f[4][1]*oy;
- const double wave=q.f[1][1]+q.f[4][2]*ox+q.f[4][3]*oy;
- const double damping=q.f[1][2]+q.f[5][0]*ox+q.f[5][1]*oy;
- const double depth=q.f[2][0]+q.f[6][0]*ox+q.f[6][1]*oy;
- const double support=q.f[2][1]+q.f[6][2]*ox+q.f[6][3]*oy;
- const double exposure=q.f[2][2]+q.f[7][0]*ox+q.f[7][1]*oy;
- const double obstacle=q.f[2][3]+q.f[7][2]*ox+q.f[7][3]*oy;
- const double h=broad(q.f[0][0]+ox,q.f[0][1]+oy,q.f[0][2]);
- residual=q.f[0][3]>.5?q.f[1][3]+q.f[5][2]*ox+q.f[5][3]*oy:0;
- addition=0;
- const double offshore=q.f[3][3]*q.f[3][0]*(1-q.f[3][2]);
- if(q.f[3][0]>.5 && q.f[3][1]>.5 && q.f[3][2]<.5 && offshore==0 && support>0 && exposure>0 && h>0 && depth>double(WaterShoreFoam::MinDepth)) {
- const double clearance=depth-double(WaterShoreFoam::MinDepth);
- const double gain=(std::max)(0.,unit(obstacle)-double(.5f/255.f)-unit(damping));
- addition=unit(support)*unit(exposure)*smooth(WaterShoreFoam::MinDepth,WaterShoreFoam::WetDepth,depth)*gain
- *clearance*std::tanh(h/clearance)*smooth(0,WaterShoreFoam::CrestHeight,h);
- }
- return base+wave*damping+residual+addition;
- };
- double maximum=0,omittedHeight=0,duplicateHeight=0,omittedResidual=0;unsigned active=0,inactive=0;
- for(unsigned c=0;c<queries.size();++c)for(unsigned y=0;y<4;++y)for(unsigned x=0;x<8;++x) {
- const Query&q=queries[c];const double ox=x*.35-y*.09,oy=x*.11+y*.29;
- double addition=0,residual=0;const double h=scalar(q,ox,oy,addition,residual);
- auto heightAt=[&](double px,double py){double a=0,r=0;return scalar(q,px,py,a,r);};
- const double gx=(heightAt(ox+1e-4,oy)-heightAt(ox-1e-4,oy))/.0002;
- const double gy=(heightAt(ox,oy+1e-4)-heightAt(ox,oy-1e-4))/.0002;
- const double inverse=1/std::sqrt(1+gx*gx+gy*gy);
- const double expected[8]={h,gx,gy,residual+addition,-gx*inverse,-gy*inverse,inverse,1};
- for(unsigned channel=0;channel<8;++channel) {
- const unsigned index=((c*4+y)*width+x+(channel>=4?8:0))*4+channel%4;
- const double error=std::abs(double(actual[index])-expected[channel]);maximum=(std::max)(maximum,error);
- if(!(std::isfinite(actual[index])&&error<.0001))printf("coastal injection case%u xy%u,%u channel%u actual%.9g expected%.9g\n",c,x,y,channel,double(actual[index]),expected[channel]);
- CHECK(std::isfinite(actual[index])&&error<.0001);
- }
- // Explicit controls: missing/doubled crest and losing the signed UV0 residual would
- // all be detected at this threshold; they are not merely alternate algebraic labels.
- omittedHeight=(std::max)(omittedHeight,std::abs(addition));duplicateHeight=(std::max)(duplicateHeight,std::abs(addition));
- omittedResidual=(std::max)(omittedResidual,std::abs(residual));
- if(addition>.01)++active;else if(addition==0)++inactive;
- if(c==0) {
- // Real generated-branch controls under identical fields: optical gate off
- // removes exactly one crest; zero UV0 removes exactly one signed residual.
- const unsigned index=(y*width+x)*4;
- CHECK(std::abs(double(actual[index])-actual[((8*4+y)*width+x)*4]-addition)<.0001);
- CHECK(std::abs(double(actual[index+3])-actual[((8*4+y)*width+x)*4+3]-addition)<.0001);
- CHECK(std::abs(double(actual[index])-actual[((13*4+y)*width+x)*4]-residual)<.0001);
- CHECK(std::abs(double(actual[index+3])-actual[((13*4+y)*width+x)*4+3]-residual)<.0001);
- }
- }
- CHECK(active>64&&inactive>192);CHECK(omittedHeight>.1&&duplicateHeight>.1&&omittedResidual>.2);
- printf("sdl_gpu_frame_selfcheck: actual coastal injection %zu cases, %u raster samples, scalar/FD-normal max %.9g; active%u inactive%u, omitted/doubled crest %.7g/%.7g, omitted UV0 %.7g, exact repeat\n",
- queries.size(),unsigned(queries.size())*32,maximum,active,inactive,omittedHeight,duplicateHeight,omittedResidual);
-}
-
-
-#if defined(__linux__)
-static void check_gpu_water_coastal_crest(SdlGpuFrame *frame)
-{
- struct Env {
- bool present;std::string saved;
- Env(){const char*p=getenv("ZH_WATER_COAST_CREST");present=p!=nullptr;saved=p?p:"";}
- ~Env(){if(present)setenv("ZH_WATER_COAST_CREST",saved.c_str(),1);else unsetenv("ZH_WATER_COAST_CREST");}
- }restore;
- PixelPipelineDescription description={};std::string baseline,production,disabled;
- CHECK(unsetenv("ZH_WATER_COAST_CREST")==0);
- bool generated=EngineShader_Pixel_Program(ENGINE_SHADER_WATER_TRAPEZOID,description,baseline,COMBINER_SHADER_TARGET_SDL3_GPU);CHECK(generated);if(!generated)return;
- CHECK(setenv("ZH_WATER_COAST_CREST","0",1)==0);
- generated=EngineShader_Pixel_Program(ENGINE_SHADER_WATER_TRAPEZOID,description,disabled,COMBINER_SHADER_TARGET_SDL3_GPU);CHECK(generated&&disabled==baseline);if(!generated)return;
- CHECK(setenv("ZH_WATER_COAST_CREST","1",1)==0);
- generated=EngineShader_Pixel_Program(ENGINE_SHADER_WATER_TRAPEZOID,description,production,COMBINER_SHADER_TARGET_SDL3_GPU);CHECK(generated);if(!generated)return;
- const std::string helper=WaterCoastalCrest::Source();const size_t at=production.find(helper);CHECK(at!=std::string::npos);if(at==std::string::npos)return;
- const std::string marker=" // All screen derivatives are evaluated before the eligibility branch.";
- const size_t begin=production.find(marker),end=production.find(" float3 normal = normalize(float3(-slope, 1.0));",begin);
- CHECK(begin!=std::string::npos&&end!=std::string::npos);if(begin==std::string::npos||end==std::string::npos)return;
- const std::string injection=production.substr(begin,end-begin);
- CHECK(injection.find("slope+=coastalCorrection.yz;meshCorrection+=coastalCorrection.x;")!=std::string::npos);
- CHECK(injection.find("offshore==0.0 && opticalContext.a>0.0 && opticalContext.b>0.0")!=std::string::npos);
- CHECK(injection.find("WaterParameters.y<0.5")!=std::string::npos);
- std::string stripped=production;stripped.erase(begin,end-begin);stripped.erase(at,helper.size());CHECK(stripped==baseline);
- // Compile both actual production variants with opt-in, not merely the small helper fixture.
- std::vector<unsigned char> fullSpirv;std::string fullError;
- CHECK(SDL3_Compile_HLSL_To_SPIRV(production,false,fullSpirv,fullError));
- std::string river;generated=EngineShader_Pixel_Program(ENGINE_SHADER_WATER_RIVER,description,river,COMBINER_SHADER_TARGET_SDL3_GPU);CHECK(generated);
- if(generated)CHECK(SDL3_Compile_HLSL_To_SPIRV(river,false,fullSpirv,fullError));
- struct Query {float f[6][4];};std::vector<Query> queries;
- for(unsigned i=0;i<32;++i) {
- Query q={{{.05f+.085f*i,.17f,-.23f,0},{.17f+.11f*i,.07f,-.04f,0},
- {.13f+float(i%6)*.11f,.031f,-.023f,0},{.21f+float(i%5)*.13f,-.017f,.021f,0},
- {.67f+float(i%4)*.07f,.011f,-.019f,0},{.03f+float(i%7)*.035f,.013f,.009f,0}}};queries.push_back(q);
- }
- Query q=queries[7];q.f[0][0]=-1;queries.push_back(q);q=queries[7];q.f[1][0]=0;queries.push_back(q);
- q=queries[7];q.f[2][0]=0;queries.push_back(q);q=queries[7];q.f[3][0]=0;queries.push_back(q);
- q=queries[7];q.f[4][0]=q.f[5][0];queries.push_back(q);q=queries[7];q.f[0][0]=std::numeric_limits<float>::quiet_NaN();queries.push_back(q);
- const unsigned rows=unsigned(queries.size()),columns=2;CHECK(rows*sizeof(Query)<=4096);if(rows*sizeof(Query)>4096)return;
- const char *vs="float4 main(uint id:SV_VertexID):SV_Position{return float4(id==1?3.0:-1.0,id==2?3.0:-1.0,0,1);}";
- const std::string shore=WaterShoreFoam::Source();CHECK(production.find(shore)!=std::string::npos);
- std::string ps="struct Query{float4 f[6];};cbuffer CoastQueries:register(b0){Query Queries["+std::to_string(rows)+"];};\n"+
- shore+production.substr(at,helper.size())+R"COAST(
-float4 main(float4 pixel:SV_Position):SV_Target0 {
- Query q=Queries[(uint)pixel.y];float3 d=waterCoastalCrest(q.f[0].xyz,q.f[1].xyz,q.f[2].xyz,q.f[3].xyz,q.f[4].xyz,q.f[5].xyz);
- if(pixel.x<1)return float4(d,.2+d.x);
- return float4(normalize(float3(-float2(.03,-.02)-d.yz,1)),1);
-}
-)COAST";
- const bool placed=sdl3target_detail::place_registers(ps,false);CHECK(placed);if(!placed)return;
- struct Resources {
- SDL_GPUDevice*device;SDL_GPUShader*vs=nullptr,*ps=nullptr;SDL_GPUGraphicsPipeline*pipeline=nullptr;SDL_GPUTexture*target=nullptr;
- ~Resources(){if(target)SDL_ReleaseGPUTexture(device,target);if(pipeline)SDL_ReleaseGPUGraphicsPipeline(device,pipeline);
- if(vs)SDL_ReleaseGPUShader(device,vs);if(ps)SDL_ReleaseGPUShader(device,ps);}
- }r;r.device=frame->Device();std::vector<unsigned char>spirv;std::string error;
- bool ok=SDL3_Compile_HLSL_To_SPIRV(vs,true,spirv,error);CHECK(ok);if(!ok)return;
- r.vs=SDL3_Create_Shader(r.device,spirv,true,error);CHECK(r.vs);if(!r.vs)return;
- ok=SDL3_Compile_HLSL_To_SPIRV(ps,false,spirv,error);CHECK(ok);if(!ok){printf("coastal crest PS: %s\n",error.c_str());return;}
- unsigned samplers=0,buffers=0;SDL3_Shader_Slots(spirv,false,samplers,buffers);CHECK(samplers==0&&buffers==1);if(samplers!=0||buffers!=1)return;
- r.ps=SDL3_Create_Shader(r.device,spirv,false,error);CHECK(r.ps);if(!r.ps)return;
- SDL_GPUColorTargetDescription colour={};colour.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
- SDL_GPUGraphicsPipelineCreateInfo pi={};pi.vertex_shader=r.vs;pi.fragment_shader=r.ps;pi.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;
- pi.target_info.color_target_descriptions=&colour;pi.target_info.num_color_targets=1;
- r.pipeline=SDL_CreateGPUGraphicsPipeline(r.device,&pi);CHECK(r.pipeline);if(!r.pipeline)return;
- SDL_GPUTextureCreateInfo ti={};ti.type=SDL_GPU_TEXTURETYPE_2D;ti.format=colour.format;ti.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;
- ti.width=columns;ti.height=rows;ti.layer_count_or_depth=ti.num_levels=1;r.target=SDL_CreateGPUTexture(r.device,&ti);CHECK(r.target);if(!r.target)return;
- CHECK(frame->Flush());
- auto render=[&](){SDL_GPUCommandBuffer*cmd=SDL_AcquireGPUCommandBuffer(r.device);CHECK(cmd);if(!cmd)return std::vector<float>();
- SDL_GPUColorTargetInfo target={};target.texture=r.target;target.load_op=SDL_GPU_LOADOP_DONT_CARE;target.store_op=SDL_GPU_STOREOP_STORE;
- SDL_GPURenderPass*pass=SDL_BeginGPURenderPass(cmd,&target,1,nullptr);CHECK(pass);if(!pass){SDL_CancelGPUCommandBuffer(cmd);return std::vector<float>();}
- SDL_BindGPUGraphicsPipeline(pass,r.pipeline);SDL_PushGPUFragmentUniformData(cmd,0,queries.data(),unsigned(rows*sizeof(Query)));
- SDL_DrawGPUPrimitives(pass,3,1,0,0);SDL_EndGPURenderPass(pass);CHECK(SDL_SubmitGPUCommandBuffer(cmd));return read_float_targets(frame,&r.target,1,columns,rows);};
- const auto actual=render(),paused=render();CHECK(actual==paused&&actual.size()==rows*columns*4);if(actual.size()!=rows*columns*4)return;
- auto scalar=[](const double f[6]) {
- auto unit=[](double x){return (std::max)(0.,(std::min)(1.,x));};
- auto smooth=[&](double a,double b,double x){const double t=unit((x-a)/(b-a));return t*t*(3-2*t);};
- for(unsigned i=0;i<6;++i)if(!std::isfinite(f[i]))return 0.;
- if(f[0]<=0||f[1]<=double(WaterShoreFoam::MinDepth))return 0.;
- const double c=f[1]-double(WaterShoreFoam::MinDepth);
- const double gain=(std::max)(0.,unit(f[4])-double(.5f/255.f)-unit(f[5]));
- return unit(f[2])*unit(f[3])*smooth(WaterShoreFoam::MinDepth,WaterShoreFoam::WetDepth,f[1])*gain*c*std::tanh(f[0]/c)*smooth(0,WaterShoreFoam::CrestHeight,f[0]);
- };
- double maximum=0;unsigned active=0;
- for(unsigned row=0;row<rows;++row) {
- double f[6];for(unsigned n=0;n<6;++n)f[n]=queries[row].f[n][0];
- double d[3]={scalar(f),0,0};
- for(unsigned axis=0;axis<2;++axis){double a[6],b[6];for(unsigned n=0;n<6;++n){a[n]=f[n]-1e-4*queries[row].f[n][axis+1];b[n]=f[n]+1e-4*queries[row].f[n][axis+1];}d[axis+1]=(scalar(b)-scalar(a))/.0002;}
- // At closed guards the production field is identically zero, including endpoint derivatives.
- if(row>=32)d[0]=d[1]=d[2]=0;
- double nx=-.03-d[1],ny=.02-d[2],nz=1,norm=std::sqrt(nx*nx+ny*ny+1);nx/=norm;ny/=norm;nz/=norm;
- const double expected[8]={d[0],d[1],d[2],.2+d[0],nx,ny,nz,1};
- for(unsigned c=0;c<8;++c){const double error=std::abs(double(actual[row*8+c])-expected[c]);maximum=(std::max)(maximum,error);
- if(!(std::isfinite(actual[row*8+c])&&error<.0001))printf("coastal crest row%u channel%u actual%.9g expected%.9g\n",row,c,double(actual[row*8+c]),expected[c]);
- CHECK(std::isfinite(actual[row*8+c])&&error<.0001);}
- active+=d[0]>.01;
- }
- CHECK(active>15);
- printf("sdl_gpu_frame_selfcheck: coastal crest %u cases; actual production helper vs independent scalar/FD-normal max %.9g, exact pause, opt-out source identity\n",rows,maximum);
- check_gpu_water_coastal_crest_injection(frame,production);
-}
-#endif // __linux__
-
#if defined(__linux__)
static void check_gpu_water_shore_front(SdlGpuFrame *frame)
{
@@ -7575,18 +6434,15 @@ static void check_gpu_water_shore_depth_gate(SdlGpuFrame *frame)
// not bottomPosition(), which deliberately has a different terrain-fallback contract.
using namespace WaterShoreFoam;
PixelPipelineDescription description={};std::string production;
- const char *old=getenv("ZH_WATER_SHORE_FOAM");const bool had=old!=nullptr;const std::string saved=old?old:"";
- CHECK(setenv("ZH_WATER_SHORE_FOAM","1",1)==0);
const bool generated=EngineShader_Pixel_Program(ENGINE_SHADER_WATER_TRAPEZOID,description,production,COMBINER_SHADER_TARGET_SDL3_GPU);
- if(had)CHECK(setenv("ZH_WATER_SHORE_FOAM",saved.c_str(),1)==0);else CHECK(unsetenv("ZH_WATER_SHORE_FOAM")==0);
CHECK(generated);if(!generated)return;
const size_t pixelAt=production.find("float2 waterScenePixel("),pixelEnd=production.find("// Depth is a point-sampled",pixelAt);
const size_t blockAt=production.find(" float shoreRate=0.0,shoreSupport=0.0;"),blockEnd=production.find(" // At a known hull",blockAt);
- const size_t cageAt=production.find(" // Contact wash follows",blockAt),shoreAt=production.find(" if(shoreFoamEnabled &&",cageAt);
+ const size_t cageAt=production.find(" // Contact wash follows",blockAt),shoreAt=production.find(" if(WaterParameters.y<0.5 &&",cageAt);
CHECK(pixelAt!=std::string::npos && pixelEnd!=std::string::npos && blockAt<cageAt && cageAt<shoreAt && shoreAt<blockEnd && blockEnd!=std::string::npos);
if(pixelAt==std::string::npos || pixelEnd==std::string::npos || !(blockAt<cageAt && cageAt<shoreAt && shoreAt<blockEnd) || blockEnd==std::string::npos)return;
// Keep the original source/history initialization and actual analytic depth-gated
- // branch. Cage wash and optional GPU surf have their own resources and fixtures.
+ // branch. Cage wash has its own resources and fixture.
const std::string block=production.substr(blockAt,cageAt-blockAt)+production.substr(shoreAt,blockEnd-shoreAt);
CHECK(block.find("waterShoreSceneDepth(SceneParameters.w,shoreRawDepth)")!=std::string::npos);
CHECK(block.find("floor(input.Position.xy)+0.5")!=std::string::npos);
@@ -7597,7 +6453,6 @@ cbuffer ShoreCase:register(b0,space3) {
};
Texture2D<float> Texture6:register(t0,space2);SamplerState Sampler6:register(s0,space2);
struct Input {float4 Position;};
-static const bool shoreFoamEnabled=true;
float terrainHeight(float2 p) {return 0.0;}
float waterShoreHistory(float2 p,float level,float time) {return CaseGradient.z;}
)SHORE"+Source()+production.substr(pixelAt,pixelEnd-pixelAt)+R"SHORE(
@@ -7718,438 +6573,6 @@ float4 main(float4 pixel:SV_Position):SV_Target0 {
}
#endif // __linux__
-// Core-only fixture: actual production FFT decode/limiter feeds the proposed source.
-// Native texture binding, graph transport and scene masks remain separate rollout gates.
-static void check_gpu_water_coastal_surf_core(SdlGpuFrame *frame)
-{
- struct Query {float f[12][4];};
- Query base={{{.015f,.065f,-.004f,.01f},{-.35f,.08f,.02f,.025f},
- {.005f,.035f,.007f,.005f},{-.15f,.02f,.03f,.02f},
- {10,20,30,40},{50,60,70,80},{2.4f,-.3f,.08f,1},
- {4,64,-1,0},{1,.4f,.4f,.5f},{1,1,0,0},{.7f,1.3f,2,.4f},{.1f,1,.25f,0}}};
- std::vector<Query> queries(20,base);
- queries[1].f[8][1]=0;queries[2].f[8][1]=1;queries[2].f[10][2]=1.7f;
- for(float &v:queries[3].f[4])v*=100000;for(float &v:queries[3].f[5])v*=100000;
- queries[4].f[6][0]=-1;queries[4].f[0][1]=queries[4].f[2][1]=-.05f;
- queries[5].f[7][2]=1;queries[6].f[10][2]=3;
- queries[7].f[7][0]=.1f;queries[8].f[8][0]=0;queries[9].f[7][1]=128;
- queries[10].f[7][0]=12;queries[11].f[9][0]=0;queries[12].f[9][1]=0;
- queries[13].f[11][0]=0;queries[14].f[11][0]=1.3f;queries[15].f[10][3]=-1;
- queries[16].f[1][0]=(std::numeric_limits<float>::max)();
- queries[17].f[7][2]=(std::numeric_limits<float>::max)();queries[18].f[11][0]=1e-40f;
- queries[19].f[6][1]=queries[19].f[6][2]=0;
- queries[19].f[1][0]=queries[19].f[1][1]=queries[19].f[3][0]=queries[19].f[3][1]=0;
- const std::string production=WaterFftSampling::PixelSource(false,false);
- const size_t start=production.find("struct FftSurface {"),end=production.find("struct FftMapSamples");
- const size_t decode=production.find("FftSurface fftDecodeSamples("),after=production.find("FftSurface fftRawSurface(");
- CHECK(start!=std::string::npos&&end>start&&decode!=std::string::npos&&after>decode);
- if(start==std::string::npos||end<=start||decode==std::string::npos||after<=decode)return;
- std::string ps="struct Query{float4 f[12];};cbuffer Queries:register(b0,space3){Query Q[20];};\n"
- +WaterFftSampling::CommonSource()+production.substr(start,end-start)
- +"struct FftMapSamples {float4 a,ad,b,bd,c,cd;};\n"+production.substr(decode,after-decode)
- +WaterCoastalSurf::IncidentSource()+WaterCoastalSurf::Source()+R"SURF(
-float4 main(float4 pixel:SV_Position):SV_Target0 {
- Query q=Q[(uint)pixel.y];FftMapSamples samples;
- samples.a=q.f[0];samples.ad=q.f[1];samples.b=q.f[2];samples.bd=q.f[3];samples.c=q.f[4];samples.cd=q.f[5];
- float4 incident=waterSurfIncident(samples),field=waterSurfBlend(q.f[6],incident,q.f[8].y);
- WaterSurfContext context;context.coast=q.f[7];context.surface=q.f[8];context.admission=q.f[9];
- float4 updated=waterSurfAdvance(context,field,q.f[10],q.f[11].x,q.f[11].y>.5);
- if(pixel.x<1)return incident;if(pixel.x<2)return field;
- if(pixel.x<3)return float4(waterSurfRate(context,field,q.f[10],q.f[11].x),waterSurfDomain(context),waterSurfCoverage(updated,q.f[11].z),1);
- if(pixel.x<4)return updated;
- return waterSurfDiffuse(q.f[10],float4(0,0,0,0),float4(1,2,3,0),float4(4,8,0,0),float4(0,0,0,0),6,5,min(q.f[11].x,.25));
-})SURF";
- const char *vs="float4 main(uint id:SV_VertexID):SV_Position{return float4(id==1?3.0:-1.0,id==2?3.0:-1.0,0,1);}";
- struct Resources {
- SDL_GPUDevice *device;SDL_GPUShader *vs=nullptr,*ps=nullptr;SDL_GPUGraphicsPipeline *pipeline=nullptr;SDL_GPUTexture *target=nullptr;
- ~Resources(){if(target)SDL_ReleaseGPUTexture(device,target);if(pipeline)SDL_ReleaseGPUGraphicsPipeline(device,pipeline);
- if(vs)SDL_ReleaseGPUShader(device,vs);if(ps)SDL_ReleaseGPUShader(device,ps);}
- }r;r.device=frame->Device();std::vector<unsigned char>spirv;std::string error;
- bool ok=SDL3_Compile_HLSL_To_SPIRV(vs,true,spirv,error);CHECK(ok);if(!ok)return;
- r.vs=SDL3_Create_Shader(r.device,spirv,true,error);CHECK(r.vs);if(!r.vs)return;
- ok=SDL3_Compile_HLSL_To_SPIRV(ps,false,spirv,error);CHECK(ok);if(!ok){printf("coastal surf core PS: %s\n",error.c_str());return;}
- unsigned samplers=0,buffers=0;SDL3_Shader_Slots(spirv,false,samplers,buffers);CHECK(samplers==0&&buffers==1);
- r.ps=SDL3_Create_Shader(r.device,spirv,false,error);CHECK(r.ps);if(!r.ps)return;
- SDL_GPUColorTargetDescription colour={};colour.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
- SDL_GPUGraphicsPipelineCreateInfo pi={};pi.vertex_shader=r.vs;pi.fragment_shader=r.ps;pi.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;
- pi.target_info.color_target_descriptions=&colour;pi.target_info.num_color_targets=1;
- r.pipeline=SDL_CreateGPUGraphicsPipeline(r.device,&pi);CHECK(r.pipeline);if(!r.pipeline)return;
- const unsigned width=5,height=unsigned(queries.size());CHECK(sizeof(Query)*height<=4096);
- SDL_GPUTextureCreateInfo ti={};ti.type=SDL_GPU_TEXTURETYPE_2D;ti.format=colour.format;ti.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;
- ti.width=width;ti.height=height;ti.layer_count_or_depth=ti.num_levels=1;
- r.target=SDL_CreateGPUTexture(r.device,&ti);CHECK(r.target);if(!r.target)return;CHECK(frame->Flush());
- auto render=[&](){
- SDL_GPUCommandBuffer *commands=SDL_AcquireGPUCommandBuffer(r.device);CHECK(commands);if(!commands)return std::vector<float>();
- SDL_GPUColorTargetInfo target={};target.texture=r.target;target.load_op=SDL_GPU_LOADOP_DONT_CARE;target.store_op=SDL_GPU_STOREOP_STORE;
- SDL_GPURenderPass *pass=SDL_BeginGPURenderPass(commands,&target,1,nullptr);CHECK(pass);if(!pass){SDL_CancelGPUCommandBuffer(commands);return std::vector<float>();}
- SDL_BindGPUGraphicsPipeline(pass,r.pipeline);SDL_PushGPUFragmentUniformData(commands,0,queries.data(),unsigned(queries.size()*sizeof(Query)));
- SDL_DrawGPUPrimitives(pass,3,1,0,0);SDL_EndGPURenderPass(pass);CHECK(SDL_SubmitGPUCommandBuffer(commands));
- return read_float_targets(frame,&r.target,1,width,height);
- };
- const auto actual=render(),repeat=render();CHECK(actual==repeat&&actual.size()==width*height*4);if(actual.size()!=width*height*4)return;
- auto clamp=[](double x,double a,double b){return (std::max)(a,(std::min)(b,x));};
- auto smooth=[&](double a,double b,double x){const double t=clamp((x-a)/(b-a),0,1);return t*t*(3-2*t);};
- const double vz=WaterFftGeometry::MaxVerticalDisplacement,xy=WaterFftGeometry::MaxHorizontalDisplacement/std::sqrt(2.0);
- double maximum=0;unsigned active=0,suppressed=0;double armedFine=0;
- for(unsigned row=0;row<height;++row){const Query&q=queries[row];
- const double h=(double(q.f[0][1])+q.f[2][1])*20;
- const double hx=double(q.f[1][0])+q.f[3][0],hy=double(q.f[1][1])+q.f[3][1];
- const double d0=(-1.2*double(q.f[0][0])-1.5*double(q.f[2][0]))*20;
- const double d1=(-1.2*double(q.f[0][2])-1.5*double(q.f[2][2]))*20;
- const double lx=1-std::pow(std::tanh(d0/xy),2),ly=1-std::pow(std::tanh(d1/xy),2);
- const double xx=(-1.2*double(q.f[1][2])-1.5*double(q.f[3][2]))*lx;
- const double cross=-1.2*double(q.f[0][3])-1.5*double(q.f[2][3]);
- const double yy=(-1.2*double(q.f[1][3])-1.5*double(q.f[3][3]))*ly;
- const double incident[4]={vz*std::tanh(h/vz),hx*(1-std::pow(std::tanh(h/vz),2)),hy*(1-std::pow(std::tanh(h/vz),2)),(1+xx)*(1+yy)-cross*cross*lx*ly};
- const double weight=q.f[8][1];double field[4];for(unsigned i=0;i<3;++i)field[i]=q.f[6][i]+(incident[i]-q.f[6][i])*weight;
- field[3]=1+(incident[3]-1)*weight;
- if(row==16){field[0]=field[1]=field[2]=0;field[3]=1;}
- const double dt=q.f[11][0],depth=q.f[7][0],distance=q.f[7][1],n=std::hypot(q.f[7][2],q.f[7][3]),slope=std::hypot(field[1],field[2]);
- const bool contextValid=std::abs(q.f[7][2])<=1024;
- const bool fieldValid=std::abs(field[0])<=64&&std::abs(field[1])<=1024&&std::abs(field[2])<=1024&&std::abs(field[3])<=1048576;
- const bool wet=contextValid&&q.f[9][0]>=.5&&q.f[9][1]>=.5&&q.f[8][0]>0&&depth>.15;
- const double domain=wet&&distance>=0?smooth(.15,.8,depth)*(1-smooth(8,12,depth))*(1-smooth(96,128,distance))*q.f[8][0]:0;
- const double ht=dt>0?(field[0]-q.f[10][2])/dt:0;double rate=0;
- if(domain>0&&fieldValid&&q.f[10][3]>=0&&dt>1e-6&&dt<=.25&&field[0]>0&&ht>0&&n>1e-8&&slope>1e-8){
- const double incoming=smooth(0,.25,(field[1]/slope)*(q.f[7][2]/n)+(field[2]/slope)*(q.f[7][3]/n));
- const double breaking=(std::max)(smooth(.4,.85,2*field[0]/(std::max)(depth+.5,1.0)),smooth(.04,.30,1-field[3]));
- const double damping=q.f[8][2]+(q.f[8][3]-q.f[8][2])*q.f[8][0];
- rate=1.2*domain*incoming*breaking*(1-damping*damping)*smooth(0,.5,field[0])*smooth(0,.08,ht);
- }
- double next[4]={0,0,0,-1};
- if(dt<=1e-6)for(unsigned i=0;i<4;++i)next[i]=q.f[10][i];
- else if(wet&&fieldValid){const double decay=std::exp(-dt/5);next[0]=decay*q.f[10][0];next[1]=decay*(q.f[10][1]+dt*q.f[10][0]);next[2]=field[0];next[3]=dt<=.25?rate:0;
- if(dt<=.25){ // independent numerical convolution, not production integral series
- constexpr unsigned steps=2048;double density=0,age=0;
- for(unsigned i=0;i<=steps;++i){const double a=dt*i/steps,r0=clamp(q.f[10][3],0,1.2),r=rate+(r0-rate)*a/dt;
- const double mass=std::exp(-a/5)*r,w=(i==0||i==steps)?1:(i%2?4:2);density+=w*mass;age+=w*a*mass;}
- next[0]+=density*dt/(3*steps);next[1]+=age*dt/(3*steps);
- }}
- double coverage=0;if(next[0]>0){const double age=next[1]/next[0];coverage=(1-std::exp(-next[0]))*(1-smooth(.4,3,age)*(1-q.f[11][2]))*(1-smooth(8,14,age));}
- const double status[4]={rate,domain,coverage,1};
- double diffusion[4]={q.f[10][0],q.f[10][1],q.f[10][2],q.f[10][3]};const double amount=2*(std::min)(dt,.25)/25;
- diffusion[0]+=amount*(5-2*diffusion[0]);diffusion[1]+=amount*(10-2*diffusion[1]);
- for(unsigned col=0;col<5;++col)for(unsigned c=0;c<4;++c){
- if(row==16&&col<2)continue; // adversarial finite magnitude is a source-admission control
- const double expected=col==0?incident[c]:col==1?field[c]:col==2?status[c]:col==3?next[c]:diffusion[c];
- const double value=actual[(row*width+col)*4+c],error=std::abs(value-expected);maximum=(std::max)(maximum,error);
- if(!(std::isfinite(value)&&error<.00003))printf("surf core row%u col%u ch%u got%.9g expected%.9g\n",row,col,c,value,expected);
- CHECK(std::isfinite(value)&&error<.00003);
- }
- active+=rate>.1;suppressed+=rate==0;
- if(row==0)armedFine=std::abs(vz*std::tanh((h+q.f[4][1]*20)/vz)-incident[0]);
- }
- CHECK(active>=3&&suppressed>=12&&armedFine>1);
- for(unsigned i=0;i<width*4;++i)CHECK(actual[i]==actual[(3*width)*4+i]); // fine-scale trigger is exactly absent
- printf("sdl_gpu_frame_selfcheck: coastal surf core %u cases actual FFT decode/shared limiter + independent blend/rate/convolution/age/diffusion max%.9g active%u suppressed%u fine-control%.6g repeat exact\n",height,maximum,active,suppressed,armedFine);
-}
-
-
-// Append after read_ocean and invoke AFTER check_gpu_fft_ocean, whose initial-state
-// assertions deliberately precede every other use of the real ocean owner.
-static void check_gpu_water_coastal_incident(SdlGpuFrame *frame)
-{
- using namespace WaterCoastalSurf;
- const uint64_t revision=0xc04157;
- std::vector<Node> nodes;
- const float positions[][2]={{0,0},{-137.25f,91.5f},{1938,736},{3050,-330}};
- for(const auto &p:positions)for(unsigned support=0;support<2;++support)for(unsigned weight=0;weight<3;++weight){
- Node node;node.world[0]=p[0];node.world[1]=p[1];node.world[2]=7+4*(support*3+weight);
- node.context={4,64,-1,0,support==0?1.f:.4f,weight==0?0.f:weight==1?.4f:1.f,.4f,.5f,1,1};
- nodes.push_back(node);
- }
- CHECK(ValidGraph(nodes,5));
- struct Resources {
- SdlGpuFrame *frame=nullptr;SDL_GPUShader *vertex=nullptr,*pixel=nullptr;SDL_GPUGraphicsPipeline *pipeline=nullptr;bool installed=false;
- ~Resources(){if(installed)CHECK(frame->Clear_Coastal_Surf());
- if(pipeline)SDL_ReleaseGPUGraphicsPipeline(frame->Device(),pipeline);
- if(vertex)SDL_ReleaseGPUShader(frame->Device(),vertex);if(pixel)SDL_ReleaseGPUShader(frame->Device(),pixel);}
- } resources;resources.frame=frame;
- std::string source,error;std::vector<unsigned char>spirv;
- const bool generated=WaterCoastalIncident::PixelSource(source);CHECK(generated);if(!generated)return;
- bool ok=SDL3_Compile_HLSL_To_SPIRV(WaterCoastalIncident::VertexSource(),true,spirv,error);CHECK(ok);if(!ok)return;
- resources.vertex=SDL3_Create_Shader(frame->Device(),spirv,true,error);CHECK(resources.vertex);if(!resources.vertex)return;
- ok=SDL3_Compile_HLSL_To_SPIRV(source,false,spirv,error);CHECK(ok);
- if(!ok){printf("coastal incident shader: %s\n",error.c_str());return;}
- unsigned samplers=0,buffers=0;SDL3_Shader_Slots(spirv,false,samplers,buffers);
- CHECK(samplers==WaterCoastalIncident::SamplerCount&&buffers==1);
- resources.pixel=SDL3_Create_Shader(frame->Device(),spirv,false,error);CHECK(resources.pixel);if(!resources.pixel)return;
- SDL_GPUColorTargetDescription colour={};colour.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
- SDL_GPUGraphicsPipelineCreateInfo pipeline={};pipeline.vertex_shader=resources.vertex;pipeline.fragment_shader=resources.pixel;
- pipeline.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;pipeline.target_info.color_target_descriptions=&colour;pipeline.target_info.num_color_targets=1;
- resources.pipeline=SDL_CreateGPUGraphicsPipeline(frame->Device(),&pipeline);CHECK(resources.pipeline);if(!resources.pipeline)return;
- resources.installed=frame->Install_Coastal_Surf(revision,nodes,5);CHECK(resources.installed);if(!resources.installed)return;
- const SdlTarget target=frame->Coastal_Surf_Field_Target(revision);
- CHECK(target.Colour&&target.Depth==nullptr&&target.Width==256&&target.Height==256);if(!target.Colour)return;
- auto render=[&](float time,float count){
- CHECK(frame->Flush());SDL_GPUCommandBuffer *commands=SDL_AcquireGPUCommandBuffer(frame->Device());CHECK(commands);
- if(!commands)return std::vector<float>();
- SDL_GPUColorTargetInfo attachment={};attachment.texture=target.Colour;attachment.load_op=SDL_GPU_LOADOP_DONT_CARE;attachment.store_op=SDL_GPU_STOREOP_STORE;
- SDL_GPURenderPass *pass=SDL_BeginGPURenderPass(commands,&attachment,1,nullptr);CHECK(pass);
- if(!pass){SDL_CancelGPUCommandBuffer(commands);return std::vector<float>();}
- SDL_BindGPUGraphicsPipeline(pass,resources.pipeline);
- SDL_GPUTextureSamplerBinding bindings[WaterCoastalIncident::SamplerCount]={};
- for(unsigned i=0;i<4;++i){bindings[i].texture=frame->Coastal_Surf_Domain(i,revision);bindings[i].sampler=frame->Coastal_Surf_Sampler(revision);}
- for(unsigned i=0;i<4;++i){bindings[4+i].texture=frame->Ocean_Map(i);bindings[4+i].sampler=frame->Ocean_Sampler();}
- SDL_BindGPUFragmentSamplers(pass,0,bindings,WaterCoastalIncident::SamplerCount);
- const WaterCoastalIncident::Parameters parameters{time,count,0,0};
- SDL_PushGPUFragmentUniformData(commands,0,&parameters,sizeof(parameters));
- SDL_DrawGPUPrimitives(pass,3,1,0,0);SDL_EndGPURenderPass(pass);CHECK(SDL_SubmitGPUCommandBuffer(commands));
- return read_float_targets(frame,&target.Colour,1,256,256);
- };
- struct Mode{double x,y,a,w,p;};
-#define COASTAL_INCIDENT_MODE(kx,ky,a,w,p) {kx,ky,a,w,p},
- const Mode legacyModes[]={WATER_SURFACE_MODES(COASTAL_INCIDENT_MODE)};
- const Mode oceanModes[]={WATER_OCEAN_MODES(COASTAL_INCIDENT_MODE)};
-#undef COASTAL_INCIDENT_MODE
- // Independent scalar equations using the source coefficient data. Derivatives
- // come from double central differences, not either generated analytic derivative.
- auto scalar=[&](double x,double y,double time,bool ocean){
- double sum=0;
- if(!ocean){for(unsigned i=0;i<3;++i){const Mode&m=legacyModes[i];const double phase=x*m.x+y*m.y-time*m.w+m.p;
- sum+=m.a*(std::sin(phase)+.13*std::sin(2*phase));}return sum;}
- const double s0=std::sin(x*.0241+y*.0157-time*.23+.4),s1=std::sin(x*-.0173+y*.0299-time*.19+2.1);
- x+=5*s0;y+=4*s1;
- for(const Mode&m:oceanModes)if(m.x*m.x+m.y*m.y<.18){const double phase=x*m.x+y*m.y-time*m.w+m.p;
- sum+=m.a*(std::sin(phase)+.08*std::sin(2*phase));}
- return sum*(.86+.14*s0*s1);
- };
- auto analytic=[&](double x,double y,double time,bool ocean){const double epsilon=.0001;
- return std::array<double,4>{scalar(x,y,time,ocean),
- (scalar(x+epsilon,y,time,ocean)-scalar(x-epsilon,y,time,ocean))/(2*epsilon),
- (scalar(x,y+epsilon,time,ocean)-scalar(x,y-epsilon,time,ocean))/(2*epsilon),1};};
- struct Texel {std::array<double,4> value{},error{};};
- auto sample=[&](const std::vector<float>&maps,unsigned map,float worldX,float worldY){
- const unsigned cascade=map/2;const float period=WaterFftSpectrum::Sizes[cascade]*WaterFftSampling::WorldScale;
- // Float division matches the production UV arithmetic; interpolation itself
- // is independent double bilinear of the REAL sampled mip-zero texels.
- const float u=worldX/period,v=worldY/period;
- const double x=double(u)*256-.5,y=double(v)*256-.5;const int ix=int(std::floor(x)),iy=int(std::floor(y));
- const double fx=x-ix,fy=y-iy;Texel result;
- auto at=[&](int px,int py,unsigned c){px=(px%256+256)%256;py=(py%256+256)%256;return double(maps[((map*256+py)*256+px)*4+c]);};
- for(unsigned c=0;c<4;++c){const double a=at(ix,iy,c),b=at(ix+1,iy,c),d=at(ix,iy+1,c),e=at(ix+1,iy+1,c);
- result.value[c]=(a+(b-a)*fx)*(1-fy)+(d+(e-d)*fx)*fy;
- // A portable 8-bit subtexel precision bound, plus float UV rounding.
- // Neighbouring cells are included if rounding crosses a bilinear edge.
- double sx=0,sy=0,magnitude=0;
- for(int yy=iy-1;yy<=iy+1;++yy)for(int xx=ix-1;xx<=ix+1;++xx){
- sx=(std::max)(sx,std::abs(at(xx+1,yy,c)-at(xx,yy,c)));
- sy=(std::max)(sy,std::abs(at(xx,yy+1,c)-at(xx,yy,c)));
- magnitude=(std::max)(magnitude,std::abs(at(xx,yy,c)));}
- const double ex=1./256+4*std::numeric_limits<float>::epsilon()*std::abs(u)*256;
- const double ey=1./256+4*std::numeric_limits<float>::epsilon()*std::abs(v)*256;
- result.error[c]=sx*ex+sy*ey+2e-7*(1+magnitude);
- }return result;
- };
- auto spectral=[&](const std::vector<float>&maps,float x,float y,bool fine){
- std::array<Texel,6> samples;for(unsigned i=0;i<(fine?6:4);++i)samples[i]=sample(maps,i,x,y);
- double displacement[3]={},derivative[5]={},de[3]={},ge[5]={};
- for(unsigned cascade=0;cascade<(fine?3:2);++cascade){const auto&a=samples[cascade*2],&b=samples[cascade*2+1];
- const double chop=cascade?-1.5:-1.2,scale=WaterFftSampling::WorldScale;
- displacement[0]+=chop*scale*a.value[0];displacement[1]+=chop*scale*a.value[2];displacement[2]+=scale*a.value[1];
- de[0]+=std::abs(chop)*scale*a.error[0];de[1]+=std::abs(chop)*scale*a.error[2];de[2]+=scale*a.error[1];
- derivative[0]+=b.value[0];derivative[1]+=b.value[1];derivative[2]+=chop*b.value[2];derivative[3]+=chop*b.value[3];derivative[4]+=chop*a.value[3];
- ge[0]+=b.error[0];ge[1]+=b.error[1];ge[2]+=std::abs(chop)*b.error[2];ge[3]+=std::abs(chop)*b.error[3];ge[4]+=std::abs(chop)*a.error[3];
- }
- const double vertical=WaterFftGeometry::MaxVerticalDisplacement,horizontal=WaterFftGeometry::MaxHorizontalDisplacement/std::sqrt(2.0);
- double limiter[3],le[3];for(unsigned i=0;i<3;++i){const double bound=i==2?vertical:horizontal;
- limiter[i]=1-std::pow(std::tanh(displacement[i]/bound),2);le[i]=2*de[i]/bound;}
- Texel result;result.value[0]=vertical*std::tanh(displacement[2]/vertical);
- result.value[1]=derivative[0]*limiter[2];result.value[2]=derivative[1]*limiter[2];
- const double a=1+derivative[2]*limiter[0],b=1+derivative[3]*limiter[1],cross=derivative[4];
- result.value[3]=a*b-cross*cross*limiter[0]*limiter[1];
- result.error[0]=de[2];result.error[1]=ge[0]+std::abs(derivative[0])*le[2];result.error[2]=ge[1]+std::abs(derivative[1])*le[2];
- const double ae=ge[2]+std::abs(derivative[2])*le[0],be=ge[3]+std::abs(derivative[3])*le[1];
- result.error[3]=std::abs(a)*be+std::abs(b)*ae+ae*be+2*std::abs(cross)*ge[4]+ge[4]*ge[4]+cross*cross*(le[0]+le[1]);
- return result;
- };
- double maximum=0,maximumBound=0,wrongBlend=0,wrongTime=0,fineArmed=0,advanced=0,oldCoastPhase=0;
- std::vector<float> first;
- for(float time:{3.4375f,7.75f}){
- CHECK(frame->Prepare_Ocean(time*WaterFftSampling::TimeScale));
- const auto maps=read_ocean(frame),actual=render(time,float(nodes.size())),repeat=render(time,float(nodes.size()));
- CHECK(actual.size()==256*256*4 && actual==repeat);if(actual.size()!=256*256*4)return;
- for(unsigned n=0;n<nodes.size();++n){const Node&node=nodes[n];
- const double r=node.context.offshore,w=node.context.exposure;
- const auto river=analytic(node.world[0],node.world[1],time,false),ocean=analytic(node.world[0],node.world[1],time,true);
- const auto wrongClock=analytic(node.world[0],node.world[1],time*WaterFftSampling::TimeScale,false);
- const auto fft=spectral(maps,node.world[0],node.world[1],false),full=spectral(maps,node.world[0],node.world[1],true);
- fineArmed=(std::max)(fineArmed,std::abs(fft.value[0]-full.value[0]));
- for(unsigned c=0;c<4;++c){const double a=c==3?1:river[c]+(ocean[c]-river[c])*r;
- const double expected=c==3?1+(fft.value[3]-1)*w*r:a+(fft.value[c]-a)*w;
- // Analytic tolerance retains the existing float-phase model bound;
- // spectral tolerance is derived from THIS point's real texel gradients.
- const double bound=.0025*(1-w)+w*fft.error[c]+.00002;
- const double error=std::abs(actual[n*4+c]-expected);maximum=(std::max)(maximum,error);maximumBound=(std::max)(maximumBound,bound);
- CHECK(std::isfinite(actual[n*4+c])&&error<bound);
- if(c<3&&w<1&&r>0)wrongBlend=(std::max)(wrongBlend,std::abs(expected-(river[c]+(fft.value[c]-river[c])*w)));
- if(c<3&&w<1&&r==0)wrongTime=(std::max)(wrongTime,std::abs((river[c]-wrongClock[c])*(1-w)));
- if(c<3&&w==1&&r==0)oldCoastPhase=(std::max)(oldCoastPhase,std::abs(expected-river[c]));
- }
- // Full connected-water support has exactly one wave phase at R0,
- // transitional R and R1. Only horizontal compression retains the R fade.
- if(n%6<3)for(unsigned c=0;c<3;++c)CHECK(std::abs(actual[n*4+c]-actual[(n-n%6)*4+c])<.000002f);
- if(r==0)CHECK(actual[n*4+3]==1);
- }
- for(unsigned n=unsigned(nodes.size());n<256*256;++n){CHECK(actual[n*4]==0&&actual[n*4+1]==0&&actual[n*4+2]==0&&actual[n*4+3]==1);}
- if(first.empty())first=actual;else for(unsigned n=0;n<nodes.size()*4;++n)advanced=(std::max)(advanced,std::abs(double(first[n])-actual[n]));
- }
- CHECK(wrongBlend>.05&&wrongTime>.05&&fineArmed>.001&&advanced>.05&&oldCoastPhase>.05);
- const auto invalid=render(std::numeric_limits<float>::quiet_NaN(),float(nodes.size()));
- const auto fractional=render(7.75f,float(nodes.size())+.5f);
- CHECK(invalid.size()==256*256*4&&fractional==invalid);
- for(unsigned n=0;n<invalid.size()/4;++n)CHECK(invalid[n*4]==0&&invalid[n*4+1]==0&&invalid[n*4+2]==0&&invalid[n*4+3]==1);
- printf("sdl_gpu_frame_selfcheck: coastal incident real FFT atlas %zu nodes x2 phases, B1 and B.4 across R0/mixed/R1, max error %.8g bound %.8g; old coastal phase mismatch %.6g, analytic mix %.6g time-scale %.6g fine %.6g advance %.6g; repeat exact, padding/invalid clear\n",
- nodes.size(),maximum,maximumBound,oldCoastPhase,wrongBlend,wrongTime,fineArmed,advanced);
-}
-
-// Run after the new presentation header/uniform transport is integrated. This fixture
-// extracts the ACTUAL generated injection, then supplies controlled scene provenance.
-// Existing scene-depth/refraction tests independently validate real reconstruction.
-#if defined(__linux__)
-static void check_gpu_water_coastal_presentation(SdlGpuFrame *frame)
-{
- struct Query{float q[7][4];};
- Query base={{{1,.1f,.0625f,1},{0,0,.4f,.4f},{.2f,1,1,1},{1,1,1,0},{0,0,0,1},{1,1,1,0},{2,1,0,0}}};
- std::vector<Query>queries(30,base);
- queries[1].q[1][2]=queries[1].q[1][3]=0;queries[2].q[1][2]=queries[2].q[1][3]=1;
- queries[3].q[0][3]=0;queries[4].q[1][0]=.2f;queries[5].q[0][2]=-.1f;queries[6].q[1][1]=1;
- queries[7].q[0][0]=0;queries[8].q[0][1]=20;queries[9].q[0][0]=std::numeric_limits<float>::quiet_NaN();
- queries[10].q[2][1]=6;queries[11].q[6][1]=-1;queries[12].q[3][0]=-2;
- queries[13].q[2][2]=5;queries[14].q[2][3]=5;queries[15].q[3][1]=0;queries[16].q[3][2]=0;
- queries[17].q[1][2]=0;queries[18].q[3][3]=.5f;queries[19].q[4][0]=.1f;
- queries[20].q[5][0]=0;queries[21].q[4][3]=0;queries[22].q[4][2]=1;
- queries[23].q[2][0]=1;queries[24].q[2][0]=-1;queries[25].q[5][3]=2;
- queries[26].q[0][1]=3;queries[27].q[0][2]=3;queries[28].q[6][0]=30;queries[29].q[1][3]=.42f;
- const unsigned rows=unsigned(queries.size()),columns=2;CHECK(queries.size()*sizeof(Query)<=4096);
- const char *oldOption=getenv("ZH_WATER_SURF_GPU"),*oldDebug=getenv("ZH_WATER_DEBUG");
- const bool hadOption=oldOption!=nullptr,hadDebug=oldDebug!=nullptr;
- const std::string savedOption=oldOption?oldOption:"",savedDebug=oldDebug?oldDebug:"";
- CHECK(setenv("ZH_WATER_SURF_GPU","1",1)==0);CHECK(unsetenv("ZH_WATER_DEBUG")==0);
- PixelPipelineDescription pd={};std::string production;
- const bool generated=EngineShader_Pixel_Program(ENGINE_SHADER_WATER_TRAPEZOID,pd,production,COMBINER_SHADER_TARGET_SDL3_GPU);
- if(hadOption)CHECK(setenv("ZH_WATER_SURF_GPU",savedOption.c_str(),1)==0);else CHECK(unsetenv("ZH_WATER_SURF_GPU")==0);
- if(hadDebug)CHECK(setenv("ZH_WATER_DEBUG",savedDebug.c_str(),1)==0);else CHECK(unsetenv("ZH_WATER_DEBUG")==0);
- CHECK(generated);if(!generated)return;
- const size_t begin=production.find("float gpuCoastFoam="),end=production.find("if(shoreFoamEnabled",begin);
- CHECK(begin!=std::string::npos&&end!=std::string::npos&&end>begin);if(begin==std::string::npos||end==std::string::npos||end<=begin)return;
- std::string ps="struct Query{float4 q[7];};cbuffer Queries:register(b0,space3){Query Q[30];};\n";
- for(unsigned i:{4u,6u,15u}){const std::string n=std::to_string(i);
- ps+="Texture2D<float4> Texture"+n+":register(t"+n+",space2);SamplerState Sampler"+n+":register(s"+n+",space2);\n";}
- ps+=R"HLSL(
-float oceanNoise(float2 p){return .5;}
-float2 waterScenePixel(float2 p){return p;}
-float3 scenePosition(float2 p,float raw){return float3(2,floor(p.y),Q[(uint)p.y].q[2].y);}
-float terrainHeight(float2 p){Query q=Q[(uint)p.y];return p.x<.5?q.q[2].z:p.x<1.5?q.q[2].w:q.q[3].x;}
-float3 vesselHullDamping(float2 p,float level){return float3(Q[(uint)p.y].q[3].z,0,0);}
-bool waterShoreSceneDepth(float available,float raw){return isfinite(available)&&available>.5&&isfinite(raw)&&raw>=0&&raw<.999999;}
-struct Input{float4 Position;float4 Diffuse;float2 TexCoord0;};
-)HLSL";
- // Keep the actual rank/coverage/porosity helpers, excluding unrelated vessel
- // history entry points that require a different atlas and uniform layout.
- const std::string foamSource=WaterFoamShading::Source();
- const size_t foamBegin=foamSource.find("float waterFoamNoiseRank("),foamEnd=foamSource.find("float waterFoamMicroCoverage(");
- CHECK(foamBegin!=std::string::npos&&foamEnd!=std::string::npos&&foamEnd>foamBegin);
- if(foamBegin==std::string::npos||foamEnd==std::string::npos||foamEnd<=foamBegin)return;
- ps+=foamSource.substr(foamBegin,foamEnd-foamBegin);ps+=WaterCoastalPresentation::Source();
- ps+=R"HLSL(
-float4 main(float4 pixel:SV_Position):SV_Target0 {
- uint row=(uint)pixel.y;Query q=Q[row];Input input;
- input.Position=float4(.5,row+.5,.5,1);input.Diffuse=float4(q.q[3].y,1,1,1);input.TexCoord0=float2(q.q[3].w,0);
- float time=q.q[6].x,baseLevel=5,fftWeight=q.q[1].z,foamFootprint=.25;
- float2 wavePosition=float2(1,row),correctionSlope=q.q[4].xy;
- float3 world=float3(0,row,5),view=float3(0,0,q.q[6].y);
- float surfaceTerrainHeight=q.q[2].z;
- float4 WaterParameters=float4(time,q.q[4].z,0,0),OpticalParameters=float4(0,0,q.q[5].z,q.q[4].w);
- float4 TerrainParameters=float4(-4.5,30,1,q.q[5].y),SceneParameters=float4(1,1,1.0/30,q.q[5].x);
- float4 CoastalArea=float4(q.q[5].w,-.5,2,30);
- float4 CoastalParams=float4(q.q[0].w,baseLevel+q.q[1].x,time-q.q[0].z,time+q.q[1].y);
- // Deliberately wrong refracted/fallback values arm use of original depth instead.
- float depth=100;float3 bottom=float3(0,0,-100),shoreSceneBottom=bottom;
-)HLSL";
- ps+=production.substr(begin,end-begin);
- ps+=R"HLSL(
- if(pixel.x<1)return float4(gpuCoastRaw,gpuCoastGate,gpuCoastFoam,1);
- float2 moments=waterCoastalAtTime(q.q[0].xy,q.q[0].z);
- return float4(moments,waterCoastalModelGate(q.q[1].z,q.q[1].w,q.q[3].w,q.q[4].xy),
- waterCoastalViewValid(CoastalArea,CoastalParams,wavePosition,baseLevel,time)?1:0);
-})HLSL";
- struct Resources{SDL_GPUDevice*d=nullptr;SDL_GPUTexture*t[3]={},*target=nullptr;SDL_GPUSampler*point=nullptr;SDL_GPUShader*vs=nullptr,*ps=nullptr;SDL_GPUGraphicsPipeline*pipeline=nullptr;
- ~Resources(){if(target)SDL_ReleaseGPUTexture(d,target);for(auto*p:t)if(p)SDL_ReleaseGPUTexture(d,p);if(point)SDL_ReleaseGPUSampler(d,point);
- if(pipeline)SDL_ReleaseGPUGraphicsPipeline(d,pipeline);if(vs)SDL_ReleaseGPUShader(d,vs);if(ps)SDL_ReleaseGPUShader(d,ps);}}r;r.d=frame->Device();
- std::vector<unsigned char>spirv;std::string error;bool ok=SDL3_Compile_HLSL_To_SPIRV(WaterFftSpectrum::VertexHlsl(),true,spirv,error);CHECK(ok);if(!ok)return;
- r.vs=SDL3_Create_Shader(r.d,spirv,true,error);CHECK(r.vs);if(!r.vs)return;
- ok=SDL3_Compile_HLSL_To_SPIRV(ps,false,spirv,error);CHECK(ok);if(!ok){printf("coastal presentation PS: %s\n",error.c_str());return;}
- unsigned samplers=0,buffers=0;SDL3_Shader_Slots(spirv,false,samplers,buffers);CHECK(samplers==16&&buffers==1);if(samplers!=16||buffers!=1)return;
- r.ps=SDL3_Create_Shader(r.d,spirv,false,error);CHECK(r.ps);if(!r.ps)return;
- SDL_GPUSamplerCreateInfo si={};si.min_filter=si.mag_filter=SDL_GPU_FILTER_NEAREST;si.mipmap_mode=SDL_GPU_SAMPLERMIPMAPMODE_NEAREST;
- si.address_mode_u=si.address_mode_v=si.address_mode_w=SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
- r.point=SDL_CreateGPUSampler(r.d,&si);CHECK(r.point);if(!r.point)return;
- SDL_GPUColorTargetDescription colour={};colour.format=SDL_GPU_TEXTUREFORMAT_R32G32B32A32_FLOAT;
- SDL_GPUGraphicsPipelineCreateInfo pi={};pi.vertex_shader=r.vs;pi.fragment_shader=r.ps;pi.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;
- pi.target_info.color_target_descriptions=&colour;pi.target_info.num_color_targets=1;r.pipeline=SDL_CreateGPUGraphicsPipeline(r.d,&pi);CHECK(r.pipeline);if(!r.pipeline)return;
- SDL_GPUTextureCreateInfo ti={};ti.type=SDL_GPU_TEXTURETYPE_2D;ti.format=colour.format;ti.usage=SDL_GPU_TEXTUREUSAGE_SAMPLER;ti.width=1;ti.height=rows;ti.layer_count_or_depth=ti.num_levels=1;
- for(auto &texture:r.t){texture=SDL_CreateGPUTexture(r.d,&ti);CHECK(texture);if(!texture)return;}
- ti.width=columns;ti.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET;r.target=SDL_CreateGPUTexture(r.d,&ti);CHECK(r.target);if(!r.target)return;
- const unsigned bytes=rows*4*sizeof(float);std::vector<float> data(rows*4*3,0);
- // Canonical phase support is B. Deliberately unrelated optical R arms the
- // regression: reading R would reject otherwise matching coastal FFT support.
- for(unsigned row=0;row<rows;++row){data[row*4]=.73f;data[row*4+2]=queries[row].q[1][3];data[rows*4+row*4]=queries[row].q[2][0];
- data[rows*8+row*4]=queries[row].q[0][0];data[rows*8+row*4+1]=queries[row].q[0][1];}
- SDL_GPUTransferBufferCreateInfo transferInfo={};transferInfo.usage=SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD;transferInfo.size=bytes*3;
- SDL_GPUTransferBuffer *transfer=SDL_CreateGPUTransferBuffer(r.d,&transferInfo);CHECK(transfer);if(!transfer)return;
- void*mapped=SDL_MapGPUTransferBuffer(r.d,transfer,false);CHECK(mapped);if(!mapped){SDL_ReleaseGPUTransferBuffer(r.d,transfer);return;}
- memcpy(mapped,data.data(),bytes*3);SDL_UnmapGPUTransferBuffer(r.d,transfer);CHECK(frame->Flush());
- SDL_GPUCommandBuffer *upload=SDL_AcquireGPUCommandBuffer(r.d);CHECK(upload);if(!upload){SDL_ReleaseGPUTransferBuffer(r.d,transfer);return;}
- SDL_GPUCopyPass *copy=SDL_BeginGPUCopyPass(upload);CHECK(copy);if(!copy){SDL_CancelGPUCommandBuffer(upload);SDL_ReleaseGPUTransferBuffer(r.d,transfer);return;}
- for(unsigned i=0;i<3;++i){SDL_GPUTextureTransferInfo source={};source.transfer_buffer=transfer;source.offset=i*bytes;source.pixels_per_row=1;source.rows_per_layer=rows;
- SDL_GPUTextureRegion region={};region.texture=r.t[i];region.w=1;region.h=rows;region.d=1;SDL_UploadToGPUTexture(copy,&source,&region,false);}
- SDL_EndGPUCopyPass(copy);CHECK(SDL_SubmitGPUCommandBuffer(upload));SDL_ReleaseGPUTransferBuffer(r.d,transfer);
- auto render=[&](){SDL_GPUCommandBuffer *commands=SDL_AcquireGPUCommandBuffer(r.d);CHECK(commands);if(!commands)return std::vector<float>();
- SDL_GPUColorTargetInfo target={};target.texture=r.target;target.load_op=SDL_GPU_LOADOP_DONT_CARE;target.store_op=SDL_GPU_STOREOP_STORE;
- SDL_GPURenderPass *pass=SDL_BeginGPURenderPass(commands,&target,1,nullptr);CHECK(pass);if(!pass){SDL_CancelGPUCommandBuffer(commands);return std::vector<float>();}
- SDL_BindGPUGraphicsPipeline(pass,r.pipeline);SDL_GPUTextureSamplerBinding bindings[16]={};for(auto &binding:bindings){binding.texture=r.t[0];binding.sampler=r.point;}
- bindings[6].texture=r.t[1];bindings[15].texture=r.t[2];SDL_BindGPUFragmentSamplers(pass,0,bindings,16);
- SDL_PushGPUFragmentUniformData(commands,0,queries.data(),unsigned(queries.size()*sizeof(Query)));SDL_DrawGPUPrimitives(pass,3,1,0,0);
- SDL_EndGPURenderPass(pass);CHECK(SDL_SubmitGPUCommandBuffer(commands));return read_float_targets(frame,&r.target,1,columns,rows);};
- const auto actual=render(),repeat=render();CHECK(actual==repeat&&actual.size()==rows*columns*4);if(actual.size()!=rows*columns*4)return;
- auto clamp=[](double x,double lo,double hi){return (std::max)(lo,(std::min)(hi,x));};
- auto smooth=[&](double a,double b,double x){const double t=clamp((x-a)/(b-a),0,1);return t*t*(3-2*t);};
- auto band=[&](double coverage,double cell){const double ratio=.25/cell,unresolved=smooth(.5,1.5,ratio),width=clamp(ratio*.5,cell==1?.08:.01,.5);
- double cutoff=coverage;if(coverage<width)cutoff=-width+std::sqrt(4*width*coverage);else if(coverage>1-width)cutoff=1+width-std::sqrt(4*width*(1-coverage));
- const double resolved=clamp((cutoff-.5+width)/(2*width),0,1);return resolved*(1-unresolved)+coverage*unresolved;};
- double maximum=0;unsigned admitted=0,rejected=0;
- for(unsigned row=0;row<rows;++row){const auto&q=queries[row].q;double density=0,age=0;
- if(std::isfinite(q[0][0])&&q[0][0]>0&&q[0][0]<=16&&q[0][1]>=0&&q[0][1]<=1024&&q[0][2]>=0&&q[0][2]<14){
- age=q[0][1]/double(q[0][0])+q[0][2];if(age<14)density=q[0][0]*std::exp(-q[0][2]/5.0);else age=0;}
- const double model=(1-smooth(.015,.06,std::abs(q[1][2]-q[1][3])))*(1-smooth(.02,.15,std::abs(q[3][3])))
- *(1-smooth(.002,.02,std::hypot(q[4][0],q[4][1])));
- const bool view=q[0][3]>=.5&&std::abs(q[1][0])<=.01&&std::abs(q[1][1])<=.0001&&q[0][2]+q[1][1]>=0
- &&q[6][0]-q[0][2]>=0&&q[5][3]<=1&&q[5][3]+2>=1;
- const bool enabled=q[4][2]<.5&&q[4][3]>.5&&q[5][0]>.5&&q[5][1]>.5&&q[5][2]>.5&&view;
- double raw=0,gate=0;
- if(enabled&&density>0){const double coverage=-std::expm1(-density),aged=smooth(.4,3,age),patch=std::sqrt(coverage);
- const double porous=band(patch,1)*band(patch,.35);
- raw=(coverage*(1-aged)+porous*aged)*(1-smooth(8,14,age));
- if(model>0&&raw>0&&q[2][0]>=0&&q[2][0]<.999999&&q[2][1]<=4.92&&(q[2][1]-5)*q[6][1]<-.01
- &&q[2][2]<(std::min)(4.92,4.85)&&q[2][3]<4.85){
- gate=model*smooth(0,.8,5-q[2][1])*smooth(.15,.8,5-q[2][2])*(1-smooth(.5,1.5,std::abs(q[2][1]-q[3][0])))
- *smooth(.001,.1,(std::min)(clamp(q[3][1],0,1),clamp(q[3][2],0,1)));}
- }
- const double expected[8]={raw,gate,raw*gate,1,density,age,model,view?1.:0.};
- for(unsigned c=0;c<8;++c){const double error=std::abs(actual[row*8+c]-expected[c]);maximum=(std::max)(maximum,error);
- if(!(std::isfinite(actual[row*8+c])&&error<.00003))printf("coast presentation row%u ch%u got%.9g expected%.9g\n",row,c,actual[row*8+c],expected[c]);
- CHECK(std::isfinite(actual[row*8+c])&&error<.00003);}
- admitted+=raw*gate>0;rejected+=raw*gate==0;
- }
- CHECK(admitted>=5&&rejected>=20);
- for(unsigned c=0;c<4;++c)CHECK(actual[c]==actual[28*8+c]); // shifted absolute time, same age: no material oscillator
- CHECK(actual[1*8+2]>0&&actual[2*8+2]>0); // R0 and R1 are both supported
- CHECK(actual[23*8+2]==0&&actual[12*8+2]==0&&actual[16*8+2]==0); // false fallback, object, known hull armed
- printf("sdl_gpu_frame_selfcheck: coastal presentation actual injection %u cases, independent moment/model/original-depth/wet/porosity oracle max%.9g admitted%u rejected%u repeat exact; absolute-time shift exact\n",rows,maximum,admitted,rejected);
-}
-#endif // __linux__
-
int main()
{
if (!SDL_Init(SDL_INIT_VIDEO)) {
@@ -8165,19 +6588,12 @@ int main()
}
printf("sdl_gpu_frame_selfcheck: %s\n", SDL_GetGPUDeviceDriver(frame->Device()));
check_gpu_fft_ocean(frame);
- check_gpu_water_coastal_incident(frame);
- check_gpu_coastal_surf_from_ocean(frame);
check_gpu_water_vertex_uniform_order(frame);
check_gpu_modern_water_material(frame);
check_gpu_water_visual_uniform_order(frame);
check_gpu_water_visual_query(frame);
#if defined(__linux__)
check_gpu_water_visual_zero_effect_skip(frame);
-#endif
- check_gpu_coastal_surf_owner(frame);
- check_gpu_coastal_surf_view(frame);
-#if defined(__linux__)
- check_gpu_water_coastal_presentation(frame);
#endif
check_gpu_foam_history_upload(frame);
check_gpu_foam_history_tiles(frame);
@@ -8188,9 +6604,7 @@ int main()
check_gpu_foam_environment(frame);
check_gpu_water_shore_source(frame);
#endif
- check_gpu_water_coastal_surf_core(frame);
#if defined(__linux__)
- check_gpu_water_coastal_crest(frame);
check_gpu_water_shore_front(frame);
check_gpu_water_shore_depth_gate(frame);
check_gpu_water_shore_history(frame);
@@ -8200,7 +6614,6 @@ int main()
check_gpu_foam_material(frame);
check_gpu_coastal_material(frame);
#endif
- check_gpu_vessel_wave_model(frame);
check_gpu_vessel_hull_damping(frame);
check_gpu_water_wave_cage(frame);
#if defined(__linux__)
@@ -8209,8 +6622,6 @@ int main()
check_gpu_water_bow_shoulder(frame);
check_gpu_water_bow_refinement(frame);
check_gpu_fft_vessel_composition(frame);
- check_gpu_fft_vessel_composition(frame,true);
- check_gpu_fft_vessel_composition(frame,true,true);
check_gpu_wave_model(frame);
check_gpu_ocean_wave_model(frame);
#if defined(__linux__)
diff --git a/GeneralsMD/Code/Tests/test_shader_sdl.cpp b/GeneralsMD/Code/Tests/test_shader_sdl.cpp
index 084ec1954..b20fc858c 100644
--- a/GeneralsMD/Code/Tests/test_shader_sdl.cpp
+++ b/GeneralsMD/Code/Tests/test_shader_sdl.cpp
@@ -314,9 +314,7 @@ TEST(fft_water_vertex_and_pixel_compile_with_separate_texture_bindings)
CHECK(compiled);if(!compiled) continue;
unsigned samplers=0,buffers=0;
SDL3_Shader_Slots(spirv,isVertex,samplers,buffers);
- const char *surfOption=getenv("ZH_WATER_SURF_GPU");
- const bool surfEnabled=surfOption && strcmp(surfOption,"1")==0;
- CHECK_EQ(samplers,isVertex?4u:(surfEnabled?16u:15u));CHECK_EQ(buffers,isVertex?2u:(WaterHullVisual::Enabled()?4u:1u));
+ CHECK_EQ(samplers,isVertex?4u:15u);CHECK_EQ(buffers,isVertex?2u:4u);
const char *validator=getenv("ZH_SPIRV_VAL");
if(validator && *validator) CHECK(validate(validator,spirv,log));
CHECK(SDL3_Translate_SPIRV_To_MSL(spirv,isVertex,msl,log));
@@ -326,23 +324,6 @@ TEST(fft_water_vertex_and_pixel_compile_with_separate_texture_bindings)
namespace {
-// Restore launch-time shader options after testing each production variant.
-struct SavedShaderOption
-{
- const char *name;
- bool present;
- std::string value;
-
- explicit SavedShaderOption(const char *key) : name(key), present(getenv(key) != NULL),
- value(present ? getenv(key) : "") {}
-
- ~SavedShaderOption()
- {
- if (present) setenv(name, value.c_str(), 1);
- else unsetenv(name);
- }
-};
-
struct WaterUniformMember
{
const char *name;
@@ -376,8 +357,6 @@ const WaterUniformMember WaterUniformMembers[] = {
WATER_UNIFORM_MEMBER(FoamHistoryParameters),
WATER_UNIFORM_MEMBER(ContactHullData),
WATER_UNIFORM_MEMBER(FoamFillLights),
- WATER_UNIFORM_MEMBER(CoastalArea),
- WATER_UNIFORM_MEMBER(CoastalParams),
WATER_UNIFORM_MEMBER(MaterialColor),
WATER_UNIFORM_MEMBER(MaterialParameters)
};
@@ -456,18 +435,13 @@ void checkCompiledWaterUniformLayout(const std::string &source, bool vertex,
TEST(modern_water_compiled_uniform_layout_matches_every_cpu_upload_field)
{
- SavedShaderOption contact("ZH_WATER_HULL_CONTACT"), debug("ZH_WATER_DEBUG");
- CHECK(unsetenv(debug.name) == 0);
- for (unsigned visual = 0; visual < 2; ++visual) {
- CHECK(setenv(contact.name, visual ? "mesh" : "0", 1) == 0);
- for (const EngineShaderProgram program : {ENGINE_SHADER_WATER_TRAPEZOID, ENGINE_SHADER_WATER_RIVER}) {
- PixelPipelineDescription pipeline = {};
- std::string source;
- const bool generated = EngineShader_Pixel_Program(program, pipeline, source,
- COMBINER_SHADER_TARGET_SDL3_GPU);
- CHECK(generated);
- if (generated) checkCompiledWaterUniformLayout(source, false, "CombinerConstants", visual != 0);
- }
+ for (const EngineShaderProgram program : {ENGINE_SHADER_WATER_TRAPEZOID, ENGINE_SHADER_WATER_RIVER}) {
+ PixelPipelineDescription pipeline = {};
+ std::string source;
+ const bool generated = EngineShader_Pixel_Program(program, pipeline, source,
+ COMBINER_SHADER_TARGET_SDL3_GPU);
+ CHECK(generated);
+ if (generated) checkCompiledWaterUniformLayout(source, false, "CombinerConstants", true);
}
VertexPipelineDescription description = shader_cases_detail::plain_vertex();
@@ -1354,169 +1328,3 @@ TEST(authored_surf_wrapper_compiles_with_original_fixed_function_fog_and_alpha)
std::string bad="not a generated combiner";const std::string saved=bad;
CHECK(!WaterShoreOverlay::WrapPixel(bad));CHECK(bad==saved);
}
-
-
-#if defined(__linux__)
-// Full Modern shader integration, including its optional production diagnostics.
-TEST(shore_source_terms_reports_actual_front_and_is_absent_from_normal_source)
-{
- struct RestoreDebug {
- bool had;std::string value;
- RestoreDebug(){const char*p=getenv("ZH_WATER_DEBUG");had=p!=nullptr;value=p?p:"";}
- ~RestoreDebug(){if(had)setenv("ZH_WATER_DEBUG",value.c_str(),1);else unsetenv("ZH_WATER_DEBUG");}
- }restore;
- for(auto program:{ENGINE_SHADER_WATER_TRAPEZOID,ENGINE_SHADER_WATER_RIVER}) {
- PixelPipelineDescription description={};std::string normal,diagnostic;
- CHECK(unsetenv("ZH_WATER_DEBUG")==0);
- CHECK(EngineShader_Pixel_Program(program,description,normal,COMBINER_SHADER_TARGET_SDL3_GPU));
- CHECK(setenv("ZH_WATER_DEBUG","shore-source-terms",1)==0);
- CHECK(EngineShader_Pixel_Program(program,description,diagnostic,COMBINER_SHADER_TARGET_SDL3_GPU));
- const std::string start="\n // Shore source attribution (M5i):";
- const std::string finish=" // End shore source attribution. Only the opt-in diagnostic recomputes residence.\n";
- const size_t begin=diagnostic.find(start),end=diagnostic.find(finish,begin);
- CHECK(begin!=std::string::npos&&end!=std::string::npos);
- if(begin==std::string::npos||end==std::string::npos)continue;
- const std::string block=diagnostic.substr(begin,end+finish.size()-begin);
- CHECK(block.find("waterShoreFrontFresh(shoreRate,sourceTermsFront.y)")!=std::string::npos);
- CHECK(block.find("shoreSupport)*fixedShoreFront.x")!=std::string::npos);
- CHECK(block.find("waterShoreFresh(")==std::string::npos); // no accidental old-cap normalization
- CHECK(block.find("fixedShoreRate/ShoreMaximumRate,finalShoreCoverage,1.0)")!=std::string::npos);
- std::string stripped=diagnostic;stripped.erase(begin,end+finish.size()-begin);
- CHECK(stripped==normal);CHECK(normal.find("sourceTermsFront")==std::string::npos);
- std::vector<unsigned char>spirv;std::string log;
- const bool compiled=SDL3_Compile_HLSL_To_SPIRV(diagnostic,false,spirv,log);
- if(!compiled)printf(" actual shore-source-terms program %d: %s\n",int(program),log.c_str());
- CHECK(compiled);
- }
-}
-
-TEST(coastal_surf_optional_texture_contract_compiles_with_exact_hull_contact)
-{
- // Exercise both branches explicitly rather than relying on the test process's
- // ambient environment. Keep the existing larger shader matrix unchanged.
- struct SavedOption {
- const char *key;bool had;std::string value;
- explicit SavedOption(const char *k):key(k),had(getenv(k)!=nullptr),value(getenv(k)?getenv(k):""){}
- ~SavedOption(){if(had)setenv(key,value.c_str(),1);else unsetenv(key);}
- } surf("ZH_WATER_SURF_GPU"),contact("ZH_WATER_HULL_CONTACT"),lift("ZH_WATER_BOW_LIFT"),
- shoulder("ZH_WATER_BOW_SHOULDER"),crest("ZH_WATER_COAST_CREST"),debug("ZH_WATER_DEBUG");
- CHECK(unsetenv("ZH_WATER_DEBUG")==0);
- CHECK(setenv("ZH_WATER_BOW_LIFT","floor",1)==0);
- CHECK(setenv("ZH_WATER_BOW_SHOULDER","contour",1)==0);
- CHECK(setenv("ZH_WATER_COAST_CREST","1",1)==0);
- PixelPipelineDescription pipeline={};
- for(unsigned hull=0;hull<2;++hull) {
- CHECK(setenv("ZH_WATER_HULL_CONTACT",hull?"mesh":"0",1)==0);
- std::string riverWithoutSurf,flatWithoutSurf;
- for(unsigned enabled=0;enabled<2;++enabled) {
- CHECK(setenv("ZH_WATER_SURF_GPU",enabled?"1":"0",1)==0);
- for(unsigned river=0;river<2;++river) {
- std::string pixel,log,msl,why;std::vector<unsigned char>spirv;
- const bool generated=EngineShader_Pixel_Program(river?ENGINE_SHADER_WATER_RIVER:ENGINE_SHADER_WATER_TRAPEZOID,
- pipeline,pixel,COMBINER_SHADER_TARGET_SDL3_GPU);
- CHECK(generated);if(!generated)continue;
- if(!enabled){if(river)riverWithoutSurf=pixel;else flatWithoutSurf=pixel;}
- if(enabled&&river)CHECK(pixel==riverWithoutSurf); // river source exactly independent of surf switch
- CHECK((pixel.find("float gpuCoastFoam=")!=std::string::npos)==bool(enabled&&!river));
- const bool compiled=SDL3_Compile_HLSL_To_SPIRV(pixel,false,spirv,log);
- if(!compiled)printf("coastal surf shader hull%u surf%u river%u: %s\n",hull,enabled,river,log.c_str());
- CHECK(compiled);if(!compiled)continue;
- unsigned samplers=0,buffers=0;SDL3_Shader_Slots(spirv,false,samplers,buffers);
- CHECK_EQ(samplers,enabled&&!river?16u:15u);CHECK_EQ(buffers,hull?4u:1u);
- const char *validator=getenv("ZH_SPIRV_VAL");
- if(validator&&*validator)CHECK(validate(validator,spirv,log));
- const bool translated=SDL3_Translate_SPIRV_To_MSL(spirv,false,msl,log);
- CHECK(translated);if(translated)CHECK(slots_kept(msl,samplers,why));
- }
- }
- // Only the exact token opts in; unset and misleading values retain the
- // same generated flat program as the explicit off mode, not merely its slots.
- for(const char *value:{static_cast<const char *>(nullptr),"true","01"}) {
- if(value)CHECK(setenv("ZH_WATER_SURF_GPU",value,1)==0);else CHECK(unsetenv("ZH_WATER_SURF_GPU")==0);
- std::string pixel;CHECK(EngineShader_Pixel_Program(ENGINE_SHADER_WATER_TRAPEZOID,pipeline,pixel,COMBINER_SHADER_TARGET_SDL3_GPU));
- CHECK(pixel==flatWithoutSurf);
- }
- }
-}
-
-TEST(water_mesh_contact_diagnostics_compile_with_the_shared_contact_material)
-{
- struct SavedOption {
- const char *key;bool had;std::string value;
- explicit SavedOption(const char *k):key(k),had(getenv(k)!=nullptr),value(getenv(k)?getenv(k):""){}
- ~SavedOption(){if(had)setenv(key,value.c_str(),1);else unsetenv(key);}
- } contact("ZH_WATER_HULL_CONTACT"),debug("ZH_WATER_DEBUG");
- CHECK(unsetenv(contact.key)==0);
- PixelPipelineDescription pipeline={};
- for(const char *mode:{"contact-mesh-query","contact-mesh-sources"}) {
- CHECK(setenv(debug.key,mode,1)==0);
- std::string pixel,log,msl,why;std::vector<unsigned char> spirv;
- CHECK(EngineShader_Pixel_Program(ENGINE_SHADER_WATER_TRAPEZOID,pipeline,pixel,COMBINER_SHADER_TARGET_SDL3_GPU));
- const bool compiled=SDL3_Compile_HLSL_To_SPIRV(pixel,false,spirv,log);
- if(!compiled)printf("mesh contact diagnostic %s: %s\n",mode,log.c_str());
- CHECK(compiled);if(!compiled)continue;
- unsigned samplers=0,buffers=0;SDL3_Shader_Slots(spirv,false,samplers,buffers);
- CHECK_EQ(buffers,4u);
- const char *validator=getenv("ZH_SPIRV_VAL");
- if(validator && *validator)CHECK(validate(validator,spirv,log));
- CHECK(SDL3_Translate_SPIRV_To_MSL(spirv,false,msl,log));
- CHECK(slots_kept(msl,samplers,why));
- }
-}
-
-TEST(water_plain_launch_matches_explicit_validated_settings)
-{
- struct SavedOption {
- const char *key;bool had;std::string value;
- explicit SavedOption(const char *k):key(k),had(getenv(k)!=nullptr),value(getenv(k)?getenv(k):""){}
- ~SavedOption(){if(had)setenv(key,value.c_str(),1);else unsetenv(key);}
- } contact("ZH_WATER_HULL_CONTACT"),lift("ZH_WATER_BOW_LIFT"),
- shoulder("ZH_WATER_BOW_SHOULDER"),debug("ZH_WATER_DEBUG");
- const char *keys[]={contact.key,lift.key,shoulder.key};
- const char *modes[]={"mesh","floor","contour"};
- auto configure=[&](unsigned disabled,bool explicitModes) {
- for(unsigned i=0;i<3;++i) {
- if(disabled&(1u<<i))CHECK(setenv(keys[i],"0",1)==0);
- else if(explicitModes)CHECK(setenv(keys[i],modes[i],1)==0);
- else CHECK(unsetenv(keys[i])==0);
- }
- CHECK(WaterHullVisual::Enabled()==!(disabled&1u));
- CHECK(WaterBowLift::Enabled()==!(disabled&2u));
- CHECK(WaterBowShoulder::Enabled()==!(disabled&4u));
- };
- VertexPipelineDescription description=shader_cases_detail::plain_vertex();
- description.FVF=0x252;description.LightingEnabled=false;description.StageCount=4;
- for(unsigned i=0;i<4;++i) {
- description.Stages[i].TextureCoordinateIndex=i<2?i:0;
- description.Stages[i].TextureTransformFlags=FF_TTFF_DISABLE;
- }
- std::string fixedVertex;
- CHECK(VertexShader_Generate(description,VERTEX_SHADER_TARGET_D3D11,fixedVertex));
- PixelPipelineDescription pipeline={};
- // Check each independent opt-out as well as the ordinary all-enabled launch.
- // Complete generated programs must match, including diagnostics and resource layouts.
- for(unsigned disabled=0;disabled<8;++disabled) {
- configure(disabled,false);std::string defaultVertex=fixedVertex;
- CHECK(WaterFftSampling::WrapVertex(defaultVertex));
- configure(disabled,true);std::string explicitVertex=fixedVertex;
- CHECK(WaterFftSampling::WrapVertex(explicitVertex));
- CHECK(defaultVertex==explicitVertex);
- for(const char *mode:{static_cast<const char *>(nullptr),"contact-mesh","bow-retention",
- "contact-mesh-query","contact-mesh-sources"}) {
- if(mode)CHECK(setenv(debug.key,mode,1)==0);else CHECK(unsetenv(debug.key)==0);
- for(auto program:{ENGINE_SHADER_WATER_TRAPEZOID,ENGINE_SHADER_WATER_RIVER}) {
- configure(disabled,false);std::string defaultPixel;
- CHECK(EngineShader_Pixel_Program(program,pipeline,defaultPixel,COMBINER_SHADER_TARGET_SDL3_GPU));
- configure(disabled,true);std::string explicitPixel;
- CHECK(EngineShader_Pixel_Program(program,pipeline,explicitPixel,COMBINER_SHADER_TARGET_SDL3_GPU));
- CHECK(defaultPixel==explicitPixel);
- }
- }
- }
- // Preserve the previous interpretation of explicit non-matching values.
- for(const char *value:{"","0","off","true","invalid"}) {
- for(const char *key:keys)CHECK(setenv(key,value,1)==0);
- CHECK(!WaterHullVisual::Enabled());CHECK(!WaterBowLift::Enabled());CHECK(!WaterBowShoulder::Enabled());
- }
-}
-#endif // __linux__
diff --git a/GeneralsMD/Code/Tests/test_water_grid.cpp b/GeneralsMD/Code/Tests/test_water_grid.cpp
index 5486bf0a4..90757ab5e 100644
--- a/GeneralsMD/Code/Tests/test_water_grid.cpp
+++ b/GeneralsMD/Code/Tests/test_water_grid.cpp
@@ -52,7 +52,6 @@
#include "Common/NameKeyGenerator.h"
#include "GameLogic/WaterGridMotion.h"
#include "Platform/WaterFoamParticlePolicy.h"
-#include "Platform/WaterCoastalCrest.h"
#include <limits>
#include <string>
@@ -173,6 +172,7 @@ TEST(water_grid_unstepped_is_not_the_golden)
#include "Platform/WaterSurfaceModel.h"
#include "Platform/WaterProjectedMesh.h"
#include "Platform/WaterBowRefinement.h"
+#include "WaterBowShoulderTest.h"
#include "Platform/WaterFftGeometry.h"
#include "Platform/WaterVesselMotion.h"
#include "Platform/WaterFoamHistory.h"
@@ -2999,127 +2999,78 @@ TEST(water_bow_refinement_invalid_input_is_atomic_and_zero_levels_are_exact)
}
namespace {
-// Independent scalar oracle: no shared production coefficients, gradient helper or
-// projection expression. Numeric derivatives below must agree with the emitted model.
+// Independent parameter oracle with no shared production coefficients.
std::array<double,3> pressureTestParameters(double beam,double speed)
{
- const double u=(std::max)(0.0,(std::min)(speed,250.0)-.3);
+ const double u=(std::max)(0.0,(std::min)(speed,250.0)-double(.3f));
return {{(std::max)(9.0,(std::min)(32.0,6+1.2*beam)),
(std::max)(4.0,(std::min)(60.0,1.5+.95*beam)),
(std::max)(3.0,(std::min)(8.0,1.8*std::sqrt(beam)))*u*u/(u*u+26*26)}};
}
-double pressureTestScalar(const std::array<double,3> &p,double along,double across)
-{
- const double q=across/p[1],s=along/p[0]+.6*(std::sqrt(1+q*q)-1);
- return p[2]*std::exp(-s*s-q*q);
-}
}
-TEST(water_bow_pressure_size_speed_and_half_height_are_independently_measured)
+TEST(water_bow_pressure_size_and_speed_parameters_are_independently_measured)
{
- using namespace WaterVesselWaves;
- for(float beam:{0.0f,.1f,2.5f,6.0f,8.37f,22.0f,54.0f,100.0f}) {
- double previous=-1;
- for(float speed:{0.0f,.3f,.3001f,1.0f,5.0f,14.0f,26.3f,40.0f,70.0f,250.0f,500.0f}) {
- const auto expected=pressureTestParameters(beam,speed);const auto p=BowPressure(beam,speed);
- CHECK_NEAR(p.along,expected[0],.00001);CHECK_NEAR(p.across,expected[1],.00001);CHECK_NEAR(p.amplitude,expected[2],.000003);
- CHECK(p.along>=9 && p.along<=32 && p.across>=4 && p.across<=60 && p.amplitude>=0 && p.amplitude<=8);
- CHECK(p.amplitude>=previous);previous=p.amplitude;
- const auto peak=EvaluateBowPressure(p,0,0);CHECK_NEAR(peak.height,expected[2],.000003);
- CHECK(peak.dAlong==0 && peak.dAcross==0);
- if(speed<=.3f) CHECK(peak.height==0);
- if(speed<1) continue;
- // Solve for the actual half-height point by scalar bisection. A stale
- // 8-unit width or sqrt(2) Gaussian convention cannot satisfy this.
- double lo=0,hi=2*expected[0];
- for(unsigned iteration=0;iteration<48;++iteration) {
- const double x=(lo+hi)*.5;if(pressureTestScalar(expected,x,0)>expected[2]*.5)lo=x;else hi=x;
- }
- CHECK_NEAR(EvaluateBowPressure(p,float((lo+hi)*.5),0).height,expected[2]*.5,.000003);
- lo=0;hi=2*expected[1];
- for(unsigned iteration=0;iteration<48;++iteration) {
- const double y=(lo+hi)*.5,u=-.6*expected[0]*(std::sqrt(1+y*y/(expected[1]*expected[1]))-1);
- if(pressureTestScalar(expected,u,y)>expected[2]*.5)lo=y;else hi=y;
- }
- const double y=(lo+hi)*.5,u=-.6*expected[0]*(std::sqrt(1+y*y/(expected[1]*expected[1]))-1);
- CHECK(u<0);CHECK_NEAR(EvaluateBowPressure(p,float(u),float(y)).height,expected[2]*.5,.000003);
- }
- CHECK(BowPressure(beam,70).amplitude>BowPressure(beam,14).amplitude*3);
- CHECK(BowPressure(beam,500).amplitude==BowPressure(beam,250).amplitude);
- }
- const auto small=BowPressure(8.37f,70),large=BowPressure(54,70);
- CHECK(large.along>small.along && large.across>small.across && large.amplitude>small.amplitude);
- // Armed old model: it saturates at speed14 and peaks eight units beyond
- // the contact bow. Neither behavior is allowed to pass as pressure response.
- CHECK(std::abs(1.9*std::exp(-1.0)-small.amplitude)>2);
- CHECK(std::abs(BowPressure(8.37f,14).amplitude-BowPressure(8.37f,70).amplitude)>2);
-}
-
-TEST(water_bow_pressure_independent_derivatives_curvature_and_bounds)
-{
- using namespace WaterVesselWaves;
- for(float beam:{.1f,6.0f,8.37f,22.0f,54.0f,100.0f}) for(float speed:{.31f,5.0f,14.0f,40.0f,70.0f,250.0f}) {
- const auto expected=pressureTestParameters(beam,speed);const auto p=BowPressure(beam,speed);
- for(double a:{-4.0,-1.7,-.7071067811865475,0.0,.31,.7071067811865475,1.7,4.0})
- for(double b:{-3.0,-1.3,-.5,0.0,.5,1.3,3.0}) {
- const float x=float(a*expected[0]),y=float(b*expected[1]);const auto value=EvaluateBowPressure(p,x,y);
- constexpr double step=.0005;
- const double dx=(pressureTestScalar(expected,x+step,y)-pressureTestScalar(expected,x-step,y))/(2*step);
- const double dy=(pressureTestScalar(expected,x,y+step)-pressureTestScalar(expected,x,y-step))/(2*step);
- CHECK_NEAR(value.height,pressureTestScalar(expected,x,y),.000005);
- CHECK_NEAR(value.dAlong,dx,.00002);CHECK_NEAR(value.dAcross,dy,.00002);
- CHECK(value.height>=0 && value.height<=p.amplitude+.000001);
- // Supremum of |2q exp(-q²)| is sqrt(2/e). The curved
- // shoulder adds at most .6 times that across-slope envelope.
- CHECK(std::abs(value.dAlong)<=std::sqrt(2/std::exp(1.0))*expected[2]/expected[0]+.000001);
- CHECK(std::abs(value.dAcross)<=1.6*std::sqrt(2/std::exp(1.0))*expected[2]/expected[1]+.000001);
- const auto mirror=EvaluateBowPressure(p,x,-y);
- CHECK(value.height==mirror.height && value.dAlong==mirror.dAlong && value.dAcross==-mirror.dAcross);
- }
- // Rest is approached quadratically, with a zero slope at the threshold.
- const auto a=BowPressure(beam,.301f),b=BowPressure(beam,.302f);
- CHECK(a.amplitude<.000001 && b.amplitude>3.9f*a.amplitude && b.amplitude<4.1f*a.amplitude);
- }
+ using namespace WaterVesselWaves;
+ for(float beam:{0.0f,.1f,2.5f,6.0f,8.37f,22.0f,54.0f,100.0f}) {
+ double previous=-1;
+ for(float speed:{0.0f,.3f,.3001f,1.0f,5.0f,14.0f,26.3f,40.0f,70.0f,250.0f,500.0f}) {
+ const auto expected=pressureTestParameters(beam,speed);const auto p=BowPressure(beam,speed);
+ CHECK_NEAR(p.along,expected[0],.00001);CHECK_NEAR(p.across,expected[1],.00001);CHECK_NEAR(p.amplitude,expected[2],.000003);
+ CHECK(p.along>=9 && p.along<=32 && p.across>=4 && p.across<=60 && p.amplitude>=0 && p.amplitude<=8);
+ CHECK(p.amplitude>=previous);previous=p.amplitude;
+ if(speed<=.3f) CHECK(p.amplitude==0);
+ }
+ CHECK(BowPressure(beam,70).amplitude>BowPressure(beam,14).amplitude*3);
+ CHECK(BowPressure(beam,500).amplitude==BowPressure(beam,250).amplitude);
+ // Motion starts quadratically, with zero slope at the rest threshold.
+ const auto a=BowPressure(beam,.301f),b=BowPressure(beam,.302f);
+ CHECK(a.amplitude<.000001 && b.amplitude>3.9f*a.amplitude && b.amplitude<4.1f*a.amplitude);
+ }
+ const auto small=BowPressure(8.37f,70),large=BowPressure(54,70);
+ CHECK(large.along>small.along && large.across>small.across && large.amplitude>small.amplitude);
+ CHECK(std::abs(BowPressure(8.37f,14).amplitude-BowPressure(8.37f,70).amplitude)>2);
}
TEST(water_bow_refinement_uses_all_contact_packets_and_velocity_selected_bow)
{
- // Explicitly exercise the legacy Gaussian fallback; contour mode has separate tests.
- using namespace WaterBowRefinement;
- for(unsigned id=1;id<=WaterHullModel::MaxHulls;++id) for(double direction:{0.0,1.3,3.141592653589793,4.7}) {
- const float modelAngle=float(id*.31),speed=float(5+id*3);
- const float vx=speed*float(std::cos(direction)),vy=speed*float(std::sin(direction));
- auto mean=foamTestHull(float(id*37),float(-int(id)*11),vx,vy,modelAngle,7),contact=mean;
- // Unequal and off-axis endpoints prevent collision-bound or symmetric-hull
- // approximations from passing as the shader's actual contact packet.
- contact.data[3][0]=-17;contact.data[3][1]=-2;contact.data[3][2]=23;contact.data[3][3]=3;
- contact.data[1][3]=float(id+2);
- Bow bow;CHECK(MakeBow(id,mean,contact,7,bow,false));
- const double length=std::hypot(double(vx),double(vy)),fx=vx/length,fy=vy/length;
- const double ax=contact.data[1][0],ay=contact.data[1][1];
- double blend=(fx*ax+fy*ay+.25)/.5;blend=(std::max)(0.0,(std::min)(1.0,blend));blend=blend*blend*(3-2*blend);
- const double localX=-17+(23+17)*blend,localY=-2+(3+2)*blend;
- const double x=contact.data[0][0]+ax*localX-ay*localY;
- const double y=contact.data[0][1]+ay*localX+ax*localY;
- CHECK(bow.id==id && bow.level==7);CHECK_NEAR(bow.origin.x,x,2e-5);CHECK_NEAR(bow.origin.y,y,2e-5);
- CHECK_NEAR(bow.centre.x,x+9*fx,2e-5);CHECK_NEAR(bow.centre.y,y+9*fy,2e-5);
- CHECK_NEAR(bow.forward.x,fx,1e-6);CHECK_NEAR(bow.forward.y,fy,1e-6);
- const auto pressure=pressureTestParameters(contact.data[1][3],length);
- CHECK_NEAR(bow.sigmaAlong,pressure[0],.00001);CHECK_NEAR(bow.sigmaAcross,pressure[1],.00001);
- CHECK_NEAR(bow.amplitude,pressure[2],.000003);
- double moving=(length-.3)/(14-.3);moving=(std::max)(0.0,(std::min)(1.0,moving));moving=moving*moving*(3-2*moving);
- CHECK_NEAR(bow.moving,moving,1e-6);
- CHECK(bow.hullCentre.x==contact.data[0][0] && bow.hullCentre.y==contact.data[0][1]);
- contact.data[0][3]=0;Bow fallback;CHECK(MakeBow(id,mean,contact,7,fallback,false));
- const double baseLocal=-12+24*blend;
- CHECK_NEAR(fallback.centre.x,mean.data[0][0]+ax*baseLocal+9*fx,2e-5);
- CHECK_NEAR(fallback.centre.y,mean.data[0][1]+ay*baseLocal+9*fy,2e-5);
- }
+ using namespace WaterBowRefinement;
+ for(unsigned id=1;id<=WaterHullModel::MaxHulls;++id) for(double direction:{0.0,1.3,3.141592653589793,4.7}) {
+ const float modelAngle=float(id*.31),speed=float(5+id*3);
+ const float vx=speed*float(std::cos(direction)),vy=speed*float(std::sin(direction));
+ auto mean=foamTestHull(float(id*37),float(-int(id)*11),vx,vy,modelAngle,7),contact=mean;
+ // An asymmetric contact contour distinguishes its support from the mean hull.
+ const float polygon[8]={-17,-2,23,-3,19,5,-15,4};
+ for(unsigned i=0;i<8;++i)contact.data[4+i/4][i%4]=polygon[i];
+ contact.data[1][3]=float(id+2);
+ Bow bow;CHECK(MakeBow(id,mean,contact,7,bow));
+ const double length=std::hypot(double(vx),double(vy)),fx=vx/length,fy=vy/length;
+ CHECK(bow.id==id && bow.level==7);
+ CHECK_NEAR(bow.forward.x,fx,1e-6);CHECK_NEAR(bow.forward.y,fy,1e-6);
+ const double width=(std::max)(3.0,(std::min)(12.0,contact.data[1][3]*double(.45f)));
+ CHECK_NEAR(bow.sigmaAlong,width,.000001);CHECK_NEAR(bow.sigmaAcross,width,.000001);
+ CHECK_NEAR(bow.contour.amplitude,pressureTestParameters(contact.data[1][3],length)[2],.000003);
+ CHECK_NEAR(bow.centre.x,bow.origin.x+.5*width*fx,.000001);
+ CHECK_NEAR(bow.centre.y,bow.origin.y+.5*width*fy,.000001);
+ CHECK(bow.hullCentre.x==contact.data[0][0] && bow.hullCentre.y==contact.data[0][1]);
+ const double ax=contact.data[1][0],ay=contact.data[1][1];
+ const double localForwardX=fx*ax+fy*ay,localForwardY=-fx*ay+fy*ax;
+ double support=-1e30;
+ for(unsigned i=0;i<4;++i) {
+ CHECK(bow.contour.points[i].x==polygon[i*2] && bow.contour.points[i].y==polygon[i*2+1]);
+ support=(std::max)(support,polygon[i*2]*localForwardX+polygon[i*2+1]*localForwardY);
+ }
+ const double dx=bow.origin.x-bow.hullCentre.x,dy=bow.origin.y-bow.hullCentre.y;
+ CHECK_NEAR((dx*ax+dy*ay)*localForwardX+(-dx*ay+dy*ax)*localForwardY,support,.00001);
+ contact.data[0][3]=0;Bow fallback,expected;
+ CHECK(MakeBow(id,mean,contact,7,fallback));CHECK(MakeBow(id,mean,mean,7,expected));
+ CHECK(fallback.origin.x==expected.origin.x && fallback.origin.y==expected.origin.y);
+ CHECK(fallback.centre.x==expected.centre.x && fallback.centre.y==expected.centre.y);
+ }
}
TEST(water_bow_registration_refinement_encloses_bounded_horizontal_inverse_image)
{
- // Explicitly exercise the legacy Gaussian fallback; contour mode has separate tests.
using namespace WaterBowRefinement;
// CommonSource emits MaxHorizontalDisplacement/sqrt(2) per component; test
// its full axis-aligned square, including diagonal corners, at rotated hulls.
@@ -3127,20 +3078,17 @@ TEST(water_bow_registration_refinement_encloses_bounded_horizontal_inverse_image
for(float beam:{.1f,6.0f,9.0f,30.0f,80.0f})for(unsigned orientation=0;orientation<8;++orientation) {
const double angle=orientation*6.283185307179586/8;
auto hull=foamTestHull(0,0,float(40*std::cos(angle)),float(40*std::sin(angle)),float(angle));hull.data[1][3]=beam;
- Bow bow;CHECK(MakeBow(1,hull,hull,7,bow,false));
+ Bow bow;CHECK(MakeBow(1,hull,hull,7,bow));
Prepared prepared;prepared.bow=bow;prepared.cell={20,20};prepared.desiredDepth=2;prepared.heightGate=1;
const Logical at={80,80};
+ const double amplitude=pressureTestParameters(beam,std::hypot(hull.data[2][0],hull.data[2][1]))[2];
for(int x=-6;x<=6;++x)for(int y=-6;y<=6;++y)
for(double shiftX:{-1.0,-.5,0.0,.5,1.0})for(double shiftY:{-1.0,-.5,0.0,.5,1.0}) {
const double localX=x*bow.sigmaAlong*.6,localY=y*bow.sigmaAcross*.6;
const Point parameter={bow.origin.x+localX*bow.forward.x-localY*bow.forward.y,
bow.origin.y+localX*bow.forward.y+localY*bow.forward.x};
const Point mapped={parameter.x+componentRadius*shiftX,parameter.y+componentRadius*shiftY};
- const double dx=mapped.x-bow.origin.x,dy=mapped.y-bow.origin.y;
- const double q=(-dx*bow.forward.y+dy*bow.forward.x)/bow.sigmaAcross;
- const double u=(dx*bow.forward.x+dy*bow.forward.y)/bow.sigmaAlong+.6*(std::sqrt(1+q*q)-1);
- const double expected=(1-Smooth(1.5,3,std::hypot(u,q)))*
- (1-Smooth(bow.reach-30,bow.reach,std::hypot(mapped.x-bow.hullCentre.x,mapped.y-bow.hullCentre.y)));
+ const double expected=WaterBowShoulderTest::oracle(hull,mapped.x,mapped.y)/amplitude;
CHECK(Demand(prepared,1,at,parameter)+1e-12>=expected);
CHECK(Demand(prepared,2,at,parameter)+1e-12>=expected);
// World expansion must never defeat the hard cell/region cost limits.
@@ -3159,7 +3107,7 @@ TEST(water_bow_refinement_stationary_wrong_level_and_nonfinite_packets_are_rejec
for(float speed:{0.0f,.01f,.29f,.3f}) {
const auto stopped=foamTestHull(0,0,speed,0);CHECK(!MakeBow(1,stopped,stopped,7,bow));
}
- const auto slow=foamTestHull(0,0,.31f,0);CHECK(MakeBow(1,slow,slow,7,bow));CHECK(bow.moving>0 && bow.moving<.00001);
+ const auto slow=foamTestHull(0,0,.31f,0);CHECK(MakeBow(1,slow,slow,7,bow));CHECK(bow.contour.amplitude>0 && bow.contour.amplitude<.00001);
for(unsigned field:{0u,1u,2u,3u}) {
auto invalid=hull;invalid.data[field][0]=NAN;CHECK(!MakeBow(1,invalid,invalid,7,bow));
}
@@ -3169,19 +3117,18 @@ TEST(water_bow_refinement_stationary_wrong_level_and_nonfinite_packets_are_rejec
for(float count:{0.0f,2.0f,13.0f,float(NAN)}) {
auto invalidContact=hull;invalidContact.data[0][3]=count;invalidContact.data[0][0]=NAN;
CHECK(MakeBow(1,hull,invalidContact,7,bow));
- CHECK(bow.origin.x==valid.origin.x && bow.origin.y==valid.origin.y && bow.amplitude==valid.amplitude);
+ CHECK(bow.origin.x==valid.origin.x && bow.origin.y==valid.origin.y && bow.contour.amplitude==valid.contour.amplitude);
}
hull.data[0][3]=0;CHECK(!MakeBow(1,hull,hull,7,bow));
}
TEST(water_bow_refinement_projected_width_matches_independent_ellipse_sampling)
{
- // Explicitly exercise the legacy Gaussian fallback; contour mode has separate tests.
using namespace WaterBowRefinement;
for(unsigned fixture=0;fixture<24;++fixture) {
const double angle=fixture*.319;
const auto hull=foamTestHull(float(fixture*3),float(-int(fixture)*2),float(30*std::cos(angle)),float(30*std::sin(angle)),float(angle));
- Bow bow;CHECK(MakeBow(fixture+1,hull,hull,7,bow,false));View view;
+ Bow bow;CHECK(MakeBow(fixture+1,hull,hull,7,bow));View view;
view.projection=bowTestProjection();view.projection.matrix[0]=.004;view.projection.matrix[1]=fixture*.00003;
view.projection.matrix[3]=-.001;view.projection.matrix[4]=.007;
view.projection.matrix[6]=fixture*.00001;view.projection.matrix[7]=-.00012;
@@ -3201,8 +3148,8 @@ TEST(water_bow_refinement_projected_width_matches_independent_ellipse_sampling)
minor=(std::min)(minor,std::hypot((hi.x-lo.x)*view.width/(4*epsilon),(hi.y-lo.y)*view.height/(4*epsilon)));
}
const double step=(std::max)(1.12*view.width/100,1.12*view.height/80);
- // Independently find the half-height radius of the actual exp(-q*q)
- // packet. Treating its width as a standard deviation adds a wrong sqrt(2).
+ // The contour ridge uses exp(-q*q) inside its compact fade. Independently
+ // find its half-height radius rather than assuming a Gaussian standard deviation.
double halfLo=0,halfHi=2;
for(unsigned i=0;i<48;++i) { const double q=(halfLo+halfHi)*.5;if(std::exp(-q*q)>.5) halfLo=q;else halfHi=q; }
const double expected=(std::max)(0.0,(std::min)(2.0,std::log2(3*step/((halfLo+halfHi)*minor))));
@@ -3218,8 +3165,7 @@ TEST(water_bow_refinement_projected_width_matches_independent_ellipse_sampling)
};
const auto lower=raised(-epsilon),upper=raised(epsilon);
const double verticalPixels=std::hypot((upper.x-lower.x)*view.width/(4*epsilon),(upper.y-lower.y)*view.height/(4*epsilon));
- const auto pressure=pressureTestParameters(hull.data[1][3],30);
- const double pressureHeight=pressureTestScalar(pressure,9,0);
+ const double pressureHeight=WaterBowShoulderTest::oracle(hull,bow.centre.x,bow.centre.y);
const double bound=WaterFftGeometry::MaxVerticalDisplacement;
double height=(verticalPixels*bound*std::tanh(pressureHeight/bound)*.75-.25)/.75;
height=(std::max)(0.0,(std::min)(1.0,height));height=height*height*(3-2*height);
@@ -3235,12 +3181,9 @@ TEST(water_bow_refinement_projected_width_matches_independent_ellipse_sampling)
TEST(water_bow_refinement_demand_is_bounded_local_continuous_and_pause_repeatable)
{
- // Explicitly exercise the legacy Gaussian fallback; contour mode has separate tests.
using namespace WaterBowRefinement;Bow bow;const auto hull=foamTestHull(0,0,30,0);
- CHECK(MakeBow(1,hull,hull,7,bow,false));Prepared p;p.bow=bow;p.cell={20,20};p.heightGate=1;
+ CHECK(MakeBow(1,hull,hull,7,bow));Prepared p;p.bow=bow;p.cell={20,20};p.heightGate=1;
const double radius=WaterFftGeometry::MaxHorizontalDisplacement;
- const double allowance=radius*std::sqrt(1/(bow.sigmaAlong*bow.sigmaAlong)+
- (1+.6*.6)/(bow.sigmaAcross*bow.sigmaAcross));
const Logical at={80,80};double previous[2]={0,0};
for(unsigned i=0;i<=400;++i) {
p.desiredDepth=double(i)/200;
@@ -3254,18 +3197,14 @@ TEST(water_bow_refinement_demand_is_bounded_local_continuous_and_pause_repeatabl
CHECK(Demand(p,level,at,bow.centre,0)==0);
CHECK_NEAR(Demand(p,level,at,bow.centre,.37),.37,1e-12);
CHECK(Demand(p,level,{at.x+17,at.y},bow.centre)==0);
- CHECK(Demand(p,level,at,{bow.origin.x+(3+allowance)*bow.sigmaAlong+.001,bow.origin.y})==0);
- CHECK(Demand(p,level,at,{bow.origin.x,bow.origin.y+(3+allowance)*bow.sigmaAcross+.001})==0);
+ CHECK(Demand(p,level,at,{bow.centre.x+3*bow.contour.width+radius+.001,bow.origin.y})==0);
+ CHECK(Demand(p,level,at,{bow.origin.x,bow.hullCentre.y+hull.data[1][3]+3.5*bow.contour.width+radius+.001})==0);
CHECK(Demand(p,level,at,{NAN,0})==0);
}
CHECK(Demand(p,0,at,bow.centre)==0 && Demand(p,3,at,bow.centre)==0);
- const double across=1.4*bow.sigmaAcross;
- const double along=-.6*bow.sigmaAlong*(std::sqrt(1+1.4*1.4)-1);
- const BowTestPoint shoulder={bow.origin.x+along,bow.origin.y+across};
- CHECK_NEAR(Demand(p,1,at,shoulder),1,1e-12);
- const BowTestPoint outside={bow.origin.x+(3.1+allowance)*bow.sigmaAlong,bow.origin.y};
- CHECK(Demand(p,1,at,outside)==0);
- // The original radial culling contract also limits the wider pressure wing.
+ const BowTestPoint flank={bow.hullCentre.x+10,bow.hullCentre.y+hull.data[1][3]+.5*bow.contour.width};
+ CHECK_NEAR(Demand(p,1,at,flank),1,1e-12);
+ // The original radial culling contract also limits the contour ridge.
CHECK(Demand(p,1,at,{bow.hullCentre.x+bow.reach+radius,bow.hullCentre.y})==0);
}
@@ -3278,9 +3217,9 @@ WaterBowRefinement::View bowTestView()
}
WaterBowRefinement::Active bowTestActive(const WaterBowRefinement::View &view,double x,double y,unsigned id=1)
{
- using namespace WaterBowRefinement;const auto hull=foamTestHull(float(x-20),float(y),30,0);
- // These legacy topology fixtures place the Gaussian centre at endpoint + 9.
- Active active;Bow bow;CHECK(MakeBow(id,hull,hull,7,bow,false));CHECK(PrepareBow(bow,view,active.prepared));
+ using namespace WaterBowRefinement;const auto hull=foamTestHull(float(x-13.5),float(y),30,0);
+ // Place the compact exterior contour ridge at the requested world-space centre.
+ Active active;Bow bow;CHECK(MakeBow(id,hull,hull,7,bow));CHECK(PrepareBow(bow,view,active.prepared));
active.amount=1;return active;
}
bool bowTestSameMesh(const WaterProjectedMesh::Mesh &a,const WaterProjectedMesh::Mesh &b)
@@ -3547,7 +3486,7 @@ TEST(water_bow_refinement_invalid_view_does_not_create_demand)
auto view=good;auto bow=active.prepared.bow;Prepared result;result.desiredDepth=.713;
if(field==0) view.width=NAN;if(field==1) view.height=INFINITY;
if(field==2) bow.centre.x=NAN;if(field==3) bow.forward.y=INFINITY;
- if(field==4) bow.sigmaAcross=NAN;if(field==5) bow.moving=NAN;
+ if(field==4) bow.sigmaAcross=NAN;if(field==5) bow.contour.amplitude=NAN;
const double amplitude=field==6?double(NAN):1;
CHECK(!PrepareBow(bow,view,result,amplitude));CHECK(result.desiredDepth==.713);
}
@@ -3607,10 +3546,10 @@ TEST(water_bow_refinement_protected_only_or_nonfresh_geometry_cannot_admit)
const Point corners[4]={{-100,-100},{100,-100},{100,100},{-100,100}};
Mesh mesh;CHECK(Build(corners,view.projection,view.resolution,mesh));const auto saved=mesh;
const auto actual=bowTestActive(view,0,0),collarOnly=bowTestActive(view,-110,0);
- // The bow's 32-world-unit support enters this polygon by only 22 units,
- // entirely inside the independently specified 24-unit protected world band.
- CHECK(collarOnly.prepared.bow.centre.x+32>corners[0].x);
- CHECK(collarOnly.prepared.bow.centre.x+32-corners[0].x<24);
+ // The expanded contour support enters only the protected world band.
+ const double extent=3*collarOnly.prepared.bow.contour.width+WaterFftGeometry::MaxHorizontalDisplacement;
+ CHECK(collarOnly.prepared.bow.centre.x+extent>corners[0].x);
+ CHECK(collarOnly.prepared.bow.centre.x+extent-corners[0].x<24);
CHECK(!HasRefinableDemand(mesh,view,corners,collarOnly.prepared));CHECK(bowTestSameMesh(mesh,saved));
CHECK(HasRefinableDemand(mesh,view,corners,actual.prepared));
for(auto &vertex:mesh.vertices) vertex.lattice=-1;const auto nonfresh=mesh;
@@ -4388,8 +4327,7 @@ struct Coverage {unsigned calls=0;double operator()(const State&s,double x,doubl
template<class Support> void Compare(const Topology&t,const std::vector<State>&s,const Mapping&m,double l,const Support&support,double time=1.375){
std::vector<uint32_t> seed(size_t(m.widthPixels)*m.heightPixels);for(size_t i=0;i<seed.size();++i)seed[i]=0xaa000000u|((uint32_t(i)*2654435761u)&0xffffffu);
auto a=seed,b=seed;Coverage ca,cb;bool ra=Reference(t,s,m,l,time,ca,a,support),rb=RasterizeAlpha(t,s,m,l,time,cb,b,support);
- CHECK(ra==rb);CHECK(ca.calls==cb.calls);if(a!=b){size_t at=0;while(at<a.size()&&a[at]==b[at])++at;
- std::fprintf(stderr,"RGBA mismatch case %u at %zu expected %08x actual %08x mapping %.17g %.17g %.17g %.17g %u %u level %.17g\n",cases,at,a[at],b[at],m.originX,m.originY,m.widthWorld,m.heightWorld,m.widthPixels,m.heightPixels,l);CHECK(a==b);}
+ CHECK(ra==rb);CHECK(ca.calls==cb.calls);CHECK(a==b);
for(size_t i=0;i<seed.size();++i)CHECK((b[i]&0xffffffu)==(seed[i]&0xffffffu));++cases;pixels+=seed.size();
}
static void Layout(const Topology&t){const auto&tiles=t.RasterTiles();CHECK(tiles.size()<=4*t.Cells().size());
@@ -4729,36 +4667,7 @@ TEST(water_foam_large_stern_normalization_preserves_fixed_time_pause_stop_and_ag
}
}
-#include "WaterBowShoulderTest.h"
-TEST(water_default_bow_refinement_matches_explicit_contour)
-{
- struct RestoreOption {
- bool had;std::string value;
- RestoreOption():had(getenv("ZH_WATER_BOW_SHOULDER")!=nullptr),
- value(getenv("ZH_WATER_BOW_SHOULDER")?getenv("ZH_WATER_BOW_SHOULDER"):""){}
- ~RestoreOption(){if(had)setenv("ZH_WATER_BOW_SHOULDER",value.c_str(),1);else unsetenv("ZH_WATER_BOW_SHOULDER");}
- } restore;
- CHECK(unsetenv("ZH_WATER_BOW_SHOULDER")==0);
- using namespace WaterBowRefinement;
- for(unsigned i=0;i<3;++i) {
- const auto hull=WaterBowShoulderTest::CapturedHull(i);
- Bow ordinary,explicitContour;
- CHECK(MakeBow(i+1,hull,hull,4,ordinary));
- CHECK(MakeBow(i+1,hull,hull,4,explicitContour,true));
- CHECK(ordinary.shoulder && explicitContour.shoulder);
- CHECK(ordinary.origin.x==explicitContour.origin.x && ordinary.origin.y==explicitContour.origin.y);
- CHECK(ordinary.centre.x==explicitContour.centre.x && ordinary.centre.y==explicitContour.centre.y);
- Prepared a,b;const auto view=bowTestView();
- CHECK(PrepareBow(ordinary,view,a));CHECK(PrepareBow(explicitContour,view,b));
- CHECK(a.desiredDepth==b.desiredDepth && a.heightGate==b.heightGate);
- const Logical at={int(std::round(a.cell.x*4)),int(std::round(a.cell.y*4))};
- for(int x=-60;x<=60;x+=5)for(int y=-20;y<=20;y+=5)for(unsigned level:{1u,2u}) {
- const Point world={ordinary.centre.x+x,ordinary.centre.y+y};
- CHECK(Demand(a,level,at,world)==Demand(b,level,at,world));
- }
- }
-}
#include "WaterHullContactFoamTest.h"
TEST(water_bow_shoulder_contour_gradient_motion_bounds_and_inverse_refinement)
{
@@ -4787,8 +4696,8 @@ TEST(water_bow_shoulder_contour_gradient_motion_bounds_and_inverse_refinement)
CHECK_NEAR(S::Evaluate(c,centre).value,c.amplitude,.000001);
CHECK(S::Evaluate(c,S::ToWorld(c,{-42,0})).value==0);
CHECK(S::Evaluate(c,S::ToWorld(c,{40+3.5*c.width,0})).value==0);
- WaterBowRefinement::Bow bow;CHECK(WaterBowRefinement::MakeBow(1,h,h,4,bow,true));
- CHECK(bow.shoulder&&bow.sigmaAlong==c.width&&bow.sigmaAcross==c.width);
+ WaterBowRefinement::Bow bow;CHECK(WaterBowRefinement::MakeBow(1,h,h,4,bow));
+ CHECK(bow.sigmaAlong==c.width&&bow.sigmaAcross==c.width);
CHECK(WaterBowRefinement::MaxAddedVertices==8190&&WaterBowRefinement::MaxAddedTriangles==16380);
auto a=S::Evaluate(c,centre),b=S::Evaluate(c,centre);CHECK(a.value==b.value&&a.dx==b.dx&&a.dy==b.dy);
h.data[2][0]=0;S::Contour stopped;CHECK(!S::Prepare(h,4,16,4,stopped));
@@ -4815,87 +4724,6 @@ TEST(water_bow_shoulder_actual_native_contours_and_detail_anchor_stability)
const auto p=S::ToWorld(a,{-42,2});CHECK_NEAR(S::Evaluate(a,p).value,S::Evaluate(b,p).value,.0001);
}
-namespace CoastalCrestAudit {
-double Scalar(const double f[6]) {
- auto unit=[](double x){return (std::max)(0.,(std::min)(1.,x));};
- auto smooth=[&](double a,double b,double x){const double t=unit((x-a)/(b-a));return t*t*(3-2*t);};
- for(unsigned i=0;i<6;++i)if(!std::isfinite(f[i]))return 0;
- const double h=f[0],d=f[1],s=unit(f[2]),e=unit(f[3]);
- const double obstacle=(std::max)(0.,unit(f[4])-double(.5f/255.f));
- const double gain=(std::max)(0.,obstacle-unit(f[5]));
- if(h<=0||d<=double(WaterShoreFoam::MinDepth))return 0;
- const double c=d-double(WaterShoreFoam::MinDepth);
- return s*e*smooth(WaterShoreFoam::MinDepth,WaterShoreFoam::WetDepth,d)*gain
- *c*std::tanh(h/c)*smooth(0,WaterShoreFoam::CrestHeight,h);
-}
-}
-TEST(water_coastal_crest_shared_height_derivative_and_zero_controls)
-{
- using namespace WaterCoastalCrest;double maximum=0;unsigned armed=0;
- for(unsigned i=0;i<96;++i) {
- Field fields[6]={{.05f+.029f*i,.17f,-.23f},{.17f+.037f*i,.07f,-.04f},
- {.13f+float(i%6)*.11f,.031f,-.023f},{.21f+float(i%5)*.13f,-.017f,.021f},
- {.67f+float(i%4)*.07f,.011f,-.019f},{.03f+float(i%7)*.035f,.013f,.009f}};
- const Field a=Correction(fields[0],fields[1],fields[2],fields[3],fields[4],fields[5]);
- double v[6];for(unsigned n=0;n<6;++n)v[n]=fields[n].height;
- CHECK_NEAR(a.height,CoastalCrestAudit::Scalar(v),.000003);
- for(unsigned axis=0;axis<2;++axis) {
- double lo[6],hi[6];for(unsigned n=0;n<6;++n){const double gradient=axis?fields[n].dy:fields[n].dx;lo[n]=v[n]-1e-4*gradient;hi[n]=v[n]+1e-4*gradient;}
- const double derivative=(CoastalCrestAudit::Scalar(hi)-CoastalCrestAudit::Scalar(lo))/.0002;
- const double error=std::abs(double(axis?a.dy:a.dx)-derivative);maximum=(std::max)(maximum,error);CHECK(error<.00008);
- }
- armed+=a.height>.01f;
- }
- CHECK(armed>30);
- CHECK(Eligible(false,true,0));CHECK(!Eligible(true,true,0));CHECK(!Eligible(false,false,0));CHECK(!Eligible(false,true,.000001f));
- CHECK(Height(-1,2,1,1,1,.1f)==0);CHECK(Height(1,0,1,1,1,.1f)==0);
- CHECK(Height(1,2,0,1,1,.1f)==0);CHECK(Height(1,2,1,0,1,.1f)==0);CHECK(Height(1,2,1,1,.1f,.1f)==0);
- CHECK(Height(std::numeric_limits<float>::quiet_NaN(),2,1,1,1,.1f)==0);
- std::printf("coastal crest independent scalar/complete product derivative96cases max %.9g\n",maximum);
-}
-TEST(water_coastal_crest_cannot_lower_mesh_or_exceed_existing_legacy_envelope)
-{
- using namespace WaterCoastalCrest;unsigned nonzero=0;float largest=0;
- for(unsigned i=0;i<20000;++i) {
- const float x=float((i*73)%1000)-500,y=float((i*47)%800)-400,time=float(i%601)/30;
- const auto wave=WaterSurfaceModel::Evaluate(x,y,time);const float broad=WaterShoreFoam::Evaluate(x,y,time).height;
- const float depth=float(i%201)*.06f,obstacle=float((i*17)%256)/255.f;
- const float damping=(std::min)(WaterSurfaceModel::ShoreDamping(depth),obstacle);
- const float add=Height(broad,depth,float((i*13)%31)/30,float((i*29)%11)/10,EncodeObstacle(obstacle),damping);
- const float old=wave.height*damping,next=old+add;
- CHECK(std::isfinite(add)&&add>=0);CHECK(next>=old);
- CHECK(add<=(std::max)(0.f,obstacle-damping)*(std::max)(0.f,broad)+.000002f);
- CHECK(std::abs(next)<=WaterSurfaceModel::LegacyMaxDisplacement+.00001f);
- CHECK(next>=-depth-.00001f); // Original conservative vertex floor still holds.
- largest=(std::max)(largest,add);nonzero+=add>.01f;
- }
- CHECK(nonzero>1000&&largest>.3f);
- // Actual existing convex morph/collar algebra: added vertices cannot lower interpolated
- // triangles, shared edge morphs or centre transitions. No topology/XY changes are proposed.
- const double old[3]={-1.1,.8,-.4},added[3]={.7,.02,1.3};
- for(unsigned i=0;i<=20;++i)for(unsigned j=0;j<=20-i;++j) {
- WaterProjectedMesh::CentreTransition t={};t.weight[0]=i/20.;t.weight[1]=j/20.;t.weight[2]=1-t.weight[0]-t.weight[1];t.analytic=.35;
- const double next[3]={old[0]+added[0],old[1]+added[1],old[2]+added[2]};
- CHECK(WaterProjectedMesh::InterpolateCentre(t,.9,next)>=WaterProjectedMesh::InterpolateCentre(t,-.2,old));
- for(unsigned k=0;k<=10;++k)CHECK(WaterSurfaceModel::MorphCoordinate(float(old[0]+added[0]),float(next[1]),float(next[2]),k/10.f)
- >=WaterSurfaceModel::MorphCoordinate(float(old[0]),float(old[1]),float(old[2]),k/10.f));
- }
- std::printf("coastal crest20000 bound/floor cases; active%u max added %.7g within original bound %.7g\n",nonzero,largest,WaterSurfaceModel::LegacyMaxDisplacement);
-}
-TEST(water_coastal_crest_uses_existing_phase_freezes_and_reports_positive_mean)
-{
- using namespace WaterCoastalCrest;double sum=0;unsigned zero=0,active=0;float peak=0;
- for(unsigned i=0;i<1920;++i) {
- const float t=i/30.f;const float h=WaterShoreFoam::Evaluate(1150,352,t).height;
- const float add=Height(h,2,1,1,EncodeObstacle(1),WaterSurfaceModel::ShoreDamping(2));
- CHECK(add==Height(WaterShoreFoam::Evaluate(1150,352,WaterSurfaceModel::AdvanceTime(t,.1f,true,false,false)).height,
- 2,1,1,EncodeObstacle(1),WaterSurfaceModel::ShoreDamping(2)));
- sum+=add;peak=(std::max)(peak,add);zero+=add==0;active+=add>.1f;
- }
- CHECK(zero>400&&active>200);CHECK(sum/1920>.02&&sum/1920<1.0);CHECK(peak>0.5f);
- std::printf("coastal crest64s phase sweep: nonzero DC %.7g world, peak %.7g, zero frames%u/1920; NOT a zero-mean fluid solver\n",sum/1920,peak,zero);
-}
-
TEST(water_bow_shoulder_large_hull_scale_cap_support_and_small_boat_identity)
{
namespace S=WaterBowShoulder;namespace T=WaterBowShoulderTest;
@@ -4932,7 +4760,7 @@ TEST(water_bow_shoulder_large_hull_scale_cap_support_and_small_boat_identity)
const auto large=T::scaledHull(280,54);const auto c=T::contour(large);
const auto outside=S::ToWorld(c,{292,0});
CHECK(S::Evaluate(c,outside).value-T::oracle(large,outside.x,outside.y,6)>3);
- WaterBowRefinement::Bow bow;CHECK(WaterBowRefinement::MakeBow(7,large,large,4,bow,true));
+ WaterBowRefinement::Bow bow;CHECK(WaterBowRefinement::MakeBow(7,large,large,4,bow));
CHECK(bow.sigmaAlong==12 && bow.sigmaAcross==12 && bow.contour.length==32);
CHECK(WaterBowRefinement::MaxRegions==3 && WaterBowRefinement::WindowRadius==6);
CHECK(WaterBowRefinement::MaxAddedVertices==8190 && WaterBowRefinement::MaxAddedTriangles==16380);
@@ -4948,238 +4776,6 @@ TEST(water_bow_shoulder_large_hull_scale_cap_support_and_small_boat_identity)
}
-#include "Platform/WaterCoastalSurf.h"
-
-namespace CoastalSurfTest {
-using namespace WaterCoastalSurf;
-inline Context Coast(){return {4,64,-1,0,1,.4f,.4f,.5f,1,1};}
-inline Field Travelling(double x,double time){const double k=6.283185307179586/64,q=k*x-time;
- return {float(2*std::sin(q)),float(2*k*std::cos(q)),0,float(1-.20*std::sin(q))};}
-inline double Simp(double duration,double lifetime,double rate0,double rate1,unsigned power){
- constexpr unsigned n=10000;double sum=0;
- for(unsigned i=0;i<=n;++i){const double age=duration*i/n;
- const double value=std::pow(age,int(power))*std::exp(-age/lifetime)*(rate1+(rate0-rate1)*age/duration);
- sum+=(i==0||i==n?1:i%2?4:2)*value;}
- return sum*duration/(3*n);
-}
-inline State Schedule(const std::vector<double>&steps,double end){
- Clock clock;State state;double time=0;auto p=clock.Inspect(7,0);CHECK(clock.Commit(7,p));
- state.height=Travelling(5,0).height;state.rate=0;
- for(unsigned i=0;time<end;++i){time=(std::min)(end,time+steps[i%steps.size()]);p=clock.Inspect(7,time);
- if(p.action==Action::Sample||p.action==Action::GapDecay)
- state=Advance(Coast(),Travelling(5,time),state,p.elapsed,p.action==Action::Sample);
- CHECK(clock.Commit(7,p));}
- return state;
-}
-}
-
-TEST(water_coastal_surf_front_propagates_from_actual_phase_and_leaves_remnants)
-{
- using namespace CoastalSurfTest;
- auto peak=[](double time){float maximum=0;double result=0;
- for(unsigned i=0;i<=256;++i){double x=-32+i*.25;Field f=Travelling(x,time);State old;
- old.height=Travelling(x,time-.1).height;old.rate=0;
- const float rate=Rate(Coast(),f,old,.1);if(rate>maximum){maximum=rate;result=x;}}
- CHECK(maximum>.25f);return result;};
- const double a=peak(0),b=peak(.5);
- CHECK(std::abs((b-a)-32/6.283185307179586)<.5); // independently known phase speed, +X
- auto c=Coast();c.outwardX=1;State old;old.height=Travelling(20,-.1).height;old.rate=0;
- CHECK(Rate(c,Travelling(20,0),old,.1)==0); // opposite coast sees an outgoing front
- State state;state.height=Travelling(0,0).height;state.rate=0;
- float maximum=0;
- for(unsigned i=1;i<=48;++i){state=Advance(Coast(),Travelling(0,i*.1),state,.1);maximum=(std::max)(maximum,state.rate);}
- CHECK(maximum>.25f && state.density>.15f);
- const State fresh=state;CHECK(Coverage(fresh,.25f)>0);
- for(unsigned i=0;i<30;++i)state=Advance(Coast(),Travelling(0,4.8+(i+1)*.1),state,.1,false);
- CHECK(state.density>0 && state.density<fresh.density);
- CHECK(state.ageMoment/state.density>fresh.ageMoment/fresh.density+2.9f);
- CHECK(Coverage(state,.25f)<Coverage(state,1)); // age produces porosity, not only fading
- for(unsigned i=0;i<150;++i)state=Advance(Coast(),Travelling(0,8+i*.1),state,.1,false);
- CHECK(Coverage(state,.25f)==0);
-}
-
-TEST(water_coastal_surf_linear_rate_integration_has_independent_density_and_age_oracles)
-{
- using namespace CoastalSurfTest;
- for(double dt:{.0001,.025,.1,.25})for(float first:{0.f,.4f,1.2f})for(float last:{0.f,.7f,1.2f}){
- State old{.7f,1.3f,1,first};State result=Integrate(old,2,last,dt,true);
- const double q=std::exp(-dt/5);
- const double density=q*.7+Simp(dt,5,first,last,0);
- const double age=q*(1.3+dt*.7)+Simp(dt,5,first,last,1);
- CHECK(std::abs(result.density-density)<.000001);
- CHECK(std::abs(result.ageMoment-age)<.000001);
- CHECK(result.height==2 && result.rate==last);
- }
- State old{.5f,.8f,1,.9f};const State paused=Integrate(old,12,1.2,0,true);
- CHECK(paused.density==old.density && paused.ageMoment==old.ageMoment && paused.height==old.height && paused.rate==old.rate);
- const State gap=Integrate(old,2,1.2,4,false);
- CHECK(std::abs(gap.density-.5*std::exp(-.8))<.000001 && gap.rate==0);
- CHECK(std::abs(gap.ageMoment-(.8+2)*std::exp(-.8))<.000001);
- CHECK(Integrate(old,2,1.2,100000,false).density==0);
-}
-
-TEST(water_coastal_surf_schedule_error_is_bounded_and_not_render_count_driven)
-{
- using namespace CoastalSurfTest;
- const State at30=Schedule({1./30},30),at120=Schedule({1./120},30);
- const State jitter=Schedule({.012,.047,.021,.035},30);
- CHECK(at30.density>.03f && at30.ageMoment>.03f);
- CHECK(std::abs(at30.density-at120.density)<.0005f);
- CHECK(std::abs(at30.ageMoment-at120.ageMoment)<.002f);
- // The source uses real current FFT samples, not extra transforms at every ideal tick.
- // Jitter may therefore change sample phase; this is an explicit error bound, not identity.
- CHECK(std::abs(at30.density-jitter.density)<.05f*(std::max)(at30.density,.1f));
- CHECK(std::abs(at30.ageMoment-jitter.ageMoment)<.06f*(std::max)(at30.ageMoment,.1f));
- Clock clock;auto p=clock.Inspect(11,2);CHECK(p.action==Action::Reset && clock.Commit(11,p));
- p=clock.Inspect(11,2);CHECK(p.action==Action::None && clock.Commit(11,p));
- p=clock.Inspect(11,2.05);CHECK(p.action==Action::None && clock.Commit(11,p));
- p=clock.Inspect(11,2.1);CHECK(p.action==Action::Sample && clock.Commit(11,p));
- const double sampled=clock.SampledTime();CHECK(clock.Inspect(11,2.1).action==Action::None);
- CHECK(clock.SampledTime()==sampled); // inspecting an unsubmitted GPU plan cannot advance state
- p=clock.Inspect(11,5);CHECK(p.action==Action::GapDecay && clock.Commit(11,p));
- CHECK(clock.Inspect(11,4.9).action==Action::Reset); // rollback clears source derivative history
- CHECK(clock.Inspect(12,5).action==Action::Reset); // map/terrain/polygon revision, even same dimensions
- CHECK(clock.Inspect(0,5).action==Action::Invalid);
- CHECK(clock.Inspect(11,std::numeric_limits<double>::infinity()).action==Action::Invalid);
- p=clock.Inspect(11,5.1);p.elapsed=.01;CHECK(!clock.Commit(11,p));
-}
-
-TEST(water_coastal_surf_distinct_domain_keeps_broad_wet_support_and_excludes_dry_pools)
-{
- using namespace CoastalSurfTest;
- Context c=Coast();Field f{2,-.25f,0,.7f};State old{.7f,.1f,1.9f,0};
- CHECK(c.distance>20 && c.offshore>0 && Domain(c)>0 && Rate(c,f,old,.1)>.1f);
- Context q=c;q.wet=0;CHECK(Advance(q,f,old,.1).density==0);
- q=c;q.depth=.15f;CHECK(Rate(q,f,old,.1)==0 && Advance(q,f,old,.1).density==0);
- q=c;q.exposure=0;CHECK(Advance(q,f,old,.1).density==0);
- q=c;q.admitted=0;CHECK(Advance(q,f,old,.1).density==0);
- q=c;q.distance=128;CHECK(Rate(q,f,old,.1)==0);
- // Wet spread margin can retain old foam after leaving source support; it cannot emit.
- const State margin=Advance(q,f,old,.1);CHECK(margin.density>0 && margin.density<old.density);
- q=c;q.depth=12;CHECK(Rate(q,f,old,.1)==0);
- q=c;q.depth=std::numeric_limits<float>::quiet_NaN();CHECK(Rate(q,f,old,.1)==0);
- Field still=f;old.height=f.height;CHECK(Rate(c,still,old,.1)==0);
- Field falling=f;falling.height=old.height-.1f;CHECK(Rate(c,falling,old,.1)==0);
- Field trough=f;trough.height=-1;CHECK(Rate(c,trough,old,.1)==0);
- q=c;q.analyticDamping=q.spectralDamping=1;old.height=1.9f;CHECK(Rate(q,f,old,.1)==0);
- q=c;q.offshore=0;
- Context offshore=q;offshore.offshore=1;
- CHECK(Rate(q,f,old,.1)==Rate(offshore,f,old,.1)); // Optical R cannot select the phase field's damping.
- q.analyticDamping=0;q.spectralDamping=1;
- CHECK(Rate(q,f,old,.1)==0); // B1/R0 uses the same spectral damping as open water.
- Field analytic{1,.3f,-.2f,1},spectral{3,-.2f,.1f,.6f};
- Field mixed=Blend(analytic,spectral,.25f);CHECK(mixed.height==1.5f);
- CHECK(std::abs(mixed.dx-.175f)<.000001f && std::abs(mixed.compression-.9f)<.000001f);
-}
-
-TEST(water_coastal_surf_wet_graph_diffusion_and_lookup_do_not_cross_levels_or_renormalize_gaps)
-{
- using namespace CoastalSurfTest;
- std::vector<Node> nodes(3);for(auto &n:nodes)n.context=Coast();
- nodes[0].world[2]=nodes[1].world[2]=7;nodes[1].world[0]=5;
- nodes[2].world[2]=11;nodes[0].neighbour[1]=2;nodes[1].neighbour[0]=1;
- CHECK(ValidGraph(nodes,5));nodes[1].neighbour[1]=3;CHECK(!ValidGraph(nodes,5));nodes[1].neighbour[1]=0;
- nodes[1].world[2]=11;CHECK(!ValidGraph(nodes,5));nodes[1].world[2]=7;
- nodes[1].context.wet=0;CHECK(!ValidGraph(nodes,5));nodes[1].context=Coast();
- nodes[1].context.admitted=0;CHECK(!ValidGraph(nodes,5));nodes[1].context=Coast();
- nodes[1].context.exposure=0;CHECK(!ValidGraph(nodes,5));nodes[1].context=Coast();
- nodes[1].context.depth=.15f;CHECK(!ValidGraph(nodes,5));nodes[1].context=Coast();
- nodes[1].context.distance=144;nodes[1].context.depth=14;
- CHECK(Domain(nodes[1].context)==0 && ValidGraph(nodes,5)); // valid wet spreading margin
- State a{1,2,1,0},b{0,0,2,0};std::array<State,4> na{},nb{};na[1]=b;nb[0]=a;
- const State da=Diffuse(a,na,2,5,.1),db=Diffuse(b,nb,1,5,.1);
- CHECK(da.density<1 && db.density>0 && std::abs(da.density+db.density-1)<.000001);
- CHECK(std::abs(da.ageMoment+db.ageMoment-2)<.000001 && da.height==a.height && db.height==b.height);
- Lookup lookup{{1,2,0,0},{.25f,.25f,0,0}};CHECK(ValidLookup(lookup,3));
- CHECK(lookup.weight[0]+lookup.weight[1]==.5f); // missing dry half remains missing
- lookup.weight[2]=.1f;CHECK(!ValidLookup(lookup,3));lookup.weight[2]=0;
- lookup.node[0]=4;CHECK(!ValidLookup(lookup,3));
- CHECK(!ValidGraph(std::vector<Node>(MaxNodes+1),5));
-}
-
-TEST(water_coastal_surf_rejects_overflow_inputs_and_preserves_tiny_step_finiteness)
-{
- using namespace CoastalSurfTest;
- State old{.7f,.1f,1.9f,0};Field f{2,-.25f,0,.7f};Context c=Coast();
- c.outwardX=std::numeric_limits<float>::max();CHECK(Rate(c,f,old,.1)==0);
- c=Coast();f.dx=std::numeric_limits<float>::max();CHECK(Rate(c,f,old,.1)==0);
- f={2,-.25f,0,.7f};c.spectralDamping=std::numeric_limits<float>::max();CHECK(Rate(c,f,old,.1)==0);
- for(double dt:{1e-40,1e-30,1e-12,1e-8}){
- const State state=Integrate(old,2,.8f,dt,true);CHECK(Finite(state));
- CHECK(std::abs(state.density-old.density)<.000001 && std::abs(state.ageMoment-old.ageMoment)<.000001);
- }
- std::vector<Node> duplicate(2);for(auto &n:duplicate){n.context=Coast();n.world[2]=7;}
- CHECK(!ValidGraph(duplicate,5));
- Lookup lookup;CHECK(!ValidLookup(lookup,MaxNodes+1));
- // R varies between constant endpoints: its static transition is not wave steepness.
- const Field a{1,0,0,1},b{2,0,0,1};const Field mixed=Blend(a,b,.5f);
- c=Coast();old.height=1.4f;CHECK(mixed.dx==0 && mixed.dy==0 && Rate(c,mixed,old,.1)==0);
-}
-
-#include "WaterWaveCageTest.h"
-TEST(water_wave_cage_phase_terrain_bounds_classification_and_constrained_smoothing)
-{
- WaterWaveCageTest::Check();
-}
-
-#include "WaterTerrainCullingTest.h"
-TEST(water_terrain_culling_preserves_wet_interiors_displacement_and_mesh_metadata)
-{
- WaterTerrainCullingTest::Check();
-}
-
-#include "WaterCoastalDomainTest.h"
-TEST(water_coastal_domain_connected_wet_geometry_limits_and_atomic_refresh)
-{
- WaterCoastalDomainTest::Check();
-}
-
-#include "WaterCoastalViewTest.h"
-TEST(water_coastal_view_centres_support_levels_limits_and_atomic_refresh)
-{
- WaterCoastalViewTest::Check();
-}
-
-#include "Platform/WaterCoastalPresentation.h"
-
-TEST(water_coastal_presentation_advances_age_and_density_without_new_births)
-{
- using namespace WaterCoastalPresentation;
- const Moments same=AtTime(2,3,0),later=AtTime(2,3,2.5f);
- CHECK(same.density==2&&same.age==1.5f);
- CHECK(std::abs(later.density-2*std::exp(-.5))<.000001&&later.age==4);
- const Moments split=AtTime(later.density,later.density*later.age,1.5f),one=AtTime(2,3,4);
- CHECK(std::abs(split.density-one.density)<.000001&&std::abs(split.age-one.age)<.000001);
- CHECK(AtTime(0,0,0).density==0&&AtTime(2,3,-1).density==0);
- CHECK(AtTime(2,3,14).density==0&&AtTime(1,14,0).density==0);
- CHECK(AtTime(std::numeric_limits<float>::quiet_NaN(),0,0).density==0);
- CHECK(AtTime(1,std::numeric_limits<float>::infinity(),0).density==0);
-}
-
-TEST(water_coastal_presentation_accepts_r0_but_rejects_unsupported_geometry)
-{
- using namespace WaterCoastalPresentation;
- CHECK(ModelGate(0,0,0,0,0)==1&&ModelGate(1,1,0,0,0)==1);
- CHECK(ModelGate(.4f,.4f,0,0,0)==1);
- CHECK(ModelGate(0,.4f,0,0,0)==0); // camera/authored-edge FFT fade
- CHECK(ModelGate(.4f,.4f,.5f,0,0)==0); // boundary/centre height correction
- CHECK(ModelGate(.4f,.4f,0,.1f,0)==0); // zero height with a nonzero correction slope
- CHECK(ModelGate(.4f,.42f,0,0,0)>0&&ModelGate(.4f,.42f,0,0,0)<1);
- CHECK(ModelGate(std::numeric_limits<float>::quiet_NaN(),0,0,0,0)==0);
-}
-
-#include "WaterCoastalFootprintTest.h"
-TEST(water_coastal_view_full_filter_footprint_blocks_subtexel_gaps)
-{
- WaterCoastalFootprintTest::Check();
-}
-
-#include "WaterCoastalCapacityTest.h"
-TEST(water_coastal_domain_stride_two_capacity_preserves_fine_connectivity_and_terrain)
-{
- WaterCoastalCapacityTest::Check();
-}
-
#if defined(__linux__)
#include "W3DDevice/GameClient/W3DWater.h"
#include "Common/LogicThread.h"
@@ -5208,15 +4804,14 @@ public:
void seedPresentation() {
m_modernHulls.resize(1);m_modernContactHulls.resize(1);m_modernVisualHulls.resize(1);
m_modernHullObjectIDs.push_back(42);m_modernFoamDrawObjectIDs.push_back(42);
- m_modernFoamDrawFrame=123;m_modernShoreReady=m_modernCoastalReady=m_modernCoastalViewReady=TRUE;
- m_modernCoastalRevision=42;m_modernProfile.frames=17;m_reflectionReused=FALSE;
+ m_modernFoamDrawFrame=123;m_modernShoreReady=TRUE;
+ m_reflectionReused=FALSE;
}
void checkChanged(bool modern) {
CHECK_EQ(bool(m_useModernWater),modern);
CHECK(m_modernHulls.empty() && m_modernContactHulls.empty() && m_modernVisualHulls.empty());
CHECK(m_modernHullObjectIDs.empty() && m_modernFoamDrawObjectIDs.empty());
- CHECK(!m_modernShoreReady && !m_modernCoastalReady && !m_modernCoastalViewReady);
- CHECK(m_modernCoastalRevision==0 && m_modernProfile.frames==0);
+ CHECK(!m_modernShoreReady);
CHECK(m_reflectionReused); // force the new clear colour even with a stationary camera
CHECK_EQ(m_modernWaveTime,37.5f);CHECK_EQ(m_level,7);CHECK(m_drawnMotionEnabled);
const auto river=EngineShader_From_File(WaterShaderNameProbe::Engine_Name_Of(m_riverWaterPixelShader).c_str());
@@ -5226,7 +4821,7 @@ public:
}
void checkUnchanged() {
CHECK(!m_modernHulls.empty() && !m_modernFoamDrawObjectIDs.empty());
- CHECK(m_modernShoreReady && m_modernCoastalRevision==42 && m_modernProfile.frames==17);
+ CHECK(m_modernShoreReady);
CHECK(!m_reflectionReused); // no per-frame history reset or forced mirror refresh
}
};
diff --git a/GeneralsMD/Code/Tools/water_preview.cpp b/GeneralsMD/Code/Tools/water_preview.cpp
index 314c1547b..8b5187b08 100644
--- a/GeneralsMD/Code/Tools/water_preview.cpp
+++ b/GeneralsMD/Code/Tools/water_preview.cpp
@@ -398,9 +398,6 @@ private:
loadMaterial();
loadColour();
if (!options.exportConfig.empty()) exportRule();
- // The preview requires the game's native FFT path even if a user's game launch disables it.
- SDL_setenv_unsafe("ZH_WATER_FFT","1",1);
- SDL_unsetenv_unsafe("ZH_WATER_DEBUG");
if (!options.offscreen) {
window = SDL_CreateWindow("Water Preview",options.width,options.height,0);
if (!window) throw std::runtime_error(std::string("create window: ")+SDL_GetError());
@@ -639,7 +636,7 @@ private:
case SDLK_L: colourPanel.visible=true; loadSavedColour(); break;
case SDLK_E:
try { exportRule(); }
- catch (const std::exception &error) { colourPanel.status="EXPORT FAILED"; std::fprintf(stderr,"%s\n",error.what()); }
+ catch (const std::exception &error) { colourPanel.status=std::string("EXPORT FAILED: ")+error.what(); }
break;
case SDLK_LEFTBRACKET: colourPanel.values.strength=std::max(0.0f,colourPanel.values.strength-.05f); colourPanel.status="UNSAVED CHANGES"; break;
case SDLK_RIGHTBRACKET: colourPanel.values.strength=std::min(1.0f,colourPanel.values.strength+.05f); colourPanel.status="UNSAVED CHANGES"; break;