简化ios下的js引擎加载流程

This commit is contained in:
cebgcontract 2022-06-30 14:39:30 +08:00
parent 833ae805ba
commit 4e7906ed8b
5 changed files with 12 additions and 755 deletions

View File

@ -483,8 +483,6 @@
5027253C190BF1B900AAF4ED /* cocos2d.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 50272539190BF1B900AAF4ED /* cocos2d.cpp */; }; 5027253C190BF1B900AAF4ED /* cocos2d.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 50272539190BF1B900AAF4ED /* cocos2d.cpp */; };
5027253D190BF1B900AAF4ED /* cocos2d.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 50272539190BF1B900AAF4ED /* cocos2d.cpp */; }; 5027253D190BF1B900AAF4ED /* cocos2d.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 50272539190BF1B900AAF4ED /* cocos2d.cpp */; };
503DD8E31926736A00CD74DD /* CCDevice-ios.mm in Sources */ = {isa = PBXBuildFile; fileRef = 503DD8D11926736A00CD74DD /* CCDevice-ios.mm */; }; 503DD8E31926736A00CD74DD /* CCDevice-ios.mm in Sources */ = {isa = PBXBuildFile; fileRef = 503DD8D11926736A00CD74DD /* CCDevice-ios.mm */; };
503DD8E61926736A00CD74DD /* CCEAGLView-ios.h in Headers */ = {isa = PBXBuildFile; fileRef = 503DD8D41926736A00CD74DD /* CCEAGLView-ios.h */; };
503DD8E71926736A00CD74DD /* CCEAGLView-ios.mm in Sources */ = {isa = PBXBuildFile; fileRef = 503DD8D51926736A00CD74DD /* CCEAGLView-ios.mm */; };
503DD8EB1926736A00CD74DD /* CCGL-ios.h in Headers */ = {isa = PBXBuildFile; fileRef = 503DD8D91926736A00CD74DD /* CCGL-ios.h */; }; 503DD8EB1926736A00CD74DD /* CCGL-ios.h in Headers */ = {isa = PBXBuildFile; fileRef = 503DD8D91926736A00CD74DD /* CCGL-ios.h */; };
503DD8EE1926736A00CD74DD /* CCImage-ios.mm in Sources */ = {isa = PBXBuildFile; fileRef = 503DD8DC1926736A00CD74DD /* CCImage-ios.mm */; }; 503DD8EE1926736A00CD74DD /* CCImage-ios.mm in Sources */ = {isa = PBXBuildFile; fileRef = 503DD8DC1926736A00CD74DD /* CCImage-ios.mm */; };
503DD8EF1926736A00CD74DD /* CCPlatformDefine-ios.h in Headers */ = {isa = PBXBuildFile; fileRef = 503DD8DD1926736A00CD74DD /* CCPlatformDefine-ios.h */; }; 503DD8EF1926736A00CD74DD /* CCPlatformDefine-ios.h in Headers */ = {isa = PBXBuildFile; fileRef = 503DD8DD1926736A00CD74DD /* CCPlatformDefine-ios.h */; };
@ -886,8 +884,6 @@
50272538190BF1B900AAF4ED /* cocos2d.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = cocos2d.h; path = ../cocos/cocos2d.h; sourceTree = "<group>"; }; 50272538190BF1B900AAF4ED /* cocos2d.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = cocos2d.h; path = ../cocos/cocos2d.h; sourceTree = "<group>"; };
50272539190BF1B900AAF4ED /* cocos2d.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = cocos2d.cpp; path = ../cocos/cocos2d.cpp; sourceTree = "<group>"; }; 50272539190BF1B900AAF4ED /* cocos2d.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = cocos2d.cpp; path = ../cocos/cocos2d.cpp; sourceTree = "<group>"; };
503DD8D11926736A00CD74DD /* CCDevice-ios.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = "CCDevice-ios.mm"; sourceTree = "<group>"; }; 503DD8D11926736A00CD74DD /* CCDevice-ios.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = "CCDevice-ios.mm"; sourceTree = "<group>"; };
503DD8D41926736A00CD74DD /* CCEAGLView-ios.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "CCEAGLView-ios.h"; sourceTree = "<group>"; };
503DD8D51926736A00CD74DD /* CCEAGLView-ios.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = "CCEAGLView-ios.mm"; sourceTree = "<group>"; };
503DD8D91926736A00CD74DD /* CCGL-ios.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "CCGL-ios.h"; sourceTree = "<group>"; }; 503DD8D91926736A00CD74DD /* CCGL-ios.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "CCGL-ios.h"; sourceTree = "<group>"; };
503DD8DC1926736A00CD74DD /* CCImage-ios.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = "CCImage-ios.mm"; sourceTree = "<group>"; }; 503DD8DC1926736A00CD74DD /* CCImage-ios.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = "CCImage-ios.mm"; sourceTree = "<group>"; };
503DD8DD1926736A00CD74DD /* CCPlatformDefine-ios.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "CCPlatformDefine-ios.h"; sourceTree = "<group>"; }; 503DD8DD1926736A00CD74DD /* CCPlatformDefine-ios.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "CCPlatformDefine-ios.h"; sourceTree = "<group>"; };
@ -1587,8 +1583,6 @@
051C017021E2F85C00D4A347 /* CCModuleConfigIOS.release.xcconfig */, 051C017021E2F85C00D4A347 /* CCModuleConfigIOS.release.xcconfig */,
46FDDC68202D733700931238 /* CCApplication-ios.mm */, 46FDDC68202D733700931238 /* CCApplication-ios.mm */,
503DD8D11926736A00CD74DD /* CCDevice-ios.mm */, 503DD8D11926736A00CD74DD /* CCDevice-ios.mm */,
503DD8D41926736A00CD74DD /* CCEAGLView-ios.h */,
503DD8D51926736A00CD74DD /* CCEAGLView-ios.mm */,
503DD8D91926736A00CD74DD /* CCGL-ios.h */, 503DD8D91926736A00CD74DD /* CCGL-ios.h */,
503DD8DC1926736A00CD74DD /* CCImage-ios.mm */, 503DD8DC1926736A00CD74DD /* CCImage-ios.mm */,
503DD8DD1926736A00CD74DD /* CCPlatformDefine-ios.h */, 503DD8DD1926736A00CD74DD /* CCPlatformDefine-ios.h */,
@ -1987,7 +1981,6 @@
50ABC0101926664800A911A9 /* CCFileUtils.h in Headers */, 50ABC0101926664800A911A9 /* CCFileUtils.h in Headers */,
1A29D77E2056667800168D9A /* csscolorparser.hpp in Headers */, 1A29D77E2056667800168D9A /* csscolorparser.hpp in Headers */,
46AE40062092F3A600F3A228 /* inspector_socket.h in Headers */, 46AE40062092F3A600F3A228 /* inspector_socket.h in Headers */,
503DD8E61926736A00CD74DD /* CCEAGLView-ios.h in Headers */,
469303972046AE05004A3D6C /* Class.hpp in Headers */, 469303972046AE05004A3D6C /* Class.hpp in Headers */,
469304112046AE06004A3D6C /* jsb_helper.hpp in Headers */, 469304112046AE06004A3D6C /* jsb_helper.hpp in Headers */,
1A52DAF7205BB81400350EE3 /* CCThreadPool.h in Headers */, 1A52DAF7205BB81400350EE3 /* CCThreadPool.h in Headers */,
@ -2412,7 +2405,6 @@
294D7D9D1D0E93A2002CE7B7 /* CCDevice-apple.mm in Sources */, 294D7D9D1D0E93A2002CE7B7 /* CCDevice-apple.mm in Sources */,
4617864F205224D6008256E1 /* HttpAsynConnection-apple.m in Sources */, 4617864F205224D6008256E1 /* HttpAsynConnection-apple.m in Sources */,
1A52DB8E2060DEF500350EE3 /* jsb_platfrom_apple.mm in Sources */, 1A52DB8E2060DEF500350EE3 /* jsb_platfrom_apple.mm in Sources */,
503DD8E71926736A00CD74DD /* CCEAGLView-ios.mm in Sources */,
1A29D785205666B200168D9A /* LocalStorage.cpp in Sources */, 1A29D785205666B200168D9A /* LocalStorage.cpp in Sources */,
46AE3FEA2092F3A600F3A228 /* inspector_socket_server.cc in Sources */, 46AE3FEA2092F3A600F3A228 /* inspector_socket_server.cc in Sources */,
4617861A20522469008256E1 /* SocketIO.cpp in Sources */, 4617861A20522469008256E1 /* SocketIO.cpp in Sources */,

View File

@ -31,7 +31,6 @@
#include "base/CCConfiguration.h" #include "base/CCConfiguration.h"
#include "scripting/js-bindings/event/EventDispatcher.h" #include "scripting/js-bindings/event/EventDispatcher.h"
#include "scripting/js-bindings/jswrapper/SeApi.h" #include "scripting/js-bindings/jswrapper/SeApi.h"
#include "CCEAGLView-ios.h"
#include "base/CCGLUtils.h" #include "base/CCGLUtils.h"
#include "platform/CCDevice.h" #include "platform/CCDevice.h"
@ -63,21 +62,19 @@ namespace
self = [super init]; self = [super init];
if (self) if (self)
{ {
_fps = 60;
_systemVersion = [[UIDevice currentDevice].systemVersion floatValue];
_application = application; _application = application;
_scheduler = _application->getScheduler(); _scheduler = _application->getScheduler();
_lastRotation = cocos2d::Device::getDeviceRotation(); // _lastRotation = cocos2d::Device::getDeviceRotation();
_isAppActive = [UIApplication sharedApplication].applicationState == UIApplicationStateActive; _isAppActive = [UIApplication sharedApplication].applicationState == UIApplicationStateActive;
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; // NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self selector:@selector(appDidBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil]; // [nc addObserver:self selector:@selector(appDidBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil];
[nc addObserver:self selector:@selector(appDidBecomeInactive) name:UIApplicationWillResignActiveNotification object:nil]; // [nc addObserver:self selector:@selector(appDidBecomeInactive) name:UIApplicationWillResignActiveNotification object:nil];
//
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications]; // [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[nc addObserver:self selector:@selector(statusBarOrientationChanged:)name:UIApplicationDidChangeStatusBarOrientationNotification // [nc addObserver:self selector:@selector(statusBarOrientationChanged:)name:UIApplicationDidChangeStatusBarOrientationNotification
object:nil]; // object:nil];
} }
return self; return self;
} }
@ -196,35 +193,6 @@ namespace
{ {
static std::chrono::steady_clock::time_point prevTime; static std::chrono::steady_clock::time_point prevTime;
static std::chrono::steady_clock::time_point now; static std::chrono::steady_clock::time_point now;
static float dt = 0.f;
if (_isAppActive)
{
EAGLContext* context = [(CCEAGLView*)(_application->getView()) getContext];
if (context != [EAGLContext currentContext])
{
glFlush();
}
[EAGLContext setCurrentContext: context];
prevTime = std::chrono::steady_clock::now();
bool downsampleEnabled = _application->isDownsampleEnabled();
if (downsampleEnabled)
_application->getRenderTexture()->prepare();
_scheduler->update(dt);
cocos2d::EventDispatcher::dispatchTickEvent(dt);
if (downsampleEnabled)
_application->getRenderTexture()->draw();
[(CCEAGLView*)(_application->getView()) swapBuffers];
cocos2d::PoolManager::getInstance()->getCurrentPool()->clear();
now = std::chrono::steady_clock::now();
dt = std::chrono::duration_cast<std::chrono::microseconds>(now - prevTime).count() / 1000000.f;
}
} }
@end @end
@ -239,18 +207,12 @@ Application::Application(const std::string& name, int width, int height)
Application::_instance = this; Application::_instance = this;
_scheduler = std::make_shared<Scheduler>(); _scheduler = std::make_shared<Scheduler>();
createView(name, width, height);
Configuration::getInstance();
glGetIntegerv(GL_FRAMEBUFFER_BINDING, &_mainFBO);
_renderTexture = new RenderTexture(width, height);
se::ScriptEngine::getInstance(); se::ScriptEngine::getInstance();
EventDispatcher::init(); EventDispatcher::init();
_delegate = [[MainLoop alloc] initWithApplication:this]; _delegate = [[MainLoop alloc] initWithApplication:this];
updateViewSize(width, height); // updateViewSize(width, height);
} }
Application::~Application() Application::~Application()
@ -265,7 +227,6 @@ Application::~Application()
[(MainLoop*)_delegate release]; [(MainLoop*)_delegate release];
_delegate = nullptr; _delegate = nullptr;
[(CCEAGLView*)_view release];
_view = nullptr; _view = nullptr;
delete _renderTexture; delete _renderTexture;
@ -289,14 +250,14 @@ void Application::updateViewSize(int width, int height)
void Application::start() void Application::start()
{ {
if (_delegate) if (_delegate)
[(MainLoop*)_delegate performSelector:@selector(firstStart:) withObject:(CCEAGLView*)_view afterDelay:0]; [(MainLoop*)_delegate firstStart:nullptr];
} }
void Application::restart() void Application::restart()
{ {
if (_delegate) { if (_delegate) {
[(MainLoop*)_delegate stopMainLoop]; [(MainLoop*)_delegate stopMainLoop];
[(MainLoop*)_delegate performSelector:@selector(firstStart:) withObject:(CCEAGLView*)_view afterDelay:0]; [(MainLoop*)_delegate firstStart:nullptr];
} }
} }
@ -414,12 +375,7 @@ void Application::onResume()
void Application::setMultitouch(bool value) void Application::setMultitouch(bool value)
{ {
if (value != _multiTouch)
{
_multiTouch = value;
if (_view)
[(CCEAGLView*)_view setMultipleTouchEnabled:_multiTouch];
}
} }
void Application::onCreateView(PixelFormat& pixelformat, DepthFormat& depthFormat, int& multisamplingCount) void Application::onCreateView(PixelFormat& pixelformat, DepthFormat& depthFormat, int& multisamplingCount)
@ -451,43 +407,6 @@ namespace
void Application::createView(const std::string& /*name*/, int width, int height) void Application::createView(const std::string& /*name*/, int width, int height)
{ {
PixelFormat pixelFormat = PixelFormat::RGB565;
DepthFormat depthFormat = DepthFormat::DEPTH24_STENCIL8;
int multisamplingCount = 0;
onCreateView(pixelFormat,
depthFormat,
multisamplingCount);
CGRect bounds;
bounds.origin.x = 0;
bounds.origin.y = 0;
bounds.size.width = width;
bounds.size.height = height;
//IDEA: iOS only support these pixel format?
// - RGB565
// - RGBA8
NSString *pixelString = kEAGLColorFormatRGB565;
if (PixelFormat::RGB565 != pixelFormat &&
PixelFormat::RGBA8 != pixelFormat)
NSLog(@"Unsupported pixel format is set, iOS only support RGB565 or RGBA8. Change to use RGB565");
else if (PixelFormat::RGBA8 == pixelFormat)
pixelString = kEAGLColorFormatRGBA8;
// create view
CCEAGLView *eaglView = [CCEAGLView viewWithFrame: bounds
pixelFormat: pixelString
depthFormat: depthFormat2GLDepthFormat(depthFormat)
preserveBackbuffer: NO
sharegroup: nil
multiSampling: multisamplingCount != 0
numberOfSamples: multisamplingCount];
[eaglView setMultipleTouchEnabled:_multiTouch];
[eaglView retain];
_view = eaglView;
} }
std::string Application::getSystemVersion() std::string Application::getSystemVersion()

View File

@ -25,7 +25,6 @@
****************************************************************************/ ****************************************************************************/
#include "CCApplication.h" #include "CCApplication.h"
#include "platform/CCDevice.h" #include "platform/CCDevice.h"
#include "platform/ios/CCEAGLView-ios.h"
// Vibrate // Vibrate
#import <AudioToolbox/AudioToolbox.h> #import <AudioToolbox/AudioToolbox.h>

View File

@ -1,121 +0,0 @@
/*
===== IMPORTANT =====
This is sample code demonstrating API, technology or techniques in development.
Although this sample code has been reviewed for technical accuracy, it is not
final. Apple is supplying this information to help you plan for the adoption of
the technologies and programming interfaces described herein. This information
is subject to change, and software implemented based on this sample code should
be tested with final operating system software and final documentation. Newer
versions of this sample code may be provided with future seeds of the API or
technology. For information about updates to this and other developer
documentation, view the New & Updated sidebars in subsequent documentation
seeds.
=====================
File: EAGLView.h
Abstract: Convenience class that wraps the CAEAGLLayer from CoreAnimation into a
UIView subclass.
Version: 1.3
Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc.
("Apple") in consideration of your agreement to the following terms, and your
use, installation, modification or redistribution of this Apple software
constitutes acceptance of these terms. If you do not agree with these terms,
please do not use, install, modify or redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and subject
to these terms, Apple grants you a personal, non-exclusive license, under
Apple's copyrights in this original Apple software (the "Apple Software"), to
use, reproduce, modify and redistribute the Apple Software, with or without
modifications, in source and/or binary forms; provided that if you redistribute
the Apple Software in its entirety and without modifications, you must retain
this notice and the following text and disclaimers in all such redistributions
of the Apple Software.
Neither the name, trademarks, service marks or logos of Apple Inc. may be used
to endorse or promote products derived from the Apple Software without specific
prior written permission from Apple. Except as expressly stated in this notice,
no other rights or licenses, express or implied, are granted by Apple herein,
including but not limited to any patent rights that may be infringed by your
derivative works or by other works in which the Apple Software may be
incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO
WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR
DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF
CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF
APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Copyright (C) 2008 Apple Inc. All Rights Reserved.
*/
#pragma once
#import <UIKit/UIKit.h>
#import <OpenGLES/EAGL.h>
#import <OpenGLES/EAGLDrawable.h>
#import <OpenGLES/ES2/gl.h>
#import <OpenGLES/ES2/glext.h>
#import <CoreFoundation/CoreFoundation.h>
//CLASS INTERFACE:
/** CCEAGLView Class.
* This class wraps the CAEAGLLayer from CoreAnimation into a convenient UIView subclass.
* The view content is basically an EAGL surface you render your OpenGL scene into.
* Note that setting the view non-opaque will only work if the EAGL surface has an alpha channel.
*/
@interface CCEAGLView : UIView
{
@private
EAGLContext *_context;
GLuint _defaultFramebuffer;
GLuint _defaultColorBuffer;
GLuint _defaultDepthBuffer;
//fsaa addition
BOOL _multisampling;
int _requestedSamples;
GLuint _msaaFramebuffer;
GLuint _msaaColorBuffer;
GLuint _msaaDepthBuffer;
NSString *_pixelformatString;
GLenum _pixelformat;
GLuint _depthFormat;
BOOL _preserveBackbuffer;
BOOL _discardFramebufferSupported;
EAGLSharegroup* _sharegroup;
unsigned int _touchIds;
UITouch* _touches[10];
BOOL _isReady;
BOOL _needToPreventTouch;
}
/** creates an initializes an CCEAGLView with a frame, a color buffer format, a depth buffer format, a sharegroup, and multisampling */
+(id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth preserveBackbuffer:(BOOL)retained sharegroup:(EAGLSharegroup*)sharegroup multiSampling:(BOOL)multisampling numberOfSamples:(unsigned int)samples;
/** Initializes an CCEAGLView with a frame, a color buffer format, a depth buffer format, a sharegroup and multisampling support */
-(id) initWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth preserveBackbuffer:(BOOL)retained sharegroup:(EAGLSharegroup*)sharegroup multiSampling:(BOOL)sampling numberOfSamples:(unsigned int)nSamples;
/** CCEAGLView uses double-buffer. This method swaps the buffers */
-(void) swapBuffers;
-(BOOL) isReady;
-(void) setPreventTouchEvent:(BOOL) flag;
-(EAGLContext*) getContext;
@end

View File

@ -1,532 +0,0 @@
/*
===== IMPORTANT =====
This is sample code demonstrating API, technology or techniques in development.
Although this sample code has been reviewed for technical accuracy, it is not
final. Apple is supplying this information to help you plan for the adoption of
the technologies and programming interfaces described herein. This information
is subject to change, and software implemented based on this sample code should
be tested with final operating system software and final documentation. Newer
versions of this sample code may be provided with future seeds of the API or
technology. For information about updates to this and other developer
documentation, view the New & Updated sidebars in subsequent documentation
seeds.
=====================
File: EAGLView.m
Abstract: Convenience class that wraps the CAEAGLLayer from CoreAnimation into a
UIView subclass.
Version: 1.3
Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc.
("Apple") in consideration of your agreement to the following terms, and your
use, installation, modification or redistribution of this Apple software
constitutes acceptance of these terms. If you do not agree with these terms,
please do not use, install, modify or redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and subject
to these terms, Apple grants you a personal, non-exclusive license, under
Apple's copyrights in this original Apple software (the "Apple Software"), to
use, reproduce, modify and redistribute the Apple Software, with or without
modifications, in source and/or binary forms; provided that if you redistribute
the Apple Software in its entirety and without modifications, you must retain
this notice and the following text and disclaimers in all such redistributions
of the Apple Software.
Neither the name, trademarks, service marks or logos of Apple Inc. may be used
to endorse or promote products derived from the Apple Software without specific
prior written permission from Apple. Except as expressly stated in this notice,
no other rights or licenses, express or implied, are granted by Apple herein,
including but not limited to any patent rights that may be infringed by your
derivative works or by other works in which the Apple Software may be
incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO
WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR
DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF
CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF
APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Copyright (C) 2008 Apple Inc. All Rights Reserved.
*/
#import "platform/ios/CCEAGLView-ios.h"
#import <QuartzCore/QuartzCore.h>
#include "scripting/js-bindings/event/EventDispatcher.h"
#include "platform/ios/OpenGL_Internal-ios.h"
#include "platform/CCApplication.h"
#include "base/ccMacros.h"
namespace
{
GLenum pixelformat2glenum(NSString* str)
{
if ([str isEqualToString:kEAGLColorFormatRGB565])
return GL_RGB565;
else
return GL_RGBA8_OES;
}
}
//CLASS IMPLEMENTATIONS:
#define MAX_TOUCH_COUNT 10
@interface CCEAGLView (Private)
@end
@implementation CCEAGLView
+ (Class) layerClass
{
return [CAEAGLLayer class];
}
+ (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth preserveBackbuffer:(BOOL)retained sharegroup:(EAGLSharegroup*)sharegroup multiSampling:(BOOL)multisampling numberOfSamples:(unsigned int)samples
{
return [[[self alloc]initWithFrame:frame pixelFormat:format depthFormat:depth preserveBackbuffer:retained sharegroup:sharegroup multiSampling:multisampling numberOfSamples:samples] autorelease];
}
- (id) initWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth preserveBackbuffer:(BOOL)retained sharegroup:(EAGLSharegroup*)sharegroup multiSampling:(BOOL)sampling numberOfSamples:(unsigned int)nSamples;
{
if((self = [super initWithFrame:frame]))
{
_pixelformatString = format;
_pixelformat = pixelformat2glenum(_pixelformatString);
_depthFormat = depth;
// Multisampling doc: https://developer.apple.com/library/content/documentation/3DDrawing/Conceptual/OpenGLES_ProgrammingGuide/WorkingwithEAGLContexts/WorkingwithEAGLContexts.html#//apple_ref/doc/uid/TP40008793-CH103-SW4
_multisampling = sampling;
_requestedSamples = nSamples;
_preserveBackbuffer = retained;
_sharegroup = sharegroup;
_isReady = FALSE;
_needToPreventTouch = FALSE;
#if GL_EXT_discard_framebuffer == 1
_discardFramebufferSupported = YES;
#else
_discardFramebufferSupported = NO;
#endif
if ([self respondsToSelector:@selector(setContentScaleFactor:)])
self.contentScaleFactor = [[UIScreen mainScreen] scale];
_touchIds = 0;
for (int i = 0; i < 10; ++i)
_touches[i] = nil;
[self setupGLContext];
}
return self;
}
- (void) dealloc
{
if (_defaultColorBuffer)
{
glDeleteRenderbuffers(1, &_defaultColorBuffer);
_defaultColorBuffer = 0;
}
if (_defaultDepthBuffer)
{
glDeleteRenderbuffers(1, &_defaultDepthBuffer);
_defaultDepthBuffer = 0;
}
if (_defaultFramebuffer)
{
glDeleteFramebuffers(1, &_defaultFramebuffer);
_defaultFramebuffer = 0;
}
if (_msaaColorBuffer)
{
glDeleteRenderbuffers(1, &_msaaColorBuffer);
_msaaColorBuffer = 0;
}
if (_msaaDepthBuffer)
{
glDeleteRenderbuffers(1, &_msaaDepthBuffer);
_msaaDepthBuffer = 0;
}
if (_msaaFramebuffer)
{
glDeleteFramebuffers(1, &_msaaFramebuffer);
_msaaFramebuffer = 0;
}
if ([EAGLContext currentContext] == _context)
[EAGLContext setCurrentContext:nil];
if (_context)
{
[_context release];
_context = nil;
}
[super dealloc];
}
- (void) layoutSubviews
{
// On some devices with iOS13, `[_context renderbufferStorage:GL_RENDERBUFFER fromDrawable:(CAEAGLLayer *)self.layer]`
// will return false if lock screen when running application, which make framebuffer in invalid state.
// FIXME: do binding framebuffer in other place?
UIApplicationState state = [[UIApplication sharedApplication] applicationState];
if (state == UIApplicationStateBackground)
return;
glBindFramebuffer(GL_FRAMEBUFFER, _defaultFramebuffer);
if (_defaultColorBuffer)
{
glBindRenderbuffer(GL_RENDERBUFFER, _defaultColorBuffer);
if(! [_context renderbufferStorage:GL_RENDERBUFFER fromDrawable:(CAEAGLLayer *)self.layer])
{
NSLog(@"failed to call context");
return;
}
}
int backingWidth = 0;
int backingHeight = 0;
glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &backingWidth);
glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &backingHeight);
if (_defaultDepthBuffer)
{
glBindRenderbuffer(GL_RENDERBUFFER, _defaultDepthBuffer);
glRenderbufferStorage(GL_RENDERBUFFER, _depthFormat, backingWidth, backingHeight);
}
if (_multisampling)
{
glBindFramebuffer(GL_FRAMEBUFFER, _msaaFramebuffer);
if (_msaaColorBuffer)
{
glBindRenderbuffer(GL_RENDERBUFFER, _msaaColorBuffer);
glRenderbufferStorageMultisampleAPPLE(GL_RENDERBUFFER, _requestedSamples, _pixelformat, backingWidth, backingHeight);
}
if (_msaaDepthBuffer)
{
glBindRenderbuffer(GL_RENDERBUFFER, _msaaDepthBuffer);
glRenderbufferStorageMultisampleAPPLE(GL_RENDERBUFFER, _requestedSamples, _depthFormat, backingWidth, backingHeight);
}
}
else
{
glBindRenderbuffer(GL_RENDERBUFFER, _defaultColorBuffer);
}
CHECK_GL_ERROR();
GLenum error;
if( (error=glCheckFramebufferStatus(GL_FRAMEBUFFER)) != GL_FRAMEBUFFER_COMPLETE)
NSLog(@"Failed to make complete framebuffer object 0x%X", error);
_isReady = TRUE;
}
- (BOOL) isReady
{
return _isReady;
}
-(void) setPreventTouchEvent:(BOOL) flag
{
_needToPreventTouch = flag;
}
-(EAGLContext*) getContext
{
return _context;
}
- (void) setupGLContext
{
CAEAGLLayer *eaglLayer = (CAEAGLLayer *)self.layer;
eaglLayer.opaque = YES;
eaglLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:_preserveBackbuffer], kEAGLDrawablePropertyRetainedBacking,
_pixelformatString, kEAGLDrawablePropertyColorFormat, nil];
if(! _sharegroup)
{
_context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES3];
if (!_context)
_context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
}
else
{
_context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES3 sharegroup:_sharegroup];
if (!_context)
_context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2 sharegroup:_sharegroup];
}
if (!_context || ![EAGLContext setCurrentContext:_context] )
{
NSLog(@"Can not crate GL context.");
return;
}
if (![self createFrameBuffer])
return;
if (![self createAndAttachColorBuffer])
return;
[self createAndAttachDepthBuffer];
}
- (BOOL) createFrameBuffer
{
if (!_context)
return FALSE;
glGenFramebuffers(1, &_defaultFramebuffer);
if (0 == _defaultFramebuffer)
{
NSLog(@"Can not create default frame buffer.");
return FALSE;
}
if (_multisampling)
{
glGenFramebuffers(1, &_msaaFramebuffer);
if (0 == _msaaFramebuffer)
{
NSLog(@"Can not create multi sampling frame buffer");
_multisampling = FALSE;
}
}
return TRUE;
}
- (BOOL) createAndAttachColorBuffer
{
if (0 == _defaultFramebuffer)
return FALSE;
glBindFramebuffer(GL_FRAMEBUFFER, _defaultFramebuffer);
glGenRenderbuffers(1, &_defaultColorBuffer);
if (0 == _defaultColorBuffer)
{
NSLog(@"Can not create default color buffer.");
return FALSE;
}
glBindRenderbuffer(GL_RENDERBUFFER, _defaultColorBuffer);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, _defaultColorBuffer);
CHECK_GL_ERROR();
if (!_multisampling || (0 == _msaaFramebuffer))
return TRUE;
glBindFramebuffer(GL_FRAMEBUFFER, _msaaFramebuffer);
glGenRenderbuffers(1, &_msaaColorBuffer);
if (0 == _msaaColorBuffer)
{
NSLog(@"Can not create multi sampling color buffer.");
// App can work without multi sampleing.
return TRUE;
}
glBindRenderbuffer(GL_RENDERBUFFER, _msaaColorBuffer);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, _msaaColorBuffer);
CHECK_GL_ERROR();
return TRUE;
}
- (BOOL) createAndAttachDepthBuffer
{
if (0 == _defaultFramebuffer || 0 == _depthFormat)
return FALSE;
glBindFramebuffer(GL_FRAMEBUFFER, _defaultFramebuffer);
glGenRenderbuffers(1, &_defaultDepthBuffer);
if (0 == _defaultDepthBuffer)
{
NSLog(@"Can not create default depth buffer.");
return FALSE;
}
glBindRenderbuffer(GL_RENDERBUFFER, _defaultDepthBuffer);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, _defaultDepthBuffer);
CHECK_GL_ERROR();
if (GL_DEPTH24_STENCIL8_OES == _depthFormat ||
GL_DEPTH_STENCIL_OES == _depthFormat)
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, _defaultDepthBuffer);
CHECK_GL_ERROR();
if (!_multisampling || (0 == _msaaFramebuffer))
return TRUE;
glBindFramebuffer(GL_FRAMEBUFFER, _msaaFramebuffer);
glGenRenderbuffers(1, &_msaaDepthBuffer);
if (0 == _msaaDepthBuffer)
{
NSLog(@"Can not create multi sampling depth buffer.");
return TRUE;
}
glBindRenderbuffer(GL_RENDERBUFFER, _msaaDepthBuffer);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, _msaaDepthBuffer);
CHECK_GL_ERROR();
if (GL_DEPTH24_STENCIL8_OES == _depthFormat ||
GL_DEPTH_STENCIL_OES == _depthFormat)
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, _msaaDepthBuffer);
CHECK_GL_ERROR();
return TRUE;
}
- (void) swapBuffers
{
// IMPORTANT:
// - preconditions
// -> context_ MUST be the OpenGL context
// -> renderbuffer_ must be the RENDER BUFFER
if (_multisampling)
{
/* Resolve from msaaFramebuffer to resolveFramebuffer */
//glDisable(GL_SCISSOR_TEST);
glBindFramebuffer(GL_READ_FRAMEBUFFER_APPLE, _msaaFramebuffer);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER_APPLE, _defaultFramebuffer);
glResolveMultisampleFramebufferAPPLE();
}
CHECK_GL_ERROR();
if (_discardFramebufferSupported)
{
if (_multisampling)
{
if (_depthFormat)
{
GLenum attachments[] = {GL_COLOR_ATTACHMENT0, GL_DEPTH_ATTACHMENT};
glDiscardFramebufferEXT(GL_READ_FRAMEBUFFER_APPLE, 2, attachments);
}
else
{
GLenum attachments[] = {GL_COLOR_ATTACHMENT0};
glDiscardFramebufferEXT(GL_READ_FRAMEBUFFER_APPLE, 1, attachments);
}
}
else if (_depthFormat)
{
// not MSAA
GLenum attachments[] = { GL_DEPTH_ATTACHMENT};
glDiscardFramebufferEXT(GL_FRAMEBUFFER, 1, attachments);
}
CHECK_GL_ERROR();
}
glBindRenderbuffer(GL_RENDERBUFFER, _defaultColorBuffer);
if(![_context presentRenderbuffer:GL_RENDERBUFFER])
NSLog(@"cocos2d: Failed to swap renderbuffer in %s\n", __FUNCTION__);
#if COCOS2D_DEBUG
CHECK_GL_ERROR();
#endif
// We can safely re-bind the framebuffer here, since this will be the
// 1st instruction of the new main loop
if(_multisampling)
glBindFramebuffer(GL_FRAMEBUFFER, _msaaFramebuffer);
}
// Pass the touches to the superview
#pragma mark CCEAGLView - Touch Delegate
namespace
{
int getUnusedID(unsigned int& touchIDs)
{
int i;
unsigned int temp = touchIDs;
for (i = 0; i < 10; i++) {
if (! (temp & 0x00000001))
{
touchIDs |= (1 << i);
return i;
}
temp >>= 1;
}
// all bits are used
return -1;
}
void resetTouchID(unsigned int& touchIDs, int index)
{
touchIDs &= ((1 << index) ^ 0xffffffff);
}
cocos2d::TouchInfo createTouchInfo(int index, UITouch* touch, float contentScaleFactor)
{
uint8_t deviceRatio = cocos2d::Application::getInstance()->getDevicePixelRatio();
// TouchInfo should located in UI coordinate system, not GL pixels
// It will be converted to display position later in View.convertToLocationInView
cocos2d::TouchInfo touchInfo;
touchInfo.index = index;
touchInfo.x = [touch locationInView: [touch view]].x / deviceRatio;
touchInfo.y = [touch locationInView: [touch view]].y / deviceRatio;
return touchInfo;
}
void deliverTouch(cocos2d::TouchEvent& touchEvent,
NSSet* touches,
UITouch** internalTouches,
float contentScaleFactor,
bool reset,
unsigned int& touchIds)
{
for (UITouch *touch in touches)
{
for (int i = 0; i < MAX_TOUCH_COUNT; ++i)
{
if (touch == internalTouches[i])
{
if (reset)
{
internalTouches[i] = nil;
resetTouchID(touchIds, i);
}
touchEvent.touches.push_back(createTouchInfo(i, touch, contentScaleFactor));
}
}
}
if (!touchEvent.touches.empty())
cocos2d::EventDispatcher::dispatchTouchEvent(touchEvent);
}
}
@end