初始化

This commit is contained in:
SmallMain
2022-06-25 00:23:03 +08:00
commit ef0589e8e5
2264 changed files with 617829 additions and 0 deletions

View File

@@ -0,0 +1,533 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2017 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#import "CCApplication.h"
#import <UIKit/UIKit.h>
#include "base/CCScheduler.h"
#include "base/CCAutoreleasePool.h"
#include "base/CCGLUtils.h"
#include "base/CCConfiguration.h"
#include "renderer/gfx/DeviceGraphics.h"
#include "scripting/js-bindings/event/EventDispatcher.h"
#include "scripting/js-bindings/jswrapper/SeApi.h"
#include "CCEAGLView-ios.h"
#include "base/CCGLUtils.h"
#include "audio/include/AudioEngine.h"
#include "platform/CCDevice.h"
#include "cocos/renderer/gfx/DeviceGraphics.h"
namespace
{
bool setCanvasCallback(se::Object* global)
{
auto &viewSize = cocos2d::Application::getInstance()->getViewSize();
se::ScriptEngine* se = se::ScriptEngine::getInstance();
uint8_t devicePixelRatio = cocos2d::Application::getInstance()->getDevicePixelRatio();
int screenScale = cocos2d::Device::getDevicePixelRatio();
char commandBuf[200] = {0};
//set window.innerWidth/innerHeight in CSS pixel units, not physical pixel units.
sprintf(commandBuf, "window.innerWidth = %d; window.innerHeight = %d;",
(int)(viewSize.x / screenScale / devicePixelRatio),
(int)(viewSize.y / screenScale / devicePixelRatio));
se->evalString(commandBuf);
glDepthMask(GL_TRUE);
return true;
}
}
@interface MainLoop : NSObject
{
id _displayLink;
int _fps;
float _systemVersion;
BOOL _isAppActive;
cocos2d::Device::Rotation _lastRotation;
cocos2d::Application* _application;
std::shared_ptr<cocos2d::Scheduler> _scheduler;
}
-(void) startMainLoop;
-(void) stopMainLoop;
-(void) doCaller: (id) sender;
-(void) setPreferredFPS:(int)fps;
-(void) firstStart:(id) view;
@end
@implementation MainLoop
- (instancetype)initWithApplication:(cocos2d::Application*) application
{
self = [super init];
if (self)
{
_fps = 60;
_systemVersion = [[UIDevice currentDevice].systemVersion floatValue];
_application = application;
_scheduler = _application->getScheduler();
_lastRotation = cocos2d::Device::getDeviceRotation();
_isAppActive = [UIApplication sharedApplication].applicationState == UIApplicationStateActive;
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self selector:@selector(appDidBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil];
[nc addObserver:self selector:@selector(appDidBecomeInactive) name:UIApplicationWillResignActiveNotification object:nil];
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[nc addObserver:self selector:@selector(statusBarOrientationChanged:)name:UIApplicationDidChangeStatusBarOrientationNotification
object:nil];
}
return self;
}
- (void) statusBarOrientationChanged:(NSNotification *)note
{
cocos2d::Device::Rotation rotation = cocos2d::Device::Rotation::_0;
UIDevice * device = [UIDevice currentDevice];
// NOTE: https://developer.apple.com/documentation/uikit/uideviceorientation
// when the device rotates to LandscapeLeft, device.orientation returns UIDeviceOrientationLandscapeRight
// when the device rotates to LandscapeRight, device.orientation returns UIDeviceOrientationLandscapeLeft
switch(device.orientation)
{
case UIDeviceOrientationPortrait:
rotation = cocos2d::Device::Rotation::_0;
break;
case UIDeviceOrientationLandscapeLeft:
rotation = cocos2d::Device::Rotation::_90;
break;
case UIDeviceOrientationPortraitUpsideDown:
rotation = cocos2d::Device::Rotation::_180;
break;
case UIDeviceOrientationLandscapeRight:
rotation = cocos2d::Device::Rotation::_270;
break;
default:
break;
};
if(_lastRotation != rotation){
cocos2d::EventDispatcher::dispatchOrientationChangeEvent((int) rotation);
_lastRotation = rotation;
}
CGRect bounds = [UIScreen mainScreen].bounds;
float scale = [[UIScreen mainScreen] scale];
float width = bounds.size.width * scale;
float height = bounds.size.height * scale;
cocos2d::Application::getInstance()->updateViewSize(width, height);
}
-(void) dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
[_displayLink release];
[super dealloc];
}
- (void)appDidBecomeActive
{
_isAppActive = YES;
}
- (void)appDidBecomeInactive
{
_isAppActive = NO;
}
-(void) firstStart:(id) view
{
if ([view isReady])
{
auto scheduler = _application->getScheduler();
scheduler->removeAllFunctionsToBePerformedInCocosThread();
scheduler->unscheduleAll();
se::ScriptEngine::getInstance()->cleanup();
cocos2d::PoolManager::getInstance()->getCurrentPool()->clear();
cocos2d::EventDispatcher::init();
cocos2d::ccInvalidateStateCache();
se::ScriptEngine* se = se::ScriptEngine::getInstance();
se->addRegisterCallback(setCanvasCallback);
if(!_application->applicationDidFinishLaunching())
return;
[self startMainLoop];
}
else
// Replace performSelector usage for Apple review policy
// https://github.com/cocos-creator/3d-tasks/issues/9770
// [self performSelector:@selector(firstStart:) withObject:view afterDelay:0];
dispatch_async(dispatch_get_main_queue(), ^{
[self firstStart:view];
});
}
-(void) startMainLoop
{
[self stopMainLoop];
_displayLink = [NSClassFromString(@"CADisplayLink") displayLinkWithTarget:self selector:@selector(doCaller:)];
if (_systemVersion >= 10.0f)
[_displayLink setPreferredFramesPerSecond: _fps];
else
[_displayLink setFrameInterval: 60 / _fps];
[_displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
}
-(void) stopMainLoop
{
if (_displayLink != nil)
{
[_displayLink invalidate];
_displayLink = nil;
}
}
-(void) setPreferredFPS:(int)fps
{
_fps = fps;
[self startMainLoop];
}
-(void) doCaller: (id) sender
{
static std::chrono::steady_clock::time_point prevTime;
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
NS_CC_BEGIN
Application* Application::_instance = nullptr;
std::shared_ptr<Scheduler> Application::_scheduler = nullptr;
Application::Application(const std::string& name, int width, int height)
{
Application::_instance = this;
_scheduler = std::make_shared<Scheduler>();
createView(name, width, height);
Configuration::getInstance();
glGetIntegerv(GL_FRAMEBUFFER_BINDING, &_mainFBO);
_renderTexture = new RenderTexture(width, height);
se::ScriptEngine::getInstance();
EventDispatcher::init();
_delegate = [[MainLoop alloc] initWithApplication:this];
updateViewSize(width, height);
}
Application::~Application()
{
#if USE_AUDIO
AudioEngine::end();
#endif
EventDispatcher::destroy();
se::ScriptEngine::destroyInstance();
// stop main loop
[(MainLoop*)_delegate stopMainLoop];
[(MainLoop*)_delegate release];
_delegate = nullptr;
[(CCEAGLView*)_view release];
_view = nullptr;
delete _renderTexture;
_renderTexture = nullptr;
Application::_instance = nullptr;
}
const cocos2d::Vec2& Application::getViewSize() const
{
return _viewSize;
}
void Application::updateViewSize(int width, int height)
{
_viewSize.x = width;
_viewSize.y = height;
cocos2d::EventDispatcher::dispatchResizeEvent(width, height);
}
void Application::start()
{
if (_delegate)
// Replace performSelector usage for Apple review policy
// https://github.com/cocos-creator/3d-tasks/issues/9770
// [(MainLoop*)_delegate performSelector:@selector(firstStart:) withObject:(CCEAGLView*)_view afterDelay:0];
dispatch_async(dispatch_get_main_queue(), ^{
[(MainLoop*)_delegate firstStart:(CCEAGLView*)_view];
});
}
void Application::restart()
{
if (_delegate) {
[(MainLoop*)_delegate stopMainLoop];
// Replace performSelector usage for Apple review policy
// https://github.com/cocos-creator/3d-tasks/issues/9770
// [(MainLoop*)_delegate performSelector:@selector(firstStart:) withObject:(CCEAGLView*)_view afterDelay:0];
dispatch_async(dispatch_get_main_queue(), ^{
[(MainLoop*)_delegate firstStart:(CCEAGLView*)_view];
});
}
}
void Application::end()
{
delete this;
exit(0);
}
void Application::setPreferredFramesPerSecond(int fps)
{
[(MainLoop*)_delegate setPreferredFPS: fps];
}
std::string Application::getCurrentLanguageCode() const
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSArray *languages = [defaults objectForKey:@"AppleLanguages"];
NSString *currentLanguage = [languages objectAtIndex:0];
return [currentLanguage UTF8String];
}
bool Application::isDisplayStats() {
se::AutoHandleScope hs;
se::Value ret;
char commandBuf[100] = "cc.debug.isDisplayStats();";
se::ScriptEngine::getInstance()->evalString(commandBuf, 100, &ret);
return ret.toBoolean();
}
void Application::setDisplayStats(bool isShow) {
se::AutoHandleScope hs;
char commandBuf[100] = {0};
sprintf(commandBuf, "cc.debug.setDisplayStats(%s);", isShow ? "true" : "false");
se::ScriptEngine::getInstance()->evalString(commandBuf);
}
Application::LanguageType Application::getCurrentLanguage() const
{
// get the current language and country config
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSArray *languages = [defaults objectForKey:@"AppleLanguages"];
NSString *currentLanguage = [languages objectAtIndex:0];
// get the current language code.(such as English is "en", Chinese is "zh" and so on)
NSDictionary* temp = [NSLocale componentsFromLocaleIdentifier:currentLanguage];
NSString * languageCode = [temp objectForKey:NSLocaleLanguageCode];
if ([languageCode isEqualToString:@"zh"]) return LanguageType::CHINESE;
if ([languageCode isEqualToString:@"en"]) return LanguageType::ENGLISH;
if ([languageCode isEqualToString:@"fr"]) return LanguageType::FRENCH;
if ([languageCode isEqualToString:@"it"]) return LanguageType::ITALIAN;
if ([languageCode isEqualToString:@"de"]) return LanguageType::GERMAN;
if ([languageCode isEqualToString:@"es"]) return LanguageType::SPANISH;
if ([languageCode isEqualToString:@"nl"]) return LanguageType::DUTCH;
if ([languageCode isEqualToString:@"ru"]) return LanguageType::RUSSIAN;
if ([languageCode isEqualToString:@"ko"]) return LanguageType::KOREAN;
if ([languageCode isEqualToString:@"ja"]) return LanguageType::JAPANESE;
if ([languageCode isEqualToString:@"hu"]) return LanguageType::HUNGARIAN;
if ([languageCode isEqualToString:@"pt"]) return LanguageType::PORTUGUESE;
if ([languageCode isEqualToString:@"ar"]) return LanguageType::ARABIC;
if ([languageCode isEqualToString:@"nb"]) return LanguageType::NORWEGIAN;
if ([languageCode isEqualToString:@"pl"]) return LanguageType::POLISH;
if ([languageCode isEqualToString:@"tr"]) return LanguageType::TURKISH;
if ([languageCode isEqualToString:@"uk"]) return LanguageType::UKRAINIAN;
if ([languageCode isEqualToString:@"ro"]) return LanguageType::ROMANIAN;
if ([languageCode isEqualToString:@"bg"]) return LanguageType::BULGARIAN;
return LanguageType::ENGLISH;
}
Application::Platform Application::getPlatform() const
{
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) // idiom for iOS <= 3.2, otherwise: [UIDevice userInterfaceIdiom] is faster.
return Platform::IPAD;
else
return Platform::IPHONE;
}
float Application::getScreenScale() const
{
return [(UIView*)_view contentScaleFactor];
}
GLint Application::getMainFBO() const
{
return _mainFBO;
}
bool Application::openURL(const std::string &url)
{
NSString* msg = [NSString stringWithCString:url.c_str() encoding:NSUTF8StringEncoding];
NSURL* nsUrl = [NSURL URLWithString:msg];
return [[UIApplication sharedApplication] openURL:nsUrl];
}
void Application::copyTextToClipboard(const std::string &text)
{
UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
pasteboard.string = [NSString stringWithCString:text.c_str() encoding:NSUTF8StringEncoding];
}
bool Application::applicationDidFinishLaunching()
{
return true;
}
void Application::onPause()
{
}
void Application::onResume()
{
}
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)
{
pixelformat = PixelFormat::RGB565;
depthFormat = DepthFormat::DEPTH24_STENCIL8;
multisamplingCount = 0;
}
namespace
{
GLenum depthFormatMap[] =
{
0, // NONE: no depth and no stencil
GL_DEPTH_COMPONENT24_OES, // DEPTH_COMPONENT16: unsupport, convert to GL_DEPTH_COMPONENT24_OES
GL_DEPTH_COMPONENT24_OES, // DEPTH_COMPONENT24
GL_DEPTH_COMPONENT24_OES, // DEPTH_COMPONENT32F: unsupport, convert to GL_DEPTH_COMPONENT24_OES
GL_DEPTH24_STENCIL8_OES, // DEPTH24_STENCIL8
GL_DEPTH24_STENCIL8_OES, // DEPTH32F_STENCIL8: unsupport, convert to GL_DEPTH24_STENCIL8_OES
GL_DEPTH_STENCIL_OES // STENCIL_INDEX8
};
GLenum depthFormat2GLDepthFormat(cocos2d::Application::DepthFormat depthFormat)
{
return depthFormatMap[(int)depthFormat];
}
}
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()
{
NSString* systemVersion = [UIDevice currentDevice].systemVersion;
return [systemVersion UTF8String];
}
NS_CC_END

View File

@@ -0,0 +1,317 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "CCApplication.h"
#include "platform/CCDevice.h"
#include "platform/ios/CCEAGLView-ios.h"
// Vibrate
#import <AudioToolbox/AudioToolbox.h>
#include "base/ccTypes.h"
#include "platform/apple/CCDevice-apple.h"
#include "CCReachability.h"
#import <UIKit/UIKit.h>
// Accelerometer
#import <CoreMotion/CoreMotion.h>
#include <CoreFoundation/CoreFoundation.h>
#include <CoreText/CoreText.h>
#include <sys/utsname.h>
static const float g = 9.80665;
static const float radToDeg = (180/M_PI);
@interface CCMotionDispatcher : NSObject<UIAccelerometerDelegate>
{
CMMotionManager* _motionManager;
cocos2d::Device::MotionValue _motionValue;
float _interval; // unit: seconds
bool _enabled;
}
+ (id) sharedMotionDispatcher;
- (id) init;
- (void) setMotionEnabled: (bool) isEnabled;
- (void) setMotionInterval:(float) interval;
@end
@implementation CCMotionDispatcher
static CCMotionDispatcher* __motionDispatcher = nullptr;
+ (id) sharedMotionDispatcher
{
if (__motionDispatcher == nil) {
__motionDispatcher = [[CCMotionDispatcher alloc] init];
}
return __motionDispatcher;
}
- (id) init
{
if( (self = [super init]) ) {
_enabled = false;
_interval = 1.0f / 60.0f;
_motionManager = [[CMMotionManager alloc] init];
}
return self;
}
- (void) dealloc
{
__motionDispatcher = nullptr;
[_motionManager release];
[super dealloc];
}
- (void) setMotionEnabled: (bool) enabled
{
if (_enabled == enabled)
return;
bool isDeviceMotionAvailable = _motionManager.isDeviceMotionAvailable;
if (enabled)
{
// Has Gyro? (iPhone4 and newer)
if (isDeviceMotionAvailable) {
[_motionManager startDeviceMotionUpdates];
_motionManager.deviceMotionUpdateInterval = _interval;
}
// Only basic accelerometer data
else {
[_motionManager startAccelerometerUpdates];
_motionManager.accelerometerUpdateInterval = _interval;
}
}
else
{
// Has Gyro? (iPhone4 and newer)
if (isDeviceMotionAvailable) {
[_motionManager stopDeviceMotionUpdates];
}
// Only basic accelerometer data
else {
[_motionManager stopAccelerometerUpdates];
}
}
_enabled = enabled;
}
-(void) setMotionInterval:(float)interval
{
_interval = interval;
if (_enabled)
{
if (_motionManager.isDeviceMotionAvailable) {
_motionManager.deviceMotionUpdateInterval = _interval;
}
else {
_motionManager.accelerometerUpdateInterval = _interval;
}
}
}
-(const cocos2d::Device::MotionValue&) getMotionValue {
if (_motionManager.isDeviceMotionAvailable) {
CMDeviceMotion* motion = _motionManager.deviceMotion;
_motionValue.accelerationX = motion.userAcceleration.x * g;
_motionValue.accelerationY = motion.userAcceleration.y * g;
_motionValue.accelerationZ = motion.userAcceleration.z * g;
_motionValue.accelerationIncludingGravityX = (motion.userAcceleration.x + motion.gravity.x) * g;
_motionValue.accelerationIncludingGravityY = (motion.userAcceleration.y + motion.gravity.y) * g;
_motionValue.accelerationIncludingGravityZ = (motion.userAcceleration.z + motion.gravity.z) * g;
_motionValue.rotationRateAlpha = motion.rotationRate.x * radToDeg;
_motionValue.rotationRateBeta = motion.rotationRate.y * radToDeg;
_motionValue.rotationRateGamma = motion.rotationRate.z * radToDeg;
}
else {
CMAccelerometerData* acc = _motionManager.accelerometerData;
_motionValue.accelerationIncludingGravityX = acc.acceleration.x * g;
_motionValue.accelerationIncludingGravityY = acc.acceleration.y * g;
_motionValue.accelerationIncludingGravityZ = acc.acceleration.z * g;
}
return _motionValue;
}
@end
//
NS_CC_BEGIN
int Device::getDPI()
{
static int dpi = -1;
if (dpi == -1)
{
float scale = scale = [[UIScreen mainScreen] scale];
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
dpi = 132 * scale;
} else if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
dpi = 163 * scale;
} else {
dpi = 160 * scale;
}
}
return dpi;
}
void Device::setAccelerometerEnabled(bool isEnabled)
{
#if !defined(CC_TARGET_OS_TVOS)
[[CCMotionDispatcher sharedMotionDispatcher] setMotionEnabled:isEnabled];
#endif
}
void Device::setAccelerometerInterval(float interval)
{
#if !defined(CC_TARGET_OS_TVOS)
[[CCMotionDispatcher sharedMotionDispatcher] setMotionInterval:interval];
#endif
}
const Device::MotionValue& Device::getDeviceMotionValue()
{
#if !defined(CC_TARGET_OS_TVOS)
return [[CCMotionDispatcher sharedMotionDispatcher] getMotionValue];
#else
static Device::MotionValue ret;
return ret;
#endif
}
Device::Rotation Device::getDeviceRotation()
{
Rotation ret = Device::Rotation::_0;
switch ([[UIApplication sharedApplication] statusBarOrientation])
{
case UIInterfaceOrientationLandscapeRight:
ret = Device::Rotation::_90;
break;
case UIInterfaceOrientationLandscapeLeft:
ret = Device::Rotation::_270;
break;
case UIInterfaceOrientationPortraitUpsideDown:
ret = Device::Rotation::_180;
break;
case UIInterfaceOrientationPortrait:
ret = Device::Rotation::_0;
break;
default:
assert(false);
break;
}
return ret;
}
std::string Device::getDeviceModel()
{
struct utsname systemInfo;
uname(&systemInfo);
return systemInfo.machine;
}
void Device::setKeepScreenOn(bool value)
{
[[UIApplication sharedApplication] setIdleTimerDisabled:(BOOL)value];
}
/*!
@brief Only works on iOS devices that support vibration (such as iPhone). Should only be used for important alerts. Use risks rejection in iTunes Store.
@param duration ignored for iOS
*/
void Device::vibrate(float duration)
{
// See https://developer.apple.com/library/ios/documentation/AudioToolbox/Reference/SystemSoundServicesReference/index.html#//apple_ref/c/econst/kSystemSoundID_Vibrate
CC_UNUSED_PARAM(duration);
// automatically vibrates for approximately 0.4 seconds
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
}
float Device::getBatteryLevel()
{
return [UIDevice currentDevice].batteryLevel;
}
Device::NetworkType Device::getNetworkType()
{
static Reachability* __reachability = nullptr;
if (__reachability == nullptr)
{
__reachability = Reachability::createForInternetConnection();
__reachability->retain();
}
NetworkType ret = NetworkType::NONE;
Reachability::NetworkStatus status = __reachability->getCurrentReachabilityStatus();
switch (status) {
case Reachability::NetworkStatus::REACHABLE_VIA_WIFI:
ret = NetworkType::LAN;
break;
case Reachability::NetworkStatus::REACHABLE_VIA_WWAN:
ret = NetworkType::WWAN;
break;
default:
ret = NetworkType::NONE;
break;
}
return ret;
}
cocos2d::Vec4 Device::getSafeAreaEdge()
{
UIView* screenView = (UIView*)Application::getInstance()->getView();
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000
float version = [[UIDevice currentDevice].systemVersion floatValue];
if (version >= 11.0f)
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpartial-availability"
UIEdgeInsets safeAreaEdge = screenView.safeAreaInsets;
#pragma clang diagnostic pop
return cocos2d::Vec4(safeAreaEdge.top, safeAreaEdge.left, safeAreaEdge.bottom, safeAreaEdge.right);
}
#endif
// If running on iOS devices lower than 11.0, return ZERO Vec4.
return cocos2d::Vec4();
}
NS_CC_END

View File

@@ -0,0 +1,121 @@
/*
===== 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

@@ -0,0 +1,577 @@
/*
===== 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"
#include "ui/edit-box/EditBox.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
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);
}
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
// When editbox is editing, should prevent glview to handle touch events.
if (_needToPreventTouch)
{
cocos2d::EditBox::complete();
return;
}
cocos2d::TouchEvent touchEvent;
touchEvent.type = cocos2d::TouchEvent::Type::BEGAN;
for (UITouch *touch in touches) {
int index = getUnusedID(_touchIds);
if (-1 == index)
return;
_touches[index] = touch;
touchEvent.touches.push_back(createTouchInfo(index, touch, self.contentScaleFactor));
}
if (!touchEvent.touches.empty())
cocos2d::EventDispatcher::dispatchTouchEvent(touchEvent);
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
cocos2d::TouchEvent touchEvent;
touchEvent.type = cocos2d::TouchEvent::Type::MOVED;
deliverTouch(touchEvent, touches, _touches, self.contentScaleFactor, false, _touchIds);
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
cocos2d::TouchEvent touchEvent;
touchEvent.type = cocos2d::TouchEvent::Type::ENDED;
deliverTouch(touchEvent, touches, _touches, self.contentScaleFactor, true, _touchIds);
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
cocos2d::TouchEvent touchEvent;
touchEvent.type = cocos2d::TouchEvent::Type::CANCELLED;
deliverTouch(touchEvent, touches, _touches, self.contentScaleFactor, true, _touchIds);
}
@end

View File

@@ -0,0 +1,49 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#pragma once
#include "platform/CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
#include <OpenGLES/ES2/gl.h>
#include <OpenGLES/ES2/glext.h>
#define glClearDepth glClearDepthf
#define glDepthRange glDepthRangef
//#define glDeleteVertexArrays glDeleteVertexArraysOES
#define glGenVertexArrays glGenVertexArraysOES
#define glBindVertexArray glBindVertexArrayOES
//#define glMapBuffer glMapBufferOES
//#define glUnmapBuffer glUnmapBufferOES
//
#define GL_DEPTH24_STENCIL8 GL_DEPTH24_STENCIL8_OES
//#define GL_DEPTH_STENCIL GL_DEPTH_STENCIL_OES
//#define GL_WRITE_ONLY GL_WRITE_ONLY_OES
//#define GL_MAX_SAMPLES_APPLE GL_MAX_SAMPLES
#endif // CC_PLATFORM_IOS

View File

@@ -0,0 +1,127 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "platform/CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
#import "platform/CCImage.h"
#import <string>
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#include <math.h>
NS_CC_BEGIN
bool cocos2d::Image::saveToFile(const std::string& filename, bool isToRGB)
{
bool saveToPNG = false;
bool needToCopyPixels = false;
std::string basename(filename);
std::transform(basename.begin(), basename.end(), basename.begin(), ::tolower);
if (std::string::npos != basename.find(".png"))
{
saveToPNG = true;
}
int bitsPerComponent = 8;
int bitsPerPixel = hasAlpha() ? 32 : 24;
if ((! saveToPNG) || isToRGB)
{
bitsPerPixel = 24;
}
int bytesPerRow = (bitsPerPixel/8) * _width;
int myDataLength = bytesPerRow * _height;
unsigned char *pixels = _data;
// The data has alpha channel, and want to save it with an RGB png file,
// or want to save as jpg, remove the alpha channel.
if (hasAlpha() && bitsPerPixel == 24)
{
pixels = new (std::nothrow) unsigned char[myDataLength];
for (int i = 0; i < _height; ++i)
{
for (int j = 0; j < _width; ++j)
{
pixels[(i * _width + j) * 3] = _data[(i * _width + j) * 4];
pixels[(i * _width + j) * 3 + 1] = _data[(i * _width + j) * 4 + 1];
pixels[(i * _width + j) * 3 + 2] = _data[(i * _width + j) * 4 + 2];
}
}
needToCopyPixels = true;
}
// make data provider with data.
CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault;
if (saveToPNG && hasAlpha() && (! isToRGB))
{
bitmapInfo |= kCGImageAlphaPremultipliedLast;
}
CGDataProviderRef provider = CGDataProviderCreateWithData(nullptr, pixels, myDataLength, nullptr);
CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
CGImageRef iref = CGImageCreate(_width, _height,
bitsPerComponent, bitsPerPixel, bytesPerRow,
colorSpaceRef, bitmapInfo, provider,
nullptr, false,
kCGRenderingIntentDefault);
UIImage* image = [[UIImage alloc] initWithCGImage:iref];
CGImageRelease(iref);
CGColorSpaceRelease(colorSpaceRef);
CGDataProviderRelease(provider);
// NOTE: Prevent memory leak. Requires ARC enabled.
@autoreleasepool {
NSData *data;
if (saveToPNG) {
data = UIImagePNGRepresentation(image);
} else {
data = UIImageJPEGRepresentation(image, 1.0f);
}
[data writeToFile:[NSString stringWithUTF8String:filename.c_str()] atomically:YES];
}
[image release];
if (needToCopyPixels)
{
delete [] pixels;
}
return true;
}
NS_CC_END
#endif // CC_PLATFORM_IOS

View File

@@ -0,0 +1,6 @@
// Configuration settings file format documentation can be found at:
// https://help.apple.com/xcode/#/dev745c5c974
// Module setting for engine
GCC_PREPROCESSOR_DEFINITIONS = $(inherited) USE_SOCKET=1 USE_DRAGONBONES=1 USE_SPINE=1 USE_AUDIO=1 USE_EDIT_BOX=1 USE_WEB_VIEW=1 USE_VIDEO=1

View File

@@ -0,0 +1,6 @@
// Configuration settings file format documentation can be found at:
// https://help.apple.com/xcode/#/dev745c5c974
// Module setting for engine
GCC_PREPROCESSOR_DEFINITIONS = $(inherited) USE_SOCKET=1 USE_DRAGONBONES=1 USE_SPINE=1 USE_AUDIO=1 USE_EDIT_BOX=1 USE_WEB_VIEW=1 USE_VIDEO=1

View File

@@ -0,0 +1,54 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __CCPLATFORMDEFINE_H__
#define __CCPLATFORMDEFINE_H__
#include "platform/CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
#include <assert.h>
#define CC_DLL
#define CC_ASSERT(cond) assert(cond)
#define CC_UNUSED_PARAM(unusedparam) (void)unusedparam
/* Define NULL pointer value */
#ifndef NULL
#ifdef __cplusplus
#define NULL 0
#else
#define NULL ((void *)0)
#endif
#endif
#endif // CC_PLATFORM_IOS
#endif /* __CCPLATFORMDEFINE_H__*/

View File

@@ -0,0 +1,246 @@
/****************************************************************************
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "CCReachability.h"
#include "base/ccMacros.h"
#include <SystemConfiguration/SystemConfiguration.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <ifaddrs.h>
#include <netdb.h>
#include <sys/socket.h>
namespace {
#define ShouldPrintReachabilityFlags 0
static void PrintReachabilityFlags(SCNetworkReachabilityFlags flags, const char* comment)
{
#if ShouldPrintReachabilityFlags
printf("Reachability Flag Status: %c%c %c%c%c%c%c%c%c %s\n",
#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
(flags & kSCNetworkReachabilityFlagsIsWWAN) ? 'W' : '-',
#else
'-',
#endif
(flags & kSCNetworkReachabilityFlagsReachable) ? 'R' : '-',
(flags & kSCNetworkReachabilityFlagsTransientConnection) ? 't' : '-',
(flags & kSCNetworkReachabilityFlagsConnectionRequired) ? 'c' : '-',
(flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) ? 'C' : '-',
(flags & kSCNetworkReachabilityFlagsInterventionRequired) ? 'i' : '-',
(flags & kSCNetworkReachabilityFlagsConnectionOnDemand) ? 'D' : '-',
(flags & kSCNetworkReachabilityFlagsIsLocalAddress) ? 'l' : '-',
(flags & kSCNetworkReachabilityFlagsIsDirect) ? 'd' : '-',
comment
);
#endif
}
cocos2d::Reachability::NetworkStatus getNetworkStatusForFlags(SCNetworkReachabilityFlags flags)
{
PrintReachabilityFlags(flags, "networkStatusForFlags");
if ((flags & kSCNetworkReachabilityFlagsReachable) == 0)
{
// The target host is not reachable.
return cocos2d::Reachability::NetworkStatus::NOT_REACHABLE;
}
cocos2d::Reachability::NetworkStatus returnValue = cocos2d::Reachability::NetworkStatus::NOT_REACHABLE;
if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0)
{
/*
If the target host is reachable and no connection is required then we'll assume (for now) that you're on Wi-Fi...
*/
returnValue = cocos2d::Reachability::NetworkStatus::REACHABLE_VIA_WIFI;
}
if ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) ||
(flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0))
{
/*
... and the connection is on-demand (or on-traffic) if the calling application is using the CFSocketStream or higher APIs...
*/
if ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0)
{
/*
... and no [user] intervention is needed...
*/
returnValue = cocos2d::Reachability::NetworkStatus::REACHABLE_VIA_WIFI;
}
}
#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN)
{
/*
... but WWAN connections are OK if the calling application is using the CFNetwork APIs.
*/
returnValue = cocos2d::Reachability::NetworkStatus::REACHABLE_VIA_WWAN;
}
#endif
return returnValue;
}
}
NS_CC_BEGIN
Reachability* Reachability::createWithHostName(const std::string& hostName)
{
Reachability* returnValue = nullptr;
SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(nullptr, hostName.c_str());
if (reachability != nullptr)
{
returnValue = new (std::nothrow) Reachability();
if (returnValue != nullptr)
{
returnValue->autorelease();
returnValue->_reachabilityRef = reachability;
}
else {
CFRelease(reachability);
}
}
return returnValue;
}
Reachability* Reachability::createWithAddress(const struct sockaddr* hostAddress)
{
SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, hostAddress);
Reachability* returnValue = nullptr;
if (reachability != nullptr)
{
returnValue = new (std::nothrow) Reachability();
if (returnValue != nullptr)
{
returnValue->autorelease();
returnValue->_reachabilityRef = reachability;
}
else {
CFRelease(reachability);
}
}
return returnValue;
}
Reachability* Reachability::createForInternetConnection()
{
struct sockaddr_in zeroAddress;
bzero(&zeroAddress, sizeof(zeroAddress));
zeroAddress.sin_len = sizeof(zeroAddress);
zeroAddress.sin_family = AF_INET;
return createWithAddress((const struct sockaddr*) &zeroAddress);
}
Reachability::Reachability()
: _callback(nullptr)
, _userData(nullptr)
, _reachabilityRef(nullptr)
{
}
Reachability::~Reachability()
{
stopNotifier();
if (_reachabilityRef != nullptr)
{
CFRelease(_reachabilityRef);
}
}
void Reachability::onReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void* info)
{
CCASSERT(info != nullptr, "info was nullptr in onReachabilityCallback");
cocos2d::Reachability* thiz = reinterpret_cast<cocos2d::Reachability*>(info);
if (thiz->_callback != nullptr)
{
NetworkStatus status = getNetworkStatusForFlags(flags);
thiz->_callback(thiz, status, thiz->_userData);
}
}
bool Reachability::startNotifier(const ReachabilityCallback& cb, void* userData)
{
_callback = cb;
_userData = userData;
bool returnValue = false;
SCNetworkReachabilityContext context = {0, this, nullptr, nullptr, nullptr};
if (SCNetworkReachabilitySetCallback(_reachabilityRef, onReachabilityCallback, &context))
{
if (SCNetworkReachabilityScheduleWithRunLoop(_reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode))
{
returnValue = true;
}
}
return returnValue;
}
void Reachability::stopNotifier()
{
if (_reachabilityRef != nullptr)
{
SCNetworkReachabilityUnscheduleFromRunLoop(_reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
}
}
bool Reachability::isConnectionRequired() const
{
CCASSERT(_reachabilityRef != nullptr, "connectionRequired called with nullptr reachabilityRef");
SCNetworkReachabilityFlags flags;
if (SCNetworkReachabilityGetFlags(_reachabilityRef, &flags))
{
return (flags & kSCNetworkReachabilityFlagsConnectionRequired);
}
return false;
}
Reachability::NetworkStatus Reachability::getCurrentReachabilityStatus() const
{
CCASSERT(_reachabilityRef != nullptr, "currentNetworkStatus called with nullptr SCNetworkReachabilityRef");
NetworkStatus returnValue = NetworkStatus::NOT_REACHABLE;
SCNetworkReachabilityFlags flags;
if (SCNetworkReachabilityGetFlags(_reachabilityRef, &flags))
{
returnValue = getNetworkStatusForFlags(flags);
}
return returnValue;
}
NS_CC_END

View File

@@ -0,0 +1,89 @@
/****************************************************************************
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#pragma once
#include "base/CCRef.h"
#include <string>
#include <functional>
#include <SystemConfiguration/SystemConfiguration.h>
struct sockaddr;
NS_CC_BEGIN
class Reachability final : public Ref
{
public:
enum class NetworkStatus : uint8_t
{
NOT_REACHABLE,
REACHABLE_VIA_WIFI,
REACHABLE_VIA_WWAN
};
/*!
* Use to check the reachability of a given host name.
*/
static Reachability* createWithHostName(const std::string& hostName);
/*!
* Use to check the reachability of a given IP address.
*/
static Reachability* createWithAddress(const struct sockaddr* hostAddress);
/*!
* Checks whether the default route is available. Should be used by applications that do not connect to a particular host.
*/
static Reachability* createForInternetConnection();
using ReachabilityCallback = std::function<void(Reachability*, NetworkStatus, void*)>;
/*!
* Start listening for reachability notifications on the current run loop.
*/
bool startNotifier(const ReachabilityCallback& cb, void* userData);
void stopNotifier();
NetworkStatus getCurrentReachabilityStatus()const;
/*!
* WWAN may be available, but not active until a connection has been established. WiFi may require a connection for VPN on Demand.
*/
bool isConnectionRequired() const;
private:
Reachability();
~Reachability();
static void onReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void* info);
ReachabilityCallback _callback;
void* _userData;
SCNetworkReachabilityRef _reachabilityRef;
};
NS_CC_END

View File

@@ -0,0 +1,89 @@
/*
===== 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: OpenGL_Internal.h
Abstract: This file is included for support purposes and isn't necessary for
understanding this sample.
Version: 1.0
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.
*/
#include "platform/CCPlatformConfig.h"
#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
/* Generic error reporting */
#define REPORT_ERROR(__FORMAT__, ...) printf("%s: %s\n", __FUNCTION__, [[NSString stringWithFormat:__FORMAT__, __VA_ARGS__] UTF8String])
/* EAGL and GL functions calling wrappers that log on error */
#define CALL_EAGL_FUNCTION(__FUNC__, ...) ({ EAGLError __error = __FUNC__( __VA_ARGS__ ); if(__error != kEAGLErrorSuccess) printf("%s() called from %s returned error %i\n", #__FUNC__, __FUNCTION__, __error); (__error ? NO : YES); })
//#define CHECK_GL_ERROR() ({ GLenum __error = glGetError(); if(__error) printf("OpenGL error 0x%04X in %s\n", __error, __FUNCTION__); (__error ? NO : YES); })
#define CHECK_GL_ERROR() ({ GLenum __error = glGetError(); if(__error) printf("OpenGL error 0x%04X in %s %d\n", __error, __FUNCTION__, __LINE__); })
/* Optional delegate methods support */
#ifndef __DELEGATE_IVAR__
#define __DELEGATE_IVAR__ _delegate
#endif
#ifndef __DELEGATE_METHODS_IVAR__
#define __DELEGATE_METHODS_IVAR__ _delegateMethods
#endif
#define TEST_DELEGATE_METHOD_BIT(__BIT__) (self->__DELEGATE_METHODS_IVAR__ & (1 << __BIT__))
/* Comment out for Apple review policy */
// https://github.com/cocos-creator/3d-tasks/issues/9770
// #define SET_DELEGATE_METHOD_BIT(__BIT__, __NAME__) { if([self->__DELEGATE_IVAR__ respondsToSelector:@selector(__NAME__)]) self->__DELEGATE_METHODS_IVAR__ |= (1 << __BIT__); else self->__DELEGATE_METHODS_IVAR__ &= ~(1 << __BIT__); }
#endif // CC_PLATFORM_IOS

View File

@@ -0,0 +1,39 @@
//
// Prefix header for all source files of the 'cocos2dx' target in the 'cocos2dx' project
//
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <float.h>
#include <math.h>
#include <stdio.h>
#include <time.h>
#include <stdint.h>
#include <assert.h>
#include <sys/time.h>
#include <sys/select.h>
#include <OpenGLES/ES2/gl.h>
#include <OpenGLES/ES2/glext.h>
#ifdef __OBJC__
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#endif
#ifdef __cplusplus
#include <vector>
#include <string>
#include <map>
#include <list>
#include <memory>
#include <functional>
#include <thread>
#include <mutex>
#include <unordered_map>
#include <list>
#include <algorithm>
#include <cstdint>
#include <stack>
#endif