Merge remote-tracking branch 'parent/gles20' into gles20

This commit is contained in:
Walzer 2012-06-28 10:49:23 +08:00
commit 5d0bcc2bc7
842 changed files with 35519 additions and 42526 deletions

8
.gitignore vendored
View File

@ -32,10 +32,12 @@ _ReSharper*/
libs/ libs/
bin/ bin/
obj/ obj/
gen/
assets/ assets/
.classpath #.classpath
.project #.project
.cproject #.cproject
local.properties
# Ignore files build by linux # Ignore files build by linux
*.o *.o

View File

@ -28,6 +28,7 @@ Developers:
Nicolas Gramlich (nicolasgramlich, Zynga) Nicolas Gramlich (nicolasgramlich, Zynga)
fixed CCDirector to use CCLabelBMFont instead of CCLabelTTF fixed CCDirector to use CCLabelBMFont instead of CCLabelTTF
added CCBReader (CCBI format)
Jianfeng Zhou (NetGragon Inc) Jianfeng Zhou (NetGragon Inc)
contributes CCListView and CCTextureWatcher. contributes CCListView and CCTextureWatcher.
@ -86,6 +87,9 @@ Developers:
jreitman jreitman
fix the bug of asynchronous loading resources for iOS fix the bug of asynchronous loading resources for iOS
Nat Weiss
Minor enhancements to the Cocos2D-X codebase and Android build scripts
Retired Core Developers: Retired Core Developers:
WenSheng Yang WenSheng Yang
Author of windows port, CCTextField, Author of windows port, CCTextField,

View File

@ -1,60 +1,60 @@
LOCAL_PATH := $(call my-dir) LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS) include $(CLEAR_VARS)
LOCAL_MODULE := box2d_static LOCAL_MODULE := box2d_static
LOCAL_MODULE_FILENAME := libbox2d LOCAL_MODULE_FILENAME := libbox2d
LOCAL_SRC_FILES := \ LOCAL_SRC_FILES := \
Collision/Shapes/b2ChainShape.cpp \ Collision/Shapes/b2ChainShape.cpp \
Collision/Shapes/b2CircleShape.cpp \ Collision/Shapes/b2CircleShape.cpp \
Collision/Shapes/b2EdgeShape.cpp \ Collision/Shapes/b2EdgeShape.cpp \
Collision/Shapes/b2PolygonShape.cpp \ Collision/Shapes/b2PolygonShape.cpp \
Collision/b2BroadPhase.cpp \ Collision/b2BroadPhase.cpp \
Collision/b2CollideCircle.cpp \ Collision/b2CollideCircle.cpp \
Collision/b2CollideEdge.cpp \ Collision/b2CollideEdge.cpp \
Collision/b2CollidePolygon.cpp \ Collision/b2CollidePolygon.cpp \
Collision/b2Collision.cpp \ Collision/b2Collision.cpp \
Collision/b2Distance.cpp \ Collision/b2Distance.cpp \
Collision/b2DynamicTree.cpp \ Collision/b2DynamicTree.cpp \
Collision/b2TimeOfImpact.cpp \ Collision/b2TimeOfImpact.cpp \
Common/b2BlockAllocator.cpp \ Common/b2BlockAllocator.cpp \
Common/b2Draw.cpp \ Common/b2Draw.cpp \
Common/b2Math.cpp \ Common/b2Math.cpp \
Common/b2Settings.cpp \ Common/b2Settings.cpp \
Common/b2StackAllocator.cpp \ Common/b2StackAllocator.cpp \
Common/b2Timer.cpp \ Common/b2Timer.cpp \
Dynamics/Contacts/b2ChainAndCircleContact.cpp \ Dynamics/Contacts/b2ChainAndCircleContact.cpp \
Dynamics/Contacts/b2ChainAndPolygonContact.cpp \ Dynamics/Contacts/b2ChainAndPolygonContact.cpp \
Dynamics/Contacts/b2CircleContact.cpp \ Dynamics/Contacts/b2CircleContact.cpp \
Dynamics/Contacts/b2Contact.cpp \ Dynamics/Contacts/b2Contact.cpp \
Dynamics/Contacts/b2ContactSolver.cpp \ Dynamics/Contacts/b2ContactSolver.cpp \
Dynamics/Contacts/b2EdgeAndCircleContact.cpp \ Dynamics/Contacts/b2EdgeAndCircleContact.cpp \
Dynamics/Contacts/b2EdgeAndPolygonContact.cpp \ Dynamics/Contacts/b2EdgeAndPolygonContact.cpp \
Dynamics/Contacts/b2PolygonAndCircleContact.cpp \ Dynamics/Contacts/b2PolygonAndCircleContact.cpp \
Dynamics/Contacts/b2PolygonContact.cpp \ Dynamics/Contacts/b2PolygonContact.cpp \
Dynamics/Joints/b2DistanceJoint.cpp \ Dynamics/Joints/b2DistanceJoint.cpp \
Dynamics/Joints/b2FrictionJoint.cpp \ Dynamics/Joints/b2FrictionJoint.cpp \
Dynamics/Joints/b2GearJoint.cpp \ Dynamics/Joints/b2GearJoint.cpp \
Dynamics/Joints/b2Joint.cpp \ Dynamics/Joints/b2Joint.cpp \
Dynamics/Joints/b2MouseJoint.cpp \ Dynamics/Joints/b2MouseJoint.cpp \
Dynamics/Joints/b2PrismaticJoint.cpp \ Dynamics/Joints/b2PrismaticJoint.cpp \
Dynamics/Joints/b2PulleyJoint.cpp \ Dynamics/Joints/b2PulleyJoint.cpp \
Dynamics/Joints/b2RevoluteJoint.cpp \ Dynamics/Joints/b2RevoluteJoint.cpp \
Dynamics/Joints/b2RopeJoint.cpp \ Dynamics/Joints/b2RopeJoint.cpp \
Dynamics/Joints/b2WeldJoint.cpp \ Dynamics/Joints/b2WeldJoint.cpp \
Dynamics/Joints/b2WheelJoint.cpp \ Dynamics/Joints/b2WheelJoint.cpp \
Dynamics/b2Body.cpp \ Dynamics/b2Body.cpp \
Dynamics/b2ContactManager.cpp \ Dynamics/b2ContactManager.cpp \
Dynamics/b2Fixture.cpp \ Dynamics/b2Fixture.cpp \
Dynamics/b2Island.cpp \ Dynamics/b2Island.cpp \
Dynamics/b2World.cpp \ Dynamics/b2World.cpp \
Dynamics/b2WorldCallbacks.cpp \ Dynamics/b2WorldCallbacks.cpp \
Rope/b2Rope.cpp Rope/b2Rope.cpp
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/.. LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/..
LOCAL_C_INCLUDES := $(LOCAL_PATH)/.. LOCAL_C_INCLUDES := $(LOCAL_PATH)/..
include $(BUILD_STATIC_LIBRARY) include $(BUILD_STATIC_LIBRARY)

View File

@ -21,7 +21,7 @@
OutputDirectory="$(SolutionDir)$(ConfigurationName).win32" OutputDirectory="$(SolutionDir)$(ConfigurationName).win32"
IntermediateDirectory="$(ConfigurationName).win32" IntermediateDirectory="$(ConfigurationName).win32"
ConfigurationType="4" ConfigurationType="4"
CharacterSet="2" CharacterSet="1"
> >
<Tool <Tool
Name="VCPreBuildEventTool" Name="VCPreBuildEventTool"
@ -85,7 +85,7 @@
OutputDirectory="$(SolutionDir)$(ConfigurationName).win32" OutputDirectory="$(SolutionDir)$(ConfigurationName).win32"
IntermediateDirectory="$(ConfigurationName).win32" IntermediateDirectory="$(ConfigurationName).win32"
ConfigurationType="4" ConfigurationType="4"
CharacterSet="2" CharacterSet="1"
> >
<Tool <Tool
Name="VCPreBuildEventTool" Name="VCPreBuildEventTool"

View File

@ -114,11 +114,11 @@
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType> <ConfigurationType>StaticLibrary</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet> <CharacterSet>Unicode</CharacterSet>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType> <ConfigurationType>StaticLibrary</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet> <CharacterSet>Unicode</CharacterSet>
</PropertyGroup> </PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings"> <ImportGroup Label="ExtensionSettings">

View File

@ -1,3 +1,90 @@
cocos2d-2.0-rc0a-x-2.0 @May.31 2012
[all platforms]
Bug #1094: fix a bug that nothing will be shown when using CCParticleBatchNode
Bug #1115: fix a bug that CCFileUtils::fullPathFromRelativePath() with resolution parameter return error value with empty string
Bug #1137: fix a memory leak in CCLabelBMFont and sync the implementation of CCLabelBMFont to gles20 branch
Bug #1138: fix a memory leak in CCTextureCache::addPVRImage.
Bug #1155: revert CCDirector singleton to original implementation
Bug #1157: fix a bug that nothing is shown in TMX Orthogonal Test
Bug #1158: fix a bug in CCParticleSystemQuad
Bug #1159: update "CallFuncND + auto remove" test demo
Bug #1160: rename 'CGFloat' to 'CCFloat'
Bug #1164: add the render mode which uses VBO without VAO in CCParticleSystemQuad
Bug #1165: merge pull request #842
Bug #1187: fix a bug that spanish(Buen día) cannot be shown completely in CCLabelBMFont unicode test
Bug #1189: CCLabelBMFont updateLabel() optimizations and fixes
Bug #1212: fix a bug that TMXBug787Test crash.
Bug #1217: fix a bug that EaseActions reverse broken
Bug #1232: fix a bug that CCLayerGradient::updateColor() assign wrong value to m_pSquareColors
Bug #1244: fix memory leak in CCParticleSystem::initWithDictionary()
Bug #1273: fix a bug that app will crash after clicking closed button in TextureCacheTest
Bug #1275: fix memory leaks in tests project
Bug #1277: implement CCToggleVisibility::copyWithZone()
Feature #1114: integrate CCControlExtension and implement corresponding tests
Feature #1180: synchronize CCConfiguration
Feature #1194: merge texturewatcher contributed by NetGragon
Feature #1205: add ccbreader and test case for CocosBuilder
Feature #1240: support TIFF format picture
Feature #1258: merge Rolando's testjs into gles20 branch
Refactor #1156: synchronize CCDirector
Refactor #1166: improve CCString and CCArray, optimize CCDictionary
Refactor #1176: change linebreak symbol to UNIX format ('\n'), replace 'tab' with four spaces
Refactor #1177: refactor platform
Refactor #1178: use macro NS_CC_BEGIN instead of "namespace cocos2d {", NS_CC_END instead of "}"
Refactor #1188: refactor directory structure
Refactor #1191: update templates for all platforms
Refactor #1198: optimize CCTextureCache::removeUnusedTextures()
Refactor #1203: remove CCFileUtils::setResource(const char* pszZipFileName) and SimpleAudioEngine::setResource
Refactor #1204: refactor AppDelegate::initInstance()
Refactor #1206: remove some unused files, only supports iOS, win32 and android
Refactor #1211: translate Chinese comments to English for CCTextureWatcher and CCListView
Refactor #1246: fix CCDirector using CCLabelBMFont instead of CCLabelTTF
Refactor #1252: add CCEGLViewProtocol::getFrameSize() method for getting the real screen size of device
Refactor #1253: add static method "purgeConfiguration" for CCConfiguration to avoid memory leak
[iOS]
Bug #1109: add parentheses to remove Xcode warnings
Bug #1230: fix a bug that Calculation of string width may be wrong on iOS
Bug #1266: fix a bug that CCTextureCahce::addImageAsync() don't work correctly on iOS
Feature #1095: IOS screen resolution support
[android]
Bug #1139: fix a bug that screen becomes black when backing from background
Bug #1140: fix a bug that ParticleTest crashed
Bug #1141: fix a bug that NodeTest crashed in StressTest1 and StressTest2
Bug #1142: fix a bug that TouchesTest crashed
Bug #1143: fix a bug that MenuTest crashed
Bug #1144: fix a bug that ParallaxTest crashed
Bug #1145: fix a bug that TileMap crashed
Bug #1146: fix a bug that IntervalTest crashed
Bug #1147: fix a bug that ChipmunkAccelTouchTest crashed
Bug #1148: fix a bug that LabelTest crashed
Bug #1149: fix a bug that SpriteTest crashed when go to second test case
Bug #1150: fix a bug that RenderTextureTest crashed at second test case
Bug #1151: fix a bug that Box2DTest crashed
Bug #1152: fix a bug that PerformanceTest crashed at 1, 2, 5 test cases
Bug #1185: fix a bug that when backing to foreground, will lost texture if it uses sprite batch node
Bug #1216: fix JNI memory leaks
Bug #1229: fix a bug that android port can not be compiled on ndk android-8 level
Bug #1236: fix a bug that JniHelper::jstring2string may crash when parameter is null
Bug #1237: fix a bug that line number message printed by CCAssert is wrong
Bug #1279: fix a bug that NodeNonOpaqueTest can't be shown correctly
Feature #1247: add profiler support for android
Feature #1265: build dynamic library of spidermonkey for Android, and implement testjs for android
Refactor #1179: popup a message box when invoking CCAssert() on Android
Refactor #1201: simplify the usage of writing Android.mk
[windows]
Bug #1215: fix a bug that Win32 retina cannot work
Bug #1251: add CocosBuilderTest to the test project for VS2008
Bug #1264: fix wrong string alignment when using utf-8 encoded text with CCLabelTTF
Bug #1268: fix a bug that Testjs will crash after clicking the close button on win32
Bug #1270: fix some warning on win32
Feature #1186: add console window for Win32 application, all debug message output to this console window
Feature #1263: build dynamic library of spidermonkey for win32, and add testjs project to solution
Refactor #1170: remove win32 template of wophone
[lua]
Refactor #1190: update lua binding to 2.0
Refactor #1220: using CCString::stringWithContentsOfFile to get string from lua script files
cocos2d-1.0.1-x-0.12.0 @ Mar.5 2012 cocos2d-1.0.1-x-0.12.0 @ Mar.5 2012
[all platforms] [all platforms]
Bug #925: rename HelloWorld/Resource to HelloWorld/Resources Bug #925: rename HelloWorld/Resource to HelloWorld/Resources

View File

@ -1,21 +1,20 @@
LOCAL_PATH := $(call my-dir) LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS) include $(CLEAR_VARS)
LOCAL_MODULE := cocosdenshion_static LOCAL_MODULE := cocosdenshion_static
LOCAL_MODULE_FILENAME := libcocosdenshion LOCAL_MODULE_FILENAME := libcocosdenshion
LOCAL_SRC_FILES := SimpleAudioEngine.cpp \ LOCAL_SRC_FILES := SimpleAudioEngine.cpp \
jni/SimpleAudioEngineJni.cpp jni/SimpleAudioEngineJni.cpp
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/../include LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/../include
LOCAL_C_INCLUDES := $(LOCAL_PATH)/../include \ LOCAL_C_INCLUDES := $(LOCAL_PATH)/../include \
$(LOCAL_PATH)/../../cocos2dx/include \ $(LOCAL_PATH)/../../cocos2dx \
$(LOCAL_PATH)/../../cocos2dx/platform \ $(LOCAL_PATH)/../../cocos2dx/include \
$(LOCAL_PATH)/../../cocos2dx/platform/android \ $(LOCAL_PATH)/../../cocos2dx/platform/android
$(LOCAL_PATH)/../../cocos2dx/platform/android/jni
LOCAL_LDLIBS := -llog
LOCAL_LDLIBS := -llog
include $(BUILD_STATIC_LIBRARY) include $(BUILD_STATIC_LIBRARY)

View File

@ -1,5 +1,5 @@
#include "SimpleAudioEngineJni.h" #include "SimpleAudioEngineJni.h"
#include "JniHelper.h" #include "platform/android/jni/JniHelper.h"
#include <android/log.h> #include <android/log.h>

View File

@ -98,6 +98,8 @@ typedef enum {
BOOL mute; BOOL mute;
BOOL enabled_; BOOL enabled_;
BOOL backgroundMusic; BOOL backgroundMusic;
// whether background music is paused
BOOL paused;
@public @public
BOOL systemPaused;//Used for auto resign handling BOOL systemPaused;//Used for auto resign handling
NSTimeInterval systemPauseLocation;//Used for auto resign handling NSTimeInterval systemPauseLocation;//Used for auto resign handling
@ -111,6 +113,7 @@ typedef enum {
@property (assign) id<CDLongAudioSourceDelegate> delegate; @property (assign) id<CDLongAudioSourceDelegate> delegate;
/* This long audio source functions as background music */ /* This long audio source functions as background music */
@property (readwrite, nonatomic) BOOL backgroundMusic; @property (readwrite, nonatomic) BOOL backgroundMusic;
@property (readonly) BOOL paused;
/** Loads the file into the audio source */ /** Loads the file into the audio source */
-(void) load:(NSString*) filePath; -(void) load:(NSString*) filePath;

View File

@ -39,7 +39,7 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised";
@implementation CDLongAudioSource @implementation CDLongAudioSource
@synthesize audioSourcePlayer, audioSourceFilePath, delegate, backgroundMusic; @synthesize audioSourcePlayer, audioSourceFilePath, delegate, backgroundMusic, paused;
-(id) init { -(id) init {
if ((self = [super init])) { if ((self = [super init])) {
@ -47,6 +47,7 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised";
volume = 1.0f; volume = 1.0f;
mute = NO; mute = NO;
enabled_ = YES; enabled_ = YES;
paused = NO;
} }
return self; return self;
} }
@ -94,6 +95,7 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised";
-(void) play { -(void) play {
if (enabled_) { if (enabled_) {
self->systemPaused = NO; self->systemPaused = NO;
self->paused = NO;
[audioSourcePlayer play]; [audioSourcePlayer play];
} else { } else {
CDLOGINFO(@"Denshion::CDLongAudioSource long audio source didn't play because it is disabled"); CDLOGINFO(@"Denshion::CDLongAudioSource long audio source didn't play because it is disabled");
@ -101,18 +103,22 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised";
} }
-(void) stop { -(void) stop {
self->paused = NO;
[audioSourcePlayer stop]; [audioSourcePlayer stop];
} }
-(void) pause { -(void) pause {
self->paused = YES;
[audioSourcePlayer pause]; [audioSourcePlayer pause];
} }
-(void) rewind { -(void) rewind {
self->paused = NO;
[audioSourcePlayer setCurrentTime:0]; [audioSourcePlayer setCurrentTime:0];
} }
-(void) resume { -(void) resume {
self->paused = NO;
[audioSourcePlayer play]; [audioSourcePlayer play];
} }
@ -542,17 +548,18 @@ static BOOL configured = FALSE;
{ {
[self.backgroundMusic load:filePath]; [self.backgroundMusic load:filePath];
if (!willPlayBackgroundMusic || _mute) { if (loop) {
CDLOGINFO(@"Denshion::CDAudioManager - play bgm aborted because audio is not exclusive or sound is muted"); [self.backgroundMusic setNumberOfLoops:-1];
return; } else {
} [self.backgroundMusic setNumberOfLoops:0];
}
if (loop) {
[self.backgroundMusic setNumberOfLoops:-1]; if (!willPlayBackgroundMusic || _mute) {
} else { CDLOGINFO(@"Denshion::CDAudioManager - play bgm aborted because audio is not exclusive or sound is muted");
[self.backgroundMusic setNumberOfLoops:0]; return;
} }
[self.backgroundMusic play];
[self.backgroundMusic play];
} }
-(void) stopBackgroundMusic -(void) stopBackgroundMusic
@ -572,6 +579,10 @@ static BOOL configured = FALSE;
return; return;
} }
if (![self.backgroundMusic paused]) {
return;
}
[self.backgroundMusic resume]; [self.backgroundMusic resume];
} }
@ -713,7 +724,7 @@ static BOOL configured = FALSE;
[self audioSessionResumed]; [self audioSessionResumed];
} }
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 40000 #if __CC_PLATFORM_IOS >= 40000
-(void) endInterruptionWithFlags:(NSUInteger)flags { -(void) endInterruptionWithFlags:(NSUInteger)flags {
CDLOGINFO(@"Denshion::CDAudioManager - interruption ended with flags %i",flags); CDLOGINFO(@"Denshion::CDAudioManager - interruption ended with flags %i",flags);
if (flags == AVAudioSessionInterruptionFlags_ShouldResume) { if (flags == AVAudioSessionInterruptionFlags_ShouldResume) {

View File

@ -88,6 +88,7 @@ void* CDloadWaveAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outD
theData = malloc(dataSize); theData = malloc(dataSize);
if (theData) if (theData)
{ {
memset(theData, 0, dataSize);
AudioFileReadBytes(afid, false, 0, &dataSize, theData); AudioFileReadBytes(afid, false, 0, &dataSize, theData);
if(err == noErr) if(err == noErr)
{ {
@ -195,6 +196,7 @@ void* CDloadCafAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDa
theData = malloc(dataSize); theData = malloc(dataSize);
if (theData) if (theData)
{ {
memset(theData, 0, dataSize);
AudioBufferList theDataBuffer; AudioBufferList theDataBuffer;
theDataBuffer.mNumberBuffers = 1; theDataBuffer.mNumberBuffers = 1;
theDataBuffer.mBuffers[0].mDataByteSize = dataSize; theDataBuffer.mBuffers[0].mDataByteSize = dataSize;

View File

@ -975,7 +975,7 @@ static BOOL _mixerRateSet = NO;
return; return;
} }
alSourcePause(sourceId); alSourcePause(sourceId);
alGetError();//Clear error in case we stopped any sounds that couldn't be paused alGetError();//Clear error in case we pause any sounds that couldn't be paused
} }
- (void) pauseAllSounds { - (void) pauseAllSounds {
@ -989,6 +989,15 @@ static BOOL _mixerRateSet = NO;
if (!functioning_) { if (!functioning_) {
return; return;
} }
// only resume a sound id that is paused
ALint state;
alGetSourcei(soundId, AL_SOURCE_STATE, &state);
if (state != AL_PAUSED)
{
return;
}
alSourcePlay(soundId); alSourcePlay(soundId);
alGetError();//Clear error in case we stopped any sounds that couldn't be resumed alGetError();//Clear error in case we stopped any sounds that couldn't be resumed
} }
@ -1370,12 +1379,11 @@ static BOOL _mixerRateSet = NO;
@synthesize filePath, soundId; @synthesize filePath, soundId;
-(id) init:(int) theSoundId filePath:(const NSString *) theFilePath { -(id) init:(int) theSoundId filePath:(const NSString *) theFilePath {
if ((self = [super init])) { if ((self = [super init])) {
soundId = theSoundId; soundId = theSoundId;
filePath = [theFilePath copy];//TODO: is retain necessary or does copy set retain count filePath = [theFilePath copy];
[filePath retain]; }
} return self;
return self;
} }
-(void) dealloc { -(void) dealloc {

View File

@ -169,7 +169,7 @@ void SimpleAudioEngine::end()
s_pEngine = NULL; s_pEngine = NULL;
} }
static_end(); static_end();
} }
void SimpleAudioEngine::preloadBackgroundMusic(const char* pszFilePath) void SimpleAudioEngine::preloadBackgroundMusic(const char* pszFilePath)
@ -184,42 +184,42 @@ void SimpleAudioEngine::playBackgroundMusic(const char* pszFilePath, bool bLoop)
void SimpleAudioEngine::stopBackgroundMusic(bool bReleaseData) void SimpleAudioEngine::stopBackgroundMusic(bool bReleaseData)
{ {
static_stopBackgroundMusic(); static_stopBackgroundMusic();
} }
void SimpleAudioEngine::pauseBackgroundMusic() void SimpleAudioEngine::pauseBackgroundMusic()
{ {
static_pauseBackgroundMusic(); static_pauseBackgroundMusic();
} }
void SimpleAudioEngine::resumeBackgroundMusic() void SimpleAudioEngine::resumeBackgroundMusic()
{ {
static_resumeBackgroundMusic(); static_resumeBackgroundMusic();
} }
void SimpleAudioEngine::rewindBackgroundMusic() void SimpleAudioEngine::rewindBackgroundMusic()
{ {
static_rewindBackgroundMusic(); static_rewindBackgroundMusic();
} }
bool SimpleAudioEngine::willPlayBackgroundMusic() bool SimpleAudioEngine::willPlayBackgroundMusic()
{ {
return static_willPlayBackgroundMusic(); return static_willPlayBackgroundMusic();
} }
bool SimpleAudioEngine::isBackgroundMusicPlaying() bool SimpleAudioEngine::isBackgroundMusicPlaying()
{ {
return static_isBackgroundMusicPlaying(); return static_isBackgroundMusicPlaying();
} }
float SimpleAudioEngine::getBackgroundMusicVolume() float SimpleAudioEngine::getBackgroundMusicVolume()
{ {
return static_getBackgroundMusicVolume(); return static_getBackgroundMusicVolume();
} }
void SimpleAudioEngine::setBackgroundMusicVolume(float volume) void SimpleAudioEngine::setBackgroundMusicVolume(float volume)
{ {
static_setBackgroundMusicVolume(volume); static_setBackgroundMusicVolume(volume);
} }
float SimpleAudioEngine::getEffectsVolume() float SimpleAudioEngine::getEffectsVolume()

View File

@ -19,7 +19,7 @@ MciPlayer::MciPlayer()
{ {
if (! s_hInstance) if (! s_hInstance)
{ {
s_hInstance = GetModuleHandle( NULL ); // Grab An Instance For Our Window s_hInstance = GetModuleHandle( NULL ); // Grab An Instance For Our Window
WNDCLASS wc; // Windows Class Structure WNDCLASS wc; // Windows Class Structure
@ -35,8 +35,8 @@ MciPlayer::MciPlayer()
wc.lpszMenuName = NULL; // We Don't Want A Menu wc.lpszMenuName = NULL; // We Don't Want A Menu
wc.lpszClassName = WIN_CLASS_NAME; // Set The Class Name wc.lpszClassName = WIN_CLASS_NAME; // Set The Class Name
if (! RegisterClass(&wc) // 注册 窗口类 失败 if (! RegisterClass(&wc)
&& 1410 != GetLastError()) // 并且失败的原因不是窗口类已注册 && 1410 != GetLastError())
{ {
return; return;
} }

View File

@ -1,7 +1,7 @@
#include "cocos2d.h" #include "cocos2d.h"
#include "AppDelegate.h" #include "AppDelegate.h"
#include "SimpleAudioEngine.h" #include "SimpleAudioEngine.h"
#include "CCScriptSupport.h" #include "script_support/CCScriptSupport.h"
#include "CCLuaEngine.h" #include "CCLuaEngine.h"
USING_NS_CC; USING_NS_CC;
@ -32,8 +32,6 @@ bool AppDelegate::applicationDidFinishLaunching()
// turn on display FPS // turn on display FPS
pDirector->setDisplayStats(true); pDirector->setDisplayStats(true);
// pDirector->setDeviceOrientation(kCCDeviceOrientationLandscapeLeft);
// set FPS. the default value is 1.0/60 if you don't call this // set FPS. the default value is 1.0/60 if you don't call this
pDirector->setAnimationInterval(1.0 / 60); pDirector->setAnimationInterval(1.0 / 60);
@ -41,14 +39,14 @@ bool AppDelegate::applicationDidFinishLaunching()
CCScriptEngineProtocol* pEngine = CCLuaEngine::engine(); CCScriptEngineProtocol* pEngine = CCLuaEngine::engine();
CCScriptEngineManager::sharedManager()->setScriptEngine(pEngine); CCScriptEngineManager::sharedManager()->setScriptEngine(pEngine);
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
CCString* pstrFileContent = CCString::stringWithContentsOfFile("hello.lua"); CCString* pstrFileContent = CCString::createWithContentsOfFile("hello.lua");
if (pstrFileContent) if (pstrFileContent)
{ {
pEngine->executeString(pstrFileContent->getCString()); pEngine->executeString(pstrFileContent->getCString());
} }
#else #else
std::string path = CCFileUtils::fullPathFromRelativePath("hello.lua"); std::string path = CCFileUtils::sharedFileUtils()->fullPathFromRelativePath("hello.lua");
pEngine->addSearchPath(path.substr(0, path.find_last_of("/")).c_str()); pEngine->addSearchPath(path.substr(0, path.find_last_of("/")).c_str());
pEngine->executeScriptFile(path.c_str()); pEngine->executeScriptFile(path.c_str());
#endif #endif
@ -59,13 +57,13 @@ bool AppDelegate::applicationDidFinishLaunching()
// This function will be called when the app is inactive. When comes a phone call,it's be invoked too // This function will be called when the app is inactive. When comes a phone call,it's be invoked too
void AppDelegate::applicationDidEnterBackground() void AppDelegate::applicationDidEnterBackground()
{ {
CCDirector::sharedDirector()->pause(); CCDirector::sharedDirector()->stopAnimation();
SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic(); SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic();
} }
// this function will be called when the app is active again // this function will be called when the app is active again
void AppDelegate::applicationWillEnterForeground() void AppDelegate::applicationWillEnterForeground()
{ {
CCDirector::sharedDirector()->resume(); CCDirector::sharedDirector()->startAnimation();
SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic(); SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic();
} }

View File

@ -1,20 +0,0 @@
# This file is for configuration settings for your
# application.
#
# The syntax is similar to windows .ini files ie
#
# [GroupName]
# Setting = Value
#
# Which can be read by your application using
# e.g s3eConfigGetString("GroupName", "Setting", string)
#
# All settings must be documented in .config.txt files.
# New settings specific to this application should be
# documented in app.config.txt
#
# Some conditional operations are also permitted, see the
# S3E documentation for details.
[S3E]
MemSize=12000000

View File

@ -22,22 +22,22 @@ local function creatDog()
-- create dog animate -- create dog animate
local textureDog = CCTextureCache:sharedTextureCache():addImage("dog.png") local textureDog = CCTextureCache:sharedTextureCache():addImage("dog.png")
local rect = CCRectMake(0, 0, frameWidth, frameHeight) local rect = CCRectMake(0, 0, frameWidth, frameHeight)
local frame0 = CCSpriteFrame:frameWithTexture(textureDog, rect) local frame0 = CCSpriteFrame:create(textureDog, rect)
rect = CCRectMake(frameWidth, 0, frameWidth, frameHeight) rect = CCRectMake(frameWidth, 0, frameWidth, frameHeight)
local frame1 = CCSpriteFrame:frameWithTexture(textureDog, rect) local frame1 = CCSpriteFrame:create(textureDog, rect)
local spriteDog = CCSprite:spriteWithSpriteFrame(frame0) local spriteDog = CCSprite:create(frame0)
spriteDog.isPaused = false spriteDog.isPaused = false
spriteDog:setPosition(0, winSize.height / 4 * 3) spriteDog:setPosition(0, winSize.height / 4 * 3)
local animFrames = CCArray:arrayWithCapacity(2) local animFrames = CCArray:create(2)
animFrames:addObject(frame0) animFrames:addObject(frame0)
animFrames:addObject(frame1) animFrames:addObject(frame1)
local animation = CCAnimation:animationWithSpriteFrames(animFrames, 0.5) local animation = CCAnimation:create(animFrames, 0.5)
local animate = CCAnimate:actionWithAnimation(animation); local animate = CCAnimate:create(animation);
spriteDog:runAction(CCRepeatForever:actionWithAction(animate)) spriteDog:runAction(CCRepeatForever:create(animate))
-- moving dog at every frame -- moving dog at every frame
local function tick() local function tick()
@ -59,28 +59,27 @@ end
-- create farm -- create farm
local function createLayerFram() local function createLayerFram()
local layerFarm = CCLayer:node() local layerFarm = CCLayer:create()
-- add in farm background -- add in farm background
local bg = CCSprite:spriteWithFile("farm.jpg") local bg = CCSprite:create("farm.jpg")
bg:setPosition(winSize.width / 2 + 80, winSize.height / 2) bg:setPosition(winSize.width / 2 + 80, winSize.height / 2)
layerFarm:addChild(bg) layerFarm:addChild(bg)
-- add land sprite -- add land sprite
for i = 0, 3 do for i = 0, 3 do
for j = 0, 1 do for j = 0, 1 do
local spriteLand = CCSprite:spriteWithFile("land.png") local spriteLand = CCSprite:create("land.png")
spriteLand:setPosition(200 + j * 180 - i % 2 * 90, 10 + i * 95 / 2) spriteLand:setPosition(200 + j * 180 - i % 2 * 90, 10 + i * 95 / 2)
layerFarm:addChild(spriteLand) layerFarm:addChild(spriteLand)
end end
end end
-- add crop -- add crop
local textureCrop = CCTextureCache:sharedTextureCache():addImage("crop.png") local frameCrop = CCSpriteFrame:create("crop.png", CCRectMake(0, 0, 105, 95))
local frameCrop = CCSpriteFrame:frameWithTexture(textureCrop, CCRectMake(0, 0, 105, 95))
for i = 0, 3 do for i = 0, 3 do
for j = 0, 1 do for j = 0, 1 do
local spriteCrop = CCSprite:spriteWithSpriteFrame(frameCrop); local spriteCrop = CCSprite:create(frameCrop);
spriteCrop:setPosition(10 + 200 + j * 180 - i % 2 * 90, 30 + 10 + i * 95 / 2) spriteCrop:setPosition(10 + 200 + j * 180 - i % 2 * 90, 30 + 10 + i * 95 / 2)
layerFarm:addChild(spriteCrop) layerFarm:addChild(spriteCrop)
end end
@ -128,7 +127,7 @@ local function createLayerFram()
end end
layerFarm:registerScriptTouchHandler(onTouch) layerFarm:registerScriptTouchHandler(onTouch)
layerFarm:setIsTouchEnabled(true) layerFarm:setTouchEnabled(true)
return layerFarm return layerFarm
end end
@ -136,36 +135,36 @@ end
-- create menu -- create menu
local function createLayerMenu() local function createLayerMenu()
local layerMenu = CCLayer:node() local layerMenu = CCLayer:create()
local menuPopup, menuTools, effectID local menuPopup, menuTools, effectID
local function menuCallbackClosePopup() local function menuCallbackClosePopup()
-- stop test sound effect -- stop test sound effect
SimpleAudioEngine:sharedEngine():stopEffect(effectID) SimpleAudioEngine:sharedEngine():stopEffect(effectID)
menuPopup:setIsVisible(false) menuPopup:setVisible(false)
end end
local function menuCallbackOpenPopup() local function menuCallbackOpenPopup()
-- loop test sound effect -- loop test sound effect
effectID = SimpleAudioEngine:sharedEngine():playEffect("effect1.wav") effectID = SimpleAudioEngine:sharedEngine():playEffect("effect1.wav")
menuPopup:setIsVisible(true) menuPopup:setVisible(true)
end end
-- add a popup menu -- add a popup menu
local menuPopupItem = CCMenuItemImage:itemWithNormalImage("menu2.png", "menu2.png") local menuPopupItem = CCMenuItemImage:create("menu2.png", "menu2.png")
menuPopupItem:setPosition(0, 0) menuPopupItem:setPosition(0, 0)
menuPopupItem:registerScriptHandler(menuCallbackClosePopup) menuPopupItem:registerScriptHandler(menuCallbackClosePopup)
menuPopup = CCMenu:menuWithItem(menuPopupItem) menuPopup = CCMenu:createWithItem(menuPopupItem)
menuPopup:setPosition(winSize.width / 2, winSize.height / 2) menuPopup:setPosition(winSize.width / 2, winSize.height / 2)
menuPopup:setIsVisible(false) menuPopup:setVisible(false)
layerMenu:addChild(menuPopup) layerMenu:addChild(menuPopup)
-- add the left-bottom "tools" menu to invoke menuPopup -- add the left-bottom "tools" menu to invoke menuPopup
local menuToolsItem = CCMenuItemImage:itemWithNormalImage("menu1.png", "menu1.png") local menuToolsItem = CCMenuItemImage:create("menu1.png", "menu1.png")
menuToolsItem:setPosition(0, 0) menuToolsItem:setPosition(0, 0)
menuToolsItem:registerScriptHandler(menuCallbackOpenPopup) menuToolsItem:registerScriptHandler(menuCallbackOpenPopup)
menuTools = CCMenu:menuWithItem(menuToolsItem) menuTools = CCMenu:createWithItem(menuToolsItem)
menuTools:setPosition(30, 40) menuTools:setPosition(30, 40)
layerMenu:addChild(menuTools) layerMenu:addChild(menuTools)
@ -177,7 +176,7 @@ SimpleAudioEngine:sharedEngine():playBackgroundMusic("background.mp3", true);
SimpleAudioEngine:sharedEngine():preloadEffect("effect1.wav"); SimpleAudioEngine:sharedEngine():preloadEffect("effect1.wav");
-- run -- run
local sceneGame = CCScene:node() local sceneGame = CCScene:create()
sceneGame:addChild(createLayerFram()) sceneGame:addChild(createLayerFram())
sceneGame:addChild(createLayerMenu()) sceneGame:addChild(createLayerMenu())
CCDirector:sharedDirector():runWithScene(sceneGame) CCDirector:sharedDirector():runWithScene(sceneGame)

View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="src" path="src_common"/>
<classpathentry kind="src" path="gen"/>
<classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
<classpathentry kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
<classpathentry kind="output" path="bin/classes"/>
</classpath>

View File

@ -0,0 +1,40 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>HelloLua</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.ApkBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>com.android.ide.eclipse.adt.AndroidNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
<linkedResources>
<link>
<name>src_common</name>
<type>2</type>
<locationURI>PARENT-2-PROJECT_LOC/cocos2dx/platform/android/java/src_common</locationURI>
</link>
</linkedResources>
</projectDescription>

View File

@ -0,0 +1,17 @@
# This file is used to override default values used by the Ant build system.
#
# This file must be checked into Version Control Systems, as it is
# integral to the build system of your project.
# This file is only used by the Ant script.
# You can use this to override default values such as
# 'source.dir' for the location of your java source folder and
# 'out.dir' for the location of your output folder.
# You can also use it define how the release builds are signed by declaring
# the following properties:
# 'key.store' for the location of your keystore and
# 'key.alias' for the name of the key to use.
# The password will be asked during the build when you use the 'release' target.

View File

@ -0,0 +1,83 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="HelloLua" default="help">
<!-- The local.properties file is created and updated by the 'android' tool.
It contains the path to the SDK. It should *NOT* be checked into
Version Control Systems. -->
<property file="local.properties" />
<!-- The ant.properties file can be created by you. It is only edited by the
'android' tool to add properties to it.
This is the place to change some Ant specific build properties.
Here are some properties you may want to change/update:
source.dir
The name of the source directory. Default is 'src'.
out.dir
The name of the output directory. Default is 'bin'.
For other overridable properties, look at the beginning of the rules
files in the SDK, at tools/ant/build.xml
Properties related to the SDK location or the project target should
be updated using the 'android' tool with the 'update' action.
This file is an integral part of the build system for your
application and should be checked into Version Control Systems.
-->
<property file="ant.properties" />
<!-- The project.properties file is created and updated by the 'android'
tool, as well as ADT.
This contains project specific properties such as project target, and library
dependencies. Lower level build properties are stored in ant.properties
(or in .classpath for Eclipse projects).
This file is an integral part of the build system for your
application and should be checked into Version Control Systems. -->
<loadproperties srcFile="project.properties" />
<!-- quick check on sdk.dir -->
<fail
message="sdk.dir is missing. Make sure to generate local.properties using 'android update project' or to inject it through an env var"
unless="sdk.dir"
/>
<!--
Import per project custom build rules if present at the root of the project.
This is the place to put custom intermediary targets such as:
-pre-build
-pre-compile
-post-compile (This is typically used for code obfuscation.
Compiled code location: ${out.classes.absolute.dir}
If this is not done in place, override ${out.dex.input.absolute.dir})
-post-package
-post-build
-pre-clean
-->
<import file="custom_rules.xml" optional="true" />
<!-- Import the actual build file.
To customize existing targets, there are two options:
- Customize only one target:
- copy/paste the target into this file, *before* the
<import> task.
- customize it to your needs.
- Customize the whole content of build.xml
- copy/paste the content of the rules files (minus the top node)
into this file, replacing the <import> task.
- customize to your needs.
***********************
****** IMPORTANT ******
***********************
In all cases you must update the value of version-tag below to read 'custom' instead of an integer,
in order to avoid having your file be overridden by tools such as "android update project"
-->
<!-- version-tag: 1 -->
<import file="${sdk.dir}/tools/ant/build.xml" />
</project>

View File

@ -62,6 +62,9 @@ cp $file $GAME_ANDROID_ROOT/assets
fi fi
done done
# Change the authority of Resources folder.
chmod -R 666 $GAME_ANDROID_ROOT/assets
# build # build
if [[ $buildexternalsfromsource ]]; then if [[ $buildexternalsfromsource ]]; then
echo "Building external dependencies from source" echo "Building external dependencies from source"

View File

@ -1,26 +0,0 @@
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package org.cocos2dx.hellolua;
public final class R {
public static final class attr {
}
public static final class drawable {
public static final int icon=0x7f020000;
}
public static final class id {
public static final int test_demo_gl_surfaceview=0x7f050001;
public static final int textField=0x7f050000;
}
public static final class layout {
public static final int game_demo=0x7f030000;
}
public static final class string {
public static final int app_name=0x7f040000;
}
}

View File

@ -1,26 +1,26 @@
LOCAL_PATH := $(call my-dir) LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS) include $(CLEAR_VARS)
LOCAL_MODULE := game_shared LOCAL_MODULE := game_shared
LOCAL_MODULE_FILENAME := libgame LOCAL_MODULE_FILENAME := libgame
LOCAL_SRC_FILES := helloworld/main.cpp \ LOCAL_SRC_FILES := helloworld/main.cpp \
../../Classes/AppDelegate.cpp \ ../../Classes/AppDelegate.cpp \
../../../lua/cocos2dx_support/CCLuaEngine.cpp \ ../../../lua/cocos2dx_support/CCLuaEngine.cpp \
../../../lua/cocos2dx_support/Cocos2dxLuaLoader.cpp \ ../../../lua/cocos2dx_support/Cocos2dxLuaLoader.cpp \
../../../lua/cocos2dx_support/LuaCocos2d.cpp \ ../../../lua/cocos2dx_support/LuaCocos2d.cpp \
../../../lua/cocos2dx_support/tolua_fix.c ../../../lua/cocos2dx_support/tolua_fix.c
LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes
LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static
LOCAL_WHOLE_STATIC_LIBRARIES += cocosdenshion_static LOCAL_WHOLE_STATIC_LIBRARIES += cocosdenshion_static
LOCAL_WHOLE_STATIC_LIBRARIES += cocos_lua_static LOCAL_WHOLE_STATIC_LIBRARIES += cocos_lua_static
include $(BUILD_SHARED_LIBRARY) include $(BUILD_SHARED_LIBRARY)
$(call import-module,cocos2dx) $(call import-module,cocos2dx)
$(call import-module,CocosDenshion/android) $(call import-module,CocosDenshion/android)
$(call import-module,lua/proj.android/jni) $(call import-module,lua/proj.android/jni)

View File

@ -1,3 +1,3 @@
APP_STL := gnustl_static APP_STL := gnustl_static
APP_CPPFLAGS := -frtti APP_CPPFLAGS := -frtti
APP_CPPFLAGS += -fexceptions APP_CPPFLAGS += -fexceptions

View File

@ -27,15 +27,15 @@ void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeInit(JNIEnv* env, jobject thi
CCEGLView *view = &CCEGLView::sharedOpenGLView(); CCEGLView *view = &CCEGLView::sharedOpenGLView();
view->setFrameSize(w, h); view->setFrameSize(w, h);
// set the design resolution screen size, if you want to use Design Resoulution scaled to current screen, please uncomment next line. // set the design resolution screen size, if you want to use Design Resoulution scaled to current screen, please uncomment next line.
// view.setDesignResolutionSize(480, 320); view->setDesignResolutionSize(480, 320);
AppDelegate *pAppDelegate = new AppDelegate(); AppDelegate *pAppDelegate = new AppDelegate();
CCApplication::sharedApplication().run(); CCApplication::sharedApplication().run();
} }
else else
{ {
ccDrawInit(); ccDrawInit();
ccGLInvalidateStateCache(); ccGLInvalidateStateCache();
CCShaderCache::sharedShaderCache()->reloadDefaultShaders(); CCShaderCache::sharedShaderCache()->reloadDefaultShaders();
CCTextureCache::reloadAllTextures(); CCTextureCache::reloadAllTextures();

View File

@ -0,0 +1,20 @@
# To enable ProGuard in your project, edit project.properties
# to define the proguard.config property as described in that file.
#
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in ${sdk.dir}/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the ProGuard
# include property in project.properties.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}

View File

@ -8,4 +8,6 @@
# project structure. # project structure.
# Project target. # Project target.
target=android-10 target=android-8
android.library.reference.1=../../cocos2dx/platform/android/java

View File

@ -1,18 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<org.cocos2dx.lib.Cocos2dxEditText
android:id="@+id/textField"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:background="@null"/>
<org.cocos2dx.lib.Cocos2dxGLSurfaceView
android:id="@+id/test_demo_gl_surfaceview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</FrameLayout>

View File

@ -23,6 +23,7 @@ THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
package org.cocos2dx.hellolua; package org.cocos2dx.hellolua;
import org.cocos2dx.lib.Cocos2dxActivity; import org.cocos2dx.lib.Cocos2dxActivity;
import org.cocos2dx.lib.Cocos2dxEditText;
import org.cocos2dx.lib.Cocos2dxGLSurfaceView; import org.cocos2dx.lib.Cocos2dxGLSurfaceView;
import org.cocos2dx.lib.Cocos2dxRenderer; import org.cocos2dx.lib.Cocos2dxRenderer;
@ -33,6 +34,8 @@ import android.opengl.GLSurfaceView;
import android.os.Bundle; import android.os.Bundle;
import android.util.Log; import android.util.Log;
import android.view.KeyEvent; import android.view.KeyEvent;
import android.widget.FrameLayout;
import android.view.ViewGroup;
public class HelloLua extends Cocos2dxActivity{ public class HelloLua extends Cocos2dxActivity{
protected void onCreate(Bundle savedInstanceState){ protected void onCreate(Bundle savedInstanceState){
@ -43,10 +46,35 @@ public class HelloLua extends Cocos2dxActivity{
String packageName = getApplication().getPackageName(); String packageName = getApplication().getPackageName();
super.setPackageName(packageName); super.setPackageName(packageName);
// 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);
// LuaGLSurfaceView
mGLView = new LuaGLSurfaceView(this); mGLView = new LuaGLSurfaceView(this);
setContentView(mGLView);
// ...add to FrameLayout
framelayout.addView(mGLView);
mGLView.setEGLContextClientVersion(2); mGLView.setEGLContextClientVersion(2);
mGLView.setCocos2dxRenderer(new Cocos2dxRenderer()); mGLView.setCocos2dxRenderer(new Cocos2dxRenderer());
mGLView.setTextField(edittext);
// Set framelayout as the content view
setContentView(framelayout);
} }
else { else {
Log.d("activity", "don't support gles2.0"); Log.d("activity", "don't support gles2.0");

View File

@ -1,381 +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.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.LinkedList;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.Paint.Align;
import android.graphics.Paint.FontMetricsInt;
import android.util.Log;
public class Cocos2dxBitmap{
/*
* The values are the same as cocos2dx/platform/CCImage.h.
* I think three alignments are OK.
*/
private static final int ALIGNCENTER = 0x33;
private static final int ALIGNLEFT = 0x31;
private static final int ALIGNRIGHT = 0x32;
private static Context context;
public static void setContext(Context context){
Cocos2dxBitmap.context = context;
}
/*
* @width: the width to draw, it can be 0
* @height: the height to draw, it can be 0
*/
public static void createTextBitmap(String content, String fontName,
int fontSize, int alignment, int width, int height){
content = refactorString(content);
Paint paint = newPaint(fontName, fontSize, alignment);
TextProperty textProperty = computeTextProperty(content, paint, width, height);
int bitmapTotalHeight = (height == 0 ? textProperty.totalHeight:height);
// Draw text to bitmap
Bitmap bitmap = Bitmap.createBitmap(textProperty.maxWidth,
bitmapTotalHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
// Draw string
FontMetricsInt fm = paint.getFontMetricsInt();
int x = 0;
int y = height == 0 ?(-fm.top):
(-fm.top + (height - textProperty.totalHeight)/2);
String[] lines = textProperty.lines;
for (String line : lines){
x = computeX(paint, line, textProperty.maxWidth, alignment);
canvas.drawText(line, x, y, paint);
y += textProperty.heightPerLine;
}
initNativeObject(bitmap);
}
private static int computeX(Paint paint, String content, int w, int alignment){
int ret = 0;
switch (alignment){
case ALIGNCENTER:
ret = w / 2;
break;
// ret = 0
case ALIGNLEFT:
break;
case ALIGNRIGHT:
ret = w;
break;
/*
* Default is align left.
* Should be same as newPaint().
*/
default:
break;
}
return ret;
}
private static class TextProperty{
// The max width of lines
int maxWidth;
// The height of all lines
int totalHeight;
int heightPerLine;
String[] lines;
TextProperty(int w, int h, String[] lines){
this.maxWidth = w;
this.heightPerLine = h;
this.totalHeight = h * lines.length;
this.lines = lines;
}
}
private static TextProperty computeTextProperty(String content, Paint paint,
int maxWidth, int maxHeight){
FontMetricsInt fm = paint.getFontMetricsInt();
int h = (int)Math.ceil(fm.bottom - fm.top);
int maxContentWidth = 0;
String[] lines = splitString(content, maxHeight, maxWidth, paint);
if (maxWidth != 0){
maxContentWidth = maxWidth;
}
else {
/*
* Compute the max width
*/
int temp = 0;
for (String line : lines){
temp = (int)Math.ceil(paint.measureText(line, 0, line.length()));
if (temp > maxContentWidth){
maxContentWidth = temp;
}
}
}
return new TextProperty(maxContentWidth, h, lines);
}
/*
* If maxWidth or maxHeight is not 0,
* split the string to fix the maxWidth and maxHeight.
*/
private static String[] splitString(String content, int maxHeight, int maxWidth,
Paint paint){
String[] lines = content.split("\\n");
String[] ret = null;
FontMetricsInt fm = paint.getFontMetricsInt();
int heightPerLine = (int)Math.ceil(fm.bottom - fm.top);
int maxLines = maxHeight / heightPerLine;
if (maxWidth != 0){
LinkedList<String> strList = new LinkedList<String>();
for (String line : lines){
/*
* The width of line is exceed maxWidth, should divide it into
* two or more lines.
*/
int lineWidth = (int)Math.ceil(paint.measureText(line));
if (lineWidth > maxWidth){
strList.addAll(divideStringWithMaxWidth(paint, line, maxWidth));
}
else{
strList.add(line);
}
/*
* Should not exceed the max height;
*/
if (maxLines > 0 && strList.size() >= maxLines){
break;
}
}
/*
* Remove exceeding lines
*/
if (maxLines > 0 && strList.size() > maxLines){
while (strList.size() > maxLines){
strList.removeLast();
}
}
ret = new String[strList.size()];
strList.toArray(ret);
} else
if (maxHeight != 0 && lines.length > maxLines) {
/*
* Remove exceeding lines
*/
LinkedList<String> strList = new LinkedList<String>();
for (int i = 0; i < maxLines; i++){
strList.add(lines[i]);
}
ret = new String[strList.size()];
strList.toArray(ret);
}
else {
ret = lines;
}
return ret;
}
private static LinkedList<String> divideStringWithMaxWidth(Paint paint, String content,
int width){
int charLength = content.length();
int start = 0;
int tempWidth = 0;
LinkedList<String> strList = new LinkedList<String>();
/*
* Break a String into String[] by the width & should wrap the word
*/
for (int i = 1; i <= charLength; ++i){
tempWidth = (int)Math.ceil(paint.measureText(content, start, i));
if (tempWidth >= width){
int lastIndexOfSpace = content.substring(0, i).lastIndexOf(" ");
if (lastIndexOfSpace != -1 && lastIndexOfSpace > start){
/**
* Should wrap the word
*/
strList.add(content.substring(start, lastIndexOfSpace));
i = lastIndexOfSpace;
}
else {
/*
* Should not exceed the width
*/
if (tempWidth > width){
strList.add(content.substring(start, i - 1));
/*
* compute from previous char
*/
--i;
}
else {
strList.add(content.substring(start, i));
}
}
start = i;
}
}
/*
* Add the last chars
*/
if (start < charLength){
strList.add(content.substring(start));
}
return strList;
}
private static Paint newPaint(String fontName, int fontSize, int alignment){
Paint paint = new Paint();
paint.setColor(Color.WHITE);
paint.setTextSize(fontSize);
paint.setAntiAlias(true);
/*
* Set type face for paint, now it support .ttf file.
*/
if (fontName.endsWith(".ttf")){
try {
//Typeface typeFace = Typeface.createFromAsset(context.getAssets(), fontName);
Typeface typeFace = Cocos2dxTypefaces.get(context, fontName);
paint.setTypeface(typeFace);
} catch (Exception e){
Log.e("Cocos2dxBitmap",
"error to create ttf type face: " + fontName);
/*
* The file may not find, use system font
*/
paint.setTypeface(Typeface.create(fontName, Typeface.NORMAL));
}
}
else {
paint.setTypeface(Typeface.create(fontName, Typeface.NORMAL));
}
switch (alignment){
case ALIGNCENTER:
paint.setTextAlign(Align.CENTER);
break;
case ALIGNLEFT:
paint.setTextAlign(Align.LEFT);
break;
case ALIGNRIGHT:
paint.setTextAlign(Align.RIGHT);
break;
default:
paint.setTextAlign(Align.LEFT);
break;
}
return paint;
}
private static String refactorString(String str){
// Avoid error when content is ""
if (str.compareTo("") == 0){
return " ";
}
/*
* If the font of "\n" is "" or "\n", insert " " in front of it.
*
* For example:
* "\nabc" -> " \nabc"
* "\nabc\n\n" -> " \nabc\n \n"
*/
StringBuilder strBuilder = new StringBuilder(str);
int start = 0;
int index = strBuilder.indexOf("\n");
while (index != -1){
if (index == 0 || strBuilder.charAt(index -1) == '\n'){
strBuilder.insert(start, " ");
start = index + 2;
} else {
start = index + 1;
}
if (start > strBuilder.length() || index == strBuilder.length()){
break;
}
index = strBuilder.indexOf("\n", start);
}
return strBuilder.toString();
}
private static void initNativeObject(Bitmap bitmap){
byte[] pixels = getPixels(bitmap);
if (pixels == null){
return;
}
nativeInitBitmapDC(bitmap.getWidth(), bitmap.getHeight(), pixels);
}
private static byte[] getPixels(Bitmap bitmap){
if (bitmap != null){
byte[] pixels = new byte[bitmap.getWidth() * bitmap.getHeight() * 4];
ByteBuffer buf = ByteBuffer.wrap(pixels);
buf.order(ByteOrder.nativeOrder());
bitmap.copyPixelsToBuffer(buf);
return pixels;
}
return null;
}
private static native void nativeInitBitmapDC(int width, int height, byte[] pixels);
}

View File

@ -0,0 +1,804 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 45;
objects = {
/* Begin PBXBuildFile section */
159A66601590486A003AEEC0 /* libcocos2dx.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 159A665D159047B3003AEEC0 /* libcocos2dx.a */; };
15DD6D83156DD1EF003E7567 /* fps_images.png in Resources */ = {isa = PBXBuildFile; fileRef = 15DD6D81156DD1EF003E7567 /* fps_images.png */; };
506EDB88102F4C4000A389B3 /* libz.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 506EDB87102F4C4000A389B3 /* libz.dylib */; };
506EDBA5102F4C9F00A389B3 /* AVFoundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 506EDBA4102F4C9F00A389B3 /* AVFoundation.framework */; };
78947C6D14EBB9B100DBD5A6 /* background.mp3 in Resources */ = {isa = PBXBuildFile; fileRef = 78947C5E14EBB9B000DBD5A6 /* background.mp3 */; };
78947C6E14EBB9B100DBD5A6 /* crop.png in Resources */ = {isa = PBXBuildFile; fileRef = 78947C5F14EBB9B000DBD5A6 /* crop.png */; };
78947C7014EBB9B100DBD5A6 /* dog.png in Resources */ = {isa = PBXBuildFile; fileRef = 78947C6114EBB9B000DBD5A6 /* dog.png */; };
78947C7114EBB9B100DBD5A6 /* effect1.wav in Resources */ = {isa = PBXBuildFile; fileRef = 78947C6214EBB9B000DBD5A6 /* effect1.wav */; };
78947C7214EBB9B100DBD5A6 /* farm.jpg in Resources */ = {isa = PBXBuildFile; fileRef = 78947C6314EBB9B000DBD5A6 /* farm.jpg */; };
78947C7414EBB9B100DBD5A6 /* hello.lua in Resources */ = {isa = PBXBuildFile; fileRef = 78947C6614EBB9B000DBD5A6 /* hello.lua */; };
78947C7514EBB9B100DBD5A6 /* hello2.lua in Resources */ = {isa = PBXBuildFile; fileRef = 78947C6714EBB9B000DBD5A6 /* hello2.lua */; };
78947C7714EBB9B100DBD5A6 /* land.png in Resources */ = {isa = PBXBuildFile; fileRef = 78947C6914EBB9B000DBD5A6 /* land.png */; };
78947C7814EBB9B100DBD5A6 /* menu1.png in Resources */ = {isa = PBXBuildFile; fileRef = 78947C6A14EBB9B000DBD5A6 /* menu1.png */; };
78947C7914EBB9B100DBD5A6 /* menu2.png in Resources */ = {isa = PBXBuildFile; fileRef = 78947C6B14EBB9B000DBD5A6 /* menu2.png */; };
78947C8B14EBBB0300DBD5A6 /* CDAudioManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 78947C8214EBBB0300DBD5A6 /* CDAudioManager.m */; };
78947C8C14EBBB0300DBD5A6 /* CDOpenALSupport.m in Sources */ = {isa = PBXBuildFile; fileRef = 78947C8514EBBB0300DBD5A6 /* CDOpenALSupport.m */; };
78947C8D14EBBB0300DBD5A6 /* CocosDenshion.m in Sources */ = {isa = PBXBuildFile; fileRef = 78947C8714EBBB0300DBD5A6 /* CocosDenshion.m */; };
78947C8E14EBBB0300DBD5A6 /* SimpleAudioEngine.mm in Sources */ = {isa = PBXBuildFile; fileRef = 78947C8814EBBB0300DBD5A6 /* SimpleAudioEngine.mm */; };
78947C8F14EBBB0300DBD5A6 /* SimpleAudioEngine_objc.m in Sources */ = {isa = PBXBuildFile; fileRef = 78947C8A14EBBB0300DBD5A6 /* SimpleAudioEngine_objc.m */; };
78DC4C9A15490B9500317402 /* Default.png in Resources */ = {isa = PBXBuildFile; fileRef = 78DC4C9815490B9500317402 /* Default.png */; };
78DC4C9B15490B9500317402 /* Icon.png in Resources */ = {isa = PBXBuildFile; fileRef = 78DC4C9915490B9500317402 /* Icon.png */; };
BF82F41713A864D700616D55 /* AppDelegate.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BF82F41513A864D700616D55 /* AppDelegate.cpp */; };
BF82F42113A8652A00616D55 /* AppController.mm in Sources */ = {isa = PBXBuildFile; fileRef = BF82F41F13A8652A00616D55 /* AppController.mm */; };
BF82F42213A8652A00616D55 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = BF82F42013A8652A00616D55 /* main.m */; };
D403B5D9135D1AF1004B518D /* libxml2.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = D403B5D8135D1AF1004B518D /* libxml2.dylib */; };
D4CEAD7913B4634300780515 /* RootViewController.mm in Sources */ = {isa = PBXBuildFile; fileRef = D4CEAD7713B4634300780515 /* RootViewController.mm */; };
DC6640030F83B3EA000B3E49 /* AudioToolbox.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = DC6640020F83B3EA000B3E49 /* AudioToolbox.framework */; };
DC6640050F83B3EA000B3E49 /* OpenAL.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = DC6640040F83B3EA000B3E49 /* OpenAL.framework */; };
DCCBF1B70F6022AE0040855A /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = DCCBF1B60F6022AE0040855A /* CoreGraphics.framework */; };
DCCBF1B90F6022AE0040855A /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = DCCBF1B80F6022AE0040855A /* Foundation.framework */; };
DCCBF1BB0F6022AE0040855A /* OpenGLES.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = DCCBF1BA0F6022AE0040855A /* OpenGLES.framework */; };
DCCBF1BD0F6022AE0040855A /* QuartzCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = DCCBF1BC0F6022AE0040855A /* QuartzCore.framework */; };
DCCBF1BF0F6022AE0040855A /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = DCCBF1BE0F6022AE0040855A /* UIKit.framework */; };
F4808BF414E3CB6C0021A5F8 /* CCLuaEngine.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F48087E114E3CB6A0021A5F8 /* CCLuaEngine.cpp */; };
F4808BF514E3CB6C0021A5F8 /* Cocos2dxLuaLoader.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F48087E314E3CB6A0021A5F8 /* Cocos2dxLuaLoader.cpp */; };
F4808BF614E3CB6C0021A5F8 /* LuaCocos2d.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F48087E514E3CB6A0021A5F8 /* LuaCocos2d.cpp */; };
F4808BF714E3CB6C0021A5F8 /* tolua_fix.c in Sources */ = {isa = PBXBuildFile; fileRef = F48087E714E3CB6A0021A5F8 /* tolua_fix.c */; };
F4808BF814E3CB6C0021A5F8 /* lapi.c in Sources */ = {isa = PBXBuildFile; fileRef = F48087EA14E3CB6A0021A5F8 /* lapi.c */; };
F4808BF914E3CB6C0021A5F8 /* lauxlib.c in Sources */ = {isa = PBXBuildFile; fileRef = F48087EC14E3CB6A0021A5F8 /* lauxlib.c */; };
F4808BFA14E3CB6C0021A5F8 /* lbaselib.c in Sources */ = {isa = PBXBuildFile; fileRef = F48087EE14E3CB6A0021A5F8 /* lbaselib.c */; };
F4808BFB14E3CB6C0021A5F8 /* lcode.c in Sources */ = {isa = PBXBuildFile; fileRef = F48087EF14E3CB6A0021A5F8 /* lcode.c */; };
F4808BFC14E3CB6C0021A5F8 /* ldblib.c in Sources */ = {isa = PBXBuildFile; fileRef = F48087F114E3CB6A0021A5F8 /* ldblib.c */; };
F4808BFD14E3CB6C0021A5F8 /* ldebug.c in Sources */ = {isa = PBXBuildFile; fileRef = F48087F214E3CB6A0021A5F8 /* ldebug.c */; };
F4808BFE14E3CB6C0021A5F8 /* ldo.c in Sources */ = {isa = PBXBuildFile; fileRef = F48087F414E3CB6A0021A5F8 /* ldo.c */; };
F4808BFF14E3CB6C0021A5F8 /* ldump.c in Sources */ = {isa = PBXBuildFile; fileRef = F48087F614E3CB6A0021A5F8 /* ldump.c */; };
F4808C0014E3CB6C0021A5F8 /* lfunc.c in Sources */ = {isa = PBXBuildFile; fileRef = F48087F714E3CB6A0021A5F8 /* lfunc.c */; };
F4808C0114E3CB6C0021A5F8 /* lgc.c in Sources */ = {isa = PBXBuildFile; fileRef = F48087F914E3CB6A0021A5F8 /* lgc.c */; };
F4808C0214E3CB6C0021A5F8 /* linit.c in Sources */ = {isa = PBXBuildFile; fileRef = F48087FB14E3CB6A0021A5F8 /* linit.c */; };
F4808C0314E3CB6C0021A5F8 /* liolib.c in Sources */ = {isa = PBXBuildFile; fileRef = F48087FC14E3CB6A0021A5F8 /* liolib.c */; };
F4808C0414E3CB6C0021A5F8 /* llex.c in Sources */ = {isa = PBXBuildFile; fileRef = F48087FD14E3CB6A0021A5F8 /* llex.c */; };
F4808C0514E3CB6C0021A5F8 /* lmathlib.c in Sources */ = {isa = PBXBuildFile; fileRef = F480880014E3CB6A0021A5F8 /* lmathlib.c */; };
F4808C0614E3CB6C0021A5F8 /* lmem.c in Sources */ = {isa = PBXBuildFile; fileRef = F480880114E3CB6A0021A5F8 /* lmem.c */; };
F4808C0714E3CB6C0021A5F8 /* loadlib.c in Sources */ = {isa = PBXBuildFile; fileRef = F480880314E3CB6A0021A5F8 /* loadlib.c */; };
F4808C0814E3CB6C0021A5F8 /* lobject.c in Sources */ = {isa = PBXBuildFile; fileRef = F480880414E3CB6A0021A5F8 /* lobject.c */; };
F4808C0914E3CB6C0021A5F8 /* lopcodes.c in Sources */ = {isa = PBXBuildFile; fileRef = F480880614E3CB6A0021A5F8 /* lopcodes.c */; };
F4808C0A14E3CB6C0021A5F8 /* loslib.c in Sources */ = {isa = PBXBuildFile; fileRef = F480880814E3CB6A0021A5F8 /* loslib.c */; };
F4808C0B14E3CB6C0021A5F8 /* lparser.c in Sources */ = {isa = PBXBuildFile; fileRef = F480880914E3CB6A0021A5F8 /* lparser.c */; };
F4808C0C14E3CB6C0021A5F8 /* lstate.c in Sources */ = {isa = PBXBuildFile; fileRef = F480880B14E3CB6A0021A5F8 /* lstate.c */; };
F4808C0D14E3CB6C0021A5F8 /* lstring.c in Sources */ = {isa = PBXBuildFile; fileRef = F480880D14E3CB6A0021A5F8 /* lstring.c */; };
F4808C0E14E3CB6C0021A5F8 /* lstrlib.c in Sources */ = {isa = PBXBuildFile; fileRef = F480880F14E3CB6A0021A5F8 /* lstrlib.c */; };
F4808C0F14E3CB6C0021A5F8 /* ltable.c in Sources */ = {isa = PBXBuildFile; fileRef = F480881014E3CB6A0021A5F8 /* ltable.c */; };
F4808C1014E3CB6C0021A5F8 /* ltablib.c in Sources */ = {isa = PBXBuildFile; fileRef = F480881214E3CB6A0021A5F8 /* ltablib.c */; };
F4808C1114E3CB6C0021A5F8 /* ltm.c in Sources */ = {isa = PBXBuildFile; fileRef = F480881314E3CB6A0021A5F8 /* ltm.c */; };
F4808C1214E3CB6C0021A5F8 /* lua.c in Sources */ = {isa = PBXBuildFile; fileRef = F480881514E3CB6A0021A5F8 /* lua.c */; };
F4808C1314E3CB6C0021A5F8 /* lundump.c in Sources */ = {isa = PBXBuildFile; fileRef = F480881914E3CB6A0021A5F8 /* lundump.c */; };
F4808C1414E3CB6C0021A5F8 /* lvm.c in Sources */ = {isa = PBXBuildFile; fileRef = F480881B14E3CB6A0021A5F8 /* lvm.c */; };
F4808C1514E3CB6C0021A5F8 /* lzio.c in Sources */ = {isa = PBXBuildFile; fileRef = F480881D14E3CB6A0021A5F8 /* lzio.c */; };
F4808C1614E3CB6C0021A5F8 /* print.c in Sources */ = {isa = PBXBuildFile; fileRef = F480881F14E3CB6A0021A5F8 /* print.c */; };
F4808C1D14E3CB6C0021A5F8 /* tolua_event.c in Sources */ = {isa = PBXBuildFile; fileRef = F480882B14E3CB6A0021A5F8 /* tolua_event.c */; };
F4808C1E14E3CB6C0021A5F8 /* tolua_is.c in Sources */ = {isa = PBXBuildFile; fileRef = F480882D14E3CB6A0021A5F8 /* tolua_is.c */; };
F4808C1F14E3CB6C0021A5F8 /* tolua_map.c in Sources */ = {isa = PBXBuildFile; fileRef = F480882E14E3CB6A0021A5F8 /* tolua_map.c */; };
F4808C2014E3CB6C0021A5F8 /* tolua_push.c in Sources */ = {isa = PBXBuildFile; fileRef = F480882F14E3CB6A0021A5F8 /* tolua_push.c */; };
F4808C2114E3CB6C0021A5F8 /* tolua_to.c in Sources */ = {isa = PBXBuildFile; fileRef = F480883014E3CB6A0021A5F8 /* tolua_to.c */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
159A665C159047B3003AEEC0 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 159A6655159047B3003AEEC0 /* cocos2dx.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 1551A33F158F2AB200E66CFE;
remoteInfo = cocos2dx;
};
159A665E15904864003AEEC0 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 159A6655159047B3003AEEC0 /* cocos2dx.xcodeproj */;
proxyType = 1;
remoteGlobalIDString = 1551A33E158F2AB200E66CFE;
remoteInfo = cocos2dx;
};
/* End PBXContainerItemProxy section */
/* Begin PBXFileReference section */
159A6655159047B3003AEEC0 /* cocos2dx.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = cocos2dx.xcodeproj; path = ../../cocos2dx/proj.ios/cocos2dx.xcodeproj; sourceTree = "<group>"; };
15DD6D81156DD1EF003E7567 /* fps_images.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = fps_images.png; sourceTree = "<group>"; };
1D6058910D05DD3D006BFB54 /* HelloLua.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = HelloLua.app; sourceTree = BUILT_PRODUCTS_DIR; };
506EDB87102F4C4000A389B3 /* libz.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libz.dylib; path = usr/lib/libz.dylib; sourceTree = SDKROOT; };
506EDBA4102F4C9F00A389B3 /* AVFoundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AVFoundation.framework; path = System/Library/Frameworks/AVFoundation.framework; sourceTree = SDKROOT; };
78947C5E14EBB9B000DBD5A6 /* background.mp3 */ = {isa = PBXFileReference; lastKnownFileType = audio.mp3; path = background.mp3; sourceTree = "<group>"; };
78947C5F14EBB9B000DBD5A6 /* crop.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = crop.png; sourceTree = "<group>"; };
78947C6114EBB9B000DBD5A6 /* dog.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = dog.png; sourceTree = "<group>"; };
78947C6214EBB9B000DBD5A6 /* effect1.wav */ = {isa = PBXFileReference; lastKnownFileType = audio.wav; path = effect1.wav; sourceTree = "<group>"; };
78947C6314EBB9B000DBD5A6 /* farm.jpg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = farm.jpg; sourceTree = "<group>"; };
78947C6614EBB9B000DBD5A6 /* hello.lua */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = hello.lua; sourceTree = "<group>"; };
78947C6714EBB9B000DBD5A6 /* hello2.lua */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = hello2.lua; sourceTree = "<group>"; };
78947C6914EBB9B000DBD5A6 /* land.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = land.png; sourceTree = "<group>"; };
78947C6A14EBB9B000DBD5A6 /* menu1.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = menu1.png; sourceTree = "<group>"; };
78947C6B14EBB9B000DBD5A6 /* menu2.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = menu2.png; sourceTree = "<group>"; };
78947C8114EBBB0300DBD5A6 /* CDAudioManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDAudioManager.h; sourceTree = "<group>"; };
78947C8214EBBB0300DBD5A6 /* CDAudioManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDAudioManager.m; sourceTree = "<group>"; };
78947C8314EBBB0300DBD5A6 /* CDConfig.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDConfig.h; sourceTree = "<group>"; };
78947C8414EBBB0300DBD5A6 /* CDOpenALSupport.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CDOpenALSupport.h; sourceTree = "<group>"; };
78947C8514EBBB0300DBD5A6 /* CDOpenALSupport.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CDOpenALSupport.m; sourceTree = "<group>"; };
78947C8614EBBB0300DBD5A6 /* CocosDenshion.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CocosDenshion.h; sourceTree = "<group>"; };
78947C8714EBBB0300DBD5A6 /* CocosDenshion.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CocosDenshion.m; sourceTree = "<group>"; };
78947C8814EBBB0300DBD5A6 /* SimpleAudioEngine.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = SimpleAudioEngine.mm; sourceTree = "<group>"; };
78947C8914EBBB0300DBD5A6 /* SimpleAudioEngine_objc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SimpleAudioEngine_objc.h; sourceTree = "<group>"; };
78947C8A14EBBB0300DBD5A6 /* SimpleAudioEngine_objc.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SimpleAudioEngine_objc.m; sourceTree = "<group>"; };
78DC4C9815490B9500317402 /* Default.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = Default.png; sourceTree = SOURCE_ROOT; };
78DC4C9915490B9500317402 /* Icon.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = Icon.png; sourceTree = SOURCE_ROOT; };
BF82F41513A864D700616D55 /* AppDelegate.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = AppDelegate.cpp; path = ../Classes/AppDelegate.cpp; sourceTree = SOURCE_ROOT; };
BF82F41613A864D700616D55 /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AppDelegate.h; path = ../Classes/AppDelegate.h; sourceTree = SOURCE_ROOT; };
BF82F41E13A8652A00616D55 /* AppController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AppController.h; sourceTree = "<group>"; };
BF82F41F13A8652A00616D55 /* AppController.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = AppController.mm; sourceTree = "<group>"; };
BF82F42013A8652A00616D55 /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = "<group>"; };
BF82F42313A8654600616D55 /* HelloLua_Prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HelloLua_Prefix.pch; sourceTree = "<group>"; };
D403B5D8135D1AF1004B518D /* libxml2.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libxml2.dylib; path = usr/lib/libxml2.dylib; sourceTree = SDKROOT; };
D4CEAD7713B4634300780515 /* RootViewController.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = RootViewController.mm; sourceTree = "<group>"; };
D4CEAD7813B4634300780515 /* RootViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RootViewController.h; sourceTree = "<group>"; };
DC6640020F83B3EA000B3E49 /* AudioToolbox.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AudioToolbox.framework; path = System/Library/Frameworks/AudioToolbox.framework; sourceTree = SDKROOT; };
DC6640040F83B3EA000B3E49 /* OpenAL.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = OpenAL.framework; path = System/Library/Frameworks/OpenAL.framework; sourceTree = SDKROOT; };
DCCBF1B60F6022AE0040855A /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = System/Library/Frameworks/CoreGraphics.framework; sourceTree = SDKROOT; };
DCCBF1B80F6022AE0040855A /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; };
DCCBF1BA0F6022AE0040855A /* OpenGLES.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = OpenGLES.framework; path = System/Library/Frameworks/OpenGLES.framework; sourceTree = SDKROOT; };
DCCBF1BC0F6022AE0040855A /* QuartzCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = QuartzCore.framework; path = System/Library/Frameworks/QuartzCore.framework; sourceTree = SDKROOT; };
DCCBF1BE0F6022AE0040855A /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = System/Library/Frameworks/UIKit.framework; sourceTree = SDKROOT; };
F480877714E3CB6A0021A5F8 /* Export.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Export.h; sourceTree = "<group>"; };
F480877814E3CB6A0021A5F8 /* SimpleAudioEngine.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SimpleAudioEngine.h; sourceTree = "<group>"; };
F48087E114E3CB6A0021A5F8 /* CCLuaEngine.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CCLuaEngine.cpp; sourceTree = "<group>"; };
F48087E214E3CB6A0021A5F8 /* CCLuaEngine.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCLuaEngine.h; sourceTree = "<group>"; };
F48087E314E3CB6A0021A5F8 /* Cocos2dxLuaLoader.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Cocos2dxLuaLoader.cpp; sourceTree = "<group>"; };
F48087E414E3CB6A0021A5F8 /* Cocos2dxLuaLoader.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Cocos2dxLuaLoader.h; sourceTree = "<group>"; };
F48087E514E3CB6A0021A5F8 /* LuaCocos2d.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = LuaCocos2d.cpp; sourceTree = "<group>"; };
F48087E614E3CB6A0021A5F8 /* LuaCocos2d.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LuaCocos2d.h; sourceTree = "<group>"; };
F48087E714E3CB6A0021A5F8 /* tolua_fix.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = tolua_fix.c; sourceTree = "<group>"; };
F48087E814E3CB6A0021A5F8 /* tolua_fix.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = tolua_fix.h; sourceTree = "<group>"; };
F48087EA14E3CB6A0021A5F8 /* lapi.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = lapi.c; sourceTree = "<group>"; };
F48087EB14E3CB6A0021A5F8 /* lapi.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = lapi.h; sourceTree = "<group>"; };
F48087EC14E3CB6A0021A5F8 /* lauxlib.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = lauxlib.c; sourceTree = "<group>"; };
F48087ED14E3CB6A0021A5F8 /* lauxlib.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = lauxlib.h; sourceTree = "<group>"; };
F48087EE14E3CB6A0021A5F8 /* lbaselib.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = lbaselib.c; sourceTree = "<group>"; };
F48087EF14E3CB6A0021A5F8 /* lcode.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = lcode.c; sourceTree = "<group>"; };
F48087F014E3CB6A0021A5F8 /* lcode.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = lcode.h; sourceTree = "<group>"; };
F48087F114E3CB6A0021A5F8 /* ldblib.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ldblib.c; sourceTree = "<group>"; };
F48087F214E3CB6A0021A5F8 /* ldebug.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ldebug.c; sourceTree = "<group>"; };
F48087F314E3CB6A0021A5F8 /* ldebug.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ldebug.h; sourceTree = "<group>"; };
F48087F414E3CB6A0021A5F8 /* ldo.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ldo.c; sourceTree = "<group>"; };
F48087F514E3CB6A0021A5F8 /* ldo.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ldo.h; sourceTree = "<group>"; };
F48087F614E3CB6A0021A5F8 /* ldump.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ldump.c; sourceTree = "<group>"; };
F48087F714E3CB6A0021A5F8 /* lfunc.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = lfunc.c; sourceTree = "<group>"; };
F48087F814E3CB6A0021A5F8 /* lfunc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = lfunc.h; sourceTree = "<group>"; };
F48087F914E3CB6A0021A5F8 /* lgc.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = lgc.c; sourceTree = "<group>"; };
F48087FA14E3CB6A0021A5F8 /* lgc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = lgc.h; sourceTree = "<group>"; };
F48087FB14E3CB6A0021A5F8 /* linit.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = linit.c; sourceTree = "<group>"; };
F48087FC14E3CB6A0021A5F8 /* liolib.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = liolib.c; sourceTree = "<group>"; };
F48087FD14E3CB6A0021A5F8 /* llex.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = llex.c; sourceTree = "<group>"; };
F48087FE14E3CB6A0021A5F8 /* llex.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = llex.h; sourceTree = "<group>"; };
F48087FF14E3CB6A0021A5F8 /* llimits.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = llimits.h; sourceTree = "<group>"; };
F480880014E3CB6A0021A5F8 /* lmathlib.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = lmathlib.c; sourceTree = "<group>"; };
F480880114E3CB6A0021A5F8 /* lmem.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = lmem.c; sourceTree = "<group>"; };
F480880214E3CB6A0021A5F8 /* lmem.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = lmem.h; sourceTree = "<group>"; };
F480880314E3CB6A0021A5F8 /* loadlib.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = loadlib.c; sourceTree = "<group>"; };
F480880414E3CB6A0021A5F8 /* lobject.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = lobject.c; sourceTree = "<group>"; };
F480880514E3CB6A0021A5F8 /* lobject.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = lobject.h; sourceTree = "<group>"; };
F480880614E3CB6A0021A5F8 /* lopcodes.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = lopcodes.c; sourceTree = "<group>"; };
F480880714E3CB6A0021A5F8 /* lopcodes.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = lopcodes.h; sourceTree = "<group>"; };
F480880814E3CB6A0021A5F8 /* loslib.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = loslib.c; sourceTree = "<group>"; };
F480880914E3CB6A0021A5F8 /* lparser.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = lparser.c; sourceTree = "<group>"; };
F480880A14E3CB6A0021A5F8 /* lparser.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = lparser.h; sourceTree = "<group>"; };
F480880B14E3CB6A0021A5F8 /* lstate.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = lstate.c; sourceTree = "<group>"; };
F480880C14E3CB6A0021A5F8 /* lstate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = lstate.h; sourceTree = "<group>"; };
F480880D14E3CB6A0021A5F8 /* lstring.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = lstring.c; sourceTree = "<group>"; };
F480880E14E3CB6A0021A5F8 /* lstring.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = lstring.h; sourceTree = "<group>"; };
F480880F14E3CB6A0021A5F8 /* lstrlib.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = lstrlib.c; sourceTree = "<group>"; };
F480881014E3CB6A0021A5F8 /* ltable.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ltable.c; sourceTree = "<group>"; };
F480881114E3CB6A0021A5F8 /* ltable.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ltable.h; sourceTree = "<group>"; };
F480881214E3CB6A0021A5F8 /* ltablib.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ltablib.c; sourceTree = "<group>"; };
F480881314E3CB6A0021A5F8 /* ltm.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ltm.c; sourceTree = "<group>"; };
F480881414E3CB6A0021A5F8 /* ltm.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ltm.h; sourceTree = "<group>"; };
F480881514E3CB6A0021A5F8 /* lua.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = lua.c; sourceTree = "<group>"; };
F480881614E3CB6A0021A5F8 /* lua.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = lua.h; sourceTree = "<group>"; };
F480881714E3CB6A0021A5F8 /* luaconf.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = luaconf.h; sourceTree = "<group>"; };
F480881814E3CB6A0021A5F8 /* lualib.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = lualib.h; sourceTree = "<group>"; };
F480881914E3CB6A0021A5F8 /* lundump.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = lundump.c; sourceTree = "<group>"; };
F480881A14E3CB6A0021A5F8 /* lundump.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = lundump.h; sourceTree = "<group>"; };
F480881B14E3CB6A0021A5F8 /* lvm.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = lvm.c; sourceTree = "<group>"; };
F480881C14E3CB6A0021A5F8 /* lvm.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = lvm.h; sourceTree = "<group>"; };
F480881D14E3CB6A0021A5F8 /* lzio.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = lzio.c; sourceTree = "<group>"; };
F480881E14E3CB6A0021A5F8 /* lzio.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = lzio.h; sourceTree = "<group>"; };
F480881F14E3CB6A0021A5F8 /* print.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = print.c; sourceTree = "<group>"; };
F480882A14E3CB6A0021A5F8 /* tolua++.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "tolua++.h"; sourceTree = "<group>"; };
F480882B14E3CB6A0021A5F8 /* tolua_event.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = tolua_event.c; sourceTree = "<group>"; };
F480882C14E3CB6A0021A5F8 /* tolua_event.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = tolua_event.h; sourceTree = "<group>"; };
F480882D14E3CB6A0021A5F8 /* tolua_is.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = tolua_is.c; sourceTree = "<group>"; };
F480882E14E3CB6A0021A5F8 /* tolua_map.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = tolua_map.c; sourceTree = "<group>"; };
F480882F14E3CB6A0021A5F8 /* tolua_push.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = tolua_push.c; sourceTree = "<group>"; };
F480883014E3CB6A0021A5F8 /* tolua_to.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = tolua_to.c; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
1D60588F0D05DD3D006BFB54 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
159A66601590486A003AEEC0 /* libcocos2dx.a in Frameworks */,
DCCBF1B70F6022AE0040855A /* CoreGraphics.framework in Frameworks */,
DCCBF1B90F6022AE0040855A /* Foundation.framework in Frameworks */,
DCCBF1BB0F6022AE0040855A /* OpenGLES.framework in Frameworks */,
DCCBF1BD0F6022AE0040855A /* QuartzCore.framework in Frameworks */,
DCCBF1BF0F6022AE0040855A /* UIKit.framework in Frameworks */,
DC6640030F83B3EA000B3E49 /* AudioToolbox.framework in Frameworks */,
DC6640050F83B3EA000B3E49 /* OpenAL.framework in Frameworks */,
506EDB88102F4C4000A389B3 /* libz.dylib in Frameworks */,
506EDBA5102F4C9F00A389B3 /* AVFoundation.framework in Frameworks */,
D403B5D9135D1AF1004B518D /* libxml2.dylib in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
159A6656159047B3003AEEC0 /* Products */ = {
isa = PBXGroup;
children = (
159A665D159047B3003AEEC0 /* libcocos2dx.a */,
);
name = Products;
sourceTree = "<group>";
};
19C28FACFE9D520D11CA2CBB /* Products */ = {
isa = PBXGroup;
children = (
1D6058910D05DD3D006BFB54 /* HelloLua.app */,
);
name = Products;
sourceTree = "<group>";
};
29B97314FDCFA39411CA2CEA /* CustomTemplate */ = {
isa = PBXGroup;
children = (
159A6655159047B3003AEEC0 /* cocos2dx.xcodeproj */,
78947C5C14EBB9B000DBD5A6 /* Resources */,
BF82F41413A864B000616D55 /* Classes */,
506EDAA3102F461B00A389B3 /* libs */,
29B97315FDCFA39411CA2CEA /* Other Sources */,
29B97323FDCFA39411CA2CEA /* Frameworks */,
19C28FACFE9D520D11CA2CBB /* Products */,
);
name = CustomTemplate;
sourceTree = "<group>";
};
29B97315FDCFA39411CA2CEA /* Other Sources */ = {
isa = PBXGroup;
children = (
D4CEAD7713B4634300780515 /* RootViewController.mm */,
D4CEAD7813B4634300780515 /* RootViewController.h */,
BF82F42313A8654600616D55 /* HelloLua_Prefix.pch */,
BF82F41E13A8652A00616D55 /* AppController.h */,
BF82F41F13A8652A00616D55 /* AppController.mm */,
BF82F42013A8652A00616D55 /* main.m */,
);
name = "Other Sources";
sourceTree = "<group>";
};
29B97323FDCFA39411CA2CEA /* Frameworks */ = {
isa = PBXGroup;
children = (
DCCBF1B60F6022AE0040855A /* CoreGraphics.framework */,
DCCBF1B80F6022AE0040855A /* Foundation.framework */,
DCCBF1BA0F6022AE0040855A /* OpenGLES.framework */,
DCCBF1BC0F6022AE0040855A /* QuartzCore.framework */,
DCCBF1BE0F6022AE0040855A /* UIKit.framework */,
DC6640040F83B3EA000B3E49 /* OpenAL.framework */,
DC6640020F83B3EA000B3E49 /* AudioToolbox.framework */,
506EDB87102F4C4000A389B3 /* libz.dylib */,
506EDBA4102F4C9F00A389B3 /* AVFoundation.framework */,
D403B5D8135D1AF1004B518D /* libxml2.dylib */,
);
name = Frameworks;
sourceTree = "<group>";
};
506EDAA3102F461B00A389B3 /* libs */ = {
isa = PBXGroup;
children = (
F480871B14E3CB6A0021A5F8 /* CocosDenshion */,
F48087DF14E3CB6A0021A5F8 /* lua */,
);
name = libs;
sourceTree = "<group>";
};
78947C5C14EBB9B000DBD5A6 /* Resources */ = {
isa = PBXGroup;
children = (
15DD6D81156DD1EF003E7567 /* fps_images.png */,
78947C5E14EBB9B000DBD5A6 /* background.mp3 */,
78947C5F14EBB9B000DBD5A6 /* crop.png */,
78DC4C9815490B9500317402 /* Default.png */,
78947C6114EBB9B000DBD5A6 /* dog.png */,
78947C6214EBB9B000DBD5A6 /* effect1.wav */,
78947C6314EBB9B000DBD5A6 /* farm.jpg */,
78947C6614EBB9B000DBD5A6 /* hello.lua */,
78947C6714EBB9B000DBD5A6 /* hello2.lua */,
78DC4C9915490B9500317402 /* Icon.png */,
78947C6914EBB9B000DBD5A6 /* land.png */,
78947C6A14EBB9B000DBD5A6 /* menu1.png */,
78947C6B14EBB9B000DBD5A6 /* menu2.png */,
);
name = Resources;
path = ../Resources;
sourceTree = "<group>";
};
78947C8014EBBB0300DBD5A6 /* ios */ = {
isa = PBXGroup;
children = (
78947C8114EBBB0300DBD5A6 /* CDAudioManager.h */,
78947C8214EBBB0300DBD5A6 /* CDAudioManager.m */,
78947C8314EBBB0300DBD5A6 /* CDConfig.h */,
78947C8414EBBB0300DBD5A6 /* CDOpenALSupport.h */,
78947C8514EBBB0300DBD5A6 /* CDOpenALSupport.m */,
78947C8614EBBB0300DBD5A6 /* CocosDenshion.h */,
78947C8714EBBB0300DBD5A6 /* CocosDenshion.m */,
78947C8814EBBB0300DBD5A6 /* SimpleAudioEngine.mm */,
78947C8914EBBB0300DBD5A6 /* SimpleAudioEngine_objc.h */,
78947C8A14EBBB0300DBD5A6 /* SimpleAudioEngine_objc.m */,
);
path = ios;
sourceTree = "<group>";
};
BF82F41413A864B000616D55 /* Classes */ = {
isa = PBXGroup;
children = (
BF82F41513A864D700616D55 /* AppDelegate.cpp */,
BF82F41613A864D700616D55 /* AppDelegate.h */,
);
name = Classes;
sourceTree = "<group>";
};
F480871B14E3CB6A0021A5F8 /* CocosDenshion */ = {
isa = PBXGroup;
children = (
78947C8014EBBB0300DBD5A6 /* ios */,
F480877614E3CB6A0021A5F8 /* include */,
);
name = CocosDenshion;
path = ../../CocosDenshion;
sourceTree = "<group>";
};
F480877614E3CB6A0021A5F8 /* include */ = {
isa = PBXGroup;
children = (
F480877714E3CB6A0021A5F8 /* Export.h */,
F480877814E3CB6A0021A5F8 /* SimpleAudioEngine.h */,
);
path = include;
sourceTree = "<group>";
};
F48087DF14E3CB6A0021A5F8 /* lua */ = {
isa = PBXGroup;
children = (
F48087E014E3CB6A0021A5F8 /* cocos2dx_support */,
F48087E914E3CB6A0021A5F8 /* lua */,
F480882914E3CB6A0021A5F8 /* tolua */,
);
name = lua;
path = ../../lua;
sourceTree = "<group>";
};
F48087E014E3CB6A0021A5F8 /* cocos2dx_support */ = {
isa = PBXGroup;
children = (
F48087E114E3CB6A0021A5F8 /* CCLuaEngine.cpp */,
F48087E214E3CB6A0021A5F8 /* CCLuaEngine.h */,
F48087E314E3CB6A0021A5F8 /* Cocos2dxLuaLoader.cpp */,
F48087E414E3CB6A0021A5F8 /* Cocos2dxLuaLoader.h */,
F48087E514E3CB6A0021A5F8 /* LuaCocos2d.cpp */,
F48087E614E3CB6A0021A5F8 /* LuaCocos2d.h */,
F48087E714E3CB6A0021A5F8 /* tolua_fix.c */,
F48087E814E3CB6A0021A5F8 /* tolua_fix.h */,
);
path = cocos2dx_support;
sourceTree = "<group>";
};
F48087E914E3CB6A0021A5F8 /* lua */ = {
isa = PBXGroup;
children = (
F48087EA14E3CB6A0021A5F8 /* lapi.c */,
F48087EB14E3CB6A0021A5F8 /* lapi.h */,
F48087EC14E3CB6A0021A5F8 /* lauxlib.c */,
F48087ED14E3CB6A0021A5F8 /* lauxlib.h */,
F48087EE14E3CB6A0021A5F8 /* lbaselib.c */,
F48087EF14E3CB6A0021A5F8 /* lcode.c */,
F48087F014E3CB6A0021A5F8 /* lcode.h */,
F48087F114E3CB6A0021A5F8 /* ldblib.c */,
F48087F214E3CB6A0021A5F8 /* ldebug.c */,
F48087F314E3CB6A0021A5F8 /* ldebug.h */,
F48087F414E3CB6A0021A5F8 /* ldo.c */,
F48087F514E3CB6A0021A5F8 /* ldo.h */,
F48087F614E3CB6A0021A5F8 /* ldump.c */,
F48087F714E3CB6A0021A5F8 /* lfunc.c */,
F48087F814E3CB6A0021A5F8 /* lfunc.h */,
F48087F914E3CB6A0021A5F8 /* lgc.c */,
F48087FA14E3CB6A0021A5F8 /* lgc.h */,
F48087FB14E3CB6A0021A5F8 /* linit.c */,
F48087FC14E3CB6A0021A5F8 /* liolib.c */,
F48087FD14E3CB6A0021A5F8 /* llex.c */,
F48087FE14E3CB6A0021A5F8 /* llex.h */,
F48087FF14E3CB6A0021A5F8 /* llimits.h */,
F480880014E3CB6A0021A5F8 /* lmathlib.c */,
F480880114E3CB6A0021A5F8 /* lmem.c */,
F480880214E3CB6A0021A5F8 /* lmem.h */,
F480880314E3CB6A0021A5F8 /* loadlib.c */,
F480880414E3CB6A0021A5F8 /* lobject.c */,
F480880514E3CB6A0021A5F8 /* lobject.h */,
F480880614E3CB6A0021A5F8 /* lopcodes.c */,
F480880714E3CB6A0021A5F8 /* lopcodes.h */,
F480880814E3CB6A0021A5F8 /* loslib.c */,
F480880914E3CB6A0021A5F8 /* lparser.c */,
F480880A14E3CB6A0021A5F8 /* lparser.h */,
F480880B14E3CB6A0021A5F8 /* lstate.c */,
F480880C14E3CB6A0021A5F8 /* lstate.h */,
F480880D14E3CB6A0021A5F8 /* lstring.c */,
F480880E14E3CB6A0021A5F8 /* lstring.h */,
F480880F14E3CB6A0021A5F8 /* lstrlib.c */,
F480881014E3CB6A0021A5F8 /* ltable.c */,
F480881114E3CB6A0021A5F8 /* ltable.h */,
F480881214E3CB6A0021A5F8 /* ltablib.c */,
F480881314E3CB6A0021A5F8 /* ltm.c */,
F480881414E3CB6A0021A5F8 /* ltm.h */,
F480881514E3CB6A0021A5F8 /* lua.c */,
F480881614E3CB6A0021A5F8 /* lua.h */,
F480881714E3CB6A0021A5F8 /* luaconf.h */,
F480881814E3CB6A0021A5F8 /* lualib.h */,
F480881914E3CB6A0021A5F8 /* lundump.c */,
F480881A14E3CB6A0021A5F8 /* lundump.h */,
F480881B14E3CB6A0021A5F8 /* lvm.c */,
F480881C14E3CB6A0021A5F8 /* lvm.h */,
F480881D14E3CB6A0021A5F8 /* lzio.c */,
F480881E14E3CB6A0021A5F8 /* lzio.h */,
F480881F14E3CB6A0021A5F8 /* print.c */,
);
path = lua;
sourceTree = "<group>";
};
F480882914E3CB6A0021A5F8 /* tolua */ = {
isa = PBXGroup;
children = (
F480882A14E3CB6A0021A5F8 /* tolua++.h */,
F480882B14E3CB6A0021A5F8 /* tolua_event.c */,
F480882C14E3CB6A0021A5F8 /* tolua_event.h */,
F480882D14E3CB6A0021A5F8 /* tolua_is.c */,
F480882E14E3CB6A0021A5F8 /* tolua_map.c */,
F480882F14E3CB6A0021A5F8 /* tolua_push.c */,
F480883014E3CB6A0021A5F8 /* tolua_to.c */,
);
path = tolua;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
1D6058900D05DD3D006BFB54 /* HelloLua */ = {
isa = PBXNativeTarget;
buildConfigurationList = 1D6058960D05DD3E006BFB54 /* Build configuration list for PBXNativeTarget "HelloLua" */;
buildPhases = (
1D60588D0D05DD3D006BFB54 /* Resources */,
1D60588E0D05DD3D006BFB54 /* Sources */,
1D60588F0D05DD3D006BFB54 /* Frameworks */,
);
buildRules = (
);
dependencies = (
159A665F15904864003AEEC0 /* PBXTargetDependency */,
);
name = HelloLua;
productName = HelloLua;
productReference = 1D6058910D05DD3D006BFB54 /* HelloLua.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
29B97313FDCFA39411CA2CEA /* Project object */ = {
isa = PBXProject;
buildConfigurationList = C01FCF4E08A954540054247B /* Build configuration list for PBXProject "HelloLua" */;
compatibilityVersion = "Xcode 3.1";
developmentRegion = English;
hasScannedForEncodings = 1;
knownRegions = (
English,
Japanese,
French,
German,
);
mainGroup = 29B97314FDCFA39411CA2CEA /* CustomTemplate */;
projectDirPath = "";
projectReferences = (
{
ProductGroup = 159A6656159047B3003AEEC0 /* Products */;
ProjectRef = 159A6655159047B3003AEEC0 /* cocos2dx.xcodeproj */;
},
);
projectRoot = "";
targets = (
1D6058900D05DD3D006BFB54 /* HelloLua */,
);
};
/* End PBXProject section */
/* Begin PBXReferenceProxy section */
159A665D159047B3003AEEC0 /* libcocos2dx.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libcocos2dx.a;
remoteRef = 159A665C159047B3003AEEC0 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
/* End PBXReferenceProxy section */
/* Begin PBXResourcesBuildPhase section */
1D60588D0D05DD3D006BFB54 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
78947C6D14EBB9B100DBD5A6 /* background.mp3 in Resources */,
78947C6E14EBB9B100DBD5A6 /* crop.png in Resources */,
78947C7014EBB9B100DBD5A6 /* dog.png in Resources */,
78947C7114EBB9B100DBD5A6 /* effect1.wav in Resources */,
78947C7214EBB9B100DBD5A6 /* farm.jpg in Resources */,
78947C7414EBB9B100DBD5A6 /* hello.lua in Resources */,
78947C7514EBB9B100DBD5A6 /* hello2.lua in Resources */,
78947C7714EBB9B100DBD5A6 /* land.png in Resources */,
78947C7814EBB9B100DBD5A6 /* menu1.png in Resources */,
78947C7914EBB9B100DBD5A6 /* menu2.png in Resources */,
78DC4C9A15490B9500317402 /* Default.png in Resources */,
78DC4C9B15490B9500317402 /* Icon.png in Resources */,
15DD6D83156DD1EF003E7567 /* fps_images.png in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
1D60588E0D05DD3D006BFB54 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
BF82F41713A864D700616D55 /* AppDelegate.cpp in Sources */,
BF82F42113A8652A00616D55 /* AppController.mm in Sources */,
BF82F42213A8652A00616D55 /* main.m in Sources */,
D4CEAD7913B4634300780515 /* RootViewController.mm in Sources */,
F4808BF414E3CB6C0021A5F8 /* CCLuaEngine.cpp in Sources */,
F4808BF514E3CB6C0021A5F8 /* Cocos2dxLuaLoader.cpp in Sources */,
F4808BF614E3CB6C0021A5F8 /* LuaCocos2d.cpp in Sources */,
F4808BF714E3CB6C0021A5F8 /* tolua_fix.c in Sources */,
F4808BF814E3CB6C0021A5F8 /* lapi.c in Sources */,
F4808BF914E3CB6C0021A5F8 /* lauxlib.c in Sources */,
F4808BFA14E3CB6C0021A5F8 /* lbaselib.c in Sources */,
F4808BFB14E3CB6C0021A5F8 /* lcode.c in Sources */,
F4808BFC14E3CB6C0021A5F8 /* ldblib.c in Sources */,
F4808BFD14E3CB6C0021A5F8 /* ldebug.c in Sources */,
F4808BFE14E3CB6C0021A5F8 /* ldo.c in Sources */,
F4808BFF14E3CB6C0021A5F8 /* ldump.c in Sources */,
F4808C0014E3CB6C0021A5F8 /* lfunc.c in Sources */,
F4808C0114E3CB6C0021A5F8 /* lgc.c in Sources */,
F4808C0214E3CB6C0021A5F8 /* linit.c in Sources */,
F4808C0314E3CB6C0021A5F8 /* liolib.c in Sources */,
F4808C0414E3CB6C0021A5F8 /* llex.c in Sources */,
F4808C0514E3CB6C0021A5F8 /* lmathlib.c in Sources */,
F4808C0614E3CB6C0021A5F8 /* lmem.c in Sources */,
F4808C0714E3CB6C0021A5F8 /* loadlib.c in Sources */,
F4808C0814E3CB6C0021A5F8 /* lobject.c in Sources */,
F4808C0914E3CB6C0021A5F8 /* lopcodes.c in Sources */,
F4808C0A14E3CB6C0021A5F8 /* loslib.c in Sources */,
F4808C0B14E3CB6C0021A5F8 /* lparser.c in Sources */,
F4808C0C14E3CB6C0021A5F8 /* lstate.c in Sources */,
F4808C0D14E3CB6C0021A5F8 /* lstring.c in Sources */,
F4808C0E14E3CB6C0021A5F8 /* lstrlib.c in Sources */,
F4808C0F14E3CB6C0021A5F8 /* ltable.c in Sources */,
F4808C1014E3CB6C0021A5F8 /* ltablib.c in Sources */,
F4808C1114E3CB6C0021A5F8 /* ltm.c in Sources */,
F4808C1214E3CB6C0021A5F8 /* lua.c in Sources */,
F4808C1314E3CB6C0021A5F8 /* lundump.c in Sources */,
F4808C1414E3CB6C0021A5F8 /* lvm.c in Sources */,
F4808C1514E3CB6C0021A5F8 /* lzio.c in Sources */,
F4808C1614E3CB6C0021A5F8 /* print.c in Sources */,
F4808C1D14E3CB6C0021A5F8 /* tolua_event.c in Sources */,
F4808C1E14E3CB6C0021A5F8 /* tolua_is.c in Sources */,
F4808C1F14E3CB6C0021A5F8 /* tolua_map.c in Sources */,
F4808C2014E3CB6C0021A5F8 /* tolua_push.c in Sources */,
F4808C2114E3CB6C0021A5F8 /* tolua_to.c in Sources */,
78947C8B14EBBB0300DBD5A6 /* CDAudioManager.m in Sources */,
78947C8C14EBBB0300DBD5A6 /* CDOpenALSupport.m in Sources */,
78947C8D14EBBB0300DBD5A6 /* CocosDenshion.m in Sources */,
78947C8E14EBBB0300DBD5A6 /* SimpleAudioEngine.mm in Sources */,
78947C8F14EBBB0300DBD5A6 /* SimpleAudioEngine_objc.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
159A665F15904864003AEEC0 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = cocos2dx;
targetProxy = 159A665E15904864003AEEC0 /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin XCBuildConfiguration section */
1D6058940D05DD3E006BFB54 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
GCC_DYNAMIC_NO_PIC = NO;
GCC_ENABLE_FIX_AND_CONTINUE = NO;
GCC_FAST_OBJC_DISPATCH = YES;
GCC_INLINES_ARE_PRIVATE_EXTERN = NO;
GCC_OBJC_CALL_CXX_CDTORS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = HelloLua_Prefix.pch;
GCC_PREPROCESSOR_DEFINITIONS = (
USE_FILE32API,
TARGET_OS_IPHONE,
);
GCC_SYMBOLS_PRIVATE_EXTERN = NO;
GCC_TREAT_WARNINGS_AS_ERRORS = NO;
GCC_VERSION = "";
GCC_WARN_ALLOW_INCOMPLETE_PROTOCOL = NO;
HEADER_SEARCH_PATHS = (
"\"$(SDKROOT)/usr/include/libxml2/\"",
"\"$(SRCROOT)/../../cocos2dx/\"",
"\"$(SRCROOT)/../../cocos2dx/kazmath/include\"",
"\"$(SRCROOT)/../../lua/tolua\"",
"\"$(SRCROOT)/../../lua/src\"",
"$(SRCROOT)/../../lua/cocos2dx_support",
"$(SRCROOT)/../../cocos2dx/platform/ios",
"$(SRCROOT)/../../cocos2dx/include",
);
INFOPLIST_FILE = Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 5.0;
LIBRARY_SEARCH_PATHS = (
"$(inherited)",
"\"$(SRCROOT)/../../cocos2dx/platform/third_party/ios/libraries\"",
);
ONLY_ACTIVE_ARCH = YES;
OTHER_LDFLAGS = (
"-ObjC",
"-all_load",
);
PREBINDING = NO;
PRODUCT_NAME = HelloLua;
SDKROOT = iphoneos;
SKIP_INSTALL = YES;
TARGETED_DEVICE_FAMILY = "1,2";
VALIDATE_PRODUCT = NO;
WARNING_CFLAGS = "";
};
name = Debug;
};
1D6058950D05DD3E006BFB54 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
COPY_PHASE_STRIP = YES;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
GCC_ENABLE_FIX_AND_CONTINUE = NO;
GCC_FAST_OBJC_DISPATCH = YES;
GCC_INLINES_ARE_PRIVATE_EXTERN = NO;
GCC_OBJC_CALL_CXX_CDTORS = YES;
GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = HelloLua_Prefix.pch;
GCC_PREPROCESSOR_DEFINITIONS = (
USE_FILE32API,
TARGET_OS_IPHONE,
);
GCC_SYMBOLS_PRIVATE_EXTERN = NO;
GCC_TREAT_WARNINGS_AS_ERRORS = NO;
GCC_VERSION = "";
GCC_WARN_ALLOW_INCOMPLETE_PROTOCOL = NO;
HEADER_SEARCH_PATHS = (
"\"$(SDKROOT)/usr/include/libxml2/\"",
"\"$(SRCROOT)/../../cocos2dx/\"",
"\"$(SRCROOT)/../../cocos2dx/kazmath/include\"",
"\"$(SRCROOT)/../../lua/tolua\"",
"\"$(SRCROOT)/../../lua/src\"",
"$(SRCROOT)/../../lua/cocos2dx_support",
"$(SRCROOT)/../../cocos2dx/platform/ios",
"$(SRCROOT)/../../cocos2dx/include",
);
INFOPLIST_FILE = Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 5.0;
LIBRARY_SEARCH_PATHS = (
"$(inherited)",
"\"$(SRCROOT)/../../cocos2dx/platform/third_party/ios/libraries\"",
);
ONLY_ACTIVE_ARCH = NO;
OTHER_LDFLAGS = (
"-ObjC",
"-all_load",
);
PREBINDING = NO;
PRODUCT_NAME = HelloLua;
SDKROOT = iphoneos;
SKIP_INSTALL = YES;
TARGETED_DEVICE_FAMILY = "1,2";
VALIDATE_PRODUCT = NO;
WARNING_CFLAGS = "";
};
name = Release;
};
C01FCF4F08A954540054247B /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
ARCHS = "$(ARCHS_STANDARD_32_BIT)";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
GCC_C_LANGUAGE_STANDARD = c99;
GCC_PREPROCESSOR_DEFINITIONS = (
DEBUG,
"COCOS2D_DEBUG=1",
"CD_DEBUG=1",
);
"GCC_THUMB_SUPPORT[arch=armv6]" = NO;
"GCC_THUMB_SUPPORT[arch=armv7]" = YES;
GCC_VERSION = "";
GCC_WARN_ABOUT_RETURN_TYPE = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 3.0;
ONLY_ACTIVE_ARCH = YES;
PREBINDING = NO;
SDKROOT = iphoneos;
TARGETED_DEVICE_FAMILY = "1,2";
VALID_ARCHS = "armv6 armv7 i386";
};
name = Debug;
};
C01FCF5008A954540054247B /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
ARCHS = "$(ARCHS_STANDARD_32_BIT)";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
GCC_C_LANGUAGE_STANDARD = c99;
"GCC_THUMB_SUPPORT[arch=armv6]" = NO;
"GCC_THUMB_SUPPORT[arch=armv7]" = YES;
GCC_UNROLL_LOOPS = YES;
GCC_VERSION = "";
GCC_WARN_ABOUT_RETURN_TYPE = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 3.0;
PREBINDING = NO;
SDKROOT = iphoneos;
TARGETED_DEVICE_FAMILY = "1,2";
VALID_ARCHS = "armv6 armv7 i386";
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
1D6058960D05DD3E006BFB54 /* Build configuration list for PBXNativeTarget "HelloLua" */ = {
isa = XCConfigurationList;
buildConfigurations = (
1D6058940D05DD3E006BFB54 /* Debug */,
1D6058950D05DD3E006BFB54 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
C01FCF4E08A954540054247B /* Build configuration list for PBXProject "HelloLua" */ = {
isa = XCConfigurationList;
buildConfigurations = (
C01FCF4F08A954540054247B /* Debug */,
C01FCF5008A954540054247B /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 29B97313FDCFA39411CA2CEA /* Project object */;
}

View File

@ -1 +0,0 @@
842462907b895bea8fcf8fc4a567560e546e440f

View File

@ -20,7 +20,7 @@
OutputDirectory="$(SolutionDir)$(ConfigurationName).win32" OutputDirectory="$(SolutionDir)$(ConfigurationName).win32"
IntermediateDirectory="$(ConfigurationName).win32" IntermediateDirectory="$(ConfigurationName).win32"
ConfigurationType="1" ConfigurationType="1"
CharacterSet="2" CharacterSet="1"
> >
<Tool <Tool
Name="VCPreBuildEventTool" Name="VCPreBuildEventTool"
@ -49,15 +49,15 @@
<Tool <Tool
Name="VCCLCompilerTool" Name="VCCLCompilerTool"
Optimization="0" Optimization="0"
AdditionalIncludeDirectories="..\Classes;&quot;$(SolutionDir)\lua\cocos2dx_support&quot;;&quot;$(SolutionDir)\lua\CocosDenshion_support&quot;;&quot;$(SolutionDir)\lua\lua&quot;;&quot;$(SolutionDir)\lua\tolua&quot;;&quot;$(SolutionDir)\lua\src&quot;;.;&quot;$(SolutionDir)cocos2dx&quot;;&quot;$(SolutionDir)cocos2dx\actions&quot;;&quot;$(SolutionDir)cocos2dx\base_nodes&quot;;&quot;$(SolutionDir)cocos2dx\cocoa&quot;;&quot;$(SolutionDir)cocos2dx\effects&quot;;&quot;$(SolutionDir)cocos2dx\include&quot;;&quot;$(SolutionDir)cocos2dx\kazmath\include&quot;;&quot;$(SolutionDir)cocos2dx\keypad_dispatcher&quot;;&quot;$(SolutionDir)cocos2dx\label_nodes&quot;;&quot;$(SolutionDir)cocos2dx\layers_scenes_transitions_nodes&quot;;&quot;$(SolutionDir)cocos2dx\menu_nodes&quot;;&quot;$(SolutionDir)cocos2dx\misc_nodes&quot;;&quot;$(SolutionDir)cocos2dx\particle_nodes&quot;;&quot;$(SolutionDir)cocos2dx\script_support&quot;;&quot;$(SolutionDir)cocos2dx\shaders&quot;;&quot;$(SolutionDir)cocos2dx\sprite_nodes&quot;;&quot;$(SolutionDir)cocos2dx\support&quot;;&quot;$(SolutionDir)cocos2dx\text_input_node&quot;;&quot;$(SolutionDir)cocos2dx\textures&quot;;&quot;$(SolutionDir)cocos2dx\tileMap_parallax_nodes&quot;;&quot;$(SolutionDir)cocos2dx\touch_dispatcher&quot;;&quot;$(SolutionDir)cocos2dx\platform&quot;;&quot;$(SolutionDir)cocos2dx\platform\win32&quot;;&quot;$(SolutionDir)cocos2dx\platform\third_party\win32\OGLES&quot;;&quot;$(SolutionDir)CocosDenshion\include&quot;" AdditionalIncludeDirectories="..\Classes;&quot;$(SolutionDir)\lua\cocos2dx_support&quot;;&quot;$(SolutionDir)\lua\CocosDenshion_support&quot;;&quot;$(SolutionDir)\lua\lua&quot;;&quot;$(SolutionDir)\lua\tolua&quot;;&quot;$(SolutionDir)\lua\src&quot;;.;&quot;$(SolutionDir)cocos2dx&quot;;&quot;$(SolutionDir)cocos2dx\include&quot;;&quot;$(SolutionDir)cocos2dx\kazmath\include&quot;;&quot;$(SolutionDir)cocos2dx\platform\win32&quot;;&quot;$(SolutionDir)cocos2dx\platform\third_party\win32\OGLES&quot;;&quot;$(SolutionDir)CocosDenshion\include&quot;"
PreprocessorDefinitions="WIN32;_WINDOWS;STRICT;_DEBUG;COCOS2D_DEBUG=1" PreprocessorDefinitions="WIN32;_WINDOWS;STRICT;_DEBUG;COCOS2D_DEBUG=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS"
MinimalRebuild="true" MinimalRebuild="true"
BasicRuntimeChecks="3" BasicRuntimeChecks="3"
RuntimeLibrary="3" RuntimeLibrary="3"
UsePrecompiledHeader="0" UsePrecompiledHeader="0"
WarningLevel="3" WarningLevel="3"
DebugInformationFormat="4" DebugInformationFormat="4"
DisableSpecificWarnings="4251" DisableSpecificWarnings="4267;4251;4244"
/> />
<Tool <Tool
Name="VCManagedResourceCompilerTool" Name="VCManagedResourceCompilerTool"
@ -73,7 +73,7 @@
/> />
<Tool <Tool
Name="VCLinkerTool" Name="VCLinkerTool"
AdditionalDependencies="libcocos2d.lib libCocosDenshion.lib libGLESv2.lib liblua.lib" AdditionalDependencies="libcocos2d.lib libCocosDenshion.lib opengl32.lib glew32.lib liblua.lib"
LinkIncremental="2" LinkIncremental="2"
AdditionalLibraryDirectories="$(OutDir)" AdditionalLibraryDirectories="$(OutDir)"
GenerateDebugInformation="true" GenerateDebugInformation="true"
@ -107,7 +107,7 @@
OutputDirectory="$(SolutionDir)$(ConfigurationName).win32" OutputDirectory="$(SolutionDir)$(ConfigurationName).win32"
IntermediateDirectory="$(ConfigurationName).win32" IntermediateDirectory="$(ConfigurationName).win32"
ConfigurationType="1" ConfigurationType="1"
CharacterSet="2" CharacterSet="1"
> >
<Tool <Tool
Name="VCPreBuildEventTool" Name="VCPreBuildEventTool"
@ -135,14 +135,14 @@
/> />
<Tool <Tool
Name="VCCLCompilerTool" Name="VCCLCompilerTool"
AdditionalIncludeDirectories="..\Classes;&quot;$(SolutionDir)lua\cocos2dx_support&quot;;&quot;$(SolutionDir)lua\CocosDenshion_support&quot;;&quot;$(SolutionDir)lua\tolua&quot;;&quot;$(SolutionDir)lua\lua&quot;;&quot;$(SolutionDir)cocos2dx&quot;;&quot;$(SolutionDir)cocos2dx\include&quot;;&quot;$(SolutionDir)cocos2dx\platform&quot;;&quot;$(SolutionDir)cocos2dx\platform\third_party\win32\OGLES&quot;;&quot;$(SolutionDir)CocosDenshion\Include&quot;" AdditionalIncludeDirectories="..\Classes;&quot;$(SolutionDir)\lua\cocos2dx_support&quot;;&quot;$(SolutionDir)\lua\CocosDenshion_support&quot;;&quot;$(SolutionDir)\lua\lua&quot;;&quot;$(SolutionDir)\lua\tolua&quot;;&quot;$(SolutionDir)\lua\src&quot;;.;&quot;$(SolutionDir)cocos2dx&quot;;&quot;$(SolutionDir)cocos2dx\include&quot;;&quot;$(SolutionDir)cocos2dx\kazmath\include&quot;;&quot;$(SolutionDir)cocos2dx\platform\win32&quot;;&quot;$(SolutionDir)cocos2dx\platform\third_party\win32\OGLES&quot;;&quot;$(SolutionDir)CocosDenshion\include&quot;"
PreprocessorDefinitions="WIN32;_WINDOWS;STRICT;NDEBUG" PreprocessorDefinitions="WIN32;_WINDOWS;STRICT;NDEBUG;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS"
ExceptionHandling="0" ExceptionHandling="0"
RuntimeLibrary="2" RuntimeLibrary="2"
UsePrecompiledHeader="0" UsePrecompiledHeader="0"
WarningLevel="3" WarningLevel="3"
DebugInformationFormat="0" DebugInformationFormat="0"
DisableSpecificWarnings="4251" DisableSpecificWarnings="4267;4251;4244"
/> />
<Tool <Tool
Name="VCManagedResourceCompilerTool" Name="VCManagedResourceCompilerTool"
@ -158,7 +158,7 @@
/> />
<Tool <Tool
Name="VCLinkerTool" Name="VCLinkerTool"
AdditionalDependencies="libcocos2d.lib libCocosDenshion.lib libgles_cm.lib liblua.lib" AdditionalDependencies="libcocos2d.lib libCocosDenshion.lib opengl32.lib glew32.lib liblua.lib"
LinkIncremental="1" LinkIncremental="1"
AdditionalLibraryDirectories="$(OutDir)" AdditionalLibraryDirectories="$(OutDir)"
SubSystem="2" SubSystem="2"

View File

@ -18,11 +18,11 @@
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType> <ConfigurationType>Application</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet> <CharacterSet>Unicode</CharacterSet>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType> <ConfigurationType>Application</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet> <CharacterSet>Unicode</CharacterSet>
</PropertyGroup> </PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings"> <ImportGroup Label="ExtensionSettings">
@ -64,8 +64,8 @@
</Midl> </Midl>
<ClCompile> <ClCompile>
<Optimization>Disabled</Optimization> <Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>.;..\Classes;..\..\cocos2dx;..\..\cocos2dx\actions;..\..\cocos2dx\base_nodes;..\..\cocos2dx\cocoa;..\..\cocos2dx\effects;..\..\cocos2dx\include;..\..\cocos2dx\kazmath\include;..\..\cocos2dx\keypad_dispatcher;..\..\cocos2dx\label_nodes;..\..\cocos2dx\layers_scenes_transitions_nodes;..\..\cocos2dx\menu_nodes;..\..\cocos2dx\misc_nodes;..\..\cocos2dx\particle_nodes;..\..\cocos2dx\script_support;..\..\cocos2dx\shaders;..\..\cocos2dx\sprite_nodes;..\..\cocos2dx\support;..\..\cocos2dx\text_input_node;..\..\cocos2dx\textures;..\..\cocos2dx\tileMap_parallax_nodes;..\..\cocos2dx\touch_dispatcher;..\..\cocos2dx\platform;..\..\cocos2dx\platform\win32;..\..\cocos2dx\platform\third_party\win32;..\..\cocos2dx\platform\third_party\win32\OGLES;..\..\CocosDenshion\Include;..\..\lua\cocos2dx_support;..\..\lua\tolua;..\..\lua\lua;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <AdditionalIncludeDirectories>.;..\Classes;..\..\cocos2dx;..\..\cocos2dx\include;..\..\cocos2dx\kazmath\include;..\..\cocos2dx\platform\win32;..\..\cocos2dx\platform\third_party\win32;..\..\cocos2dx\platform\third_party\win32\OGLES;..\..\CocosDenshion\Include;..\..\lua\cocos2dx_support;..\..\lua\tolua;..\..\lua\lua;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_WINDOWS;STRICT;_DEBUG;COCOS2D_DEBUG=1;ENABLE_LUA;%(PreprocessorDefinitions)</PreprocessorDefinitions> <PreprocessorDefinitions>WIN32;_WINDOWS;STRICT;_DEBUG;COCOS2D_DEBUG=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>true</MinimalRebuild> <MinimalRebuild>true</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks> <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary> <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
@ -73,7 +73,7 @@
</PrecompiledHeader> </PrecompiledHeader>
<WarningLevel>Level3</WarningLevel> <WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>EditAndContinue</DebugInformationFormat> <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
<DisableSpecificWarnings>4251;%(DisableSpecificWarnings)</DisableSpecificWarnings> <DisableSpecificWarnings>4267;4251;4244;%(DisableSpecificWarnings)</DisableSpecificWarnings>
</ClCompile> </ClCompile>
<ResourceCompile> <ResourceCompile>
<PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions> <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
@ -102,8 +102,8 @@
<ProxyFileName>HelloLua_p.c</ProxyFileName> <ProxyFileName>HelloLua_p.c</ProxyFileName>
</Midl> </Midl>
<ClCompile> <ClCompile>
<AdditionalIncludeDirectories>.;..\Classes;..\..\cocos2dx;..\..\cocos2dx\actions;..\..\cocos2dx\base_nodes;..\..\cocos2dx\cocoa;..\..\cocos2dx\effects;..\..\cocos2dx\include;..\..\cocos2dx\kazmath\include;..\..\cocos2dx\keypad_dispatcher;..\..\cocos2dx\label_nodes;..\..\cocos2dx\layers_scenes_transitions_nodes;..\..\cocos2dx\menu_nodes;..\..\cocos2dx\misc_nodes;..\..\cocos2dx\particle_nodes;..\..\cocos2dx\script_support;..\..\cocos2dx\shaders;..\..\cocos2dx\sprite_nodes;..\..\cocos2dx\support;..\..\cocos2dx\text_input_node;..\..\cocos2dx\textures;..\..\cocos2dx\tileMap_parallax_nodes;..\..\cocos2dx\touch_dispatcher;..\..\cocos2dx\platform;..\..\cocos2dx\platform\win32;..\..\cocos2dx\platform\third_party\win32;..\..\cocos2dx\platform\third_party\win32\OGLES;..\..\CocosDenshion\Include;..\..\lua\cocos2dx_support;..\..\lua\tolua;..\..\lua\lua;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <AdditionalIncludeDirectories>.;..\Classes;..\..\cocos2dx;..\..\cocos2dx\include;..\..\cocos2dx\kazmath\include;..\..\cocos2dx\platform\win32;..\..\cocos2dx\platform\third_party\win32;..\..\cocos2dx\platform\third_party\win32\OGLES;..\..\CocosDenshion\Include;..\..\lua\cocos2dx_support;..\..\lua\tolua;..\..\lua\lua;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_WINDOWS;STRICT;NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions> <PreprocessorDefinitions>WIN32;_WINDOWS;STRICT;NDEBUG;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ExceptionHandling> <ExceptionHandling>
</ExceptionHandling> </ExceptionHandling>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary> <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
@ -112,7 +112,7 @@
<WarningLevel>Level3</WarningLevel> <WarningLevel>Level3</WarningLevel>
<DebugInformationFormat> <DebugInformationFormat>
</DebugInformationFormat> </DebugInformationFormat>
<DisableSpecificWarnings>4251;%(DisableSpecificWarnings)</DisableSpecificWarnings> <DisableSpecificWarnings>4267;4251;4244;%(DisableSpecificWarnings)</DisableSpecificWarnings>
</ClCompile> </ClCompile>
<ResourceCompile> <ResourceCompile>
<PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions> <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
@ -120,7 +120,7 @@
<AdditionalIncludeDirectories>$(IntDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <AdditionalIncludeDirectories>$(IntDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ResourceCompile> </ResourceCompile>
<Link> <Link>
<AdditionalDependencies>libcocos2d.lib;libCocosDenshion.lib;libgles_cm.lib;liblua.lib;%(AdditionalDependencies)</AdditionalDependencies> <AdditionalDependencies>libcocos2d.lib;libCocosDenshion.lib;liblua.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalLibraryDirectories>$(OutDir);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories> <AdditionalLibraryDirectories>$(OutDir);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<SubSystem>Windows</SubSystem> <SubSystem>Windows</SubSystem>
<TargetMachine>MachineX86</TargetMachine> <TargetMachine>MachineX86</TargetMachine>

View File

@ -1,10 +1,6 @@
#include "AppDelegate.h" #include "AppDelegate.h"
#include "cocos2d.h"
#include "HelloWorldScene.h" #include "HelloWorldScene.h"
#include "CCEGLView.h"
USING_NS_CC; USING_NS_CC;
AppDelegate::AppDelegate() { AppDelegate::AppDelegate() {
@ -27,8 +23,6 @@ bool AppDelegate::applicationDidFinishLaunching() {
// turn on display FPS // turn on display FPS
pDirector->setDisplayStats(true); pDirector->setDisplayStats(true);
// pDirector->setDeviceOrientation(kCCDeviceOrientationLandscapeLeft);
// set FPS. the default value is 1.0/60 if you don't call this // set FPS. the default value is 1.0/60 if you don't call this
pDirector->setAnimationInterval(1.0 / 60); pDirector->setAnimationInterval(1.0 / 60);
@ -43,7 +37,7 @@ bool AppDelegate::applicationDidFinishLaunching() {
// This function will be called when the app is inactive. When comes a phone call,it's be invoked too // This function will be called when the app is inactive. When comes a phone call,it's be invoked too
void AppDelegate::applicationDidEnterBackground() { void AppDelegate::applicationDidEnterBackground() {
CCDirector::sharedDirector()->pause(); CCDirector::sharedDirector()->stopAnimation();
// if you use SimpleAudioEngine, it must be pause // if you use SimpleAudioEngine, it must be pause
// SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic(); // SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic();
@ -51,7 +45,7 @@ void AppDelegate::applicationDidEnterBackground() {
// this function will be called when the app is active again // this function will be called when the app is active again
void AppDelegate::applicationWillEnterForeground() { void AppDelegate::applicationWillEnterForeground() {
CCDirector::sharedDirector()->resume(); CCDirector::sharedDirector()->startAnimation();
// if you use SimpleAudioEngine, it must resume here // if you use SimpleAudioEngine, it must resume here
// SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic(); // SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic();

View File

@ -1,7 +1,7 @@
#ifndef _APP_DELEGATE_H_ #ifndef _APP_DELEGATE_H_
#define _APP_DELEGATE_H_ #define _APP_DELEGATE_H_
#include "CCApplication.h" #include "cocos2d.h"
/** /**
@brief The cocos2d Application. @brief The cocos2d Application.

View File

@ -5,10 +5,10 @@ USING_NS_CC;
CCScene* HelloWorld::scene() CCScene* HelloWorld::scene()
{ {
// 'scene' is an autorelease object // 'scene' is an autorelease object
CCScene *scene = CCScene::node(); CCScene *scene = CCScene::create();
// 'layer' is an autorelease object // 'layer' is an autorelease object
HelloWorld *layer = HelloWorld::node(); HelloWorld *layer = HelloWorld::create();
// add layer as a child to scene // add layer as a child to scene
scene->addChild(layer); scene->addChild(layer);
@ -32,7 +32,7 @@ bool HelloWorld::init()
// you may modify it. // you may modify it.
// add a "close" icon to exit the progress. it's an autorelease object // add a "close" icon to exit the progress. it's an autorelease object
CCMenuItemImage *pCloseItem = CCMenuItemImage::itemWithNormalImage( CCMenuItemImage *pCloseItem = CCMenuItemImage::create(
"CloseNormal.png", "CloseNormal.png",
"CloseSelected.png", "CloseSelected.png",
this, this,
@ -40,7 +40,7 @@ bool HelloWorld::init()
pCloseItem->setPosition( ccp(CCDirector::sharedDirector()->getWinSize().width - 20, 20) ); pCloseItem->setPosition( ccp(CCDirector::sharedDirector()->getWinSize().width - 20, 20) );
// create menu, it's an autorelease object // create menu, it's an autorelease object
CCMenu* pMenu = CCMenu::menuWithItems(pCloseItem, NULL); CCMenu* pMenu = CCMenu::create(pCloseItem, NULL);
pMenu->setPosition( CCPointZero ); pMenu->setPosition( CCPointZero );
this->addChild(pMenu, 1); this->addChild(pMenu, 1);
@ -49,7 +49,7 @@ bool HelloWorld::init()
// add a label shows "Hello World" // add a label shows "Hello World"
// create and initialize a label // create and initialize a label
CCLabelTTF* pLabel = CCLabelTTF::labelWithString("Hello World", "Arial", 24); CCLabelTTF* pLabel = CCLabelTTF::create("Hello World", "Arial", 24);
// ask director the window size // ask director the window size
CCSize size = CCDirector::sharedDirector()->getWinSize(); CCSize size = CCDirector::sharedDirector()->getWinSize();
@ -60,7 +60,7 @@ bool HelloWorld::init()
this->addChild(pLabel, 1); this->addChild(pLabel, 1);
// add "HelloWorld" splash screen" // add "HelloWorld" splash screen"
CCSprite* pSprite = CCSprite::spriteWithFile("HelloWorld.png"); CCSprite* pSprite = CCSprite::create("HelloWorld.png");
// position the sprite on the center of the screen // position the sprite on the center of the screen
pSprite->setPosition( ccp(size.width/2, size.height/2) ); pSprite->setPosition( ccp(size.width/2, size.height/2) );

View File

@ -13,10 +13,10 @@ public:
static cocos2d::CCScene* scene(); static cocos2d::CCScene* scene();
// a selector callback // a selector callback
virtual void menuCloseCallback(CCObject* pSender); void menuCloseCallback(CCObject* pSender);
// implement the "static node()" method manually // implement the "static node()" method manually
LAYER_NODE_FUNC(HelloWorld); LAYER_CREATE_FUNC(HelloWorld);
}; };
#endif // __HELLOWORLD_SCENE_H__ #endif // __HELLOWORLD_SCENE_H__

View File

@ -1,5 +0,0 @@
[Trace]
GAME <0 or 1> Game Channel
[Assert]
GAME <0 or 1> Game Assert Channel

View File

@ -1,17 +0,0 @@
[S3E]
MemSize=4000000
#MemFlags0=USE_STACK_ALLOCATOR
#SysStackSwitch=1
#landscape
#DispFixRot=2
#or portrait
#DispFixRot=1
#autorotate
#DispFixRot=0
# fix for new ati drivers in simulator
# DisableGL=1
[Trace]
GAME=1
IW_GL=1
IW_GL_VERBOSE=1

View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="gen"/>
<classpathentry kind="src" path="src_common"/>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
<classpathentry kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
<classpathentry kind="output" path="bin/classes"/>
</classpath>

View File

@ -0,0 +1,40 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>HelloWorld</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.ApkBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>com.android.ide.eclipse.adt.AndroidNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
<linkedResources>
<link>
<name>src_common</name>
<type>2</type>
<locationURI>PARENT-2-PROJECT_LOC/cocos2dx/platform/android/java/src_common</locationURI>
</link>
</linkedResources>
</projectDescription>

View File

@ -0,0 +1,85 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="HelloWorld" default="help">
<!-- The local.properties file is created and updated by the 'android' tool.
It contains the path to the SDK. It should *NOT* be checked into
Version Control Systems. -->
<property file="local.properties" />
<!-- The ant.properties file can be created by you. It is only edited by the
'android' tool to add properties to it.
This is the place to change some Ant specific build properties.
Here are some properties you may want to change/update:
source.dir
The name of the source directory. Default is 'src'.
out.dir
The name of the output directory. Default is 'bin'.
For other overridable properties, look at the beginning of the rules
files in the SDK, at tools/ant/build.xml
Properties related to the SDK location or the project target should
be updated using the 'android' tool with the 'update' action.
This file is an integral part of the build system for your
application and should be checked into Version Control Systems.
-->
<property file="ant.properties" />
<!-- The project.properties file is created and updated by the 'android'
tool, as well as ADT.
This contains project specific properties such as project target, and library
dependencies. Lower level build properties are stored in ant.properties
(or in .classpath for Eclipse projects).
This file is an integral part of the build system for your
application and should be checked into Version Control Systems. -->
<loadproperties srcFile="project.properties" />
<!-- quick check on sdk.dir -->
<fail
message="sdk.dir is missing. Make sure to generate local.properties using 'android update project' or to inject it through an env var"
unless="sdk.dir"
/>
<!-- extension targets. Uncomment the ones where you want to do custom work
in between standard targets -->
<!--
<target name="-pre-build">
</target>
<target name="-pre-compile">
</target>
/* This is typically used for code obfuscation.
Compiled code location: ${out.classes.absolute.dir}
If this is not done in place, override ${out.dex.input.absolute.dir} */
<target name="-post-compile">
</target>
-->
<!-- Import the actual build file.
To customize existing targets, there are two options:
- Customize only one target:
- copy/paste the target into this file, *before* the
<import> task.
- customize it to your needs.
- Customize the whole content of build.xml
- copy/paste the content of the rules files (minus the top node)
into this file, replacing the <import> task.
- customize to your needs.
***********************
****** IMPORTANT ******
***********************
In all cases you must update the value of version-tag below to read 'custom' instead of an integer,
in order to avoid having your file be overridden by tools such as "android update project"
-->
<!-- version-tag: 1 -->
<import file="${sdk.dir}/tools/ant/build.xml" />
</project>

View File

@ -60,6 +60,9 @@ cp $file $HELLOWORLD_ROOT/assets
fi fi
done done
# Change the authority of Resources folder.
chmod -R 666 $HELLOWORLD_ROOT/assets
if [[ $buildexternalsfromsource ]]; then if [[ $buildexternalsfromsource ]]; then
echo "Building external dependencies from source" echo "Building external dependencies from source"
$NDK_ROOT_LOCAL/ndk-build -C $HELLOWORLD_ROOT $* \ $NDK_ROOT_LOCAL/ndk-build -C $HELLOWORLD_ROOT $* \

View File

@ -1,26 +0,0 @@
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package org.cocos2dx.application;
public final class R {
public static final class attr {
}
public static final class drawable {
public static final int icon=0x7f020000;
}
public static final class id {
public static final int helloworld_gl_surfaceview=0x7f050001;
public static final int textField=0x7f050000;
}
public static final class layout {
public static final int helloworld_demo=0x7f030000;
}
public static final class string {
public static final int app_name=0x7f040000;
}
}

View File

@ -1,20 +1,20 @@
LOCAL_PATH := $(call my-dir) LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS) include $(CLEAR_VARS)
LOCAL_MODULE := helloworld_shared LOCAL_MODULE := helloworld_shared
LOCAL_MODULE_FILENAME := libhelloworld LOCAL_MODULE_FILENAME := libhelloworld
LOCAL_SRC_FILES := helloworld/main.cpp \ LOCAL_SRC_FILES := helloworld/main.cpp \
../../Classes/AppDelegate.cpp \ ../../Classes/AppDelegate.cpp \
../../Classes/HelloWorldScene.cpp ../../Classes/HelloWorldScene.cpp
LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes
LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static
include $(BUILD_SHARED_LIBRARY) include $(BUILD_SHARED_LIBRARY)
$(call import-module,cocos2dx) $(call import-module,cocos2dx)

View File

@ -1,2 +1,2 @@
APP_STL := gnustl_static APP_STL := gnustl_static
APP_CPPFLAGS := -frtti APP_CPPFLAGS := -frtti

View File

@ -1,7 +1,5 @@
#include "AppDelegate.h" #include "AppDelegate.h"
#include "cocos2d.h"
#include "platform/android/jni/JniHelper.h" #include "platform/android/jni/JniHelper.h"
#include "CCEventType.h"
#include <jni.h> #include <jni.h>
#include <android/log.h> #include <android/log.h>
@ -30,7 +28,7 @@ void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeInit(JNIEnv* env, jobject thi
CCEGLView *view = &CCEGLView::sharedOpenGLView(); CCEGLView *view = &CCEGLView::sharedOpenGLView();
view->setFrameSize(w, h); view->setFrameSize(w, h);
// set the design resolution screen size, if you want to use Design Resoulution scaled to current screen, please uncomment next line. // set the design resolution screen size, if you want to use Design Resoulution scaled to current screen, please uncomment next line.
// view.setDesignResolutionSize(480, 320); // view->setDesignResolutionSize(480, 320);
AppDelegate *pAppDelegate = new AppDelegate(); AppDelegate *pAppDelegate = new AppDelegate();
CCApplication::sharedApplication().run(); CCApplication::sharedApplication().run();

View File

@ -8,4 +8,6 @@
# project structure. # project structure.
# Project target. # Project target.
target=android-10 target=android-8
android.library.reference.1=../../cocos2dx/platform/android/java

View File

@ -1,18 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<org.cocos2dx.lib.Cocos2dxEditText
android:id="@+id/textField"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:background="@null"/>
<org.cocos2dx.lib.Cocos2dxGLSurfaceView
android:id="@+id/helloworld_gl_surfaceview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</FrameLayout>

View File

@ -33,6 +33,8 @@ import android.content.Context;
import android.content.pm.ConfigurationInfo; import android.content.pm.ConfigurationInfo;
import android.os.Bundle; import android.os.Bundle;
import android.util.Log; import android.util.Log;
import android.widget.FrameLayout;
import android.view.ViewGroup;
public class ApplicationDemo extends Cocos2dxActivity{ public class ApplicationDemo extends Cocos2dxActivity{
private Cocos2dxGLSurfaceView mGLView; private Cocos2dxGLSurfaceView mGLView;
@ -45,11 +47,35 @@ public class ApplicationDemo extends Cocos2dxActivity{
String packageName = getApplication().getPackageName(); String packageName = getApplication().getPackageName();
super.setPackageName(packageName); super.setPackageName(packageName);
setContentView(R.layout.helloworld_demo); // FrameLayout
mGLView = (Cocos2dxGLSurfaceView) findViewById(R.id.helloworld_gl_surfaceview); ViewGroup.LayoutParams framelayout_params =
mGLView.setTextField((Cocos2dxEditText)findViewById(R.id.textField)); 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
mGLView = new Cocos2dxGLSurfaceView(this);
// ...add to FrameLayout
framelayout.addView(mGLView);
mGLView.setEGLContextClientVersion(2); mGLView.setEGLContextClientVersion(2);
mGLView.setCocos2dxRenderer(new Cocos2dxRenderer()); mGLView.setCocos2dxRenderer(new Cocos2dxRenderer());
mGLView.setTextField(edittext);
// Set framelayout as the content view
setContentView(framelayout);
} }
else { else {
Log.d("activity", "don't support gles2.0"); Log.d("activity", "don't support gles2.0");

View File

@ -1,107 +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.view.Display;
import android.view.Surface;
import android.view.WindowManager;
/**
*
* This class is used for controlling the Accelerometer
*
*/
public class Cocos2dxAccelerometer implements SensorEventListener {
private static final String TAG = "Cocos2dxAccelerometer";
private Context mContext;
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private int mNaturalOrientation;
public Cocos2dxAccelerometer(Context context){
mContext = context;
//Get an instance of the SensorManager
mSensorManager = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
Display display = ((WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
mNaturalOrientation = display.getOrientation();
}
public void enable() {
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_GAME);
}
public void disable () {
mSensorManager.unregisterListener(this);
}
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER){
return;
}
float x = event.values[0];
float y = event.values[1];
float z = event.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.
*/
int orientation = mContext.getResources().getConfiguration().orientation;
if ((orientation == Configuration.ORIENTATION_LANDSCAPE) && (mNaturalOrientation != Surface.ROTATION_0)){
float tmp = x;
x = -y;
y = tmp;
}
else if ((orientation == Configuration.ORIENTATION_PORTRAIT) && (mNaturalOrientation != Surface.ROTATION_0))
{
float tmp = x;
x = y;
y = -tmp;
}
onSensorChanged(x, y, z, event.timestamp);
// Log.d(TAG, "x = " + event.values[0] + " y = " + event.values[1] + " z = " + event.values[2]);
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
private static native void onSensorChanged(float x, float y, float z, long timeStamp);
}

View File

@ -1,253 +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.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
public class Cocos2dxActivity extends Activity{
private static Cocos2dxMusic backgroundMusicPlayer;
private static Cocos2dxSound soundPlayer;
private static Cocos2dxAccelerometer accelerometer;
private static boolean accelerometerEnabled = false;
private static Handler handler;
private final static int HANDLER_SHOW_DIALOG = 1;
private static String packageName;
private static native void nativeSetPaths(String apkPath);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// get frame size
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
accelerometer = new Cocos2dxAccelerometer(this);
// init media player and sound player
backgroundMusicPlayer = new Cocos2dxMusic(this);
soundPlayer = new Cocos2dxSound(this);
// init bitmap context
Cocos2dxBitmap.setContext(this);
handler = new Handler(){
public void handleMessage(Message msg){
switch(msg.what){
case HANDLER_SHOW_DIALOG:
showDialog(((DialogMessage)msg.obj).title, ((DialogMessage)msg.obj).message);
break;
}
}
};
}
public static String getCurrentLanguage() {
String languageName = java.util.Locale.getDefault().getLanguage();
return languageName;
}
public static void showMessageBox(String title, String message){
Message msg = new Message();
msg.what = HANDLER_SHOW_DIALOG;
msg.obj = new DialogMessage(title, message);
handler.sendMessage(msg);
}
public static void enableAccelerometer() {
accelerometerEnabled = true;
accelerometer.enable();
}
public static void disableAccelerometer() {
accelerometerEnabled = false;
accelerometer.disable();
}
public static void preloadBackgroundMusic(String path){
backgroundMusicPlayer.preloadBackgroundMusic(path);
}
public static void playBackgroundMusic(String path, boolean isLoop){
backgroundMusicPlayer.playBackgroundMusic(path, isLoop);
}
public static void stopBackgroundMusic(){
backgroundMusicPlayer.stopBackgroundMusic();
}
public static void pauseBackgroundMusic(){
backgroundMusicPlayer.pauseBackgroundMusic();
}
public static void resumeBackgroundMusic(){
backgroundMusicPlayer.resumeBackgroundMusic();
}
public static void rewindBackgroundMusic(){
backgroundMusicPlayer.rewindBackgroundMusic();
}
public static boolean isBackgroundMusicPlaying(){
return backgroundMusicPlayer.isBackgroundMusicPlaying();
}
public static float getBackgroundMusicVolume(){
return backgroundMusicPlayer.getBackgroundVolume();
}
public static void setBackgroundMusicVolume(float volume){
backgroundMusicPlayer.setBackgroundVolume(volume);
}
public static int playEffect(String path, boolean isLoop){
return soundPlayer.playEffect(path, isLoop);
}
public static void stopEffect(int soundId){
soundPlayer.stopEffect(soundId);
}
public static void pauseEffect(int soundId){
soundPlayer.pauseEffect(soundId);
}
public static void resumeEffect(int soundId){
soundPlayer.resumeEffect(soundId);
}
public static float getEffectsVolume(){
return soundPlayer.getEffectsVolume();
}
public static void setEffectsVolume(float volume){
soundPlayer.setEffectsVolume(volume);
}
public static void preloadEffect(String path){
soundPlayer.preloadEffect(path);
}
public static void unloadEffect(String path){
soundPlayer.unloadEffect(path);
}
public static void stopAllEffects(){
soundPlayer.stopAllEffects();
}
public static void pauseAllEffects(){
soundPlayer.pauseAllEffects();
}
public static void resumeAllEffects(){
soundPlayer.resumeAllEffects();
}
public static void end(){
backgroundMusicPlayer.end();
soundPlayer.end();
}
public static String getCocos2dxPackageName(){
return packageName;
}
public static void terminateProcess(){
android.os.Process.killProcess(android.os.Process.myPid());
}
@Override
protected void onResume() {
super.onResume();
if (accelerometerEnabled) {
accelerometer.enable();
}
}
@Override
protected void onPause() {
super.onPause();
if (accelerometerEnabled) {
accelerometer.disable();
}
}
protected void setPackageName(String packageName) {
Cocos2dxActivity.packageName = packageName;
String apkFilePath = "";
ApplicationInfo appInfo = null;
PackageManager packMgmr = getApplication().getPackageManager();
try {
appInfo = packMgmr.getApplicationInfo(packageName, 0);
} catch (NameNotFoundException e) {
e.printStackTrace();
throw new RuntimeException("Unable to locate assets, aborting...");
}
apkFilePath = appInfo.sourceDir;
Log.w("apk path", apkFilePath);
// add this link at the renderer class
nativeSetPaths(apkFilePath);
}
private void showDialog(String title, String message){
Dialog dialog = new AlertDialog.Builder(this)
.setTitle(title)
.setMessage(message)
.setPositiveButton("Ok",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton){
}
}).create();
dialog.show();
}
}
class DialogMessage {
public String title;
public String message;
public DialogMessage(String title, String message){
this.message = message;
this.title = title;
}
}

View File

@ -1,381 +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.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.LinkedList;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.Paint.Align;
import android.graphics.Paint.FontMetricsInt;
import android.util.Log;
public class Cocos2dxBitmap{
/*
* The values are the same as cocos2dx/platform/CCImage.h.
* I think three alignments are OK.
*/
private static final int ALIGNCENTER = 0x33;
private static final int ALIGNLEFT = 0x31;
private static final int ALIGNRIGHT = 0x32;
private static Context context;
public static void setContext(Context context){
Cocos2dxBitmap.context = context;
}
/*
* @width: the width to draw, it can be 0
* @height: the height to draw, it can be 0
*/
public static void createTextBitmap(String content, String fontName,
int fontSize, int alignment, int width, int height){
content = refactorString(content);
Paint paint = newPaint(fontName, fontSize, alignment);
TextProperty textProperty = computeTextProperty(content, paint, width, height);
int bitmapTotalHeight = (height == 0 ? textProperty.totalHeight:height);
// Draw text to bitmap
Bitmap bitmap = Bitmap.createBitmap(textProperty.maxWidth,
bitmapTotalHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
// Draw string
FontMetricsInt fm = paint.getFontMetricsInt();
int x = 0;
int y = height == 0 ?(-fm.top):
(-fm.top + (height - textProperty.totalHeight)/2);
String[] lines = textProperty.lines;
for (String line : lines){
x = computeX(paint, line, textProperty.maxWidth, alignment);
canvas.drawText(line, x, y, paint);
y += textProperty.heightPerLine;
}
initNativeObject(bitmap);
}
private static int computeX(Paint paint, String content, int w, int alignment){
int ret = 0;
switch (alignment){
case ALIGNCENTER:
ret = w / 2;
break;
// ret = 0
case ALIGNLEFT:
break;
case ALIGNRIGHT:
ret = w;
break;
/*
* Default is align left.
* Should be same as newPaint().
*/
default:
break;
}
return ret;
}
private static class TextProperty{
// The max width of lines
int maxWidth;
// The height of all lines
int totalHeight;
int heightPerLine;
String[] lines;
TextProperty(int w, int h, String[] lines){
this.maxWidth = w;
this.heightPerLine = h;
this.totalHeight = h * lines.length;
this.lines = lines;
}
}
private static TextProperty computeTextProperty(String content, Paint paint,
int maxWidth, int maxHeight){
FontMetricsInt fm = paint.getFontMetricsInt();
int h = (int)Math.ceil(fm.bottom - fm.top);
int maxContentWidth = 0;
String[] lines = splitString(content, maxHeight, maxWidth, paint);
if (maxWidth != 0){
maxContentWidth = maxWidth;
}
else {
/*
* Compute the max width
*/
int temp = 0;
for (String line : lines){
temp = (int)Math.ceil(paint.measureText(line, 0, line.length()));
if (temp > maxContentWidth){
maxContentWidth = temp;
}
}
}
return new TextProperty(maxContentWidth, h, lines);
}
/*
* If maxWidth or maxHeight is not 0,
* split the string to fix the maxWidth and maxHeight.
*/
private static String[] splitString(String content, int maxHeight, int maxWidth,
Paint paint){
String[] lines = content.split("\\n");
String[] ret = null;
FontMetricsInt fm = paint.getFontMetricsInt();
int heightPerLine = (int)Math.ceil(fm.bottom - fm.top);
int maxLines = maxHeight / heightPerLine;
if (maxWidth != 0){
LinkedList<String> strList = new LinkedList<String>();
for (String line : lines){
/*
* The width of line is exceed maxWidth, should divide it into
* two or more lines.
*/
int lineWidth = (int)Math.ceil(paint.measureText(line));
if (lineWidth > maxWidth){
strList.addAll(divideStringWithMaxWidth(paint, line, maxWidth));
}
else{
strList.add(line);
}
/*
* Should not exceed the max height;
*/
if (maxLines > 0 && strList.size() >= maxLines){
break;
}
}
/*
* Remove exceeding lines
*/
if (maxLines > 0 && strList.size() > maxLines){
while (strList.size() > maxLines){
strList.removeLast();
}
}
ret = new String[strList.size()];
strList.toArray(ret);
} else
if (maxHeight != 0 && lines.length > maxLines) {
/*
* Remove exceeding lines
*/
LinkedList<String> strList = new LinkedList<String>();
for (int i = 0; i < maxLines; i++){
strList.add(lines[i]);
}
ret = new String[strList.size()];
strList.toArray(ret);
}
else {
ret = lines;
}
return ret;
}
private static LinkedList<String> divideStringWithMaxWidth(Paint paint, String content,
int width){
int charLength = content.length();
int start = 0;
int tempWidth = 0;
LinkedList<String> strList = new LinkedList<String>();
/*
* Break a String into String[] by the width & should wrap the word
*/
for (int i = 1; i <= charLength; ++i){
tempWidth = (int)Math.ceil(paint.measureText(content, start, i));
if (tempWidth >= width){
int lastIndexOfSpace = content.substring(0, i).lastIndexOf(" ");
if (lastIndexOfSpace != -1 && lastIndexOfSpace > start){
/**
* Should wrap the word
*/
strList.add(content.substring(start, lastIndexOfSpace));
i = lastIndexOfSpace;
}
else {
/*
* Should not exceed the width
*/
if (tempWidth > width){
strList.add(content.substring(start, i - 1));
/*
* compute from previous char
*/
--i;
}
else {
strList.add(content.substring(start, i));
}
}
start = i;
}
}
/*
* Add the last chars
*/
if (start < charLength){
strList.add(content.substring(start));
}
return strList;
}
private static Paint newPaint(String fontName, int fontSize, int alignment){
Paint paint = new Paint();
paint.setColor(Color.WHITE);
paint.setTextSize(fontSize);
paint.setAntiAlias(true);
/*
* Set type face for paint, now it support .ttf file.
*/
if (fontName.endsWith(".ttf")){
try {
//Typeface typeFace = Typeface.createFromAsset(context.getAssets(), fontName);
Typeface typeFace = Cocos2dxTypefaces.get(context, fontName);
paint.setTypeface(typeFace);
} catch (Exception e){
Log.e("Cocos2dxBitmap",
"error to create ttf type face: " + fontName);
/*
* The file may not find, use system font
*/
paint.setTypeface(Typeface.create(fontName, Typeface.NORMAL));
}
}
else {
paint.setTypeface(Typeface.create(fontName, Typeface.NORMAL));
}
switch (alignment){
case ALIGNCENTER:
paint.setTextAlign(Align.CENTER);
break;
case ALIGNLEFT:
paint.setTextAlign(Align.LEFT);
break;
case ALIGNRIGHT:
paint.setTextAlign(Align.RIGHT);
break;
default:
paint.setTextAlign(Align.LEFT);
break;
}
return paint;
}
private static String refactorString(String str){
// Avoid error when content is ""
if (str.compareTo("") == 0){
return " ";
}
/*
* If the font of "\n" is "" or "\n", insert " " in front of it.
*
* For example:
* "\nabc" -> " \nabc"
* "\nabc\n\n" -> " \nabc\n \n"
*/
StringBuilder strBuilder = new StringBuilder(str);
int start = 0;
int index = strBuilder.indexOf("\n");
while (index != -1){
if (index == 0 || strBuilder.charAt(index -1) == '\n'){
strBuilder.insert(start, " ");
start = index + 2;
} else {
start = index + 1;
}
if (start > strBuilder.length() || index == strBuilder.length()){
break;
}
index = strBuilder.indexOf("\n", start);
}
return strBuilder.toString();
}
private static void initNativeObject(Bitmap bitmap){
byte[] pixels = getPixels(bitmap);
if (pixels == null){
return;
}
nativeInitBitmapDC(bitmap.getWidth(), bitmap.getHeight(), pixels);
}
private static byte[] getPixels(Bitmap bitmap){
if (bitmap != null){
byte[] pixels = new byte[bitmap.getWidth() * bitmap.getHeight() * 4];
ByteBuffer buf = ByteBuffer.wrap(pixels);
buf.order(ByteOrder.nativeOrder());
bitmap.copyPixelsToBuffer(buf);
return pixels;
}
return null;
}
private static native void nativeInitBitmapDC(int width, int height, byte[] pixels);
}

View File

@ -1,65 +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 {
private Cocos2dxGLSurfaceView mView;
public Cocos2dxEditText(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public Cocos2dxEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
public Cocos2dxEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void setMainView(Cocos2dxGLSurfaceView glSurfaceView) {
mView = glSurfaceView;
}
/*
* Let GlSurfaceView get focus if back key is input
*/
public boolean onKeyDown(int keyCode, KeyEvent event) {
super.onKeyDown(keyCode, event);
if (keyCode == KeyEvent.KEYCODE_BACK) {
mView.requestFocus();
}
return true;
}
}

View File

@ -1,417 +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.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
class TextInputWraper implements TextWatcher, OnEditorActionListener {
private static final Boolean debug = false;
private void LogD(String msg) {
if (debug) Log.d("TextInputFilter", msg);
}
private Cocos2dxGLSurfaceView mMainView;
private String mText;
private String mOriginText;
private Boolean isFullScreenEdit() {
InputMethodManager imm = (InputMethodManager)mMainView.getTextField().getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
return imm.isFullscreenMode();
}
public TextInputWraper(Cocos2dxGLSurfaceView view) {
mMainView = view;
}
public void setOriginText(String text) {
mOriginText = text;
}
@Override
public void afterTextChanged(Editable s) {
if (isFullScreenEdit()) {
return;
}
LogD("afterTextChanged: " + s);
int nModified = s.length() - mText.length();
if (nModified > 0) {
final String insertText = s.subSequence(mText.length(), s.length()).toString();
mMainView.insertText(insertText);
LogD("insertText(" + insertText + ")");
}
else {
for (; nModified < 0; ++nModified) {
mMainView.deleteBackward();
LogD("deleteBackward");
}
}
mText = s.toString();
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
LogD("beforeTextChanged(" + s + ")start: " + start + ",count: " + count + ",after: " + after);
mText = s.toString();
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (mMainView.getTextField() == v && isFullScreenEdit()) {
// user press the action button, delete all old text and insert new text
for (int i = mOriginText.length(); i > 0; --i) {
mMainView.deleteBackward();
LogD("deleteBackward");
}
String text = v.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;
mMainView.insertText(insertText);
LogD("insertText(" + insertText + ")");
}
return false;
}
}
public class Cocos2dxGLSurfaceView extends GLSurfaceView {
static private Cocos2dxGLSurfaceView mainView;
private static final String TAG = Cocos2dxGLSurfaceView.class.getCanonicalName();
private Cocos2dxRenderer mRenderer;
private static final boolean debug = false;
///////////////////////////////////////////////////////////////////////////
// for initialize
///////////////////////////////////////////////////////////////////////////
public Cocos2dxGLSurfaceView(Context context) {
super(context);
initView();
}
public Cocos2dxGLSurfaceView(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
public void setCocos2dxRenderer(Cocos2dxRenderer renderer){
mRenderer = renderer;
setRenderer(mRenderer);
}
protected void initView() {
setFocusableInTouchMode(true);
textInputWraper = new TextInputWraper(this);
handler = new Handler(){
public void handleMessage(Message msg){
switch(msg.what){
case HANDLER_OPEN_IME_KEYBOARD:
if (null != mTextField && mTextField.requestFocus()) {
mTextField.removeTextChangedListener(textInputWraper);
mTextField.setText("");
String text = (String)msg.obj;
mTextField.append(text);
textInputWraper.setOriginText(text);
mTextField.addTextChangedListener(textInputWraper);
InputMethodManager imm = (InputMethodManager)mainView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(mTextField, 0);
Log.d("GLSurfaceView", "showSoftInput");
}
break;
case HANDLER_CLOSE_IME_KEYBOARD:
if (null != mTextField) {
mTextField.removeTextChangedListener(textInputWraper);
InputMethodManager imm = (InputMethodManager)mainView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mTextField.getWindowToken(), 0);
Log.d("GLSurfaceView", "HideSoftInput");
}
break;
}
}
};
mainView = this;
}
public void onPause(){
queueEvent(new Runnable() {
@Override
public void run() {
mRenderer.handleOnPause();
}
});
super.onPause();
}
public void onResume(){
super.onResume();
queueEvent(new Runnable() {
@Override
public void run() {
mRenderer.handleOnResume();
}
});
}
///////////////////////////////////////////////////////////////////////////
// for text input
///////////////////////////////////////////////////////////////////////////
private final static int HANDLER_OPEN_IME_KEYBOARD = 2;
private final static int HANDLER_CLOSE_IME_KEYBOARD = 3;
private static Handler handler;
private static TextInputWraper textInputWraper;
private Cocos2dxEditText mTextField;
public TextView getTextField() {
return mTextField;
}
public void setTextField(Cocos2dxEditText view) {
mTextField = view;
if (null != mTextField && null != textInputWraper) {
mTextField.setOnEditorActionListener(textInputWraper);
mTextField.setMainView(this);
this.requestFocus();
}
}
public static void openIMEKeyboard() {
Message msg = new Message();
msg.what = HANDLER_OPEN_IME_KEYBOARD;
msg.obj = mainView.getContentText();
handler.sendMessage(msg);
}
private String getContentText() {
return mRenderer.getContentText();
}
public static void closeIMEKeyboard() {
Message msg = new Message();
msg.what = HANDLER_CLOSE_IME_KEYBOARD;
handler.sendMessage(msg);
}
public void insertText(final String text) {
queueEvent(new Runnable() {
@Override
public void run() {
mRenderer.handleInsertText(text);
}
});
}
public void deleteBackward() {
queueEvent(new Runnable() {
@Override
public void run() {
mRenderer.handleDeleteBackward();
}
});
}
///////////////////////////////////////////////////////////////////////////
// for touch event
///////////////////////////////////////////////////////////////////////////
public boolean onTouchEvent(final MotionEvent event) {
// these data are used in ACTION_MOVE and ACTION_CANCEL
final int pointerNumber = event.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] = event.getPointerId(i);
xs[i] = event.getX(i);
ys[i] = event.getY(i);
}
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_POINTER_DOWN:
final int indexPointerDown = event.getAction() >> MotionEvent.ACTION_POINTER_ID_SHIFT;
final int idPointerDown = event.getPointerId(indexPointerDown);
final float xPointerDown = event.getX(indexPointerDown);
final float yPointerDown = event.getY(indexPointerDown);
queueEvent(new Runnable() {
@Override
public void run() {
mRenderer.handleActionDown(idPointerDown, xPointerDown, yPointerDown);
}
});
break;
case MotionEvent.ACTION_DOWN:
// there are only one finger on the screen
final int idDown = event.getPointerId(0);
final float xDown = xs[0];
final float yDown = ys[0];
queueEvent(new Runnable() {
@Override
public void run() {
mRenderer.handleActionDown(idDown, xDown, yDown);
}
});
break;
case MotionEvent.ACTION_MOVE:
queueEvent(new Runnable() {
@Override
public void run() {
mRenderer.handleActionMove(ids, xs, ys);
}
});
break;
case MotionEvent.ACTION_POINTER_UP:
final int indexPointUp = event.getAction() >> MotionEvent.ACTION_POINTER_ID_SHIFT;
final int idPointerUp = event.getPointerId(indexPointUp);
final float xPointerUp = event.getX(indexPointUp);
final float yPointerUp = event.getY(indexPointUp);
queueEvent(new Runnable() {
@Override
public void run() {
mRenderer.handleActionUp(idPointerUp, xPointerUp, yPointerUp);
}
});
break;
case MotionEvent.ACTION_UP:
// there are only one finger on the screen
final int idUp = event.getPointerId(0);
final float xUp = xs[0];
final float yUp = ys[0];
queueEvent(new Runnable() {
@Override
public void run() {
mRenderer.handleActionUp(idUp, xUp, yUp);
}
});
break;
case MotionEvent.ACTION_CANCEL:
queueEvent(new Runnable() {
@Override
public void run() {
mRenderer.handleActionCancel(ids, xs, ys);
}
});
break;
}
if (debug){
dumpEvent(event);
}
return true;
}
/*
* This function is called before Cocos2dxRenderer.nativeInit(), so the width and height is correct.
*/
protected void onSizeChanged(int w, int h, int oldw, int oldh){
this.mRenderer.setScreenWidthAndHeight(w, h);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
final int kc = keyCode;
if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_MENU) {
queueEvent(new Runnable() {
@Override
public void run() {
mRenderer.handleKeyDown(kc);
}
});
return true;
}
return super.onKeyDown(keyCode, event);
}
// Show an event in the LogCat view, for debugging
private void dumpEvent(MotionEvent event) {
String names[] = { "DOWN" , "UP" , "MOVE" , "CANCEL" , "OUTSIDE" ,
"POINTER_DOWN" , "POINTER_UP" , "7?" , "8?" , "9?" };
StringBuilder sb = new StringBuilder();
int action = event.getAction();
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(TAG, sb.toString());
}
}

View File

@ -1,228 +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.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.util.Log;
/**
*
* This class is used for controlling background music
*
*/
public class Cocos2dxMusic {
private static final String TAG = "Cocos2dxMusic";
private float mLeftVolume;
private float mRightVolume;
private Context mContext;
private MediaPlayer mBackgroundMediaPlayer;
private boolean mIsPaused;
private String mCurrentPath;
public Cocos2dxMusic(Context context){
this.mContext = context;
initData();
}
public void preloadBackgroundMusic(String path){
if ((mCurrentPath == null) || (! mCurrentPath.equals(path))){
// preload new background music
// release old resource and create a new one
if (mBackgroundMediaPlayer != null){
mBackgroundMediaPlayer.release();
}
mBackgroundMediaPlayer = createMediaplayerFromAssets(path);
// record the path
mCurrentPath = path;
}
}
public void playBackgroundMusic(String path, boolean isLoop){
if (mCurrentPath == null){
// it is the first time to play background music
// or end() was called
mBackgroundMediaPlayer = createMediaplayerFromAssets(path);
mCurrentPath = path;
}
else {
if (! mCurrentPath.equals(path)){
// play new background music
// release old resource and create a new one
if (mBackgroundMediaPlayer != null){
mBackgroundMediaPlayer.release();
}
mBackgroundMediaPlayer = createMediaplayerFromAssets(path);
// record the path
mCurrentPath = path;
}
}
if (mBackgroundMediaPlayer == null){
Log.e(TAG, "playBackgroundMusic: background media player is null");
} else {
// if the music is playing or paused, stop it
mBackgroundMediaPlayer.stop();
mBackgroundMediaPlayer.setLooping(isLoop);
try {
mBackgroundMediaPlayer.prepare();
mBackgroundMediaPlayer.seekTo(0);
mBackgroundMediaPlayer.start();
this.mIsPaused = false;
} catch (Exception e){
Log.e(TAG, "playBackgroundMusic: error state");
}
}
}
public void stopBackgroundMusic(){
if (mBackgroundMediaPlayer != null){
mBackgroundMediaPlayer.stop();
// should set the state, if not , the following sequence will be error
// play -> pause -> stop -> resume
this.mIsPaused = false;
}
}
public void pauseBackgroundMusic(){
if (mBackgroundMediaPlayer != null && mBackgroundMediaPlayer.isPlaying()){
mBackgroundMediaPlayer.pause();
this.mIsPaused = true;
}
}
public void resumeBackgroundMusic(){
if (mBackgroundMediaPlayer != null && this.mIsPaused){
mBackgroundMediaPlayer.start();
this.mIsPaused = false;
}
}
public void rewindBackgroundMusic(){
if (mBackgroundMediaPlayer != null){
mBackgroundMediaPlayer.stop();
try {
mBackgroundMediaPlayer.prepare();
mBackgroundMediaPlayer.seekTo(0);
mBackgroundMediaPlayer.start();
this.mIsPaused = false;
} catch (Exception e){
Log.e(TAG, "rewindBackgroundMusic: error state");
}
}
}
public boolean isBackgroundMusicPlaying(){
boolean ret = false;
if (mBackgroundMediaPlayer == null){
ret = false;
} else {
ret = mBackgroundMediaPlayer.isPlaying();
}
return ret;
}
public void end(){
if (mBackgroundMediaPlayer != null){
mBackgroundMediaPlayer.release();
}
initData();
}
public float getBackgroundVolume(){
if (this.mBackgroundMediaPlayer != null){
return (this.mLeftVolume + this.mRightVolume) / 2;
} else {
return 0.0f;
}
}
public void setBackgroundVolume(float volume){
if (volume < 0.0f){
volume = 0.0f;
}
if (volume > 1.0f){
volume = 1.0f;
}
this.mLeftVolume = this.mRightVolume = volume;
if (this.mBackgroundMediaPlayer != null){
this.mBackgroundMediaPlayer.setVolume(this.mLeftVolume, this.mRightVolume);
}
}
private void initData(){
mLeftVolume =0.5f;
mRightVolume = 0.5f;
mBackgroundMediaPlayer = null;
mIsPaused = false;
mCurrentPath = null;
}
/**
* create mediaplayer for music
* @param path the path relative to assets
* @return
*/
private MediaPlayer createMediaplayerFromAssets(String path){
MediaPlayer mediaPlayer = new MediaPlayer();
try{
if (path.startsWith("/")) {
mediaPlayer.setDataSource(path);
}
else {
AssetFileDescriptor assetFileDescritor = mContext.getAssets().openFd(path);
mediaPlayer.setDataSource(assetFileDescritor.getFileDescriptor(),
assetFileDescritor.getStartOffset(), assetFileDescritor.getLength());
}
mediaPlayer.prepare();
mediaPlayer.setVolume(mLeftVolume, mRightVolume);
}catch (Exception e) {
mediaPlayer = null;
Log.e(TAG, "error: " + e.getMessage(), e);
}
return mediaPlayer;
}
}

View File

@ -1,137 +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 {
private final static long NANOSECONDSPERSECOND = 1000000000L;
private final static long NANOSECONDSPERMINISECOND = 1000000;
private static long animationInterval = (long)(1.0 / 60 * NANOSECONDSPERSECOND);
private long last;
private int screenWidth;
private int screenHeight;
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
nativeInit(screenWidth, screenHeight);
last = System.nanoTime();
}
public void setScreenWidthAndHeight(int w, int h){
this.screenWidth = w;
this.screenHeight = h;
}
public void onSurfaceChanged(GL10 gl, int w, int h) {
}
public void onDrawFrame(GL10 gl) {
long now = System.nanoTime();
long interval = now - last;
// should render a frame when onDrawFrame() is called
// or there is a "ghost"
nativeRender();
// fps controlling
if (interval < animationInterval){
try {
// because we render it before, so we should sleep twice time interval
Thread.sleep((animationInterval - interval) * 2 / NANOSECONDSPERMINISECOND);
} catch (Exception e){}
}
last = now;
}
public void handleActionDown(int id, float x, float y)
{
nativeTouchesBegin(id, x, y);
}
public void handleActionUp(int id, float x, float y)
{
nativeTouchesEnd(id, x, y);
}
public void handleActionCancel(int[] id, float[] x, float[] y)
{
nativeTouchesCancel(id, x, y);
}
public void handleActionMove(int[] id, float[] x, float[] y)
{
nativeTouchesMove(id, x, y);
}
public void handleKeyDown(int keyCode)
{
nativeKeyDown(keyCode);
}
public void handleOnPause(){
nativeOnPause();
}
public void handleOnResume(){
nativeOnResume();
}
public static void setAnimationInterval(double interval){
animationInterval = (long)(interval * NANOSECONDSPERSECOND);
}
private static native void nativeTouchesBegin(int id, float x, float y);
private static native void nativeTouchesEnd(int id, float x, float y);
private static native void nativeTouchesMove(int[] id, float[] x, float[] y);
private static native void nativeTouchesCancel(int[] id, float[] x, float[] y);
private static native boolean nativeKeyDown(int keyCode);
private static native void nativeRender();
private static native void nativeInit(int w, int h);
private static native void nativeOnPause();
private static native void nativeOnResume();
/////////////////////////////////////////////////////////////////////////////////
// handle input method edit message
/////////////////////////////////////////////////////////////////////////////////
public void handleInsertText(final String text) {
nativeInsertText(text);
}
public void handleDeleteBackward() {
nativeDeleteBackward();
}
public String getContentText() {
return nativeGetContentText();
}
private static native void nativeInsertText(String text);
private static native void nativeDeleteBackward();
private static native String nativeGetContentText();
}

View File

@ -1,258 +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.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;
import android.util.Log;
/**
*
* This class is used for controlling effect
*
*/
public class Cocos2dxSound {
private Context mContext;
private SoundPool mSoundPool;
private float mLeftVolume;
private float mRightVolume;
// sound id and stream id map
private HashMap<Integer,Integer> mSoundIdStreamIdMap;
// sound path and sound id map
private HashMap<String,Integer> mPathSoundIDMap;
private static final String TAG = "Cocos2dxSound";
private static final int MAX_SIMULTANEOUS_STREAMS_DEFAULT = 5;
private static final float SOUND_RATE = 1.0f;
private static final int SOUND_PRIORITY = 1;
private static final int SOUND_QUALITY = 5;
private final int INVALID_SOUND_ID = -1;
private final int INVALID_STREAM_ID = -1;
public Cocos2dxSound(Context context){
this.mContext = context;
initData();
}
public int preloadEffect(String path){
int soundId = INVALID_SOUND_ID;
// if the sound is preloaded, pass it
if (this.mPathSoundIDMap.get(path) != null){
soundId = this.mPathSoundIDMap.get(path).intValue();
} else {
soundId = createSoundIdFromAsset(path);
if (soundId != INVALID_SOUND_ID){
// the sound is loaded but has not been played
this.mSoundIdStreamIdMap.put(soundId, INVALID_STREAM_ID);
// record path and sound id map
this.mPathSoundIDMap.put(path, soundId);
}
}
return soundId;
}
public void unloadEffect(String path){
// get sound id and remove from mPathSoundIDMap
Integer soundId = this.mPathSoundIDMap.remove(path);
if (soundId != null){
// unload effect
this.mSoundPool.unload(soundId.intValue());
// remove record from mSoundIdStreamIdMap
this.mSoundIdStreamIdMap.remove(soundId);
}
}
public int playEffect(String path, boolean isLoop){
Integer soundId = this.mPathSoundIDMap.get(path);
if (soundId != null){
// the sound is preloaded, stop it first
this.mSoundPool.stop(soundId);
// play sound
int streamId = this.mSoundPool.play(soundId.intValue(), this.mLeftVolume,
this.mRightVolume, SOUND_PRIORITY, isLoop ? -1 : 0, SOUND_RATE);
// record sound id and stream id map
this.mSoundIdStreamIdMap.put(soundId, streamId);
} else {
// the effect is not prepared
soundId = preloadEffect(path);
if (soundId == INVALID_SOUND_ID){
// can not preload effect
return INVALID_SOUND_ID;
}
/*
* Someone reports that, it can not play effect for the
* first time. If you are lucky to meet it. There are two
* ways to resolve it.
* 1. Add some delay here. I don't know how long it is, so
* I don't add it here.
* 2. If you use 2.2(API level 8), you can call
* SoundPool.setOnLoadCompleteListener() to play the effect.
* Because the method is supported from 2.2, so I can't use
* it here.
*/
playEffect(path, isLoop);
}
return soundId.intValue();
}
public void stopEffect(int soundId){
Integer streamId = this.mSoundIdStreamIdMap.get(soundId);
if (streamId != null && streamId.intValue() != INVALID_STREAM_ID){
this.mSoundPool.stop(streamId.intValue());
this.mPathSoundIDMap.remove(soundId);
}
}
public void pauseEffect(int soundId){
Integer streamId = this.mSoundIdStreamIdMap.get(soundId);
if (streamId != null && streamId.intValue() != INVALID_STREAM_ID){
this.mSoundPool.pause(streamId.intValue());
this.mPathSoundIDMap.remove(soundId);
}
}
public void resumeEffect(int soundId){
Integer streamId = this.mSoundIdStreamIdMap.get(soundId);
if (streamId != null && streamId.intValue() != INVALID_STREAM_ID){
this.mSoundPool.resume(streamId.intValue());
this.mPathSoundIDMap.remove(soundId);
}
}
public void pauseAllEffects(){
// autoResume is available since level 8
pauseOrResumeAllEffects(true);
}
public void resumeAllEffects(){
// autoPause() is available since level 8
pauseOrResumeAllEffects(false);
}
@SuppressWarnings("unchecked")
public void stopAllEffects(){
Iterator<?> iter = this.mSoundIdStreamIdMap.entrySet().iterator();
while (iter.hasNext()){
Map.Entry<Integer, Integer> entry = (Map.Entry<Integer, Integer>)iter.next();
int soundId = entry.getKey();
this.stopEffect(soundId);
}
}
public float getEffectsVolume(){
return (this.mLeftVolume + this.mRightVolume) / 2;
}
@SuppressWarnings("unchecked")
public void setEffectsVolume(float volume){
// volume should be in [0, 1.0]
if (volume < 0){
volume = 0;
}
if (volume > 1){
volume = 1;
}
this.mLeftVolume = this.mRightVolume = volume;
// change the volume of playing sounds
Iterator<?> iter = this.mSoundIdStreamIdMap.entrySet().iterator();
while (iter.hasNext()){
Map.Entry<Integer, Integer> entry = (Map.Entry<Integer, Integer>)iter.next();
this.mSoundPool.setVolume(entry.getValue(), mLeftVolume, mRightVolume);
}
}
public void end(){
this.mSoundPool.release();
this.mPathSoundIDMap.clear();
this.mSoundIdStreamIdMap.clear();
initData();
}
public int createSoundIdFromAsset(String path){
int soundId = INVALID_SOUND_ID;
try {
if (path.startsWith("/")){
soundId = mSoundPool.load(path, 0);
}
else {
soundId = mSoundPool.load(mContext.getAssets().openFd(path), 0);
}
} catch(Exception e){
soundId = INVALID_SOUND_ID;
Log.e(TAG, "error: " + e.getMessage(), e);
}
return soundId;
}
private void initData(){
this.mSoundIdStreamIdMap = new HashMap<Integer,Integer>();
mSoundPool = new SoundPool(MAX_SIMULTANEOUS_STREAMS_DEFAULT, AudioManager.STREAM_MUSIC, SOUND_QUALITY);
mPathSoundIDMap = new HashMap<String,Integer>();
this.mLeftVolume = 0.5f;
this.mRightVolume = 0.5f;
}
@SuppressWarnings("unchecked")
private void pauseOrResumeAllEffects(boolean isPause){
Iterator<?> iter = this.mSoundIdStreamIdMap.entrySet().iterator();
while (iter.hasNext()){
Map.Entry<Integer, Integer> entry = (Map.Entry<Integer, Integer>)iter.next();
int soundId = entry.getKey();
if (isPause) {
this.pauseEffect(soundId);
} else {
this.resumeEffect(soundId);
}
}
}
}

View File

@ -1,44 +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.util.Hashtable;
import android.content.Context;
import android.graphics.Typeface;
public class Cocos2dxTypefaces {
private static final Hashtable<String, Typeface> cache = new Hashtable<String, Typeface>();
public static Typeface get(Context context, String name){
synchronized(cache){
if (! cache.containsKey(name)){
Typeface t = Typeface.createFromAsset(context.getAssets(), name);
cache.put(name, t);
}
return cache.get(name);
}
}
}

View File

@ -0,0 +1,405 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 45;
objects = {
/* Begin PBXBuildFile section */
1551A89A158F33C400E66CFE /* libcocos2dx.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1551A897158F2F7D00E66CFE /* libcocos2dx.a */; };
15DD6D7A156DD120003E7567 /* fps_images.png in Resources */ = {isa = PBXBuildFile; fileRef = 15DD6D78156DD120003E7567 /* fps_images.png */; };
1D60589F0D05DD5A006BFB54 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1D30AB110D05D00D00671497 /* Foundation.framework */; };
1DF5F4E00D08C38300B7A737 /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1DF5F4DF0D08C38300B7A737 /* UIKit.framework */; };
288765A50DF7441C002DB57D /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 288765A40DF7441C002DB57D /* CoreGraphics.framework */; };
782F4619153FEDF0009FC2E5 /* Default.png in Resources */ = {isa = PBXBuildFile; fileRef = 782F4617153FEDF0009FC2E5 /* Default.png */; };
782F461A153FEDF0009FC2E5 /* Icon.png in Resources */ = {isa = PBXBuildFile; fileRef = 782F4618153FEDF0009FC2E5 /* Icon.png */; };
784521CE14EBA449009D533B /* CloseNormal.png in Resources */ = {isa = PBXBuildFile; fileRef = 784521C514EBA449009D533B /* CloseNormal.png */; };
784521CF14EBA449009D533B /* CloseSelected.png in Resources */ = {isa = PBXBuildFile; fileRef = 784521C614EBA449009D533B /* CloseSelected.png */; };
784521D214EBA449009D533B /* HelloWorld.png in Resources */ = {isa = PBXBuildFile; fileRef = 784521CA14EBA449009D533B /* HelloWorld.png */; };
BF1373EF128A898400D9F789 /* OpenGLES.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = BF492D4B1289302400A09262 /* OpenGLES.framework */; };
BF1373F0128A899500D9F789 /* libxml2.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = BF492C21128924A800A09262 /* libxml2.dylib */; };
BF1373F1128A899E00D9F789 /* libz.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = BF492B6912891AC600A09262 /* libz.dylib */; };
BF13742F128A8E6A00D9F789 /* QuartzCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = BF137426128A8E4600D9F789 /* QuartzCore.framework */; };
BF23D4E7143315EB00657E08 /* AppDelegate.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BF23D4E3143315EB00657E08 /* AppDelegate.cpp */; };
BF23D4E8143315EB00657E08 /* HelloWorldScene.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BF23D4E5143315EB00657E08 /* HelloWorldScene.cpp */; };
BF365AA812A103F70050DCF4 /* AppController.mm in Sources */ = {isa = PBXBuildFile; fileRef = BF365AA712A103F70050DCF4 /* AppController.mm */; };
BF4DE6AD138BB89600CF907D /* RootViewController.mm in Sources */ = {isa = PBXBuildFile; fileRef = BF4DE6AC138BB89600CF907D /* RootViewController.mm */; };
D4ABB4B313B4395300552E6E /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = D4ABB4B213B4395300552E6E /* main.m */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
1551A896158F2F7D00E66CFE /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 1551A88F158F2F7D00E66CFE /* cocos2dx.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 1551A33F158F2AB200E66CFE;
remoteInfo = cocos2dx;
};
1551A898158F339F00E66CFE /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 1551A88F158F2F7D00E66CFE /* cocos2dx.xcodeproj */;
proxyType = 1;
remoteGlobalIDString = 1551A33E158F2AB200E66CFE;
remoteInfo = cocos2dx;
};
/* End PBXContainerItemProxy section */
/* Begin PBXFileReference section */
1551A88F158F2F7D00E66CFE /* cocos2dx.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = cocos2dx.xcodeproj; path = ../../cocos2dx/proj.ios/cocos2dx.xcodeproj; sourceTree = "<group>"; };
15DD6D78156DD120003E7567 /* fps_images.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = fps_images.png; sourceTree = "<group>"; };
1D30AB110D05D00D00671497 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; };
1D6058910D05DD3D006BFB54 /* HelloWorld.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = HelloWorld.app; sourceTree = BUILT_PRODUCTS_DIR; };
1DF5F4DF0D08C38300B7A737 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = System/Library/Frameworks/UIKit.framework; sourceTree = SDKROOT; };
288765A40DF7441C002DB57D /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = System/Library/Frameworks/CoreGraphics.framework; sourceTree = SDKROOT; };
781C33B11547F06B00633F88 /* OpenAL.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = OpenAL.framework; path = System/Library/Frameworks/OpenAL.framework; sourceTree = SDKROOT; };
781C33B31547F06B00633F88 /* AudioToolbox.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AudioToolbox.framework; path = System/Library/Frameworks/AudioToolbox.framework; sourceTree = SDKROOT; };
781C33B51547F06B00633F88 /* AVFoundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AVFoundation.framework; path = System/Library/Frameworks/AVFoundation.framework; sourceTree = SDKROOT; };
782F4617153FEDF0009FC2E5 /* Default.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = Default.png; sourceTree = SOURCE_ROOT; };
782F4618153FEDF0009FC2E5 /* Icon.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = Icon.png; sourceTree = SOURCE_ROOT; };
784521C514EBA449009D533B /* CloseNormal.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = CloseNormal.png; sourceTree = "<group>"; };
784521C614EBA449009D533B /* CloseSelected.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = CloseSelected.png; sourceTree = "<group>"; };
784521CA14EBA449009D533B /* HelloWorld.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = HelloWorld.png; sourceTree = "<group>"; };
BF137426128A8E4600D9F789 /* QuartzCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = QuartzCore.framework; path = System/Library/Frameworks/QuartzCore.framework; sourceTree = SDKROOT; };
BF23D4E3143315EB00657E08 /* AppDelegate.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = AppDelegate.cpp; sourceTree = "<group>"; };
BF23D4E4143315EB00657E08 /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = "<group>"; };
BF23D4E5143315EB00657E08 /* HelloWorldScene.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = HelloWorldScene.cpp; sourceTree = "<group>"; };
BF23D4E6143315EB00657E08 /* HelloWorldScene.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HelloWorldScene.h; sourceTree = "<group>"; };
BF365AA612A103F70050DCF4 /* AppController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AppController.h; sourceTree = "<group>"; };
BF365AA712A103F70050DCF4 /* AppController.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = AppController.mm; sourceTree = "<group>"; };
BF492B6912891AC600A09262 /* libz.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libz.dylib; path = usr/lib/libz.dylib; sourceTree = SDKROOT; };
BF492C21128924A800A09262 /* libxml2.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libxml2.dylib; path = usr/lib/libxml2.dylib; sourceTree = SDKROOT; };
BF492D4B1289302400A09262 /* OpenGLES.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = OpenGLES.framework; path = System/Library/Frameworks/OpenGLES.framework; sourceTree = SDKROOT; };
BF4DE6AB138BB89600CF907D /* RootViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RootViewController.h; sourceTree = "<group>"; };
BF4DE6AC138BB89600CF907D /* RootViewController.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = RootViewController.mm; sourceTree = "<group>"; };
D4ABB4B213B4395300552E6E /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
1D60588F0D05DD3D006BFB54 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
1551A89A158F33C400E66CFE /* libcocos2dx.a in Frameworks */,
1D60589F0D05DD5A006BFB54 /* Foundation.framework in Frameworks */,
1DF5F4E00D08C38300B7A737 /* UIKit.framework in Frameworks */,
288765A50DF7441C002DB57D /* CoreGraphics.framework in Frameworks */,
BF1373EF128A898400D9F789 /* OpenGLES.framework in Frameworks */,
BF1373F0128A899500D9F789 /* libxml2.dylib in Frameworks */,
BF1373F1128A899E00D9F789 /* libz.dylib in Frameworks */,
BF13742F128A8E6A00D9F789 /* QuartzCore.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
1551A890158F2F7D00E66CFE /* Products */ = {
isa = PBXGroup;
children = (
1551A897158F2F7D00E66CFE /* libcocos2dx.a */,
);
name = Products;
sourceTree = "<group>";
};
19C28FACFE9D520D11CA2CBB /* Products */ = {
isa = PBXGroup;
children = (
1D6058910D05DD3D006BFB54 /* HelloWorld.app */,
);
name = Products;
sourceTree = "<group>";
};
29B97314FDCFA39411CA2CEA /* CustomTemplate */ = {
isa = PBXGroup;
children = (
1551A88F158F2F7D00E66CFE /* cocos2dx.xcodeproj */,
BF23D4E2143315EB00657E08 /* Classes */,
29B97323FDCFA39411CA2CEA /* Frameworks */,
BF5681CC1313A84D0055EEAC /* ios */,
19C28FACFE9D520D11CA2CBB /* Products */,
784521C214EBA449009D533B /* Resources */,
);
name = CustomTemplate;
sourceTree = "<group>";
};
29B97323FDCFA39411CA2CEA /* Frameworks */ = {
isa = PBXGroup;
children = (
BF492B6912891AC600A09262 /* libz.dylib */,
BF137426128A8E4600D9F789 /* QuartzCore.framework */,
BF492D4B1289302400A09262 /* OpenGLES.framework */,
BF492C21128924A800A09262 /* libxml2.dylib */,
1DF5F4DF0D08C38300B7A737 /* UIKit.framework */,
1D30AB110D05D00D00671497 /* Foundation.framework */,
288765A40DF7441C002DB57D /* CoreGraphics.framework */,
781C33B11547F06B00633F88 /* OpenAL.framework */,
781C33B31547F06B00633F88 /* AudioToolbox.framework */,
781C33B51547F06B00633F88 /* AVFoundation.framework */,
);
name = Frameworks;
sourceTree = "<group>";
};
784521C214EBA449009D533B /* Resources */ = {
isa = PBXGroup;
children = (
15DD6D78156DD120003E7567 /* fps_images.png */,
782F4617153FEDF0009FC2E5 /* Default.png */,
782F4618153FEDF0009FC2E5 /* Icon.png */,
784521C514EBA449009D533B /* CloseNormal.png */,
784521C614EBA449009D533B /* CloseSelected.png */,
784521CA14EBA449009D533B /* HelloWorld.png */,
);
name = Resources;
path = ../Resources;
sourceTree = "<group>";
};
BF23D4E2143315EB00657E08 /* Classes */ = {
isa = PBXGroup;
children = (
BF23D4E3143315EB00657E08 /* AppDelegate.cpp */,
BF23D4E4143315EB00657E08 /* AppDelegate.h */,
BF23D4E5143315EB00657E08 /* HelloWorldScene.cpp */,
BF23D4E6143315EB00657E08 /* HelloWorldScene.h */,
);
name = Classes;
path = ../Classes;
sourceTree = SOURCE_ROOT;
};
BF5681CC1313A84D0055EEAC /* ios */ = {
isa = PBXGroup;
children = (
D4ABB4B213B4395300552E6E /* main.m */,
BF365AA612A103F70050DCF4 /* AppController.h */,
BF365AA712A103F70050DCF4 /* AppController.mm */,
BF4DE6AB138BB89600CF907D /* RootViewController.h */,
BF4DE6AC138BB89600CF907D /* RootViewController.mm */,
);
name = ios;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
1D6058900D05DD3D006BFB54 /* HelloWorld */ = {
isa = PBXNativeTarget;
buildConfigurationList = 1D6058960D05DD3E006BFB54 /* Build configuration list for PBXNativeTarget "HelloWorld" */;
buildPhases = (
1D60588D0D05DD3D006BFB54 /* Resources */,
1D60588E0D05DD3D006BFB54 /* Sources */,
1D60588F0D05DD3D006BFB54 /* Frameworks */,
);
buildRules = (
);
dependencies = (
1551A899158F339F00E66CFE /* PBXTargetDependency */,
);
name = HelloWorld;
productName = HelloWorld;
productReference = 1D6058910D05DD3D006BFB54 /* HelloWorld.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
29B97313FDCFA39411CA2CEA /* Project object */ = {
isa = PBXProject;
buildConfigurationList = C01FCF4E08A954540054247B /* Build configuration list for PBXProject "HelloWorld" */;
compatibilityVersion = "Xcode 3.1";
developmentRegion = English;
hasScannedForEncodings = 1;
knownRegions = (
English,
Japanese,
French,
German,
);
mainGroup = 29B97314FDCFA39411CA2CEA /* CustomTemplate */;
projectDirPath = "";
projectReferences = (
{
ProductGroup = 1551A890158F2F7D00E66CFE /* Products */;
ProjectRef = 1551A88F158F2F7D00E66CFE /* cocos2dx.xcodeproj */;
},
);
projectRoot = "";
targets = (
1D6058900D05DD3D006BFB54 /* HelloWorld */,
);
};
/* End PBXProject section */
/* Begin PBXReferenceProxy section */
1551A897158F2F7D00E66CFE /* libcocos2dx.a */ = {
isa = PBXReferenceProxy;
fileType = archive.ar;
path = libcocos2dx.a;
remoteRef = 1551A896158F2F7D00E66CFE /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
/* End PBXReferenceProxy section */
/* Begin PBXResourcesBuildPhase section */
1D60588D0D05DD3D006BFB54 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
784521CE14EBA449009D533B /* CloseNormal.png in Resources */,
784521CF14EBA449009D533B /* CloseSelected.png in Resources */,
784521D214EBA449009D533B /* HelloWorld.png in Resources */,
782F4619153FEDF0009FC2E5 /* Default.png in Resources */,
782F461A153FEDF0009FC2E5 /* Icon.png in Resources */,
15DD6D7A156DD120003E7567 /* fps_images.png in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
1D60588E0D05DD3D006BFB54 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
BF365AA812A103F70050DCF4 /* AppController.mm in Sources */,
BF4DE6AD138BB89600CF907D /* RootViewController.mm in Sources */,
D4ABB4B313B4395300552E6E /* main.m in Sources */,
BF23D4E7143315EB00657E08 /* AppDelegate.cpp in Sources */,
BF23D4E8143315EB00657E08 /* HelloWorldScene.cpp in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
1551A899158F339F00E66CFE /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
name = cocos2dx;
targetProxy = 1551A898158F339F00E66CFE /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin XCBuildConfiguration section */
1D6058940D05DD3E006BFB54 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
ARCHS = "$(ARCHS_STANDARD_32_BIT)";
COPY_PHASE_STRIP = NO;
GCC_DYNAMIC_NO_PIC = NO;
GCC_INLINES_ARE_PRIVATE_EXTERN = NO;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = HelloWorld_Prefix.pch;
GCC_PREPROCESSOR_DEFINITIONS = (
USE_FILE32API,
TARGET_OS_IPHONE,
"COCOS2D_DEBUG=1",
);
GCC_PREPROCESSOR_DEFINITIONS_NOT_USED_IN_PRECOMPS = "";
GCC_SYMBOLS_PRIVATE_EXTERN = NO;
GCC_VERSION = "";
HEADER_SEARCH_PATHS = (
"\"$(SDKROOT)/usr/include/libxml2/\"",
"\"$(SRCROOT)/../../cocos2dx/include\"",
"\"$(SRCROOT)/../../cocos2dx\"",
"\"$(SRCROOT)/../../cocos2dx/platform/ios\"",
"\"$(SRCROOT)/../../cocos2dx/kazmath/include\"",
);
INFOPLIST_FILE = "HelloWorld-Info.plist";
IPHONEOS_DEPLOYMENT_TARGET = 4.0;
PRODUCT_NAME = HelloWorld;
SDKROOT = iphoneos;
TARGETED_DEVICE_FAMILY = "1,2";
VALID_ARCHS = "armv6 armv7 i386";
};
name = Debug;
};
1D6058950D05DD3E006BFB54 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
ARCHS = "$(ARCHS_STANDARD_32_BIT)";
COPY_PHASE_STRIP = YES;
GCC_INLINES_ARE_PRIVATE_EXTERN = NO;
GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = HelloWorld_Prefix.pch;
GCC_PREPROCESSOR_DEFINITIONS = (
USE_FILE32API,
TARGET_OS_IPHONE,
);
GCC_PREPROCESSOR_DEFINITIONS_NOT_USED_IN_PRECOMPS = "";
GCC_SYMBOLS_PRIVATE_EXTERN = NO;
GCC_VERSION = "";
HEADER_SEARCH_PATHS = (
"\"$(SDKROOT)/usr/include/libxml2/\"",
"\"$(SRCROOT)/../../cocos2dx/include\"",
"\"$(SRCROOT)/../../cocos2dx\"",
"\"$(SRCROOT)/../../cocos2dx/platform/ios\"",
"\"$(SRCROOT)/../../cocos2dx/kazmath/include\"",
);
INFOPLIST_FILE = "HelloWorld-Info.plist";
IPHONEOS_DEPLOYMENT_TARGET = 4.0;
PRODUCT_NAME = HelloWorld;
SDKROOT = iphoneos;
TARGETED_DEVICE_FAMILY = "1,2";
VALIDATE_PRODUCT = YES;
VALID_ARCHS = "armv6 armv7 i386";
};
name = Release;
};
C01FCF4F08A954540054247B /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ARCHS = "$(ARCHS_STANDARD_32_BIT)";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
GCC_C_LANGUAGE_STANDARD = c99;
GCC_VERSION = "";
GCC_WARN_ABOUT_RETURN_TYPE = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
PREBINDING = NO;
SDKROOT = iphoneos;
VALID_ARCHS = "armv6 armv7 i386";
};
name = Debug;
};
C01FCF5008A954540054247B /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ARCHS = "$(ARCHS_STANDARD_32_BIT)";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
GCC_C_LANGUAGE_STANDARD = c99;
GCC_VERSION = "";
GCC_WARN_ABOUT_RETURN_TYPE = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
OTHER_CFLAGS = "-DNS_BLOCK_ASSERTIONS=1";
PREBINDING = NO;
SDKROOT = iphoneos;
VALID_ARCHS = "armv6 armv7 i386";
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
1D6058960D05DD3E006BFB54 /* Build configuration list for PBXNativeTarget "HelloWorld" */ = {
isa = XCConfigurationList;
buildConfigurations = (
1D6058940D05DD3E006BFB54 /* Debug */,
1D6058950D05DD3E006BFB54 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
C01FCF4E08A954540054247B /* Build configuration list for PBXProject "HelloWorld" */ = {
isa = XCConfigurationList;
buildConfigurations = (
C01FCF4F08A954540054247B /* Debug */,
C01FCF5008A954540054247B /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 29B97313FDCFA39411CA2CEA /* Project object */;
}

View File

@ -1 +0,0 @@
c7a3fbb2c6d8e698889720796681db135c37b25b

View File

@ -21,7 +21,7 @@
OutputDirectory="$(SolutionDir)$(ConfigurationName).win32" OutputDirectory="$(SolutionDir)$(ConfigurationName).win32"
IntermediateDirectory="$(ConfigurationName).win32" IntermediateDirectory="$(ConfigurationName).win32"
ConfigurationType="1" ConfigurationType="1"
CharacterSet="2" CharacterSet="1"
> >
<Tool <Tool
Name="VCPreBuildEventTool" Name="VCPreBuildEventTool"
@ -41,14 +41,15 @@
<Tool <Tool
Name="VCCLCompilerTool" Name="VCCLCompilerTool"
Optimization="0" Optimization="0"
AdditionalIncludeDirectories="&quot;$(SolutionDir)cocos2dx&quot;;&quot;$(SolutionDir)cocos2dx\actions&quot;;&quot;$(SolutionDir)cocos2dx\base_nodes&quot;;&quot;$(SolutionDir)cocos2dx\cocoa&quot;;&quot;$(SolutionDir)cocos2dx\effects&quot;;&quot;$(SolutionDir)cocos2dx\include&quot;;&quot;$(SolutionDir)cocos2dx\kazmath\include&quot;;&quot;$(SolutionDir)cocos2dx\keypad_dispatcher&quot;;&quot;$(SolutionDir)cocos2dx\label_nodes&quot;;&quot;$(SolutionDir)cocos2dx\layers_scenes_transitions_nodes&quot;;&quot;$(SolutionDir)cocos2dx\menu_nodes&quot;;&quot;$(SolutionDir)cocos2dx\misc_nodes&quot;;&quot;$(SolutionDir)cocos2dx\particle_nodes&quot;;&quot;$(SolutionDir)cocos2dx\script_support&quot;;&quot;$(SolutionDir)cocos2dx\shaders&quot;;&quot;$(SolutionDir)cocos2dx\sprite_nodes&quot;;&quot;$(SolutionDir)cocos2dx\support&quot;;&quot;$(SolutionDir)cocos2dx\text_input_node&quot;;&quot;$(SolutionDir)cocos2dx\textures&quot;;&quot;$(SolutionDir)cocos2dx\tileMap_parallax_nodes&quot;;&quot;$(SolutionDir)cocos2dx\touch_dispatcher&quot;;&quot;$(SolutionDir)cocos2dx\platform&quot;;&quot;$(SolutionDir)cocos2dx\platform\win32&quot;;&quot;$(SolutionDir)cocos2dx\platform\third_party\win32\OGLES&quot;;..\Classes" AdditionalIncludeDirectories="&quot;$(SolutionDir)cocos2dx&quot;;&quot;$(SolutionDir)cocos2dx\include&quot;;&quot;$(SolutionDir)cocos2dx\kazmath\include&quot;;&quot;$(SolutionDir)cocos2dx\platform\win32&quot;;&quot;$(SolutionDir)cocos2dx\platform\third_party\win32\OGLES&quot;;..\Classes"
PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS" PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;COCOS2D_DEBUG=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS"
MinimalRebuild="true" MinimalRebuild="true"
BasicRuntimeChecks="3" BasicRuntimeChecks="3"
RuntimeLibrary="3" RuntimeLibrary="3"
UsePrecompiledHeader="0" UsePrecompiledHeader="0"
WarningLevel="3" WarningLevel="3"
DebugInformationFormat="4" DebugInformationFormat="4"
DisableSpecificWarnings="4267;4251;4244"
/> />
<Tool <Tool
Name="VCManagedResourceCompilerTool" Name="VCManagedResourceCompilerTool"
@ -61,7 +62,7 @@
/> />
<Tool <Tool
Name="VCLinkerTool" Name="VCLinkerTool"
AdditionalDependencies="libcocos2d.lib libGLESv2.lib" AdditionalDependencies="opengl32.lib glew32.lib libcocos2d.lib"
OutputFile="$(OutDir)\$(ProjectName).exe" OutputFile="$(OutDir)\$(ProjectName).exe"
LinkIncremental="2" LinkIncremental="2"
AdditionalLibraryDirectories="$(OutDir)" AdditionalLibraryDirectories="$(OutDir)"
@ -97,7 +98,7 @@
OutputDirectory="$(SolutionDir)$(ConfigurationName).win32" OutputDirectory="$(SolutionDir)$(ConfigurationName).win32"
IntermediateDirectory="$(ConfigurationName).win32" IntermediateDirectory="$(ConfigurationName).win32"
ConfigurationType="1" ConfigurationType="1"
CharacterSet="2" CharacterSet="1"
WholeProgramOptimization="1" WholeProgramOptimization="1"
> >
<Tool <Tool
@ -119,13 +120,14 @@
Name="VCCLCompilerTool" Name="VCCLCompilerTool"
Optimization="2" Optimization="2"
EnableIntrinsicFunctions="true" EnableIntrinsicFunctions="true"
AdditionalIncludeDirectories="&quot;$(SolutionDir)cocos2dx&quot;;&quot;$(SolutionDir)cocos2dx\actions&quot;;&quot;$(SolutionDir)cocos2dx\base_nodes&quot;;&quot;$(SolutionDir)cocos2dx\cocoa&quot;;&quot;$(SolutionDir)cocos2dx\effects&quot;;&quot;$(SolutionDir)cocos2dx\include&quot;;&quot;$(SolutionDir)cocos2dx\kazmath\include&quot;;&quot;$(SolutionDir)cocos2dx\keypad_dispatcher&quot;;&quot;$(SolutionDir)cocos2dx\label_nodes&quot;;&quot;$(SolutionDir)cocos2dx\layers_scenes_transitions_nodes&quot;;&quot;$(SolutionDir)cocos2dx\menu_nodes&quot;;&quot;$(SolutionDir)cocos2dx\misc_nodes&quot;;&quot;$(SolutionDir)cocos2dx\particle_nodes&quot;;&quot;$(SolutionDir)cocos2dx\script_support&quot;;&quot;$(SolutionDir)cocos2dx\shaders&quot;;&quot;$(SolutionDir)cocos2dx\sprite_nodes&quot;;&quot;$(SolutionDir)cocos2dx\support&quot;;&quot;$(SolutionDir)cocos2dx\text_input_node&quot;;&quot;$(SolutionDir)cocos2dx\textures&quot;;&quot;$(SolutionDir)cocos2dx\tileMap_parallax_nodes&quot;;&quot;$(SolutionDir)cocos2dx\touch_dispatcher&quot;;&quot;$(SolutionDir)cocos2dx\platform&quot;;&quot;$(SolutionDir)cocos2dx\platform\win32&quot;;&quot;$(SolutionDir)cocos2dx\platform\third_party\win32\OGLES&quot;;..\Classes" AdditionalIncludeDirectories="&quot;$(SolutionDir)cocos2dx&quot;;&quot;$(SolutionDir)cocos2dx\include&quot;;&quot;$(SolutionDir)cocos2dx\kazmath\include&quot;;&quot;$(SolutionDir)cocos2dx\platform\win32&quot;;&quot;$(SolutionDir)cocos2dx\platform\third_party\win32\OGLES&quot;;..\Classes"
PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS" PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS"
RuntimeLibrary="2" RuntimeLibrary="2"
EnableFunctionLevelLinking="true" EnableFunctionLevelLinking="true"
UsePrecompiledHeader="0" UsePrecompiledHeader="0"
WarningLevel="3" WarningLevel="3"
DebugInformationFormat="3" DebugInformationFormat="3"
DisableSpecificWarnings="4267;4251;4244"
/> />
<Tool <Tool
Name="VCManagedResourceCompilerTool" Name="VCManagedResourceCompilerTool"
@ -138,7 +140,7 @@
/> />
<Tool <Tool
Name="VCLinkerTool" Name="VCLinkerTool"
AdditionalDependencies="libcocos2d.lib" AdditionalDependencies="opengl32.lib glew32.lib libcocos2d.lib"
OutputFile="$(OutDir)\$(ProjectName).exe" OutputFile="$(OutDir)\$(ProjectName).exe"
LinkIncremental="1" LinkIncremental="1"
AdditionalLibraryDirectories="$(OutDir)" AdditionalLibraryDirectories="$(OutDir)"

View File

@ -19,12 +19,12 @@
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType> <ConfigurationType>Application</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet> <CharacterSet>Unicode</CharacterSet>
<WholeProgramOptimization>true</WholeProgramOptimization> <WholeProgramOptimization>true</WholeProgramOptimization>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType> <ConfigurationType>Application</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet> <CharacterSet>Unicode</CharacterSet>
</PropertyGroup> </PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings"> <ImportGroup Label="ExtensionSettings">
@ -54,8 +54,8 @@
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile> <ClCompile>
<Optimization>Disabled</Optimization> <Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>.;..\Classes;..\..\cocos2dx;..\..\cocos2dx\actions;..\..\cocos2dx\base_nodes;..\..\cocos2dx\cocoa;..\..\cocos2dx\effects;..\..\cocos2dx\include;..\..\cocos2dx\kazmath\include;..\..\cocos2dx\keypad_dispatcher;..\..\cocos2dx\label_nodes;..\..\cocos2dx\layers_scenes_transitions_nodes;..\..\cocos2dx\menu_nodes;..\..\cocos2dx\misc_nodes;..\..\cocos2dx\particle_nodes;..\..\cocos2dx\script_support;..\..\cocos2dx\shaders;..\..\cocos2dx\sprite_nodes;..\..\cocos2dx\support;..\..\cocos2dx\text_input_node;..\..\cocos2dx\textures;..\..\cocos2dx\tileMap_parallax_nodes;..\..\cocos2dx\touch_dispatcher;..\..\cocos2dx\platform;..\..\cocos2dx\platform\win32;..\..\cocos2dx\platform\third_party\win32;..\..\cocos2dx\platform\third_party\win32\OGLES;..\..\CocosDenshion\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <AdditionalIncludeDirectories>.;..\Classes;..\..\cocos2dx;..\..\cocos2dx\include;..\..\cocos2dx\kazmath\include;..\..\cocos2dx\platform\win32;..\..\cocos2dx\platform\third_party\win32;..\..\cocos2dx\platform\third_party\win32\OGLES;..\..\CocosDenshion\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions> <PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;COCOS2D_DEBUG=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>true</MinimalRebuild> <MinimalRebuild>true</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks> <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary> <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
@ -63,6 +63,7 @@
</PrecompiledHeader> </PrecompiledHeader>
<WarningLevel>Level3</WarningLevel> <WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>EditAndContinue</DebugInformationFormat> <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
<DisableSpecificWarnings>4267;4251;4244</DisableSpecificWarnings>
</ClCompile> </ClCompile>
<Link> <Link>
<AdditionalDependencies>libcocos2d.lib;%(AdditionalDependencies)</AdditionalDependencies> <AdditionalDependencies>libcocos2d.lib;%(AdditionalDependencies)</AdditionalDependencies>
@ -81,14 +82,15 @@
<ClCompile> <ClCompile>
<Optimization>MaxSpeed</Optimization> <Optimization>MaxSpeed</Optimization>
<IntrinsicFunctions>true</IntrinsicFunctions> <IntrinsicFunctions>true</IntrinsicFunctions>
<AdditionalIncludeDirectories>.;..\Classes;..\..\cocos2dx;..\..\cocos2dx\actions;..\..\cocos2dx\base_nodes;..\..\cocos2dx\cocoa;..\..\cocos2dx\effects;..\..\cocos2dx\include;..\..\cocos2dx\kazmath\include;..\..\cocos2dx\keypad_dispatcher;..\..\cocos2dx\label_nodes;..\..\cocos2dx\layers_scenes_transitions_nodes;..\..\cocos2dx\menu_nodes;..\..\cocos2dx\misc_nodes;..\..\cocos2dx\particle_nodes;..\..\cocos2dx\script_support;..\..\cocos2dx\shaders;..\..\cocos2dx\sprite_nodes;..\..\cocos2dx\support;..\..\cocos2dx\text_input_node;..\..\cocos2dx\textures;..\..\cocos2dx\tileMap_parallax_nodes;..\..\cocos2dx\touch_dispatcher;..\..\cocos2dx\platform;..\..\cocos2dx\platform\win32;..\..\cocos2dx\platform\third_party\win32;..\..\cocos2dx\platform\third_party\win32\OGLES;..\..\CocosDenshion\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <AdditionalIncludeDirectories>.;..\Classes;..\..\cocos2dx;..\..\cocos2dx\include;..\..\cocos2dx\kazmath\include;..\..\cocos2dx\platform\win32;..\..\cocos2dx\platform\third_party\win32;..\..\cocos2dx\platform\third_party\win32\OGLES;..\..\CocosDenshion\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions> <PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary> <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<FunctionLevelLinking>true</FunctionLevelLinking> <FunctionLevelLinking>true</FunctionLevelLinking>
<PrecompiledHeader> <PrecompiledHeader>
</PrecompiledHeader> </PrecompiledHeader>
<WarningLevel>Level3</WarningLevel> <WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat> <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<DisableSpecificWarnings>4267;4251;4244</DisableSpecificWarnings>
</ClCompile> </ClCompile>
<Link> <Link>
<AdditionalDependencies>libcocos2d.lib;%(AdditionalDependencies)</AdditionalDependencies> <AdditionalDependencies>libcocos2d.lib;%(AdditionalDependencies)</AdditionalDependencies>

View File

@ -2,14 +2,14 @@ cocos2d-x
================== ==================
[cocos2d-x][1] is a multi-platform 2D game engine in C++, based on [cocos2d-iphone][2] and licensed under MIT. [cocos2d-x][1] is a multi-platform 2D game engine in C++, based on [cocos2d-iphone][2] and licensed under MIT.
Now this engine has been expended to iOS, Android, Bada, BlackBerry Playbook, Marmalade and desktop operating systems like Linux, WindowsXP & Windows7. Now this engine has been expanded to iOS, Android, Bada, BlackBerry, Marmalade and desktop operating systems like Linux, WindowsXP & Windows7.
Multi Platform Multi Platform
------------- -------------
* iOS: stable, well tested on iOS 4.0 ~ 5.0 SDK. * iOS: stable, well tested on iOS 4.x ~ 5.x SDK.
* Android: stable, well tested on 2.0~3.1, based on ndk r5 ~ r7. * Android: stable, well tested on 2.0~4.0, based on ndk r5 ~ r8.
* Bada: stable on Bada SDK 1.0 & 2.0 * Bada: stable on Bada SDK 1.0 & 2.0
* BlackBerry Playbook: stable, contribued by engineers working at RIM * BlackBerry Playbook & BB10: stable, contribued by engineers working at RIM
* Marmalade: stable since cocos2d-x-0.11.0 * Marmalade: stable since cocos2d-x-0.11.0
* Windows: stable, tested on WinXP, Vista, Win7. Please upgrde the drive of your video card if you meet problems on OpenGL functions * Windows: stable, tested on WinXP, Vista, Win7. Please upgrde the drive of your video card if you meet problems on OpenGL functions
* Linux: usable. * Linux: usable.
@ -28,7 +28,7 @@ Contact us
[1]: http://www.cocos2d-x.org "cocos2d-x" [1]: http://www.cocos2d-x.org "cocos2d-x"
[2]: http://www.cocos2d-iphone.org "cocos2d for iPhone" [2]: http://www.cocos2d-iphone.org "cocos2d for iPhone"
[3]: http://www.cocos2d-x.org "www.cocos2d-x.org" [3]: http://www.cocos2d-x.org "www.cocos2d-x.org"
[4]: http://www.cocos2d-x.org/embedded/cocos2d-x/classes.html "API References" [4]: http://www.cocos2d-x.org/projects/cocos2d-x/wiki/Reference "API References"
[5]: http://forum.cocos2d-x.org "http://forum.cocos2d-x.org" [5]: http://forum.cocos2d-x.org "http://forum.cocos2d-x.org"
[6]: http://www.twitter.com/cocos2dx "http://www.twitter.com/cocos2dx" [6]: http://www.twitter.com/cocos2dx "http://www.twitter.com/cocos2dx"
[7]: http://t.sina.com.cn/cocos2dx "http://t.sina.com.cn/cocos2dx" [7]: http://t.sina.com.cn/cocos2dx "http://t.sina.com.cn/cocos2dx"

View File

@ -46,6 +46,7 @@ set CC_TEST_BIN=tests.exe
set CC_TEST_RES=..\tests\Resources\*.* set CC_TEST_RES=..\tests\Resources\*.*
set CC_HELLOWORLD_RES=..\HelloWorld\Resources\*.* set CC_HELLOWORLD_RES=..\HelloWorld\Resources\*.*
set CC_HELLOLUA_RES=..\HelloLua\Resources\*.* set CC_HELLOLUA_RES=..\HelloLua\Resources\*.*
set CC_TESTJS_RES=..\testjs\Resources\*.*
if not exist "%CC_TEST_BIN%" ( if not exist "%CC_TEST_BIN%" (
echo Can't find the binary "tests.exe", is there build error? echo Can't find the binary "tests.exe", is there build error?
@ -59,6 +60,8 @@ echo.
xcopy /E /Y /Q "%CC_TEST_RES%" . xcopy /E /Y /Q "%CC_TEST_RES%" .
xcopy /E /Y /Q "%CC_HELLOWORLD_RES%" . xcopy /E /Y /Q "%CC_HELLOWORLD_RES%" .
xcopy /E /Y /Q "%CC_HELLOLUA_RES%" . xcopy /E /Y /Q "%CC_HELLOLUA_RES%" .
xcopy /E /Y /Q "%CC_TESTJS_RES%" .
call "%CC_TEST_BIN%" call "%CC_TEST_BIN%"
start http://www.cocos2d-x.org/projects/cocos2d-x/wiki/Cocos2d-x_Application_Wizard_for_Visual_Studio_User_Guide start http://www.cocos2d-x.org/projects/cocos2d-x/wiki/Cocos2d-x_Application_Wizard_for_Visual_Studio_User_Guide
goto EOF goto EOF
@ -66,4 +69,4 @@ goto EOF
:ERROR :ERROR
pause pause
:EOF :EOF

View File

@ -1,45 +1,45 @@
LOCAL_PATH := $(call my-dir) LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS) include $(CLEAR_VARS)
LOCAL_MODULE := chipmunk_static LOCAL_MODULE := chipmunk_static
LOCAL_MODULE_FILENAME := libchipmunk LOCAL_MODULE_FILENAME := libchipmunk
LOCAL_SRC_FILES := \ LOCAL_SRC_FILES := \
src/chipmunk.c \ src/chipmunk.c \
src/constraints/cpConstraint.c \ src/constraints/cpConstraint.c \
src/constraints/cpDampedRotarySpring.c \ src/constraints/cpDampedRotarySpring.c \
src/constraints/cpDampedSpring.c \ src/constraints/cpDampedSpring.c \
src/constraints/cpGearJoint.c \ src/constraints/cpGearJoint.c \
src/constraints/cpGrooveJoint.c \ src/constraints/cpGrooveJoint.c \
src/constraints/cpPinJoint.c \ src/constraints/cpPinJoint.c \
src/constraints/cpPivotJoint.c \ src/constraints/cpPivotJoint.c \
src/constraints/cpRatchetJoint.c \ src/constraints/cpRatchetJoint.c \
src/constraints/cpRotaryLimitJoint.c \ src/constraints/cpRotaryLimitJoint.c \
src/constraints/cpSimpleMotor.c \ src/constraints/cpSimpleMotor.c \
src/constraints/cpSlideJoint.c \ src/constraints/cpSlideJoint.c \
src/cpArbiter.c \ src/cpArbiter.c \
src/cpArray.c \ src/cpArray.c \
src/cpBB.c \ src/cpBB.c \
src/cpBBTree.c \ src/cpBBTree.c \
src/cpBody.c \ src/cpBody.c \
src/cpCollision.c \ src/cpCollision.c \
src/cpHashSet.c \ src/cpHashSet.c \
src/cpPolyShape.c \ src/cpPolyShape.c \
src/cpShape.c \ src/cpShape.c \
src/cpSpace.c \ src/cpSpace.c \
src/cpSpaceComponent.c \ src/cpSpaceComponent.c \
src/cpSpaceHash.c \ src/cpSpaceHash.c \
src/cpSpaceQuery.c \ src/cpSpaceQuery.c \
src/cpSpaceStep.c \ src/cpSpaceStep.c \
src/cpSpatialIndex.c \ src/cpSpatialIndex.c \
src/cpSweep1D.c \ src/cpSweep1D.c \
src/cpVect.c src/cpVect.c
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/include/chipmunk LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/include/chipmunk
LOCAL_C_INCLUDES := $(LOCAL_PATH)/include/chipmunk LOCAL_C_INCLUDES := $(LOCAL_PATH)/include/chipmunk
LOCAL_CFLAGS := -std=c99 LOCAL_CFLAGS := -std=c99
include $(BUILD_STATIC_LIBRARY) include $(BUILD_STATIC_LIBRARY)

View File

@ -22,31 +22,34 @@
#ifndef CHIPMUNK_HEADER #ifndef CHIPMUNK_HEADER
#define CHIPMUNK_HEADER #define CHIPMUNK_HEADER
#include <stdlib.h>
#include <math.h>
#ifdef __cplusplus #ifdef __cplusplus
extern "C" { extern "C" {
#endif #endif
#ifndef CP_ALLOW_PRIVATE_ACCESS #ifndef CP_ALLOW_PRIVATE_ACCESS
#define CP_ALLOW_PRIVATE_ACCESS 0 #define CP_ALLOW_PRIVATE_ACCESS 0
#endif #endif
#if CP_ALLOW_PRIVATE_ACCESS == 1 #if CP_ALLOW_PRIVATE_ACCESS == 1
#define CP_PRIVATE(symbol) symbol #define CP_PRIVATE(symbol) symbol
#else #else
#define CP_PRIVATE(symbol) symbol##_private #define CP_PRIVATE(symbol) symbol##_private
#endif #endif
void cpMessage(const char *condition, const char *file, int line, int isError, int isHardError, const char *message, ...); void cpMessage(const char *condition, const char *file, int line, int isError, int isHardError, const char *message, ...);
#ifdef NDEBUG #ifdef NDEBUG
#define cpAssertWarn(condition, ...) #define cpAssertWarn(condition, ...)
#else #else
#define cpAssertWarn(condition, ...) if(!(condition)) cpMessage(#condition, __FILE__, __LINE__, 0, 0, __VA_ARGS__) #define cpAssertWarn(condition, ...) if(!(condition)) cpMessage(#condition, __FILE__, __LINE__, 0, 0, __VA_ARGS__)
#endif #endif
#ifdef NDEBUG #ifdef NDEBUG
#define cpAssertSoft(condition, ...) #define cpAssertSoft(condition, ...)
#else #else
#define cpAssertSoft(condition, ...) if(!(condition)) cpMessage(#condition, __FILE__, __LINE__, 1, 0, __VA_ARGS__) #define cpAssertSoft(condition, ...) if(!(condition)) cpMessage(#condition, __FILE__, __LINE__, 1, 0, __VA_ARGS__)
#endif #endif
// Hard assertions are important and cheap to execute. They are not disabled by compiling as debug. // Hard assertions are important and cheap to execute. They are not disabled by compiling as debug.
@ -54,28 +57,28 @@ void cpMessage(const char *condition, const char *file, int line, int isError, i
#include "chipmunk_types.h" #include "chipmunk_types.h"
/// @defgroup misc Misc /// @defgroup misc Misc
/// @{ /// @{
/// Allocated size for various Chipmunk buffers /// Allocated size for various Chipmunk buffers
#ifndef CP_BUFFER_BYTES #ifndef CP_BUFFER_BYTES
#define CP_BUFFER_BYTES (32*1024) #define CP_BUFFER_BYTES (32*1024)
#endif #endif
#ifndef cpcalloc #ifndef cpcalloc
/// Chipmunk calloc() alias. /// Chipmunk calloc() alias.
#define cpcalloc calloc #define cpcalloc calloc
#endif #endif
#ifndef cprealloc #ifndef cprealloc
/// Chipmunk realloc() alias. /// Chipmunk realloc() alias.
#define cprealloc realloc #define cprealloc realloc
#endif #endif
#ifndef cpfree #ifndef cpfree
/// Chipmunk free() alias. /// Chipmunk free() alias.
#define cpfree free #define cpfree free
#endif #endif
typedef struct cpArray cpArray; typedef struct cpArray cpArray;
@ -98,15 +101,15 @@ typedef struct cpSpace cpSpace;
#include "cpShape.h" #include "cpShape.h"
#include "cpPolyShape.h" #include "cpPolyShape.h"
#include "cpArbiter.h" #include "cpArbiter.h"
#include "constraints/cpConstraint.h" #include "constraints/cpConstraint.h"
#include "cpSpace.h" #include "cpSpace.h"
// Chipmunk 6.0.3 // Chipmunk 6.1.1
#define CP_VERSION_MAJOR 6 #define CP_VERSION_MAJOR 6
#define CP_VERSION_MINOR 0 #define CP_VERSION_MINOR 1
#define CP_VERSION_RELEASE 3 #define CP_VERSION_RELEASE 1
/// Version string. /// Version string.
extern const char *cpVersionString; extern const char *cpVersionString;
@ -148,6 +151,54 @@ cpFloat cpMomentForBox(cpFloat m, cpFloat width, cpFloat height);
/// Calculate the moment of inertia for a solid box. /// Calculate the moment of inertia for a solid box.
cpFloat cpMomentForBox2(cpFloat m, cpBB box); cpFloat cpMomentForBox2(cpFloat m, cpBB box);
/// Calculate the convex hull of a given set of points. Returns the count of points in the hull.
/// @c result must be a pointer to a @c cpVect array with at least @c count elements. If @c result is @c NULL, then @c verts will be reduced instead.
/// @c first is an optional pointer to an integer to store where the first vertex in the hull came from (i.e. verts[first] == result[0])
/// @c tol is the allowed amount to shrink the hull when simplifying it. A tolerance of 0.0 creates an exact hull.
int cpConvexHull(int count, cpVect *verts, cpVect *result, int *first, cpFloat tol);
#ifdef _MSC_VER
#include "malloc.h"
#endif
/// Convenience macro to work with cpConvexHull.
/// @c count and @c verts is the input array passed to cpConvexHull().
/// @c count_var and @c verts_var are the names of the variables the macro creates to store the result.
/// The output vertex array is allocated on the stack using alloca() so it will be freed automatically, but cannot be returned from the current scope.
#define CP_CONVEX_HULL(__count__, __verts__, __count_var__, __verts_var__) \
cpVect *__verts_var__ = (cpVect *)alloca(__count__*sizeof(cpVect)); \
int __count_var__ = cpConvexHull(__count__, __verts__, __verts_var__, NULL, 0.0); \
#if defined(__has_extension)
#if __has_extension(blocks)
// Define alternate block based alternatives for a few of the callback heavy functions.
// Collision handlers are post-step callbacks are not included to avoid memory management issues.
// If you want to use blocks for those and are aware of how to correctly manage the memory, the implementation is trivial.
void cpSpaceEachBody_b(cpSpace *space, void (^block)(cpBody *body));
void cpSpaceEachShape_b(cpSpace *space, void (^block)(cpShape *shape));
void cpSpaceEachConstraint_b(cpSpace *space, void (^block)(cpConstraint *constraint));
void cpBodyEachShape_b(cpBody *body, void (^block)(cpShape *shape));
void cpBodyEachConstraint_b(cpBody *body, void (^block)(cpConstraint *constraint));
void cpBodyEachArbiter_b(cpBody *body, void (^block)(cpArbiter *arbiter));
typedef void (^cpSpaceNearestPointQueryBlock)(cpShape *shape, cpFloat distance, cpVect point);
void cpSpaceNearestPointQuery_b(cpSpace *space, cpVect point, cpFloat maxDistance, cpLayers layers, cpGroup group, cpSpaceNearestPointQueryBlock block);
typedef void (^cpSpaceSegmentQueryBlock)(cpShape *shape, cpFloat t, cpVect n);
void cpSpaceSegmentQuery_b(cpSpace *space, cpVect start, cpVect end, cpLayers layers, cpGroup group, cpSpaceSegmentQueryBlock block);
typedef void (^cpSpaceBBQueryBlock)(cpShape *shape);
void cpSpaceBBQuery_b(cpSpace *space, cpBB bb, cpLayers layers, cpGroup group, cpSpaceBBQueryBlock block);
typedef void (^cpSpaceShapeQueryBlock)(cpShape *shape, cpContactPointSet *points);
cpBool cpSpaceShapeQuery_b(cpSpace *space, cpShape *shape, cpSpaceShapeQueryBlock block);
#endif
#endif
//@} //@}
#ifdef __cplusplus #ifdef __cplusplus

View File

@ -14,7 +14,7 @@
#endif #endif
#define MAKE_PROPERTIES_REF(struct, property) \ #define MAKE_PROPERTIES_REF(struct, property) \
MAKE_REF(struct##Get##property); MAKE_REF(struct##Set##property); MAKE_REF(struct##Get##property); MAKE_REF(struct##Set##property);
MAKE_REF(cpv); // makes a variable named _cpv that contains the function pointer for cpv() MAKE_REF(cpv); // makes a variable named _cpv that contains the function pointer for cpv()
MAKE_REF(cpveql); MAKE_REF(cpveql);
@ -152,7 +152,6 @@ MAKE_REF(cpSpatialIndexInsert);
MAKE_REF(cpSpatialIndexRemove); MAKE_REF(cpSpatialIndexRemove);
MAKE_REF(cpSpatialIndexReindex); MAKE_REF(cpSpatialIndexReindex);
MAKE_REF(cpSpatialIndexReindexObject); MAKE_REF(cpSpatialIndexReindexObject);
MAKE_REF(cpSpatialIndexPointQuery);
MAKE_REF(cpSpatialIndexSegmentQuery); MAKE_REF(cpSpatialIndexSegmentQuery);
MAKE_REF(cpSpatialIndexQuery); MAKE_REF(cpSpatialIndexQuery);
MAKE_REF(cpSpatialIndexReindexQuery); MAKE_REF(cpSpatialIndexReindexQuery);

View File

@ -28,8 +28,8 @@
//MARK: cpArray //MARK: cpArray
struct cpArray { struct cpArray {
int num, max; int num, max;
void **arr; void **arr;
}; };
cpArray *cpArrayNew(int size); cpArray *cpArrayNew(int size);
@ -48,26 +48,26 @@ void cpArrayFreeEach(cpArray *arr, void (freeFunc)(void*));
static inline cpConstraint * static inline cpConstraint *
cpConstraintNext(cpConstraint *node, cpBody *body) cpConstraintNext(cpConstraint *node, cpBody *body)
{ {
return (node->a == body ? node->next_a : node->next_b); return (node->a == body ? node->next_a : node->next_b);
} }
#define CP_BODY_FOREACH_CONSTRAINT(bdy, var)\ #define CP_BODY_FOREACH_CONSTRAINT(bdy, var)\
for(cpConstraint *var = bdy->constraintList; var; var = cpConstraintNext(var, bdy)) for(cpConstraint *var = bdy->constraintList; var; var = cpConstraintNext(var, bdy))
static inline cpArbiter * static inline cpArbiter *
cpArbiterNext(cpArbiter *node, cpBody *body) cpArbiterNext(cpArbiter *node, cpBody *body)
{ {
return (node->body_a == body ? node->thread_a.next : node->thread_b.next); return (node->body_a == body ? node->thread_a.next : node->thread_b.next);
} }
#define CP_BODY_FOREACH_ARBITER(bdy, var)\ #define CP_BODY_FOREACH_ARBITER(bdy, var)\
for(cpArbiter *var = bdy->arbiterList; var; var = cpArbiterNext(var, bdy)) for(cpArbiter *var = bdy->arbiterList; var; var = cpArbiterNext(var, bdy))
#define CP_BODY_FOREACH_SHAPE(body, var)\ #define CP_BODY_FOREACH_SHAPE(body, var)\
for(cpShape *var = body->shapeList; var; var = var->next) for(cpShape *var = body->shapeList; var; var = var->next)
#define CP_BODY_FOREACH_COMPONENT(root, var)\ #define CP_BODY_FOREACH_COMPONENT(root, var)\
for(cpBody *var = root; var; var = var->node.next) for(cpBody *var = root; var; var = var->node.next)
//MARK: cpHashSet //MARK: cpHashSet
@ -99,54 +99,80 @@ void cpBodyRemoveConstraint(cpBody *body, cpConstraint *constraint);
//MARK: Shape/Collision Functions //MARK: Shape/Collision Functions
// TODO should move this to the cpVect API. It's pretty useful.
static inline cpVect
cpClosetPointOnSegment(const cpVect p, const cpVect a, const cpVect b)
{
cpVect delta = cpvsub(a, b);
cpFloat t = cpfclamp01(cpvdot(delta, cpvsub(p, b))/cpvlengthsq(delta));
return cpvadd(b, cpvmult(delta, t));
}
cpShape* cpShapeInit(cpShape *shape, const cpShapeClass *klass, cpBody *body); cpShape* cpShapeInit(cpShape *shape, const cpShapeClass *klass, cpBody *body);
static inline cpBool static inline cpBool
cpShapeActive(cpShape *shape) cpShapeActive(cpShape *shape)
{ {
return shape->prev || shape->body->shapeList == shape; return shape->prev || (shape->body && shape->body->shapeList == shape);
} }
int cpCollideShapes(const cpShape *a, const cpShape *b, cpContact *arr); int cpCollideShapes(const cpShape *a, const cpShape *b, cpContact *arr);
// TODO doesn't really need to be inline, but need a better place to put this function
static inline cpSplittingPlane
cpSplittingPlaneNew(cpVect a, cpVect b)
{
cpVect n = cpvnormalize(cpvperp(cpvsub(b, a)));
cpSplittingPlane plane = {n, cpvdot(n, a)};
return plane;
}
static inline cpFloat
cpSplittingPlaneCompare(cpSplittingPlane plane, cpVect v)
{
return cpvdot(plane.n, v) - plane.d;
}
void cpLoopIndexes(cpVect *verts, int count, int *start, int *end);
static inline cpFloat static inline cpFloat
cpPolyShapeValueOnAxis(const cpPolyShape *poly, const cpVect n, const cpFloat d) cpPolyShapeValueOnAxis(const cpPolyShape *poly, const cpVect n, const cpFloat d)
{ {
cpVect *verts = poly->tVerts; cpVect *verts = poly->tVerts;
cpFloat min = cpvdot(n, verts[0]); cpFloat min = cpvdot(n, verts[0]);
for(int i=1; i<poly->numVerts; i++){ for(int i=1; i<poly->numVerts; i++){
min = cpfmin(min, cpvdot(n, verts[i])); min = cpfmin(min, cpvdot(n, verts[i]));
} }
return min - d; return min - d;
} }
static inline cpBool static inline cpBool
cpPolyShapeContainsVert(const cpPolyShape *poly, const cpVect v) cpPolyShapeContainsVert(const cpPolyShape *poly, const cpVect v)
{ {
cpPolyShapeAxis *axes = poly->tAxes; cpSplittingPlane *planes = poly->tPlanes;
for(int i=0; i<poly->numVerts; i++){ for(int i=0; i<poly->numVerts; i++){
cpFloat dist = cpvdot(axes[i].n, v) - axes[i].d; cpFloat dist = cpSplittingPlaneCompare(planes[i], v);
if(dist > 0.0f) return cpFalse; if(dist > 0.0f) return cpFalse;
} }
return cpTrue; return cpTrue;
} }
static inline cpBool static inline cpBool
cpPolyShapeContainsVertPartial(const cpPolyShape *poly, const cpVect v, const cpVect n) cpPolyShapeContainsVertPartial(const cpPolyShape *poly, const cpVect v, const cpVect n)
{ {
cpPolyShapeAxis *axes = poly->tAxes; cpSplittingPlane *planes = poly->tPlanes;
for(int i=0; i<poly->numVerts; i++){ for(int i=0; i<poly->numVerts; i++){
if(cpvdot(axes[i].n, n) < 0.0f) continue; if(cpvdot(planes[i].n, n) < 0.0f) continue;
cpFloat dist = cpvdot(axes[i].n, v) - axes[i].d; cpFloat dist = cpSplittingPlaneCompare(planes[i], v);
if(dist > 0.0f) return cpFalse; if(dist > 0.0f) return cpFalse;
} }
return cpTrue; return cpTrue;
} }
//MARK: Spatial Index Functions //MARK: Spatial Index Functions
@ -162,7 +188,7 @@ void cpSpacePushFreshContactBuffer(cpSpace *space);
cpContact *cpContactBufferGetArray(cpSpace *space); cpContact *cpContactBufferGetArray(cpSpace *space);
void cpSpacePushContacts(cpSpace *space, int count); void cpSpacePushContacts(cpSpace *space, int count);
void *cpSpaceGetPostStepData(cpSpace *space, void *obj); void *cpSpaceGetPostStepData(cpSpace *space, void *key);
cpBool cpSpaceArbiterSetFilter(cpArbiter *arb, cpSpace *space); cpBool cpSpaceArbiterSetFilter(cpArbiter *arb, cpSpace *space);
void cpSpaceFilterArbiters(cpSpace *space, cpBody *body, cpShape *filter); void cpSpaceFilterArbiters(cpSpace *space, cpBody *body, cpShape *filter);
@ -174,18 +200,18 @@ void cpSpaceUnlock(cpSpace *space, cpBool runPostStep);
static inline cpCollisionHandler * static inline cpCollisionHandler *
cpSpaceLookupHandler(cpSpace *space, cpCollisionType a, cpCollisionType b) cpSpaceLookupHandler(cpSpace *space, cpCollisionType a, cpCollisionType b)
{ {
cpCollisionType types[] = {a, b}; cpCollisionType types[] = {a, b};
return (cpCollisionHandler *)cpHashSetFind(space->collisionHandlers, CP_HASH_PAIR(a, b), types); return (cpCollisionHandler *)cpHashSetFind(space->collisionHandlers, CP_HASH_PAIR(a, b), types);
} }
static inline void static inline void
cpSpaceUncacheArbiter(cpSpace *space, cpArbiter *arb) cpSpaceUncacheArbiter(cpSpace *space, cpArbiter *arb)
{ {
cpShape *a = arb->a, *b = arb->b; cpShape *a = arb->a, *b = arb->b;
cpShape *shape_pair[] = {a, b}; cpShape *shape_pair[] = {a, b};
cpHashValue arbHashID = CP_HASH_PAIR((cpHashValue)a, (cpHashValue)b); cpHashValue arbHashID = CP_HASH_PAIR((cpHashValue)a, (cpHashValue)b);
cpHashSetRemove(space->cachedArbiters, arbHashID, shape_pair); cpHashSetRemove(space->cachedArbiters, arbHashID, shape_pair);
cpArrayDeleteObj(space->arbiters, arb); cpArrayDeleteObj(space->arbiters, arb);
} }
void cpShapeUpdateFunc(cpShape *shape, void *unused); void cpShapeUpdateFunc(cpShape *shape, void *unused);
@ -196,16 +222,16 @@ void cpSpaceCollideShapes(cpShape *a, cpShape *b, cpSpace *space);
//MARK: Arbiters //MARK: Arbiters
struct cpContact { struct cpContact {
cpVect p, n; cpVect p, n;
cpFloat dist; cpFloat dist;
cpVect r1, r2; cpVect r1, r2;
cpFloat nMass, tMass, bounce; cpFloat nMass, tMass, bounce;
cpFloat jnAcc, jtAcc, jBias; cpFloat jnAcc, jtAcc, jBias;
cpFloat bias; cpFloat bias;
cpHashValue hash; cpHashValue hash;
}; };
cpContact* cpContactInit(cpContact *con, cpVect p, cpVect n, cpFloat dist, cpHashValue hash); cpContact* cpContactInit(cpContact *con, cpVect p, cpVect n, cpFloat dist, cpHashValue hash);
@ -214,15 +240,15 @@ cpArbiter* cpArbiterInit(cpArbiter *arb, cpShape *a, cpShape *b);
static inline void static inline void
cpArbiterCallSeparate(cpArbiter *arb, cpSpace *space) cpArbiterCallSeparate(cpArbiter *arb, cpSpace *space)
{ {
// The handler needs to be looked up again as the handler cached on the arbiter may have been deleted since the last step. // The handler needs to be looked up again as the handler cached on the arbiter may have been deleted since the last step.
cpCollisionHandler *handler = cpSpaceLookupHandler(space, arb->a->collision_type, arb->b->collision_type); cpCollisionHandler *handler = cpSpaceLookupHandler(space, arb->a->collision_type, arb->b->collision_type);
handler->separate(arb, space, handler->data); handler->separate(arb, space, handler->data);
} }
static inline struct cpArbiterThread * static inline struct cpArbiterThread *
cpArbiterThreadForBody(cpArbiter *arb, cpBody *body) cpArbiterThreadForBody(cpArbiter *arb, cpBody *body)
{ {
return (arb->body_a == body ? &arb->thread_a : &arb->thread_b); return (arb->body_a == body ? &arb->thread_a : &arb->thread_b);
} }
void cpArbiterUnthread(cpArbiter *arb); void cpArbiterUnthread(cpArbiter *arb);

View File

@ -5,27 +5,27 @@
#import "TargetConditionals.h" #import "TargetConditionals.h"
#endif #endif
#if (TARGET_OS_IPHONE == 1) && (!defined CP_USE_CGPOINTS) #if (TARGET_OS_IPHONE == 1) || (TARGET_OS_MAC == 1) && (!defined CP_USE_CGPOINTS)
#define CP_USE_CGPOINTS 1 #define CP_USE_CGPOINTS 1
#endif #endif
#ifdef CP_USE_CGPOINTS #if CP_USE_CGPOINTS == 1
#if TARGET_OS_IPHONE #if TARGET_OS_IPHONE
#import <CoreGraphics/CGGeometry.h> #import <CoreGraphics/CGGeometry.h>
#elif TARGET_OS_MAC #elif TARGET_OS_MAC
#import <ApplicationServices/ApplicationServices.h> #import <ApplicationServices/ApplicationServices.h>
#endif #endif
#if defined(__LP64__) && __LP64__ #if defined(__LP64__) && __LP64__
#define CP_USE_DOUBLES 1 #define CP_USE_DOUBLES 1
#else #else
#define CP_USE_DOUBLES 0 #define CP_USE_DOUBLES 0
#endif #endif
#endif #endif
#ifndef CP_USE_DOUBLES #ifndef CP_USE_DOUBLES
// use doubles by default for higher precision // use doubles by default for higher precision
#define CP_USE_DOUBLES 1 #define CP_USE_DOUBLES 1
#endif #endif
/// @defgroup basicTypes Basic Types /// @defgroup basicTypes Basic Types
@ -35,89 +35,88 @@
#if CP_USE_DOUBLES #if CP_USE_DOUBLES
/// Chipmunk's floating point type. /// Chipmunk's floating point type.
/// Can be reconfigured at compile time. /// Can be reconfigured at compile time.
typedef double cpFloat; typedef double cpFloat;
#define cpfsqrt sqrt #define cpfsqrt sqrt
#define cpfsin sin #define cpfsin sin
#define cpfcos cos #define cpfcos cos
#define cpfacos acos #define cpfacos acos
#define cpfatan2 atan2 #define cpfatan2 atan2
#define cpfmod fmod #define cpfmod fmod
#define cpfexp exp #define cpfexp exp
#define cpfpow pow #define cpfpow pow
#define cpffloor floor #define cpffloor floor
#define cpfceil ceil #define cpfceil ceil
#else #else
typedef float cpFloat; typedef float cpFloat;
#define cpfsqrt sqrtf #define cpfsqrt sqrtf
#define cpfsin sinf #define cpfsin sinf
#define cpfcos cosf #define cpfcos cosf
#define cpfacos acosf #define cpfacos acosf
#define cpfatan2 atan2f #define cpfatan2 atan2f
#define cpfmod fmodf #define cpfmod fmodf
#define cpfexp expf #define cpfexp expf
#define cpfpow powf #define cpfpow powf
#define cpffloor floorf #define cpffloor floorf
#define cpfceil ceilf #define cpfceil ceilf
#endif #endif
#ifndef INFINITY #ifndef INFINITY
//TODO use C++ infinity #ifdef _MSC_VER
#ifdef _MSC_VER union MSVC_EVIL_FLOAT_HACK
union MSVC_EVIL_FLOAT_HACK {
{ unsigned __int8 Bytes[4];
unsigned __int8 Bytes[4]; float Value;
float Value; };
}; static union MSVC_EVIL_FLOAT_HACK INFINITY_HACK = {{0x00, 0x00, 0x80, 0x7F}};
static union MSVC_EVIL_FLOAT_HACK INFINITY_HACK = {{0x00, 0x00, 0x80, 0x7F}}; #define INFINITY (INFINITY_HACK.Value)
#define INFINITY (INFINITY_HACK.Value) #endif
#endif
#ifdef __GNUC__
#ifdef __GNUC__ #define INFINITY (__builtin_inf())
#define INFINITY (__builtin_inf()) #endif
#endif
#ifndef INFINITY
#ifndef INFINITY #define INFINITY (1e1000)
#define INFINITY (1e1000) #endif
#endif
#endif #endif
#ifndef M_PI #ifndef M_PI
#define M_PI 3.14159265358979323846264338327950288 #define M_PI 3.14159265358979323846264338327950288
#endif #endif
#ifndef M_E #ifndef M_E
#define M_E 2.71828182845904523536028747135266250 #define M_E 2.71828182845904523536028747135266250
#endif #endif
/// Return the max of two cpFloats. /// Return the max of two cpFloats.
static inline cpFloat cpfmax(cpFloat a, cpFloat b) static inline cpFloat cpfmax(cpFloat a, cpFloat b)
{ {
return (a > b) ? a : b; return (a > b) ? a : b;
} }
/// Return the min of two cpFloats. /// Return the min of two cpFloats.
static inline cpFloat cpfmin(cpFloat a, cpFloat b) static inline cpFloat cpfmin(cpFloat a, cpFloat b)
{ {
return (a < b) ? a : b; return (a < b) ? a : b;
} }
/// Return the absolute value of a cpFloat. /// Return the absolute value of a cpFloat.
static inline cpFloat cpfabs(cpFloat f) static inline cpFloat cpfabs(cpFloat f)
{ {
return (f < 0) ? -f : f; return (f < 0) ? -f : f;
} }
/// Clamp @c f to be between @c min and @c max. /// Clamp @c f to be between @c min and @c max.
static inline cpFloat cpfclamp(cpFloat f, cpFloat min, cpFloat max) static inline cpFloat cpfclamp(cpFloat f, cpFloat min, cpFloat max)
{ {
return cpfmin(cpfmax(f, min), max); return cpfmin(cpfmax(f, min), max);
} }
/// Clamp @c f to be between 0 and 1. /// Clamp @c f to be between 0 and 1.
static inline cpFloat cpfclamp01(cpFloat f) static inline cpFloat cpfclamp01(cpFloat f)
{ {
return cpfmax(0.0f, cpfmin(f, 1.0f)); return cpfmax(0.0f, cpfmin(f, 1.0f));
} }
@ -125,13 +124,13 @@ static inline cpFloat cpfclamp01(cpFloat f)
/// Linearly interpolate (or extrapolate) between @c f1 and @c f2 by @c t percent. /// Linearly interpolate (or extrapolate) between @c f1 and @c f2 by @c t percent.
static inline cpFloat cpflerp(cpFloat f1, cpFloat f2, cpFloat t) static inline cpFloat cpflerp(cpFloat f1, cpFloat f2, cpFloat t)
{ {
return f1*(1.0f - t) + f2*t; return f1*(1.0f - t) + f2*t;
} }
/// Linearly interpolate from @c f1 to @c f2 by no more than @c d. /// Linearly interpolate from @c f1 to @c f2 by no more than @c d.
static inline cpFloat cpflerpconst(cpFloat f1, cpFloat f2, cpFloat d) static inline cpFloat cpflerpconst(cpFloat f1, cpFloat f2, cpFloat d)
{ {
return f1 + cpfclamp(f2 - f1, -d, d); return f1 + cpfclamp(f2 - f1, -d, d);
} }
/// Hash value type. /// Hash value type.
@ -140,75 +139,75 @@ typedef uintptr_t cpHashValue;
// Oh C, how we love to define our own boolean types to get compiler compatibility // Oh C, how we love to define our own boolean types to get compiler compatibility
/// Chipmunk's boolean type. /// Chipmunk's boolean type.
#ifdef CP_BOOL_TYPE #ifdef CP_BOOL_TYPE
typedef CP_BOOL_TYPE cpBool; typedef CP_BOOL_TYPE cpBool;
#else #else
typedef int cpBool; typedef int cpBool;
#endif #endif
#ifndef cpTrue #ifndef cpTrue
/// true value. /// true value.
#define cpTrue 1 #define cpTrue 1
#endif #endif
#ifndef cpFalse #ifndef cpFalse
/// false value. /// false value.
#define cpFalse 0 #define cpFalse 0
#endif #endif
#ifdef CP_DATA_POINTER_TYPE #ifdef CP_DATA_POINTER_TYPE
typedef CP_DATA_POINTER_TYPE cpDataPointer; typedef CP_DATA_POINTER_TYPE cpDataPointer;
#else #else
/// Type used for user data pointers. /// Type used for user data pointers.
typedef void * cpDataPointer; typedef void * cpDataPointer;
#endif #endif
#ifdef CP_COLLISION_TYPE_TYPE #ifdef CP_COLLISION_TYPE_TYPE
typedef CP_COLLISION_TYPE_TYPE cpCollisionType; typedef CP_COLLISION_TYPE_TYPE cpCollisionType;
#else #else
/// Type used for cpSpace.collision_type. /// Type used for cpSpace.collision_type.
typedef uintptr_t cpCollisionType; typedef uintptr_t cpCollisionType;
#endif #endif
#ifdef CP_GROUP_TYPE #ifdef CP_GROUP_TYPE
typedef CP_GROUP_TYPE cpGroup; typedef CP_GROUP_TYPE cpGroup;
#else #else
/// Type used for cpShape.group. /// Type used for cpShape.group.
typedef uintptr_t cpGroup; typedef uintptr_t cpGroup;
#endif #endif
#ifdef CP_LAYERS_TYPE #ifdef CP_LAYERS_TYPE
typedef CP_LAYERS_TYPE cpLayers; typedef CP_LAYERS_TYPE cpLayers;
#else #else
/// Type used for cpShape.layers. /// Type used for cpShape.layers.
typedef unsigned int cpLayers; typedef unsigned int cpLayers;
#endif #endif
#ifdef CP_TIMESTAMP_TYPE #ifdef CP_TIMESTAMP_TYPE
typedef CP_TIMESTAMP_TYPE cpTimestamp; typedef CP_TIMESTAMP_TYPE cpTimestamp;
#else #else
/// Type used for various timestamps in Chipmunk. /// Type used for various timestamps in Chipmunk.
typedef unsigned int cpTimestamp; typedef unsigned int cpTimestamp;
#endif #endif
#ifndef CP_NO_GROUP #ifndef CP_NO_GROUP
/// Value for cpShape.group signifying that a shape is in no group. /// Value for cpShape.group signifying that a shape is in no group.
#define CP_NO_GROUP ((cpGroup)0) #define CP_NO_GROUP ((cpGroup)0)
#endif #endif
#ifndef CP_ALL_LAYERS #ifndef CP_ALL_LAYERS
/// Value for cpShape.layers signifying that a shape is in every layer. /// Value for cpShape.layers signifying that a shape is in every layer.
#define CP_ALL_LAYERS (~(cpLayers)0) #define CP_ALL_LAYERS (~(cpLayers)0)
#endif #endif
/// @} /// @}
// CGPoints are structurally the same, and allow // CGPoints are structurally the same, and allow
// easy interoperability with other Cocoa libraries // easy interoperability with other Cocoa libraries
#ifdef CP_USE_CGPOINTS #if CP_USE_CGPOINTS
typedef CGPoint cpVect; typedef CGPoint cpVect;
#else #else
/// Chipmunk's 2D vector type. /// Chipmunk's 2D vector type.
/// @addtogroup cpVect /// @addtogroup cpVect
typedef struct cpVect{cpFloat x,y;} cpVect; typedef struct cpVect{cpFloat x,y;} cpVect;
#endif #endif

View File

@ -31,10 +31,10 @@ typedef cpFloat (*cpConstraintGetImpulseImpl)(cpConstraint *constraint);
/// @private /// @private
struct cpConstraintClass { struct cpConstraintClass {
cpConstraintPreStepImpl preStep; cpConstraintPreStepImpl preStep;
cpConstraintApplyCachedImpulseImpl applyCachedImpulse; cpConstraintApplyCachedImpulseImpl applyCachedImpulse;
cpConstraintApplyImpulseImpl applyImpulse; cpConstraintApplyImpulseImpl applyImpulse;
cpConstraintGetImpulseImpl getImpulse; cpConstraintGetImpulseImpl getImpulse;
}; };
/// Callback function type that gets called before solving a joint. /// Callback function type that gets called before solving a joint.
@ -45,41 +45,41 @@ typedef void (*cpConstraintPostSolveFunc)(cpConstraint *constraint, cpSpace *spa
/// Opaque cpConstraint struct. /// Opaque cpConstraint struct.
struct cpConstraint { struct cpConstraint {
CP_PRIVATE(const cpConstraintClass *klass); CP_PRIVATE(const cpConstraintClass *klass);
/// The first body connected to this constraint. /// The first body connected to this constraint.
cpBody *a; cpBody *a;
/// The second body connected to this constraint. /// The second body connected to this constraint.
cpBody *b; cpBody *b;
CP_PRIVATE(cpSpace *space); CP_PRIVATE(cpSpace *space);
CP_PRIVATE(cpConstraint *next_a); CP_PRIVATE(cpConstraint *next_a);
CP_PRIVATE(cpConstraint *next_b); CP_PRIVATE(cpConstraint *next_b);
/// The maximum force that this constraint is allowed to use. /// The maximum force that this constraint is allowed to use.
/// Defaults to infinity. /// Defaults to infinity.
cpFloat maxForce; cpFloat maxForce;
/// The rate at which joint error is corrected. /// The rate at which joint error is corrected.
/// Defaults to pow(1.0 - 0.1, 60.0) meaning that it will /// Defaults to pow(1.0 - 0.1, 60.0) meaning that it will
/// correct 10% of the error every 1/60th of a second. /// correct 10% of the error every 1/60th of a second.
cpFloat errorBias; cpFloat errorBias;
/// The maximum rate at which joint error is corrected. /// The maximum rate at which joint error is corrected.
/// Defaults to infinity. /// Defaults to infinity.
cpFloat maxBias; cpFloat maxBias;
/// Function called before the solver runs. /// Function called before the solver runs.
/// Animate your joint anchors, update your motor torque, etc. /// Animate your joint anchors, update your motor torque, etc.
cpConstraintPreSolveFunc preSolve; cpConstraintPreSolveFunc preSolve;
/// Function called after the solver runs. /// Function called after the solver runs.
/// Use the applied impulse to perform effects like breakable joints. /// Use the applied impulse to perform effects like breakable joints.
cpConstraintPostSolveFunc postSolve; cpConstraintPostSolveFunc postSolve;
/// User definable data pointer. /// User definable data pointer.
/// Generally this points to your the game object class so you can access it /// Generally this points to your the game object class so you can access it
/// when given a cpConstraint reference in a callback. /// when given a cpConstraint reference in a callback.
cpDataPointer data; cpDataPointer data;
}; };
/// Destroy a constraint. /// Destroy a constraint.
@ -90,8 +90,8 @@ void cpConstraintFree(cpConstraint *constraint);
/// @private /// @private
static inline void cpConstraintActivateBodies(cpConstraint *constraint) static inline void cpConstraintActivateBodies(cpConstraint *constraint)
{ {
cpBody *a = constraint->a; if(a) cpBodyActivate(a); cpBody *a = constraint->a; if(a) cpBodyActivate(a);
cpBody *b = constraint->b; if(b) cpBodyActivate(b); cpBody *b = constraint->b; if(b) cpBodyActivate(b);
} }
/// @private /// @private
@ -101,8 +101,8 @@ static inline type cpConstraint##Get##name(const cpConstraint *constraint){retur
/// @private /// @private
#define CP_DefineConstraintStructSetter(type, member, name) \ #define CP_DefineConstraintStructSetter(type, member, name) \
static inline void cpConstraint##Set##name(cpConstraint *constraint, type value){ \ static inline void cpConstraint##Set##name(cpConstraint *constraint, type value){ \
cpConstraintActivateBodies(constraint); \ cpConstraintActivateBodies(constraint); \
constraint->member = value; \ constraint->member = value; \
} }
/// @private /// @private
@ -110,6 +110,8 @@ static inline void cpConstraint##Set##name(cpConstraint *constraint, type value)
CP_DefineConstraintStructGetter(type, member, name) \ CP_DefineConstraintStructGetter(type, member, name) \
CP_DefineConstraintStructSetter(type, member, name) CP_DefineConstraintStructSetter(type, member, name)
CP_DefineConstraintStructGetter(cpSpace*, CP_PRIVATE(space), Space);
CP_DefineConstraintStructGetter(cpBody*, a, A); CP_DefineConstraintStructGetter(cpBody*, a, A);
CP_DefineConstraintStructGetter(cpBody*, b, B); CP_DefineConstraintStructGetter(cpBody*, b, B);
CP_DefineConstraintStructProperty(cpFloat, maxForce, MaxForce); CP_DefineConstraintStructProperty(cpFloat, maxForce, MaxForce);
@ -122,25 +124,25 @@ CP_DefineConstraintStructProperty(cpDataPointer, data, UserData);
// Get the last impulse applied by this constraint. // Get the last impulse applied by this constraint.
static inline cpFloat cpConstraintGetImpulse(cpConstraint *constraint) static inline cpFloat cpConstraintGetImpulse(cpConstraint *constraint)
{ {
return constraint->CP_PRIVATE(klass)->getImpulse(constraint); return constraint->CP_PRIVATE(klass)->getImpulse(constraint);
} }
/// @} /// @}
#define cpConstraintCheckCast(constraint, struct) \ #define cpConstraintCheckCast(constraint, struct) \
cpAssertHard(constraint->CP_PRIVATE(klass) == struct##GetClass(), "Constraint is not a "#struct) cpAssertHard(constraint->CP_PRIVATE(klass) == struct##GetClass(), "Constraint is not a "#struct)
#define CP_DefineConstraintGetter(struct, type, member, name) \ #define CP_DefineConstraintGetter(struct, type, member, name) \
static inline type struct##Get##name(const cpConstraint *constraint){ \ static inline type struct##Get##name(const cpConstraint *constraint){ \
cpConstraintCheckCast(constraint, struct); \ cpConstraintCheckCast(constraint, struct); \
return ((struct *)constraint)->member; \ return ((struct *)constraint)->member; \
} }
#define CP_DefineConstraintSetter(struct, type, member, name) \ #define CP_DefineConstraintSetter(struct, type, member, name) \
static inline void struct##Set##name(cpConstraint *constraint, type value){ \ static inline void struct##Set##name(cpConstraint *constraint, type value){ \
cpConstraintCheckCast(constraint, struct); \ cpConstraintCheckCast(constraint, struct); \
cpConstraintActivateBodies(constraint); \ cpConstraintActivateBodies(constraint); \
((struct *)constraint)->member = value; \ ((struct *)constraint)->member = value; \
} }
#define CP_DefineConstraintProperty(struct, type, member, name) \ #define CP_DefineConstraintProperty(struct, type, member, name) \

View File

@ -28,16 +28,16 @@ const cpConstraintClass *cpDampedRotarySpringGetClass(void);
/// @private /// @private
typedef struct cpDampedRotarySpring { typedef struct cpDampedRotarySpring {
cpConstraint constraint; cpConstraint constraint;
cpFloat restAngle; cpFloat restAngle;
cpFloat stiffness; cpFloat stiffness;
cpFloat damping; cpFloat damping;
cpDampedRotarySpringTorqueFunc springTorqueFunc; cpDampedRotarySpringTorqueFunc springTorqueFunc;
cpFloat target_wrn; cpFloat target_wrn;
cpFloat w_coef; cpFloat w_coef;
cpFloat iSum; cpFloat iSum;
} cpDampedRotarySpring; } cpDampedRotarySpring;
/// Allocate a damped rotary spring. /// Allocate a damped rotary spring.

View File

@ -30,19 +30,19 @@ const cpConstraintClass *cpDampedSpringGetClass(void);
/// @private /// @private
struct cpDampedSpring { struct cpDampedSpring {
cpConstraint constraint; cpConstraint constraint;
cpVect anchr1, anchr2; cpVect anchr1, anchr2;
cpFloat restLength; cpFloat restLength;
cpFloat stiffness; cpFloat stiffness;
cpFloat damping; cpFloat damping;
cpDampedSpringForceFunc springForceFunc; cpDampedSpringForceFunc springForceFunc;
cpFloat target_vrn; cpFloat target_vrn;
cpFloat v_coef; cpFloat v_coef;
cpVect r1, r2; cpVect r1, r2;
cpFloat nMass; cpFloat nMass;
cpVect n; cpVect n;
}; };
/// Allocate a damped spring. /// Allocate a damped spring.

View File

@ -26,14 +26,14 @@ const cpConstraintClass *cpGearJointGetClass(void);
/// @private /// @private
typedef struct cpGearJoint { typedef struct cpGearJoint {
cpConstraint constraint; cpConstraint constraint;
cpFloat phase, ratio; cpFloat phase, ratio;
cpFloat ratio_inv; cpFloat ratio_inv;
cpFloat iSum; cpFloat iSum;
cpFloat bias; cpFloat bias;
cpFloat jAcc, jMax; cpFloat jAcc, jMax;
} cpGearJoint; } cpGearJoint;
/// Allocate a gear joint. /// Allocate a gear joint.

View File

@ -26,18 +26,18 @@ const cpConstraintClass *cpGrooveJointGetClass(void);
/// @private /// @private
typedef struct cpGrooveJoint { typedef struct cpGrooveJoint {
cpConstraint constraint; cpConstraint constraint;
cpVect grv_n, grv_a, grv_b; cpVect grv_n, grv_a, grv_b;
cpVect anchr2; cpVect anchr2;
cpVect grv_tn; cpVect grv_tn;
cpFloat clamp; cpFloat clamp;
cpVect r1, r2; cpVect r1, r2;
cpVect k1, k2; cpVect k1, k2;
cpVect jAcc; cpVect jAcc;
cpFloat jMaxLen; cpFloat jMaxLen;
cpVect bias; cpVect bias;
} cpGrooveJoint; } cpGrooveJoint;
/// Allocate a groove joint. /// Allocate a groove joint.

View File

@ -26,16 +26,16 @@ const cpConstraintClass *cpPinJointGetClass(void);
/// @private /// @private
typedef struct cpPinJoint { typedef struct cpPinJoint {
cpConstraint constraint; cpConstraint constraint;
cpVect anchr1, anchr2; cpVect anchr1, anchr2;
cpFloat dist; cpFloat dist;
cpVect r1, r2; cpVect r1, r2;
cpVect n; cpVect n;
cpFloat nMass; cpFloat nMass;
cpFloat jnAcc, jnMax; cpFloat jnAcc, jnMax;
cpFloat bias; cpFloat bias;
} cpPinJoint; } cpPinJoint;
/// Allocate a pin joint. /// Allocate a pin joint.

View File

@ -26,15 +26,15 @@ const cpConstraintClass *cpPivotJointGetClass(void);
/// @private /// @private
typedef struct cpPivotJoint { typedef struct cpPivotJoint {
cpConstraint constraint; cpConstraint constraint;
cpVect anchr1, anchr2; cpVect anchr1, anchr2;
cpVect r1, r2; cpVect r1, r2;
cpVect k1, k2; cpVect k1, k2;
cpVect jAcc; cpVect jAcc;
cpFloat jMaxLen; cpFloat jMaxLen;
cpVect bias; cpVect bias;
} cpPivotJoint; } cpPivotJoint;
/// Allocate a pivot joint /// Allocate a pivot joint

View File

@ -26,13 +26,13 @@ const cpConstraintClass *cpRatchetJointGetClass(void);
/// @private /// @private
typedef struct cpRatchetJoint { typedef struct cpRatchetJoint {
cpConstraint constraint; cpConstraint constraint;
cpFloat angle, phase, ratchet; cpFloat angle, phase, ratchet;
cpFloat iSum; cpFloat iSum;
cpFloat bias; cpFloat bias;
cpFloat jAcc, jMax; cpFloat jAcc, jMax;
} cpRatchetJoint; } cpRatchetJoint;
/// Allocate a ratchet joint. /// Allocate a ratchet joint.

View File

@ -26,13 +26,13 @@ const cpConstraintClass *cpRotaryLimitJointGetClass(void);
/// @private /// @private
typedef struct cpRotaryLimitJoint { typedef struct cpRotaryLimitJoint {
cpConstraint constraint; cpConstraint constraint;
cpFloat min, max; cpFloat min, max;
cpFloat iSum; cpFloat iSum;
cpFloat bias; cpFloat bias;
cpFloat jAcc, jMax; cpFloat jAcc, jMax;
} cpRotaryLimitJoint; } cpRotaryLimitJoint;
/// Allocate a damped rotary limit joint. /// Allocate a damped rotary limit joint.

View File

@ -26,12 +26,12 @@ const cpConstraintClass *cpSimpleMotorGetClass(void);
/// @private /// @private
typedef struct cpSimpleMotor { typedef struct cpSimpleMotor {
cpConstraint constraint; cpConstraint constraint;
cpFloat rate; cpFloat rate;
cpFloat iSum; cpFloat iSum;
cpFloat jAcc, jMax; cpFloat jAcc, jMax;
} cpSimpleMotor; } cpSimpleMotor;
/// Allocate a simple motor. /// Allocate a simple motor.

View File

@ -26,16 +26,16 @@ const cpConstraintClass *cpSlideJointGetClass(void);
/// @private /// @private
typedef struct cpSlideJoint { typedef struct cpSlideJoint {
cpConstraint constraint; cpConstraint constraint;
cpVect anchr1, anchr2; cpVect anchr1, anchr2;
cpFloat min, max; cpFloat min, max;
cpVect r1, r2; cpVect r1, r2;
cpVect n; cpVect n;
cpFloat nMass; cpFloat nMass;
cpFloat jnAcc, jnMax; cpFloat jnAcc, jnMax;
cpFloat bias; cpFloat bias;
} cpSlideJoint; } cpSlideJoint;
/// Allocate a slide joint. /// Allocate a slide joint.

View File

@ -31,105 +31,105 @@ void cpConstraintInit(cpConstraint *constraint, const cpConstraintClass *klass,
static inline cpVect static inline cpVect
relative_velocity(cpBody *a, cpBody *b, cpVect r1, cpVect r2){ relative_velocity(cpBody *a, cpBody *b, cpVect r1, cpVect r2){
cpVect v1_sum = cpvadd(a->v, cpvmult(cpvperp(r1), a->w)); cpVect v1_sum = cpvadd(a->v, cpvmult(cpvperp(r1), a->w));
cpVect v2_sum = cpvadd(b->v, cpvmult(cpvperp(r2), b->w)); cpVect v2_sum = cpvadd(b->v, cpvmult(cpvperp(r2), b->w));
return cpvsub(v2_sum, v1_sum); return cpvsub(v2_sum, v1_sum);
} }
static inline cpFloat static inline cpFloat
normal_relative_velocity(cpBody *a, cpBody *b, cpVect r1, cpVect r2, cpVect n){ normal_relative_velocity(cpBody *a, cpBody *b, cpVect r1, cpVect r2, cpVect n){
return cpvdot(relative_velocity(a, b, r1, r2), n); return cpvdot(relative_velocity(a, b, r1, r2), n);
} }
static inline void static inline void
apply_impulse(cpBody *body, cpVect j, cpVect r){ apply_impulse(cpBody *body, cpVect j, cpVect r){
body->v = cpvadd(body->v, cpvmult(j, body->m_inv)); body->v = cpvadd(body->v, cpvmult(j, body->m_inv));
body->w += body->i_inv*cpvcross(r, j); body->w += body->i_inv*cpvcross(r, j);
} }
static inline void static inline void
apply_impulses(cpBody *a , cpBody *b, cpVect r1, cpVect r2, cpVect j) apply_impulses(cpBody *a , cpBody *b, cpVect r1, cpVect r2, cpVect j)
{ {
apply_impulse(a, cpvneg(j), r1); apply_impulse(a, cpvneg(j), r1);
apply_impulse(b, j, r2); apply_impulse(b, j, r2);
} }
static inline void static inline void
apply_bias_impulse(cpBody *body, cpVect j, cpVect r) apply_bias_impulse(cpBody *body, cpVect j, cpVect r)
{ {
body->CP_PRIVATE(v_bias) = cpvadd(body->CP_PRIVATE(v_bias), cpvmult(j, body->m_inv)); body->CP_PRIVATE(v_bias) = cpvadd(body->CP_PRIVATE(v_bias), cpvmult(j, body->m_inv));
body->CP_PRIVATE(w_bias) += body->i_inv*cpvcross(r, j); body->CP_PRIVATE(w_bias) += body->i_inv*cpvcross(r, j);
} }
static inline void static inline void
apply_bias_impulses(cpBody *a , cpBody *b, cpVect r1, cpVect r2, cpVect j) apply_bias_impulses(cpBody *a , cpBody *b, cpVect r1, cpVect r2, cpVect j)
{ {
apply_bias_impulse(a, cpvneg(j), r1); apply_bias_impulse(a, cpvneg(j), r1);
apply_bias_impulse(b, j, r2); apply_bias_impulse(b, j, r2);
} }
static inline cpFloat static inline cpFloat
k_scalar_body(cpBody *body, cpVect r, cpVect n) k_scalar_body(cpBody *body, cpVect r, cpVect n)
{ {
cpFloat rcn = cpvcross(r, n); cpFloat rcn = cpvcross(r, n);
return body->m_inv + body->i_inv*rcn*rcn; return body->m_inv + body->i_inv*rcn*rcn;
} }
static inline cpFloat static inline cpFloat
k_scalar(cpBody *a, cpBody *b, cpVect r1, cpVect r2, cpVect n) k_scalar(cpBody *a, cpBody *b, cpVect r1, cpVect r2, cpVect n)
{ {
cpFloat value = k_scalar_body(a, r1, n) + k_scalar_body(b, r2, n); cpFloat value = k_scalar_body(a, r1, n) + k_scalar_body(b, r2, n);
cpAssertSoft(value != 0.0, "Unsolvable collision or constraint."); cpAssertSoft(value != 0.0, "Unsolvable collision or constraint.");
return value; return value;
} }
static inline void static inline void
k_tensor(cpBody *a, cpBody *b, cpVect r1, cpVect r2, cpVect *k1, cpVect *k2) k_tensor(cpBody *a, cpBody *b, cpVect r1, cpVect r2, cpVect *k1, cpVect *k2)
{ {
// calculate mass matrix // calculate mass matrix
// If I wasn't lazy and wrote a proper matrix class, this wouldn't be so gross... // If I wasn't lazy and wrote a proper matrix class, this wouldn't be so gross...
cpFloat k11, k12, k21, k22; cpFloat k11, k12, k21, k22;
cpFloat m_sum = a->m_inv + b->m_inv; cpFloat m_sum = a->m_inv + b->m_inv;
// start with I*m_sum // start with I*m_sum
k11 = m_sum; k12 = 0.0f; k11 = m_sum; k12 = 0.0f;
k21 = 0.0f; k22 = m_sum; k21 = 0.0f; k22 = m_sum;
// add the influence from r1 // add the influence from r1
cpFloat a_i_inv = a->i_inv; cpFloat a_i_inv = a->i_inv;
cpFloat r1xsq = r1.x * r1.x * a_i_inv; cpFloat r1xsq = r1.x * r1.x * a_i_inv;
cpFloat r1ysq = r1.y * r1.y * a_i_inv; cpFloat r1ysq = r1.y * r1.y * a_i_inv;
cpFloat r1nxy = -r1.x * r1.y * a_i_inv; cpFloat r1nxy = -r1.x * r1.y * a_i_inv;
k11 += r1ysq; k12 += r1nxy; k11 += r1ysq; k12 += r1nxy;
k21 += r1nxy; k22 += r1xsq; k21 += r1nxy; k22 += r1xsq;
// add the influnce from r2 // add the influnce from r2
cpFloat b_i_inv = b->i_inv; cpFloat b_i_inv = b->i_inv;
cpFloat r2xsq = r2.x * r2.x * b_i_inv; cpFloat r2xsq = r2.x * r2.x * b_i_inv;
cpFloat r2ysq = r2.y * r2.y * b_i_inv; cpFloat r2ysq = r2.y * r2.y * b_i_inv;
cpFloat r2nxy = -r2.x * r2.y * b_i_inv; cpFloat r2nxy = -r2.x * r2.y * b_i_inv;
k11 += r2ysq; k12 += r2nxy; k11 += r2ysq; k12 += r2nxy;
k21 += r2nxy; k22 += r2xsq; k21 += r2nxy; k22 += r2xsq;
// invert // invert
cpFloat determinant = k11*k22 - k12*k21; cpFloat determinant = k11*k22 - k12*k21;
cpAssertSoft(determinant != 0.0, "Unsolvable constraint."); cpAssertSoft(determinant != 0.0, "Unsolvable constraint.");
cpFloat det_inv = 1.0f/determinant; cpFloat det_inv = 1.0f/determinant;
*k1 = cpv( k22*det_inv, -k12*det_inv); *k1 = cpv( k22*det_inv, -k12*det_inv);
*k2 = cpv(-k21*det_inv, k11*det_inv); *k2 = cpv(-k21*det_inv, k11*det_inv);
} }
static inline cpVect static inline cpVect
mult_k(cpVect vr, cpVect k1, cpVect k2) mult_k(cpVect vr, cpVect k1, cpVect k2)
{ {
return cpv(cpvdot(vr, k1), cpvdot(vr, k2)); return cpv(cpvdot(vr, k1), cpvdot(vr, k2));
} }
static inline cpFloat static inline cpFloat
bias_coef(cpFloat errorBias, cpFloat dt) bias_coef(cpFloat errorBias, cpFloat dt)
{ {
return 1.0f - cpfpow(errorBias, dt); return 1.0f - cpfpow(errorBias, dt);
} }

View File

@ -39,13 +39,13 @@ typedef void (*cpCollisionSeparateFunc)(cpArbiter *arb, cpSpace *space, void *da
/// @private /// @private
struct cpCollisionHandler { struct cpCollisionHandler {
cpCollisionType a; cpCollisionType a;
cpCollisionType b; cpCollisionType b;
cpCollisionBeginFunc begin; cpCollisionBeginFunc begin;
cpCollisionPreSolveFunc preSolve; cpCollisionPreSolveFunc preSolve;
cpCollisionPostSolveFunc postSolve; cpCollisionPostSolveFunc postSolve;
cpCollisionSeparateFunc separate; cpCollisionSeparateFunc separate;
void *data; void *data;
}; };
typedef struct cpContact cpContact; typedef struct cpContact cpContact;
@ -54,50 +54,50 @@ typedef struct cpContact cpContact;
/// @private /// @private
typedef enum cpArbiterState { typedef enum cpArbiterState {
// Arbiter is active and its the first collision. // Arbiter is active and its the first collision.
cpArbiterStateFirstColl, cpArbiterStateFirstColl,
// Arbiter is active and its not the first collision. // Arbiter is active and its not the first collision.
cpArbiterStateNormal, cpArbiterStateNormal,
// Collision has been explicitly ignored. // Collision has been explicitly ignored.
// Either by returning false from a begin collision handler or calling cpArbiterIgnore(). // Either by returning false from a begin collision handler or calling cpArbiterIgnore().
cpArbiterStateIgnore, cpArbiterStateIgnore,
// Collison is no longer active. A space will cache an arbiter for up to cpSpace.collisionPersistence more steps. // Collison is no longer active. A space will cache an arbiter for up to cpSpace.collisionPersistence more steps.
cpArbiterStateCached, cpArbiterStateCached,
} cpArbiterState; } cpArbiterState;
/// @private /// @private
struct cpArbiterThread { struct cpArbiterThread {
// Links to next and previous arbiters in the contact graph. // Links to next and previous arbiters in the contact graph.
struct cpArbiter *next, *prev; struct cpArbiter *next, *prev;
}; };
/// A colliding pair of shapes. /// A colliding pair of shapes.
struct cpArbiter { struct cpArbiter {
/// Calculated value to use for the elasticity coefficient. /// Calculated value to use for the elasticity coefficient.
/// Override in a pre-solve collision handler for custom behavior. /// Override in a pre-solve collision handler for custom behavior.
cpFloat e; cpFloat e;
/// Calculated value to use for the friction coefficient. /// Calculated value to use for the friction coefficient.
/// Override in a pre-solve collision handler for custom behavior. /// Override in a pre-solve collision handler for custom behavior.
cpFloat u; cpFloat u;
/// Calculated value to use for applying surface velocities. /// Calculated value to use for applying surface velocities.
/// Override in a pre-solve collision handler for custom behavior. /// Override in a pre-solve collision handler for custom behavior.
cpVect surface_vr; cpVect surface_vr;
CP_PRIVATE(cpShape *a); CP_PRIVATE(cpShape *a);
CP_PRIVATE(cpShape *b); CP_PRIVATE(cpShape *b);
CP_PRIVATE(cpBody *body_a); CP_PRIVATE(cpBody *body_a);
CP_PRIVATE(cpBody *body_b); CP_PRIVATE(cpBody *body_b);
CP_PRIVATE(struct cpArbiterThread thread_a); CP_PRIVATE(struct cpArbiterThread thread_a);
CP_PRIVATE(struct cpArbiterThread thread_b); CP_PRIVATE(struct cpArbiterThread thread_b);
CP_PRIVATE(int numContacts); CP_PRIVATE(int numContacts);
CP_PRIVATE(cpContact *contacts); CP_PRIVATE(cpContact *contacts);
CP_PRIVATE(cpTimestamp stamp); CP_PRIVATE(cpTimestamp stamp);
CP_PRIVATE(cpCollisionHandler *handler); CP_PRIVATE(cpCollisionHandler *handler);
CP_PRIVATE(cpBool swappedColl); CP_PRIVATE(cpBool swappedColl);
CP_PRIVATE(cpArbiterState state); CP_PRIVATE(cpArbiterState state);
}; };
#define CP_DefineArbiterStructGetter(type, member, name) \ #define CP_DefineArbiterStructGetter(type, member, name) \
@ -135,11 +135,11 @@ void cpArbiterIgnore(cpArbiter *arb);
/// the order set when the collision handler was registered. /// the order set when the collision handler was registered.
static inline void cpArbiterGetShapes(const cpArbiter *arb, cpShape **a, cpShape **b) static inline void cpArbiterGetShapes(const cpArbiter *arb, cpShape **a, cpShape **b)
{ {
if(arb->CP_PRIVATE(swappedColl)){ if(arb->CP_PRIVATE(swappedColl)){
(*a) = arb->CP_PRIVATE(b), (*b) = arb->CP_PRIVATE(a); (*a) = arb->CP_PRIVATE(b), (*b) = arb->CP_PRIVATE(a);
} else { } else {
(*a) = arb->CP_PRIVATE(a), (*b) = arb->CP_PRIVATE(b); (*a) = arb->CP_PRIVATE(a), (*b) = arb->CP_PRIVATE(b);
} }
} }
/// A macro shortcut for defining and retrieving the shapes from an arbiter. /// A macro shortcut for defining and retrieving the shapes from an arbiter.
#define CP_ARBITER_GET_SHAPES(arb, a, b) cpShape *a, *b; cpArbiterGetShapes(arb, &a, &b); #define CP_ARBITER_GET_SHAPES(arb, a, b) cpShape *a, *b; cpArbiterGetShapes(arb, &a, &b);
@ -149,43 +149,35 @@ static inline void cpArbiterGetShapes(const cpArbiter *arb, cpShape **a, cpShape
/// the order set when the collision handler was registered. /// the order set when the collision handler was registered.
static inline void cpArbiterGetBodies(const cpArbiter *arb, cpBody **a, cpBody **b) static inline void cpArbiterGetBodies(const cpArbiter *arb, cpBody **a, cpBody **b)
{ {
CP_ARBITER_GET_SHAPES(arb, shape_a, shape_b); CP_ARBITER_GET_SHAPES(arb, shape_a, shape_b);
(*a) = shape_a->body; (*a) = shape_a->body;
(*b) = shape_b->body; (*b) = shape_b->body;
} }
/// A macro shortcut for defining and retrieving the bodies from an arbiter. /// A macro shortcut for defining and retrieving the bodies from an arbiter.
#define CP_ARBITER_GET_BODIES(arb, a, b) cpBody *a, *b; cpArbiterGetBodies(arb, &a, &b); #define CP_ARBITER_GET_BODIES(arb, a, b) cpBody *a, *b; cpArbiterGetBodies(arb, &a, &b);
/// Returns true if this is the first step a pair of objects started colliding.
static inline cpBool cpArbiterIsFirstContact(const cpArbiter *arb)
{
return arb->CP_PRIVATE(state) == cpArbiterStateFirstColl;
}
/// Get the number of contact points for this arbiter.
static inline int cpArbiterGetCount(const cpArbiter *arb)
{
return arb->CP_PRIVATE(numContacts);
}
/// A struct that wraps up the important collision data for an arbiter. /// A struct that wraps up the important collision data for an arbiter.
typedef struct cpContactPointSet { typedef struct cpContactPointSet {
/// The number of contact points in the set. /// The number of contact points in the set.
int count; int count;
/// The array of contact points. /// The array of contact points.
struct { struct {
/// The position of the contact point. /// The position of the contact point.
cpVect point; cpVect point;
/// The normal of the contact point. /// The normal of the contact point.
cpVect normal; cpVect normal;
/// The depth of the contact point. /// The depth of the contact point.
cpFloat dist; cpFloat dist;
} points[CP_MAX_CONTACTS_PER_ARBITER]; } points[CP_MAX_CONTACTS_PER_ARBITER];
} cpContactPointSet; } cpContactPointSet;
/// Return a contact set from an arbiter. /// Return a contact set from an arbiter.
cpContactPointSet cpArbiterGetContactPointSet(const cpArbiter *arb); cpContactPointSet cpArbiterGetContactPointSet(const cpArbiter *arb);
/// Returns true if this is the first step a pair of objects started colliding.
cpBool cpArbiterIsFirstContact(const cpArbiter *arb);
/// Get the number of contact points for this arbiter.
int cpArbiterGetCount(const cpArbiter *arb);
/// Get the normal of the @c ith contact point. /// Get the normal of the @c ith contact point.
cpVect cpArbiterGetNormal(const cpArbiter *arb, int i); cpVect cpArbiterGetNormal(const cpArbiter *arb, int i);
/// Get the position of the @c ith contact point. /// Get the position of the @c ith contact point.

View File

@ -25,101 +25,101 @@
/// Chipmunk's axis-aligned 2D bounding box type. (left, bottom, right, top) /// Chipmunk's axis-aligned 2D bounding box type. (left, bottom, right, top)
typedef struct cpBB{ typedef struct cpBB{
cpFloat l, b, r ,t; cpFloat l, b, r ,t;
} cpBB; } cpBB;
/// Convenience constructor for cpBB structs. /// Convenience constructor for cpBB structs.
static inline cpBB cpBBNew(const cpFloat l, const cpFloat b, const cpFloat r, const cpFloat t) static inline cpBB cpBBNew(const cpFloat l, const cpFloat b, const cpFloat r, const cpFloat t)
{ {
cpBB bb = {l, b, r, t}; cpBB bb = {l, b, r, t};
return bb; return bb;
} }
/// Constructs a cpBB for a circle with the given position and radius. /// Constructs a cpBB for a circle with the given position and radius.
static inline cpBB cpBBNewForCircle(const cpVect p, const cpFloat r) static inline cpBB cpBBNewForCircle(const cpVect p, const cpFloat r)
{ {
return cpBBNew(p.x - r, p.y - r, p.x + r, p.y + r); return cpBBNew(p.x - r, p.y - r, p.x + r, p.y + r);
} }
/// Returns true if @c a and @c b intersect. /// Returns true if @c a and @c b intersect.
static inline cpBool cpBBIntersects(const cpBB a, const cpBB b) static inline cpBool cpBBIntersects(const cpBB a, const cpBB b)
{ {
return (a.l <= b.r && b.l <= a.r && a.b <= b.t && b.b <= a.t); return (a.l <= b.r && b.l <= a.r && a.b <= b.t && b.b <= a.t);
} }
/// Returns true if @c other lies completely within @c bb. /// Returns true if @c other lies completely within @c bb.
static inline cpBool cpBBContainsBB(const cpBB bb, const cpBB other) static inline cpBool cpBBContainsBB(const cpBB bb, const cpBB other)
{ {
return (bb.l <= other.l && bb.r >= other.r && bb.b <= other.b && bb.t >= other.t); return (bb.l <= other.l && bb.r >= other.r && bb.b <= other.b && bb.t >= other.t);
} }
/// Returns true if @c bb contains @c v. /// Returns true if @c bb contains @c v.
static inline cpBool cpBBContainsVect(const cpBB bb, const cpVect v) static inline cpBool cpBBContainsVect(const cpBB bb, const cpVect v)
{ {
return (bb.l <= v.x && bb.r >= v.x && bb.b <= v.y && bb.t >= v.y); return (bb.l <= v.x && bb.r >= v.x && bb.b <= v.y && bb.t >= v.y);
} }
/// Returns a bounding box that holds both bounding boxes. /// Returns a bounding box that holds both bounding boxes.
static inline cpBB cpBBMerge(const cpBB a, const cpBB b){ static inline cpBB cpBBMerge(const cpBB a, const cpBB b){
return cpBBNew( return cpBBNew(
cpfmin(a.l, b.l), cpfmin(a.l, b.l),
cpfmin(a.b, b.b), cpfmin(a.b, b.b),
cpfmax(a.r, b.r), cpfmax(a.r, b.r),
cpfmax(a.t, b.t) cpfmax(a.t, b.t)
); );
} }
/// Returns a bounding box that holds both @c bb and @c v. /// Returns a bounding box that holds both @c bb and @c v.
static inline cpBB cpBBExpand(const cpBB bb, const cpVect v){ static inline cpBB cpBBExpand(const cpBB bb, const cpVect v){
return cpBBNew( return cpBBNew(
cpfmin(bb.l, v.x), cpfmin(bb.l, v.x),
cpfmin(bb.b, v.y), cpfmin(bb.b, v.y),
cpfmax(bb.r, v.x), cpfmax(bb.r, v.x),
cpfmax(bb.t, v.y) cpfmax(bb.t, v.y)
); );
} }
/// Returns the area of the bounding box. /// Returns the area of the bounding box.
static inline cpFloat cpBBArea(cpBB bb) static inline cpFloat cpBBArea(cpBB bb)
{ {
return (bb.r - bb.l)*(bb.t - bb.b); return (bb.r - bb.l)*(bb.t - bb.b);
} }
/// Merges @c a and @c b and returns the area of the merged bounding box. /// Merges @c a and @c b and returns the area of the merged bounding box.
static inline cpFloat cpBBMergedArea(cpBB a, cpBB b) static inline cpFloat cpBBMergedArea(cpBB a, cpBB b)
{ {
return (cpfmax(a.r, b.r) - cpfmin(a.l, b.l))*(cpfmax(a.t, b.t) - cpfmin(a.b, b.b)); return (cpfmax(a.r, b.r) - cpfmin(a.l, b.l))*(cpfmax(a.t, b.t) - cpfmin(a.b, b.b));
} }
/// Returns the fraction along the segment query the cpBB is hit. Returns INFINITY if it doesn't hit. /// Returns the fraction along the segment query the cpBB is hit. Returns INFINITY if it doesn't hit.
static inline cpFloat cpBBSegmentQuery(cpBB bb, cpVect a, cpVect b) static inline cpFloat cpBBSegmentQuery(cpBB bb, cpVect a, cpVect b)
{ {
cpFloat idx = 1.0f/(b.x - a.x); cpFloat idx = 1.0f/(b.x - a.x);
cpFloat tx1 = (bb.l == a.x ? -INFINITY : (bb.l - a.x)*idx); cpFloat tx1 = (bb.l == a.x ? -INFINITY : (bb.l - a.x)*idx);
cpFloat tx2 = (bb.r == a.x ? INFINITY : (bb.r - a.x)*idx); cpFloat tx2 = (bb.r == a.x ? INFINITY : (bb.r - a.x)*idx);
cpFloat txmin = cpfmin(tx1, tx2); cpFloat txmin = cpfmin(tx1, tx2);
cpFloat txmax = cpfmax(tx1, tx2); cpFloat txmax = cpfmax(tx1, tx2);
cpFloat idy = 1.0f/(b.y - a.y); cpFloat idy = 1.0f/(b.y - a.y);
cpFloat ty1 = (bb.b == a.y ? -INFINITY : (bb.b - a.y)*idy); cpFloat ty1 = (bb.b == a.y ? -INFINITY : (bb.b - a.y)*idy);
cpFloat ty2 = (bb.t == a.y ? INFINITY : (bb.t - a.y)*idy); cpFloat ty2 = (bb.t == a.y ? INFINITY : (bb.t - a.y)*idy);
cpFloat tymin = cpfmin(ty1, ty2); cpFloat tymin = cpfmin(ty1, ty2);
cpFloat tymax = cpfmax(ty1, ty2); cpFloat tymax = cpfmax(ty1, ty2);
if(tymin <= txmax && txmin <= tymax){ if(tymin <= txmax && txmin <= tymax){
cpFloat min = cpfmax(txmin, tymin); cpFloat min = cpfmax(txmin, tymin);
cpFloat max = cpfmin(txmax, tymax); cpFloat max = cpfmin(txmax, tymax);
if(0.0 <= max && min <= 1.0) return cpfmax(min, 0.0); if(0.0 <= max && min <= 1.0) return cpfmax(min, 0.0);
} }
return INFINITY; return INFINITY;
} }
/// Return true if the bounding box intersects the line segment with ends @c a and @c b. /// Return true if the bounding box intersects the line segment with ends @c a and @c b.
static inline cpBool cpBBIntersectsSegment(cpBB bb, cpVect a, cpVect b) static inline cpBool cpBBIntersectsSegment(cpBB bb, cpVect a, cpVect b)
{ {
return (cpBBSegmentQuery(bb, a, b) != INFINITY); return (cpBBSegmentQuery(bb, a, b) != INFINITY);
} }
/// Clamp a vector to a bounding box. /// Clamp a vector to a bounding box.

View File

@ -33,70 +33,70 @@ typedef void (*cpBodyPositionFunc)(cpBody *body, cpFloat dt);
/// Used internally to track information on the collision graph. /// Used internally to track information on the collision graph.
/// @private /// @private
typedef struct cpComponentNode { typedef struct cpComponentNode {
cpBody *root; cpBody *root;
cpBody *next; cpBody *next;
cpFloat idleTime; cpFloat idleTime;
} cpComponentNode; } cpComponentNode;
/// Chipmunk's rigid body struct. /// Chipmunk's rigid body struct.
struct cpBody { struct cpBody {
/// Function that is called to integrate the body's velocity. (Defaults to cpBodyUpdateVelocity) /// Function that is called to integrate the body's velocity. (Defaults to cpBodyUpdateVelocity)
cpBodyVelocityFunc velocity_func; cpBodyVelocityFunc velocity_func;
/// Function that is called to integrate the body's position. (Defaults to cpBodyUpdatePosition) /// Function that is called to integrate the body's position. (Defaults to cpBodyUpdatePosition)
cpBodyPositionFunc position_func; cpBodyPositionFunc position_func;
/// Mass of the body. /// Mass of the body.
/// Must agree with cpBody.m_inv! Use cpBodySetMass() when changing the mass for this reason. /// Must agree with cpBody.m_inv! Use cpBodySetMass() when changing the mass for this reason.
cpFloat m; cpFloat m;
/// Mass inverse. /// Mass inverse.
cpFloat m_inv; cpFloat m_inv;
/// Moment of inertia of the body. /// Moment of inertia of the body.
/// Must agree with cpBody.i_inv! Use cpBodySetMoment() when changing the moment for this reason. /// Must agree with cpBody.i_inv! Use cpBodySetMoment() when changing the moment for this reason.
cpFloat i; cpFloat i;
/// Moment of inertia inverse. /// Moment of inertia inverse.
cpFloat i_inv; cpFloat i_inv;
/// Position of the rigid body's center of gravity. /// Position of the rigid body's center of gravity.
cpVect p; cpVect p;
/// Velocity of the rigid body's center of gravity. /// Velocity of the rigid body's center of gravity.
cpVect v; cpVect v;
/// Force acting on the rigid body's center of gravity. /// Force acting on the rigid body's center of gravity.
cpVect f; cpVect f;
/// Rotation of the body around it's center of gravity in radians. /// Rotation of the body around it's center of gravity in radians.
/// Must agree with cpBody.rot! Use cpBodySetAngle() when changing the angle for this reason. /// Must agree with cpBody.rot! Use cpBodySetAngle() when changing the angle for this reason.
cpFloat a; cpFloat a;
/// Angular velocity of the body around it's center of gravity in radians/second. /// Angular velocity of the body around it's center of gravity in radians/second.
cpFloat w; cpFloat w;
/// Torque applied to the body around it's center of gravity. /// Torque applied to the body around it's center of gravity.
cpFloat t; cpFloat t;
/// Cached unit length vector representing the angle of the body. /// Cached unit length vector representing the angle of the body.
/// Used for fast rotations using cpvrotate(). /// Used for fast rotations using cpvrotate().
cpVect rot; cpVect rot;
/// User definable data pointer. /// User definable data pointer.
/// Generally this points to your the game object class so you can access it /// Generally this points to your the game object class so you can access it
/// when given a cpBody reference in a callback. /// when given a cpBody reference in a callback.
cpDataPointer data; cpDataPointer data;
/// Maximum velocity allowed when updating the velocity. /// Maximum velocity allowed when updating the velocity.
cpFloat v_limit; cpFloat v_limit;
/// Maximum rotational rate (in radians/second) allowed when updating the angular velocity. /// Maximum rotational rate (in radians/second) allowed when updating the angular velocity.
cpFloat w_limit; cpFloat w_limit;
CP_PRIVATE(cpVect v_bias); CP_PRIVATE(cpVect v_bias);
CP_PRIVATE(cpFloat w_bias); CP_PRIVATE(cpFloat w_bias);
CP_PRIVATE(cpSpace *space); CP_PRIVATE(cpSpace *space);
CP_PRIVATE(cpShape *shapeList); CP_PRIVATE(cpShape *shapeList);
CP_PRIVATE(cpArbiter *arbiterList); CP_PRIVATE(cpArbiter *arbiterList);
CP_PRIVATE(cpConstraint *constraintList); CP_PRIVATE(cpConstraint *constraintList);
CP_PRIVATE(cpComponentNode node); CP_PRIVATE(cpComponentNode node);
}; };
/// Allocate a cpBody. /// Allocate a cpBody.
@ -118,10 +118,10 @@ void cpBodyFree(cpBody *body);
/// Check that the properties of a body is sane. (Only in debug mode) /// Check that the properties of a body is sane. (Only in debug mode)
#ifdef NDEBUG #ifdef NDEBUG
#define cpBodyAssertSane(body) #define cpBodyAssertSane(body)
#else #else
void cpBodySanityCheck(cpBody *body); void cpBodySanityCheck(cpBody *body);
#define cpBodyAssertSane(body) cpBodySanityCheck(body) #define cpBodyAssertSane(body) cpBodySanityCheck(body)
#endif #endif
// Defined in cpSpace.c // Defined in cpSpace.c
@ -138,19 +138,19 @@ void cpBodySleepWithGroup(cpBody *body, cpBody *group);
/// Returns true if the body is sleeping. /// Returns true if the body is sleeping.
static inline cpBool cpBodyIsSleeping(const cpBody *body) static inline cpBool cpBodyIsSleeping(const cpBody *body)
{ {
return (CP_PRIVATE(body->node).root != ((cpBody*)0)); return (CP_PRIVATE(body->node).root != ((cpBody*)0));
} }
/// Returns true if the body is static. /// Returns true if the body is static.
static inline cpBool cpBodyIsStatic(const cpBody *body) static inline cpBool cpBodyIsStatic(const cpBody *body)
{ {
return CP_PRIVATE(body->node).idleTime == INFINITY; return CP_PRIVATE(body->node).idleTime == INFINITY;
} }
/// Returns true if the body has not been added to a space. /// Returns true if the body has not been added to a space.
static inline cpBool cpBodyIsRogue(const cpBody *body) static inline cpBool cpBodyIsRogue(const cpBody *body)
{ {
return (body->CP_PRIVATE(space) == ((cpSpace*)0)); return (body->CP_PRIVATE(space) == ((cpSpace*)0));
} }
@ -159,15 +159,18 @@ static inline type cpBodyGet##name(const cpBody *body){return body->member;}
#define CP_DefineBodyStructSetter(type, member, name) \ #define CP_DefineBodyStructSetter(type, member, name) \
static inline void cpBodySet##name(cpBody *body, const type value){ \ static inline void cpBodySet##name(cpBody *body, const type value){ \
cpBodyActivate(body); \ cpBodyActivate(body); \
cpBodyAssertSane(body); \ cpBodyAssertSane(body); \
body->member = value; \ body->member = value; \
} }
#define CP_DefineBodyStructProperty(type, member, name) \ #define CP_DefineBodyStructProperty(type, member, name) \
CP_DefineBodyStructGetter(type, member, name) \ CP_DefineBodyStructGetter(type, member, name) \
CP_DefineBodyStructSetter(type, member, name) CP_DefineBodyStructSetter(type, member, name)
// TODO add to docs
CP_DefineBodyStructGetter(cpSpace*, CP_PRIVATE(space), Space);
CP_DefineBodyStructGetter(cpFloat, m, Mass); CP_DefineBodyStructGetter(cpFloat, m, Mass);
/// Set the mass of a body. /// Set the mass of a body.
void cpBodySetMass(cpBody *body, cpFloat m); void cpBodySetMass(cpBody *body, cpFloat m);
@ -198,13 +201,13 @@ void cpBodyUpdatePosition(cpBody *body, cpFloat dt);
/// Convert body relative/local coordinates to absolute/world coordinates. /// Convert body relative/local coordinates to absolute/world coordinates.
static inline cpVect cpBodyLocal2World(const cpBody *body, const cpVect v) static inline cpVect cpBodyLocal2World(const cpBody *body, const cpVect v)
{ {
return cpvadd(body->p, cpvrotate(v, body->rot)); return cpvadd(body->p, cpvrotate(v, body->rot));
} }
/// Convert body absolute/world coordinates to relative/local coordinates. /// Convert body absolute/world coordinates to relative/local coordinates.
static inline cpVect cpBodyWorld2Local(const cpBody *body, const cpVect v) static inline cpVect cpBodyWorld2Local(const cpBody *body, const cpVect v)
{ {
return cpvunrotate(cpvsub(v, body->p), body->rot); return cpvunrotate(cpvsub(v, body->p), body->rot);
} }
/// Set the forces and torque or a body to zero. /// Set the forces and torque or a body to zero.
@ -223,10 +226,10 @@ cpVect cpBodyGetVelAtLocalPoint(cpBody *body, cpVect point);
/// Get the kinetic energy of a body. /// Get the kinetic energy of a body.
static inline cpFloat cpBodyKineticEnergy(const cpBody *body) static inline cpFloat cpBodyKineticEnergy(const cpBody *body)
{ {
// Need to do some fudging to avoid NaNs // Need to do some fudging to avoid NaNs
cpFloat vsq = cpvdot(body->v, body->v); cpFloat vsq = cpvdot(body->v, body->v);
cpFloat wsq = body->w*body->w; cpFloat wsq = body->w*body->w;
return (vsq ? vsq*body->m : 0.0f) + (wsq ? wsq*body->i : 0.0f); return (vsq ? vsq*body->m : 0.0f) + (wsq ? wsq*body->i : 0.0f);
} }
/// Body/shape iterator callback function type. /// Body/shape iterator callback function type.

View File

@ -23,27 +23,27 @@
/// @{ /// @{
/// @private /// @private
typedef struct cpPolyShapeAxis { typedef struct cpSplittingPlane {
cpVect n; cpVect n;
cpFloat d; cpFloat d;
} cpPolyShapeAxis; } cpSplittingPlane;
/// @private /// @private
typedef struct cpPolyShape { typedef struct cpPolyShape {
cpShape shape; cpShape shape;
int numVerts; int numVerts;
cpVect *verts, *tVerts; cpVect *verts, *tVerts;
cpPolyShapeAxis *axes, *tAxes; cpSplittingPlane *planes, *tPlanes;
} cpPolyShape; } cpPolyShape;
/// Allocate a polygon shape. /// Allocate a polygon shape.
cpPolyShape* cpPolyShapeAlloc(void); cpPolyShape* cpPolyShapeAlloc(void);
/// Initialize a polygon shape. /// Initialize a polygon shape.
/// The vertexes must be convex and have a clockwise winding. /// A convex hull will be created from the vertexes.
cpPolyShape* cpPolyShapeInit(cpPolyShape *poly, cpBody *body, int numVerts, cpVect *verts, cpVect offset); cpPolyShape* cpPolyShapeInit(cpPolyShape *poly, cpBody *body, int numVerts, cpVect *verts, cpVect offset);
/// Allocate and initialize a polygon shape. /// Allocate and initialize a polygon shape.
/// The vertexes must be convex and have a clockwise winding. /// A convex hull will be created from the vertexes.
cpShape* cpPolyShapeNew(cpBody *body, int numVerts, cpVect *verts, cpVect offset); cpShape* cpPolyShapeNew(cpBody *body, int numVerts, cpVect *verts, cpVect offset);
/// Initialize a box shaped polygon shape. /// Initialize a box shaped polygon shape.
@ -56,6 +56,7 @@ cpShape* cpBoxShapeNew(cpBody *body, cpFloat width, cpFloat height);
cpShape* cpBoxShapeNew2(cpBody *body, cpBB box); cpShape* cpBoxShapeNew2(cpBody *body, cpBB box);
/// Check that a set of vertexes is convex and has a clockwise winding. /// Check that a set of vertexes is convex and has a clockwise winding.
/// NOTE: Due to floating point precision issues, hulls created with cpQuickHull() are not guaranteed to validate!
cpBool cpPolyValidate(const cpVect *verts, const int numVerts); cpBool cpPolyValidate(const cpVect *verts, const int numVerts);
/// Get the number of verts in a polygon shape. /// Get the number of verts in a polygon shape.

View File

@ -25,78 +25,88 @@
typedef struct cpShapeClass cpShapeClass; typedef struct cpShapeClass cpShapeClass;
/// Nearest point query info struct.
typedef struct cpNearestPointQueryInfo {
/// The nearest shape, NULL if no shape was within range.
cpShape *shape;
/// The closest point on the shape's surface. (in world space coordinates)
cpVect p;
/// The distance to the point. The distance is negative if the point is inside the shape.
cpFloat d;
} cpNearestPointQueryInfo;
/// Segment query info struct. /// Segment query info struct.
typedef struct cpSegmentQueryInfo { typedef struct cpSegmentQueryInfo {
/// The shape that was hit, NULL if no collision occured. /// The shape that was hit, NULL if no collision occured.
cpShape *shape; cpShape *shape;
/// The normalized distance along the query segment in the range [0, 1]. /// The normalized distance along the query segment in the range [0, 1].
cpFloat t; cpFloat t;
/// The normal of the surface hit. /// The normal of the surface hit.
cpVect n; cpVect n;
} cpSegmentQueryInfo; } cpSegmentQueryInfo;
/// @private /// @private
typedef enum cpShapeType{ typedef enum cpShapeType{
CP_CIRCLE_SHAPE, CP_CIRCLE_SHAPE,
CP_SEGMENT_SHAPE, CP_SEGMENT_SHAPE,
CP_POLY_SHAPE, CP_POLY_SHAPE,
CP_NUM_SHAPES CP_NUM_SHAPES
} cpShapeType; } cpShapeType;
typedef cpBB (*cpShapeCacheDataImpl)(cpShape *shape, cpVect p, cpVect rot); typedef cpBB (*cpShapeCacheDataImpl)(cpShape *shape, cpVect p, cpVect rot);
typedef void (*cpShapeDestroyImpl)(cpShape *shape); typedef void (*cpShapeDestroyImpl)(cpShape *shape);
typedef cpBool (*cpShapePointQueryImpl)(cpShape *shape, cpVect p); typedef void (*cpShapeNearestPointQueryImpl)(cpShape *shape, cpVect p, cpNearestPointQueryInfo *info);
typedef void (*cpShapeSegmentQueryImpl)(cpShape *shape, cpVect a, cpVect b, cpSegmentQueryInfo *info); typedef void (*cpShapeSegmentQueryImpl)(cpShape *shape, cpVect a, cpVect b, cpSegmentQueryInfo *info);
/// @private /// @private
struct cpShapeClass { struct cpShapeClass {
cpShapeType type; cpShapeType type;
cpShapeCacheDataImpl cacheData; cpShapeCacheDataImpl cacheData;
cpShapeDestroyImpl destroy; cpShapeDestroyImpl destroy;
cpShapePointQueryImpl pointQuery; cpShapeNearestPointQueryImpl nearestPointQuery;
cpShapeSegmentQueryImpl segmentQuery; cpShapeSegmentQueryImpl segmentQuery;
}; };
/// Opaque collision shape struct. /// Opaque collision shape struct.
struct cpShape { struct cpShape {
CP_PRIVATE(const cpShapeClass *klass); CP_PRIVATE(const cpShapeClass *klass);
/// The rigid body this collision shape is attached to. /// The rigid body this collision shape is attached to.
cpBody *body; cpBody *body;
/// The current bounding box of the shape. /// The current bounding box of the shape.
cpBB bb; cpBB bb;
/// Sensor flag. /// Sensor flag.
/// Sensor shapes call collision callbacks but don't produce collisions. /// Sensor shapes call collision callbacks but don't produce collisions.
cpBool sensor; cpBool sensor;
/// Coefficient of restitution. (elasticity) /// Coefficient of restitution. (elasticity)
cpFloat e; cpFloat e;
/// Coefficient of friction. /// Coefficient of friction.
cpFloat u; cpFloat u;
/// Surface velocity used when solving for friction. /// Surface velocity used when solving for friction.
cpVect surface_v; cpVect surface_v;
/// User definable data pointer. /// User definable data pointer.
/// Generally this points to your the game object class so you can access it /// Generally this points to your the game object class so you can access it
/// when given a cpShape reference in a callback. /// when given a cpShape reference in a callback.
cpDataPointer data; cpDataPointer data;
/// Collision type of this shape used when picking collision handlers. /// Collision type of this shape used when picking collision handlers.
cpCollisionType collision_type; cpCollisionType collision_type;
/// Group of this shape. Shapes in the same group don't collide. /// Group of this shape. Shapes in the same group don't collide.
cpGroup group; cpGroup group;
// Layer bitmask for this shape. Shapes only collide if the bitwise and of their layers is non-zero. // Layer bitmask for this shape. Shapes only collide if the bitwise and of their layers is non-zero.
cpLayers layers; cpLayers layers;
CP_PRIVATE(cpSpace *space); CP_PRIVATE(cpSpace *space);
CP_PRIVATE(cpShape *next); CP_PRIVATE(cpShape *next);
CP_PRIVATE(cpShape *prev); CP_PRIVATE(cpShape *prev);
CP_PRIVATE(cpHashValue hashid); CP_PRIVATE(cpHashValue hashid);
}; };
/// Destroy a shape. /// Destroy a shape.
@ -112,19 +122,40 @@ cpBB cpShapeUpdate(cpShape *shape, cpVect pos, cpVect rot);
/// Test if a point lies within a shape. /// Test if a point lies within a shape.
cpBool cpShapePointQuery(cpShape *shape, cpVect p); cpBool cpShapePointQuery(cpShape *shape, cpVect p);
/// Perform a nearest point query. It finds the closest point on the surface of shape to a specific point.
/// The value returned is the distance between the points. A negative distance means the point is inside the shape.
cpFloat cpShapeNearestPointQuery(cpShape *shape, cpVect p, cpNearestPointQueryInfo *out);
/// Perform a segment query against a shape. @c info must be a pointer to a valid cpSegmentQueryInfo structure.
cpBool cpShapeSegmentQuery(cpShape *shape, cpVect a, cpVect b, cpSegmentQueryInfo *info);
/// Get the hit point for a segment query.
static inline cpVect cpSegmentQueryHitPoint(const cpVect start, const cpVect end, const cpSegmentQueryInfo info)
{
return cpvlerp(start, end, info.t);
}
/// Get the hit distance for a segment query.
static inline cpFloat cpSegmentQueryHitDist(const cpVect start, const cpVect end, const cpSegmentQueryInfo info)
{
return cpvdist(start, end)*info.t;
}
#define CP_DefineShapeStructGetter(type, member, name) \ #define CP_DefineShapeStructGetter(type, member, name) \
static inline type cpShapeGet##name(const cpShape *shape){return shape->member;} static inline type cpShapeGet##name(const cpShape *shape){return shape->member;}
#define CP_DefineShapeStructSetter(type, member, name, activates) \ #define CP_DefineShapeStructSetter(type, member, name, activates) \
static inline void cpShapeSet##name(cpShape *shape, type value){ \ static inline void cpShapeSet##name(cpShape *shape, type value){ \
if(activates && shape->body) cpBodyActivate(shape->body); \ if(activates && shape->body) cpBodyActivate(shape->body); \
shape->member = value; \ shape->member = value; \
} }
#define CP_DefineShapeStructProperty(type, member, name, activates) \ #define CP_DefineShapeStructProperty(type, member, name, activates) \
CP_DefineShapeStructGetter(type, member, name) \ CP_DefineShapeStructGetter(type, member, name) \
CP_DefineShapeStructSetter(type, member, name, activates) CP_DefineShapeStructSetter(type, member, name, activates)
CP_DefineShapeStructGetter(cpSpace*, CP_PRIVATE(space), Space);
CP_DefineShapeStructGetter(cpBody*, body, Body); CP_DefineShapeStructGetter(cpBody*, body, Body);
void cpShapeSetBody(cpShape *shape, cpBody *body); void cpShapeSetBody(cpShape *shape, cpBody *body);
@ -143,21 +174,6 @@ CP_DefineShapeStructProperty(cpLayers, layers, Layers, cpTrue);
/// when recreating a space. This will make the simulation be deterministic. /// when recreating a space. This will make the simulation be deterministic.
void cpResetShapeIdCounter(void); void cpResetShapeIdCounter(void);
/// Perform a segment query against a shape. @c info must be a pointer to a valid cpSegmentQueryInfo structure.
cpBool cpShapeSegmentQuery(cpShape *shape, cpVect a, cpVect b, cpSegmentQueryInfo *info);
/// Get the hit point for a segment query.
static inline cpVect cpSegmentQueryHitPoint(const cpVect start, const cpVect end, const cpSegmentQueryInfo info)
{
return cpvlerp(start, end, info.t);
}
/// Get the hit distance for a segment query.
static inline cpFloat cpSegmentQueryHitDist(const cpVect start, const cpVect end, const cpSegmentQueryInfo info)
{
return cpvdist(start, end)*info.t;
}
#define CP_DeclareShapeGetter(struct, type, name) type struct##Get##name(const cpShape *shape) #define CP_DeclareShapeGetter(struct, type, name) type struct##Get##name(const cpShape *shape)
/// @} /// @}
@ -165,10 +181,10 @@ static inline cpFloat cpSegmentQueryHitDist(const cpVect start, const cpVect end
/// @private /// @private
typedef struct cpCircleShape { typedef struct cpCircleShape {
cpShape shape; cpShape shape;
cpVect c, tc; cpVect c, tc;
cpFloat r; cpFloat r;
} cpCircleShape; } cpCircleShape;
/// Allocate a circle shape. /// Allocate a circle shape.
@ -186,13 +202,13 @@ CP_DeclareShapeGetter(cpCircleShape, cpFloat, Radius);
/// @private /// @private
typedef struct cpSegmentShape { typedef struct cpSegmentShape {
cpShape shape; cpShape shape;
cpVect a, b, n; cpVect a, b, n;
cpVect ta, tb, tn; cpVect ta, tb, tn;
cpFloat r; cpFloat r;
cpVect a_tangent, b_tangent; cpVect a_tangent, b_tangent;
} cpSegmentShape; } cpSegmentShape;
/// Allocate a segment shape. /// Allocate a segment shape.

View File

@ -27,82 +27,82 @@ typedef void (*cpSpaceArbiterApplyImpulseFunc)(cpArbiter *arb);
/// Basic Unit of Simulation in Chipmunk /// Basic Unit of Simulation in Chipmunk
struct cpSpace { struct cpSpace {
/// Number of iterations to use in the impulse solver to solve contacts. /// Number of iterations to use in the impulse solver to solve contacts.
int iterations; int iterations;
/// Gravity to pass to rigid bodies when integrating velocity. /// Gravity to pass to rigid bodies when integrating velocity.
cpVect gravity; cpVect gravity;
/// Damping rate expressed as the fraction of velocity bodies retain each second. /// Damping rate expressed as the fraction of velocity bodies retain each second.
/// A value of 0.9 would mean that each body's velocity will drop 10% per second. /// A value of 0.9 would mean that each body's velocity will drop 10% per second.
/// The default value is 1.0, meaning no damping is applied. /// The default value is 1.0, meaning no damping is applied.
/// @note This damping value is different than those of cpDampedSpring and cpDampedRotarySpring. /// @note This damping value is different than those of cpDampedSpring and cpDampedRotarySpring.
cpFloat damping; cpFloat damping;
/// Speed threshold for a body to be considered idle. /// Speed threshold for a body to be considered idle.
/// The default value of 0 means to let the space guess a good threshold based on gravity. /// The default value of 0 means to let the space guess a good threshold based on gravity.
cpFloat idleSpeedThreshold; cpFloat idleSpeedThreshold;
/// Time a group of bodies must remain idle in order to fall asleep. /// Time a group of bodies must remain idle in order to fall asleep.
/// Enabling sleeping also implicitly enables the the contact graph. /// Enabling sleeping also implicitly enables the the contact graph.
/// The default value of INFINITY disables the sleeping algorithm. /// The default value of INFINITY disables the sleeping algorithm.
cpFloat sleepTimeThreshold; cpFloat sleepTimeThreshold;
/// Amount of encouraged penetration between colliding shapes. /// Amount of encouraged penetration between colliding shapes.
/// Used to reduce oscillating contacts and keep the collision cache warm. /// Used to reduce oscillating contacts and keep the collision cache warm.
/// Defaults to 0.1. If you have poor simulation quality, /// Defaults to 0.1. If you have poor simulation quality,
/// increase this number as much as possible without allowing visible amounts of overlap. /// increase this number as much as possible without allowing visible amounts of overlap.
cpFloat collisionSlop; cpFloat collisionSlop;
/// Determines how fast overlapping shapes are pushed apart. /// Determines how fast overlapping shapes are pushed apart.
/// Expressed as a fraction of the error remaining after each second. /// Expressed as a fraction of the error remaining after each second.
/// Defaults to pow(1.0 - 0.1, 60.0) meaning that Chipmunk fixes 10% of overlap each frame at 60Hz. /// Defaults to pow(1.0 - 0.1, 60.0) meaning that Chipmunk fixes 10% of overlap each frame at 60Hz.
cpFloat collisionBias; cpFloat collisionBias;
/// Number of frames that contact information should persist. /// Number of frames that contact information should persist.
/// Defaults to 3. There is probably never a reason to change this value. /// Defaults to 3. There is probably never a reason to change this value.
cpTimestamp collisionPersistence; cpTimestamp collisionPersistence;
/// Rebuild the contact graph during each step. Must be enabled to use the cpBodyEachArbiter() function. /// Rebuild the contact graph during each step. Must be enabled to use the cpBodyEachArbiter() function.
/// Disabled by default for a small performance boost. Enabled implicitly when the sleeping feature is enabled. /// Disabled by default for a small performance boost. Enabled implicitly when the sleeping feature is enabled.
cpBool enableContactGraph; cpBool enableContactGraph;
/// User definable data pointer. /// User definable data pointer.
/// Generally this points to your game's controller or game state /// Generally this points to your game's controller or game state
/// class so you can access it when given a cpSpace reference in a callback. /// class so you can access it when given a cpSpace reference in a callback.
cpDataPointer data; cpDataPointer data;
/// The designated static body for this space. /// The designated static body for this space.
/// You can modify this body, or replace it with your own static body. /// You can modify this body, or replace it with your own static body.
/// By default it points to a statically allocated cpBody in the cpSpace struct. /// By default it points to a statically allocated cpBody in the cpSpace struct.
cpBody *staticBody; cpBody *staticBody;
CP_PRIVATE(cpTimestamp stamp); CP_PRIVATE(cpTimestamp stamp);
CP_PRIVATE(cpFloat curr_dt); CP_PRIVATE(cpFloat curr_dt);
CP_PRIVATE(cpArray *bodies); CP_PRIVATE(cpArray *bodies);
CP_PRIVATE(cpArray *rousedBodies); CP_PRIVATE(cpArray *rousedBodies);
CP_PRIVATE(cpArray *sleepingComponents); CP_PRIVATE(cpArray *sleepingComponents);
CP_PRIVATE(cpSpatialIndex *staticShapes); CP_PRIVATE(cpSpatialIndex *staticShapes);
CP_PRIVATE(cpSpatialIndex *activeShapes); CP_PRIVATE(cpSpatialIndex *activeShapes);
CP_PRIVATE(cpArray *arbiters); CP_PRIVATE(cpArray *arbiters);
CP_PRIVATE(cpContactBufferHeader *contactBuffersHead); CP_PRIVATE(cpContactBufferHeader *contactBuffersHead);
CP_PRIVATE(cpHashSet *cachedArbiters); CP_PRIVATE(cpHashSet *cachedArbiters);
CP_PRIVATE(cpArray *pooledArbiters); CP_PRIVATE(cpArray *pooledArbiters);
CP_PRIVATE(cpArray *constraints); CP_PRIVATE(cpArray *constraints);
CP_PRIVATE(cpArray *allocatedBuffers); CP_PRIVATE(cpArray *allocatedBuffers);
CP_PRIVATE(int locked); CP_PRIVATE(int locked);
CP_PRIVATE(cpHashSet *collisionHandlers); CP_PRIVATE(cpHashSet *collisionHandlers);
CP_PRIVATE(cpCollisionHandler defaultHandler); CP_PRIVATE(cpCollisionHandler defaultHandler);
CP_PRIVATE(cpHashSet *postStepCallbacks);
CP_PRIVATE(cpBool skipPostStep);
CP_PRIVATE(cpSpaceArbiterApplyImpulseFunc arbiterApplyImpulse); CP_PRIVATE(cpArray *postStepCallbacks);
CP_PRIVATE(cpBody _staticBody); CP_PRIVATE(cpBody _staticBody);
}; };
/// Allocate a cpSpace. /// Allocate a cpSpace.
@ -144,7 +144,7 @@ CP_DefineSpaceStructGetter(cpFloat, CP_PRIVATE(curr_dt), CurrentTimeStep);
static inline cpBool static inline cpBool
cpSpaceIsLocked(cpSpace *space) cpSpaceIsLocked(cpSpace *space)
{ {
return space->CP_PRIVATE(locked); return space->CP_PRIVATE(locked);
} }
/// Set a default collision handler for this space. /// Set a default collision handler for this space.
@ -152,24 +152,24 @@ cpSpaceIsLocked(cpSpace *space)
/// that isn't explicitly handled by a specific collision handler. /// that isn't explicitly handled by a specific collision handler.
/// You can pass NULL for any function you don't want to implement. /// You can pass NULL for any function you don't want to implement.
void cpSpaceSetDefaultCollisionHandler( void cpSpaceSetDefaultCollisionHandler(
cpSpace *space, cpSpace *space,
cpCollisionBeginFunc begin, cpCollisionBeginFunc begin,
cpCollisionPreSolveFunc preSolve, cpCollisionPreSolveFunc preSolve,
cpCollisionPostSolveFunc postSolve, cpCollisionPostSolveFunc postSolve,
cpCollisionSeparateFunc separate, cpCollisionSeparateFunc separate,
void *data void *data
); );
/// Set a collision handler to be used whenever the two shapes with the given collision types collide. /// Set a collision handler to be used whenever the two shapes with the given collision types collide.
/// You can pass NULL for any function you don't want to implement. /// You can pass NULL for any function you don't want to implement.
void cpSpaceAddCollisionHandler( void cpSpaceAddCollisionHandler(
cpSpace *space, cpSpace *space,
cpCollisionType a, cpCollisionType b, cpCollisionType a, cpCollisionType b,
cpCollisionBeginFunc begin, cpCollisionBeginFunc begin,
cpCollisionPreSolveFunc preSolve, cpCollisionPreSolveFunc preSolve,
cpCollisionPostSolveFunc postSolve, cpCollisionPostSolveFunc postSolve,
cpCollisionSeparateFunc separate, cpCollisionSeparateFunc separate,
void *data void *data
); );
/// Unset a collision handler. /// Unset a collision handler.
@ -204,8 +204,8 @@ cpBool cpSpaceContainsConstraint(cpSpace *space, cpConstraint *constraint);
/// Post Step callback function type. /// Post Step callback function type.
typedef void (*cpPostStepFunc)(cpSpace *space, void *obj, void *data); typedef void (*cpPostStepFunc)(cpSpace *space, void *obj, void *data);
/// Schedule a post-step callback to be called when cpSpaceStep() finishes. /// Schedule a post-step callback to be called when cpSpaceStep() finishes.
/// @c obj is used a key, you can only register one callback per unique value for @c obj /// You can only register one callback per unique value for @c key.
void cpSpaceAddPostStepCallback(cpSpace *space, cpPostStepFunc func, void *obj, void *data); void cpSpaceAddPostStepCallback(cpSpace *space, cpPostStepFunc func, void *key, void *data);
/// Point query callback function type. /// Point query callback function type.
typedef void (*cpSpacePointQueryFunc)(cpShape *shape, void *data); typedef void (*cpSpacePointQueryFunc)(cpShape *shape, void *data);
@ -214,6 +214,13 @@ void cpSpacePointQuery(cpSpace *space, cpVect point, cpLayers layers, cpGroup gr
/// Query the space at a point and return the first shape found. Returns NULL if no shapes were found. /// Query the space at a point and return the first shape found. Returns NULL if no shapes were found.
cpShape *cpSpacePointQueryFirst(cpSpace *space, cpVect point, cpLayers layers, cpGroup group); cpShape *cpSpacePointQueryFirst(cpSpace *space, cpVect point, cpLayers layers, cpGroup group);
/// Nearest point query callback function type.
typedef void (*cpSpaceNearestPointQueryFunc)(cpShape *shape, cpFloat distance, cpVect point, void *data);
/// Query the space at a point and call @c func for each shape found.
void cpSpaceNearestPointQuery(cpSpace *space, cpVect point, cpFloat maxDistance, cpLayers layers, cpGroup group, cpSpaceNearestPointQueryFunc func, void *data);
/// Query the space at a point and return the nearest shape found. Returns NULL if no shapes were found.
cpShape *cpSpaceNearestPointQueryNearest(cpSpace *space, cpVect point, cpFloat maxDistance, cpLayers layers, cpGroup group, cpNearestPointQueryInfo *out);
/// Segment query callback function type. /// Segment query callback function type.
typedef void (*cpSpaceSegmentQueryFunc)(cpShape *shape, cpFloat t, cpVect n, void *data); typedef void (*cpSpaceSegmentQueryFunc)(cpShape *shape, cpFloat t, cpVect n, void *data);
/// Perform a directed line segment query (like a raycast) against the space calling @c func for each shape intersected. /// Perform a directed line segment query (like a raycast) against the space calling @c func for each shape intersected.

View File

@ -20,21 +20,21 @@
*/ */
/** /**
@defgroup cpSpatialIndex cpSpatialIndex @defgroup cpSpatialIndex cpSpatialIndex
Spatial indexes are data structures that are used to accelerate collision detection Spatial indexes are data structures that are used to accelerate collision detection
and spatial queries. Chipmunk provides a number of spatial index algorithms to pick from and spatial queries. Chipmunk provides a number of spatial index algorithms to pick from
and they are programmed in a generic way so that you can use them for holding more than and they are programmed in a generic way so that you can use them for holding more than
just cpShape structs. just cpShape structs.
It works by using @c void pointers to the objects you add and using a callback to ask your code It works by using @c void pointers to the objects you add and using a callback to ask your code
for bounding boxes when it needs them. Several types of queries can be performed an index as well for bounding boxes when it needs them. Several types of queries can be performed an index as well
as reindexing and full collision information. All communication to the spatial indexes is performed as reindexing and full collision information. All communication to the spatial indexes is performed
through callback functions. through callback functions.
Spatial indexes should be treated as opaque structs. Spatial indexes should be treated as opaque structs.
This meanns you shouldn't be reading any of the struct fields. This meanns you shouldn't be reading any of the struct fields.
@{ @{
*/ */
//MARK: Spatial Index //MARK: Spatial Index
@ -56,11 +56,11 @@ typedef struct cpSpatialIndex cpSpatialIndex;
/// @private /// @private
struct cpSpatialIndex { struct cpSpatialIndex {
cpSpatialIndexClass *klass; cpSpatialIndexClass *klass;
cpSpatialIndexBBFunc bbfunc; cpSpatialIndexBBFunc bbfunc;
cpSpatialIndex *staticIndex, *dynamicIndex; cpSpatialIndex *staticIndex, *dynamicIndex;
}; };
@ -127,27 +127,25 @@ typedef void (*cpSpatialIndexReindexImpl)(cpSpatialIndex *index);
typedef void (*cpSpatialIndexReindexObjectImpl)(cpSpatialIndex *index, void *obj, cpHashValue hashid); typedef void (*cpSpatialIndexReindexObjectImpl)(cpSpatialIndex *index, void *obj, cpHashValue hashid);
typedef void (*cpSpatialIndexReindexQueryImpl)(cpSpatialIndex *index, cpSpatialIndexQueryFunc func, void *data); typedef void (*cpSpatialIndexReindexQueryImpl)(cpSpatialIndex *index, cpSpatialIndexQueryFunc func, void *data);
typedef void (*cpSpatialIndexPointQueryImpl)(cpSpatialIndex *index, cpVect point, cpSpatialIndexQueryFunc func, void *data);
typedef void (*cpSpatialIndexSegmentQueryImpl)(cpSpatialIndex *index, void *obj, cpVect a, cpVect b, cpFloat t_exit, cpSpatialIndexSegmentQueryFunc func, void *data);
typedef void (*cpSpatialIndexQueryImpl)(cpSpatialIndex *index, void *obj, cpBB bb, cpSpatialIndexQueryFunc func, void *data); typedef void (*cpSpatialIndexQueryImpl)(cpSpatialIndex *index, void *obj, cpBB bb, cpSpatialIndexQueryFunc func, void *data);
typedef void (*cpSpatialIndexSegmentQueryImpl)(cpSpatialIndex *index, void *obj, cpVect a, cpVect b, cpFloat t_exit, cpSpatialIndexSegmentQueryFunc func, void *data);
struct cpSpatialIndexClass { struct cpSpatialIndexClass {
cpSpatialIndexDestroyImpl destroy; cpSpatialIndexDestroyImpl destroy;
cpSpatialIndexCountImpl count; cpSpatialIndexCountImpl count;
cpSpatialIndexEachImpl each; cpSpatialIndexEachImpl each;
cpSpatialIndexContainsImpl contains; cpSpatialIndexContainsImpl contains;
cpSpatialIndexInsertImpl insert; cpSpatialIndexInsertImpl insert;
cpSpatialIndexRemoveImpl remove; cpSpatialIndexRemoveImpl remove;
cpSpatialIndexReindexImpl reindex; cpSpatialIndexReindexImpl reindex;
cpSpatialIndexReindexObjectImpl reindexObject; cpSpatialIndexReindexObjectImpl reindexObject;
cpSpatialIndexReindexQueryImpl reindexQuery; cpSpatialIndexReindexQueryImpl reindexQuery;
cpSpatialIndexPointQueryImpl pointQuery; cpSpatialIndexQueryImpl query;
cpSpatialIndexSegmentQueryImpl segmentQuery; cpSpatialIndexSegmentQueryImpl segmentQuery;
cpSpatialIndexQueryImpl query;
}; };
/// Destroy and free a spatial index. /// Destroy and free a spatial index.
@ -158,71 +156,64 @@ void cpSpatialIndexCollideStatic(cpSpatialIndex *dynamicIndex, cpSpatialIndex *s
/// Destroy a spatial index. /// Destroy a spatial index.
static inline void cpSpatialIndexDestroy(cpSpatialIndex *index) static inline void cpSpatialIndexDestroy(cpSpatialIndex *index)
{ {
if(index->klass) index->klass->destroy(index); if(index->klass) index->klass->destroy(index);
} }
/// Get the number of objects in the spatial index. /// Get the number of objects in the spatial index.
static inline int cpSpatialIndexCount(cpSpatialIndex *index) static inline int cpSpatialIndexCount(cpSpatialIndex *index)
{ {
return index->klass->count(index); return index->klass->count(index);
} }
/// Iterate the objects in the spatial index. @c func will be called once for each object. /// Iterate the objects in the spatial index. @c func will be called once for each object.
static inline void cpSpatialIndexEach(cpSpatialIndex *index, cpSpatialIndexIteratorFunc func, void *data) static inline void cpSpatialIndexEach(cpSpatialIndex *index, cpSpatialIndexIteratorFunc func, void *data)
{ {
index->klass->each(index, func, data); index->klass->each(index, func, data);
} }
/// Returns true if the spatial index contains the given object. /// Returns true if the spatial index contains the given object.
/// Most spatial indexes use hashed storage, so you must provide a hash value too. /// Most spatial indexes use hashed storage, so you must provide a hash value too.
static inline cpBool cpSpatialIndexContains(cpSpatialIndex *index, void *obj, cpHashValue hashid) static inline cpBool cpSpatialIndexContains(cpSpatialIndex *index, void *obj, cpHashValue hashid)
{ {
return index->klass->contains(index, obj, hashid); return index->klass->contains(index, obj, hashid);
} }
/// Add an object to a spatial index. /// Add an object to a spatial index.
/// Most spatial indexes use hashed storage, so you must provide a hash value too. /// Most spatial indexes use hashed storage, so you must provide a hash value too.
static inline void cpSpatialIndexInsert(cpSpatialIndex *index, void *obj, cpHashValue hashid) static inline void cpSpatialIndexInsert(cpSpatialIndex *index, void *obj, cpHashValue hashid)
{ {
index->klass->insert(index, obj, hashid); index->klass->insert(index, obj, hashid);
} }
/// Remove an object from a spatial index. /// Remove an object from a spatial index.
/// Most spatial indexes use hashed storage, so you must provide a hash value too. /// Most spatial indexes use hashed storage, so you must provide a hash value too.
static inline void cpSpatialIndexRemove(cpSpatialIndex *index, void *obj, cpHashValue hashid) static inline void cpSpatialIndexRemove(cpSpatialIndex *index, void *obj, cpHashValue hashid)
{ {
index->klass->remove(index, obj, hashid); index->klass->remove(index, obj, hashid);
} }
/// Perform a full reindex of a spatial index. /// Perform a full reindex of a spatial index.
static inline void cpSpatialIndexReindex(cpSpatialIndex *index) static inline void cpSpatialIndexReindex(cpSpatialIndex *index)
{ {
index->klass->reindex(index); index->klass->reindex(index);
} }
/// Reindex a single object in the spatial index. /// Reindex a single object in the spatial index.
static inline void cpSpatialIndexReindexObject(cpSpatialIndex *index, void *obj, cpHashValue hashid) static inline void cpSpatialIndexReindexObject(cpSpatialIndex *index, void *obj, cpHashValue hashid)
{ {
index->klass->reindexObject(index, obj, hashid); index->klass->reindexObject(index, obj, hashid);
}
/// Perform a point query against the spatial index, calling @c func for each potential match.
/// A pointer to the point will be passed as @c obj1 of @c func.
static inline void cpSpatialIndexPointQuery(cpSpatialIndex *index, cpVect point, cpSpatialIndexQueryFunc func, void *data)
{
index->klass->pointQuery(index, point, func, data);
}
/// Perform a segment query against the spatial index, calling @c func for each potential match.
static inline void cpSpatialIndexSegmentQuery(cpSpatialIndex *index, void *obj, cpVect a, cpVect b, cpFloat t_exit, cpSpatialIndexSegmentQueryFunc func, void *data)
{
index->klass->segmentQuery(index, obj, a, b, t_exit, func, data);
} }
/// Perform a rectangle query against the spatial index, calling @c func for each potential match. /// Perform a rectangle query against the spatial index, calling @c func for each potential match.
static inline void cpSpatialIndexQuery(cpSpatialIndex *index, void *obj, cpBB bb, cpSpatialIndexQueryFunc func, void *data) static inline void cpSpatialIndexQuery(cpSpatialIndex *index, void *obj, cpBB bb, cpSpatialIndexQueryFunc func, void *data)
{ {
index->klass->query(index, obj, bb, func, data); index->klass->query(index, obj, bb, func, data);
}
/// Perform a segment query against the spatial index, calling @c func for each potential match.
static inline void cpSpatialIndexSegmentQuery(cpSpatialIndex *index, void *obj, cpVect a, cpVect b, cpFloat t_exit, cpSpatialIndexSegmentQueryFunc func, void *data)
{
index->klass->segmentQuery(index, obj, a, b, t_exit, func, data);
} }
/// Simultaneously reindex and find all colliding objects. /// Simultaneously reindex and find all colliding objects.
@ -230,7 +221,7 @@ static inline void cpSpatialIndexQuery(cpSpatialIndex *index, void *obj, cpBB bb
/// If the spatial index was initialized with a static index, it will collide it's objects against that as well. /// If the spatial index was initialized with a static index, it will collide it's objects against that as well.
static inline void cpSpatialIndexReindexQuery(cpSpatialIndex *index, cpSpatialIndexQueryFunc func, void *data) static inline void cpSpatialIndexReindexQuery(cpSpatialIndex *index, cpSpatialIndexQueryFunc func, void *data)
{ {
index->klass->reindexQuery(index, func, data); index->klass->reindexQuery(index, func, data);
} }
///@} ///@}

View File

@ -29,8 +29,8 @@ static const cpVect cpvzero = {0.0f,0.0f};
/// Convenience constructor for cpVect structs. /// Convenience constructor for cpVect structs.
static inline cpVect cpv(const cpFloat x, const cpFloat y) static inline cpVect cpv(const cpFloat x, const cpFloat y)
{ {
cpVect v = {x, y}; cpVect v = {x, y};
return v; return v;
} }
/// Returns the length of v. /// Returns the length of v.
@ -48,45 +48,45 @@ cpVect cpvforangle(const cpFloat a);
/// Returns the angular direction v is pointing in (in radians). /// Returns the angular direction v is pointing in (in radians).
cpFloat cpvtoangle(const cpVect v); cpFloat cpvtoangle(const cpVect v);
/// Returns a string representation of v. Intended mostly for debugging purposes and not production use. /// Returns a string representation of v. Intended mostly for debugging purposes and not production use.
/// @attention The string points to a static local and is reset every time the function is called. /// @attention The string points to a static local and is reset every time the function is called.
/// If you want to print more than one vector you will have to split up your printing onto separate lines. /// If you want to print more than one vector you will have to split up your printing onto separate lines.
char* cpvstr(const cpVect v); char* cpvstr(const cpVect v);
/// Check if two vectors are equal. (Be careful when comparing floating point numbers!) /// Check if two vectors are equal. (Be careful when comparing floating point numbers!)
static inline cpBool cpveql(const cpVect v1, const cpVect v2) static inline cpBool cpveql(const cpVect v1, const cpVect v2)
{ {
return (v1.x == v2.x && v1.y == v2.y); return (v1.x == v2.x && v1.y == v2.y);
} }
/// Add two vectors /// Add two vectors
static inline cpVect cpvadd(const cpVect v1, const cpVect v2) static inline cpVect cpvadd(const cpVect v1, const cpVect v2)
{ {
return cpv(v1.x + v2.x, v1.y + v2.y); return cpv(v1.x + v2.x, v1.y + v2.y);
} }
/// Subtract two vectors. /// Subtract two vectors.
static inline cpVect cpvsub(const cpVect v1, const cpVect v2) static inline cpVect cpvsub(const cpVect v1, const cpVect v2)
{ {
return cpv(v1.x - v2.x, v1.y - v2.y); return cpv(v1.x - v2.x, v1.y - v2.y);
} }
/// Negate a vector. /// Negate a vector.
static inline cpVect cpvneg(const cpVect v) static inline cpVect cpvneg(const cpVect v)
{ {
return cpv(-v.x, -v.y); return cpv(-v.x, -v.y);
} }
/// Scalar multiplication. /// Scalar multiplication.
static inline cpVect cpvmult(const cpVect v, const cpFloat s) static inline cpVect cpvmult(const cpVect v, const cpFloat s)
{ {
return cpv(v.x*s, v.y*s); return cpv(v.x*s, v.y*s);
} }
/// Vector dot product. /// Vector dot product.
static inline cpFloat cpvdot(const cpVect v1, const cpVect v2) static inline cpFloat cpvdot(const cpVect v1, const cpVect v2)
{ {
return v1.x*v2.x + v1.y*v2.y; return v1.x*v2.x + v1.y*v2.y;
} }
/// 2D vector cross product analog. /// 2D vector cross product analog.
@ -94,90 +94,90 @@ static inline cpFloat cpvdot(const cpVect v1, const cpVect v2)
/// This function returns the magnitude of the z value. /// This function returns the magnitude of the z value.
static inline cpFloat cpvcross(const cpVect v1, const cpVect v2) static inline cpFloat cpvcross(const cpVect v1, const cpVect v2)
{ {
return v1.x*v2.y - v1.y*v2.x; return v1.x*v2.y - v1.y*v2.x;
} }
/// Returns a perpendicular vector. (90 degree rotation) /// Returns a perpendicular vector. (90 degree rotation)
static inline cpVect cpvperp(const cpVect v) static inline cpVect cpvperp(const cpVect v)
{ {
return cpv(-v.y, v.x); return cpv(-v.y, v.x);
} }
/// Returns a perpendicular vector. (-90 degree rotation) /// Returns a perpendicular vector. (-90 degree rotation)
static inline cpVect cpvrperp(const cpVect v) static inline cpVect cpvrperp(const cpVect v)
{ {
return cpv(v.y, -v.x); return cpv(v.y, -v.x);
} }
/// Returns the vector projection of v1 onto v2. /// Returns the vector projection of v1 onto v2.
static inline cpVect cpvproject(const cpVect v1, const cpVect v2) static inline cpVect cpvproject(const cpVect v1, const cpVect v2)
{ {
return cpvmult(v2, cpvdot(v1, v2)/cpvdot(v2, v2)); return cpvmult(v2, cpvdot(v1, v2)/cpvdot(v2, v2));
} }
/// Uses complex number multiplication to rotate v1 by v2. Scaling will occur if v1 is not a unit vector. /// Uses complex number multiplication to rotate v1 by v2. Scaling will occur if v1 is not a unit vector.
static inline cpVect cpvrotate(const cpVect v1, const cpVect v2) static inline cpVect cpvrotate(const cpVect v1, const cpVect v2)
{ {
return cpv(v1.x*v2.x - v1.y*v2.y, v1.x*v2.y + v1.y*v2.x); return cpv(v1.x*v2.x - v1.y*v2.y, v1.x*v2.y + v1.y*v2.x);
} }
/// Inverse of cpvrotate(). /// Inverse of cpvrotate().
static inline cpVect cpvunrotate(const cpVect v1, const cpVect v2) static inline cpVect cpvunrotate(const cpVect v1, const cpVect v2)
{ {
return cpv(v1.x*v2.x + v1.y*v2.y, v1.y*v2.x - v1.x*v2.y); return cpv(v1.x*v2.x + v1.y*v2.y, v1.y*v2.x - v1.x*v2.y);
} }
/// Returns the squared length of v. Faster than cpvlength() when you only need to compare lengths. /// Returns the squared length of v. Faster than cpvlength() when you only need to compare lengths.
static inline cpFloat cpvlengthsq(const cpVect v) static inline cpFloat cpvlengthsq(const cpVect v)
{ {
return cpvdot(v, v); return cpvdot(v, v);
} }
/// Linearly interpolate between v1 and v2. /// Linearly interpolate between v1 and v2.
static inline cpVect cpvlerp(const cpVect v1, const cpVect v2, const cpFloat t) static inline cpVect cpvlerp(const cpVect v1, const cpVect v2, const cpFloat t)
{ {
return cpvadd(cpvmult(v1, 1.0f - t), cpvmult(v2, t)); return cpvadd(cpvmult(v1, 1.0f - t), cpvmult(v2, t));
} }
/// Returns a normalized copy of v. /// Returns a normalized copy of v.
static inline cpVect cpvnormalize(const cpVect v) static inline cpVect cpvnormalize(const cpVect v)
{ {
return cpvmult(v, 1.0f/cpvlength(v)); return cpvmult(v, 1.0f/cpvlength(v));
} }
/// Returns a normalized copy of v or cpvzero if v was already cpvzero. Protects against divide by zero errors. /// Returns a normalized copy of v or cpvzero if v was already cpvzero. Protects against divide by zero errors.
static inline cpVect cpvnormalize_safe(const cpVect v) static inline cpVect cpvnormalize_safe(const cpVect v)
{ {
return (v.x == 0.0f && v.y == 0.0f ? cpvzero : cpvnormalize(v)); return (v.x == 0.0f && v.y == 0.0f ? cpvzero : cpvnormalize(v));
} }
/// Clamp v to length len. /// Clamp v to length len.
static inline cpVect cpvclamp(const cpVect v, const cpFloat len) static inline cpVect cpvclamp(const cpVect v, const cpFloat len)
{ {
return (cpvdot(v,v) > len*len) ? cpvmult(cpvnormalize(v), len) : v; return (cpvdot(v,v) > len*len) ? cpvmult(cpvnormalize(v), len) : v;
} }
/// Linearly interpolate between v1 towards v2 by distance d. /// Linearly interpolate between v1 towards v2 by distance d.
static inline cpVect cpvlerpconst(cpVect v1, cpVect v2, cpFloat d) static inline cpVect cpvlerpconst(cpVect v1, cpVect v2, cpFloat d)
{ {
return cpvadd(v1, cpvclamp(cpvsub(v2, v1), d)); return cpvadd(v1, cpvclamp(cpvsub(v2, v1), d));
} }
/// Returns the distance between v1 and v2. /// Returns the distance between v1 and v2.
static inline cpFloat cpvdist(const cpVect v1, const cpVect v2) static inline cpFloat cpvdist(const cpVect v1, const cpVect v2)
{ {
return cpvlength(cpvsub(v1, v2)); return cpvlength(cpvsub(v1, v2));
} }
/// Returns the squared distance between v1 and v2. Faster than cpvdist() when you only need to compare distances. /// Returns the squared distance between v1 and v2. Faster than cpvdist() when you only need to compare distances.
static inline cpFloat cpvdistsq(const cpVect v1, const cpVect v2) static inline cpFloat cpvdistsq(const cpVect v1, const cpVect v2)
{ {
return cpvlengthsq(cpvsub(v1, v2)); return cpvlengthsq(cpvsub(v1, v2));
} }
/// Returns true if the distance between v1 and v2 is less than dist. /// Returns true if the distance between v1 and v2 is less than dist.
static inline cpBool cpvnear(const cpVect v1, const cpVect v2, const cpFloat dist) static inline cpBool cpvnear(const cpVect v1, const cpVect v2, const cpFloat dist)
{ {
return cpvdistsq(v1, v2) < dist*dist; return cpvdistsq(v1, v2) < dist*dist;
} }
/// @} /// @}

View File

@ -20,7 +20,7 @@
OutputDirectory="$(SolutionDir)$(ConfigurationName).win32" OutputDirectory="$(SolutionDir)$(ConfigurationName).win32"
IntermediateDirectory="$(ConfigurationName).win32" IntermediateDirectory="$(ConfigurationName).win32"
ConfigurationType="4" ConfigurationType="4"
CharacterSet="2" CharacterSet="1"
> >
<Tool <Tool
Name="VCPreBuildEventTool" Name="VCPreBuildEventTool"
@ -87,7 +87,7 @@
OutputDirectory="$(SolutionDir)$(ConfigurationName).win32" OutputDirectory="$(SolutionDir)$(ConfigurationName).win32"
IntermediateDirectory="$(ConfigurationName).win32" IntermediateDirectory="$(ConfigurationName).win32"
ConfigurationType="4" ConfigurationType="4"
CharacterSet="2" CharacterSet="1"
> >
<Tool <Tool
Name="VCPreBuildEventTool" Name="VCPreBuildEventTool"

View File

@ -18,11 +18,11 @@
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType> <ConfigurationType>StaticLibrary</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet> <CharacterSet>Unicode</CharacterSet>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType> <ConfigurationType>StaticLibrary</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet> <CharacterSet>Unicode</CharacterSet>
</PropertyGroup> </PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings"> <ImportGroup Label="ExtensionSettings">

View File

@ -9,7 +9,7 @@ if(BUILD_SHARED)
${chipmunk_source_files} ${chipmunk_source_files}
) )
# set the lib's version number # set the lib's version number
set_target_properties(chipmunk PROPERTIES VERSION 6.0.3) set_target_properties(chipmunk PROPERTIES VERSION 6.1.1)
install(TARGETS chipmunk RUNTIME DESTINATION lib LIBRARY DESTINATION lib) install(TARGETS chipmunk RUNTIME DESTINATION lib LIBRARY DESTINATION lib)
endif(BUILD_SHARED) endif(BUILD_SHARED)

View File

@ -19,36 +19,27 @@
* SOFTWARE. * SOFTWARE.
*/ */
#include <stdlib.h>
#include <stdio.h> #include <stdio.h>
#include <math.h> #include <string.h>
#include <stdarg.h> #include <stdarg.h>
#include "chipmunk_private.h" #include "chipmunk_private.h"
//#ifdef __cplusplus
//extern "C" {
//#endif
// void cpInitCollisionFuncs(void);
//#ifdef __cplusplus
//}
//#endif
void void
cpMessage(const char *condition, const char *file, int line, cpBool isError, cpBool isHardError, const char *message, ...) cpMessage(const char *condition, const char *file, int line, cpBool isError, cpBool isHardError, const char *message, ...)
{ {
fprintf(stderr, (isError ? "Aborting due to Chipmunk error: " : "Chipmunk warning: ")); fprintf(stderr, (isError ? "Aborting due to Chipmunk error: " : "Chipmunk warning: "));
va_list vargs; va_list vargs;
va_start(vargs, message); { va_start(vargs, message); {
vfprintf(stderr, message, vargs); vfprintf(stderr, message, vargs);
fprintf(stderr, "\n"); fprintf(stderr, "\n");
} va_end(vargs); } va_end(vargs);
fprintf(stderr, "\tFailed condition: %s\n", condition); fprintf(stderr, "\tFailed condition: %s\n", condition);
fprintf(stderr, "\tSource:%s:%d\n", file, line); fprintf(stderr, "\tSource:%s:%d\n", file, line);
if(isHardError) abort(); if(isError) abort();
} }
#define STR(s) #s #define STR(s) #s
@ -59,112 +50,273 @@ const char *cpVersionString = XSTR(CP_VERSION_MAJOR)"."XSTR(CP_VERSION_MINOR)"."
void void
cpInitChipmunk(void) cpInitChipmunk(void)
{ {
//#ifndef NDEBUG cpAssertWarn(cpFalse, "cpInitChipmunk is deprecated and no longer required. It will be removed in the future.");
// printf("Initializing Chipmunk v%s (Debug Enabled)\n", cpVersionString);
// printf("Compile with -DNDEBUG defined to disable debug mode and runtime assertion checks\n");
//#endif
//
// cpInitCollisionFuncs();
} }
//MARK: Misc Functions
cpFloat cpFloat
cpMomentForCircle(cpFloat m, cpFloat r1, cpFloat r2, cpVect offset) cpMomentForCircle(cpFloat m, cpFloat r1, cpFloat r2, cpVect offset)
{ {
return m*(0.5f*(r1*r1 + r2*r2) + cpvlengthsq(offset)); return m*(0.5f*(r1*r1 + r2*r2) + cpvlengthsq(offset));
} }
cpFloat cpFloat
cpAreaForCircle(cpFloat r1, cpFloat r2) cpAreaForCircle(cpFloat r1, cpFloat r2)
{ {
return (cpFloat)M_PI*cpfabs(r1*r1 - r2*r2); return (cpFloat)M_PI*cpfabs(r1*r1 - r2*r2);
} }
cpFloat cpFloat
cpMomentForSegment(cpFloat m, cpVect a, cpVect b) cpMomentForSegment(cpFloat m, cpVect a, cpVect b)
{ {
cpFloat length = cpvlength(cpvsub(b, a)); cpVect offset = cpvmult(cpvadd(a, b), 0.5f);
cpVect offset = cpvmult(cpvadd(a, b), 1.0f/2.0f); return m*(cpvdistsq(b, a)/12.0f + cpvlengthsq(offset));
return m*(length*length/12.0f + cpvlengthsq(offset));
} }
cpFloat cpFloat
cpAreaForSegment(cpVect a, cpVect b, cpFloat r) cpAreaForSegment(cpVect a, cpVect b, cpFloat r)
{ {
return r*((cpFloat)M_PI*r + 2.0f*cpvdist(a, b)); return r*((cpFloat)M_PI*r + 2.0f*cpvdist(a, b));
} }
cpFloat cpFloat
cpMomentForPoly(cpFloat m, const int numVerts, const cpVect *verts, cpVect offset) cpMomentForPoly(cpFloat m, const int numVerts, const cpVect *verts, cpVect offset)
{ {
cpFloat sum1 = 0.0f; cpFloat sum1 = 0.0f;
cpFloat sum2 = 0.0f; cpFloat sum2 = 0.0f;
for(int i=0; i<numVerts; i++){ for(int i=0; i<numVerts; i++){
cpVect v1 = cpvadd(verts[i], offset); cpVect v1 = cpvadd(verts[i], offset);
cpVect v2 = cpvadd(verts[(i+1)%numVerts], offset); cpVect v2 = cpvadd(verts[(i+1)%numVerts], offset);
cpFloat a = cpvcross(v2, v1); cpFloat a = cpvcross(v2, v1);
cpFloat b = cpvdot(v1, v1) + cpvdot(v1, v2) + cpvdot(v2, v2); cpFloat b = cpvdot(v1, v1) + cpvdot(v1, v2) + cpvdot(v2, v2);
sum1 += a*b; sum1 += a*b;
sum2 += a; sum2 += a;
} }
return (m*sum1)/(6.0f*sum2); return (m*sum1)/(6.0f*sum2);
} }
cpFloat cpFloat
cpAreaForPoly(const int numVerts, const cpVect *verts) cpAreaForPoly(const int numVerts, const cpVect *verts)
{ {
cpFloat area = 0.0f; cpFloat area = 0.0f;
for(int i=0; i<numVerts; i++){ for(int i=0; i<numVerts; i++){
area += cpvcross(verts[i], verts[(i+1)%numVerts]); area += cpvcross(verts[i], verts[(i+1)%numVerts]);
} }
return -area/2.0f; return -area/2.0f;
} }
cpVect cpVect
cpCentroidForPoly(const int numVerts, const cpVect *verts) cpCentroidForPoly(const int numVerts, const cpVect *verts)
{ {
cpFloat sum = 0.0f; cpFloat sum = 0.0f;
cpVect vsum = cpvzero; cpVect vsum = cpvzero;
for(int i=0; i<numVerts; i++){ for(int i=0; i<numVerts; i++){
cpVect v1 = verts[i]; cpVect v1 = verts[i];
cpVect v2 = verts[(i+1)%numVerts]; cpVect v2 = verts[(i+1)%numVerts];
cpFloat cross = cpvcross(v1, v2); cpFloat cross = cpvcross(v1, v2);
sum += cross; sum += cross;
vsum = cpvadd(vsum, cpvmult(cpvadd(v1, v2), cross)); vsum = cpvadd(vsum, cpvmult(cpvadd(v1, v2), cross));
} }
return cpvmult(vsum, 1.0f/(3.0f*sum)); return cpvmult(vsum, 1.0f/(3.0f*sum));
} }
void void
cpRecenterPoly(const int numVerts, cpVect *verts){ cpRecenterPoly(const int numVerts, cpVect *verts){
cpVect centroid = cpCentroidForPoly(numVerts, verts); cpVect centroid = cpCentroidForPoly(numVerts, verts);
for(int i=0; i<numVerts; i++){ for(int i=0; i<numVerts; i++){
verts[i] = cpvsub(verts[i], centroid); verts[i] = cpvsub(verts[i], centroid);
} }
} }
cpFloat cpFloat
cpMomentForBox(cpFloat m, cpFloat width, cpFloat height) cpMomentForBox(cpFloat m, cpFloat width, cpFloat height)
{ {
return m*(width*width + height*height)/12.0f; return m*(width*width + height*height)/12.0f;
} }
cpFloat cpFloat
cpMomentForBox2(cpFloat m, cpBB box) cpMomentForBox2(cpFloat m, cpBB box)
{ {
cpFloat width = box.r - box.l; cpFloat width = box.r - box.l;
cpFloat height = box.t - box.b; cpFloat height = box.t - box.b;
cpVect offset = cpvmult(cpv(box.l + box.r, box.b + box.t), 0.5f); cpVect offset = cpvmult(cpv(box.l + box.r, box.b + box.t), 0.5f);
return cpMomentForBox(m, width, height) + m*cpvlengthsq(offset); // TODO NaN when offset is 0 and m is INFINITY
return cpMomentForBox(m, width, height) + m*cpvlengthsq(offset);
} }
//MARK: Quick Hull
void
cpLoopIndexes(cpVect *verts, int count, int *start, int *end)
{
(*start) = (*end) = 0;
cpVect min = verts[0];
cpVect max = min;
for(int i=1; i<count; i++){
cpVect v = verts[i];
if(v.x < min.x || (v.x == min.x && v.y < min.y)){
min = v;
(*start) = i;
} else if(v.x > max.x || (v.x == max.x && v.y > max.y)){
max = v;
(*end) = i;
}
}
}
#define SWAP(__A__, __B__) {cpVect __TMP__ = __A__; __A__ = __B__; __B__ = __TMP__;}
static int
QHullPartition(cpVect *verts, int count, cpVect a, cpVect b, cpFloat tol)
{
if(count == 0) return 0;
cpFloat max = 0;
int pivot = 0;
cpVect delta = cpvsub(b, a);
cpFloat valueTol = tol*cpvlength(delta);
int head = 0;
for(int tail = count-1; head <= tail;){
cpFloat value = cpvcross(delta, cpvsub(verts[head], a));
if(value > valueTol){
if(value > max){
max = value;
pivot = head;
}
head++;
} else {
SWAP(verts[head], verts[tail]);
tail--;
}
}
// move the new pivot to the front if it's not already there.
if(pivot != 0) SWAP(verts[0], verts[pivot]);
return head;
}
static int
QHullReduce(cpFloat tol, cpVect *verts, int count, cpVect a, cpVect pivot, cpVect b, cpVect *result)
{
if(count < 0){
return 0;
} else if(count == 0) {
result[0] = pivot;
return 1;
} else {
int left_count = QHullPartition(verts, count, a, pivot, tol);
int index = QHullReduce(tol, verts + 1, left_count - 1, a, verts[0], pivot, result);
result[index++] = pivot;
int right_count = QHullPartition(verts + left_count, count - left_count, pivot, b, tol);
return index + QHullReduce(tol, verts + left_count + 1, right_count - 1, pivot, verts[left_count], b, result + index);
}
}
// QuickHull seemed like a neat algorithm, and efficient-ish for large input sets.
// My implementation performs an in place reduction using the result array as scratch space.
int
cpConvexHull(int count, cpVect *verts, cpVect *result, int *first, cpFloat tol)
{
if(result){
// Copy the line vertexes into the empty part of the result polyline to use as a scratch buffer.
memcpy(result, verts, count*sizeof(cpVect));
} else {
// If a result array was not specified, reduce the input instead.
result = verts;
}
// Degenerate case, all poins are the same.
int start, end;
cpLoopIndexes(verts, count, &start, &end);
if(start == end){
if(first) (*first) = 0;
return 1;
}
SWAP(result[0], result[start]);
SWAP(result[1], result[end == 0 ? start : end]);
cpVect a = result[0];
cpVect b = result[1];
if(first) (*first) = start;
int resultCount = QHullReduce(tol, result + 2, count - 2, a, b, a, result + 1) + 1;
cpAssertSoft(cpPolyValidate(result, resultCount),
"Internal error: cpConvexHull() and cpPolyValidate() did not agree."
"Please report this error with as much info as you can.");
return resultCount;
}
//MARK: Alternate Block Iterators
#if defined(__has_extension)
#if __has_extension(blocks)
static void IteratorFunc(void *ptr, void (^block)(void *ptr)){block(ptr);}
void cpSpaceEachBody_b(cpSpace *space, void (^block)(cpBody *body)){
cpSpaceEachBody(space, (cpSpaceBodyIteratorFunc)IteratorFunc, block);
}
void cpSpaceEachShape_b(cpSpace *space, void (^block)(cpShape *shape)){
cpSpaceEachShape(space, (cpSpaceShapeIteratorFunc)IteratorFunc, block);
}
void cpSpaceEachConstraint_b(cpSpace *space, void (^block)(cpConstraint *constraint)){
cpSpaceEachConstraint(space, (cpSpaceConstraintIteratorFunc)IteratorFunc, block);
}
static void BodyIteratorFunc(cpBody *body, void *ptr, void (^block)(void *ptr)){block(ptr);}
void cpBodyEachShape_b(cpBody *body, void (^block)(cpShape *shape)){
cpBodyEachShape(body, (cpBodyShapeIteratorFunc)BodyIteratorFunc, block);
}
void cpBodyEachConstraint_b(cpBody *body, void (^block)(cpConstraint *constraint)){
cpBodyEachConstraint(body, (cpBodyConstraintIteratorFunc)BodyIteratorFunc, block);
}
void cpBodyEachArbiter_b(cpBody *body, void (^block)(cpArbiter *arbiter)){
cpBodyEachArbiter(body, (cpBodyArbiterIteratorFunc)BodyIteratorFunc, block);
}
static void NearestPointQueryIteratorFunc(cpShape *shape, cpFloat distance, cpVect point, cpSpaceNearestPointQueryBlock block){block(shape, distance, point);}
void cpSpaceNearestPointQuery_b(cpSpace *space, cpVect point, cpFloat maxDistance, cpLayers layers, cpGroup group, cpSpaceNearestPointQueryBlock block){
cpSpaceNearestPointQuery(space, point, maxDistance, layers, group, (cpSpaceNearestPointQueryFunc)NearestPointQueryIteratorFunc, block);
}
static void SegmentQueryIteratorFunc(cpShape *shape, cpFloat t, cpVect n, cpSpaceSegmentQueryBlock block){block(shape, t, n);}
void cpSpaceSegmentQuery_b(cpSpace *space, cpVect start, cpVect end, cpLayers layers, cpGroup group, cpSpaceSegmentQueryBlock block){
cpSpaceSegmentQuery(space, start, end, layers, group, (cpSpaceSegmentQueryFunc)SegmentQueryIteratorFunc, block);
}
void cpSpaceBBQuery_b(cpSpace *space, cpBB bb, cpLayers layers, cpGroup group, cpSpaceBBQueryBlock block){
cpSpaceBBQuery(space, bb, layers, group, (cpSpaceBBQueryFunc)IteratorFunc, block);
}
static void ShapeQueryIteratorFunc(cpShape *shape, cpContactPointSet *points, cpSpaceShapeQueryBlock block){block(shape, points);}
cpBool cpSpaceShapeQuery_b(cpSpace *space, cpShape *shape, cpSpaceShapeQueryBlock block){
return cpSpaceShapeQuery(space, shape, (cpSpaceShapeQueryFunc)ShapeQueryIteratorFunc, block);
}
#endif
#endif
#include "chipmunk_ffi.h" #include "chipmunk_ffi.h"

View File

@ -19,9 +19,6 @@
* SOFTWARE. * SOFTWARE.
*/ */
#include <stdlib.h>
#include <math.h>
#include "chipmunk_private.h" #include "chipmunk_private.h"
#include "constraints/util.h" #include "constraints/util.h"
@ -32,10 +29,10 @@ void cpConstraintDestroy(cpConstraint *constraint){}
void void
cpConstraintFree(cpConstraint *constraint) cpConstraintFree(cpConstraint *constraint)
{ {
if(constraint){ if(constraint){
cpConstraintDestroy(constraint); cpConstraintDestroy(constraint);
cpfree(constraint); cpfree(constraint);
} }
} }
// *** declared in util.h TODO move declaration to chipmunk_private.h // *** declared in util.h TODO move declaration to chipmunk_private.h
@ -43,18 +40,19 @@ cpConstraintFree(cpConstraint *constraint)
void void
cpConstraintInit(cpConstraint *constraint, const cpConstraintClass *klass, cpBody *a, cpBody *b) cpConstraintInit(cpConstraint *constraint, const cpConstraintClass *klass, cpBody *a, cpBody *b)
{ {
constraint->klass = klass; constraint->klass = klass;
constraint->a = a; constraint->a = a;
constraint->b = b; constraint->b = b;
constraint->space = NULL;
constraint->next_a = NULL;
constraint->next_b = NULL; constraint->next_a = NULL;
constraint->next_b = NULL;
constraint->maxForce = (cpFloat)INFINITY;
constraint->errorBias = cpfpow(1.0f - 0.1f, 60.0f); constraint->maxForce = (cpFloat)INFINITY;
constraint->maxBias = (cpFloat)INFINITY; constraint->errorBias = cpfpow(1.0f - 0.1f, 60.0f);
constraint->maxBias = (cpFloat)INFINITY;
constraint->preSolve = NULL;
constraint->postSolve = NULL; constraint->preSolve = NULL;
constraint->postSolve = NULL;
} }

View File

@ -19,34 +19,31 @@
* SOFTWARE. * SOFTWARE.
*/ */
#include <stdlib.h>
#include <math.h>
#include "chipmunk_private.h" #include "chipmunk_private.h"
#include "constraints/util.h" #include "constraints/util.h"
static cpFloat static cpFloat
defaultSpringTorque(cpDampedRotarySpring *spring, cpFloat relativeAngle){ defaultSpringTorque(cpDampedRotarySpring *spring, cpFloat relativeAngle){
return (relativeAngle - spring->restAngle)*spring->stiffness; return (relativeAngle - spring->restAngle)*spring->stiffness;
} }
static void static void
preStep(cpDampedRotarySpring *spring, cpFloat dt) preStep(cpDampedRotarySpring *spring, cpFloat dt)
{ {
cpBody *a = spring->constraint.a; cpBody *a = spring->constraint.a;
cpBody *b = spring->constraint.b; cpBody *b = spring->constraint.b;
cpFloat moment = a->i_inv + b->i_inv; cpFloat moment = a->i_inv + b->i_inv;
cpAssertSoft(moment != 0.0, "Unsolvable spring."); cpAssertSoft(moment != 0.0, "Unsolvable spring.");
spring->iSum = 1.0f/moment; spring->iSum = 1.0f/moment;
spring->w_coef = 1.0f - cpfexp(-spring->damping*dt*moment); spring->w_coef = 1.0f - cpfexp(-spring->damping*dt*moment);
spring->target_wrn = 0.0f; spring->target_wrn = 0.0f;
// apply spring torque // apply spring torque
cpFloat j_spring = spring->springTorqueFunc((cpConstraint *)spring, a->a - b->a)*dt; cpFloat j_spring = spring->springTorqueFunc((cpConstraint *)spring, a->a - b->a)*dt;
a->w -= j_spring*a->i_inv; a->w -= j_spring*a->i_inv;
b->w += j_spring*b->i_inv; b->w += j_spring*b->i_inv;
} }
static void applyCachedImpulse(cpDampedRotarySpring *spring, cpFloat dt_coef){} static void applyCachedImpulse(cpDampedRotarySpring *spring, cpFloat dt_coef){}
@ -54,58 +51,58 @@ static void applyCachedImpulse(cpDampedRotarySpring *spring, cpFloat dt_coef){}
static void static void
applyImpulse(cpDampedRotarySpring *spring) applyImpulse(cpDampedRotarySpring *spring)
{ {
cpBody *a = spring->constraint.a; cpBody *a = spring->constraint.a;
cpBody *b = spring->constraint.b; cpBody *b = spring->constraint.b;
// compute relative velocity // compute relative velocity
cpFloat wrn = a->w - b->w;//normal_relative_velocity(a, b, r1, r2, n) - spring->target_vrn; cpFloat wrn = a->w - b->w;//normal_relative_velocity(a, b, r1, r2, n) - spring->target_vrn;
// compute velocity loss from drag // compute velocity loss from drag
// not 100% certain this is derived correctly, though it makes sense // not 100% certain this is derived correctly, though it makes sense
cpFloat w_damp = (spring->target_wrn - wrn)*spring->w_coef; cpFloat w_damp = (spring->target_wrn - wrn)*spring->w_coef;
spring->target_wrn = wrn + w_damp; spring->target_wrn = wrn + w_damp;
//apply_impulses(a, b, spring->r1, spring->r2, cpvmult(spring->n, v_damp*spring->nMass)); //apply_impulses(a, b, spring->r1, spring->r2, cpvmult(spring->n, v_damp*spring->nMass));
cpFloat j_damp = w_damp*spring->iSum; cpFloat j_damp = w_damp*spring->iSum;
a->w += j_damp*a->i_inv; a->w += j_damp*a->i_inv;
b->w -= j_damp*b->i_inv; b->w -= j_damp*b->i_inv;
} }
static cpFloat static cpFloat
getImpulse(cpConstraint *constraint) getImpulse(cpConstraint *constraint)
{ {
return 0.0f; return 0.0f;
} }
static const cpConstraintClass klass = { static const cpConstraintClass klass = {
(cpConstraintPreStepImpl)preStep, (cpConstraintPreStepImpl)preStep,
(cpConstraintApplyCachedImpulseImpl)applyCachedImpulse, (cpConstraintApplyCachedImpulseImpl)applyCachedImpulse,
(cpConstraintApplyImpulseImpl)applyImpulse, (cpConstraintApplyImpulseImpl)applyImpulse,
(cpConstraintGetImpulseImpl)getImpulse, (cpConstraintGetImpulseImpl)getImpulse,
}; };
CP_DefineClassGetter(cpDampedRotarySpring) CP_DefineClassGetter(cpDampedRotarySpring)
cpDampedRotarySpring * cpDampedRotarySpring *
cpDampedRotarySpringAlloc(void) cpDampedRotarySpringAlloc(void)
{ {
return (cpDampedRotarySpring *)cpcalloc(1, sizeof(cpDampedRotarySpring)); return (cpDampedRotarySpring *)cpcalloc(1, sizeof(cpDampedRotarySpring));
} }
cpDampedRotarySpring * cpDampedRotarySpring *
cpDampedRotarySpringInit(cpDampedRotarySpring *spring, cpBody *a, cpBody *b, cpFloat restAngle, cpFloat stiffness, cpFloat damping) cpDampedRotarySpringInit(cpDampedRotarySpring *spring, cpBody *a, cpBody *b, cpFloat restAngle, cpFloat stiffness, cpFloat damping)
{ {
cpConstraintInit((cpConstraint *)spring, &klass, a, b); cpConstraintInit((cpConstraint *)spring, &klass, a, b);
spring->restAngle = restAngle; spring->restAngle = restAngle;
spring->stiffness = stiffness; spring->stiffness = stiffness;
spring->damping = damping; spring->damping = damping;
spring->springTorqueFunc = (cpDampedRotarySpringTorqueFunc)defaultSpringTorque; spring->springTorqueFunc = (cpDampedRotarySpringTorqueFunc)defaultSpringTorque;
return spring; return spring;
} }
cpConstraint * cpConstraint *
cpDampedRotarySpringNew(cpBody *a, cpBody *b, cpFloat restAngle, cpFloat stiffness, cpFloat damping) cpDampedRotarySpringNew(cpBody *a, cpBody *b, cpFloat restAngle, cpFloat stiffness, cpFloat damping)
{ {
return (cpConstraint *)cpDampedRotarySpringInit(cpDampedRotarySpringAlloc(), a, b, restAngle, stiffness, damping); return (cpConstraint *)cpDampedRotarySpringInit(cpDampedRotarySpringAlloc(), a, b, restAngle, stiffness, damping);
} }

View File

@ -19,40 +19,37 @@
* SOFTWARE. * SOFTWARE.
*/ */
#include <stdlib.h>
#include <math.h>
#include "chipmunk_private.h" #include "chipmunk_private.h"
#include "constraints/util.h" #include "constraints/util.h"
static cpFloat static cpFloat
defaultSpringForce(cpDampedSpring *spring, cpFloat dist){ defaultSpringForce(cpDampedSpring *spring, cpFloat dist){
return (spring->restLength - dist)*spring->stiffness; return (spring->restLength - dist)*spring->stiffness;
} }
static void static void
preStep(cpDampedSpring *spring, cpFloat dt) preStep(cpDampedSpring *spring, cpFloat dt)
{ {
cpBody *a = spring->constraint.a; cpBody *a = spring->constraint.a;
cpBody *b = spring->constraint.b; cpBody *b = spring->constraint.b;
spring->r1 = cpvrotate(spring->anchr1, a->rot); spring->r1 = cpvrotate(spring->anchr1, a->rot);
spring->r2 = cpvrotate(spring->anchr2, b->rot); spring->r2 = cpvrotate(spring->anchr2, b->rot);
cpVect delta = cpvsub(cpvadd(b->p, spring->r2), cpvadd(a->p, spring->r1)); cpVect delta = cpvsub(cpvadd(b->p, spring->r2), cpvadd(a->p, spring->r1));
cpFloat dist = cpvlength(delta); cpFloat dist = cpvlength(delta);
spring->n = cpvmult(delta, 1.0f/(dist ? dist : INFINITY)); spring->n = cpvmult(delta, 1.0f/(dist ? dist : INFINITY));
cpFloat k = k_scalar(a, b, spring->r1, spring->r2, spring->n); cpFloat k = k_scalar(a, b, spring->r1, spring->r2, spring->n);
cpAssertSoft(k != 0.0, "Unsolvable spring."); cpAssertSoft(k != 0.0, "Unsolvable spring.");
spring->nMass = 1.0f/k; spring->nMass = 1.0f/k;
spring->target_vrn = 0.0f; spring->target_vrn = 0.0f;
spring->v_coef = 1.0f - cpfexp(-spring->damping*dt*k); spring->v_coef = 1.0f - cpfexp(-spring->damping*dt*k);
// apply spring force // apply spring force
cpFloat f_spring = spring->springForceFunc((cpConstraint *)spring, dist); cpFloat f_spring = spring->springForceFunc((cpConstraint *)spring, dist);
apply_impulses(a, b, spring->r1, spring->r2, cpvmult(spring->n, f_spring*dt)); apply_impulses(a, b, spring->r1, spring->r2, cpvmult(spring->n, f_spring*dt));
} }
static void applyCachedImpulse(cpDampedSpring *spring, cpFloat dt_coef){} static void applyCachedImpulse(cpDampedSpring *spring, cpFloat dt_coef){}
@ -60,61 +57,61 @@ static void applyCachedImpulse(cpDampedSpring *spring, cpFloat dt_coef){}
static void static void
applyImpulse(cpDampedSpring *spring) applyImpulse(cpDampedSpring *spring)
{ {
cpBody *a = spring->constraint.a; cpBody *a = spring->constraint.a;
cpBody *b = spring->constraint.b; cpBody *b = spring->constraint.b;
cpVect n = spring->n; cpVect n = spring->n;
cpVect r1 = spring->r1; cpVect r1 = spring->r1;
cpVect r2 = spring->r2; cpVect r2 = spring->r2;
// compute relative velocity // compute relative velocity
cpFloat vrn = normal_relative_velocity(a, b, r1, r2, n); cpFloat vrn = normal_relative_velocity(a, b, r1, r2, n);
// compute velocity loss from drag // compute velocity loss from drag
cpFloat v_damp = (spring->target_vrn - vrn)*spring->v_coef; cpFloat v_damp = (spring->target_vrn - vrn)*spring->v_coef;
spring->target_vrn = vrn + v_damp; spring->target_vrn = vrn + v_damp;
apply_impulses(a, b, spring->r1, spring->r2, cpvmult(spring->n, v_damp*spring->nMass)); apply_impulses(a, b, spring->r1, spring->r2, cpvmult(spring->n, v_damp*spring->nMass));
} }
static cpFloat static cpFloat
getImpulse(cpConstraint *constraint) getImpulse(cpConstraint *constraint)
{ {
return 0.0f; return 0.0f;
} }
static const cpConstraintClass klass = { static const cpConstraintClass klass = {
(cpConstraintPreStepImpl)preStep, (cpConstraintPreStepImpl)preStep,
(cpConstraintApplyCachedImpulseImpl)applyCachedImpulse, (cpConstraintApplyCachedImpulseImpl)applyCachedImpulse,
(cpConstraintApplyImpulseImpl)applyImpulse, (cpConstraintApplyImpulseImpl)applyImpulse,
(cpConstraintGetImpulseImpl)getImpulse, (cpConstraintGetImpulseImpl)getImpulse,
}; };
CP_DefineClassGetter(cpDampedSpring) CP_DefineClassGetter(cpDampedSpring)
cpDampedSpring * cpDampedSpring *
cpDampedSpringAlloc(void) cpDampedSpringAlloc(void)
{ {
return (cpDampedSpring *)cpcalloc(1, sizeof(cpDampedSpring)); return (cpDampedSpring *)cpcalloc(1, sizeof(cpDampedSpring));
} }
cpDampedSpring * cpDampedSpring *
cpDampedSpringInit(cpDampedSpring *spring, cpBody *a, cpBody *b, cpVect anchr1, cpVect anchr2, cpFloat restLength, cpFloat stiffness, cpFloat damping) cpDampedSpringInit(cpDampedSpring *spring, cpBody *a, cpBody *b, cpVect anchr1, cpVect anchr2, cpFloat restLength, cpFloat stiffness, cpFloat damping)
{ {
cpConstraintInit((cpConstraint *)spring, cpDampedSpringGetClass(), a, b); cpConstraintInit((cpConstraint *)spring, cpDampedSpringGetClass(), a, b);
spring->anchr1 = anchr1; spring->anchr1 = anchr1;
spring->anchr2 = anchr2; spring->anchr2 = anchr2;
spring->restLength = restLength; spring->restLength = restLength;
spring->stiffness = stiffness; spring->stiffness = stiffness;
spring->damping = damping; spring->damping = damping;
spring->springForceFunc = (cpDampedSpringForceFunc)defaultSpringForce; spring->springForceFunc = (cpDampedSpringForceFunc)defaultSpringForce;
return spring; return spring;
} }
cpConstraint * cpConstraint *
cpDampedSpringNew(cpBody *a, cpBody *b, cpVect anchr1, cpVect anchr2, cpFloat restLength, cpFloat stiffness, cpFloat damping) cpDampedSpringNew(cpBody *a, cpBody *b, cpVect anchr1, cpVect anchr2, cpFloat restLength, cpFloat stiffness, cpFloat damping)
{ {
return (cpConstraint *)cpDampedSpringInit(cpDampedSpringAlloc(), a, b, anchr1, anchr2, restLength, stiffness, damping); return (cpConstraint *)cpDampedSpringInit(cpDampedSpringAlloc(), a, b, anchr1, anchr2, restLength, stiffness, damping);
} }

View File

@ -19,105 +19,102 @@
* SOFTWARE. * SOFTWARE.
*/ */
#include <stdlib.h>
#include <math.h>
#include "chipmunk_private.h" #include "chipmunk_private.h"
#include "constraints/util.h" #include "constraints/util.h"
static void static void
preStep(cpGearJoint *joint, cpFloat dt) preStep(cpGearJoint *joint, cpFloat dt)
{ {
cpBody *a = joint->constraint.a; cpBody *a = joint->constraint.a;
cpBody *b = joint->constraint.b; cpBody *b = joint->constraint.b;
// calculate moment of inertia coefficient. // calculate moment of inertia coefficient.
joint->iSum = 1.0f/(a->i_inv*joint->ratio_inv + joint->ratio*b->i_inv); joint->iSum = 1.0f/(a->i_inv*joint->ratio_inv + joint->ratio*b->i_inv);
// calculate bias velocity // calculate bias velocity
cpFloat maxBias = joint->constraint.maxBias; cpFloat maxBias = joint->constraint.maxBias;
joint->bias = cpfclamp(-bias_coef(joint->constraint.errorBias, dt)*(b->a*joint->ratio - a->a - joint->phase)/dt, -maxBias, maxBias); joint->bias = cpfclamp(-bias_coef(joint->constraint.errorBias, dt)*(b->a*joint->ratio - a->a - joint->phase)/dt, -maxBias, maxBias);
// compute max impulse // compute max impulse
joint->jMax = J_MAX(joint, dt); joint->jMax = J_MAX(joint, dt);
} }
static void static void
applyCachedImpulse(cpGearJoint *joint, cpFloat dt_coef) applyCachedImpulse(cpGearJoint *joint, cpFloat dt_coef)
{ {
cpBody *a = joint->constraint.a; cpBody *a = joint->constraint.a;
cpBody *b = joint->constraint.b; cpBody *b = joint->constraint.b;
cpFloat j = joint->jAcc*dt_coef; cpFloat j = joint->jAcc*dt_coef;
a->w -= j*a->i_inv*joint->ratio_inv; a->w -= j*a->i_inv*joint->ratio_inv;
b->w += j*b->i_inv; b->w += j*b->i_inv;
} }
static void static void
applyImpulse(cpGearJoint *joint) applyImpulse(cpGearJoint *joint)
{ {
cpBody *a = joint->constraint.a; cpBody *a = joint->constraint.a;
cpBody *b = joint->constraint.b; cpBody *b = joint->constraint.b;
// compute relative rotational velocity // compute relative rotational velocity
cpFloat wr = b->w*joint->ratio - a->w; cpFloat wr = b->w*joint->ratio - a->w;
// compute normal impulse // compute normal impulse
cpFloat j = (joint->bias - wr)*joint->iSum; cpFloat j = (joint->bias - wr)*joint->iSum;
cpFloat jOld = joint->jAcc; cpFloat jOld = joint->jAcc;
joint->jAcc = cpfclamp(jOld + j, -joint->jMax, joint->jMax); joint->jAcc = cpfclamp(jOld + j, -joint->jMax, joint->jMax);
j = joint->jAcc - jOld; j = joint->jAcc - jOld;
// apply impulse // apply impulse
a->w -= j*a->i_inv*joint->ratio_inv; a->w -= j*a->i_inv*joint->ratio_inv;
b->w += j*b->i_inv; b->w += j*b->i_inv;
} }
static cpFloat static cpFloat
getImpulse(cpGearJoint *joint) getImpulse(cpGearJoint *joint)
{ {
return cpfabs(joint->jAcc); return cpfabs(joint->jAcc);
} }
static const cpConstraintClass klass = { static const cpConstraintClass klass = {
(cpConstraintPreStepImpl)preStep, (cpConstraintPreStepImpl)preStep,
(cpConstraintApplyCachedImpulseImpl)applyCachedImpulse, (cpConstraintApplyCachedImpulseImpl)applyCachedImpulse,
(cpConstraintApplyImpulseImpl)applyImpulse, (cpConstraintApplyImpulseImpl)applyImpulse,
(cpConstraintGetImpulseImpl)getImpulse, (cpConstraintGetImpulseImpl)getImpulse,
}; };
CP_DefineClassGetter(cpGearJoint) CP_DefineClassGetter(cpGearJoint)
cpGearJoint * cpGearJoint *
cpGearJointAlloc(void) cpGearJointAlloc(void)
{ {
return (cpGearJoint *)cpcalloc(1, sizeof(cpGearJoint)); return (cpGearJoint *)cpcalloc(1, sizeof(cpGearJoint));
} }
cpGearJoint * cpGearJoint *
cpGearJointInit(cpGearJoint *joint, cpBody *a, cpBody *b, cpFloat phase, cpFloat ratio) cpGearJointInit(cpGearJoint *joint, cpBody *a, cpBody *b, cpFloat phase, cpFloat ratio)
{ {
cpConstraintInit((cpConstraint *)joint, &klass, a, b); cpConstraintInit((cpConstraint *)joint, &klass, a, b);
joint->phase = phase; joint->phase = phase;
joint->ratio = ratio; joint->ratio = ratio;
joint->ratio_inv = 1.0f/ratio; joint->ratio_inv = 1.0f/ratio;
joint->jAcc = 0.0f; joint->jAcc = 0.0f;
return joint; return joint;
} }
cpConstraint * cpConstraint *
cpGearJointNew(cpBody *a, cpBody *b, cpFloat phase, cpFloat ratio) cpGearJointNew(cpBody *a, cpBody *b, cpFloat phase, cpFloat ratio)
{ {
return (cpConstraint *)cpGearJointInit(cpGearJointAlloc(), a, b, phase, ratio); return (cpConstraint *)cpGearJointInit(cpGearJointAlloc(), a, b, phase, ratio);
} }
void void
cpGearJointSetRatio(cpConstraint *constraint, cpFloat value) cpGearJointSetRatio(cpConstraint *constraint, cpFloat value)
{ {
cpConstraintCheckCast(constraint, cpGearJoint); cpConstraintCheckCast(constraint, cpGearJoint);
((cpGearJoint *)constraint)->ratio = value; ((cpGearJoint *)constraint)->ratio = value;
((cpGearJoint *)constraint)->ratio_inv = 1.0f/value; ((cpGearJoint *)constraint)->ratio_inv = 1.0f/value;
cpConstraintActivateBodies(constraint); cpConstraintActivateBodies(constraint);
} }

Some files were not shown because too many files have changed in this diff Show More