Rise
The Vieneo Province
Loading...
Searching...
No Matches
CloudVolume.h
Go to the documentation of this file.
1#pragma once
2
3#include <algorithm>
4#include <cmath>
5#include <cstdint>
6#include <array>
7#include "CloudWeatherMap.h"
8#include "CloudBillowNoise.h"
9#include "CloudPerlinNoise.h"
10#include "CloudBaseWeather.h"
11#include "CelestialEclipse.h"
12
13// Planet-fixed coordinates in km, in the renderer's (-planet position) convention.
14// TCP is a cube projection of this same position. Sampling in 3D rather than
15// reseeding at the current TCP preserves formations across cells and cube seams.
16namespace CloudVolume
17{
18 constexpr int NoiseSize = 64;
19 constexpr uint32_t DefaultSeed = 0x52495345u;
20 constexpr int RaySteps = 72;
21 // Shared with the GPU search shell. The strongest clustered tops approach
22 // 22 km MSL above the nominal 10 km deck, including procedural relief.
23 constexpr float MaxTopRiseKm = 12.f;
24 constexpr unsigned MaxWidth = 2048, MaxHeight = 1152;
25
26 struct Point { float x, y, z; };
28 {
29 float radius = 2939.6f;
30 float base = 1.8f;
31 float top = 10.0f;
32 float activity = 0.0f;
33 bool organic = false; // candidate, enabled only with the matching native field
37 CelestialEclipse::Sphere eclipse; // planet-fixed render coordinates, zero disables
38 };
39 // Select the same field for CPU optics/flight and native rendering. The
40 // caller clears render history whenever this returns true, including
41 // simulator entry/exit and shader/device availability changes.
42 inline bool SelectOrganicMode(Parameters& params,bool matchingRendererReady,bool simulator)
43 {
44 const bool next=matchingRendererReady && !simulator;
45 const bool changed=params.organic!=next;
46 params.organic=next;
47 return changed;
48 }
49 inline float Saturate(float x) { return (std::max)(0.f, (std::min)(1.f, x)); }
50 inline float Lerp(float a, float b, float t) { return a + (b-a)*t; }
51 inline float Smooth(float x) { x = Saturate(x); return x*x*(3.f-2.f*x); }
52 inline float BackgroundZenithWeight(float altitude, const Parameters& params)
53 {
54 // Uncovered distant terrain must meet the same haze as the cloud base.
55 // Blend only the background toward clear sky through the deck; this
56 // does not add a screen veil or change scene/cloud transmission.
57 return Smooth((altitude-params.base)/(std::max)(.01f,params.top-params.base));
58 }
59 inline float AmbientWeight(float altitudeAboveTop)
60 {
61 // Scattered deck light fades through the actual formation boundary;
62 // it must not switch off when flight mode changes at 10 km MSL.
63 return 1.f-Smooth((altitudeAboveTop+.5f)/1.5f);
64 }
65 inline float AtmosphereWeight(float altitude, float scaleHeight)
66 {
67 // Match the visible sky's altitude envelope, independently of cloud tops.
68 return std::sqrt(1.f-Saturate(altitude/(6.f*scaleHeight)));
69 }
70 constexpr float ShiplightScatterDistanceKm = .1f;
71 inline float ShiplightScatterWeight(float altitude, float deckTop, float scaleHeight,
72 float visibilityKm, float localCloudOpacity)
73 {
74 // This is the broad, directionless wash from nav/strobe lights, not
75 // direct lamp illumination. Use the fraction scattered over 100 m
76 // (within the shader's 200 m reach), not the mere presence of air.
77 // Atmospheric fog uses a linear visibility scale; local cloud opacity
78 // comes from the actual extinction at the light source over that path.
79 const float air=Saturate(ShiplightScatterDistanceKm/(std::max)(.01f,visibilityKm));
80 const float medium=Lerp(air,1.f,Saturate(localCloudOpacity));
81 const float height=(std::max)(0.f,altitude-deckTop);
82 return medium*std::exp(-height/scaleHeight)*(1.f-Smooth((altitude-4.f*scaleHeight)/(2.f*scaleHeight)));
83 }
84 inline Point VehicleAmbient(Point cloudLight, Point skyLight, float altitudeAboveTop)
85 {
86 // Sky RGB already includes altitude and time of day. A half-strength
87 // sky hemisphere fills shaded surfaces above the deck; inside/below
88 // it keep the existing scattered cloud light, without adding airglow.
89 const float cloud=AmbientWeight(altitudeAboveTop);
90 return {Lerp(skyLight.x*.5f,cloudLight.x,cloud),
91 Lerp(skyLight.y*.5f,cloudLight.y,cloud),Lerp(skyLight.z*.5f,cloudLight.z,cloud)};
92 }
93 inline Point Scale(Point p, float s) { return {p.x*s,p.y*s,p.z*s}; }
94 inline float Length(Point p) { return std::sqrt(p.x*p.x+p.y*p.y+p.z*p.z); }
95 inline Point Add(Point a, Point b) { return {a.x+b.x,a.y+b.y,a.z+b.z}; }
96 inline void Advect(Parameters& params, Point physicalWindKms, double elapsed)
97 {
98 if (!std::isfinite(elapsed) || elapsed<=0) return;
99 // Physics positions and render positions have opposite signs. Sampling
100 // p + integral(wind) moves visible formations with the physical wind.
101 // 6400 km is a common period of all noise scales (integer hundredths).
102 const auto advance=[&](float offset,float speed) {
103 return std::isfinite(speed) ? float(std::remainder(double(offset)+speed*2.1*elapsed,6400.0)) : offset;
104 };
105 params.noiseOffset={advance(params.noiseOffset.x,physicalWindKms.x),
106 advance(params.noiseOffset.y,physicalWindKms.y),advance(params.noiseOffset.z,physicalWindKms.z)};
107 }
108 inline void UpdateLocalWeather(Parameters& params, Point& deckWind, bool belowDeck,
109 float base, float activity, Point observedWind, double elapsed, bool reset = false)
110 {
111 // Flight weather above the deck describes the aircraft, not the clouds.
112 // Until a global map arrives, retain the last deck observation aloft.
113 if (belowDeck)
114 {
115 // The received ceiling is already converted to MSL. A zero AGL
116 // ceiling must follow the terrain, including below sea level.
117 params.base=(std::min)(8.5f,base);
118 if (reset)
119 params.activity=Saturate(activity);
120 else if (std::isfinite(elapsed) && elapsed>0)
121 params.activity=Lerp(params.activity,Saturate(activity),float(1-std::exp(-elapsed/120)));
122 deckWind=observedWind;
123 }
124 Advect(params,deckWind,elapsed);
125 }
126 inline float ScreenOpacity(bool volumeEnabled, float cloudOpacity, float overrideOpacity)
127 {
128 // Preserve local density for illumination and electrical effects.
129 // Visibility itself comes from integrating the cloud along each ray.
130 return volumeEnabled && overrideOpacity<0 ? 0.f : cloudOpacity;
131 }
132 // Legacy above-cloud override; 42.16 km is the unsupplied-weather fallback.
133 // This is an atmospheric fog scale, not an orbital cloud draw distance.
134 constexpr float ClearVisibilityKm = 168.64f;
135 inline float SunGlareStrength(bool volumeEnabled, float altitudeAboveTop,
136 float visibleSun, float transmission)
137 {
138 // A local cloud-top height is not an optical boundary. Wisps already
139 // attenuate sunlight continuously along the actual column to the sun.
140 return volumeEnabled || altitudeAboveTop>0 ? Saturate(visibleSun)*Saturate(transmission) : 0.f;
141 }
142 inline float AtmosphericVisibility(float surfaceVisibility, float altitude, float surfaceAltitude, float clearAltitude)
143 {
144 if (altitude>=clearAltitude) return ClearVisibilityKm;
145 const float surface=(std::max)(0.f,(std::min)(clearAltitude-.01f,surfaceAltitude));
146 const float visibility=Lerp((std::max)(.01f,(std::min)(ClearVisibilityKm,surfaceVisibility)),
147 ClearVisibilityKm,Smooth((altitude-surface)/(clearAltitude-surface)));
148 // Fast floating-point Release code can overshoot the endpoint by one
149 // ULP; keep the clear-air limit bounded in both build configurations.
150 return (std::min)(ClearVisibilityKm,visibility);
151 }
153 {
154 // Do not quantize the blurred light: an isolated 0.1-strength colony
155 // is below one UNORM8 step after the 3x3 average.
156 std::array<Point,64*64> pixels{};
157 int cube=-1, u=0, v=0;
158 // Light-weighted terrain altitude at each smoothed source, in km MSL.
159 std::array<float,64*64> sourceAltitudeKm{};
160 };
162 inline GroundLightTexel GroundLightAt(const GroundLighting& lighting,size_t index)
163 {
164 const auto rgb=lighting.pixels[index];
165 const float r=rgb.x,g=rgb.y,b=rgb.z;
166 // Premultiply height by light so bilinear filtering does not pull a
167 // lit source toward the height of neighboring unlit terrain.
168 return {r,g,b,lighting.sourceAltitudeKm[index]*(r+g+b)};
169 }
170 struct GroundProjection { Point normal, east, down; float u, v; };
171 inline GroundProjection ProjectGround(int cube,int u,int v)
172 {
173 static constexpr Point normals[]={{0,-1,0},{1,0,0},{-1,0,0},{0,1,0},{0,0,-1},{0,0,1}};
174 static constexpr Point east[]={{1,0,0},{0,1,0},{0,-1,0},{-1,0,0},{1,0,0},{1,0,0}};
175 static constexpr Point down[]={{0,0,1},{0,0,1},{0,0,1},{0,0,1},{0,-1,0},{0,1,0}};
176 static constexpr int centerU[]={1019,3057,-1019,5095,1019,1019};
177 static constexpr int centerV[]={1019,1019,1019,1019,-1019,3057};
178 if (cube<0 || cube>5) return {};
179 return {normals[cube],Scale(east[cube],1019.f/64),Scale(down[cube],1019.f/64),
180 (centerU[cube]-u+31.5f)/64,(centerV[cube]-v+31.5f)/64};
181 }
182
183 inline uint8_t Voxel(int x, int y, int z, uint32_t seed)
184 {
185 uint32_t h = seed ^ (uint32_t(x)&63u)*0x8da6b343u
186 ^ (uint32_t(y)&63u)*0xd8163841u ^ (uint32_t(z)&63u)*0xcb1ab31fu;
187 h ^= h >> 16; h *= 0x7feb352du; h ^= h >> 15;
188 h *= 0x846ca68bu; h ^= h >> 16;
189 return uint8_t(h >> 24);
190 }
191 // Matches the GPU's quantized, trilinearly filtered noise volume exactly.
192 inline float Noise(Point p, uint32_t seed = DefaultSeed, int mask=63)
193 {
194 const int x = int(std::floor(p.x)), y = int(std::floor(p.y)), z = int(std::floor(p.z));
195 const float u = Smooth(p.x-x), v = Smooth(p.y-y), w = Smooth(p.z-z);
196 float slices[2];
197 for (int k=0;k<2;++k)
198 slices[k] = Lerp(Lerp(float(Voxel(x&mask,y&mask,(z+k)&mask,seed)),float(Voxel((x+1)&mask,y&mask,(z+k)&mask,seed)),u),
199 Lerp(float(Voxel(x&mask,(y+1)&mask,(z+k)&mask,seed)),float(Voxel((x+1)&mask,(y+1)&mask,(z+k)&mask,seed)),u),v);
200 return Lerp(slices[0],slices[1],w)/255.f;
201 }
202 // Round the cap edge as well as its crest: an unmodified square root
203 // has an infinite slope where the lobe meets the surrounding deck.
204 inline float TopLobe(float distance,float radius)
205 {
206 const float cell=distance/radius,cap=Saturate(1.f-cell*cell);
207 return std::sqrt(cap)*Smooth(cap/.5f);
208 }
209 inline float ShallowLobe(float distance,float radius)
210 {
211 const float cell=distance/radius,cap=Saturate(1.f-cell*cell);
212 return cap*cap;
213 }
215 {
216 return CloudBaseWeather::Sample(params.localBase,{p.x,p.y,p.z},Length(p)-params.radius,
217 params.top,params.base,weather);
218 }
219 inline float MinimumBase(const Parameters& params)
220 {return CloudBaseWeather::Active(params.localBase) ? (std::min)(params.base,params.localBase.grid->minimumBase) : params.base;}
222 inline Column LegacyBoundaries(Point p, const Parameters& params, uint32_t seed = DefaultSeed)
223 {
224 const float len = Length(p);
225 const Point surface = Add(Scale(p, params.radius / (std::max)(len,1.f)),params.noiseOffset);
226 // Match the shader's warped 100/25/6 km field. The server still places
227 // storms; this bends the cluster grid and fills it with rounded billows.
228 // Integer hundredths preserve the shared 6400 km wind-wrap period.
229 const float coarse=Noise(Add(Scale(surface,.01f),{19,7,31}),seed);
230 const Point warp=Scale({1.5f,-1.1f,.9f},coarse-.5f);
231 const float broad=.65f*Noise(Add(Scale(surface,.04f),warp),seed)+.35f*coarse;
232 const float topBillow=Noise(Add(Scale(surface,.17f),warp),seed);
233 const float billow = Noise(Scale(surface,.71f),seed);
234 const float weather=CloudWeather::Sample(params.weather,p.x,p.y,p.z);
235 const float growth=Smooth((weather-.2f)/.65f);
236 const float topGrowth=Smooth((weather-.15f)/.85f);
237 const float cluster=Smooth((broad-.25f)/.5f);
238 const float structure=topGrowth*(.35f+.65f*cluster);
239 // A broad parent dome carries unequal shoulders and smaller crowns.
240 // Reuse the shallow field at both scales; the unit-bounded composite
241 // redistributes the existing convective height budget, not its limits.
242 const float parent=TopLobe(CloudBillows::Sample(surface.x*.07f,surface.y*.07f,surface.z*.07f),.55f);
243 const float shoulderDistance=CloudBillows::Sample(surface.x*.19f,surface.y*.19f,surface.z*.19f);
244 const float crownDistance=CloudBillows::Sample(surface.x*.43f+3.f,surface.y*.43f+5.f,surface.z*.43f+1.f);
245 const float shoulder=TopLobe(shoulderDistance,.65f);
246 const float crown=TopLobe(crownDistance,.55f);
247 const float joined=(std::max)(parent,shoulder*(.35f+.45f*parent));
248 const float parent2=parent*parent,parent4=parent2*parent2;
249 const float tower=joined-.3f*(joined-parent4*parent4)*(1.f-crown);
250 const float shallow=ShallowLobe(shoulderDistance,.9f);
251 const float topLobe=.35f*shallow+.65f*ShallowLobe(crownDistance,.55f)*(.25f+.75f*shallow);
252 // Quiet stratus varies by +/-60 m; active bases by at most +/-180 m.
253 // Center both on the local ceiling instead of lowering whole storms.
254 const float globalBase=params.base + (billow-.5f)*(.12f+.24f*growth);
255 const auto controls=BaseControls(p,params,weather);
256 const float base=controls.base+(billow-.5f)*(.12f+.24f*Smooth((controls.turbulence-.2f)/.65f));
257 // The continuous deck reaches 10 km. Above it, convection grows
258 // clusters instead of lifting an entire region into a solid slab.
259 return {base,
260 (std::max)(globalBase+2.5f, params.top+.7f+cluster*.12f+topBillow*.08f
261 +topLobe*(.4f+.4f*structure)
262 +topGrowth*(cluster*8.2f*tower+topBillow*(.5f+1.5f*cluster))),
263 weather,structure,controls.turbulence};
264 }
265 // Artistic top-shape model, not a condensate/microphysics calculation.
266 // Erode inward from the existing envelope with nested rounded 3D lobes.
267 // Nonnegative erosion preserves clearance bounds and the solid 10 km deck.
268 inline float TopErosion(Point advected,float detail,float fine,float structure)
269 {
270 const float broad=CloudBillows::Sample(advected.x*.19f,advected.y*.19f,advected.z*.19f);
271 const float fineBillow=CloudBillows::Sample(advected.x*.43f+3.f,advected.y*.43f+5.f,advected.z*.43f+1.f);
272 return (broad*1.4f+fineBillow*.35f+(1.f-detail)*.04f+(1.f-fine)*.01f)*(.18f+.40f*structure);
273 }
274 struct Medium { float density, extinction, pocket; };
275 inline float Pocket(float detail, float fine)
276 {
277 return Smooth((.35f*detail+.65f*fine-.32f)/.36f);
278 }
279 inline Medium LegacySampleMedium(Point p, const Parameters& params, uint32_t seed = DefaultSeed)
280 {
281 const float altitude = Length(p)-params.radius;
282 if (altitude < MinimumBase(params)-.4f || altitude > params.top+MaxTopRiseKm) return {};
283 const auto column = LegacyBoundaries(p,params,seed);
284 const Point advected=Add(p,params.noiseOffset);
285 const float body = Noise(Scale(advected,.71f),seed);
286 const float detail = Noise(Scale(advected,2.17f),seed);
287 const float fine = Noise(Scale(advected,6.13f),seed);
288 const float topRawErosion = TopErosion(advected,detail,fine,column.structure);
289 const float globalBase=params.base+(Noise(Scale(Add(Scale(p,params.radius/(std::max)(Length(p),1.f)),params.noiseOffset),.71f),seed)-.5f)
290 *(.12f+.24f*Smooth((column.weather-.2f)/.65f));
291 const float available=(std::max)(.01f,column.top-(std::max)(params.top+.65f,globalBase+1.3f));
292 const float erosion=available*topRawErosion/(available+topRawErosion);
293 float bottom=1;
294 if (altitude<column.base+.8f)
295 {
296 // Smaller billows and wisps belong to the actual density surface.
297 // Only evaluate them near the base; opaque top views skip this work.
298 const float rawErosion=(1.f-detail)*.16f+(1.f-fine)*.12f
299 +(1.f-Noise(Scale(advected,19.17f),seed))*.03f
300 +(1.f-Noise(Scale(advected,53.71f),seed))*.01f;
301 const float growth=Smooth((column.baseWeather-.2f)/.65f);
302 // Reduce relief around the same mean erosion/ceiling. This also
303 // keeps the shader's MODULATE2X lighting centered on the horizon.
304 const float baseErosion=.16f+(rawErosion-.16f)*(.3f+.4f*growth);
305 bottom=Smooth((altitude-column.base-baseErosion)/.32f);
306 }
307 const float top = Smooth(((std::max)(params.top+.65f,column.top-erosion)-altitude)/.65f);
308 // Calm tops scatter through a more even body; preserve the underside's
309 // existing density/lighting and develop texture within active clusters.
310 const float contrast=Lerp(1.f,.35f+.65f*column.structure,Smooth((altitude-column.base-.8f)/1.2f));
311 const float bodyDensity=Lerp(.75f,Saturate(.3f+body*.65f+detail*.25f),contrast);
312 const float d=bottom*top*bodyDensity*(.65f+column.weather*.35f)*(.5f+.5f*column.weather);
313 // Interior pockets are finer than the visible billow/erosion field:
314 // 163 m and 54 m cells vary about three times faster during flight.
315 const float pocket=Pocket(fine,Noise(Scale(advected,18.39f),seed));
316 // Preserve feathered surfaces and wing outlines in the densest mist.
317 // Limit extinction, not accumulated opacity: long paths stay opaque.
318 const float core=Smooth((altitude-column.base-.3f)/.5f)*Smooth((column.top-altitude-.3f)/.7f);
319 return {d,(std::min)(100.f,d*24.f*(1.f+9.f*pocket*pocket*pocket*core)),pocket};
320 }
321 }
322#include "CloudOrganicShape.inl"
323namespace CloudVolume
324{
325 inline Column Boundaries(Point p,const Parameters& params,uint32_t seed=DefaultSeed)
326 {
327 return params.organic ? CloudOrganicShape::SurfaceColumn(p,params,seed) : LegacyBoundaries(p,params,seed);
328 }
329 inline Medium SampleMedium(Point p,const Parameters& params,uint32_t seed=DefaultSeed)
330 {
331 if(!params.organic || Length(p)-params.radius<=params.top-.5f || CloudOrganicShape::Weight(params)<=0)
332 return LegacySampleMedium(p,params,seed);
333 const auto sample=CloudOrganicShape::Evaluate(p,params,seed);
334 if(sample.density<=0)return {};
335 // Preserve the existing small-scale flight variation. Optical
336 // extinction is supplied by the shared 3D medium, not this pocket.
337 const Point advected=Add(p,params.noiseOffset);
338 const float pocket=Pocket(Noise(Scale(advected,6.13f),seed),Noise(Scale(advected,18.39f),seed));
339 return {sample.density,sample.extinction,pocket};
340 }
341 inline float Density(Point p, const Parameters& params, uint32_t seed = DefaultSeed)
342 {
343 return SampleMedium(p,params,seed).density;
344 }
345 inline float RainDensity(const Medium& medium)
346 {
347 return Smooth(medium.density*4.f)*(.2f+.8f*medium.pocket);
348 }
349 inline float BaseLightingWeight(Point eye, const Parameters& params, uint32_t seed=DefaultSeed)
350 {
351 return (1.f-Smooth(Density(eye,params,seed)*4.f))
352 *(1.f-Smooth((Length(eye)-params.radius-BaseControls(eye,params,0).base-.8f)/.5f));
353 }
354 inline float DiffuseSunTransmission(Point p, Point towardSun, const Parameters& params, uint32_t seed=DefaultSeed)
355 {
356 // Multiple-scattered sunlight, separate from direct-beam extinction.
357 // Fit quadrature to the local column. Growing fixed intervals could
358 // count a whole interval as cloudy as the eye climbed into its midpoint.
359 const float radius=Length(p),altitude=radius-params.radius;
360 const auto column=Boundaries(p,params,seed);
361 const float cosine=(std::max)(.15f,(p.x*towardSun.x+p.y*towardSun.y+p.z*towardSun.z)/radius);
362 const float start=(std::max)(0.f,(column.base-altitude)/cosine);
363 const float span=(std::max)(.5f,(column.top-(std::max)(column.base,altitude))/cosine);
364 const float step=span/8;
365 float opticalDepth=0;
366 for(int i=0;i<8;++i)
367 {
368 opticalDepth+=Density(Add(p,Scale(towardSun,start+(i+.5f)*step)),params,seed)*step*.7f;
369 }
370 return std::exp(-opticalDepth);
371 }
372 inline float AtmosphericHazeDistanceKm(float nominalTop)
373 {
374 // Match weather::SunAttenuation: vertical optical depth above altitude
375 // h is 0.5*exp(-h/7.5). Visibility distance is not this extinction scale.
376 return 7.5f/(.5f*std::exp(-nominalTop/7.5f));
377 }
378 inline float AirglowVisibility(float sunCosine)
379 {
380 // Fade through twilight (-6 to +3 degrees). Use the sun elevation,
381 // not cloud-shadowed light, so dense daytime clouds cannot turn green.
382 return 1.f-Smooth((sunCosine+.104528f)/.156864f);
383 }
384 inline float DiffuseSunDisplayAttenuation(float transmission, float sunCosine)
385 {
386 // Deois daylight audit: codex://threads/01a103d2-137e-7433-836e-da1d78903c9c
387 // The existing depth/density integral estimates scattered sunlight, but
388 // our legacy shaders multiply encoded texture RGB without sRGB conversion.
389 // Encode ONLY the cloud attenuation (gamma 2.2 approximation): applying
390 // the 6% linear floor directly to those textures crushes displayed light
391 // to about 0.2%. This is not a global gamma or eye-adaptation change.
392 // Fade the correction in between sun cosines .05 and .25 (about 3-14
393 // degrees) to retain twilight/night lighting. Keep solar elevation and
394 // incident color outside the power; clear cloud tops still return 1.
395 // Match diffuseSunDisplayAttenuation in CloudVolume.fx. Convection
396 // already changes column density/depth; do not darken it again for rain.
397 const float attenuation=.06f+.94f*Saturate(transmission);
398 return Lerp(attenuation,std::pow(attenuation,1.f/2.2f),Smooth((sunCosine-.05f)/.20f));
399 }
400 inline Point ScatteredSunlight(Point incident, float sunCosine, float transmission)
401 {
402 return Scale(incident,Saturate(sunCosine)*DiffuseSunDisplayAttenuation(transmission,sunCosine));
403 }
404 inline Point WithAirglow(Point scattered, Point airglow, float sunCosine,
405 float altitude, float base, float top)
406 {
407 const float height=Saturate((altitude-base)/(std::max)(1.f,top-base));
408 const float emission=AirglowVisibility(sunCosine)
409 *(.15f+.85f*std::exp(-.125f*(altitude-9)*(altitude-9)))*Lerp(1.f,.04f,Smooth(height));
410 const auto channel=[&](float light,float glow) {
411 // Match the cloud shader's strongest-source rule. This color is
412 // reused as the base/horizon baseline, so it must not add airglow.
413 return (std::max)(Saturate(light),glow*emission);
414 };
415 return {channel(scattered.x,airglow.x),channel(scattered.y,airglow.y),channel(scattered.z,airglow.z)};
416 }
417 // Shared extinction for point lights and direct sunlight, which cannot
418 // use the opaque scene-depth composite. Positions are planet-fixed render
419 // coordinates, in kilometers, just like Density and the GPU raymarch.
420 inline float Transmittance(Point from, Point to, const Parameters& params, uint32_t seed=DefaultSeed)
421 {
422 Point direction=Add(to,Scale(from,-1));
423 const float distance=Length(direction);
424 if (distance<=.00001f) return 1;
425 direction=Scale(direction,1/distance);
426 const double eyeLength=Length(from);
427 const double b=double(from.x)*direction.x+double(from.y)*direction.y+double(from.z)*direction.z;
428 const auto sphere=[&](double radius, double& nearHit, double& farHit) {
429 const double discriminant=b*b-(eyeLength-radius)*(eyeLength+radius);
430 if (discriminant<0) return false;
431 const double root=std::sqrt(discriminant);
432 nearHit=-b-root; farHit=-b+root; return true;
433 };
434 double nearHit,farHit;
435 if (!sphere(params.radius+params.top+MaxTopRiseKm,nearHit,farHit)) return 1;
436 float start=float((std::max)(0.0,nearHit)),end=float((std::min)(double(distance),farHit));
437 const double inner=params.radius+MinimumBase(params)-.4f;
438 if (sphere(inner,nearHit,farHit))
439 {
440 if (eyeLength<inner) start=(std::max)(start,float(farHit));
441 else if (nearHit>0) end=(std::min)(end,float(nearHit));
442 }
443 if (end<=start) return 1;
444 float opticalDepth=0,step=.025f;
445 // Bound the work even on grazing planetary rays; the opaque core
446 // normally terminates after a few hundred meters. Quadrature samples
447 // are small at entry so thin wisps and nearby lamps fade continuously.
448 for (int i=0;i<512 && start<end;++i)
449 {
450 const float ds=(std::min)((std::max)(step,(end-start)/(512-i)),end-start);
451 opticalDepth+=SampleMedium(Add(from,Scale(direction,start+ds*.5f)),params,seed).extinction*ds;
452 if (opticalDepth>12) return 0;
453 start+=ds; step=(std::min)(.5f,step*1.12f);
454 }
455 return std::exp(-opticalDepth);
456 }
457}
SCRIPT_CONTROL SCRIPT_STATE const void int
bool Active(const Frame &frame)
Controls Sample(const Frame &frame, Point p, float altitude, float top, float base, float turbulence)
float Sample(float x, float y, float z)
Column SurfaceColumn(Point p, const Parameters &params, uint32_t seed=DefaultSeed)
Sample Evaluate(Point p, const Parameters &params, uint32_t seed=DefaultSeed, const Region *prepared=nullptr)
float Weight(const Parameters &params)
float Smooth(float x)
Definition CloudVolume.h:51
float DiffuseSunDisplayAttenuation(float transmission, float sunCosine)
Column LegacyBoundaries(Point p, const Parameters &params, uint32_t seed=DefaultSeed)
constexpr int NoiseSize
Definition CloudVolume.h:18
uint8_t Voxel(int x, int y, int z, uint32_t seed)
GroundProjection ProjectGround(int cube, int u, int v)
constexpr float MaxTopRiseKm
Definition CloudVolume.h:23
float Lerp(float a, float b, float t)
Definition CloudVolume.h:50
Point Scale(Point p, float s)
Definition CloudVolume.h:93
float AtmosphericHazeDistanceKm(float nominalTop)
float BackgroundZenithWeight(float altitude, const Parameters &params)
Definition CloudVolume.h:52
float AirglowVisibility(float sunCosine)
Point Add(Point a, Point b)
Definition CloudVolume.h:95
float AtmosphereWeight(float altitude, float scaleHeight)
Definition CloudVolume.h:65
void UpdateLocalWeather(Parameters &params, Point &deckWind, bool belowDeck, float base, float activity, Point observedWind, double elapsed, bool reset=false)
void Advect(Parameters &params, Point physicalWindKms, double elapsed)
Definition CloudVolume.h:96
CloudBaseWeather::Controls BaseControls(Point p, const Parameters &params, float weather)
Point VehicleAmbient(Point cloudLight, Point skyLight, float altitudeAboveTop)
Definition CloudVolume.h:84
float Noise(Point p, uint32_t seed=DefaultSeed, int mask=63)
constexpr unsigned MaxHeight
Definition CloudVolume.h:24
constexpr float ShiplightScatterDistanceKm
Definition CloudVolume.h:70
constexpr uint32_t DefaultSeed
Definition CloudVolume.h:19
constexpr int RaySteps
Definition CloudVolume.h:20
float AmbientWeight(float altitudeAboveTop)
Definition CloudVolume.h:59
constexpr float ClearVisibilityKm
bool SelectOrganicMode(Parameters &params, bool matchingRendererReady, bool simulator)
Definition CloudVolume.h:42
float Transmittance(Point from, Point to, const Parameters &params, uint32_t seed=DefaultSeed)
GroundLightTexel GroundLightAt(const GroundLighting &lighting, size_t index)
float DiffuseSunTransmission(Point p, Point towardSun, const Parameters &params, uint32_t seed=DefaultSeed)
float ShiplightScatterWeight(float altitude, float deckTop, float scaleHeight, float visibilityKm, float localCloudOpacity)
Definition CloudVolume.h:71
Column Boundaries(Point p, const Parameters &params, uint32_t seed=DefaultSeed)
Medium SampleMedium(Point p, const Parameters &params, uint32_t seed=DefaultSeed)
float Saturate(float x)
Definition CloudVolume.h:49
float ShallowLobe(float distance, float radius)
float Pocket(float detail, float fine)
float MinimumBase(const Parameters &params)
float AtmosphericVisibility(float surfaceVisibility, float altitude, float surfaceAltitude, float clearAltitude)
constexpr unsigned MaxWidth
Definition CloudVolume.h:24
Medium LegacySampleMedium(Point p, const Parameters &params, uint32_t seed=DefaultSeed)
float Density(Point p, const Parameters &params, uint32_t seed=DefaultSeed)
float SunGlareStrength(bool volumeEnabled, float altitudeAboveTop, float visibleSun, float transmission)
float Length(Point p)
Definition CloudVolume.h:94
float RainDensity(const Medium &medium)
float ScreenOpacity(bool volumeEnabled, float cloudOpacity, float overrideOpacity)
float BaseLightingWeight(Point eye, const Parameters &params, uint32_t seed=DefaultSeed)
float TopErosion(Point advected, float detail, float fine, float structure)
float TopLobe(float distance, float radius)
Point ScatteredSunlight(Point incident, float sunCosine, float transmission)
Point WithAirglow(Point scattered, Point airglow, float sunCosine, float altitude, float base, float top)
float Sample(const MapPtr &map, float u, float v)
std::array< Point, 64 *64 > pixels
std::array< float, 64 *64 > sourceAltitudeKm
CelestialEclipse::Sphere eclipse
Definition CloudVolume.h:37
CloudWeather::Frame weather
Definition CloudVolume.h:35
CloudBaseWeather::Frame localBase
Definition CloudVolume.h:36