2014-01-07 11:25:07 +08:00
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2014 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.
****************************************************************************/
2014-01-28 08:44:10 +08:00
2014-04-27 01:35:57 +08:00
#include "base/CCPlatformConfig.h"
2014-01-28 08:44:10 +08:00
#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
2013-02-16 19:36:21 +08:00
#include "CCDevice.h"
2014-04-27 01:11:22 +08:00
#include "2d/ccTypes.h"
#include "2d/CCEventDispatcher.h"
#include "2d/CCEventAcceleration.h"
#include "2d/CCDirector.h"
2013-09-03 18:22:03 +08:00
#import <UIKit/UIKit.h>
// Accelerometer
2013-10-08 13:44:35 +08:00
#import<CoreMotion/CoreMotion.h>
2013-10-08 10:11:52 +08:00
#import<CoreFoundation/CoreFoundation.h>
2013-09-03 18:22:03 +08:00
@interface CCAccelerometerDispatcher : NSObject<UIAccelerometerDelegate>
{
cocos2d::Acceleration *_acceleration;
2013-10-08 10:11:52 +08:00
CMMotionManager *_motionManager;
2013-09-03 18:22:03 +08:00
}
+ (id) sharedAccelerometerDispather;
- (id) init;
- (void) setAccelerometerEnabled: (bool) isEnabled;
- (void) setAccelerometerInterval:(float) interval;
@end
@implementation CCAccelerometerDispatcher
static CCAccelerometerDispatcher* s_pAccelerometerDispatcher;
+ (id) sharedAccelerometerDispather
{
if (s_pAccelerometerDispatcher == nil) {
s_pAccelerometerDispatcher = [[self alloc] init];
}
return s_pAccelerometerDispatcher;
}
- (id) init
{
2013-11-12 08:07:46 +08:00
if( (self = [super init]) ) {
_acceleration = new cocos2d::Acceleration();
_motionManager = [[CMMotionManager alloc] init];
}
2013-09-03 18:22:03 +08:00
return self;
}
- (void) dealloc
{
s_pAccelerometerDispatcher = nullptr;
delete _acceleration;
2013-10-08 10:11:52 +08:00
[_motionManager release];
2013-09-03 18:22:03 +08:00
[super dealloc];
}
- (void) setAccelerometerEnabled: (bool) isEnabled
{
if (isEnabled)
{
2013-10-08 10:11:52 +08:00
[_motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
[self accelerometer:accelerometerData];
}];
2013-09-03 18:22:03 +08:00
}
else
{
2013-10-08 10:11:52 +08:00
[_motionManager stopAccelerometerUpdates];
2013-09-03 18:22:03 +08:00
}
}
-(void) setAccelerometerInterval:(float)interval
{
2013-10-08 10:11:52 +08:00
_motionManager.accelerometerUpdateInterval = interval;
2013-09-03 18:22:03 +08:00
}
2013-10-08 10:11:52 +08:00
- (void)accelerometer:(CMAccelerometerData *)accelerometerData
2013-09-03 18:22:03 +08:00
{
2013-10-08 10:11:52 +08:00
_acceleration->x = accelerometerData.acceleration.x;
_acceleration->y = accelerometerData.acceleration.y;
_acceleration->z = accelerometerData.acceleration.z;
_acceleration->timestamp = accelerometerData.timestamp;
2013-09-03 18:22:03 +08:00
double tmp = _acceleration->x;
switch ([[UIApplication sharedApplication] statusBarOrientation])
{
case UIInterfaceOrientationLandscapeRight:
_acceleration->x = -_acceleration->y;
_acceleration->y = tmp;
break;
case UIInterfaceOrientationLandscapeLeft:
_acceleration->x = _acceleration->y;
_acceleration->y = -tmp;
break;
case UIInterfaceOrientationPortraitUpsideDown:
_acceleration->x = -_acceleration->y;
_acceleration->y = -tmp;
break;
case UIInterfaceOrientationPortrait:
break;
}
2013-09-20 19:19:31 +08:00
cocos2d::EventAcceleration event(*_acceleration);
2013-10-29 16:20:42 +08:00
auto dispatcher = cocos2d::Director::getInstance()->getEventDispatcher();
dispatcher->dispatchEvent(&event);
2013-09-03 18:22:03 +08:00
}
@end
//
2013-02-16 19:36:21 +08:00
NS_CC_BEGIN
2013-06-20 14:13:12 +08:00
int Device::getDPI()
2013-02-16 19:36:21 +08:00
{
2013-02-17 17:13:06 +08:00
static int dpi = -1;
if (dpi == -1)
{
float scale = 1.0f;
if ([[UIScreen mainScreen] respondsToSelector:@selector(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;
}
2013-02-16 19:36:21 +08:00
}
return dpi;
}
2013-09-03 18:22:03 +08:00
void Device::setAccelerometerEnabled(bool isEnabled)
{
[[CCAccelerometerDispatcher sharedAccelerometerDispather] setAccelerometerEnabled:isEnabled];
}
void Device::setAccelerometerInterval(float interval)
{
[[CCAccelerometerDispatcher sharedAccelerometerDispather] setAccelerometerInterval:interval];
}
2014-02-13 21:08:43 +08:00
typedef struct
{
unsigned int height;
unsigned int width;
bool isPremultipliedAlpha;
bool hasShadow;
CGSize shadowOffset;
float shadowBlur;
float shadowOpacity;
bool hasStroke;
float strokeColorR;
float strokeColorG;
float strokeColorB;
float strokeSize;
float tintColorR;
float tintColorG;
float tintColorB;
unsigned char* data;
} tImageInfo;
2014-04-01 15:08:08 +08:00
static bool s_isIOS7OrHigher = false;
2014-04-01 14:47:52 +08:00
static inline void lazyCheckIOS7()
{
static bool isInited = false;
if (!isInited)
{
2014-04-01 15:08:08 +08:00
s_isIOS7OrHigher = [[[UIDevice currentDevice] systemVersion] compare:@"7.0" options:NSNumericSearch] != NSOrderedAscending;
2014-04-01 14:47:52 +08:00
isInited = true;
}
}
2014-02-13 21:08:43 +08:00
static CGSize _calculateStringSize(NSString *str, id font, CGSize *constrainSize)
{
NSArray *listItems = [str componentsSeparatedByString: @"\n"];
CGSize dim = CGSizeZero;
CGSize textRect = CGSizeZero;
textRect.width = constrainSize->width > 0 ? constrainSize->width
: 0x7fffffff;
textRect.height = constrainSize->height > 0 ? constrainSize->height
: 0x7fffffff;
for (NSString *s in listItems)
{
CGSize tmp = [s sizeWithFont:font constrainedToSize:textRect];
if (tmp.width > dim.width)
{
dim.width = tmp.width;
}
dim.height += tmp.height;
}
2014-04-01 14:47:52 +08:00
dim.width = ceilf(dim.width);
dim.height = ceilf(dim.height);
2014-02-13 21:08:43 +08:00
return dim;
}
// refer Image::ETextAlign
#define ALIGN_TOP 1
#define ALIGN_CENTER 3
#define ALIGN_BOTTOM 2
2014-04-01 14:47:52 +08:00
2014-02-13 21:08:43 +08:00
static bool _initWithString(const char * text, cocos2d::Device::TextAlign align, const char * fontName, int size, tImageInfo* info)
{
2014-04-01 14:47:52 +08:00
// lazy check whether it is iOS7 device
lazyCheckIOS7();
2014-02-13 21:08:43 +08:00
bool bRet = false;
do
{
CC_BREAK_IF(! text || ! info);
NSString * str = [NSString stringWithUTF8String:text];
NSString * fntName = [NSString stringWithUTF8String:fontName];
CGSize dim, constrainSize;
constrainSize.width = info->width;
constrainSize.height = info->height;
// On iOS custom fonts must be listed beforehand in the App info.plist (in order to be usable) and referenced only the by the font family name itself when
// calling [UIFont fontWithName]. Therefore even if the developer adds 'SomeFont.ttf' or 'fonts/SomeFont.ttf' to the App .plist, the font must
// be referenced as 'SomeFont' when calling [UIFont fontWithName]. Hence we strip out the folder path components and the extension here in order to get just
// the font family name itself. This stripping step is required especially for references to user fonts stored in CCB files; CCB files appear to store
// the '.ttf' extensions when referring to custom fonts.
fntName = [[fntName lastPathComponent] stringByDeletingPathExtension];
// create the font
id font = [UIFont fontWithName:fntName size:size];
if (font)
{
dim = _calculateStringSize(str, font, &constrainSize);
}
else
{
if (!font)
{
font = [UIFont systemFontOfSize:size];
}
if (font)
{
dim = _calculateStringSize(str, font, &constrainSize);
}
}
CC_BREAK_IF(! font);
// compute start point
int startH = 0;
if (constrainSize.height > dim.height)
{
// vertical alignment
unsigned int vAlignment = ((int)align >> 4) & 0x0F;
if (vAlignment == ALIGN_TOP)
{
startH = 0;
}
else if (vAlignment == ALIGN_CENTER)
{
startH = (constrainSize.height - dim.height) / 2;
}
else
{
startH = constrainSize.height - dim.height;
}
}
// adjust text rect
if (constrainSize.width > 0 && constrainSize.width > dim.width)
{
dim.width = constrainSize.width;
}
if (constrainSize.height > 0 && constrainSize.height > dim.height)
{
dim.height = constrainSize.height;
}
// compute the padding needed by shadow and stroke
float shadowStrokePaddingX = 0.0f;
float shadowStrokePaddingY = 0.0f;
if ( info->hasStroke )
{
shadowStrokePaddingX = ceilf(info->strokeSize);
shadowStrokePaddingY = ceilf(info->strokeSize);
}
// add the padding (this could be 0 if no shadow and no stroke)
2014-03-24 11:33:52 +08:00
dim.width += shadowStrokePaddingX*2;
dim.height += shadowStrokePaddingY*2;
2014-02-13 21:08:43 +08:00
2014-02-18 10:11:04 +08:00
unsigned char* data = (unsigned char*)malloc(sizeof(unsigned char) * (int)(dim.width * dim.height * 4));
2014-02-13 21:08:43 +08:00
memset(data, 0, (int)(dim.width * dim.height * 4));
// draw text
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(data,
dim.width,
dim.height,
8,
(int)(dim.width) * 4,
colorSpace,
kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
if (!context)
{
CGColorSpaceRelease(colorSpace);
2014-02-18 10:11:04 +08:00
CC_SAFE_FREE(data);
2014-02-13 21:08:43 +08:00
break;
}
// text color
CGContextSetRGBFillColor(context, info->tintColorR, info->tintColorG, info->tintColorB, 1);
// move Y rendering to the top of the image
CGContextTranslateCTM(context, 0.0f, (dim.height - shadowStrokePaddingY) );
CGContextScaleCTM(context, 1.0f, -1.0f); //NOTE: NSString draws in UIKit referential i.e. renders upside-down compared to CGBitmapContext referential
// store the current context
UIGraphicsPushContext(context);
// measure text size with specified font and determine the rectangle to draw text in
unsigned uHoriFlag = (int)align & 0x0f;
2014-03-24 11:33:52 +08:00
NSTextAlignment nsAlign = (2 == uHoriFlag) ? NSTextAlignmentRight
: (3 == uHoriFlag) ? NSTextAlignmentCenter
: NSTextAlignmentLeft;
2014-03-26 14:11:40 +08:00
2014-02-13 21:08:43 +08:00
CGColorSpaceRelease(colorSpace);
// compute the rect used for rendering the text
// based on wether shadows or stroke are enabled
2014-03-24 11:33:52 +08:00
float textOriginX = 0;
float textOrigingY = startH;
2014-02-13 21:08:43 +08:00
2014-03-24 11:33:52 +08:00
float textWidth = dim.width;
float textHeight = dim.height;
2014-02-13 21:08:43 +08:00
2014-03-24 11:33:52 +08:00
CGRect rect = CGRectMake(textOriginX, textOrigingY, textWidth, textHeight);
2014-02-13 21:08:43 +08:00
2014-03-24 11:33:52 +08:00
CGContextSetShouldSubpixelQuantizeFonts(context, false);
2014-02-13 21:08:43 +08:00
2014-03-24 11:33:52 +08:00
CGContextBeginTransparencyLayerWithRect(context, rect, NULL);
if ( info->hasStroke )
2014-02-13 21:08:43 +08:00
{
2014-03-24 11:33:52 +08:00
CGContextSetTextDrawingMode(context, kCGTextStroke);
2014-04-01 15:08:08 +08:00
if(s_isIOS7OrHigher)
2014-03-24 11:33:52 +08:00
{
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.alignment = nsAlign;
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
[str drawInRect:rect withAttributes:@{
NSFontAttributeName: font,
NSStrokeWidthAttributeName: [NSNumber numberWithFloat: info->strokeSize / size * 100 ],
NSForegroundColorAttributeName:[UIColor colorWithRed:info->tintColorR
green:info->tintColorG
blue:info->tintColorB
alpha:1.0f],
NSParagraphStyleAttributeName:paragraphStyle,
NSStrokeColorAttributeName: [UIColor colorWithRed:info->strokeColorR
green:info->strokeColorG
blue:info->strokeColorB
alpha:1.0f]
}
];
[paragraphStyle release];
}
else
{
CGContextSetRGBStrokeColor(context, info->strokeColorR, info->strokeColorG, info->strokeColorB, 1);
CGContextSetLineWidth(context, info->strokeSize);
//original code that was not working in iOS 7
[str drawInRect: rect withFont:font lineBreakMode:NSLineBreakByWordWrapping alignment:nsAlign];
}
2014-02-13 21:08:43 +08:00
}
2014-03-24 11:33:52 +08:00
CGContextSetTextDrawingMode(context, kCGTextFill);
2014-02-13 21:08:43 +08:00
// actually draw the text in the context
2014-03-24 11:33:52 +08:00
[str drawInRect: rect withFont:font lineBreakMode:NSLineBreakByWordWrapping alignment:nsAlign];
2014-04-01 14:47:52 +08:00
2014-02-13 21:08:43 +08:00
CGContextEndTransparencyLayer(context);
// pop the context
UIGraphicsPopContext();
// release the context
CGContextRelease(context);
// output params
info->data = data;
info->isPremultipliedAlpha = true;
info->width = dim.width;
info->height = dim.height;
bRet = true;
} while (0);
return bRet;
}
Data Device::getTextureDataForText(const char * text,const FontDefinition& textDefinition,TextAlign align,int &width,int &height)
{
Data ret;
do {
tImageInfo info = {0};
info.width = textDefinition._dimensions.width;
info.height = textDefinition._dimensions.height;
info.hasShadow = textDefinition._shadow._shadowEnabled;
info.shadowOffset.width = textDefinition._shadow._shadowOffset.width;
info.shadowOffset.height = textDefinition._shadow._shadowOffset.height;
info.shadowBlur = textDefinition._shadow._shadowBlur;
info.shadowOpacity = textDefinition._shadow._shadowOpacity;
info.hasStroke = textDefinition._stroke._strokeEnabled;
info.strokeColorR = textDefinition._stroke._strokeColor.r;
info.strokeColorG = textDefinition._stroke._strokeColor.g;
info.strokeColorB = textDefinition._stroke._strokeColor.b;
info.strokeSize = textDefinition._stroke._strokeSize;
info.tintColorR = textDefinition._fontFillColor.r;
info.tintColorG = textDefinition._fontFillColor.g;
info.tintColorB = textDefinition._fontFillColor.b;
if (! _initWithString(text, align, textDefinition._fontName.c_str(), textDefinition._fontSize, &info))
{
break;
}
height = (short)info.height;
2014-02-14 09:41:06 +08:00
width = (short)info.width;
2014-02-13 21:08:43 +08:00
ret.fastSet(info.data,width * height * 4);
} while (0);
return ret;
}
2013-09-03 18:22:03 +08:00
2013-02-16 19:36:21 +08:00
NS_CC_END
2014-01-28 08:44:10 +08:00
#endif // CC_PLATFORM_IOS
2014-02-13 21:08:43 +08:00