Skip to content

Instantly share code, notes, and snippets.

@bradparks
Forked from psineur/AWTextureEffects.h
Created February 20, 2012 18:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bradparks/1870505 to your computer and use it in GitHub Desktop.
Save bradparks/1870505 to your computer and use it in GitHub Desktop.
BlurCombo
//
// AWTextureEffects.h
//
// Created by Manuel Martinez-Almeida Castañeda on 09/05/10.
// Copyright 2010 Abstraction Works. All rights reserved.
// http://www.abstractionworks.com
//
#import "CCMutableTexture2D.h"
@interface AWTextureEffect : NSObject {}
///
// @param input: Original texture data
// @param output: Empty (or not) buffer
// @param format: Pixel format of the data
// @param width: Real width (is a power of two)
// @param height: Real height (is a power of two)
// @param position: Top left vertex of the blur effect
// @param size: The size of the blur effect
// @param contentSize:
// @param radios: It's the radius of the blur effect
///
+ (void) blurInput:(void*)input output:(void*)output format:(CCTexture2DPixelFormat)format width:(int)width height:(int)height position:(ccGridSize)position size:(ccGridSize)size contentSize:(CGSize)contentSize radius:(int)radius;
+ (CCMutableTexture2D*) blur:(CCMutableTexture2D*)texture position:(ccGridSize)position size:(ccGridSize)size radius:(int)radius;
+ (CCMutableTexture2D*) blur:(CCMutableTexture2D*)texture radius:(int)radius;
@end
//
// AWTextureEffects.m
//
// Created by Manuel Martinez-Almeida Castañeda on 09/05/10.
// Copyright 2010 Abstraction Works. All rights reserved.
// http://www.abstractionworks.com
//
#import "AWTextureEffects.h"
#import "ccMacros.h"
@implementation AWTextureEffect
+ (void) blurInput:(void*)input output:(void*)output format:(CCTexture2DPixelFormat)format width:(int)width height:(int)height position:(ccGridSize)position size:(ccGridSize)size contentSize:(CGSize)contentSize radius:(int)radius
{
int cr, cg, cb, ca;
int read, i, xl, yl, yi, ym, ri, riw;
int wh = width*height;
size.x = (size.x==0) ? contentSize.width : size.x;
size.y = (size.y==0) ? contentSize.height : size.y;
//Check data
position = ccg(MAX(0, position.x), MAX(0, position.y));
size.x = position.x+size.x-MAX(0, (position.x+size.x)-width);
size.y = position.y+size.y-MAX(0, (position.y+size.y)-height);
yi = position.y*width;
//Generate Gaussian kernel
radius = MIN(MAX(1,radius), 248);
int kernelSize = 1+radius*2;
int kernel[kernelSize];
int g = 0, sum = 0;
//Gaussian filter
for (i = 0; i<radius;i++){
g = i*i+1;
kernel[i] = kernel[kernelSize-i-1] = g;
sum+=g*2;
}
g = radius*radius;
kernel[radius] = g;
sum+=g;
if(format == kTexture2DPixelFormat_RGBA8888){
ccColor4B* originalData = (ccColor4B*) input;
ccColor4B* data = (ccColor4B*) output;
ccColor4B* temp = malloc(wh*4);
ccColor4B *pixel;
//Horizontal blur
for (yl = position.y; yl<size.y; yl++){
for (xl = position.x; xl<size.x; xl++){
cb = cg = cr = ca = 0;
ri = xl-radius;
for (i = 0; i<kernelSize; i++){
read = ri+i;
if (read>=position.x && read<size.x){
read+=yi;
pixel = &originalData[read];
cr+= pixel->r*kernel[i];
cg+= pixel->g*kernel[i];
cb+= pixel->b*kernel[i];
ca+= pixel->a*kernel[i];
}
}
ri = yi+xl;
pixel = &temp[ri];
pixel->r = cr/sum;
pixel->g = cg/sum;
pixel->b = cb/sum;
pixel->a = ca/sum;
}
yi+=width;
}
yi = position.y*width;
//Vertical blur
for (yl = position.y; yl<size.y; yl++){
ym = yl-radius;
riw = ym*width;
for (xl = position.x; xl<size.x; xl++){
cb = cg = cr = ca = 0;
ri = ym;
read = xl+riw;
for (i = 0; i<kernelSize; i++){
if (ri<size.y && ri>=position.y){
pixel = &temp[read];
cr+= pixel->r*kernel[i];
cg+= pixel->g*kernel[i];
cb+= pixel->b*kernel[i];
ca+= pixel->a*kernel[i];
}
ri++;
read+=width;
}
pixel = &data[xl+yi];
pixel->r = cr/sum;
pixel->g = cg/sum;
pixel->b = cb/sum;
pixel->a = ca/sum;
}
yi+=width;
}
//Free temp data
free(temp);
}else{
[NSException raise:@"AWTextureEffect" format:@"Pixel format don't supported"];
}
}
+ (CCMutableTexture2D*) blur:(CCMutableTexture2D*)texture radius:(int)radius
{
return [self blur:texture position:ccg(0,0) size:ccg(0,0) radius:radius];
}
+ (CCMutableTexture2D*) blur:(CCMutableTexture2D*)texture position:(ccGridSize)position size:(ccGridSize)size radius:(int)radius
{
if(!texture)
return nil;
//Apply the effect to the texture
[self blurInput:texture.originalTexData output:texture.texData format:texture.pixelFormat width:texture.pixelsWide height:texture.pixelsHigh position:position size:size contentSize:texture.contentSize radius:radius];
//Update the GPU data
[texture apply];
return texture;
}
@end
//
// CCMutableTexture.h
// Created by Lam Hoang Pham.
//
#import "CCTexture2D.h"
#import "ccTypes.h"
#import "CCRenderTexture.h"
@interface CCRenderTexture (MutableExtension)
- (id) mutableTexture;
@end
@interface CCTexture2D (MutableExtension) <NSMutableCopying>
- (id) mutableCopyWithZone:(NSZone *)zone;
@end
@class CCRenderTexture;
@interface CCMutableTexture2D : CCTexture2D {
void *originalData_;
void *data_;
NSUInteger bytesPerPixel_;
bool dirty_;
}
@property(nonatomic, readonly) void *originalTexData;
@property(nonatomic, readwrite) void *texData;
- (ccColor4B) pixelAt:(CGPoint) pt;
///
// @param pt is a point to get a pixel (0,0) is top-left to (width,height) bottom-right
// @param c is a ccColor4B which is a colour.
// @returns if a pixel was set
// Remember to call apply to actually update the texture canvas.
///
- (BOOL) setPixelAt:(CGPoint) pt rgba:(ccColor4B) c;
///
// Fill with specified colour
///
- (void) fill:(ccColor4B) c;
///
// @param textureToCopy is the texture image to copy over
// @param offset also offset's the texture image
///
- (id) copy;
- (void) copy:(CCMutableTexture2D*)textureToCopy offset:(CGPoint) offset;
///
// apply actually updates the texture with any new data we added.
///
- (void) apply;
@end
//
// CCMutableTexture.m
// Created by Lam Hoang Pham.
//
#import "CCMutableTexture2D.h"
#import "ccMacros.h"
@interface CCRenderTexture (MutableExtensionPrivate)
-(GLvoid*)getPixels;
@end
@implementation CCRenderTexture (MutableExtension)
- (CCMutableTexture2D *) mutableTexture
{
CGSize s = [texture_ contentSizeInPixels];
int tx = s.width;
int ty = s.height;
GLvoid *pixels = [self getPixels];
id tex = [[ [CCMutableTexture2D alloc] initWithData: pixels
pixelFormat: texture_.pixelFormat
pixelsWide: tx
pixelsHigh: ty
contentSize: s ] autorelease];
free(pixels);
return tex;
}
-(GLvoid*)getPixels
{
NSAssert(pixelFormat_ == kCCTexture2DPixelFormat_RGBA8888,@"only RGBA8888 can be saved as image");
CGSize s = [texture_ contentSizeInPixels];
int tx = s.width;
int ty = s.height;
//int bitsPerComponent=8;
// int bitsPerPixel=32;
//
// int bytesPerRow = (bitsPerPixel/8) * tx;
// NSInteger myDataLength = bytesPerRow * ty;
// GLubyte *buffer = malloc(sizeof(GLubyte)*myDataLength);
NSUInteger bytesPerPixel = 0;
switch (texture_.pixelFormat ) {
case kTexture2DPixelFormat_RGBA8888: bytesPerPixel = 4; break;
case kTexture2DPixelFormat_A8: bytesPerPixel = 1; break;
case kTexture2DPixelFormat_RGBA4444:
case kTexture2DPixelFormat_RGB565:
case kTexture2DPixelFormat_RGB5A1:
bytesPerPixel = 2;
break;
default:break;
}
GLvoid *pixels;
NSUInteger max = tx*ty*bytesPerPixel;
pixels = malloc(max);
if( ! pixels )
{
CCLOG(@"cocos2d: CCRenderTexture#getPixels: not enough memory");
free(pixels);
return NULL;
}
[self begin];
//glReadPixels(0,0,tx,ty,GL_RGBA,GL_UNSIGNED_BYTE, buffer);
switch(texture_.pixelFormat )
{
//GL_TEXTURE_2D -> name_
case kCCTexture2DPixelFormat_RGBA8888:
glReadPixels(0,0,tx,ty, GL_RGBA, GL_UNSIGNED_BYTE, pixels );
break;
case kCCTexture2DPixelFormat_RGBA4444:
glReadPixels(0,0,tx,ty, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, pixels);
break;
case kCCTexture2DPixelFormat_RGB5A1:
glReadPixels(0,0,tx,ty, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, pixels);
break;
case kCCTexture2DPixelFormat_RGB565:
glReadPixels(0,0,tx,ty, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, pixels);
break;
case kCCTexture2DPixelFormat_A8:
glReadPixels(0,0,tx,ty, GL_ALPHA, GL_UNSIGNED_BYTE, pixels);
break;
default:
[NSException raise:NSInternalInconsistencyException format:@""];
}
[self end];
return pixels;
}
@end
@implementation CCTexture2D (MutableExtension)
- (id) mutableCopyWithZone:(NSZone *)zone
{
NSUInteger bytesPerPixel = 0;
switch (format_) {
case kTexture2DPixelFormat_RGBA8888: bytesPerPixel = 4; break;
case kTexture2DPixelFormat_A8: bytesPerPixel = 1; break;
case kTexture2DPixelFormat_RGBA4444:
case kTexture2DPixelFormat_RGB565:
case kTexture2DPixelFormat_RGB5A1:
bytesPerPixel = 2;
break;
default:break;
}
GLvoid *pixels;
NSUInteger max = width_*height_*bytesPerPixel;
pixels = malloc(max);
glBindTexture(GL_TEXTURE_2D, name_);
switch(format_)
{
//GL_TEXTURE_2D -> name_
case kCCTexture2DPixelFormat_RGBA8888:
glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels );
break;
case kCCTexture2DPixelFormat_RGBA4444:
glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, pixels);
break;
case kCCTexture2DPixelFormat_RGB5A1:
glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, pixels);
break;
case kCCTexture2DPixelFormat_RGB565:
glGetTexImage(GL_TEXTURE_2D, 0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, pixels);
break;
case kCCTexture2DPixelFormat_A8:
glGetTexImage(GL_TEXTURE_2D, 0, GL_ALPHA, GL_UNSIGNED_BYTE, pixels);
break;
default:
[NSException raise:NSInternalInconsistencyException format:@""];
}
id tex = [ [CCMutableTexture2D allocWithZone: zone] initWithData: pixels
pixelFormat: format_
pixelsWide: width_
pixelsHigh: height_
contentSize: size_ ];
free(pixels);
return tex;
}
@end
@implementation CCMutableTexture2D
@synthesize texData = data_;
@synthesize originalTexData = originalData_;
- (void) releaseData:(void*)data {
//Don't free the data
}
- (id) initWithData:(void*)data pixelFormat:(CCTexture2DPixelFormat)pixelFormat pixelsWide:(NSUInteger)width pixelsHigh:(NSUInteger)height contentSize:(CGSize)size{
if((self = [super initWithData:data pixelFormat:pixelFormat pixelsWide:width pixelsHigh:height contentSize:size])){
switch (pixelFormat) {
case kTexture2DPixelFormat_RGBA8888: bytesPerPixel_ = 4; break;
case kTexture2DPixelFormat_A8: bytesPerPixel_ = 1; break;
case kTexture2DPixelFormat_RGBA4444:
case kTexture2DPixelFormat_RGB565:
case kTexture2DPixelFormat_RGB5A1:
bytesPerPixel_ = 2;
break;
default:break;
}
NSUInteger max = width*height*bytesPerPixel_;
data_ = (void*) data;
originalData_ = malloc(max);
memcpy(originalData_, data_, max);
}
return self;
}
- (ccColor4B) pixelAt:(CGPoint) pt {
ccColor4B c = {0, 0, 0, 0};
if(!data_) return c;
if(pt.x < 0 || pt.y < 0) return c;
if(pt.x >= size_.width || pt.y >= size_.height) return c;
uint x = pt.x, y = pt.y;
if(format_ == kTexture2DPixelFormat_RGBA8888){
uint *pixel = data_;
pixel = pixel + (y * width_) + x;
c.r = *pixel & 0xff;
c.g = (*pixel >> 8) & 0xff;
c.b = (*pixel >> 16) & 0xff;
c.a = (*pixel >> 24) & 0xff;
} else if(format_ == kTexture2DPixelFormat_RGBA4444){
GLushort *pixel = data_;
pixel = pixel + (y * width_) + x;
c.a = ((*pixel & 0xf) << 4) | (*pixel & 0xf);
c.b = (((*pixel >> 4) & 0xf) << 4) | ((*pixel >> 4) & 0xf);
c.g = (((*pixel >> 8) & 0xf) << 4) | ((*pixel >> 8) & 0xf);
c.r = (((*pixel >> 12) & 0xf) << 4) | ((*pixel >> 12) & 0xf);
} else if(format_ == kTexture2DPixelFormat_RGB5A1){
GLushort *pixel = data_;
pixel = pixel + (y * width_) + x;
c.r = ((*pixel >> 11) & 0x1f)<<3;
c.g = ((*pixel >> 6) & 0x1f)<<3;
c.b = ((*pixel >> 1) & 0x1f)<<3;
c.a = (*pixel & 0x1)*255;
} else if(format_ == kTexture2DPixelFormat_RGB565){
GLushort *pixel = data_;
pixel = pixel + (y * width_) + x;
c.b = (*pixel & 0x1f)<<3;
c.g = ((*pixel >> 5) & 0x3f)<<2;
c.r = ((*pixel >> 11) & 0x1f)<<3;
c.a = 255;
} else if(format_ == kTexture2DPixelFormat_A8){
GLubyte *pixel = data_;
c.a = pixel[(y * width_) + x];
// Default white
c.r = 255;
c.g = 255;
c.b = 255;
}
return c;
}
- (BOOL) setPixelAt:(CGPoint) pt rgba:(ccColor4B) c {
if(!data_)return NO;
if(pt.x < 0 || pt.y < 0) return NO;
if(pt.x >= size_.width || pt.y >= size_.height) return NO;
uint x = pt.x, y = pt.y;
dirty_ = true;
// Shifted bit placement based on little-endian, let's make this more
// portable =/
if(format_ == kTexture2DPixelFormat_RGBA8888){
uint *pixel = data_;
pixel[(y * width_) + x] = (c.a << 24) | (c.b << 16) | (c.g << 8) | c.r;
} else if(format_ == kTexture2DPixelFormat_RGBA4444){
GLushort *pixel = data_;
pixel = pixel + (y * width_) + x;
*pixel = ((c.r >> 4) << 12) | ((c.g >> 4) << 8) | ((c.b >> 4) << 4) | (c.a >> 4);
} else if(format_ == kTexture2DPixelFormat_RGB5A1){
GLushort *pixel = data_;
pixel = pixel + (y * width_) + x;
*pixel = ((c.r >> 3) << 11) | ((c.g >> 3) << 6) | ((c.b >> 3) << 1) | (c.a > 0);
} else if(format_ == kTexture2DPixelFormat_RGB565){
GLushort *pixel = data_;
pixel = pixel + (y * width_) + x;
*pixel = ((c.r >> 3) << 11) | ((c.g >> 2) << 5) | (c.b >> 3);
} else if(format_ == kTexture2DPixelFormat_A8){
GLubyte *pixel = data_;
pixel[(y * width_) + x] = c.a;
} else {
dirty_ = false;
return NO;
}
return YES;
}
- (void) fill:(ccColor4B) p {
for(int r = 0; r < size_.height;++r){
for(int c = 0; c < size_.width; ++c){
[self setPixelAt:CGPointMake(c, r) rgba:p];
}
}
}
- (id) copy{
return [[[CCMutableTexture2D alloc] initWithData:data_ pixelFormat:format_ pixelsWide:width_ pixelsHigh:height_ contentSize:size_] autorelease];
}
- (void) copy:(CCMutableTexture2D*)textureToCopy offset:(CGPoint) offset {
for(int r = 0; r < size_.height;++r){
for(int c = 0; c < size_.width; ++c){
[self setPixelAt:CGPointMake(c + offset.x, r + offset.y) rgba:[textureToCopy pixelAt:CGPointMake(c, r)]];
}
}
}
- (void) restore {
memcpy(data_, originalData_, bytesPerPixel_*width_*height_);
[self apply];
}
- (void) apply {
//if(!dirty_) return;
if(!data_) return;
glBindTexture(GL_TEXTURE_2D, name_);
switch(format_)
{
case kTexture2DPixelFormat_RGBA8888:
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width_, height_, 0, GL_RGBA, GL_UNSIGNED_BYTE, data_);
break;
case kTexture2DPixelFormat_RGBA4444:
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width_, height_, 0, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, data_);
break;
case kTexture2DPixelFormat_RGB5A1:
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width_, height_, 0, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, data_);
break;
case kTexture2DPixelFormat_RGB565:
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width_, height_, 0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, data_);
break;
case kTexture2DPixelFormat_A8:
glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, width_, height_, 0, GL_ALPHA, GL_UNSIGNED_BYTE, data_);
break;
default:
[NSException raise:NSInternalInconsistencyException format:@""];
}
glBindTexture(GL_TEXTURE_2D, 0);
dirty_ = NO;
}
- (void) dealloc
{
free(data_);
free(originalData_);
[super dealloc];
}
@end
/*
===== IMPORTANT =====
This is sample code demonstrating API, technology or techniques in development.
Although this sample code has been reviewed for technical accuracy, it is not
final. Apple is supplying this information to help you plan for the adoption of
the technologies and programming interfaces described herein. This information
is subject to change, and software implemented based on this sample code should
be tested with final operating system software and final documentation. Newer
versions of this sample code may be provided with future seeds of the API or
technology. For information about updates to this and other developer
documentation, view the New & Updated sidebars in subsequent documentation
seeds.
=====================
File: Texture2D.h
Abstract: Creates OpenGL 2D textures from images or text.
Version: 1.6
Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc.
("Apple") in consideration of your agreement to the following terms, and your
use, installation, modification or redistribution of this Apple software
constitutes acceptance of these terms. If you do not agree with these terms,
please do not use, install, modify or redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and subject
to these terms, Apple grants you a personal, non-exclusive license, under
Apple's copyrights in this original Apple software (the "Apple Software"), to
use, reproduce, modify and redistribute the Apple Software, with or without
modifications, in source and/or binary forms; provided that if you redistribute
the Apple Software in its entirety and without modifications, you must retain
this notice and the following text and disclaimers in all such redistributions
of the Apple Software.
Neither the name, trademarks, service marks or logos of Apple Inc. may be used
to endorse or promote products derived from the Apple Software without specific
prior written permission from Apple. Except as expressly stated in this notice,
no other rights or licenses, express or implied, are granted by Apple herein,
including but not limited to any patent rights that may be infringed by your
derivative works or by other works in which the Apple Software may be
incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO
WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR
DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF
CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF
APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Copyright (C) 2008 Apple Inc. All Rights Reserved.
*/
#import <Availability.h>
#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
#import <UIKit/UIKit.h> // for UIImage
#endif
#import <Foundation/Foundation.h> // for NSObject
#import "Platforms/CCGL.h" // OpenGL stuff
#import "Platforms/CCNS.h" // Next-Step stuff
//CONSTANTS:
/** @typedef CCTexture2DPixelFormat
Possible texture pixel formats
*/
typedef enum {
kCCTexture2DPixelFormat_Automatic = 0,
//! 32-bit texture: RGBA8888
kCCTexture2DPixelFormat_RGBA8888,
//! 16-bit texture: used with images that have alpha pre-multiplied
kCCTexture2DPixelFormat_RGB565,
//! 8-bit textures used as masks
kCCTexture2DPixelFormat_A8,
//! 16-bit textures: RGBA4444
kCCTexture2DPixelFormat_RGBA4444,
//! 16-bit textures: RGB5A1
kCCTexture2DPixelFormat_RGB5A1,
//! Default texture format: RGBA8888
kCCTexture2DPixelFormat_Default = kCCTexture2DPixelFormat_RGBA8888,
// backward compatibility stuff
kTexture2DPixelFormat_Automatic = kCCTexture2DPixelFormat_Automatic,
kTexture2DPixelFormat_RGBA8888 = kCCTexture2DPixelFormat_RGBA8888,
kTexture2DPixelFormat_RGB565 = kCCTexture2DPixelFormat_RGB565,
kTexture2DPixelFormat_A8 = kCCTexture2DPixelFormat_A8,
kTexture2DPixelFormat_RGBA4444 = kCCTexture2DPixelFormat_RGBA4444,
kTexture2DPixelFormat_RGB5A1 = kCCTexture2DPixelFormat_RGB5A1,
kTexture2DPixelFormat_Default = kCCTexture2DPixelFormat_Default
} CCTexture2DPixelFormat;
//CLASS INTERFACES:
/** CCTexture2D class.
* This class allows to easily create OpenGL 2D textures from images, text or raw data.
* The created CCTexture2D object will always have power-of-two dimensions.
* Depending on how you create the CCTexture2D object, the actual image area of the texture might be smaller than the texture dimensions i.e. "contentSize" != (pixelsWide, pixelsHigh) and (maxS, maxT) != (1.0, 1.0).
* Be aware that the content of the generated textures will be upside-down!
*/
@interface CCTexture2D : NSObject
{
GLuint name_;
CGSize size_;
NSUInteger width_,
height_;
CCTexture2DPixelFormat format_;
GLfloat maxS_,
maxT_;
BOOL hasPremultipliedAlpha_;
}
/** Intializes with a texture2d with data */
- (id) initWithData:(const void*)data pixelFormat:(CCTexture2DPixelFormat)pixelFormat pixelsWide:(NSUInteger)width pixelsHigh:(NSUInteger)height contentSize:(CGSize)size;
/** pixel format of the texture */
@property(nonatomic,readonly) CCTexture2DPixelFormat pixelFormat;
/** width in pixels */
@property(nonatomic,readonly) NSUInteger pixelsWide;
/** hight in pixels */
@property(nonatomic,readonly) NSUInteger pixelsHigh;
/** texture name */
@property(nonatomic,readonly) GLuint name;
/** returns content size of the texture in pixels */
@property(nonatomic,readonly, nonatomic) CGSize contentSizeInPixels;
/** texture max S */
@property(nonatomic,readwrite) GLfloat maxS;
/** texture max T */
@property(nonatomic,readwrite) GLfloat maxT;
/** whether or not the texture has their Alpha premultiplied */
@property(nonatomic,readonly) BOOL hasPremultipliedAlpha;
/** returns the content size of the texture in points */
-(CGSize) contentSize;
@end
/**
Drawing extensions to make it easy to draw basic quads using a CCTexture2D object.
These functions require GL_TEXTURE_2D and both GL_VERTEX_ARRAY and GL_TEXTURE_COORD_ARRAY client states to be enabled.
*/
@interface CCTexture2D (Drawing)
/** draws a texture at a given point */
- (void) drawAtPoint:(CGPoint)point;
/** draws a texture inside a rect */
- (void) drawInRect:(CGRect)rect;
@end
/**
Extensions to make it easy to create a CCTexture2D object from an image file.
Note that RGBA type textures will have their alpha premultiplied - use the blending mode (GL_ONE, GL_ONE_MINUS_SRC_ALPHA).
*/
@interface CCTexture2D (Image)
/** Initializes a texture from a UIImage object */
#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
- (id) initWithImage:(UIImage *)uiImage;
#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED)
- (id) initWithImage:(CGImageRef)cgImage;
#endif
@end
/**
Extensions to make it easy to create a CCTexture2D object from a string of text.
Note that the generated textures are of type A8 - use the blending mode (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA).
*/
@interface CCTexture2D (Text)
/** Initializes a texture from a string with dimensions, alignment, font name and font size */
- (id) initWithString:(NSString*)string dimensions:(CGSize)dimensions alignment:(CCTextAlignment)alignment fontName:(NSString*)name fontSize:(CGFloat)size;
/** Initializes a texture from a string with font name and font size */
- (id) initWithString:(NSString*)string fontName:(NSString*)name fontSize:(CGFloat)size;
@end
/**
Extensions to make it easy to create a CCTexture2D object from a PVRTC file
Note that the generated textures don't have their alpha premultiplied - use the blending mode (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA).
*/
@interface CCTexture2D (PVRSupport)
/** Initializes a texture from a PVR Texture Compressed (PVRTC) buffer
*
* IMPORTANT: This method is only defined on iOS. It is not supported on the Mac version.
*/
#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
-(id) initWithPVRTCData: (const void*)data level:(int)level bpp:(int)bpp hasAlpha:(BOOL)hasAlpha length:(int)length;
#endif // __IPHONE_OS_VERSION_MAX_ALLOWED
/** Initializes a texture from a PVR file.
Supported PVR formats:
- BGRA 8888
- RGBA 8888
- RGBA 4444
- RGBA 5551
- RBG 565
- A 8
- I 8
- AI 8
- PVRTC 2BPP
- PVRTC 4BPP
By default PVR images are treated as if they alpha channel is NOT premultiplied. You can override this behavior with this class method:
- PVRImagesHavePremultipliedAlpha:(BOOL)haveAlphaPremultiplied;
IMPORTANT: This method is only defined on iOS. It is not supported on the Mac version.
*/
-(id) initWithPVRFile: (NSString*) file;
/** treats (or not) PVR files as if they have alpha premultiplied.
Since it is impossible to know at runtime if the PVR images have the alpha channel premultiplied, it is
possible load them as if they have (or not) the alpha channel premultiplied.
By default it is disabled by default.
@since v0.99.5
*/
+(void) PVRImagesHavePremultipliedAlpha:(BOOL)haveAlphaPremultiplied;
@end
/**
Extension to set the Min / Mag filter
*/
typedef struct _ccTexParams {
GLuint minFilter;
GLuint magFilter;
GLuint wrapS;
GLuint wrapT;
} ccTexParams;
@interface CCTexture2D (GLFilter)
/** sets the min filter, mag filter, wrap s and wrap t texture parameters.
If the texture size is NPOT (non power of 2), then in can only use GL_CLAMP_TO_EDGE in GL_TEXTURE_WRAP_{S,T}.
@since v0.8
*/
-(void) setTexParameters: (ccTexParams*) texParams;
/** sets antialias texture parameters:
- GL_TEXTURE_MIN_FILTER = GL_LINEAR
- GL_TEXTURE_MAG_FILTER = GL_LINEAR
@since v0.8
*/
- (void) setAntiAliasTexParameters;
/** sets alias texture parameters:
- GL_TEXTURE_MIN_FILTER = GL_NEAREST
- GL_TEXTURE_MAG_FILTER = GL_NEAREST
@since v0.8
*/
- (void) setAliasTexParameters;
/** Generates mipmap images for the texture.
It only works if the texture size is POT (power of 2).
@since v0.99.0
*/
-(void) generateMipmap;
@end
@interface CCTexture2D (PixelFormat)
/** sets the default pixel format for UIImages that contains alpha channel.
If the UIImage contains alpha channel, then the options are:
- generate 32-bit textures: kCCTexture2DPixelFormat_RGBA8888 (default one)
- generate 16-bit textures: kCCTexture2DPixelFormat_RGBA4444
- generate 16-bit textures: kCCTexture2DPixelFormat_RGB5A1
- generate 16-bit textures: kCCTexture2DPixelFormat_RGB565
- generate 8-bit textures: kCCTexture2DPixelFormat_A8 (only use it if you use just 1 color)
How does it work ?
- If the image is an RGBA (with Alpha) then the default pixel format will be used (it can be a 8-bit, 16-bit or 32-bit texture)
- If the image is an RGB (without Alpha) then an RGB565 texture will be used (16-bit texture)
This parameter is not valid for PVR images.
@since v0.8
*/
+(void) setDefaultAlphaPixelFormat:(CCTexture2DPixelFormat)format;
/** returns the alpha pixel format
@since v0.8
*/
+(CCTexture2DPixelFormat) defaultAlphaPixelFormat;
@end
/*
===== IMPORTANT =====
This is sample code demonstrating API, technology or techniques in development.
Although this sample code has been reviewed for technical accuracy, it is not
final. Apple is supplying this information to help you plan for the adoption of
the technologies and programming interfaces described herein. This information
is subject to change, and software implemented based on this sample code should
be tested with final operating system software and final documentation. Newer
versions of this sample code may be provided with future seeds of the API or
technology. For information about updates to this and other developer
documentation, view the New & Updated sidebars in subsequent documentationd
seeds.
=====================
File: Texture2D.m
Abstract: Creates OpenGL 2D textures from images or text.
Version: 1.6
Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc.
("Apple") in consideration of your agreement to the following terms, and your
use, installation, modification or redistribution of this Apple software
constitutes acceptance of these terms. If you do not agree with these terms,
please do not use, install, modify or redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and subject
to these terms, Apple grants you a personal, non-exclusive license, under
Apple's copyrights in this original Apple software (the "Apple Software"), to
use, reproduce, modify and redistribute the Apple Software, with or without
modifications, in source and/or binary forms; provided that if you redistribute
the Apple Software in its entirety and without modifications, you must retain
this notice and the following text and disclaimers in all such redistributions
of the Apple Software.
Neither the name, trademarks, service marks or logos of Apple Inc. may be used
to endorse or promote products derived from the Apple Software without specific
prior written permission from Apple. Except as expressly stated in this notice,
no other rights or licenses, express or implied, are granted by Apple herein,
including but not limited to any patent rights that may be infringed by your
derivative works or by other works in which the Apple Software may be
incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO
WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR
DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF
CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF
APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Copyright (C) 2008 Apple Inc. All Rights Reserved.
*/
/*
* Support for RGBA_4_4_4_4 and RGBA_5_5_5_1 was copied from:
* https://devforums.apple.com/message/37855#37855 by a1studmuffin
*/
#import <Availability.h>
#import "Platforms/CCGL.h"
#import "Platforms/CCNS.h"
#import "CCTexture2D.h"
#import "ccConfig.h"
#import "ccMacros.h"
#import "CCConfiguration.h"
#import "Support/ccUtils.h"
#import "CCTexturePVR.h"
#if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && CC_FONT_LABEL_SUPPORT
// FontLabel support
#import "FontManager.h"
#import "FontLabelStringDrawing.h"
#endif// CC_FONT_LABEL_SUPPORT
// For Labels use 32-bit textures on iPhone 3GS / iPads since A8 textures are very slow
#if defined(__ARM_NEON__) && CC_USE_RGBA32_LABELS_ON_NEON_ARCH
#define USE_TEXT_WITH_A8_TEXTURES 0
#else
#define USE_TEXT_WITH_A8_TEXTURES 1
#endif
//CLASS IMPLEMENTATIONS:
// If the image has alpha, you can create RGBA8 (32-bit) or RGBA4 (16-bit) or RGB5A1 (16-bit)
// Default is: RGBA8888 (32-bit textures)
static CCTexture2DPixelFormat defaultAlphaPixelFormat_ = kCCTexture2DPixelFormat_Default;
#pragma mark -
#pragma mark CCTexture2D - Main
@implementation CCTexture2D
- (void) releaseData:(void*)data {
free(data);
}
@synthesize contentSizeInPixels=size_, pixelFormat=format_, pixelsWide=width_, pixelsHigh=height_, name=name_, maxS=maxS_, maxT=maxT_;
@synthesize hasPremultipliedAlpha=hasPremultipliedAlpha_;
- (id) initWithData:(const void*)data pixelFormat:(CCTexture2DPixelFormat)pixelFormat pixelsWide:(NSUInteger)width pixelsHigh:(NSUInteger)height contentSize:(CGSize)size
{
if((self = [super init])) {
glGenTextures(1, &name_);
glBindTexture(GL_TEXTURE_2D, name_);
[self setAntiAliasTexParameters];
// Specify OpenGL texture image
switch(pixelFormat)
{
case kCCTexture2DPixelFormat_RGBA8888:
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
break;
case kCCTexture2DPixelFormat_RGBA4444:
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, data);
break;
case kCCTexture2DPixelFormat_RGB5A1:
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, data);
break;
case kCCTexture2DPixelFormat_RGB565:
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, data);
break;
case kCCTexture2DPixelFormat_A8:
glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, width, height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, data);
break;
default:
[NSException raise:NSInternalInconsistencyException format:@""];
}
size_ = size;
width_ = width;
height_ = height;
format_ = pixelFormat;
maxS_ = size.width / (float)width;
maxT_ = size.height / (float)height;
hasPremultipliedAlpha_ = NO;
}
return self;
}
- (void) dealloc
{
CCLOGINFO(@"cocos2d: deallocing %@", self);
if(name_)
glDeleteTextures(1, &name_);
[super dealloc];
}
- (NSString*) description
{
return [NSString stringWithFormat:@"<%@ = %08X | Name = %i | Dimensions = %ix%i | Coordinates = (%.2f, %.2f)>", [self class], self, name_, width_, height_, maxS_, maxT_];
}
-(CGSize) contentSize
{
CGSize ret;
ret.width = size_.width / CC_CONTENT_SCALE_FACTOR();
ret.height = size_.height / CC_CONTENT_SCALE_FACTOR();
return ret;
}
@end
#pragma mark -
#pragma mark CCTexture2D - Image
@implementation CCTexture2D (Image)
#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
- (id) initWithImage:(UIImage *)uiImage
#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED)
- (id) initWithImage:(CGImageRef)CGImage
#endif
{
NSUInteger POTWide, POTHigh;
CGContextRef context = nil;
void* data = nil;;
CGColorSpaceRef colorSpace;
void* tempData;
unsigned int* inPixel32;
unsigned short* outPixel16;
BOOL hasAlpha;
CGImageAlphaInfo info;
CGSize imageSize;
CCTexture2DPixelFormat pixelFormat;
#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
CGImageRef CGImage = uiImage.CGImage;
#endif
if(CGImage == NULL) {
CCLOG(@"cocos2d: CCTexture2D. Can't create Texture. UIImage is nil");
[self release];
return nil;
}
CCConfiguration *conf = [CCConfiguration sharedConfiguration];
#if CC_TEXTURE_NPOT_SUPPORT
if( [conf supportsNPOT] ) {
POTWide = CGImageGetWidth(CGImage);
POTHigh = CGImageGetHeight(CGImage);
} else
#endif
{
POTWide = ccNextPOT(CGImageGetWidth(CGImage));
POTHigh = ccNextPOT(CGImageGetHeight(CGImage));
}
NSUInteger maxTextureSize = [conf maxTextureSize];
if( POTHigh > maxTextureSize || POTWide > maxTextureSize ) {
CCLOG(@"cocos2d: WARNING: Image (%d x %d) is bigger than the supported %d x %d",
(unsigned int)POTWide, (unsigned int)POTHigh,
(unsigned int)maxTextureSize, (unsigned int)maxTextureSize);
[self release];
return nil;
}
info = CGImageGetAlphaInfo(CGImage);
hasAlpha = ((info == kCGImageAlphaPremultipliedLast) || (info == kCGImageAlphaPremultipliedFirst) || (info == kCGImageAlphaLast) || (info == kCGImageAlphaFirst) ? YES : NO);
size_t bpp = CGImageGetBitsPerComponent(CGImage);
colorSpace = CGImageGetColorSpace(CGImage);
if(colorSpace) {
if(hasAlpha || bpp >= 8)
pixelFormat = defaultAlphaPixelFormat_;
else {
CCLOG(@"cocos2d: CCTexture2D: Using RGB565 texture since image has no alpha");
pixelFormat = kCCTexture2DPixelFormat_RGB565;
}
} else {
// NOTE: No colorspace means a mask image
CCLOG(@"cocos2d: CCTexture2D: Using A8 texture since image is a mask");
pixelFormat = kCCTexture2DPixelFormat_A8;
}
imageSize = CGSizeMake(CGImageGetWidth(CGImage), CGImageGetHeight(CGImage));
// Create the bitmap graphics context
switch(pixelFormat) {
case kCCTexture2DPixelFormat_RGBA8888:
case kCCTexture2DPixelFormat_RGBA4444:
case kCCTexture2DPixelFormat_RGB5A1:
colorSpace = CGColorSpaceCreateDeviceRGB();
data = malloc(POTHigh * POTWide * 4);
info = hasAlpha ? kCGImageAlphaPremultipliedLast : kCGImageAlphaNoneSkipLast;
// info = kCGImageAlphaPremultipliedLast; // issue #886. This patch breaks BMP images.
context = CGBitmapContextCreate(data, POTWide, POTHigh, 8, 4 * POTWide, colorSpace, info | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
break;
case kCCTexture2DPixelFormat_RGB565:
colorSpace = CGColorSpaceCreateDeviceRGB();
data = malloc(POTHigh * POTWide * 4);
info = kCGImageAlphaNoneSkipLast;
context = CGBitmapContextCreate(data, POTWide, POTHigh, 8, 4 * POTWide, colorSpace, info | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
break;
case kCCTexture2DPixelFormat_A8:
data = malloc(POTHigh * POTWide);
info = kCGImageAlphaOnly;
context = CGBitmapContextCreate(data, POTWide, POTHigh, 8, POTWide, NULL, info);
break;
default:
[NSException raise:NSInternalInconsistencyException format:@"Invalid pixel format"];
}
CGContextClearRect(context, CGRectMake(0, 0, POTWide, POTHigh));
CGContextTranslateCTM(context, 0, POTHigh - imageSize.height);
CGContextDrawImage(context, CGRectMake(0, 0, CGImageGetWidth(CGImage), CGImageGetHeight(CGImage)), CGImage);
// Repack the pixel data into the right format
if(pixelFormat == kCCTexture2DPixelFormat_RGB565) {
//Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRRGGGGGGBBBBB"
tempData = malloc(POTHigh * POTWide * 2);
inPixel32 = (unsigned int*)data;
outPixel16 = (unsigned short*)tempData;
for(unsigned int i = 0; i < POTWide * POTHigh; ++i, ++inPixel32)
*outPixel16++ = ((((*inPixel32 >> 0) & 0xFF) >> 3) << 11) | ((((*inPixel32 >> 8) & 0xFF) >> 2) << 5) | ((((*inPixel32 >> 16) & 0xFF) >> 3) << 0);
free(data);
data = tempData;
}
else if (pixelFormat == kCCTexture2DPixelFormat_RGBA4444) {
//Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRGGGGBBBBAAAA"
tempData = malloc(POTHigh * POTWide * 2);
inPixel32 = (unsigned int*)data;
outPixel16 = (unsigned short*)tempData;
for(unsigned int i = 0; i < POTWide * POTHigh; ++i, ++inPixel32)
*outPixel16++ =
((((*inPixel32 >> 0) & 0xFF) >> 4) << 12) | // R
((((*inPixel32 >> 8) & 0xFF) >> 4) << 8) | // G
((((*inPixel32 >> 16) & 0xFF) >> 4) << 4) | // B
((((*inPixel32 >> 24) & 0xFF) >> 4) << 0); // A
free(data);
data = tempData;
}
else if (pixelFormat == kCCTexture2DPixelFormat_RGB5A1) {
//Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRRGGGGGBBBBBA"
tempData = malloc(POTHigh * POTWide * 2);
inPixel32 = (unsigned int*)data;
outPixel16 = (unsigned short*)tempData;
for(unsigned int i = 0; i < POTWide * POTHigh; ++i, ++inPixel32)
*outPixel16++ =
((((*inPixel32 >> 0) & 0xFF) >> 3) << 11) | // R
((((*inPixel32 >> 8) & 0xFF) >> 3) << 6) | // G
((((*inPixel32 >> 16) & 0xFF) >> 3) << 1) | // B
((((*inPixel32 >> 24) & 0xFF) >> 7) << 0); // A
free(data);
data = tempData;
}
self = [self initWithData:data pixelFormat:pixelFormat pixelsWide:POTWide pixelsHigh:POTHigh contentSize:imageSize];
// should be after calling super init
hasPremultipliedAlpha_ = (info == kCGImageAlphaPremultipliedLast || info == kCGImageAlphaPremultipliedFirst);
CGContextRelease(context);
[self releaseData: data];
return self;
}
@end
#pragma mark -
#pragma mark CCTexture2D - Text
@implementation CCTexture2D (Text)
#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
- (id) initWithString:(NSString*)string dimensions:(CGSize)dimensions alignment:(CCTextAlignment)alignment font:(id)uifont
{
NSAssert( uifont, @"Invalid font");
NSUInteger POTWide = ccNextPOT(dimensions.width);
NSUInteger POTHigh = ccNextPOT(dimensions.height);
unsigned char* data;
CGContextRef context;
CGColorSpaceRef colorSpace;
#if USE_TEXT_WITH_A8_TEXTURES
colorSpace = CGColorSpaceCreateDeviceGray();
data = calloc(POTHigh, POTWide);
context = CGBitmapContextCreate(data, POTWide, POTHigh, 8, POTWide, colorSpace, kCGImageAlphaNone);
#else
colorSpace = CGColorSpaceCreateDeviceRGB();
data = calloc(POTHigh, POTWide * 4);
context = CGBitmapContextCreate(data, POTWide, POTHigh, 8, 4 * POTWide, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
#endif
CGColorSpaceRelease(colorSpace);
if( ! context ) {
free(data);
[self release];
return nil;
}
CGContextSetGrayFillColor(context, 1.0f, 1.0f);
CGContextTranslateCTM(context, 0.0f, POTHigh);
CGContextScaleCTM(context, 1.0f, -1.0f); //NOTE: NSString draws in UIKit referential i.e. renders upside-down compared to CGBitmapContext referential
UIGraphicsPushContext(context);
// normal fonts
if( [uifont isKindOfClass:[UIFont class] ] )
[string drawInRect:CGRectMake(0, 0, dimensions.width, dimensions.height) withFont:uifont lineBreakMode:UILineBreakModeWordWrap alignment:alignment];
#if CC_FONT_LABEL_SUPPORT
else // ZFont class
[string drawInRect:CGRectMake(0, 0, dimensions.width, dimensions.height) withZFont:uifont lineBreakMode:UILineBreakModeWordWrap alignment:alignment];
#endif
UIGraphicsPopContext();
#if USE_TEXT_WITH_A8_TEXTURES
self = [self initWithData:data pixelFormat:kCCTexture2DPixelFormat_A8 pixelsWide:POTWide pixelsHigh:POTHigh contentSize:dimensions];
#else
self = [self initWithData:data pixelFormat:kCCTexture2DPixelFormat_RGBA8888 pixelsWide:POTWide pixelsHigh:POTHigh contentSize:dimensions];
#endif
CGContextRelease(context);
[self releaseData: data];
return self;
}
#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED)
- (id) initWithString:(NSString*)string dimensions:(CGSize)dimensions alignment:(CCTextAlignment)alignment attributedString:(NSAttributedString*)stringWithAttributes
{
NSAssert( stringWithAttributes, @"Invalid stringWithAttributes");
NSUInteger POTWide = ccNextPOT(dimensions.width);
NSUInteger POTHigh = ccNextPOT(dimensions.height);
unsigned char* data;
NSSize realDimensions = [stringWithAttributes size];
//Alignment
float xPadding = 0;
// Mac crashes if the width or height is 0
if( realDimensions.width > 0 && realDimensions.height > 0 ) {
switch (alignment) {
case CCTextAlignmentLeft: xPadding = 0; break;
case CCTextAlignmentCenter: xPadding = (dimensions.width-realDimensions.width)/2.0f; break;
case CCTextAlignmentRight: xPadding = dimensions.width-realDimensions.width; break;
default: break;
}
//Disable antialias
[[NSGraphicsContext currentContext] setShouldAntialias:NO];
NSImage *image = [[NSImage alloc] initWithSize:NSMakeSize(POTWide, POTHigh)];
[image lockFocus];
[stringWithAttributes drawAtPoint:NSMakePoint(xPadding, POTHigh-dimensions.height)]; // draw at offset position
NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc] initWithFocusedViewRect:NSMakeRect (0.0f, 0.0f, POTWide, POTHigh)];
[image unlockFocus];
data = (unsigned char*) [bitmap bitmapData]; //Use the same buffer to improve the performance.
for(int i = 0; i<(POTWide*POTHigh); i++) //Convert RGBA8888 to A8
data[i] = data[i*4+3];
self = [self initWithData:data pixelFormat:kCCTexture2DPixelFormat_A8 pixelsWide:POTWide pixelsHigh:POTHigh contentSize:dimensions];
[bitmap release];
[image release];
} else {
[self release];
return nil;
}
return self;
}
#endif // __MAC_OS_X_VERSION_MAX_ALLOWED
- (id) initWithString:(NSString*)string fontName:(NSString*)name fontSize:(CGFloat)size
{
CGSize dim;
#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
id font;
font = [UIFont fontWithName:name size:size];
if( font )
dim = [string sizeWithFont:font];
#if CC_FONT_LABEL_SUPPORT
if( ! font ){
font = [[FontManager sharedManager] zFontWithName:name pointSize:size];
if (font)
dim = [string sizeWithZFont:font];
}
#endif // CC_FONT_LABEL_SUPPORT
if( ! font ) {
CCLOG(@"cocos2d: Unable to load font %@", name);
[self release];
return nil;
}
return [self initWithString:string dimensions:dim alignment:CCTextAlignmentCenter font:font];
#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED)
{
NSAttributedString *stringWithAttributes =
[[[NSAttributedString alloc] initWithString:string
attributes:[NSDictionary dictionaryWithObject:[[NSFontManager sharedFontManager]
fontWithFamily:name
traits:NSUnboldFontMask | NSUnitalicFontMask
weight:0
size:size]
forKey:NSFontAttributeName]
]
autorelease];
dim = NSSizeToCGSize( [stringWithAttributes size] );
return [self initWithString:string dimensions:dim alignment:CCTextAlignmentCenter attributedString:stringWithAttributes];
}
#endif // __MAC_OS_X_VERSION_MAX_ALLOWED
}
- (id) initWithString:(NSString*)string dimensions:(CGSize)dimensions alignment:(CCTextAlignment)alignment fontName:(NSString*)name fontSize:(CGFloat)size
{
#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
id uifont = nil;
uifont = [UIFont fontWithName:name size:size];
#if CC_FONT_LABEL_SUPPORT
if( ! uifont )
uifont = [[FontManager sharedManager] zFontWithName:name pointSize:size];
#endif // CC_FONT_LABEL_SUPPORT
if( ! uifont ) {
CCLOG(@"cocos2d: Texture2d: Invalid Font: %@. Verify the .ttf name", name);
[self release];
return nil;
}
return [self initWithString:string dimensions:dimensions alignment:alignment font:uifont];
#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED)
//String with attributes
NSAttributedString *stringWithAttributes =
[[[NSAttributedString alloc] initWithString:string
attributes:[NSDictionary dictionaryWithObject:[[NSFontManager sharedFontManager]
fontWithFamily:name
traits:NSUnboldFontMask | NSUnitalicFontMask
weight:0
size:size]
forKey:NSFontAttributeName]
]
autorelease];
return [self initWithString:string dimensions:dimensions alignment:CCTextAlignmentCenter attributedString:stringWithAttributes];
#endif // Mac
}
@end
#pragma mark -
#pragma mark CCTexture2D - PVRSupport
@implementation CCTexture2D (PVRSupport)
// By default PVR images are treated as if they don't have the alpha channel premultiplied
static BOOL PVRHaveAlphaPremultiplied_ = NO;
#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
-(id) initWithPVRTCData: (const void*)data level:(int)level bpp:(int)bpp hasAlpha:(BOOL)hasAlpha length:(int)length
{
// GLint saveName;
if( ! [[CCConfiguration sharedConfiguration] supportsPVRTC] ) {
CCLOG(@"cocos2d: WARNING: PVRTC images is not supported");
[self release];
return nil;
}
if((self = [super init])) {
glGenTextures(1, &name_);
glBindTexture(GL_TEXTURE_2D, name_);
[self setAntiAliasTexParameters];
GLenum format;
GLsizei size = length * length * bpp / 8;
if(hasAlpha) {
format = (bpp == 4) ? GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG : GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
} else {
format = (bpp == 4) ? GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG : GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
}
if(size < 32) {
size = 32;
}
glCompressedTexImage2D(GL_TEXTURE_2D, level, format, length, length, 0, size, data);
size_ = CGSizeMake(length, length);
width_ = length;
height_ = length;
maxS_ = 1.0f;
maxT_ = 1.0f;
hasPremultipliedAlpha_ = PVRHaveAlphaPremultiplied_;
}
return self;
}
#endif // __IPHONE_OS_VERSION_MAX_ALLOWED
-(id) initWithPVRFile: (NSString*) file
{
if( (self = [super init]) ) {
CCTexturePVR *pvr = [[CCTexturePVR alloc] initWithContentsOfFile:file];
if( pvr ) {
pvr.retainName = YES; // don't dealloc texture on release
name_ = pvr.name; // texture id
maxS_ = 1; // only POT texture are supported
maxT_ = 1;
width_ = pvr.width;
height_ = pvr.height;
size_ = CGSizeMake(width_, height_);
hasPremultipliedAlpha_ = PVRHaveAlphaPremultiplied_;
[pvr release];
[self setAntiAliasTexParameters];
} else {
CCLOG(@"cocos2d: Couldn't load PVR image");
[self release];
return nil;
}
}
return self;
}
+(void) PVRImagesHavePremultipliedAlpha:(BOOL)haveAlphaPremultiplied
{
PVRHaveAlphaPremultiplied_ = haveAlphaPremultiplied;
}
@end
#pragma mark -
#pragma mark CCTexture2D - Drawing
@implementation CCTexture2D (Drawing)
- (void) drawAtPoint:(CGPoint)point
{
GLfloat coordinates[] = { 0.0f, maxT_,
maxS_, maxT_,
0.0f, 0.0f,
maxS_, 0.0f };
GLfloat width = (GLfloat)width_ * maxS_,
height = (GLfloat)height_ * maxT_;
GLfloat vertices[] = { point.x, point.y, 0.0f,
width + point.x, point.y, 0.0f,
point.x, height + point.y, 0.0f,
width + point.x, height + point.y, 0.0f };
glBindTexture(GL_TEXTURE_2D, name_);
glVertexPointer(3, GL_FLOAT, 0, vertices);
glTexCoordPointer(2, GL_FLOAT, 0, coordinates);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
}
- (void) drawInRect:(CGRect)rect
{
GLfloat coordinates[] = { 0.0f, maxT_,
maxS_, maxT_,
0.0f, 0.0f,
maxS_, 0.0f };
GLfloat vertices[] = { rect.origin.x, rect.origin.y, /*0.0f,*/
rect.origin.x + rect.size.width, rect.origin.y, /*0.0f,*/
rect.origin.x, rect.origin.y + rect.size.height, /*0.0f,*/
rect.origin.x + rect.size.width, rect.origin.y + rect.size.height, /*0.0f*/ };
glBindTexture(GL_TEXTURE_2D, name_);
glVertexPointer(2, GL_FLOAT, 0, vertices);
glTexCoordPointer(2, GL_FLOAT, 0, coordinates);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
}
@end
#pragma mark -
#pragma mark CCTexture2D - GLFilter
//
// Use to apply MIN/MAG filter
//
@implementation CCTexture2D (GLFilter)
-(void) generateMipmap
{
NSAssert( width_ == ccNextPOT(width_) && height_ == ccNextPOT(height_), @"Mimpap texture only works in POT textures");
glBindTexture( GL_TEXTURE_2D, name_ );
ccglGenerateMipmap(GL_TEXTURE_2D);
}
-(void) setTexParameters: (ccTexParams*) texParams
{
NSAssert( (width_ == ccNextPOT(width_) && height_ == ccNextPOT(height_)) ||
(texParams->wrapS == GL_CLAMP_TO_EDGE && texParams->wrapT == GL_CLAMP_TO_EDGE),
@"GL_CLAMP_TO_EDGE should be used in NPOT textures");
glBindTexture( GL_TEXTURE_2D, self.name );
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, texParams->minFilter );
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, texParams->magFilter );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, texParams->wrapS );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, texParams->wrapT );
}
-(void) setAliasTexParameters
{
ccTexParams texParams = { GL_NEAREST, GL_NEAREST, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE };
[self setTexParameters: &texParams];
}
-(void) setAntiAliasTexParameters
{
ccTexParams texParams = { GL_LINEAR, GL_LINEAR, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE };
[self setTexParameters: &texParams];
}
@end
#pragma mark -
#pragma mark CCTexture2D - Pixel Format
//
// Texture options for images that contains alpha
//
@implementation CCTexture2D (PixelFormat)
+(void) setDefaultAlphaPixelFormat:(CCTexture2DPixelFormat)format
{
defaultAlphaPixelFormat_ = format;
}
+(CCTexture2DPixelFormat) defaultAlphaPixelFormat
{
return defaultAlphaPixelFormat_;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment