CCSprite does not display on iPad+Retina - ios

I have another weird problem which I have not been able to solve in reasonable time. My app works well on iPhone 4S and iPod 4-th with and without retina enabled. It also works well on iPad3 without retina. But when iPad has retina enabled, CCSprites just do not appear. I do have camera image underlay which is shown but not graphics on top of it. I think I have all "-hd" versions of files available and they are also shown well on iPhone in retina mode.
I paste code which I think is related:
- (void) applicationDidFinishLaunching:(UIApplication*)applicationv{
CCLOG(#"applicationDidFinishLaunching");
window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
if( ! [CCDirector setDirectorType:kCCDirectorTypeDisplayLink] )
[CCDirector setDirectorType:kCCDirectorTypeDefault];
CCDirector *director = [CCDirector sharedDirector];
viewController = [[RootViewController alloc] initWithNibName:nil bundle:nil];
viewController.wantsFullScreenLayout = YES;
EAGLView *glView = [EAGLView viewWithFrame:[window bounds]
pixelFormat:kEAGLColorFormatRGBA8
depthFormat:0 // GL_DEPTH_COMPONENT16_OES
];
// attach the openglView to the director
[director setOpenGLView:glView];
// Enables High Res mode (Retina Display) on iPhone 4 and maintains low res on all other devices
if( ! [director enableRetinaDisplay:YES] )
CCLOG(#"Retina Display Not supported");
#if GAME_AUTOROTATION == kGameAutorotationUIViewController
[director setDeviceOrientation:kCCDeviceOrientationPortrait];
#else
[director setDeviceOrientation:kCCDeviceOrientationLandscapeRight];
#endif
[director setAnimationInterval:1.0/20];
[director setDisplayFPS:NO];
[viewController setView:glView];
[window addSubview: viewController.view];
[CCDirector sharedDirector].openGLView.backgroundColor = [UIColor clearColor];
[CCDirector sharedDirector].openGLView.opaque = NO;
glClearColor(0.0, 0.0, 0.0, 0.0);
_cameraView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
_cameraView.opaque = NO;
_cameraView.backgroundColor=[UIColor clearColor];
[window addSubview:_cameraView];
_imageView = [[UIImageView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
[_cameraView addSubview:_imageView];
[window bringSubviewToFront:viewController.view];
[window makeKeyAndVisible];
[CCTexture2D setDefaultAlphaPixelFormat:kCCTexture2DPixelFormat_RGBA8888];
CCScene *scene = [CCScene node];
_layer =[[[HelloWorldLayer alloc] init] autorelease];
_menu =[MenuScene node];
[scene addChild:_layer];
[_layer addChild:_menu];
viewController.fdLayer = _layer;
_layer.root = viewController;
[[CCDirector sharedDirector] runWithScene: scene];
And MenuScene.m:
#implementation MenuScene
+(id) scene {
CCScene* scene = [CCScene node];
CCLayer* layer = [MenuScene node];
[scene addChild:layer];
return scene;
}
-(id) init {
if ((self = [super init])) {
CCLOG(#"init %#", self);
CGSize screen = [[CCDirector sharedDirector] winSize];
CCLOG(#"%f %f",screen.width,screen.height);
CCLayerColor *b = [CCLayerColor layerWithColor:ccc4(0, 0, 0, 100) width:screen.width height:screen.height/4];
b.isRelativeAnchorPoint=YES;
b.anchorPoint=ccp(0, 1); // left top corner
b.position=ccp(0, screen.height);
[self addChild:b];
CCSprite* bg = [CCSprite spriteWithFile:#"01-main-logo.png"];
bg.position = CGPointMake(screen.width / 2, screen.height*0.12);
[b addChild:bg];
EDIT: I made temporary hack:
if (UI_USER_INTERFACE_IDIOM() != UIUserInterfaceIdiomPad) {
// Enables High Res mode (Retina Display) on iPhone 4 and maintains low res on all other devices
if( ! [director enableRetinaDisplay:YES] )
CCLOG(#"Retina Display Not supported");
}
but question remains - why?

Problem solved. "Make Clean" was not enough. Keeping "Option" button down when pressing "Clean" forces even more to be cleaned up. After that things started to work. There is also possibility that it was related to "Compress PNG files" setting which I changed to "No" after problems started but it was maybe not enforced. Anyway problem gone away and thanks for watching :)

Related

Newly created UIWindow is sideways when app is opened on landscape

I have an iPad application in which I create a new UIWindow at the beginning of the app and show it while I do some resource synchronization. When the app is launched while the iPad is on portrait orientation, everything's fine. However, when on landscape orientation, the newly created UIWindow's size seems fine but it appears sideways and it's coordinates seem all weird. Here are the screenshots for both portrait and landscape orientations:
The landscape one is obtained by rotating to right once.
The piece of code where I create and show the UIWindow is as follows:
UIWindow *window=[UIApplication sharedApplication].keyWindow;
self.progressWindow = [[UIWindow alloc] initWithFrame:window.frame];
self.progressWindow.backgroundColor = [UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:0.5f];
self.progressWindow.windowLevel = UIWindowLevelAlert;
/* some other code to create the subviews */
[self.progressWindow makeKeyAndVisible];
This problem only occurs on iOS 8.
As far as I understood, newly created UIWindow's do not rotate automatically when the orientation changes. I don't know whether this is new to iOS 8 or if it is a bug, but I was able to overcome the problem with the following piece of code:
UIWindow *window=[UIApplication sharedApplication].keyWindow;
self.progressWindow = [[UIWindow alloc] initWithFrame:window.frame];
self.progressWindow.backgroundColor = [UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:0.5f];
self.progressWindow.windowLevel = UIWindowLevelAlert;
/* some other code to create the subviews */
[self handleOrientationChange];
[self.progressWindow makeKeyAndVisible];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(handleOrientationChange) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
Implementation for handleOrientationChange is as follows:
#define DegreesToRadians(degrees) (degrees * M_PI / 180)
- (void)handleOrientationChange
{
if (self.progressWindow)
{
// rotate the UIWindow manually
UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
[self.progressWindow setTransform:[self transformForOrientation:orientation]];
// resize the UIWindow according to the new screen size
if ([[UIScreen mainScreen] respondsToSelector:#selector(nativeBounds)])
{
// iOS 8
CGRect screenRect = [UIScreen mainScreen].nativeBounds;
CGRect progressWindowFrame = self.progressWindow.frame;
progressWindowFrame.origin.x = 0;
progressWindowFrame.origin.y = 0;
progressWindowFrame.size.width = screenRect.size.width / [UIScreen mainScreen].nativeScale;
progressWindowFrame.size.height = screenRect.size.height / [UIScreen mainScreen].nativeScale;
self.progressWindow.frame = progressWindowFrame;
}
else
{
// iOs 7 or below
CGRect screenRect = [UIScreen mainScreen].bounds;
CGRect progressWindowFrame = self.progressWindow.frame;
progressWindowFrame.origin.x = 0;
progressWindowFrame.origin.y = 0;
progressWindowFrame.size.width = screenRect.size.width;
progressWindowFrame.size.height = screenRect.size.height;
self.progressWindow.frame = progressWindowFrame;
}
}
}
- (CGAffineTransform)transformForOrientation:(UIInterfaceOrientation)orientation {
switch (orientation) {
case UIInterfaceOrientationLandscapeLeft:
return CGAffineTransformMakeRotation(-DegreesToRadians(90));
case UIInterfaceOrientationLandscapeRight:
return CGAffineTransformMakeRotation(DegreesToRadians(90));
case UIInterfaceOrientationPortraitUpsideDown:
return CGAffineTransformMakeRotation(DegreesToRadians(180));
case UIInterfaceOrientationPortrait:
default:
return CGAffineTransformMakeRotation(DegreesToRadians(0));
}
}
I got the idea from the accepted answer of this question.
The shared application maintains a reference to the window through its
key- Window property:
let w = UIApplication.sharedApplication().keyWindow
That reference, however,
is slightly volatile, because the system can create temporary windows
and interpose them as the application’s key window.
try instead
[[UIApplication sharedApplication].delegate window]

Game not rotating PortraitUpsideDown

The orientation is shown in 'support interface orientations' in the info.plist file, however still does not rotate when turned.
I am looking to make Portrait & Portraitupsidedown
This is from the RootViewController.m
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
//
// There are 2 ways to support auto-rotation:
// - The OpenGL / cocos2d way
// - Faster, but doesn't rotate the UIKit objects
// - The ViewController way
// - A bit slower, but the UiKit objects are placed in the right place
//
#if GAME_AUTOROTATION==kGameAutorotationNone
//
// EAGLView won't be autorotated.
// Since this method should return YES in at least 1 orientation,
// we return YES only in the Portrait orientation
//
#elif GAME_AUTOROTATION==kGameAutorotationCCDirector
//
// EAGLView will be rotated by cocos2d
//
// Sample: Autorotate only in landscape mode
//
if( interfaceOrientation == UIInterfaceOrientationLandscapeLeft ) {
[[CCDirector sharedDirector] setDeviceOrientation: kCCDeviceOrientationLandscapeRight];
} else if( interfaceOrientation == UIInterfaceOrientationLandscapeRight) {
[[CCDirector sharedDirector] setDeviceOrientation: kCCDeviceOrientationLandscapeLeft];
}
// Since this method should return YES in at least 1 orientation,
// we return YES only in the Portrait orientation
return ( interfaceOrientation == UIInterfaceOrientationPortrait );
#elif GAME_AUTOROTATION == kGameAutorotationUIViewController
//
// EAGLView will be rotated by the UIViewController
//
// Sample: Autorotate only in landscpe mode
//
// return YES for the supported orientations
return ( UIInterfaceOrientationIsPortrait(interfaceOrientation));
#else
#error Unknown value in GAME_AUTOROTATION
#endif // GAME_AUTOROTATION
// Shold not happen
return NO;
}
//
// This callback only will be called when GAME_AUTOROTATION == kGameAutorotationUIViewController
//
#if GAME_AUTOROTATION == kGameAutorotationUIViewController
-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
//
// Assuming that the main window has the size of the screen
// BUG: This won't work if the EAGLView is not fullscreen
///
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGRect rect = CGRectZero;
if(toInterfaceOrientation == UIInterfaceOrientationPortrait || toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)
rect = screenRect;
else if(toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight)
rect.size = CGSizeMake( screenRect.size.height, screenRect.size.width );
CCDirector *director = [CCDirector sharedDirector];
EAGLView *glView = [director openGLView];
float contentScaleFactor = [director contentScaleFactor];
if( contentScaleFactor != 1 ) {
rect.size.width *= contentScaleFactor;
rect.size.height *= contentScaleFactor;
}
glView.frame = rect;
}
#endif // GAME_AUTOROTATION == kGameAutorotationUIViewController
From the AppDelegate.m file I also have;
// Init the window
window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Try to use CADisplayLink director
// if it fails (SDK < 3.1) use the default director
if( ! [CCDirector setDirectorType:kCCDirectorTypeDisplayLink] )
[CCDirector setDirectorType:kCCDirectorTypeDefault];
CCDirector *director = [CCDirector sharedDirector];
// Init the View Controller
viewController = [[RootViewController alloc] initWithNibName:nil bundle:nil];
viewController.wantsFullScreenLayout = YES;
//
// Create the EAGLView manually
// 1. Create a RGB565 format. Alternative: RGBA8
// 2. depth format of 0 bit. Use 16 or 24 bit for 3d effects, like CCPageTurnTransition
//
//
EAGLView *glView = [EAGLView viewWithFrame:[window bounds]
pixelFormat:kEAGLColorFormatRGB565 // kEAGLColorFormatRGBA8
depthFormat:0 // GL_DEPTH_COMPONENT16_OES
];
// attach the openglView to the director
[director setOpenGLView:glView];
// // Enables High Res mode (Retina Display) on iPhone 4 and maintains low res on all other devices
if( ! [director enableRetinaDisplay:YES] )
CCLOG(#"Retina Display Not supported");
//
// VERY IMPORTANT:
// If the rotation is going to be controlled by a UIViewController
// then the device orientation should be "Portrait".
//
// IMPORTANT:
// By default, this template only supports Landscape orientations.
// Edit the RootViewController.m file to edit the supported orientations.
//
[director setDeviceOrientation:kCCDeviceOrientationPortrait];
[director setAnimationInterval:1.0/60];
[director setDisplayFPS:NO];
// make the OpenGLView a child of the view controller
[viewController setView:glView];
// make the View Controller a child of the main window
[window addSubview: viewController.view];
[window makeKeyAndVisible];
I have other games, using Cocos2d that I have managed to get to rotate and I cross-checked the settings with those, they are the same, so I cannot figure out why it is not rotating?
EDIT -
This could be a telling message about this...
Application windows are expected to have a root view controller at the end of application launch
Try adding rootViewController
[window setRootViewController: viewController];
In your rootview controller, comment out
CCDirector *director = [CCDirector sharedDirector];
EAGLView *glView = [director openGLView];
float contentScaleFactor = [director contentScaleFactor];
if( contentScaleFactor != 1 ) {
rect.size.width *= contentScaleFactor;
rect.size.height *= contentScaleFactor;
}
glView.frame = rect;

IOS Landscape Mode not working OPEN GL

Ok tried almost everything and it didn't work.
I need my engine to start up in LandscapeRight mode, therefore i call:
//
[[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight animated:NO];
The problem is that the rest is not rotated at all,
I managed to rotate the view by using:
[pExternViewController setTransform:CGAffineTransformMakeRotation(M_PI/2.0f)];
But it doesn't work as expected, the Frame Buffer size is correct now:
FrameBuffer: width: 960, height: 640
Still you can see it is not 960x640, and i can't figure out why?
Ok, finally made it.
First add this key to your plist file (required)
<key>UILaunchStoryboardName</key>
<string>Launch Screen</string>
Screen Size definitions
#define SCREEN_WIDTH (IOS_VERSION_LOWER_THAN_8 ? (UIInterfaceOrientationIsPortrait([UIApplication sharedApplication].statusBarOrientation) ? [[UIScreen mainScreen] bounds].size.width : [[UIScreen mainScreen] bounds].size.height) : [[UIScreen mainScreen] bounds].size.width)
#define SCREEN_HEIGHT (IOS_VERSION_LOWER_THAN_8 ? (UIInterfaceOrientationIsPortrait([UIApplication sharedApplication].statusBarOrientation) ? [[UIScreen mainScreen] bounds].size.height : [[UIScreen mainScreen] bounds].size.width) : [[UIScreen mainScreen] bounds].size.height)
#define IOS_VERSION_LOWER_THAN_8 (NSFoundationVersionNumber <= NSFoundationVersionNumber_iOS_7_1)
The window initialization
- (void) applicationDidFinishLaunching: (UIApplication*) application
{
// Start in Landscape
[[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight animated:NO];
// Disable Auto Lock screen
[[UIApplication sharedApplication] setIdleTimerDisabled: YES];
// Set Bounds with the proper screen resolution
CGRect screenBounds = [[UIScreen mainScreen] bounds];
screenBounds = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
// Create window and view controler
m_window = [[UIWindow alloc] initWithFrame: screenBounds];
m_window.backgroundColor = [UIColor redColor];
// Create new view controller
pExternViewController = [SvgzViewController alloc] ;
// Initialize view controler with all pointers set up
if( [pExternViewController initWithFrame: screenBounds ] == nil)
{
assert(!"Failed to initialize screen");
exit(0);
}
// Rotate the window
[m_window setTransform:CGAffineTransformMakeRotation(M_PI/2.0f)];
// Set the proper window center after transformation
m_window.center = CGPointMake(screenBounds.size.height/2, screenBounds.size.width/2);
// Add GL window
[m_window addSubview: pExternViewController];
//
[m_window makeKeyAndVisible];
}
At least no GL side change has to be done by doing it this way.

How do I fix this random continuous slow down in Cocos2D 2.1 in iOS 7?

I've had a slow down issue since around September when I upgraded my iPad to iOS 7.
Using: Cocos2D 2.1 on iOS 7.1
I've done a lot of testing trying to solve this problem, but so far I cannot find any root cause.
Some clues:
I found if I turn off particles it happens less often, but doesn't
get rid of it entirely.
Sometimes it occurs when a scene starts.
When the slow down happens, the frame rate visibly drops, but the debug frame rate number does not change. It could stay at 60, but it's still slower.
When the slow down starts, it persists until a new scene is loaded.
A clue that makes me think this may be caused outside of the scene or cocos2D, is that the debug frame rate number does not change. Could it be the way I have my delegate setup?
I pasted the code below. It's kind of a mess because it's been through a lot.
.h
#import <UIKit/UIKit.h>
#import "cocos2d.h"
#import "ForegroundLabelView.h"
#import "ParallaxCCLayer.h"
#class ParallaxCCLayer;
#import "ColorBGView.h"
#class RootViewController;
#interface cocosTestsAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window_;
RootViewController *viewController;
ForegroundLabelView *foregroundLabelView;
ParallaxCCLayer *parallaxCCLayer;
CAGradientLayer *bgLayer;
CAGradientLayer *bgLayerTransition;
CCDirectorIOS *director_; // weak ref
}
#property (nonatomic, retain) UIWindow *window;
#property (nonatomic, retain) RootViewController *viewController;
#property (nonatomic, retain) ForegroundLabelView *foregroundLabelView;
#property (nonatomic, retain) ParallaxCCLayer *parallaxCCLayer;
#property (nonatomic, retain) CAGradientLayer *bgLayer;
#property (nonatomic, retain) CAGradientLayer *bgLayerTransition;
#property (readonly) CCDirectorIOS *director;
-(void) resumeGame:(NSTimer *) sender;
-(void) changeColorBGViewWithName:(NSString *)name;
-(void) adjustBGViewPosWithXOffset:(float)xOffset withYOffset:(float)yOffset;
-(void) addBGLayerTransitionWithName:(NSString *)name withXOffset:(float)xOffset withYOffset:(float)yOffset;
-(void) removeBGLayerTransition;
#end
.m
#import "cocosTestsAppDelegate.h"
#import "GameConfig.h"
#import "BlankScene.h"
#import "RootViewController.h"
#import "ExGlobal.h"
#implementation cocosTestsAppDelegate
#synthesize window=window_, director=director_, viewController, foregroundLabelView, parallaxCCLayer, bgLayer, bgLayerTransition;
- (void) removeStartupFlicker
{
//
// THIS CODE REMOVES THE STARTUP FLICKER
//
// Uncomment the following code if you Application only supports landscape mode
//
#if GAME_AUTOROTATION == kGameAutorotationUIViewController
//CC_ENABLE_DEFAULT_GL_STATES();
//CCDirector *director = [CCDirector sharedDirector];
//CGSize size = [director winSize];
//CCSprite *sprite = [CCSprite spriteWithFile:#"Default.png"];
//sprite.position = ccp(size.width/2, size.height/2);
//sprite.rotation = -90;
//[sprite visit];
//[[director openGLView] swapBuffers];
//CC_ENABLE_DEFAULT_GL_STATES();
#endif // GAME_AUTOROTATION == kGameAutorotationUIViewController
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Init the window
window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Try to use CADisplayLink director
// if it fails (SDK < 3.1) use the default director
// if( ! [CCDirector setDirectorType:kCCDirectorTypeDisplayLink] )
// [CCDirector setDirectorType:kCCDirectorTypeDefault];
//CCDirector *director = [CCDirector sharedDirector];
// Init the View Controller
viewController = [[RootViewController alloc] initWithNibName:nil bundle:nil];
//viewController.wantsFullScreenLayout = YES;
viewController.edgesForExtendedLayout = UIRectEdgeAll;
//
// Create the EAGLView manually
// 1. Create a RGB565 format. Alternative: RGBA8
// 2. depth format of 0 bit. Use 16 or 24 bit for 3d effects, like CCPageTurnTransition
//
//
// EAGLView *glView = [EAGLView viewWithFrame:[window bounds]
// pixelFormat:kEAGLColorFormatRGBA8 // kEAGLColorFormatRGBA8, kEAGLColorFormatRGB565
// depthFormat:0 // GL_DEPTH_COMPONENT16_OES
// ];
CCGLView *glView = [CCGLView viewWithFrame:[window_ bounds]
pixelFormat:kEAGLColorFormatRGBA8
depthFormat:GL_DEPTH24_STENCIL8_OES
preserveBackbuffer:NO
sharegroup:nil
multiSampling:NO
numberOfSamples:0];
[glView setMultipleTouchEnabled:YES];
director_ = (CCDirectorIOS*) [CCDirector sharedDirector];
[director_ setDisplayStats:YES];
[director_ setAnimationInterval:1.0/60];
// attach the openglView to the director
[director_ setView:glView];
// 2D projection
[director_ setProjection:kCCDirectorProjection2D];
// // Enables High Res mode (Retina Display) on iPhone 4 and maintains low res on all other devices
if( ! [director_ enableRetinaDisplay:NO] )
CCLOG(#"Retina Display Not supported");
// Default texture format for PNG/BMP/TIFF/JPEG/GIF images
// It can be RGBA8888, RGBA4444, RGB5_A1, RGB565
// You can change anytime.
[CCTexture2D setDefaultAlphaPixelFormat:kCCTexture2DPixelFormat_RGBA8888]; //kCCTexture2DPixelFormat_RGBA8888
// If the 1st suffix is not found and if fallback is enabled then fallback suffixes are going to searched. If none is found, it will try with the name without suffix.
// On iPad HD : "-ipadhd", "-ipad", "-hd"
// On iPad : "-ipad", "-hd"
// On iPhone HD: "-hd"
CCFileUtils *sharedFileUtils = [CCFileUtils sharedFileUtils];
[sharedFileUtils setEnableFallbackSuffixes:NO]; // Default: NO. No fallback suffixes are going to be used
//[sharedFileUtils setiPhoneRetinaDisplaySuffix:#"-hd"]; // Default on iPhone RetinaDisplay is "-hd"
//[sharedFileUtils setiPadSuffix:#"-ipad"]; // Default on iPad is "ipad"
//[sharedFileUtils setiPadRetinaDisplaySuffix:#"-ipadhd"]; // Default on iPad RetinaDisplay is "-ipadhd"
[sharedFileUtils setiPadRetinaDisplaySuffix:#"-hd"];
glView.opaque = NO;
glClearColor(0.0f,0.0f,0.0f,0.0f);
//glClear(GL_COLOR_BUFFER_BIT);
// Assume that PVR images have premultiplied alpha
[CCTexture2D PVRImagesHavePremultipliedAlpha:YES];
//
// VERY IMPORTANT:
// If the rotation is going to be controlled by a UIViewController
// then the device orientation should be "Portrait".
//
// IMPORTANT:
// By default, this template only supports Landscape orientations.
// Edit the RootViewController.m file to edit the supported orientations.
//
//#if GAME_AUTOROTATION == kGameAutorotationUIViewController
// [director_ setDeviceOrientation:kCCDeviceOrientationPortrait];
//#else
// [director setDeviceOrientation:kCCDeviceOrientationLandscapeLeft];
//#endif
//[director setDisplayFPS:[[ExGlobal sharedSingleton] debugState:#"FramesPerSec"]];
// color/gradient BG
bgLayer = [ColorBGView createGradientWithName:#"darkCave"];
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat screenHeight = screenRect.size.height;
bgLayer.frame = CGRectMake(0, 0, screenHeight, screenWidth);
[viewController.view.layer insertSublayer:bgLayer atIndex:0];
// make the OpenGLView a child of the view controller
glView.frame = CGRectMake(0, 0, screenHeight, screenWidth);
[viewController.view insertSubview:glView atIndex:2];
viewController.view.opaque = YES;
viewController.view.backgroundColor = [UIColor blackColor];
// make the View Controllers childs of the main window
window_.rootViewController = viewController;
parallaxCCLayer = [[ParallaxCCLayer alloc] init];
[[CCDirector sharedDirector] setNotificationNode:parallaxCCLayer]; // Layer should be placed here
[parallaxCCLayer onEnter]; // Schedule for updates
foregroundLabelView = [[ForegroundLabelView alloc] init];
foregroundLabelView.frame = CGRectMake(0, 0, screenHeight, screenWidth);
[viewController.view insertSubview:foregroundLabelView atIndex:3];
foregroundLabelView.hidden = YES;
[foregroundLabelView release];
[window_ makeKeyAndVisible];
// Removes the startup flicker
[self removeStartupFlicker];
// Run the intro Scene
[[CCDirector sharedDirector] runWithScene: [BlankScene scene]];
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application {
[[CCDirector sharedDirector] pause];
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
[[CCDirector sharedDirector] resume];
}
-(void) resumeGame:(NSTimer *) sender {
[[CCDirector sharedDirector] resume];
}
-(void) changeColorBGViewWithName:(NSString *)name {
//NSLog(#"RECOLORED ****** %#",name);
bgLayer = [ColorBGView createGradientWithName:name];
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat screenHeight = screenRect.size.height;
bgLayer.frame = CGRectMake(0, 0, screenHeight, screenWidth);
[viewController.view.layer replaceSublayer:[[viewController.view.layer sublayers] objectAtIndex:0] with:bgLayer];
}
-(void) adjustBGViewPosWithXOffset:(float)xOffset withYOffset:(float)yOffset {
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.height;
CGFloat screenHeight = screenRect.size.width;
CGFloat startX = screenWidth*xOffset;
CGFloat startY = screenHeight*yOffset;
//NSLog(#"%f",screenWidth*yOffset);
//NSLog(#"%f",screenHeight*yOffset);
[bgLayer removeAllAnimations];
bgLayer.frame = CGRectMake(startX, startY, screenWidth, screenHeight);
CGFloat transOffsetX;
CGFloat transOffsetY;
if(startX > 0){
transOffsetX = screenWidth*-1;
transOffsetY = 0;
}
else if(startX < 0){
transOffsetX = screenWidth;
transOffsetY = 0;
}
else if(startY > 0){
transOffsetX = 0;
transOffsetY = screenHeight*-1;
}
else if(startY < 0){
transOffsetX = 0;
transOffsetY = screenHeight;
}
//check needs to be performed to see if frames are still being requested to change
//even though both x AND y are 0
if(fabs(xOffset) > 0 | fabs(yOffset) > 0){
//NSLog(#"moving *****x=%f y=%f",xOffset,yOffset);
[bgLayerTransition removeAllAnimations];
bgLayerTransition.frame = CGRectMake(startX+transOffsetX, startY+transOffsetY, screenWidth, screenHeight);
}
}
-(void) addBGLayerTransitionWithName:(NSString *)name withXOffset:(float)xOffset withYOffset:(float)yOffset {
//NSLog(#"ADDED *****");
bgLayerTransition = [ColorBGView createGradientWithName:name];
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat screenHeight = screenRect.size.height;
[bgLayerTransition removeAllAnimations];
bgLayerTransition.frame = CGRectMake(xOffset, yOffset, screenHeight, screenWidth);
bgLayerTransition.zPosition = -1;
[viewController.view.layer insertSublayer:bgLayerTransition atIndex:-1];
}
-(void) removeBGLayerTransition {
//NSLog(#"REMOVED *****");
[bgLayerTransition removeFromSuperlayer];
}
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
[[CCDirector sharedDirector] purgeCachedData];
}
-(void) applicationDidEnterBackground:(UIApplication*)application {
[[CCDirector sharedDirector] stopAnimation];
}
-(void) applicationWillEnterForeground:(UIApplication*)application {
// *** This fixes the frame rate bug when hitting home or making device go to sleep when projecting with kEAGLColorFormatRGBA8
[NSTimer scheduledTimerWithTimeInterval:0.00 target:self selector:#selector(resumeGame:) userInfo:nil repeats:NO];
[[CCDirector sharedDirector] startAnimation];
}
- (void)applicationWillTerminate:(UIApplication *)application {
[[[CCDirector sharedDirector] view] removeFromSuperview];
[viewController release];
[window_ release];
[director_ end];
}
- (void)applicationSignificantTimeChange:(UIApplication *)application {
[[CCDirector sharedDirector] setNextDeltaTimeZero:YES];
}
// Supported orientations: Landscape. Customize it for your own needs
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{
return UIInterfaceOrientationIsLandscape(interfaceOrientation);
}
- (void)dealloc {
[[CCDirector sharedDirector] end];
[viewController release]; //should i dealloc this?
[parallaxCCLayer release];
[window_ release];
[super dealloc];
}
#end

GlView causes OpenGL error

I am new in cocos2d.I am making a gaming with uiview with cocos2d(3.0 Beta) platform.I set a GLView in custom viewcontroller. Below is my code.
- (void)setupCocos2D {
CCGLView *glView = [CCGLView viewWithFrame:self.view.bounds pixelFormat:kEAGLColorFormatRGB565 depthFormat:0];**
glView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[self.view insertSubview:glView atIndex:0];
[[CCDirector sharedDirector] setView:glView];**
}
It's working fine.But when we put on object then give me Following Memory worning.
OpenGL error 0x0506 in -[CCSprite draw] 544
OpenGL error 0x0502 in -[CCGLView swapBuffers] 287**
I think when we call ([[CCDirector sharedDirector] setView:glView]) setView method it's not find CCDirector method but UIView method.I can't Access the CCDirector method.Same Method I also can't call in AppDelegate class.
- (void)applicationWillTerminate:(UIApplication *)application {
CCDirector *director = [CCDirector sharedDirector];
//openGLView is now (setView in Latest version).It's Can't Access here.**
[[director openGLView] removeFromSuperview];
[director end];
}
You use below Code in setupCocos2D
- (void)setupCocos2D
{
[[CCDirector sharedDirector] end];
UIWindow *window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
[window_ setBackgroundColor:[UIColor whiteColor]];
CCGLView *glView = [CCGLView viewWithFrame:[window_ bounds]
pixelFormat:kEAGLColorFormatRGB565
depthFormat:0
preserveBackbuffer:NO
sharegroup:nil
multiSampling:NO
numberOfSamples:0];
director_ = (CCDirectorIOS*) [CCDirector sharedDirector];
director_.wantsFullScreenLayout = YES;
// Display FSP and SPF
[director_ setDisplayStats:NO];
// set FPS at 60
[director_ setAnimationInterval:1.0/60];
// attach the openglView to the director
[director_ setView:glView];
// 2D projection
[director_ setProjection:kCCDirectorProjection2D];
// [director setProjection:kCCDirectorProjection3D];
// Enables High Res mode (Retina Display) on iPhone 4 and maintains low res on all other devices
if( ! [director_ enableRetinaDisplay:YES] )
CCLOG(#"Retina Display Not supported");
// Default texture format for PNG/BMP/TIFF/JPEG/GIF images
// It can be RGBA8888, RGBA4444, RGB5_A1, RGB565
// You can change this setting at any time.
[CCTexture2D setDefaultAlphaPixelFormat:kCCTexture2DPixelFormat_RGBA8888];
CCFileUtils *sharedFileUtils = [CCFileUtils sharedFileUtils];
[sharedFileUtils setEnableFallbackSuffixes:NO]; // Default: NO. No fallback suffixes are going to be used
[sharedFileUtils setiPhoneRetinaDisplaySuffix:#"-hd"]; // Default on iPhone RetinaDisplay is "-hd"
[sharedFileUtils setiPadSuffix:#"-ipad"]; // Default on iPad is "ipad"
[sharedFileUtils setiPadRetinaDisplaySuffix:#"-ipadhd"]; // Default on iPad RetinaDisplay is "-ipadhd"
// Assume that PVR images have premultiplied alpha
[CCTexture2D PVRImagesHavePremultipliedAlpha:YES];
}

Resources