Rise
The Vieneo Province
Loading...
Searching...
No Matches
Tests/TerrainWeatherTests.cpp

Source at documentation-generation time. See Test catalog for fixture associations.

1#include "../Viewscreen/globals.h"
2#include "../Protocol/TerrainWeather.h"
3#include "../Viewscreen/GridLightning.h"
4#include "../Viewscreen/TerrainSnow.h"
5#include "../Viewscreen/WeatherOverrides.h"
6#include "../Viewscreen/CloudVolume.h"
7#include "../Viewscreen/SpatialFogWeather.h"
8#include "../Logger.h"
9#include <cfloat>
10#include <iostream>
11#include <memory>
12#include <limits>
13#include <stdexcept>
14#include <vector>
15#include <unordered_map>
16#include <chrono>
17
18struct Logger::CrashState {};
19Logger::Logger() = default;
20Logger::~Logger() = default;
21void Logger::AddToCallStack(const char*) {}
22void Logger::Log(const char* text, Level level, int)
23{ if (level >= Error) throw std::runtime_error(text); }
24LOCALGRID2 gridarray[64][64];
25bool visiblegrid[63][63];
28bool g_bAboveClouds = false;
29float RandomFloat() { return .5f; }
30static int checks = 0;
31static void Check(bool condition, const char* message)
32{ ++checks; if (!condition) throw std::runtime_error(message); }
33
34// Rendering sink: exercise production weather-to-GPU packing and lifecycle.
35namespace Rendering {
36struct CloudRenderer11 {
37 struct RainGrid {int cube=0,u=0,v=0;uint64_t revision=0;std::array<RiseMath::Vector4,4096> cells{};};
38 RainGrid latest;bool active=false;unsigned uploads=0;
39 bool HasRainGrid(uint64_t revision,int cube,int u,int v) const
40 {return active && latest.revision==revision && latest.cube==cube && latest.u==u && latest.v==v;}
41 void SetRainGrid(const RainGrid* grid){active=grid!=nullptr;if(grid){latest=*grid;++uploads;}}
42};
43}
44struct RainRendererSink {
45 Rendering::CloudRenderer11 renderer;unsigned historyResets=0;
46 bool lightningDiagnostic=false;
47 auto* Effect(){return &renderer;}
48 void ResetHistory(){++historyResets;}
49 bool SetLightningDiagnostic(bool enabled){lightningDiagnostic=enabled;return true;}
50};
51class grid;
52class Viewscreen;
53struct Weather
54{
55 Viewscreen* viewscreen = nullptr; Logger* logger = nullptr;
56 int resets = 0;
57 bool weatherPending = true, weatherRequestQueued = true;
58 bool plotWeatherSuspended = false,spatialFogRendering=false;
59 void PrepareRainCurtains(bool);
60 bool UpdatePlotWeatherAltitude();
61 uint16_t weatherRequestToken = 1;
62 PlotWeather::Store plotWeather;
63 SpatialFogWeather::Store spatialFogWeather;
64 CloudVolume::Point ObservedWindKms() const;
65 void UpdateSpatialFogSnapshot(bool full);
66 void AdvanceSpatialFog(float elapsed);
67 CloudBaseWeather::Store cloudBaseWeather;
68 uint32_t cloudBaseWeatherRevision=0;
69 uint16_t cloudBaseRequestToken=0;
70 uint64_t cloudBaseTerrainRevision=0;
71 void UpdateCloudBaseWeather(float elapsed);
72 void ResetCloudBaseWeather();
73 CloudVolume::Parameters cloudParameters;
74 TerrainSnow::Store terrainSnow;
75 uint32_t snowWeatherRevision=0;uint16_t snowRequestToken=0;uint64_t snowTerrainRevision=0;
76 float orbitSunLatitude=0;
77 void UpdateTerrainSnow(float);
78 RiseMath::Vector4 TerrainSnowTint(int,int) const;
79 GridLightning::System gridLightning{};
80 uint32_t lightningWeatherRevision=0;
81 uint64_t lightningTerrainRevision=0,rainTerrainRevision=0;
82 float snowBlend=0,precipOverride=-1;
83 bool RefreshLightningGrid();
84 void UpdateLightningSpawns(float);
85 void ReceiveGridLightning(short,short,int,int);
86 bool TriggerForwardLightning();
87 float cloudCeilingOverrideKm=-1;
88 float GetCloudCeilingKm() const {return cloudCeilingSmoothAglKm;}
89 float GetPrecip() const;
90 float GetRainPrecip() const;
91 float GetVisibilityKm() const;
92 float visibilityOverrideKm=-1;
93 void SetPrecipOverride(float);
94 float GetTurbulence() const;
95 void ResetTurbulence();
96 void FrameTurbulenceReset();
97 ULONGLONG weatherDiagnosticUntil = 0, weatherNextDiagnostic = 0;
98 float cloudSurfaceTargetKm = 0, cloudCeilingTargetKm = 1.8f, visibility = 42.16f;
99 float precip=2, smoothPrecip=-1, winddir=0, temperature=0, windspeed=0;
100 void SetPrecip(float);
101 void SetWindDirectionRadians(float value) { winddir=value; }
102 void SetTemperatureCelsius(float value) { temperature=value; }
103 void SetWindspeedKms(float value) { windspeed=value; }
104 float GetWindspeedKms() const {return playerships[0].isSimulator ? 0 : windspeed;}
105 float GetWindDirectionRadians() const {return winddir;}
106 float cloudSurfaceSmoothKm = -1, cloudCeilingSmoothAglKm = -1, smoothVisibility = -1;
107 void SetCloudSurfaceTargetKm(float v) { cloudSurfaceTargetKm=v; if(cloudSurfaceSmoothKm==-1) cloudSurfaceSmoothKm=v; }
108 void SetCloudCeilingTargetKm(float v) { cloudCeilingTargetKm=v; if(cloudCeilingSmoothAglKm==-1) cloudCeilingSmoothAglKm=v; }
109 void SetVisibility(float v) { visibility=v; if(smoothVisibility==-1) smoothVisibility=v; }
110 void ForceSmoothValues() { ++resets; smoothPrecip=precip; cloudSurfaceSmoothKm=cloudSurfaceTargetKm; cloudCeilingSmoothAglKm=cloudCeilingTargetKm; smoothVisibility=visibility; }
111 void ResetPlotWeatherConnection();
112 void RequestPlotWeather(bool);
113 void QueuePlotWeatherReset();
114 void ReceivePlotWeather(const unsigned char*, size_t);
115 void UpdatePlotWeatherConditions();
116};
117struct Network
118{
119 struct CloudWeatherSource {
121 CloudWeather::MapPtr Latest() const { return latest; }
122 } cloudWeather;
123 std::vector<SClientPacket> requests, weatherRequests, lightningRequests;
124 void SendToServer(const void* data, size_t size, bool reliable, PacketOrdering ordering=ORDERING_NONE)
125 {
126 Check(size == sizeof(SClientPacket) && reliable, "request framing/reliability changed");
127 const auto packet = *static_cast<const SClientPacket*>(data);
128 if(packet.type == 42) {
129 Check(ordering==ORDERING_NONE && packet.f_z>=0 && packet.f_z<=2
130 && packet.f_w>=0 && packet.f_w<=32767,"lightning wire fields/order changed");
131 lightningRequests.push_back(packet);
132 } else if(packet.type == 45) {
133 Check(ordering == ORDERING_WEATHER && ordering == 9 && packet.f_x >= 0 && packet.f_x <= 65535
134 && packet.f_x == floorf(packet.f_x) && packet.f_y == 0 && packet.f_z == 0 && packet.f_w == 0,
135 "weather request token/channel/padding changed");
136 weatherRequests.push_back(packet);
137 } else {
138 Check(ordering == ORDERING_TERRAIN, "terrain ordering changed");
139 requests.push_back(packet);
140 }
141 }
142};
143struct FixtureBus { VECTOR2SHORT DebugApn; };
144struct Game { FixtureBus* bus; Network* networking; };
145class Viewscreen
146{
147public:
148 Logger* logger; Game* gameclass; grid* ptrGrid; Weather weather; Weather* ptrWeather = &weather;
149 short BCLoffsetu = 0, BCLoffsetv = 0; char msg[999]{};
150 float onlinePlayersInVicinity=1; int strikes=0, legacyStrikes=0;
151 bool advanceframe=false, volumeEnabled=true;
152 float turbEnergy=0, turbLow=0;
153 RiseMath::Matrix matrixLook;
154 RiseMath::Vector3 posnorml{0,-1,0},compassnorth{0,0,-1};
155 bool testStrike=false; int strikeChains=-1;
156 RainRendererSink cloudVolume;
157 bool VolumeCloudsEnabled() const { return volumeEnabled; }
158 RiseMath::Vector3 strikeGround{},strikeCloud{}; float strikeDistance=0;
159 void TriggerBCLLightningAt(const RiseMath::Vector3& ground,const RiseMath::Vector3& cloud,float distance,int,int chains,bool test=false) {
160 ++strikes; strikeGround=ground;strikeCloud=cloud;strikeDistance=distance;testStrike=test;strikeChains=chains;
161 }
162 void TriggerBCLLightning(int,int,float,int,int) { ++legacyStrikes; }
163 bool IsRepositionSettling() const { return false; }
164 char CalculateCube(RiseMath::Vector3) const;
165 VECTOR2SHORT CalculateCGC(RiseMath::Vector3, char) const;
166 VECTOR2SHORT CalculateWrap(short, short, char, char*) const;
167 RiseMath::Vector3 CalculatePlanar(short, short);
168 LOCALGRID2 CalculateSRV(short, short, VECTOR2SHORT, char, SRenderVertex);
169};
170class grid
171{
172public:
173 mutable uint64_t elevationRevision = 1, elevationIndexRevision = 0;
174 struct SurfacePoint { short meters; bool water; };
175 mutable std::unordered_map<uint32_t, SurfacePoint> elevationByPlot;
176 bool TryRadarSurface(char face, short u, short v, short& meters, bool& water) const;
177 bool InterpolateRadarSurface(char face, double u, double v, float& meters, float& waterFraction) const;
178 // Coordinates describe the requested face, independently of the terrain center.
179 bool TryElevation(char face, short u, short v, short& meters) const;
180 bool InterpolateElevation(char face, double u, double v, float& meters) const;
181 uint64_t ElevationRevision() const { return elevationRevision; }
182 void ElevationChanged() const { ++elevationRevision; }
183 Viewscreen* viewscreen;
184 explicit grid(Viewscreen* owner) : viewscreen(owner) {}
185 char oldcube = -1, cube = -1, dataPending = 0, requestedCube = -1;
186 VECTOR2SHORT oldtcp, tcp, requestedTcp;
187 bool wholeGridPending = false, wholeGridReceived = false, resetWeatherOnNextGrid = false;
188 bool g_bAboveCloudsOld = false;
189 bool dataReady = false, geometryReady = false, patchGeometry = false;
190 void Trace(const char* text, Logger::Level level = Logger::Info) const { viewscreen->logger->Log(text, level); }
191 void ClearGrid(short, short) const; void ClearGrid(); void CalculateCubeAndTcp();
192 void ReceiveWholeGrid(const SRenderGrid&); void RequestWholeGrid(); void PrepareForReposition(); void Process();
193 void CalculateInsideArray(short, short) const {}
194 void RemoveBuildZone(short) const { throw std::runtime_error("weather touched a terrain building"); }
195};
196#include "TerrainGeometry.generated.h"
197#include "TerrainGrid.generated.h"
198#include "TerrainWeatherSource.generated.h"
199
200struct Receiver
201{
202 struct HandlerGame { Viewscreen* viewscreen; } owner;
203 HandlerGame* game = &owner; char msg[999]{};
204 int commands = 0, buildings = 0, menus = 0;
205 void Trace(const char* text, Logger::Level level = Logger::Info) { game->viewscreen->logger->Log(text, level); }
206 void Receive(const std::vector<unsigned char>& wire)
207 {
208 struct Packet { const unsigned char* data; unsigned length; } storage{wire.data(), static_cast<unsigned>(wire.size())};
209 auto* packet = &storage;
210 if (!packet->length || packet->data[0] != ID_USER_PACKET_ENUM) return;
211 switch (packet->length - 1)
212 {
213 case sizeof SServerPacket: {
214 SServerPacket datapacket;
215 memcpy(&datapacket,packet->data+1,sizeof datapacket);
216 switch(datapacket.type) {
217#include "Weather1Receiver.generated.h"
218#include "LightningReceiver.generated.h"
219 default: ++commands; break;
220 }
221 break;
222 }
223 case sizeof SRenderBuilding: ++buildings; break;
224 case sizeof SPacketMenu: ++menus; break;
225#include "TerrainReceiver.generated.h"
226 }
227 }
228};
229
230static void Put16(unsigned char* p, int value)
231{ p[0]=static_cast<unsigned char>(value); p[1]=static_cast<unsigned char>(value >> 8); }
232static void Put32(unsigned char* p, uint32_t value)
233{ Put16(p,value & 65535); Put16(p+2,value >> 16); }
234static void PutSample(unsigned char* p, int i)
235{
236 p[0]=static_cast<unsigned char>(20+i%141); p[1]=static_cast<unsigned char>((i/7)%256);
237 p[4]=static_cast<unsigned char>(i%256);p[5]=static_cast<unsigned char>((i/5)%256);
238 p[6]=static_cast<unsigned char>((i/3)%256);p[7]=0;
239 Put16(p+2,300+i); Put16(p+8,42160-i);
240 p[10]=static_cast<unsigned char>(i%158);p[11]=static_cast<unsigned char>((i/11)%256);
241}
242static std::vector<unsigned char> Packet(bool full, VECTOR2SHORT center, unsigned cube,
243 uint32_t revision, uint32_t base, uint16_t token, unsigned side=0, int first=0)
244{
245 std::vector<unsigned char> bytes(1+(full?49168:784));
246 bytes[0]=ID_USER_PACKET_ENUM;
247 auto* p=bytes.data()+1;
248 Put16(p,center.u); Put16(p+2,center.v); p[4]=static_cast<unsigned char>(cube);
249 p[5]=static_cast<unsigned char>(side); Put16(p+6,token); Put32(p+8,revision); Put32(p+12,base);
250 for(int i=0;i<(full?4096:64);++i) PutSample(p+16+i*12,first+i);
251 return bytes;
252}
253static PlotWeather::Result Accept(PlotWeather::Store& store, const std::vector<unsigned char>& p, uint16_t token=7)
254{ return store.Accept(p.data()+1,p.size()-1,token); }
255static void CheckSample(const SRenderWeather* sample, int index)
256{
257 Check(sample && sample->HasVisibility(), "expected a valid located weather sample");
258 Check(sample->precipitation==20+index%141 && sample->ceiling==300+index
259 && sample->visibility==42160-index && sample->snowDepthMm==index%256
260 && sample->surfaceWaterTenthsMm==(index/5)%256 && sample->unused==0
261 && sample->windDirectionRadians==index%158 && sample->windSpeedMs==(index/11)%256
262 && sample->snowAgeHours==(index/3)%256 && sample->turbulence==(index/7)%256, "weather shifted onto the wrong plot");
263}
264static std::vector<unsigned char> Weather1Packet(unsigned char encoded,float unusedTurbulence=.3f)
265{
266 SServerPacket data{}; data.type=14; data.array=encoded;
267 data.f_x=1.2f; data.f_y=unusedTurbulence; data.f_z=15.f; data.f_w=.02f;
268 std::vector<unsigned char> wire(1+sizeof data); wire[0]=ID_USER_PACKET_ENUM;
269 memcpy(wire.data()+1,&data,sizeof data); return wire;
270}
271static std::vector<unsigned char> Weather2Packet()
272{
273 SServerPacket data{};data.type=39;data.array=1;
274 data.f_x=9;data.f_y=9;data.f_z=9;
275 std::vector<unsigned char> wire(1+sizeof data);wire[0]=ID_USER_PACKET_ENUM;
276 memcpy(wire.data()+1,&data,sizeof data);return wire;
277}
278static void CheckStore()
279{
280 // Literal bytes emitted by Server.NET's Marshal layout fixture.
281 const unsigned char goldenHeader[16]{0x34,0x12,0xfe,0xff,0x04,0x01,0xcd,0xab,
282 0x78,0x56,0x34,0x12,0x77,0x56,0x34,0x12};
283 std::vector<unsigned char> goldenRow(784);
284 memcpy(goldenRow.data(),goldenHeader,sizeof goldenHeader);
285 SPlotWeatherHeader golden;
286 Check(PlotWeather::ParseHeader(goldenRow.data(),goldenRow.size(),golden)
287 && golden.tcp.u==0x1234 && golden.tcp.v==-2 && golden.cube==4 && golden.side==1
288 && golden.requestToken==0xabcd && golden.revision==0x12345678 && golden.baseRevision==0x12345677,
289 "managed server header golden bytes changed");
290 const VECTOR2SHORT center(500,1100);
291 auto full=Packet(true,center,0,100,0,7);
292 SPlotWeatherHeader header;
293 for(size_t length:{size_t(0),size_t(20),size_t(28),size_t(32),size_t(528),size_t(656),size_t(32784),size_t(40976),size_t(783),size_t(785),size_t(49167),size_t(49169),size_t(400),size_t(24592)})
294 Check(!PlotWeather::ParseHeader(full.data()+1,length,header),"malformed weather length accepted");
295 Check(!PlotWeather::ParseHeader(nullptr,49168,header),"null weather payload accepted");
296 for(unsigned cube:{6u,255u}) {
297 auto invalid=full; invalid[5]=static_cast<unsigned char>(cube);
298 Check(!PlotWeather::ParseHeader(invalid.data()+1,49168,header),"invalid cube accepted");
299 }
300 auto invalid=full; invalid[6]=1;
301 Check(!PlotWeather::ParseHeader(invalid.data()+1,49168,header),"full packet with strip side accepted");
302 invalid=full; Put32(invalid.data()+9,0);
303 Check(!PlotWeather::ParseHeader(invalid.data()+1,49168,header),"zero revision accepted");
304 invalid=full; Put32(invalid.data()+13,1);
305 Check(!PlotWeather::ParseHeader(invalid.data()+1,49168,header),"full packet with base accepted");
306
307 for(int side=1;side<=4;++side)
308 {
309 PlotWeather::Store store;
310 Check(Accept(store,full)==PlotWeather::Result::Full,"full weather grid rejected");
311 for(int q=0;q<64;++q) for(int r=0;r<64;++r)
312 CheckSample(store.At(0,VECTOR2SHORT(center.u+q-31,center.v+r-31),7),q*64+r);
313 Check(!store.At(1,center,7) && !store.At(0,center,8)
314 && !store.At(0,VECTOR2SHORT(center.u+33,center.v),7),"weather sampling escaped face/token/bounds");
315 const int du=side==3?1:side==4?-1:0, dv=side==2?1:side==1?-1:0;
316 const VECTOR2SHORT next(center.u+du,center.v+dv);
317 auto row=Packet(false,next,0,117,100,7,side,6000);
318 Check(Accept(store,row)==PlotWeather::Result::Row,"valid weather strip rejected");
319 for(int q=0;q<64;++q) for(int r=0;r<64;++r)
320 {
321 const int oldQ=q+du, oldR=r+dv;
322 const bool retained=oldQ>=0 && oldQ<64 && oldR>=0 && oldR<64;
323 const int expected=retained?oldQ*64+oldR:6000+(du?r:q);
324 CheckSample(store.At(0,VECTOR2SHORT(next.u+q-31,next.v+r-31),7),expected);
325 }
326 Check(Accept(store,row)==PlotWeather::Result::Ignored && Accept(store,full)==PlotWeather::Result::Ignored,
327 "duplicate/delayed packet overwrote a newer grid");
328 auto gap=Packet(false,VECTOR2SHORT(next.u+du,next.v+dv),0,120,116,7,side);
329 Check(Accept(store,gap)==PlotWeather::Result::NeedFull && store.Header().revision==117,
330 "missing strip base failed to request repair or mutated storage");
331 auto wrongStep=Packet(false,next,0,120,117,7,side);
332 Check(Accept(store,wrongStep)==PlotWeather::Result::NeedFull,"invalid strip displacement accepted");
333 auto wrongFace=Packet(false,VECTOR2SHORT(next.u+du,next.v+dv),1,120,117,7,side);
334 Check(Accept(store,wrongFace)==PlotWeather::Result::NeedFull,"cross-face strip accepted");
335 Check(Accept(store,Packet(true,next,0,121,0,8))==PlotWeather::Result::Ignored,"unrequested token accepted");
336 Check(Accept(store,Packet(true,next,0,122,0,7))==PlotWeather::Result::Full,"repair full rejected");
337 }
338
339 PlotWeather::Store store;
340 Check(Accept(store,Packet(false,center,0,2,1,7,1))==PlotWeather::Result::NeedFull,"row established an empty grid");
341 Check(Accept(store,Packet(true,center,0,0xfffffff0u,0,7))==PlotWeather::Result::Full,"large initial revision rejected");
342 Check(Accept(store,Packet(false,VECTOR2SHORT(501,1100),0,5,0xfffffff0u,7,3))==PlotWeather::Result::Row,"revision wrap broke a valid strip");
343 Check(Accept(store,Packet(true,center,0,6,0,0),0)==PlotWeather::Result::Full,"request token zero/wrap rejected");
344 store.Reset();
345 Check(Accept(store,Packet(true,center,0,1,0,7))==PlotWeather::Result::Full,"connection reset retained revision watermark");
346 auto unavailable=full; unavailable[17]=19;
347 Check(Accept(store,unavailable)==PlotWeather::Result::Full
348 && !store.At(0,VECTOR2SHORT(469,1069),7)->Available(),"invalid sample was treated as valid weather");
349 unsigned char sample[12]{0x49,0x7b,0xd2,0x04,0x19,0x7b,0xf0,0x00,0xb0,0xa4,0x1f,0x0d};
350 auto decoded=PlotWeather::Sample(sample);
351 Check(decoded.ceiling==1234 && decoded.visibility==42160
352 && decoded.precipitation==73 && decoded.turbulence==123
353 && decoded.snowDepthMm==25 && decoded.surfaceWaterTenthsMm==123 && decoded.snowAgeHours==240
354 && decoded.unused==0 && decoded.windDirectionRadians==31 && decoded.windSpeedMs==13
355 && memcmp(&decoded,sample,sizeof sample)==0,
356 "twelve-byte server golden cell or little-endian units changed");
357 // Independent depths, including age-zero snow and simultaneous meltwater.
358 for(int snow=0;snow<=255;++snow) for(int water:{0,1,123,255}) for(int age:{0,1,127,240,255}) {
359 sample[4]=static_cast<unsigned char>(snow);sample[5]=static_cast<unsigned char>(water);
360 sample[6]=static_cast<unsigned char>(age);sample[7]=0xa5;
361 const auto cell=PlotWeather::Sample(sample);
362 Check(cell.HasVisibility() && cell.turbulence==123 && cell.snowDepthMm==snow
363 && cell.surfaceWaterTenthsMm==water && cell.snowAgeHours==age
364 && cell.windDirectionRadians==31 && cell.windSpeedMs==13,
365 "independent surface fields or reserved byte affected another quantity");
366 }
367 for(int value:{0,1,127,255}) {
368 sample[1]=sample[10]=sample[11]=static_cast<unsigned char>(value);
369 const auto cell=PlotWeather::Sample(sample);
370 Check(cell.turbulence==value && cell.windDirectionRadians==value && cell.windSpeedMs==value
371 && cell.snowDepthMm==255 && cell.surfaceWaterTenthsMm==255,"byte endpoints lost independent fields");
372 }
373 for(int meters:{0,1,10,42160,42161,65535}) {
374 Put16(sample+8,meters);
375 Check(PlotWeather::Sample(sample).HasVisibility()==(meters>0 && meters<=42160),"visibility limits changed");
376 }
377 Put16(sample+8,42160);
378 for(int meters:{-32768,-1,0,32767}) {
379 Put16(sample+2,meters);
380 Check(PlotWeather::Sample(sample).HasVisibility()==(meters>=0),"ceiling validity changed");
381 }
382 const unsigned char absent[12]{};
383 decoded=PlotWeather::Sample(absent);
384 Check(!decoded.HasVisibility() && memcmp(&decoded,absent,sizeof absent)==0,"missing weather invented surface values");
385
386}
387
388
389static bool Near(float a, float b, float tolerance=.001f) { return fabsf(a-b)<=tolerance; }
390static void CheckInterpolation()
391{
392 const VECTOR2SHORT center(500,1100);
393 const auto full=Packet(true,center,0,100,0,7);
394 PlotWeather::Store store;
395 Accept(store,full);
397 const double u=500.25, v=1100.75, index=31.25*64+31.75;
398 Check(store.Interpolate(0,u,v,7,local)
399 && Near(local.ceilingMeters,float(index+300)) && Near(local.visibilityMeters,float(42160-index)),
400 "fractional bilinear targets do not match the four control samples");
401 for(int axis=0;axis<2;++axis) {
402 PlotWeather::LocalSample left,right;
403 const double a=axis?500.25:500.999999, b=axis?1100.999999:1100.75;
404 Check(store.Interpolate(0,a,b,7,left)
405 && store.Interpolate(0,a+(axis?0:.000002),b+(axis?.000002:0),7,right)
406 && Near(left.ceilingMeters,right.ceilingMeters)
408 "local weather target jumped across a control-point boundary");
409 }
410 for(int side=1;side<=4;++side) {
411 PlotWeather::Store shifted; Accept(shifted,full);
412 const int du=side==3?1:side==4?-1:0, dv=side==2?1:side==1?-1:0;
413 const auto row=Packet(false,VECTOR2SHORT(center.u+du,center.v+dv),0,117,100,7,side,6000);
414 Accept(shifted,row);
415 for(int q=1;q<62;++q) for(int r=1;r<62;++r) {
416 const double x=center.u+q-31+.25, y=center.v+r-31+.75;
417 PlotWeather::LocalSample before,after;
418 Check(store.Interpolate(0,x,y,7,before) && shifted.Interpolate(0,x,y,7,after)
419 && before.ceilingMeters==after.ceilingMeters
420 && before.visibilityMeters==after.visibilityMeters && before.precipitation==after.precipitation
421 && before.snowDepthMm==after.snowDepthMm && before.snowAgeHours==after.snowAgeHours
422 && before.surfaceWaterMm==after.surfaceWaterMm && before.turbulence==after.turbulence
424 && before.surfaceWindSpeedMs==after.surfaceWindSpeedMs,
425 "shifting the grid changed local interpolation in the retained footprint");
426 }
427 }
428 Check(store.Interpolate(0,469,1069,7,local) && Near(local.ceilingMeters,300)
429 && store.Interpolate(0,532,1132,7,local) && Near(local.ceilingMeters,4395),
430 "exact edge samples needed a nonexistent neighbor");
431 Check(!store.Interpolate(0,532.01,1132,7,local) && !store.Interpolate(1,u,v,7,local)
432 && !store.Interpolate(0,u,v,8,local),"interpolation crossed coverage, face or token");
433 // Unequal weights preserve independent depth units, even for fresh snow.
434 auto mixed=full;
435 const int depths[4]{40,123,255,255}, waters[4]{100,123,255,0}, ages[4]{1,0,255,0};
436 for(int dq=0;dq<2;++dq)for(int dr=0;dr<2;++dr) {
437 auto* cell=mixed.data()+17+((31+dq)*64+31+dr)*12;
438 cell[4]=static_cast<unsigned char>(depths[dq*2+dr]);
439 cell[5]=static_cast<unsigned char>(waters[dq*2+dr]);
440 cell[6]=static_cast<unsigned char>(ages[dq*2+dr]);
441 }
442 PlotWeather::Store mixedStore;Accept(mixedStore,mixed);
443 Check(mixedStore.Interpolate(0,u,v,7,local) && Near(local.snowDepthMm,140.4375f)
444 && Near(local.snowAgeHours,16.125f) && Near(local.surfaceWaterMm,10.3875f),
445 "snow/water interpolation lost independent depth units");
446 Check(mixedStore.Interpolate(0,500,1101,7,local) && Near(local.snowDepthMm,123)
447 && Near(local.snowAgeHours,0) && Near(local.surfaceWaterMm,12.3f),
448 "age-zero snow and surface water must coexist");
449 Check(mixedStore.Interpolate(0,501,1100,7,local) && Near(local.snowDepthMm,255)
450 && Near(local.snowAgeHours,255) && Near(local.surfaceWaterMm,25.5f),
451 "aged snow lost simultaneous surface water");
452 auto missing=full;
453 missing[17+(31*64+32)*12]=0;
454 PlotWeather::Store partial; Accept(partial,missing);
455 local={123,456,2};
456 Check(!partial.Interpolate(0,u,v,7,local) && local.ceilingMeters==123
457 && partial.Interpolate(0,500,1100,7,local),
458 "missing neighbor blended zeroes, changed the output, or invalidated an exact good point");
459 const double nan=std::numeric_limits<double>::quiet_NaN();
460 Check(!store.Interpolate(0,nan,v,7,local) && !store.Interpolate(0,u,nan,7,local),
461 "nonfinite interpolation coordinates accepted");
462}
463static void CheckSurfaceWind()
464{
465 const unsigned char golden[12]{0x49,0x7b,0xd2,0x04,0x19,0x7b,0xf0,0,0xb0,0xa4,0x1f,0x0d};
466 auto wire=Packet(true,{500,1100},0,100,0,7);
467 for(int i=0;i<4096;++i) memcpy(wire.data()+17+i*12,golden,12);
468 PlotWeather::Store store;Accept(store,wire);
470 Check(store.Interpolate(0,500.25,1100.75,7,local)
471 && Near(local.surfaceWindDirectionRadians,1.24f) && Near(local.surfaceWindSpeedMs,13)
472 && Near(local.surfaceWindSpeedMs*.001f,.013f) && Near(local.surfaceWaterMm,12.3f)
473 && Near(local.snowDepthMm,25),"server golden wind/surface units differ");
474
475 auto blend=[&](unsigned char direction0,unsigned char speed0,unsigned char direction1,unsigned char speed1) {
476 auto packet=wire;
477 for(int q=0;q<64;++q)for(int r=0;r<64;++r) {
478 auto* cell=packet.data()+17+(q*64+r)*12;
479 cell[10]=q<=31?direction0:direction1;cell[11]=q<=31?speed0:speed1;
480 }
481 store.Reset();Accept(store,packet);
482 Check(store.Interpolate(0,500.5,1100.25,7,local),"wind blend fixture unavailable");
483 };
484 blend(0,10,157,10); // 0 and 6.28 radians straddle the direction wrap.
485 Check(Near(local.surfaceWindDirectionRadians,6.28159265f,.00001f)
486 && Near(local.surfaceWindSpeedMs,10,.0001f),"wind direction took the long route across north");
487 blend(0,10,79,10); // Quantization makes 3.16 radians nearly, not exactly, opposite.
488 Check(local.surfaceWindSpeedMs<.1f && std::isfinite(local.surfaceWindDirectionRadians),
489 "opposing surface winds did not cancel as vectors");
490 blend(78,0,31,20);
491 Check(Near(local.surfaceWindDirectionRadians,1.24f) && Near(local.surfaceWindSpeedMs,10),
492 "calm cell bearing rotated the active surface wind");
493 blend(0,0,157,0);
494 Check(local.surfaceWindDirectionRadians==0 && local.surfaceWindSpeedMs==0,
495 "calm wind has nonfinite or stale direction/speed");
496 blend(31,255,31,255);
497 Check(Near(local.surfaceWindDirectionRadians,1.24f) && Near(local.surfaceWindSpeedMs,255),
498 "surface wind upper byte endpoint changed units");
499
500 auto unequal=wire;
501 const unsigned char speeds[]{0,10,100,200};
502 for(int q=0;q<2;++q)for(int r=0;r<2;++r)
503 unequal[17+((31+q)*64+31+r)*12+11]=speeds[q*2+r];
504 store.Reset();Accept(store,unequal);
505 Check(store.Interpolate(0,500.25,1100.75,7,local)
506 && Near(local.surfaceWindDirectionRadians,1.24f) && Near(local.surfaceWindSpeedMs,49.375f),
507 "surface wind used different bilinear weights");
508 const auto previous=local;
509 unequal[17+(31*64+32)*12]=0;
510 store.Reset();Accept(store,unequal);
511 Check(!store.Interpolate(0,500.25,1100.75,7,local)
512 && local.surfaceWindDirectionRadians==previous.surfaceWindDirectionRadians
513 && local.surfaceWindSpeedMs==previous.surfaceWindSpeedMs,"missing weather changed retained surface wind");
514}
515static void CheckCoordinates(Viewscreen& view)
516{
517 const VECTOR2SHORT centers[6]{{1019,1019},{3057,1019},{-1019,1019},{5095,1019},{1019,-1019},{1019,3057}};
518 for(unsigned face=0;face<6;++face) for(int offset=-900;offset<=900;offset+=300) {
519 const auto center=centers[face];
520 // Fractional planar position from four production ground control points.
521 auto point=[&](short u,short v) {
522 auto p=view.CalculatePlanar(u,v);
523 const float dominant=(face==0||face==3)?fabsf(p.y):(face==1||face==2)?fabsf(p.x):fabsf(p.z);
524 return p/dominant;
525 };
526 const short x=center.u+offset,y=center.v-offset;
527 auto position=(point(x,y)*.1875f+point(x+1,y)*.0625f+point(x,y+1)*.5625f+point(x+1,y+1)*.1875f)*6000.f;
528 double u,v;
529 Check(unsigned(view.CalculateCube(position))==face && PlotWeather::Coordinates(position,face,u,v)
530 && fabs(u-(x+.25))<.001 && fabs(v-(y+.75))<.001,
531 "fractional weather projection differs from production ground geometry");
532 const auto integral=view.CalculateCGC(position,static_cast<char>(face));
533 Check(integral.u==x && integral.v==y,"fractional projection lost negative-face alignment");
534 position=position*1.1f;
535 Check(PlotWeather::Coordinates(position,face,u,v) && fabs(u-(x+.25))<.001 && fabs(v-(y+.75))<.001,
536 "altitude changed fractional weather coordinates");
537 }
538 double u,v;
540 && !PlotWeather::Coordinates(RiseMath::Vector3(1,1,1),6,u,v),"invalid weather projection accepted");
541}
542
543static void LoadTerrain(Viewscreen& view, VECTOR2SHORT center, char cube, short elevation=200, bool slope=false)
544{
545 auto& terrain=*view.ptrGrid;
546 terrain.requestedCube=cube;terrain.requestedTcp=center;terrain.wholeGridPending=true;
547 auto data=std::make_unique<SRenderGrid>();data->tcp=center;
548 for(int q=0;q<64;++q)for(int r=0;r<64;++r) {
549 auto& sample=data->gridarray[q][r];sample.pri_landform=2;
550 sample.elevation=slope?short(100+(center.u+q-31)*2+(center.v+r-31)*3):elevation;
551 }
552 terrain.ReceiveWholeGrid(*data);
553 terrain.geometryReady=true;terrain.wholeGridReceived=false;
554}
555
556static void InitialTerrain(Viewscreen& view, grid& terrain, Receiver& receiver)
557{
558 terrain.ClearGrid();
559 const float lat=RiseMath::ToRadian(5.413f), lon=RiseMath::ToRadian(-26.359f);
560 playerships[0].position=RiseMath::Vector3(sinf(lon)*cosf(lat),-cosf(lon)*cosf(lat),sinf(lat))*(radiusC+.405f);
561 terrain.CalculateCubeAndTcp(); terrain.RequestWholeGrid();
562 auto data=std::make_unique<SRenderGrid>(); data->tcp=terrain.requestedTcp;
563 for(auto& column:data->gridarray) for(auto& v:column) { v.pri_landform=2; v.elevation=300; v.color=0xff445566; }
564 std::vector<unsigned char> wire(1+sizeof *data); wire[0]=ID_USER_PACKET_ENUM;
565 memcpy(wire.data()+1,data.get(),sizeof *data); receiver.Receive(wire);
566 Check(terrain.dataReady && !terrain.wholeGridPending,"legacy terrain full stopped working");
567 terrain.geometryReady=true; terrain.wholeGridReceived=false;
568}
569static std::vector<LOCALGRID2> TerrainSnapshot()
570{
571 std::vector<LOCALGRID2> result(4096); memcpy(result.data(),gridarray,sizeof gridarray); return result;
572}
573static void TerrainUnchanged(const std::vector<LOCALGRID2>& before)
574{ Check(memcmp(before.data(),gridarray,sizeof gridarray)==0,"weather packet mutated ground/building storage"); }
575
576static void CheckIntegration(Viewscreen& view, grid& terrain, Receiver& receiver, Network& network)
577{
578 InitialTerrain(view,terrain,receiver);
579 auto& weather=view.weather;
580 const auto center=terrain.tcp; const unsigned cube=terrain.cube;
581 gridarray[31][31].buildzoneOrdinal=7;
582 const auto ground=TerrainSnapshot();
583 const float initialPrecip=weather.precip;
584 receiver.Receive(Weather1Packet(72));
585 Check(weather.precip==initialPrecip,"deprecated Weather1 array changed precipitation before grid detection");
586 receiver.Receive(Weather2Packet());
587 Check(weather.resets==0 && weather.cloudCeilingSmoothAglKm==-1,
588 "retired Weather2 initialized weather before grid arrival");
589 const int before=weather.resets;
590 weather.UpdatePlotWeatherConditions(); // no capability push is needed
591 Check(network.weatherRequests.size()==1 && network.weatherRequests.back().f_x==1,
592 "startup did not request grid weather before receiving any weather packet");
593 receiver.Receive(Packet(true,center,cube,10,0,0));
594 Check(weather.weatherPending && !weather.plotWeather.Ready() && weather.resets==before,"initial push bypassed causal request");
596 Check(network.weatherRequests.size()==1 && network.weatherRequests.back().f_x==1,"initial weather request missing");
597 receiver.Receive(Packet(true,center,cube,11,0,0));
598 Check(weather.weatherPending && weather.resets==before,"old token consumed initial reset");
599 receiver.Receive(Packet(true,center,cube,12,0,1));
600 double localU,localV;
601 Check(PlotWeather::Coordinates(playerships[0].position,cube,localU,localV),"initial weather coordinate failed");
602 const float localIndex=float((31+localU-center.u)*64+31+localV-center.v);
603 Check(!weather.weatherPending && weather.resets==before+1
604 && fabsf(weather.cloudSurfaceSmoothKm+weather.cloudCeilingSmoothAglKm-(600+localIndex)*.001f)<.00001f
605 && fabsf(weather.smoothVisibility-(42160-localIndex)*.001f)<.00001f,"independent full did not initialize local weather");
606 TerrainUnchanged(ground);
607 PlotWeather::LocalSample interpolated;
608 Check(weather.plotWeather.Interpolate(cube,localU,localV,1,interpolated)
610 "grid precipitation did not feed/snap the local target");
611 Check(weather.winddir==1.2f && weather.windspeed==.02f && weather.temperature==15.f,
612 "surface wind replaced altitude-specific Weather1 values during grid application");
613 const float gridPrecip=weather.precip;
614 receiver.Receive(Weather1Packet(0,0)); receiver.Receive(Weather1Packet(252));
615 Check(weather.precip==gridPrecip && weather.winddir==1.2f && weather.GetTurbulence()==interpolated.turbulence
616 && weather.temperature==15.f && weather.windspeed==.02f,
617 "modern Weather1 changed precipitation or lost wind/temperature fields");
618 receiver.Receive(Weather2Packet());
619 Check(weather.resets==before+1 && weather.visibility>40,"Weather2 overwrote independent weather");
620
621 // A strip shifts only weather; the terrain grid and buildings remain identical.
622 receiver.Receive(Packet(false,VECTOR2SHORT(center.u+1,center.v),cube,13,12,1,3,6000));
623 TerrainUnchanged(ground);
624 Check(terrain.geometryReady && weather.resets==before+1,"weather strip rebuilt mesh or reset smoothers");
625 receiver.Receive(std::vector<unsigned char>(21,ID_USER_PACKET_ENUM));
626 receiver.Receive(std::vector<unsigned char>(25,ID_USER_PACKET_ENUM));
627 receiver.Receive(std::vector<unsigned char>(533,ID_USER_PACKET_ENUM));
628 Check(receiver.commands==1 && receiver.buildings==1 && receiver.menus==1,"weather envelope collided with existing messages");
629
631 Check(weather.weatherPending && network.weatherRequests.back().f_x==2,"W0 did not request a new weather token");
632 receiver.Receive(Packet(true,center,cube,14,0,1));
633 Check(weather.weatherPending && weather.resets==before+1,"delayed same-position full consumed W0 reset");
634 receiver.Receive(Packet(true,VECTOR2SHORT(center.u+100,center.v),cube,15,0,2));
635 Check(weather.weatherPending && weather.resets==before+1,"off-location full consumed reset");
636 auto missing=Packet(true,center,cube,16,0,2); missing[17+(31*64+31)*12]=0;
637 receiver.Receive(missing);
638 Check(weather.weatherPending && weather.resets==before+1,"missing weather consumed reset");
639 receiver.Receive(Packet(true,center,cube,17,0,2));
640 Check(!weather.weatherPending && weather.resets==before+2,"destination full did not consume reset once");
641 TerrainUnchanged(ground);
642 receiver.Receive(Packet(false,VECTOR2SHORT(center.u+1,center.v),cube,20,18,2,3));
643 Check(weather.weatherRequestQueued && !weather.weatherPending,"gap recovery incorrectly armed a local reset");
645 Check(network.weatherRequests.back().f_x==3,"missing base did not request repair");
646 receiver.Receive(Packet(true,center,cube,21,0,3));
647 Check(weather.resets==before+2,"transport repair reset weather smoothers");
648
649 // Terrain clearing is independent; weather suspends at the same cloud state.
650 gridarray[31][31].buildzoneOrdinal=-1;
651 const auto requestCount=network.weatherRequests.size();
652 const float heldVisibility=weather.visibility, heldBase=weather.cloudCeilingSmoothAglKm;
655 && network.weatherRequests.size()==requestCount,"ascent retained grid or sent a request");
657 receiver.Receive(Packet(true,center,cube,22,0,4));
658 Check(weather.weatherPending && weather.resets==before+2 && !weather.plotWeather.Ready()
659 && weather.visibility==heldVisibility && weather.cloudCeilingSmoothAglKm==heldBase
660 && network.weatherRequests.size()==requestCount,"above-cloud packet applied weather/W0");
662 Check(network.weatherRequests.size()==requestCount+1 && network.weatherRequests.back().f_x==5,
663 "descent did not replace the deferred W0 token");
664 receiver.Receive(Packet(true,center,cube,23,0,4));
665 Check(weather.weatherPending && !weather.plotWeather.Ready(),"in-flight full crossed descent token");
666 receiver.Receive(Packet(true,center,cube,24,0,5));
667 Check(weather.weatherPending && weather.resets==before+2,"weather without terrain consumed deferred W0");
668 LoadTerrain(view,center,static_cast<char>(cube),300);weather.UpdatePlotWeatherConditions();
669 Check(!weather.weatherPending && weather.resets==before+3,"deferred W0 did not snap after terrain arrived");
670 const auto aboveCenter=center;
671
673 Check(network.weatherRequests.back().f_x==0,"request token did not wrap as ushort");
674 receiver.Receive(Packet(true,aboveCenter,cube,25,0,0));
675 Check(!weather.weatherPending && weather.resets==before+4,"wrapped token full failed");
676 const float smoothBefore=weather.smoothVisibility, smoothPrecipBefore=weather.smoothPrecip;
677 auto refresh=Packet(true,aboveCenter,cube,26,0,0);
678 for(int i=0;i<4096;++i) { Put16(refresh.data()+17+i*12+8,1000); refresh[17+i*12]=140; }
679 receiver.Receive(refresh);
680 Check(weather.resets==before+4 && weather.visibility==1.f && weather.smoothVisibility==smoothBefore
681 && weather.precip==14.f && weather.smoothPrecip==smoothPrecipBefore,
682 "ordinary full weather advance bypassed temporal smoothing");
685 "connection reset failed to queue a fresh modern grid");
686 const float reconnectVisibility=weather.smoothVisibility;
687 receiver.Receive(Weather2Packet());
688 Check(weather.smoothVisibility==reconnectVisibility && weather.weatherPending,
689 "retired Weather2 consumed a reconnect reset");
690 const float reconnectPrecip=weather.precip;
691 receiver.Receive(Weather1Packet(72));
692 Check(weather.precip==reconnectPrecip,"connection reset restored deprecated Weather1 precipitation decoding");
693}
694
695
696static std::vector<unsigned char> LightningPacket(float u,float v,float seed=77,float chains=1)
697{
698 SServerPacket data{};data.type=42;data.f_x=u;data.f_y=v;data.f_z=chains;data.f_w=seed;
699 std::vector<unsigned char> wire(1+sizeof data);wire[0]=ID_USER_PACKET_ENUM;
700 memcpy(wire.data()+1,&data,sizeof data);return wire;
701}
702static std::vector<unsigned char> StormGrid(VECTOR2SHORT center,unsigned cube,uint32_t revision,uint16_t token,bool eastOnly)
703{
704 auto packet=Packet(true,center,cube,revision,0,token);
705 for(int q=0;q<64;++q) for(int r=0;r<64;++r) {
706 auto* p=packet.data()+17+(q*64+r)*12;
707 p[0]=eastOnly && q<33?20:160;
708 Put16(p+2,900+q*30);Put16(p+8,15000);
709 }
710 return packet;
711}
712static void CheckLightningIntegration(Viewscreen& view,Receiver& receiver,Network& network)
713{
714 auto& weather=view.weather;
715 playerships[0].position=view.CalculatePlanar(500,1100)*(radiusC+.4f);
717 const unsigned cube=view.CalculateCube(playerships[0].position);
718 const auto center=view.CalculateCGC(playerships[0].position,static_cast<char>(cube));
719 LoadTerrain(view,center,static_cast<char>(cube));
721 receiver.Receive(StormGrid(center,cube,100,0,true));weather.UpdatePlotWeatherConditions();
722 receiver.Receive(StormGrid(center,cube,101,1,true));
723 Check(!weather.weatherPending && weather.precip==2.f,"storm direction fixture is not locally clear");
725 network.lightningRequests.clear();
726 for(int i=0;i<6000;++i) weather.UpdateLightningSpawns(.1f);
727 Check(network.lightningRequests.size()>250 && network.lightningRequests.size()<550,
728 "regional storm rate multiplied by wet-sector count or depended on local rain");
729 for(const auto& packet:network.lightningRequests)
730 Check(packet.f_x>=center.u+2,"lightning spawned in the dry/wrong direction");
731 const auto sent=network.lightningRequests.front();
732 const int before=view.strikes;
733 receiver.Receive(LightningPacket(sent.f_x,sent.f_y,sent.f_w,sent.f_z));
734 const float cellCeiling=(900+(sent.f_x-center.u+31)*30)*.001f;
735 Check(view.strikes==before+1 && view.legacyStrikes==0
736 && Near(RiseMath::Vec3Length(&view.strikeGround),radiusC+.2f,.002f)
737 && Near(RiseMath::Vec3Length(&view.strikeCloud),radiusC+.2f+cellCeiling,.002f)
738 && Near(view.strikeDistance,GridLightning::Distance(view.strikeGround,playerships[0].position),.001f),
739 "strike did not use selected cell elevation, ceiling and actual observer distance");
740 const auto count=network.lightningRequests.size();
742 receiver.Receive(LightningPacket(sent.f_x,sent.f_y));
743 Check(network.lightningRequests.size()==count && view.strikes==before+1,"lightning generated/rendered at or above 10 km");
745 receiver.Receive(LightningPacket(sent.f_x,sent.f_y));
746 Check(network.lightningRequests.size()==count && view.strikes==before+1,"simulator generated lightning");
747 playerships[0].isSimulator=false;
749 receiver.Receive(LightningPacket(sent.f_x,sent.f_y));
750 Check(network.lightningRequests.size()==count && view.strikes==before+1 && weather.gridLightning.CellCount()==0,
751 "pending W0 used the old storm footprint");
752 receiver.Receive(LightningPacket(std::numeric_limits<float>::quiet_NaN(),sent.f_y));
753 receiver.Receive(LightningPacket(sent.f_x+.5f,sent.f_y));
754 receiver.Receive(LightningPacket(sent.f_x,sent.f_y,77,100));
755 Check(view.strikes==before+1,"malformed lightning packet reached renderer");
756
757 // EP's north neighbor has a rotated canonical TCP on NP. Old subtraction
758 // against the terrain center discarded it despite being only a few km away.
759 playerships[0].position=view.CalculatePlanar(3057,1)*(radiusC+.4f);
760 const auto seamCube=view.CalculateCube(playerships[0].position);
761 const auto seamCenter=view.CalculateCGC(playerships[0].position,seamCube);
762 Check(seamCube==1,"seam fixture left EP");
763 LoadTerrain(view,seamCenter,static_cast<char>(seamCube));
765 receiver.Receive(StormGrid(seamCenter,seamCube,200,0,false));weather.UpdatePlotWeatherConditions();
766 receiver.Receive(StormGrid(seamCenter,seamCube,201,1,false));
767 char rotation;
768 const auto canonical=view.CalculateWrap(3057,-1,seamCube,&rotation);
769 const int seamBefore=view.strikes;
770 receiver.Receive(LightningPacket(canonical.u,canonical.v));
771 Check(rotation!=0 && view.strikes==seamBefore+1 && view.strikeDistance<20,
772 "rotated cube-seam lightning lost its geographic position");
773 const auto savedRevision=weather.lightningWeatherRevision;
774 const auto* strike=weather.gridLightning.Find(canonical.u,canonical.v);
775 Check(strike!=nullptr && savedRevision==201,"lightning geometry cache did not use the accepted weather revision");
778 Check(weather.gridLightning.CellCount()==0 && view.strikes==seamBefore+1,
779 "disconnect retained lightning or accepted a strike without current weather");
780
781 // No grid means no strike, even with valid terrain and an old packet.
782 const int legacyBefore=view.legacyStrikes, modernBefore=view.strikes;
783 receiver.Receive(LightningPacket(seamCenter.u,seamCenter.v));
784 Check(view.legacyStrikes==legacyBefore && view.strikes==modernBefore,
785 "retired terrain-only lightning path accepted a strike without weather");
786 playerships[0].isSimulator=true;
787 const auto sentBefore=network.lightningRequests.size();
789 receiver.Receive(LightningPacket(seamCenter.u,seamCenter.v));
790 Check(view.legacyStrikes==legacyBefore && view.strikes==modernBefore
791 && network.lightningRequests.size()==sentBefore,
792 "legacy-server lightning escaped simulator suppression");
793 playerships[0].isSimulator=false;
795 Check(view.legacyStrikes==legacyBefore && view.strikes==modernBefore,
796 "leaving simulator replayed a discarded strike");
797 receiver.Receive(LightningPacket(seamCenter.u,seamCenter.v));
798 Check(view.legacyStrikes==legacyBefore && view.strikes==modernBefore,
799 "simulator exit restored retired lightning fallback");
800}
801
802static void CheckWeatherCommands(Viewscreen& view,Receiver& receiver,Network& network)
803{
804 auto& weather=view.weather;
805 playerships[0].isSimulator=false;
806 playerships[0].mslKm=.4f;
807 playerships[0].position=view.CalculatePlanar(3057,1)*(radiusC+.4f);
808 const auto cube=view.CalculateCube(playerships[0].position);
809 const auto center=view.CalculateCGC(playerships[0].position,cube);
810 LoadTerrain(view,center,cube);
812 auto dry=StormGrid(center,cube,300,0,false);
813 for(int i=0;i<4096;++i) dry[17+i*12]=20;
814 receiver.Receive(dry);weather.UpdatePlotWeatherConditions();
815 Put16(dry.data()+7,1); // current request token
816 receiver.Receive(dry);
817 Check(!weather.weatherPending,"dry BOLT fixture failed synchronization");
819 Check(weather.GetRainPrecip()==16 && weather.GetPrecip()==2 && weather.smoothPrecip==2,
820 "RAIN changed live weather or contaminated its smoother");
821 network.lightningRequests.clear();
822 for(int i=0;i<6000;++i) weather.UpdateLightningSpawns(.1f);
823 Check(network.lightningRequests.empty(),"RAIN manufactured a regional storm");
824 RiseMath::Vector3 up,right,ahead;
825 RiseMath::Vec3Normalize(&up,&playerships[0].position);
826 const RiseMath::Vector3 axis(0,0,1);
827 RiseMath::Vec3Cross(&right,&up,&axis);RiseMath::Vec3Normalize(&right,&right);
828 RiseMath::Vec3Cross(&ahead,&up,&right);
829 for(float yaw:{0.f,1.5f,3.f,4.5f})for(float pitch:{-.5f,0.f,.5f})
830 {
831 const auto bearing=right*cosf(yaw)+ahead*sinf(yaw);
832 const auto look=bearing*cosf(pitch)+up*sinf(pitch);
833 const auto cameraEye=-right*.03f-up*.02f,at=cameraEye-look,renderUp=-up;
834 RiseMath::MatrixLookAtRH(&view.matrixLook,&cameraEye,&at,&renderUp);
835 const int before=view.strikes;
836 Check(weather.TriggerForwardLightning() && view.strikes==before+1 && view.testStrike,
837 "BOLT failed to trigger its local diagnostic in dry weather at the cube seam");
838 Check(view.strikeChains>=0 && view.strikeChains<=LightningTiming::MaxChainedBolts,
839 "BOLT requested an unsupported chain count");
840 auto delta=view.strikeGround-(playerships[0].position-cameraEye);
841 delta-=up*RiseMath::Vec3Dot(&delta,&up);
842 Check(Near(RiseMath::Vec3Length(&delta),1,.002f) && RiseMath::Vec3Dot(&delta,&bearing)>.998f,
843 "BOLT was not 1 km along the camera bearing");
844 RiseMath::Vector3 projected;const auto relative=playerships[0].position-view.strikeGround;
845 RiseMath::Vec3TransformCoord(&projected,&relative,&view.matrixLook);
846 Check(std::abs(projected.x)<.002f && projected.z<0,"BOLT was behind/beside the active camera");
847 Check(Near(RiseMath::Vec3Length(&view.strikeGround),radiusC+.2f,.002f)
848 && GridLightning::Distance(view.strikeGround,view.strikeCloud)>.8f,"BOLT did not attach to terrain/cloud base");
849 Check(network.lightningRequests.empty(),"BOLT broadcast a random replacement/echo");
850 weather.gridLightning.Observe(view.strikeGround);
851 }
854 && Near(GridLightning::Distance(view.strikeGround,view.strikeCloud),.45f,.002f),"BOLT ignored the cloud ceiling override");
857 weather.smoothPrecip=7; // live weather continues smoothing during the test
858 Check(weather.GetRainPrecip()==16 && weather.GetPrecip()==7,"RAIN leaked into live weather");
860 Check(weather.GetRainPrecip()==7 && weather.precip==9,
861 "RAIN reset did not resume current live rain");
864 Check(weather.smoothPrecip==4 && weather.GetPrecip()==4 && weather.GetRainPrecip()==16,
865 "live weather initialization inherited RAIN");
866 const int beforeReset=view.strikes;
867 const auto historyBefore=view.cloudVolume.historyResets;
869 Check(view.cloudVolume.historyResets==historyBefore+1,"reposition retained cloud image history");
870 Check(!weather.TriggerForwardLightning() && view.strikes==beforeReset,"BOLT used stale weather after W0");
872 // Reconnect may replace the weather snapshot before a frame observes an
873 // empty map. The production connection reset must explicitly cancel a
874 // previously armed orbital diagnostic, independently of weather upload.
875 Check(view.cloudVolume.SetLightningDiagnostic(true) && view.cloudVolume.lightningDiagnostic,
876 "connection-reset fixture did not arm its orbital lightning diagnostic");
878 Check(view.cloudVolume.historyResets==historyBefore+2,"connection reset retained cloud image history");
879 Check(!view.cloudVolume.lightningDiagnostic,"connection reset retained orbital lightning diagnostic");
881 Check(!weather.TriggerForwardLightning() && view.strikes==beforeReset,"BOLT used a retired fallback without weather");
882 playerships[0].isSimulator=true;
883 Check(!weather.TriggerForwardLightning(),"simulator accepted a diagnostic bolt");
884 playerships[0].isSimulator=false;
885 view.ptrGrid->ClearGrid();
886 Check(!weather.TriggerForwardLightning(),"BOLT manufactured missing terrain");
887}
888
889static void CheckAltitudeLifecycle(Viewscreen& view,Receiver& receiver,Network& network)
890{
891 auto& weather=view.weather;
893 playerships[0].position=view.CalculatePlanar(500,1100)*(radiusC+.4f);
894 const auto cube=view.CalculateCube(playerships[0].position);
895 const auto center=view.CalculateCGC(playerships[0].position,cube);
896 LoadTerrain(view,center,cube);
898 receiver.Receive(StormGrid(center,cube,400,0,false));weather.UpdatePlotWeatherConditions();
899 receiver.Receive(StormGrid(center,cube,401,1,false));
900 Check(!weather.weatherPending && weather.GetPrecip()==16,"altitude fixture not initialized");
901 Check(weather.RefreshLightningGrid() && weather.gridLightning.CellCount()>0,"altitude fixture has no lightning cells");
902 const int resets=weather.resets;
905 const auto requests=network.weatherRequests.size();
906 weather.RequestPlotWeather(false); // unsent repair must not escape during ascent
907 const auto preAscentToken=weather.weatherRequestToken;
908 g_bAboveClouds=true;playerships[0].mslKm=10.1f;
912 "ascent failed to discard weather/lightning/unsent request state");
913 for(int i=0;i<5;++i) {
914 receiver.Receive(StormGrid(center,cube,402+i,preAscentToken,false));
916 }
917 receiver.Receive(Packet(false,VECTOR2SHORT(center.u+1,center.v),cube,408,407,preAscentToken,3));
918 Check(network.weatherRequests.size()==requests && weather.resets==resets && !weather.plotWeather.Ready()
919 && weather.precip==16 && Near(weather.visibility,15.f) && weather.GetPrecip()==2,
920 "above-cloud grid traffic changed weather or produced a request");
922 "volume atmosphere retained ground fog above cloud tops");
923 receiver.Receive(Weather1Packet(252));
924 Check(weather.winddir==1.2f && weather.temperature==15.f && weather.GetTurbulence()==0.f
925 && weather.windspeed==.02f && weather.precip==16,"above-cloud Weather1 fields or reserved byte regressed");
927 Check(weather.GetRainPrecip()==16 && weather.GetPrecip()==2,"RAIN override leaked into above-cloud weather");
929 playerships[0].mslKm=9.7f;view.volumeEnabled=false;
931 "legacy renderer lost above-cloud clear-air visibility");
933 Check(weather.GetVisibilityKm()==.5f,"above-cloud gate masked explicit VIS test");
934 weather.visibilityOverrideKm=-1;view.volumeEnabled=true;
936 Check(network.weatherRequests.size()==requests && !weather.RefreshLightningGrid(),
937 "9.5-to-10 km hysteresis band resumed local grid/lightning too early");
938
939 // A queued network packet may arrive before the first below-cloud frame.
940 g_bAboveClouds=false;playerships[0].mslKm=9.49f;
941 receiver.Receive(StormGrid(center,cube,410,preAscentToken,false));
942 const auto descentToken=weather.weatherRequestToken;
943 Check(descentToken==uint16_t(preAscentToken+1) && !weather.plotWeather.Ready()
944 && weather.weatherRequestQueued && !weather.weatherPending,"descent did not reject stale token before application");
946 Check(network.weatherRequests.size()==requests+1 && network.weatherRequests.back().f_x==descentToken,
947 "descent did not send exactly one causal full-grid request");
948 auto fresh=StormGrid(center,cube,411,descentToken,false);
949 for(int i=0;i<4096;++i) {
950 auto* cell=fresh.data()+17+i*12;cell[0]=80;
951 Put16(cell+2,3000);Put16(cell+8,5000);
952 }
953 LoadTerrain(view,center,cube,1000);
954 receiver.Receive(fresh);
957 "fresh descent full did not replace local targets");
958 Check(weather.resets==resets && weather.smoothPrecip==14 && weather.smoothVisibility==12
960 "ordinary descent snapped local smoothers");
961 for(int i=0;i<5;++i) weather.UpdatePlotWeatherConditions();
962 Check(network.weatherRequests.size()==requests+1,"descent repeatedly requested full grids");
963
964 // Startup while aloft must defer its initial reset, without capability discovery.
966 playerships[0].isSimulator=true;
968 const auto startupRequests=network.weatherRequests.size();
969 receiver.Receive(StormGrid(center,cube,500,0,false));weather.UpdatePlotWeatherConditions();
971 && network.weatherRequests.size()==startupRequests && weather.weatherPending,
972 "above-cloud simulator startup sent/applied local grid");
974 Check(network.weatherRequests.size()==startupRequests+1 && weather.weatherRequestToken==2,
975 "first descent failed to request its initial full");
976 receiver.Receive(StormGrid(center,cube,501,0,false));
977 Check(weather.weatherPending && !weather.plotWeather.Ready(),"initial descent consumed unsolicited full");
978 receiver.Receive(StormGrid(center,cube,502,2,false));
979 Check(!weather.weatherPending && weather.resets==resets+1,"initial descent lost its one-time reset");
981}
982
983
984template<class T> static void ReceiveTerrainPacket(Receiver& receiver, const T& packet)
985{
986 std::vector<unsigned char> wire(1+sizeof packet);wire[0]=ID_USER_PACKET_ENUM;
987 memcpy(wire.data()+1,&packet,sizeof packet);receiver.Receive(wire);
988}
989static void CheckTerrainAlignment(Viewscreen& view,grid& terrain,Receiver& receiver)
990{
991 const VECTOR2SHORT centers[6]{{2037,1019},{3057,1},{-1019,1},{5095,1},{2037,-1019},{2037,3057}};
992 for(char face=0;face<6;++face) {
993 const auto center=centers[face];
994 const VECTOR2SHORT shifted(center.u+5,center.v-3);
995 LoadTerrain(view,shifted,face,0,true);
996 for(int q=0;q<64;++q)for(int r=0;r<64;++r) {
997 const short u=center.u+q-31,v=center.v+r-31;
998 char rotation;const auto canonical=view.CalculateWrap(u,v,face,&rotation);
999 const bool overlap=q>=5 && r<61 && canonical.u!=30000 && canonical.v!=30000;
1000 short height=-12345;
1001 const bool found=terrain.TryElevation(face,u,v,height);
1002 Check(found==overlap,"terrain/weather centers or cube wrapping misaligned elevation");
1003 if(found) Check(height==100+u*2+v*3,"terrain elevation came from matching array indices");
1004 else Check(height==-12345,"missing terrain published a replacement elevation");
1005 }
1006 }
1007 // EP's rotated north edge is NP's right edge. The old face remains usable
1008 // where it really overlaps, without interpreting its indices on the new face.
1009 LoadTerrain(view,{3057,1},1,650);
1010 short height=0;
1011 Check(terrain.TryElevation(4,2037,-1019,height) && height==650,
1012 "cross-face overlap could not resolve a wrapped terrain control point");
1013 Check(!terrain.TryElevation(4,1019,-1019,height),"unrelated old face supplied elevation");
1014
1015 const VECTOR2SHORT center(500,1100), weatherCenter(505,1100);
1016 g_bAboveClouds=false;terrain.g_bAboveCloudsOld=false;playerships[0].mslKm=.4f;
1017 playerships[0].position=view.CalculatePlanar(center.u,center.v)*(radiusC+.4f);
1018 LoadTerrain(view,center,0,200);
1019 auto& weather=view.weather;auto& rain=view.cloudVolume.renderer;
1021 receiver.Receive(StormGrid(weatherCenter,0,1000,0,false));weather.UpdatePlotWeatherConditions();
1022 receiver.Receive(StormGrid(weatherCenter,0,1001,1,false));
1023 Check(!weather.weatherPending,"aligned fixture failed to initialize");
1025 const auto revision=weather.plotWeather.Header().revision;
1026 const auto rainIndex=[&](int u,int v){return (v-weatherCenter.v+31)*64+u-weatherCenter.u+31;};
1027 const auto uploads=rain.uploads;const auto terrainRevision=terrain.ElevationRevision();
1028 SRenderPoint point{};point.tcp=center;point.gridarray.pri_landform=2;point.gridarray.elevation=900;
1029 ReceiveTerrainPacket(receiver,point);
1031 const auto* strike=weather.gridLightning.Find(center.u,center.v);
1032 Check(terrain.ElevationRevision()!=terrainRevision && rain.uploads==uploads+1
1033 && weather.plotWeather.Header().revision==revision && strike
1034 && Near(RiseMath::Vec3Length(&strike->ground),radiusC+.9f,.002f)
1035 && Near(rain.latest.cells[rainIndex(center.u,center.v)].x,.9f)
1036 && Near(weather.cloudSurfaceTargetKm,.9f,.002f),
1037 "terrain-only point failed to refresh local weather, rain or lightning");
1038
1039 // Fractional observers require all four terrain controls; one missing
1040 // contributor must hold the entire previous target rather than inject zero.
1041 auto a=view.CalculatePlanar(500,1100),b=view.CalculatePlanar(501,1100);
1042 auto c=view.CalculatePlanar(500,1101),d=view.CalculatePlanar(501,1101);
1043 a=a/fabsf(a.y);b=b/fabsf(b.y);c=c/fabsf(c.y);d=d/fabsf(d.y);
1044 playerships[0].position=(a*.1875f+b*.0625f+c*.5625f+d*.1875f)*radiusC;
1045 double u,v;Check(PlotWeather::Coordinates(playerships[0].position,0,u,v),"fractional terrain observer");
1046 float interpolated;
1047 Check(terrain.InterpolateElevation(0,u,v,interpolated)
1048 && Near(interpolated,331.25f,.15f),"terrain bilinear interpolation lost fractional continuity");
1050 point.tcp={501,1101};point.gridarray.pri_landform=255;ReceiveTerrainPacket(receiver,point);
1052 Check(weather.cloudSurfaceTargetKm==heldSurface && !rain.active
1053 && !weather.gridLightning.Find(501,1101),"missing terrain corner injected sea level or retained a strike");
1054 point.gridarray.pri_landform=2;point.gridarray.elevation=-200;ReceiveTerrainPacket(receiver,point);
1055 Check(terrain.TryElevation(0,501,1101,height) && height==-200,"valid negative terrain elevation was rejected");
1056 point.gridarray.elevation=0;ReceiveTerrainPacket(receiver,point);
1057 Check(terrain.TryElevation(0,501,1101,height) && height==0,"valid sea-level terrain was mistaken for missing data");
1058
1059 // A real one-cell terrain shift clears the new edge before its row arrives.
1060 // Weather remains at its independent center and revision throughout.
1061 playerships[0].position=view.CalculatePlanar(501,1100)*.75f+view.CalculatePlanar(502,1101)*.25f;
1063 terrain.Process();
1064 Check(terrain.dataPending==1 && !terrain.wholeGridPending && terrain.oldtcp.u==501,
1065 "terrain strip fixture did not shift east");
1066 Check(!terrain.TryElevation(0,533,1100,height),"cleared strip retained its former location's elevation");
1068 Check(rain.active && rain.latest.cells[rainIndex(533,1100)].w==2
1069 && !weather.gridLightning.Find(533,1100),"unreceived strip rendered a rain/lightning column");
1070 SRenderRow row{};row.tcp=terrain.tcp;row.side=3;
1071 for(auto& cell:row.gridarray){cell.pri_landform=2;cell.elevation=777;}
1072 const auto beforeRow=rain.uploads;ReceiveTerrainPacket(receiver,row);
1074 strike=weather.gridLightning.Find(533,1100);
1075 Check(rain.uploads==beforeRow+1 && strike && Near(rain.latest.cells[rainIndex(533,1100)].x,.777f)
1076 && Near(RiseMath::Vec3Length(&strike->ground),radiusC+.777f,.002f)
1077 && weather.plotWeather.Header().revision==revision,"terrain-only strip did not refresh weather consumers");
1078 Check(terrain.TryElevation(0,500,1100,height) && height==900,"terrain shift changed retained plot elevation");
1079
1080 // A full terrain replacement at unchanged weather revision also rebuilds.
1081 LoadTerrain(view,{501,1100},0,1200);
1082 const auto beforeFull=rain.uploads;
1084 strike=weather.gridLightning.Find(500,1100);
1085 Check(rain.uploads==beforeFull+1 && Near(weather.cloudSurfaceTargetKm,1.2f) && strike
1086 && Near(RiseMath::Vec3Length(&strike->ground),radiusC+1.2f,.002f),
1087 "terrain-only full retained old weather heights");
1088
1089 // Weather first, no terrain or wrong-location terrain: hold smoothers and
1090 // pending reset until the same weather generation acquires valid coverage.
1092 receiver.Receive(StormGrid(weatherCenter,0,1002,weather.weatherRequestToken,false));
1093 const auto resets=weather.resets;const auto held=weather.cloudSurfaceTargetKm;
1095 Check(weather.weatherPending && !rain.active && weather.cloudSurfaceTargetKm==held,
1096 "weather first used a fabricated terrain surface");
1097 LoadTerrain(view,{1500,1500},0,2500);weather.UpdatePlotWeatherConditions();
1098 Check(weather.weatherPending && weather.resets==resets && weather.cloudSurfaceTargetKm==held,
1099 "wrong-location terrain consumed weather reset");
1100 LoadTerrain(view,{501,1100},0,800);weather.UpdatePlotWeatherConditions();
1101 Check(!weather.weatherPending && weather.resets==resets+1 && Near(weather.cloudSurfaceTargetKm,.8f),
1102 "unchanged weather did not initialize after matching terrain arrived");
1103
1104 // Continuous slopes survive grid shifts, exact edges, and all four corners.
1105 LoadTerrain(view,{500,1100},0,0,true);
1106 float before,after;
1107 for(int axis=0;axis<2;++axis) {
1108 const double x=axis?500.25:500.999999,y=axis?1100.999999:1100.75;
1109 Check(terrain.InterpolateElevation(0,x,y,before)
1110 && terrain.InterpolateElevation(0,x+(axis?0:.000002),y+(axis?.000002:0),after)
1111 && Near(before,after),"terrain-driven local base jumped across a plot boundary");
1112 }
1113 Check(terrain.InterpolateElevation(0,500.25,1100.75,before),"slope before terrain recenter");
1114 LoadTerrain(view,{505,1097},0,0,true);
1115 Check(terrain.InterpolateElevation(0,500.25,1100.75,after) && before==after,
1116 "terrain recenter changed the same geographical surface");
1117 Check(terrain.InterpolateElevation(0,537,1129,after)
1118 && !terrain.InterpolateElevation(0,537.01,1129,after),"terrain exact-edge validity changed");
1119 weather.ResetPlotWeatherConnection();rain.uploads=0;
1120}
1121
1122static void CheckRadarSurface(Viewscreen& view,grid& terrain)
1123{
1124 LoadTerrain(view,{500,1100},0,175);
1125 float height=0,water=0;
1126 Check(terrain.InterpolateRadarSurface(0,500.5,1100.5,height,water) && height==175 && water==0,
1127 "radar surface preserves elevation and land classification");
1128 gridarray[31][31].pri_landform=1;terrain.ElevationChanged();
1129 Check(terrain.InterpolateRadarSurface(0,500.5,1100.5,height,water) && water==.25f,
1130 "radar coastline interpolates supplied water vertices above MSL");
1131 gridarray[31][31].pri_landform=2;gridarray[31][31].sec_landform=1;
1132 gridarray[31][31].pri_transition=0;terrain.ElevationChanged();
1133 Check(terrain.InterpolateRadarSurface(0,500,1100,height,water) && water==0,
1134 "inactive secondary water landform does not turn land into water");
1135 gridarray[31][31].pri_transition=1;terrain.ElevationChanged();
1136 Check(terrain.InterpolateRadarSurface(0,500,1100,height,water) && water==1,
1137 "active coastal landform refreshes cached radar material");
1138 gridarray[32][32].elevationAvailable=false;terrain.ElevationChanged();
1139 Check(!terrain.InterpolateRadarSurface(0,500.5,1100.5,height,water),
1140 "missing terrain corner cannot be filled with invented water or land");
1141}
1142
1143static void BenchmarkTerrainJoin(Viewscreen& view,grid& terrain,Receiver& receiver)
1144{
1145 using Clock=std::chrono::steady_clock;
1146 const VECTOR2SHORT center(500,1100);
1147 playerships[0].position=view.CalculatePlanar(center.u,center.v)*(radiusC+.4f);
1148 g_bAboveClouds=false;LoadTerrain(view,center,0,200);
1149 auto& weather=view.weather;
1151 receiver.Receive(StormGrid({505,1097},0,1000,0,false));weather.UpdatePlotWeatherConditions();
1152 receiver.Receive(StormGrid({505,1097},0,1001,1,false));
1154 const auto measure=[](int count,auto run) {
1155 const auto start=Clock::now();
1156 for(int i=0;i<count;++i)run();
1157 return std::chrono::duration<double,std::milli>(Clock::now()-start).count()/count;
1158 };
1159 short surface=0;
1160 const auto rebuild=measure(500,[&]{
1161 terrain.ElevationChanged();terrain.TryElevation(0,500,1100,surface);
1162 });
1163 const auto rain=measure(500,[&]{weather.rainTerrainRevision=0;weather.PrepareRainCurtains(true);});
1164 const auto lightning=measure(500,[&]{weather.lightningTerrainRevision=0;weather.RefreshLightningGrid();});
1165 const auto cached=measure(20000,[&]{
1167 });
1168 Check(surface==200,"benchmark terrain lookup");
1169 std::cout<<"CPU-only ms/operation: terrain index rebuild="<<rebuild
1170 <<" full 4096-cell rain join="<<rain<<" lightning join="<<lightning
1171 <<" cached local/rain/lightning frame="<<cached
1172 <<"; offline logger and rendering sink, no GPU upload/draw timing\n";
1173}
1174
1175static void CheckSnow(Viewscreen& view,grid& terrain)
1176{
1177 auto& weather=view.weather;
1179 const VECTOR2SHORT centers[6]{{2037,1019},{3057,1},{-1019,1},{5095,1},{2037,-1019},{2037,3057}};
1180 uint32_t revision=10000;
1181 for(char face=0;face<6;++face) {
1183 const auto center=centers[face];
1184 LoadTerrain(view,{short(center.u+5),short(center.v-3)},face,500);
1185 const auto base=TerrainSnapshot();
1186 auto packet=Packet(true,center,face,++revision,0,7);
1187 Check(Accept(weather.plotWeather,packet)==PlotWeather::Result::Full,"snow full rejected");
1189 size_t overlap=0;
1190 for(int q=5;q<64;++q)for(int r=0;r<61;++r) {
1191 char rotation;
1192 const auto canonical=view.CalculateWrap(center.u+q-31,center.v+r-31,face,&rotation);
1193 if(canonical.u==30000 || canonical.v==30000)continue;
1194 const auto* surface=weather.terrainSnow.At(canonical);
1195 const int index=q*64+r;
1196 const int age=(index/3)%256;
1197 Check(surface && Near(surface->depthMm,float(index%256))
1198 && Near(surface->ageHours,float(age))
1199 && Near(surface->waterMm,((index/5)%256)*.1f),"canonical snow/water alignment failed");
1200 ++overlap;
1201 }
1202 Check(overlap>3000,"snow seam fixture lacks overlap");
1203 const auto p=gridarray[31][31].tcp;
1204 const auto before=*weather.terrainSnow.At(p);
1205 auto changed=Packet(true,{short(center.u+1),center.v},face,++revision,0,7);
1206 for(int i=0;i<4096;++i){auto* cell=changed.data()+17+i*12;cell[1]=123;cell[4]=40;cell[5]=123;cell[6]=240;}
1207 Check(Accept(weather.plotWeather,changed)==PlotWeather::Result::Full,"snow recenter rejected");
1209 const auto after=*weather.terrainSnow.At(p);
1210 Check(Near(after.depthMm,before.depthMm) && Near(after.waterMm,before.waterMm),
1211 "weather recenter snapped retained snow");
1213 const auto smoothed=*weather.terrainSnow.At(p);
1214 const float f=1-expf(-1);
1215 Check(Near(smoothed.depthMm,before.depthMm+(40-before.depthMm)*f)
1216 && Near(smoothed.waterMm,before.waterMm+(12.3f-before.waterMm)*f),"three-second surface smoothing incorrect");
1218 Check(Near(weather.terrainSnow.At(p)->waterMm,12.3f),"snow cell lost coexisting surface water");
1219 const auto color1=weather.TerrainSnowTint(31,31),color2=weather.TerrainSnowTint(31,31);
1220 Check(color1==color2 && Near(color1.w,1) && Near(color1.x,200.f/255),"aged full snow tint");
1221 Check(memcmp(base.data(),gridarray,sizeof(gridarray))==0,"snow cumulatively modified terrain storage");
1222 Check(weather.terrainSnow.Size()<=8192,"surface cache unbounded");
1224 Check(weather.plotWeather.Interpolate(face,center.u+.25,center.v+.75,7,local)
1225 && Near(local.snowDepthMm,40) && Near(local.snowAgeHours,240) && Near(local.surfaceWaterMm,12.3f),
1226 "surface properties missing from weather interpolation");
1227 // Missing data holds previous surface state on loaded terrain.
1228 std::fill(changed.begin()+17,changed.end(),0);Put32(changed.data()+9,++revision);
1229 Check(Accept(weather.plotWeather,changed)==PlotWeather::Result::Full,"missing snow fixture");
1231 Check(Near(weather.terrainSnow.At(p)->depthMm,40),"missing cell erased known terrain snow");
1232 // Snow/water -> water only -> fresh snow with water -> dry.
1233 const int transitionDepths[3]{0,40,0}, transitionWater[3]{123,255,0}, transitionAges[3]{0,0,0};
1234 for(int step=0;step<3;++step) {
1235 changed=Packet(true,{short(center.u+1),center.v},face,++revision,0,7);
1236 const int depth=transitionDepths[step], water=transitionWater[step], age=transitionAges[step];
1237 for(int i=0;i<4096;++i){auto* cell=changed.data()+17+i*12;cell[4]=static_cast<unsigned char>(depth);cell[5]=static_cast<unsigned char>(water);cell[6]=static_cast<unsigned char>(age);}
1238 Check(Accept(weather.plotWeather,changed)==PlotWeather::Result::Full,"surface transition full rejected");
1239 const auto previous=*weather.terrainSnow.At(p);
1241 Check(Near(weather.terrainSnow.At(p)->depthMm,previous.depthMm)
1242 && Near(weather.terrainSnow.At(p)->waterMm,previous.waterMm),"surface transition snapped smoothing");
1244 const auto* transitioned=weather.terrainSnow.At(p);
1245 Check(Near(transitioned->depthMm,float(depth)) && Near(transitioned->ageHours,float(age))
1246 && Near(transitioned->waterMm,water*.1f),"surface transition retained the inactive quantity");
1247 }
1248 }
1249 const TerrainSnow::Surface dry{},fresh{40,0,0},aged{40,240,0},partial{20,0,0};
1250 Check(Near(TerrainSnow::Tint(dry,45,0).w,0) && Near(TerrainSnow::Tint(dry,55,0).w,.5f)
1251 && Near(TerrainSnow::Tint(dry,-65,0).w,1) && Near(TerrainSnow::Tint(dry,65,20).w,0),"polar visual coverage");
1252 Check(Near(TerrainSnow::Tint(fresh,0,0).x,232.f/255) && Near(TerrainSnow::Tint(aged,0,0).z,215.f/255)
1253 && Near(TerrainSnow::Tint(partial,0,0).w,.5f),"physical snow color or coverage");
1254 Check(dry.depthMm==0 && dry.waterMm==0,"polar policy changed physical amounts");
1256 Check(!weather.terrainSnow.Size() && weather.TerrainSnowTint(31,31)==RiseMath::Vector4(0,0,0,0),
1257 "legacy/reconnect snow lifecycle");
1258}
1259
1260#include "LightningThunderTests.h"
1261#include "PrecipitationAudioTests.h"
1262#include "LocalCloudBaseLifecycleTests.h"
1263
1264#include "TurbulenceGridTests.h"
1265#include "SpatialFogWeatherTests.h"
1266
1267int main(int argc,char** argv)
1268{
1269 try {
1270 CheckStore();
1271 CheckSpatialFogTransport();
1272 Logger logger; FixtureBus bus; Network network; Game game{&bus,&network};
1273 Viewscreen view{&logger,&game}; grid terrain{&view}; view.ptrGrid=&terrain;
1274 view.weather.viewscreen=&view; view.weather.logger=&logger;
1275 Receiver receiver; receiver.owner.viewscreen=&view;
1276 if(argc==2 && !strcmp(argv[1],"--terrain-benchmark")) {BenchmarkTerrainJoin(view,terrain,receiver);return 0;}
1277 CheckInterpolation(); CheckSurfaceWind(); CheckCoordinates(view);
1278 CheckIntegration(view,terrain,receiver,network);
1279 CheckLightningIntegration(view,receiver,network);
1280 CheckWeatherCommands(view,receiver,network);
1281 LightningThunderTests(view);
1282 PrecipitationAudioTests();
1283 CheckAltitudeLifecycle(view,receiver,network);
1284 CheckTerrainAlignment(view,terrain,receiver);
1285 CheckRadarSurface(view,terrain);
1286 CheckSpatialFogLifecycle(view,terrain,receiver);
1287 CheckSnow(view,terrain);
1288 const int beforeCloudBase=checks;
1289 CheckLocalCloudBaseLifecycle(view,terrain);
1290 std::cout<<"PASS "<<checks-beforeCloudBase<<" local cloud-base lifecycle checks\n";
1291 const int beforeTurbulence=checks;
1292 CheckGridTurbulence(view,terrain,receiver,network);
1293 std::cout<<"PASS "<<checks-beforeTurbulence<<" vehicle turbulence grid checks\n";
1294 auto& weather=view.weather;auto& rain=view.cloudVolume.renderer;
1296 view.volumeEnabled=true;weather.visibilityOverrideKm=-1;
1297 playerships[0].position=view.CalculatePlanar(1019,1019)*(radiusC+.4f);
1298 LoadTerrain(view,{1024,1016},0,450); // intentionally different centers
1299 weather.weatherPending=false;
1300 const auto full=Packet(true,{1019,1019},0,1000,0,7);
1301 Check(Accept(weather.plotWeather,full)==PlotWeather::Result::Full,"rain fixture full grid");
1303 Check(weather.spatialFogRendering && rain.active && rain.uploads==1,"valid grid enables spatial fog");
1304 const auto& cell=rain.latest.cells[5*64+9];const int sample=9*64+5;
1305 Check(Near(cell.x,.45f) && Near(cell.y,(750+sample)*.001f)
1306 && Near(cell.z,(42160-sample)*.001f) && Near(cell.w,(20+sample%141)*.1f),
1307 "rain grid is transposed or has incorrect units/surface plus ceiling");
1309 Check(rain.uploads==1 && Near(rain.latest.cells[5*64+9].w,(20+sample%141)*.1f),
1310 "RAIN command changed spatial weather or unchanged grid uploaded again");
1312 Check(!rain.active && !weather.spatialFogRendering,"simulator entry retained spatial fog");
1313 Check(Accept(weather.plotWeather,Packet(true,{1019,1019},0,1001,0,7))==PlotWeather::Result::Full,
1314 "simulator weather update fixture");
1316 Check(!rain.active && rain.uploads==1,"valid weather grid reactivated simulator fog");
1318 Check(rain.active && weather.spatialFogRendering && rain.uploads==2,
1319 "simulator exit must republish current weather instead of retaining a GPU fog generation");
1321 Check(!weather.spatialFogRendering && !rain.active,"VIS must retain uniform diagnostic fog");
1323 Check(!rain.active,"enclosed/windowless view enabled spatial fog");
1325 Check(!rain.active && !weather.spatialFogRendering,"above-cloud state retained rain");
1327 Check(!rain.active,"stale generation enabled rain");
1329 Check(!rain.active,"unavailable grid enabled rain");
1331 Check(rain.active,"reconnect fixture active");
1333 Check(!rain.active && !weather.spatialFogRendering,"reconnect retained a GPU generation with reusable token/revision");
1335 std::cout<<"PASS "<<checks<<" independent weather grid/decoder/request/reset checks\n";
1336 return 0;
1337 } catch(const std::exception& error) { std::cerr<<"FAIL: "<<error.what()<<'\n'; return 1; }
1338}
float RandomFloat()
PacketOrdering
Definition ServerTypes.h:11
@ ORDERING_WEATHER
Definition ServerTypes.h:19
@ ORDERING_NONE
Definition ServerTypes.h:12
@ ORDERING_TERRAIN
Definition ServerTypes.h:14
#define MAX_SCAN
Rendering::CloudRenderer11 renderer
bool SetLightningDiagnostic(bool enabled)
void Observe(const Vector3 &ground)
void Seed(uint32_t seed)
const Cell * Find(short u, short v) const
size_t CellCount() const
void Log(const char *msg, Level level=Info, int errorCode=0)
Definition Logger.cpp:283
void AddToCallStack(const char *msg)
Definition Logger.cpp:355
Logger()
Definition Logger.cpp:392
~Logger()
Definition Logger.cpp:448
Level
Definition Logger.h:23
@ Info
Definition Logger.h:25
@ Error
Definition Logger.h:28
Result Accept(const unsigned char *p, size_t length, uint16_t expectedToken)
bool Interpolate(unsigned cube, double u, double v, uint16_t token, LocalSample &result) const
const SRenderWeather * At(unsigned cube, VECTOR2SHORT tcp, uint16_t token) const
const SPlotWeatherHeader & Header() const
bool HasRainGrid(uint64_t revision, int cube, int u, int v) const
void SetRainGrid(const RainGrid *grid)
const Surface * At(VECTOR2SHORT p) const
Definition TerrainSnow.h:52
size_t Size() const
Definition TerrainSnow.h:27
float turbLow
Definition Viewscreen.h:97
char msg[199]
Definition Viewscreen.h:50
bool advanceframe
Definition Viewscreen.h:375
CloudVolumeRenderer cloudVolume
Definition Viewscreen.h:396
bool VolumeCloudsEnabled() const
Definition Viewscreen.h:404
GameClass * gameclass
Definition Viewscreen.h:439
RiseMath::Vector3 compassnorth
Definition Viewscreen.h:107
RiseMath::Matrix matrixLook
Definition Viewscreen.h:346
std::unique_ptr< weather > ptrWeather
Definition Viewscreen.h:434
RiseMath::Vector3 posnorml
Definition Viewscreen.h:383
std::unique_ptr< grid > ptrGrid
Definition Viewscreen.h:426
bool IsRepositionSettling() const
Definition Viewscreen.h:152
float turbEnergy
Definition Viewscreen.h:98
VECTOR2SHORT CalculateCGC(RiseMath::Vector3 position, char cube) const
short BCLoffsetv
Definition Viewscreen.h:419
VECTOR2SHORT CalculateWrap(short u, short v, char cube, char *rotate) const
short BCLoffsetu
Definition Viewscreen.h:419
LOCALGRID2 CalculateSRV(short t, short s, VECTOR2SHORT tcp, char cube, SRenderVertex sourcedata)
RiseMath::Vector3 CalculatePlanar(short u, short v)
void TriggerBCLLightningAt(const RiseMath::Vector3 &ground, const RiseMath::Vector3 &cloud, float distanceKm, int seed, int chainedBolts, bool testStrike=false) const
float onlinePlayersInVicinity
Definition Viewscreen.h:100
char CalculateCube(RiseMath::Vector3 position) const
Logger * logger
Definition Viewscreen.h:440
void TriggerBCLLightning(int u, int v, float distanceKm, int seed, int chainedBolts) const
Definition grid.h:14
bool geometryReady
Definition grid.h:37
void ClearGrid()
Definition grid.cpp:78
char requestedCube
Definition grid.h:20
VECTOR2SHORT requestedTcp
Definition grid.h:21
uint64_t ElevationRevision() const
Definition grid.h:54
bool InterpolateElevation(char face, double u, double v, float &meters) const
Definition grid.cpp:167
grid(Viewscreen *ptrGame)
Definition grid.cpp:5
std::unordered_map< uint32_t, SurfacePoint > elevationByPlot
Definition grid.h:26
void ElevationChanged() const
Definition grid.h:55
bool g_bAboveCloudsOld
Definition grid.h:19
bool wholeGridPending
Definition grid.h:40
void ReceiveWholeGrid(const SRenderGrid &datapacket)
Definition grid.cpp:219
char cube
Definition grid.h:45
bool dataReady
Definition grid.h:36
void CalculateInsideArray(short t, short s) const
Definition grid.cpp:1230
void CalculateCubeAndTcp()
Definition grid.cpp:101
void Process()
Definition grid.cpp:310
uint64_t elevationRevision
Definition grid.h:24
void Trace(const char *msg, Logger::Level severity=Logger::Level::Info) const
Definition grid.cpp:37
bool TryElevation(char face, short u, short v, short &meters) const
Definition grid.cpp:132
bool TryRadarSurface(char face, short u, short v, short &meters, bool &water) const
Definition grid.cpp:138
void RequestWholeGrid()
Definition grid.cpp:279
void RemoveBuildZone(short ordinal) const
Definition grid.cpp:13
char oldcube
Definition grid.h:17
void PrepareForReposition()
Definition grid.cpp:271
bool wholeGridReceived
Definition grid.h:22
VECTOR2SHORT oldtcp
Definition grid.h:18
bool patchGeometry
Definition grid.h:38
Viewscreen * viewscreen
Definition grid.h:15
VECTOR2SHORT tcp
Definition grid.h:44
bool resetWeatherOnNextGrid
Definition grid.h:41
bool InterpolateRadarSurface(char face, double u, double v, float &meters, float &waterFraction) const
Definition grid.cpp:173
char dataPending
Definition grid.h:39
uint64_t elevationIndexRevision
Definition grid.h:24
float cloudCeilingOverrideKm
Definition weather.h:75
float GetPrecip() const
Definition weather.cpp:1365
void UpdateLightningSpawns(float elapsed)
Definition weather.cpp:1225
float smoothVisibility
Definition weather.h:64
void ReceiveGridLightning(short u, short v, int seed, int chainedBolts)
Definition weather.cpp:1214
uint64_t lightningTerrainRevision
Definition weather.h:104
uint32_t lightningWeatherRevision
Definition weather.h:103
float cloudSurfaceTargetKm
Definition weather.h:77
float GetTurbulence() const
Definition weather.cpp:1436
bool RefreshLightningGrid()
Definition weather.cpp:1120
float cloudCeilingSmoothAglKm
Definition weather.h:74
float GetRainPrecip() const
Definition weather.cpp:1360
void UpdateTerrainSnow(float elapsed)
Definition weather.cpp:1296
void SetPrecip(float prmPrecip)
Definition weather.cpp:893
float smoothPrecip
Definition weather.h:60
RiseMath::Vector4 TerrainSnowTint(int u, int v) const
Definition weather.cpp:1324
float temperature
Definition weather.h:70
float winddir
Definition weather.h:67
void RequestPlotWeather(bool reset)
Definition weather.cpp:1053
TerrainSnow::Store terrainSnow
Definition weather.h:97
bool weatherPending
Definition weather.h:82
void QueuePlotWeatherReset()
Definition weather.cpp:1060
GridLightning::System gridLightning
Definition weather.h:102
float windspeed
Definition weather.h:55
float visibility
Definition weather.h:63
void PrepareRainCurtains(bool exteriorView)
Definition weather.cpp:1375
float precipOverride
Definition weather.h:61
bool TriggerForwardLightning()
Definition weather.cpp:1161
bool plotWeatherSuspended
Definition weather.h:83
uint16_t weatherRequestToken
Definition weather.h:85
float cloudCeilingTargetKm
Definition weather.h:73
bool weatherRequestQueued
Definition weather.h:82
uint32_t snowWeatherRevision
Definition weather.h:98
float visibilityOverrideKm
Definition weather.h:65
float cloudSurfaceSmoothKm
Definition weather.h:78
void SetPrecipOverride(float value)
Definition weather.cpp:905
float precip
Definition weather.h:59
void ResetPlotWeatherConnection()
Definition weather.cpp:1008
float GetVisibilityKm() const
Definition weather.cpp:1411
void UpdatePlotWeatherConditions()
Definition weather.cpp:1085
bool spatialFogRendering
Definition weather.h:84
uint64_t rainTerrainRevision
Definition weather.h:104
PlotWeather::Store plotWeather
Definition weather.h:86
s_network_objects playerships[MAX_SCAN]
Definition globals.cpp:112
bool visiblegrid[63][63]
Definition globals.cpp:101
RiseMath::Vector3 insidearray[63][63][3]
Definition globals.cpp:102
bool g_bAboveClouds
Definition globals.cpp:16
LOCALGRID2 gridarray[64][64]
Definition globals.cpp:100
#define radiusC
Definition globals.h:87
constexpr float ClearVisibilityKm
std::shared_ptr< const Map > MapPtr
float Distance(const Vector3 &a, const Vector3 &b)
constexpr int MaxChainedBolts
std::wstring Clock(double seconds)
bool ParseHeader(const unsigned char *p, size_t length, SPlotWeatherHeader &result)
SRenderWeather Sample(const unsigned char *p)
bool Coordinates(const RiseMath::Vector3 &position, unsigned cube, double &u, double &v)
bool Near(const Body &b, const Triangle &t, double extra)
Definition RigidProp.h:141
auto ToRadian(T value)
Definition ClientMath.h:13
float Vec3Length(const Vector3 *a)
Definition ClientMath.h:95
Vector3 * Vec3Cross(Vector3 *out, const Vector3 *a, const Vector3 *b)
Definition ClientMath.h:105
Matrix * MatrixLookAtRH(Matrix *out, const Vector3 *eye, const Vector3 *at, const Vector3 *up)
Definition ClientMath.h:141
Vector3 * Vec3TransformCoord(Vector3 *out, const Vector3 *a, const Matrix *m)
Definition ClientMath.h:109
float Vec3Dot(const Vector3 *a, const Vector3 *b)
Definition ClientMath.h:93
Vector3 * Vec3Normalize(Vector3 *out, const Vector3 *a)
Definition ClientMath.h:103
RiseMath::Vector4 Tint(const Surface &surface, float latitude, float sunLatitude)
Definition TerrainSnow.h:12
std::vector< Segment > Network(float width, float height, uint32_t seed)
@ Game
Use the game audio system.
Definition discordpp.h:505
unsigned char sec_landform
Definition globals.h:280
unsigned char pri_landform
Definition globals.h:278
short buildzoneOrdinal
Definition globals.h:286
unsigned char pri_transition
Definition globals.h:279
VECTOR2SHORT tcp
Definition globals.h:290
bool elevationAvailable
Definition globals.h:291
std::array< Color, 4096 > cells
VECTOR2SHORT tcp
SRenderVertex gridarray
SRenderVertex gridarray[64]
VECTOR2SHORT tcp
unsigned char side
unsigned char pri_landform
unsigned char windDirectionRadians
bool HasVisibility() const
unsigned char unused
unsigned char precipitation
unsigned char snowDepthMm
uint16_t visibility
unsigned char turbulence
unsigned char snowAgeHours
unsigned char surfaceWaterTenthsMm
unsigned char windSpeedMs
unsigned char array
unsigned char type
RiseMath::Vector3 position
Definition globals.h:511