mirror of https://github.com/axmolengine/axmol.git
Merge branch 'develop' of https://github.com/cocos2d/cocos2d-x into develop
This commit is contained in:
commit
2077bc6d2f
6
AUTHORS
6
AUTHORS
|
@ -38,6 +38,7 @@ Developers:
|
|||
carlomorgantinizynga
|
||||
CCLabelTTF supports for shadow and stroke
|
||||
Adding CCLabelTTF::createWithFontDefinition.
|
||||
New label support.
|
||||
|
||||
James Gregory (j4m3z0r, Zynga)
|
||||
Maintainer of Emscripten port.
|
||||
|
@ -423,6 +424,8 @@ Developers:
|
|||
Added some guards in fileutils. Fixed a bug in emscripten file utils.
|
||||
Added emscripten keyboard support
|
||||
Clang support for Linux
|
||||
Multiple emscripten template support. Emscripten multiple resolutions support.
|
||||
Toplevel Makefile refactoring
|
||||
|
||||
elmiro
|
||||
Correction of passed buffer size to readlink and verification of result return by readlink.
|
||||
|
@ -556,6 +559,9 @@ Developers:
|
|||
Nako Sung (nakosung)
|
||||
Fixing a bug that wrong logic when pass an empty std::vector to WebSocket::init.
|
||||
Exposing cc.RemoveSelf to JS.
|
||||
|
||||
dotsquid
|
||||
Fixed the crash caused by improper deletion of VBOs and VAO in ParticleSystemQuad.
|
||||
|
||||
Retired Core Developers:
|
||||
WenSheng Yang
|
||||
|
|
|
@ -5,10 +5,10 @@ LOCAL_MODULE := cocosdenshion_static
|
|||
|
||||
LOCAL_MODULE_FILENAME := libcocosdenshion
|
||||
|
||||
LOCAL_SRC_FILES := SimpleAudioEngine.cpp \
|
||||
jni/SimpleAudioEngineJni.cpp \
|
||||
opensl/OpenSLEngine.cpp \
|
||||
opensl/SimpleAudioEngineOpenSL.cpp
|
||||
LOCAL_SRC_FILES := cddSimpleAudioEngine.cpp \
|
||||
ccdandroidUtils.cpp \
|
||||
jni/cddandroidAndroidJavaEngine.cpp \
|
||||
opensl/cddandroidOpenSLEngine.cpp
|
||||
|
||||
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/../include
|
||||
|
||||
|
|
|
@ -1,309 +0,0 @@
|
|||
/****************************************************************************
|
||||
Copyright (c) 2010 cocos2d-x.org
|
||||
|
||||
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 "SimpleAudioEngine.h"
|
||||
#include "jni/SimpleAudioEngineJni.h"
|
||||
#include "opensl/SimpleAudioEngineOpenSL.h"
|
||||
|
||||
#include "cocos2d.h"
|
||||
#include <cstring>
|
||||
#include <android/log.h>
|
||||
#include <jni/JniHelper.h>
|
||||
#include <jni.h>
|
||||
|
||||
#define I9100_MODEL "GT-I9100"
|
||||
#define LOG_TAG "Device Model"
|
||||
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
|
||||
|
||||
static bool s_bI9100 = false;
|
||||
|
||||
USING_NS_CC;
|
||||
/**********************************************************************************
|
||||
* jni
|
||||
**********************************************************************************/
|
||||
#define CLASS_NAME "org/cocos2dx/lib/Cocos2dxHelper"
|
||||
#define METHOD_NAME "getDeviceModel"
|
||||
|
||||
namespace CocosDenshion {
|
||||
|
||||
static std::string getFullPathWithoutAssetsPrefix(const char* pszFilename)
|
||||
{
|
||||
// Changing file path to full path
|
||||
std::string fullPath = FileUtils::getInstance()->fullPathForFilename(pszFilename);
|
||||
// Removing `assets` since it isn't needed for the API of playing sound.
|
||||
size_t pos = fullPath.find("assets/");
|
||||
if (pos == 0)
|
||||
{
|
||||
fullPath = fullPath.substr(strlen("assets/"));
|
||||
}
|
||||
return fullPath;
|
||||
}
|
||||
|
||||
static SimpleAudioEngine *s_pEngine = 0;
|
||||
|
||||
SimpleAudioEngine::SimpleAudioEngine()
|
||||
{
|
||||
JniMethodInfo methodInfo;
|
||||
jstring jstr;
|
||||
if (JniHelper::getStaticMethodInfo(methodInfo, CLASS_NAME, METHOD_NAME, "()Ljava/lang/String;"))
|
||||
{
|
||||
jstr = (jstring)methodInfo.env->CallStaticObjectMethod(methodInfo.classID, methodInfo.methodID);
|
||||
}
|
||||
methodInfo.env->DeleteLocalRef(methodInfo.classID);
|
||||
|
||||
const char* deviceModel = methodInfo.env->GetStringUTFChars(jstr, NULL);
|
||||
|
||||
LOGD("%s", deviceModel);
|
||||
|
||||
if (strcmp(I9100_MODEL, deviceModel) == 0)
|
||||
{
|
||||
LOGD("i9100 model\nSwitch to OpenSLES");
|
||||
s_bI9100 = true;
|
||||
}
|
||||
|
||||
methodInfo.env->ReleaseStringUTFChars(jstr, deviceModel);
|
||||
methodInfo.env->DeleteLocalRef(jstr);
|
||||
}
|
||||
|
||||
SimpleAudioEngine::~SimpleAudioEngine()
|
||||
{
|
||||
if (s_bI9100)
|
||||
{
|
||||
SimpleAudioEngineOpenSL::sharedEngine()->end();
|
||||
}
|
||||
}
|
||||
|
||||
SimpleAudioEngine* SimpleAudioEngine::getInstance()
|
||||
{
|
||||
if (! s_pEngine)
|
||||
{
|
||||
s_pEngine = new SimpleAudioEngine();
|
||||
}
|
||||
|
||||
return s_pEngine;
|
||||
}
|
||||
|
||||
void SimpleAudioEngine::end()
|
||||
{
|
||||
if (s_bI9100)
|
||||
{
|
||||
SimpleAudioEngineOpenSL::sharedEngine()->end();
|
||||
}
|
||||
else
|
||||
{
|
||||
endJNI();
|
||||
}
|
||||
}
|
||||
|
||||
void SimpleAudioEngine::preloadBackgroundMusic(const char* pszFilePath)
|
||||
{
|
||||
std::string fullPath = getFullPathWithoutAssetsPrefix(pszFilePath);
|
||||
preloadBackgroundMusicJNI(fullPath.c_str());
|
||||
}
|
||||
|
||||
void SimpleAudioEngine::playBackgroundMusic(const char* pszFilePath, bool bLoop)
|
||||
{
|
||||
std::string fullPath = getFullPathWithoutAssetsPrefix(pszFilePath);
|
||||
playBackgroundMusicJNI(fullPath.c_str(), bLoop);
|
||||
}
|
||||
|
||||
void SimpleAudioEngine::stopBackgroundMusic(bool bReleaseData)
|
||||
{
|
||||
stopBackgroundMusicJNI();
|
||||
}
|
||||
|
||||
void SimpleAudioEngine::pauseBackgroundMusic()
|
||||
{
|
||||
pauseBackgroundMusicJNI();
|
||||
}
|
||||
|
||||
void SimpleAudioEngine::resumeBackgroundMusic()
|
||||
{
|
||||
resumeBackgroundMusicJNI();
|
||||
}
|
||||
|
||||
void SimpleAudioEngine::rewindBackgroundMusic()
|
||||
{
|
||||
rewindBackgroundMusicJNI();
|
||||
}
|
||||
|
||||
bool SimpleAudioEngine::willPlayBackgroundMusic()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
bool SimpleAudioEngine::isBackgroundMusicPlaying()
|
||||
{
|
||||
return isBackgroundMusicPlayingJNI();
|
||||
}
|
||||
|
||||
float SimpleAudioEngine::getBackgroundMusicVolume()
|
||||
{
|
||||
return getBackgroundMusicVolumeJNI();
|
||||
}
|
||||
|
||||
void SimpleAudioEngine::setBackgroundMusicVolume(float volume)
|
||||
{
|
||||
setBackgroundMusicVolumeJNI(volume);
|
||||
}
|
||||
|
||||
float SimpleAudioEngine::getEffectsVolume()
|
||||
{
|
||||
if (s_bI9100)
|
||||
{
|
||||
return SimpleAudioEngineOpenSL::sharedEngine()->getEffectsVolume();
|
||||
}
|
||||
else
|
||||
{
|
||||
return getEffectsVolumeJNI();
|
||||
}
|
||||
}
|
||||
|
||||
void SimpleAudioEngine::setEffectsVolume(float volume)
|
||||
{
|
||||
if (s_bI9100)
|
||||
{
|
||||
SimpleAudioEngineOpenSL::sharedEngine()->setEffectsVolume(volume);
|
||||
}
|
||||
else
|
||||
{
|
||||
setEffectsVolumeJNI(volume);
|
||||
}
|
||||
}
|
||||
|
||||
unsigned int SimpleAudioEngine::playEffect(const char* pszFilePath, bool bLoop,
|
||||
float pitch, float pan, float gain)
|
||||
{
|
||||
std::string fullPath = getFullPathWithoutAssetsPrefix(pszFilePath);
|
||||
if (s_bI9100)
|
||||
{
|
||||
return SimpleAudioEngineOpenSL::sharedEngine()->playEffect(fullPath.c_str(), bLoop, pitch, pan, gain);
|
||||
}
|
||||
else
|
||||
{
|
||||
return playEffectJNI(fullPath.c_str(), bLoop, pitch, pan, gain);
|
||||
}
|
||||
}
|
||||
|
||||
void SimpleAudioEngine::stopEffect(unsigned int nSoundId)
|
||||
{
|
||||
if (s_bI9100)
|
||||
{
|
||||
SimpleAudioEngineOpenSL::sharedEngine()->stopEffect(nSoundId);
|
||||
}
|
||||
else
|
||||
{
|
||||
stopEffectJNI(nSoundId);
|
||||
}
|
||||
}
|
||||
|
||||
void SimpleAudioEngine::preloadEffect(const char* pszFilePath)
|
||||
{
|
||||
std::string fullPath = getFullPathWithoutAssetsPrefix(pszFilePath);
|
||||
|
||||
if (s_bI9100)
|
||||
{
|
||||
SimpleAudioEngineOpenSL::sharedEngine()->preloadEffect(fullPath.c_str());
|
||||
}
|
||||
else
|
||||
{
|
||||
preloadEffectJNI(fullPath.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
void SimpleAudioEngine::unloadEffect(const char* pszFilePath)
|
||||
{
|
||||
std::string fullPath = getFullPathWithoutAssetsPrefix(pszFilePath);
|
||||
|
||||
if (s_bI9100)
|
||||
{
|
||||
SimpleAudioEngineOpenSL::sharedEngine()->unloadEffect(fullPath.c_str());
|
||||
}
|
||||
else
|
||||
{
|
||||
unloadEffectJNI(fullPath.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
void SimpleAudioEngine::pauseEffect(unsigned int nSoundId)
|
||||
{
|
||||
if (s_bI9100)
|
||||
{
|
||||
SimpleAudioEngineOpenSL::sharedEngine()->pauseEffect(nSoundId);
|
||||
}
|
||||
else
|
||||
{
|
||||
pauseEffectJNI(nSoundId);
|
||||
}
|
||||
}
|
||||
|
||||
void SimpleAudioEngine::pauseAllEffects()
|
||||
{
|
||||
if (s_bI9100)
|
||||
{
|
||||
SimpleAudioEngineOpenSL::sharedEngine()->pauseAllEffects();
|
||||
}
|
||||
else
|
||||
{
|
||||
pauseAllEffectsJNI();
|
||||
}
|
||||
}
|
||||
|
||||
void SimpleAudioEngine::resumeEffect(unsigned int nSoundId)
|
||||
{
|
||||
if (s_bI9100)
|
||||
{
|
||||
SimpleAudioEngineOpenSL::sharedEngine()->resumeEffect(nSoundId);
|
||||
}
|
||||
else
|
||||
{
|
||||
resumeEffectJNI(nSoundId);
|
||||
}
|
||||
}
|
||||
|
||||
void SimpleAudioEngine::resumeAllEffects()
|
||||
{
|
||||
if (s_bI9100)
|
||||
{
|
||||
SimpleAudioEngineOpenSL::sharedEngine()->resumeAllEffects();
|
||||
}
|
||||
else
|
||||
{
|
||||
resumeAllEffectsJNI();
|
||||
}
|
||||
}
|
||||
|
||||
void SimpleAudioEngine::stopAllEffects()
|
||||
{
|
||||
if (s_bI9100)
|
||||
{
|
||||
SimpleAudioEngineOpenSL::sharedEngine()->stopAllEffects();
|
||||
}
|
||||
else
|
||||
{
|
||||
stopAllEffectsJNI();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,59 @@
|
|||
#include "ccdandroidUtils.h"
|
||||
#include "cocos2d.h"
|
||||
|
||||
#include <jni.h>
|
||||
#include <android/log.h>
|
||||
#include "jni/JniHelper.h"
|
||||
|
||||
USING_NS_CC;
|
||||
|
||||
namespace CocosDenshion {
|
||||
namespace android {
|
||||
|
||||
#define I9100_MODEL "GT-I9100"
|
||||
#define LOG_TAG "Device Model"
|
||||
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
|
||||
#define CLASS_NAME "org/cocos2dx/lib/Cocos2dxHelper"
|
||||
#define METHOD_NAME "getDeviceModel"
|
||||
|
||||
bool is_buggy_device(void) {
|
||||
JniMethodInfo methodInfo;
|
||||
jstring jstr;
|
||||
if (JniHelper::getStaticMethodInfo(methodInfo,
|
||||
CLASS_NAME,
|
||||
METHOD_NAME,
|
||||
"()Ljava/lang/String;")) {
|
||||
jstr = (jstring)methodInfo.env->CallStaticObjectMethod(methodInfo.classID,
|
||||
methodInfo.methodID);
|
||||
}
|
||||
|
||||
const char* deviceModel = methodInfo.env->GetStringUTFChars(jstr, NULL);
|
||||
if (NULL == deviceModel) {
|
||||
return false;
|
||||
}
|
||||
|
||||
LOGD("deviceModel = %s", deviceModel);
|
||||
methodInfo.env->ReleaseStringUTFChars(jstr, deviceModel);
|
||||
methodInfo.env->DeleteLocalRef(jstr);
|
||||
|
||||
if (strcmp(I9100_MODEL, deviceModel) == 0) {
|
||||
LOGD("i9100 model\nSwitch to OpenSLES");
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
std::string getFullPathWithoutAssetsPrefix(const char* pszFilename) {
|
||||
// Changing file path to full path
|
||||
std::string fullPath = cocos2d::FileUtils::getInstance()->fullPathForFilename(pszFilename);
|
||||
// Removing `assets` since it isn't needed for the API of playing sound.
|
||||
size_t pos = fullPath.find("assets/");
|
||||
if (pos == 0)
|
||||
{
|
||||
fullPath = fullPath.substr(strlen("assets/"));
|
||||
}
|
||||
return fullPath;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
#ifndef __CCDANDROIDUTILS_H__
|
||||
#define __CCDANDROIDUTILS_H__
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace CocosDenshion {
|
||||
namespace android {
|
||||
bool is_buggy_device(void);
|
||||
std::string getFullPathWithoutAssetsPrefix(const char* pszFilename);
|
||||
}
|
||||
}
|
||||
|
||||
#endif //__CCDANDROIDUTILS_H__
|
|
@ -0,0 +1,87 @@
|
|||
/****************************************************************************
|
||||
Copyright (c) 2010 cocos2d-x.org
|
||||
|
||||
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 "SimpleAudioEngine.h"
|
||||
#include "jni/cddandroidAndroidJavaEngine.h"
|
||||
#include "opensl/cddandroidOpenSLEngine.h"
|
||||
#include "ccdandroidUtils.h"
|
||||
|
||||
namespace CocosDenshion {
|
||||
|
||||
static SimpleAudioEngine *s_pEngine = 0;
|
||||
|
||||
SimpleAudioEngine* SimpleAudioEngine::getInstance() {
|
||||
if (! s_pEngine) {
|
||||
// if (CocosDenshion::android::is_buggy_device()) {
|
||||
// use the Java Audio implementation until compatibility is confirmed
|
||||
s_pEngine = new CocosDenshion::android::AndroidJavaEngine();
|
||||
// } else {
|
||||
// s_pEngine = new CocosDenshion::android::OpenSLEngine();
|
||||
// }
|
||||
}
|
||||
|
||||
return s_pEngine;
|
||||
}
|
||||
|
||||
void SimpleAudioEngine::end() {
|
||||
if (s_pEngine) {
|
||||
delete s_pEngine;
|
||||
s_pEngine = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
SimpleAudioEngine::SimpleAudioEngine() {
|
||||
}
|
||||
|
||||
SimpleAudioEngine::~SimpleAudioEngine() {
|
||||
}
|
||||
|
||||
// Empty implementations. On Android, only subclasses are meant to be used
|
||||
void SimpleAudioEngine::preloadBackgroundMusic(const char* pszFilePath) { }
|
||||
void SimpleAudioEngine::playBackgroundMusic(const char* pszFilePath, bool bLoop) { }
|
||||
void SimpleAudioEngine::stopBackgroundMusic(bool bReleaseData) { }
|
||||
void SimpleAudioEngine::pauseBackgroundMusic() { }
|
||||
void SimpleAudioEngine::resumeBackgroundMusic() { }
|
||||
void SimpleAudioEngine::rewindBackgroundMusic() { }
|
||||
bool SimpleAudioEngine::willPlayBackgroundMusic() { return false; }
|
||||
bool SimpleAudioEngine::isBackgroundMusicPlaying() { return false; }
|
||||
float SimpleAudioEngine::getBackgroundMusicVolume() { return 0.0f; }
|
||||
void SimpleAudioEngine::setBackgroundMusicVolume(float volume) { }
|
||||
float SimpleAudioEngine::getEffectsVolume() { return 0.0f; }
|
||||
void SimpleAudioEngine::setEffectsVolume(float volume) { }
|
||||
unsigned int SimpleAudioEngine::playEffect(const char* pszFilePath,
|
||||
bool bLoop,
|
||||
float pitch,
|
||||
float pan,
|
||||
float gain) {
|
||||
return 0; }
|
||||
void SimpleAudioEngine::pauseEffect(unsigned int nSoundId) { }
|
||||
void SimpleAudioEngine::pauseAllEffects() { }
|
||||
void SimpleAudioEngine::resumeEffect(unsigned int nSoundId) { }
|
||||
void SimpleAudioEngine::resumeAllEffects() { }
|
||||
void SimpleAudioEngine::stopEffect(unsigned int nSoundId) { }
|
||||
void SimpleAudioEngine::stopAllEffects() { }
|
||||
void SimpleAudioEngine::preloadEffect(const char* pszFilePath) { }
|
||||
void SimpleAudioEngine::unloadEffect(const char* pszFilePath) { }
|
||||
}
|
|
@ -1,443 +0,0 @@
|
|||
#include "SimpleAudioEngineJni.h"
|
||||
#include "platform/android/jni/JniHelper.h"
|
||||
|
||||
#include <android/log.h>
|
||||
|
||||
#define LOG_TAG "libSimpleAudioEngine"
|
||||
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
|
||||
#define CLASS_NAME "org/cocos2dx/lib/Cocos2dxHelper"
|
||||
|
||||
typedef struct JniMethodInfo_
|
||||
{
|
||||
JNIEnv * env;
|
||||
jclass classID;
|
||||
jmethodID methodID;
|
||||
} JniMethodInfo;
|
||||
|
||||
|
||||
extern "C"
|
||||
{
|
||||
// get env and cache it
|
||||
static JNIEnv* getJNIEnv(void)
|
||||
{
|
||||
|
||||
JavaVM* jvm = cocos2d::JniHelper::getJavaVM();
|
||||
if (NULL == jvm) {
|
||||
LOGD("Failed to get JNIEnv. JniHelper::getJavaVM() is NULL");
|
||||
return NULL;
|
||||
}
|
||||
|
||||
JNIEnv *env = NULL;
|
||||
// get jni environment
|
||||
jint ret = jvm->GetEnv((void**)&env, JNI_VERSION_1_4);
|
||||
|
||||
switch (ret) {
|
||||
case JNI_OK :
|
||||
// Success!
|
||||
return env;
|
||||
|
||||
case JNI_EDETACHED :
|
||||
// Thread not attached
|
||||
|
||||
// TODO : If calling AttachCurrentThread() on a native thread
|
||||
// must call DetachCurrentThread() in future.
|
||||
// see: http://developer.android.com/guide/practices/design/jni.html
|
||||
|
||||
if (jvm->AttachCurrentThread(&env, NULL) < 0)
|
||||
{
|
||||
LOGD("Failed to get the environment using AttachCurrentThread()");
|
||||
return NULL;
|
||||
} else {
|
||||
// Success : Attached and obtained JNIEnv!
|
||||
return env;
|
||||
}
|
||||
|
||||
case JNI_EVERSION :
|
||||
// Cannot recover from this error
|
||||
LOGD("JNI interface version 1.4 not supported");
|
||||
default :
|
||||
LOGD("Failed to get the environment using GetEnv()");
|
||||
return NULL;
|
||||
}
|
||||
}
|
||||
|
||||
// get class and make it a global reference, release it at endJni().
|
||||
static jclass getClassID(JNIEnv *pEnv)
|
||||
{
|
||||
jclass ret = pEnv->FindClass(CLASS_NAME);
|
||||
if (! ret)
|
||||
{
|
||||
LOGD("Failed to find class of %s", CLASS_NAME);
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
static bool getStaticMethodInfo(JniMethodInfo &methodinfo, const char *methodName, const char *paramCode)
|
||||
{
|
||||
jmethodID methodID = 0;
|
||||
JNIEnv *pEnv = 0;
|
||||
bool bRet = false;
|
||||
|
||||
do
|
||||
{
|
||||
pEnv = getJNIEnv();
|
||||
if (! pEnv)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
jclass classID = getClassID(pEnv);
|
||||
|
||||
methodID = pEnv->GetStaticMethodID(classID, methodName, paramCode);
|
||||
if (! methodID)
|
||||
{
|
||||
LOGD("Failed to find static method id of %s", methodName);
|
||||
break;
|
||||
}
|
||||
|
||||
methodinfo.classID = classID;
|
||||
methodinfo.env = pEnv;
|
||||
methodinfo.methodID = methodID;
|
||||
|
||||
bRet = true;
|
||||
} while (0);
|
||||
|
||||
return bRet;
|
||||
}
|
||||
|
||||
void preloadBackgroundMusicJNI(const char *path)
|
||||
{
|
||||
// void playBackgroundMusic(String,boolean)
|
||||
JniMethodInfo methodInfo;
|
||||
|
||||
if (! getStaticMethodInfo(methodInfo, "preloadBackgroundMusic", "(Ljava/lang/String;)V"))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
jstring stringArg = methodInfo.env->NewStringUTF(path);
|
||||
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, stringArg);
|
||||
methodInfo.env->DeleteLocalRef(stringArg);
|
||||
methodInfo.env->DeleteLocalRef(methodInfo.classID);
|
||||
}
|
||||
|
||||
void playBackgroundMusicJNI(const char *path, bool isLoop)
|
||||
{
|
||||
// void playBackgroundMusic(String,boolean)
|
||||
|
||||
JniMethodInfo methodInfo;
|
||||
|
||||
if (! getStaticMethodInfo(methodInfo, "playBackgroundMusic", "(Ljava/lang/String;Z)V"))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
jstring stringArg = methodInfo.env->NewStringUTF(path);
|
||||
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, stringArg, isLoop);
|
||||
methodInfo.env->DeleteLocalRef(stringArg);
|
||||
methodInfo.env->DeleteLocalRef(methodInfo.classID);
|
||||
}
|
||||
|
||||
void stopBackgroundMusicJNI()
|
||||
{
|
||||
// void stopBackgroundMusic()
|
||||
|
||||
JniMethodInfo methodInfo;
|
||||
|
||||
if (! getStaticMethodInfo(methodInfo, "stopBackgroundMusic", "()V"))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID);
|
||||
methodInfo.env->DeleteLocalRef(methodInfo.classID);
|
||||
}
|
||||
|
||||
void pauseBackgroundMusicJNI()
|
||||
{
|
||||
// void pauseBackgroundMusic()
|
||||
|
||||
JniMethodInfo methodInfo;
|
||||
|
||||
if (! getStaticMethodInfo(methodInfo, "pauseBackgroundMusic", "()V"))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID);
|
||||
methodInfo.env->DeleteLocalRef(methodInfo.classID);
|
||||
}
|
||||
|
||||
void resumeBackgroundMusicJNI()
|
||||
{
|
||||
// void resumeBackgroundMusic()
|
||||
|
||||
JniMethodInfo methodInfo;
|
||||
|
||||
if (! getStaticMethodInfo(methodInfo, "resumeBackgroundMusic", "()V"))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID);
|
||||
methodInfo.env->DeleteLocalRef(methodInfo.classID);
|
||||
}
|
||||
|
||||
void rewindBackgroundMusicJNI()
|
||||
{
|
||||
// void rewindBackgroundMusic()
|
||||
|
||||
JniMethodInfo methodInfo;
|
||||
|
||||
if (! getStaticMethodInfo(methodInfo, "rewindBackgroundMusic", "()V"))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID);
|
||||
methodInfo.env->DeleteLocalRef(methodInfo.classID);
|
||||
}
|
||||
|
||||
bool isBackgroundMusicPlayingJNI()
|
||||
{
|
||||
// boolean rewindBackgroundMusic()
|
||||
|
||||
JniMethodInfo methodInfo;
|
||||
jboolean ret = false;
|
||||
|
||||
if (! getStaticMethodInfo(methodInfo, "isBackgroundMusicPlaying", "()Z"))
|
||||
{
|
||||
return ret;
|
||||
}
|
||||
|
||||
ret = methodInfo.env->CallStaticBooleanMethod(methodInfo.classID, methodInfo.methodID);
|
||||
methodInfo.env->DeleteLocalRef(methodInfo.classID);
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
float getBackgroundMusicVolumeJNI()
|
||||
{
|
||||
// float getBackgroundMusicVolume()
|
||||
|
||||
JniMethodInfo methodInfo;
|
||||
jfloat ret = -1.0;
|
||||
|
||||
if (! getStaticMethodInfo(methodInfo, "getBackgroundMusicVolume", "()F"))
|
||||
{
|
||||
return ret;
|
||||
}
|
||||
|
||||
ret = methodInfo.env->CallStaticFloatMethod(methodInfo.classID, methodInfo.methodID);
|
||||
methodInfo.env->DeleteLocalRef(methodInfo.classID);
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
void setBackgroundMusicVolumeJNI(float volume)
|
||||
{
|
||||
// void setBackgroundMusicVolume()
|
||||
|
||||
JniMethodInfo methodInfo;
|
||||
|
||||
if (! getStaticMethodInfo(methodInfo, "setBackgroundMusicVolume", "(F)V"))
|
||||
{
|
||||
return ;
|
||||
}
|
||||
|
||||
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, volume);
|
||||
methodInfo.env->DeleteLocalRef(methodInfo.classID);
|
||||
}
|
||||
|
||||
unsigned int playEffectJNI(const char* path, bool bLoop, float pitch, float pan, float gain)
|
||||
{
|
||||
// int playEffect(String)
|
||||
|
||||
JniMethodInfo methodInfo;
|
||||
int ret = 0;
|
||||
|
||||
if (! getStaticMethodInfo(methodInfo, "playEffect", "(Ljava/lang/String;ZFFF)I"))
|
||||
{
|
||||
return ret;
|
||||
}
|
||||
|
||||
jstring stringArg = methodInfo.env->NewStringUTF(path);
|
||||
ret = methodInfo.env->CallStaticIntMethod(methodInfo.classID, methodInfo.methodID, stringArg, bLoop, pitch, pan, gain);
|
||||
methodInfo.env->DeleteLocalRef(stringArg);
|
||||
methodInfo.env->DeleteLocalRef(methodInfo.classID);
|
||||
|
||||
return (unsigned int)ret;
|
||||
}
|
||||
|
||||
void stopEffectJNI(unsigned int nSoundId)
|
||||
{
|
||||
// void stopEffect(int)
|
||||
|
||||
JniMethodInfo methodInfo;
|
||||
|
||||
if (! getStaticMethodInfo(methodInfo, "stopEffect", "(I)V"))
|
||||
{
|
||||
return ;
|
||||
}
|
||||
|
||||
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, (int)nSoundId);
|
||||
methodInfo.env->DeleteLocalRef(methodInfo.classID);
|
||||
}
|
||||
|
||||
void endJNI()
|
||||
{
|
||||
// void end()
|
||||
|
||||
JniMethodInfo methodInfo;
|
||||
|
||||
if (! getStaticMethodInfo(methodInfo, "end", "()V"))
|
||||
{
|
||||
return ;
|
||||
}
|
||||
|
||||
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID);
|
||||
methodInfo.env->DeleteLocalRef(methodInfo.classID);
|
||||
}
|
||||
|
||||
float getEffectsVolumeJNI()
|
||||
{
|
||||
// float getEffectsVolume()
|
||||
|
||||
JniMethodInfo methodInfo;
|
||||
jfloat ret = -1.0;
|
||||
|
||||
if (! getStaticMethodInfo(methodInfo, "getEffectsVolume", "()F"))
|
||||
{
|
||||
return ret;
|
||||
}
|
||||
|
||||
ret = methodInfo.env->CallStaticFloatMethod(methodInfo.classID, methodInfo.methodID);
|
||||
methodInfo.env->DeleteLocalRef(methodInfo.classID);
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
void setEffectsVolumeJNI(float volume)
|
||||
{
|
||||
// void setEffectsVolume(float)
|
||||
JniMethodInfo methodInfo;
|
||||
|
||||
if (! getStaticMethodInfo(methodInfo, "setEffectsVolume", "(F)V"))
|
||||
{
|
||||
return ;
|
||||
}
|
||||
|
||||
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, volume);
|
||||
methodInfo.env->DeleteLocalRef(methodInfo.classID);
|
||||
}
|
||||
|
||||
void preloadEffectJNI(const char *path)
|
||||
{
|
||||
// void preloadEffect(String)
|
||||
|
||||
JniMethodInfo methodInfo;
|
||||
|
||||
if (! getStaticMethodInfo(methodInfo, "preloadEffect", "(Ljava/lang/String;)V"))
|
||||
{
|
||||
return ;
|
||||
}
|
||||
|
||||
jstring stringArg = methodInfo.env->NewStringUTF(path);
|
||||
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, stringArg);
|
||||
methodInfo.env->DeleteLocalRef(stringArg);
|
||||
methodInfo.env->DeleteLocalRef(methodInfo.classID);
|
||||
}
|
||||
|
||||
void unloadEffectJNI(const char* path)
|
||||
{
|
||||
// void unloadEffect(String)
|
||||
|
||||
JniMethodInfo methodInfo;
|
||||
|
||||
if (! getStaticMethodInfo(methodInfo, "unloadEffect", "(Ljava/lang/String;)V"))
|
||||
{
|
||||
return ;
|
||||
}
|
||||
|
||||
jstring stringArg = methodInfo.env->NewStringUTF(path);
|
||||
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, stringArg);
|
||||
methodInfo.env->DeleteLocalRef(stringArg);
|
||||
methodInfo.env->DeleteLocalRef(methodInfo.classID);
|
||||
}
|
||||
|
||||
void pauseEffectJNI(unsigned int nSoundId)
|
||||
{
|
||||
// void pauseEffect(int)
|
||||
|
||||
JniMethodInfo methodInfo;
|
||||
|
||||
if (! getStaticMethodInfo(methodInfo, "pauseEffect", "(I)V"))
|
||||
{
|
||||
return ;
|
||||
}
|
||||
|
||||
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, (int)nSoundId);
|
||||
methodInfo.env->DeleteLocalRef(methodInfo.classID);
|
||||
}
|
||||
|
||||
void pauseAllEffectsJNI()
|
||||
{
|
||||
// void pauseAllEffects()
|
||||
|
||||
JniMethodInfo methodInfo;
|
||||
|
||||
if (! getStaticMethodInfo(methodInfo, "pauseAllEffects", "()V"))
|
||||
{
|
||||
return ;
|
||||
}
|
||||
|
||||
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID);
|
||||
methodInfo.env->DeleteLocalRef(methodInfo.classID);
|
||||
}
|
||||
|
||||
void resumeEffectJNI(unsigned int nSoundId)
|
||||
{
|
||||
// void resumeEffect(int)
|
||||
|
||||
JniMethodInfo methodInfo;
|
||||
|
||||
if (! getStaticMethodInfo(methodInfo, "resumeEffect", "(I)V"))
|
||||
{
|
||||
return ;
|
||||
}
|
||||
|
||||
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, (int)nSoundId);
|
||||
methodInfo.env->DeleteLocalRef(methodInfo.classID);
|
||||
}
|
||||
|
||||
void resumeAllEffectsJNI()
|
||||
{
|
||||
// void resumeAllEffects()
|
||||
|
||||
JniMethodInfo methodInfo;
|
||||
|
||||
if (! getStaticMethodInfo(methodInfo, "resumeAllEffects", "()V"))
|
||||
{
|
||||
return ;
|
||||
}
|
||||
|
||||
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID);
|
||||
methodInfo.env->DeleteLocalRef(methodInfo.classID);
|
||||
}
|
||||
|
||||
void stopAllEffectsJNI()
|
||||
{
|
||||
// void stopAllEffects()
|
||||
|
||||
JniMethodInfo methodInfo;
|
||||
|
||||
if (! getStaticMethodInfo(methodInfo, "stopAllEffects", "()V"))
|
||||
{
|
||||
return ;
|
||||
}
|
||||
|
||||
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID);
|
||||
methodInfo.env->DeleteLocalRef(methodInfo.classID);
|
||||
}
|
||||
}
|
|
@ -1,32 +0,0 @@
|
|||
#ifndef __SIMPLE_AUDIO_ENGINE_JNI__
|
||||
#define __SIMPLE_AUDIO_ENGINE_JNI__
|
||||
|
||||
#include <jni.h>
|
||||
|
||||
extern "C"
|
||||
{
|
||||
extern void preloadBackgroundMusicJNI(const char *path);
|
||||
extern void playBackgroundMusicJNI(const char *path, bool isLoop);
|
||||
extern void stopBackgroundMusicJNI();
|
||||
extern void pauseBackgroundMusicJNI();
|
||||
extern void resumeBackgroundMusicJNI();
|
||||
extern void rewindBackgroundMusicJNI();
|
||||
extern bool isBackgroundMusicPlayingJNI();
|
||||
extern float getBackgroundMusicVolumeJNI();
|
||||
extern void setBackgroundMusicVolumeJNI(float volume);
|
||||
extern unsigned int playEffectJNI(const char* path, bool bLoop,
|
||||
float pitch, float pan, float gain);
|
||||
extern void stopEffectJNI(unsigned int nSoundId);
|
||||
extern void endJNI();
|
||||
extern float getEffectsVolumeJNI();
|
||||
extern void setEffectsVolumeJNI(float volume);
|
||||
extern void preloadEffectJNI(const char *path);
|
||||
extern void unloadEffectJNI(const char* path);
|
||||
extern void pauseEffectJNI(unsigned int nSoundId);
|
||||
extern void pauseAllEffectsJNI();
|
||||
extern void resumeEffectJNI(unsigned int nSoundId);
|
||||
extern void resumeAllEffectsJNI();
|
||||
extern void stopAllEffectsJNI();
|
||||
}
|
||||
|
||||
#endif // __SIMPLE_AUDIO_ENGINE_JNI__
|
|
@ -0,0 +1,297 @@
|
|||
#include "cddandroidAndroidJavaEngine.h"
|
||||
#include "platform/android/jni/JniHelper.h"
|
||||
#include "ccdandroidUtils.h"
|
||||
#include <android/log.h>
|
||||
#include <jni.h>
|
||||
|
||||
// logging
|
||||
#define LOG_TAG "cocosdenshion::android::AndroidJavaEngine"
|
||||
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
|
||||
|
||||
// Java class
|
||||
#define CLASS_NAME "org/cocos2dx/lib/Cocos2dxHelper"
|
||||
|
||||
namespace CocosDenshion {
|
||||
namespace android {
|
||||
|
||||
bool AndroidJavaEngine::getJNIStaticMethodInfo(cocos2d::JniMethodInfo &methodinfo,
|
||||
const char *methodName,
|
||||
const char *paramCode) {
|
||||
return cocos2d::JniHelper::getStaticMethodInfo(methodinfo,
|
||||
CLASS_NAME,
|
||||
methodName,
|
||||
paramCode);
|
||||
}
|
||||
|
||||
AndroidJavaEngine::~AndroidJavaEngine() {
|
||||
cocos2d::JniMethodInfo methodInfo;
|
||||
|
||||
if (!getJNIStaticMethodInfo(methodInfo, "end", "()V")) {
|
||||
return ;
|
||||
}
|
||||
|
||||
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID);
|
||||
methodInfo.env->DeleteLocalRef(methodInfo.classID);
|
||||
}
|
||||
|
||||
void AndroidJavaEngine::preloadBackgroundMusic(const char* pszFilePath) {
|
||||
std::string fullPath = CocosDenshion::android::getFullPathWithoutAssetsPrefix(pszFilePath);
|
||||
|
||||
// void playBackgroundMusic(String,boolean)
|
||||
cocos2d::JniMethodInfo methodInfo;
|
||||
|
||||
if (! getJNIStaticMethodInfo(methodInfo, "preloadBackgroundMusic", "(Ljava/lang/String;)V")) {
|
||||
return;
|
||||
}
|
||||
|
||||
jstring stringArg = methodInfo.env->NewStringUTF(fullPath.c_str());
|
||||
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, stringArg);
|
||||
methodInfo.env->DeleteLocalRef(stringArg);
|
||||
methodInfo.env->DeleteLocalRef(methodInfo.classID);
|
||||
}
|
||||
|
||||
void AndroidJavaEngine::playBackgroundMusic(const char* pszFilePath, bool bLoop) {
|
||||
std::string fullPath = CocosDenshion::android::getFullPathWithoutAssetsPrefix(pszFilePath);
|
||||
|
||||
cocos2d::JniMethodInfo methodInfo;
|
||||
|
||||
if (! getJNIStaticMethodInfo(methodInfo, "playBackgroundMusic", "(Ljava/lang/String;Z)V")) {
|
||||
return;
|
||||
}
|
||||
|
||||
jstring stringArg = methodInfo.env->NewStringUTF(fullPath.c_str());
|
||||
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, stringArg, bLoop);
|
||||
methodInfo.env->DeleteLocalRef(stringArg);
|
||||
methodInfo.env->DeleteLocalRef(methodInfo.classID);
|
||||
}
|
||||
|
||||
void AndroidJavaEngine::stopBackgroundMusic(bool bReleaseData) {
|
||||
cocos2d::JniMethodInfo methodInfo;
|
||||
|
||||
if (! getJNIStaticMethodInfo(methodInfo, "stopBackgroundMusic", "()V")) {
|
||||
return;
|
||||
}
|
||||
|
||||
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID);
|
||||
methodInfo.env->DeleteLocalRef(methodInfo.classID);
|
||||
}
|
||||
|
||||
void AndroidJavaEngine::pauseBackgroundMusic() {
|
||||
cocos2d::JniMethodInfo methodInfo;
|
||||
|
||||
if (! getJNIStaticMethodInfo(methodInfo, "pauseBackgroundMusic", "()V")) {
|
||||
return;
|
||||
}
|
||||
|
||||
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID);
|
||||
methodInfo.env->DeleteLocalRef(methodInfo.classID);
|
||||
}
|
||||
|
||||
void AndroidJavaEngine::resumeBackgroundMusic() {
|
||||
cocos2d::JniMethodInfo methodInfo;
|
||||
|
||||
if (! getJNIStaticMethodInfo(methodInfo, "resumeBackgroundMusic", "()V")) {
|
||||
return;
|
||||
}
|
||||
|
||||
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID);
|
||||
methodInfo.env->DeleteLocalRef(methodInfo.classID);
|
||||
}
|
||||
|
||||
void AndroidJavaEngine::rewindBackgroundMusic() {
|
||||
cocos2d::JniMethodInfo methodInfo;
|
||||
|
||||
if (! getJNIStaticMethodInfo(methodInfo, "rewindBackgroundMusic", "()V")) {
|
||||
return;
|
||||
}
|
||||
|
||||
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID);
|
||||
methodInfo.env->DeleteLocalRef(methodInfo.classID);
|
||||
}
|
||||
|
||||
|
||||
bool AndroidJavaEngine::willPlayBackgroundMusic() {
|
||||
return true;
|
||||
}
|
||||
|
||||
bool AndroidJavaEngine::isBackgroundMusicPlaying() {
|
||||
cocos2d::JniMethodInfo methodInfo;
|
||||
jboolean ret = false;
|
||||
|
||||
if (! getJNIStaticMethodInfo(methodInfo, "isBackgroundMusicPlaying", "()Z")) {
|
||||
return ret;
|
||||
}
|
||||
|
||||
ret = methodInfo.env->CallStaticBooleanMethod(methodInfo.classID, methodInfo.methodID);
|
||||
methodInfo.env->DeleteLocalRef(methodInfo.classID);
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
float AndroidJavaEngine::getBackgroundMusicVolume() {
|
||||
cocos2d::JniMethodInfo methodInfo;
|
||||
jfloat ret = -1.0;
|
||||
|
||||
if (! getJNIStaticMethodInfo(methodInfo, "getBackgroundMusicVolume", "()F")) {
|
||||
return ret;
|
||||
}
|
||||
|
||||
ret = methodInfo.env->CallStaticFloatMethod(methodInfo.classID, methodInfo.methodID);
|
||||
methodInfo.env->DeleteLocalRef(methodInfo.classID);
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
void AndroidJavaEngine::setBackgroundMusicVolume(float volume) {
|
||||
cocos2d::JniMethodInfo methodInfo;
|
||||
|
||||
if (! getJNIStaticMethodInfo(methodInfo, "setBackgroundMusicVolume", "(F)V")) {
|
||||
return ;
|
||||
}
|
||||
|
||||
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, volume);
|
||||
methodInfo.env->DeleteLocalRef(methodInfo.classID);
|
||||
}
|
||||
|
||||
float AndroidJavaEngine::getEffectsVolume() {
|
||||
cocos2d::JniMethodInfo methodInfo;
|
||||
jfloat ret = -1.0;
|
||||
|
||||
if (! getJNIStaticMethodInfo(methodInfo, "getEffectsVolume", "()F")) {
|
||||
return ret;
|
||||
}
|
||||
|
||||
ret = methodInfo.env->CallStaticFloatMethod(methodInfo.classID, methodInfo.methodID);
|
||||
methodInfo.env->DeleteLocalRef(methodInfo.classID);
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
void AndroidJavaEngine::setEffectsVolume(float volume) {
|
||||
cocos2d::JniMethodInfo methodInfo;
|
||||
|
||||
if (! getJNIStaticMethodInfo(methodInfo, "setEffectsVolume", "(F)V")) {
|
||||
return ;
|
||||
}
|
||||
|
||||
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, volume);
|
||||
methodInfo.env->DeleteLocalRef(methodInfo.classID);
|
||||
}
|
||||
|
||||
unsigned int AndroidJavaEngine::playEffect(const char* pszFilePath, bool bLoop,
|
||||
float pitch, float pan, float gain) {
|
||||
cocos2d::JniMethodInfo methodInfo;
|
||||
int ret = 0;
|
||||
std::string fullPath = CocosDenshion::android::getFullPathWithoutAssetsPrefix(pszFilePath);
|
||||
|
||||
if (! getJNIStaticMethodInfo(methodInfo, "playEffect", "(Ljava/lang/String;ZFFF)I")) {
|
||||
return ret;
|
||||
}
|
||||
|
||||
jstring stringArg = methodInfo.env->NewStringUTF(fullPath.c_str());
|
||||
ret = methodInfo.env->CallStaticIntMethod(methodInfo.classID,
|
||||
methodInfo.methodID,
|
||||
stringArg,
|
||||
bLoop,
|
||||
pitch, pan, gain);
|
||||
methodInfo.env->DeleteLocalRef(stringArg);
|
||||
methodInfo.env->DeleteLocalRef(methodInfo.classID);
|
||||
|
||||
return (unsigned int)ret;
|
||||
}
|
||||
|
||||
void AndroidJavaEngine::pauseEffect(unsigned int nSoundId) {
|
||||
cocos2d::JniMethodInfo methodInfo;
|
||||
|
||||
if (! getJNIStaticMethodInfo(methodInfo, "pauseEffect", "(I)V")) {
|
||||
return ;
|
||||
}
|
||||
|
||||
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, (int)nSoundId);
|
||||
methodInfo.env->DeleteLocalRef(methodInfo.classID);
|
||||
}
|
||||
|
||||
void AndroidJavaEngine::pauseAllEffects() {
|
||||
cocos2d::JniMethodInfo methodInfo;
|
||||
|
||||
if (! getJNIStaticMethodInfo(methodInfo, "pauseAllEffects", "()V")) {
|
||||
return ;
|
||||
}
|
||||
|
||||
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID);
|
||||
methodInfo.env->DeleteLocalRef(methodInfo.classID);
|
||||
}
|
||||
|
||||
void AndroidJavaEngine::resumeEffect(unsigned int nSoundId) {
|
||||
cocos2d::JniMethodInfo methodInfo;
|
||||
|
||||
if (! getJNIStaticMethodInfo(methodInfo, "resumeEffect", "(I)V")) {
|
||||
return ;
|
||||
}
|
||||
|
||||
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, (int)nSoundId);
|
||||
methodInfo.env->DeleteLocalRef(methodInfo.classID);
|
||||
}
|
||||
|
||||
void AndroidJavaEngine::resumeAllEffects() {
|
||||
cocos2d::JniMethodInfo methodInfo;
|
||||
|
||||
if (! getJNIStaticMethodInfo(methodInfo, "resumeAllEffects", "()V")) {
|
||||
return ;
|
||||
}
|
||||
|
||||
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID);
|
||||
methodInfo.env->DeleteLocalRef(methodInfo.classID);
|
||||
}
|
||||
|
||||
void AndroidJavaEngine::stopEffect(unsigned int nSoundId) {
|
||||
cocos2d::JniMethodInfo methodInfo;
|
||||
|
||||
if (! getJNIStaticMethodInfo(methodInfo, "stopEffect", "(I)V")) {
|
||||
return ;
|
||||
}
|
||||
|
||||
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, (int)nSoundId);
|
||||
methodInfo.env->DeleteLocalRef(methodInfo.classID);
|
||||
}
|
||||
|
||||
void AndroidJavaEngine::stopAllEffects() {
|
||||
cocos2d::JniMethodInfo methodInfo;
|
||||
|
||||
if (! getJNIStaticMethodInfo(methodInfo, "stopAllEffects", "()V")) {
|
||||
return ;
|
||||
}
|
||||
|
||||
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID);
|
||||
methodInfo.env->DeleteLocalRef(methodInfo.classID);
|
||||
}
|
||||
|
||||
void AndroidJavaEngine::preloadEffect(const char* pszFilePath) {
|
||||
cocos2d::JniMethodInfo methodInfo;
|
||||
std::string fullPath = CocosDenshion::android::getFullPathWithoutAssetsPrefix(pszFilePath);
|
||||
|
||||
if (! getJNIStaticMethodInfo(methodInfo, "preloadEffect", "(Ljava/lang/String;)V")) {
|
||||
return ;
|
||||
}
|
||||
|
||||
jstring stringArg = methodInfo.env->NewStringUTF(fullPath.c_str());
|
||||
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, stringArg);
|
||||
methodInfo.env->DeleteLocalRef(stringArg);
|
||||
methodInfo.env->DeleteLocalRef(methodInfo.classID);
|
||||
}
|
||||
|
||||
void AndroidJavaEngine::unloadEffect(const char* pszFilePath) {
|
||||
cocos2d::JniMethodInfo methodInfo;
|
||||
std::string fullPath = CocosDenshion::android::getFullPathWithoutAssetsPrefix(pszFilePath);
|
||||
|
||||
if (! getJNIStaticMethodInfo(methodInfo, "unloadEffect", "(Ljava/lang/String;)V")) {
|
||||
return ;
|
||||
}
|
||||
|
||||
jstring stringArg = methodInfo.env->NewStringUTF(fullPath.c_str());
|
||||
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, stringArg);
|
||||
methodInfo.env->DeleteLocalRef(stringArg);
|
||||
methodInfo.env->DeleteLocalRef(methodInfo.classID);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
#ifndef __CDDANDRIODANDROIDJAVAENGINE_H__
|
||||
#define __CDDANDRIODANDROIDJAVAENGINE_H__
|
||||
|
||||
#include "SimpleAudioEngine.h"
|
||||
#include "platform/android/jni/JniHelper.h"
|
||||
|
||||
namespace CocosDenshion {
|
||||
namespace android {
|
||||
class AndroidJavaEngine : public SimpleAudioEngine {
|
||||
~AndroidJavaEngine();
|
||||
|
||||
void preloadBackgroundMusic(const char* pszFilePath);
|
||||
void playBackgroundMusic(const char* pszFilePath, bool bLoop);
|
||||
void stopBackgroundMusic(bool bReleaseData);
|
||||
void pauseBackgroundMusic();
|
||||
void resumeBackgroundMusic();
|
||||
void rewindBackgroundMusic();
|
||||
bool willPlayBackgroundMusic();
|
||||
bool isBackgroundMusicPlaying();
|
||||
float getBackgroundMusicVolume();
|
||||
void setBackgroundMusicVolume(float volume);
|
||||
float getEffectsVolume();
|
||||
void setEffectsVolume(float volume);
|
||||
unsigned int playEffect(const char* pszFilePath, bool bLoop = false,
|
||||
float pitch = 1.0f, float pan = 0.0f, float gain = 1.0f);
|
||||
void pauseEffect(unsigned int nSoundId);
|
||||
void pauseAllEffects();
|
||||
void resumeEffect(unsigned int nSoundId);
|
||||
void resumeAllEffects();
|
||||
void stopEffect(unsigned int nSoundId);
|
||||
void stopAllEffects();
|
||||
void preloadEffect(const char* pszFilePath);
|
||||
void unloadEffect(const char* pszFilePath);
|
||||
|
||||
private :
|
||||
static bool getJNIStaticMethodInfo(cocos2d::JniMethodInfo &methodinfo,
|
||||
const char *methodName,
|
||||
const char *paramCode);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
#endif //__CDDANDRIODANDROIDJAVAENGINE_H__
|
|
@ -9,11 +9,11 @@
|
|||
#include <map>
|
||||
#include <vector>
|
||||
#include <dlfcn.h>
|
||||
#include "SLES/OpenSLES.h"
|
||||
#include "SLES/OpenSLES_Android.h"
|
||||
#include <SLES/OpenSLES.h>
|
||||
#include <SLES/OpenSLES_Android.h>
|
||||
#include <sys/types.h>
|
||||
#include "android/asset_manager.h"
|
||||
#include "android/asset_manager_jni.h"
|
||||
#include <android/asset_manager.h>
|
||||
#include <android/asset_manager_jni.h>
|
||||
#include <android/log.h>
|
||||
#include <jni/JniHelper.h>
|
||||
#include <dlfcn.h>
|
||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -1,242 +0,0 @@
|
|||
/*
|
||||
* Copyright (C) 2010 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef OPENSL_ES_ANDROID_H_
|
||||
#define OPENSL_ES_ANDROID_H_
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/*---------------------------------------------------------------------------*/
|
||||
/* Android common types */
|
||||
/*---------------------------------------------------------------------------*/
|
||||
|
||||
typedef sl_int64_t SLAint64; /* 64 bit signed integer */
|
||||
|
||||
|
||||
/*---------------------------------------------------------------------------*/
|
||||
/* Android Effect interface */
|
||||
/*---------------------------------------------------------------------------*/
|
||||
|
||||
extern SLAPIENTRY const SLInterfaceID SL_IID_ANDROIDEFFECT;
|
||||
|
||||
/** Android Effect interface methods */
|
||||
|
||||
struct SLAndroidEffectItf_;
|
||||
typedef const struct SLAndroidEffectItf_ * const * SLAndroidEffectItf;
|
||||
|
||||
struct SLAndroidEffectItf_ {
|
||||
|
||||
SLresult (*CreateEffect) (SLAndroidEffectItf self,
|
||||
SLInterfaceID effectImplementationId);
|
||||
|
||||
SLresult (*ReleaseEffect) (SLAndroidEffectItf self,
|
||||
SLInterfaceID effectImplementationId);
|
||||
|
||||
SLresult (*SetEnabled) (SLAndroidEffectItf self,
|
||||
SLInterfaceID effectImplementationId,
|
||||
SLboolean enabled);
|
||||
|
||||
SLresult (*IsEnabled) (SLAndroidEffectItf self,
|
||||
SLInterfaceID effectImplementationId,
|
||||
SLboolean *pEnabled);
|
||||
|
||||
SLresult (*SendCommand) (SLAndroidEffectItf self,
|
||||
SLInterfaceID effectImplementationId,
|
||||
SLuint32 command,
|
||||
SLuint32 commandSize,
|
||||
void *pCommandData,
|
||||
SLuint32 *replySize,
|
||||
void *pReplyData);
|
||||
};
|
||||
|
||||
|
||||
/*---------------------------------------------------------------------------*/
|
||||
/* Android Effect Send interface */
|
||||
/*---------------------------------------------------------------------------*/
|
||||
|
||||
extern SLAPIENTRY const SLInterfaceID SL_IID_ANDROIDEFFECTSEND;
|
||||
|
||||
/** Android Effect Send interface methods */
|
||||
|
||||
struct SLAndroidEffectSendItf_;
|
||||
typedef const struct SLAndroidEffectSendItf_ * const * SLAndroidEffectSendItf;
|
||||
|
||||
struct SLAndroidEffectSendItf_ {
|
||||
SLresult (*EnableEffectSend) (
|
||||
SLAndroidEffectSendItf self,
|
||||
SLInterfaceID effectImplementationId,
|
||||
SLboolean enable,
|
||||
SLmillibel initialLevel
|
||||
);
|
||||
SLresult (*IsEnabled) (
|
||||
SLAndroidEffectSendItf self,
|
||||
SLInterfaceID effectImplementationId,
|
||||
SLboolean *pEnable
|
||||
);
|
||||
SLresult (*SetDirectLevel) (
|
||||
SLAndroidEffectSendItf self,
|
||||
SLmillibel directLevel
|
||||
);
|
||||
SLresult (*GetDirectLevel) (
|
||||
SLAndroidEffectSendItf self,
|
||||
SLmillibel *pDirectLevel
|
||||
);
|
||||
SLresult (*SetSendLevel) (
|
||||
SLAndroidEffectSendItf self,
|
||||
SLInterfaceID effectImplementationId,
|
||||
SLmillibel sendLevel
|
||||
);
|
||||
SLresult (*GetSendLevel)(
|
||||
SLAndroidEffectSendItf self,
|
||||
SLInterfaceID effectImplementationId,
|
||||
SLmillibel *pSendLevel
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
/*---------------------------------------------------------------------------*/
|
||||
/* Android Effect Capabilities interface */
|
||||
/*---------------------------------------------------------------------------*/
|
||||
|
||||
extern SLAPIENTRY const SLInterfaceID SL_IID_ANDROIDEFFECTCAPABILITIES;
|
||||
|
||||
/** Android Effect Capabilities interface methods */
|
||||
|
||||
struct SLAndroidEffectCapabilitiesItf_;
|
||||
typedef const struct SLAndroidEffectCapabilitiesItf_ * const * SLAndroidEffectCapabilitiesItf;
|
||||
|
||||
struct SLAndroidEffectCapabilitiesItf_ {
|
||||
|
||||
SLresult (*QueryNumEffects) (SLAndroidEffectCapabilitiesItf self,
|
||||
SLuint32 *pNumSupportedEffects);
|
||||
|
||||
|
||||
SLresult (*QueryEffect) (SLAndroidEffectCapabilitiesItf self,
|
||||
SLuint32 index,
|
||||
SLInterfaceID *pEffectType,
|
||||
SLInterfaceID *pEffectImplementation,
|
||||
SLchar *pName,
|
||||
SLuint16 *pNameSize);
|
||||
};
|
||||
|
||||
|
||||
/*---------------------------------------------------------------------------*/
|
||||
/* Android Configuration interface */
|
||||
/*---------------------------------------------------------------------------*/
|
||||
extern SLAPIENTRY const SLInterfaceID SL_IID_ANDROIDCONFIGURATION;
|
||||
|
||||
/** Android Configuration interface methods */
|
||||
|
||||
struct SLAndroidConfigurationItf_;
|
||||
typedef const struct SLAndroidConfigurationItf_ * const * SLAndroidConfigurationItf;
|
||||
|
||||
struct SLAndroidConfigurationItf_ {
|
||||
|
||||
SLresult (*SetConfiguration) (SLAndroidConfigurationItf self,
|
||||
const SLchar *configKey,
|
||||
const void *pConfigValue,
|
||||
SLuint32 valueSize);
|
||||
|
||||
SLresult (*GetConfiguration) (SLAndroidConfigurationItf self,
|
||||
const SLchar *configKey,
|
||||
SLuint32 *pValueSize,
|
||||
void *pConfigValue
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
/*---------------------------------------------------------------------------*/
|
||||
/* Android Simple Buffer Queue Interface */
|
||||
/*---------------------------------------------------------------------------*/
|
||||
|
||||
extern SLAPIENTRY const SLInterfaceID SL_IID_ANDROIDSIMPLEBUFFERQUEUE;
|
||||
|
||||
struct SLAndroidSimpleBufferQueueItf_;
|
||||
typedef const struct SLAndroidSimpleBufferQueueItf_ * const * SLAndroidSimpleBufferQueueItf;
|
||||
|
||||
typedef void (/*SLAPIENTRY*/ *slAndroidSimpleBufferQueueCallback)(
|
||||
SLAndroidSimpleBufferQueueItf caller,
|
||||
void *pContext
|
||||
);
|
||||
|
||||
/** Android simple buffer queue state **/
|
||||
|
||||
typedef struct SLAndroidSimpleBufferQueueState_ {
|
||||
SLuint32 count;
|
||||
SLuint32 index;
|
||||
} SLAndroidSimpleBufferQueueState;
|
||||
|
||||
|
||||
struct SLAndroidSimpleBufferQueueItf_ {
|
||||
SLresult (*Enqueue) (
|
||||
SLAndroidSimpleBufferQueueItf self,
|
||||
const void *pBuffer,
|
||||
SLuint32 size
|
||||
);
|
||||
SLresult (*Clear) (
|
||||
SLAndroidSimpleBufferQueueItf self
|
||||
);
|
||||
SLresult (*GetState) (
|
||||
SLAndroidSimpleBufferQueueItf self,
|
||||
SLAndroidSimpleBufferQueueState *pState
|
||||
);
|
||||
SLresult (*RegisterCallback) (
|
||||
SLAndroidSimpleBufferQueueItf self,
|
||||
slAndroidSimpleBufferQueueCallback callback,
|
||||
void* pContext
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
/*---------------------------------------------------------------------------*/
|
||||
/* Android File Descriptor Data Locator */
|
||||
/*---------------------------------------------------------------------------*/
|
||||
|
||||
/** Addendum to Data locator macros */
|
||||
#define SL_DATALOCATOR_ANDROIDFD ((SLuint32) 0x800007BC)
|
||||
|
||||
#define SL_DATALOCATOR_ANDROIDFD_USE_FILE_SIZE ((SLAint64) 0xFFFFFFFFFFFFFFFFll)
|
||||
|
||||
/** File Descriptor-based data locator definition, locatorType must be SL_DATALOCATOR_ANDROIDFD */
|
||||
typedef struct SLDataLocator_AndroidFD_ {
|
||||
SLuint32 locatorType;
|
||||
SLint32 fd;
|
||||
SLAint64 offset;
|
||||
SLAint64 length;
|
||||
} SLDataLocator_AndroidFD;
|
||||
|
||||
|
||||
/*---------------------------------------------------------------------------*/
|
||||
/* Android Android Simple Buffer Queue Data Locator */
|
||||
/*---------------------------------------------------------------------------*/
|
||||
|
||||
/** Addendum to Data locator macros */
|
||||
#define SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE ((SLuint32) 0x800007BD)
|
||||
|
||||
/** BufferQueue-based data locator definition where locatorType must be SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE*/
|
||||
typedef struct SLDataLocator_AndroidSimpleBufferQueue {
|
||||
SLuint32 locatorType;
|
||||
SLuint32 numBuffers;
|
||||
} SLDataLocator_AndroidSimpleBufferQueue;
|
||||
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif /* __cplusplus */
|
||||
|
||||
#endif /* OPENSL_ES_ANDROID_H_ */
|
|
@ -1,69 +0,0 @@
|
|||
/*
|
||||
* Copyright (C) 2010 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef OPENSL_ES_ANDROIDCONFIGURATION_H_
|
||||
#define OPENSL_ES_ANDROIDCONFIGURATION_H_
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
|
||||
/*---------------------------------------------------------------------------*/
|
||||
/* Android AudioRecorder configuration */
|
||||
/*---------------------------------------------------------------------------*/
|
||||
|
||||
/** Audio recording preset */
|
||||
/** Audio recording preset key */
|
||||
#define SL_ANDROID_KEY_RECORDING_PRESET ((const SLchar*) "androidRecordingPreset")
|
||||
/** Audio recording preset values */
|
||||
/** preset "none" cannot be set, it is used to indicate the current settings
|
||||
* do not match any of the presets. */
|
||||
#define SL_ANDROID_RECORDING_PRESET_NONE ((SLuint32) 0x00000000)
|
||||
/** generic recording configuration on the platform */
|
||||
#define SL_ANDROID_RECORDING_PRESET_GENERIC ((SLuint32) 0x00000001)
|
||||
/** uses the microphone audio source with the same orientation as the camera
|
||||
* if available, the main device microphone otherwise */
|
||||
#define SL_ANDROID_RECORDING_PRESET_CAMCORDER ((SLuint32) 0x00000002)
|
||||
/** uses the main microphone tuned for voice recognition */
|
||||
#define SL_ANDROID_RECORDING_PRESET_VOICE_RECOGNITION ((SLuint32) 0x00000003)
|
||||
|
||||
/*---------------------------------------------------------------------------*/
|
||||
/* Android AudioPlayer configuration */
|
||||
/*---------------------------------------------------------------------------*/
|
||||
|
||||
/** Audio playback stream type */
|
||||
/** Audio playback stream type key */
|
||||
#define SL_ANDROID_KEY_STREAM_TYPE ((const SLchar*) "androidPlaybackStreamType")
|
||||
|
||||
/** Audio playback stream type values */
|
||||
/* same as android.media.AudioManager.STREAM_VOICE_CALL */
|
||||
#define SL_ANDROID_STREAM_VOICE ((SLint32) 0x00000000)
|
||||
/* same as android.media.AudioManager.STREAM_SYSTEM */
|
||||
#define SL_ANDROID_STREAM_SYSTEM ((SLint32) 0x00000001)
|
||||
/* same as android.media.AudioManager.STREAM_RING */
|
||||
#define SL_ANDROID_STREAM_RING ((SLint32) 0x00000002)
|
||||
/* same as android.media.AudioManager.STREAM_MUSIC */
|
||||
#define SL_ANDROID_STREAM_MEDIA ((SLint32) 0x00000003)
|
||||
/* same as android.media.AudioManager.STREAM_ALARM */
|
||||
#define SL_ANDROID_STREAM_ALARM ((SLint32) 0x00000004)
|
||||
/* same as android.media.AudioManager.STREAM_NOTIFICATION */
|
||||
#define SL_ANDROID_STREAM_NOTIFICATION ((SLint32) 0x00000005)
|
||||
|
||||
|
||||
|
||||
}
|
||||
#endif /* __cplusplus */
|
||||
|
||||
#endif /* OPENSL_ES_ANDROIDCONFIGURATION_H_ */
|
|
@ -1,52 +0,0 @@
|
|||
/*
|
||||
* Copyright (c) 2007-2009 The Khronos Group Inc.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and /or associated documentation files (the "Materials "), to
|
||||
* deal in the Materials without restriction, including without limitation the
|
||||
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
||||
* sell copies of the Materials, and to permit persons to whom the Materials are
|
||||
* 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 Materials.
|
||||
*
|
||||
* THE MATERIALS ARE 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 MATERIALS OR THE USE OR OTHER DEALINGS IN THE
|
||||
* MATERIALS.
|
||||
*
|
||||
* OpenSLES_Platform.h - OpenSL ES version 1.0
|
||||
*
|
||||
*/
|
||||
|
||||
/****************************************************************************/
|
||||
/* NOTE: This file contains definitions for the base types and the */
|
||||
/* SLAPIENTRY macro. This file **WILL NEED TO BE EDITED** to provide */
|
||||
/* the correct definitions specific to the platform being used. */
|
||||
/****************************************************************************/
|
||||
|
||||
#ifndef _OPENSLES_PLATFORM_H_
|
||||
#define _OPENSLES_PLATFORM_H_
|
||||
|
||||
typedef unsigned char sl_uint8_t;
|
||||
typedef signed char sl_int8_t;
|
||||
typedef unsigned short sl_uint16_t;
|
||||
typedef signed short sl_int16_t;
|
||||
typedef unsigned long sl_uint32_t;
|
||||
typedef signed long sl_int32_t;
|
||||
typedef long long sl_int64_t;
|
||||
|
||||
#ifndef SLAPIENTRY
|
||||
#ifdef __GNUC__
|
||||
#define SLAPIENTRY /* override per-platform */
|
||||
#else
|
||||
#define SLAPIENTRY __declspec(dllimport)
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#endif /* _OPENSLES_PLATFORM_H_ */
|
|
@ -1,140 +0,0 @@
|
|||
/*
|
||||
* Copyright (C) 2010 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
|
||||
#ifndef ANDROID_ASSET_MANAGER_H
|
||||
#define ANDROID_ASSET_MANAGER_H
|
||||
|
||||
#include <sys/types.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
struct AAssetManager;
|
||||
typedef struct AAssetManager AAssetManager;
|
||||
|
||||
struct AAssetDir;
|
||||
typedef struct AAssetDir AAssetDir;
|
||||
|
||||
struct AAsset;
|
||||
typedef struct AAsset AAsset;
|
||||
|
||||
/* Available modes for opening assets */
|
||||
enum {
|
||||
AASSET_MODE_UNKNOWN = 0,
|
||||
AASSET_MODE_RANDOM = 1,
|
||||
AASSET_MODE_STREAMING = 2,
|
||||
AASSET_MODE_BUFFER = 3
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Open the named directory within the asset hierarchy. The directory can then
|
||||
* be inspected with the AAssetDir functions. To open the top-level directory,
|
||||
* pass in "" as the dirName.
|
||||
*
|
||||
* The object returned here should be freed by calling AAssetDir_close().
|
||||
*/
|
||||
AAssetDir* AAssetManager_openDir(AAssetManager* mgr, const char* dirName);
|
||||
|
||||
/**
|
||||
* Open an asset.
|
||||
*
|
||||
* The object returned here should be freed by calling AAsset_close().
|
||||
*/
|
||||
AAsset* AAssetManager_open(AAssetManager* mgr, const char* filename, int mode);
|
||||
|
||||
/**
|
||||
* Iterate over the files in an asset directory. A NULL string is returned
|
||||
* when all the file names have been returned.
|
||||
*
|
||||
* The returned file name is suitable for passing to AAssetManager_open().
|
||||
*
|
||||
* The string returned here is owned by the AssetDir implementation and is not
|
||||
* guaranteed to remain valid if any other calls are made on this AAssetDir
|
||||
* instance.
|
||||
*/
|
||||
const char* AAssetDir_getNextFileName(AAssetDir* assetDir);
|
||||
|
||||
/**
|
||||
* Reset the iteration state of AAssetDir_getNextFileName() to the beginning.
|
||||
*/
|
||||
void AAssetDir_rewind(AAssetDir* assetDir);
|
||||
|
||||
/**
|
||||
* Close an opened AAssetDir, freeing any related resources.
|
||||
*/
|
||||
void AAssetDir_close(AAssetDir* assetDir);
|
||||
|
||||
/**
|
||||
* Attempt to read 'count' bytes of data from the current offset.
|
||||
*
|
||||
* Returns the number of bytes read, zero on EOF, or < 0 on error.
|
||||
*/
|
||||
int AAsset_read(AAsset* asset, void* buf, size_t count);
|
||||
|
||||
/**
|
||||
* Seek to the specified offset within the asset data. 'whence' uses the
|
||||
* same constants as lseek()/fseek().
|
||||
*
|
||||
* Returns the new position on success, or (off_t) -1 on error.
|
||||
*/
|
||||
off_t AAsset_seek(AAsset* asset, off_t offset, int whence);
|
||||
|
||||
/**
|
||||
* Close the asset, freeing all associated resources.
|
||||
*/
|
||||
void AAsset_close(AAsset* asset);
|
||||
|
||||
/**
|
||||
* Get a pointer to a buffer holding the entire contents of the assset.
|
||||
*
|
||||
* Returns NULL on failure.
|
||||
*/
|
||||
const void* AAsset_getBuffer(AAsset* asset);
|
||||
|
||||
/**
|
||||
* Report the total size of the asset data.
|
||||
*/
|
||||
off_t AAsset_getLength(AAsset* asset);
|
||||
|
||||
/**
|
||||
* Report the total amount of asset data that can be read from the current position.
|
||||
*/
|
||||
off_t AAsset_getRemainingLength(AAsset* asset);
|
||||
|
||||
/**
|
||||
* Open a new file descriptor that can be used to read the asset data.
|
||||
*
|
||||
* Returns < 0 if direct fd access is not possible (for example, if the asset is
|
||||
* compressed).
|
||||
*/
|
||||
int AAsset_openFileDescriptor(AAsset* asset, off_t* outStart, off_t* outLength);
|
||||
|
||||
/**
|
||||
* Returns whether this asset's internal buffer is allocated in ordinary RAM (i.e. not
|
||||
* mmapped).
|
||||
*/
|
||||
int AAsset_isAllocated(AAsset* asset);
|
||||
|
||||
|
||||
|
||||
#ifdef __cplusplus
|
||||
};
|
||||
#endif
|
||||
|
||||
#endif // ANDROID_ASSET_MANAGER_H
|
|
@ -1,40 +0,0 @@
|
|||
/*
|
||||
* Copyright (C) 2010 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
|
||||
#ifndef ANDROID_ASSET_MANAGER_JNI_H
|
||||
#define ANDROID_ASSET_MANAGER_JNI_H
|
||||
|
||||
#include "asset_manager.h"
|
||||
#include <jni.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/**
|
||||
* Given a Dalvik AssetManager object, obtain the corresponding native AAssetManager
|
||||
* object. Note that the caller is responsible for obtaining and holding a VM reference
|
||||
* to the jobject to prevent its being garbage collected while the native object is
|
||||
* in use.
|
||||
*/
|
||||
AAssetManager* AAssetManager_fromJava(JNIEnv* env, jobject assetManager);
|
||||
|
||||
#ifdef __cplusplus
|
||||
};
|
||||
#endif
|
||||
|
||||
#endif // ANDROID_ASSET_MANAGER_JNI_H
|
|
@ -0,0 +1,35 @@
|
|||
#include "cddandroidOpenSLEngine.h"
|
||||
|
||||
namespace CocosDenshion {
|
||||
namespace android {
|
||||
OpenSLEngine::~OpenSLEngine() {
|
||||
}
|
||||
|
||||
void OpenSLEngine::preloadBackgroundMusic(const char* pszFilePath) { }
|
||||
void OpenSLEngine::playBackgroundMusic(const char* pszFilePath, bool bLoop) { }
|
||||
void OpenSLEngine::stopBackgroundMusic(bool bReleaseData) { }
|
||||
void OpenSLEngine::pauseBackgroundMusic() { }
|
||||
void OpenSLEngine::resumeBackgroundMusic() { }
|
||||
void OpenSLEngine::rewindBackgroundMusic() { }
|
||||
bool OpenSLEngine::willPlayBackgroundMusic() { }
|
||||
bool OpenSLEngine::isBackgroundMusicPlaying() { }
|
||||
float OpenSLEngine::getBackgroundMusicVolume() { }
|
||||
void OpenSLEngine::setBackgroundMusicVolume(float volume) { }
|
||||
float OpenSLEngine::getEffectsVolume() { }
|
||||
void OpenSLEngine::setEffectsVolume(float volume) { }
|
||||
unsigned int OpenSLEngine::playEffect(const char* pszFilePath,
|
||||
bool bLoop,
|
||||
float pitch, float pan,
|
||||
float gain) {
|
||||
}
|
||||
void OpenSLEngine::pauseEffect(unsigned int nSoundId) { }
|
||||
void OpenSLEngine::pauseAllEffects() { }
|
||||
void OpenSLEngine::resumeEffect(unsigned int nSoundId) { }
|
||||
void OpenSLEngine::resumeAllEffects() { }
|
||||
void OpenSLEngine::stopEffect(unsigned int nSoundId) { }
|
||||
void OpenSLEngine::stopAllEffects() { }
|
||||
void OpenSLEngine::preloadEffect(const char* pszFilePath) { }
|
||||
void OpenSLEngine::unloadEffect(const char* pszFilePath) { }
|
||||
|
||||
}
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
#ifndef __CDDANDROIDOPENSLENGINE_H__
|
||||
#define __CDDANDROIDOPENSLENGINE_H__
|
||||
|
||||
#include "SimpleAudioEngine.h"
|
||||
|
||||
namespace CocosDenshion {
|
||||
namespace android {
|
||||
class OpenSLEngine : public SimpleAudioEngine {
|
||||
~OpenSLEngine();
|
||||
|
||||
void preloadBackgroundMusic(const char* pszFilePath);
|
||||
void playBackgroundMusic(const char* pszFilePath, bool bLoop);
|
||||
void stopBackgroundMusic(bool bReleaseData);
|
||||
void pauseBackgroundMusic();
|
||||
void resumeBackgroundMusic();
|
||||
void rewindBackgroundMusic();
|
||||
bool willPlayBackgroundMusic();
|
||||
bool isBackgroundMusicPlaying();
|
||||
float getBackgroundMusicVolume();
|
||||
void setBackgroundMusicVolume(float volume);
|
||||
float getEffectsVolume();
|
||||
void setEffectsVolume(float volume);
|
||||
unsigned int playEffect(const char* pszFilePath,
|
||||
bool bLoop = false,
|
||||
float pitch = 1.0f, float pan = 0.0f,
|
||||
float gain = 1.0f);
|
||||
void pauseEffect(unsigned int nSoundId);
|
||||
void pauseAllEffects();
|
||||
void resumeEffect(unsigned int nSoundId);
|
||||
void resumeAllEffects();
|
||||
void stopEffect(unsigned int nSoundId);
|
||||
void stopAllEffects();
|
||||
void preloadEffect(const char* pszFilePath);
|
||||
void unloadEffect(const char* pszFilePath);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
#endif //__CDDANDROIDOPENSLENGINE_H__
|
|
@ -84,8 +84,11 @@ public:
|
|||
*/
|
||||
static void end();
|
||||
|
||||
protected:
|
||||
SimpleAudioEngine();
|
||||
~SimpleAudioEngine();
|
||||
virtual ~SimpleAudioEngine();
|
||||
|
||||
public:
|
||||
|
||||
virtual long getClassTypeInfo() {
|
||||
return getHashCodeByString(typeid(CocosDenshion::SimpleAudioEngine).name());
|
||||
|
@ -95,47 +98,47 @@ public:
|
|||
@brief Preload background music
|
||||
@param pszFilePath The path of the background music file.
|
||||
*/
|
||||
void preloadBackgroundMusic(const char* pszFilePath);
|
||||
virtual void preloadBackgroundMusic(const char* pszFilePath);
|
||||
|
||||
/**
|
||||
@brief Play background music
|
||||
@param pszFilePath The path of the background music file,or the FileName of T_SoundResInfo
|
||||
@param bLoop Whether the background music loop or not
|
||||
*/
|
||||
void playBackgroundMusic(const char* pszFilePath, bool bLoop = false);
|
||||
virtual void playBackgroundMusic(const char* pszFilePath, bool bLoop = false);
|
||||
|
||||
/**
|
||||
@brief Stop playing background music
|
||||
@param bReleaseData If release the background music data or not.As default value is false
|
||||
*/
|
||||
void stopBackgroundMusic(bool bReleaseData = false);
|
||||
virtual void stopBackgroundMusic(bool bReleaseData = false);
|
||||
|
||||
/**
|
||||
@brief Pause playing background music
|
||||
*/
|
||||
void pauseBackgroundMusic();
|
||||
virtual void pauseBackgroundMusic();
|
||||
|
||||
/**
|
||||
@brief Resume playing background music
|
||||
*/
|
||||
void resumeBackgroundMusic();
|
||||
virtual void resumeBackgroundMusic();
|
||||
|
||||
/**
|
||||
@brief Rewind playing background music
|
||||
*/
|
||||
void rewindBackgroundMusic();
|
||||
virtual void rewindBackgroundMusic();
|
||||
|
||||
/**
|
||||
@brief Indicates whether any background music can be played or not.
|
||||
@return <i>true</i> if background music can be played, otherwise <i>false</i>.
|
||||
*/
|
||||
bool willPlayBackgroundMusic();
|
||||
virtual bool willPlayBackgroundMusic();
|
||||
|
||||
/**
|
||||
@brief Indicates whether the background music is playing
|
||||
@return <i>true</i> if the background music is playing, otherwise <i>false</i>
|
||||
*/
|
||||
bool isBackgroundMusicPlaying();
|
||||
virtual bool isBackgroundMusicPlaying();
|
||||
|
||||
//
|
||||
// properties
|
||||
|
@ -144,24 +147,24 @@ public:
|
|||
/**
|
||||
@brief The volume of the background music within the range of 0.0 as the minimum and 1.0 as the maximum.
|
||||
*/
|
||||
float getBackgroundMusicVolume();
|
||||
virtual float getBackgroundMusicVolume();
|
||||
|
||||
/**
|
||||
@brief Set the volume of background music
|
||||
@param volume must be within the range of 0.0 as the minimum and 1.0 as the maximum.
|
||||
*/
|
||||
void setBackgroundMusicVolume(float volume);
|
||||
virtual void setBackgroundMusicVolume(float volume);
|
||||
|
||||
/**
|
||||
@brief The volume of the effects within the range of 0.0 as the minimum and 1.0 as the maximum.
|
||||
*/
|
||||
float getEffectsVolume();
|
||||
virtual float getEffectsVolume();
|
||||
|
||||
/**
|
||||
@brief Set the volume of sound effects
|
||||
@param volume must be within the range of 0.0 as the minimum and 1.0 as the maximum.
|
||||
*/
|
||||
void setEffectsVolume(float volume);
|
||||
virtual void setEffectsVolume(float volume);
|
||||
|
||||
//
|
||||
// for sound effects
|
||||
|
@ -179,57 +182,56 @@ public:
|
|||
- no pitch effect on Samsung Galaxy S2 with OpenSL backend enabled;
|
||||
- no pitch/pan/gain on emscrippten, win32, marmalade.
|
||||
*/
|
||||
unsigned int playEffect(const char* pszFilePath, bool bLoop = false,
|
||||
float pitch = 1.0f, float pan = 0.0f, float gain = 1.0f);
|
||||
virtual unsigned int playEffect(const char* pszFilePath, bool bLoop = false,
|
||||
float pitch = 1.0f, float pan = 0.0f, float gain = 1.0f);
|
||||
|
||||
/**
|
||||
@brief Pause playing sound effect
|
||||
@param nSoundId The return value of function playEffect
|
||||
*/
|
||||
void pauseEffect(unsigned int nSoundId);
|
||||
virtual void pauseEffect(unsigned int nSoundId);
|
||||
|
||||
/**
|
||||
@brief Pause all playing sound effect
|
||||
*/
|
||||
void pauseAllEffects();
|
||||
virtual void pauseAllEffects();
|
||||
|
||||
/**
|
||||
@brief Resume playing sound effect
|
||||
@param nSoundId The return value of function playEffect
|
||||
*/
|
||||
void resumeEffect(unsigned int nSoundId);
|
||||
virtual void resumeEffect(unsigned int nSoundId);
|
||||
|
||||
/**
|
||||
@brief Resume all playing sound effect
|
||||
*/
|
||||
void resumeAllEffects();
|
||||
virtual void resumeAllEffects();
|
||||
|
||||
/**
|
||||
@brief Stop playing sound effect
|
||||
@param nSoundId The return value of function playEffect
|
||||
*/
|
||||
void stopEffect(unsigned int nSoundId);
|
||||
virtual void stopEffect(unsigned int nSoundId);
|
||||
|
||||
/**
|
||||
@brief Stop all playing sound effects
|
||||
*/
|
||||
void stopAllEffects();
|
||||
virtual void stopAllEffects();
|
||||
|
||||
/**
|
||||
@brief preload a compressed audio file
|
||||
@details the compressed audio will be decoded to wave, then written into an internal buffer in SimpleAudioEngine
|
||||
@param pszFilePath The path of the effect file
|
||||
*/
|
||||
void preloadEffect(const char* pszFilePath);
|
||||
virtual void preloadEffect(const char* pszFilePath);
|
||||
|
||||
/**
|
||||
@brief unload the preloaded effect from internal buffer
|
||||
@param pszFilePath The path of the effect file
|
||||
*/
|
||||
void unloadEffect(const char* pszFilePath);
|
||||
virtual void unloadEffect(const char* pszFilePath);
|
||||
};
|
||||
|
||||
} // end of namespace CocosDenshion
|
||||
|
||||
#endif // _SIMPLE_AUDIO_ENGINE_H_
|
||||
|
||||
|
|
|
@ -94,7 +94,6 @@
|
|||
</option>
|
||||
<option id="sbi.gnu.cpp.linker.option.frameworks_lflags.cpp.181465864" name="Tizen-Frameworks-Other-Lflags" superClass="sbi.gnu.cpp.linker.option.frameworks_lflags.cpp" valueType="stringList">
|
||||
<listOptionValue builtIn="false" value="--sysroot="${SBI_SYSROOT}""/>
|
||||
<listOptionValue builtIn="false" value="-Xlinker -rpath="/opt/usr/apps/null/lib""/>
|
||||
</option>
|
||||
</tool>
|
||||
<tool command="i386-linux-gnueabi-as.exe" id="org.tizen.nativeapp.tool.sbi.gnu.assembler.base.165476943" name="Assembler" superClass="org.tizen.nativeapp.tool.sbi.gnu.assembler.base">
|
||||
|
@ -205,7 +204,6 @@
|
|||
</option>
|
||||
<option id="sbi.gnu.cpp.linker.option.frameworks_lflags.cpp.557112687" name="Tizen-Frameworks-Other-Lflags" superClass="sbi.gnu.cpp.linker.option.frameworks_lflags.cpp" valueType="stringList">
|
||||
<listOptionValue builtIn="false" value="--sysroot="${SBI_SYSROOT}""/>
|
||||
<listOptionValue builtIn="false" value="-Xlinker -rpath="/opt/usr/apps/null/lib""/>
|
||||
</option>
|
||||
</tool>
|
||||
<tool command="arm-linux-gnueabi-as.exe" id="org.tizen.nativeapp.tool.sbi.gnu.assembler.base.1047247012" name="Assembler" superClass="org.tizen.nativeapp.tool.sbi.gnu.assembler.base">
|
||||
|
|
|
@ -7,6 +7,7 @@
|
|||
<buildSpec>
|
||||
<buildCommand>
|
||||
<name>org.eclipse.cdt.managedbuilder.core.genmakebuilder</name>
|
||||
<triggers>clean,full,incremental,</triggers>
|
||||
<arguments>
|
||||
<dictionary>
|
||||
<key>?name?</key>
|
||||
|
@ -42,7 +43,7 @@
|
|||
</dictionary>
|
||||
<dictionary>
|
||||
<key>org.eclipse.cdt.make.core.enableAutoBuild</key>
|
||||
<value>true</value>
|
||||
<value>false</value>
|
||||
</dictionary>
|
||||
<dictionary>
|
||||
<key>org.eclipse.cdt.make.core.enableCleanBuild</key>
|
||||
|
|
85
Makefile
85
Makefile
|
@ -1,31 +1,70 @@
|
|||
PLATFORM ?= linux
|
||||
|
||||
define MAKE_TARGETS
|
||||
+$(MAKE) -C external/chipmunk/proj.$(PLATFORM) $@
|
||||
+$(MAKE) -C external/Box2D/proj.$(PLATFORM) $@
|
||||
+$(MAKE) -C CocosDenshion/proj.$(PLATFORM) $@
|
||||
+$(MAKE) -C extensions/proj.$(PLATFORM) $@
|
||||
+$(MAKE) -C cocos2dx/proj.$(PLATFORM) $@
|
||||
+$(MAKE) -C scripting/lua/proj.$(PLATFORM) $@
|
||||
+$(MAKE) -C samples/Cpp/HelloCpp/proj.$(PLATFORM) $@
|
||||
+$(MAKE) -C samples/Cpp/TestCpp/proj.$(PLATFORM) $@
|
||||
+$(MAKE) -C samples/Cpp/SimpleGame/proj.$(PLATFORM) $@
|
||||
endef
|
||||
all:
|
||||
|
||||
chipmunk:
|
||||
$(MAKE) -C external/chipmunk/proj.$(PLATFORM)
|
||||
chipmunk-clean:
|
||||
$(MAKE) -C external/chipmunk/proj.$(PLATFORM) clean
|
||||
|
||||
box2d:
|
||||
$(MAKE) -C external/Box2D/proj.$(PLATFORM)
|
||||
box2d-clean:
|
||||
$(MAKE) -C external/Box2D/proj.$(PLATFORM) clean
|
||||
|
||||
libextensions: cocosdenshion chipmunk box2d
|
||||
$(MAKE) -C extensions/proj.$(PLATFORM)
|
||||
libextensions-clean:
|
||||
$(MAKE) -C extensions/proj.$(PLATFORM) clean
|
||||
|
||||
libcocos2dx: libextensions
|
||||
$(MAKE) -C cocos2dx/proj.$(PLATFORM)
|
||||
libcocos2dx-clean:
|
||||
$(MAKE) -C cocos2dx/proj.$(PLATFORM) clean
|
||||
|
||||
cocosdenshion: libcocos2dx
|
||||
$(MAKE) -C CocosDenshion/proj.$(PLATFORM)
|
||||
cocosdenshion-clean:
|
||||
$(MAKE) -C CocosDenshion/proj.$(PLATFORM) clean
|
||||
|
||||
lua: libextensions
|
||||
$(MAKE) -C scripting/lua/proj.$(PLATFORM)
|
||||
lua-clean:
|
||||
$(MAKE) -C scripting/lua/proj.$(PLATFORM) clean
|
||||
|
||||
hellocpp: libcocos2dx
|
||||
$(MAKE) -C samples/Cpp/HelloCpp/proj.$(PLATFORM)
|
||||
hellocpp-clean:
|
||||
$(MAKE) -C samples/Cpp/HelloCpp/proj.$(PLATFORM) clean
|
||||
|
||||
testcpp: libcocos2dx libextensions
|
||||
$(MAKE) -C samples/Cpp/TestCpp/proj.$(PLATFORM)
|
||||
testcpp-clean:
|
||||
$(MAKE) -C samples/Cpp/TestCpp/proj.$(PLATFORM) clean
|
||||
|
||||
simplegame: libcocos2dx
|
||||
$(MAKE) -C samples/Cpp/SimpleGame/proj.$(PLATFORM)
|
||||
simplegame-clean:
|
||||
$(MAKE) -C samples/Cpp/SimpleGame/proj.$(PLATFORM) clean
|
||||
|
||||
all: box2d cocosdenshion libextensions libcocos2dx lua hellocpp testcpp simplegame
|
||||
clean: libcocos2dx-clean box2d-clean chipmunk-clean cocosdenshion-clean libextensions-clean lua-clean hellocpp-clean testcpp-clean simplegame-clean
|
||||
|
||||
# Haven't yet got the lua projects working with emscripten
|
||||
ifneq ($(PLATFORM),emscripten)
|
||||
define MAKE_LUA
|
||||
+$(MAKE) -C samples/Lua/HelloLua/proj.$(PLATFORM) $@
|
||||
+$(MAKE) -C samples/Lua/TestLua/proj.$(PLATFORM) $@
|
||||
endef
|
||||
|
||||
hellolua: libcocos2dx lua
|
||||
$(MAKE) -C samples/Lua/HelloLua/proj.$(PLATFORM)
|
||||
hellolua-clean:
|
||||
$(MAKE) -C samples/Lua/HelloLua/proj.$(PLATFORM) clean
|
||||
|
||||
testlua: libcocos2dx lua
|
||||
$(MAKE) -C samples/Lua/TestLua/proj.$(PLATFORM)
|
||||
testlua-clean:
|
||||
$(MAKE) -C samples/Lua/TestLua/proj.$(PLATFORM) clean
|
||||
|
||||
all: hellolua testlua
|
||||
clean: hellolua-clean testlua-clean
|
||||
endif
|
||||
|
||||
all:
|
||||
$(call MAKE_TARGETS,all)
|
||||
$(call MAKE_LUA,all)
|
||||
|
||||
clean:
|
||||
$(call MAKE_TARGETS,clean)
|
||||
$(call MAKE_LUA,clean)
|
||||
|
||||
.PHONY: all clean
|
||||
|
|
|
@ -0,0 +1,149 @@
|
|||
<img src="http://www.cocos2d-x.org/attachments/801/cocos2dx_portrait.png" width=200>
|
||||
|
||||
|
||||
cocos2d-x
|
||||
=========
|
||||
|
||||
[![Build Status](https://travis-ci.org/cocos2d/cocos2d-x.png?branch=master)](https://travis-ci.org/cocos2d/cocos2d-x)
|
||||
|
||||
[cocos2d-x][1] is a multi-platform framework for building 2d games, interactive books, demos and other graphical applications.
|
||||
It is based on [cocos2d-iphone][2], but instead of using Objective-C, it uses C++.
|
||||
It works on iOS, Android, OS X, Windows, Linux, Emscripten, Google Native Client, BlackBerry and Tizen.
|
||||
|
||||
cocos2d-x is:
|
||||
|
||||
* Fast
|
||||
* Free
|
||||
* Easy to use
|
||||
* Community Supported
|
||||
|
||||
|
||||
|
||||
How to start a new game
|
||||
-----------------------
|
||||
|
||||
1. Download the code from [Github][3] or from [cocos2d download site][4]
|
||||
|
||||
2. Run the `create-multi-platform-projects.py` script
|
||||
|
||||
Example:
|
||||
|
||||
$ cd cocos2d-x
|
||||
$ ./create-multi-platform-projects.py -p mygame -k com.your_company.mygame -l cpp
|
||||
$ cd projects/mygame
|
||||
|
||||
|
||||
Main features
|
||||
-------------
|
||||
* Scene management (workflow)
|
||||
* Transitions between scenes
|
||||
* Sprites and Sprite Sheets
|
||||
* Effects: Lens, Ripple, Waves, Liquid, etc.
|
||||
* Actions (behaviours):
|
||||
* Trasformation Actions: Move, Rotate, Scale, Fade, Tint, etc.
|
||||
* Composable actions: Sequence, Spawn, Repeat, Reverse
|
||||
* Ease Actions: Exp, Sin, Cubic, Elastic, etc.
|
||||
* Misc actions: CallFunc, OrbitCamera, Follow, Tween
|
||||
* Basic menus and buttons
|
||||
* Integrated with physics engines: [Box2d][5] and [Chipmunk][6]
|
||||
* Particle system
|
||||
* Skeleton Animations: [Spine][7] and Armature support
|
||||
* Fonts:
|
||||
* Fast font rendering using Fixed and Variable width fonts
|
||||
* Support for .ttf fonts
|
||||
* Tile Map support: Orthogonal, Isometric and Hexagonal
|
||||
* Parallax scrolling
|
||||
* Motion Streak
|
||||
* Render To Texture
|
||||
* Touch/Accelerometer on mobile devices
|
||||
* Touch/Mouse/Keyboard on desktop
|
||||
* Sound Engine support (CocosDenshion library) based on OpenAL
|
||||
* Integrated Slow motion/Fast forward
|
||||
* Fast and compressed textures: PVR compressed and uncompressed textures, ETC1 compressed textures, and more
|
||||
* Resolution Independence
|
||||
* Language: C++, with Lua and JavaScript bindings
|
||||
* Open Source Commercial Friendly: Compatible with open and closed source projects
|
||||
* OpenGL ES 2.0 (mobile) / OpenGL 2.1 (desktop) based
|
||||
|
||||
Build Requirements
|
||||
------------------
|
||||
|
||||
* Mac OS X 10.7+, Xcode 4.6+
|
||||
* or Ubuntu 13.04+
|
||||
* or Windows 7+, VS 2012+
|
||||
|
||||
|
||||
Runtime Requirements
|
||||
--------------------
|
||||
* iOS 5.0+ for iPhone / iPad games
|
||||
* Android 2.3+ for Android games
|
||||
* OS X v10.6+ for Mac games
|
||||
* Windows 7+ for Win games
|
||||
* Tizen 2.2+
|
||||
* Emscripten
|
||||
* Google Native Client
|
||||
|
||||
|
||||
Running Tests
|
||||
--------------------
|
||||
|
||||
Select the test you want from Xcode Scheme chooser.
|
||||
|
||||
* For OS X / iOS
|
||||
|
||||
```
|
||||
$ cd cocos2d-x/samples
|
||||
$ open samples.xcodeproj
|
||||
```
|
||||
|
||||
* For Linux
|
||||
|
||||
```
|
||||
$ cd cocos2d-x
|
||||
$ ./make-all-linux-projects.sh
|
||||
```
|
||||
|
||||
or open the `cocos2d-x/cocos2dx-qt5.pro` file using QT Creator 5.
|
||||
|
||||
* For Windows
|
||||
|
||||
Open the `cocos2d-x/cocos2d-win32.vc2012.sln`
|
||||
|
||||
* For Android
|
||||
|
||||
```
|
||||
$ cd cocos2d-x/samples/Cpp/HelloCpp/proj.android
|
||||
$ ./build_native.sh
|
||||
```
|
||||
|
||||
Import HelloCpp Android project using Eclipse(released with Android SDK). The path to be imported is `cocos2d-x/samples/Cpp/HelloCpp/proj.android`.
|
||||
|
||||
|
||||
Contributing to the Project
|
||||
--------------------------------
|
||||
|
||||
Did you find a bug? Do you have feature request? Do you want to merge a feature?
|
||||
|
||||
* [contributing to cocos2d-x][8]
|
||||
|
||||
|
||||
Contact us
|
||||
----------
|
||||
|
||||
* Forum: [http://forum.cocos2d-x.org][9]
|
||||
* Twitter: [http://www.twitter.com/cocos2dx][10]
|
||||
* Weibo: [http://t.sina.com.cn/cocos2dx][11]
|
||||
* IRC: [https://webchat.freenode.net/][12] (#cocos2d and #cocos2d-x channels)
|
||||
|
||||
[1]: http://www.cocos2d-x.org "cocos2d-x"
|
||||
[2]: http://www.cocos2d-iphone.org "cocos2d for iPhone"
|
||||
[3]: http://www.cocos2d-x.org/projects/cocos2d-x/wiki/Download
|
||||
[4]: https://github.com/cocos2d/cocos2d-x/tree/develop
|
||||
[5]: http://www.box2d.org "Box2D"
|
||||
[6]: http://www.chipmunk-physics.net "Chipmunk2D"
|
||||
[7]: http://esotericsoftware.com/ "http://esotericsoftware.com/"
|
||||
[8]: http://www.cocos2d-x.org/projects/cocos2d-x/wiki/Contribution
|
||||
[9]: http://forum.cocos2d-x.org "http://forum.cocos2d-x.org"
|
||||
[10]: http://www.twitter.com/cocos2dx "http://www.twitter.com/cocos2dx"
|
||||
[11]: http://t.sina.com.cn/cocos2dx "http://t.sina.com.cn/cocos2dx"
|
||||
[12]: https://webchat.freenode.net/ "https://webchat.freenode.net/"
|
64
README.mdown
64
README.mdown
|
@ -1,64 +0,0 @@
|
|||
cocos2d-x
|
||||
=========
|
||||
|
||||
[![Build Status](https://travis-ci.org/cocos2d/cocos2d-x.png?branch=master)](https://travis-ci.org/cocos2d/cocos2d-x)
|
||||
|
||||
[cocos2d-x][1] is a multi-platform 2D game framework in C++, branched on
|
||||
[cocos2d-iphone][2] and licensed under MIT. The master branch on github uses
|
||||
OpenGL ES 2.0 rendering, while the old gles11 branch uses OpenGL ES 1.1
|
||||
rendering. Currently we focus on gles20 developmenet.
|
||||
|
||||
Supported Platforms
|
||||
-------------------
|
||||
|
||||
* iOS: stable, well tested on iOS 5.x ~ 6.x SDK.
|
||||
* Android: stable, well tested on 2.0~4.x, ndk r5 ~ r8. If you use gles20
|
||||
branch or cocos2d-x v2.0 above, only android 2.3 and higher are supported
|
||||
* Windows Phone 8 and Win8 Metro: stable, it's in another repo
|
||||
http://github.com/cocos2d-x/cocos2dx-win8.
|
||||
* Bada: cocos2d-x v1.x supports Bada SDK 1.0 & 2.0. Bada support was
|
||||
deprecated since cocos2d-x v2.0.
|
||||
* BlackBerry: stable, contributed by staffs in RIM, supports Playbook & BB10.
|
||||
* Marmalade: stable since cocos2d-x v0.11.0, contributed by Marmalade's staff.
|
||||
* Native Client (NaCl): contributed by the Native Client authors.
|
||||
* Windows: stable, well tested on WinXP/Vista/Win7. Please upgrde the drive
|
||||
of your video card if you meet problems on OpenGL functions
|
||||
* Linux: support but not very stable.
|
||||
* Emscripten: Alpha-level. Most features implemented. Needs testing.
|
||||
Contributed by Zynga staff.
|
||||
* Tizen: Experimental. Essential features implemented. Needs more implementing.
|
||||
Contributed by Lee, Jae-Hong.
|
||||
|
||||
You can visit our continuous integration system http://ci.cocos2d-x.org to
|
||||
check the stability on edge version.
|
||||
|
||||
Supported Programming Languages
|
||||
-------------------------------
|
||||
|
||||
* C++ is the major programming language of cocos2d-x. Tons of top-chart
|
||||
cocos2d-x games were written in C++.
|
||||
* Lua binding is also widely used. Glu mobile, Zynga, UCWEB, 4399, Renren
|
||||
Games are using lua on cocos2d-x.
|
||||
* Javascript binding is our recommendation since 2012 H2. Cocos2d community
|
||||
are cooperating on the same Javasciprt API on cocos2d-iphone/-x/-html5.
|
||||
|
||||
Documentations
|
||||
--------------
|
||||
|
||||
* Wiki: [wiki.cocos2d-x.org][3]
|
||||
* [Online API References][4]
|
||||
|
||||
Contact us
|
||||
----------
|
||||
|
||||
* Forum: [http://forum.cocos2d-x.org][5]
|
||||
* Twitter: [http://www.twitter.com/cocos2dx][6]
|
||||
* Weibo: [http://t.sina.com.cn/cocos2dx][7]
|
||||
|
||||
[1]: http://www.cocos2d-x.org "cocos2d-x"
|
||||
[2]: http://www.cocos2d-iphone.org "cocos2d for iPhone"
|
||||
[3]: http://wiki.cocos2d-x.org "wiki.cocos2d-x.org"
|
||||
[4]: http://www.cocos2d-x.org/projects/cocos2d-x/wiki/Reference "API References"
|
||||
[5]: http://forum.cocos2d-x.org "http://forum.cocos2d-x.org"
|
||||
[6]: http://www.twitter.com/cocos2dx "http://www.twitter.com/cocos2dx"
|
||||
[7]: http://t.sina.com.cn/cocos2dx "http://t.sina.com.cn/cocos2dx"
|
|
@ -1 +1 @@
|
|||
0e11ea510c133e9dcecc692632cf3c6eeeb1fd8d
|
||||
f315741eede504af20f8823c22d486dece3d95a9
|
|
@ -61,9 +61,23 @@ kazmath/src/GL/matrix.c \
|
|||
keypad_dispatcher/CCKeypadDelegate.cpp \
|
||||
keypad_dispatcher/CCKeypadDispatcher.cpp \
|
||||
keyboard_dispatcher/CCKeyboardDispatcher.cpp \
|
||||
label_nodes/CCFont.cpp \
|
||||
label_nodes/CCFontAtlas.cpp \
|
||||
label_nodes/CCFontAtlasCache.cpp \
|
||||
label_nodes/CCFontAtlasFactory.cpp \
|
||||
label_nodes/CCFontCache.cpp \
|
||||
label_nodes/CCFontDefinition.cpp \
|
||||
label_nodes/CCFontFNT.cpp \
|
||||
label_nodes/CCFontFreeType.cpp \
|
||||
label_nodes/CCFontRenderFreeType.cpp \
|
||||
label_nodes/CCLabel.cpp \
|
||||
label_nodes/CCLabelAtlas.cpp \
|
||||
label_nodes/CCLabelBMFont.cpp \
|
||||
label_nodes/CCLabelTTF.cpp \
|
||||
label_nodes/CCLabelTextFormatter.cpp \
|
||||
label_nodes/CCStringBMFont.cpp \
|
||||
label_nodes/CCStringTTF.cpp \
|
||||
label_nodes/CCTextImage.cpp \
|
||||
layers_scenes_transitions_nodes/CCLayer.cpp \
|
||||
layers_scenes_transitions_nodes/CCScene.cpp \
|
||||
layers_scenes_transitions_nodes/CCTransitionPageTurn.cpp \
|
||||
|
@ -83,21 +97,6 @@ platform/CCSAXParser.cpp \
|
|||
platform/CCThread.cpp \
|
||||
platform/CCFileUtils.cpp \
|
||||
platform/CCEGLViewProtocol.cpp \
|
||||
platform/android/CCDevice.cpp \
|
||||
platform/android/CCEGLView.cpp \
|
||||
platform/android/CCAccelerometer.cpp \
|
||||
platform/android/CCApplication.cpp \
|
||||
platform/android/CCCommon.cpp \
|
||||
platform/android/CCFileUtilsAndroid.cpp \
|
||||
platform/android/CCImage.cpp \
|
||||
platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxBitmap.cpp \
|
||||
platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.cpp \
|
||||
platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxRenderer.cpp \
|
||||
platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxAccelerometer.cpp \
|
||||
platform/android/jni/JniHelper.cpp \
|
||||
platform/android/jni/IMEJni.cpp \
|
||||
platform/android/jni/TouchesJni.cpp \
|
||||
platform/android/jni/DPIJni.cpp \
|
||||
script_support/CCScriptSupport.cpp \
|
||||
shaders/ccShaders.cpp \
|
||||
shaders/CCGLProgram.cpp \
|
||||
|
@ -145,7 +144,6 @@ LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) \
|
|||
$(LOCAL_PATH)/include \
|
||||
$(LOCAL_PATH)/kazmath/include \
|
||||
$(LOCAL_PATH)/platform/android \
|
||||
$(LOCAL_PATH)/platform/third_party/common/etc
|
||||
|
||||
LOCAL_C_INCLUDES := $(LOCAL_PATH) \
|
||||
$(LOCAL_PATH)/include \
|
||||
|
@ -169,6 +167,7 @@ LOCAL_WHOLE_STATIC_LIBRARIES += cocos_jpeg_static
|
|||
LOCAL_WHOLE_STATIC_LIBRARIES += cocos_libxml2_static
|
||||
LOCAL_WHOLE_STATIC_LIBRARIES += cocos_libtiff_static
|
||||
LOCAL_WHOLE_STATIC_LIBRARIES += cocos_libwebp_static
|
||||
LOCAL_WHOLE_STATIC_LIBRARIES += cocos_freetype2_static
|
||||
|
||||
# define the macro to compile through support/zip_support/ioapi.c
|
||||
LOCAL_CFLAGS := -Wno-psabi -DUSE_FILE32API
|
||||
|
@ -180,3 +179,4 @@ $(call import-module,libjpeg)
|
|||
$(call import-module,libpng)
|
||||
$(call import-module,libtiff)
|
||||
$(call import-module,libwebp)
|
||||
$(call import-module,libfreetype2)
|
||||
|
|
|
@ -208,7 +208,7 @@ void Director::setDefaultValues(void)
|
|||
_displayStats = conf->getBool("cocos2d.x.display_fps", false);
|
||||
|
||||
// GL projection
|
||||
const char *projection = conf->getCString("cocos2d.x.gl.projection", "3d");
|
||||
const char *projection = conf->getCString("cocos2d.x.gl.projection", "2d");
|
||||
if( strcmp(projection, "3d") == 0 )
|
||||
_projection = Projection::_3D;
|
||||
else if (strcmp(projection, "2d") == 0)
|
||||
|
|
|
@ -804,8 +804,8 @@ CC_DEPRECATED_ATTRIBUTE typedef FontShadow ccFontShadow;
|
|||
CC_DEPRECATED_ATTRIBUTE typedef FontStroke ccFontStroke;
|
||||
CC_DEPRECATED_ATTRIBUTE typedef FontDefinition ccFontDefinition;
|
||||
|
||||
CC_DEPRECATED_ATTRIBUTE typedef Label::VAlignment CCVerticalTextAlignment;
|
||||
CC_DEPRECATED_ATTRIBUTE typedef Label::HAlignment CCTextAlignment;
|
||||
CC_DEPRECATED_ATTRIBUTE typedef TextVAlignment CCVerticalTextAlignment;
|
||||
CC_DEPRECATED_ATTRIBUTE typedef TextHAlignment CCTextAlignment;
|
||||
CC_DEPRECATED_ATTRIBUTE typedef ProgressTimer::Type CCProgressTimerType;
|
||||
|
||||
CC_DEPRECATED_ATTRIBUTE typedef void* CCZone;
|
||||
|
@ -866,13 +866,13 @@ CC_DEPRECATED_ATTRIBUTE const Director::Projection kCCDirectorProjectionCustom =
|
|||
CC_DEPRECATED_ATTRIBUTE const Director::Projection kCCDirectorProjectionDefault = Director::Projection::DEFAULT;
|
||||
CC_DEPRECATED_ATTRIBUTE typedef Director::Projection ccDirectorProjection;
|
||||
|
||||
CC_DEPRECATED_ATTRIBUTE const Label::VAlignment kCCVerticalTextAlignmentTop = Label::VAlignment::TOP;
|
||||
CC_DEPRECATED_ATTRIBUTE const Label::VAlignment kCCVerticalTextAlignmentCenter = Label::VAlignment::CENTER;
|
||||
CC_DEPRECATED_ATTRIBUTE const Label::VAlignment kCCVerticalTextAlignmentBottom = Label::VAlignment::BOTTOM;
|
||||
CC_DEPRECATED_ATTRIBUTE const TextVAlignment kCCVerticalTextAlignmentTop = TextVAlignment::TOP;
|
||||
CC_DEPRECATED_ATTRIBUTE const TextVAlignment kCCVerticalTextAlignmentCenter = TextVAlignment::CENTER;
|
||||
CC_DEPRECATED_ATTRIBUTE const TextVAlignment kCCVerticalTextAlignmentBottom = TextVAlignment::BOTTOM;
|
||||
|
||||
CC_DEPRECATED_ATTRIBUTE const Label::HAlignment kCCTextAlignmentLeft = Label::HAlignment::LEFT;
|
||||
CC_DEPRECATED_ATTRIBUTE const Label::HAlignment kCCTextAlignmentCenter = Label::HAlignment::CENTER;
|
||||
CC_DEPRECATED_ATTRIBUTE const Label::HAlignment kCCTextAlignmentRight = Label::HAlignment::RIGHT;
|
||||
CC_DEPRECATED_ATTRIBUTE const TextHAlignment kCCTextAlignmentLeft = TextHAlignment::LEFT;
|
||||
CC_DEPRECATED_ATTRIBUTE const TextHAlignment kCCTextAlignmentCenter = TextHAlignment::CENTER;
|
||||
CC_DEPRECATED_ATTRIBUTE const TextHAlignment kCCTextAlignmentRight = TextHAlignment::RIGHT;
|
||||
|
||||
CC_DEPRECATED_ATTRIBUTE const Texture2D::PixelFormat kCCTexture2DPixelFormat_RGBA8888 = Texture2D::PixelFormat::RGBA8888;
|
||||
CC_DEPRECATED_ATTRIBUTE const Texture2D::PixelFormat kCCTexture2DPixelFormat_RGB888 = Texture2D::PixelFormat::RGB888;
|
||||
|
|
|
@ -99,7 +99,7 @@ To enabled set it to 1. Disabled by default.
|
|||
Default value: 0.1f
|
||||
*/
|
||||
#ifndef CC_DIRECTOR_STATS_INTERVAL
|
||||
#define CC_DIRECTOR_STATS_INTERVAL (0.5f)
|
||||
#define CC_DIRECTOR_STATS_INTERVAL (2.0f)
|
||||
#endif
|
||||
|
||||
/** @def CC_DIRECTOR_FPS_POSITION
|
||||
|
|
|
@ -311,26 +311,25 @@ struct BlendFunc
|
|||
const static BlendFunc ADDITIVE;
|
||||
};
|
||||
|
||||
class Label : public Object
|
||||
// Label::VAlignment
|
||||
// Label::HAlignment
|
||||
|
||||
// XXX: If any of these enums are edited and/or reordered, update Texture2D.m
|
||||
//! Vertical text alignment type
|
||||
enum class TextVAlignment
|
||||
{
|
||||
public:
|
||||
// XXX: If any of these enums are edited and/or reordered, update Texture2D.m
|
||||
//! Vertical text alignment type
|
||||
enum class VAlignment
|
||||
{
|
||||
TOP,
|
||||
CENTER,
|
||||
BOTTOM,
|
||||
};
|
||||
|
||||
// XXX: If any of these enums are edited and/or reordered, update Texture2D.m
|
||||
//! Horizontal text alignment type
|
||||
enum class HAlignment
|
||||
{
|
||||
LEFT,
|
||||
CENTER,
|
||||
RIGHT,
|
||||
};
|
||||
TOP,
|
||||
CENTER,
|
||||
BOTTOM,
|
||||
};
|
||||
|
||||
// XXX: If any of these enums are edited and/or reordered, update Texture2D.m
|
||||
//! Horizontal text alignment type
|
||||
enum class TextHAlignment
|
||||
{
|
||||
LEFT,
|
||||
CENTER,
|
||||
RIGHT,
|
||||
};
|
||||
|
||||
// types for animation in particle systems
|
||||
|
@ -360,6 +359,7 @@ struct AnimationFrameData
|
|||
types used for defining fonts properties (i.e. font name, size, stroke or shadow)
|
||||
*/
|
||||
|
||||
|
||||
// shadow attributes
|
||||
struct FontShadow
|
||||
{
|
||||
|
@ -410,8 +410,8 @@ public:
|
|||
|
||||
FontDefinition()
|
||||
: _fontSize(0)
|
||||
, _alignment(Label::HAlignment::CENTER)
|
||||
, _vertAlignment(Label::VAlignment::TOP)
|
||||
, _alignment(TextHAlignment::CENTER)
|
||||
, _vertAlignment(TextVAlignment::TOP)
|
||||
, _dimensions(Size::ZERO)
|
||||
, _fontFillColor(Color3B::WHITE)
|
||||
{}
|
||||
|
@ -421,9 +421,9 @@ public:
|
|||
// font size
|
||||
int _fontSize;
|
||||
// horizontal alignment
|
||||
Label::HAlignment _alignment;
|
||||
TextHAlignment _alignment;
|
||||
// vertical alignment
|
||||
Label::VAlignment _vertAlignment;
|
||||
TextVAlignment _vertAlignment;
|
||||
// renering box
|
||||
Size _dimensions;
|
||||
// font color
|
||||
|
|
|
@ -99,6 +99,8 @@ THE SOFTWARE.
|
|||
#include "label_nodes/CCLabelAtlas.h"
|
||||
#include "label_nodes/CCLabelTTF.h"
|
||||
#include "label_nodes/CCLabelBMFont.h"
|
||||
#include "label_nodes/CCStringBMFont.h"
|
||||
#include "label_nodes/CCStringTTF.h"
|
||||
|
||||
// layers_scenes_transitions_nodes
|
||||
#include "layers_scenes_transitions_nodes/CCLayer.h"
|
||||
|
|
|
@ -0,0 +1,85 @@
|
|||
/****************************************************************************
|
||||
Copyright (c) 2013 Zynga 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.
|
||||
****************************************************************************/
|
||||
|
||||
#include "CCFont.h"
|
||||
#include "support/ccUTF8.h"
|
||||
|
||||
NS_CC_BEGIN
|
||||
|
||||
unsigned short int * Font::getUTF16Text(const char *pText, int &outNumLetters)
|
||||
{
|
||||
unsigned short* utf16String = cc_utf8_to_utf16(pText);
|
||||
|
||||
if(!utf16String)
|
||||
return 0;
|
||||
|
||||
outNumLetters = cc_wcslen(utf16String);
|
||||
return utf16String;
|
||||
}
|
||||
|
||||
int Font::getUTF16TextLenght(unsigned short int *pText)
|
||||
{
|
||||
return cc_wcslen(pText);
|
||||
}
|
||||
|
||||
unsigned short int * Font::trimUTF16Text(unsigned short int *pText, int newBegin, int newEnd)
|
||||
{
|
||||
if ( newBegin<0 || newEnd<=0 )
|
||||
return 0;
|
||||
|
||||
if ( newBegin>=newEnd )
|
||||
return 0;
|
||||
|
||||
if (newEnd >= cc_wcslen(pText))
|
||||
return 0;
|
||||
|
||||
int newLenght = newEnd - newBegin + 2;
|
||||
unsigned short* trimmedString = new unsigned short[newLenght];
|
||||
|
||||
for(int c = 0; c < (newLenght-1); ++c)
|
||||
{
|
||||
trimmedString[c] = pText[newBegin + c];
|
||||
}
|
||||
|
||||
// last char
|
||||
trimmedString[newLenght-1] = 0x0000;
|
||||
|
||||
// done
|
||||
return trimmedString;
|
||||
}
|
||||
|
||||
Rect Font::getRectForChar(unsigned short theChar)
|
||||
{
|
||||
Rect temp;
|
||||
temp.size.width = 0;
|
||||
temp.size.height = 0;
|
||||
temp.origin.x = 0;
|
||||
temp.origin.y = 0;
|
||||
|
||||
return temp;
|
||||
}
|
||||
|
||||
NS_CC_END
|
||||
|
||||
|
|
@ -0,0 +1,59 @@
|
|||
/****************************************************************************
|
||||
Copyright (c) 2013 Zynga 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.
|
||||
****************************************************************************/
|
||||
|
||||
#ifndef _CCFont_h_
|
||||
#define _CCFont_h_
|
||||
|
||||
#include <string>
|
||||
#include "cocos2d.h"
|
||||
|
||||
NS_CC_BEGIN
|
||||
|
||||
class GlyphDef;
|
||||
|
||||
class CC_DLL Font : public Object
|
||||
{
|
||||
public:
|
||||
|
||||
virtual ~Font() {}
|
||||
|
||||
virtual Size * getAdvancesForTextUTF16(unsigned short *pText, int &outNumLetters) = 0;
|
||||
|
||||
virtual bool createFontObject(const std::string &fontName, int fontSize) { return false; }
|
||||
virtual int getLetterPadding() { return 0; }
|
||||
virtual unsigned char * getGlyphBitmap(unsigned short theChar, int &outWidth, int &outHeight) { return 0; }
|
||||
virtual int getFontMaxHeight() { return 0; }
|
||||
virtual GlyphDef * getGlyphDefintionsForText(const char *pText, int &outNumGlyphs, bool UTF16text = false) { return 0; }
|
||||
virtual Rect getRectForChar(unsigned short theChar);
|
||||
|
||||
virtual unsigned short int * getUTF16Text(const char *pText, int &outNumLetters);
|
||||
virtual int getUTF16TextLenght(unsigned short int *pText);
|
||||
virtual unsigned short int * trimUTF16Text(unsigned short int *pText, int newBegin, int newEnd);
|
||||
|
||||
};
|
||||
|
||||
NS_CC_END
|
||||
|
||||
|
||||
#endif
|
|
@ -0,0 +1,95 @@
|
|||
//
|
||||
// CCFontAtlas.cpp
|
||||
// cocos2d_libs
|
||||
//
|
||||
// Created by Carlo Morgantini on 7/18/13.
|
||||
//
|
||||
//
|
||||
|
||||
#include "cocos2d.h"
|
||||
#include "CCFontAtlas.h"
|
||||
#include "CCFont.h"
|
||||
|
||||
NS_CC_BEGIN
|
||||
|
||||
FontAtlas::FontAtlas(Font &theFont) : _font(theFont)
|
||||
{
|
||||
_font.retain();
|
||||
}
|
||||
|
||||
FontAtlas::~FontAtlas()
|
||||
{
|
||||
_font.release();
|
||||
relaseTextures();
|
||||
}
|
||||
|
||||
void FontAtlas::relaseTextures()
|
||||
{
|
||||
for( auto &item: _atlasTextures)
|
||||
{
|
||||
if ( item.second )
|
||||
item.second->release();
|
||||
}
|
||||
|
||||
_atlasTextures.clear();
|
||||
}
|
||||
|
||||
void FontAtlas::addLetterDefinition(const FontLetterDefinition &letterDefinition)
|
||||
{
|
||||
_fontLetterDefinitions[letterDefinition.letteCharUTF16] = letterDefinition;
|
||||
}
|
||||
|
||||
bool FontAtlas::getLetterDefinitionForChar(unsigned short letteCharUTF16, FontLetterDefinition &outDefinition) const
|
||||
{
|
||||
auto outIterator = _fontLetterDefinitions.find(letteCharUTF16);
|
||||
|
||||
if (outIterator != _fontLetterDefinitions.end())
|
||||
{
|
||||
outDefinition = (*outIterator).second;
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
void FontAtlas::addTexture(Texture2D &texture, int slot)
|
||||
{
|
||||
texture.retain();
|
||||
_atlasTextures[slot] = &texture;
|
||||
}
|
||||
|
||||
Texture2D & FontAtlas::getTexture(int slot)
|
||||
{
|
||||
return *(_atlasTextures[slot]);
|
||||
}
|
||||
|
||||
float FontAtlas::getCommonLineHeight() const
|
||||
{
|
||||
return _commonLineHeight;
|
||||
}
|
||||
|
||||
void FontAtlas::setCommonLineHeight(float newHeight)
|
||||
{
|
||||
_commonLineHeight = newHeight;
|
||||
}
|
||||
|
||||
unsigned short int * FontAtlas::getUTF16Text(const char *pText, int &outNumLetters) const
|
||||
{
|
||||
unsigned short* utf16String = cc_utf8_to_utf16(pText);
|
||||
|
||||
if(!utf16String)
|
||||
return 0;
|
||||
|
||||
outNumLetters = cc_wcslen(utf16String);
|
||||
return utf16String;
|
||||
}
|
||||
|
||||
Font & FontAtlas::getFont() const
|
||||
{
|
||||
return _font;
|
||||
}
|
||||
|
||||
|
||||
NS_CC_END
|
|
@ -0,0 +1,79 @@
|
|||
/****************************************************************************
|
||||
Copyright (c) 2013 Zynga 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.
|
||||
****************************************************************************/
|
||||
#ifndef _CCFontAtlas_h_
|
||||
#define _CCFontAtlas_h_
|
||||
|
||||
|
||||
#include <map>
|
||||
|
||||
NS_CC_BEGIN
|
||||
|
||||
struct FontLetterDefinition
|
||||
{
|
||||
unsigned short letteCharUTF16;
|
||||
float U;
|
||||
float V;
|
||||
float width;
|
||||
float height;
|
||||
float offsetX;
|
||||
float offsetY;
|
||||
int textureID;
|
||||
float commonLineHeight;
|
||||
float anchorX;
|
||||
float anchorY;
|
||||
bool validDefinition;
|
||||
};
|
||||
|
||||
class CC_DLL FontAtlas : public Object
|
||||
{
|
||||
|
||||
public:
|
||||
|
||||
FontAtlas(Font &theFont);
|
||||
virtual ~FontAtlas();
|
||||
|
||||
void addLetterDefinition(const FontLetterDefinition &letterDefinition);
|
||||
bool getLetterDefinitionForChar(unsigned short letteCharUTF16, FontLetterDefinition &outDefinition) const;
|
||||
void addTexture(Texture2D &texture, int slot);
|
||||
Texture2D & getTexture(int slot);
|
||||
void setCommonLineHeight(float newHeight);
|
||||
float getCommonLineHeight() const;
|
||||
unsigned short int * getUTF16Text(const char *pText, int &outNumLetters) const;
|
||||
Font & getFont() const;
|
||||
|
||||
private:
|
||||
|
||||
void relaseTextures();
|
||||
std::map<int, Texture2D *> _atlasTextures;
|
||||
std::map<unsigned short, FontLetterDefinition> _fontLetterDefinitions;
|
||||
float _commonLineHeight;
|
||||
Font & _font;
|
||||
|
||||
};
|
||||
|
||||
|
||||
NS_CC_END
|
||||
|
||||
|
||||
#endif /* defined(__cocos2d_libs__CCFontAtlas__) */
|
|
@ -0,0 +1,144 @@
|
|||
/****************************************************************************
|
||||
Copyright (c) 2013 Zynga 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.
|
||||
****************************************************************************/
|
||||
|
||||
#include "CCFontAtlasCache.h"
|
||||
#include "CCFontAtlasFactory.h"
|
||||
|
||||
|
||||
NS_CC_BEGIN
|
||||
|
||||
std::map<std::string, FontAtlas *> FontAtlasCache::_atlasMap;
|
||||
|
||||
|
||||
FontAtlas * FontAtlasCache::getFontAtlasTTF(const char *fontFileName, int size, GlyphCollection glyphs, const char *customGlyphs)
|
||||
{
|
||||
std::string atlasName = generateFontName(fontFileName, size, glyphs);
|
||||
FontAtlas *tempAtlas = _atlasMap[atlasName];
|
||||
|
||||
if ( !tempAtlas )
|
||||
{
|
||||
tempAtlas = FontAtlasFactory::createAtlasFromTTF(fontFileName, size, glyphs, customGlyphs);
|
||||
|
||||
if (tempAtlas)
|
||||
{
|
||||
_atlasMap[atlasName] = tempAtlas;
|
||||
}
|
||||
else
|
||||
{
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
tempAtlas->retain();
|
||||
}
|
||||
|
||||
return tempAtlas;
|
||||
}
|
||||
|
||||
FontAtlas * FontAtlasCache::getFontAtlasFNT(const char *fontFileName)
|
||||
{
|
||||
std::string atlasName = generateFontName(fontFileName, 0, GlyphCollection::CUSTOM);
|
||||
FontAtlas *tempAtlas = _atlasMap[atlasName];
|
||||
|
||||
if ( !tempAtlas )
|
||||
{
|
||||
tempAtlas = FontAtlasFactory::createAtlasFromFNT(fontFileName);
|
||||
|
||||
if (tempAtlas)
|
||||
{
|
||||
_atlasMap[atlasName] = tempAtlas;
|
||||
}
|
||||
else
|
||||
{
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
tempAtlas->retain();
|
||||
}
|
||||
|
||||
return tempAtlas;
|
||||
}
|
||||
|
||||
std::string FontAtlasCache::generateFontName(const char *fontFileName, int size, GlyphCollection theGlyphs)
|
||||
{
|
||||
std::string tempName(fontFileName);
|
||||
|
||||
switch (theGlyphs)
|
||||
{
|
||||
|
||||
case GlyphCollection::DYNAMIC:
|
||||
tempName.append("_DYNAMIC_");
|
||||
break;
|
||||
|
||||
case GlyphCollection::NEHE:
|
||||
tempName.append("_NEHE_");
|
||||
break;
|
||||
|
||||
case GlyphCollection::ASCII:
|
||||
tempName.append("_ASCII_");
|
||||
break;
|
||||
|
||||
case GlyphCollection::CUSTOM:
|
||||
tempName.append("_CUSTOM_");
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
std::stringstream ss;
|
||||
ss << size;
|
||||
// std::to_string is not supported on android, using std::stringstream instead.
|
||||
return tempName.append(ss.str());
|
||||
}
|
||||
|
||||
bool FontAtlasCache::releaseFontAtlas(FontAtlas *atlas)
|
||||
{
|
||||
if (atlas)
|
||||
{
|
||||
for( auto &item: _atlasMap)
|
||||
{
|
||||
if ( item.second == atlas )
|
||||
{
|
||||
bool removeFromList = false;
|
||||
if(item.second->isSingleReference())
|
||||
removeFromList = true;
|
||||
|
||||
item.second->release();
|
||||
|
||||
if (removeFromList)
|
||||
_atlasMap.erase(item.first);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
NS_CC_END
|
|
@ -0,0 +1,53 @@
|
|||
/****************************************************************************
|
||||
Copyright (c) 2013 Zynga 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.
|
||||
****************************************************************************/
|
||||
|
||||
#ifndef _CCFontAtlasCache_h_
|
||||
#define _CCFontAtlasCache_h_
|
||||
|
||||
#include <iostream>
|
||||
#include <map>
|
||||
|
||||
#include "cocos2d.h"
|
||||
#include "CCFontAtlas.h"
|
||||
|
||||
NS_CC_BEGIN
|
||||
|
||||
class CC_DLL FontAtlasCache
|
||||
{
|
||||
|
||||
public:
|
||||
|
||||
static FontAtlas * getFontAtlasTTF(const char *fontFileName, int size, GlyphCollection glyphs, const char *customGlyphs = 0);
|
||||
static FontAtlas * getFontAtlasFNT(const char *fontFileName);
|
||||
static bool releaseFontAtlas(FontAtlas *atlas);
|
||||
|
||||
private:
|
||||
|
||||
static std::string generateFontName(const char *fontFileName, int size, GlyphCollection theGlyphs);
|
||||
static std::map<std::string, FontAtlas *> _atlasMap;
|
||||
};
|
||||
|
||||
NS_CC_END
|
||||
|
||||
#endif
|
|
@ -0,0 +1,167 @@
|
|||
//
|
||||
// CCFontAtlasFactory.cpp
|
||||
// cocos2d_libs
|
||||
//
|
||||
// Created by Carlo Morgantini on 7/23/13.
|
||||
//
|
||||
//
|
||||
|
||||
#include "CCFontAtlasFactory.h"
|
||||
#include "CCFontFNT.h"
|
||||
|
||||
// carloX this NEEDS to be changed
|
||||
#include "CCLabelBMFont.h"
|
||||
|
||||
NS_CC_BEGIN
|
||||
|
||||
|
||||
const char *FontAtlasFactory::glyphASCII = "\"!#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþ ";
|
||||
|
||||
const char *FontAtlasFactory::glyphNEHE = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ";
|
||||
|
||||
|
||||
|
||||
FontAtlas * FontAtlasFactory::createAtlasFromTTF(const char* fntFilePath, int fontSize, GlyphCollection glyphs, const char *customGlyphs)
|
||||
{
|
||||
FontDefinitionTTF *def = 0;
|
||||
if ( (glyphs == GlyphCollection::NEHE) || (glyphs == GlyphCollection::ASCII) )
|
||||
{
|
||||
def = FontDefinitionTTF::create(fntFilePath, fontSize, getGlyphCollection(glyphs));
|
||||
}
|
||||
else
|
||||
{
|
||||
if( glyphs == GlyphCollection::DYNAMIC )
|
||||
{
|
||||
log("ERROR: GlyphCollection::DYNAMIC is not supported yet!");
|
||||
return nullptr;
|
||||
}
|
||||
else
|
||||
{
|
||||
if ( !customGlyphs )
|
||||
{
|
||||
log("ERROR: GlyphCollection::CUSTOM used but no input glyphs provided!");
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
def = FontDefinitionTTF::create(fntFilePath, fontSize, customGlyphs);
|
||||
}
|
||||
}
|
||||
|
||||
if(!def)
|
||||
return nullptr;
|
||||
|
||||
// create the font atlas from the font definition
|
||||
FontAtlas *tempAtlas = def->createFontAtlas();
|
||||
|
||||
// release the font definition, we don't need it anymore
|
||||
def->release();
|
||||
|
||||
// return the atlas
|
||||
return tempAtlas;
|
||||
}
|
||||
|
||||
FontAtlas * FontAtlasFactory::createAtlasFromFNT(const char* fntFilePath)
|
||||
{
|
||||
CCBMFontConfiguration *newConf = FNTConfigLoadFile(fntFilePath);
|
||||
|
||||
if (newConf)
|
||||
return createFontAtlasFromFNTConfig(newConf);
|
||||
else
|
||||
return 0;
|
||||
}
|
||||
|
||||
const char * FontAtlasFactory::getGlyphCollection(GlyphCollection glyphs)
|
||||
{
|
||||
switch (glyphs)
|
||||
{
|
||||
case GlyphCollection::NEHE:
|
||||
return glyphNEHE;
|
||||
break;
|
||||
|
||||
case GlyphCollection::ASCII:
|
||||
return glyphASCII;
|
||||
break;
|
||||
|
||||
default:
|
||||
return 0;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
FontAtlas * FontAtlasFactory::createFontAtlasFromFNTConfig(CCBMFontConfiguration *theConfig)
|
||||
{
|
||||
if (!theConfig)
|
||||
return 0;
|
||||
|
||||
FontFNT *tempFont = new FontFNT(theConfig);
|
||||
if (!tempFont)
|
||||
return 0;
|
||||
|
||||
FontAtlas *tempAtlas = new FontAtlas(*tempFont);
|
||||
if (!tempAtlas)
|
||||
return 0;
|
||||
|
||||
// check that everything is fine with the BMFontCofniguration
|
||||
if (!theConfig->_fontDefDictionary)
|
||||
return 0;
|
||||
|
||||
|
||||
int numGlyphs = theConfig->_characterSet->size();
|
||||
if (!numGlyphs)
|
||||
return 0;
|
||||
|
||||
if (theConfig->_commonHeight == 0)
|
||||
return 0;
|
||||
|
||||
// commone height
|
||||
tempAtlas->setCommonLineHeight(theConfig->_commonHeight);
|
||||
|
||||
|
||||
ccBMFontDef fontDef;
|
||||
tFontDefHashElement *current_element, *tmp;
|
||||
|
||||
// Purge uniform hash
|
||||
HASH_ITER(hh, theConfig->_fontDefDictionary, current_element, tmp)
|
||||
{
|
||||
|
||||
FontLetterDefinition tempDefinition;
|
||||
|
||||
fontDef = current_element->fontDef;
|
||||
Rect tempRect;
|
||||
|
||||
tempRect = fontDef.rect;
|
||||
tempRect = CC_RECT_PIXELS_TO_POINTS(tempRect);
|
||||
|
||||
tempDefinition.letteCharUTF16 = fontDef.charID;
|
||||
|
||||
tempDefinition.offsetX = fontDef.xOffset;
|
||||
tempDefinition.offsetY = fontDef.yOffset;
|
||||
|
||||
tempDefinition.U = tempRect.origin.x;
|
||||
tempDefinition.V = tempRect.origin.y;
|
||||
|
||||
tempDefinition.width = tempRect.size.width;
|
||||
tempDefinition.height = tempRect.size.height;
|
||||
|
||||
//carloX: only one texture supported FOR NOW
|
||||
tempDefinition.textureID = 0;
|
||||
|
||||
tempDefinition.anchorX = 0.5f;
|
||||
tempDefinition.anchorY = 0.5f;
|
||||
|
||||
// add the new definition
|
||||
tempAtlas->addLetterDefinition(tempDefinition);
|
||||
}
|
||||
|
||||
// add the texture (only one texture for now)
|
||||
|
||||
Texture2D *tempTexture = TextureCache::getInstance()->addImage(theConfig->getAtlasName());
|
||||
if (!tempTexture)
|
||||
return 0;
|
||||
|
||||
// add the texture
|
||||
tempAtlas->addTexture(*tempTexture, 0);
|
||||
return tempAtlas;
|
||||
}
|
||||
|
||||
NS_CC_END
|
|
@ -0,0 +1,55 @@
|
|||
/****************************************************************************
|
||||
Copyright (c) 2013 Zynga 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.
|
||||
****************************************************************************/
|
||||
|
||||
#ifndef _CCFontAtlasFactory_h_
|
||||
#define _CCFontAtlasFactory_h_
|
||||
|
||||
#include "cocos2d.h"
|
||||
#include "CCFontAtlas.h"
|
||||
|
||||
NS_CC_BEGIN
|
||||
|
||||
class CC_DLL FontAtlasFactory
|
||||
{
|
||||
|
||||
public:
|
||||
|
||||
static FontAtlas * createAtlasFromTTF(const char* fntFilePath, int fontSize, GlyphCollection glyphs, const char *customGlyphs = 0);
|
||||
static FontAtlas * createAtlasFromFNT(const char* fntFilePath);
|
||||
|
||||
private:
|
||||
|
||||
static const char * getGlyphCollection(GlyphCollection glyphs);
|
||||
|
||||
// carloX: this needs to be moved somewhere else, but it's good enough for now
|
||||
static FontAtlas * createFontAtlasFromFNTConfig(CCBMFontConfiguration *theConfig);
|
||||
|
||||
static const char *glyphASCII;
|
||||
static const char *glyphNEHE;
|
||||
|
||||
};
|
||||
|
||||
NS_CC_END
|
||||
|
||||
#endif /* defined(_CCFontAtlasFactory_h_) */
|
|
@ -0,0 +1,101 @@
|
|||
/****************************************************************************
|
||||
Copyright (c) 2013 Zynga 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.
|
||||
****************************************************************************/
|
||||
|
||||
#include "CCFontCache.h"
|
||||
|
||||
NS_CC_BEGIN
|
||||
|
||||
|
||||
const char *glpyhsASCII = "\"!#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþ";
|
||||
const char *glpyhsNEHE = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
|
||||
|
||||
std::map<std::string, FontDefinitionTTF *> CCFontCache::_fontsMap;
|
||||
|
||||
FontDefinitionTTF * CCFontCache::getFontDefinition(const char *fontFileName, int size, GlyphCollection glyphs)
|
||||
{
|
||||
std::string fontName = generateFontName(fontFileName, size);
|
||||
FontDefinitionTTF *tempDefinition = _fontsMap[fontName];
|
||||
|
||||
if ( !tempDefinition )
|
||||
{
|
||||
tempDefinition = FontDefinitionTTF::create(fontFileName, size, getGlyphCollection(glyphs));
|
||||
if (tempDefinition)
|
||||
{
|
||||
_fontsMap[fontName] = tempDefinition;
|
||||
}
|
||||
else
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
return tempDefinition;
|
||||
}
|
||||
|
||||
std::string CCFontCache::generateFontName(const char *fontFileName, int size)
|
||||
{
|
||||
std::string tempName(fontFileName);
|
||||
// std::to_string is not supported on android, using std::stringstream instead.
|
||||
std::stringstream ss;
|
||||
ss << size;
|
||||
return tempName + ss.str();
|
||||
}
|
||||
|
||||
bool CCFontCache::releaseFontDefinition(FontDefinitionTTF *def)
|
||||
{
|
||||
if (def)
|
||||
{
|
||||
for( auto &item: _fontsMap)
|
||||
{
|
||||
if ( item.second == def )
|
||||
{
|
||||
item.second->release();
|
||||
_fontsMap.erase(item.first);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
const char * CCFontCache::getGlyphCollection(GlyphCollection glyphs)
|
||||
{
|
||||
switch (glyphs)
|
||||
{
|
||||
case GlyphCollection::NEHE:
|
||||
return glpyhsNEHE;
|
||||
break;
|
||||
|
||||
case GlyphCollection::ASCII:
|
||||
return glpyhsASCII;
|
||||
break;
|
||||
|
||||
default:
|
||||
return 0;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
NS_CC_END
|
|
@ -0,0 +1,54 @@
|
|||
/****************************************************************************
|
||||
Copyright (c) 2013 Zynga 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.
|
||||
****************************************************************************/
|
||||
|
||||
#ifndef _CCFontCache_h_
|
||||
#define _CCFontCache_h_
|
||||
|
||||
#include <iostream>
|
||||
#include <map>
|
||||
|
||||
#include "cocos2d.h"
|
||||
#include "CCFontDefinition.h"
|
||||
|
||||
NS_CC_BEGIN
|
||||
|
||||
class CC_DLL CCFontCache
|
||||
{
|
||||
|
||||
public:
|
||||
|
||||
static FontDefinitionTTF * getFontDefinition(const char *fontFileName, int size, GlyphCollection glyphs);
|
||||
static bool releaseFontDefinition(FontDefinitionTTF *def);
|
||||
|
||||
private:
|
||||
|
||||
static std::string generateFontName(const char *fontFileName, int size);
|
||||
static std::map<std::string, FontDefinitionTTF *> _fontsMap;
|
||||
static const char * getGlyphCollection(GlyphCollection glyphs);
|
||||
|
||||
};
|
||||
|
||||
NS_CC_END
|
||||
|
||||
#endif
|
|
@ -0,0 +1,246 @@
|
|||
/****************************************************************************
|
||||
Copyright (c) 2013 Zynga 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.
|
||||
****************************************************************************/
|
||||
|
||||
#include "cocos2d.h"
|
||||
#include "CCFontDefinition.h"
|
||||
|
||||
NS_CC_BEGIN
|
||||
|
||||
|
||||
FontDefinitionTTF::FontDefinitionTTF():_textImages(0), _commonLineHeight(0)
|
||||
{
|
||||
}
|
||||
|
||||
FontDefinitionTTF* FontDefinitionTTF::create(const char *fontName, int fontSize, const char *letters, int textureSize )
|
||||
{
|
||||
FontDefinitionTTF *ret = new FontDefinitionTTF;
|
||||
|
||||
if(!ret)
|
||||
return 0;
|
||||
|
||||
if ( ret->initDefinition( fontName, fontSize, letters, textureSize ) )
|
||||
{
|
||||
return ret;
|
||||
}
|
||||
else
|
||||
{
|
||||
delete ret;
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
FontDefinitionTTF::~FontDefinitionTTF()
|
||||
{
|
||||
if (_textImages)
|
||||
{
|
||||
delete _textImages;
|
||||
}
|
||||
}
|
||||
|
||||
bool FontDefinitionTTF::prepareLetterDefinitions(TextFontPagesDef *pageDefs)
|
||||
{
|
||||
// get all the pages
|
||||
TextFontPagesDef *pPages = pageDefs;
|
||||
if (!pPages)
|
||||
return (false);
|
||||
|
||||
float maxLineHeight = -1;
|
||||
|
||||
// loops all the pages
|
||||
for (int cPages = 0; cPages<pPages->getNumPages(); ++cPages)
|
||||
{
|
||||
// loops all the lines in this page
|
||||
for (int cLines = 0; cLines<pPages->getPageAt(cPages)->getNumLines(); ++cLines)
|
||||
{
|
||||
float posXUV = 0.0;
|
||||
float posYUV = pPages->getPageAt(cPages)->getLineAt(cLines)->getY();
|
||||
|
||||
int charsCounter = 0;
|
||||
|
||||
for (int c = 0; c < pPages->getPageAt(cPages)->getLineAt(cLines)->getNumGlyph(); ++c)
|
||||
{
|
||||
|
||||
// the current glyph
|
||||
GlyphDef currentGlyph = pPages->getPageAt(cPages)->getLineAt(cLines)->getGlyphAt(c);
|
||||
|
||||
// letter width
|
||||
float letterWidth = currentGlyph.getRect().size.width;
|
||||
|
||||
// letter height
|
||||
float letterHeight = pPages->getPageAt(cPages)->getLineAt(cLines)->getHeight();
|
||||
|
||||
// add this letter definition
|
||||
FontLetterDefinition tempDef;
|
||||
|
||||
|
||||
// carloX little hack (this should be done outside the loop)
|
||||
if (posXUV == 0.0)
|
||||
posXUV = currentGlyph.getPadding();
|
||||
|
||||
tempDef.validDefinition = currentGlyph.isValid();
|
||||
|
||||
if (tempDef.validDefinition)
|
||||
{
|
||||
tempDef.letteCharUTF16 = currentGlyph.getUTF8Letter();
|
||||
tempDef.width = letterWidth + currentGlyph.getPadding();
|
||||
tempDef.height = (letterHeight - 1);
|
||||
tempDef.U = (posXUV - 1);
|
||||
tempDef.V = posYUV;
|
||||
|
||||
tempDef.offsetX = currentGlyph.getRect().origin.x;
|
||||
tempDef.offsetY = currentGlyph.getRect().origin.y;
|
||||
|
||||
tempDef.textureID = cPages;
|
||||
tempDef.commonLineHeight = currentGlyph.getCommonHeight();
|
||||
|
||||
// take from pixels to points
|
||||
tempDef.width = tempDef.width / CC_CONTENT_SCALE_FACTOR();
|
||||
tempDef.height = tempDef.height / CC_CONTENT_SCALE_FACTOR();
|
||||
tempDef.U = tempDef.U / CC_CONTENT_SCALE_FACTOR();
|
||||
tempDef.V = tempDef.V / CC_CONTENT_SCALE_FACTOR();
|
||||
|
||||
if (tempDef.commonLineHeight>maxLineHeight)
|
||||
maxLineHeight = tempDef.commonLineHeight;
|
||||
}
|
||||
else
|
||||
{
|
||||
tempDef.letteCharUTF16 = currentGlyph.getUTF8Letter();
|
||||
tempDef.commonLineHeight = 0;
|
||||
tempDef.width = 0;
|
||||
tempDef.height = 0;
|
||||
tempDef.U = 0;
|
||||
tempDef.V = 0;
|
||||
tempDef.offsetX = 0;
|
||||
tempDef.offsetY = 0;
|
||||
tempDef.textureID = 0;
|
||||
}
|
||||
|
||||
|
||||
// add this definition
|
||||
addLetterDefinition(tempDef);
|
||||
|
||||
// move bounding box to the next letter
|
||||
posXUV += letterWidth + currentGlyph.getPadding();
|
||||
|
||||
// next char in the string
|
||||
++charsCounter;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// store the common line height
|
||||
_commonLineHeight = maxLineHeight;
|
||||
|
||||
//
|
||||
return true;
|
||||
}
|
||||
|
||||
bool FontDefinitionTTF::initDefinition(const char *fontName, int fontSize, const char *letters, int textureSize)
|
||||
{
|
||||
// preare texture/image stuff
|
||||
_textImages = new TextImage();
|
||||
if (!_textImages)
|
||||
return false;
|
||||
|
||||
if (!_textImages->initWithString(letters, textureSize, textureSize, fontName, fontSize, true))
|
||||
{
|
||||
delete _textImages;
|
||||
_textImages = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
// prepare the new letter definition
|
||||
return prepareLetterDefinitions(_textImages->getPages());
|
||||
}
|
||||
|
||||
void FontDefinitionTTF::addLetterDefinition(FontLetterDefinition &defToAdd)
|
||||
{
|
||||
if (_fontLettersDefinitionUTF16.find(defToAdd.letteCharUTF16) == _fontLettersDefinitionUTF16.end())
|
||||
{
|
||||
_fontLettersDefinitionUTF16[defToAdd.letteCharUTF16] = defToAdd;
|
||||
}
|
||||
}
|
||||
|
||||
FontLetterDefinition & FontDefinitionTTF::getLetterDefinition(unsigned short int theLetter)
|
||||
{
|
||||
return _fontLettersDefinitionUTF16[theLetter];
|
||||
}
|
||||
|
||||
Texture2D * FontDefinitionTTF::getTexture(int index)
|
||||
{
|
||||
TextFontPagesDef *pPages = _textImages->getPages();
|
||||
|
||||
if (!pPages)
|
||||
return nullptr;
|
||||
|
||||
return pPages->getPageAt(index)->getPageTexture();
|
||||
}
|
||||
|
||||
int FontDefinitionTTF::getNumTextures()
|
||||
{
|
||||
TextFontPagesDef *pPages = _textImages->getPages();
|
||||
if (pPages)
|
||||
{
|
||||
return pPages->getNumPages();
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
FontAtlas * FontDefinitionTTF::createFontAtlas()
|
||||
{
|
||||
FontAtlas *retAtlas = new FontAtlas( *_textImages->getFont() );
|
||||
|
||||
if (!retAtlas)
|
||||
return 0;
|
||||
|
||||
// add all the textures
|
||||
int numTextures = getNumTextures();
|
||||
if (!numTextures)
|
||||
return 0;
|
||||
|
||||
for (int c = 0; c<numTextures; ++c)
|
||||
retAtlas->addTexture(*getTexture(c), c);
|
||||
|
||||
// set the common line height
|
||||
retAtlas->setCommonLineHeight(getCommonLineHeight() * 0.8);
|
||||
|
||||
|
||||
for( auto &item: _fontLettersDefinitionUTF16 )
|
||||
{
|
||||
if ( item.second.validDefinition )
|
||||
{
|
||||
FontLetterDefinition tempDefinition = item.second;
|
||||
tempDefinition.offsetX = 0;
|
||||
tempDefinition.anchorX = 0.0f;
|
||||
tempDefinition.anchorY = 1.0f;
|
||||
retAtlas->addLetterDefinition(tempDefinition);
|
||||
}
|
||||
}
|
||||
|
||||
// done here
|
||||
return retAtlas;
|
||||
}
|
||||
|
||||
NS_CC_END
|
|
@ -0,0 +1,67 @@
|
|||
/****************************************************************************
|
||||
Copyright (c) 2013 Zynga 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.
|
||||
****************************************************************************/
|
||||
|
||||
#ifndef _FontDefinition_h_
|
||||
#define _FontDefinition_h_
|
||||
|
||||
#include "CCTextImage.h"
|
||||
#include "CCFont.h"
|
||||
#include "CCFontAtlas.h"
|
||||
|
||||
NS_CC_BEGIN
|
||||
|
||||
#define DEFAULT_ATLAS_TEXTURE_SIZE 1024
|
||||
|
||||
/**
|
||||
*/
|
||||
class CC_DLL FontDefinitionTTF : public Object
|
||||
{
|
||||
public:
|
||||
|
||||
static FontDefinitionTTF* create(const char *fontName, int fontSize, const char *letters, int textureSize = DEFAULT_ATLAS_TEXTURE_SIZE);
|
||||
FontLetterDefinition & getLetterDefinition(unsigned short int theLetter);
|
||||
Texture2D * getTexture(int index);
|
||||
int getNumTextures();
|
||||
Font * getFont() { return _textImages->getFont(); }
|
||||
float getCommonLineHeight() { return _commonLineHeight; }
|
||||
FontAtlas * createFontAtlas();
|
||||
|
||||
private:
|
||||
|
||||
FontDefinitionTTF();
|
||||
~FontDefinitionTTF();
|
||||
|
||||
bool initDefinition(const char *fontName, int fontSize, const char *letters, int textureSize);
|
||||
bool prepareLetterDefinitions(TextFontPagesDef *pageDefs);
|
||||
void addLetterDefinition(FontLetterDefinition &defToAdd);
|
||||
|
||||
TextImage * _textImages;
|
||||
std::map<unsigned short, FontLetterDefinition> _fontLettersDefinitionUTF16;
|
||||
float _commonLineHeight;
|
||||
|
||||
};
|
||||
|
||||
NS_CC_END
|
||||
|
||||
#endif
|
|
@ -0,0 +1,103 @@
|
|||
//
|
||||
// CCFontFNT.cpp
|
||||
// cocos2d_libs
|
||||
//
|
||||
// Created by Carlo Morgantini on 7/24/13.
|
||||
//
|
||||
//
|
||||
|
||||
#include "CCFontFNT.h"
|
||||
|
||||
|
||||
NS_CC_BEGIN
|
||||
|
||||
|
||||
FontFNT::~FontFNT()
|
||||
{
|
||||
if (_configuration)
|
||||
_configuration->release();
|
||||
}
|
||||
|
||||
Size * FontFNT::getAdvancesForTextUTF16(unsigned short *pText, int &outNumLetters)
|
||||
{
|
||||
if (!pText)
|
||||
return 0;
|
||||
|
||||
outNumLetters = cc_wcslen(pText);
|
||||
|
||||
if (!outNumLetters)
|
||||
return 0;
|
||||
|
||||
Size *pSizes = new Size[outNumLetters];
|
||||
if (!pSizes)
|
||||
return 0;
|
||||
|
||||
for (int c = 0; c<outNumLetters; ++c)
|
||||
{
|
||||
int advance = 0;
|
||||
int kerning = 0;
|
||||
|
||||
advance = getAdvanceForChar(pText[c]);
|
||||
|
||||
if ( c < (outNumLetters-1) )
|
||||
kerning = getHorizontalKerningForChars(pText[c], pText[c+1]);
|
||||
|
||||
pSizes[c].width = (advance + kerning);
|
||||
}
|
||||
|
||||
return pSizes;
|
||||
}
|
||||
|
||||
int FontFNT::getAdvanceForChar(unsigned short theChar)
|
||||
{
|
||||
tFontDefHashElement *element = NULL;
|
||||
|
||||
// unichar is a short, and an int is needed on HASH_FIND_INT
|
||||
unsigned int key = theChar;
|
||||
HASH_FIND_INT(_configuration->_fontDefDictionary, &key, element);
|
||||
if (! element)
|
||||
return -1;
|
||||
|
||||
return element->fontDef.xAdvance;
|
||||
}
|
||||
|
||||
int FontFNT::getHorizontalKerningForChars(unsigned short firstChar, unsigned short secondChar)
|
||||
{
|
||||
int ret = 0;
|
||||
unsigned int key = (firstChar<<16) | (secondChar & 0xffff);
|
||||
|
||||
if( _configuration->_kerningDictionary )
|
||||
{
|
||||
tKerningHashElement *element = NULL;
|
||||
HASH_FIND_INT(_configuration->_kerningDictionary, &key, element);
|
||||
|
||||
if(element)
|
||||
ret = element->amount;
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
Rect FontFNT::getRectForCharInternal(unsigned short theChar)
|
||||
{
|
||||
Rect retRect;
|
||||
ccBMFontDef fontDef;
|
||||
tFontDefHashElement *element = NULL;
|
||||
unsigned int key = theChar;
|
||||
|
||||
HASH_FIND_INT(_configuration->_fontDefDictionary, &key, element);
|
||||
|
||||
if (element)
|
||||
{
|
||||
retRect = element->fontDef.rect;
|
||||
}
|
||||
|
||||
return retRect;
|
||||
}
|
||||
|
||||
Rect FontFNT::getRectForChar(unsigned short theChar)
|
||||
{
|
||||
return getRectForCharInternal(theChar);
|
||||
}
|
||||
|
||||
NS_CC_END
|
|
@ -0,0 +1,55 @@
|
|||
/****************************************************************************
|
||||
Copyright (c) 2013 Zynga 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.
|
||||
****************************************************************************/
|
||||
|
||||
#ifndef _CCFontFNT_h_
|
||||
#define _CCFontFNT_h_
|
||||
|
||||
#include "cocos2d.h"
|
||||
#include "CCFont.h"
|
||||
|
||||
NS_CC_BEGIN
|
||||
|
||||
class FontFNT : public Font
|
||||
{
|
||||
|
||||
public:
|
||||
|
||||
FontFNT(CCBMFontConfiguration *theContfig) : _configuration(theContfig) {}
|
||||
virtual ~FontFNT();
|
||||
virtual Size* getAdvancesForTextUTF16(unsigned short *pText, int &outNumLetters);
|
||||
virtual Rect getRectForChar(unsigned short theChar);
|
||||
|
||||
private:
|
||||
|
||||
int getAdvanceForChar(unsigned short theChar);
|
||||
int getHorizontalKerningForChars(unsigned short firstChar, unsigned short secondChar);
|
||||
Rect getRectForCharInternal(unsigned short theChar);
|
||||
|
||||
CCBMFontConfiguration * _configuration;
|
||||
|
||||
};
|
||||
|
||||
NS_CC_END
|
||||
|
||||
#endif /* defined(__cocos2d_libs__CCFontFNT__) */
|
|
@ -0,0 +1,339 @@
|
|||
/****************************************************************************
|
||||
Copyright (c) 2013 Zynga 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.
|
||||
****************************************************************************/
|
||||
|
||||
#include <stdio.h>
|
||||
#include "cocos2d.h"
|
||||
#include "support/ccUTF8.h"
|
||||
#include "CCFontFreeType.h"
|
||||
#include "CCTextImage.h"
|
||||
|
||||
NS_CC_BEGIN
|
||||
|
||||
|
||||
FT_Library FontFreeType::_FTlibrary;
|
||||
bool FontFreeType::_FTInitialized = false;
|
||||
|
||||
|
||||
|
||||
bool FontFreeType::initFreeType()
|
||||
{
|
||||
if (_FTInitialized == false)
|
||||
{
|
||||
// begin freetype
|
||||
if (FT_Init_FreeType( &_FTlibrary ))
|
||||
return false;
|
||||
|
||||
_FTInitialized = true;
|
||||
}
|
||||
|
||||
return _FTInitialized;
|
||||
}
|
||||
|
||||
void FontFreeType::shutdownFreeType()
|
||||
{
|
||||
if (_FTInitialized == true)
|
||||
{
|
||||
FT_Done_FreeType(_FTlibrary);
|
||||
}
|
||||
}
|
||||
|
||||
FT_Library FontFreeType::getFTLibrary()
|
||||
{
|
||||
initFreeType();
|
||||
return _FTlibrary;
|
||||
}
|
||||
|
||||
FontFreeType::FontFreeType() : _letterPadding(5)
|
||||
{
|
||||
}
|
||||
|
||||
bool FontFreeType::createFontObject(const std::string &fontName, int fontSize)
|
||||
{
|
||||
unsigned char* data = NULL;
|
||||
int dpi = 72;
|
||||
|
||||
int len = 0;
|
||||
data = FileUtils::getInstance()->getFileData(fontName.c_str(), "rb", (unsigned long *)(&len) );
|
||||
|
||||
if (!data)
|
||||
return false;
|
||||
|
||||
// create the new face
|
||||
FT_Face face;
|
||||
|
||||
// create the face from the data
|
||||
if ( FT_New_Memory_Face(getFTLibrary(), data, len, 0, &face ) )
|
||||
return false;
|
||||
|
||||
//we want to use unicode
|
||||
if( FT_Select_Charmap(face, FT_ENCODING_UNICODE) )
|
||||
return false;
|
||||
|
||||
// set the requested font size
|
||||
int fontSizePoints = (int)(64.f * fontSize);
|
||||
if( FT_Set_Char_Size(face, fontSizePoints, fontSizePoints, dpi, dpi) )
|
||||
return false;
|
||||
|
||||
// store the face globally
|
||||
_fontRef = face;
|
||||
|
||||
// save font name locally
|
||||
_fontName = fontName;
|
||||
|
||||
// done and good
|
||||
return true;
|
||||
}
|
||||
|
||||
FontFreeType::~FontFreeType()
|
||||
{
|
||||
// release the font
|
||||
// TO DO
|
||||
}
|
||||
|
||||
bool FontFreeType::getBBOXFotChar(unsigned short theChar, Rect &outRect)
|
||||
{
|
||||
if (!_fontRef)
|
||||
return false;
|
||||
|
||||
// get the ID to the char we need
|
||||
int glyph_index = FT_Get_Char_Index(_fontRef, theChar);
|
||||
|
||||
if (!glyph_index)
|
||||
return false;
|
||||
|
||||
// load glyph infos
|
||||
if (FT_Load_Glyph(_fontRef, glyph_index, FT_LOAD_DEFAULT))
|
||||
return false;
|
||||
|
||||
// store result in the passed rectangle
|
||||
outRect.origin.x = 0;
|
||||
outRect.origin.y = - (_fontRef->glyph->metrics.horiBearingY >> 6);
|
||||
outRect.size.width = (_fontRef->glyph->metrics.width >> 6);
|
||||
outRect.size.height = (_fontRef->glyph->metrics.height >> 6);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
GlyphDef * FontFreeType::getGlyphDefintionsForText(const char *pText, int &outNumGlyphs, bool UTF16text)
|
||||
{
|
||||
unsigned short* utf16String = 0;
|
||||
|
||||
if (UTF16text)
|
||||
{
|
||||
utf16String = (unsigned short*) pText;
|
||||
}
|
||||
else
|
||||
{
|
||||
utf16String = cc_utf8_to_utf16(pText);
|
||||
}
|
||||
|
||||
//
|
||||
if (!utf16String)
|
||||
return 0;
|
||||
|
||||
int numChar = cc_wcslen(utf16String);
|
||||
if (!numChar)
|
||||
return 0;
|
||||
|
||||
// allocate the needed Glyphs
|
||||
GlyphDef *pGlyphs = new GlyphDef[numChar];
|
||||
assert( pGlyphs != NULL );
|
||||
if (!pGlyphs)
|
||||
return 0;
|
||||
|
||||
// sore result as CCRect
|
||||
for (int c=0; c<numChar; ++c)
|
||||
{
|
||||
Rect tempRect;
|
||||
|
||||
if( !getBBOXFotChar(utf16String[c], tempRect) )
|
||||
{
|
||||
log("Warning: Cannot find definition for glyph: %c in font:%s", utf16String[c], _fontName.c_str());
|
||||
|
||||
tempRect.origin.x = 0;
|
||||
tempRect.origin.y = 0;
|
||||
tempRect.size.width = 0;
|
||||
tempRect.size.height = 0;
|
||||
|
||||
pGlyphs[c].setRect(tempRect);
|
||||
pGlyphs[c].setUTF16Letter(utf16String[c]);
|
||||
pGlyphs[c].setValid(false);
|
||||
pGlyphs[c].setPadding(_letterPadding);
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
pGlyphs[c].setRect(tempRect);
|
||||
pGlyphs[c].setUTF16Letter(utf16String[c]);
|
||||
pGlyphs[c].setPadding(_letterPadding);
|
||||
pGlyphs[c].setValid(true);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
outNumGlyphs = numChar;
|
||||
|
||||
// free memory
|
||||
if (!UTF16text)
|
||||
delete [] utf16String;
|
||||
|
||||
// done
|
||||
return pGlyphs;
|
||||
}
|
||||
|
||||
Size * FontFreeType::getAdvancesForTextUTF16(unsigned short *pText, int &outNumLetters)
|
||||
{
|
||||
if (!pText)
|
||||
return 0;
|
||||
|
||||
outNumLetters = cc_wcslen(pText);
|
||||
|
||||
if (!outNumLetters)
|
||||
return 0;
|
||||
|
||||
Size *pSizes = new Size[outNumLetters];
|
||||
if (!pSizes)
|
||||
return 0;
|
||||
|
||||
for (int c = 0; c<outNumLetters; ++c)
|
||||
{
|
||||
int advance = 0;
|
||||
int kerning = 0;
|
||||
|
||||
advance = getAdvanceForChar(pText[c]) - getBearingXForChar(pText[c]);
|
||||
|
||||
if ( c < (outNumLetters-1) )
|
||||
kerning = getHorizontalKerningForChars(pText[c], pText[c+1]);
|
||||
|
||||
pSizes[c].width = (advance + kerning);
|
||||
}
|
||||
|
||||
return pSizes;
|
||||
}
|
||||
|
||||
int FontFreeType::getAdvanceForChar(unsigned short theChar)
|
||||
{
|
||||
if (!_fontRef)
|
||||
return 0;
|
||||
|
||||
// get the ID to the char we need
|
||||
int glyph_index = FT_Get_Char_Index(_fontRef, theChar);
|
||||
|
||||
if (!glyph_index)
|
||||
return 0;
|
||||
|
||||
// load glyph infos
|
||||
if (FT_Load_Glyph(_fontRef, glyph_index, FT_LOAD_DEFAULT))
|
||||
return 0;
|
||||
|
||||
// get to the advance for this glyph
|
||||
return (_fontRef->glyph->advance.x >> 6);
|
||||
}
|
||||
|
||||
int FontFreeType::getBearingXForChar(unsigned short theChar)
|
||||
{
|
||||
|
||||
if (!_fontRef)
|
||||
return 0;
|
||||
|
||||
// get the ID to the char we need
|
||||
int glyph_index = FT_Get_Char_Index(_fontRef, theChar);
|
||||
|
||||
if (!glyph_index)
|
||||
return 0;
|
||||
|
||||
// load glyph infos
|
||||
if (FT_Load_Glyph(_fontRef, glyph_index, FT_LOAD_DEFAULT))
|
||||
return 0;
|
||||
|
||||
return (_fontRef->glyph->metrics.horiBearingX >>6);
|
||||
}
|
||||
|
||||
int FontFreeType::getHorizontalKerningForChars(unsigned short firstChar, unsigned short secondChar)
|
||||
{
|
||||
if (!_fontRef)
|
||||
return 0;
|
||||
|
||||
bool hasKerning = FT_HAS_KERNING( _fontRef );
|
||||
|
||||
if (!hasKerning)
|
||||
return 0;
|
||||
|
||||
// get the ID to the char we need
|
||||
int glyph_index1 = FT_Get_Char_Index(_fontRef, firstChar);
|
||||
|
||||
if (!glyph_index1)
|
||||
return 0;
|
||||
|
||||
// get the ID to the char we need
|
||||
int glyph_index2 = FT_Get_Char_Index(_fontRef, secondChar);
|
||||
|
||||
if (!glyph_index2)
|
||||
return 0;
|
||||
|
||||
FT_Vector kerning;
|
||||
|
||||
if (FT_Get_Kerning( _fontRef, glyph_index1, glyph_index2, FT_KERNING_DEFAULT, &kerning ))
|
||||
return 0;
|
||||
|
||||
return ( kerning.x >> 6 );
|
||||
}
|
||||
|
||||
int FontFreeType::getFontMaxHeight()
|
||||
{
|
||||
return (_fontRef->size->metrics.height >> 6);
|
||||
}
|
||||
|
||||
unsigned char * FontFreeType::getGlyphBitmap(unsigned short theChar, int &outWidth, int &outHeight)
|
||||
{
|
||||
if (!_fontRef)
|
||||
return 0;
|
||||
|
||||
// get the ID to the char we need
|
||||
int glyph_index = FT_Get_Char_Index(_fontRef, theChar);
|
||||
|
||||
if (!glyph_index)
|
||||
return 0;
|
||||
|
||||
// load glyph infos
|
||||
if (FT_Load_Glyph(_fontRef, glyph_index, FT_LOAD_DEFAULT))
|
||||
return 0;
|
||||
|
||||
if (FT_Render_Glyph( _fontRef->glyph, FT_RENDER_MODE_NORMAL ))
|
||||
return 0;
|
||||
|
||||
outWidth = _fontRef->glyph->bitmap.width;
|
||||
outHeight = _fontRef->glyph->bitmap.rows;
|
||||
|
||||
// return the pointer to the bitmap
|
||||
return _fontRef->glyph->bitmap.buffer;
|
||||
}
|
||||
|
||||
int FontFreeType::getLetterPadding()
|
||||
{
|
||||
return _letterPadding;
|
||||
}
|
||||
|
||||
NS_CC_END
|
|
@ -0,0 +1,73 @@
|
|||
/****************************************************************************
|
||||
Copyright (c) 2013 Zynga 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.
|
||||
****************************************************************************/
|
||||
|
||||
#ifndef _FontFreetype_h_
|
||||
#define _FontFreetype_h_
|
||||
|
||||
#include "CCFont.h"
|
||||
#include <string>
|
||||
#include <ft2build.h>
|
||||
#include FT_FREETYPE_H
|
||||
|
||||
NS_CC_BEGIN
|
||||
|
||||
class CC_DLL FontFreeType : public Font
|
||||
{
|
||||
public:
|
||||
|
||||
FontFreeType();
|
||||
virtual ~FontFreeType();
|
||||
|
||||
virtual Size * getAdvancesForTextUTF16(unsigned short *pText, int &outNumLetters);
|
||||
|
||||
virtual bool createFontObject(const std::string &fontName, int fontSize);
|
||||
virtual GlyphDef * getGlyphDefintionsForText(const char *pText, int &outNumGlyphs, bool UTF16text = false);
|
||||
unsigned char * getGlyphBitmap(unsigned short theChar, int &outWidth, int &outHeight);
|
||||
virtual int getFontMaxHeight();
|
||||
virtual int getLetterPadding();
|
||||
|
||||
private:
|
||||
|
||||
bool initFreeType();
|
||||
void shutdownFreeType();
|
||||
FT_Library getFTLibrary();
|
||||
|
||||
bool getBBOXFotChar(unsigned short theChar, Rect &outRect);
|
||||
int getAdvanceForChar(unsigned short theChar);
|
||||
int getBearingXForChar(unsigned short theChar);
|
||||
int getHorizontalKerningForChars(unsigned short firstChar, unsigned short secondChar);
|
||||
|
||||
static FT_Library _FTlibrary;
|
||||
static bool _FTInitialized;
|
||||
|
||||
FT_Face _fontRef;
|
||||
const int _letterPadding;
|
||||
|
||||
std::string _fontName;
|
||||
|
||||
};
|
||||
|
||||
NS_CC_END
|
||||
|
||||
#endif
|
|
@ -0,0 +1,51 @@
|
|||
/****************************************************************************
|
||||
Copyright (c) 2013 Zynga 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.
|
||||
****************************************************************************/
|
||||
|
||||
#ifndef _FontRender_h_
|
||||
#define _FontRender_h_
|
||||
|
||||
NS_CC_BEGIN
|
||||
|
||||
// FWD
|
||||
class Font;
|
||||
class TextPageDef;
|
||||
|
||||
class CC_DLL FontRender
|
||||
{
|
||||
|
||||
public:
|
||||
|
||||
FontRender(Font *pFont) { _font = pFont; }
|
||||
virtual ~FontRender() {}
|
||||
virtual unsigned char * preparePageGlyphData(TextPageDef *thePage) = 0;
|
||||
|
||||
protected:
|
||||
|
||||
Font * _font;
|
||||
};
|
||||
|
||||
NS_CC_END
|
||||
|
||||
|
||||
#endif
|
|
@ -0,0 +1,138 @@
|
|||
/****************************************************************************
|
||||
Copyright (c) 2013 Zynga 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.
|
||||
****************************************************************************/
|
||||
|
||||
#include "cocos2d.h"
|
||||
#include "CCTextImage.h"
|
||||
#include "CCFontRenderFreeType.h"
|
||||
|
||||
#include <ft2build.h>
|
||||
#include FT_FREETYPE_H
|
||||
|
||||
//#define _DEBUG_FONTS_
|
||||
#ifdef _DEBUG_FONTS_
|
||||
#include "CCImage.h"
|
||||
#endif
|
||||
|
||||
|
||||
NS_CC_BEGIN
|
||||
|
||||
bool FontRenderFreeType::renderCharAt(unsigned short int charToRender, int posX, int posY, unsigned char *destMemory, int destSize)
|
||||
{
|
||||
if (!_font)
|
||||
return false;
|
||||
|
||||
unsigned char *sourceBitmap = 0;
|
||||
int sourceWidth = 0;
|
||||
int sourceHeight = 0;
|
||||
|
||||
// get the glyph's bitmap
|
||||
sourceBitmap = _font->getGlyphBitmap(charToRender, sourceWidth, sourceHeight);
|
||||
|
||||
if(!sourceBitmap)
|
||||
return false;
|
||||
|
||||
int iX = posX;
|
||||
int iY = posY;
|
||||
|
||||
for (int y = 0; y < sourceHeight; ++y)
|
||||
{
|
||||
int bitmap_y = y * sourceWidth;
|
||||
|
||||
for (int x = 0; x < sourceWidth; ++x)
|
||||
{
|
||||
unsigned char cTemp = sourceBitmap[bitmap_y + x];
|
||||
|
||||
// the final pixel
|
||||
int iTemp = cTemp << 24 | cTemp << 16 | cTemp << 8 | cTemp;
|
||||
*(int*) &destMemory[(iX + ( iY * destSize ) ) * 4] = iTemp;
|
||||
|
||||
iX += 1;
|
||||
}
|
||||
|
||||
iX = posX;
|
||||
iY += 1;
|
||||
}
|
||||
|
||||
//everything good
|
||||
return true;
|
||||
}
|
||||
|
||||
unsigned char * FontRenderFreeType::preparePageGlyphData(TextPageDef *thePage)
|
||||
{
|
||||
if (!thePage)
|
||||
return 0;
|
||||
|
||||
if (!_font)
|
||||
return 0;
|
||||
|
||||
if (thePage->getNumLines() == 0)
|
||||
return NULL;
|
||||
|
||||
int pageWidth = thePage->getWidth();
|
||||
int pageHeight = thePage->getHeight();
|
||||
|
||||
// prepare memory and clean to 0
|
||||
int sizeInBytes = (pageWidth * pageHeight * 4);
|
||||
unsigned char* data = new unsigned char[sizeInBytes];
|
||||
|
||||
if (!data)
|
||||
return 0;
|
||||
|
||||
memset(data, 0, sizeInBytes);
|
||||
|
||||
int numLines = thePage->getNumLines();
|
||||
|
||||
for (int c = 0; c<numLines; ++c)
|
||||
{
|
||||
TextLineDef *pCurrentLine = thePage->getLineAt(c);
|
||||
|
||||
float origX = _font->getLetterPadding();
|
||||
float origY = pCurrentLine->getY();
|
||||
|
||||
int numGlyphToRender = pCurrentLine->getNumGlyph();
|
||||
|
||||
for (int cglyph = 0; cglyph < numGlyphToRender; ++cglyph)
|
||||
{
|
||||
GlyphDef currGlyph = pCurrentLine->getGlyphAt(cglyph);
|
||||
renderCharAt(currGlyph.getUTF8Letter(), origX, origY, data, pageWidth);
|
||||
origX += (currGlyph.getRect().size.width + _font->getLetterPadding());
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef _DEBUG_FONTS_
|
||||
static int counter = 0;
|
||||
char outFilename[512];
|
||||
sprintf(outFilename,"carlottone%d", counter);
|
||||
++counter;
|
||||
Image *pImage = new Image;
|
||||
pImage->initWithRawData(data, (pageWidth * pageWidth * 4), 1024, 1024, 8, false);
|
||||
pImage->saveToFile(outFilename);
|
||||
#endif
|
||||
|
||||
// we are done here
|
||||
return data;
|
||||
}
|
||||
|
||||
|
||||
NS_CC_END
|
|
@ -0,0 +1,48 @@
|
|||
/****************************************************************************
|
||||
Copyright (c) 2013 Zynga 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.
|
||||
****************************************************************************/
|
||||
|
||||
#ifndef _FontRenderFreeType_h_
|
||||
#define _FontRenderFreeType_h_
|
||||
|
||||
#include "CCFontRender.h"
|
||||
|
||||
NS_CC_BEGIN
|
||||
|
||||
class CC_DLL FontRenderFreeType : public FontRender
|
||||
{
|
||||
public:
|
||||
|
||||
FontRenderFreeType(Font *pFont): FontRender(pFont) {}
|
||||
virtual ~FontRenderFreeType() {}
|
||||
virtual unsigned char * preparePageGlyphData(TextPageDef *thePage);
|
||||
|
||||
private:
|
||||
|
||||
bool renderCharAt(unsigned short int charToRender, int posX, int posY, unsigned char *destMemory, int destSize);
|
||||
|
||||
};
|
||||
|
||||
NS_CC_END
|
||||
|
||||
#endif
|
|
@ -0,0 +1,88 @@
|
|||
/****************************************************************************
|
||||
Copyright (c) 2013 Zynga 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.
|
||||
****************************************************************************/
|
||||
|
||||
#include "CCLabel.h"
|
||||
#include "CCStringBMFont.h"
|
||||
#include "CCStringTTF.h"
|
||||
#include "CCFontDefinition.h"
|
||||
#include "CCFontCache.h"
|
||||
#include "CCFontAtlasCache.h"
|
||||
|
||||
NS_CC_BEGIN
|
||||
|
||||
Label* Label::createWithTTF( const char* label, const char* fntFilePath, int fontSize, GlyphCollection glyphs, int lineSize, const char *customGlyphs )
|
||||
{
|
||||
FontAtlas *tempAtlas = FontAtlasCache::getFontAtlasTTF(fntFilePath, fontSize, glyphs, customGlyphs);
|
||||
if (!tempAtlas)
|
||||
return nullptr;
|
||||
|
||||
// create the actual label
|
||||
StringTTF* templabel = StringTTF::create(tempAtlas, TextHAlignment::CENTER, lineSize);
|
||||
|
||||
if (templabel)
|
||||
{
|
||||
templabel->setText(label, lineSize, TextHAlignment::CENTER, false);
|
||||
return templabel;
|
||||
}
|
||||
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
Label* Label::createWithBMFont( const char* label, const char* bmfontFilePath, int lineSize)
|
||||
{
|
||||
FontAtlas *tempAtlas = FontAtlasCache::getFontAtlasFNT(bmfontFilePath);
|
||||
|
||||
if (!tempAtlas)
|
||||
return 0;
|
||||
|
||||
StringTTF* templabel = StringTTF::create(tempAtlas, TextHAlignment::CENTER, lineSize);
|
||||
|
||||
if (templabel)
|
||||
{
|
||||
templabel->setText(label, lineSize, TextHAlignment::CENTER, false);
|
||||
return templabel;
|
||||
}
|
||||
else
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
Label::Label()
|
||||
{
|
||||
}
|
||||
|
||||
Label::~Label()
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
// TESTING STUFF THAT NEEDS TO GO ////////////////////////////////////////////////////////////////
|
||||
Label* Label::createWithBMFontOLD( const char* label, const char* bmfontFilePath, int lineSize)
|
||||
{
|
||||
return StringBMFont::create(label, bmfontFilePath, lineSize);
|
||||
}
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
NS_CC_END
|
|
@ -0,0 +1,71 @@
|
|||
/****************************************************************************
|
||||
Copyright (c) 2013 Zynga 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.
|
||||
****************************************************************************/
|
||||
|
||||
|
||||
#ifndef _COCOS2D_CCLABEL_H_
|
||||
#define _COCOS2D_CCLABEL_H_
|
||||
|
||||
#include "sprite_nodes/CCSpriteBatchNode.h"
|
||||
|
||||
NS_CC_BEGIN
|
||||
|
||||
enum class GlyphCollection {
|
||||
|
||||
DYNAMIC,
|
||||
NEHE,
|
||||
ASCII,
|
||||
CUSTOM
|
||||
|
||||
};
|
||||
|
||||
class CC_DLL Label : public SpriteBatchNode, public LabelProtocol, public RGBAProtocol
|
||||
{
|
||||
public:
|
||||
|
||||
static Label* createWithTTF( const char* label, const char* fntFilePath, int fontSize, GlyphCollection glyphs = GlyphCollection::NEHE, int lineSize = 0, const char *customGlyphs = 0 );
|
||||
static Label* createWithBMFont( const char* label, const char* bmfontFilePath, int lineSize = 0 );
|
||||
|
||||
virtual ~Label();
|
||||
Label();
|
||||
|
||||
virtual void setAlignment(TextHAlignment alignment) = 0;
|
||||
virtual void setWidth(float width) = 0;
|
||||
virtual void setLineBreakWithoutSpace(bool breakWithoutSpace) = 0;
|
||||
virtual void setScale(float scale) = 0;
|
||||
virtual void setScaleX(float scaleX) = 0;
|
||||
virtual void setScaleY(float scaleY) = 0;
|
||||
|
||||
|
||||
// needs to go - TEST STUFF /////////////////////////////////////////////////////////////////////////
|
||||
static Label* createWithBMFontOLD( const char* label, const char* bmfontFilePath, int lineSize = 0);
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
private:
|
||||
|
||||
|
||||
};
|
||||
|
||||
NS_CC_END
|
||||
|
||||
#endif /*__COCOS2D_CCLABEL_H */
|
|
@ -430,23 +430,23 @@ LabelBMFont * LabelBMFont::create()
|
|||
return NULL;
|
||||
}
|
||||
|
||||
LabelBMFont * LabelBMFont::create(const char *str, const char *fntFile, float width, Label::HAlignment alignment)
|
||||
LabelBMFont * LabelBMFont::create(const char *str, const char *fntFile, float width, TextHAlignment alignment)
|
||||
{
|
||||
return LabelBMFont::create(str, fntFile, width, alignment, Point::ZERO);
|
||||
}
|
||||
|
||||
LabelBMFont * LabelBMFont::create(const char *str, const char *fntFile, float width)
|
||||
{
|
||||
return LabelBMFont::create(str, fntFile, width, Label::HAlignment::LEFT, Point::ZERO);
|
||||
return LabelBMFont::create(str, fntFile, width, TextHAlignment::LEFT, Point::ZERO);
|
||||
}
|
||||
|
||||
LabelBMFont * LabelBMFont::create(const char *str, const char *fntFile)
|
||||
{
|
||||
return LabelBMFont::create(str, fntFile, kLabelAutomaticWidth, Label::HAlignment::LEFT, Point::ZERO);
|
||||
return LabelBMFont::create(str, fntFile, kLabelAutomaticWidth, TextHAlignment::LEFT, Point::ZERO);
|
||||
}
|
||||
|
||||
//LabelBMFont - Creation & Init
|
||||
LabelBMFont *LabelBMFont::create(const char *str, const char *fntFile, float width/* = kLabelAutomaticWidth*/, Label::HAlignment alignment/* = Label::HAlignment::LEFT*/, Point imageOffset/* = Point::ZERO*/)
|
||||
LabelBMFont *LabelBMFont::create(const char *str, const char *fntFile, float width/* = kLabelAutomaticWidth*/, TextHAlignment alignment/* = TextHAlignment::LEFT*/, Point imageOffset/* = Point::ZERO*/)
|
||||
{
|
||||
LabelBMFont *pRet = new LabelBMFont();
|
||||
if(pRet && pRet->initWithString(str, fntFile, width, alignment, imageOffset))
|
||||
|
@ -460,10 +460,10 @@ LabelBMFont *LabelBMFont::create(const char *str, const char *fntFile, float wid
|
|||
|
||||
bool LabelBMFont::init()
|
||||
{
|
||||
return initWithString(NULL, NULL, kLabelAutomaticWidth, Label::HAlignment::LEFT, Point::ZERO);
|
||||
return initWithString(NULL, NULL, kLabelAutomaticWidth, TextHAlignment::LEFT, Point::ZERO);
|
||||
}
|
||||
|
||||
bool LabelBMFont::initWithString(const char *theString, const char *fntFile, float width/* = kLabelAutomaticWidth*/, Label::HAlignment alignment/* = Label::HAlignment::LEFT*/, Point imageOffset/* = Point::ZERO*/)
|
||||
bool LabelBMFont::initWithString(const char *theString, const char *fntFile, float width/* = kLabelAutomaticWidth*/, TextHAlignment alignment/* = TextHAlignment::LEFT*/, Point imageOffset/* = Point::ZERO*/)
|
||||
{
|
||||
CCASSERT(!_configuration, "re-init is no longer supported");
|
||||
CCASSERT( (theString && fntFile) || (theString==NULL && fntFile==NULL), "Invalid params for LabelBMFont");
|
||||
|
@ -530,7 +530,7 @@ bool LabelBMFont::initWithString(const char *theString, const char *fntFile, flo
|
|||
LabelBMFont::LabelBMFont()
|
||||
: _string(NULL)
|
||||
, _initialString(NULL)
|
||||
, _alignment(Label::HAlignment::CENTER)
|
||||
, _alignment(TextHAlignment::CENTER)
|
||||
, _width(-1.0f)
|
||||
, _configuration(NULL)
|
||||
, _lineBreakWithoutSpaces(false)
|
||||
|
@ -1094,7 +1094,7 @@ void LabelBMFont::updateLabel()
|
|||
}
|
||||
|
||||
// Step 2: Make alignment
|
||||
if (_alignment != Label::HAlignment::LEFT)
|
||||
if (_alignment != TextHAlignment::LEFT)
|
||||
{
|
||||
int i = 0;
|
||||
|
||||
|
@ -1125,10 +1125,10 @@ void LabelBMFont::updateLabel()
|
|||
float shift = 0;
|
||||
switch (_alignment)
|
||||
{
|
||||
case Label::HAlignment::CENTER:
|
||||
case TextHAlignment::CENTER:
|
||||
shift = getContentSize().width/2.0f - lineWidth/2.0f;
|
||||
break;
|
||||
case Label::HAlignment::RIGHT:
|
||||
case TextHAlignment::RIGHT:
|
||||
shift = getContentSize().width - lineWidth;
|
||||
break;
|
||||
default:
|
||||
|
@ -1160,7 +1160,7 @@ void LabelBMFont::updateLabel()
|
|||
}
|
||||
|
||||
// LabelBMFont - Alignment
|
||||
void LabelBMFont::setAlignment(Label::HAlignment alignment)
|
||||
void LabelBMFont::setAlignment(TextHAlignment alignment)
|
||||
{
|
||||
this->_alignment = alignment;
|
||||
updateLabel();
|
||||
|
|
|
@ -192,9 +192,9 @@ public:
|
|||
static void purgeCachedData();
|
||||
|
||||
/** creates a bitmap font atlas with an initial string and the FNT file */
|
||||
static LabelBMFont * create(const char *str, const char *fntFile, float width, Label::HAlignment alignment, Point imageOffset);
|
||||
static LabelBMFont * create(const char *str, const char *fntFile, float width, TextHAlignment alignment, Point imageOffset);
|
||||
|
||||
static LabelBMFont * create(const char *str, const char *fntFile, float width, Label::HAlignment alignment);
|
||||
static LabelBMFont * create(const char *str, const char *fntFile, float width, TextHAlignment alignment);
|
||||
|
||||
static LabelBMFont * create(const char *str, const char *fntFile, float width);
|
||||
|
||||
|
@ -206,7 +206,7 @@ public:
|
|||
|
||||
bool init();
|
||||
/** init a bitmap font atlas with an initial string and the FNT file */
|
||||
bool initWithString(const char *str, const char *fntFile, float width = kLabelAutomaticWidth, Label::HAlignment alignment = Label::HAlignment::LEFT, Point imageOffset = Point::ZERO);
|
||||
bool initWithString(const char *str, const char *fntFile, float width = kLabelAutomaticWidth, TextHAlignment alignment = TextHAlignment::LEFT, Point imageOffset = Point::ZERO);
|
||||
|
||||
/** updates the font chars based on the string to render */
|
||||
void createFontChars();
|
||||
|
@ -218,7 +218,7 @@ public:
|
|||
virtual void setCString(const char *label);
|
||||
virtual void setAnchorPoint(const Point& var);
|
||||
virtual void updateLabel();
|
||||
virtual void setAlignment(Label::HAlignment alignment);
|
||||
virtual void setAlignment(TextHAlignment alignment);
|
||||
virtual void setWidth(float width);
|
||||
virtual void setLineBreakWithoutSpace(bool breakWithoutSpace);
|
||||
virtual void setScale(float scale);
|
||||
|
@ -265,7 +265,7 @@ protected:
|
|||
std::string _initialStringUTF8;
|
||||
|
||||
// alignment of all lines
|
||||
Label::HAlignment _alignment;
|
||||
TextHAlignment _alignment;
|
||||
// max width until a line break is added
|
||||
float _width;
|
||||
|
||||
|
|
|
@ -40,8 +40,8 @@ NS_CC_BEGIN
|
|||
//CCLabelTTF
|
||||
//
|
||||
LabelTTF::LabelTTF()
|
||||
: _alignment(Label::HAlignment::CENTER)
|
||||
, _vAlignment(Label::VAlignment::TOP)
|
||||
: _alignment(TextHAlignment::CENTER)
|
||||
, _vAlignment(TextVAlignment::TOP)
|
||||
, _fontName(NULL)
|
||||
, _fontSize(0.0)
|
||||
, _string("")
|
||||
|
@ -73,18 +73,18 @@ LabelTTF * LabelTTF::create()
|
|||
LabelTTF * LabelTTF::create(const char *string, const char *fontName, float fontSize)
|
||||
{
|
||||
return LabelTTF::create(string, fontName, fontSize,
|
||||
Size::ZERO, Label::HAlignment::CENTER, Label::VAlignment::TOP);
|
||||
Size::ZERO, TextHAlignment::CENTER, TextVAlignment::TOP);
|
||||
}
|
||||
|
||||
LabelTTF * LabelTTF::create(const char *string, const char *fontName, float fontSize,
|
||||
const Size& dimensions, Label::HAlignment hAlignment)
|
||||
const Size& dimensions, TextHAlignment hAlignment)
|
||||
{
|
||||
return LabelTTF::create(string, fontName, fontSize, dimensions, hAlignment, Label::VAlignment::TOP);
|
||||
return LabelTTF::create(string, fontName, fontSize, dimensions, hAlignment, TextVAlignment::TOP);
|
||||
}
|
||||
|
||||
LabelTTF* LabelTTF::create(const char *string, const char *fontName, float fontSize,
|
||||
const Size &dimensions, Label::HAlignment hAlignment,
|
||||
Label::VAlignment vAlignment)
|
||||
const Size &dimensions, TextHAlignment hAlignment,
|
||||
TextVAlignment vAlignment)
|
||||
{
|
||||
LabelTTF *pRet = new LabelTTF();
|
||||
if(pRet && pRet->initWithString(string, fontName, fontSize, dimensions, hAlignment, vAlignment))
|
||||
|
@ -114,20 +114,20 @@ bool LabelTTF::init()
|
|||
}
|
||||
|
||||
bool LabelTTF::initWithString(const char *label, const char *fontName, float fontSize,
|
||||
const Size& dimensions, Label::HAlignment alignment)
|
||||
const Size& dimensions, TextHAlignment alignment)
|
||||
{
|
||||
return this->initWithString(label, fontName, fontSize, dimensions, alignment, Label::VAlignment::TOP);
|
||||
return this->initWithString(label, fontName, fontSize, dimensions, alignment, TextVAlignment::TOP);
|
||||
}
|
||||
|
||||
bool LabelTTF::initWithString(const char *label, const char *fontName, float fontSize)
|
||||
{
|
||||
return this->initWithString(label, fontName, fontSize,
|
||||
Size::ZERO, Label::HAlignment::LEFT, Label::VAlignment::TOP);
|
||||
Size::ZERO, TextHAlignment::LEFT, TextVAlignment::TOP);
|
||||
}
|
||||
|
||||
bool LabelTTF::initWithString(const char *string, const char *fontName, float fontSize,
|
||||
const cocos2d::Size &dimensions, Label::HAlignment hAlignment,
|
||||
Label::VAlignment vAlignment)
|
||||
const cocos2d::Size &dimensions, TextHAlignment hAlignment,
|
||||
TextVAlignment vAlignment)
|
||||
{
|
||||
if (Sprite::init())
|
||||
{
|
||||
|
@ -193,12 +193,12 @@ const char* LabelTTF::description() const
|
|||
return String::createWithFormat("<LabelTTF | FontName = %s, FontSize = %.1f>", _fontName->c_str(), _fontSize)->getCString();
|
||||
}
|
||||
|
||||
Label::HAlignment LabelTTF::getHorizontalAlignment() const
|
||||
TextHAlignment LabelTTF::getHorizontalAlignment() const
|
||||
{
|
||||
return _alignment;
|
||||
}
|
||||
|
||||
void LabelTTF::setHorizontalAlignment(Label::HAlignment alignment)
|
||||
void LabelTTF::setHorizontalAlignment(TextHAlignment alignment)
|
||||
{
|
||||
if (alignment != _alignment)
|
||||
{
|
||||
|
@ -212,12 +212,12 @@ void LabelTTF::setHorizontalAlignment(Label::HAlignment alignment)
|
|||
}
|
||||
}
|
||||
|
||||
Label::VAlignment LabelTTF::getVerticalAlignment() const
|
||||
TextVAlignment LabelTTF::getVerticalAlignment() const
|
||||
{
|
||||
return _vAlignment;
|
||||
}
|
||||
|
||||
void LabelTTF::setVerticalAlignment(Label::VAlignment verticalAlignment)
|
||||
void LabelTTF::setVerticalAlignment(TextVAlignment verticalAlignment)
|
||||
{
|
||||
if (verticalAlignment != _vAlignment)
|
||||
{
|
||||
|
|
|
@ -48,9 +48,9 @@ NS_CC_BEGIN
|
|||
* Custom ttf file can be put in assets/ or external storage that the Application can access.
|
||||
* @code
|
||||
* LabelTTF *label1 = LabelTTF::create("alignment left", "A Damn Mess", fontSize, blockSize,
|
||||
* Label::HAlignment::LEFT, Label::VAlignment::CENTER);
|
||||
* TextHAlignment::LEFT, TextVAlignment::CENTER);
|
||||
* LabelTTF *label2 = LabelTTF::create("alignment right", "/mnt/sdcard/Scissor Cuts.ttf", fontSize, blockSize,
|
||||
* Label::HAlignment::LEFT, Label::VAlignment::CENTER);
|
||||
* TextHAlignment::LEFT, TextVAlignment::CENTER);
|
||||
* @endcode
|
||||
*
|
||||
*/
|
||||
|
@ -70,14 +70,14 @@ public:
|
|||
@since v2.0.1
|
||||
*/
|
||||
static LabelTTF * create(const char *string, const char *fontName, float fontSize,
|
||||
const Size& dimensions, Label::HAlignment hAlignment);
|
||||
const Size& dimensions, TextHAlignment hAlignment);
|
||||
|
||||
/** creates a Label from a fontname, alignment, dimension in points and font size in points
|
||||
@since v2.0.1
|
||||
*/
|
||||
static LabelTTF * create(const char *string, const char *fontName, float fontSize,
|
||||
const Size& dimensions, Label::HAlignment hAlignment,
|
||||
Label::VAlignment vAlignment);
|
||||
const Size& dimensions, TextHAlignment hAlignment,
|
||||
TextVAlignment vAlignment);
|
||||
|
||||
|
||||
/** Create a lable with string and a font definition*/
|
||||
|
@ -88,12 +88,12 @@ public:
|
|||
|
||||
/** initializes the LabelTTF with a font name, alignment, dimension and font size */
|
||||
bool initWithString(const char *string, const char *fontName, float fontSize,
|
||||
const Size& dimensions, Label::HAlignment hAlignment);
|
||||
const Size& dimensions, TextHAlignment hAlignment);
|
||||
|
||||
/** initializes the LabelTTF with a font name, alignment, dimension and font size */
|
||||
bool initWithString(const char *string, const char *fontName, float fontSize,
|
||||
const Size& dimensions, Label::HAlignment hAlignment,
|
||||
Label::VAlignment vAlignment);
|
||||
const Size& dimensions, TextHAlignment hAlignment,
|
||||
TextVAlignment vAlignment);
|
||||
|
||||
/** initializes the LabelTTF with a font name, alignment, dimension and font size */
|
||||
bool initWithStringAndTextDefinition(const char *string, FontDefinition &textDefinition);
|
||||
|
@ -136,11 +136,11 @@ public:
|
|||
virtual void setString(const char *label);
|
||||
virtual const char* getString(void) const;
|
||||
|
||||
Label::HAlignment getHorizontalAlignment() const;
|
||||
void setHorizontalAlignment(Label::HAlignment alignment);
|
||||
TextHAlignment getHorizontalAlignment() const;
|
||||
void setHorizontalAlignment(TextHAlignment alignment);
|
||||
|
||||
Label::VAlignment getVerticalAlignment() const;
|
||||
void setVerticalAlignment(Label::VAlignment verticalAlignment);
|
||||
TextVAlignment getVerticalAlignment() const;
|
||||
void setVerticalAlignment(TextVAlignment verticalAlignment);
|
||||
|
||||
const Size& getDimensions() const;
|
||||
void setDimensions(const Size &dim);
|
||||
|
@ -162,9 +162,9 @@ protected:
|
|||
/** Dimensions of the label in Points */
|
||||
Size _dimensions;
|
||||
/** The alignment of the label */
|
||||
Label::HAlignment _alignment;
|
||||
TextHAlignment _alignment;
|
||||
/** The vertical alignment of the label */
|
||||
Label::VAlignment _vAlignment;
|
||||
TextVAlignment _vAlignment;
|
||||
/** Font name used in the label */
|
||||
std::string * _fontName;
|
||||
/** Font size of the label */
|
||||
|
|
|
@ -0,0 +1,67 @@
|
|||
/****************************************************************************
|
||||
Copyright (c) 2013 Zynga 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.
|
||||
****************************************************************************/
|
||||
|
||||
#ifndef _CCLabelTextFormatProtocol_h_
|
||||
#define _CCLabelTextFormatProtocol_h_
|
||||
|
||||
NS_CC_BEGIN
|
||||
|
||||
class CC_DLL LabelTextFormatProtocol
|
||||
{
|
||||
public:
|
||||
|
||||
// sprite related stuff
|
||||
virtual cocos2d::Sprite * getSpriteChild(int ID) = 0;
|
||||
virtual cocos2d::Array * getChildrenLetters() = 0;
|
||||
virtual cocos2d::Sprite * getSpriteForChar(unsigned short int theChar, int spriteIndexHint) = 0;
|
||||
virtual float getLetterPosXLeft( cocos2d::Sprite* sp ) = 0;
|
||||
virtual float getLetterPosXRight( cocos2d::Sprite* sp ) = 0;
|
||||
|
||||
// font related stuff
|
||||
virtual int getCommonLineHeight() = 0;
|
||||
virtual int getKerningForCharsPair(unsigned short first, unsigned short second) = 0;
|
||||
virtual int getXOffsetForChar(unsigned short c) = 0;
|
||||
virtual int getYOffsetForChar(unsigned short c) = 0;
|
||||
virtual int getAdvanceForChar(unsigned short c, int hintPositionInString) = 0;
|
||||
virtual cocos2d::Rect getRectForChar(unsigned short c) = 0;
|
||||
|
||||
// string related stuff
|
||||
virtual int getStringNumLines() = 0;
|
||||
virtual int getStringLenght() = 0;
|
||||
virtual unsigned short getCharAtStringPosition(int position) = 0;
|
||||
virtual unsigned short * getUTF8String() = 0;
|
||||
virtual void assignNewUTF8String(unsigned short *newString) = 0;
|
||||
virtual TextHAlignment getTextAlignment() = 0;
|
||||
|
||||
// label related stuff
|
||||
virtual float getMaxLineWidth() = 0;
|
||||
virtual bool breakLineWithoutSpace() = 0;
|
||||
virtual cocos2d::Size getLabelContentSize() = 0;
|
||||
virtual void setLabelContentSize(const Size &newSize) = 0;
|
||||
|
||||
};
|
||||
|
||||
NS_CC_END
|
||||
|
||||
#endif
|
|
@ -0,0 +1,388 @@
|
|||
/****************************************************************************
|
||||
Copyright (c) 2013 Zynga 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.
|
||||
****************************************************************************/
|
||||
|
||||
#include <vector>
|
||||
|
||||
#include "cocos2d.h"
|
||||
#include "support/ccUTF8.h"
|
||||
#include "CCLabelTextFormatter.h"
|
||||
|
||||
using namespace std;
|
||||
|
||||
NS_CC_BEGIN
|
||||
|
||||
bool LabelTextFormatter::multilineText(LabelTextFormatProtocol *theLabel)
|
||||
{
|
||||
// to do if (m_fWidth > 0)
|
||||
if (theLabel->getMaxLineWidth())
|
||||
{
|
||||
// Step 1: Make multiline
|
||||
vector<unsigned short> strWhole = cc_utf16_vec_from_utf16_str(theLabel->getUTF8String());
|
||||
unsigned int stringLength = strWhole.size();
|
||||
|
||||
vector<unsigned short> multiline_string;
|
||||
multiline_string.reserve( stringLength );
|
||||
|
||||
vector<unsigned short> last_word;
|
||||
last_word.reserve( stringLength );
|
||||
|
||||
unsigned int line = 1, i = 0;
|
||||
|
||||
bool start_line = false, start_word = false;
|
||||
float startOfLine = -1, startOfWord = -1;
|
||||
|
||||
int skip = 0;
|
||||
|
||||
Array* children = theLabel->getChildrenLetters();
|
||||
|
||||
for (unsigned int j = 0; j < children->count(); j++)
|
||||
{
|
||||
Sprite* characterSprite;
|
||||
unsigned int justSkipped = 0;
|
||||
|
||||
while (!(characterSprite = theLabel->getSpriteChild(j + skip + justSkipped)))
|
||||
{
|
||||
justSkipped++;
|
||||
}
|
||||
|
||||
skip += justSkipped;
|
||||
|
||||
if (!characterSprite->isVisible())
|
||||
continue;
|
||||
|
||||
if (i >= stringLength)
|
||||
break;
|
||||
|
||||
unsigned short character = strWhole[i];
|
||||
|
||||
if (!start_word)
|
||||
{
|
||||
startOfWord = theLabel->getLetterPosXLeft( characterSprite );
|
||||
start_word = true;
|
||||
}
|
||||
|
||||
if (!start_line)
|
||||
{
|
||||
startOfLine = startOfWord;
|
||||
start_line = true;
|
||||
}
|
||||
|
||||
// Newline.
|
||||
if (character == '\n')
|
||||
{
|
||||
cc_utf8_trim_ws(&last_word);
|
||||
|
||||
last_word.push_back('\n');
|
||||
multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end());
|
||||
last_word.clear();
|
||||
start_word = false;
|
||||
start_line = false;
|
||||
startOfWord = -1;
|
||||
startOfLine = -1;
|
||||
i+=justSkipped;
|
||||
line++;
|
||||
|
||||
if (i >= stringLength)
|
||||
break;
|
||||
|
||||
character = strWhole[i];
|
||||
|
||||
if (!startOfWord)
|
||||
{
|
||||
startOfWord = theLabel->getLetterPosXLeft( characterSprite );
|
||||
start_word = true;
|
||||
}
|
||||
if (!startOfLine)
|
||||
{
|
||||
startOfLine = startOfWord;
|
||||
start_line = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Whitespace.
|
||||
if (isspace_unicode(character))
|
||||
{
|
||||
last_word.push_back(character);
|
||||
multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end());
|
||||
last_word.clear();
|
||||
start_word = false;
|
||||
startOfWord = -1;
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Out of bounds.
|
||||
if ( theLabel->getLetterPosXRight( characterSprite ) - startOfLine > theLabel->getMaxLineWidth() )
|
||||
{
|
||||
if (!theLabel->breakLineWithoutSpace())
|
||||
{
|
||||
last_word.push_back(character);
|
||||
|
||||
int found = cc_utf8_find_last_not_char(multiline_string, ' ');
|
||||
if (found != -1)
|
||||
cc_utf8_trim_ws(&multiline_string);
|
||||
else
|
||||
multiline_string.clear();
|
||||
|
||||
if (multiline_string.size() > 0)
|
||||
multiline_string.push_back('\n');
|
||||
|
||||
line++;
|
||||
start_line = false;
|
||||
startOfLine = -1;
|
||||
i++;
|
||||
}
|
||||
else
|
||||
{
|
||||
cc_utf8_trim_ws(&last_word);
|
||||
|
||||
last_word.push_back('\n');
|
||||
multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end());
|
||||
last_word.clear();
|
||||
start_word = false;
|
||||
start_line = false;
|
||||
startOfWord = -1;
|
||||
startOfLine = -1;
|
||||
line++;
|
||||
|
||||
if (i >= stringLength)
|
||||
break;
|
||||
|
||||
if (!startOfWord)
|
||||
{
|
||||
startOfWord = theLabel->getLetterPosXLeft( characterSprite );
|
||||
start_word = true;
|
||||
}
|
||||
if (!startOfLine)
|
||||
{
|
||||
startOfLine = startOfWord;
|
||||
start_line = true;
|
||||
}
|
||||
|
||||
j--;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Character is normal.
|
||||
last_word.push_back(character);
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end());
|
||||
|
||||
int size = multiline_string.size();
|
||||
unsigned short* str_new = new unsigned short[size + 1];
|
||||
|
||||
for (int i = 0; i < size; ++i)
|
||||
{
|
||||
str_new[i] = multiline_string[i];
|
||||
}
|
||||
|
||||
str_new[size] = 0;
|
||||
theLabel->assignNewUTF8String(str_new);
|
||||
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool LabelTextFormatter::alignText(LabelTextFormatProtocol *theLabel)
|
||||
{
|
||||
int i = 0;
|
||||
|
||||
int lineNumber = 0;
|
||||
int str_len = cc_wcslen(theLabel->getUTF8String());
|
||||
vector<unsigned short> last_line;
|
||||
for (int ctr = 0; ctr <= str_len; ++ctr)
|
||||
{
|
||||
unsigned char currentChar = theLabel->getCharAtStringPosition(ctr);
|
||||
|
||||
if (currentChar == '\n' || currentChar == 0)
|
||||
{
|
||||
float lineWidth = 0.0f;
|
||||
unsigned int line_length = last_line.size();
|
||||
|
||||
// if last line is empty we must just increase lineNumber and work with next line
|
||||
if (line_length == 0)
|
||||
{
|
||||
lineNumber++;
|
||||
continue;
|
||||
}
|
||||
int index = i + line_length - 1 + lineNumber;
|
||||
if (index < 0) continue;
|
||||
|
||||
Sprite* lastChar = theLabel->getSpriteChild(index);
|
||||
if ( lastChar == NULL )
|
||||
continue;
|
||||
|
||||
lineWidth = lastChar->getPosition().x + lastChar->getContentSize().width / 2.0f;
|
||||
|
||||
float shift = 0;
|
||||
switch (theLabel->getTextAlignment())
|
||||
{
|
||||
case TextHAlignment::CENTER:
|
||||
shift = theLabel->getLabelContentSize().width/2.0f - lineWidth/2.0f;
|
||||
break;
|
||||
case TextHAlignment::RIGHT:
|
||||
shift = theLabel->getLabelContentSize().width - lineWidth;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
if (shift != 0)
|
||||
{
|
||||
for (unsigned j = 0; j < line_length; j++)
|
||||
{
|
||||
index = i + j + lineNumber;
|
||||
if (index < 0) continue;
|
||||
|
||||
Sprite* characterSprite = theLabel->getSpriteChild(index);
|
||||
|
||||
if (characterSprite)
|
||||
characterSprite->setPosition( characterSprite->getPosition() + Point(shift, 0.0f));
|
||||
}
|
||||
}
|
||||
|
||||
i += line_length;
|
||||
lineNumber++;
|
||||
|
||||
last_line.clear();
|
||||
continue;
|
||||
}
|
||||
|
||||
last_line.push_back(currentChar);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool LabelTextFormatter::createStringSprites(LabelTextFormatProtocol *theLabel)
|
||||
{
|
||||
// check for string
|
||||
unsigned int stringLen = theLabel->getStringLenght();
|
||||
|
||||
// no string
|
||||
if (stringLen == 0)
|
||||
return false;
|
||||
|
||||
int nextFontPositionX = 0;
|
||||
int nextFontPositionY = 0;
|
||||
|
||||
unsigned short prev = -1;
|
||||
|
||||
|
||||
Size tmpSize = Size::ZERO;
|
||||
|
||||
int longestLine = 0;
|
||||
unsigned int totalHeight = 0;
|
||||
|
||||
|
||||
int quantityOfLines = theLabel->getStringNumLines();
|
||||
int commonLineHeight = theLabel->getCommonLineHeight();
|
||||
|
||||
totalHeight = commonLineHeight * quantityOfLines;
|
||||
nextFontPositionY = 0 - ( commonLineHeight - totalHeight );
|
||||
|
||||
Rect rect;
|
||||
|
||||
Rect charRect;
|
||||
int charXOffset = 0;
|
||||
int charYOffset = 0;
|
||||
int charAdvance = 0;
|
||||
|
||||
for (unsigned int i = 0; i < stringLen; i++)
|
||||
{
|
||||
// get the current character
|
||||
unsigned short c = theLabel->getCharAtStringPosition(i);
|
||||
|
||||
charXOffset = theLabel->getXOffsetForChar(c);
|
||||
charYOffset = theLabel->getYOffsetForChar(c);
|
||||
charAdvance = theLabel->getAdvanceForChar(c, i);
|
||||
charRect = theLabel->getRectForChar(c);
|
||||
|
||||
int kerningAmount = theLabel->getKerningForCharsPair(prev, c);
|
||||
|
||||
if (c == '\n')
|
||||
{
|
||||
nextFontPositionX = 0;
|
||||
nextFontPositionY -= commonLineHeight;
|
||||
continue;
|
||||
}
|
||||
|
||||
// get the sprite to this letter
|
||||
Sprite *pLetterSprite = theLabel->getSpriteForChar(c, i);
|
||||
|
||||
if (!pLetterSprite)
|
||||
{
|
||||
log("WARNING: can't find letter definition in font file for letter: %c", c);
|
||||
continue;
|
||||
}
|
||||
|
||||
// See issue 1343. cast( signed short + unsigned integer ) == unsigned integer (sign is lost!)
|
||||
int yOffset = commonLineHeight - charYOffset;
|
||||
|
||||
|
||||
Point fontPos = Point( (float)nextFontPositionX + charXOffset + charRect.size.width * 0.5f + kerningAmount,
|
||||
(float)nextFontPositionY + yOffset - charRect.size.height * 0.5f );
|
||||
|
||||
// set the sprite position
|
||||
pLetterSprite->setPosition(CC_POINT_PIXELS_TO_POINTS(fontPos));
|
||||
|
||||
// update kerning
|
||||
nextFontPositionX += charAdvance + kerningAmount;
|
||||
prev = c;
|
||||
|
||||
if (longestLine < nextFontPositionX)
|
||||
{
|
||||
longestLine = nextFontPositionX;
|
||||
}
|
||||
}
|
||||
|
||||
// If the last character processed has an xAdvance which is less that the width of the characters image, then we need
|
||||
// to adjust the width of the string to take this into account, or the character will overlap the end of the bounding
|
||||
// box
|
||||
if (charAdvance < charRect.size.width)
|
||||
{
|
||||
tmpSize.width = longestLine + charRect.size.width - charAdvance;
|
||||
}
|
||||
else
|
||||
{
|
||||
tmpSize.width = longestLine;
|
||||
}
|
||||
|
||||
tmpSize.height = totalHeight;
|
||||
theLabel->setLabelContentSize(CC_SIZE_PIXELS_TO_POINTS(tmpSize));
|
||||
return true;
|
||||
}
|
||||
|
||||
NS_CC_END
|
|
@ -0,0 +1,44 @@
|
|||
/****************************************************************************
|
||||
Copyright (c) 2013 Zynga 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.
|
||||
****************************************************************************/
|
||||
|
||||
#ifndef _CCLabelTextFormatter_h_
|
||||
#define _CCLabelTextFormatter_h_
|
||||
|
||||
#include "CCLabelTextFormatProtocol.h"
|
||||
|
||||
NS_CC_BEGIN
|
||||
|
||||
class CC_DLL LabelTextFormatter
|
||||
{
|
||||
public:
|
||||
|
||||
static bool multilineText(LabelTextFormatProtocol *theLabel);
|
||||
static bool alignText(LabelTextFormatProtocol *theLabel);
|
||||
static bool createStringSprites(LabelTextFormatProtocol *theLabel);
|
||||
|
||||
};
|
||||
|
||||
NS_CC_END
|
||||
|
||||
#endif
|
|
@ -0,0 +1,733 @@
|
|||
/****************************************************************************
|
||||
Copyright (c) 2010-2012 cocos2d-x.org
|
||||
Copyright (c) 2008-2010 Ricardo Quesada
|
||||
Copyright (c) 2011 Zynga 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.
|
||||
|
||||
Use any of these editors to generate BMFonts:
|
||||
http://glyphdesigner.71squared.com/ (Commercial, Mac OS X)
|
||||
http://www.n4te.com/hiero/hiero.jnlp (Free, Java)
|
||||
http://slick.cokeandcode.com/demos/hiero.jnlp (Free, Java)
|
||||
http://www.angelcode.com/products/bmfont/ (Free, Windows only)
|
||||
|
||||
****************************************************************************/
|
||||
#include "CCStringBMFont.h"
|
||||
#include "cocoa/CCString.h"
|
||||
#include "cocoa/CCDictionary.h"
|
||||
#include "CCConfiguration.h"
|
||||
#include "CCLabelTextFormatter.h"
|
||||
#include "draw_nodes/CCDrawingPrimitives.h"
|
||||
#include "sprite_nodes/CCSprite.h"
|
||||
//#include "support/CCPointExtension.h"
|
||||
#include "platform/CCFileUtils.h"
|
||||
#include "CCDirector.h"
|
||||
#include "textures/CCTextureCache.h"
|
||||
#include "support/ccUTF8.h"
|
||||
|
||||
using namespace std;
|
||||
|
||||
NS_CC_BEGIN
|
||||
|
||||
|
||||
// The return value needs to be deleted by CC_SAFE_DELETE_ARRAY.
|
||||
static unsigned short* copyUTF16StringNN(unsigned short* str)
|
||||
{
|
||||
int length = str ? cc_wcslen(str) : 0;
|
||||
unsigned short* ret = new unsigned short[length+1];
|
||||
for (int i = 0; i < length; ++i) {
|
||||
ret[i] = str[i];
|
||||
}
|
||||
ret[length] = 0;
|
||||
return ret;
|
||||
}
|
||||
|
||||
//
|
||||
//CCLabelBMFont
|
||||
//
|
||||
|
||||
//LabelBMFont - Purge Cache
|
||||
void StringBMFont::purgeCachedData()
|
||||
{
|
||||
FNTConfigRemoveCache();
|
||||
}
|
||||
|
||||
StringBMFont * StringBMFont::create()
|
||||
{
|
||||
StringBMFont * pRet = new StringBMFont();
|
||||
if (pRet && pRet->init())
|
||||
{
|
||||
pRet->autorelease();
|
||||
return pRet;
|
||||
}
|
||||
CC_SAFE_DELETE(pRet);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
StringBMFont * StringBMFont::create(const char *str, const char *fntFile, float width, TextHAlignment alignment)
|
||||
{
|
||||
return StringBMFont::create(str, fntFile, width, alignment, Point::ZERO);
|
||||
}
|
||||
|
||||
StringBMFont * StringBMFont::create(const char *str, const char *fntFile, float width)
|
||||
{
|
||||
return StringBMFont::create(str, fntFile, width, TextHAlignment::LEFT, Point::ZERO);
|
||||
}
|
||||
|
||||
StringBMFont * StringBMFont::create(const char *str, const char *fntFile)
|
||||
{
|
||||
return StringBMFont::create(str, fntFile, kLabelAutomaticWidth, TextHAlignment::LEFT, Point::ZERO);
|
||||
}
|
||||
|
||||
//LabelBMFont - Creation & Init
|
||||
StringBMFont *StringBMFont::create(const char *str, const char *fntFile, float width/* = kLabelAutomaticWidth*/, TextHAlignment alignment/* = kTextAlignmentLeft*/, Point imageOffset/* = Point::ZERO*/)
|
||||
{
|
||||
StringBMFont *pRet = new StringBMFont();
|
||||
if(pRet && pRet->initWithString(str, fntFile, width, alignment, imageOffset))
|
||||
{
|
||||
pRet->autorelease();
|
||||
return pRet;
|
||||
}
|
||||
CC_SAFE_DELETE(pRet);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
bool StringBMFont::init()
|
||||
{
|
||||
return initWithString(NULL, NULL, kLabelAutomaticWidth, TextHAlignment::LEFT, Point::ZERO);
|
||||
}
|
||||
|
||||
bool StringBMFont::initWithString(const char *theString, const char *fntFile, float width/* = kLabelAutomaticWidth*/, TextHAlignment alignment/* = kTextAlignmentLeft*/, Point imageOffset/* = Point::ZERO*/)
|
||||
{
|
||||
CCAssert(!_configuration, "re-init is no longer supported");
|
||||
CCAssert( (theString && fntFile) || (theString==NULL && fntFile==NULL), "Invalid params for StringBMFont");
|
||||
|
||||
Texture2D *texture = NULL;
|
||||
|
||||
if (fntFile)
|
||||
{
|
||||
CCBMFontConfiguration *newConf = FNTConfigLoadFile(fntFile);
|
||||
if (!newConf)
|
||||
{
|
||||
CCLOG("cocos2d: WARNING. StringBMFont: Impossible to create font. Please check file: '%s'", fntFile);
|
||||
release();
|
||||
return false;
|
||||
}
|
||||
|
||||
newConf->retain();
|
||||
CC_SAFE_RELEASE(_configuration);
|
||||
_configuration = newConf;
|
||||
|
||||
_fntFile = fntFile;
|
||||
|
||||
texture = TextureCache::getInstance()->addImage(_configuration->getAtlasName());
|
||||
}
|
||||
else
|
||||
{
|
||||
texture = new Texture2D();
|
||||
texture->autorelease();
|
||||
}
|
||||
|
||||
if (theString == NULL)
|
||||
{
|
||||
theString = "";
|
||||
}
|
||||
|
||||
if (SpriteBatchNode::initWithTexture(texture, strlen(theString)))
|
||||
{
|
||||
_width = width;
|
||||
_alignment = alignment;
|
||||
|
||||
_displayedOpacity = _realOpacity = 255;
|
||||
_displayedColor = _realColor = Color3B::WHITE;
|
||||
_cascadeOpacityEnabled = true;
|
||||
_cascadeColorEnabled = true;
|
||||
|
||||
_contentSize = Size::ZERO;
|
||||
|
||||
_isOpacityModifyRGB = _textureAtlas->getTexture()->hasPremultipliedAlpha();
|
||||
_anchorPoint = Point(0.5f, 0.5f);
|
||||
|
||||
_imageOffset = imageOffset;
|
||||
|
||||
_reusedChar = new Sprite();
|
||||
_reusedChar->initWithTexture(_textureAtlas->getTexture(), Rect(0, 0, 0, 0), false);
|
||||
_reusedChar->setBatchNode(this);
|
||||
|
||||
this->setString(theString);
|
||||
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
StringBMFont::StringBMFont()
|
||||
: _string(NULL)
|
||||
, _initialString(NULL)
|
||||
, _alignment(TextHAlignment::CENTER)
|
||||
, _width(-1.0f)
|
||||
, _configuration(NULL)
|
||||
, _lineBreakWithoutSpaces(false)
|
||||
, _imageOffset(Point::ZERO)
|
||||
, _reusedChar(NULL)
|
||||
, _displayedOpacity(255)
|
||||
, _realOpacity(255)
|
||||
, _displayedColor(Color3B::WHITE)
|
||||
, _realColor(Color3B::WHITE)
|
||||
, _cascadeColorEnabled(true)
|
||||
, _cascadeOpacityEnabled(true)
|
||||
, _isOpacityModifyRGB(false)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
StringBMFont::~StringBMFont()
|
||||
{
|
||||
CC_SAFE_RELEASE(_reusedChar);
|
||||
CC_SAFE_DELETE_ARRAY(_string);
|
||||
CC_SAFE_DELETE_ARRAY(_initialString);
|
||||
CC_SAFE_RELEASE(_configuration);
|
||||
}
|
||||
|
||||
// StringBMFont - Atlas generation
|
||||
int StringBMFont::kerningAmountForFirst(unsigned short first, unsigned short second)
|
||||
{
|
||||
int ret = 0;
|
||||
unsigned int key = (first<<16) | (second & 0xffff);
|
||||
|
||||
if( _configuration->_kerningDictionary ) {
|
||||
tKerningHashElement *element = NULL;
|
||||
HASH_FIND_INT(_configuration->_kerningDictionary, &key, element);
|
||||
if(element)
|
||||
ret = element->amount;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
const char* StringBMFont::getString(void) const
|
||||
{
|
||||
return _initialStringUTF8.c_str();
|
||||
}
|
||||
|
||||
//StringBMFont - RGBAProtocol protocol
|
||||
const Color3B& StringBMFont::getColor() const
|
||||
{
|
||||
return _realColor;
|
||||
}
|
||||
|
||||
const Color3B& StringBMFont::getDisplayedColor() const
|
||||
{
|
||||
return _displayedColor;
|
||||
}
|
||||
|
||||
void StringBMFont::setColor(const Color3B& color)
|
||||
{
|
||||
_displayedColor = _realColor = color;
|
||||
|
||||
if( _cascadeColorEnabled ) {
|
||||
Color3B parentColor = Color3B::WHITE;
|
||||
RGBAProtocol* pParent = dynamic_cast<RGBAProtocol*>(_parent);
|
||||
if (pParent && pParent->isCascadeColorEnabled())
|
||||
{
|
||||
parentColor = pParent->getDisplayedColor();
|
||||
}
|
||||
this->updateDisplayedColor(parentColor);
|
||||
}
|
||||
}
|
||||
|
||||
GLubyte StringBMFont::getOpacity(void) const
|
||||
{
|
||||
return _realOpacity;
|
||||
}
|
||||
|
||||
GLubyte StringBMFont::getDisplayedOpacity(void) const
|
||||
{
|
||||
return _displayedOpacity;
|
||||
}
|
||||
|
||||
/** Override synthesized setOpacity to recurse items */
|
||||
void StringBMFont::setOpacity(GLubyte opacity)
|
||||
{
|
||||
_displayedOpacity = _realOpacity = opacity;
|
||||
|
||||
if( _cascadeOpacityEnabled ) {
|
||||
GLubyte parentOpacity = 255;
|
||||
RGBAProtocol* pParent = dynamic_cast<RGBAProtocol*>(_parent);
|
||||
if (pParent && pParent->isCascadeOpacityEnabled())
|
||||
{
|
||||
parentOpacity = pParent->getDisplayedOpacity();
|
||||
}
|
||||
this->updateDisplayedOpacity(parentOpacity);
|
||||
}
|
||||
}
|
||||
|
||||
void StringBMFont::setOpacityModifyRGB(bool var)
|
||||
{
|
||||
_isOpacityModifyRGB = var;
|
||||
if (_children && _children->count() != 0)
|
||||
{
|
||||
Object* child;
|
||||
CCARRAY_FOREACH(_children, child)
|
||||
{
|
||||
Node* pNode = static_cast<Node*>( child );
|
||||
if (pNode)
|
||||
{
|
||||
RGBAProtocol *pRGBAProtocol = dynamic_cast<RGBAProtocol*>(pNode);
|
||||
if (pRGBAProtocol)
|
||||
{
|
||||
pRGBAProtocol->setOpacityModifyRGB(_isOpacityModifyRGB);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
bool StringBMFont::isOpacityModifyRGB() const
|
||||
{
|
||||
return _isOpacityModifyRGB;
|
||||
}
|
||||
|
||||
void StringBMFont::updateDisplayedOpacity(GLubyte parentOpacity)
|
||||
{
|
||||
_displayedOpacity = _realOpacity * parentOpacity/255.0;
|
||||
|
||||
Object* pObj;
|
||||
CCARRAY_FOREACH(_children, pObj)
|
||||
{
|
||||
Sprite *item = static_cast<Sprite*>( pObj );
|
||||
item->updateDisplayedOpacity(_displayedOpacity);
|
||||
}
|
||||
}
|
||||
|
||||
void StringBMFont::updateDisplayedColor(const Color3B& parentColor)
|
||||
{
|
||||
_displayedColor.r = _realColor.r * parentColor.r/255.0;
|
||||
_displayedColor.g = _realColor.g * parentColor.g/255.0;
|
||||
_displayedColor.b = _realColor.b * parentColor.b/255.0;
|
||||
|
||||
Object* pObj;
|
||||
CCARRAY_FOREACH(_children, pObj)
|
||||
{
|
||||
Sprite *item = static_cast<Sprite*>( pObj );
|
||||
item->updateDisplayedColor(_displayedColor);
|
||||
}
|
||||
}
|
||||
|
||||
bool StringBMFont::isCascadeColorEnabled() const
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
void StringBMFont::setCascadeColorEnabled(bool cascadeColorEnabled)
|
||||
{
|
||||
_cascadeColorEnabled = cascadeColorEnabled;
|
||||
}
|
||||
|
||||
bool StringBMFont::isCascadeOpacityEnabled() const
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
void StringBMFont::setCascadeOpacityEnabled(bool cascadeOpacityEnabled)
|
||||
{
|
||||
_cascadeOpacityEnabled = cascadeOpacityEnabled;
|
||||
}
|
||||
|
||||
// StringBMFont - AnchorPoint
|
||||
void StringBMFont::setAnchorPoint(const Point& point)
|
||||
{
|
||||
if( ! point.equals(_anchorPoint))
|
||||
{
|
||||
SpriteBatchNode::setAnchorPoint(point);
|
||||
updateLabel();
|
||||
}
|
||||
}
|
||||
|
||||
// StringBMFont - Alignment
|
||||
void StringBMFont::setAlignment(TextHAlignment alignment)
|
||||
{
|
||||
this->_alignment = alignment;
|
||||
updateLabel();
|
||||
}
|
||||
|
||||
void StringBMFont::setWidth(float width)
|
||||
{
|
||||
this->_width = width;
|
||||
updateLabel();
|
||||
}
|
||||
|
||||
void StringBMFont::setLineBreakWithoutSpace( bool breakWithoutSpace )
|
||||
{
|
||||
_lineBreakWithoutSpaces = breakWithoutSpace;
|
||||
updateLabel();
|
||||
}
|
||||
|
||||
void StringBMFont::setScale(float scale)
|
||||
{
|
||||
SpriteBatchNode::setScale(scale);
|
||||
updateLabel();
|
||||
}
|
||||
|
||||
void StringBMFont::setScaleX(float scaleX)
|
||||
{
|
||||
SpriteBatchNode::setScaleX(scaleX);
|
||||
updateLabel();
|
||||
}
|
||||
|
||||
void StringBMFont::setScaleY(float scaleY)
|
||||
{
|
||||
SpriteBatchNode::setScaleY(scaleY);
|
||||
updateLabel();
|
||||
}
|
||||
|
||||
float StringBMFont::getLetterPosXLeft( Sprite* sp )
|
||||
{
|
||||
return sp->getPosition().x * _scaleX - (sp->getContentSize().width * _scaleX * sp->getAnchorPoint().x);
|
||||
}
|
||||
|
||||
float StringBMFont::getLetterPosXRight( Sprite* sp )
|
||||
{
|
||||
return sp->getPosition().x * _scaleX + (sp->getContentSize().width * _scaleX * sp->getAnchorPoint().x);
|
||||
}
|
||||
|
||||
// StringBMFont - FntFile
|
||||
void StringBMFont::setFntFile(const char* fntFile)
|
||||
{
|
||||
if (fntFile != NULL && strcmp(fntFile, _fntFile.c_str()) != 0 )
|
||||
{
|
||||
CCBMFontConfiguration *newConf = FNTConfigLoadFile(fntFile);
|
||||
|
||||
CCAssert( newConf, "CCStringBMFont: Impossible to create font. Please check file");
|
||||
|
||||
_fntFile = fntFile;
|
||||
|
||||
CC_SAFE_RETAIN(newConf);
|
||||
CC_SAFE_RELEASE(_configuration);
|
||||
_configuration = newConf;
|
||||
|
||||
this->setTexture(TextureCache::getInstance()->addImage(_configuration->getAtlasName()));
|
||||
LabelTextFormatter::createStringSprites(this);
|
||||
}
|
||||
}
|
||||
|
||||
const char* StringBMFont::getFntFile()
|
||||
{
|
||||
return _fntFile.c_str();
|
||||
}
|
||||
|
||||
|
||||
//StringBMFont - Debug draw
|
||||
#if CC_LabelBMFontNew_DEBUG_DRAW
|
||||
void StringBMFont::draw()
|
||||
{
|
||||
SpriteBatchNode::draw();
|
||||
const Size& s = this->getContentSize();
|
||||
Point vertices[4]={
|
||||
ccp(0,0),ccp(s.width,0),
|
||||
ccp(s.width,s.height),ccp(0,s.height),
|
||||
};
|
||||
ccDrawPoly(vertices, 4, true);
|
||||
}
|
||||
|
||||
#endif // CC_LABELBMFONT_DEBUG_DRAW
|
||||
|
||||
|
||||
int StringBMFont::getCommonLineHeight()
|
||||
{
|
||||
if (_configuration)
|
||||
{
|
||||
return _configuration->_commonHeight;
|
||||
}
|
||||
else
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
int StringBMFont::getKerningForCharsPair(unsigned short first, unsigned short second)
|
||||
{
|
||||
return this->kerningAmountForFirst(first, second);
|
||||
}
|
||||
|
||||
ccBMFontDef StringBMFont::getFontDefForChar(unsigned short int theChar)
|
||||
{
|
||||
ccBMFontDef fontDef;
|
||||
tFontDefHashElement *element = NULL;
|
||||
unsigned int key = theChar;
|
||||
|
||||
HASH_FIND_INT(_configuration->_fontDefDictionary, &key, element);
|
||||
|
||||
if (element)
|
||||
{
|
||||
fontDef = element->fontDef;
|
||||
}
|
||||
|
||||
return fontDef;
|
||||
}
|
||||
|
||||
// return a sprite for rendering one letter
|
||||
Sprite * StringBMFont::getSpriteForChar(unsigned short int theChar, int spriteIndexHint)
|
||||
{
|
||||
Rect rect;
|
||||
ccBMFontDef fontDef;
|
||||
Sprite *pRetSprite = 0;
|
||||
|
||||
// unichar is a short, and an int is needed on HASH_FIND_INT
|
||||
tFontDefHashElement *element = NULL;
|
||||
unsigned int key = theChar;
|
||||
|
||||
HASH_FIND_INT(_configuration->_fontDefDictionary, &key, element);
|
||||
|
||||
if (! element)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
fontDef = element->fontDef;
|
||||
|
||||
rect = fontDef.rect;
|
||||
rect = CC_RECT_PIXELS_TO_POINTS(rect);
|
||||
|
||||
rect.origin.x += _imageOffset.x;
|
||||
rect.origin.y += _imageOffset.y;
|
||||
|
||||
//bool hasSprite = true;
|
||||
pRetSprite = (Sprite*)(this->getChildByTag(spriteIndexHint));
|
||||
|
||||
if(pRetSprite )
|
||||
{
|
||||
// Reusing previous Sprite
|
||||
pRetSprite->setVisible(true);
|
||||
}
|
||||
else
|
||||
{
|
||||
pRetSprite = new Sprite();
|
||||
pRetSprite->initWithTexture(_textureAtlas->getTexture(), rect);
|
||||
addChild(pRetSprite, spriteIndexHint, spriteIndexHint);
|
||||
pRetSprite->release();
|
||||
|
||||
// Apply label properties
|
||||
pRetSprite->setOpacityModifyRGB(_isOpacityModifyRGB);
|
||||
|
||||
// Color MUST be set before opacity, since opacity might change color if OpacityModifyRGB is on
|
||||
pRetSprite->updateDisplayedColor(_displayedColor);
|
||||
pRetSprite->updateDisplayedOpacity(_displayedOpacity);
|
||||
}
|
||||
|
||||
// updating previous sprite
|
||||
pRetSprite->setTextureRect(rect, false, rect.size);
|
||||
return pRetSprite;
|
||||
}
|
||||
|
||||
int StringBMFont::getStringNumLines()
|
||||
{
|
||||
int quantityOfLines = 1;
|
||||
|
||||
unsigned int stringLen = _string ? cc_wcslen(_string) : 0;
|
||||
if (stringLen == 0)
|
||||
return (-1);
|
||||
|
||||
// count number of lines
|
||||
for (unsigned int i = 0; i < stringLen - 1; ++i)
|
||||
{
|
||||
unsigned short c = _string[i];
|
||||
if (c == '\n')
|
||||
{
|
||||
quantityOfLines++;
|
||||
}
|
||||
}
|
||||
|
||||
return quantityOfLines;
|
||||
}
|
||||
|
||||
// need cross implementation
|
||||
int StringBMFont::getStringLenght()
|
||||
{
|
||||
return _string ? cc_wcslen(_string) : 0;
|
||||
}
|
||||
|
||||
unsigned short StringBMFont::getCharAtStringPosition(int position)
|
||||
{
|
||||
return _string[position];
|
||||
}
|
||||
|
||||
int StringBMFont::getXOffsetForChar(unsigned short c)
|
||||
{
|
||||
ccBMFontDef fontDef = getFontDefForChar(c);
|
||||
return fontDef.xOffset;
|
||||
}
|
||||
|
||||
int StringBMFont::getYOffsetForChar(unsigned short c)
|
||||
{
|
||||
ccBMFontDef fontDef = getFontDefForChar(c);
|
||||
return fontDef.yOffset;
|
||||
}
|
||||
|
||||
Rect StringBMFont::getRectForChar(unsigned short c)
|
||||
{
|
||||
ccBMFontDef fontDef = getFontDefForChar(c);
|
||||
return fontDef.rect;
|
||||
}
|
||||
|
||||
int StringBMFont::getAdvanceForChar(unsigned short c, int hintPositionInString)
|
||||
{
|
||||
ccBMFontDef fontDef = getFontDefForChar(c);
|
||||
return fontDef.xAdvance;
|
||||
}
|
||||
|
||||
void StringBMFont::setLabelContentSize(const Size &newSize)
|
||||
{
|
||||
setContentSize(newSize);
|
||||
}
|
||||
|
||||
void StringBMFont::createStringSprites()
|
||||
{
|
||||
LabelTextFormatter::createStringSprites(this);
|
||||
}
|
||||
|
||||
void StringBMFont::setString(const char *newString)
|
||||
{
|
||||
// store initial string in char8 format
|
||||
_initialStringUTF8 = newString;
|
||||
|
||||
// update the initial string if needed
|
||||
unsigned short* utf16String = cc_utf8_to_utf16(newString);
|
||||
unsigned short* tmp = _initialString;
|
||||
_initialString = copyUTF16StringNN(utf16String);
|
||||
|
||||
CC_SAFE_DELETE_ARRAY(tmp);
|
||||
CC_SAFE_DELETE_ARRAY(utf16String);
|
||||
|
||||
// do the rest of the josb
|
||||
updateLabel();
|
||||
}
|
||||
|
||||
void StringBMFont::setCString(const char *label)
|
||||
{
|
||||
setString(label);
|
||||
}
|
||||
|
||||
void StringBMFont::updateLabel()
|
||||
{
|
||||
if ( _initialString!=0 )
|
||||
{
|
||||
// set the new string
|
||||
CC_SAFE_DELETE_ARRAY(_string);
|
||||
_string = copyUTF16StringNN(_initialString);
|
||||
|
||||
// hide all the letters and create or recicle sprites for the new letters
|
||||
updateLetterSprites();
|
||||
|
||||
// format the text on more than line
|
||||
multilineText();
|
||||
|
||||
// align the text (left - center - right)
|
||||
alignText();
|
||||
}
|
||||
}
|
||||
|
||||
void StringBMFont::updateLetterSprites()
|
||||
{
|
||||
// hide all the letters
|
||||
hideStringSprites();
|
||||
|
||||
// create new letters sprites
|
||||
createStringSprites();
|
||||
}
|
||||
|
||||
void StringBMFont::hideStringSprites()
|
||||
{
|
||||
if (_children && _children->count() != 0)
|
||||
{
|
||||
Object* child;
|
||||
CCARRAY_FOREACH(_children, child)
|
||||
{
|
||||
Node* pNode = (Node*) child;
|
||||
if (pNode)
|
||||
{
|
||||
pNode->setVisible(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void StringBMFont::multilineText()
|
||||
{
|
||||
if (_width > 0)
|
||||
{
|
||||
// format on more than one line
|
||||
LabelTextFormatter::multilineText(this);
|
||||
|
||||
// hide all the letter sprites and create/reclaim letters sprite with new position
|
||||
updateLetterSprites();
|
||||
}
|
||||
}
|
||||
|
||||
void StringBMFont::alignText()
|
||||
{
|
||||
if (_alignment != TextHAlignment::LEFT)
|
||||
{
|
||||
LabelTextFormatter::alignText(this);
|
||||
}
|
||||
}
|
||||
|
||||
unsigned short * StringBMFont::getUTF8String()
|
||||
{
|
||||
return _string;
|
||||
}
|
||||
|
||||
Sprite * StringBMFont::getSpriteChild(int ID)
|
||||
{
|
||||
return (Sprite*)this->getChildByTag(ID);
|
||||
}
|
||||
|
||||
float StringBMFont::getMaxLineWidth()
|
||||
{
|
||||
return _width;
|
||||
}
|
||||
|
||||
TextHAlignment StringBMFont::getTextAlignment()
|
||||
{
|
||||
return _alignment;
|
||||
}
|
||||
|
||||
Array* StringBMFont::getChildrenLetters()
|
||||
{
|
||||
return _children;
|
||||
}
|
||||
|
||||
void StringBMFont::assignNewUTF8String(unsigned short *newString)
|
||||
{
|
||||
CC_SAFE_DELETE_ARRAY(_string);
|
||||
_string = newString;
|
||||
}
|
||||
|
||||
Size StringBMFont::getLabelContentSize()
|
||||
{
|
||||
return getContentSize();
|
||||
}
|
||||
|
||||
bool StringBMFont::breakLineWithoutSpace()
|
||||
{
|
||||
return _lineBreakWithoutSpaces;
|
||||
}
|
||||
|
||||
|
||||
NS_CC_END
|
|
@ -0,0 +1,204 @@
|
|||
/****************************************************************************
|
||||
Copyright (c) 2010-2012 cocos2d-x.org
|
||||
Copyright (c) 2008-2010 Ricardo Quesada
|
||||
Copyright (c) 2011 Zynga 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.
|
||||
|
||||
Use any of these editors to generate BMFonts:
|
||||
http://glyphdesigner.71squared.com/ (Commercial, Mac OS X)
|
||||
http://www.n4te.com/hiero/hiero.jnlp (Free, Java)
|
||||
http://slick.cokeandcode.com/demos/hiero.jnlp (Free, Java)
|
||||
http://www.angelcode.com/products/bmfont/ (Free, Windows only)
|
||||
|
||||
****************************************************************************/
|
||||
#ifndef __CCBITMAP_FONT_ATLAS_H__NEW_
|
||||
#define __CCBITMAP_FONT_ATLAS_H__NEW_
|
||||
|
||||
#include "sprite_nodes/CCSpriteBatchNode.h"
|
||||
#include "support/data_support/uthash.h"
|
||||
#include "CCLabelBMFont.h"
|
||||
#include "CCLabelTextFormatProtocol.h"
|
||||
#include <map>
|
||||
#include <sstream>
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
#include "CCLabel.h"
|
||||
|
||||
NS_CC_BEGIN
|
||||
|
||||
class CC_DLL StringBMFont: public Label, public LabelTextFormatProtocol
|
||||
{
|
||||
public:
|
||||
StringBMFont();
|
||||
|
||||
virtual ~StringBMFont();
|
||||
/** Purges the cached data.
|
||||
Removes from memory the cached configurations and the atlas name dictionary.
|
||||
@since v0.99.3
|
||||
*/
|
||||
static void purgeCachedData();
|
||||
|
||||
/** creates a bitmap font atlas with an initial string and the FNT file */
|
||||
static StringBMFont * create(const char *str, const char *fntFile, float width, TextHAlignment alignment, Point imageOffset);
|
||||
|
||||
static StringBMFont * create(const char *str, const char *fntFile, float width, TextHAlignment alignment);
|
||||
|
||||
static StringBMFont * create(const char *str, const char *fntFile, float width);
|
||||
|
||||
static StringBMFont * create(const char *str, const char *fntFile);
|
||||
|
||||
/** Creates an label.
|
||||
*/
|
||||
static StringBMFont * create();
|
||||
|
||||
bool init();
|
||||
/** init a bitmap font atlas with an initial string and the FNT file */
|
||||
bool initWithString(const char *str, const char *fntFile, float width = kLabelAutomaticWidth, TextHAlignment alignment = TextHAlignment::LEFT, Point imageOffset = Point::ZERO);
|
||||
|
||||
/** updates the font chars based on the string to render */
|
||||
// super method
|
||||
virtual void setString(const char *newString);
|
||||
|
||||
virtual const char* getString(void) const;
|
||||
virtual void setCString(const char *label);
|
||||
virtual void setAnchorPoint(const Point& var);
|
||||
virtual void updateLabel();
|
||||
virtual void setAlignment(TextHAlignment alignment);
|
||||
virtual void setWidth(float width);
|
||||
virtual void setLineBreakWithoutSpace(bool breakWithoutSpace);
|
||||
virtual void setScale(float scale);
|
||||
virtual void setScaleX(float scaleX);
|
||||
virtual void setScaleY(float scaleY);
|
||||
|
||||
// RGBAProtocol
|
||||
virtual bool isOpacityModifyRGB() const;
|
||||
virtual void setOpacityModifyRGB(bool isOpacityModifyRGB);
|
||||
virtual GLubyte getOpacity() const;
|
||||
virtual GLubyte getDisplayedOpacity() const;
|
||||
virtual void setOpacity(GLubyte opacity);
|
||||
virtual void updateDisplayedOpacity(GLubyte parentOpacity);
|
||||
virtual bool isCascadeOpacityEnabled() const;
|
||||
virtual void setCascadeOpacityEnabled(bool cascadeOpacityEnabled);
|
||||
virtual const Color3B& getColor(void) const;
|
||||
virtual const Color3B& getDisplayedColor() const;
|
||||
virtual void setColor(const Color3B& color);
|
||||
virtual void updateDisplayedColor(const Color3B& parentColor);
|
||||
virtual bool isCascadeColorEnabled() const;
|
||||
virtual void setCascadeColorEnabled(bool cascadeColorEnabled);
|
||||
|
||||
|
||||
// StringBMFont protocol stuff
|
||||
virtual Sprite * getSpriteChild(int ID);
|
||||
virtual Array * getChildrenLetters();
|
||||
virtual Sprite * getSpriteForChar(unsigned short int theChar, int spriteIndexHint);
|
||||
virtual int getCommonLineHeight();
|
||||
virtual int getKerningForCharsPair(unsigned short first, unsigned short second);
|
||||
virtual int getXOffsetForChar(unsigned short c);
|
||||
virtual int getYOffsetForChar(unsigned short c);
|
||||
virtual int getAdvanceForChar(unsigned short c, int hintPositionInString);
|
||||
virtual Rect getRectForChar(unsigned short c);
|
||||
float getLetterPosXLeft( Sprite* sp );
|
||||
float getLetterPosXRight( Sprite* sp );
|
||||
virtual int getStringNumLines();
|
||||
virtual int getStringLenght();
|
||||
virtual unsigned short getCharAtStringPosition(int position);
|
||||
virtual unsigned short * getUTF8String();
|
||||
virtual void assignNewUTF8String(unsigned short *newString);
|
||||
virtual float getMaxLineWidth();
|
||||
virtual bool breakLineWithoutSpace();
|
||||
virtual TextHAlignment getTextAlignment();
|
||||
virtual Size getLabelContentSize();
|
||||
virtual void setLabelContentSize(const Size &newSize);
|
||||
|
||||
|
||||
void setFntFile(const char* fntFile);
|
||||
const char* getFntFile();
|
||||
|
||||
#if CC_LABELBMFONT_DEBUG_DRAW
|
||||
virtual void draw();
|
||||
#endif // CC_LABELBMFONT_DEBUG_DRAW
|
||||
|
||||
private:
|
||||
char * atlasNameFromFntFile(const char *fntFile);
|
||||
int kerningAmountForFirst(unsigned short first, unsigned short second);
|
||||
|
||||
// some more new stuff
|
||||
void alignText();
|
||||
void multilineText();
|
||||
ccBMFontDef getFontDefForChar(unsigned short int theChar);
|
||||
void createStringSprites();
|
||||
void hideStringSprites();
|
||||
void updateLetterSprites();
|
||||
|
||||
|
||||
protected:
|
||||
|
||||
// string to render
|
||||
unsigned short* _string;
|
||||
|
||||
// name of fntFile
|
||||
std::string _fntFile;
|
||||
|
||||
// initial string without line breaks
|
||||
unsigned short* _initialString;
|
||||
std::string _initialStringUTF8;
|
||||
|
||||
// alignment of all lines
|
||||
TextHAlignment _alignment;
|
||||
// max width until a line break is added
|
||||
float _width;
|
||||
|
||||
CCBMFontConfiguration *_configuration;
|
||||
|
||||
bool _lineBreakWithoutSpaces;
|
||||
// offset of the texture atlas
|
||||
Point _imageOffset;
|
||||
|
||||
// reused char
|
||||
Sprite *_reusedChar;
|
||||
|
||||
// texture RGBA
|
||||
GLubyte _displayedOpacity;
|
||||
GLubyte _realOpacity;
|
||||
Color3B _displayedColor;
|
||||
Color3B _realColor;
|
||||
bool _cascadeColorEnabled;
|
||||
bool _cascadeOpacityEnabled;
|
||||
/** conforms to RGBAProtocol protocol */
|
||||
bool _isOpacityModifyRGB;
|
||||
|
||||
};
|
||||
|
||||
/** Free function that parses a FNT file a place it on the cache
|
||||
*/
|
||||
CC_DLL CCBMFontConfiguration * FNTConfigLoadFile( const char *file );
|
||||
/** Purges the FNT config cache
|
||||
*/
|
||||
CC_DLL void FNTConfigRemoveCache( void );
|
||||
|
||||
// end of GUI group
|
||||
/// @}
|
||||
/// @}
|
||||
|
||||
NS_CC_END
|
||||
|
||||
#endif //__CCBITMAP_FONT_ATLAS_H__
|
|
@ -0,0 +1,671 @@
|
|||
/****************************************************************************
|
||||
Copyright (c) 2013 Zynga 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.
|
||||
****************************************************************************/
|
||||
|
||||
#include "cocos2d.h"
|
||||
#include "CCStringTTF.h"
|
||||
#include "CCFont.h"
|
||||
#include "CCLabelTextFormatter.h"
|
||||
#include "CCFontAtlasCache.h"
|
||||
|
||||
NS_CC_BEGIN
|
||||
|
||||
StringTTF::StringTTF(FontAtlas *pAtlas, TextHAlignment alignment): _currentUTF8String(0),
|
||||
_originalUTF8String(0),
|
||||
_fontAtlas(pAtlas),
|
||||
_alignment(alignment),
|
||||
_lineBreakWithoutSpaces(false),
|
||||
_advances(0),
|
||||
_displayedColor(Color3B::WHITE),
|
||||
_realColor(Color3B::WHITE),
|
||||
_cascadeColorEnabled(true)
|
||||
{
|
||||
}
|
||||
|
||||
StringTTF* StringTTF::create(FontAtlas *pAtlas, TextHAlignment alignment, int lineSize)
|
||||
{
|
||||
StringTTF *ret = new StringTTF(pAtlas, alignment);
|
||||
|
||||
if (!ret)
|
||||
return nullptr;
|
||||
|
||||
if( ret->init() )
|
||||
{
|
||||
ret->autorelease();
|
||||
return ret;
|
||||
}
|
||||
else
|
||||
{
|
||||
delete ret;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
StringTTF::~StringTTF()
|
||||
{
|
||||
if (_currentUTF8String)
|
||||
{
|
||||
delete [] _currentUTF8String;
|
||||
_currentUTF8String = 0;
|
||||
}
|
||||
|
||||
if (_advances)
|
||||
{
|
||||
delete [] _advances;
|
||||
_advances = 0;
|
||||
}
|
||||
|
||||
if (_fontAtlas)
|
||||
{
|
||||
FontAtlasCache::releaseFontAtlas(_fontAtlas);
|
||||
}
|
||||
}
|
||||
|
||||
bool StringTTF::init()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
void StringTTF::setString(const char *stringToRender)
|
||||
{
|
||||
setText(stringToRender, 0, TextHAlignment::CENTER, false);
|
||||
}
|
||||
|
||||
bool StringTTF::setText(const char *stringToRender, float lineWidth, TextHAlignment alignment, bool lineBreakWithoutSpaces)
|
||||
{
|
||||
if (!_fontAtlas)
|
||||
return false;
|
||||
|
||||
_width = lineWidth;
|
||||
_alignment = alignment;
|
||||
_lineBreakWithoutSpaces = lineBreakWithoutSpaces;
|
||||
|
||||
// release all the sprites
|
||||
moveAllSpritesToCache();
|
||||
|
||||
// store locally common line height
|
||||
_commonLineHeight = _fontAtlas->getCommonLineHeight();
|
||||
if (_commonLineHeight <= 0)
|
||||
return false;
|
||||
|
||||
int numLetter = 0;
|
||||
unsigned short* utf16String = cc_utf8_to_utf16(stringToRender);
|
||||
if(!utf16String)
|
||||
return false;
|
||||
|
||||
numLetter = cc_wcslen(utf16String);
|
||||
SpriteBatchNode::initWithTexture(&_fontAtlas->getTexture(0), numLetter);
|
||||
_cascadeColorEnabled = true;
|
||||
|
||||
//
|
||||
setCurrentString(utf16String);
|
||||
setOriginalString(utf16String);
|
||||
|
||||
// align text
|
||||
alignText();
|
||||
|
||||
// done here
|
||||
return true;
|
||||
}
|
||||
|
||||
void StringTTF::setAlignment(TextHAlignment alignment)
|
||||
{
|
||||
// store the new alignment
|
||||
if (alignment != _alignment)
|
||||
{
|
||||
// store
|
||||
_alignment = alignment;
|
||||
|
||||
// reset the string
|
||||
resetCurrentString();
|
||||
|
||||
// need to align text again
|
||||
alignText();
|
||||
}
|
||||
}
|
||||
|
||||
void StringTTF::setWidth(float width)
|
||||
{
|
||||
if (width != _width)
|
||||
{
|
||||
// store
|
||||
_width = width;
|
||||
|
||||
// need to align text again
|
||||
alignText();
|
||||
}
|
||||
}
|
||||
|
||||
void StringTTF::setLineBreakWithoutSpace(bool breakWithoutSpace)
|
||||
{
|
||||
if (breakWithoutSpace != _lineBreakWithoutSpaces)
|
||||
{
|
||||
// store
|
||||
_lineBreakWithoutSpaces = breakWithoutSpace;
|
||||
|
||||
// need to align text again
|
||||
alignText();
|
||||
}
|
||||
}
|
||||
|
||||
void StringTTF::setScale(float scale)
|
||||
{
|
||||
Node::setScale(scale);
|
||||
alignText();
|
||||
}
|
||||
|
||||
void StringTTF::setScaleX(float scaleX)
|
||||
{
|
||||
Node::setScaleX(scaleX);
|
||||
alignText();
|
||||
}
|
||||
|
||||
void StringTTF::setScaleY(float scaleY)
|
||||
{
|
||||
Node::setScaleY(scaleY);
|
||||
alignText();
|
||||
}
|
||||
|
||||
void StringTTF::alignText()
|
||||
{
|
||||
hideAllLetters();
|
||||
LabelTextFormatter::createStringSprites(this);
|
||||
|
||||
if( LabelTextFormatter::multilineText(this) )
|
||||
{
|
||||
hideAllLetters();
|
||||
LabelTextFormatter::createStringSprites(this);
|
||||
}
|
||||
|
||||
LabelTextFormatter::alignText(this);
|
||||
}
|
||||
|
||||
void StringTTF::hideAllLetters()
|
||||
{
|
||||
Object* Obj = NULL;
|
||||
CCARRAY_FOREACH(&_spriteArray, Obj)
|
||||
{
|
||||
((Sprite *)Obj)->setVisible(false);
|
||||
}
|
||||
|
||||
CCARRAY_FOREACH(&_spriteArrayCache, Obj)
|
||||
{
|
||||
((Sprite *)Obj)->setVisible(false);
|
||||
}
|
||||
}
|
||||
|
||||
bool StringTTF::computeAdvancesForString(unsigned short int *stringToRender)
|
||||
{
|
||||
if (_advances)
|
||||
{
|
||||
delete [] _advances;
|
||||
_advances = 0;
|
||||
}
|
||||
|
||||
Font &theFont = _fontAtlas->getFont();
|
||||
|
||||
int letterCount = 0;
|
||||
_advances = theFont.getAdvancesForTextUTF16(stringToRender, letterCount);
|
||||
|
||||
if(!_advances)
|
||||
return false;
|
||||
else
|
||||
return true;
|
||||
}
|
||||
|
||||
bool StringTTF::setOriginalString(unsigned short *stringToSet)
|
||||
{
|
||||
if (_originalUTF8String)
|
||||
{
|
||||
delete [] _originalUTF8String;
|
||||
_originalUTF8String = 0;
|
||||
}
|
||||
|
||||
int newStringLenght = cc_wcslen(stringToSet);
|
||||
_originalUTF8String = new unsigned short int [newStringLenght + 1];
|
||||
memset(_originalUTF8String, 0, (newStringLenght + 1) * 2);
|
||||
memcpy(_originalUTF8String, stringToSet, (newStringLenght * 2));
|
||||
_originalUTF8String[newStringLenght] = 0;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool StringTTF::setCurrentString(unsigned short *stringToSet)
|
||||
{
|
||||
// set the new string
|
||||
if (_currentUTF8String)
|
||||
{
|
||||
delete [] _currentUTF8String;
|
||||
_currentUTF8String = 0;
|
||||
}
|
||||
//
|
||||
_currentUTF8String = stringToSet;
|
||||
// compute the advances
|
||||
return computeAdvancesForString(stringToSet);
|
||||
}
|
||||
|
||||
void StringTTF::resetCurrentString()
|
||||
{
|
||||
// set the new string
|
||||
if (_currentUTF8String)
|
||||
{
|
||||
delete [] _currentUTF8String;
|
||||
_currentUTF8String = 0;
|
||||
}
|
||||
|
||||
int stringLenght = cc_wcslen(_originalUTF8String);
|
||||
_currentUTF8String = new unsigned short int [stringLenght + 1];
|
||||
memcpy(_currentUTF8String, _originalUTF8String, stringLenght * 2);
|
||||
_currentUTF8String[stringLenght] = 0;
|
||||
|
||||
}
|
||||
|
||||
Sprite * StringTTF::createNewSpriteFromLetterDefinition(FontLetterDefinition &theDefinition, Texture2D *theTexture)
|
||||
{
|
||||
Rect uvRect;
|
||||
uvRect.size.height = theDefinition.height;
|
||||
uvRect.size.width = theDefinition.width;
|
||||
uvRect.origin.x = theDefinition.U;
|
||||
uvRect.origin.y = theDefinition.V;
|
||||
|
||||
SpriteFrame *pFrame = SpriteFrame::createWithTexture(theTexture, uvRect);
|
||||
Sprite *tempSprite = getSprite();
|
||||
|
||||
if (!tempSprite)
|
||||
return nullptr;
|
||||
|
||||
tempSprite->initWithSpriteFrame(pFrame);
|
||||
tempSprite->setAnchorPoint(Point(theDefinition.anchorX, theDefinition.anchorY));
|
||||
tempSprite->setBatchNode(this);
|
||||
|
||||
return tempSprite;
|
||||
}
|
||||
|
||||
Sprite * StringTTF::updateSpriteWithLetterDefinition(Sprite *spriteToUpdate, FontLetterDefinition &theDefinition, Texture2D *theTexture)
|
||||
{
|
||||
if (!spriteToUpdate)
|
||||
{
|
||||
return nullptr;
|
||||
}
|
||||
else
|
||||
{
|
||||
Rect uvRect;
|
||||
uvRect.size.height = theDefinition.height;
|
||||
uvRect.size.width = theDefinition.width;
|
||||
uvRect.origin.x = theDefinition.U;
|
||||
uvRect.origin.y = theDefinition.V;
|
||||
|
||||
SpriteFrame *frame = SpriteFrame::createWithTexture(theTexture, uvRect);
|
||||
if (frame)
|
||||
{
|
||||
spriteToUpdate->setTexture(theTexture);
|
||||
spriteToUpdate->setDisplayFrame(frame);
|
||||
spriteToUpdate->setAnchorPoint(Point(theDefinition.anchorX, theDefinition.anchorY));
|
||||
spriteToUpdate->setBatchNode(this);
|
||||
}
|
||||
|
||||
return spriteToUpdate;
|
||||
}
|
||||
}
|
||||
|
||||
Sprite * StringTTF::getSpriteForLetter(unsigned short int newLetter)
|
||||
{
|
||||
if (!_fontAtlas)
|
||||
return nullptr;
|
||||
|
||||
FontLetterDefinition tempDefinition;
|
||||
bool validDefinition = _fontAtlas->getLetterDefinitionForChar(newLetter, tempDefinition);
|
||||
if (validDefinition)
|
||||
{
|
||||
Sprite *newSprite = createNewSpriteFromLetterDefinition(tempDefinition, &_fontAtlas->getTexture(tempDefinition.textureID) );
|
||||
this->addChild(newSprite);
|
||||
return newSprite;
|
||||
}
|
||||
else
|
||||
{
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
Sprite * StringTTF::updateSpriteForLetter(Sprite *spriteToUpdate, unsigned short int newLetter)
|
||||
{
|
||||
if (!spriteToUpdate || !_fontAtlas)
|
||||
return nullptr;
|
||||
|
||||
FontLetterDefinition tempDefinition;
|
||||
bool validDefinition = _fontAtlas->getLetterDefinitionForChar(newLetter, tempDefinition);
|
||||
if (validDefinition)
|
||||
{
|
||||
Sprite *pNewSprite = updateSpriteWithLetterDefinition(spriteToUpdate, tempDefinition, &_fontAtlas->getTexture(tempDefinition.textureID) );
|
||||
return pNewSprite;
|
||||
}
|
||||
else
|
||||
{
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void StringTTF::moveAllSpritesToCache()
|
||||
{
|
||||
Object* pObj = NULL;
|
||||
CCARRAY_FOREACH(&_spriteArray, pObj)
|
||||
{
|
||||
((Sprite *)pObj)->removeFromParent();
|
||||
_spriteArrayCache.addObject(pObj);
|
||||
}
|
||||
|
||||
_spriteArray.removeAllObjects();
|
||||
}
|
||||
|
||||
Sprite * StringTTF::getSprite()
|
||||
{
|
||||
if (_spriteArrayCache.count())
|
||||
{
|
||||
Sprite *retSprite = (Sprite *) _spriteArrayCache.lastObject();
|
||||
_spriteArrayCache.removeLastObject();
|
||||
return retSprite;
|
||||
}
|
||||
else
|
||||
{
|
||||
Sprite *retSprite = new Sprite;
|
||||
return retSprite;
|
||||
}
|
||||
}
|
||||
|
||||
///// PROTOCOL STUFF
|
||||
|
||||
Sprite * StringTTF::getSpriteChild(int ID)
|
||||
{
|
||||
Object* pObj = NULL;
|
||||
CCARRAY_FOREACH(&_spriteArray, pObj)
|
||||
{
|
||||
Sprite *pSprite = (Sprite *)pObj;
|
||||
if ( pSprite->getTag() == ID)
|
||||
{
|
||||
return pSprite;
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
Array * StringTTF::getChildrenLetters()
|
||||
{
|
||||
return &_spriteArray;
|
||||
}
|
||||
|
||||
Sprite * StringTTF::getSpriteForChar(unsigned short int theChar, int spriteIndexHint)
|
||||
{
|
||||
// ret sprite
|
||||
Sprite *retSprite = 0;
|
||||
|
||||
// look for already existing sprites
|
||||
retSprite = getSpriteChild(spriteIndexHint);
|
||||
|
||||
if (!retSprite)
|
||||
{
|
||||
retSprite = getSpriteForLetter(theChar);
|
||||
if (!retSprite)
|
||||
return nullptr;
|
||||
|
||||
if (retSprite)
|
||||
retSprite->setTag(spriteIndexHint);
|
||||
|
||||
_spriteArray.addObject(retSprite);
|
||||
}
|
||||
|
||||
// the sprite is now visible
|
||||
retSprite->setVisible(true);
|
||||
|
||||
// set the right texture letter to the sprite
|
||||
updateSpriteForLetter(retSprite, theChar);
|
||||
|
||||
// we are done here
|
||||
return retSprite;
|
||||
}
|
||||
|
||||
float StringTTF::getLetterPosXLeft( Sprite* sp )
|
||||
{
|
||||
float scaleX = _scaleX;
|
||||
return sp->getPosition().x * scaleX - (sp->getContentSize().width * scaleX * sp->getAnchorPoint().x);
|
||||
}
|
||||
|
||||
float StringTTF::getLetterPosXRight( Sprite* sp )
|
||||
{
|
||||
float scaleX = _scaleX;
|
||||
return sp->getPosition().x * scaleX + (sp->getContentSize().width * scaleX * sp->getAnchorPoint().x);
|
||||
}
|
||||
|
||||
int StringTTF::getCommonLineHeight()
|
||||
{
|
||||
return _commonLineHeight;
|
||||
}
|
||||
|
||||
int StringTTF::getKerningForCharsPair(unsigned short first, unsigned short second)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
int StringTTF::getXOffsetForChar(unsigned short c)
|
||||
{
|
||||
FontLetterDefinition tempDefinition;
|
||||
bool validDefinition = _fontAtlas->getLetterDefinitionForChar(c, tempDefinition);
|
||||
if (!validDefinition)
|
||||
return -1;
|
||||
|
||||
return (tempDefinition.offsetX);
|
||||
}
|
||||
|
||||
int StringTTF::getYOffsetForChar(unsigned short c)
|
||||
{
|
||||
FontLetterDefinition tempDefinition;
|
||||
bool validDefinition = _fontAtlas->getLetterDefinitionForChar(c, tempDefinition);
|
||||
if (!validDefinition)
|
||||
return -1;
|
||||
|
||||
return (tempDefinition.offsetY);
|
||||
}
|
||||
|
||||
int StringTTF::getAdvanceForChar(unsigned short c, int hintPositionInString)
|
||||
{
|
||||
if (_advances)
|
||||
{
|
||||
// not that advance contains the X offset already
|
||||
FontLetterDefinition tempDefinition;
|
||||
bool validDefinition = _fontAtlas->getLetterDefinitionForChar(c, tempDefinition);
|
||||
if (!validDefinition)
|
||||
return -1;
|
||||
|
||||
return (_advances[hintPositionInString].width - tempDefinition.offsetX);
|
||||
}
|
||||
else
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
Rect StringTTF::getRectForChar(unsigned short c)
|
||||
{
|
||||
return _fontAtlas->getFont().getRectForChar(c);
|
||||
}
|
||||
|
||||
// string related stuff
|
||||
int StringTTF::getStringNumLines()
|
||||
{
|
||||
int quantityOfLines = 1;
|
||||
|
||||
unsigned int stringLen = _currentUTF8String ? cc_wcslen(_currentUTF8String) : 0;
|
||||
if (stringLen == 0)
|
||||
return (-1);
|
||||
|
||||
// count number of lines
|
||||
for (unsigned int i = 0; i < stringLen - 1; ++i)
|
||||
{
|
||||
unsigned short c = _currentUTF8String[i];
|
||||
if (c == '\n')
|
||||
{
|
||||
quantityOfLines++;
|
||||
}
|
||||
}
|
||||
|
||||
return quantityOfLines;
|
||||
}
|
||||
|
||||
int StringTTF::getStringLenght()
|
||||
{
|
||||
return _currentUTF8String ? cc_wcslen(_currentUTF8String) : 0;
|
||||
}
|
||||
|
||||
unsigned short StringTTF::getCharAtStringPosition(int position)
|
||||
{
|
||||
return _currentUTF8String[position];
|
||||
}
|
||||
|
||||
unsigned short * StringTTF::getUTF8String()
|
||||
{
|
||||
return _currentUTF8String;
|
||||
}
|
||||
|
||||
void StringTTF::assignNewUTF8String(unsigned short *newString)
|
||||
{
|
||||
setCurrentString(newString);
|
||||
}
|
||||
|
||||
TextHAlignment StringTTF::getTextAlignment()
|
||||
{
|
||||
return _alignment;
|
||||
}
|
||||
|
||||
// label related stuff
|
||||
float StringTTF::getMaxLineWidth()
|
||||
{
|
||||
return _width;
|
||||
}
|
||||
|
||||
bool StringTTF::breakLineWithoutSpace()
|
||||
{
|
||||
return _lineBreakWithoutSpaces;
|
||||
}
|
||||
|
||||
Size StringTTF::getLabelContentSize()
|
||||
{
|
||||
return getContentSize();
|
||||
}
|
||||
|
||||
void StringTTF::setLabelContentSize(const Size &newSize)
|
||||
{
|
||||
setContentSize(newSize);
|
||||
}
|
||||
|
||||
|
||||
// RGBA protocol
|
||||
|
||||
|
||||
bool StringTTF::isOpacityModifyRGB() const
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
void StringTTF::setOpacityModifyRGB(bool isOpacityModifyRGB)
|
||||
{
|
||||
}
|
||||
|
||||
unsigned char StringTTF::getOpacity() const
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
unsigned char StringTTF::getDisplayedOpacity() const
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
void StringTTF::setOpacity(GLubyte opacity)
|
||||
{
|
||||
}
|
||||
void StringTTF::updateDisplayedOpacity(GLubyte parentOpacity)
|
||||
{
|
||||
}
|
||||
|
||||
bool StringTTF::isCascadeOpacityEnabled() const
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
void StringTTF::setCascadeOpacityEnabled(bool cascadeOpacityEnabled)
|
||||
{
|
||||
}
|
||||
|
||||
const Color3B& StringTTF::getColor(void) const
|
||||
{
|
||||
return _realColor;
|
||||
}
|
||||
|
||||
const Color3B& StringTTF::getDisplayedColor() const
|
||||
{
|
||||
return _displayedColor;
|
||||
}
|
||||
|
||||
void StringTTF::setColor(const Color3B& color)
|
||||
{
|
||||
_displayedColor = _realColor = color;
|
||||
|
||||
if( _cascadeColorEnabled )
|
||||
{
|
||||
Color3B parentColor = Color3B::WHITE;
|
||||
RGBAProtocol* pParent = dynamic_cast<RGBAProtocol*>(_parent);
|
||||
|
||||
if (pParent && pParent->isCascadeColorEnabled())
|
||||
parentColor = pParent->getDisplayedColor();
|
||||
|
||||
updateDisplayedColor(parentColor);
|
||||
}
|
||||
}
|
||||
|
||||
void StringTTF::updateDisplayedColor(const Color3B& parentColor)
|
||||
{
|
||||
_displayedColor.r = _realColor.r * parentColor.r/255.0;
|
||||
_displayedColor.g = _realColor.g * parentColor.g/255.0;
|
||||
_displayedColor.b = _realColor.b * parentColor.b/255.0;
|
||||
|
||||
Object* pObj;
|
||||
CCARRAY_FOREACH(_children, pObj)
|
||||
{
|
||||
Sprite *item = static_cast<Sprite*>( pObj );
|
||||
item->updateDisplayedColor(_displayedColor);
|
||||
}
|
||||
}
|
||||
|
||||
bool StringTTF::isCascadeColorEnabled() const
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
void StringTTF::setCascadeColorEnabled(bool cascadeColorEnabled)
|
||||
{
|
||||
_cascadeColorEnabled = cascadeColorEnabled;
|
||||
}
|
||||
|
||||
NS_CC_END
|
|
@ -0,0 +1,146 @@
|
|||
/****************************************************************************
|
||||
Copyright (c) 2013 Zynga 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.
|
||||
****************************************************************************/
|
||||
|
||||
#ifndef _StringTTF_h
|
||||
#define _StringTTF_h
|
||||
|
||||
#include "CCFontDefinition.h"
|
||||
#include "CCLabelTextFormatProtocol.h"
|
||||
#include "CCLabel.h"
|
||||
#include "CCFontAtlas.h"
|
||||
|
||||
NS_CC_BEGIN
|
||||
|
||||
class CC_DLL StringTTF : public Label, public LabelTextFormatProtocol
|
||||
{
|
||||
public:
|
||||
|
||||
static StringTTF* create(FontAtlas *pAtlas, TextHAlignment alignment = TextHAlignment::LEFT, int lineSize = 0);
|
||||
|
||||
// main interface
|
||||
bool setText(const char *stringToRender, float lineWidth, TextHAlignment alignment = TextHAlignment::LEFT, bool lineBreakWithoutSpaces = false);
|
||||
void setString(const char *stringToRender);
|
||||
const char* getString() const { return "not implemented"; }
|
||||
|
||||
virtual void setAlignment(TextHAlignment alignment);
|
||||
virtual void setWidth(float width);
|
||||
virtual void setLineBreakWithoutSpace(bool breakWithoutSpace);
|
||||
virtual void setScale(float scale);
|
||||
virtual void setScaleX(float scaleX);
|
||||
virtual void setScaleY(float scaleY);
|
||||
|
||||
|
||||
// RGBAProtocol
|
||||
virtual bool isOpacityModifyRGB() const;
|
||||
virtual void setOpacityModifyRGB(bool isOpacityModifyRGB);
|
||||
virtual unsigned char getOpacity() const;
|
||||
virtual unsigned char getDisplayedOpacity() const;
|
||||
virtual void setOpacity(GLubyte opacity);
|
||||
virtual void updateDisplayedOpacity(GLubyte parentOpacity);
|
||||
virtual bool isCascadeOpacityEnabled() const;
|
||||
virtual void setCascadeOpacityEnabled(bool cascadeOpacityEnabled);
|
||||
virtual const Color3B& getColor(void) const;
|
||||
virtual const Color3B& getDisplayedColor() const;
|
||||
virtual void setColor(const Color3B& color);
|
||||
virtual void updateDisplayedColor(const Color3B& parentColor);
|
||||
virtual bool isCascadeColorEnabled() const;
|
||||
virtual void setCascadeColorEnabled(bool cascadeColorEnabled);
|
||||
|
||||
|
||||
// CCLabelTextFormat protocol implementation
|
||||
|
||||
// sprite related stuff
|
||||
virtual Sprite * getSpriteChild(int ID);
|
||||
virtual Array * getChildrenLetters();
|
||||
virtual Sprite * getSpriteForChar(unsigned short int theChar, int spriteIndexHint);
|
||||
virtual float getLetterPosXLeft( Sprite* sp );
|
||||
virtual float getLetterPosXRight( Sprite* sp );
|
||||
|
||||
// font related stuff
|
||||
virtual int getCommonLineHeight();
|
||||
virtual int getKerningForCharsPair(unsigned short first, unsigned short second);
|
||||
virtual int getXOffsetForChar(unsigned short c);
|
||||
virtual int getYOffsetForChar(unsigned short c);
|
||||
virtual int getAdvanceForChar(unsigned short c, int hintPositionInString);
|
||||
virtual Rect getRectForChar(unsigned short c) ;
|
||||
|
||||
// string related stuff
|
||||
virtual int getStringNumLines();
|
||||
virtual int getStringLenght();
|
||||
virtual unsigned short getCharAtStringPosition(int position);
|
||||
virtual unsigned short * getUTF8String();
|
||||
virtual void assignNewUTF8String(unsigned short *newString);
|
||||
virtual TextHAlignment getTextAlignment();
|
||||
|
||||
// label related stuff
|
||||
virtual float getMaxLineWidth() ;
|
||||
virtual bool breakLineWithoutSpace();
|
||||
virtual Size getLabelContentSize();
|
||||
virtual void setLabelContentSize(const Size &newSize);
|
||||
|
||||
|
||||
private:
|
||||
|
||||
//
|
||||
StringTTF(FontAtlas *pAtlas, TextHAlignment alignment = TextHAlignment::LEFT);
|
||||
~StringTTF();
|
||||
|
||||
bool init();
|
||||
|
||||
void alignText();
|
||||
void hideAllLetters();
|
||||
void moveAllSpritesToCache();
|
||||
|
||||
bool computeAdvancesForString(unsigned short int *stringToRender);
|
||||
bool setCurrentString(unsigned short *stringToSet);
|
||||
bool setOriginalString(unsigned short *stringToSet);
|
||||
void resetCurrentString();
|
||||
|
||||
Sprite * getSprite();
|
||||
Sprite * createNewSpriteFromLetterDefinition(FontLetterDefinition &theDefinition, Texture2D *theTexture);
|
||||
Sprite * updateSpriteWithLetterDefinition(Sprite *spriteToUpdate, FontLetterDefinition &theDefinition, Texture2D *theTexture);
|
||||
Sprite * getSpriteForLetter(unsigned short int newLetter);
|
||||
Sprite * updateSpriteForLetter(Sprite *spriteToUpdate, unsigned short int newLetter);
|
||||
|
||||
Array _spriteArray;
|
||||
Array _spriteArrayCache;
|
||||
float _commonLineHeight;
|
||||
bool _lineBreakWithoutSpaces;
|
||||
float _width;
|
||||
TextHAlignment _alignment;
|
||||
unsigned short int * _currentUTF8String;
|
||||
unsigned short int * _originalUTF8String;
|
||||
Size * _advances;
|
||||
FontAtlas * _fontAtlas;
|
||||
Color3B _displayedColor;
|
||||
Color3B _realColor;
|
||||
bool _cascadeColorEnabled;
|
||||
|
||||
};
|
||||
|
||||
NS_CC_END
|
||||
|
||||
#endif
|
||||
|
||||
|
|
@ -0,0 +1,475 @@
|
|||
/****************************************************************************
|
||||
Copyright (c) 2013 Zynga 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.
|
||||
****************************************************************************/
|
||||
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
|
||||
#include "cocos2d.h"
|
||||
#include "CCTextImage.h"
|
||||
#include "CCFontFreeType.h"
|
||||
#include "CCFontRenderFreeType.h"
|
||||
|
||||
NS_CC_BEGIN
|
||||
|
||||
|
||||
TextLineDef::TextLineDef(float x, float y, float width, float height) :_x(x), _y(y), _width(width), _height(height)
|
||||
{
|
||||
}
|
||||
|
||||
TextPageDef::TextPageDef(int pageNum, int width, int height): _pageNum(pageNum),
|
||||
_width(width),
|
||||
_height(height),
|
||||
_pageData(0),
|
||||
_pageTexture(0)
|
||||
{
|
||||
}
|
||||
|
||||
TextPageDef::~TextPageDef()
|
||||
{
|
||||
int numLines = _lines.size();
|
||||
|
||||
for( int c = 0; c<numLines; ++c )
|
||||
{
|
||||
delete _lines[c];
|
||||
}
|
||||
|
||||
_lines.clear();
|
||||
|
||||
if (_pageData)
|
||||
{
|
||||
delete [] _pageData;
|
||||
}
|
||||
|
||||
if (_pageTexture)
|
||||
{
|
||||
_pageTexture->release();
|
||||
}
|
||||
}
|
||||
|
||||
bool TextPageDef::generatePageTexture(bool releasePageData)
|
||||
{
|
||||
if (!_pageData)
|
||||
return false;
|
||||
|
||||
if (_pageTexture)
|
||||
{
|
||||
_pageTexture->release();
|
||||
_pageTexture = 0;
|
||||
}
|
||||
|
||||
Size imageSize = Size((float)(_width), (float)(_height));
|
||||
if( (imageSize.width <=0) || (imageSize.height<=0) )
|
||||
return false;
|
||||
|
||||
_pageTexture = new Texture2D();
|
||||
if (!_pageTexture)
|
||||
return false;
|
||||
|
||||
int dataLenght = (_width * _height * 4);
|
||||
bool textureCreated = _pageTexture->initWithData(_pageData, dataLenght, Texture2D::PixelFormat::RGBA8888, _width, _height, imageSize);
|
||||
|
||||
// _pageTexture->setPremultipliedAlpha(true);
|
||||
|
||||
// release the page data if requested
|
||||
if ( releasePageData && textureCreated )
|
||||
{
|
||||
delete [] _pageData;
|
||||
_pageData = 0;
|
||||
}
|
||||
|
||||
return textureCreated;
|
||||
}
|
||||
|
||||
void TextPageDef::preparePageTexture(bool releaseRAWData)
|
||||
{
|
||||
generatePageTexture(releaseRAWData);
|
||||
}
|
||||
|
||||
Texture2D *TextPageDef::getPageTexture()
|
||||
{
|
||||
if (!_pageTexture)
|
||||
{
|
||||
generatePageTexture();
|
||||
}
|
||||
|
||||
return _pageTexture;
|
||||
}
|
||||
|
||||
TextFontPagesDef::TextFontPagesDef()
|
||||
{
|
||||
}
|
||||
|
||||
TextFontPagesDef::~TextFontPagesDef()
|
||||
{
|
||||
int numPages = _pages.size();
|
||||
for( int c = 0; c<numPages; ++c )
|
||||
{
|
||||
if (_pages[c])
|
||||
delete _pages[c];
|
||||
}
|
||||
}
|
||||
|
||||
TextImage::TextImage(): _font(0), _fontRender(0), _fontPages(0)
|
||||
{
|
||||
}
|
||||
|
||||
TextImage::~TextImage()
|
||||
{
|
||||
if (_fontPages)
|
||||
delete _fontPages;
|
||||
|
||||
if (_font)
|
||||
_font->release();
|
||||
|
||||
if (_fontRender)
|
||||
delete _fontRender;
|
||||
}
|
||||
|
||||
bool TextImage::initWithString(const char * pText, int nWidth, int nHeight, const char * pFontName, int nSize, bool releaseRAWData)
|
||||
{
|
||||
// carloX
|
||||
bool textIsUTF16 = false;
|
||||
|
||||
// create the reference to the font we want to use
|
||||
if ( !createFontRef(pFontName, nSize) )
|
||||
return false;
|
||||
|
||||
// generate the glyphs for the requested text (glyphs are latter's bounding boxes)
|
||||
if ( !generateTextGlyphs(pText) )
|
||||
return false;
|
||||
|
||||
Size constrainSize;
|
||||
unsigned short int *strUTF16 = 0;
|
||||
int stringNumChars;
|
||||
|
||||
if ( textIsUTF16 )
|
||||
{
|
||||
strUTF16 = (unsigned short int *)pText;
|
||||
stringNumChars = cc_wcslen(strUTF16);
|
||||
}
|
||||
else
|
||||
{
|
||||
// string needs to go to unicode
|
||||
strUTF16 = _font->getUTF16Text(pText, stringNumChars);
|
||||
}
|
||||
|
||||
if (!strUTF16 || !stringNumChars)
|
||||
return false;
|
||||
|
||||
// create all the needed pages
|
||||
if (!createPageDefinitions(strUTF16, nWidth, nHeight, _font->getFontMaxHeight()))
|
||||
return false;
|
||||
|
||||
// release the original string if needed
|
||||
if ( !textIsUTF16 )
|
||||
delete [] strUTF16;
|
||||
|
||||
// actually create the needed images
|
||||
return createImageDataFromPages(_fontPages, releaseRAWData);
|
||||
}
|
||||
|
||||
bool TextImage::createPageDefinitions(unsigned short int *inText, int imageWidth, int imageHeight, int lineHeight)
|
||||
{
|
||||
bool needToReleaseText = false;
|
||||
int delta = 0;
|
||||
int currentPage = 0;
|
||||
float currentY = 0.0;
|
||||
|
||||
//
|
||||
unsigned short int *strUTF16 = inText;
|
||||
|
||||
if (_fontPages)
|
||||
delete _fontPages;
|
||||
|
||||
// create pages for the font
|
||||
_fontPages = new TextFontPagesDef();
|
||||
if (!_fontPages)
|
||||
return false;
|
||||
|
||||
// create the first page (ther is going to be at least one page)
|
||||
TextPageDef *currentPageDef = new TextPageDef(currentPage, imageWidth, imageHeight);
|
||||
if ( !currentPageDef )
|
||||
return false;
|
||||
|
||||
// add the current page
|
||||
_fontPages->addPage(currentPageDef);
|
||||
|
||||
// work out creating pages
|
||||
|
||||
do {
|
||||
|
||||
// choose texture page
|
||||
if ( ( currentY + lineHeight ) > imageHeight )
|
||||
{
|
||||
currentY = 0;
|
||||
currentPage += 1;
|
||||
|
||||
// create a new page and add
|
||||
currentPageDef = new TextPageDef(currentPage, imageWidth, imageHeight);
|
||||
if ( !currentPageDef )
|
||||
return false;
|
||||
|
||||
_fontPages->addPage(currentPageDef);
|
||||
}
|
||||
|
||||
// get the new fitting string
|
||||
Size tempSize;
|
||||
tempSize.width = imageWidth;
|
||||
tempSize.height = imageHeight;
|
||||
|
||||
// figure out how many glyphs fit in this line
|
||||
int newLineSize = 0;
|
||||
int numFittingChar = getNumGlyphsFittingInSize(_textGlyphs, strUTF16, _font, &tempSize, newLineSize);
|
||||
|
||||
// crete the temporary new string
|
||||
unsigned short int *pTempString = 0;
|
||||
pTempString = _font->trimUTF16Text(strUTF16, 0, (numFittingChar - 1));
|
||||
|
||||
// create the new line and add to the current page
|
||||
TextLineDef *newLine = new TextLineDef(0.0, currentY, newLineSize, lineHeight);
|
||||
if ( !newLine )
|
||||
return false;
|
||||
|
||||
// add all the glyphs to this line
|
||||
addGlyphsToLine(newLine, (const char *)pTempString, true);
|
||||
|
||||
// add the line the to current page
|
||||
currentPageDef->addLine(newLine);
|
||||
|
||||
// can now release the string
|
||||
delete [] pTempString;
|
||||
|
||||
// create the new string
|
||||
int stringLenght = _font->getUTF16TextLenght(strUTF16);
|
||||
delta = (stringLenght - numFittingChar);
|
||||
|
||||
// there is still some leftover, need to work on it
|
||||
if ( delta )
|
||||
{
|
||||
// create the new string
|
||||
unsigned short int *tempS = _font->trimUTF16Text(strUTF16, numFittingChar, (stringLenght - 1));
|
||||
|
||||
if (needToReleaseText)
|
||||
delete [] strUTF16;
|
||||
|
||||
// a copy of the string has been created, so next time I'll need to release it
|
||||
needToReleaseText = true;
|
||||
|
||||
// assign pointer
|
||||
strUTF16 = tempS;
|
||||
}
|
||||
|
||||
// go to next line
|
||||
currentY += lineHeight;
|
||||
|
||||
} while( delta );
|
||||
|
||||
if (needToReleaseText)
|
||||
delete [] strUTF16;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
int TextImage::getNumGlyphsFittingInSize(std::map<unsigned short int, GlyphDef> &glyphDefs, unsigned short int *strUTF8, Font *pFont, Size *constrainSize, int &outNewSize)
|
||||
{
|
||||
if (!strUTF8)
|
||||
return 0;
|
||||
|
||||
float widthWithBBX = 0.0f;
|
||||
float lastWidth = 0.0f;
|
||||
|
||||
// get the string to UTF8
|
||||
int numChar = cc_wcslen(strUTF8);
|
||||
|
||||
for (int c = 0; c<numChar; ++c)
|
||||
{
|
||||
widthWithBBX += (glyphDefs[strUTF8[c]].getRect().size.width + glyphDefs[strUTF8[c]].getPadding());
|
||||
|
||||
if (widthWithBBX >= constrainSize->width)
|
||||
{
|
||||
outNewSize = lastWidth;
|
||||
return c;
|
||||
}
|
||||
|
||||
lastWidth = widthWithBBX;
|
||||
}
|
||||
|
||||
outNewSize = constrainSize->width;
|
||||
return numChar;
|
||||
}
|
||||
|
||||
bool TextImage::createFontRef(const char *fontName, int fontSize)
|
||||
{
|
||||
if (_font)
|
||||
{
|
||||
_font->release();
|
||||
_font = 0;
|
||||
}
|
||||
|
||||
// carloX
|
||||
_font = new FontFreeType();
|
||||
|
||||
if (!_font)
|
||||
return false;
|
||||
|
||||
_font->retain();
|
||||
|
||||
if( !_font->createFontObject(fontName, fontSize))
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool TextImage::createFontRender()
|
||||
{
|
||||
if (!_font)
|
||||
return false;
|
||||
|
||||
if (_fontRender)
|
||||
{
|
||||
delete _fontRender;
|
||||
_fontRender = 0;
|
||||
}
|
||||
|
||||
// carloX
|
||||
_fontRender = new FontRenderFreeType(_font);
|
||||
|
||||
if (!_fontRender)
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool TextImage::addGlyphsToLine(TextLineDef *line, const char *lineText, bool textIsUTF16)
|
||||
{
|
||||
if (!_font)
|
||||
return false;
|
||||
|
||||
int numLetters = 0;
|
||||
unsigned short int *UTF16string = 0;
|
||||
|
||||
if (textIsUTF16)
|
||||
{
|
||||
UTF16string = (unsigned short int *) lineText;
|
||||
numLetters = cc_wcslen(UTF16string);
|
||||
}
|
||||
else
|
||||
{
|
||||
UTF16string = _font->getUTF16Text(lineText, numLetters);
|
||||
}
|
||||
|
||||
for (int c=0; c<numLetters; ++c)
|
||||
{
|
||||
_textGlyphs[UTF16string[c]].setCommonHeight(line->getHeight());
|
||||
line->addGlyph(_textGlyphs[UTF16string[c]] );
|
||||
}
|
||||
|
||||
if(!textIsUTF16)
|
||||
delete [] UTF16string;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool TextImage::generateTextGlyphs(const char * pText)
|
||||
{
|
||||
if (!_font)
|
||||
return false;
|
||||
|
||||
int numGlyphs = 0;
|
||||
GlyphDef *pNewGlyphs = _font->getGlyphDefintionsForText(pText, numGlyphs);
|
||||
|
||||
if (!pNewGlyphs)
|
||||
return false;
|
||||
|
||||
if (!_textGlyphs.empty())
|
||||
_textGlyphs.clear();
|
||||
|
||||
for (int c=0; c < numGlyphs; ++c)
|
||||
_textGlyphs[pNewGlyphs[c].getUTF8Letter()] = pNewGlyphs[c];
|
||||
|
||||
delete [] pNewGlyphs;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool TextImage::createImageDataFromPages(TextFontPagesDef *thePages, bool releaseRAWData)
|
||||
{
|
||||
int numPages = thePages->getNumPages();
|
||||
if (!numPages)
|
||||
return false;
|
||||
|
||||
for (int c = 0; c < numPages; ++c)
|
||||
{
|
||||
unsigned char *pPageData = 0;
|
||||
pPageData = preparePageGlyphData(thePages->getPageAt(c));
|
||||
|
||||
if (pPageData)
|
||||
{
|
||||
// set the page data
|
||||
thePages->getPageAt(c)->setPageData(pPageData);
|
||||
|
||||
// crete page texture and relase RAW data
|
||||
thePages->getPageAt(c)->preparePageTexture(releaseRAWData);
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
unsigned char * TextImage::preparePageGlyphData(TextPageDef *thePage)
|
||||
{
|
||||
if ( !_fontRender )
|
||||
{
|
||||
createFontRender();
|
||||
}
|
||||
|
||||
if (_fontRender)
|
||||
{
|
||||
return _fontRender->preparePageGlyphData(thePage);
|
||||
}
|
||||
else
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
NS_CC_END
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
|
@ -0,0 +1,191 @@
|
|||
/****************************************************************************
|
||||
Copyright (c) 2013 Zynga 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.
|
||||
****************************************************************************/
|
||||
|
||||
#ifndef _TextImage_h_
|
||||
#define _TextImage_h_
|
||||
|
||||
#include "CCFontRender.h"
|
||||
#include "CCFont.h"
|
||||
|
||||
NS_CC_BEGIN
|
||||
|
||||
/** @brief GlyphDef defines one single glyph (character) in a text image
|
||||
*
|
||||
* it defines the bounding box for the glyph in the texture page, the character the padding (spacing) between characters
|
||||
*
|
||||
*/
|
||||
|
||||
class CC_DLL GlyphDef
|
||||
{
|
||||
public:
|
||||
|
||||
GlyphDef() : _validGlyph(false) { /*do nothing*/ }
|
||||
GlyphDef(unsigned short int letterUTF8, Rect &rect) { _gliphRect = rect; _uTF16Letter = letterUTF8; }
|
||||
|
||||
void setUTF16Letter(unsigned short int letterUTF8) { _uTF16Letter = letterUTF8; }
|
||||
void setRect(Rect & theRect) { _gliphRect = theRect; }
|
||||
unsigned short int getUTF8Letter() { return _uTF16Letter; }
|
||||
Rect & getRect() { return _gliphRect; }
|
||||
void setPadding(float padding) { _padding = padding; }
|
||||
float getPadding() { return _padding; }
|
||||
void setCommonHeight(float commonHeight) { _commonHeight = commonHeight; }
|
||||
float getCommonHeight() { return _commonHeight; }
|
||||
void setValid(bool isValid) { _validGlyph = isValid; }
|
||||
bool isValid() { return _validGlyph; }
|
||||
|
||||
private:
|
||||
|
||||
Rect _gliphRect;
|
||||
unsigned short int _uTF16Letter;
|
||||
float _padding;
|
||||
float _commonHeight;
|
||||
bool _validGlyph;
|
||||
|
||||
};
|
||||
|
||||
/** @brief TextLineDef define a line of text in a text image texture page
|
||||
*
|
||||
* conllects all the GlyphDef for a text line plus line size and line position in text image space
|
||||
*
|
||||
*/
|
||||
class CC_DLL TextLineDef
|
||||
{
|
||||
public:
|
||||
|
||||
TextLineDef(float x, float y, float width, float height);
|
||||
|
||||
float getX() { return _x; }
|
||||
float getY() { return _y; }
|
||||
float getWidth() { return _width; }
|
||||
float getHeight() { return _height; }
|
||||
|
||||
void addGlyph(GlyphDef theGlyph) { _glyphs.push_back(theGlyph); }
|
||||
int getNumGlyph() { return _glyphs.size(); }
|
||||
GlyphDef & getGlyphAt(int index) { return _glyphs[index]; }
|
||||
|
||||
private:
|
||||
|
||||
float _x;
|
||||
float _y;
|
||||
float _width;
|
||||
float _height;
|
||||
std::vector<GlyphDef> _glyphs;
|
||||
|
||||
};
|
||||
|
||||
/** @brief TextPageDef defines one text image page (a TextImage can have/use more than one page)
|
||||
*
|
||||
* collects all the TextLineDef for one page, the witdh and height of the page and the graphics (texture) for the page
|
||||
*
|
||||
*/
|
||||
class CC_DLL TextPageDef
|
||||
{
|
||||
public:
|
||||
|
||||
TextPageDef(int pageNum, int width, int height);
|
||||
~TextPageDef();
|
||||
|
||||
void addLine(TextLineDef *theLine) { _lines.push_back(theLine); }
|
||||
int getNumLines() { return _lines.size(); }
|
||||
TextLineDef * getLineAt(int index) { return _lines[index]; }
|
||||
int getWidth() { return _width; }
|
||||
int getHeight() { return _height; }
|
||||
int getPageNumber() { return _pageNum; }
|
||||
void setPageData(unsigned char *pData) { _pageData = pData; }
|
||||
unsigned char * getPageData() { return _pageData; }
|
||||
Texture2D *getPageTexture();
|
||||
void preparePageTexture(bool releaseRAWData = true);
|
||||
|
||||
private:
|
||||
|
||||
bool generatePageTexture(bool releasePageData = false);
|
||||
|
||||
int _pageNum;
|
||||
int _width;
|
||||
int _height;
|
||||
unsigned char * _pageData;
|
||||
Texture2D * _pageTexture;
|
||||
std::vector<TextLineDef *> _lines;
|
||||
|
||||
};
|
||||
|
||||
/** @brief CCTextFontPages collection of pages (TextPageDef)
|
||||
*
|
||||
* A TextImage is composed by one or more text pages. This calss collects all of those pages
|
||||
*/
|
||||
class CC_DLL TextFontPagesDef
|
||||
{
|
||||
public:
|
||||
|
||||
TextFontPagesDef();
|
||||
~TextFontPagesDef();
|
||||
|
||||
void addPage(TextPageDef *newPage) { _pages.push_back(newPage); }
|
||||
int getNumPages() { return _pages.size(); }
|
||||
TextPageDef* getPageAt(int index) { return _pages[index]; }
|
||||
|
||||
private:
|
||||
|
||||
std::vector<TextPageDef *> _pages;
|
||||
|
||||
};
|
||||
|
||||
/** @brief TextImage
|
||||
*
|
||||
*/
|
||||
class CC_DLL TextImage
|
||||
{
|
||||
public:
|
||||
|
||||
TextImage();
|
||||
~TextImage();
|
||||
|
||||
bool initWithString(const char *pText, int nWidth, int nHeight, const char * pFontName, int nSize, bool releaseRAWData = true);
|
||||
TextFontPagesDef * getPages() { return _fontPages; }
|
||||
Font * getFont() { return _font; }
|
||||
|
||||
private:
|
||||
|
||||
unsigned char * preparePageGlyphData(TextPageDef *thePage);
|
||||
bool createImageDataFromPages(TextFontPagesDef *thePages, bool releaseRAWData = true);
|
||||
bool createFontRender();
|
||||
bool addGlyphsToLine(TextLineDef *line, const char *lineText, bool textIsUTF16 = false);
|
||||
bool createFontRef(const char *fontName, int size);
|
||||
bool generateTextGlyphs(const char * pText);
|
||||
int getNumGlyphsFittingInSize(std::map<unsigned short int, GlyphDef> &glyphDefs, unsigned short int *strUTF8, Font *pFont, Size *constrainSize, int &outNewSize);
|
||||
bool createPageDefinitions(unsigned short int *inText, int imageWidth, int imageHeight, int lineHeight);
|
||||
|
||||
std::map<unsigned short int, GlyphDef> _textGlyphs;
|
||||
TextFontPagesDef * _fontPages;
|
||||
Font * _font;
|
||||
FontRender * _fontRender;
|
||||
|
||||
|
||||
};
|
||||
|
||||
|
||||
NS_CC_END
|
||||
|
||||
|
||||
#endif
|
|
@ -596,9 +596,11 @@ void ParticleSystemQuad::setBatchNode(ParticleBatchNode * batchNode)
|
|||
CC_SAFE_FREE(_indices);
|
||||
|
||||
glDeleteBuffers(2, &_buffersVBO[0]);
|
||||
memset(_buffersVBO, 0, sizeof(_buffersVBO));
|
||||
#if CC_TEXTURE_ATLAS_USE_VAO
|
||||
glDeleteVertexArrays(1, &_VAOname);
|
||||
GL::bindVAO(0);
|
||||
_VAOname = 0;
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
|
|
@ -42,11 +42,12 @@ NS_CC_BEGIN
|
|||
* @addtogroup platform
|
||||
* @{
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
@brief Structure which can tell where mipmap begins and how long is it
|
||||
*/
|
||||
typedef struct _MipmapInfo {
|
||||
@brief Structure which can tell where mipmap begins and how long is it
|
||||
*/
|
||||
typedef struct _MipmapInfo
|
||||
{
|
||||
unsigned char* address;
|
||||
int len;
|
||||
}MipmapInfo;
|
||||
|
@ -58,14 +59,6 @@ public:
|
|||
|
||||
Image();
|
||||
virtual ~Image();
|
||||
|
||||
/**
|
||||
@brief Determine how many mipmaps can we have.
|
||||
Its same as define but it respects namespaces
|
||||
*/
|
||||
enum {
|
||||
CC_MIPMAP_MAX = 16,
|
||||
};
|
||||
|
||||
/** Supported formats for Image */
|
||||
enum class Format
|
||||
|
@ -114,10 +107,10 @@ public:
|
|||
@param dataLen data length expressed in (number of) bytes.
|
||||
@return true if loaded correctly.
|
||||
*/
|
||||
bool initWithImageData(void * data, int dataLen);
|
||||
bool initWithImageData(const void * data, int dataLen);
|
||||
|
||||
// @warning kFmtRawData only support RGBA8888
|
||||
bool initWithRawData(void *data, int dataLen, int nWidth, int nHeight, int nBitsPerComponent = 8, bool bPreMulti = false);
|
||||
bool initWithRawData(const void * data, int dataLen, int width, int height, int bitsPerComponent, bool preMulti = false);
|
||||
|
||||
/**
|
||||
@brief Create image with specified string.
|
||||
|
@ -189,22 +182,24 @@ public:
|
|||
bool saveToFile(const char *filePath, bool isToRGB = true);
|
||||
|
||||
protected:
|
||||
bool initWithJpgData(void *data, int dataLen);
|
||||
bool initWithPngData(void *data, int dataLen);
|
||||
bool initWithTiffData(void *data, int dataLen);
|
||||
bool initWithWebpData(void *data, int dataLen);
|
||||
bool initWithPVRData(void *data, int dataLen);
|
||||
bool initWithPVRv2Data(void *data, int dataLen);
|
||||
bool initWithPVRv3Data(void *data, int dataLen);
|
||||
bool initWithETCData(void *data, int dataLen);
|
||||
|
||||
bool saveImageToPNG(const char *pszFilePath, bool bIsToRGB = true);
|
||||
bool saveImageToJPG(const char *pszFilePath);
|
||||
|
||||
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
|
||||
bool iosSaveToFile(const char *pszFilePath, bool bIsToRGB = true);
|
||||
#endif
|
||||
bool initWithJpgData(const void *data, int dataLen);
|
||||
bool initWithPngData(const void *data, int dataLen);
|
||||
bool initWithTiffData(const void *data, int dataLen);
|
||||
bool initWithWebpData(const void *data, int dataLen);
|
||||
bool initWithPVRData(const void *data, int dataLen);
|
||||
bool initWithPVRv2Data(const void *data, int dataLen);
|
||||
bool initWithPVRv3Data(const void *data, int dataLen);
|
||||
bool initWithETCData(const void *data, int dataLen);
|
||||
|
||||
bool saveImageToPNG(const char *filePath, bool isToRGB = true);
|
||||
bool saveImageToJPG(const char *filePath);
|
||||
|
||||
private:
|
||||
/**
|
||||
@brief Determine how many mipmaps can we have.
|
||||
Its same as define but it respects namespaces
|
||||
*/
|
||||
static const int MIPMAP_MAX = 16;
|
||||
unsigned char *_data;
|
||||
int _dataLen;
|
||||
int _width;
|
||||
|
@ -212,7 +207,7 @@ protected:
|
|||
Format _fileType;
|
||||
Texture2D::PixelFormat _renderFormat;
|
||||
bool _preMulti;
|
||||
MipmapInfo _mipmaps[CC_MIPMAP_MAX]; // pointer to mipmap images
|
||||
MipmapInfo _mipmaps[MIPMAP_MAX]; // pointer to mipmap images
|
||||
int _numberOfMipmaps;
|
||||
// false if we cann't auto detect the image is premultiplied or not.
|
||||
bool _hasPremultipliedAlpha;
|
||||
|
@ -232,15 +227,13 @@ private:
|
|||
*/
|
||||
bool initWithImageFileThreadSafe(const char *fullpath);
|
||||
|
||||
Format detectFormat(void* data, int dataLen);
|
||||
bool isPng(void *data, int dataLen);
|
||||
bool isJpg(void *data, int dataLen);
|
||||
bool isTiff(void *data, int dataLen);
|
||||
bool isWebp(void *data, int dataLen);
|
||||
bool isPvr(void *data, int dataLen);
|
||||
bool isEtc(void *data, int dataLen);
|
||||
|
||||
bool testFormatForPvrTCSupport(uint64_t format);
|
||||
Format detectFormat(const void* data, int dataLen);
|
||||
bool isPng(const void *data, int dataLen);
|
||||
bool isJpg(const void *data, int dataLen);
|
||||
bool isTiff(const void *data, int dataLen);
|
||||
bool isWebp(const void *data, int dataLen);
|
||||
bool isPvr(const void *data, int dataLen);
|
||||
bool isEtc(const void *data, int dataLen);
|
||||
};
|
||||
|
||||
// end of platform group
|
||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -31,7 +31,9 @@ NS_CC_BEGIN
|
|||
|
||||
Thread::~Thread()
|
||||
{
|
||||
|
||||
// To prevent warning: private field '_autoreasePool' is not
|
||||
// used [-Wunused-private-field] by CLANG.
|
||||
_autoReleasePool = nullptr;
|
||||
}
|
||||
|
||||
void Thread::createAutoreleasePool()
|
||||
|
@ -41,4 +43,4 @@ void Thread::createAutoreleasePool()
|
|||
|
||||
NS_CC_END
|
||||
|
||||
#endif
|
||||
#endif
|
||||
|
|
|
@ -38,16 +38,17 @@ NS_CC_BEGIN
|
|||
/* On iOS, should create autorelease pool when create a new thread
|
||||
* and release it when the thread end.
|
||||
*/
|
||||
|
||||
class CC_DLL Thread
|
||||
{
|
||||
public:
|
||||
Thread() : _autoreasePool(0) {}
|
||||
Thread() : _autoReleasePool(nullptr) {}
|
||||
~Thread();
|
||||
|
||||
void createAutoreleasePool();
|
||||
|
||||
private:
|
||||
void *_autoreasePool;
|
||||
void *_autoReleasePool;
|
||||
};
|
||||
|
||||
// end of platform group
|
||||
|
|
|
@ -0,0 +1,57 @@
|
|||
LOCAL_PATH := $(call my-dir)
|
||||
|
||||
include $(CLEAR_VARS)
|
||||
|
||||
LOCAL_MODULE := cocos2dxandroid_static
|
||||
|
||||
LOCAL_MODULE_FILENAME := libcocos2dandroid
|
||||
|
||||
LOCAL_SRC_FILES := \
|
||||
CCDevice.cpp \
|
||||
CCEGLView.cpp \
|
||||
CCAccelerometer.cpp \
|
||||
CCApplication.cpp \
|
||||
CCCommon.cpp \
|
||||
CCFileUtilsAndroid.cpp \
|
||||
CCImage.cpp \
|
||||
nativeactivity.cpp \
|
||||
jni/Java_org_cocos2dx_lib_Cocos2dxBitmap.cpp \
|
||||
jni/Java_org_cocos2dx_lib_Cocos2dxHelper.cpp \
|
||||
jni/Java_org_cocos2dx_lib_Cocos2dxAccelerometer.cpp \
|
||||
jni/JniHelper.cpp \
|
||||
jni/IMEJni.cpp \
|
||||
jni/TouchesJni.cpp \
|
||||
jni/DPIJni.cpp
|
||||
|
||||
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)
|
||||
|
||||
LOCAL_C_INCLUDES := $(LOCAL_PATH) \
|
||||
$(LOCAL_PATH)/../.. \
|
||||
$(LOCAL_PATH)/../../include \
|
||||
$(LOCAL_PATH)/../../kazmath/include \
|
||||
$(LOCAL_PATH)/../../platform/third_party/common/etc
|
||||
|
||||
LOCAL_LDLIBS := -lGLESv1_CM \
|
||||
-lGLESv2 \
|
||||
-lEGL \
|
||||
-llog \
|
||||
-lz \
|
||||
-landroid
|
||||
|
||||
LOCAL_EXPORT_LDLIBS := -lGLESv1_CM \
|
||||
-lGLESv2 \
|
||||
-lEGL \
|
||||
-llog \
|
||||
-lz \
|
||||
-landroid
|
||||
|
||||
LOCAL_WHOLE_STATIC_LIBRARIES := android_native_app_glue cocos_libpng_static cocos_jpeg_static cocos_libxml2_static cocos_libtiff_static cocos_libwebp_static
|
||||
|
||||
|
||||
include $(BUILD_STATIC_LIBRARY)
|
||||
|
||||
$(call import-module,libjpeg)
|
||||
$(call import-module,libpng)
|
||||
$(call import-module,libtiff)
|
||||
$(call import-module,libwebp)
|
||||
$(call import-module,android/native_app_glue)
|
|
@ -22,7 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#include "CCAccelerometer.h"
|
||||
#include "jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h"
|
||||
#include "nativeactivity.h"
|
||||
#include <stdio.h>
|
||||
#include <android/log.h>
|
||||
|
||||
|
@ -45,19 +45,17 @@ namespace cocos2d
|
|||
{
|
||||
_function = function;
|
||||
|
||||
if (_function)
|
||||
{
|
||||
enableAccelerometerJNI();
|
||||
if (_function) {
|
||||
enableAccelerometer();
|
||||
}
|
||||
else
|
||||
{
|
||||
disableAccelerometerJNI();
|
||||
else {
|
||||
disableAccelerometer();
|
||||
}
|
||||
}
|
||||
|
||||
void Accelerometer::setAccelerometerInterval(float interval)
|
||||
{
|
||||
setAccelerometerIntervalJNI(interval);
|
||||
setAccelerometerInterval(interval);
|
||||
}
|
||||
|
||||
|
||||
|
|
|
@ -40,16 +40,7 @@ int Application::run()
|
|||
|
||||
void Application::setAnimationInterval(double interval)
|
||||
{
|
||||
JniMethodInfo methodInfo;
|
||||
if (! JniHelper::getStaticMethodInfo(methodInfo, "org/cocos2dx/lib/Cocos2dxRenderer", "setAnimationInterval",
|
||||
"(D)V"))
|
||||
{
|
||||
CCLOG("%s %d: error to get methodInfo", __FILE__, __LINE__);
|
||||
}
|
||||
else
|
||||
{
|
||||
methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, interval);
|
||||
}
|
||||
// NYI
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
|
|
@ -6,8 +6,6 @@
|
|||
|
||||
NS_CC_BEGIN
|
||||
|
||||
class Rect;
|
||||
|
||||
class CC_DLL Application : public ApplicationProtocol
|
||||
{
|
||||
public:
|
||||
|
|
|
@ -34,26 +34,19 @@ THE SOFTWARE.
|
|||
|
||||
using namespace std;
|
||||
|
||||
static AAssetManager* s_assetmanager;
|
||||
|
||||
extern "C" {
|
||||
JNIEXPORT void JNICALL
|
||||
Java_org_cocos2dx_lib_Cocos2dxHelper_nativeSetAssetManager(JNIEnv* env,
|
||||
jobject thiz,
|
||||
jobject java_assetmanager) {
|
||||
AAssetManager* assetmanager =
|
||||
AAssetManager_fromJava(env, java_assetmanager);
|
||||
if (NULL == assetmanager) {
|
||||
LOGD("assetmanager : is NULL");
|
||||
return;
|
||||
}
|
||||
|
||||
s_assetmanager = assetmanager;
|
||||
}
|
||||
}
|
||||
AAssetManager* cocos2d::FileUtilsAndroid::assetmanager = NULL;
|
||||
|
||||
NS_CC_BEGIN
|
||||
|
||||
void FileUtilsAndroid::setassetmanager(AAssetManager* a) {
|
||||
if (NULL == a) {
|
||||
LOGD("setassetmanager : received unexpected NULL parameter");
|
||||
return;
|
||||
}
|
||||
|
||||
cocos2d::FileUtilsAndroid::assetmanager = a;
|
||||
}
|
||||
|
||||
FileUtils* FileUtils::getInstance()
|
||||
{
|
||||
if (s_sharedFileUtils == NULL)
|
||||
|
@ -100,8 +93,8 @@ bool FileUtilsAndroid::isFileExist(const std::string& strFilePath)
|
|||
// Found "assets/" at the beginning of the path and we don't want it
|
||||
if (strFilePath.find(_defaultResRootPath) == 0) s += strlen("assets/");
|
||||
|
||||
if (s_assetmanager) {
|
||||
AAsset* aa = AAssetManager_open(s_assetmanager, s, AASSET_MODE_UNKNOWN);
|
||||
if (FileUtilsAndroid::assetmanager) {
|
||||
AAsset* aa = AAssetManager_open(FileUtilsAndroid::assetmanager, s, AASSET_MODE_UNKNOWN);
|
||||
if (aa)
|
||||
{
|
||||
bFound = true;
|
||||
|
@ -161,30 +154,38 @@ unsigned char* FileUtilsAndroid::doGetFileData(const char* filename, const char*
|
|||
if (fullPath[0] != '/')
|
||||
{
|
||||
|
||||
string fullPath(filename);
|
||||
// fullPathForFilename is not thread safe.
|
||||
if (! forAsync)
|
||||
{
|
||||
fullPath = fullPathForFilename(filename);
|
||||
if (forAsync) {
|
||||
LOGD("Async loading not supported. fullPathForFilename is not thread safe.");
|
||||
return NULL;
|
||||
}
|
||||
|
||||
const char* relativepath = fullPath.c_str();
|
||||
string fullPath = fullPathForFilename(filename);
|
||||
LOGD("full path = %s", fullPath.c_str());
|
||||
|
||||
// "assets/" is at the beginning of the path and we don't want it
|
||||
relativepath += strlen("assets/");
|
||||
string relativePath = string();
|
||||
|
||||
if (NULL == s_assetmanager) {
|
||||
LOGD("... s_assetmanager is NULL");
|
||||
size_t position = fullPath.find("assets/");
|
||||
if (0 == position) {
|
||||
// "assets/" is at the beginning of the path and we don't want it
|
||||
relativePath += fullPath.substr(strlen("assets/"));
|
||||
} else {
|
||||
relativePath += fullPath;
|
||||
}
|
||||
LOGD("relative path = %s", relativePath.c_str());
|
||||
|
||||
if (NULL == FileUtilsAndroid::assetmanager) {
|
||||
LOGD("... FileUtilsAndroid::assetmanager is NULL");
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// read asset data
|
||||
AAsset* asset =
|
||||
AAssetManager_open(s_assetmanager,
|
||||
relativepath,
|
||||
AAssetManager_open(FileUtilsAndroid::assetmanager,
|
||||
relativePath.c_str(),
|
||||
AASSET_MODE_UNKNOWN);
|
||||
if (NULL == asset) {
|
||||
LOGD("asset : is NULL");
|
||||
LOGD("asset is NULL");
|
||||
return NULL;
|
||||
}
|
||||
|
||||
|
|
|
@ -33,10 +33,6 @@
|
|||
#include "jni.h"
|
||||
#include "android/asset_manager.h"
|
||||
|
||||
extern "C" {
|
||||
JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxHelper_nativeSetAssetManager(JNIEnv* env, jobject thiz, jobject java_assetmanager);
|
||||
}
|
||||
|
||||
NS_CC_BEGIN
|
||||
|
||||
/**
|
||||
|
@ -52,6 +48,8 @@ class CC_DLL FileUtilsAndroid : public FileUtils
|
|||
public:
|
||||
virtual ~FileUtilsAndroid();
|
||||
|
||||
static void setassetmanager(AAssetManager* a);
|
||||
|
||||
/* override funtions */
|
||||
bool init();
|
||||
virtual unsigned char* getFileData(const char* filename, const char* pszMode, unsigned long * pSize);
|
||||
|
@ -66,6 +64,7 @@ public:
|
|||
|
||||
private:
|
||||
unsigned char* doGetFileData(const char* filename, const char* pszMode, unsigned long * pSize, bool forAsync);
|
||||
static AAssetManager* assetmanager;
|
||||
};
|
||||
|
||||
// end of platform group
|
||||
|
|
|
@ -1,144 +0,0 @@
|
|||
/****************************************************************************
|
||||
Copyright (c) 2010-2011 cocos2d-x.org
|
||||
|
||||
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.
|
||||
****************************************************************************/
|
||||
package org.cocos2dx.lib;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.res.Configuration;
|
||||
import android.hardware.Sensor;
|
||||
import android.hardware.SensorEvent;
|
||||
import android.hardware.SensorEventListener;
|
||||
import android.hardware.SensorManager;
|
||||
import android.util.Log;
|
||||
import android.view.Display;
|
||||
import android.view.Surface;
|
||||
import android.view.WindowManager;
|
||||
import android.os.Build.*;
|
||||
|
||||
public class Cocos2dxAccelerometer implements SensorEventListener {
|
||||
// ===========================================================
|
||||
// Constants
|
||||
// ===========================================================
|
||||
|
||||
private static final String TAG = Cocos2dxAccelerometer.class.getSimpleName();
|
||||
|
||||
// ===========================================================
|
||||
// Fields
|
||||
// ===========================================================
|
||||
|
||||
private final Context mContext;
|
||||
private final SensorManager mSensorManager;
|
||||
private final Sensor mAccelerometer;
|
||||
private final int mNaturalOrientation;
|
||||
|
||||
// ===========================================================
|
||||
// Constructors
|
||||
// ===========================================================
|
||||
|
||||
public Cocos2dxAccelerometer(final Context pContext) {
|
||||
this.mContext = pContext;
|
||||
|
||||
this.mSensorManager = (SensorManager) this.mContext.getSystemService(Context.SENSOR_SERVICE);
|
||||
this.mAccelerometer = this.mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
|
||||
|
||||
final Display display = ((WindowManager) this.mContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
|
||||
this.mNaturalOrientation = display.getOrientation();
|
||||
}
|
||||
|
||||
// ===========================================================
|
||||
// Getter & Setter
|
||||
// ===========================================================
|
||||
|
||||
public void enable() {
|
||||
this.mSensorManager.registerListener(this, this.mAccelerometer, SensorManager.SENSOR_DELAY_GAME);
|
||||
}
|
||||
|
||||
public void setInterval(float interval) {
|
||||
// Honeycomb version is 11
|
||||
if(android.os.Build.VERSION.SDK_INT < 11) {
|
||||
this.mSensorManager.registerListener(this, this.mAccelerometer, SensorManager.SENSOR_DELAY_GAME);
|
||||
} else {
|
||||
//convert seconds to microseconds
|
||||
this.mSensorManager.registerListener(this, this.mAccelerometer, (int)(interval*100000));
|
||||
}
|
||||
}
|
||||
|
||||
public void disable() {
|
||||
this.mSensorManager.unregisterListener(this);
|
||||
}
|
||||
|
||||
// ===========================================================
|
||||
// Methods for/from SuperClass/Interfaces
|
||||
// ===========================================================
|
||||
|
||||
@Override
|
||||
public void onSensorChanged(final SensorEvent pSensorEvent) {
|
||||
if (pSensorEvent.sensor.getType() != Sensor.TYPE_ACCELEROMETER) {
|
||||
return;
|
||||
}
|
||||
|
||||
float x = pSensorEvent.values[0];
|
||||
float y = pSensorEvent.values[1];
|
||||
final float z = pSensorEvent.values[2];
|
||||
|
||||
/*
|
||||
* Because the axes are not swapped when the device's screen orientation
|
||||
* changes. So we should swap it here. In tablets such as Motorola Xoom,
|
||||
* the default orientation is landscape, so should consider this.
|
||||
*/
|
||||
final int orientation = this.mContext.getResources().getConfiguration().orientation;
|
||||
|
||||
if ((orientation == Configuration.ORIENTATION_LANDSCAPE) && (this.mNaturalOrientation != Surface.ROTATION_0)) {
|
||||
final float tmp = x;
|
||||
x = -y;
|
||||
y = tmp;
|
||||
} else if ((orientation == Configuration.ORIENTATION_PORTRAIT) && (this.mNaturalOrientation != Surface.ROTATION_0)) {
|
||||
final float tmp = x;
|
||||
x = y;
|
||||
y = -tmp;
|
||||
}
|
||||
|
||||
Cocos2dxGLSurfaceView.queueAccelerometer(x,y,z,pSensorEvent.timestamp);
|
||||
|
||||
/*
|
||||
if(BuildConfig.DEBUG) {
|
||||
Log.d(TAG, "x = " + pSensorEvent.values[0] + " y = " + pSensorEvent.values[1] + " z = " + pSensorEvent.values[2]);
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onAccuracyChanged(final Sensor pSensor, final int pAccuracy) {
|
||||
}
|
||||
|
||||
// ===========================================================
|
||||
// Methods
|
||||
// Native method called from Cocos2dxGLSurfaceView (To be in the same thread)
|
||||
// ===========================================================
|
||||
|
||||
public static native void onSensorChanged(final float pX, final float pY, final float pZ, final long pTimestamp);
|
||||
|
||||
// ===========================================================
|
||||
// Inner and Anonymous Classes
|
||||
// ===========================================================
|
||||
}
|
|
@ -1,171 +0,0 @@
|
|||
/****************************************************************************
|
||||
Copyright (c) 2010-2013 cocos2d-x.org
|
||||
|
||||
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.
|
||||
****************************************************************************/
|
||||
package org.cocos2dx.lib;
|
||||
|
||||
import org.cocos2dx.lib.Cocos2dxHelper.Cocos2dxHelperListener;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.content.Context;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import android.os.Message;
|
||||
import android.view.ViewGroup;
|
||||
import android.util.Log;
|
||||
import android.widget.FrameLayout;
|
||||
|
||||
public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelperListener {
|
||||
// ===========================================================
|
||||
// Constants
|
||||
// ===========================================================
|
||||
|
||||
private static final String TAG = Cocos2dxActivity.class.getSimpleName();
|
||||
|
||||
// ===========================================================
|
||||
// Fields
|
||||
// ===========================================================
|
||||
|
||||
private Cocos2dxGLSurfaceView mGLSurfaceView;
|
||||
private Cocos2dxHandler mHandler;
|
||||
private static Context sContext = null;
|
||||
|
||||
public static Context getContext() {
|
||||
return sContext;
|
||||
}
|
||||
|
||||
// ===========================================================
|
||||
// Constructors
|
||||
// ===========================================================
|
||||
|
||||
@Override
|
||||
protected void onCreate(final Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
sContext = this;
|
||||
this.mHandler = new Cocos2dxHandler(this);
|
||||
|
||||
this.init();
|
||||
|
||||
Cocos2dxHelper.init(this, this);
|
||||
}
|
||||
|
||||
// ===========================================================
|
||||
// Getter & Setter
|
||||
// ===========================================================
|
||||
|
||||
// ===========================================================
|
||||
// Methods for/from SuperClass/Interfaces
|
||||
// ===========================================================
|
||||
|
||||
@Override
|
||||
public void onWindowFocusChanged(final boolean hasWindowFocus) {
|
||||
super.onWindowFocusChanged(hasWindowFocus);
|
||||
if (hasWindowFocus) {
|
||||
Cocos2dxHelper.onResume();
|
||||
this.mGLSurfaceView.onResume();
|
||||
} else {
|
||||
Cocos2dxHelper.onPause();
|
||||
this.mGLSurfaceView.onPause();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void showDialog(final String pTitle, final String pMessage) {
|
||||
Message msg = new Message();
|
||||
msg.what = Cocos2dxHandler.HANDLER_SHOW_DIALOG;
|
||||
msg.obj = new Cocos2dxHandler.DialogMessage(pTitle, pMessage);
|
||||
this.mHandler.sendMessage(msg);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void showEditTextDialog(final String pTitle, final String pContent, final int pInputMode, final int pInputFlag, final int pReturnType, final int pMaxLength) {
|
||||
Message msg = new Message();
|
||||
msg.what = Cocos2dxHandler.HANDLER_SHOW_EDITBOX_DIALOG;
|
||||
msg.obj = new Cocos2dxHandler.EditBoxMessage(pTitle, pContent, pInputMode, pInputFlag, pReturnType, pMaxLength);
|
||||
this.mHandler.sendMessage(msg);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void runOnGLThread(final Runnable pRunnable) {
|
||||
this.mGLSurfaceView.queueEvent(pRunnable);
|
||||
}
|
||||
|
||||
// ===========================================================
|
||||
// Methods
|
||||
// ===========================================================
|
||||
public void init() {
|
||||
|
||||
// FrameLayout
|
||||
ViewGroup.LayoutParams framelayout_params =
|
||||
new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
|
||||
ViewGroup.LayoutParams.FILL_PARENT);
|
||||
FrameLayout framelayout = new FrameLayout(this);
|
||||
framelayout.setLayoutParams(framelayout_params);
|
||||
|
||||
// Cocos2dxEditText layout
|
||||
ViewGroup.LayoutParams edittext_layout_params =
|
||||
new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
|
||||
ViewGroup.LayoutParams.WRAP_CONTENT);
|
||||
Cocos2dxEditText edittext = new Cocos2dxEditText(this);
|
||||
edittext.setLayoutParams(edittext_layout_params);
|
||||
|
||||
// ...add to FrameLayout
|
||||
framelayout.addView(edittext);
|
||||
|
||||
// Cocos2dxGLSurfaceView
|
||||
this.mGLSurfaceView = this.onCreateView();
|
||||
|
||||
// ...add to FrameLayout
|
||||
framelayout.addView(this.mGLSurfaceView);
|
||||
|
||||
// Switch to supported OpenGL (ARGB888) mode on emulator
|
||||
if (isAndroidEmulator())
|
||||
this.mGLSurfaceView.setEGLConfigChooser(8 , 8, 8, 8, 16, 0);
|
||||
|
||||
this.mGLSurfaceView.setCocos2dxRenderer(new Cocos2dxRenderer());
|
||||
this.mGLSurfaceView.setCocos2dxEditText(edittext);
|
||||
|
||||
// Set framelayout as the content view
|
||||
setContentView(framelayout);
|
||||
}
|
||||
|
||||
public Cocos2dxGLSurfaceView onCreateView() {
|
||||
return new Cocos2dxGLSurfaceView(this);
|
||||
}
|
||||
|
||||
private final static boolean isAndroidEmulator() {
|
||||
String model = Build.MODEL;
|
||||
Log.d(TAG, "model=" + model);
|
||||
String product = Build.PRODUCT;
|
||||
Log.d(TAG, "product=" + product);
|
||||
boolean isEmulator = false;
|
||||
if (product != null) {
|
||||
isEmulator = product.equals("sdk") || product.contains("_sdk") || product.contains("sdk_");
|
||||
}
|
||||
Log.d(TAG, "isEmulator=" + isEmulator);
|
||||
return isEmulator;
|
||||
}
|
||||
|
||||
// ===========================================================
|
||||
// Inner and Anonymous Classes
|
||||
// ===========================================================
|
||||
}
|
|
@ -1,89 +0,0 @@
|
|||
/****************************************************************************
|
||||
Copyright (c) 2012 cocos2d-x.org
|
||||
|
||||
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.
|
||||
****************************************************************************/
|
||||
package org.cocos2dx.lib;
|
||||
|
||||
import android.content.Context;
|
||||
import android.util.AttributeSet;
|
||||
import android.view.KeyEvent;
|
||||
import android.widget.EditText;
|
||||
|
||||
public class Cocos2dxEditText extends EditText {
|
||||
// ===========================================================
|
||||
// Constants
|
||||
// ===========================================================
|
||||
|
||||
// ===========================================================
|
||||
// Fields
|
||||
// ===========================================================
|
||||
|
||||
private Cocos2dxGLSurfaceView mCocos2dxGLSurfaceView;
|
||||
|
||||
// ===========================================================
|
||||
// Constructors
|
||||
// ===========================================================
|
||||
|
||||
public Cocos2dxEditText(final Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
public Cocos2dxEditText(final Context context, final AttributeSet attrs) {
|
||||
super(context, attrs);
|
||||
}
|
||||
|
||||
public Cocos2dxEditText(final Context context, final AttributeSet attrs, final int defStyle) {
|
||||
super(context, attrs, defStyle);
|
||||
}
|
||||
|
||||
// ===========================================================
|
||||
// Getter & Setter
|
||||
// ===========================================================
|
||||
|
||||
public void setCocos2dxGLSurfaceView(final Cocos2dxGLSurfaceView pCocos2dxGLSurfaceView) {
|
||||
this.mCocos2dxGLSurfaceView = pCocos2dxGLSurfaceView;
|
||||
}
|
||||
|
||||
// ===========================================================
|
||||
// Methods for/from SuperClass/Interfaces
|
||||
// ===========================================================
|
||||
|
||||
@Override
|
||||
public boolean onKeyDown(final int pKeyCode, final KeyEvent pKeyEvent) {
|
||||
super.onKeyDown(pKeyCode, pKeyEvent);
|
||||
|
||||
/* Let GlSurfaceView get focus if back key is input. */
|
||||
if (pKeyCode == KeyEvent.KEYCODE_BACK) {
|
||||
this.mCocos2dxGLSurfaceView.requestFocus();
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// ===========================================================
|
||||
// Methods
|
||||
// ===========================================================
|
||||
|
||||
// ===========================================================
|
||||
// Inner and Anonymous Classes
|
||||
// ===========================================================
|
||||
}
|
|
@ -1,370 +0,0 @@
|
|||
/****************************************************************************
|
||||
Copyright (c) 2010-2011 cocos2d-x.org
|
||||
|
||||
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.
|
||||
****************************************************************************/
|
||||
package org.cocos2dx.lib;
|
||||
|
||||
import android.content.Context;
|
||||
import android.opengl.GLSurfaceView;
|
||||
import android.os.Handler;
|
||||
import android.os.Message;
|
||||
import android.util.AttributeSet;
|
||||
import android.util.Log;
|
||||
import android.view.KeyEvent;
|
||||
import android.view.MotionEvent;
|
||||
import android.view.inputmethod.InputMethodManager;
|
||||
|
||||
public class Cocos2dxGLSurfaceView extends GLSurfaceView {
|
||||
// ===========================================================
|
||||
// Constants
|
||||
// ===========================================================
|
||||
|
||||
private static final String TAG = Cocos2dxGLSurfaceView.class.getSimpleName();
|
||||
|
||||
private final static int HANDLER_OPEN_IME_KEYBOARD = 2;
|
||||
private final static int HANDLER_CLOSE_IME_KEYBOARD = 3;
|
||||
|
||||
// ===========================================================
|
||||
// Fields
|
||||
// ===========================================================
|
||||
|
||||
// TODO Static handler -> Potential leak!
|
||||
private static Handler sHandler;
|
||||
|
||||
private static Cocos2dxGLSurfaceView mCocos2dxGLSurfaceView;
|
||||
private static Cocos2dxTextInputWraper sCocos2dxTextInputWraper;
|
||||
|
||||
private Cocos2dxRenderer mCocos2dxRenderer;
|
||||
private Cocos2dxEditText mCocos2dxEditText;
|
||||
|
||||
// ===========================================================
|
||||
// Constructors
|
||||
// ===========================================================
|
||||
|
||||
public Cocos2dxGLSurfaceView(final Context context) {
|
||||
super(context);
|
||||
|
||||
this.initView();
|
||||
}
|
||||
|
||||
public Cocos2dxGLSurfaceView(final Context context, final AttributeSet attrs) {
|
||||
super(context, attrs);
|
||||
|
||||
this.initView();
|
||||
}
|
||||
|
||||
protected void initView() {
|
||||
this.setEGLContextClientVersion(2);
|
||||
this.setFocusableInTouchMode(true);
|
||||
|
||||
Cocos2dxGLSurfaceView.mCocos2dxGLSurfaceView = this;
|
||||
Cocos2dxGLSurfaceView.sCocos2dxTextInputWraper = new Cocos2dxTextInputWraper(this);
|
||||
|
||||
Cocos2dxGLSurfaceView.sHandler = new Handler() {
|
||||
@Override
|
||||
public void handleMessage(final Message msg) {
|
||||
switch (msg.what) {
|
||||
case HANDLER_OPEN_IME_KEYBOARD:
|
||||
if (null != Cocos2dxGLSurfaceView.this.mCocos2dxEditText && Cocos2dxGLSurfaceView.this.mCocos2dxEditText.requestFocus()) {
|
||||
Cocos2dxGLSurfaceView.this.mCocos2dxEditText.removeTextChangedListener(Cocos2dxGLSurfaceView.sCocos2dxTextInputWraper);
|
||||
Cocos2dxGLSurfaceView.this.mCocos2dxEditText.setText("");
|
||||
final String text = (String) msg.obj;
|
||||
Cocos2dxGLSurfaceView.this.mCocos2dxEditText.append(text);
|
||||
Cocos2dxGLSurfaceView.sCocos2dxTextInputWraper.setOriginText(text);
|
||||
Cocos2dxGLSurfaceView.this.mCocos2dxEditText.addTextChangedListener(Cocos2dxGLSurfaceView.sCocos2dxTextInputWraper);
|
||||
final InputMethodManager imm = (InputMethodManager) Cocos2dxGLSurfaceView.mCocos2dxGLSurfaceView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
|
||||
imm.showSoftInput(Cocos2dxGLSurfaceView.this.mCocos2dxEditText, 0);
|
||||
Log.d("GLSurfaceView", "showSoftInput");
|
||||
}
|
||||
break;
|
||||
|
||||
case HANDLER_CLOSE_IME_KEYBOARD:
|
||||
if (null != Cocos2dxGLSurfaceView.this.mCocos2dxEditText) {
|
||||
Cocos2dxGLSurfaceView.this.mCocos2dxEditText.removeTextChangedListener(Cocos2dxGLSurfaceView.sCocos2dxTextInputWraper);
|
||||
final InputMethodManager imm = (InputMethodManager) Cocos2dxGLSurfaceView.mCocos2dxGLSurfaceView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
|
||||
imm.hideSoftInputFromWindow(Cocos2dxGLSurfaceView.this.mCocos2dxEditText.getWindowToken(), 0);
|
||||
Cocos2dxGLSurfaceView.this.requestFocus();
|
||||
Log.d("GLSurfaceView", "HideSoftInput");
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// ===========================================================
|
||||
// Getter & Setter
|
||||
// ===========================================================
|
||||
|
||||
|
||||
public static Cocos2dxGLSurfaceView getInstance() {
|
||||
return mCocos2dxGLSurfaceView;
|
||||
}
|
||||
|
||||
public static void queueAccelerometer(final float x, final float y, final float z, final long timestamp) {
|
||||
mCocos2dxGLSurfaceView.queueEvent(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
Cocos2dxAccelerometer.onSensorChanged(x, y, z, timestamp);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void setCocos2dxRenderer(final Cocos2dxRenderer renderer) {
|
||||
this.mCocos2dxRenderer = renderer;
|
||||
this.setRenderer(this.mCocos2dxRenderer);
|
||||
}
|
||||
|
||||
private String getContentText() {
|
||||
return this.mCocos2dxRenderer.getContentText();
|
||||
}
|
||||
|
||||
public Cocos2dxEditText getCocos2dxEditText() {
|
||||
return this.mCocos2dxEditText;
|
||||
}
|
||||
|
||||
public void setCocos2dxEditText(final Cocos2dxEditText pCocos2dxEditText) {
|
||||
this.mCocos2dxEditText = pCocos2dxEditText;
|
||||
if (null != this.mCocos2dxEditText && null != Cocos2dxGLSurfaceView.sCocos2dxTextInputWraper) {
|
||||
this.mCocos2dxEditText.setOnEditorActionListener(Cocos2dxGLSurfaceView.sCocos2dxTextInputWraper);
|
||||
this.mCocos2dxEditText.setCocos2dxGLSurfaceView(this);
|
||||
this.requestFocus();
|
||||
}
|
||||
}
|
||||
|
||||
// ===========================================================
|
||||
// Methods for/from SuperClass/Interfaces
|
||||
// ===========================================================
|
||||
|
||||
@Override
|
||||
public void onResume() {
|
||||
super.onResume();
|
||||
|
||||
this.queueEvent(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleOnResume();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPause() {
|
||||
this.queueEvent(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleOnPause();
|
||||
}
|
||||
});
|
||||
|
||||
//super.onPause();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onTouchEvent(final MotionEvent pMotionEvent) {
|
||||
// these data are used in ACTION_MOVE and ACTION_CANCEL
|
||||
final int pointerNumber = pMotionEvent.getPointerCount();
|
||||
final int[] ids = new int[pointerNumber];
|
||||
final float[] xs = new float[pointerNumber];
|
||||
final float[] ys = new float[pointerNumber];
|
||||
|
||||
for (int i = 0; i < pointerNumber; i++) {
|
||||
ids[i] = pMotionEvent.getPointerId(i);
|
||||
xs[i] = pMotionEvent.getX(i);
|
||||
ys[i] = pMotionEvent.getY(i);
|
||||
}
|
||||
|
||||
switch (pMotionEvent.getAction() & MotionEvent.ACTION_MASK) {
|
||||
case MotionEvent.ACTION_POINTER_DOWN:
|
||||
final int indexPointerDown = pMotionEvent.getAction() >> MotionEvent.ACTION_POINTER_ID_SHIFT;
|
||||
final int idPointerDown = pMotionEvent.getPointerId(indexPointerDown);
|
||||
final float xPointerDown = pMotionEvent.getX(indexPointerDown);
|
||||
final float yPointerDown = pMotionEvent.getY(indexPointerDown);
|
||||
|
||||
this.queueEvent(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleActionDown(idPointerDown, xPointerDown, yPointerDown);
|
||||
}
|
||||
});
|
||||
break;
|
||||
|
||||
case MotionEvent.ACTION_DOWN:
|
||||
// there are only one finger on the screen
|
||||
final int idDown = pMotionEvent.getPointerId(0);
|
||||
final float xDown = xs[0];
|
||||
final float yDown = ys[0];
|
||||
|
||||
this.queueEvent(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleActionDown(idDown, xDown, yDown);
|
||||
}
|
||||
});
|
||||
break;
|
||||
|
||||
case MotionEvent.ACTION_MOVE:
|
||||
this.queueEvent(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleActionMove(ids, xs, ys);
|
||||
}
|
||||
});
|
||||
break;
|
||||
|
||||
case MotionEvent.ACTION_POINTER_UP:
|
||||
final int indexPointUp = pMotionEvent.getAction() >> MotionEvent.ACTION_POINTER_ID_SHIFT;
|
||||
final int idPointerUp = pMotionEvent.getPointerId(indexPointUp);
|
||||
final float xPointerUp = pMotionEvent.getX(indexPointUp);
|
||||
final float yPointerUp = pMotionEvent.getY(indexPointUp);
|
||||
|
||||
this.queueEvent(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleActionUp(idPointerUp, xPointerUp, yPointerUp);
|
||||
}
|
||||
});
|
||||
break;
|
||||
|
||||
case MotionEvent.ACTION_UP:
|
||||
// there are only one finger on the screen
|
||||
final int idUp = pMotionEvent.getPointerId(0);
|
||||
final float xUp = xs[0];
|
||||
final float yUp = ys[0];
|
||||
|
||||
this.queueEvent(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleActionUp(idUp, xUp, yUp);
|
||||
}
|
||||
});
|
||||
break;
|
||||
|
||||
case MotionEvent.ACTION_CANCEL:
|
||||
this.queueEvent(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleActionCancel(ids, xs, ys);
|
||||
}
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
/*
|
||||
if (BuildConfig.DEBUG) {
|
||||
Cocos2dxGLSurfaceView.dumpMotionEvent(pMotionEvent);
|
||||
}
|
||||
*/
|
||||
return true;
|
||||
}
|
||||
|
||||
/*
|
||||
* This function is called before Cocos2dxRenderer.nativeInit(), so the
|
||||
* width and height is correct.
|
||||
*/
|
||||
@Override
|
||||
protected void onSizeChanged(final int pNewSurfaceWidth, final int pNewSurfaceHeight, final int pOldSurfaceWidth, final int pOldSurfaceHeight) {
|
||||
if(!this.isInEditMode()) {
|
||||
this.mCocos2dxRenderer.setScreenWidthAndHeight(pNewSurfaceWidth, pNewSurfaceHeight);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onKeyDown(final int pKeyCode, final KeyEvent pKeyEvent) {
|
||||
switch (pKeyCode) {
|
||||
case KeyEvent.KEYCODE_BACK:
|
||||
case KeyEvent.KEYCODE_MENU:
|
||||
this.queueEvent(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleKeyDown(pKeyCode);
|
||||
}
|
||||
});
|
||||
return true;
|
||||
default:
|
||||
return super.onKeyDown(pKeyCode, pKeyEvent);
|
||||
}
|
||||
}
|
||||
|
||||
// ===========================================================
|
||||
// Methods
|
||||
// ===========================================================
|
||||
|
||||
// ===========================================================
|
||||
// Inner and Anonymous Classes
|
||||
// ===========================================================
|
||||
|
||||
public static void openIMEKeyboard() {
|
||||
final Message msg = new Message();
|
||||
msg.what = Cocos2dxGLSurfaceView.HANDLER_OPEN_IME_KEYBOARD;
|
||||
msg.obj = Cocos2dxGLSurfaceView.mCocos2dxGLSurfaceView.getContentText();
|
||||
Cocos2dxGLSurfaceView.sHandler.sendMessage(msg);
|
||||
}
|
||||
|
||||
public static void closeIMEKeyboard() {
|
||||
final Message msg = new Message();
|
||||
msg.what = Cocos2dxGLSurfaceView.HANDLER_CLOSE_IME_KEYBOARD;
|
||||
Cocos2dxGLSurfaceView.sHandler.sendMessage(msg);
|
||||
}
|
||||
|
||||
public void insertText(final String pText) {
|
||||
this.queueEvent(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleInsertText(pText);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void deleteBackward() {
|
||||
this.queueEvent(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleDeleteBackward();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static void dumpMotionEvent(final MotionEvent event) {
|
||||
final String names[] = { "DOWN", "UP", "MOVE", "CANCEL", "OUTSIDE", "POINTER_DOWN", "POINTER_UP", "7?", "8?", "9?" };
|
||||
final StringBuilder sb = new StringBuilder();
|
||||
final int action = event.getAction();
|
||||
final int actionCode = action & MotionEvent.ACTION_MASK;
|
||||
sb.append("event ACTION_").append(names[actionCode]);
|
||||
if (actionCode == MotionEvent.ACTION_POINTER_DOWN || actionCode == MotionEvent.ACTION_POINTER_UP) {
|
||||
sb.append("(pid ").append(action >> MotionEvent.ACTION_POINTER_ID_SHIFT);
|
||||
sb.append(")");
|
||||
}
|
||||
sb.append("[");
|
||||
for (int i = 0; i < event.getPointerCount(); i++) {
|
||||
sb.append("#").append(i);
|
||||
sb.append("(pid ").append(event.getPointerId(i));
|
||||
sb.append(")=").append((int) event.getX(i));
|
||||
sb.append(",").append((int) event.getY(i));
|
||||
if (i + 1 < event.getPointerCount()) {
|
||||
sb.append(";");
|
||||
}
|
||||
}
|
||||
sb.append("]");
|
||||
Log.d(Cocos2dxGLSurfaceView.TAG, sb.toString());
|
||||
}
|
||||
}
|
|
@ -1,135 +0,0 @@
|
|||
/****************************************************************************
|
||||
Copyright (c) 2010-2011 cocos2d-x.org
|
||||
|
||||
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.
|
||||
****************************************************************************/
|
||||
|
||||
package org.cocos2dx.lib;
|
||||
|
||||
import java.lang.ref.WeakReference;
|
||||
|
||||
import android.app.AlertDialog;
|
||||
import android.content.DialogInterface;
|
||||
import android.os.Handler;
|
||||
import android.os.Message;
|
||||
|
||||
public class Cocos2dxHandler extends Handler {
|
||||
// ===========================================================
|
||||
// Constants
|
||||
// ===========================================================
|
||||
public final static int HANDLER_SHOW_DIALOG = 1;
|
||||
public final static int HANDLER_SHOW_EDITBOX_DIALOG = 2;
|
||||
|
||||
// ===========================================================
|
||||
// Fields
|
||||
// ===========================================================
|
||||
private WeakReference<Cocos2dxActivity> mActivity;
|
||||
|
||||
// ===========================================================
|
||||
// Constructors
|
||||
// ===========================================================
|
||||
public Cocos2dxHandler(Cocos2dxActivity activity) {
|
||||
this.mActivity = new WeakReference<Cocos2dxActivity>(activity);
|
||||
}
|
||||
|
||||
// ===========================================================
|
||||
// Getter & Setter
|
||||
// ===========================================================
|
||||
|
||||
// ===========================================================
|
||||
// Methods for/from SuperClass/Interfaces
|
||||
// ===========================================================
|
||||
|
||||
// ===========================================================
|
||||
// Methods
|
||||
// ===========================================================
|
||||
|
||||
public void handleMessage(Message msg) {
|
||||
switch (msg.what) {
|
||||
case Cocos2dxHandler.HANDLER_SHOW_DIALOG:
|
||||
showDialog(msg);
|
||||
break;
|
||||
case Cocos2dxHandler.HANDLER_SHOW_EDITBOX_DIALOG:
|
||||
showEditBoxDialog(msg);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void showDialog(Message msg) {
|
||||
Cocos2dxActivity theActivity = this.mActivity.get();
|
||||
DialogMessage dialogMessage = (DialogMessage)msg.obj;
|
||||
new AlertDialog.Builder(theActivity)
|
||||
.setTitle(dialogMessage.titile)
|
||||
.setMessage(dialogMessage.message)
|
||||
.setPositiveButton("Ok",
|
||||
new DialogInterface.OnClickListener() {
|
||||
|
||||
@Override
|
||||
public void onClick(DialogInterface dialog, int which) {
|
||||
// TODO Auto-generated method stub
|
||||
|
||||
}
|
||||
}).create().show();
|
||||
}
|
||||
|
||||
private void showEditBoxDialog(Message msg) {
|
||||
EditBoxMessage editBoxMessage = (EditBoxMessage)msg.obj;
|
||||
new Cocos2dxEditBoxDialog(this.mActivity.get(),
|
||||
editBoxMessage.title,
|
||||
editBoxMessage.content,
|
||||
editBoxMessage.inputMode,
|
||||
editBoxMessage.inputFlag,
|
||||
editBoxMessage.returnType,
|
||||
editBoxMessage.maxLength).show();
|
||||
}
|
||||
|
||||
// ===========================================================
|
||||
// Inner and Anonymous Classes
|
||||
// ===========================================================
|
||||
|
||||
public static class DialogMessage {
|
||||
public String titile;
|
||||
public String message;
|
||||
|
||||
public DialogMessage(String title, String message) {
|
||||
this.titile = title;
|
||||
this.message = message;
|
||||
}
|
||||
}
|
||||
|
||||
public static class EditBoxMessage {
|
||||
public String title;
|
||||
public String content;
|
||||
public int inputMode;
|
||||
public int inputFlag;
|
||||
public int returnType;
|
||||
public int maxLength;
|
||||
|
||||
public EditBoxMessage(String title, String content, int inputMode, int inputFlag, int returnType, int maxLength){
|
||||
this.content = content;
|
||||
this.title = title;
|
||||
this.inputMode = inputMode;
|
||||
this.inputFlag = inputFlag;
|
||||
this.returnType = returnType;
|
||||
this.maxLength = maxLength;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -29,7 +29,9 @@ import java.util.Locale;
|
|||
import android.app.Activity;
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import android.content.pm.ActivityInfo;
|
||||
import android.content.pm.ApplicationInfo;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.content.res.AssetManager;
|
||||
import android.os.Build;
|
||||
import android.util.DisplayMetrics;
|
||||
|
@ -49,37 +51,62 @@ public class Cocos2dxHelper {
|
|||
private static Cocos2dxMusic sCocos2dMusic;
|
||||
private static Cocos2dxSound sCocos2dSound;
|
||||
private static AssetManager sAssetManager;
|
||||
private static Cocos2dxAccelerometer sCocos2dxAccelerometer;
|
||||
private static boolean sAccelerometerEnabled;
|
||||
private static String sPackageName;
|
||||
private static String sFileDirectory;
|
||||
private static Context sContext = null;
|
||||
private static Activity sActivity = null;
|
||||
private static Cocos2dxHelperListener sCocos2dxHelperListener;
|
||||
|
||||
/**
|
||||
* Optional meta-that can be in the manifest for this component, specifying
|
||||
* the name of the native shared library to load. If not specified,
|
||||
* "main" is used.
|
||||
*/
|
||||
private static final String META_DATA_LIB_NAME = "android.app.lib_name";
|
||||
private static final String DEFAULT_LIB_NAME = "main";
|
||||
|
||||
// ===========================================================
|
||||
// Constructors
|
||||
// ===========================================================
|
||||
|
||||
public static void init(final Context pContext, final Cocos2dxHelperListener pCocos2dxHelperListener) {
|
||||
final ApplicationInfo applicationInfo = pContext.getApplicationInfo();
|
||||
public static void init(final Activity activity) {
|
||||
final ApplicationInfo applicationInfo = activity.getApplicationInfo();
|
||||
|
||||
Cocos2dxHelper.sContext = pContext;
|
||||
Cocos2dxHelper.sCocos2dxHelperListener = pCocos2dxHelperListener;
|
||||
Cocos2dxHelper.sActivity = activity;
|
||||
|
||||
try {
|
||||
// Get the lib_name from AndroidManifest.xml metadata
|
||||
ActivityInfo ai =
|
||||
activity.getPackageManager().getActivityInfo(activity.getIntent().getComponent(), PackageManager.GET_META_DATA);
|
||||
if (null != ai.metaData) {
|
||||
String lib_name = ai.metaData.getString(META_DATA_LIB_NAME);
|
||||
if (null != lib_name) {
|
||||
System.loadLibrary(lib_name);
|
||||
} else {
|
||||
System.loadLibrary(DEFAULT_LIB_NAME);
|
||||
}
|
||||
}
|
||||
} catch (PackageManager.NameNotFoundException e) {
|
||||
throw new RuntimeException("Error getting activity info", e);
|
||||
}
|
||||
|
||||
Cocos2dxHelper.sPackageName = applicationInfo.packageName;
|
||||
Cocos2dxHelper.sFileDirectory = pContext.getFilesDir().getAbsolutePath();
|
||||
Cocos2dxHelper.nativeSetApkPath(applicationInfo.sourceDir);
|
||||
Cocos2dxHelper.sFileDirectory = activity.getFilesDir().getAbsolutePath();
|
||||
//Cocos2dxHelper.nativeSetApkPath(applicationInfo.sourceDir);
|
||||
|
||||
Cocos2dxHelper.sCocos2dxAccelerometer = new Cocos2dxAccelerometer(pContext);
|
||||
Cocos2dxHelper.sCocos2dMusic = new Cocos2dxMusic(pContext);
|
||||
Cocos2dxHelper.sCocos2dSound = new Cocos2dxSound(pContext);
|
||||
Cocos2dxHelper.sAssetManager = pContext.getAssets();
|
||||
Cocos2dxHelper.sCocos2dMusic = new Cocos2dxMusic(activity);
|
||||
Cocos2dxHelper.sCocos2dSound = new Cocos2dxSound(activity);
|
||||
Cocos2dxHelper.sAssetManager = activity.getAssets();
|
||||
|
||||
Cocos2dxHelper.nativeSetAssetManager(sAssetManager);
|
||||
Cocos2dxBitmap.setContext(pContext);
|
||||
Cocos2dxETCLoader.setContext(pContext);
|
||||
//Cocos2dxHelper.nativeSetAssetManager(sAssetManager);
|
||||
Cocos2dxBitmap.setContext(activity);
|
||||
Cocos2dxETCLoader.setContext(activity);
|
||||
}
|
||||
|
||||
public static Activity getActivity() {
|
||||
return sActivity;
|
||||
}
|
||||
|
||||
// ===========================================================
|
||||
// Getter & Setter
|
||||
// ===========================================================
|
||||
|
@ -92,12 +119,8 @@ public class Cocos2dxHelper {
|
|||
// Methods
|
||||
// ===========================================================
|
||||
|
||||
private static native void nativeSetApkPath(final String pApkPath);
|
||||
|
||||
private static native void nativeSetEditTextDialogResult(final byte[] pBytes);
|
||||
|
||||
private static native void nativeSetAssetManager(AssetManager a);
|
||||
|
||||
public static String getCocos2dxPackageName() {
|
||||
return Cocos2dxHelper.sPackageName;
|
||||
}
|
||||
|
@ -118,21 +141,6 @@ public class Cocos2dxHelper {
|
|||
return Cocos2dxHelper.sAssetManager;
|
||||
}
|
||||
|
||||
public static void enableAccelerometer() {
|
||||
Cocos2dxHelper.sAccelerometerEnabled = true;
|
||||
Cocos2dxHelper.sCocos2dxAccelerometer.enable();
|
||||
}
|
||||
|
||||
|
||||
public static void setAccelerometerInterval(float interval) {
|
||||
Cocos2dxHelper.sCocos2dxAccelerometer.setInterval(interval);
|
||||
}
|
||||
|
||||
public static void disableAccelerometer() {
|
||||
Cocos2dxHelper.sAccelerometerEnabled = false;
|
||||
Cocos2dxHelper.sCocos2dxAccelerometer.disable();
|
||||
}
|
||||
|
||||
public static void preloadBackgroundMusic(final String pPath) {
|
||||
Cocos2dxHelper.sCocos2dMusic.preloadBackgroundMusic(pPath);
|
||||
}
|
||||
|
@ -218,18 +226,6 @@ public class Cocos2dxHelper {
|
|||
Cocos2dxHelper.sCocos2dSound.end();
|
||||
}
|
||||
|
||||
public static void onResume() {
|
||||
if (Cocos2dxHelper.sAccelerometerEnabled) {
|
||||
Cocos2dxHelper.sCocos2dxAccelerometer.enable();
|
||||
}
|
||||
}
|
||||
|
||||
public static void onPause() {
|
||||
if (Cocos2dxHelper.sAccelerometerEnabled) {
|
||||
Cocos2dxHelper.sCocos2dxAccelerometer.disable();
|
||||
}
|
||||
}
|
||||
|
||||
public static void terminateProcess() {
|
||||
android.os.Process.killProcess(android.os.Process.myPid());
|
||||
}
|
||||
|
@ -259,10 +255,10 @@ public class Cocos2dxHelper {
|
|||
|
||||
public static int getDPI()
|
||||
{
|
||||
if (sContext != null)
|
||||
if (sActivity != null)
|
||||
{
|
||||
DisplayMetrics metrics = new DisplayMetrics();
|
||||
WindowManager wm = ((Activity)sContext).getWindowManager();
|
||||
WindowManager wm = sActivity.getWindowManager();
|
||||
if (wm != null)
|
||||
{
|
||||
Display d = wm.getDefaultDisplay();
|
||||
|
@ -281,47 +277,47 @@ public class Cocos2dxHelper {
|
|||
// ===========================================================
|
||||
|
||||
public static boolean getBoolForKey(String key, boolean defaultValue) {
|
||||
SharedPreferences settings = ((Activity)sContext).getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
|
||||
SharedPreferences settings = sActivity.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
|
||||
return settings.getBoolean(key, defaultValue);
|
||||
}
|
||||
|
||||
public static int getIntegerForKey(String key, int defaultValue) {
|
||||
SharedPreferences settings = ((Activity)sContext).getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
|
||||
SharedPreferences settings = sActivity.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
|
||||
return settings.getInt(key, defaultValue);
|
||||
}
|
||||
|
||||
public static float getFloatForKey(String key, float defaultValue) {
|
||||
SharedPreferences settings = ((Activity)sContext).getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
|
||||
SharedPreferences settings = sActivity.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
|
||||
return settings.getFloat(key, defaultValue);
|
||||
}
|
||||
|
||||
public static double getDoubleForKey(String key, double defaultValue) {
|
||||
// SharedPreferences doesn't support saving double value
|
||||
SharedPreferences settings = ((Activity)sContext).getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
|
||||
SharedPreferences settings = sActivity.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
|
||||
return settings.getFloat(key, (float)defaultValue);
|
||||
}
|
||||
|
||||
public static String getStringForKey(String key, String defaultValue) {
|
||||
SharedPreferences settings = ((Activity)sContext).getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
|
||||
SharedPreferences settings = sActivity.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
|
||||
return settings.getString(key, defaultValue);
|
||||
}
|
||||
|
||||
public static void setBoolForKey(String key, boolean value) {
|
||||
SharedPreferences settings = ((Activity)sContext).getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
|
||||
SharedPreferences settings = sActivity.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
|
||||
SharedPreferences.Editor editor = settings.edit();
|
||||
editor.putBoolean(key, value);
|
||||
editor.commit();
|
||||
}
|
||||
|
||||
public static void setIntegerForKey(String key, int value) {
|
||||
SharedPreferences settings = ((Activity)sContext).getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
|
||||
SharedPreferences settings = sActivity.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
|
||||
SharedPreferences.Editor editor = settings.edit();
|
||||
editor.putInt(key, value);
|
||||
editor.commit();
|
||||
}
|
||||
|
||||
public static void setFloatForKey(String key, float value) {
|
||||
SharedPreferences settings = ((Activity)sContext).getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
|
||||
SharedPreferences settings = sActivity.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
|
||||
SharedPreferences.Editor editor = settings.edit();
|
||||
editor.putFloat(key, value);
|
||||
editor.commit();
|
||||
|
@ -329,14 +325,14 @@ public class Cocos2dxHelper {
|
|||
|
||||
public static void setDoubleForKey(String key, double value) {
|
||||
// SharedPreferences doesn't support recording double value
|
||||
SharedPreferences settings = ((Activity)sContext).getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
|
||||
SharedPreferences settings = sActivity.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
|
||||
SharedPreferences.Editor editor = settings.edit();
|
||||
editor.putFloat(key, (float)value);
|
||||
editor.commit();
|
||||
}
|
||||
|
||||
public static void setStringForKey(String key, String value) {
|
||||
SharedPreferences settings = ((Activity)sContext).getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
|
||||
SharedPreferences settings = sActivity.getSharedPreferences(Cocos2dxHelper.PREFS_NAME, 0);
|
||||
SharedPreferences.Editor editor = settings.edit();
|
||||
editor.putString(key, value);
|
||||
editor.commit();
|
||||
|
|
|
@ -46,10 +46,10 @@ public class Cocos2dxLocalStorage {
|
|||
* @return
|
||||
*/
|
||||
public static boolean init(String dbName, String tableName) {
|
||||
if (Cocos2dxActivity.getContext() != null) {
|
||||
if (Cocos2dxHelper.getActivity() != null) {
|
||||
DATABASE_NAME = dbName;
|
||||
TABLE_NAME = tableName;
|
||||
mDatabaseOpenHelper = new DBOpenHelper(Cocos2dxActivity.getContext());
|
||||
mDatabaseOpenHelper = new DBOpenHelper(Cocos2dxHelper.getActivity());
|
||||
mDatabase = mDatabaseOpenHelper.getWritableDatabase();
|
||||
return true;
|
||||
}
|
||||
|
|
|
@ -1,171 +0,0 @@
|
|||
/****************************************************************************
|
||||
Copyright (c) 2010-2011 cocos2d-x.org
|
||||
|
||||
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.
|
||||
****************************************************************************/
|
||||
package org.cocos2dx.lib;
|
||||
|
||||
import javax.microedition.khronos.egl.EGLConfig;
|
||||
import javax.microedition.khronos.opengles.GL10;
|
||||
|
||||
import android.opengl.GLSurfaceView;
|
||||
|
||||
public class Cocos2dxRenderer implements GLSurfaceView.Renderer {
|
||||
// ===========================================================
|
||||
// Constants
|
||||
// ===========================================================
|
||||
|
||||
private final static long NANOSECONDSPERSECOND = 1000000000L;
|
||||
private final static long NANOSECONDSPERMICROSECOND = 1000000;
|
||||
|
||||
private static long sAnimationInterval = (long) (1.0 / 60 * Cocos2dxRenderer.NANOSECONDSPERSECOND);
|
||||
|
||||
// ===========================================================
|
||||
// Fields
|
||||
// ===========================================================
|
||||
|
||||
private long mLastTickInNanoSeconds;
|
||||
private int mScreenWidth;
|
||||
private int mScreenHeight;
|
||||
|
||||
// ===========================================================
|
||||
// Constructors
|
||||
// ===========================================================
|
||||
|
||||
// ===========================================================
|
||||
// Getter & Setter
|
||||
// ===========================================================
|
||||
|
||||
public static void setAnimationInterval(final double pAnimationInterval) {
|
||||
Cocos2dxRenderer.sAnimationInterval = (long) (pAnimationInterval * Cocos2dxRenderer.NANOSECONDSPERSECOND);
|
||||
}
|
||||
|
||||
public void setScreenWidthAndHeight(final int pSurfaceWidth, final int pSurfaceHeight) {
|
||||
this.mScreenWidth = pSurfaceWidth;
|
||||
this.mScreenHeight = pSurfaceHeight;
|
||||
}
|
||||
|
||||
// ===========================================================
|
||||
// Methods for/from SuperClass/Interfaces
|
||||
// ===========================================================
|
||||
|
||||
@Override
|
||||
public void onSurfaceCreated(final GL10 pGL10, final EGLConfig pEGLConfig) {
|
||||
Cocos2dxRenderer.nativeInit(this.mScreenWidth, this.mScreenHeight);
|
||||
this.mLastTickInNanoSeconds = System.nanoTime();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSurfaceChanged(final GL10 pGL10, final int pWidth, final int pHeight) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDrawFrame(final GL10 gl) {
|
||||
/*
|
||||
* FPS controlling algorithm is not accurate, and it will slow down FPS
|
||||
* on some devices. So comment FPS controlling code.
|
||||
*/
|
||||
|
||||
/*
|
||||
final long nowInNanoSeconds = System.nanoTime();
|
||||
final long interval = nowInNanoSeconds - this.mLastTickInNanoSeconds;
|
||||
*/
|
||||
|
||||
// should render a frame when onDrawFrame() is called or there is a
|
||||
// "ghost"
|
||||
Cocos2dxRenderer.nativeRender();
|
||||
|
||||
/*
|
||||
// fps controlling
|
||||
if (interval < Cocos2dxRenderer.sAnimationInterval) {
|
||||
try {
|
||||
// because we render it before, so we should sleep twice time interval
|
||||
Thread.sleep((Cocos2dxRenderer.sAnimationInterval - interval) / Cocos2dxRenderer.NANOSECONDSPERMICROSECOND);
|
||||
} catch (final Exception e) {
|
||||
}
|
||||
}
|
||||
|
||||
this.mLastTickInNanoSeconds = nowInNanoSeconds;
|
||||
*/
|
||||
}
|
||||
|
||||
// ===========================================================
|
||||
// Methods
|
||||
// ===========================================================
|
||||
|
||||
private static native void nativeTouchesBegin(final int pID, final float pX, final float pY);
|
||||
private static native void nativeTouchesEnd(final int pID, final float pX, final float pY);
|
||||
private static native void nativeTouchesMove(final int[] pIDs, final float[] pXs, final float[] pYs);
|
||||
private static native void nativeTouchesCancel(final int[] pIDs, final float[] pXs, final float[] pYs);
|
||||
private static native boolean nativeKeyDown(final int pKeyCode);
|
||||
private static native void nativeRender();
|
||||
private static native void nativeInit(final int pWidth, final int pHeight);
|
||||
private static native void nativeOnPause();
|
||||
private static native void nativeOnResume();
|
||||
|
||||
public void handleActionDown(final int pID, final float pX, final float pY) {
|
||||
Cocos2dxRenderer.nativeTouchesBegin(pID, pX, pY);
|
||||
}
|
||||
|
||||
public void handleActionUp(final int pID, final float pX, final float pY) {
|
||||
Cocos2dxRenderer.nativeTouchesEnd(pID, pX, pY);
|
||||
}
|
||||
|
||||
public void handleActionCancel(final int[] pIDs, final float[] pXs, final float[] pYs) {
|
||||
Cocos2dxRenderer.nativeTouchesCancel(pIDs, pXs, pYs);
|
||||
}
|
||||
|
||||
public void handleActionMove(final int[] pIDs, final float[] pXs, final float[] pYs) {
|
||||
Cocos2dxRenderer.nativeTouchesMove(pIDs, pXs, pYs);
|
||||
}
|
||||
|
||||
public void handleKeyDown(final int pKeyCode) {
|
||||
Cocos2dxRenderer.nativeKeyDown(pKeyCode);
|
||||
}
|
||||
|
||||
public void handleOnPause() {
|
||||
Cocos2dxRenderer.nativeOnPause();
|
||||
}
|
||||
|
||||
public void handleOnResume() {
|
||||
Cocos2dxRenderer.nativeOnResume();
|
||||
}
|
||||
|
||||
private static native void nativeInsertText(final String pText);
|
||||
private static native void nativeDeleteBackward();
|
||||
private static native String nativeGetContentText();
|
||||
|
||||
public void handleInsertText(final String pText) {
|
||||
Cocos2dxRenderer.nativeInsertText(pText);
|
||||
}
|
||||
|
||||
public void handleDeleteBackward() {
|
||||
Cocos2dxRenderer.nativeDeleteBackward();
|
||||
}
|
||||
|
||||
public String getContentText() {
|
||||
return Cocos2dxRenderer.nativeGetContentText();
|
||||
}
|
||||
|
||||
// ===========================================================
|
||||
// Inner and Anonymous Classes
|
||||
// ===========================================================
|
||||
}
|
|
@ -1,168 +0,0 @@
|
|||
/****************************************************************************
|
||||
Copyright (c) 2010-2011 cocos2d-x.org
|
||||
|
||||
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.
|
||||
****************************************************************************/
|
||||
package org.cocos2dx.lib;
|
||||
|
||||
import android.content.Context;
|
||||
import android.text.Editable;
|
||||
import android.text.TextWatcher;
|
||||
import android.util.Log;
|
||||
import android.view.KeyEvent;
|
||||
import android.view.inputmethod.EditorInfo;
|
||||
import android.view.inputmethod.InputMethodManager;
|
||||
import android.widget.TextView;
|
||||
import android.widget.TextView.OnEditorActionListener;
|
||||
|
||||
public class Cocos2dxTextInputWraper implements TextWatcher, OnEditorActionListener {
|
||||
// ===========================================================
|
||||
// Constants
|
||||
// ===========================================================
|
||||
|
||||
private static final String TAG = Cocos2dxTextInputWraper.class.getSimpleName();
|
||||
|
||||
// ===========================================================
|
||||
// Fields
|
||||
// ===========================================================
|
||||
|
||||
private final Cocos2dxGLSurfaceView mCocos2dxGLSurfaceView;
|
||||
private String mText;
|
||||
private String mOriginText;
|
||||
|
||||
// ===========================================================
|
||||
// Constructors
|
||||
// ===========================================================
|
||||
|
||||
public Cocos2dxTextInputWraper(final Cocos2dxGLSurfaceView pCocos2dxGLSurfaceView) {
|
||||
this.mCocos2dxGLSurfaceView = pCocos2dxGLSurfaceView;
|
||||
}
|
||||
|
||||
// ===========================================================
|
||||
// Getter & Setter
|
||||
// ===========================================================
|
||||
|
||||
private boolean isFullScreenEdit() {
|
||||
final TextView textField = this.mCocos2dxGLSurfaceView.getCocos2dxEditText();
|
||||
final InputMethodManager imm = (InputMethodManager) textField.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
|
||||
return imm.isFullscreenMode();
|
||||
}
|
||||
|
||||
public void setOriginText(final String pOriginText) {
|
||||
this.mOriginText = pOriginText;
|
||||
}
|
||||
|
||||
// ===========================================================
|
||||
// Methods for/from SuperClass/Interfaces
|
||||
// ===========================================================
|
||||
|
||||
@Override
|
||||
public void afterTextChanged(final Editable s) {
|
||||
if (this.isFullScreenEdit()) {
|
||||
return;
|
||||
}
|
||||
|
||||
//if (BuildConfig.DEBUG) {
|
||||
//Log.d(TAG, "afterTextChanged: " + s);
|
||||
//}
|
||||
int nModified = s.length() - this.mText.length();
|
||||
if (nModified > 0) {
|
||||
final String insertText = s.subSequence(this.mText.length(), s.length()).toString();
|
||||
this.mCocos2dxGLSurfaceView.insertText(insertText);
|
||||
/*
|
||||
if (BuildConfig.DEBUG) {
|
||||
Log.d(TAG, "insertText(" + insertText + ")");
|
||||
}
|
||||
*/
|
||||
} else {
|
||||
for (; nModified < 0; ++nModified) {
|
||||
this.mCocos2dxGLSurfaceView.deleteBackward();
|
||||
/*
|
||||
if (BuildConfig.DEBUG) {
|
||||
Log.d(TAG, "deleteBackward");
|
||||
}
|
||||
*/
|
||||
}
|
||||
}
|
||||
this.mText = s.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void beforeTextChanged(final CharSequence pCharSequence, final int start, final int count, final int after) {
|
||||
/*
|
||||
if (BuildConfig.DEBUG) {
|
||||
Log.d(TAG, "beforeTextChanged(" + pCharSequence + ")start: " + start + ",count: " + count + ",after: " + after);
|
||||
}
|
||||
*/
|
||||
this.mText = pCharSequence.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onTextChanged(final CharSequence pCharSequence, final int start, final int before, final int count) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onEditorAction(final TextView pTextView, final int pActionID, final KeyEvent pKeyEvent) {
|
||||
if (this.mCocos2dxGLSurfaceView.getCocos2dxEditText() == pTextView && this.isFullScreenEdit()) {
|
||||
// user press the action button, delete all old text and insert new text
|
||||
for (int i = this.mOriginText.length(); i > 0; i--) {
|
||||
this.mCocos2dxGLSurfaceView.deleteBackward();
|
||||
/*
|
||||
if (BuildConfig.DEBUG) {
|
||||
Log.d(TAG, "deleteBackward");
|
||||
}
|
||||
*/
|
||||
}
|
||||
String text = pTextView.getText().toString();
|
||||
|
||||
/* If user input nothing, translate "\n" to engine. */
|
||||
if (text.compareTo("") == 0) {
|
||||
text = "\n";
|
||||
}
|
||||
|
||||
if ('\n' != text.charAt(text.length() - 1)) {
|
||||
text += '\n';
|
||||
}
|
||||
|
||||
final String insertText = text;
|
||||
this.mCocos2dxGLSurfaceView.insertText(insertText);
|
||||
/*
|
||||
if (BuildConfig.DEBUG) {
|
||||
Log.d(TAG, "insertText(" + insertText + ")");
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
if (pActionID == EditorInfo.IME_ACTION_DONE) {
|
||||
this.mCocos2dxGLSurfaceView.requestFocus();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// ===========================================================
|
||||
// Methods
|
||||
// ===========================================================
|
||||
|
||||
// ===========================================================
|
||||
// Inner and Anonymous Classes
|
||||
// ===========================================================
|
||||
}
|
|
@ -9,7 +9,5 @@ using namespace cocos2d;
|
|||
|
||||
extern "C" {
|
||||
JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxAccelerometer_onSensorChanged(JNIEnv* env, jobject thiz, jfloat x, jfloat y, jfloat z, jlong timeStamp) {
|
||||
Director* pDirector = Director::getInstance();
|
||||
pDirector->getAccelerometer()->update(x, y, z, timeStamp);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -153,33 +153,6 @@ std::string getCurrentLanguageJNI() {
|
|||
return ret;
|
||||
}
|
||||
|
||||
void enableAccelerometerJNI() {
|
||||
JniMethodInfo t;
|
||||
|
||||
if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "enableAccelerometer", "()V")) {
|
||||
t.env->CallStaticVoidMethod(t.classID, t.methodID);
|
||||
t.env->DeleteLocalRef(t.classID);
|
||||
}
|
||||
}
|
||||
|
||||
void setAccelerometerIntervalJNI(float interval) {
|
||||
JniMethodInfo t;
|
||||
|
||||
if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "setAccelerometerInterval", "(F)V")) {
|
||||
t.env->CallStaticVoidMethod(t.classID, t.methodID, interval);
|
||||
t.env->DeleteLocalRef(t.classID);
|
||||
}
|
||||
}
|
||||
|
||||
void disableAccelerometerJNI() {
|
||||
JniMethodInfo t;
|
||||
|
||||
if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "disableAccelerometer", "()V")) {
|
||||
t.env->CallStaticVoidMethod(t.classID, t.methodID);
|
||||
t.env->DeleteLocalRef(t.classID);
|
||||
}
|
||||
}
|
||||
|
||||
// functions for UserDefault
|
||||
bool getBoolForKeyJNI(const char* pKey, bool defaultValue)
|
||||
{
|
||||
|
|
|
@ -35,9 +35,6 @@ extern void terminateProcessJNI();
|
|||
extern std::string getCurrentLanguageJNI();
|
||||
extern std::string getPackageNameJNI();
|
||||
extern std::string getFileDirectoryJNI();
|
||||
extern void enableAccelerometerJNI();
|
||||
extern void disableAccelerometerJNI();
|
||||
extern void setAccelerometerIntervalJNI(float interval);
|
||||
// functions for UserDefault
|
||||
extern bool getBoolForKeyJNI(const char* pKey, bool defaultValue);
|
||||
extern int getIntegerForKeyJNI(const char* pKey, int defaultValue);
|
||||
|
|
|
@ -1,48 +0,0 @@
|
|||
#include "text_input_node/CCIMEDispatcher.h"
|
||||
#include "CCDirector.h"
|
||||
#include "../CCApplication.h"
|
||||
#include "platform/CCFileUtils.h"
|
||||
#include "CCEventType.h"
|
||||
#include "support/CCNotificationCenter.h"
|
||||
#include "JniHelper.h"
|
||||
#include <jni.h>
|
||||
|
||||
using namespace cocos2d;
|
||||
|
||||
extern "C" {
|
||||
JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeRender(JNIEnv* env) {
|
||||
cocos2d::Director::getInstance()->mainLoop();
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeOnPause() {
|
||||
Application::getInstance()->applicationDidEnterBackground();
|
||||
|
||||
NotificationCenter::getInstance()->postNotification(EVENT_COME_TO_BACKGROUND, NULL);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeOnResume() {
|
||||
if (Director::getInstance()->getOpenGLView()) {
|
||||
Application::getInstance()->applicationWillEnterForeground();
|
||||
}
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeInsertText(JNIEnv* env, jobject thiz, jstring text) {
|
||||
const char* pszText = env->GetStringUTFChars(text, NULL);
|
||||
cocos2d::IMEDispatcher::sharedDispatcher()->dispatchInsertText(pszText, strlen(pszText));
|
||||
env->ReleaseStringUTFChars(text, pszText);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeDeleteBackward(JNIEnv* env, jobject thiz) {
|
||||
cocos2d::IMEDispatcher::sharedDispatcher()->dispatchDeleteBackward();
|
||||
}
|
||||
|
||||
JNIEXPORT jstring JNICALL Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeGetContentText() {
|
||||
JNIEnv * env = 0;
|
||||
|
||||
if (JniHelper::getJavaVM()->GetEnv((void**)&env, JNI_VERSION_1_4) != JNI_OK || ! env) {
|
||||
return 0;
|
||||
}
|
||||
const char * pszText = cocos2d::IMEDispatcher::sharedDispatcher()->getContentText();
|
||||
return env->NewStringUTF(pszText);
|
||||
}
|
||||
}
|
|
@ -24,193 +24,245 @@ THE SOFTWARE.
|
|||
#include "JniHelper.h"
|
||||
#include <android/log.h>
|
||||
#include <string.h>
|
||||
#include <pthread.h>
|
||||
|
||||
#if 1
|
||||
#define LOG_TAG "JniHelper"
|
||||
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
|
||||
#else
|
||||
#define LOGD(...)
|
||||
#endif
|
||||
|
||||
#define JAVAVM cocos2d::JniHelper::getJavaVM()
|
||||
|
||||
using namespace std;
|
||||
|
||||
extern "C"
|
||||
{
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// java vm helper function
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
static bool getEnv(JNIEnv **env)
|
||||
{
|
||||
bool bRet = false;
|
||||
|
||||
do
|
||||
{
|
||||
if (JAVAVM->GetEnv((void**)env, JNI_VERSION_1_4) != JNI_OK)
|
||||
{
|
||||
LOGD("Failed to get the environment using GetEnv()");
|
||||
break;
|
||||
}
|
||||
|
||||
if (JAVAVM->AttachCurrentThread(env, 0) < 0)
|
||||
{
|
||||
LOGD("Failed to get the environment using AttachCurrentThread()");
|
||||
break;
|
||||
}
|
||||
|
||||
bRet = true;
|
||||
} while (0);
|
||||
|
||||
return bRet;
|
||||
jclass _getClassID(const char *className) {
|
||||
if (NULL == className) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static jclass getClassID_(const char *className, JNIEnv *env)
|
||||
{
|
||||
JNIEnv *pEnv = env;
|
||||
jclass ret = 0;
|
||||
JNIEnv* env = cocos2d::JniHelper::getEnv();
|
||||
|
||||
do
|
||||
{
|
||||
if (! pEnv)
|
||||
{
|
||||
if (! getEnv(&pEnv))
|
||||
jstring _jstrClassName = env->NewStringUTF(className);
|
||||
|
||||
jclass _clazz = (jclass) env->CallObjectMethod(cocos2d::JniHelper::classloader,
|
||||
cocos2d::JniHelper::loadclassMethod_methodID,
|
||||
_jstrClassName);
|
||||
|
||||
if (NULL == _clazz) {
|
||||
LOGD("Classloader failed to find class of %s", className);
|
||||
}
|
||||
|
||||
env->DeleteLocalRef(_jstrClassName);
|
||||
|
||||
return _clazz;
|
||||
}
|
||||
|
||||
namespace cocos2d {
|
||||
|
||||
JavaVM* JniHelper::_psJavaVM = NULL;
|
||||
jmethodID JniHelper::loadclassMethod_methodID = NULL;
|
||||
jobject JniHelper::classloader = NULL;
|
||||
JNIEnv* JniHelper::env = NULL;
|
||||
|
||||
JavaVM* JniHelper::getJavaVM() {
|
||||
pthread_t thisthread = pthread_self();
|
||||
LOGD("JniHelper::getJavaVM(), pthread_self() = %X", thisthread);
|
||||
return _psJavaVM;
|
||||
}
|
||||
|
||||
void JniHelper::setJavaVM(JavaVM *javaVM) {
|
||||
pthread_t thisthread = pthread_self();
|
||||
LOGD("JniHelper::setJavaVM(%p), pthread_self() = %X", javaVM, thisthread);
|
||||
_psJavaVM = javaVM;
|
||||
|
||||
JniHelper::cacheEnv(javaVM);
|
||||
}
|
||||
|
||||
bool JniHelper::cacheEnv(JavaVM* jvm) {
|
||||
JNIEnv* _env = NULL;
|
||||
// get jni environment
|
||||
jint ret = jvm->GetEnv((void**)&_env, JNI_VERSION_1_4);
|
||||
|
||||
switch (ret) {
|
||||
case JNI_OK :
|
||||
// Success!
|
||||
JniHelper::env = _env;
|
||||
return true;
|
||||
|
||||
case JNI_EDETACHED :
|
||||
// Thread not attached
|
||||
|
||||
// TODO : If calling AttachCurrentThread() on a native thread
|
||||
// must call DetachCurrentThread() in future.
|
||||
// see: http://developer.android.com/guide/practices/design/jni.html
|
||||
|
||||
if (jvm->AttachCurrentThread(&_env, NULL) < 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
LOGD("Failed to get the environment using AttachCurrentThread()");
|
||||
|
||||
JniHelper::env = NULL;
|
||||
return false;
|
||||
} else {
|
||||
// Success : Attached and obtained JNIEnv!
|
||||
JniHelper::env = _env;
|
||||
return true;
|
||||
}
|
||||
|
||||
case JNI_EVERSION :
|
||||
// Cannot recover from this error
|
||||
LOGD("JNI interface version 1.4 not supported");
|
||||
default :
|
||||
LOGD("Failed to get the environment using GetEnv()");
|
||||
JniHelper::env = NULL;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
JNIEnv* JniHelper::getEnv() {
|
||||
return JniHelper::env;
|
||||
}
|
||||
|
||||
bool JniHelper::setClassLoaderFrom(jobject nativeactivityinstance) {
|
||||
JniMethodInfo _getclassloaderMethod;
|
||||
if (!JniHelper::getMethodInfo_DefaultClassLoader(_getclassloaderMethod,
|
||||
"android/app/NativeActivity",
|
||||
"getClassLoader",
|
||||
"()Ljava/lang/ClassLoader;")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
jobject _c = cocos2d::JniHelper::getEnv()->CallObjectMethod(nativeactivityinstance,
|
||||
_getclassloaderMethod.methodID);
|
||||
|
||||
if (NULL == _c) {
|
||||
return false;
|
||||
}
|
||||
|
||||
JniMethodInfo _m;
|
||||
if (!JniHelper::getMethodInfo_DefaultClassLoader(_m,
|
||||
"java/lang/ClassLoader",
|
||||
"loadClass",
|
||||
"(Ljava/lang/String;)Ljava/lang/Class;")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
JniHelper::classloader = _c;
|
||||
JniHelper::loadclassMethod_methodID = _m.methodID;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool JniHelper::getStaticMethodInfo(JniMethodInfo &methodinfo,
|
||||
const char *className,
|
||||
const char *methodName,
|
||||
const char *paramCode) {
|
||||
if ((NULL == className) ||
|
||||
(NULL == methodName) ||
|
||||
(NULL == paramCode)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
JNIEnv *pEnv = JniHelper::getEnv();
|
||||
if (!pEnv) {
|
||||
LOGD("Failed to get JNIEnv");
|
||||
return false;
|
||||
}
|
||||
|
||||
ret = pEnv->FindClass(className);
|
||||
if (! ret)
|
||||
{
|
||||
LOGD("Failed to find class of %s", className);
|
||||
break;
|
||||
}
|
||||
} while (0);
|
||||
jclass classID = _getClassID(className);
|
||||
if (! classID) {
|
||||
LOGD("Failed to find class %s", className);
|
||||
return false;
|
||||
}
|
||||
|
||||
return ret;
|
||||
jmethodID methodID = pEnv->GetStaticMethodID(classID, methodName, paramCode);
|
||||
if (! methodID) {
|
||||
LOGD("Failed to find static method id of %s", methodName);
|
||||
return false;
|
||||
}
|
||||
|
||||
methodinfo.classID = classID;
|
||||
methodinfo.env = pEnv;
|
||||
methodinfo.methodID = methodID;
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool getStaticMethodInfo_(cocos2d::JniMethodInfo &methodinfo, const char *className, const char *methodName, const char *paramCode)
|
||||
{
|
||||
jmethodID methodID = 0;
|
||||
JNIEnv *pEnv = 0;
|
||||
bool bRet = false;
|
||||
bool JniHelper::getMethodInfo_DefaultClassLoader(JniMethodInfo &methodinfo,
|
||||
const char *className,
|
||||
const char *methodName,
|
||||
const char *paramCode) {
|
||||
if ((NULL == className) ||
|
||||
(NULL == methodName) ||
|
||||
(NULL == paramCode)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
do
|
||||
{
|
||||
if (! getEnv(&pEnv))
|
||||
{
|
||||
break;
|
||||
}
|
||||
JNIEnv *pEnv = JniHelper::getEnv();
|
||||
if (!pEnv) {
|
||||
return false;
|
||||
}
|
||||
|
||||
jclass classID = getClassID_(className, pEnv);
|
||||
jclass classID = pEnv->FindClass(className);
|
||||
if (! classID) {
|
||||
LOGD("Failed to find class %s", className);
|
||||
return false;
|
||||
}
|
||||
|
||||
methodID = pEnv->GetStaticMethodID(classID, methodName, paramCode);
|
||||
if (! methodID)
|
||||
{
|
||||
LOGD("Failed to find static method id of %s", methodName);
|
||||
break;
|
||||
}
|
||||
jmethodID methodID = pEnv->GetMethodID(classID, methodName, paramCode);
|
||||
if (! methodID) {
|
||||
LOGD("Failed to find method id of %s", methodName);
|
||||
return false;
|
||||
}
|
||||
|
||||
methodinfo.classID = classID;
|
||||
methodinfo.env = pEnv;
|
||||
methodinfo.methodID = methodID;
|
||||
methodinfo.classID = classID;
|
||||
methodinfo.env = pEnv;
|
||||
methodinfo.methodID = methodID;
|
||||
|
||||
bRet = true;
|
||||
} while (0);
|
||||
|
||||
return bRet;
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool getMethodInfo_(cocos2d::JniMethodInfo &methodinfo, const char *className, const char *methodName, const char *paramCode)
|
||||
{
|
||||
jmethodID methodID = 0;
|
||||
JNIEnv *pEnv = 0;
|
||||
bool bRet = false;
|
||||
bool JniHelper::getMethodInfo(JniMethodInfo &methodinfo,
|
||||
const char *className,
|
||||
const char *methodName,
|
||||
const char *paramCode) {
|
||||
if ((NULL == className) ||
|
||||
(NULL == methodName) ||
|
||||
(NULL == paramCode)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
do
|
||||
{
|
||||
if (! getEnv(&pEnv))
|
||||
{
|
||||
break;
|
||||
}
|
||||
JNIEnv *pEnv = JniHelper::getEnv();
|
||||
if (!pEnv) {
|
||||
return false;
|
||||
}
|
||||
|
||||
jclass classID = getClassID_(className, pEnv);
|
||||
jclass classID = _getClassID(className);
|
||||
if (! classID) {
|
||||
LOGD("Failed to find class %s", className);
|
||||
return false;
|
||||
}
|
||||
|
||||
methodID = pEnv->GetMethodID(classID, methodName, paramCode);
|
||||
if (! methodID)
|
||||
{
|
||||
LOGD("Failed to find method id of %s", methodName);
|
||||
break;
|
||||
}
|
||||
jmethodID methodID = pEnv->GetMethodID(classID, methodName, paramCode);
|
||||
if (! methodID) {
|
||||
LOGD("Failed to find method id of %s", methodName);
|
||||
return false;
|
||||
}
|
||||
|
||||
methodinfo.classID = classID;
|
||||
methodinfo.env = pEnv;
|
||||
methodinfo.methodID = methodID;
|
||||
methodinfo.classID = classID;
|
||||
methodinfo.env = pEnv;
|
||||
methodinfo.methodID = methodID;
|
||||
|
||||
bRet = true;
|
||||
} while (0);
|
||||
|
||||
return bRet;
|
||||
return true;
|
||||
}
|
||||
|
||||
static string jstring2string_(jstring jstr)
|
||||
{
|
||||
if (jstr == NULL)
|
||||
{
|
||||
std::string JniHelper::jstring2string(jstring jstr) {
|
||||
if (jstr == NULL) {
|
||||
return "";
|
||||
}
|
||||
|
||||
JNIEnv *env = 0;
|
||||
|
||||
if (! getEnv(&env))
|
||||
{
|
||||
return 0;
|
||||
JNIEnv *pEnv = JniHelper::getEnv();
|
||||
if (!env) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
const char* chars = env->GetStringUTFChars(jstr, NULL);
|
||||
string ret(chars);
|
||||
std::string ret(chars);
|
||||
env->ReleaseStringUTFChars(jstr, chars);
|
||||
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
|
||||
NS_CC_BEGIN
|
||||
|
||||
JavaVM* JniHelper::_psJavaVM = NULL;
|
||||
|
||||
JavaVM* JniHelper::getJavaVM()
|
||||
{
|
||||
return _psJavaVM;
|
||||
}
|
||||
|
||||
void JniHelper::setJavaVM(JavaVM *javaVM)
|
||||
{
|
||||
_psJavaVM = javaVM;
|
||||
}
|
||||
|
||||
jclass JniHelper::getClassID(const char *className, JNIEnv *env)
|
||||
{
|
||||
return getClassID_(className, env);
|
||||
}
|
||||
|
||||
bool JniHelper::getStaticMethodInfo(JniMethodInfo &methodinfo, const char *className, const char *methodName, const char *paramCode)
|
||||
{
|
||||
return getStaticMethodInfo_(methodinfo, className, methodName, paramCode);
|
||||
}
|
||||
|
||||
bool JniHelper::getMethodInfo(JniMethodInfo &methodinfo, const char *className, const char *methodName, const char *paramCode)
|
||||
{
|
||||
return getMethodInfo_(methodinfo, className, methodName, paramCode);
|
||||
}
|
||||
|
||||
string JniHelper::jstring2string(jstring str)
|
||||
{
|
||||
return jstring2string_(str);
|
||||
}
|
||||
|
||||
NS_CC_END
|
||||
} //namespace cocos2d
|
||||
|
|
|
@ -40,15 +40,35 @@ typedef struct JniMethodInfo_
|
|||
class CC_DLL JniHelper
|
||||
{
|
||||
public:
|
||||
static JavaVM* getJavaVM();
|
||||
static void setJavaVM(JavaVM *javaVM);
|
||||
static jclass getClassID(const char *className, JNIEnv *env=0);
|
||||
static bool getStaticMethodInfo(JniMethodInfo &methodinfo, const char *className, const char *methodName, const char *paramCode);
|
||||
static bool getMethodInfo(JniMethodInfo &methodinfo, const char *className, const char *methodName, const char *paramCode);
|
||||
static JavaVM* getJavaVM();
|
||||
static JNIEnv* getEnv();
|
||||
|
||||
static bool setClassLoaderFrom(jobject nativeActivityInstance);
|
||||
static bool getStaticMethodInfo(JniMethodInfo &methodinfo,
|
||||
const char *className,
|
||||
const char *methodName,
|
||||
const char *paramCode);
|
||||
static bool getMethodInfo(JniMethodInfo &methodinfo,
|
||||
const char *className,
|
||||
const char *methodName,
|
||||
const char *paramCode);
|
||||
|
||||
static std::string jstring2string(jstring str);
|
||||
|
||||
static jmethodID loadclassMethod_methodID;
|
||||
static jobject classloader;
|
||||
|
||||
private:
|
||||
static JavaVM *_psJavaVM;
|
||||
static bool cacheEnv(JavaVM* jvm);
|
||||
|
||||
static bool getMethodInfo_DefaultClassLoader(JniMethodInfo &methodinfo,
|
||||
const char *className,
|
||||
const char *methodName,
|
||||
const char *paramCode);
|
||||
|
||||
static JavaVM* _psJavaVM;
|
||||
static JNIEnv* env;
|
||||
};
|
||||
|
||||
NS_CC_END
|
||||
|
|
|
@ -0,0 +1,558 @@
|
|||
#include "nativeactivity.h"
|
||||
|
||||
#include <jni.h>
|
||||
#include <errno.h>
|
||||
|
||||
#include <EGL/egl.h>
|
||||
#include <GLES/gl.h>
|
||||
|
||||
#include <android/sensor.h>
|
||||
#include <android/log.h>
|
||||
#include <android_native_app_glue.h>
|
||||
|
||||
#include <pthread.h>
|
||||
|
||||
#include "CCDirector.h"
|
||||
#include "CCApplication.h"
|
||||
#include "CCEventType.h"
|
||||
#include "support/CCNotificationCenter.h"
|
||||
#include "CCFileUtilsAndroid.h"
|
||||
#include "CCAccelerometer.h"
|
||||
#include "jni/JniHelper.h"
|
||||
|
||||
#include "CCEGLView.h"
|
||||
#include "draw_nodes/CCDrawingPrimitives.h"
|
||||
#include "shaders/CCShaderCache.h"
|
||||
#include "textures/CCTextureCache.h"
|
||||
|
||||
#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "cocos2dx/nativeactivity.cpp", __VA_ARGS__))
|
||||
#define LOGW(...) ((void)__android_log_print(ANDROID_LOG_WARN, "cocos2dx/nativeactivity.cpp", __VA_ARGS__))
|
||||
|
||||
#define LOG_RENDER_DEBUG(...)
|
||||
// #define LOG_RENDER_DEBUG(...) ((void)__android_log_print(ANDROID_LOG_INFO, "cocos2dx/nativeactivity.cpp", __VA_ARGS__))
|
||||
|
||||
#define LOG_EVENTS_DEBUG(...)
|
||||
// #define LOG_EVENTS_DEBUG(...) ((void)__android_log_print(ANDROID_LOG_INFO, "cocos2dx/nativeactivity.cpp", __VA_ARGS__))
|
||||
|
||||
void cocos_android_app_init(void);
|
||||
|
||||
/**
|
||||
* Our saved state data.
|
||||
*/
|
||||
struct saved_state {
|
||||
float angle;
|
||||
int32_t x;
|
||||
int32_t y;
|
||||
};
|
||||
|
||||
/**
|
||||
* Shared state for our app.
|
||||
*/
|
||||
struct engine {
|
||||
struct android_app* app;
|
||||
|
||||
ASensorManager* sensorManager;
|
||||
const ASensor* accelerometerSensor;
|
||||
ASensorEventQueue* sensorEventQueue;
|
||||
|
||||
int animating;
|
||||
EGLDisplay display;
|
||||
EGLSurface surface;
|
||||
EGLContext context;
|
||||
int32_t width;
|
||||
int32_t height;
|
||||
struct saved_state state;
|
||||
};
|
||||
|
||||
static struct engine engine;
|
||||
|
||||
typedef struct cocos_dimensions {
|
||||
int w;
|
||||
int h;
|
||||
} cocos_dimensions;
|
||||
|
||||
static void cocos_init(cocos_dimensions d, AAssetManager* assetmanager) {
|
||||
LOGI("cocos_init(...)");
|
||||
pthread_t thisthread = pthread_self();
|
||||
LOGI("pthread_self() = %X", thisthread);
|
||||
|
||||
cocos2d::FileUtilsAndroid::setassetmanager(assetmanager);
|
||||
|
||||
if (!cocos2d::Director::getInstance()->getOpenGLView())
|
||||
{
|
||||
cocos2d::EGLView *view = cocos2d::EGLView::getInstance();
|
||||
view->setFrameSize(d.w, d.h);
|
||||
|
||||
cocos_android_app_init();
|
||||
|
||||
cocos2d::Application::getInstance()->run();
|
||||
}
|
||||
else
|
||||
{
|
||||
cocos2d::GL::invalidateStateCache();
|
||||
cocos2d::ShaderCache::getInstance()->reloadDefaultShaders();
|
||||
cocos2d::DrawPrimitives::init();
|
||||
cocos2d::TextureCache::reloadAllTextures();
|
||||
cocos2d::NotificationCenter::getInstance()->postNotification(EVNET_COME_TO_FOREGROUND, NULL);
|
||||
cocos2d::Director::getInstance()->setGLDefaultValues();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize an EGL context for the current display.
|
||||
*/
|
||||
static cocos_dimensions engine_init_display(struct engine* engine) {
|
||||
cocos_dimensions r;
|
||||
r.w = -1;
|
||||
r.h = -1;
|
||||
|
||||
// initialize OpenGL ES and EGL
|
||||
|
||||
/*
|
||||
* Here specify the attributes of the desired configuration.
|
||||
* Below, we select an EGLConfig with at least 8 bits per color
|
||||
* component compatible with on-screen windows
|
||||
*/
|
||||
const EGLint attribs[] = {
|
||||
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
|
||||
EGL_BLUE_SIZE, 5,
|
||||
EGL_GREEN_SIZE, 6,
|
||||
EGL_RED_SIZE, 5,
|
||||
EGL_DEPTH_SIZE, 16,
|
||||
EGL_STENCIL_SIZE, 8,
|
||||
EGL_NONE
|
||||
};
|
||||
EGLint w, h, dummy, format;
|
||||
EGLint numConfigs;
|
||||
EGLConfig config;
|
||||
EGLSurface surface;
|
||||
EGLContext context;
|
||||
|
||||
EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
|
||||
|
||||
eglInitialize(display, 0, 0);
|
||||
|
||||
/* Here, the application chooses the configuration it desires. In this
|
||||
* sample, we have a very simplified selection process, where we pick
|
||||
* the first EGLConfig that matches our criteria */
|
||||
eglChooseConfig(display, attribs, &config, 1, &numConfigs);
|
||||
|
||||
/* EGL_NATIVE_VISUAL_ID is an attribute of the EGLConfig that is
|
||||
* guaranteed to be accepted by ANativeWindow_setBuffersGeometry().
|
||||
* As soon as we picked a EGLConfig, we can safely reconfigure the
|
||||
* ANativeWindow buffers to match, using EGL_NATIVE_VISUAL_ID. */
|
||||
eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format);
|
||||
|
||||
ANativeWindow_setBuffersGeometry(engine->app->window, 0, 0, format);
|
||||
|
||||
surface = eglCreateWindowSurface(display, config, engine->app->window, NULL);
|
||||
|
||||
const EGLint eglContextAttrs[] =
|
||||
{
|
||||
EGL_CONTEXT_CLIENT_VERSION, 2,
|
||||
EGL_NONE
|
||||
};
|
||||
|
||||
context = eglCreateContext(display, config, NULL, eglContextAttrs);
|
||||
|
||||
if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE) {
|
||||
LOGW("Unable to eglMakeCurrent");
|
||||
return r;
|
||||
}
|
||||
|
||||
eglQuerySurface(display, surface, EGL_WIDTH, &w);
|
||||
eglQuerySurface(display, surface, EGL_HEIGHT, &h);
|
||||
|
||||
engine->display = display;
|
||||
engine->context = context;
|
||||
engine->surface = surface;
|
||||
engine->width = w;
|
||||
engine->height = h;
|
||||
engine->state.angle = 0;
|
||||
|
||||
// Initialize GL state.
|
||||
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST);
|
||||
glEnable(GL_CULL_FACE);
|
||||
glShadeModel(GL_SMOOTH);
|
||||
glDisable(GL_DEPTH_TEST);
|
||||
|
||||
r.w = w;
|
||||
r.h = h;
|
||||
|
||||
return r;
|
||||
}
|
||||
|
||||
/**
|
||||
* Just the current frame in the display.
|
||||
*/
|
||||
static void engine_draw_frame(struct engine* engine) {
|
||||
LOG_RENDER_DEBUG("engine_draw_frame(...)");
|
||||
pthread_t thisthread = pthread_self();
|
||||
LOG_RENDER_DEBUG("pthread_self() = %X", thisthread);
|
||||
|
||||
if (engine->display == NULL) {
|
||||
// No display.
|
||||
LOGW("engine_draw_frame : No display.");
|
||||
return;
|
||||
}
|
||||
|
||||
cocos2d::Director::getInstance()->mainLoop();
|
||||
LOG_RENDER_DEBUG("engine_draw_frame : just called cocos' mainLoop()");
|
||||
|
||||
/* // Just fill the screen with a color. */
|
||||
/* glClearColor(((float)engine->state.x)/engine->width, engine->state.angle, */
|
||||
/* ((float)engine->state.y)/engine->height, 1); */
|
||||
/* glClear(GL_COLOR_BUFFER_BIT); */
|
||||
|
||||
eglSwapBuffers(engine->display, engine->surface);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tear down the EGL context currently associated with the display.
|
||||
*/
|
||||
static void engine_term_display(struct engine* engine) {
|
||||
if (engine->display != EGL_NO_DISPLAY) {
|
||||
eglMakeCurrent(engine->display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
|
||||
if (engine->context != EGL_NO_CONTEXT) {
|
||||
eglDestroyContext(engine->display, engine->context);
|
||||
}
|
||||
if (engine->surface != EGL_NO_SURFACE) {
|
||||
eglDestroySurface(engine->display, engine->surface);
|
||||
}
|
||||
eglTerminate(engine->display);
|
||||
}
|
||||
engine->animating = 0;
|
||||
engine->display = EGL_NO_DISPLAY;
|
||||
engine->context = EGL_NO_CONTEXT;
|
||||
engine->surface = EGL_NO_SURFACE;
|
||||
}
|
||||
|
||||
/*
|
||||
* Get X, Y positions and ID's for all pointers
|
||||
*/
|
||||
static void getTouchPos(AInputEvent *event, int ids[], float xs[], float ys[]) {
|
||||
int pointerCount = AMotionEvent_getPointerCount(event);
|
||||
for(int i = 0; i < pointerCount; ++i) {
|
||||
ids[i] = AMotionEvent_getPointerId(event, i);
|
||||
xs[i] = AMotionEvent_getX(event, i);
|
||||
ys[i] = AMotionEvent_getY(event, i);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Handle Touch Inputs
|
||||
*/
|
||||
static int32_t handle_touch_input(AInputEvent *event) {
|
||||
|
||||
pthread_t thisthread = pthread_self();
|
||||
LOG_EVENTS_DEBUG("handle_touch_input(%X), pthread_self() = %X", event, thisthread);
|
||||
|
||||
switch(AMotionEvent_getAction(event) &
|
||||
AMOTION_EVENT_ACTION_MASK) {
|
||||
|
||||
case AMOTION_EVENT_ACTION_DOWN:
|
||||
{
|
||||
LOG_EVENTS_DEBUG("AMOTION_EVENT_ACTION_DOWN");
|
||||
int pointerId = AMotionEvent_getPointerId(event, 0);
|
||||
float xP = AMotionEvent_getX(event,0);
|
||||
float yP = AMotionEvent_getY(event,0);
|
||||
|
||||
LOG_EVENTS_DEBUG("Event: Action DOWN x=%f y=%f pointerID=%d\n",
|
||||
xP, yP, pointerId);
|
||||
int pId = pointerId;
|
||||
float x = xP;
|
||||
float y = yP;
|
||||
|
||||
cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesBegin(1, &pId, &x, &y);
|
||||
return 1;
|
||||
}
|
||||
break;
|
||||
|
||||
case AMOTION_EVENT_ACTION_POINTER_DOWN:
|
||||
{
|
||||
LOG_EVENTS_DEBUG("AMOTION_EVENT_ACTION_POINTER_DOWN");
|
||||
int pointerIndex = AMotionEvent_getAction(event) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
|
||||
int pointerId = AMotionEvent_getPointerId(event, pointerIndex);
|
||||
float xP = AMotionEvent_getX(event,pointerIndex);
|
||||
float yP = AMotionEvent_getY(event,pointerIndex);
|
||||
|
||||
LOG_EVENTS_DEBUG("Event: Action POINTER DOWN x=%f y=%f pointerID=%d\n",
|
||||
xP, yP, pointerId);
|
||||
int pId = pointerId;
|
||||
float x = xP;
|
||||
float y = yP;
|
||||
|
||||
cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesBegin(1, &pId, &x, &y);
|
||||
return 1;
|
||||
}
|
||||
break;
|
||||
|
||||
case AMOTION_EVENT_ACTION_MOVE:
|
||||
{
|
||||
LOG_EVENTS_DEBUG("AMOTION_EVENT_ACTION_MOVE");
|
||||
int pointerCount = AMotionEvent_getPointerCount(event);
|
||||
int ids[pointerCount];
|
||||
float xs[pointerCount], ys[pointerCount];
|
||||
getTouchPos(event, ids, xs, ys);
|
||||
cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesMove(pointerCount, ids, xs, ys);
|
||||
return 1;
|
||||
}
|
||||
break;
|
||||
|
||||
case AMOTION_EVENT_ACTION_UP:
|
||||
{
|
||||
LOG_EVENTS_DEBUG("AMOTION_EVENT_ACTION_UP");
|
||||
int pointerId = AMotionEvent_getPointerId(event, 0);
|
||||
float xP = AMotionEvent_getX(event,0);
|
||||
float yP = AMotionEvent_getY(event,0);
|
||||
LOG_EVENTS_DEBUG("Event: Action UP x=%f y=%f pointerID=%d\n",
|
||||
xP, yP, pointerId);
|
||||
int pId = pointerId;
|
||||
float x = xP;
|
||||
float y = yP;
|
||||
|
||||
cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesEnd(1, &pId, &x, &y);
|
||||
return 1;
|
||||
}
|
||||
break;
|
||||
|
||||
case AMOTION_EVENT_ACTION_POINTER_UP:
|
||||
{
|
||||
LOG_EVENTS_DEBUG("AMOTION_EVENT_ACTION_POINTER_UP");
|
||||
int pointerIndex = AMotionEvent_getAction(event) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
|
||||
int pointerId = AMotionEvent_getPointerId(event, pointerIndex);
|
||||
float xP = AMotionEvent_getX(event,pointerIndex);
|
||||
float yP = AMotionEvent_getY(event,pointerIndex);
|
||||
LOG_EVENTS_DEBUG("Event: Action POINTER UP x=%f y=%f pointerID=%d\n",
|
||||
xP, yP, pointerIndex);
|
||||
int pId = pointerId;
|
||||
float x = xP;
|
||||
float y = yP;
|
||||
|
||||
cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesEnd(1, &pId, &x, &y);
|
||||
return 1;
|
||||
}
|
||||
break;
|
||||
|
||||
case AMOTION_EVENT_ACTION_CANCEL:
|
||||
{
|
||||
LOG_EVENTS_DEBUG("AMOTION_EVENT_ACTION_CANCEL");
|
||||
int pointerCount = AMotionEvent_getPointerCount(event);
|
||||
int ids[pointerCount];
|
||||
float xs[pointerCount], ys[pointerCount];
|
||||
getTouchPos(event, ids, xs, ys);
|
||||
cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesCancel(pointerCount, ids, xs, ys);
|
||||
return 1;
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
LOG_EVENTS_DEBUG("handle_touch_input() default case.... NOT HANDLE");
|
||||
return 0;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process the next input event.
|
||||
*/
|
||||
static int32_t engine_handle_input(struct android_app* app, AInputEvent* event) {
|
||||
|
||||
pthread_t thisthread = pthread_self();
|
||||
LOG_EVENTS_DEBUG("engine_handle_input(%X, %X), pthread_self() = %X", app, event, thisthread);
|
||||
|
||||
struct engine* engine = (struct engine*)app->userData;
|
||||
if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_MOTION) {
|
||||
engine->animating = 1;
|
||||
engine->state.x = AMotionEvent_getX(event, 0);
|
||||
engine->state.y = AMotionEvent_getY(event, 0);
|
||||
|
||||
return handle_touch_input(event);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
void enableAccelerometer(void) {
|
||||
LOGI("enableAccelerometer()");
|
||||
|
||||
if (engine.accelerometerSensor != NULL) {
|
||||
ASensorEventQueue_enableSensor(engine.sensorEventQueue,
|
||||
engine.accelerometerSensor);
|
||||
|
||||
// Set a default sample rate
|
||||
// We'd like to get 60 events per second (in us).
|
||||
ASensorEventQueue_setEventRate(engine.sensorEventQueue,
|
||||
engine.accelerometerSensor, (1000L/60)*1000);
|
||||
}
|
||||
}
|
||||
|
||||
void disableAccelerometer(void) {
|
||||
LOGI("disableAccelerometer()");
|
||||
|
||||
if (engine.accelerometerSensor != NULL) {
|
||||
ASensorEventQueue_disableSensor(engine.sensorEventQueue,
|
||||
engine.accelerometerSensor);
|
||||
}
|
||||
}
|
||||
|
||||
void setAccelerometerInterval(float interval) {
|
||||
LOGI("setAccelerometerInterval(%f)", interval);
|
||||
// We'd like to get 60 events per second (in us).
|
||||
ASensorEventQueue_setEventRate(engine.sensorEventQueue,
|
||||
engine.accelerometerSensor, interval * 1000000L);
|
||||
}
|
||||
|
||||
/**
|
||||
* Process the next main command.
|
||||
*/
|
||||
static void engine_handle_cmd(struct android_app* app, int32_t cmd) {
|
||||
struct engine* engine = (struct engine*)app->userData;
|
||||
switch (cmd) {
|
||||
case APP_CMD_SAVE_STATE:
|
||||
// The system has asked us to save our current state. Do so.
|
||||
engine->app->savedState = malloc(sizeof(struct saved_state));
|
||||
*((struct saved_state*)engine->app->savedState) = engine->state;
|
||||
engine->app->savedStateSize = sizeof(struct saved_state);
|
||||
break;
|
||||
case APP_CMD_INIT_WINDOW:
|
||||
// The window is being shown, get it ready.
|
||||
if (engine->app->window != NULL) {
|
||||
cocos_dimensions d = engine_init_display(engine);
|
||||
if ((d.w > 0) &&
|
||||
(d.h > 0)) {
|
||||
cocos2d::JniHelper::setJavaVM(app->activity->vm);
|
||||
cocos2d::JniHelper::setClassLoaderFrom(app->activity->clazz);
|
||||
|
||||
// call Cocos2dxHelper.init()
|
||||
cocos2d::JniMethodInfo ccxhelperInit;
|
||||
if (!cocos2d::JniHelper::getStaticMethodInfo(ccxhelperInit,
|
||||
"org/cocos2dx/lib/Cocos2dxHelper",
|
||||
"init",
|
||||
"(Landroid/app/Activity;)V")) {
|
||||
LOGI("cocos2d::JniHelper::getStaticMethodInfo(ccxhelperInit) FAILED");
|
||||
}
|
||||
ccxhelperInit.env->CallStaticVoidMethod(ccxhelperInit.classID,
|
||||
ccxhelperInit.methodID,
|
||||
app->activity->clazz);
|
||||
|
||||
cocos_init(d, app->activity->assetManager);
|
||||
}
|
||||
engine->animating = 1;
|
||||
engine_draw_frame(engine);
|
||||
}
|
||||
break;
|
||||
case APP_CMD_TERM_WINDOW:
|
||||
// The window is being hidden or closed, clean it up.
|
||||
engine_term_display(engine);
|
||||
break;
|
||||
case APP_CMD_GAINED_FOCUS:
|
||||
if (cocos2d::Director::getInstance()->getOpenGLView()) {
|
||||
cocos2d::Application::getInstance()->applicationWillEnterForeground();
|
||||
}
|
||||
|
||||
break;
|
||||
case APP_CMD_LOST_FOCUS:
|
||||
cocos2d::Application::getInstance()->applicationDidEnterBackground();
|
||||
cocos2d::NotificationCenter::getInstance()->postNotification(EVENT_COME_TO_BACKGROUND, NULL);
|
||||
|
||||
// Also stop animating.
|
||||
engine->animating = 0;
|
||||
engine_draw_frame(engine);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This is the main entry point of a native application that is using
|
||||
* android_native_app_glue. It runs in its own thread, with its own
|
||||
* event loop for receiving input events and doing other things.
|
||||
*/
|
||||
void android_main(struct android_app* state) {
|
||||
|
||||
// Make sure glue isn't stripped.
|
||||
app_dummy();
|
||||
|
||||
memset(&engine, 0, sizeof(engine));
|
||||
state->userData = &engine;
|
||||
state->onAppCmd = engine_handle_cmd;
|
||||
state->onInputEvent = engine_handle_input;
|
||||
engine.app = state;
|
||||
|
||||
// Prepare to monitor accelerometer
|
||||
engine.sensorManager = ASensorManager_getInstance();
|
||||
engine.accelerometerSensor = ASensorManager_getDefaultSensor(engine.sensorManager,
|
||||
ASENSOR_TYPE_ACCELEROMETER);
|
||||
engine.sensorEventQueue = ASensorManager_createEventQueue(engine.sensorManager,
|
||||
state->looper, LOOPER_ID_USER, NULL, NULL);
|
||||
|
||||
if (state->savedState != NULL) {
|
||||
// We are starting with a previous saved state; restore from it.
|
||||
engine.state = *(struct saved_state*)state->savedState;
|
||||
}
|
||||
|
||||
// loop waiting for stuff to do.
|
||||
|
||||
while (1) {
|
||||
// Read all pending events.
|
||||
int ident;
|
||||
int events;
|
||||
struct android_poll_source* source;
|
||||
|
||||
// If not animating, we will block forever waiting for events.
|
||||
// If animating, we loop until all events are read, then continue
|
||||
// to draw the next frame of animation.
|
||||
while ((ident=ALooper_pollAll(engine.animating ? 0 : -1, NULL, &events,
|
||||
(void**)&source)) >= 0) {
|
||||
|
||||
// Process this event.
|
||||
if (source != NULL) {
|
||||
source->process(state, source);
|
||||
}
|
||||
|
||||
// If a sensor has data, process it now.
|
||||
if (ident == LOOPER_ID_USER) {
|
||||
if (engine.accelerometerSensor != NULL) {
|
||||
ASensorEvent event;
|
||||
while (ASensorEventQueue_getEvents(engine.sensorEventQueue,
|
||||
&event, 1) > 0) {
|
||||
|
||||
cocos2d::Director* pDirector = cocos2d::Director::getInstance();
|
||||
pDirector->getAccelerometer()->update(event.acceleration.x,
|
||||
event.acceleration.y,
|
||||
event.acceleration.z,
|
||||
0);
|
||||
|
||||
LOG_EVENTS_DEBUG("accelerometer: x=%f y=%f z=%f",
|
||||
event.acceleration.x, event.acceleration.y,
|
||||
event.acceleration.z);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check if we are exiting.
|
||||
if (state->destroyRequested != 0) {
|
||||
engine_term_display(&engine);
|
||||
|
||||
memset(&engine, 0, sizeof(engine));
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (engine.animating) {
|
||||
// Done with events; draw next animation frame.
|
||||
engine.state.angle += .01f;
|
||||
if (engine.state.angle > 1) {
|
||||
engine.state.angle = 0;
|
||||
}
|
||||
|
||||
// Drawing is throttled to the screen update rate, so there
|
||||
// is no need to do timing here.
|
||||
LOG_RENDER_DEBUG("android_main : engine.animating");
|
||||
engine_draw_frame(&engine);
|
||||
} else {
|
||||
LOG_RENDER_DEBUG("android_main : !engine.animating");
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,12 @@
|
|||
#ifndef __COCOSNATIVEACTIVITY_H__
|
||||
#define __COCOSNATIVEACTIVITY_H__
|
||||
|
||||
/**
|
||||
* This is the interface to the Android native activity
|
||||
*/
|
||||
|
||||
void enableAccelerometer(void);
|
||||
void disableAccelerometer(void);
|
||||
void setAccelerometerInterval(float interval);
|
||||
|
||||
#endif // __COCOSNATIVEACTIVITY_H__
|
|
@ -379,7 +379,7 @@ bool Image::initWithStringShadowStroke(
|
|||
return true;
|
||||
}
|
||||
|
||||
bool Image::iosSaveToFile(const char *pszFilePath, bool bIsToRGB)
|
||||
bool Image::saveToFile(const char *pszFilePath, bool bIsToRGB)
|
||||
{
|
||||
bool saveToPNG = false;
|
||||
bool needToCopyPixels = false;
|
||||
|
|
|
@ -28,12 +28,12 @@ NS_CC_BEGIN
|
|||
|
||||
Thread::~Thread()
|
||||
{
|
||||
[(id)_autoreasePool release];
|
||||
[(id)_autoReleasePool release];
|
||||
}
|
||||
|
||||
void Thread::createAutoreleasePool()
|
||||
{
|
||||
_autoreasePool = [[NSAutoreleasePool alloc] init];
|
||||
_autoReleasePool = [[NSAutoreleasePool alloc] init];
|
||||
}
|
||||
|
||||
NS_CC_END
|
||||
|
|
|
@ -53,6 +53,7 @@ struct LineBreakLine {
|
|||
};
|
||||
|
||||
NS_CC_BEGIN
|
||||
|
||||
class BitmapDC
|
||||
{
|
||||
public:
|
||||
|
|
|
@ -28,12 +28,12 @@ NS_CC_BEGIN
|
|||
|
||||
Thread::~Thread()
|
||||
{
|
||||
[(id)_autoreasePool release];
|
||||
[(id)_autoReleasePool release];
|
||||
}
|
||||
|
||||
void Thread::createAutoreleasePool()
|
||||
{
|
||||
_autoreasePool = [[NSAutoreleasePool alloc] init];
|
||||
_autoReleasePool = [[NSAutoreleasePool alloc] init];
|
||||
}
|
||||
|
||||
NS_CC_END
|
||||
|
|
|
@ -0,0 +1,8 @@
|
|||
LOCAL_PATH := $(call my-dir)
|
||||
|
||||
include $(CLEAR_VARS)
|
||||
LOCAL_MODULE := cocos_freetype2_static
|
||||
LOCAL_MODULE_FILENAME := freetype2
|
||||
LOCAL_SRC_FILES := libs/$(TARGET_ARCH_ABI)/libfreetype.a
|
||||
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/include $(LOCAL_PATH)/include/freetype2
|
||||
include $(PREBUILT_STATIC_LIBRARY)
|
|
@ -0,0 +1,627 @@
|
|||
/* ftconfig.h. Generated from ftconfig.in by configure. */
|
||||
/***************************************************************************/
|
||||
/* */
|
||||
/* ftconfig.in */
|
||||
/* */
|
||||
/* UNIX-specific configuration file (specification only). */
|
||||
/* */
|
||||
/* Copyright 1996-2004, 2006-2009, 2011, 2013 by */
|
||||
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
|
||||
/* */
|
||||
/* This file is part of the FreeType project, and may only be used, */
|
||||
/* modified, and distributed under the terms of the FreeType project */
|
||||
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
|
||||
/* this file you indicate that you have read the license and */
|
||||
/* understand and accept it fully. */
|
||||
/* */
|
||||
/***************************************************************************/
|
||||
|
||||
|
||||
/*************************************************************************/
|
||||
/* */
|
||||
/* This header file contains a number of macro definitions that are used */
|
||||
/* by the rest of the engine. Most of the macros here are automatically */
|
||||
/* determined at compile time, and you should not need to change it to */
|
||||
/* port FreeType, except to compile the library with a non-ANSI */
|
||||
/* compiler. */
|
||||
/* */
|
||||
/* Note however that if some specific modifications are needed, we */
|
||||
/* advise you to place a modified copy in your build directory. */
|
||||
/* */
|
||||
/* The build directory is usually `freetype/builds/<system>', and */
|
||||
/* contains system-specific files that are always included first when */
|
||||
/* building the library. */
|
||||
/* */
|
||||
/*************************************************************************/
|
||||
|
||||
|
||||
#ifndef __FTCONFIG_H__
|
||||
#define __FTCONFIG_H__
|
||||
|
||||
#include <ft2build.h>
|
||||
#include FT_CONFIG_OPTIONS_H
|
||||
#include FT_CONFIG_STANDARD_LIBRARY_H
|
||||
|
||||
|
||||
FT_BEGIN_HEADER
|
||||
|
||||
|
||||
/*************************************************************************/
|
||||
/* */
|
||||
/* PLATFORM-SPECIFIC CONFIGURATION MACROS */
|
||||
/* */
|
||||
/* These macros can be toggled to suit a specific system. The current */
|
||||
/* ones are defaults used to compile FreeType in an ANSI C environment */
|
||||
/* (16bit compilers are also supported). Copy this file to your own */
|
||||
/* `freetype/builds/<system>' directory, and edit it to port the engine. */
|
||||
/* */
|
||||
/*************************************************************************/
|
||||
|
||||
|
||||
#define HAVE_UNISTD_H 1
|
||||
#define HAVE_FCNTL_H 1
|
||||
#define HAVE_STDINT_H 1
|
||||
|
||||
|
||||
/* There are systems (like the Texas Instruments 'C54x) where a `char' */
|
||||
/* has 16 bits. ANSI C says that sizeof(char) is always 1. Since an */
|
||||
/* `int' has 16 bits also for this system, sizeof(int) gives 1 which */
|
||||
/* is probably unexpected. */
|
||||
/* */
|
||||
/* `CHAR_BIT' (defined in limits.h) gives the number of bits in a */
|
||||
/* `char' type. */
|
||||
|
||||
#ifndef FT_CHAR_BIT
|
||||
#define FT_CHAR_BIT CHAR_BIT
|
||||
#endif
|
||||
|
||||
|
||||
/* #undef FT_USE_AUTOCONF_SIZEOF_TYPES */
|
||||
#ifdef FT_USE_AUTOCONF_SIZEOF_TYPES
|
||||
|
||||
#define SIZEOF_INT 4
|
||||
#define SIZEOF_LONG 4
|
||||
#define FT_SIZEOF_INT SIZEOF_INT
|
||||
#define FT_SIZEOF_LONG SIZEOF_LONG
|
||||
|
||||
#else /* !FT_USE_AUTOCONF_SIZEOF_TYPES */
|
||||
|
||||
/* Following cpp computation of the bit length of int and long */
|
||||
/* is copied from default include/freetype/config/ftconfig.h. */
|
||||
/* If any improvement is required for this file, it should be */
|
||||
/* applied to the original header file for the builders that */
|
||||
/* does not use configure script. */
|
||||
|
||||
/* The size of an `int' type. */
|
||||
#if FT_UINT_MAX == 0xFFFFUL
|
||||
#define FT_SIZEOF_INT (16 / FT_CHAR_BIT)
|
||||
#elif FT_UINT_MAX == 0xFFFFFFFFUL
|
||||
#define FT_SIZEOF_INT (32 / FT_CHAR_BIT)
|
||||
#elif FT_UINT_MAX > 0xFFFFFFFFUL && FT_UINT_MAX == 0xFFFFFFFFFFFFFFFFUL
|
||||
#define FT_SIZEOF_INT (64 / FT_CHAR_BIT)
|
||||
#else
|
||||
#error "Unsupported size of `int' type!"
|
||||
#endif
|
||||
|
||||
/* The size of a `long' type. A five-byte `long' (as used e.g. on the */
|
||||
/* DM642) is recognized but avoided. */
|
||||
#if FT_ULONG_MAX == 0xFFFFFFFFUL
|
||||
#define FT_SIZEOF_LONG (32 / FT_CHAR_BIT)
|
||||
#elif FT_ULONG_MAX > 0xFFFFFFFFUL && FT_ULONG_MAX == 0xFFFFFFFFFFUL
|
||||
#define FT_SIZEOF_LONG (32 / FT_CHAR_BIT)
|
||||
#elif FT_ULONG_MAX > 0xFFFFFFFFUL && FT_ULONG_MAX == 0xFFFFFFFFFFFFFFFFUL
|
||||
#define FT_SIZEOF_LONG (64 / FT_CHAR_BIT)
|
||||
#else
|
||||
#error "Unsupported size of `long' type!"
|
||||
#endif
|
||||
|
||||
#endif /* !FT_USE_AUTOCONF_SIZEOF_TYPES */
|
||||
|
||||
|
||||
/* FT_UNUSED is a macro used to indicate that a given parameter is not */
|
||||
/* used -- this is only used to get rid of unpleasant compiler warnings */
|
||||
#ifndef FT_UNUSED
|
||||
#define FT_UNUSED( arg ) ( (arg) = (arg) )
|
||||
#endif
|
||||
|
||||
|
||||
/*************************************************************************/
|
||||
/* */
|
||||
/* AUTOMATIC CONFIGURATION MACROS */
|
||||
/* */
|
||||
/* These macros are computed from the ones defined above. Don't touch */
|
||||
/* their definition, unless you know precisely what you are doing. No */
|
||||
/* porter should need to mess with them. */
|
||||
/* */
|
||||
/*************************************************************************/
|
||||
|
||||
|
||||
/*************************************************************************/
|
||||
/* */
|
||||
/* Mac support */
|
||||
/* */
|
||||
/* This is the only necessary change, so it is defined here instead */
|
||||
/* providing a new configuration file. */
|
||||
/* */
|
||||
#if defined( __APPLE__ ) || ( defined( __MWERKS__ ) && defined( macintosh ) )
|
||||
/* no Carbon frameworks for 64bit 10.4.x */
|
||||
/* AvailabilityMacros.h is available since Mac OS X 10.2, */
|
||||
/* so guess the system version by maximum errno before inclusion */
|
||||
#include <errno.h>
|
||||
#ifdef ECANCELED /* defined since 10.2 */
|
||||
#include "AvailabilityMacros.h"
|
||||
#endif
|
||||
#if defined( __LP64__ ) && \
|
||||
( MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_4 )
|
||||
#undef FT_MACINTOSH
|
||||
#endif
|
||||
|
||||
#elif defined( __SC__ ) || defined( __MRC__ )
|
||||
/* Classic MacOS compilers */
|
||||
#include "ConditionalMacros.h"
|
||||
#if TARGET_OS_MAC
|
||||
#define FT_MACINTOSH 1
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
/* Fix compiler warning with sgi compiler */
|
||||
#if defined( __sgi ) && !defined( __GNUC__ )
|
||||
#if defined( _COMPILER_VERSION ) && ( _COMPILER_VERSION >= 730 )
|
||||
#pragma set woff 3505
|
||||
#endif
|
||||
#endif
|
||||
|
||||
|
||||
/*************************************************************************/
|
||||
/* */
|
||||
/* <Section> */
|
||||
/* basic_types */
|
||||
/* */
|
||||
/*************************************************************************/
|
||||
|
||||
|
||||
/*************************************************************************/
|
||||
/* */
|
||||
/* <Type> */
|
||||
/* FT_Int16 */
|
||||
/* */
|
||||
/* <Description> */
|
||||
/* A typedef for a 16bit signed integer type. */
|
||||
/* */
|
||||
typedef signed short FT_Int16;
|
||||
|
||||
|
||||
/*************************************************************************/
|
||||
/* */
|
||||
/* <Type> */
|
||||
/* FT_UInt16 */
|
||||
/* */
|
||||
/* <Description> */
|
||||
/* A typedef for a 16bit unsigned integer type. */
|
||||
/* */
|
||||
typedef unsigned short FT_UInt16;
|
||||
|
||||
/* */
|
||||
|
||||
|
||||
/* this #if 0 ... #endif clause is for documentation purposes */
|
||||
#if 0
|
||||
|
||||
/*************************************************************************/
|
||||
/* */
|
||||
/* <Type> */
|
||||
/* FT_Int32 */
|
||||
/* */
|
||||
/* <Description> */
|
||||
/* A typedef for a 32bit signed integer type. The size depends on */
|
||||
/* the configuration. */
|
||||
/* */
|
||||
typedef signed XXX FT_Int32;
|
||||
|
||||
|
||||
/*************************************************************************/
|
||||
/* */
|
||||
/* <Type> */
|
||||
/* FT_UInt32 */
|
||||
/* */
|
||||
/* A typedef for a 32bit unsigned integer type. The size depends on */
|
||||
/* the configuration. */
|
||||
/* */
|
||||
typedef unsigned XXX FT_UInt32;
|
||||
|
||||
|
||||
/*************************************************************************/
|
||||
/* */
|
||||
/* <Type> */
|
||||
/* FT_Int64 */
|
||||
/* */
|
||||
/* A typedef for a 64bit signed integer type. The size depends on */
|
||||
/* the configuration. Only defined if there is real 64bit support; */
|
||||
/* otherwise, it gets emulated with a structure (if necessary). */
|
||||
/* */
|
||||
typedef signed XXX FT_Int64;
|
||||
|
||||
|
||||
/*************************************************************************/
|
||||
/* */
|
||||
/* <Type> */
|
||||
/* FT_UInt64 */
|
||||
/* */
|
||||
/* A typedef for a 64bit unsigned integer type. The size depends on */
|
||||
/* the configuration. Only defined if there is real 64bit support; */
|
||||
/* otherwise, it gets emulated with a structure (if necessary). */
|
||||
/* */
|
||||
typedef unsigned XXX FT_UInt64;
|
||||
|
||||
/* */
|
||||
|
||||
#endif
|
||||
|
||||
#if FT_SIZEOF_INT == 4
|
||||
|
||||
typedef signed int FT_Int32;
|
||||
typedef unsigned int FT_UInt32;
|
||||
|
||||
#elif FT_SIZEOF_LONG == 4
|
||||
|
||||
typedef signed long FT_Int32;
|
||||
typedef unsigned long FT_UInt32;
|
||||
|
||||
#else
|
||||
#error "no 32bit type found -- please check your configuration files"
|
||||
#endif
|
||||
|
||||
|
||||
/* look up an integer type that is at least 32 bits */
|
||||
#if FT_SIZEOF_INT >= 4
|
||||
|
||||
typedef int FT_Fast;
|
||||
typedef unsigned int FT_UFast;
|
||||
|
||||
#elif FT_SIZEOF_LONG >= 4
|
||||
|
||||
typedef long FT_Fast;
|
||||
typedef unsigned long FT_UFast;
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
/* determine whether we have a 64-bit int type for platforms without */
|
||||
/* Autoconf */
|
||||
#if FT_SIZEOF_LONG == 8
|
||||
|
||||
/* FT_LONG64 must be defined if a 64-bit type is available */
|
||||
#define FT_LONG64
|
||||
#define FT_INT64 long
|
||||
|
||||
#elif defined( _MSC_VER ) && _MSC_VER >= 900 /* Visual C++ (and Intel C++) */
|
||||
|
||||
/* this compiler provides the __int64 type */
|
||||
#define FT_LONG64
|
||||
#define FT_INT64 __int64
|
||||
|
||||
#elif defined( __BORLANDC__ ) /* Borland C++ */
|
||||
|
||||
/* XXXX: We should probably check the value of __BORLANDC__ in order */
|
||||
/* to test the compiler version. */
|
||||
|
||||
/* this compiler provides the __int64 type */
|
||||
#define FT_LONG64
|
||||
#define FT_INT64 __int64
|
||||
|
||||
#elif defined( __WATCOMC__ ) /* Watcom C++ */
|
||||
|
||||
/* Watcom doesn't provide 64-bit data types */
|
||||
|
||||
#elif defined( __MWERKS__ ) /* Metrowerks CodeWarrior */
|
||||
|
||||
#define FT_LONG64
|
||||
#define FT_INT64 long long int
|
||||
|
||||
#elif defined( __GNUC__ )
|
||||
|
||||
/* GCC provides the `long long' type */
|
||||
#define FT_LONG64
|
||||
#define FT_INT64 long long int
|
||||
|
||||
#endif /* FT_SIZEOF_LONG == 8 */
|
||||
|
||||
|
||||
/*************************************************************************/
|
||||
/* */
|
||||
/* A 64-bit data type will create compilation problems if you compile */
|
||||
/* in strict ANSI mode. To avoid them, we disable its use if __STDC__ */
|
||||
/* is defined. You can however ignore this rule by defining the */
|
||||
/* FT_CONFIG_OPTION_FORCE_INT64 configuration macro. */
|
||||
/* */
|
||||
#if defined( FT_LONG64 ) && !defined( FT_CONFIG_OPTION_FORCE_INT64 )
|
||||
|
||||
#ifdef __STDC__
|
||||
|
||||
/* Undefine the 64-bit macros in strict ANSI compilation mode. */
|
||||
/* Since `#undef' doesn't survive in configuration header files */
|
||||
/* we use the postprocessing facility of AC_CONFIG_HEADERS to */
|
||||
/* replace the leading `/' with `#'. */
|
||||
#undef FT_LONG64
|
||||
#undef FT_INT64
|
||||
|
||||
#endif /* __STDC__ */
|
||||
|
||||
#endif /* FT_LONG64 && !FT_CONFIG_OPTION_FORCE_INT64 */
|
||||
|
||||
#ifdef FT_LONG64
|
||||
typedef FT_INT64 FT_Int64;
|
||||
typedef FT_UINT64 FT_UInt64;
|
||||
#endif
|
||||
|
||||
|
||||
#define FT_BEGIN_STMNT do {
|
||||
#define FT_END_STMNT } while ( 0 )
|
||||
#define FT_DUMMY_STMNT FT_BEGIN_STMNT FT_END_STMNT
|
||||
|
||||
|
||||
#ifndef FT_CONFIG_OPTION_NO_ASSEMBLER
|
||||
/* Provide assembler fragments for performance-critical functions. */
|
||||
/* These must be defined `static __inline__' with GCC. */
|
||||
|
||||
#if defined( __CC_ARM ) || defined( __ARMCC__ ) /* RVCT */
|
||||
#define FT_MULFIX_ASSEMBLER FT_MulFix_arm
|
||||
|
||||
/* documentation is in freetype.h */
|
||||
|
||||
static __inline FT_Int32
|
||||
FT_MulFix_arm( FT_Int32 a,
|
||||
FT_Int32 b )
|
||||
{
|
||||
register FT_Int32 t, t2;
|
||||
|
||||
|
||||
__asm
|
||||
{
|
||||
smull t2, t, b, a /* (lo=t2,hi=t) = a*b */
|
||||
mov a, t, asr #31 /* a = (hi >> 31) */
|
||||
add a, a, #0x8000 /* a += 0x8000 */
|
||||
adds t2, t2, a /* t2 += a */
|
||||
adc t, t, #0 /* t += carry */
|
||||
mov a, t2, lsr #16 /* a = t2 >> 16 */
|
||||
orr a, a, t, lsl #16 /* a |= t << 16 */
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
||||
#endif /* __CC_ARM || __ARMCC__ */
|
||||
|
||||
|
||||
#ifdef __GNUC__
|
||||
|
||||
#if defined( __arm__ ) && !defined( __thumb__ ) && \
|
||||
!( defined( __CC_ARM ) || defined( __ARMCC__ ) )
|
||||
#define FT_MULFIX_ASSEMBLER FT_MulFix_arm
|
||||
|
||||
/* documentation is in freetype.h */
|
||||
|
||||
static __inline__ FT_Int32
|
||||
FT_MulFix_arm( FT_Int32 a,
|
||||
FT_Int32 b )
|
||||
{
|
||||
register FT_Int32 t, t2;
|
||||
|
||||
|
||||
__asm__ __volatile__ (
|
||||
"smull %1, %2, %4, %3\n\t" /* (lo=%1,hi=%2) = a*b */
|
||||
"mov %0, %2, asr #31\n\t" /* %0 = (hi >> 31) */
|
||||
"add %0, %0, #0x8000\n\t" /* %0 += 0x8000 */
|
||||
"adds %1, %1, %0\n\t" /* %1 += %0 */
|
||||
"adc %2, %2, #0\n\t" /* %2 += carry */
|
||||
"mov %0, %1, lsr #16\n\t" /* %0 = %1 >> 16 */
|
||||
"orr %0, %0, %2, lsl #16\n\t" /* %0 |= %2 << 16 */
|
||||
: "=r"(a), "=&r"(t2), "=&r"(t)
|
||||
: "r"(a), "r"(b)
|
||||
: "cc" );
|
||||
return a;
|
||||
}
|
||||
|
||||
#endif /* __arm__ && !__thumb__ && !( __CC_ARM || __ARMCC__ ) */
|
||||
|
||||
#if defined( __i386__ )
|
||||
#define FT_MULFIX_ASSEMBLER FT_MulFix_i386
|
||||
|
||||
/* documentation is in freetype.h */
|
||||
|
||||
static __inline__ FT_Int32
|
||||
FT_MulFix_i386( FT_Int32 a,
|
||||
FT_Int32 b )
|
||||
{
|
||||
register FT_Int32 result;
|
||||
|
||||
|
||||
__asm__ __volatile__ (
|
||||
"imul %%edx\n"
|
||||
"movl %%edx, %%ecx\n"
|
||||
"sarl $31, %%ecx\n"
|
||||
"addl $0x8000, %%ecx\n"
|
||||
"addl %%ecx, %%eax\n"
|
||||
"adcl $0, %%edx\n"
|
||||
"shrl $16, %%eax\n"
|
||||
"shll $16, %%edx\n"
|
||||
"addl %%edx, %%eax\n"
|
||||
: "=a"(result), "=d"(b)
|
||||
: "a"(a), "d"(b)
|
||||
: "%ecx", "cc" );
|
||||
return result;
|
||||
}
|
||||
|
||||
#endif /* i386 */
|
||||
|
||||
#endif /* __GNUC__ */
|
||||
|
||||
|
||||
#ifdef _MSC_VER /* Visual C++ */
|
||||
|
||||
#ifdef _M_IX86
|
||||
|
||||
#define FT_MULFIX_ASSEMBLER FT_MulFix_i386
|
||||
|
||||
/* documentation is in freetype.h */
|
||||
|
||||
static __inline FT_Int32
|
||||
FT_MulFix_i386( FT_Int32 a,
|
||||
FT_Int32 b )
|
||||
{
|
||||
register FT_Int32 result;
|
||||
|
||||
__asm
|
||||
{
|
||||
mov eax, a
|
||||
mov edx, b
|
||||
imul edx
|
||||
mov ecx, edx
|
||||
sar ecx, 31
|
||||
add ecx, 8000h
|
||||
add eax, ecx
|
||||
adc edx, 0
|
||||
shr eax, 16
|
||||
shl edx, 16
|
||||
add eax, edx
|
||||
mov result, eax
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
#endif /* _M_IX86 */
|
||||
|
||||
#endif /* _MSC_VER */
|
||||
|
||||
#endif /* !FT_CONFIG_OPTION_NO_ASSEMBLER */
|
||||
|
||||
|
||||
#ifdef FT_CONFIG_OPTION_INLINE_MULFIX
|
||||
#ifdef FT_MULFIX_ASSEMBLER
|
||||
#define FT_MULFIX_INLINED FT_MULFIX_ASSEMBLER
|
||||
#endif
|
||||
#endif
|
||||
|
||||
|
||||
#ifdef FT_MAKE_OPTION_SINGLE_OBJECT
|
||||
|
||||
#define FT_LOCAL( x ) static x
|
||||
#define FT_LOCAL_DEF( x ) static x
|
||||
|
||||
#else
|
||||
|
||||
#ifdef __cplusplus
|
||||
#define FT_LOCAL( x ) extern "C" x
|
||||
#define FT_LOCAL_DEF( x ) extern "C" x
|
||||
#else
|
||||
#define FT_LOCAL( x ) extern x
|
||||
#define FT_LOCAL_DEF( x ) x
|
||||
#endif
|
||||
|
||||
#endif /* FT_MAKE_OPTION_SINGLE_OBJECT */
|
||||
|
||||
|
||||
#ifndef FT_BASE
|
||||
|
||||
#ifdef __cplusplus
|
||||
#define FT_BASE( x ) extern "C" x
|
||||
#else
|
||||
#define FT_BASE( x ) extern x
|
||||
#endif
|
||||
|
||||
#endif /* !FT_BASE */
|
||||
|
||||
|
||||
#ifndef FT_BASE_DEF
|
||||
|
||||
#ifdef __cplusplus
|
||||
#define FT_BASE_DEF( x ) x
|
||||
#else
|
||||
#define FT_BASE_DEF( x ) x
|
||||
#endif
|
||||
|
||||
#endif /* !FT_BASE_DEF */
|
||||
|
||||
|
||||
#ifndef FT_EXPORT
|
||||
|
||||
#ifdef __cplusplus
|
||||
#define FT_EXPORT( x ) extern "C" x
|
||||
#else
|
||||
#define FT_EXPORT( x ) extern x
|
||||
#endif
|
||||
|
||||
#endif /* !FT_EXPORT */
|
||||
|
||||
|
||||
#ifndef FT_EXPORT_DEF
|
||||
|
||||
#ifdef __cplusplus
|
||||
#define FT_EXPORT_DEF( x ) extern "C" x
|
||||
#else
|
||||
#define FT_EXPORT_DEF( x ) extern x
|
||||
#endif
|
||||
|
||||
#endif /* !FT_EXPORT_DEF */
|
||||
|
||||
|
||||
#ifndef FT_EXPORT_VAR
|
||||
|
||||
#ifdef __cplusplus
|
||||
#define FT_EXPORT_VAR( x ) extern "C" x
|
||||
#else
|
||||
#define FT_EXPORT_VAR( x ) extern x
|
||||
#endif
|
||||
|
||||
#endif /* !FT_EXPORT_VAR */
|
||||
|
||||
/* The following macros are needed to compile the library with a */
|
||||
/* C++ compiler and with 16bit compilers. */
|
||||
/* */
|
||||
|
||||
/* This is special. Within C++, you must specify `extern "C"' for */
|
||||
/* functions which are used via function pointers, and you also */
|
||||
/* must do that for structures which contain function pointers to */
|
||||
/* assure C linkage -- it's not possible to have (local) anonymous */
|
||||
/* functions which are accessed by (global) function pointers. */
|
||||
/* */
|
||||
/* */
|
||||
/* FT_CALLBACK_DEF is used to _define_ a callback function. */
|
||||
/* */
|
||||
/* FT_CALLBACK_TABLE is used to _declare_ a constant variable that */
|
||||
/* contains pointers to callback functions. */
|
||||
/* */
|
||||
/* FT_CALLBACK_TABLE_DEF is used to _define_ a constant variable */
|
||||
/* that contains pointers to callback functions. */
|
||||
/* */
|
||||
/* */
|
||||
/* Some 16bit compilers have to redefine these macros to insert */
|
||||
/* the infamous `_cdecl' or `__fastcall' declarations. */
|
||||
/* */
|
||||
#ifndef FT_CALLBACK_DEF
|
||||
#ifdef __cplusplus
|
||||
#define FT_CALLBACK_DEF( x ) extern "C" x
|
||||
#else
|
||||
#define FT_CALLBACK_DEF( x ) static x
|
||||
#endif
|
||||
#endif /* FT_CALLBACK_DEF */
|
||||
|
||||
#ifndef FT_CALLBACK_TABLE
|
||||
#ifdef __cplusplus
|
||||
#define FT_CALLBACK_TABLE extern "C"
|
||||
#define FT_CALLBACK_TABLE_DEF extern "C"
|
||||
#else
|
||||
#define FT_CALLBACK_TABLE extern
|
||||
#define FT_CALLBACK_TABLE_DEF /* nothing */
|
||||
#endif
|
||||
#endif /* FT_CALLBACK_TABLE */
|
||||
|
||||
|
||||
FT_END_HEADER
|
||||
|
||||
|
||||
#endif /* __FTCONFIG_H__ */
|
||||
|
||||
|
||||
/* END */
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue