summary refs log tree commit diff stats
path: root/libs/cocos2d/Platforms/iOS
diff options
context:
space:
mode:
Diffstat (limited to 'libs/cocos2d/Platforms/iOS')
-rwxr-xr-xlibs/cocos2d/Platforms/iOS/CCDirectorIOS.h255
-rwxr-xr-xlibs/cocos2d/Platforms/iOS/CCDirectorIOS.m735
-rwxr-xr-xlibs/cocos2d/Platforms/iOS/CCTouchDelegateProtocol.h75
-rwxr-xr-xlibs/cocos2d/Platforms/iOS/CCTouchDispatcher.h123
-rwxr-xr-xlibs/cocos2d/Platforms/iOS/CCTouchDispatcher.m347
-rwxr-xr-xlibs/cocos2d/Platforms/iOS/CCTouchHandler.h93
-rwxr-xr-xlibs/cocos2d/Platforms/iOS/CCTouchHandler.m135
-rwxr-xr-xlibs/cocos2d/Platforms/iOS/EAGLView.h155
-rwxr-xr-xlibs/cocos2d/Platforms/iOS/EAGLView.m343
-rwxr-xr-xlibs/cocos2d/Platforms/iOS/ES1Renderer.h72
-rwxr-xr-xlibs/cocos2d/Platforms/iOS/ES1Renderer.m259
-rwxr-xr-xlibs/cocos2d/Platforms/iOS/ESRenderer.h54
-rwxr-xr-xlibs/cocos2d/Platforms/iOS/glu.c113
-rwxr-xr-xlibs/cocos2d/Platforms/iOS/glu.h29
14 files changed, 2788 insertions, 0 deletions
diff --git a/libs/cocos2d/Platforms/iOS/CCDirectorIOS.h b/libs/cocos2d/Platforms/iOS/CCDirectorIOS.h new file mode 100755 index 0000000..1c264e4 --- /dev/null +++ b/libs/cocos2d/Platforms/iOS/CCDirectorIOS.h
@@ -0,0 +1,255 @@
1/*
2 * cocos2d for iPhone: http://www.cocos2d-iphone.org
3 *
4 * Copyright (c) 2008-2010 Ricardo Quesada
5 * Copyright (c) 2011 Zynga Inc.
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 * THE SOFTWARE.
24 */
25
26
27// Only compile this code on iOS. These files should NOT be included on your Mac project.
28// But in case they are included, it won't be compiled.
29#import <Availability.h>
30#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
31
32#import "../../CCDirector.h"
33
34/** @typedef ccDeviceOrientation
35 Possible device orientations
36 */
37typedef enum {
38 /// Device oriented vertically, home button on the bottom
39 kCCDeviceOrientationPortrait = UIDeviceOrientationPortrait,
40 /// Device oriented vertically, home button on the top
41 kCCDeviceOrientationPortraitUpsideDown = UIDeviceOrientationPortraitUpsideDown,
42 /// Device oriented horizontally, home button on the right
43 kCCDeviceOrientationLandscapeLeft = UIDeviceOrientationLandscapeLeft,
44 /// Device oriented horizontally, home button on the left
45 kCCDeviceOrientationLandscapeRight = UIDeviceOrientationLandscapeRight,
46
47 // Backward compatibility stuff
48 CCDeviceOrientationPortrait = kCCDeviceOrientationPortrait,
49 CCDeviceOrientationPortraitUpsideDown = kCCDeviceOrientationPortraitUpsideDown,
50 CCDeviceOrientationLandscapeLeft = kCCDeviceOrientationLandscapeLeft,
51 CCDeviceOrientationLandscapeRight = kCCDeviceOrientationLandscapeRight,
52} ccDeviceOrientation;
53
54/** @typedef ccDirectorType
55 Possible Director Types.
56 @since v0.8.2
57 */
58typedef enum {
59 /** Will use a Director that triggers the main loop from an NSTimer object
60 *
61 * Features and Limitations:
62 * - Integrates OK with UIKit objects
63 * - It the slowest director
64 * - The invertal update is customizable from 1 to 60
65 */
66 kCCDirectorTypeNSTimer,
67
68 /** will use a Director that triggers the main loop from a custom main loop.
69 *
70 * Features and Limitations:
71 * - Faster than NSTimer Director
72 * - It doesn't integrate well with UIKit objecgts
73 * - The interval update can't be customizable
74 */
75 kCCDirectorTypeMainLoop,
76
77 /** Will use a Director that triggers the main loop from a thread, but the main loop will be executed on the main thread.
78 *
79 * Features and Limitations:
80 * - Faster than NSTimer Director
81 * - It doesn't integrate well with UIKit objecgts
82 * - The interval update can't be customizable
83 */
84 kCCDirectorTypeThreadMainLoop,
85
86 /** Will use a Director that synchronizes timers with the refresh rate of the display.
87 *
88 * Features and Limitations:
89 * - Faster than NSTimer Director
90 * - Only available on 3.1+
91 * - Scheduled timers & drawing are synchronizes with the refresh rate of the display
92 * - Integrates OK with UIKit objects
93 * - The interval update can be 1/60, 1/30, 1/15
94 */
95 kCCDirectorTypeDisplayLink,
96
97 /** Default director is the NSTimer directory */
98 kCCDirectorTypeDefault = kCCDirectorTypeNSTimer,
99
100 // backward compatibility stuff
101 CCDirectorTypeNSTimer = kCCDirectorTypeNSTimer,
102 CCDirectorTypeMainLoop = kCCDirectorTypeMainLoop,
103 CCDirectorTypeThreadMainLoop = kCCDirectorTypeThreadMainLoop,
104 CCDirectorTypeDisplayLink = kCCDirectorTypeDisplayLink,
105 CCDirectorTypeDefault = kCCDirectorTypeDefault,
106
107
108} ccDirectorType;
109
110/** CCDirector extensions for iPhone
111 */
112@interface CCDirector (iOSExtension)
113
114// rotates the screen if an orientation differnent than Portrait is used
115-(void) applyOrientation;
116
117/** Sets the device orientation.
118 If the orientation is going to be controlled by an UIViewController, then the orientation should be Portrait
119 */
120-(void) setDeviceOrientation:(ccDeviceOrientation)orientation;
121
122/** returns the device orientation */
123-(ccDeviceOrientation) deviceOrientation;
124
125/** The size in pixels of the surface. It could be different than the screen size.
126 High-res devices might have a higher surface size than the screen size.
127 In non High-res device the contentScale will be emulated.
128
129 The recommend way to enable Retina Display is by using the "enableRetinaDisplay:(BOOL)enabled" method.
130
131 @since v0.99.4
132 */
133-(void) setContentScaleFactor:(CGFloat)scaleFactor;
134
135/** Will enable Retina Display on devices that supports it.
136 It will enable Retina Display on iPhone4 and iPod Touch 4.
137 It will return YES, if it could enabled it, otherwise it will return NO.
138
139 This is the recommened way to enable Retina Display.
140 @since v0.99.5
141 */
142-(BOOL) enableRetinaDisplay:(BOOL)yes;
143
144
145/** returns the content scale factor */
146-(CGFloat) contentScaleFactor;
147@end
148
149@interface CCDirector (iOSExtensionClassMethods)
150
151/** There are 4 types of Director.
152 - kCCDirectorTypeNSTimer (default)
153 - kCCDirectorTypeMainLoop
154 - kCCDirectorTypeThreadMainLoop
155 - kCCDirectorTypeDisplayLink
156
157 Each Director has it's own benefits, limitations.
158 If you are using SDK 3.1 or newer it is recommed to use the DisplayLink director
159
160 This method should be called before any other call to the director.
161
162 It will return NO if the director type is kCCDirectorTypeDisplayLink and the running SDK is < 3.1. Otherwise it will return YES.
163
164 @since v0.8.2
165 */
166+(BOOL) setDirectorType:(ccDirectorType) directorType;
167@end
168
169#pragma mark -
170#pragma mark CCDirectorIOS
171
172/** CCDirectorIOS: Base class of iOS directors
173 @since v0.99.5
174 */
175@interface CCDirectorIOS : CCDirector
176{
177 /* orientation */
178 ccDeviceOrientation deviceOrientation_;
179
180 /* contentScaleFactor could be simulated */
181 BOOL isContentScaleSupported_;
182
183}
184@end
185
186/** FastDirector is a Director that triggers the main loop as fast as possible.
187 *
188 * Features and Limitations:
189 * - Faster than "normal" director
190 * - Consumes more battery than the "normal" director
191 * - It has some issues while using UIKit objects
192 */
193@interface CCDirectorFast : CCDirectorIOS
194{
195 BOOL isRunning;
196
197 NSAutoreleasePool *autoreleasePool;
198}
199-(void) mainLoop;
200@end
201
202/** ThreadedFastDirector is a Director that triggers the main loop from a thread.
203 *
204 * Features and Limitations:
205 * - Faster than "normal" director
206 * - Consumes more battery than the "normal" director
207 * - It can be used with UIKit objects
208 *
209 * @since v0.8.2
210 */
211@interface CCDirectorFastThreaded : CCDirectorIOS
212{
213 BOOL isRunning;
214}
215-(void) mainLoop;
216@end
217
218/** DisplayLinkDirector is a Director that synchronizes timers with the refresh rate of the display.
219 *
220 * Features and Limitations:
221 * - Only available on 3.1+
222 * - Scheduled timers & drawing are synchronizes with the refresh rate of the display
223 * - Only supports animation intervals of 1/60 1/30 & 1/15
224 *
225 * It is the recommended Director if the SDK is 3.1 or newer
226 *
227 * @since v0.8.2
228 */
229@interface CCDirectorDisplayLink : CCDirectorIOS
230{
231 id displayLink;
232}
233-(void) mainLoop:(id)sender;
234@end
235
236/** TimerDirector is a Director that calls the main loop from an NSTimer object
237 *
238 * Features and Limitations:
239 * - Integrates OK with UIKit objects
240 * - It the slowest director
241 * - The invertal update is customizable from 1 to 60
242 *
243 * It is the default Director.
244 */
245@interface CCDirectorTimer : CCDirectorIOS
246{
247 NSTimer *animationTimer;
248}
249-(void) mainLoop;
250@end
251
252// optimization. Should only be used to read it. Never to write it.
253extern CGFloat __ccContentScaleFactor;
254
255#endif // __IPHONE_OS_VERSION_MAX_ALLOWED
diff --git a/libs/cocos2d/Platforms/iOS/CCDirectorIOS.m b/libs/cocos2d/Platforms/iOS/CCDirectorIOS.m new file mode 100755 index 0000000..c483665 --- /dev/null +++ b/libs/cocos2d/Platforms/iOS/CCDirectorIOS.m
@@ -0,0 +1,735 @@
1/*
2 * cocos2d for iPhone: http://www.cocos2d-iphone.org
3 *
4 * Copyright (c) 2010 Ricardo Quesada
5 * Copyright (c) 2011 Zynga Inc.
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 * THE SOFTWARE.
24 *
25 */
26
27// Only compile this code on iOS. These files should NOT be included on your Mac project.
28// But in case they are included, it won't be compiled.
29#import <Availability.h>
30#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
31
32#import <unistd.h>
33
34// cocos2d imports
35#import "CCDirectorIOS.h"
36#import "CCTouchDelegateProtocol.h"
37#import "CCTouchDispatcher.h"
38#import "../../CCScheduler.h"
39#import "../../CCActionManager.h"
40#import "../../CCTextureCache.h"
41#import "../../ccMacros.h"
42#import "../../CCScene.h"
43
44// support imports
45#import "glu.h"
46#import "../../Support/OpenGL_Internal.h"
47#import "../../Support/CGPointExtension.h"
48
49#import "CCLayer.h"
50
51#if CC_ENABLE_PROFILERS
52#import "../../Support/CCProfiling.h"
53#endif
54
55
56#pragma mark -
57#pragma mark Director - global variables (optimization)
58
59CGFloat __ccContentScaleFactor = 1;
60
61#pragma mark -
62#pragma mark Director iOS
63
64@interface CCDirector ()
65-(void) setNextScene;
66-(void) showFPS;
67-(void) calculateDeltaTime;
68@end
69
70@implementation CCDirector (iOSExtensionClassMethods)
71
72+(Class) defaultDirector
73{
74 return [CCDirectorTimer class];
75}
76
77+ (BOOL) setDirectorType:(ccDirectorType)type
78{
79 if( type == CCDirectorTypeDisplayLink ) {
80 NSString *reqSysVer = @"3.1";
81 NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
82
83 if([currSysVer compare:reqSysVer options:NSNumericSearch] == NSOrderedAscending)
84 return NO;
85 }
86 switch (type) {
87 case CCDirectorTypeNSTimer:
88 [CCDirectorTimer sharedDirector];
89 break;
90 case CCDirectorTypeDisplayLink:
91 [CCDirectorDisplayLink sharedDirector];
92 break;
93 case CCDirectorTypeMainLoop:
94 [CCDirectorFast sharedDirector];
95 break;
96 case CCDirectorTypeThreadMainLoop:
97 [CCDirectorFastThreaded sharedDirector];
98 break;
99 default:
100 NSAssert(NO,@"Unknown director type");
101 }
102
103 return YES;
104}
105
106@end
107
108
109
110#pragma mark -
111#pragma mark CCDirectorIOS
112
113@interface CCDirectorIOS ()
114-(void) updateContentScaleFactor;
115
116@end
117
118@implementation CCDirectorIOS
119
120- (id) init
121{
122 if( (self=[super init]) ) {
123
124 // portrait mode default
125 deviceOrientation_ = CCDeviceOrientationPortrait;
126
127 __ccContentScaleFactor = 1;
128 isContentScaleSupported_ = NO;
129
130 // running thread is main thread on iOS
131 runningThread_ = [NSThread currentThread];
132 }
133
134 return self;
135}
136
137- (void) dealloc
138{
139 [super dealloc];
140}
141
142//
143// Draw the Scene
144//
145- (void) drawScene
146{
147 /* calculate "global" dt */
148 [self calculateDeltaTime];
149
150 /* tick before glClear: issue #533 */
151 if( ! isPaused_ ) {
152 [[CCScheduler sharedScheduler] tick: dt];
153 }
154
155 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
156
157 /* to avoid flickr, nextScene MUST be here: after tick and before draw.
158 XXX: Which bug is this one. It seems that it can't be reproduced with v0.9 */
159 if( nextScene_ )
160 [self setNextScene];
161
162 glPushMatrix();
163
164 [self applyOrientation];
165
166 // By default enable VertexArray, ColorArray, TextureCoordArray and Texture2D
167 CC_ENABLE_DEFAULT_GL_STATES();
168
169 /* draw the scene */
170 [runningScene_ visit];
171
172 /* draw the notification node */
173 [notificationNode_ visit];
174
175 if( displayFPS_ )
176 [self showFPS];
177
178#if CC_ENABLE_PROFILERS
179 [self showProfilers];
180#endif
181
182 CC_DISABLE_DEFAULT_GL_STATES();
183
184 glPopMatrix();
185
186 [openGLView_ swapBuffers];
187}
188
189-(void) setProjection:(ccDirectorProjection)projection
190{
191 CGSize size = winSizeInPixels_;
192
193 switch (projection) {
194 case kCCDirectorProjection2D:
195 glViewport(0, 0, size.width, size.height);
196 glMatrixMode(GL_PROJECTION);
197 glLoadIdentity();
198 ccglOrtho(0, size.width, 0, size.height, -1024 * CC_CONTENT_SCALE_FACTOR(), 1024 * CC_CONTENT_SCALE_FACTOR());
199 glMatrixMode(GL_MODELVIEW);
200 glLoadIdentity();
201 break;
202
203 case kCCDirectorProjection3D:
204 {
205 float zeye = [self getZEye];
206
207 glViewport(0, 0, size.width, size.height);
208 glMatrixMode(GL_PROJECTION);
209 glLoadIdentity();
210// gluPerspective(60, (GLfloat)size.width/size.height, zeye-size.height/2, zeye+size.height/2 );
211 gluPerspective(60, (GLfloat)size.width/size.height, 0.5f, 1500);
212
213 glMatrixMode(GL_MODELVIEW);
214 glLoadIdentity();
215 gluLookAt( size.width/2, size.height/2, zeye,
216 size.width/2, size.height/2, 0,
217 0.0f, 1.0f, 0.0f);
218 break;
219 }
220
221 case kCCDirectorProjectionCustom:
222 if( projectionDelegate_ )
223 [projectionDelegate_ updateProjection];
224 break;
225
226 default:
227 CCLOG(@"cocos2d: Director: unrecognized projecgtion");
228 break;
229 }
230
231 projection_ = projection;
232}
233
234#pragma mark Director Integration with a UIKit view
235
236-(void) setOpenGLView:(EAGLView *)view
237{
238 if( view != openGLView_ ) {
239
240 [super setOpenGLView:view];
241
242 // set size
243 winSizeInPixels_ = CGSizeMake(winSizeInPoints_.width * __ccContentScaleFactor, winSizeInPoints_.height *__ccContentScaleFactor);
244
245 if( __ccContentScaleFactor != 1 )
246 [self updateContentScaleFactor];
247
248 CCTouchDispatcher *touchDispatcher = [CCTouchDispatcher sharedDispatcher];
249 [openGLView_ setTouchDelegate: touchDispatcher];
250 [touchDispatcher setDispatchEvents: YES];
251 }
252}
253
254#pragma mark Director - Retina Display
255
256-(CGFloat) contentScaleFactor
257{
258 return __ccContentScaleFactor;
259}
260
261-(void) setContentScaleFactor:(CGFloat)scaleFactor
262{
263 if( scaleFactor != __ccContentScaleFactor ) {
264
265 __ccContentScaleFactor = scaleFactor;
266 winSizeInPixels_ = CGSizeMake( winSizeInPoints_.width * scaleFactor, winSizeInPoints_.height * scaleFactor );
267
268 if( openGLView_ )
269 [self updateContentScaleFactor];
270
271 // update projection
272 [self setProjection:projection_];
273 }
274}
275
276-(void) updateContentScaleFactor
277{
278 // Based on code snippet from: http://developer.apple.com/iphone/prerelease/library/snippets/sp2010/sp28.html
279 if ([openGLView_ respondsToSelector:@selector(setContentScaleFactor:)])
280 {
281 [openGLView_ setContentScaleFactor: __ccContentScaleFactor];
282
283 isContentScaleSupported_ = YES;
284 }
285 else
286 CCLOG(@"cocos2d: 'setContentScaleFactor:' is not supported on this device");
287}
288
289-(BOOL) enableRetinaDisplay:(BOOL)enabled
290{
291 // Already enabled ?
292 if( enabled && __ccContentScaleFactor == 2 )
293 return YES;
294
295 // Already disabled
296 if( ! enabled && __ccContentScaleFactor == 1 )
297 return YES;
298
299 // setContentScaleFactor is not supported
300 if (! [openGLView_ respondsToSelector:@selector(setContentScaleFactor:)])
301 return NO;
302
303 // SD device
304 if ([[UIScreen mainScreen] scale] == 1.0)
305 return NO;
306
307 float newScale = enabled ? 2 : 1;
308 [self setContentScaleFactor:newScale];
309
310 return YES;
311}
312
313// overriden, don't call super
314-(void) reshapeProjection:(CGSize)size
315{
316 winSizeInPoints_ = [openGLView_ bounds].size;
317 winSizeInPixels_ = CGSizeMake(winSizeInPoints_.width * __ccContentScaleFactor, winSizeInPoints_.height *__ccContentScaleFactor);
318
319 [self setProjection:projection_];
320}
321
322#pragma mark Director Scene Landscape
323
324-(CGPoint)convertToGL:(CGPoint)uiPoint
325{
326 CGSize s = winSizeInPoints_;
327 float newY = s.height - uiPoint.y;
328 float newX = s.width - uiPoint.x;
329
330 CGPoint ret = CGPointZero;
331 switch ( deviceOrientation_) {
332 case CCDeviceOrientationPortrait:
333 ret = ccp( uiPoint.x, newY );
334 break;
335 case CCDeviceOrientationPortraitUpsideDown:
336 ret = ccp(newX, uiPoint.y);
337 break;
338 case CCDeviceOrientationLandscapeLeft:
339 ret.x = uiPoint.y;
340 ret.y = uiPoint.x;
341 break;
342 case CCDeviceOrientationLandscapeRight:
343 ret.x = newY;
344 ret.y = newX;
345 break;
346 }
347 return ret;
348}
349
350-(CGPoint)convertToUI:(CGPoint)glPoint
351{
352 CGSize winSize = winSizeInPoints_;
353 int oppositeX = winSize.width - glPoint.x;
354 int oppositeY = winSize.height - glPoint.y;
355 CGPoint uiPoint = CGPointZero;
356 switch ( deviceOrientation_) {
357 case CCDeviceOrientationPortrait:
358 uiPoint = ccp(glPoint.x, oppositeY);
359 break;
360 case CCDeviceOrientationPortraitUpsideDown:
361 uiPoint = ccp(oppositeX, glPoint.y);
362 break;
363 case CCDeviceOrientationLandscapeLeft:
364 uiPoint = ccp(glPoint.y, glPoint.x);
365 break;
366 case CCDeviceOrientationLandscapeRight:
367 // Can't use oppositeX/Y because x/y are flipped
368 uiPoint = ccp(winSize.width-glPoint.y, winSize.height-glPoint.x);
369 break;
370 }
371 return uiPoint;
372}
373
374// get the current size of the glview
375-(CGSize) winSize
376{
377 CGSize s = winSizeInPoints_;
378
379 if( deviceOrientation_ == CCDeviceOrientationLandscapeLeft || deviceOrientation_ == CCDeviceOrientationLandscapeRight ) {
380 // swap x,y in landscape mode
381 CGSize tmp = s;
382 s.width = tmp.height;
383 s.height = tmp.width;
384 }
385 return s;
386}
387
388-(CGSize) winSizeInPixels
389{
390 CGSize s = [self winSize];
391
392 s.width *= CC_CONTENT_SCALE_FACTOR();
393 s.height *= CC_CONTENT_SCALE_FACTOR();
394
395 return s;
396}
397
398-(ccDeviceOrientation) deviceOrientation
399{
400 return deviceOrientation_;
401}
402
403- (void) setDeviceOrientation:(ccDeviceOrientation) orientation
404{
405 if( deviceOrientation_ != orientation ) {
406 deviceOrientation_ = orientation;
407 switch( deviceOrientation_) {
408 case CCDeviceOrientationPortrait:
409 [[UIApplication sharedApplication] setStatusBarOrientation: UIInterfaceOrientationPortrait animated:NO];
410 break;
411 case CCDeviceOrientationPortraitUpsideDown:
412 [[UIApplication sharedApplication] setStatusBarOrientation: UIInterfaceOrientationPortraitUpsideDown animated:NO];
413 break;
414 case CCDeviceOrientationLandscapeLeft:
415 [[UIApplication sharedApplication] setStatusBarOrientation: UIInterfaceOrientationLandscapeRight animated:NO];
416 break;
417 case CCDeviceOrientationLandscapeRight:
418 [[UIApplication sharedApplication] setStatusBarOrientation: UIInterfaceOrientationLandscapeLeft animated:NO];
419 break;
420 default:
421 NSLog(@"Director: Unknown device orientation");
422 break;
423 }
424 }
425}
426
427-(void) applyOrientation
428{
429 CGSize s = winSizeInPixels_;
430 float w = s.width / 2;
431 float h = s.height / 2;
432
433 // XXX it's using hardcoded values.
434 // What if the the screen size changes in the future?
435 switch ( deviceOrientation_ ) {
436 case CCDeviceOrientationPortrait:
437 // nothing
438 break;
439 case CCDeviceOrientationPortraitUpsideDown:
440 // upside down
441 glTranslatef(w,h,0);
442 glRotatef(180,0,0,1);
443 glTranslatef(-w,-h,0);
444 break;
445 case CCDeviceOrientationLandscapeRight:
446 glTranslatef(w,h,0);
447 glRotatef(90,0,0,1);
448 glTranslatef(-h,-w,0);
449 break;
450 case CCDeviceOrientationLandscapeLeft:
451 glTranslatef(w,h,0);
452 glRotatef(-90,0,0,1);
453 glTranslatef(-h,-w,0);
454 break;
455 }
456}
457
458-(void) end
459{
460 // don't release the event handlers
461 // They are needed in case the director is run again
462 [[CCTouchDispatcher sharedDispatcher] removeAllDelegates];
463
464 [super end];
465}
466
467@end
468
469
470#pragma mark -
471#pragma mark Director TimerDirector
472
473@implementation CCDirectorTimer
474- (void)startAnimation
475{
476 NSAssert( animationTimer == nil, @"animationTimer must be nil. Calling startAnimation twice?");
477
478 if( gettimeofday( &lastUpdate_, NULL) != 0 ) {
479 CCLOG(@"cocos2d: Director: Error in gettimeofday");
480 }
481
482 animationTimer = [NSTimer scheduledTimerWithTimeInterval:animationInterval_ target:self selector:@selector(mainLoop) userInfo:nil repeats:YES];
483
484 //
485 // If you want to attach the opengl view into UIScrollView
486 // uncomment this line to prevent 'freezing'.
487 // It doesn't work on with the Fast Director
488 //
489 // [[NSRunLoop currentRunLoop] addTimer:animationTimer
490 // forMode:NSRunLoopCommonModes];
491}
492
493-(void) mainLoop
494{
495 [self drawScene];
496}
497
498- (void)stopAnimation
499{
500 [animationTimer invalidate];
501 animationTimer = nil;
502}
503
504- (void)setAnimationInterval:(NSTimeInterval)interval
505{
506 animationInterval_ = interval;
507
508 if(animationTimer) {
509 [self stopAnimation];
510 [self startAnimation];
511 }
512}
513
514-(void) dealloc
515{
516 [animationTimer release];
517 [super dealloc];
518}
519@end
520
521
522#pragma mark -
523#pragma mark Director DirectorFast
524
525@implementation CCDirectorFast
526
527- (id) init
528{
529 if(( self = [super init] )) {
530
531#if CC_DIRECTOR_DISPATCH_FAST_EVENTS
532 CCLOG(@"cocos2d: Fast Events enabled");
533#else
534 CCLOG(@"cocos2d: Fast Events disabled");
535#endif
536 isRunning = NO;
537
538 // XXX:
539 // XXX: Don't create any autorelease object before calling "fast director"
540 // XXX: else it will be leaked
541 // XXX:
542 autoreleasePool = [NSAutoreleasePool new];
543 }
544
545 return self;
546}
547
548- (void) startAnimation
549{
550 NSAssert( isRunning == NO, @"isRunning must be NO. Calling startAnimation twice?");
551
552 // XXX:
553 // XXX: release autorelease objects created
554 // XXX: between "use fast director" and "runWithScene"
555 // XXX:
556 [autoreleasePool release];
557 autoreleasePool = nil;
558
559 if ( gettimeofday( &lastUpdate_, NULL) != 0 ) {
560 CCLOG(@"cocos2d: Director: Error in gettimeofday");
561 }
562
563
564 isRunning = YES;
565
566 SEL selector = @selector(mainLoop);
567 NSMethodSignature* sig = [[[CCDirector sharedDirector] class]
568 instanceMethodSignatureForSelector:selector];
569 NSInvocation* invocation = [NSInvocation
570 invocationWithMethodSignature:sig];
571 [invocation setTarget:[CCDirector sharedDirector]];
572 [invocation setSelector:selector];
573 [invocation performSelectorOnMainThread:@selector(invokeWithTarget:)
574 withObject:[CCDirector sharedDirector] waitUntilDone:NO];
575
576// NSInvocationOperation *loopOperation = [[[NSInvocationOperation alloc]
577// initWithTarget:self selector:@selector(mainLoop) object:nil]
578// autorelease];
579//
580// [loopOperation performSelectorOnMainThread:@selector(start) withObject:nil
581// waitUntilDone:NO];
582}
583
584-(void) mainLoop
585{
586 while (isRunning) {
587
588 NSAutoreleasePool *loopPool = [NSAutoreleasePool new];
589
590#if CC_DIRECTOR_DISPATCH_FAST_EVENTS
591 while( CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.004f, FALSE) == kCFRunLoopRunHandledSource);
592#else
593 while(CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0, TRUE) == kCFRunLoopRunHandledSource);
594#endif
595
596 if (isPaused_) {
597 usleep(250000); // Sleep for a quarter of a second (250,000 microseconds) so that the framerate is 4 fps.
598 }
599
600 [self drawScene];
601
602#if CC_DIRECTOR_DISPATCH_FAST_EVENTS
603 while( CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.004f, FALSE) == kCFRunLoopRunHandledSource);
604#else
605 while(CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0, TRUE) == kCFRunLoopRunHandledSource);
606#endif
607
608 [loopPool release];
609 }
610}
611- (void) stopAnimation
612{
613 isRunning = NO;
614}
615
616- (void)setAnimationInterval:(NSTimeInterval)interval
617{
618 NSLog(@"FastDirectory doesn't support setAnimationInterval, yet");
619}
620@end
621
622#pragma mark -
623#pragma mark Director DirectorThreadedFast
624
625@implementation CCDirectorFastThreaded
626
627- (id) init
628{
629 if(( self = [super init] )) {
630 isRunning = NO;
631 }
632
633 return self;
634}
635
636- (void) startAnimation
637{
638 NSAssert( isRunning == NO, @"isRunning must be NO. Calling startAnimation twice?");
639
640 if ( gettimeofday( &lastUpdate_, NULL) != 0 ) {
641 CCLOG(@"cocos2d: ThreadedFastDirector: Error on gettimeofday");
642 }
643
644 isRunning = YES;
645
646 NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(mainLoop) object:nil];
647 [thread start];
648 [thread release];
649}
650
651-(void) mainLoop
652{
653 while( ![[NSThread currentThread] isCancelled] ) {
654 if( isRunning )
655 [self performSelectorOnMainThread:@selector(drawScene) withObject:nil waitUntilDone:YES];
656
657 if (isPaused_) {
658 usleep(250000); // Sleep for a quarter of a second (250,000 microseconds) so that the framerate is 4 fps.
659 } else {
660// usleep(2000);
661 }
662 }
663}
664- (void) stopAnimation
665{
666 isRunning = NO;
667}
668
669- (void)setAnimationInterval:(NSTimeInterval)interval
670{
671 NSLog(@"FastDirector doesn't support setAnimationInterval, yet");
672}
673@end
674
675#pragma mark -
676#pragma mark DirectorDisplayLink
677
678// Allows building DisplayLinkDirector for pre-3.1 SDKS
679// without getting compiler warnings.
680@interface NSObject(CADisplayLink)
681+ (id) displayLinkWithTarget:(id)arg1 selector:(SEL)arg2;
682- (void) addToRunLoop:(id)arg1 forMode:(id)arg2;
683- (void) setFrameInterval:(int)interval;
684- (void) invalidate;
685@end
686
687@implementation CCDirectorDisplayLink
688
689- (void)setAnimationInterval:(NSTimeInterval)interval
690{
691 animationInterval_ = interval;
692 if(displayLink){
693 [self stopAnimation];
694 [self startAnimation];
695 }
696}
697
698- (void) startAnimation
699{
700 NSAssert( displayLink == nil, @"displayLink must be nil. Calling startAnimation twice?");
701
702 if ( gettimeofday( &lastUpdate_, NULL) != 0 ) {
703 CCLOG(@"cocos2d: DisplayLinkDirector: Error on gettimeofday");
704 }
705
706 // approximate frame rate
707 // assumes device refreshes at 60 fps
708 int frameInterval = (int) floor(animationInterval_ * 60.0f);
709
710 CCLOG(@"cocos2d: Frame interval: %d", frameInterval);
711
712 displayLink = [NSClassFromString(@"CADisplayLink") displayLinkWithTarget:self selector:@selector(mainLoop:)];
713 [displayLink setFrameInterval:frameInterval];
714 [displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
715}
716
717-(void) mainLoop:(id)sender
718{
719 [self drawScene];
720}
721
722- (void) stopAnimation
723{
724 [displayLink invalidate];
725 displayLink = nil;
726}
727
728-(void) dealloc
729{
730 [displayLink release];
731 [super dealloc];
732}
733@end
734
735#endif // __IPHONE_OS_VERSION_MAX_ALLOWED
diff --git a/libs/cocos2d/Platforms/iOS/CCTouchDelegateProtocol.h b/libs/cocos2d/Platforms/iOS/CCTouchDelegateProtocol.h new file mode 100755 index 0000000..20ba036 --- /dev/null +++ b/libs/cocos2d/Platforms/iOS/CCTouchDelegateProtocol.h
@@ -0,0 +1,75 @@
1/*
2 * cocos2d for iPhone: http://www.cocos2d-iphone.org
3 *
4 * Copyright (c) 2009 Valentin Milea
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 *
24 */
25
26// Only compile this code on iOS. These files should NOT be included on your Mac project.
27// But in case they are included, it won't be compiled.
28#import <Availability.h>
29#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
30
31#import <UIKit/UIKit.h>
32
33/**
34 CCTargetedTouchDelegate.
35
36 Using this type of delegate results in two benefits:
37 1. You don't need to deal with NSSets, the dispatcher does the job of splitting
38 them. You get exactly one UITouch per call.
39 2. You can *claim* a UITouch by returning YES in ccTouchBegan. Updates of claimed
40 touches are sent only to the delegate(s) that claimed them. So if you get a move/
41 ended/cancelled update you're sure it's your touch. This frees you from doing a
42 lot of checks when doing multi-touch.
43
44 (The name TargetedTouchDelegate relates to updates "targeting" their specific
45 handler, without bothering the other handlers.)
46 @since v0.8
47 */
48@protocol CCTargetedTouchDelegate <NSObject>
49
50/** Return YES to claim the touch.
51 @since v0.8
52 */
53- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event;
54@optional
55// touch updates:
56- (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event;
57- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event;
58- (void)ccTouchCancelled:(UITouch *)touch withEvent:(UIEvent *)event;
59@end
60
61/**
62 CCStandardTouchDelegate.
63
64 This type of delegate is the same one used by CocoaTouch. You will receive all the events (Began,Moved,Ended,Cancelled).
65 @since v0.8
66*/
67@protocol CCStandardTouchDelegate <NSObject>
68@optional
69- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
70- (void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
71- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
72- (void)ccTouchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;
73@end
74
75#endif // __IPHONE_OS_VERSION_MAX_ALLOWED
diff --git a/libs/cocos2d/Platforms/iOS/CCTouchDispatcher.h b/libs/cocos2d/Platforms/iOS/CCTouchDispatcher.h new file mode 100755 index 0000000..9931189 --- /dev/null +++ b/libs/cocos2d/Platforms/iOS/CCTouchDispatcher.h
@@ -0,0 +1,123 @@
1/*
2 * cocos2d for iPhone: http://www.cocos2d-iphone.org
3 *
4 * Copyright (c) 2009 Valentin Milea
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 *
24 */
25
26// Only compile this code on iOS. These files should NOT be included on your Mac project.
27// But in case they are included, it won't be compiled.
28#import <Availability.h>
29#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
30
31#import "CCTouchDelegateProtocol.h"
32#import "EAGLView.h"
33
34
35typedef enum
36{
37 kCCTouchSelectorBeganBit = 1 << 0,
38 kCCTouchSelectorMovedBit = 1 << 1,
39 kCCTouchSelectorEndedBit = 1 << 2,
40 kCCTouchSelectorCancelledBit = 1 << 3,
41 kCCTouchSelectorAllBits = ( kCCTouchSelectorBeganBit | kCCTouchSelectorMovedBit | kCCTouchSelectorEndedBit | kCCTouchSelectorCancelledBit),
42} ccTouchSelectorFlag;
43
44
45enum {
46 kCCTouchBegan,
47 kCCTouchMoved,
48 kCCTouchEnded,
49 kCCTouchCancelled,
50
51 kCCTouchMax,
52};
53
54struct ccTouchHandlerHelperData {
55 SEL touchesSel;
56 SEL touchSel;
57 ccTouchSelectorFlag type;
58};
59
60/** CCTouchDispatcher.
61 Singleton that handles all the touch events.
62 The dispatcher dispatches events to the registered TouchHandlers.
63 There are 2 different type of touch handlers:
64 - Standard Touch Handlers
65 - Targeted Touch Handlers
66
67 The Standard Touch Handlers work like the CocoaTouch touch handler: a set of touches is passed to the delegate.
68 On the other hand, the Targeted Touch Handlers only receive 1 touch at the time, and they can "swallow" touches (avoid the propagation of the event).
69
70 Firstly, the dispatcher sends the received touches to the targeted touches.
71 These touches can be swallowed by the Targeted Touch Handlers. If there are still remaining touches, then the remaining touches will be sent
72 to the Standard Touch Handlers.
73
74 @since v0.8.0
75 */
76@interface CCTouchDispatcher : NSObject <EAGLTouchDelegate>
77{
78 NSMutableArray *targetedHandlers;
79 NSMutableArray *standardHandlers;
80
81 BOOL locked;
82 BOOL toAdd;
83 BOOL toRemove;
84 NSMutableArray *handlersToAdd;
85 NSMutableArray *handlersToRemove;
86 BOOL toQuit;
87
88 BOOL dispatchEvents;
89
90 // 4, 1 for each type of event
91 struct ccTouchHandlerHelperData handlerHelperData[kCCTouchMax];
92}
93
94/** singleton of the CCTouchDispatcher */
95+ (CCTouchDispatcher*)sharedDispatcher;
96
97/** Whether or not the events are going to be dispatched. Default: YES */
98@property (nonatomic,readwrite, assign) BOOL dispatchEvents;
99
100/** Adds a standard touch delegate to the dispatcher's list.
101 See StandardTouchDelegate description.
102 IMPORTANT: The delegate will be retained.
103 */
104-(void) addStandardDelegate:(id<CCStandardTouchDelegate>) delegate priority:(int)priority;
105/** Adds a targeted touch delegate to the dispatcher's list.
106 See TargetedTouchDelegate description.
107 IMPORTANT: The delegate will be retained.
108 */
109-(void) addTargetedDelegate:(id<CCTargetedTouchDelegate>) delegate priority:(int)priority swallowsTouches:(BOOL)swallowsTouches;
110/** Removes a touch delegate.
111 The delegate will be released
112 */
113-(void) removeDelegate:(id) delegate;
114/** Removes all touch delegates, releasing all the delegates */
115-(void) removeAllDelegates;
116/** Changes the priority of a previously added delegate. The lower the number,
117 the higher the priority */
118-(void) setPriority:(int) priority forDelegate:(id) delegate;
119
120NSComparisonResult sortByPriority(id first, id second, void *context);
121@end
122
123#endif // __IPHONE_OS_VERSION_MAX_ALLOWED
diff --git a/libs/cocos2d/Platforms/iOS/CCTouchDispatcher.m b/libs/cocos2d/Platforms/iOS/CCTouchDispatcher.m new file mode 100755 index 0000000..1553b48 --- /dev/null +++ b/libs/cocos2d/Platforms/iOS/CCTouchDispatcher.m
@@ -0,0 +1,347 @@
1/*
2 * cocos2d for iPhone: http://www.cocos2d-iphone.org
3 *
4 * Copyright (c) 2009 Valentin Milea
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 *
24 */
25
26// Only compile this code on iOS. These files should NOT be included on your Mac project.
27// But in case they are included, it won't be compiled.
28#import <Availability.h>
29#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
30
31
32#import "CCTouchDispatcher.h"
33#import "CCTouchHandler.h"
34
35@implementation CCTouchDispatcher
36
37@synthesize dispatchEvents;
38
39static CCTouchDispatcher *sharedDispatcher = nil;
40
41+(CCTouchDispatcher*) sharedDispatcher
42{
43 @synchronized(self) {
44 if (sharedDispatcher == nil)
45 sharedDispatcher = [[self alloc] init]; // assignment not done here
46 }
47 return sharedDispatcher;
48}
49
50+(id) allocWithZone:(NSZone *)zone
51{
52 @synchronized(self) {
53 NSAssert(sharedDispatcher == nil, @"Attempted to allocate a second instance of a singleton.");
54 return [super allocWithZone:zone];
55 }
56 return nil; // on subsequent allocation attempts return nil
57}
58
59-(id) init
60{
61 if((self = [super init])) {
62
63 dispatchEvents = YES;
64 targetedHandlers = [[NSMutableArray alloc] initWithCapacity:8];
65 standardHandlers = [[NSMutableArray alloc] initWithCapacity:4];
66
67 handlersToAdd = [[NSMutableArray alloc] initWithCapacity:8];
68 handlersToRemove = [[NSMutableArray alloc] initWithCapacity:8];
69
70 toRemove = NO;
71 toAdd = NO;
72 toQuit = NO;
73 locked = NO;
74
75 handlerHelperData[kCCTouchBegan] = (struct ccTouchHandlerHelperData) {@selector(ccTouchesBegan:withEvent:),@selector(ccTouchBegan:withEvent:),kCCTouchSelectorBeganBit};
76 handlerHelperData[kCCTouchMoved] = (struct ccTouchHandlerHelperData) {@selector(ccTouchesMoved:withEvent:),@selector(ccTouchMoved:withEvent:),kCCTouchSelectorMovedBit};
77 handlerHelperData[kCCTouchEnded] = (struct ccTouchHandlerHelperData) {@selector(ccTouchesEnded:withEvent:),@selector(ccTouchEnded:withEvent:),kCCTouchSelectorEndedBit};
78 handlerHelperData[kCCTouchCancelled] = (struct ccTouchHandlerHelperData) {@selector(ccTouchesCancelled:withEvent:),@selector(ccTouchCancelled:withEvent:),kCCTouchSelectorCancelledBit};
79
80 }
81
82 return self;
83}
84
85-(void) dealloc
86{
87 [targetedHandlers release];
88 [standardHandlers release];
89 [handlersToAdd release];
90 [handlersToRemove release];
91 [super dealloc];
92}
93
94//
95// handlers management
96//
97
98#pragma mark TouchDispatcher - Add Hanlder
99
100-(void) forceAddHandler:(CCTouchHandler*)handler array:(NSMutableArray*)array
101{
102 NSUInteger i = 0;
103
104 for( CCTouchHandler *h in array ) {
105 if( h.priority < handler.priority )
106 i++;
107
108 NSAssert( h.delegate != handler.delegate, @"Delegate already added to touch dispatcher.");
109 }
110 [array insertObject:handler atIndex:i];
111}
112
113-(void) addStandardDelegate:(id<CCStandardTouchDelegate>) delegate priority:(int)priority
114{
115 CCTouchHandler *handler = [CCStandardTouchHandler handlerWithDelegate:delegate priority:priority];
116 if( ! locked ) {
117 [self forceAddHandler:handler array:standardHandlers];
118 } else {
119 [handlersToAdd addObject:handler];
120 toAdd = YES;
121 }
122}
123
124-(void) addTargetedDelegate:(id<CCTargetedTouchDelegate>) delegate priority:(int)priority swallowsTouches:(BOOL)swallowsTouches
125{
126 CCTouchHandler *handler = [CCTargetedTouchHandler handlerWithDelegate:delegate priority:priority swallowsTouches:swallowsTouches];
127 if( ! locked ) {
128 [self forceAddHandler:handler array:targetedHandlers];
129 } else {
130 [handlersToAdd addObject:handler];
131 toAdd = YES;
132 }
133}
134
135#pragma mark TouchDispatcher - removeDelegate
136
137-(void) forceRemoveDelegate:(id)delegate
138{
139 // XXX: remove it from both handlers ???
140
141 for( CCTouchHandler *handler in targetedHandlers ) {
142 if( handler.delegate == delegate ) {
143 [targetedHandlers removeObject:handler];
144 break;
145 }
146 }
147
148 for( CCTouchHandler *handler in standardHandlers ) {
149 if( handler.delegate == delegate ) {
150 [standardHandlers removeObject:handler];
151 break;
152 }
153 }
154}
155
156-(void) removeDelegate:(id) delegate
157{
158 if( delegate == nil )
159 return;
160
161 if( ! locked ) {
162 [self forceRemoveDelegate:delegate];
163 } else {
164 [handlersToRemove addObject:delegate];
165 toRemove = YES;
166 }
167}
168
169#pragma mark TouchDispatcher - removeAllDelegates
170
171-(void) forceRemoveAllDelegates
172{
173 [standardHandlers removeAllObjects];
174 [targetedHandlers removeAllObjects];
175}
176-(void) removeAllDelegates
177{
178 if( ! locked )
179 [self forceRemoveAllDelegates];
180 else
181 toQuit = YES;
182}
183
184#pragma mark Changing priority of added handlers
185
186-(CCTouchHandler*) findHandler:(id)delegate
187{
188 for( CCTouchHandler *handler in targetedHandlers ) {
189 if( handler.delegate == delegate ) {
190 return handler;
191 }
192 }
193
194 for( CCTouchHandler *handler in standardHandlers ) {
195 if( handler.delegate == delegate ) {
196 return handler;
197 }
198 }
199 return nil;
200}
201
202NSComparisonResult sortByPriority(id first, id second, void *context)
203{
204 if (((CCTouchHandler*)first).priority < ((CCTouchHandler*)second).priority)
205 return NSOrderedAscending;
206 else if (((CCTouchHandler*)first).priority > ((CCTouchHandler*)second).priority)
207 return NSOrderedDescending;
208 else
209 return NSOrderedSame;
210}
211
212-(void) rearrangeHandlers:(NSMutableArray*)array
213{
214 [array sortUsingFunction:sortByPriority context:nil];
215}
216
217-(void) setPriority:(int) priority forDelegate:(id) delegate
218{
219 NSAssert(delegate != nil, @"Got nil touch delegate!");
220
221 CCTouchHandler *handler = nil;
222 handler = [self findHandler:delegate];
223
224 NSAssert(handler != nil, @"Delegate not found!");
225
226 handler.priority = priority;
227
228 [self rearrangeHandlers:targetedHandlers];
229 [self rearrangeHandlers:standardHandlers];
230}
231
232//
233// dispatch events
234//
235-(void) touches:(NSSet*)touches withEvent:(UIEvent*)event withTouchType:(unsigned int)idx
236{
237 NSAssert(idx < 4, @"Invalid idx value");
238
239 id mutableTouches;
240 locked = YES;
241
242 // optimization to prevent a mutable copy when it is not necessary
243 unsigned int targetedHandlersCount = [targetedHandlers count];
244 unsigned int standardHandlersCount = [standardHandlers count];
245 BOOL needsMutableSet = (targetedHandlersCount && standardHandlersCount);
246
247 mutableTouches = (needsMutableSet ? [touches mutableCopy] : touches);
248
249 struct ccTouchHandlerHelperData helper = handlerHelperData[idx];
250 //
251 // process the target handlers 1st
252 //
253 if( targetedHandlersCount > 0 ) {
254 for( UITouch *touch in touches ) {
255 for(CCTargetedTouchHandler *handler in targetedHandlers) {
256
257 BOOL claimed = NO;
258 if( idx == kCCTouchBegan ) {
259 claimed = [handler.delegate ccTouchBegan:touch withEvent:event];
260 if( claimed )
261 [handler.claimedTouches addObject:touch];
262 }
263
264 // else (moved, ended, cancelled)
265 else if( [handler.claimedTouches containsObject:touch] ) {
266 claimed = YES;
267 if( handler.enabledSelectors & helper.type )
268 [handler.delegate performSelector:helper.touchSel withObject:touch withObject:event];
269
270 if( helper.type & (kCCTouchSelectorCancelledBit | kCCTouchSelectorEndedBit) )
271 [handler.claimedTouches removeObject:touch];
272 }
273
274 if( claimed && handler.swallowsTouches ) {
275 if( needsMutableSet )
276 [mutableTouches removeObject:touch];
277 break;
278 }
279 }
280 }
281 }
282
283 //
284 // process standard handlers 2nd
285 //
286 if( standardHandlersCount > 0 && [mutableTouches count]>0 ) {
287 for( CCTouchHandler *handler in standardHandlers ) {
288 if( handler.enabledSelectors & helper.type )
289 [handler.delegate performSelector:helper.touchesSel withObject:mutableTouches withObject:event];
290 }
291 }
292 if( needsMutableSet )
293 [mutableTouches release];
294
295 //
296 // Optimization. To prevent a [handlers copy] which is expensive
297 // the add/removes/quit is done after the iterations
298 //
299 locked = NO;
300 if( toRemove ) {
301 toRemove = NO;
302 for( id delegate in handlersToRemove )
303 [self forceRemoveDelegate:delegate];
304 [handlersToRemove removeAllObjects];
305 }
306 if( toAdd ) {
307 toAdd = NO;
308 for( CCTouchHandler *handler in handlersToAdd ) {
309 Class targetedClass = [CCTargetedTouchHandler class];
310 if( [handler isKindOfClass:targetedClass] )
311 [self forceAddHandler:handler array:targetedHandlers];
312 else
313 [self forceAddHandler:handler array:standardHandlers];
314 }
315 [handlersToAdd removeAllObjects];
316 }
317 if( toQuit ) {
318 toQuit = NO;
319 [self forceRemoveAllDelegates];
320 }
321}
322
323- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
324{
325 if( dispatchEvents )
326 [self touches:touches withEvent:event withTouchType:kCCTouchBegan];
327}
328- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
329{
330 if( dispatchEvents )
331 [self touches:touches withEvent:event withTouchType:kCCTouchMoved];
332}
333
334- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
335{
336 if( dispatchEvents )
337 [self touches:touches withEvent:event withTouchType:kCCTouchEnded];
338}
339
340- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
341{
342 if( dispatchEvents )
343 [self touches:touches withEvent:event withTouchType:kCCTouchCancelled];
344}
345@end
346
347#endif // __IPHONE_OS_VERSION_MAX_ALLOWED
diff --git a/libs/cocos2d/Platforms/iOS/CCTouchHandler.h b/libs/cocos2d/Platforms/iOS/CCTouchHandler.h new file mode 100755 index 0000000..31a3e36 --- /dev/null +++ b/libs/cocos2d/Platforms/iOS/CCTouchHandler.h
@@ -0,0 +1,93 @@
1/*
2 * cocos2d for iPhone: http://www.cocos2d-iphone.org
3 *
4 * Copyright (c) 2009 Valentin Milea
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 *
24 */
25
26// Only compile this code on iOS. These files should NOT be included on your Mac project.
27// But in case they are included, it won't be compiled.
28#import <Availability.h>
29#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
30
31/*
32 * This file contains the delegates of the touches
33 * There are 2 possible delegates:
34 * - CCStandardTouchHandler: propagates all the events at once
35 * - CCTargetedTouchHandler: propagates 1 event at the time
36 */
37
38#import "CCTouchDelegateProtocol.h"
39#import "CCTouchDispatcher.h"
40
41/**
42 CCTouchHandler
43 Object than contains the delegate and priority of the event handler.
44*/
45@interface CCTouchHandler : NSObject {
46 id delegate;
47 int priority;
48 ccTouchSelectorFlag enabledSelectors_;
49}
50
51/** delegate */
52@property(nonatomic, readwrite, retain) id delegate;
53/** priority */
54@property(nonatomic, readwrite) int priority; // default 0
55/** enabled selectors */
56@property(nonatomic,readwrite) ccTouchSelectorFlag enabledSelectors;
57
58/** allocates a TouchHandler with a delegate and a priority */
59+ (id)handlerWithDelegate:(id)aDelegate priority:(int)priority;
60/** initializes a TouchHandler with a delegate and a priority */
61- (id)initWithDelegate:(id)aDelegate priority:(int)priority;
62@end
63
64/** CCStandardTouchHandler
65 It forwardes each event to the delegate.
66 */
67@interface CCStandardTouchHandler : CCTouchHandler
68{
69}
70@end
71
72/**
73 CCTargetedTouchHandler
74 Object than contains the claimed touches and if it swallos touches.
75 Used internally by TouchDispatcher
76 */
77@interface CCTargetedTouchHandler : CCTouchHandler {
78 BOOL swallowsTouches;
79 NSMutableSet *claimedTouches;
80}
81/** whether or not the touches are swallowed */
82@property(nonatomic, readwrite) BOOL swallowsTouches; // default NO
83/** MutableSet that contains the claimed touches */
84@property(nonatomic, readonly) NSMutableSet *claimedTouches;
85
86/** allocates a TargetedTouchHandler with a delegate, a priority and whether or not it swallows touches or not */
87+ (id)handlerWithDelegate:(id) aDelegate priority:(int)priority swallowsTouches:(BOOL)swallowsTouches;
88/** initializes a TargetedTouchHandler with a delegate, a priority and whether or not it swallows touches or not */
89- (id)initWithDelegate:(id) aDelegate priority:(int)priority swallowsTouches:(BOOL)swallowsTouches;
90
91@end
92
93#endif // __IPHONE_OS_VERSION_MAX_ALLOWED
diff --git a/libs/cocos2d/Platforms/iOS/CCTouchHandler.m b/libs/cocos2d/Platforms/iOS/CCTouchHandler.m new file mode 100755 index 0000000..a52103b --- /dev/null +++ b/libs/cocos2d/Platforms/iOS/CCTouchHandler.m
@@ -0,0 +1,135 @@
1/*
2 * cocos2d for iPhone: http://www.cocos2d-iphone.org
3 *
4 * Copyright (c) 2009 Valentin Milea
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 *
24 */
25
26
27// Only compile this code on iOS. These files should NOT be included on your Mac project.
28// But in case they are included, it won't be compiled.
29#import <Availability.h>
30#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
31
32/*
33 * This file contains the delegates of the touches
34 * There are 2 possible delegates:
35 * - CCStandardTouchHandler: propagates all the events at once
36 * - CCTargetedTouchHandler: propagates 1 event at the time
37 */
38
39#import "CCTouchHandler.h"
40#import "../../ccMacros.h"
41
42#pragma mark -
43#pragma mark TouchHandler
44@implementation CCTouchHandler
45
46@synthesize delegate, priority;
47@synthesize enabledSelectors=enabledSelectors_;
48
49+ (id)handlerWithDelegate:(id) aDelegate priority:(int)aPriority
50{
51 return [[[self alloc] initWithDelegate:aDelegate priority:aPriority] autorelease];
52}
53
54- (id)initWithDelegate:(id) aDelegate priority:(int)aPriority
55{
56 NSAssert(aDelegate != nil, @"Touch delegate may not be nil");
57
58 if ((self = [super init])) {
59 self.delegate = aDelegate;
60 priority = aPriority;
61 enabledSelectors_ = 0;
62 }
63
64 return self;
65}
66
67- (void)dealloc {
68 CCLOGINFO(@"cocos2d: deallocing %@", self);
69 [delegate release];
70 [super dealloc];
71}
72@end
73
74#pragma mark -
75#pragma mark StandardTouchHandler
76@implementation CCStandardTouchHandler
77-(id) initWithDelegate:(id)del priority:(int)pri
78{
79 if( (self=[super initWithDelegate:del priority:pri]) ) {
80 if( [del respondsToSelector:@selector(ccTouchesBegan:withEvent:)] )
81 enabledSelectors_ |= kCCTouchSelectorBeganBit;
82 if( [del respondsToSelector:@selector(ccTouchesMoved:withEvent:)] )
83 enabledSelectors_ |= kCCTouchSelectorMovedBit;
84 if( [del respondsToSelector:@selector(ccTouchesEnded:withEvent:)] )
85 enabledSelectors_ |= kCCTouchSelectorEndedBit;
86 if( [del respondsToSelector:@selector(ccTouchesCancelled:withEvent:)] )
87 enabledSelectors_ |= kCCTouchSelectorCancelledBit;
88 }
89 return self;
90}
91@end
92
93#pragma mark -
94#pragma mark TargetedTouchHandler
95
96@interface CCTargetedTouchHandler (private)
97-(void) updateKnownTouches:(NSMutableSet *)touches withEvent:(UIEvent *)event selector:(SEL)selector unclaim:(BOOL)doUnclaim;
98@end
99
100@implementation CCTargetedTouchHandler
101
102@synthesize swallowsTouches, claimedTouches;
103
104+ (id)handlerWithDelegate:(id)aDelegate priority:(int)priority swallowsTouches:(BOOL)swallow
105{
106 return [[[self alloc] initWithDelegate:aDelegate priority:priority swallowsTouches:swallow] autorelease];
107}
108
109- (id)initWithDelegate:(id)aDelegate priority:(int)aPriority swallowsTouches:(BOOL)swallow
110{
111 if ((self = [super initWithDelegate:aDelegate priority:aPriority])) {
112 claimedTouches = [[NSMutableSet alloc] initWithCapacity:2];
113 swallowsTouches = swallow;
114
115 if( [aDelegate respondsToSelector:@selector(ccTouchBegan:withEvent:)] )
116 enabledSelectors_ |= kCCTouchSelectorBeganBit;
117 if( [aDelegate respondsToSelector:@selector(ccTouchMoved:withEvent:)] )
118 enabledSelectors_ |= kCCTouchSelectorMovedBit;
119 if( [aDelegate respondsToSelector:@selector(ccTouchEnded:withEvent:)] )
120 enabledSelectors_ |= kCCTouchSelectorEndedBit;
121 if( [aDelegate respondsToSelector:@selector(ccTouchCancelled:withEvent:)] )
122 enabledSelectors_ |= kCCTouchSelectorCancelledBit;
123 }
124
125 return self;
126}
127
128- (void)dealloc {
129 [claimedTouches release];
130 [super dealloc];
131}
132@end
133
134
135#endif // __IPHONE_OS_VERSION_MAX_ALLOWED \ No newline at end of file
diff --git a/libs/cocos2d/Platforms/iOS/EAGLView.h b/libs/cocos2d/Platforms/iOS/EAGLView.h new file mode 100755 index 0000000..3b6c2f3 --- /dev/null +++ b/libs/cocos2d/Platforms/iOS/EAGLView.h
@@ -0,0 +1,155 @@
1/*
2
3===== IMPORTANT =====
4
5This is sample code demonstrating API, technology or techniques in development.
6Although this sample code has been reviewed for technical accuracy, it is not
7final. Apple is supplying this information to help you plan for the adoption of
8the technologies and programming interfaces described herein. This information
9is subject to change, and software implemented based on this sample code should
10be tested with final operating system software and final documentation. Newer
11versions of this sample code may be provided with future seeds of the API or
12technology. For information about updates to this and other developer
13documentation, view the New & Updated sidebars in subsequent documentation
14seeds.
15
16=====================
17
18File: EAGLView.h
19Abstract: Convenience class that wraps the CAEAGLLayer from CoreAnimation into a
20UIView subclass.
21
22Version: 1.3
23
24Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc.
25("Apple") in consideration of your agreement to the following terms, and your
26use, installation, modification or redistribution of this Apple software
27constitutes acceptance of these terms. If you do not agree with these terms,
28please do not use, install, modify or redistribute this Apple software.
29
30In consideration of your agreement to abide by the following terms, and subject
31to these terms, Apple grants you a personal, non-exclusive license, under
32Apple's copyrights in this original Apple software (the "Apple Software"), to
33use, reproduce, modify and redistribute the Apple Software, with or without
34modifications, in source and/or binary forms; provided that if you redistribute
35the Apple Software in its entirety and without modifications, you must retain
36this notice and the following text and disclaimers in all such redistributions
37of the Apple Software.
38Neither the name, trademarks, service marks or logos of Apple Inc. may be used
39to endorse or promote products derived from the Apple Software without specific
40prior written permission from Apple. Except as expressly stated in this notice,
41no other rights or licenses, express or implied, are granted by Apple herein,
42including but not limited to any patent rights that may be infringed by your
43derivative works or by other works in which the Apple Software may be
44incorporated.
45
46The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO
47WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
48WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
49PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
50COMBINATION WITH YOUR PRODUCTS.
51
52IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
53CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
54GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
55ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR
56DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF
57CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF
58APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
59
60Copyright (C) 2008 Apple Inc. All Rights Reserved.
61
62*/
63
64// Only compile this code on iOS. These files should NOT be included on your Mac project.
65// But in case they are included, it won't be compiled.
66#import <Availability.h>
67#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
68
69#import <UIKit/UIKit.h>
70#import <OpenGLES/EAGL.h>
71#import <OpenGLES/EAGLDrawable.h>
72#import <OpenGLES/ES1/gl.h>
73#import <OpenGLES/ES1/glext.h>
74
75#import "ESRenderer.h"
76
77//CLASSES:
78
79@class EAGLView;
80@class EAGLSharegroup;
81
82//PROTOCOLS:
83
84@protocol EAGLTouchDelegate <NSObject>
85- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
86- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
87- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
88- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;
89@end
90
91//CLASS INTERFACE:
92
93/** EAGLView Class.
94 * This class wraps the CAEAGLLayer from CoreAnimation into a convenient UIView subclass.
95 * The view content is basically an EAGL surface you render your OpenGL scene into.
96 * Note that setting the view non-opaque will only work if the EAGL surface has an alpha channel.
97 */
98@interface EAGLView : UIView
99{
100 id<ESRenderer> renderer_;
101 EAGLContext *context_; // weak ref
102
103 NSString *pixelformat_;
104 GLuint depthFormat_;
105 BOOL preserveBackbuffer_;
106
107 CGSize size_;
108 BOOL discardFramebufferSupported_;
109 id<EAGLTouchDelegate> touchDelegate_;
110
111 //fsaa addition
112 BOOL multisampling_;
113 unsigned int requestedSamples_;
114}
115
116/** creates an initializes an EAGLView with a frame and 0-bit depth buffer, and a RGB565 color buffer. */
117+ (id) viewWithFrame:(CGRect)frame;
118/** creates an initializes an EAGLView with a frame, a color buffer format, and 0-bit depth buffer. */
119+ (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format;
120/** creates an initializes an EAGLView with a frame, a color buffer format, and a depth buffer. */
121+ (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth;
122/** creates an initializes an EAGLView with a frame, a color buffer format, a depth buffer format, a sharegroup, and multisamping */
123+ (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth preserveBackbuffer:(BOOL)retained sharegroup:(EAGLSharegroup*)sharegroup multiSampling:(BOOL)multisampling numberOfSamples:(unsigned int)samples;
124
125/** Initializes an EAGLView with a frame and 0-bit depth buffer, and a RGB565 color buffer */
126- (id) initWithFrame:(CGRect)frame; //These also set the current context
127/** Initializes an EAGLView with a frame, a color buffer format, and 0-bit depth buffer */
128- (id) initWithFrame:(CGRect)frame pixelFormat:(NSString*)format;
129/** Initializes an EAGLView with a frame, a color buffer format, a depth buffer format, a sharegroup and multisampling support */
130- (id) initWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth preserveBackbuffer:(BOOL)retained sharegroup:(EAGLSharegroup*)sharegroup multiSampling:(BOOL)sampling numberOfSamples:(unsigned int)nSamples;
131
132/** pixel format: it could be RGBA8 (32-bit) or RGB565 (16-bit) */
133@property(nonatomic,readonly) NSString* pixelFormat;
134/** depth format of the render buffer: 0, 16 or 24 bits*/
135@property(nonatomic,readonly) GLuint depthFormat;
136
137/** returns surface size in pixels */
138@property(nonatomic,readonly) CGSize surfaceSize;
139
140/** OpenGL context */
141@property(nonatomic,readonly) EAGLContext *context;
142
143@property(nonatomic,readwrite) BOOL multiSampling;
144
145/** touch delegate */
146@property(nonatomic,readwrite,assign) id<EAGLTouchDelegate> touchDelegate;
147
148/** EAGLView uses double-buffer. This method swaps the buffers */
149-(void) swapBuffers;
150
151- (CGPoint) convertPointFromViewToSurface:(CGPoint)point;
152- (CGRect) convertRectFromViewToSurface:(CGRect)rect;
153@end
154
155#endif // __IPHONE_OS_VERSION_MAX_ALLOWED
diff --git a/libs/cocos2d/Platforms/iOS/EAGLView.m b/libs/cocos2d/Platforms/iOS/EAGLView.m new file mode 100755 index 0000000..d5ead65 --- /dev/null +++ b/libs/cocos2d/Platforms/iOS/EAGLView.m
@@ -0,0 +1,343 @@
1/*
2
3===== IMPORTANT =====
4
5This is sample code demonstrating API, technology or techniques in development.
6Although this sample code has been reviewed for technical accuracy, it is not
7final. Apple is supplying this information to help you plan for the adoption of
8the technologies and programming interfaces described herein. This information
9is subject to change, and software implemented based on this sample code should
10be tested with final operating system software and final documentation. Newer
11versions of this sample code may be provided with future seeds of the API or
12technology. For information about updates to this and other developer
13documentation, view the New & Updated sidebars in subsequent documentation
14seeds.
15
16=====================
17
18File: EAGLView.m
19Abstract: Convenience class that wraps the CAEAGLLayer from CoreAnimation into a
20UIView subclass.
21
22Version: 1.3
23
24Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc.
25("Apple") in consideration of your agreement to the following terms, and your
26use, installation, modification or redistribution of this Apple software
27constitutes acceptance of these terms. If you do not agree with these terms,
28please do not use, install, modify or redistribute this Apple software.
29
30In consideration of your agreement to abide by the following terms, and subject
31to these terms, Apple grants you a personal, non-exclusive license, under
32Apple's copyrights in this original Apple software (the "Apple Software"), to
33use, reproduce, modify and redistribute the Apple Software, with or without
34modifications, in source and/or binary forms; provided that if you redistribute
35the Apple Software in its entirety and without modifications, you must retain
36this notice and the following text and disclaimers in all such redistributions
37of the Apple Software.
38Neither the name, trademarks, service marks or logos of Apple Inc. may be used
39to endorse or promote products derived from the Apple Software without specific
40prior written permission from Apple. Except as expressly stated in this notice,
41no other rights or licenses, express or implied, are granted by Apple herein,
42including but not limited to any patent rights that may be infringed by your
43derivative works or by other works in which the Apple Software may be
44incorporated.
45
46The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO
47WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
48WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
49PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
50COMBINATION WITH YOUR PRODUCTS.
51
52IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
53CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
54GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
55ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR
56DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF
57CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF
58APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
59
60Copyright (C) 2008 Apple Inc. All Rights Reserved.
61
62*/
63
64// Only compile this code on iOS. These files should NOT be included on your Mac project.
65// But in case they are included, it won't be compiled.
66#import <Availability.h>
67#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
68
69#import <QuartzCore/QuartzCore.h>
70
71#import "EAGLView.h"
72#import "ES1Renderer.h"
73#import "../../CCDirector.h"
74#import "../../ccMacros.h"
75#import "../../CCConfiguration.h"
76#import "../../Support/OpenGL_Internal.h"
77
78
79//CLASS IMPLEMENTATIONS:
80
81@interface EAGLView (Private)
82- (BOOL) setupSurfaceWithSharegroup:(EAGLSharegroup*)sharegroup;
83- (unsigned int) convertPixelFormat:(NSString*) pixelFormat;
84@end
85
86@implementation EAGLView
87
88@synthesize surfaceSize=size_;
89@synthesize pixelFormat=pixelformat_, depthFormat=depthFormat_;
90@synthesize touchDelegate=touchDelegate_;
91@synthesize context=context_;
92@synthesize multiSampling=multiSampling_;
93
94+ (Class) layerClass
95{
96 return [CAEAGLLayer class];
97}
98
99+ (id) viewWithFrame:(CGRect)frame
100{
101 return [[[self alloc] initWithFrame:frame] autorelease];
102}
103
104+ (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format
105{
106 return [[[self alloc] initWithFrame:frame pixelFormat:format] autorelease];
107}
108
109+ (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth
110{
111 return [[[self alloc] initWithFrame:frame pixelFormat:format depthFormat:depth preserveBackbuffer:NO sharegroup:nil multiSampling:NO numberOfSamples:0] autorelease];
112}
113
114+ (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth preserveBackbuffer:(BOOL)retained sharegroup:(EAGLSharegroup*)sharegroup multiSampling:(BOOL)multisampling numberOfSamples:(unsigned int)samples
115{
116 return [[[self alloc] initWithFrame:frame pixelFormat:format depthFormat:depth preserveBackbuffer:retained sharegroup:sharegroup multiSampling:multisampling numberOfSamples:samples] autorelease];
117}
118
119- (id) initWithFrame:(CGRect)frame
120{
121 return [self initWithFrame:frame pixelFormat:kEAGLColorFormatRGB565 depthFormat:0 preserveBackbuffer:NO sharegroup:nil multiSampling:NO numberOfSamples:0];
122}
123
124- (id) initWithFrame:(CGRect)frame pixelFormat:(NSString*)format
125{
126 return [self initWithFrame:frame pixelFormat:format depthFormat:0 preserveBackbuffer:NO sharegroup:nil multiSampling:NO numberOfSamples:0];
127}
128
129- (id) initWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth preserveBackbuffer:(BOOL)retained sharegroup:(EAGLSharegroup*)sharegroup multiSampling:(BOOL)sampling numberOfSamples:(unsigned int)nSamples
130{
131 if((self = [super initWithFrame:frame]))
132 {
133 pixelformat_ = format;
134 depthFormat_ = depth;
135 multiSampling_ = sampling;
136 requestedSamples_ = nSamples;
137 preserveBackbuffer_ = retained;
138
139 if( ! [self setupSurfaceWithSharegroup:sharegroup] ) {
140 [self release];
141 return nil;
142 }
143 }
144
145 return self;
146}
147
148-(id) initWithCoder:(NSCoder *)aDecoder
149{
150 if( (self = [super initWithCoder:aDecoder]) ) {
151
152 CAEAGLLayer* eaglLayer = (CAEAGLLayer*)[self layer];
153
154 pixelformat_ = kEAGLColorFormatRGB565;
155 depthFormat_ = 0; // GL_DEPTH_COMPONENT24_OES;
156 multiSampling_= NO;
157 requestedSamples_ = 0;
158 size_ = [eaglLayer bounds].size;
159
160 if( ! [self setupSurfaceWithSharegroup:nil] ) {
161 [self release];
162 return nil;
163 }
164 }
165
166 return self;
167}
168
169-(BOOL) setupSurfaceWithSharegroup:(EAGLSharegroup*)sharegroup
170{
171 CAEAGLLayer *eaglLayer = (CAEAGLLayer *)self.layer;
172
173 eaglLayer.opaque = YES;
174 eaglLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys:
175 [NSNumber numberWithBool:preserveBackbuffer_], kEAGLDrawablePropertyRetainedBacking,
176 pixelformat_, kEAGLDrawablePropertyColorFormat, nil];
177
178
179 renderer_ = [[ES1Renderer alloc] initWithDepthFormat:depthFormat_
180 withPixelFormat:[self convertPixelFormat:pixelformat_]
181 withSharegroup:sharegroup
182 withMultiSampling:multiSampling_
183 withNumberOfSamples:requestedSamples_];
184 if (!renderer_)
185 return NO;
186
187 context_ = [renderer_ context];
188 [context_ renderbufferStorage:GL_RENDERBUFFER_OES fromDrawable:eaglLayer];
189
190 discardFramebufferSupported_ = [[CCConfiguration sharedConfiguration] supportsDiscardFramebuffer];
191
192 return YES;
193}
194
195- (void) dealloc
196{
197 CCLOGINFO(@"cocos2d: deallocing %@", self);
198
199
200 [renderer_ release];
201 [super dealloc];
202}
203
204- (void) layoutSubviews
205{
206 size_ = [renderer_ backingSize];
207
208 [renderer_ resizeFromLayer:(CAEAGLLayer*)self.layer];
209
210 // Issue #914 #924
211 CCDirector *director = [CCDirector sharedDirector];
212 [director reshapeProjection:size_];
213
214 // Avoid flicker. Issue #350
215 [director performSelectorOnMainThread:@selector(drawScene) withObject:nil waitUntilDone:YES];
216}
217
218- (void) swapBuffers
219{
220 // IMPORTANT:
221 // - preconditions
222 // -> context_ MUST be the OpenGL context
223 // -> renderbuffer_ must be the the RENDER BUFFER
224
225#ifdef __IPHONE_4_0
226
227 if (multiSampling_)
228 {
229 /* Resolve from msaaFramebuffer to resolveFramebuffer */
230 //glDisable(GL_SCISSOR_TEST);
231 glBindFramebufferOES(GL_READ_FRAMEBUFFER_APPLE, [renderer_ msaaFrameBuffer]);
232 glBindFramebufferOES(GL_DRAW_FRAMEBUFFER_APPLE, [renderer_ defaultFrameBuffer]);
233 glResolveMultisampleFramebufferAPPLE();
234 }
235
236 if( discardFramebufferSupported_)
237 {
238 if (multiSampling_)
239 {
240 if (depthFormat_)
241 {
242 GLenum attachments[] = {GL_COLOR_ATTACHMENT0_OES, GL_DEPTH_ATTACHMENT_OES};
243 glDiscardFramebufferEXT(GL_READ_FRAMEBUFFER_APPLE, 2, attachments);
244 }
245 else
246 {
247 GLenum attachments[] = {GL_COLOR_ATTACHMENT0_OES};
248 glDiscardFramebufferEXT(GL_READ_FRAMEBUFFER_APPLE, 1, attachments);
249 }
250
251 glBindRenderbufferOES(GL_RENDERBUFFER_OES, [renderer_ colorRenderBuffer]);
252
253 }
254
255 // not MSAA
256 else if (depthFormat_ ) {
257 GLenum attachments[] = { GL_DEPTH_ATTACHMENT_OES};
258 glDiscardFramebufferEXT(GL_FRAMEBUFFER_OES, 1, attachments);
259 }
260 }
261
262#endif // __IPHONE_4_0
263
264 if(![context_ presentRenderbuffer:GL_RENDERBUFFER_OES])
265 CCLOG(@"cocos2d: Failed to swap renderbuffer in %s\n", __FUNCTION__);
266
267#if COCOS2D_DEBUG
268 CHECK_GL_ERROR();
269#endif
270
271 // We can safely re-bind the framebuffer here, since this will be the
272 // 1st instruction of the new main loop
273 if( multiSampling_ )
274 glBindFramebufferOES(GL_FRAMEBUFFER_OES, [renderer_ msaaFrameBuffer]);
275}
276
277- (unsigned int) convertPixelFormat:(NSString*) pixelFormat
278{
279 // define the pixel format
280 GLenum pFormat;
281
282
283 if([pixelFormat isEqualToString:@"EAGLColorFormat565"])
284 pFormat = GL_RGB565_OES;
285 else
286 pFormat = GL_RGBA8_OES;
287
288 return pFormat;
289}
290
291#pragma mark EAGLView - Point conversion
292
293- (CGPoint) convertPointFromViewToSurface:(CGPoint)point
294{
295 CGRect bounds = [self bounds];
296
297 return CGPointMake((point.x - bounds.origin.x) / bounds.size.width * size_.width, (point.y - bounds.origin.y) / bounds.size.height * size_.height);
298}
299
300- (CGRect) convertRectFromViewToSurface:(CGRect)rect
301{
302 CGRect bounds = [self bounds];
303
304 return CGRectMake((rect.origin.x - bounds.origin.x) / bounds.size.width * size_.width, (rect.origin.y - bounds.origin.y) / bounds.size.height * size_.height, rect.size.width / bounds.size.width * size_.width, rect.size.height / bounds.size.height * size_.height);
305}
306
307// Pass the touches to the superview
308#pragma mark EAGLView - Touch Delegate
309
310- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
311{
312 if(touchDelegate_)
313 {
314 [touchDelegate_ touchesBegan:touches withEvent:event];
315 }
316}
317
318- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
319{
320 if(touchDelegate_)
321 {
322 [touchDelegate_ touchesMoved:touches withEvent:event];
323 }
324}
325
326- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
327{
328 if(touchDelegate_)
329 {
330 [touchDelegate_ touchesEnded:touches withEvent:event];
331 }
332}
333- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
334{
335 if(touchDelegate_)
336 {
337 [touchDelegate_ touchesCancelled:touches withEvent:event];
338 }
339}
340
341@end
342
343#endif // __IPHONE_OS_VERSION_MAX_ALLOWED \ No newline at end of file
diff --git a/libs/cocos2d/Platforms/iOS/ES1Renderer.h b/libs/cocos2d/Platforms/iOS/ES1Renderer.h new file mode 100755 index 0000000..fd946a7 --- /dev/null +++ b/libs/cocos2d/Platforms/iOS/ES1Renderer.h
@@ -0,0 +1,72 @@
1/*
2 * cocos2d for iPhone: http://www.cocos2d-iphone.org
3 *
4 * Copyright (c) 2010 Ricardo Quesada
5 * Copyright (c) 2011 Zynga Inc.
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 * THE SOFTWARE.
24 *
25 *
26 * File autogenerated with Xcode. Adapted for cocos2d needs.
27 */
28
29// Only compile this code on iOS. These files should NOT be included on your Mac project.
30// But in case they are included, it won't be compiled.
31#import <Availability.h>
32#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
33
34
35#import "ESRenderer.h"
36
37#import <OpenGLES/ES1/gl.h>
38#import <OpenGLES/ES1/glext.h>
39
40@interface ES1Renderer : NSObject <ESRenderer>
41{
42 // The pixel dimensions of the CAEAGLLayer
43 GLint backingWidth_;
44 GLint backingHeight_;
45
46 unsigned int samplesToUse_;
47 BOOL multiSampling_;
48
49 unsigned int depthFormat_;
50 unsigned int pixelFormat_;
51
52 // The OpenGL ES names for the framebuffer and renderbuffer used to render to this view
53 GLuint defaultFramebuffer_;
54 GLuint colorRenderbuffer_;
55 GLuint depthBuffer_;
56
57
58 //buffers for MSAA
59 GLuint msaaFramebuffer_;
60 GLuint msaaColorbuffer_;
61
62 EAGLContext *context_;
63}
64
65/** EAGLContext */
66@property (nonatomic,readonly) EAGLContext* context;
67
68- (BOOL)resizeFromLayer:(CAEAGLLayer *)layer;
69
70@end
71
72#endif // __IPHONE_OS_VERSION_MAX_ALLOWED
diff --git a/libs/cocos2d/Platforms/iOS/ES1Renderer.m b/libs/cocos2d/Platforms/iOS/ES1Renderer.m new file mode 100755 index 0000000..398d946 --- /dev/null +++ b/libs/cocos2d/Platforms/iOS/ES1Renderer.m
@@ -0,0 +1,259 @@
1/*
2 * cocos2d for iPhone: http://www.cocos2d-iphone.org
3 *
4 * Copyright (c) 2010 Ricardo Quesada
5 * Copyright (c) 2011 Zynga Inc.
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 * THE SOFTWARE.
24 *
25 *
26 * File autogenerated with Xcode. Adapted for cocos2d needs.
27 */
28
29// Only compile this code on iOS. These files should NOT be included on your Mac project.
30// But in case they are included, it won't be compiled.
31#import <Availability.h>
32#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
33
34#import "ES1Renderer.h"
35#import "../../Support/OpenGL_Internal.h"
36#import "../../ccMacros.h"
37
38
39@interface ES1Renderer (private)
40
41- (GLenum) convertPixelFormat:(int) pixelFormat;
42
43@end
44
45
46@implementation ES1Renderer
47
48@synthesize context=context_;
49
50- (id) initWithDepthFormat:(unsigned int)depthFormat withPixelFormat:(unsigned int)pixelFormat withSharegroup:(EAGLSharegroup*)sharegroup withMultiSampling:(BOOL) multiSampling withNumberOfSamples:(unsigned int) requestedSamples
51{
52 if ((self = [super init]))
53 {
54 if ( sharegroup == nil )
55 {
56 context_ = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES1];
57 }
58 else
59 {
60 context_ = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES1 sharegroup:sharegroup];
61 }
62
63 if (!context_ || ![EAGLContext setCurrentContext:context_])
64 {
65 [self release];
66 return nil;
67 }
68
69 // Create default framebuffer object. The backing will be allocated for the current layer in -resizeFromLayer
70 glGenFramebuffersOES(1, &defaultFramebuffer_);
71 NSAssert( defaultFramebuffer_, @"Can't create default frame buffer");
72 glGenRenderbuffersOES(1, &colorRenderbuffer_);
73 NSAssert( colorRenderbuffer_, @"Can't create default render buffer");
74
75 glBindFramebufferOES(GL_FRAMEBUFFER_OES, defaultFramebuffer_);
76 glBindRenderbufferOES(GL_RENDERBUFFER_OES, colorRenderbuffer_);
77 glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorRenderbuffer_);
78
79 depthFormat_ = depthFormat;
80
81 if( depthFormat_ ) {
82// glGenRenderbuffersOES(1, &depthBuffer_);
83// glBindRenderbufferOES(GL_RENDERBUFFER_OES, depthBuffer_);
84// glRenderbufferStorageOES(GL_RENDERBUFFER_OES, depthFormat_, 100, 100);
85// glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBuffer_);
86
87 // default buffer
88// glBindRenderbufferOES(GL_RENDERBUFFER_OES, colorRenderbuffer_);
89 }
90
91 pixelFormat_ = pixelFormat;
92 multiSampling_ = multiSampling;
93 if (multiSampling_)
94 {
95 GLint maxSamplesAllowed;
96 glGetIntegerv(GL_MAX_SAMPLES_APPLE, &maxSamplesAllowed);
97 samplesToUse_ = MIN(maxSamplesAllowed,requestedSamples);
98
99 /* Create the MSAA framebuffer (offscreen) */
100 glGenFramebuffersOES(1, &msaaFramebuffer_);
101 glBindFramebufferOES(GL_FRAMEBUFFER_OES, msaaFramebuffer_);
102
103 }
104
105 CHECK_GL_ERROR();
106 }
107
108 return self;
109}
110
111- (BOOL)resizeFromLayer:(CAEAGLLayer *)layer
112{
113 // Allocate color buffer backing based on the current layer size
114
115 glBindRenderbufferOES(GL_RENDERBUFFER_OES, colorRenderbuffer_);
116
117 if (![context_ renderbufferStorage:GL_RENDERBUFFER_OES fromDrawable:layer])
118 {
119 CCLOG(@"failed to call context");
120 }
121
122 glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &backingWidth_);
123 glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &backingHeight_);
124
125 CCLOG(@"cocos2d: surface size: %dx%d", (int)backingWidth_, (int)backingHeight_);
126
127 if (multiSampling_)
128 {
129
130 if ( msaaColorbuffer_) {
131 glDeleteRenderbuffersOES(1, &msaaColorbuffer_);
132 msaaColorbuffer_ = 0;
133 }
134
135 /* Create the offscreen MSAA color buffer.
136 After rendering, the contents of this will be blitted into ColorRenderbuffer */
137
138 //msaaFrameBuffer needs to be binded
139 glBindFramebufferOES(GL_FRAMEBUFFER_OES, msaaFramebuffer_);
140 glGenRenderbuffersOES(1, &msaaColorbuffer_);
141 glBindRenderbufferOES(GL_RENDERBUFFER_OES, msaaColorbuffer_);
142 glRenderbufferStorageMultisampleAPPLE(GL_RENDERBUFFER_OES, samplesToUse_,pixelFormat_ , backingWidth_, backingHeight_);
143 glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, msaaColorbuffer_);
144
145 if (glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES) != GL_FRAMEBUFFER_COMPLETE_OES)
146 {
147 CCLOG(@"Failed to make complete framebuffer object %x", glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES));
148 return NO;
149 }
150 }
151
152 if (depthFormat_)
153 {
154 if( ! depthBuffer_ )
155 glGenRenderbuffersOES(1, &depthBuffer_);
156
157 glBindRenderbufferOES(GL_RENDERBUFFER_OES, depthBuffer_);
158 if( multiSampling_ )
159 glRenderbufferStorageMultisampleAPPLE(GL_RENDERBUFFER_OES, samplesToUse_, depthFormat_,backingWidth_, backingHeight_);
160 else
161 glRenderbufferStorageOES(GL_RENDERBUFFER_OES, depthFormat_, backingWidth_, backingHeight_);
162 glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBuffer_);
163
164 // bind color buffer
165 glBindRenderbufferOES(GL_RENDERBUFFER_OES, colorRenderbuffer_);
166 }
167
168 glBindFramebufferOES(GL_FRAMEBUFFER_OES, defaultFramebuffer_);
169
170 if (glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES) != GL_FRAMEBUFFER_COMPLETE_OES)
171 {
172 CCLOG(@"Failed to make complete framebuffer object %x", glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES));
173 return NO;
174 }
175
176 CHECK_GL_ERROR();
177
178 return YES;
179}
180
181-(CGSize) backingSize
182{
183 return CGSizeMake( backingWidth_, backingHeight_);
184}
185
186- (NSString*) description
187{
188 return [NSString stringWithFormat:@"<%@ = %08X | size = %ix%i>", [self class], self, backingWidth_, backingHeight_];
189}
190
191
192- (void)dealloc
193{
194 CCLOGINFO(@"cocos2d: deallocing %@", self);
195
196 // Tear down GL
197 if(defaultFramebuffer_)
198 {
199 glDeleteFramebuffersOES(1, &defaultFramebuffer_);
200 defaultFramebuffer_ = 0;
201 }
202
203 if(colorRenderbuffer_)
204 {
205 glDeleteRenderbuffersOES(1, &colorRenderbuffer_);
206 colorRenderbuffer_ = 0;
207 }
208
209 if( depthBuffer_ )
210 {
211 glDeleteRenderbuffersOES(1, &depthBuffer_);
212 depthBuffer_ = 0;
213 }
214
215 if ( msaaColorbuffer_)
216 {
217 glDeleteRenderbuffersOES(1, &msaaColorbuffer_);
218 msaaColorbuffer_ = 0;
219 }
220
221 if ( msaaFramebuffer_)
222 {
223 glDeleteRenderbuffersOES(1, &msaaFramebuffer_);
224 msaaFramebuffer_ = 0;
225 }
226
227 // Tear down context
228 if ([EAGLContext currentContext] == context_)
229 [EAGLContext setCurrentContext:nil];
230
231 [context_ release];
232 context_ = nil;
233
234 [super dealloc];
235}
236
237- (unsigned int) colorRenderBuffer
238{
239 return colorRenderbuffer_;
240}
241
242- (unsigned int) defaultFrameBuffer
243{
244 return defaultFramebuffer_;
245}
246
247- (unsigned int) msaaFrameBuffer
248{
249 return msaaFramebuffer_;
250}
251
252- (unsigned int) msaaColorBuffer
253{
254 return msaaColorbuffer_;
255}
256
257@end
258
259#endif // __IPHONE_OS_VERSION_MAX_ALLOWED
diff --git a/libs/cocos2d/Platforms/iOS/ESRenderer.h b/libs/cocos2d/Platforms/iOS/ESRenderer.h new file mode 100755 index 0000000..e612eee --- /dev/null +++ b/libs/cocos2d/Platforms/iOS/ESRenderer.h
@@ -0,0 +1,54 @@
1/*
2 * cocos2d for iPhone: http://www.cocos2d-iphone.org
3 *
4 * Copyright (c) 2010 Ricardo Quesada
5 * Copyright (c) 2011 Zynga Inc.
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 * THE SOFTWARE.
24 *
25 *
26 * File autogenerated with Xcode. Adapted for cocos2d needs.
27 */
28
29// Only compile this code on iOS. These files should NOT be included on your Mac project.
30// But in case they are included, it won't be compiled.
31#import <Availability.h>
32#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
33
34#import <QuartzCore/QuartzCore.h>
35
36#import <OpenGLES/EAGL.h>
37#import <OpenGLES/EAGLDrawable.h>
38
39@protocol ESRenderer <NSObject>
40
41- (id) initWithDepthFormat:(unsigned int)depthFormat withPixelFormat:(unsigned int)pixelFormat withSharegroup:(EAGLSharegroup*)sharegroup withMultiSampling:(BOOL) multiSampling withNumberOfSamples:(unsigned int) requestedSamples;
42
43- (BOOL) resizeFromLayer:(CAEAGLLayer *)layer;
44
45- (EAGLContext*) context;
46- (CGSize) backingSize;
47
48- (unsigned int) colorRenderBuffer;
49- (unsigned int) defaultFrameBuffer;
50- (unsigned int) msaaFrameBuffer;
51- (unsigned int) msaaColorBuffer;
52@end
53
54#endif // __IPHONE_OS_VERSION_MAX_ALLOWED
diff --git a/libs/cocos2d/Platforms/iOS/glu.c b/libs/cocos2d/Platforms/iOS/glu.c new file mode 100755 index 0000000..2e00d5f --- /dev/null +++ b/libs/cocos2d/Platforms/iOS/glu.c
@@ -0,0 +1,113 @@
1//
2// cocos2d (incomplete) GLU implementation
3//
4// gluLookAt and gluPerspective from:
5// http://jet.ro/creations (San Angeles Observation)
6//
7//
8
9// Only compile this code on iOS. These files should NOT be included on your Mac project.
10// But in case they are included, it won't be compiled.
11#import <Availability.h>
12#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
13
14#import <OpenGLES/ES1/gl.h>
15#import <math.h>
16#import "../../Support/OpenGL_Internal.h"
17#include "glu.h"
18
19void gluPerspective(GLfloat fovy, GLfloat aspect, GLfloat zNear, GLfloat zFar)
20{
21 GLfloat xmin, xmax, ymin, ymax;
22
23 ymax = zNear * (GLfloat)tanf(fovy * (float)M_PI / 360);
24 ymin = -ymax;
25 xmin = ymin * aspect;
26 xmax = ymax * aspect;
27
28 glFrustumf(xmin, xmax,
29 ymin, ymax,
30 zNear, zFar);
31}
32
33void gluLookAt(GLfloat eyex, GLfloat eyey, GLfloat eyez,
34 GLfloat centerx, GLfloat centery, GLfloat centerz,
35 GLfloat upx, GLfloat upy, GLfloat upz)
36{
37 GLfloat m[16];
38 GLfloat x[3], y[3], z[3];
39 GLfloat mag;
40
41 /* Make rotation matrix */
42
43 /* Z vector */
44 z[0] = eyex - centerx;
45 z[1] = eyey - centery;
46 z[2] = eyez - centerz;
47 mag = (float)sqrtf(z[0] * z[0] + z[1] * z[1] + z[2] * z[2]);
48 if (mag) {
49 z[0] /= mag;
50 z[1] /= mag;
51 z[2] /= mag;
52 }
53
54 /* Y vector */
55 y[0] = upx;
56 y[1] = upy;
57 y[2] = upz;
58
59 /* X vector = Y cross Z */
60 x[0] = y[1] * z[2] - y[2] * z[1];
61 x[1] = -y[0] * z[2] + y[2] * z[0];
62 x[2] = y[0] * z[1] - y[1] * z[0];
63
64 /* Recompute Y = Z cross X */
65 y[0] = z[1] * x[2] - z[2] * x[1];
66 y[1] = -z[0] * x[2] + z[2] * x[0];
67 y[2] = z[0] * x[1] - z[1] * x[0];
68
69 /* cross product gives area of parallelogram, which is < 1.0 for
70 * non-perpendicular unit-length vectors; so normalize x, y here
71 */
72
73 mag = (float)sqrtf(x[0] * x[0] + x[1] * x[1] + x[2] * x[2]);
74 if (mag) {
75 x[0] /= mag;
76 x[1] /= mag;
77 x[2] /= mag;
78 }
79
80 mag = (float)sqrtf(y[0] * y[0] + y[1] * y[1] + y[2] * y[2]);
81 if (mag) {
82 y[0] /= mag;
83 y[1] /= mag;
84 y[2] /= mag;
85 }
86
87#define M(row,col) m[col*4+row]
88 M(0, 0) = x[0];
89 M(0, 1) = x[1];
90 M(0, 2) = x[2];
91 M(0, 3) = 0.0f;
92 M(1, 0) = y[0];
93 M(1, 1) = y[1];
94 M(1, 2) = y[2];
95 M(1, 3) = 0.0f;
96 M(2, 0) = z[0];
97 M(2, 1) = z[1];
98 M(2, 2) = z[2];
99 M(2, 3) = 0.0f;
100 M(3, 0) = 0.0f;
101 M(3, 1) = 0.0f;
102 M(3, 2) = 0.0f;
103 M(3, 3) = 1.0f;
104#undef M
105
106 glMultMatrixf(m);
107
108
109 /* Translate Eye to Origin */
110 glTranslatef(-eyex, -eyey, -eyez);
111}
112
113#endif // __IPHONE_OS_VERSION_MAX_ALLOWED
diff --git a/libs/cocos2d/Platforms/iOS/glu.h b/libs/cocos2d/Platforms/iOS/glu.h new file mode 100755 index 0000000..86dcac7 --- /dev/null +++ b/libs/cocos2d/Platforms/iOS/glu.h
@@ -0,0 +1,29 @@
1//
2// cocos2d GLU implementation
3//
4// implementation of GLU functions
5//
6#ifndef __COCOS2D_GLU_H
7#define __COCOS2D_GLU_H
8
9// Only compile this code on iOS. These files should NOT be included on your Mac project.
10// But in case they are included, it won't be compiled.
11#import <Availability.h>
12#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
13
14#import <OpenGLES/ES1/gl.h>
15
16/**
17 @file
18 cocos2d OpenGL GLU implementation
19 */
20
21/** OpenGL gluLookAt implementation */
22void gluLookAt(float eyeX, float eyeY, float eyeZ, float lookAtX, float lookAtY, float lookAtZ, float upX, float upY, float upZ);
23/** OpenGL gluPerspective implementation */
24void gluPerspective(GLfloat fovy, GLfloat aspect, GLfloat zNear, GLfloat zFar);
25
26#endif // __IPHONE_OS_VERSION_MAX_ALLOWED
27
28#endif /* __COCOS2D_GLU_H */
29