Oolite
Loading...
Searching...
No Matches
OODefaultShaderSynthesizer.m
Go to the documentation of this file.
1/*
2
3OODefaultShaderSynthesizer.m
4
5
6Copyright © 2011-2013 Jens Ayton
7
8Permission is hereby granted, free of charge, to any person obtaining a copy
9of this software and associated documentation files (the “Software”), to deal
10in the Software without restriction, including without limitation the rights
11to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12copies of the Software, and to permit persons to whom the Software is
13furnished to do so, subject to the following conditions:
14
15The above copyright notice and this permission notice shall be included in all
16copies or substantial portions of the Software.
17
18THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24SOFTWARE.
25
26*/
27
29#import "OOColor.h"
30#import "OOMesh.h"
31#import "OOTexture.h"
32
37#import "ResourceManager.h"
38
39/*
40 * GNUstep 1.20.1 does not support NSIntegerHashCallBacks but uses
41 * NSIntHashCallBacks instead. NSIntHashCallBacks was deprecated in favor of
42 * NSIntegerHashCallBacks in GNUstep versions later than 1.20.1. If we move to
43 * a newer GNUstep version for Oolite the #define below may not be necessary
44 * anymore but for now we need it to be able to build. - Nikos 20120208.
45 */
46#if OOLITE_GNUSTEP
47#define NSIntegerHashCallBacks NSIntHashCallBacks
48#endif
49
50static NSDictionary* CanonicalizeMaterialSpecifier(NSDictionary* spec, NSString* materialKey);
51
52static NSString* FormatFloat(double value);
53
54@interface OODefaultShaderSynthesizer : NSObject {
55@private
56 NSDictionary* _configuration;
57 NSString* _materialKey;
58 NSString* _entityName;
59
60 NSString* _vertexShader;
61 NSString* _fragmentShader;
62 NSMutableArray* _textures;
63 NSMutableDictionary* _uniforms;
64
65 NSMutableString* _attributes;
66 NSMutableString* _varyings;
67 NSMutableString* _vertexUniforms;
68 NSMutableString* _fragmentUniforms;
69 NSMutableString* _vertexHelpers;
70 NSMutableString* _fragmentHelpers;
71 NSMutableString* _vertexBody;
72 NSMutableString* _fragmentPreTextures;
73 NSMutableString* _fragmentTextureLookups;
74 NSMutableString* _fragmentBody;
75
76 // _texturesByName: dictionary mapping texture file names to texture specifications.
77 NSMutableDictionary* _texturesByName;
78 // _textureIDs: dictionary mapping texture file names to numerical IDs used to name variables.
79 NSMutableDictionary* _textureIDs;
80 // _sampledTextures: hash of integer texture IDs for which we’ve set up a sample.
81 NSHashTable* _sampledTextures;
82
83 NSMutableDictionary* _uniformBindingNames;
84
85 NSUInteger _usesNormalMap : 1,
89
90 // Completion flags for various generation stages.
99 // _completedwriteNormal: 1,
105
106#ifndef NDEBUG
107 NSHashTable* _stagesInProgress;
108#endif
109}
110
111- (id)initWithMaterialConfiguration:(NSDictionary*)configuration
112 materialKey:(NSString*)materialKey
113 entityName:(NSString*)name;
114
115- (BOOL)run;
116
117- (NSString*)vertexShader;
118- (NSString*)fragmentShader;
119- (NSArray*)textureSpecifications;
120- (NSDictionary*)uniformSpecifications;
121
122- (NSString*)materialKey;
123- (NSString*)entityName;
124
125- (void)createTemporaries;
126- (void)destroyTemporaries;
127
128- (void)composeVertexShader;
129- (void)composeFragmentShader;
130
131// Write various types of declarations.
132- (void)appendVariable:(NSString*)name ofType:(NSString*)type withPrefix:(NSString*)prefix to:(NSMutableString*)buffer;
133- (void)addAttribute:(NSString*)name ofType:(NSString*)type;
134- (void)addVarying:(NSString*)name ofType:(NSString*)type;
135- (void)addVertexUniform:(NSString*)name ofType:(NSString*)type;
136- (void)addFragmentUniform:(NSString*)name ofType:(NSString*)type;
137
138// Create or retrieve a uniform variable name for a given binding.
139- (NSString*)defineBindingUniform:(NSDictionary*)binding ofType:(NSString*)type;
140
141- (NSString*)readRGBForTextureSpec:(NSDictionary*)textureSpec mapName:(NSString*)mapName; // Generate a read for an RGB value, or a single channel splatted across RGB.
142- (NSString*)readOneChannelForTextureSpec:(NSDictionary*)textureSpec mapName:(NSString*)mapName; // Generate a read for a single channel.
143
144// Details of texture setup; generally use -read*ForTextureSpec:mapName: instead.
145- (NSUInteger)textureIDForSpec:(NSDictionary*)textureSpec;
146- (void)setUpOneTexture:(NSDictionary*)textureSpec;
147- (void)getSampleName:(NSString**)outSampleName andSwizzleOp:(NSString**)outSwizzleOp forTextureSpec:(NSDictionary*)textureSpec;
148
149/* Stages. These should only be called through the REQUIRE_STAGE macro to
150 avoid duplicated code and ensure data depedencies are met.
151*/
152
153/* writeTextureCoordRead
154 Generate vec2 texCoords.
155*/
156- (void)writeTextureCoordRead;
157
158/* writeDiffuseColorTermIfNeeded
159 Generates and populates the fragment shader value vec3 diffuseColor, unless
160 the diffuse term is black. If a diffuseColor is generated, _usesDiffuseTerm
161 is set. The value will be const if possible.
162 See also: writeDiffuseColorTerm.
163*/
164- (void)writeDiffuseColorTermIfNeeded;
165
166/* writeDiffuseColorTerm
167 Generates vec3 diffuseColor unconditionally – that is, even if the diffuse
168 term is black.
169 See also: writeDiffuseColorTermIfNeeded.
170*/
171- (void)writeDiffuseColorTerm;
172
173/* writeDiffuseLighting
174 Generate the fragment variable vec3 diffuseLight and add Lambertian and
175 ambient terms to it.
176*/
177- (void)writeDiffuseLighting;
178
179/* writeLightVector
180 Generate the fragment variable vec3 lightVector (unit vector) for temporary
181 lighting. Calling this if lighting mode is kLightingUniform will cause an
182 exception.
183*/
184- (void)writeLightVector;
185
186/* writeEyeVector
187 Generate vec3 lightVector, the normalized direction from the fragment to
188 the light source.
189*/
190- (void)writeEyeVector;
191
192/* writeVertexTangentBasis
193 Generates tangent space basis matrix (TBN) in vertex shader, if in tangent-
194 space lighting mode. If not, an exeception is raised.
195*/
196- (void)writeVertexTangentBasis;
197
198/* writeNormalIfNeeded
199 Writes fragment variable vec3 normal if necessary. Otherwise, it sets
200 _constZNormal, indicating that the normal is always (0, 0, 1).
201
202 See also: writeNormal.
203*/
204- (void)writeNormalIfNeeded;
205
206/* writeNormal
207 Generates vec3 normal unconditionally – if _constZNormal is set, normal will
208 be const vec3 normal = vec3 (0.0, 0.0, 1.0).
209*/
210- (void)writeNormal;
211
212/* writeSpecularLighting
213 Calculate specular writing and add it to totalColor.
214*/
215- (void)writeSpecularLighting;
216
217/* writeLightMaps
218 Add emission and illumination maps to totalColor.
219*/
220- (void)writeLightMaps;
221
222/* writeVertexPosition
223 Calculate vertex position and write it to gl_Position.
224*/
225- (void)writeVertexPosition;
226
227/* writeTotalColor
228 Generate vec3 totalColor, the accumulator for output colour values.
229*/
230- (void)writeTotalColor;
231
232/* writeFinalColorComposite
233 This stage writes the final fragment shader. It also pulls in other stages
234 through dependencies.
235*/
236- (void)writeFinalColorComposite;
237
238/*
239 REQUIRE_STAGE(): pull in the required stage. A stage must have a
240 zero-parameter method and a matching _completed_stage instance variable.
241
242 In debug/testrelease builds, this dispatches through performStage: which
243 checks for recursive calls.
244*/
245#ifndef NDEBUG
246#define REQUIRE_STAGE(NAME) \
247 if (!_completed_##NAME) { \
248 [self performStage:@selector(NAME)]; \
249 _completed_##NAME = YES; \
250 }
251- (void)performStage:(SEL)stage;
252#else
253#define REQUIRE_STAGE(NAME) \
254 if (!_completed_##NAME) { \
255 [self NAME]; \
256 _completed_##NAME = YES; \
257 }
258#endif
259
260@end
261
262static NSString* GetExtractMode(NSDictionary* textureSpecifier);
263
264BOOL OOSynthesizeMaterialShader(NSDictionary* configuration, NSString* materialKey, NSString* entityName, NSString** outVertexShader, NSString** outFragmentShader, NSArray** outTextureSpecs, NSDictionary** outUniformSpecs)
265{
266 NSCParameterAssert(configuration != nil && outVertexShader != NULL && outFragmentShader != NULL && outTextureSpecs != NULL && outUniformSpecs != NULL);
267
268 NSAutoreleasePool* pool = [NSAutoreleasePool new];
269
271 initWithMaterialConfiguration:configuration
272 materialKey:materialKey
273 entityName:entityName];
274 [synthesizer autorelease];
275
276 BOOL OK = [synthesizer run];
277 if (OK) {
278 *outVertexShader = [[synthesizer vertexShader] retain];
279 *outFragmentShader = [[synthesizer fragmentShader] retain];
280 *outTextureSpecs = [[synthesizer textureSpecifications] retain];
281 *outUniformSpecs = [[synthesizer uniformSpecifications] retain];
282 } else {
283 *outVertexShader = nil;
284 *outFragmentShader = nil;
285 *outTextureSpecs = nil;
286 *outUniformSpecs = nil;
287 }
288
289 [pool release];
290
291 [*outVertexShader autorelease];
292 [*outFragmentShader autorelease];
293 [*outTextureSpecs autorelease];
294 [*outUniformSpecs autorelease];
295
296 return YES;
297}
298
299@implementation OODefaultShaderSynthesizer
300
301- (id)initWithMaterialConfiguration:(NSDictionary*)configuration
302 materialKey:(NSString*)materialKey
303 entityName:(NSString*)name
304{
305 if ((self = [super init])) {
306 _configuration = [CanonicalizeMaterialSpecifier(configuration, materialKey) retain];
307 _materialKey = [materialKey copy];
308 _entityName = [_entityName copy];
309 }
310
311 return self;
312}
313
314- (void)dealloc
315{
316 [self destroyTemporaries];
323
324 [super dealloc];
325}
326
327- (NSString*)vertexShader
328{
329 return _vertexShader;
330}
331
332- (NSString*)fragmentShader
333{
334 return _fragmentShader;
335}
336
338{
339#ifndef NDEBUG
340 return [NSArray arrayWithArray:_textures];
341#else
342 return _textures;
343#endif
344}
345
346- (NSDictionary*)uniformSpecifications
347{
348#ifndef NDEBUG
349 return [NSDictionary dictionaryWithDictionary:_uniforms];
350#else
351 return _uniforms;
352#endif
353}
354
355- (BOOL)run
356{
357 [self createTemporaries];
358 _uniforms = [[NSMutableDictionary alloc] init];
359 [_vertexBody appendString:@"void main(void)\n{\n"];
360 [_fragmentPreTextures appendString:@"void main(void)\n{\n"];
361
362 @try {
364
365 [self composeVertexShader];
367 }
368 @catch (NSException* exception) {
369 // Error should have been reported already.
370 return NO;
371 }
372 @finally {
373 [self destroyTemporaries];
374 }
375
376 return YES;
377}
378
379- (NSString*)materialKey
380{
381 return _materialKey;
382}
383
384- (NSString*)entityName
385{
386 return _entityName;
387}
388
389// MARK: - Utilities
390
391static void AppendIfNotEmpty(NSMutableString* buffer, NSString* segment, NSString* name)
392{
393 if ([segment length] > 0) {
394 if ([buffer length] > 0)
395 [buffer appendString:@"\n\n"];
396 if ([name length] > 0)
397 [buffer appendFormat:@"// %@\n", name];
398 [buffer appendString:segment];
399 }
400}
401
402static NSString* GetExtractMode(NSDictionary* textureSpecifier)
403{
404 NSString* result = nil;
405
406 NSString* rawMode = [textureSpecifier oo_stringForKey:kOOTextureSpecifierSwizzleKey];
407 if (rawMode != nil) {
408 NSUInteger length = [rawMode length];
409 if (1 <= length && length <= 4) {
410 static NSCharacterSet* nonRGBACharset = nil;
411 if (nonRGBACharset == nil) {
412 nonRGBACharset = [[[NSCharacterSet characterSetWithCharactersInString:@"rgba"] invertedSet] retain];
413 }
414
415 if ([rawMode rangeOfCharacterFromSet:nonRGBACharset].location == NSNotFound) {
416 result = rawMode;
417 }
418 }
419 }
420
421 return result;
422}
423
424- (void)appendVariable:(NSString*)name ofType:(NSString*)type withPrefix:(NSString*)prefix to:(NSMutableString*)buffer
425{
426 NSUInteger typeDeclLength = [prefix length] + [type length] + 1;
427 NSUInteger padding = (typeDeclLength < 20) ? (23 - typeDeclLength) / 4 : 1;
428 [buffer appendFormat:@"%@ %@%@%@;\n", prefix, type, OOTabString(padding), name];
429}
430
431- (void)addAttribute:(NSString*)name ofType:(NSString*)type
432{
433 [self appendVariable:name ofType:type withPrefix:@"attribute" to:_attributes];
434}
435
436- (void)addVarying:(NSString*)name ofType:(NSString*)type
437{
438 [self appendVariable:name ofType:type withPrefix:@"varying" to:_varyings];
439}
440
441- (void)addVertexUniform:(NSString*)name ofType:(NSString*)type
442{
443 [self appendVariable:name ofType:type withPrefix:@"uniform" to:_vertexUniforms];
444}
445
446- (void)addFragmentUniform:(NSString*)name ofType:(NSString*)type
447{
448 [self appendVariable:name ofType:type withPrefix:@"uniform" to:_fragmentUniforms];
449}
450
451- (NSString*)defineBindingUniform:(NSDictionary*)binding ofType:(NSString*)type
452{
453 NSString* name = [binding oo_stringForKey:@"binding"];
454 NSParameterAssert([name length] > 0);
455
456 NSMutableDictionary* bindingSpec = [[binding mutableCopy] autorelease];
457 if ([bindingSpec oo_stringForKey:@"type"] == nil)
458 [bindingSpec setObject:@"binding" forKey:@"type"];
459
460 // Use existing uniform if one is defined.
461 NSString* uniformName = [_uniformBindingNames objectForKey:bindingSpec];
462 if (uniformName != nil)
463 return uniformName;
464
465 // Capitalize first char of name, and prepend u.
466 unichar firstChar = toupper([name characterAtIndex:0]);
467 NSString* baseName = [NSString stringWithFormat:@"u%C%@", firstChar, [name substringFromIndex:1]];
468
469 // Ensure name is unique.
470 name = baseName;
471 unsigned idx = 1;
472 while ([_uniforms objectForKey:name] != nil) {
473 name = [NSString stringWithFormat:@"%@%u", baseName, ++idx];
474 }
475
476 [self addFragmentUniform:name ofType:type];
477
478 [_uniforms setObject:bindingSpec forKey:name];
479 [_uniformBindingNames setObject:name forKey:bindingSpec];
480
481 return name;
482}
483
485{
486 while ([_vertexBody hasSuffix:@"\t\n"]) {
487 [_vertexBody deleteCharactersInRange:(NSRange) { [_vertexBody length] - 2, 2 }];
488 }
489 [_vertexBody appendString:@"}"];
490
491 NSMutableString* vertexShader = [NSMutableString string];
495 AppendIfNotEmpty(vertexShader, _vertexHelpers, @"Helper functions");
497
498#ifndef NDEBUG
499 _vertexShader = [vertexShader copy];
500#else
501 _vertexShader = [vertexShader retain];
502#endif
503}
504
506{
507 while ([_fragmentBody hasSuffix:@"\t\n"]) {
508 [_fragmentBody deleteCharactersInRange:(NSRange) { [_fragmentBody length] - 2, 2 }];
509 }
510
511 NSMutableString* fragmentShader = [NSMutableString string];
514 AppendIfNotEmpty(fragmentShader, _fragmentHelpers, @"Helper functions");
516 if ([_fragmentTextureLookups length] > 0) {
517 [fragmentShader appendString:@"\t\n\t// Texture lookups\n"];
518 [fragmentShader appendString:_fragmentTextureLookups];
519 }
520 [fragmentShader appendString:@"\t\n"];
521 [fragmentShader appendString:_fragmentBody];
522 [fragmentShader appendString:@"}"];
523
524#ifndef NDEBUG
525 _fragmentShader = [fragmentShader copy];
526#else
527 _fragmentShader = [fragmentShader retain];
528#endif
529}
530
531/*
532 Build a key for a texture specifier, taking all texture configuration
533 options into account and ignoring the other stuff that might be there.
534
535 FIXME: efficiency and stuff.
536*/
537static NSString* KeyFromTextureParameters(NSString* name, OOTextureFlags options, float anisotropy, float lodBias)
538{
539#ifndef NDEBUG
540 options = OOApplyTextureOptionDefaults(options);
541#endif
542
543 // Extraction modes are ignored in synthesized shaders, since we use swizzling instead.
545
546 return [NSString stringWithFormat:@"%@:%X:%g:%g", name, options, anisotropy, lodBias];
547}
548
549static NSString* KeyFromTextureSpec(NSDictionary* spec)
550{
551 NSString* texName = nil;
552 OOTextureFlags texOptions;
553 float anisotropy, lodBias;
554 if (!OOInterpretTextureSpecifier(spec, &texName, &texOptions, &anisotropy, &lodBias, YES)) {
555 // OOInterpretTextureSpecifier() will have logged something.
556 [NSException raise:NSGenericException format:@"Invalid texture specifier"];
557 }
558
559 return KeyFromTextureParameters(texName, texOptions, anisotropy, lodBias);
560}
561
562- (NSUInteger)assignIDForTexture:(NSDictionary*)spec
563{
564 NSParameterAssert(spec != nil);
565
566 // extract_channel doesn't affect uniqueness, and we don't want OOTexture to do actual extraction.
567 if ([spec objectForKey:kOOTextureSpecifierSwizzleKey] != nil) {
568 spec = [spec dictionaryByRemovingObjectForKey:kOOTextureSpecifierSwizzleKey];
569 }
570
571 NSString* texName = nil;
572 OOTextureFlags texOptions;
573 float anisotropy, lodBias;
574 if (!OOInterpretTextureSpecifier(spec, &texName, &texOptions, &anisotropy, &lodBias, YES)) {
575 // OOInterpretTextureSpecifier() will have logged something.
576 [NSException raise:NSGenericException format:@"Invalid texture specifier"];
577 }
578
579 if (texOptions & kOOTextureAllowCubeMap) {
580 // cube_map = true; fail regardless of whether actual texture qualifies.
581 OOLogERR(@"material.synthesis.error.cubeMap", @"The material \"%@\" of \"%@\" specifies a cube map texture, but doesn't have custom shaders. Cube map textures are not supported with the default shaders.", [self materialKey], [self entityName]);
582 [NSException raise:NSGenericException format:@"Invalid material"];
583 }
584
585 NSString* key = KeyFromTextureParameters(texName, texOptions, anisotropy, lodBias);
586 NSUInteger texID;
587 NSObject* existing = [_texturesByName objectForKey:key];
588 if (existing == nil) {
589 texID = [_texturesByName count];
590 NSNumber* texIDObj = [NSNumber numberWithUnsignedInteger:texID];
591 NSString* texUniform = [NSString stringWithFormat:@"uTexture%zu", texID];
592
593#ifndef NDEBUG
594 BOOL useInternalFormat = NO;
595#else
596 BOOL useInternalFormat = YES;
597#endif
598
599 [_textures addObject:OOMakeTextureSpecifier(texName, texOptions, anisotropy, lodBias, useInternalFormat)];
600 [_texturesByName setObject:spec forKey:key];
601 [_textureIDs setObject:texIDObj forKey:key];
602 [_uniforms setObject:[NSDictionary dictionaryWithObjectsAndKeys:@"texture", @"type", texIDObj, @"value", nil]
603 forKey:texUniform];
604
605 [self addFragmentUniform:texUniform ofType:@"sampler2D"];
606 } else {
607 texID = [_textureIDs oo_unsignedIntegerForKey:texName];
608 }
609
610 return texID;
611}
612
613- (NSUInteger)textureIDForSpec:(NSDictionary*)textureSpec
614{
615 return [_textureIDs oo_unsignedIntegerForKey:KeyFromTextureSpec(textureSpec)];
616}
617
618- (void)setUpOneTexture:(NSDictionary*)textureSpec
619{
620 if (textureSpec == nil)
621 return;
622
624
625 NSUInteger texID = [self assignIDForTexture:textureSpec];
626 if ((NSUInteger)NSHashGet(_sampledTextures, (const void*)(texID + 1)) == 0) {
627 NSHashInsertKnownAbsent(_sampledTextures, (const void*)(texID + 1));
628 [_fragmentTextureLookups appendFormat:@"\tvec4 tex%zuSample = texture2D(uTexture%zu, texCoords); // %@\n", texID, texID, [textureSpec oo_stringForKey:kOOTextureSpecifierNameKey]];
629 }
630}
631
632- (void)getSampleName:(NSString**)outSampleName andSwizzleOp:(NSString**)outSwizzleOp forTextureSpec:(NSDictionary*)textureSpec
633{
634 NSParameterAssert(outSampleName != NULL && outSwizzleOp != NULL && textureSpec != nil);
635
636 [self setUpOneTexture:textureSpec];
637 NSUInteger texID = [self textureIDForSpec:textureSpec];
638
639 *outSampleName = [NSString stringWithFormat:@"tex%zuSample", texID];
640 *outSwizzleOp = GetExtractMode(textureSpec);
641}
642
643- (NSString*)readRGBForTextureSpec:(NSDictionary*)textureSpec mapName:(NSString*)mapName
644{
645 NSString *sample, *swizzle;
646 [self getSampleName:&sample andSwizzleOp:&swizzle forTextureSpec:textureSpec];
647
648 if (swizzle == nil) {
649 return [sample stringByAppendingString:@".rgb"];
650 }
651
652 NSUInteger channelCount = [swizzle length];
653
654 if (channelCount == 1) {
655 return [NSString stringWithFormat:@"%@.%@%@%@", sample, swizzle, swizzle, swizzle];
656 } else if (channelCount == 3) {
657 return [NSString stringWithFormat:@"%@.%@", sample, swizzle];
658 }
659
660 OOLogWARN(@"material.synthesis.warning.extractionMismatch", @"The %@ map for material \"%@\" of \"%@\" specifies %zu channels to extract, but only %@ may be used.", mapName, [self materialKey], [self entityName], channelCount, @"1 or 3");
661 return nil;
662}
663
664- (NSString*)readOneChannelForTextureSpec:(NSDictionary*)textureSpec mapName:(NSString*)mapName
665{
666 NSString *sample, *swizzle;
667 [self getSampleName:&sample andSwizzleOp:&swizzle forTextureSpec:textureSpec];
668
669 if (swizzle == nil) {
670 return [sample stringByAppendingString:@".r"];
671 }
672
673 NSUInteger channelCount = [swizzle length];
674
675 if (channelCount == 1) {
676 return [NSString stringWithFormat:@"%@.%@", sample, swizzle];
677 }
678
679 OOLogWARN(@"material.synthesis.warning.extractionMismatch", @"The %@ map for material \"%@\" of \"%@\" specifies %zu channels to extract, but only %@ may be used.", mapName, [self materialKey], [self entityName], channelCount, @"1");
680 return nil;
681}
682
683#ifndef NDEBUG
684- (void)performStage:(SEL)stage
685{
686 // Ensure that we aren’t recursing.
687 if (NSHashGet(_stagesInProgress, stage) != NULL) {
688 OOLogERR(@"material.synthesis.error.recursion", @"Shader synthesis recursion for stage %@.", NSStringFromSelector(stage));
689 [NSException raise:NSInternalInconsistencyException format:@"stage recursion"];
690 }
691
692 NSHashInsertKnownAbsent(_stagesInProgress, stage);
693
694 [self performSelector:stage];
695
696 NSHashRemove(_stagesInProgress, stage);
697}
698#endif
699
701{
702 _attributes = [[NSMutableString alloc] init];
703 _varyings = [[NSMutableString alloc] init];
704 _vertexUniforms = [[NSMutableString alloc] init];
705 _fragmentUniforms = [[NSMutableString alloc] init];
706 _vertexHelpers = [[NSMutableString alloc] init];
707 _fragmentHelpers = [[NSMutableString alloc] init];
708 _vertexBody = [[NSMutableString alloc] init];
709 _fragmentPreTextures = [[NSMutableString alloc] init];
711 _fragmentBody = [[NSMutableString alloc] init];
712
713 _textures = [[NSMutableArray alloc] init];
714 _texturesByName = [[NSMutableDictionary alloc] init];
715 _textureIDs = [[NSMutableDictionary alloc] init];
716 _sampledTextures = NSCreateHashTable(NSIntegerHashCallBacks, 0);
717
719
720#ifndef NDEBUG
721 _stagesInProgress = NSCreateHashTable(NSNonOwnedPointerHashCallBacks, 0);
722#endif
723}
724
726{
737
740 if (_sampledTextures != NULL) {
741 NSFreeHashTable(_sampledTextures);
742 _sampledTextures = NULL;
743 }
744
746
747#ifndef NDEBUG
748 if (_stagesInProgress != NULL) {
749 NSFreeHashTable(_stagesInProgress);
750 _stagesInProgress = NULL;
751 }
752#endif
753}
754
755// MARK: - Synthesis stages
756
758{
759 [self addVarying:@"vTexCoords" ofType:@"vec2"];
760 [_vertexBody appendString:@"\tvTexCoords = gl_MultiTexCoord0.st;\n\t\n"];
761
762 BOOL haveTexCoords = NO;
763 NSDictionary* parallaxMap = [_configuration oo_parallaxMapSpecifier];
764
765 if (parallaxMap != nil) {
766 float parallaxScale = [_configuration oo_parallaxScale];
767 if (parallaxScale != 0.0f) {
768 /*
769 We can’t call -getSampleName:... here because the standard
770 texture loading mechanism has to occur after determining
771 texture coordinates (duh).
772 */
773 NSString* swizzle = GetExtractMode(parallaxMap) ?: (NSString*)@"a";
774 NSUInteger channelCount = [swizzle length];
775 if (channelCount == 1) {
776 haveTexCoords = YES;
777
779
780 [_fragmentPreTextures appendString:@"\t// Parallax mapping\n"];
781
782 NSUInteger texID = [self assignIDForTexture:parallaxMap];
783 [_fragmentPreTextures appendFormat:@"\tfloat parallax = texture2D(uTexture%zu, vTexCoords).%@;\n", texID, swizzle];
784
785 if (parallaxScale != 1.0f) {
786 [_fragmentPreTextures appendFormat:@"\tparallax *= %@; // Parallax scale\n", FormatFloat(parallaxScale)];
787 }
788
789 float parallaxBias = [_configuration oo_parallaxBias];
790 if (parallaxBias != 0.0) {
791 [_fragmentPreTextures appendFormat:@"\tparallax += %@; // Parallax bias\n", FormatFloat(parallaxBias)];
792 }
793
794 [_fragmentPreTextures appendString:@"\tvec2 texCoords = vTexCoords - parallax * eyeVector.xy * vec2(1.0, -1.0);\n"];
795 } else {
796 OOLogWARN(@"material.synthesis.warning.extractionMismatch", @"The %@ map for material \"%@\" of \"%@\" specifies %zu channels to extract, but only %@ may be used.", @"parallax", [self materialKey], [self entityName], channelCount, @"1");
797 }
798 }
799 }
800
801 if (!haveTexCoords) {
802 [_fragmentPreTextures appendString:@"\tvec2 texCoords = vTexCoords;\n"];
803 }
804}
805
807{
808 NSDictionary* diffuseMap = [_configuration oo_diffuseMapSpecifierWithDefaultName:[self materialKey]];
809 OOColor* diffuseColor = [_configuration oo_diffuseColor] ?: [OOColor whiteColor];
810
811 if ([diffuseColor isBlack])
812 return;
813 _usesDiffuseTerm = YES;
814
815 BOOL haveDiffuseColor = NO;
816 if (diffuseMap != nil) {
817 NSString* readInstr = [self readRGBForTextureSpec:diffuseMap mapName:@"diffuse"];
818 if (EXPECT_NOT(readInstr == nil)) {
819 [_fragmentBody appendString:@"\t// INVALID EXTRACTION KEY\n\t\n"];
820 } else {
821 [_fragmentBody appendFormat:@"\tvec3 diffuseColor = %@;\n", readInstr];
822 haveDiffuseColor = YES;
823 }
824 }
825
826 if (!haveDiffuseColor || ![diffuseColor isWhite]) {
827 float rgba[4];
828 [diffuseColor getRed:&rgba[0] green:&rgba[1] blue:&rgba[2] alpha:&rgba[3]];
829 NSString* format = nil;
830 if (haveDiffuseColor) {
831 format = @"\tdiffuseColor *= vec3(%@, %@, %@);\n";
832 } else {
833 format = @"\tconst vec3 diffuseColor = vec3(%@, %@, %@);\n";
834 haveDiffuseColor = YES;
835 }
836 [_fragmentBody appendFormat:format, FormatFloat(rgba[0]), FormatFloat(rgba[1]), FormatFloat(rgba[2])];
837 }
838
839 (void)haveDiffuseColor;
840 [_fragmentBody appendString:@"\t\n"];
841}
842
844{
846
847 if (!_usesDiffuseTerm) {
848 [_fragmentBody appendString:@"\tconst vec3 diffuseColor = vec3(0.0); // Diffuse colour is black.\n\t\n"];
849 }
850}
851
853{
855 if (!_usesDiffuseTerm)
856 return;
857
862
863 // FIXME: currently uncoloured diffuse and ambient lighting.
864 NSString* normalDotLight = _constZNormal ? @"lightVector.z" : @"dot(normal, lightVector)";
865
866 [_fragmentBody appendFormat:
867 @"\t// Diffuse (Lambertian) and ambient lighting\n"
868 "\tvec3 diffuseLight = (gl_LightSource[1].diffuse * max(0.0, %@) + gl_LightModel.ambient).rgb;\n\t\n",
869 normalDotLight];
870
871 _haveDiffuseLight = YES;
872}
873
875{
878
879 [self addVarying:@"vLightVector" ofType:@"vec3"];
880
881 [_vertexBody appendString:
882 @"\tvec3 lightVector = gl_LightSource[1].position.xyz;\n"
883 "\tvLightVector = lightVector * TBN;\n\t\n"];
884 [_fragmentBody appendFormat:@"\tvec3 lightVector = normalize(vLightVector);\n\t\n"];
885}
886
888{
891
892 [self addVarying:@"vEyeVector" ofType:@"vec3"];
893
894 [_vertexBody appendString:@"\tvEyeVector = position.xyz * TBN;\n\t\n"];
895 [_fragmentPreTextures appendString:@"\tvec3 eyeVector = normalize(vEyeVector);\n\t\n"];
896}
897
899{
900 [self addAttribute:@"tangent" ofType:@"vec3"];
901
902 [_vertexBody appendString:
903 @"\t// Build tangent space basis\n"
904 "\tvec3 n = gl_NormalMatrix * gl_Normal;\n"
905 "\tvec3 t = gl_NormalMatrix * tangent;\n"
906 "\tvec3 b = cross(n, t);\n"
907 "\tmat3 TBN = mat3(t, b, n);\n\t\n"];
908}
909
911{
914
915 NSDictionary* normalMap = [_configuration oo_normalMapSpecifier];
916 if (normalMap == nil) {
917 // FIXME: this stuff should be handled in OOMaterialSpecifier.m when synthesizer takes over the world. -- Ahruman 2012-02-08
918 normalMap = [_configuration oo_normalAndParallaxMapSpecifier];
919 }
920 if (normalMap != nil) {
921 NSString *sample, *swizzle;
922 [self getSampleName:&sample andSwizzleOp:&swizzle forTextureSpec:normalMap];
923 if (swizzle == nil)
924 swizzle = @"rgb";
925 if ([swizzle length] == 3) {
926 [_fragmentBody appendFormat:@"\tvec3 normal = normalize(%@.%@ - 0.5);\n\t\n", sample, swizzle];
927 _usesNormalMap = YES;
928 return;
929 } else {
930 OOLogWARN(@"material.synthesis.warning.extractionMismatch", @"The %@ map for material \"%@\" of \"%@\" specifies %zu channels to extract, but only %@ may be used.", @"normal", [self materialKey], [self entityName], [swizzle length], @"3");
931 }
932 }
933 _constZNormal = YES;
934}
935
937{
939
940 if (_constZNormal) {
941 [_fragmentBody appendString:@"\tconst vec3 normal = vec3(0.0, 0.0, 1.0);\n\t\n"];
942 }
943}
944
946{
947 float specularExponent = [_configuration oo_specularExponent];
948 if (specularExponent <= 0)
949 return;
950
951 NSDictionary* specularColorMap = [_configuration oo_specularColorMapSpecifier];
952 NSDictionary* specularExponentMap = [_configuration oo_specularExponentMapSpecifier];
953 float scaleFactor = 1.0f;
954
955 if (specularColorMap) {
956 scaleFactor = [specularColorMap oo_doubleForKey:kOOTextureSpecifierScaleFactorKey defaultValue:1.0f];
957 }
958
959 OOColor* specularColor = nil;
960 if (specularColorMap == nil) {
961 specularColor = [_configuration oo_specularColor];
962 } else {
963 specularColor = [_configuration oo_specularModulateColor];
964 }
965
966 if ([specularColor isBlack])
967 return;
968
969 BOOL modulateWithDiffuse = [specularColorMap oo_boolForKey:kOOTextureSpecifierSelfColorKey];
970
975 if (modulateWithDiffuse) {
977 }
978
979 [_fragmentBody appendString:@"\t// Specular (Blinn-Phong) lighting\n"];
980
981 BOOL haveSpecularColor = NO;
982 if (specularColorMap != nil) {
983 NSString* readInstr = [self readRGBForTextureSpec:specularColorMap mapName:@"specular colour"];
984 if (EXPECT_NOT(readInstr == nil)) {
985 [_fragmentBody appendString:@"\t// INVALID EXTRACTION KEY\n\t\n"];
986 return;
987 }
988
989 [_fragmentBody appendFormat:@"\tvec3 specularColor = %@;\n", readInstr];
990 haveSpecularColor = YES;
991 }
992
993 if (!haveSpecularColor || ![specularColor isWhite]) {
994 float rgba[4];
995 [specularColor getRed:&rgba[0] green:&rgba[1] blue:&rgba[2] alpha:&rgba[3]];
996
997 NSString* comment = (scaleFactor == 1.0f) ? @"Constant colour" : @"Constant colour and scale factor";
998
999 // Handle scale factor, colour, and colour alpha scaling as one multiply.
1000 scaleFactor *= rgba[3];
1001 rgba[0] *= scaleFactor;
1002 rgba[1] *= scaleFactor;
1003 rgba[2] *= scaleFactor;
1004
1005 // Avoid reapplying scaleFactor below.
1006 scaleFactor = 1.0;
1007
1008 NSString* format = nil;
1009 if (haveSpecularColor) {
1010 format = @"\tspecularColor *= vec3(%@, %@, %@); // %@\n";
1011 } else {
1012 format = @"\tvec3 specularColor = vec3(%@, %@, %@); // %@\n";
1013 haveSpecularColor = YES;
1014 }
1015 [_fragmentBody appendFormat:format, FormatFloat(rgba[0]), FormatFloat(rgba[1]), FormatFloat(rgba[2]), comment];
1016 }
1017
1018 // Handle scale_factor if no constant colour.
1019 if (haveSpecularColor && scaleFactor != 1.0f) {
1020 [_fragmentBody appendFormat:@"\tspecularColor *= %@; // Scale factor\n", FormatFloat(scaleFactor)];
1021 }
1022
1023 // Handle self_color.
1024 if (modulateWithDiffuse) {
1025 [_fragmentBody appendString:@"\tspecularColor *= diffuseColor; // Self-colouring\n"];
1026 }
1027
1028 // Specular exponent.
1029 BOOL haveSpecularExponent = NO;
1030 if (specularExponentMap != nil) {
1031 NSString* readInstr = [self readOneChannelForTextureSpec:specularExponentMap mapName:@"specular exponent"];
1032 if (EXPECT_NOT(readInstr == nil)) {
1033 [_fragmentBody appendString:@"\t// INVALID EXTRACTION KEY\n\t\n"];
1034 return;
1035 }
1036
1037 [_fragmentBody appendFormat:@"\tfloat specularExponent = %@ * %.1f;\n", readInstr, specularExponent];
1038 haveSpecularExponent = YES;
1039 }
1040 if (!haveSpecularExponent) {
1041 [_fragmentBody appendFormat:@"\tconst float specularExponent = %.1f;\n", specularExponent];
1042 }
1043
1044 if (_usesNormalMap) {
1045 [_fragmentBody appendFormat:@"\tvec3 reflection = reflect(lightVector, normal);\n"];
1046 } else {
1047 /* reflect(I, N) is defined as I - 2 * dot(N, I) * N
1048 If N is (0,0,1), this becomes (I.x,I.y,-I.z).
1049 */
1050 [_fragmentBody appendFormat:@"\tvec3 reflection = vec3(lightVector.x, lightVector.y, -lightVector.z); // Equivalent to reflect(lightVector, normal) since normal is known to be (0, 0, 1) in tangent space.\n"];
1051 }
1052
1053 [_fragmentBody appendFormat:
1054 @"\tfloat specIntensity = dot(reflection, eyeVector);\n"
1055 "\tspecIntensity = pow(max(0.0, specIntensity), specularExponent);\n"
1056 "\ttotalColor += specIntensity * specularColor * gl_LightSource[1].specular.rgb;\n\t\n"];
1057}
1058
1060{
1061 NSArray* lightMaps = [_configuration oo_arrayForKey:kOOMaterialLightMapsName];
1062 NSUInteger idx, count = [lightMaps count];
1063 if (count == 0)
1064 return;
1065
1067
1068 // Check if we need the diffuse colour term.
1069 for (idx = 0; idx < count; idx++) {
1070 NSDictionary* lightMapSpec = [lightMaps oo_dictionaryAtIndex:idx];
1071 if ([lightMapSpec oo_boolForKey:kOOTextureSpecifierIlluminationModeKey]) {
1074 break;
1075 }
1076 }
1077
1078 [_fragmentBody appendString:@"\tvec3 lightMapColor;\n"];
1079
1080 for (idx = 0; idx < count; idx++) {
1081 NSDictionary* lightMapSpec = [lightMaps oo_dictionaryAtIndex:idx];
1082 NSDictionary* textureSpec = OOTextureSpecFromObject(lightMapSpec, nil);
1083 NSArray* color = [lightMapSpec oo_arrayForKey:kOOTextureSpecifierModulateColorKey];
1084 float rgba[4] = { 1.0f, 1.0f, 1.0f, 1.0f };
1085 BOOL isIllumination = [lightMapSpec oo_boolForKey:kOOTextureSpecifierIlluminationModeKey];
1086
1087 if (EXPECT_NOT(color == nil && textureSpec == nil)) {
1088 [_fragmentBody appendString:@"\t// Light map with neither colour nor texture has no effect.\n\t\n"];
1089 continue;
1090 }
1091
1092 if (color != nil) {
1093 NSUInteger idx, count = [color count];
1094 if (count > 4)
1095 count = 4;
1096 for (idx = 0; idx < count; idx++) {
1097 rgba[idx] = [color oo_doubleAtIndex:idx];
1098 }
1099 rgba[0] *= rgba[3];
1100 rgba[1] *= rgba[3];
1101 rgba[2] *= rgba[3];
1102 }
1103
1104 if (EXPECT_NOT((rgba[0] == 0.0f && rgba[1] == 0.0f && rgba[2] == 0.0f) || (!_usesDiffuseTerm && isIllumination))) {
1105 [_fragmentBody appendString:@"\t// Light map tinted black has no effect.\n\t\n"];
1106 continue;
1107 }
1108
1109 if (textureSpec != nil) {
1110 NSString* readInstr = [self readRGBForTextureSpec:textureSpec mapName:@"light"];
1111 if (EXPECT_NOT(readInstr == nil)) {
1112 [_fragmentBody appendString:@"\t// INVALID EXTRACTION KEY\n\n"];
1113 continue;
1114 }
1115
1116 [_fragmentBody appendFormat:@"\tlightMapColor = %@;\n", readInstr];
1117
1118 if (rgba[0] != 1.0f || rgba[1] != 1.0f || rgba[2] != 1.0f) {
1119 [_fragmentBody appendFormat:@"\tlightMapColor *= vec3(%@, %@, %@);\n", FormatFloat(rgba[0]), FormatFloat(rgba[1]), FormatFloat(rgba[2])];
1120 }
1121 } else {
1122 [_fragmentBody appendFormat:@"\tlightMapColor = vec3(%@, %@, %@);\n", FormatFloat(rgba[0]), FormatFloat(rgba[1]), FormatFloat(rgba[2])];
1123 }
1124
1125 NSDictionary* binding = [textureSpec oo_dictionaryForKey:kOOTextureSpecifierBindingKey];
1126 if (binding != nil) {
1127 NSString* bindingName = [binding oo_stringForKey:@"binding"];
1128 NSDictionary* typeDict = [[ResourceManager shaderBindingTypesDictionary] oo_dictionaryForKey:@"player"]; // FIXME: select appropriate binding subset.
1129 NSString* bindingType = [typeDict oo_stringForKey:bindingName];
1130 NSString* glslType = nil;
1131 NSString* swizzle = @"";
1132
1133 if ([bindingType isEqualToString:@"float"]) {
1134 glslType = @"float";
1135 } else if ([bindingType isEqualToString:@"vector"]) {
1136 glslType = @"vec3";
1137 } else if ([bindingType isEqualToString:@"color"]) {
1138 glslType = @"vec4";
1139 swizzle = @".rgb";
1140 }
1141
1142 if (glslType != nil) {
1143 NSString* uniformName = [self defineBindingUniform:binding ofType:bindingType];
1144 [_fragmentBody appendFormat:@"\tlightMapColor *= %@%@;\n", uniformName, swizzle];
1145 } else {
1146 if (bindingType == nil) {
1147 OOLogERR(@"material.binding.error.unknown", @"Cannot bind light map to unknown attribute \"%@\".", bindingName);
1148 } else {
1149 OOLogERR(@"material.binding.error.badType", @"Cannot bind light map to attribute \"%@\" of type %@.", bindingName, bindingType);
1150 }
1151 [_fragmentBody appendString:@"\tlightMapColor = vec3(0.0); // Bad binding, see log.\n"];
1152 }
1153 }
1154
1155 if (!isIllumination) {
1156 [_fragmentBody appendString:@"\ttotalColor += lightMapColor;\n\t\n"];
1157 } else {
1158 [_fragmentBody appendString:@"\tdiffuseLight += lightMapColor;\n\t\n"];
1159 }
1160 }
1161}
1162
1164{
1165 [_vertexBody appendString:
1166 @"\tvec4 position = gl_ModelViewMatrix * gl_Vertex;\n"
1167 "\tgl_Position = gl_ProjectionMatrix * position;\n\t\n"];
1168}
1169
1171{
1172 [_fragmentPreTextures appendString:@"\tvec3 totalColor = vec3(0.0);\n\t\n"];
1173}
1174
1176{
1177 REQUIRE_STAGE(writeTotalColor); // Needed even if none of the following stages does anything.
1181
1182 if (_haveDiffuseLight) {
1183 [_fragmentBody appendString:@"\ttotalColor += diffuseColor * diffuseLight;\n"];
1184 }
1185
1186 [_fragmentBody appendString:@"\tgl_FragColor = vec4(totalColor, 1.0);\n\t\n"];
1187}
1188
1189@end
1190
1191/*
1192 Convert any legacy properties and simplified forms in a material specifier
1193 to the standard form.
1194
1195 FIXME: this should be done up front in OOShipRegistry. When doing that, it
1196 also need to be done when materials are set on the fly through JS,
1197*/
1198static NSDictionary* CanonicalizeMaterialSpecifier(NSDictionary* spec, NSString* materialKey)
1199{
1200 NSMutableDictionary* result = [NSMutableDictionary dictionary];
1201 OOColor* col = nil;
1202 id texSpec = nil;
1203
1204 // Colours.
1205 col = [OOColor colorWithDescription:[spec objectForKey:kOOMaterialDiffuseColorName]];
1206 if (col == nil)
1207 col = [OOColor colorWithDescription:[spec objectForKey:kOOMaterialDiffuseColorLegacyName]];
1208 if (col != nil)
1209 [result setObject:[col normalizedArray] forKey:kOOMaterialDiffuseColorName];
1210
1211 col = [OOColor colorWithDescription:[spec objectForKey:kOOMaterialAmbientColorName]];
1212 if (col == nil)
1213 col = [OOColor colorWithDescription:[spec objectForKey:kOOMaterialAmbientColorLegacyName]];
1214 if (col != nil)
1215 [result setObject:[col normalizedArray] forKey:kOOMaterialAmbientColorName];
1216
1217 col = [OOColor colorWithDescription:[spec objectForKey:kOOMaterialSpecularColorName]];
1218 if (col == nil)
1219 col = [OOColor colorWithDescription:[spec objectForKey:kOOMaterialSpecularColorLegacyName]];
1220 if (col != nil)
1221 [result setObject:[col normalizedArray] forKey:kOOMaterialSpecularColorName];
1222
1223 col = [OOColor colorWithDescription:[spec objectForKey:kOOMaterialSpecularModulateColorName]];
1224 if (col != nil)
1225 [result setObject:[col normalizedArray] forKey:kOOMaterialSpecularModulateColorName];
1226
1227 col = [OOColor colorWithDescription:[spec objectForKey:kOOMaterialEmissionColorName]];
1228 if (col == nil)
1229 col = [OOColor colorWithDescription:[spec objectForKey:kOOMaterialEmissionColorLegacyName]];
1230 if (col != nil)
1231 [result setObject:[col normalizedArray] forKey:kOOMaterialEmissionColorName];
1232
1233 // Diffuse map.
1234 texSpec = [spec objectForKey:kOOMaterialDiffuseMapName];
1235 if ([texSpec isKindOfClass:[NSString class]]) {
1236 if ([texSpec length] > 0) {
1237 texSpec = [NSDictionary dictionaryWithObject:texSpec forKey:kOOTextureSpecifierNameKey];
1238 }
1239 } else if ([texSpec isKindOfClass:[NSDictionary class]]) {
1240 /* Special case for diffuse map: no name is changed to
1241 name = materialKey, while name = "" is changed to no name.
1242 */
1243 NSString* name = [texSpec objectForKey:kOOTextureSpecifierNameKey];
1244 if (name == nil)
1245 texSpec = [texSpec dictionaryByAddingObject:materialKey forKey:kOOTextureSpecifierNameKey];
1246 else if ([name length] == 0) {
1247 texSpec = [texSpec dictionaryByRemovingObjectForKey:kOOTextureSpecifierNameKey];
1248 }
1249 } else {
1250 // Special case for unspecified diffuse map.
1251 texSpec = [NSDictionary dictionaryWithObject:materialKey forKey:kOOTextureSpecifierNameKey];
1252 }
1253 [result setObject:texSpec forKey:kOOMaterialDiffuseMapName];
1254
1255 // Specular maps.
1256 {
1257 BOOL haveNewSpecular = NO;
1258 texSpec = [spec objectForKey:kOOMaterialSpecularColorMapName];
1259 if ([texSpec isKindOfClass:[NSString class]]) {
1260 texSpec = [NSDictionary dictionaryWithObject:texSpec forKey:kOOTextureSpecifierNameKey];
1261 } else if (![texSpec isKindOfClass:[NSDictionary class]]) {
1262 texSpec = nil;
1263 }
1264 if (texSpec != nil) {
1265 haveNewSpecular = YES;
1266 [result setObject:texSpec forKey:kOOMaterialSpecularColorMapName];
1267 }
1268
1269 texSpec = [spec objectForKey:kOOMaterialSpecularExponentMapName];
1270 if ([texSpec isKindOfClass:[NSString class]]) {
1271 texSpec = [NSDictionary dictionaryWithObject:texSpec forKey:kOOTextureSpecifierNameKey];
1272 } else if (![texSpec isKindOfClass:[NSDictionary class]]) {
1273 texSpec = nil;
1274 }
1275 if (texSpec != nil) {
1276 haveNewSpecular = YES;
1277 [result setObject:texSpec forKey:kOOMaterialSpecularExponentMapName];
1278 }
1279
1280 if (!haveNewSpecular) {
1281 // Fall back to legacy combined specular map if defined.
1282 texSpec = [spec objectForKey:kOOMaterialCombinedSpecularMapName];
1283 if ([texSpec isKindOfClass:[NSString class]]) {
1284 texSpec = [NSDictionary dictionaryWithObject:texSpec forKey:kOOTextureSpecifierNameKey];
1285 } else if (![texSpec isKindOfClass:[NSDictionary class]]) {
1286 texSpec = nil;
1287 }
1288 if (texSpec != nil) {
1289 [result setObject:texSpec forKey:kOOMaterialSpecularColorMapName];
1290 texSpec = [texSpec dictionaryByAddingObject:@"a" forKey:kOOTextureSpecifierSwizzleKey];
1291 [result setObject:texSpec forKey:kOOMaterialSpecularExponentMapName];
1292 }
1293 }
1294 }
1295
1296 // Normal and parallax maps.
1297 {
1298 BOOL haveParallax = NO;
1299 BOOL haveNewNormal = NO;
1300 texSpec = [spec objectForKey:kOOMaterialNormalMapName];
1301 if ([texSpec isKindOfClass:[NSString class]]) {
1302 texSpec = [NSDictionary dictionaryWithObject:texSpec forKey:kOOTextureSpecifierNameKey];
1303 } else if (![texSpec isKindOfClass:[NSDictionary class]]) {
1304 texSpec = nil;
1305 }
1306 if (texSpec != nil) {
1307 haveNewNormal = YES;
1308 [result setObject:texSpec forKey:kOOMaterialNormalMapName];
1309 }
1310
1311 texSpec = [spec objectForKey:kOOMaterialParallaxMapName];
1312 if ([texSpec isKindOfClass:[NSString class]]) {
1313 texSpec = [NSDictionary dictionaryWithObject:texSpec forKey:kOOTextureSpecifierNameKey];
1314 } else if (![texSpec isKindOfClass:[NSDictionary class]]) {
1315 texSpec = nil;
1316 }
1317 if (texSpec != nil) {
1318 haveNewNormal = YES;
1319 haveParallax = YES;
1320 [result setObject:texSpec forKey:kOOMaterialParallaxMapName];
1321 }
1322
1323 if (!haveNewNormal) {
1324 // Fall back to legacy combined normal and parallax map if defined.
1325 texSpec = [spec objectForKey:kOOMaterialNormalAndParallaxMapName];
1326 if ([texSpec isKindOfClass:[NSString class]]) {
1327 texSpec = [NSDictionary dictionaryWithObject:texSpec forKey:kOOTextureSpecifierNameKey];
1328 } else if (![texSpec isKindOfClass:[NSDictionary class]]) {
1329 texSpec = nil;
1330 }
1331 if (texSpec != nil) {
1332 haveParallax = YES;
1333 [result setObject:texSpec forKey:kOOMaterialNormalMapName];
1334 texSpec = [texSpec dictionaryByAddingObject:@"a" forKey:kOOTextureSpecifierSwizzleKey];
1335 [result setObject:texSpec forKey:kOOMaterialParallaxMapName];
1336 }
1337 }
1338
1339 // Additional parallax parameters.
1340 if (haveParallax) {
1341 float parallaxScale = [spec oo_floatForKey:kOOMaterialParallaxScaleName defaultValue:kOOMaterialDefaultParallaxScale];
1342 [result oo_setFloat:parallaxScale forKey:kOOMaterialParallaxScaleName];
1343
1344 float parallaxBias = [spec oo_floatForKey:kOOMaterialParallaxBiasName];
1345 [result oo_setFloat:parallaxBias forKey:kOOMaterialParallaxBiasName];
1346 }
1347 }
1348
1349 // Light maps.
1350 {
1351 NSMutableArray* lightMaps = [NSMutableArray array];
1352 id lightMapSpecs = [spec objectForKey:kOOMaterialLightMapsName];
1353 if (lightMapSpecs != nil && ![lightMapSpecs isKindOfClass:[NSArray class]]) {
1354 lightMapSpecs = [NSArray arrayWithObject:lightMapSpecs];
1355 }
1356
1357 id lmSpec = nil;
1358 foreach (lmSpec, lightMapSpecs) {
1359 if ([lmSpec isKindOfClass:[NSString class]]) {
1360 lmSpec = [NSMutableDictionary dictionaryWithObject:lmSpec forKey:kOOTextureSpecifierNameKey];
1361 } else if ([lmSpec isKindOfClass:[NSDictionary class]]) {
1362 lmSpec = [[lmSpec mutableCopy] autorelease];
1363 } else {
1364 continue;
1365 }
1366
1367 id modulateColor = [lmSpec objectForKey:kOOTextureSpecifierModulateColorKey];
1368 if (modulateColor != nil && ![modulateColor isKindOfClass:[NSArray class]]) {
1369 // Don't convert arrays here, because we specifically don't want the behaviour of treating numbers greater than 1 as 0..255 components.
1370 col = [OOColor colorWithDescription:modulateColor];
1371 [lmSpec setObject:[col normalizedArray] forKey:kOOTextureSpecifierModulateColorKey];
1372 }
1373
1374 id binding = [lmSpec objectForKey:kOOTextureSpecifierBindingKey];
1375 if (binding != nil) {
1376 if ([binding isKindOfClass:[NSString class]]) {
1377 NSDictionary* expandedBinding = [NSDictionary dictionaryWithObjectsAndKeys:@"binding", @"type", binding, @"binding", nil];
1378 [lmSpec setObject:expandedBinding forKey:kOOTextureSpecifierBindingKey];
1379 } else if (![binding isKindOfClass:[NSDictionary class]] || [[binding oo_stringForKey:@"binding"] length] == 0) {
1380 [lmSpec removeObjectForKey:kOOTextureSpecifierBindingKey];
1381 }
1382 }
1383
1384 [lightMaps addObject:[[lmSpec copy] autorelease]];
1385 }
1386
1387 if ([lightMaps count] == 0) {
1388 // If light_map isn't use, handle legacy emission_map, illumination_map and emission_and_illumination_map.
1389 id emissionSpec = [spec objectForKey:kOOMaterialEmissionMapName];
1390 id illuminationSpec = [spec objectForKey:kOOMaterialIlluminationMapName];
1391
1392 if (emissionSpec == nil && illuminationSpec == nil) {
1393 emissionSpec = [spec objectForKey:kOOMaterialEmissionAndIlluminationMapName];
1394 if ([emissionSpec isKindOfClass:[NSString class]]) {
1395 // Redundantish check required because we want to modify this as a dictionary to make illuminationSpec.
1396 emissionSpec = [NSDictionary dictionaryWithObject:emissionSpec forKey:kOOTextureSpecifierNameKey];
1397 } else if (![emissionSpec isKindOfClass:[NSDictionary class]]) {
1398 emissionSpec = nil;
1399 }
1400
1401 if (emissionSpec != nil) {
1402 illuminationSpec = [emissionSpec dictionaryByAddingObject:@"a" forKey:kOOTextureSpecifierSwizzleKey];
1403 }
1404 }
1405
1406 if (emissionSpec != nil) {
1407 if ([emissionSpec isKindOfClass:[NSString class]]) {
1408 emissionSpec = [NSDictionary dictionaryWithObject:emissionSpec forKey:kOOTextureSpecifierNameKey];
1409 }
1410 if ([emissionSpec isKindOfClass:[NSDictionary class]]) {
1411 col = [OOColor colorWithDescription:[spec objectForKey:kOOMaterialEmissionModulateColorName]];
1412 if (col != nil)
1413 emissionSpec = [emissionSpec dictionaryByAddingObject:[col normalizedArray] forKey:kOOTextureSpecifierModulateColorKey];
1414
1415 [lightMaps addObject:emissionSpec];
1416 }
1417 }
1418
1419 if (illuminationSpec != nil) {
1420 if ([illuminationSpec isKindOfClass:[NSString class]]) {
1421 illuminationSpec = [NSDictionary dictionaryWithObject:illuminationSpec forKey:kOOTextureSpecifierNameKey];
1422 }
1423 if ([illuminationSpec isKindOfClass:[NSDictionary class]]) {
1424 col = [OOColor colorWithDescription:[spec objectForKey:kOOMaterialIlluminationModulateColorName]];
1425 if (col != nil)
1426 illuminationSpec = [illuminationSpec dictionaryByAddingObject:[col normalizedArray] forKey:kOOTextureSpecifierModulateColorKey];
1427
1428 illuminationSpec = [illuminationSpec dictionaryByAddingObject:[NSNumber numberWithBool:YES] forKey:kOOTextureSpecifierIlluminationModeKey];
1429
1430 [lightMaps addObject:illuminationSpec];
1431 }
1432 }
1433 }
1434
1435 [result setObject:lightMaps forKey:kOOMaterialLightMapsName];
1436 }
1437
1438 OOLog(@"material.canonicalForm", @"Canonicalized material %@:\nORIGINAL:\n%@\n\n@CANONICAL:\n%@", materialKey, spec, result);
1439
1440 return result;
1441}
1442
1443static NSString* FormatFloat(double value)
1444{
1445 long long intValue = value;
1446 if (value == intValue) {
1447 return [NSString stringWithFormat:@"%lli.0", intValue];
1448 } else {
1449 return [NSString stringWithFormat:@"%g", value];
1450 }
1451}
static NSString * GetExtractMode(NSDictionary *textureSpecifier)
static NSString * FormatFloat(double value)
#define REQUIRE_STAGE(NAME)
static NSDictionary * CanonicalizeMaterialSpecifier(NSDictionary *spec, NSString *materialKey)
BOOL OOSynthesizeMaterialShader(NSDictionary *configuration, NSString *materialKey, NSString *entityName, NSString **outVertexShader, NSString **outFragmentShader, NSArray **outTextureSpecs, NSDictionary **outUniformSpecs)
#define DESTROY(x)
#define EXPECT_NOT(x)
#define OOLogWARN(class, format,...)
Definition OOLogging.h:126
#define OOLogERR(class, format,...)
Definition OOLogging.h:125
#define OOLog(class, format,...)
Definition OOLogging.h:84
unsigned count
return nil
OOTextureFlags OOApplyTextureOptionDefaults(OOTextureFlags options)
Definition OOTexture.m:819
NSDictionary * OOTextureSpecFromObject(id object, NSString *defaultName)
Definition OOTexture.m:602
@ kOOTextureExtractChannelMask
Definition OOTexture.h:65
@ kOOTextureAllowCubeMap
Definition OOTexture.h:61
NSString *const kOOTextureSpecifierIlluminationModeKey
Definition OOTexture.m:57
uint32_t OOTextureFlags
Definition OOTexture.h:95
BOOL OOInterpretTextureSpecifier(id specifier, NSString **outName, OOTextureFlags *outOptions, float *outAnisotropy, float *outLODBias, BOOL ignoreExtract)
Definition OOTexture.m:648
NSString *const kOOTextureSpecifierSwizzleKey
Definition OOTexture.m:45
OOColor * colorWithDescription:(id description)
Definition OOColor.m:135
void getRed:green:blue:alpha:(float *red,[green] float *green,[blue] float *blue,[alpha] float *alpha)
Definition OOColor.m:344
NSArray * normalizedArray()
Definition OOColor.m:465
OOColor * whiteColor()
Definition OOColor.m:249
NSUInteger textureIDForSpec:(NSDictionary *textureSpec)
NSString * defineBindingUniform:ofType:(NSDictionary *binding,[ofType] NSString *type)
static void AppendIfNotEmpty(NSMutableString *buffer, NSString *segment, NSString *name)
static NSString * KeyFromTextureSpec(NSDictionary *spec)
NSString * readOneChannelForTextureSpec:mapName:(NSDictionary *textureSpec,[mapName] NSString *mapName)
void setUpOneTexture:(NSDictionary *textureSpec)
void addFragmentUniform:ofType:(NSString *name,[ofType] NSString *type)
void getSampleName:andSwizzleOp:forTextureSpec:(NSString **outSampleName,[andSwizzleOp] NSString **outSwizzleOp,[forTextureSpec] NSDictionary *textureSpec)
NSUInteger assignIDForTexture:(NSDictionary *spec)
NSMutableDictionary * _uniformBindingNames
void appendVariable:ofType:withPrefix:to:(NSString *name,[ofType] NSString *type,[withPrefix] NSString *prefix,[to] NSMutableString *buffer)
void addAttribute:ofType:(NSString *name,[ofType] NSString *type)
static NSString * GetExtractMode(NSDictionary *textureSpecifier)
void addVarying:ofType:(NSString *name,[ofType] NSString *type)
static NSString * KeyFromTextureParameters(NSString *name, OOTextureFlags options, float anisotropy, float lodBias)
NSString * readRGBForTextureSpec:mapName:(NSDictionary *textureSpec,[mapName] NSString *mapName)
NSDictionary * shaderBindingTypesDictionary()