Oolite
Loading...
Searching...
No Matches
OOStandaloneAtmosphereGenerator.m
Go to the documentation of this file.
1/*
2 OOStandaloneAtmosphereGenerator.m
3
4 Generator for atmosphere textures when the planet is using a
5 non-generated diffuse map.
6
7
8 Oolite
9 Copyright (C) 2004-2013 Giles C Williams and contributors
10
11 This program is free software; you can redistribute it and/or
12 modify it under the terms of the GNU General Public License
13 as published by the Free Software Foundation; either version 2
14 of the License, or (at your option) any later version.
15
16 This program is distributed in the hope that it will be useful,
17 but WITHOUT ANY WARRANTY; without even the implied warranty of
18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 GNU General Public License for more details.
20
21 You should have received a copy of the GNU General Public License
22 along with this program; if not, write to the Free Software
23 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
24 MA 02110-1301, USA.
25*/
26
27#import "OOFoundation.h"
28#import "OOStellarBody.h"
29
30#if NEW_PLANETS
31
32#define DEBUG_DUMP (0 && OOLITE_DEBUG)
33#define DEBUG_DUMP_RAW (1 && DEBUG_DUMP)
34
35#define ALBEDO_FACTOR 0.7f // Overall darkening of everything, allowing better contrast for snow and specular highlights.
36
38#import "OOColor.h"
40
41#ifndef TEXGEN_TEST_RIG
42#import "OOTexture.h"
43#import "Universe.h"
44#endif
45
46#if DEBUG_DUMP
47#import "MyOpenGLView.h"
48#endif
49
50#define FREE(x) \
51 do { \
52 if (0) { \
53 void* x__ = x; \
54 x__ = x__; \
55 } /* Preceeding is for type checking only. */ \
56 void** x_ = (void**)&(x); \
57 free(*x_); \
58 *x_ = NULL; \
59 } while (0)
60
61#define PLANET_TEXTURE_OPTIONS (kOOTextureMinFilterLinear | kOOTextureMagFilterLinear | kOOTextureRepeatS | kOOTextureNoShrink)
62
63enum {
64 kRandomBufferSize = 128
65};
66
67@interface OOStandaloneAtmosphereGenerator (Private)
68
69#if DEBUG_DUMP_RAW
70- (void)dumpNoiseBuffer:(float*)noise;
71#endif
72
73@end
74
75static FloatRGB FloatRGBFromDictColor(NSDictionary* dictionary, NSString* key);
76
77static BOOL FillFBMBuffer(OOStandaloneAtmosphereGeneratorInfo* info);
78static float QFactor(float* accbuffer, int x, int y, unsigned width, float polar_y_value, float bias, float polar_y);
79static float BlendAlpha(float fraction, float a, float b);
80static FloatRGBA CloudMix(OOStandaloneAtmosphereGeneratorInfo* info, float q, float nearPole);
81
82enum {
83 kPlanetScale256x256 = 1,
84 kPlanetScale512x512,
85 kPlanetScale1024x1024,
86 kPlanetScale2048x2048,
87 kPlanetScale4096x4096,
88
89 kPlanetScaleReducedDetail = kPlanetScale512x512,
90 kPlanetScaleFullDetail = kPlanetScale1024x1024
91};
92
93@implementation OOStandaloneAtmosphereGenerator
94
95- (id)initWithPlanetInfo:(NSDictionary*)planetInfo
96{
97 OOLog(@"texture.planet.generate", @"%@", @"Initialising standalone atmosphere generator");
98
99 // AllowCubeMap not used yet but might be in future
100 if ((self = [super initWithPath:[NSString stringWithFormat:@"OOStandaloneAtmosphereTexture@%p", self] options:kOOTextureAllowCubeMap])) {
101 OOLog(@"texture.planet.generate", @"Extracting parameters for generator %@", self);
102 [[planetInfo objectForKey:@"noise_map_seed"] getValue:&_info.seed];
103 OOLog(@"texture.planet.generate", @"%@", @"Extracting atmosphere parameters");
104 // we are an atmosphere:
105 _info.cloudAlpha = [planetInfo oo_floatForKey:@"cloud_alpha" defaultValue:1.0f];
106 _info.cloudFraction = OOClamp_0_1_f([planetInfo oo_floatForKey:@"cloud_fraction" defaultValue:0.3]);
107 _info.cloudColor = FloatRGBFromDictColor(planetInfo, @"cloud_color");
108 _info.paleCloudColor = FloatRGBFromDictColor(planetInfo, @"polar_cloud_color");
109
110 OOGraphicsDetail detailLevel = [UNIVERSE detailLevel];
111
112#ifndef TEXGEN_TEST_RIG
113 if (detailLevel < DETAIL_LEVEL_SHADERS) {
114 _planetScale = kPlanetScaleReducedDetail;
115 } else {
116 _planetScale = kPlanetScaleFullDetail;
117 }
118#else
119 _planetScale = kPlanetScale4096x4096;
120#endif
121 _info.perlin3d = [planetInfo oo_boolForKey:@"perlin_3d" defaultValue:detailLevel > DETAIL_LEVEL_SHADERS];
122 _info.planetAspectRatio = _info.perlin3d ? 2 : 1;
123 _info.planetScaleOffset = 8 - _info.planetAspectRatio;
124 }
125
126 return self;
127}
128
129+ (OOTexture*)planetTextureWithInfo:(NSDictionary*)planetInfo
130{
131 OOTexture* result = nil;
132 OOStandaloneAtmosphereGenerator* generator = [[self alloc] initWithPlanetInfo:planetInfo];
133 if (generator != nil) {
134 result = [OOTexture textureWithGenerator:generator];
135 [generator release];
136 }
137
138 return result;
139}
140
141+ (BOOL)generateAtmosphereTexture:(OOTexture**)texture withInfo:(NSDictionary*)planetInfo
142{
143 NSParameterAssert(texture != NULL);
144
145 OOStandaloneAtmosphereGenerator* atmoGen = [[[self alloc] initWithPlanetInfo:planetInfo] autorelease];
146 if (atmoGen == nil)
147 return NO;
148
149 *texture = [OOTexture textureWithGenerator:atmoGen];
150
151 return *texture != nil;
152}
153
154- (void)dealloc
155{
156 [super dealloc];
157}
158
159- (NSString*)descriptionComponents
160{
161 return [NSString stringWithFormat:@"seed: %u,%u", _info.seed.high, _info.seed.low];
162}
163
164- (uint32_t)textureOptions
165{
166 return PLANET_TEXTURE_OPTIONS;
167}
168
169- (NSString*)cacheKey
170{
171 return [NSString stringWithFormat:@"OOStandaloneAtmosphereGenerator-@%u\n%u,%u/%u,%u/%f/%f/%f,%f,%f/%f,%f,%f/%f,%f,%f",
172 _planetScale,
173 _info.width, _info.height, _info.seed.high, _info.seed.low,
174 _info.cloudAlpha, _info.cloudFraction,
175 _info.airColor.r, _info.airColor.g, _info.airColor.b,
176 _info.cloudColor.r, _info.cloudColor.g, _info.cloudColor.b,
177 _info.paleCloudColor.r, _info.paleCloudColor.g, _info.paleCloudColor.b];
178}
179
180- (BOOL)getResult:(OOPixMap*)outData
181 format:(OOTextureDataFormat*)outFormat
182 width:(uint32_t*)outWidth
183 height:(uint32_t*)outHeight
184{
185 BOOL waiting = NO;
186 if (![self isReady]) {
187 waiting = true;
188 OOLog(@"texture.planet.generate.wait", @"%s generator %@", "Waiting for", self);
189 }
190
191 BOOL result = [super getResult:outData format:outFormat originalWidth:outWidth originalHeight:outHeight];
192
193 if (waiting) {
194 OOLog(@"texture.planet.generate.dequeue", @"%s generator %@", result ? "Dequeued" : "Failed to dequeue", self);
195 } else {
196 OOLog(@"texture.planet.generate.dequeue", @"%s generator %@ without waiting.", result ? "Dequeued" : "Failed to dequeue", self);
197 }
198
199 return result;
200}
201
202/* TODO: fix duplication between here and OOPlanetTextureGenerator of
203 * various noise, interpolation, etc. functions */
204- (void)loadTexture
205{
206 OOLog(@"texture.planet.generate.begin", @"Started generator %@", self);
207
208 BOOL success = NO;
209
210 uint8_t *aBuffer = NULL, *apx = NULL;
211 float* randomBuffer = NULL;
212
213 _height = _info.height = 1 << (_planetScale + _info.planetScaleOffset);
214 _width = _info.width = _height * _info.planetAspectRatio;
215
216#define FAIL_IF(cond) \
217 do { \
218 if (EXPECT_NOT(cond)) \
219 goto END; \
220 } while (0)
221#define FAIL_IF_NULL(x) FAIL_IF((x) == NULL)
222
223 aBuffer = malloc(4 * _width * _height);
224 FAIL_IF_NULL(aBuffer);
225 apx = aBuffer;
226
227 FAIL_IF(!FillFBMBuffer(&_info));
228#if DEBUG_DUMP_RAW
229 [self dumpNoiseBuffer:_info.fbmBuffer];
230#endif
231
232 float paleClouds = (_info.cloudFraction * _info.fbmBuffer[0] < 1.0f - _info.cloudFraction) ? 0.0f : 1.0f;
233
234 int x, y;
235 FloatRGBA color;
236 float q, nearPole;
237 float rHeight = 1.0f / _height;
238 float fy, fHeight = _height;
239
240 float cloudFraction = _info.cloudFraction;
241
242 for (y = (int)_height - 1, fy = (float)y; y >= 0; y--, fy--) {
243 nearPole = (2.0f * fy - fHeight) * rHeight;
244 nearPole *= nearPole;
245
246 for (x = (int)_width - 1; x >= 0; x--) {
247 q = QFactor(_info.fbmBuffer, x, y, _width, paleClouds, cloudFraction, nearPole);
248 color = CloudMix(&_info, q, nearPole);
249 *apx++ = 255.0f * color.r;
250 *apx++ = 255.0f * color.g;
251 *apx++ = 255.0f * color.b;
252 *apx++ = 255.0f * color.a * _info.cloudAlpha;
253 }
254 }
255
256 success = YES;
257 _format = kOOTextureDataRGBA;
258
259END:
260 FREE(_info.fbmBuffer);
261 FREE(randomBuffer);
262 if (success) {
263 _data = aBuffer;
264 } else {
265 FREE(aBuffer);
266 }
267
268 OOLog(@"texture.planet.generate.complete", @"Completed generator %@ %@successfully", self, success ? @"" : @"un");
269
270#if DEBUG_DUMP
271 if (success) {
272 NSString* diffuseName = [NSString stringWithFormat:@"atmosphere-%u-%u-diffuse-new", _info.seed.high, _info.seed.low];
273 NSString* lightsName = [NSString stringWithFormat:@"atmosphere-%u-%u-alpha-new", _info.seed.high, _info.seed.low];
274
275 [[UNIVERSE gameView] dumpRGBAToRGBFileNamed:diffuseName
276 andGrayFileNamed:lightsName
277 bytes:aBuffer
278 width:_width
279 height:_height
280 rowBytes:_width * 4];
281 }
282#endif
283}
284
285#if DEBUG_DUMP_RAW
286
287- (void)dumpNoiseBuffer:(float*)noise
288{
289 NSString* noiseName = [NSString stringWithFormat:@"atmosphere-%u-%u-noise-new", _info.seed.high, _info.seed.low];
290
291 uint8_t* noisePx = malloc(_width * _height);
292 unsigned x, y;
293 for (y = 0; y < _height; y++) {
294 for (x = 0; x < _width; x++) {
295 noisePx[y * _width + x] = 255.0f * noise[y * _width + x];
296 }
297 }
298
299 [[UNIVERSE gameView] dumpGrayToFileNamed:noiseName
300 bytes:noisePx
301 width:_width
302 height:_height
303 rowBytes:_width];
304 FREE(noisePx);
305}
306
307#endif
308
309@end
310
311OOINLINE float Lerp(float v0, float v1, float fraction)
312{
313 // Linear interpolation - equivalent to v0 * (1.0f - fraction) + v1 * fraction.
314 return v0 + fraction * (v1 - v0);
315}
316
317static FloatRGB Blend(float fraction, FloatRGB a, FloatRGB b)
318{
319 return (FloatRGB) {
320 Lerp(b.r, a.r, fraction),
321 Lerp(b.g, a.g, fraction),
322 Lerp(b.b, a.b, fraction)
323 };
324}
325
326static float BlendAlpha(float fraction, float a, float b)
327{
328 return Lerp(b, a, fraction);
329}
330
331static FloatRGBA CloudMix(OOStandaloneAtmosphereGeneratorInfo* info, float q, float nearPole)
332{
333// #define AIR_ALPHA (0.15f)
334// #define CLOUD_ALPHA (1.0f)
335// CIM: make distinction between cloud and not-cloud bigger
336#define AIR_ALPHA (0.05f)
337#define CLOUD_ALPHA (2.0f)
338
339#define POLAR_BOUNDARY (0.33f)
340#define CLOUD_BOUNDARY (0.5f)
341#define RECIP_CLOUD_BOUNDARY (1.0f / CLOUD_BOUNDARY)
342
343 FloatRGB cloudColor = info->cloudColor;
344 float alpha = info->cloudAlpha, portion = 0.0f;
345
346 q -= CLOUD_BOUNDARY * 0.5f;
347
348 if (nearPole > POLAR_BOUNDARY) {
349 portion = nearPole > POLAR_BOUNDARY + 0.2f ? 1.0f : (nearPole - POLAR_BOUNDARY) * 5.0f;
350 cloudColor = Blend(portion, info->paleCloudColor, cloudColor);
351
352 portion = nearPole > POLAR_BOUNDARY + 0.625f ? 1.0f : (nearPole - POLAR_BOUNDARY) * 1.6f;
353 }
354
355 if (q <= 0.0f) {
356 if (q >= -CLOUD_BOUNDARY) {
357 alpha *= BlendAlpha(-q * 0.5f * RECIP_CLOUD_BOUNDARY + 0.5f, CLOUD_ALPHA, AIR_ALPHA);
358 } else {
359 alpha *= CLOUD_ALPHA;
360 }
361 } else {
362 if (q < CLOUD_BOUNDARY) {
363 alpha *= BlendAlpha(q * 0.5f * RECIP_CLOUD_BOUNDARY + 0.5f, AIR_ALPHA, CLOUD_ALPHA);
364 } else {
365 alpha *= AIR_ALPHA;
366 }
367 }
368 // magic numbers! at the poles we have fairly thin air.
369 alpha *= BlendAlpha(portion, 0.6f, 1.0f);
370 if (alpha > 1.0) {
371 alpha = 1.0;
372 }
373
374 return (FloatRGBA) { cloudColor.r, cloudColor.g, cloudColor.b, alpha };
375}
376
377static FloatRGB FloatRGBFromDictColor(NSDictionary* dictionary, NSString* key)
378{
379 OOColor* color = [dictionary objectForKey:key];
380 NSCAssert1([color isKindOfClass:[OOColor class]], @"Expected OOColor, got %@", [color class]);
381
382 return (FloatRGB) { [color redComponent] * ALBEDO_FACTOR, [color greenComponent] * ALBEDO_FACTOR, [color blueComponent] * ALBEDO_FACTOR };
383}
384
385OOINLINE float Hermite(float q)
386{
387 return 3.0f * q * q - 2.0f * q * q * q;
388}
389
390#if __BIG_ENDIAN__
391#define iman_ 1
392#else
393#define iman_ 0
394#endif
395
396// (same behaviour as, but faster than, FLOAT->INT)
397// Works OK for -32728 to 32727.99999236688
398OOINLINE int32_t fast_floor(double val)
399{
400 val += 68719476736.0 * 1.5;
401 return (((int32_t*)&val)[iman_] >> 16);
402}
403
404static BOOL GenerateFBMNoise(OOStandaloneAtmosphereGeneratorInfo* info);
405static BOOL GenerateFBMNoise3D(OOStandaloneAtmosphereGeneratorInfo* info);
406
407static BOOL FillFBMBuffer(OOStandaloneAtmosphereGeneratorInfo* info)
408{
409 NSCParameterAssert(info != NULL);
410
411 // Allocate result buffer.
412 info->fbmBuffer = calloc(info->width * info->height, sizeof(float));
413 if (info->fbmBuffer != NULL) {
414 if (!info->perlin3d) {
415 GenerateFBMNoise(info);
416 } else {
417 GenerateFBMNoise3D(info);
418 }
419
420 return YES;
421 }
422 return NO;
423}
424
425enum {
426 // Size of permutation buffer used to map integer coordinates to gradients. Must be power of two.
427 kPermutationCount = 1 << 10,
428 kPermutationMask = kPermutationCount - 1,
429
430 // Number of different gradient vectors used. The most important thing is that the gradients are evenly distributed and sum to 0.
431 kGradientCount = 12
432};
433
434#define LUT_DOT 1
435
436#if !LUT_DOT
437static const Vector kGradients[kGradientCount] = {
438 { 1, 1, 0 },
439 { -1, 1, 0 },
440 { 1, -1, 0 },
441 { -1, -1, 0 },
442 { 1, 0, 1 },
443 { -1, 0, 1 },
444 { 1, 0, -1 },
445 { -1, 0, -1 },
446 { 0, 1, 1 },
447 { 0, -1, 1 },
448 { 0, 1, -1 },
449 { 0, -1, -1 }
450};
451#else
452static const uint8_t kGradients[kGradientCount][3] = {
453 { 2, 2, 1 },
454 { 0, 2, 1 },
455 { 2, 0, 1 },
456 { 0, 0, 1 },
457 { 2, 1, 2 },
458 { 0, 1, 2 },
459 { 2, 1, 0 },
460 { 0, 1, 0 },
461 { 1, 2, 2 },
462 { 1, 0, 2 },
463 { 1, 2, 0 },
464 { 1, 0, 0 }
465};
466
467/* Attempted speedup that didn't pan out, but might inspire something better.
468 Since our gradient vectors' components are all -1, 0 or 1, we should be
469 able to calculate the dot product without any multiplication at all, by
470 simply summing the right combination of (x, y, z), (0, 0, 0) and (-x, -y, -z).
471
472 This turns out to be slightly slower than using multiplication, even if
473 the negations are precalculated.
474*/
475OOINLINE float TDot3(const uint8_t grad[3], float x, float y, float z)
476{
477 float xt[3] = { -x, 0.0f, x };
478 float yt[3] = { -y, 0.0f, y };
479 float zt[3] = { -z, 0.0f, z };
480
481 return xt[grad[0]] + yt[grad[1]] + zt[grad[2]];
482}
483#endif
484
485// Sample 3D noise function defined by kGradients and permutation table at point p.
486static float SampleNoise3D(OOStandaloneAtmosphereGeneratorInfo* info, Vector p)
487{
488 uint16_t* permutations = info->permutations;
489
490 // Split coordinates into integer and fractional parts.
491 float fx = floor(p.x);
492 float fy = floor(p.y);
493 float fz = floor(p.z);
494 int X = fx;
495 int Y = fy;
496 int Z = fz;
497 float x = p.x - fx;
498 float y = p.y - fy;
499 float z = p.z - fz;
500
501 // Select gradient for each corner.
502#define PERM(v) permutations[(v) & kPermutationMask]
503
504 unsigned PZ0 = PERM(Z);
505 unsigned PZ1 = PERM(Z + 1);
506
507 unsigned PY0Z0 = PERM(Y + PZ0);
508 unsigned PY1Z0 = PERM(Y + 1 + PZ0);
509 unsigned PY0Z1 = PERM(Y + PZ1);
510 unsigned PY1Z1 = PERM(Y + 1 + PZ1);
511
512 unsigned gi000 = PERM(X + PY0Z0);
513 unsigned gi010 = PERM(X + PY1Z0);
514 unsigned gi100 = PERM(X + 1 + PY0Z0);
515 unsigned gi110 = PERM(X + 1 + PY1Z0);
516 unsigned gi001 = PERM(X + PY0Z1);
517 unsigned gi011 = PERM(X + PY1Z1);
518 unsigned gi101 = PERM(X + 1 + PY0Z1);
519 unsigned gi111 = PERM(X + 1 + PY1Z1);
520
521#undef PERM
522
523 // Calculate noise contributions from each of the eight corners.
524#if !LUT_DOT
525#define DOT3(idx, x_, y_, z_) dot_product(kGradients[(idx) % kGradientCount], (Vector) { (x_), (y_), (z_) })
526#else
527#define DOT3(idx, x_, y_, z_) TDot3(kGradients[(idx) % kGradientCount], (x_), (y_), (z_))
528#endif
529
530 float x1 = x - 1.0f;
531 float y1 = y - 1.0f;
532 float z1 = z - 1.0f;
533 float n000 = DOT3(gi000, x, y, z);
534 float n010 = DOT3(gi010, x, y1, z);
535 float n100 = DOT3(gi100, x1, y, z);
536 float n110 = DOT3(gi110, x1, y1, z);
537 float n001 = DOT3(gi001, x, y, z1);
538 float n011 = DOT3(gi011, x, y1, z1);
539 float n101 = DOT3(gi101, x1, y, z1);
540 float n111 = DOT3(gi111, x1, y1, z1);
541
542#undef DOT3
543
544 // Compute the fade curve value for each of x, y, z
545 float u = Hermite(x);
546 float v = Hermite(y);
547 float w = Hermite(z);
548
549 // Interpolate along the contributions from each of the corners.
550 float nx00 = Lerp(n000, n100, u);
551 float nx01 = Lerp(n001, n101, u);
552 float nx10 = Lerp(n010, n110, u);
553 float nx11 = Lerp(n011, n111, u);
554
555 float nxy0 = Lerp(nx00, nx10, v);
556 float nxy1 = Lerp(nx01, nx11, v);
557
558 float nxyz = Lerp(nxy0, nxy1, w);
559
560 return nxyz;
561}
562
563/* Generate shuffled permutation order - each value from 0 to
564 kPermutationCount - 1 occurs exactly once. This shuffling provides all the
565 randomness in the resulting noise. Don't worry, though - for
566 kPermutationCount = 1024 this allows for 4e2567 different noise maps,
567 which is a lot more than RanRot will actually give us.
568*/
569static BOOL MakePermutationTable(OOStandaloneAtmosphereGeneratorInfo* info)
570{
571 uint16_t* perms = malloc(sizeof *info->permutations * kPermutationCount);
572 if (EXPECT_NOT(perms == NULL))
573 return NO;
574
575 /* Fisher-Yates/Durstenfeld/Knuth shuffle, "inside-out" variant.
576 Based on pseudocode from http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
577
578 When comparing to the pseudocode, note that it generates a one-based
579 series, but this version generates a zero-based series.
580 */
581 perms[0] = 0;
582 uint16_t* curr = perms;
583 uint16_t n;
584 for (n = 1; n < kPermutationCount; n++) {
585 uint16_t j = RanrotWithSeed(&info->seed) & kPermutationMask;
586 *++curr = perms[j];
587 perms[j] = n - 1;
588 }
589
590 info->permutations = perms;
591 return YES;
592}
593
594static BOOL GenerateFBMNoise3D(OOStandaloneAtmosphereGeneratorInfo* info)
595{
596 BOOL OK = NO;
597
598 FAIL_IF(!MakePermutationTable(info));
599
600 unsigned x, y, width = info->width, height = info->height;
601 float lon, lat; // Longitude and latitude in radians.
602 float dlon = 2.0f * M_PI / width;
603 float dlat = M_PI / height;
604 float* px = info->fbmBuffer;
605
606 for (y = 0, lat = -M_PI_2; y < height; y++, lat += dlat) {
607 float las = sin(lat);
608 float lac = cos(lat);
609
610 for (x = 0, lon = -M_PI; x < width; x++, lon += dlon) {
611 // FIXME: in real life, we really don't want sin and cos per pixel.
612 // Convert spherical coordinates to vector.
613 float los = sin(lon);
614 float loc = cos(lon);
615
616 Vector p = {
617 los * lac,
618 las,
619 loc * lac
620 };
621
622#if 1
623 // fBM
624 unsigned octaveMask = 4;
625 float octave = octaveMask;
626 octaveMask -= 1;
627 float scale = 0.4f;
628 float sum = 0;
629
630 while ((octaveMask + 1) < height) {
631 Vector ps = vector_multiply_scalar(p, octave);
632 sum += scale * SampleNoise3D(info, ps);
633
634 octave *= 2.0f;
635 octaveMask = (octaveMask << 1) | 1;
636 scale *= 0.5f;
637 }
638#else
639 // Single octave
640 p = vector_multiply_scalar(p, 4.0f);
641 float sum = 0.5f * SampleNoise3D(info, p);
642#endif
643
644 *px++ = sum + 0.5f;
645 }
646 }
647
648END:
649 FREE(info->permutations);
650 return OK;
651}
652
653// Old 2D value noise.
654
655static void FillRandomBuffer(float* randomBuffer, RANROTSeed seed)
656{
657 unsigned i, len = kRandomBufferSize * kRandomBufferSize;
658 for (i = 0; i < len; i++) {
659 randomBuffer[i] = randfWithSeed(&seed);
660 }
661}
662
663static void AddNoise(OOStandaloneAtmosphereGeneratorInfo* info, float* randomBuffer, float octave, unsigned octaveMask, float scale, float* qxBuffer, int* ixBuffer)
664{
665 unsigned x, y;
666 unsigned width = info->width, height = info->height;
667 int ix, jx, iy, jy;
668 float rr = octave / width;
669 float fx, fy, qx, qy, rix, rjx, rfinal;
670 float* dst = info->fbmBuffer;
671
672 for (fy = 0, y = 0; y < height; fy++, y++) {
673 qy = fy * rr;
674 iy = fast_floor(qy);
675 jy = (iy + 1) & octaveMask;
676 qy = Hermite(qy - iy);
677 iy &= (kRandomBufferSize - 1);
678 jy &= (kRandomBufferSize - 1);
679
680 for (fx = 0, x = 0; x < width; fx++, x++) {
681 if (y == 0) {
682 // first pass: initialise buffers.
683 qx = fx * rr;
684 ix = fast_floor(qx);
685 qx -= ix;
686 ix &= (kRandomBufferSize - 1);
687 ixBuffer[x] = ix;
688 qxBuffer[x] = Hermite(qx);
689 } else {
690 // later passes: grab the stored values.
691 ix = ixBuffer[x];
692 qx = qxBuffer[x];
693 }
694
695 jx = (ix + 1) & octaveMask;
696 jx &= (kRandomBufferSize - 1);
697
698 rix = Lerp(randomBuffer[iy * kRandomBufferSize + ix], randomBuffer[iy * kRandomBufferSize + jx], qx);
699 rjx = Lerp(randomBuffer[jy * kRandomBufferSize + ix], randomBuffer[jy * kRandomBufferSize + jx], qx);
700 rfinal = Lerp(rix, rjx, qy);
701
702 *dst++ += scale * rfinal;
703 }
704 }
705}
706
707static BOOL GenerateFBMNoise(OOStandaloneAtmosphereGeneratorInfo* info)
708{
709 // Allocate the temporary buffers we need in one fell swoop, to avoid administrative overhead.
710 size_t randomBufferSize = kRandomBufferSize * kRandomBufferSize * sizeof(float);
711 size_t qxBufferSize = info->width * sizeof(float);
712 size_t ixBufferSize = info->width * sizeof(int);
713 char* sharedBuffer = malloc(randomBufferSize + qxBufferSize + ixBufferSize);
714 if (sharedBuffer == NULL)
715 return NO;
716
717 float* randomBuffer = (float*)sharedBuffer;
718 float* qxBuffer = (float*)(sharedBuffer + randomBufferSize);
719 int* ixBuffer = (int*)(sharedBuffer + randomBufferSize + qxBufferSize);
720
721 // Get us some value noise.
722 FillRandomBuffer(randomBuffer, info->seed);
723
724 // Generate basic fBM noise.
725 unsigned height = info->height;
726 unsigned octaveMask = 8 * info->planetAspectRatio;
727 float octave = octaveMask;
728 octaveMask -= 1;
729 float scale = 0.5f;
730
731 while ((octaveMask + 1) < height) {
732 AddNoise(info, randomBuffer, octave, octaveMask, scale, qxBuffer, ixBuffer);
733 octave *= 2.0f;
734 octaveMask = (octaveMask << 1) | 1;
735 scale *= 0.5f;
736 }
737
738 FREE(sharedBuffer);
739 return YES;
740}
741
742static float QFactor(float* accbuffer, int x, int y, unsigned width, float polar_y_value, float bias, float polar_y)
743{
744 float q = accbuffer[y * width + x]; // 0.0 -> 1.0
745 q += bias;
746
747 // Polar Y smooth.
748 q = q * (1.0f - polar_y) + polar_y * polar_y_value;
749
750 return q;
751}
752
753#endif // NEW_PLANETS
OOINLINE float OOClamp_0_1_f(float value) INLINE_CONST_FUNC
#define EXPECT_NOT(x)
#define OOINLINE
#define OOLog(class, format,...)
Definition OOLogging.h:84
#define M_PI_2
Definition OOMaths.h:57
#define M_PI
Definition OOMaths.h:54
struct OOPixMap OOPixMap
return nil
float y
float x
struct OOStandaloneAtmosphereGeneratorInfo OOStandaloneAtmosphereGeneratorInfo
@ kOOTextureAllowCubeMap
Definition OOTexture.h:61
@ kOOTextureDataRGBA
Definition OOTexture.h:103
OOPixMapFormat OOTextureDataFormat
Definition OOTexture.h:107
OOGraphicsDetail
Definition OOTypes.h:208
@ DETAIL_LEVEL_SHADERS
Definition OOTypes.h:211
struct Vector Vector
OOINLINE Vector vector_multiply_scalar(Vector v, OOScalar s) INLINE_CONST_FUNC
Definition OOVector.h:180
#define CLOUD_ALPHA
static FloatRGB FloatRGBFromDictColor(NSDictionary *dictionary, NSString *key)
static FloatRGB Blend(float fraction, FloatRGB a, FloatRGB b)
float blueComponent()
Definition OOColor.m:339
float redComponent()
Definition OOColor.m:329
float greenComponent()
Definition OOColor.m:334
id textureWithGenerator:(OOTextureGenerator *generator)
Definition OOTexture.m:209
typedef int(ZCALLBACK *close_file_func) OF((voidpf opaque
float randfWithSeed(RANROTSeed *ioSeed)
unsigned RanrotWithSeed(RANROTSeed *ioSeed)
struct RANROTSeed RANROTSeed
OOScalar x
Definition OOVector.h:32
OOScalar y
Definition OOVector.h:33
OOScalar z
Definition OOVector.h:34