AccelerometerDelegateWrapper.h   AccelerometerDelegateWrapper.h 
skipping to change at line 31 skipping to change at line 31
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
************************************************************************** **/ ************************************************************************** **/
#import <Foundation/Foundation.h> #import <Foundation/Foundation.h>
#import "CCAccelerometerDelegate.h" #import "CCAccelerometerDelegate.h"
#import <UIKit/UIKit.h> #import <UIKit/UIKit.h>
@interface AccelerometerDispatcher : NSObject<UIAccelerometerDelegate> @interface AccelerometerDispatcher : NSObject<UIAccelerometerDelegate>
{ {
cocos2d::CCAccelerometerDelegate *delegate_; cocos2d::CCAccelerometerDelegate *delegate_;
cocos2d::CCAcceleration *acceleration_; cocos2d::CCAcceleration *acceleration_;
} }
@property(readwrite) cocos2d::CCAccelerometerDelegate *delegate_; @property(readwrite) cocos2d::CCAccelerometerDelegate *delegate_;
@property(readwrite) cocos2d::CCAcceleration *acceleration_; @property(readwrite) cocos2d::CCAcceleration *acceleration_;
+ (id) sharedAccelerometerDispather; + (id) sharedAccelerometerDispather;
- (id) init; - (id) init;
- (void) addDelegate: (cocos2d::CCAccelerometerDelegate *) delegate; - (void) addDelegate: (cocos2d::CCAccelerometerDelegate *) delegate;
@end @end
 End of changes. 1 change blocks. 
2 lines changed or deleted 2 lines changed or added


 AccelerometerTest.h   AccelerometerTest.h 
#ifndef _ACCELEROMETER_TEST_H_ #ifndef _ACCELEROMETER_TEST_H_
#define _ACCELEROMETER_TEST_H_ #define _ACCELEROMETER_TEST_H_
#include "../testBasic.h" #include "../testBasic.h"
using namespace cocos2d; USING_NS_CC;
class AccelerometerTest: public CCLayer class AccelerometerTest: public CCLayer
{ {
protected: protected:
CCSprite* m_pBall; CCSprite* m_pBall;
double m_fLastTime; double m_fLastTime;
public: public:
AccelerometerTest(void); AccelerometerTest(void);
~AccelerometerTest(void); ~AccelerometerTest(void);
virtual void didAccelerate(CCAcceleration* pAccelerationValue); virtual void didAccelerate(CCAcceleration* pAccelerationValue);
virtual std::string title(); virtual std::string title();
virtual void onEnter(); virtual void onEnter();
}; };
class AccelerometerTestScene : public TestScene class AccelerometerTestScene : public TestScene
{ {
public: public:
virtual void runThisTest(); virtual void runThisTest();
}; };
#endif #endif
 End of changes. 3 change blocks. 
5 lines changed or deleted 5 lines changed or added


 ActionManagerTest.h   ActionManagerTest.h 
#ifndef _ACTION_MANAGER_TEST_H_ #ifndef _ACTION_MANAGER_TEST_H_
#define _ACTION_MANAGER_TEST_H_ #define _ACTION_MANAGER_TEST_H_
#include "../testBasic.h" #include "../testBasic.h"
class ActionManagerTest: public CCLayer class ActionManagerTest: public CCLayer
{ {
protected: protected:
CCTextureAtlas* m_atlas; CCTextureAtlas* m_atlas;
std::string m_strTitle; std::string m_strTitle;
public: public:
ActionManagerTest(void); ActionManagerTest(void);
~ActionManagerTest(void); ~ActionManagerTest(void);
virtual std::string title(); virtual std::string title();
virtual void onEnter(); virtual void onEnter();
void restartCallback(CCObject* pSender); void restartCallback(CCObject* pSender);
void nextCallback(CCObject* pSender); void nextCallback(CCObject* pSender);
void backCallback(CCObject* pSender); void backCallback(CCObject* pSender);
}; };
class CrashTest : public ActionManagerTest class CrashTest : public ActionManagerTest
{ {
public: public:
virtual std::string title(); virtual std::string title();
virtual void onEnter(); virtual void onEnter();
void removeThis(); void removeThis();
}; };
class LogicTest : public ActionManagerTest class LogicTest : public ActionManagerTest
{ {
public: public:
virtual std::string title(); virtual std::string title();
virtual void onEnter(); virtual void onEnter();
void bugMe(CCNode* node); void bugMe(CCNode* node);
}; };
class PauseTest : public ActionManagerTest class PauseTest : public ActionManagerTest
{ {
public: public:
virtual std::string title(); virtual std::string title();
virtual void onEnter(); virtual void onEnter();
void unpause(ccTime dt); void unpause(float dt);
}; };
class RemoveTest : public ActionManagerTest class RemoveTest : public ActionManagerTest
{ {
public: public:
virtual std::string title(); virtual std::string title();
virtual void onEnter(); virtual void onEnter();
void stopAction(); void stopAction();
}; };
class ResumeTest : public ActionManagerTest class ResumeTest : public ActionManagerTest
{ {
public: public:
virtual std::string title(); virtual std::string title();
virtual void onEnter(); virtual void onEnter();
void resumeGrossini(ccTime time); void resumeGrossini(float time);
}; };
class ActionManagerTestScene : public TestScene class ActionManagerTestScene : public TestScene
{ {
public: public:
virtual void runThisTest(); virtual void runThisTest();
}; };
#endif #endif
 End of changes. 8 change blocks. 
18 lines changed or deleted 18 lines changed or added


 ActionsTest.h   ActionsTest.h 
#ifndef _ActionsTest_H_ #ifndef _ActionsTest_H_
#define _ActionsTest_H_ #define _ActionsTest_H_
#include "../testBasic.h" #include "../testBasic.h"
////----#include "cocos2d.h" ////----#include "cocos2d.h"
using namespace cocos2d; USING_NS_CC;
enum enum
{ {
ACTION_MANUAL_LAYER = 0, ACTION_MANUAL_LAYER = 0,
ACTION_MOVE_LAYER, ACTION_MOVE_LAYER,
ACTION_SCALE_LAYER, ACTION_SCALE_LAYER,
ACTION_ROTATE_LAYER, ACTION_ROTATE_LAYER,
ACTION_SKEW_LAYER, ACTION_SKEW_LAYER,
ACTION_SKEWROTATE_LAYER, ACTION_SKEWROTATE_LAYER,
ACTION_JUMP_LAYER, ACTION_JUMP_LAYER,
ACTION_CARDINALSPLINE_LAYER,
ACTION_CATMULLROM_LAYER,
ACTION_BEZIER_LAYER, ACTION_BEZIER_LAYER,
ACTION_BLINK_LAYER, ACTION_BLINK_LAYER,
ACTION_FADE_LAYER, ACTION_FADE_LAYER,
ACTION_TINT_LAYER, ACTION_TINT_LAYER,
ACTION_ANIMATE_LAYER, ACTION_ANIMATE_LAYER,
ACTION_SEQUENCE_LAYER, ACTION_SEQUENCE_LAYER,
ACTION_SEQUENCE2_LAYER, ACTION_SEQUENCE2_LAYER,
ACTION_SPAWN_LAYER, ACTION_SPAWN_LAYER,
ACTION_REVERSE, ACTION_REVERSE,
ACTION_DELAYTIME_LAYER, ACTION_DELAYTIME_LAYER,
ACTION_REPEAT_LAYER, ACTION_REPEAT_LAYER,
ACTION_REPEATEFOREVER_LAYER, ACTION_REPEATEFOREVER_LAYER,
ACTION_ROTATETOREPEATE_LAYER, ACTION_ROTATETOREPEATE_LAYER,
ACTION_ROTATEJERK_LAYER, ACTION_ROTATEJERK_LAYER,
ACTION_CALLFUNC_LAYER, ACTION_CALLFUNC_LAYER,
ACTION_CALLFUNCND_LAYER, ACTION_CALLFUNCND_LAYER,
ACTION_REVERSESEQUENCE_LAYER, ACTION_REVERSESEQUENCE_LAYER,
ACTION_REVERSESEQUENCE2_LAYER, ACTION_REVERSESEQUENCE2_LAYER,
ACTION_ORBIT_LAYER, ACTION_ORBIT_LAYER,
ACTION_FLLOW_LAYER, ACTION_FLLOW_LAYER,
ACTION_TARGETED_LAYER,
PAUSERESUMEACTIONS_LAYER,
ACTION_ISSUE1305_LAYER,
ACTION_ISSUE1305_2_LAYER,
ACTION_ISSUE1288_LAYER,
ACTION_ISSUE1288_2_LAYER,
ACTION_ISSUE1327_LAYER,
ACTION_LAYER_COUNT, ACTION_LAYER_COUNT,
}; };
// the class inherit from TestScene // the class inherit from TestScene
// every Scene each test used must inherit from TestScene, // every Scene each test used must inherit from TestScene,
// make sure the test have the menu item for back to main menu // make sure the test have the menu item for back to main menu
class ActionsTestScene : public TestScene class ActionsTestScene : public TestScene
{ {
public: public:
virtual void runThisTest(); virtual void runThisTest();
}; };
class ActionsDemo : public CCLayer class ActionsDemo : public CCLayer
{ {
protected: protected:
CCSprite* m_grossini; CCSprite* m_grossini;
CCSprite* m_tamara; CCSprite* m_tamara;
CCSprite* m_kathia;public: CCSprite* m_kathia;
public:
virtual void onEnter(); virtual void onEnter();
virtual void onExit(); virtual void onExit();
void centerSprites(unsigned int numberOfSprites); void centerSprites(unsigned int numberOfSprites);
void alignSpritesLeft(unsigned int numberOfSprites); void alignSpritesLeft(unsigned int numberOfSprites);
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
void restartCallback(CCObject* pSender); void restartCallback(CCObject* pSender);
void nextCallback(CCObject* pSender); void nextCallback(CCObject* pSender);
skipping to change at line 92 skipping to change at line 102
class ActionScale : public ActionsDemo class ActionScale : public ActionsDemo
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
virtual std::string subtitle(); virtual std::string subtitle();
}; };
class ActionSkew : public ActionsDemo class ActionSkew : public ActionsDemo
{ {
virtual void onEnter(); virtual void onEnter();
virtual std::string subtitle(); virtual std::string subtitle();
}; };
class ActionSkewRotateScale : public ActionsDemo class ActionSkewRotateScale : public ActionsDemo
{ {
virtual void onEnter(); virtual void onEnter();
virtual std::string subtitle(); virtual std::string subtitle();
}; };
class ActionRotate : public ActionsDemo class ActionRotate : public ActionsDemo
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
virtual std::string subtitle(); virtual std::string subtitle();
}; };
class ActionJump : public ActionsDemo class ActionJump : public ActionsDemo
skipping to change at line 148 skipping to change at line 158
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
virtual std::string subtitle(); virtual std::string subtitle();
}; };
class ActionAnimate : public ActionsDemo class ActionAnimate : public ActionsDemo
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
virtual void onExit();
virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
}; };
class ActionSequence : public ActionsDemo class ActionSequence : public ActionsDemo
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
virtual std::string subtitle(); virtual std::string subtitle();
}; };
skipping to change at line 258 skipping to change at line 270
void callback2(CCNode* pTarget); void callback2(CCNode* pTarget);
void callback3(CCNode* pTarget, void* data); void callback3(CCNode* pTarget, void* data);
}; };
class ActionCallFuncND : public ActionsDemo class ActionCallFuncND : public ActionsDemo
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
void removeFromParentAndCleanup(CCNode* pSender, void* data);
}; };
class ActionFollow : public ActionsDemo class ActionFollow : public ActionsDemo
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
virtual std::string subtitle(); virtual std::string subtitle();
}; };
class ActionTargeted : public ActionsDemo
{
public:
virtual void onEnter();
virtual std::string title();
virtual std::string subtitle();
};
class Issue1305 : public ActionsDemo
{
public:
virtual void onEnter();
virtual void onExit();
void log(CCNode* pSender);
void addSprite(float dt);
virtual std::string title();
virtual std::string subtitle();
private:
CCSprite* m_pSpriteTmp;
};
class Issue1305_2 : public ActionsDemo
{
public:
virtual void onEnter();
void log1();
void log2();
void log3();
void log4();
virtual std::string title();
virtual std::string subtitle();
};
class Issue1288 : public ActionsDemo
{
public:
virtual void onEnter();
virtual std::string title();
virtual std::string subtitle();
};
class Issue1288_2 : public ActionsDemo
{
public:
virtual void onEnter();
virtual std::string title();
virtual std::string subtitle();
};
class Issue1327 : public ActionsDemo
{
public:
virtual void onEnter();
virtual std::string subtitle();
virtual std::string title();
void logSprRotation(CCNode* pSender);
};
class ActionCatmullRom : public ActionsDemo
{
public:
~ActionCatmullRom();
virtual void onEnter();
virtual void draw();
virtual std::string subtitle();
virtual std::string title();
private:
CCPointArray *m_pArray1;
CCPointArray *m_pArray2;
};
class ActionCardinalSpline : public ActionsDemo
{
public:
~ActionCardinalSpline();
virtual void onEnter();
virtual void draw();
virtual std::string subtitle();
virtual std::string title();
private:
CCPointArray *m_pArray;
};
class PauseResumeActions : public ActionsDemo
{
public:
PauseResumeActions();
virtual ~PauseResumeActions();
virtual void onEnter();
virtual std::string subtitle();
virtual std::string title();
void pause(float dt);
void resume(float dt);
private:
CCSet *m_pPausedTargets;
};
#endif #endif
 End of changes. 10 change blocks. 
10 lines changed or deleted 123 lines changed or added


 AddPair.h   AddPair.h 
#ifndef AddPair_H #ifndef AddPair_H
#define AddPair_H #define AddPair_H
class AddPair : public Test class AddPair : public Test
{ {
public: public:
AddPair() AddPair()
{ {
m_world->SetGravity(b2Vec2(0.0f,0.0f)); m_world->SetGravity(b2Vec2(0.0f,0.0f));
{ {
b2CircleShape shape; b2CircleShape shape;
shape.m_p.SetZero(); shape.m_p.SetZero();
shape.m_radius = 0.1f; shape.m_radius = 0.1f;
float minX = -6.0f; float minX = -6.0f;
float maxX = 0.0f; float maxX = 0.0f;
float minY = 4.0f; float minY = 4.0f;
float maxY = 6.0f; float maxY = 6.0f;
for (int32 i = 0; i < 400; ++i) for (int32 i = 0; i < 400; ++i)
{ {
b2BodyDef bd; b2BodyDef bd;
bd.type = b2_dynamicBody; bd.type = b2_dynamicBody;
bd.position = b2Vec2(RandomFloat(minX,maxX), bd.position = b2Vec2(RandomFloat(minX,maxX),RandomFloat(min
RandomFloat(minY,maxY)); Y,maxY));
b2Body* body = m_world->CreateBody(&bd); b2Body* body = m_world->CreateBody(&bd);
body->CreateFixture(&shape, 0.01f); body->CreateFixture(&shape, 0.01f);
} }
} }
{ {
b2PolygonShape shape; b2PolygonShape shape;
shape.SetAsBox(1.5f, 1.5f); shape.SetAsBox(1.5f, 1.5f);
b2BodyDef bd; b2BodyDef bd;
bd.type = b2_dynamicBody; bd.type = b2_dynamicBody;
bd.position.Set(-40.0f,5.0f); bd.position.Set(-40.0f,5.0f);
bd.bullet = true; bd.bullet = true;
b2Body* body = m_world->CreateBody(&bd); b2Body* body = m_world->CreateBody(&bd);
body->CreateFixture(&shape, 1.0f); body->CreateFixture(&shape, 1.0f);
body->SetLinearVelocity(b2Vec2(150.0f, 0.0f)); body->SetLinearVelocity(b2Vec2(150.0f, 0.0f));
} }
} }
static Test* Create() static Test* Create()
{ {
return new AddPair; return new AddPair;
} }
}; };
#endif #endif
 End of changes. 1 change blocks. 
41 lines changed or deleted 41 lines changed or added


 AppController.h   AppController.h 
skipping to change at line 25 skipping to change at line 25
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL TH E FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL TH E
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FR OM, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FR OM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
************************************************************************** **/ ************************************************************************** **/
@class RootViewController; #pragma once
@interface AppController : NSObject <UIAccelerometerDelegate, UIAlertViewDe #import "cocos2d.h"
legate, UITextFieldDelegate,UIApplicationDelegate> { #import "EAGLView.h"
UIWindow *window;
RootViewController *viewController; @interface AppController : NSObject <NSApplicationDelegate>
} {
NSWindow *window;
EAGLView *glView;
}
@property (nonatomic, assign) IBOutlet NSWindow* window;
@property (nonatomic, assign) IBOutlet EAGLView* glView;
-(IBAction) toggleFullScreen:(id)sender;
-(IBAction) exitFullScreen:(id)sender;
@end @end
 End of changes. 2 change blocks. 
6 lines changed or deleted 15 lines changed or added


 AppDelegate.h   AppDelegate.h 
#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.
The reason for implement as private inheritance is to hide some interface c all by CCDirector. The reason for implement as private inheritance is to hide some interface c all by CCDirector.
*/ */
class AppDelegate : private cocos2d::CCApplication class AppDelegate : private cocos2d::CCApplication
{ {
public: public:
AppDelegate(); AppDelegate();
virtual ~AppDelegate(); virtual ~AppDelegate();
/** /**
@brief Implement for initialize OpenGL instance, set source path, e @brief Implement CCDirector and CCScene init code here.
tc...
*/
virtual bool initInstance();
/**
@brief Implement CCDirector and CCScene init code here.
@return true Initialize success, app continue. @return true Initialize success, app continue.
@return false Initialize failed, app terminate. @return false Initialize failed, app terminate.
*/ */
virtual bool applicationDidFinishLaunching(); virtual bool applicationDidFinishLaunching();
/** /**
@brief The function be called when the application enter background @brief The function be called when the application enter background
@param the pointer of the application @param the pointer of the application
*/ */
virtual void applicationDidEnterBackground(); virtual void applicationDidEnterBackground();
/** /**
@brief The function be called when the application enter foreground @brief The function be called when the application enter foreground
@param the pointer of the application @param the pointer of the application
*/ */
virtual void applicationWillEnterForeground(); virtual void applicationWillEnterForeground();
}; };
#endif // _APP_DELEGATE_H_ #endif // __APP_DELEGATE_H__
 End of changes. 6 change blocks. 
13 lines changed or deleted 7 lines changed or added


 ApplyForce.h   ApplyForce.h 
skipping to change at line 25 skipping to change at line 25
* misrepresented as being the original software. * misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution . * 3. This notice may not be removed or altered from any source distribution .
*/ */
#ifndef APPLY_FORCE_H #ifndef APPLY_FORCE_H
#define APPLY_FORCE_H #define APPLY_FORCE_H
class ApplyForce : public Test class ApplyForce : public Test
{ {
public: public:
ApplyForce() ApplyForce()
{ {
m_world->SetGravity(b2Vec2(0.0f, 0.0f)); m_world->SetGravity(b2Vec2(0.0f, 0.0f));
const float32 k_restitution = 0.4f; const float32 k_restitution = 0.4f;
b2Body* ground; b2Body* ground;
{ {
b2BodyDef bd; b2BodyDef bd;
bd.position.Set(0.0f, 20.0f); bd.position.Set(0.0f, 20.0f);
ground = m_world->CreateBody(&bd); ground = m_world->CreateBody(&bd);
b2EdgeShape shape; b2EdgeShape shape;
b2FixtureDef sd; b2FixtureDef sd;
sd.shape = &shape; sd.shape = &shape;
sd.density = 0.0f; sd.density = 0.0f;
sd.restitution = k_restitution; sd.restitution = k_restitution;
// Left vertical // Left vertical
shape.Set(b2Vec2(-20.0f, -20.0f), b2Vec2(-20.0f, 20. shape.Set(b2Vec2(-20.0f, -20.0f), b2Vec2(-20.0f, 20.0f));
0f)); ground->CreateFixture(&sd);
ground->CreateFixture(&sd);
// Right vertical
// Right vertical shape.Set(b2Vec2(20.0f, -20.0f), b2Vec2(20.0f, 20.0f));
shape.Set(b2Vec2(20.0f, -20.0f), b2Vec2(20.0f, 20.0f ground->CreateFixture(&sd);
));
ground->CreateFixture(&sd); // Top horizontal
shape.Set(b2Vec2(-20.0f, 20.0f), b2Vec2(20.0f, 20.0f));
// Top horizontal ground->CreateFixture(&sd);
shape.Set(b2Vec2(-20.0f, 20.0f), b2Vec2(20.0f, 20.0f
)); // Bottom horizontal
ground->CreateFixture(&sd); shape.Set(b2Vec2(-20.0f, -20.0f), b2Vec2(20.0f, -20.0f));
ground->CreateFixture(&sd);
// Bottom horizontal }
shape.Set(b2Vec2(-20.0f, -20.0f), b2Vec2(20.0f, -20.
0f)); {
ground->CreateFixture(&sd); b2Transform xf1;
} xf1.q.Set(0.3524f * b2_pi);
xf1.p = xf1.q.GetXAxis();
{
b2Transform xf1; b2Vec2 vertices[3];
xf1.q.Set(0.3524f * b2_pi); vertices[0] = b2Mul(xf1, b2Vec2(-1.0f, 0.0f));
xf1.p = xf1.q.GetXAxis(); vertices[1] = b2Mul(xf1, b2Vec2(1.0f, 0.0f));
vertices[2] = b2Mul(xf1, b2Vec2(0.0f, 0.5f));
b2Vec2 vertices[3];
vertices[0] = b2Mul(xf1, b2Vec2(-1.0f, 0.0f)); b2PolygonShape poly1;
vertices[1] = b2Mul(xf1, b2Vec2(1.0f, 0.0f)); poly1.Set(vertices, 3);
vertices[2] = b2Mul(xf1, b2Vec2(0.0f, 0.5f));
b2FixtureDef sd1;
b2PolygonShape poly1; sd1.shape = &poly1;
poly1.Set(vertices, 3); sd1.density = 4.0f;
b2FixtureDef sd1; b2Transform xf2;
sd1.shape = &poly1; xf2.q.Set(-0.3524f * b2_pi);
sd1.density = 4.0f; xf2.p = -xf2.q.GetXAxis();
b2Transform xf2; vertices[0] = b2Mul(xf2, b2Vec2(-1.0f, 0.0f));
xf2.q.Set(-0.3524f * b2_pi); vertices[1] = b2Mul(xf2, b2Vec2(1.0f, 0.0f));
xf2.p = -xf2.q.GetXAxis(); vertices[2] = b2Mul(xf2, b2Vec2(0.0f, 0.5f));
vertices[0] = b2Mul(xf2, b2Vec2(-1.0f, 0.0f)); b2PolygonShape poly2;
vertices[1] = b2Mul(xf2, b2Vec2(1.0f, 0.0f)); poly2.Set(vertices, 3);
vertices[2] = b2Mul(xf2, b2Vec2(0.0f, 0.5f));
b2FixtureDef sd2;
b2PolygonShape poly2; sd2.shape = &poly2;
poly2.Set(vertices, 3); sd2.density = 2.0f;
b2FixtureDef sd2; b2BodyDef bd;
sd2.shape = &poly2; bd.type = b2_dynamicBody;
sd2.density = 2.0f; bd.angularDamping = 5.0f;
bd.linearDamping = 0.1f;
b2BodyDef bd;
bd.type = b2_dynamicBody; bd.position.Set(0.0f, 2.0);
bd.angularDamping = 5.0f; bd.angle = b2_pi;
bd.linearDamping = 0.1f; bd.allowSleep = false;
m_body = m_world->CreateBody(&bd);
bd.position.Set(0.0f, 2.0); m_body->CreateFixture(&sd1);
bd.angle = b2_pi; m_body->CreateFixture(&sd2);
bd.allowSleep = false; }
m_body = m_world->CreateBody(&bd);
m_body->CreateFixture(&sd1); {
m_body->CreateFixture(&sd2); b2PolygonShape shape;
} shape.SetAsBox(0.5f, 0.5f);
{ b2FixtureDef fd;
b2PolygonShape shape; fd.shape = &shape;
shape.SetAsBox(0.5f, 0.5f); fd.density = 1.0f;
fd.friction = 0.3f;
b2FixtureDef fd;
fd.shape = &shape; for (int i = 0; i < 10; ++i)
fd.density = 1.0f; {
fd.friction = 0.3f; b2BodyDef bd;
bd.type = b2_dynamicBody;
for (int i = 0; i < 10; ++i)
{ bd.position.Set(0.0f, 5.0f + 1.54f * i);
b2BodyDef bd; b2Body* body = m_world->CreateBody(&bd);
bd.type = b2_dynamicBody;
body->CreateFixture(&fd);
bd.position.Set(0.0f, 5.0f + 1.54f * i);
b2Body* body = m_world->CreateBody(&bd); float32 gravity = 10.0f;
float32 I = body->GetInertia();
body->CreateFixture(&fd); float32 mass = body->GetMass();
float32 gravity = 10.0f; // For a circle: I = 0.5 * m * r * r ==> r = sqrt(2 * I / m
float32 I = body->GetInertia(); )
float32 mass = body->GetMass(); float32 radius = b2Sqrt(2.0f * I / mass);
// For a circle: I = 0.5 * m * r * r ==> r = b2FrictionJointDef jd;
sqrt(2 * I / m) jd.localAnchorA.SetZero();
float32 radius = b2Sqrt(2.0f * I / mass); jd.localAnchorB.SetZero();
jd.bodyA = ground;
b2FrictionJointDef jd; jd.bodyB = body;
jd.localAnchorA.SetZero(); jd.collideConnected = true;
jd.localAnchorB.SetZero(); jd.maxForce = mass * gravity;
jd.bodyA = ground; jd.maxTorque = mass * radius * gravity;
jd.bodyB = body;
jd.collideConnected = true; m_world->CreateJoint(&jd);
jd.maxForce = mass * gravity; }
jd.maxTorque = mass * radius * gravity; }
}
m_world->CreateJoint(&jd);
} void Keyboard(unsigned char key)
} {
} switch (key)
{
void Keyboard(unsigned char key) case 'w':
{ {
switch (key) b2Vec2 f = m_body->GetWorldVector(b2Vec2(0.0f, -200.0f));
{ b2Vec2 p = m_body->GetWorldPoint(b2Vec2(0.0f, 2.0f));
case 'w': m_body->ApplyForce(f, p);
{ }
b2Vec2 f = m_body->GetWorldVector(b2Vec2(0.0 break;
f, -200.0f));
b2Vec2 p = m_body->GetWorldPoint(b2Vec2(0.0f case 'a':
, 2.0f)); {
m_body->ApplyForce(f, p); m_body->ApplyTorque(50.0f);
} }
break; break;
case 'a': case 'd':
{ {
m_body->ApplyTorque(50.0f); m_body->ApplyTorque(-50.0f);
} }
break; break;
}
case 'd': }
{
m_body->ApplyTorque(-50.0f); static Test* Create()
} {
break; return new ApplyForce;
} }
}
static Test* Create()
{
return new ApplyForce;
}
b2Body* m_body; b2Body* m_body;
}; };
#endif #endif
 End of changes. 2 change blocks. 
159 lines changed or deleted 153 lines changed or added


 Ball.h   Ball.h 
#ifndef _BALL_H_ #ifndef _BALL_H_
#define _BALL_H_ #define _BALL_H_
#include "cocos2d.h" #include "cocos2d.h"
class Paddle; class Paddle;
using namespace cocos2d; USING_NS_CC;
class Ball : public CCSprite class Ball : public CCSprite
{ {
CCPoint m_velocity; CCPoint m_velocity;
public: public:
Ball(void); Ball(void);
virtual ~Ball(void); virtual ~Ball(void);
float radius(); float radius();
//BOOL initWithTexture(CCTexture2D* aTexture); //BOOL initWithTexture(CCTexture2D* aTexture);
//virtual void setTexture(CCTexture2D* newTexture); //virtual void setTexture(CCTexture2D* newTexture);
void move(ccTime delta); void move(float delta);
void collideWithPaddle(Paddle* paddle); void collideWithPaddle(Paddle* paddle);
public: public:
void setVelocity(CCPoint velocity){m_velocity = velocity;} void setVelocity(CCPoint velocity){m_velocity = velocity;}
CCPoint getVelocity(){return m_velocity;} CCPoint getVelocity(){return m_velocity;}
public: public:
static Ball* ballWithTexture(CCTexture2D* aTexture); static Ball* ballWithTexture(CCTexture2D* aTexture);
}; };
#endif #endif
 End of changes. 6 change blocks. 
12 lines changed or deleted 12 lines changed or added


 BodyTypes.h   BodyTypes.h 
skipping to change at line 25 skipping to change at line 25
* misrepresented as being the original software. * misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution . * 3. This notice may not be removed or altered from any source distribution .
*/ */
#ifndef BODY_TYPES_H #ifndef BODY_TYPES_H
#define BODY_TYPES_H #define BODY_TYPES_H
class BodyTypes : public Test class BodyTypes : public Test
{ {
public: public:
BodyTypes() BodyTypes()
{ {
b2Body* ground = NULL; b2Body* ground = NULL;
{ {
b2BodyDef bd; b2BodyDef bd;
ground = m_world->CreateBody(&bd); ground = m_world->CreateBody(&bd);
b2EdgeShape shape; b2EdgeShape shape;
shape.Set(b2Vec2(-20.0f, 0.0f), b2Vec2(20.0f, 0.0f)) shape.Set(b2Vec2(-20.0f, 0.0f), b2Vec2(20.0f, 0.0f));
;
b2FixtureDef fd;
b2FixtureDef fd; fd.shape = &shape;
fd.shape = &shape;
ground->CreateFixture(&fd);
ground->CreateFixture(&fd); }
}
// Define attachment
// Define attachment {
{ b2BodyDef bd;
b2BodyDef bd; bd.type = b2_dynamicBody;
bd.type = b2_dynamicBody; bd.position.Set(0.0f, 3.0f);
bd.position.Set(0.0f, 3.0f); m_attachment = m_world->CreateBody(&bd);
m_attachment = m_world->CreateBody(&bd);
b2PolygonShape shape;
b2PolygonShape shape; shape.SetAsBox(0.5f, 2.0f);
shape.SetAsBox(0.5f, 2.0f); m_attachment->CreateFixture(&shape, 2.0f);
m_attachment->CreateFixture(&shape, 2.0f); }
}
// Define platform
// Define platform {
{ b2BodyDef bd;
b2BodyDef bd; bd.type = b2_dynamicBody;
bd.type = b2_dynamicBody; bd.position.Set(-4.0f, 5.0f);
bd.position.Set(-4.0f, 5.0f); m_platform = m_world->CreateBody(&bd);
m_platform = m_world->CreateBody(&bd);
b2PolygonShape shape;
b2PolygonShape shape; shape.SetAsBox(0.5f, 4.0f, b2Vec2(4.0f, 0.0f), 0.5f * b2_pi);
shape.SetAsBox(0.5f, 4.0f, b2Vec2(4.0f, 0.0f), 0.5f
* b2_pi); b2FixtureDef fd;
fd.shape = &shape;
b2FixtureDef fd; fd.friction = 0.6f;
fd.shape = &shape; fd.density = 2.0f;
fd.friction = 0.6f; m_platform->CreateFixture(&fd);
fd.density = 2.0f;
m_platform->CreateFixture(&fd); b2RevoluteJointDef rjd;
rjd.Initialize(m_attachment, m_platform, b2Vec2(0.0f, 5.0f));
b2RevoluteJointDef rjd; rjd.maxMotorTorque = 50.0f;
rjd.Initialize(m_attachment, m_platform, b2Vec2(0.0f rjd.enableMotor = true;
, 5.0f)); m_world->CreateJoint(&rjd);
rjd.maxMotorTorque = 50.0f;
rjd.enableMotor = true; b2PrismaticJointDef pjd;
m_world->CreateJoint(&rjd); pjd.Initialize(ground, m_platform, b2Vec2(0.0f, 5.0f), b2Vec2(1
.0f, 0.0f));
b2PrismaticJointDef pjd;
pjd.Initialize(ground, m_platform, b2Vec2(0.0f, 5.0f pjd.maxMotorForce = 1000.0f;
), b2Vec2(1.0f, 0.0f)); pjd.enableMotor = true;
pjd.lowerTranslation = -10.0f;
pjd.maxMotorForce = 1000.0f; pjd.upperTranslation = 10.0f;
pjd.enableMotor = true; pjd.enableLimit = true;
pjd.lowerTranslation = -10.0f;
pjd.upperTranslation = 10.0f; m_world->CreateJoint(&pjd);
pjd.enableLimit = true;
m_speed = 3.0f;
m_world->CreateJoint(&pjd); }
m_speed = 3.0f; // Create a payload
} {
b2BodyDef bd;
// Create a payload bd.type = b2_dynamicBody;
{ bd.position.Set(0.0f, 8.0f);
b2BodyDef bd; b2Body* body = m_world->CreateBody(&bd);
bd.type = b2_dynamicBody;
bd.position.Set(0.0f, 8.0f); b2PolygonShape shape;
b2Body* body = m_world->CreateBody(&bd); shape.SetAsBox(0.75f, 0.75f);
b2PolygonShape shape; b2FixtureDef fd;
shape.SetAsBox(0.75f, 0.75f); fd.shape = &shape;
fd.friction = 0.6f;
b2FixtureDef fd; fd.density = 2.0f;
fd.shape = &shape;
fd.friction = 0.6f; body->CreateFixture(&fd);
fd.density = 2.0f; }
}
body->CreateFixture(&fd);
} void Keyboard(unsigned char key)
} {
switch (key)
void Keyboard(unsigned char key) {
{ case 'd':
switch (key) m_platform->SetType(b2_dynamicBody);
{ break;
case 'd':
m_platform->SetType(b2_dynamicBody); case 's':
break; m_platform->SetType(b2_staticBody);
break;
case 's':
m_platform->SetType(b2_staticBody); case 'k':
break; m_platform->SetType(b2_kinematicBody);
m_platform->SetLinearVelocity(b2Vec2(-m_speed, 0.0f));
case 'k': m_platform->SetAngularVelocity(0.0f);
m_platform->SetType(b2_kinematicBody); break;
m_platform->SetLinearVelocity(b2Vec2(-m_speed, 0.0f) }
); }
m_platform->SetAngularVelocity(0.0f);
break; void Step(Settings* settings)
} {
} // Drive the kinematic body.
if (m_platform->GetType() == b2_kinematicBody)
void Step(Settings* settings) {
{ b2Vec2 p = m_platform->GetTransform().p;
// Drive the kinematic body. b2Vec2 v = m_platform->GetLinearVelocity();
if (m_platform->GetType() == b2_kinematicBody)
{ if ((p.x < -10.0f && v.x < 0.0f) ||
b2Vec2 p = m_platform->GetTransform().p; (p.x > 10.0f && v.x > 0.0f))
b2Vec2 v = m_platform->GetLinearVelocity(); {
v.x = -v.x;
if ((p.x < -10.0f && v.x < 0.0f) || m_platform->SetLinearVelocity(v);
(p.x > 10.0f && v.x > 0.0f)) }
{ }
v.x = -v.x;
m_platform->SetLinearVelocity(v); Test::Step(settings);
} m_debugDraw.DrawString(5, m_textLine, "Keys: (d) dynamic, (s) stati
} c, (k) kinematic");
m_textLine += 15;
Test::Step(settings); }
m_debugDraw.DrawString(5, m_textLine, "Keys: (d) dynamic, (s
) static, (k) kinematic"); static Test* Create()
m_textLine += 15; {
} return new BodyTypes;
}
static Test* Create()
{ b2Body* m_attachment;
return new BodyTypes; b2Body* m_platform;
} float32 m_speed;
b2Body* m_attachment;
b2Body* m_platform;
float32 m_speed;
}; };
#endif #endif
 End of changes. 1 change blocks. 
138 lines changed or deleted 134 lines changed or added


 Box2dTest.h   Box2dTest.h 
#ifndef _BOX2D_TEST_H_ #ifndef _BOX2D_TEST_H_
#define _BOX2D_TEST_H_ #define _BOX2D_TEST_H_
#include "cocos2d.h" #include "cocos2d.h"
#include "Box2D/Box2D.h" #include "Box2D/Box2D.h"
#include "../testBasic.h" #include "../testBasic.h"
class PhysicsSprite : public CCSprite
{
public:
PhysicsSprite();
void setPhysicsBody(b2Body * body);
virtual bool isDirty(void);
virtual CCAffineTransform nodeToParentTransform(void);
private:
b2Body* m_pBody; // strong ref
};
class Box2DTestLayer : public CCLayer class Box2DTestLayer : public CCLayer
{ {
b2World* world; CCTexture2D* m_pSpriteTexture; // weak ref
//GLESDebugDraw *m_debugDraw; b2World* world;
// GLESDebugDraw* m_debugDraw;
public: public:
Box2DTestLayer(); Box2DTestLayer();
~Box2DTestLayer(); ~Box2DTestLayer();
virtual void draw();
void addNewSpriteWithCoords(CCPoint p); void initPhysics();
void update(ccTime dt); void createResetButton();
virtual void ccTouchesEnded(CCSet* touches, CCEvent* event); void reset(CCObject* sender);
virtual void draw();
void addNewSpriteAtPosition(CCPoint p);
void update(float dt);
virtual void ccTouchesEnded(CCSet* touches, CCEvent* event);
//CREATE_NODE(Box2DTestLayer); //CREATE_NODE(Box2DTestLayer);
} ; } ;
class Box2DTestScene : public TestScene class Box2DTestScene : public TestScene
{ {
public: public:
virtual void runThisTest(); virtual void runThisTest();
}; };
#endif #endif
 End of changes. 5 change blocks. 
10 lines changed or deleted 25 lines changed or added


 Box2dView.h   Box2dView.h 
#ifndef _BOX2D_VIEW_H_ #ifndef _BOX2D_VIEW_H_
#define _BOX2D_VIEW_H_ #define _BOX2D_VIEW_H_
//#include "cocos2d.h" //#include "cocos2d.h"
#include "../testBasic.h" #include "../testBasic.h"
class MenuLayer : public CCLayer class MenuLayer : public CCLayer
{ {
int m_entryID; int m_entryID;
public: public:
MenuLayer(void); MenuLayer(void);
virtual ~MenuLayer(void); virtual ~MenuLayer(void);
bool initWithEntryID(int entryId); bool initWithEntryID(int entryId);
void restartCallback(CCObject* sender); void restartCallback(CCObject* sender);
void nextCallback(CCObject* sender); void nextCallback(CCObject* sender);
void backCallback(CCObject* sender); void backCallback(CCObject* sender);
virtual void registerWithTouchDispatcher(); virtual void registerWithTouchDispatcher();
virtual bool ccTouchBegan(CCTouch* touch, CCEvent* event); virtual bool ccTouchBegan(CCTouch* touch, CCEvent* event);
virtual void ccTouchMoved(CCTouch* touch, CCEvent* event); virtual void ccTouchMoved(CCTouch* touch, CCEvent* event);
public: public:
static MenuLayer* menuWithEntryID(int entryId); static MenuLayer* menuWithEntryID(int entryId);
}; };
struct TestEntry; struct TestEntry;
class Test; class Test;
class Box2DView : public CCLayer class Box2DView : public CCLayer
{ {
TestEntry* m_entry; TestEntry* m_entry;
Test* m_test; Test* m_test;
int m_entryID; int m_entryID;
public: public:
Box2DView(void); Box2DView(void);
virtual ~Box2DView(void); virtual ~Box2DView(void);
bool initWithEntryID(int entryId); bool initWithEntryID(int entryId);
std::string title(); std::string title();
void tick(ccTime dt); void tick(float dt);
void draw(); void draw();
virtual void registerWithTouchDispatcher(); virtual void registerWithTouchDispatcher();
virtual bool ccTouchBegan(CCTouch* touch, CCEvent* event); virtual bool ccTouchBegan(CCTouch* touch, CCEvent* event);
virtual void ccTouchMoved(CCTouch* touch, CCEvent* event); virtual void ccTouchMoved(CCTouch* touch, CCEvent* event);
virtual void ccTouchEnded(CCTouch* touch, CCEvent* event); virtual void ccTouchEnded(CCTouch* touch, CCEvent* event);
//virtual void accelerometer(UIAccelerometer* accelerometer, CCAccel //virtual void accelerometer(UIAccelerometer* accelerometer, CCAccelera
eration* acceleration); tion* acceleration);
static Box2DView* viewWithEntryID(int entryId); static Box2DView* viewWithEntryID(int entryId);
}; };
class Box2dTestBedScene : public TestScene class Box2dTestBedScene : public TestScene
{ {
public: public:
virtual void runThisTest(); virtual void runThisTest();
}; };
#endif #endif
 End of changes. 11 change blocks. 
28 lines changed or deleted 28 lines changed or added


 Breakable.h   Breakable.h 
skipping to change at line 27 skipping to change at line 27
*/ */
#ifndef BREAKABLE_TEST_H #ifndef BREAKABLE_TEST_H
#define BREAKABLE_TEST_H #define BREAKABLE_TEST_H
// This is used to test sensor shapes. // This is used to test sensor shapes.
class Breakable : public Test class Breakable : public Test
{ {
public: public:
enum enum
{ {
e_count = 7 e_count = 7
}; };
Breakable() Breakable()
{ {
// Ground body // Ground body
{ {
b2BodyDef bd; b2BodyDef bd;
b2Body* ground = m_world->CreateBody(&bd); b2Body* ground = m_world->CreateBody(&bd);
b2EdgeShape shape; b2EdgeShape shape;
shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)) shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f));
; ground->CreateFixture(&shape, 0.0f);
ground->CreateFixture(&shape, 0.0f); }
}
// Breakable dynamic body
// Breakable dynamic body {
{ b2BodyDef bd;
b2BodyDef bd; bd.type = b2_dynamicBody;
bd.type = b2_dynamicBody; bd.position.Set(0.0f, 40.0f);
bd.position.Set(0.0f, 40.0f); bd.angle = 0.25f * b2_pi;
bd.angle = 0.25f * b2_pi; m_body1 = m_world->CreateBody(&bd);
m_body1 = m_world->CreateBody(&bd);
m_shape1.SetAsBox(0.5f, 0.5f, b2Vec2(-0.5f, 0.0f), 0.0f);
m_shape1.SetAsBox(0.5f, 0.5f, b2Vec2(-0.5f, 0.0f), 0 m_piece1 = m_body1->CreateFixture(&m_shape1, 1.0f);
.0f);
m_piece1 = m_body1->CreateFixture(&m_shape1, 1.0f); m_shape2.SetAsBox(0.5f, 0.5f, b2Vec2(0.5f, 0.0f), 0.0f);
m_piece2 = m_body1->CreateFixture(&m_shape2, 1.0f);
m_shape2.SetAsBox(0.5f, 0.5f, b2Vec2(0.5f, 0.0f), 0. }
0f);
m_piece2 = m_body1->CreateFixture(&m_shape2, 1.0f); m_break = false;
} m_broke = false;
}
m_break = false;
m_broke = false; void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse)
} {
if (m_broke)
void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse) {
{ // The body already broke.
if (m_broke) return;
{ }
// The body already broke.
return; // Should the body break?
} int32 count = contact->GetManifold()->pointCount;
// Should the body break? float32 maxImpulse = 0.0f;
int32 count = contact->GetManifold()->pointCount; for (int32 i = 0; i < count; ++i)
{
float32 maxImpulse = 0.0f; maxImpulse = b2Max(maxImpulse, impulse->normalImpulses[i]);
for (int32 i = 0; i < count; ++i) }
{
maxImpulse = b2Max(maxImpulse, impulse->normalImpuls if (maxImpulse > 40.0f)
es[i]); {
} // Flag the body for breaking.
m_break = true;
if (maxImpulse > 40.0f) }
{ }
// Flag the body for breaking.
m_break = true; void Break()
} {
} // Create two bodies from one.
b2Body* body1 = m_piece1->GetBody();
void Break() b2Vec2 center = body1->GetWorldCenter();
{
// Create two bodies from one. body1->DestroyFixture(m_piece2);
b2Body* body1 = m_piece1->GetBody(); m_piece2 = NULL;
b2Vec2 center = body1->GetWorldCenter();
b2BodyDef bd;
body1->DestroyFixture(m_piece2); bd.type = b2_dynamicBody;
m_piece2 = NULL; bd.position = body1->GetPosition();
bd.angle = body1->GetAngle();
b2BodyDef bd;
bd.type = b2_dynamicBody; b2Body* body2 = m_world->CreateBody(&bd);
bd.position = body1->GetPosition(); m_piece2 = body2->CreateFixture(&m_shape2, 1.0f);
bd.angle = body1->GetAngle();
// Compute consistent velocities for new bodies based on
b2Body* body2 = m_world->CreateBody(&bd); // cached velocity.
m_piece2 = body2->CreateFixture(&m_shape2, 1.0f); b2Vec2 center1 = body1->GetWorldCenter();
b2Vec2 center2 = body2->GetWorldCenter();
// Compute consistent velocities for new bodies based on
// cached velocity. b2Vec2 velocity1 = m_velocity + b2Cross(m_angularVelocity, center1
b2Vec2 center1 = body1->GetWorldCenter(); - center);
b2Vec2 center2 = body2->GetWorldCenter(); b2Vec2 velocity2 = m_velocity + b2Cross(m_angularVelocity, center2
- center);
b2Vec2 velocity1 = m_velocity + b2Cross(m_angularVelocity, c
enter1 - center); body1->SetAngularVelocity(m_angularVelocity);
b2Vec2 velocity2 = m_velocity + b2Cross(m_angularVelocity, c body1->SetLinearVelocity(velocity1);
enter2 - center);
body2->SetAngularVelocity(m_angularVelocity);
body1->SetAngularVelocity(m_angularVelocity); body2->SetLinearVelocity(velocity2);
body1->SetLinearVelocity(velocity1); }
body2->SetAngularVelocity(m_angularVelocity); void Step(Settings* settings)
body2->SetLinearVelocity(velocity2); {
} if (m_break)
{
void Step(Settings* settings) Break();
{ m_broke = true;
if (m_break) m_break = false;
{ }
Break();
m_broke = true; // Cache velocities to improve movement on breakage.
m_break = false; if (m_broke == false)
} {
m_velocity = m_body1->GetLinearVelocity();
// Cache velocities to improve movement on breakage. m_angularVelocity = m_body1->GetAngularVelocity();
if (m_broke == false) }
{
m_velocity = m_body1->GetLinearVelocity(); Test::Step(settings);
m_angularVelocity = m_body1->GetAngularVelocity(); }
}
static Test* Create()
Test::Step(settings); {
} return new Breakable;
}
static Test* Create()
{ b2Body* m_body1;
return new Breakable; b2Vec2 m_velocity;
} float32 m_angularVelocity;
b2PolygonShape m_shape1;
b2Body* m_body1; b2PolygonShape m_shape2;
b2Vec2 m_velocity; b2Fixture* m_piece1;
float32 m_angularVelocity; b2Fixture* m_piece2;
b2PolygonShape m_shape1;
b2PolygonShape m_shape2;
b2Fixture* m_piece1;
b2Fixture* m_piece2;
bool m_broke; bool m_broke;
bool m_break; bool m_break;
}; };
#endif #endif
 End of changes. 2 change blocks. 
131 lines changed or deleted 127 lines changed or added


 Bridge.h   Bridge.h 
skipping to change at line 26 skipping to change at line 26
* 3. This notice may not be removed or altered from any source distribution . * 3. This notice may not be removed or altered from any source distribution .
*/ */
#ifndef BRIDGE_H #ifndef BRIDGE_H
#define BRIDGE_H #define BRIDGE_H
class Bridge : public Test class Bridge : public Test
{ {
public: public:
enum enum
{ {
e_count = 30 e_count = 30
}; };
Bridge() Bridge()
{ {
b2Body* ground = NULL; b2Body* ground = NULL;
{ {
b2BodyDef bd; b2BodyDef bd;
ground = m_world->CreateBody(&bd); ground = m_world->CreateBody(&bd);
b2EdgeShape shape; b2EdgeShape shape;
shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)) shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f));
; ground->CreateFixture(&shape, 0.0f);
ground->CreateFixture(&shape, 0.0f); }
}
{
{ b2PolygonShape shape;
b2PolygonShape shape; shape.SetAsBox(0.5f, 0.125f);
shape.SetAsBox(0.5f, 0.125f);
b2FixtureDef fd;
b2FixtureDef fd; fd.shape = &shape;
fd.shape = &shape; fd.density = 20.0f;
fd.density = 20.0f; fd.friction = 0.2f;
fd.friction = 0.2f;
b2RevoluteJointDef jd;
b2RevoluteJointDef jd;
b2Body* prevBody = ground;
b2Body* prevBody = ground; for (int32 i = 0; i < e_count; ++i)
for (int32 i = 0; i < e_count; ++i) {
{ b2BodyDef bd;
b2BodyDef bd; bd.type = b2_dynamicBody;
bd.type = b2_dynamicBody; bd.position.Set(-14.5f + 1.0f * i, 5.0f);
bd.position.Set(-14.5f + 1.0f * i, 5.0f); b2Body* body = m_world->CreateBody(&bd);
b2Body* body = m_world->CreateBody(&bd); body->CreateFixture(&fd);
body->CreateFixture(&fd);
b2Vec2 anchor(-15.0f + 1.0f * i, 5.0f);
b2Vec2 anchor(-15.0f + 1.0f * i, 5.0f); jd.Initialize(prevBody, body, anchor);
jd.Initialize(prevBody, body, anchor); m_world->CreateJoint(&jd);
m_world->CreateJoint(&jd);
if (i == (e_count >> 1))
if (i == (e_count >> 1)) {
{ m_middle = body;
m_middle = body; }
} prevBody = body;
prevBody = body; }
}
b2Vec2 anchor(-15.0f + 1.0f * e_count, 5.0f);
b2Vec2 anchor(-15.0f + 1.0f * e_count, 5.0f); jd.Initialize(prevBody, ground, anchor);
jd.Initialize(prevBody, ground, anchor); m_world->CreateJoint(&jd);
m_world->CreateJoint(&jd); }
}
for (int32 i = 0; i < 2; ++i)
for (int32 i = 0; i < 2; ++i) {
{ b2Vec2 vertices[3];
b2Vec2 vertices[3]; vertices[0].Set(-0.5f, 0.0f);
vertices[0].Set(-0.5f, 0.0f); vertices[1].Set(0.5f, 0.0f);
vertices[1].Set(0.5f, 0.0f); vertices[2].Set(0.0f, 1.5f);
vertices[2].Set(0.0f, 1.5f);
b2PolygonShape shape;
b2PolygonShape shape; shape.Set(vertices, 3);
shape.Set(vertices, 3);
b2FixtureDef fd;
b2FixtureDef fd; fd.shape = &shape;
fd.shape = &shape; fd.density = 1.0f;
fd.density = 1.0f;
b2BodyDef bd;
b2BodyDef bd; bd.type = b2_dynamicBody;
bd.type = b2_dynamicBody; bd.position.Set(-8.0f + 8.0f * i, 12.0f);
bd.position.Set(-8.0f + 8.0f * i, 12.0f); b2Body* body = m_world->CreateBody(&bd);
b2Body* body = m_world->CreateBody(&bd); body->CreateFixture(&fd);
body->CreateFixture(&fd); }
}
for (int32 i = 0; i < 3; ++i)
for (int32 i = 0; i < 3; ++i) {
{ b2CircleShape shape;
b2CircleShape shape; shape.m_radius = 0.5f;
shape.m_radius = 0.5f;
b2FixtureDef fd;
b2FixtureDef fd; fd.shape = &shape;
fd.shape = &shape; fd.density = 1.0f;
fd.density = 1.0f;
b2BodyDef bd;
b2BodyDef bd; bd.type = b2_dynamicBody;
bd.type = b2_dynamicBody; bd.position.Set(-6.0f + 6.0f * i, 10.0f);
bd.position.Set(-6.0f + 6.0f * i, 10.0f); b2Body* body = m_world->CreateBody(&bd);
b2Body* body = m_world->CreateBody(&bd); body->CreateFixture(&fd);
body->CreateFixture(&fd); }
} }
}
static Test* Create()
static Test* Create() {
{ return new Bridge;
return new Bridge; }
}
b2Body* m_middle; b2Body* m_middle;
}; };
#endif #endif
 End of changes. 2 change blocks. 
97 lines changed or deleted 96 lines changed or added


 Bug-1159.h   Bug-1159.h 
#ifndef __BUG_1159_H__ #ifndef __BUG_1159_H__
#define __BUG_1159_H__ #define __BUG_1159_H__
#include "BugsTest.h" #include "BugsTest.h"
class Bug1159Layer : public BugsTestBaseLayer class Bug1159Layer : public BugsTestBaseLayer
{ {
public: public:
virtual bool init(); virtual bool init();
virtual void onExit();
static CCScene* scene(); static CCScene* scene();
void callBack(CCObject* pSender); void callBack(CCObject* pSender);
LAYER_NODE_FUNC(Bug1159Layer); CREATE_FUNC(Bug1159Layer);
}; };
#endif // __BUG_1159_H__ #endif // __BUG_1159_H__
 End of changes. 2 change blocks. 
1 lines changed or deleted 2 lines changed or added


 Bug-624.h   Bug-624.h 
#ifndef __BUG_624_H__ #ifndef __BUG_624_H__
#define __BUG_624_H__ #define __BUG_624_H__
#include "BugsTest.h" #include "BugsTest.h"
class Bug624Layer : public BugsTestBaseLayer class Bug624Layer : public BugsTestBaseLayer
{ {
public: public:
virtual bool init(); virtual bool init();
void switchLayer(ccTime dt); void switchLayer(float dt);
virtual void didAccelerate(CCAcceleration* pAccelerationValue); virtual void didAccelerate(CCAcceleration* pAccelerationValue);
LAYER_NODE_FUNC(Bug624Layer); CREATE_FUNC(Bug624Layer);
}; };
class Bug624Layer2 : public BugsTestBaseLayer class Bug624Layer2 : public BugsTestBaseLayer
{ {
public: public:
virtual bool init(); virtual bool init();
void switchLayer(ccTime dt); void switchLayer(float dt);
virtual void didAccelerate(CCAcceleration* pAccelerationValue); virtual void didAccelerate(CCAcceleration* pAccelerationValue);
LAYER_NODE_FUNC(Bug624Layer2); CREATE_FUNC(Bug624Layer2);
}; };
#endif // __BUG_624_H__ #endif // __BUG_624_H__
 End of changes. 4 change blocks. 
4 lines changed or deleted 4 lines changed or added


 Bug-914.h   Bug-914.h 
skipping to change at line 16 skipping to change at line 16
class Bug914Layer : public BugsTestBaseLayer class Bug914Layer : public BugsTestBaseLayer
{ {
public: public:
static CCScene* scene(); static CCScene* scene();
virtual bool init(); virtual bool init();
void ccTouchesMoved(CCSet *touches, CCEvent * event); void ccTouchesMoved(CCSet *touches, CCEvent * event);
void ccTouchesBegan(CCSet *touches, CCEvent * event); void ccTouchesBegan(CCSet *touches, CCEvent * event);
void restart(CCObject* sender); void restart(CCObject* sender);
LAYER_NODE_FUNC(Bug914Layer); CREATE_FUNC(Bug914Layer);
}; };
#endif // __BUG_914_H__ #endif // __BUG_914_H__
 End of changes. 1 change blocks. 
1 lines changed or deleted 1 lines changed or added


 BulletTest.h   BulletTest.h 
skipping to change at line 26 skipping to change at line 26
* 3. This notice may not be removed or altered from any source distribution . * 3. This notice may not be removed or altered from any source distribution .
*/ */
#ifndef BULLET_TEST_H #ifndef BULLET_TEST_H
#define BULLET_TEST_H #define BULLET_TEST_H
class BulletTest : public Test class BulletTest : public Test
{ {
public: public:
BulletTest() BulletTest()
{ {
{ {
b2BodyDef bd; b2BodyDef bd;
bd.position.Set(0.0f, 0.0f); bd.position.Set(0.0f, 0.0f);
b2Body* body = m_world->CreateBody(&bd); b2Body* body = m_world->CreateBody(&bd);
b2EdgeShape edge; b2EdgeShape edge;
edge.Set(b2Vec2(-10.0f, 0.0f), b2Vec2(10.0f, 0.0f)); edge.Set(b2Vec2(-10.0f, 0.0f), b2Vec2(10.0f, 0.0f));
body->CreateFixture(&edge, 0.0f); body->CreateFixture(&edge, 0.0f);
b2PolygonShape shape; b2PolygonShape shape;
shape.SetAsBox(0.2f, 1.0f, b2Vec2(0.5f, 1.0f), 0.0f) shape.SetAsBox(0.2f, 1.0f, b2Vec2(0.5f, 1.0f), 0.0f);
; body->CreateFixture(&shape, 0.0f);
body->CreateFixture(&shape, 0.0f); }
}
{
{ b2BodyDef bd;
b2BodyDef bd; bd.type = b2_dynamicBody;
bd.type = b2_dynamicBody; bd.position.Set(0.0f, 4.0f);
bd.position.Set(0.0f, 4.0f);
b2PolygonShape box;
b2PolygonShape box; box.SetAsBox(2.0f, 0.1f);
box.SetAsBox(2.0f, 0.1f);
m_body = m_world->CreateBody(&bd);
m_body = m_world->CreateBody(&bd); m_body->CreateFixture(&box, 1.0f);
m_body->CreateFixture(&box, 1.0f);
box.SetAsBox(0.25f, 0.25f);
box.SetAsBox(0.25f, 0.25f);
//m_x = RandomFloat(-1.0f, 1.0f);
//m_x = RandomFloat(-1.0f, 1.0f); m_x = 0.20352793f;
m_x = 0.20352793f; bd.position.Set(m_x, 10.0f);
bd.position.Set(m_x, 10.0f); bd.bullet = true;
bd.bullet = true;
m_bullet = m_world->CreateBody(&bd);
m_bullet = m_world->CreateBody(&bd); m_bullet->CreateFixture(&box, 100.0f);
m_bullet->CreateFixture(&box, 100.0f);
m_bullet->SetLinearVelocity(b2Vec2(0.0f, -50.0f));
m_bullet->SetLinearVelocity(b2Vec2(0.0f, -50.0f)); }
} }
}
void Launch()
void Launch() {
{ m_body->SetTransform(b2Vec2(0.0f, 4.0f), 0.0f);
m_body->SetTransform(b2Vec2(0.0f, 4.0f), 0.0f); m_body->SetLinearVelocity(b2Vec2_zero);
m_body->SetLinearVelocity(b2Vec2_zero); m_body->SetAngularVelocity(0.0f);
m_body->SetAngularVelocity(0.0f);
m_x = RandomFloat(-1.0f, 1.0f);
m_x = RandomFloat(-1.0f, 1.0f); m_bullet->SetTransform(b2Vec2(m_x, 10.0f), 0.0f);
m_bullet->SetTransform(b2Vec2(m_x, 10.0f), 0.0f); m_bullet->SetLinearVelocity(b2Vec2(0.0f, -50.0f));
m_bullet->SetLinearVelocity(b2Vec2(0.0f, -50.0f)); m_bullet->SetAngularVelocity(0.0f);
m_bullet->SetAngularVelocity(0.0f);
extern int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters;
extern int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters; extern int32 b2_toiCalls, b2_toiIters, b2_toiMaxIters;
extern int32 b2_toiCalls, b2_toiIters, b2_toiMaxIters; extern int32 b2_toiRootIters, b2_toiMaxRootIters;
extern int32 b2_toiRootIters, b2_toiMaxRootIters;
b2_gjkCalls = 0;
b2_gjkCalls = 0; b2_gjkIters = 0;
b2_gjkIters = 0; b2_gjkMaxIters = 0;
b2_gjkMaxIters = 0;
b2_toiCalls = 0;
b2_toiCalls = 0; b2_toiIters = 0;
b2_toiIters = 0; b2_toiMaxIters = 0;
b2_toiMaxIters = 0; b2_toiRootIters = 0;
b2_toiRootIters = 0; b2_toiMaxRootIters = 0;
b2_toiMaxRootIters = 0; }
}
void Step(Settings* settings)
void Step(Settings* settings) {
{ Test::Step(settings);
Test::Step(settings);
extern int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters;
extern int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters; extern int32 b2_toiCalls, b2_toiIters;
extern int32 b2_toiCalls, b2_toiIters; extern int32 b2_toiRootIters, b2_toiMaxRootIters;
extern int32 b2_toiRootIters, b2_toiMaxRootIters;
if (b2_gjkCalls > 0)
if (b2_gjkCalls > 0) {
{ m_debugDraw.DrawString(5, m_textLine, "gjk calls = %d, ave gjk
m_debugDraw.DrawString(5, m_textLine, "gjk calls = % iters = %3.1f, max gjk iters = %d",
d, ave gjk iters = %3.1f, max gjk iters = %d", b2_gjkCalls, b2_gjkIters / float32(b2_gjkCalls), b2_gjkMaxI
b2_gjkCalls, b2_gjkIters / float32(b2_gjkCal ters);
ls), b2_gjkMaxIters); m_textLine += 15;
m_textLine += 15; }
}
if (b2_toiCalls > 0)
if (b2_toiCalls > 0) {
{ m_debugDraw.DrawString(5, m_textLine, "toi calls = %d, ave toi
m_debugDraw.DrawString(5, m_textLine, "toi calls = % iters = %3.1f, max toi iters = %d",
d, ave toi iters = %3.1f, max toi iters = %d", b2_toiCalls, b2_toiIters / float32(b2_toiCalls), b2_toiMaxR
b2_toiCalls, b2_toiIters / float32(b2_toiCal ootIters);
ls), b2_toiMaxRootIters); m_textLine += 15;
m_textLine += 15;
m_debugDraw.DrawString(5, m_textLine, "ave toi root iters = %3.
m_debugDraw.DrawString(5, m_textLine, "ave toi root 1f, max toi root iters = %d",
iters = %3.1f, max toi root iters = %d", b2_toiRootIters / float32(b2_toiCalls), b2_toiMaxRootIters)
b2_toiRootIters / float32(b2_toiCalls), b2_t ;
oiMaxRootIters); m_textLine += 15;
m_textLine += 15; }
}
if (m_stepCount % 60 == 0)
if (m_stepCount % 60 == 0) {
{ Launch();
Launch(); }
} }
}
static Test* Create()
static Test* Create() {
{ return new BulletTest;
return new BulletTest; }
}
b2Body* m_body;
b2Body* m_body; b2Body* m_bullet;
b2Body* m_bullet; float32 m_x;
float32 m_x;
}; };
#endif #endif
 End of changes. 1 change blocks. 
115 lines changed or deleted 114 lines changed or added


 CCAccelerometer.h   CCAccelerometer.h 
skipping to change at line 24 skipping to change at line 24
all copies or substantial portions of the Software. all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CC_CCAccelerometer_H__
#define __CC_CCAccelerometer_H__
#include "platform/CCAccelerometer_platform.h" #ifndef __PLATFORM_IPHONE_CCACCELEROMETER_H__
#define __PLATFORM_IPHONE_CCACCELEROMETER_H__
#endif // __CC_CCAccelerometer_H__ #include "platform/CCAccelerometerDelegate.h"
NS_CC_BEGIN
class CC_DLL CCAccelerometer
{
public:
CCAccelerometer();
~CCAccelerometer();
void setDelegate(CCAccelerometerDelegate* pDelegate);
};
NS_CC_END
#endif
 End of changes. 3 change blocks. 
3 lines changed or deleted 2 lines changed or added


 CCAccelerometerDelegate.h   CCAccelerometerDelegate.h 
skipping to change at line 30 skipping to change at line 30
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CCACCELEROMETER_DELEGATE_H__ #ifndef __CCACCELEROMETER_DELEGATE_H__
#define __CCACCELEROMETER_DELEGATE_H__ #define __CCACCELEROMETER_DELEGATE_H__
#include "CCCommon.h" #include "CCCommon.h"
namespace cocos2d { NS_CC_BEGIN
/** /**
@brief The device accelerometer reports values for each axis in units of g- force @brief The device accelerometer reports values for each axis in units of g- force
*/ */
typedef struct typedef struct
{ {
double x; double x;
double y; double y;
double z; double z;
double timestamp; double timestamp;
skipping to change at line 54 skipping to change at line 54
@brief @brief
The CCAccelerometerDelegate defines a single method for The CCAccelerometerDelegate defines a single method for
receiving acceleration-related data from the system. receiving acceleration-related data from the system.
*/ */
class CC_DLL CCAccelerometerDelegate class CC_DLL CCAccelerometerDelegate
{ {
public: public:
virtual void didAccelerate(CCAcceleration* pAccelerationValue) {CC_UNUS ED_PARAM(pAccelerationValue);} virtual void didAccelerate(CCAcceleration* pAccelerationValue) {CC_UNUS ED_PARAM(pAccelerationValue);}
}; };
} //namespace cocos2d NS_CC_END
#endif #endif
 End of changes. 2 change blocks. 
2 lines changed or deleted 2 lines changed or added


 CCAction.h   CCAction.h 
/************************************************************************** ** /************************************************************************** **
Copyright (c) 2010-2011 cocos2d-x.org Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011 Zynga Inc. Copyright (c) 2011 Zynga Inc.
http://www.cocos2d-x.org http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a cop y Permission is hereby granted, free of charge, to any person obtaining a cop y
of this software and associated documentation files (the "Software"), to de al of this software and associated documentation files (the "Software"), to de al
in the Software without restriction, including without limitation the right s in the Software without restriction, including without limitation the right s
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
skipping to change at line 30 skipping to change at line 30
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __ACTIONS_CCACTION_H__ #ifndef __ACTIONS_CCACTION_H__
#define __ACTIONS_CCACTION_H__ #define __ACTIONS_CCACTION_H__
#include "ccTypes.h" #include "cocoa/CCObject.h"
#include "CCObject.h" #include "cocoa/CCGeometry.h"
#include "CCZone.h" #include "platform/CCPlatformMacros.h"
#include "CCNode.h"
namespace cocos2d { NS_CC_BEGIN
enum { enum {
//! Default tag //! Default tag
kCCActionTagInvalid = -1, kCCActionTagInvalid = -1,
}; };
/** /**
* @addtogroup actions
* @{
*/
/**
@brief Base class for CCAction objects. @brief Base class for CCAction objects.
*/ */
class CC_DLL CCAction : public CCObject class CC_DLL CCAction : public CCObject
{ {
public: public:
CCAction(void); CCAction(void);
virtual ~CCAction(void); virtual ~CCAction(void);
char * description(); const char* description();
virtual CCObject* copyWithZone(CCZone *pZone); virtual CCObject* copyWithZone(CCZone *pZone);
//! return true if the action has finished //! return true if the action has finished
virtual bool isDone(void); virtual bool isDone(void);
//! called before the action start. It will also set the target. //! called before the action start. It will also set the target.
virtual void startWithTarget(CCNode *pTarget); virtual void startWithTarget(CCNode *pTarget);
/** /**
called after the action has finished. It will set the 'target' to ni called after the action has finished. It will set the 'target' to nil.
l.
IMPORTANT: You should never call "[action stop]" manually. Instead, use : "target->stopAction(action);" IMPORTANT: You should never call "[action stop]" manually. Instead, use : "target->stopAction(action);"
*/ */
virtual void stop(void); virtual void stop(void);
//! called every frame with it's delta time. DON'T override unless y //! called every frame with it's delta time. DON'T override unless you
ou know what you are doing. know what you are doing.
virtual void step(ccTime dt); virtual void step(float dt);
/** /**
called once per frame. time a value between 0 and 1 called once per frame. time a value between 0 and 1
For example: For example:
- 0 means that the action just started - 0 means that the action just started
- 0.5 means that the action is in the middle - 0.5 means that the action is in the middle
- 1 means that the action is over - 1 means that the action is over
*/ */
virtual void update(ccTime time); virtual void update(float time);
inline CCNode* getTarget(void) { return m_pTarget; } inline CCNode* getTarget(void) { return m_pTarget; }
/** The action will modify the target properties. */ /** The action will modify the target properties. */
inline void setTarget(CCNode *pTarget) { m_pTarget = pTarget; } inline void setTarget(CCNode *pTarget) { m_pTarget = pTarget; }
inline CCNode* getOriginalTarget(void) { return m_pOriginalTarget; } inline CCNode* getOriginalTarget(void) { return m_pOriginalTarget; }
/** Set the original target, since target can be nil. /** Set the original target, since target can be nil.
Is the target that were used to run the action. Unless you are doing Is the target that were used to run the action. Unless you are doing so
something complex, like CCActionManager, you should NOT call this method. mething complex, like CCActionManager, you should NOT call this method.
The target is 'assigned', it is not 'retained'. The target is 'assigned', it is not 'retained'.
@since v0.8.2 @since v0.8.2
*/ */
inline void setOriginalTarget(CCNode *pOriginalTarget) { m_pOriginal inline void setOriginalTarget(CCNode *pOriginalTarget) { m_pOriginalTar
Target = pOriginalTarget; } get = pOriginalTarget; }
inline int getTag(void) { return m_nTag; } inline int getTag(void) { return m_nTag; }
inline void setTag(int nTag) { m_nTag = nTag; } inline void setTag(int nTag) { m_nTag = nTag; }
public: public:
/** Allocates and initializes the action */ /** Allocates and initializes the action
static CCAction* action(); @deprecated: Please use create() instead. This interface will be deprec
ated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCAction* action();
/** Create an action */
static CCAction* create();
protected: protected:
CCNode *m_pOriginalTarget; CCNode *m_pOriginalTarget;
/** The "target". /** The "target".
The target will be set with the 'startWithTarget' method. The target will be set with the 'startWithTarget' method.
When the 'stop' method is called, target will be set to nil. When the 'stop' method is called, target will be set to nil.
The target is 'assigned', it is not 'retained'. The target is 'assigned', it is not 'retained'.
*/ */
CCNode *m_pTarget; CCNode *m_pTarget;
/** The action tag. An identifier of the action */ /** The action tag. An identifier of the action */
int m_nTag; int m_nTag;
}; };
/** /**
@brief @brief
Base class actions that do have a finite time duration. Base class actions that do have a finite time duration.
Possible actions: Possible actions:
- An action with a duration of 0 seconds - An action with a duration of 0 seconds
- An action with a duration of 35.5 seconds - An action with a duration of 35.5 seconds
Infinite time actions are valid Infinite time actions are valid
*/ */
class CC_DLL CCFiniteTimeAction : public CCAction class CC_DLL CCFiniteTimeAction : public CCAction
{ {
public: public:
CCFiniteTimeAction() CCFiniteTimeAction()
: m_fDuration(0) : m_fDuration(0)
{} {}
virtual ~CCFiniteTimeAction(){} virtual ~CCFiniteTimeAction(){}
//! get duration in seconds of the action //! get duration in seconds of the action
inline ccTime getDuration(void) { return m_fDuration; } inline float getDuration(void) { return m_fDuration; }
//! set duration in seconds of the action //! set duration in seconds of the action
inline void setDuration(ccTime duration) { m_fDuration = duration; } inline void setDuration(float duration) { m_fDuration = duration; }
/** returns a reversed action */ /** returns a reversed action */
virtual CCFiniteTimeAction* reverse(void); virtual CCFiniteTimeAction* reverse(void);
protected: protected:
//! duration in seconds //! duration in seconds
ccTime m_fDuration; float m_fDuration;
}; };
class CCActionInterval; class CCActionInterval;
class CCRepeatForever; class CCRepeatForever;
/** /**
@brief Changes the speed of an action, making it take longer (speed>1) @brief Changes the speed of an action, making it take longer (speed>1)
or less (speed<1) time. or less (speed<1) time.
Useful to simulate 'slow motion' or 'fast forward' effect. Useful to simulate 'slow motion' or 'fast forward' effect.
@warning This action can't be Sequenceable because it is not an CCInterval Action @warning This action can't be Sequenceable because it is not an CCInterval Action
*/ */
class CC_DLL CCSpeed : public CCAction class CC_DLL CCSpeed : public CCAction
{ {
public: public:
CCSpeed() CCSpeed()
: m_fSpeed(0.0) : m_fSpeed(0.0)
, m_pInnerAction(NULL) , m_pInnerAction(NULL)
{} {}
virtual ~CCSpeed(void); virtual ~CCSpeed(void);
inline float getSpeed(void) { return m_fSpeed; } inline float getSpeed(void) { return m_fSpeed; }
/** alter the speed of the inner function in runtime */ /** alter the speed of the inner function in runtime */
inline void setSpeed(float fSpeed) { m_fSpeed = fSpeed; } inline void setSpeed(float fSpeed) { m_fSpeed = fSpeed; }
/** initializes the action */ /** initializes the action */
bool initWithAction(CCActionInterval *pAction, float fRate); bool initWithAction(CCActionInterval *pAction, float fSpeed);
virtual CCObject* copyWithZone(CCZone *pZone); virtual CCObject* copyWithZone(CCZone *pZone);
virtual void startWithTarget(CCNode* pTarget); virtual void startWithTarget(CCNode* pTarget);
virtual void stop(); virtual void stop();
virtual void step(ccTime dt); virtual void step(float dt);
virtual bool isDone(void); virtual bool isDone(void);
virtual CCActionInterval* reverse(void); virtual CCActionInterval* reverse(void);
void setInnerAction(CCActionInterval *pAction); void setInnerAction(CCActionInterval *pAction);
inline CCActionInterval* getInnerAction() inline CCActionInterval* getInnerAction()
{ {
return m_pInnerAction; return m_pInnerAction;
} }
public: public:
/** creates the action */ /** creates the action
static CCSpeed* actionWithAction(CCActionInterval *pAction, float fR @deprecated: Please use create(CCActionInterval* float) instead. This i
ate); nterface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCSpeed* actionWithAction(CCActionInterv
al *pAction, float fSpeed);
/** create the action */
static CCSpeed* create(CCActionInterval* pAction, float fSpeed);
protected: protected:
float m_fSpeed; float m_fSpeed;
CCActionInterval *m_pInnerAction; CCActionInterval *m_pInnerAction;
}; };
class CCNode;
class CCPoint;
class CCRect;
/** /**
@brief CCFollow is an action that "follows" a node. @brief CCFollow is an action that "follows" a node.
Eg: Eg:
layer->runAction(CCFollow::actionWithTarget(hero)); layer->runAction(CCFollow::actionWithTarget(hero));
Instead of using CCCamera as a "follower", use this action instead. Instead of using CCCamera as a "follower", use this action instead.
@since v0.99.2 @since v0.99.2
*/ */
class CC_DLL CCFollow : public CCAction class CC_DLL CCFollow : public CCAction
{ {
public: public:
CCFollow() CCFollow()
: m_pobFollowedNode(NULL) : m_pobFollowedNode(NULL)
, m_bBoundarySet(false) , m_bBoundarySet(false)
, m_bBoundaryFullyCovered(false) , m_bBoundaryFullyCovered(false)
, m_fLeftBoundary(0.0) , m_fLeftBoundary(0.0)
, m_fRightBoundary(0.0) , m_fRightBoundary(0.0)
, m_fTopBoundary(0.0) , m_fTopBoundary(0.0)
, m_fBottomBoundary(0.0) , m_fBottomBoundary(0.0)
{} {}
virtual ~CCFollow(void); virtual ~CCFollow(void);
inline bool isBoundarySet(void) { return m_bBoundarySet; } inline bool isBoundarySet(void) { return m_bBoundarySet; }
/** alter behavior - turn on/off boundary */ /** alter behavior - turn on/off boundary */
inline void setBoudarySet(bool bValue) { m_bBoundarySet = bValue; } inline void setBoudarySet(bool bValue) { m_bBoundarySet = bValue; }
/** initializes the action */ /** initializes the action with a set boundary */
bool initWithTarget(CCNode *pFollowedNode); bool initWithTarget(CCNode *pFollowedNode, const CCRect& rect = CCRectZ
ero);
/** initializes the action with a set boundary */
bool initWithTarget(CCNode *pFollowedNode, const CCRect& rect); virtual CCObject* copyWithZone(CCZone *pZone);
virtual void step(float dt);
virtual CCObject* copyWithZone(CCZone *pZone); virtual bool isDone(void);
virtual void step(ccTime dt); virtual void stop(void);
virtual bool isDone(void);
virtual void stop(void);
public: public:
/** creates the action with no boundary set */ /** creates the action with a set boundary,
static CCFollow* actionWithTarget(CCNode *pFollowedNode); It will work with no boundary if @param rect is equal to CCRectZero
.
/** creates the action with a set boundary */ @deprecated: Please use create(CCNode*, const CCRect&) intead. This int
static CCFollow* actionWithTarget(CCNode *pFollowedNode, const CCRec erface will be deprecated sooner or later.
t& rect); */
CC_DEPRECATED_ATTRIBUTE static CCFollow* actionWithTarget(CCNode *pFoll
owedNode, const CCRect& rect = CCRectZero);
/** creates the action with a set boundary,
It will work with no boundary if @param rect is equal to CCRectZero.
*/
static CCFollow* create(CCNode *pFollowedNode, const CCRect& rect = CCR
ectZero);
protected: protected:
// node to follow // node to follow
CCNode *m_pobFollowedNode; CCNode *m_pobFollowedNode;
// whether camera should be limited to certain area // whether camera should be limited to certain area
bool m_bBoundarySet; bool m_bBoundarySet;
// if screen size is bigger than the boundary - update not needed // if screen size is bigger than the boundary - update not needed
bool m_bBoundaryFullyCovered; bool m_bBoundaryFullyCovered;
// fast access to the screen dimensions // fast access to the screen dimensions
CCPoint m_obHalfScreenSize; CCPoint m_obHalfScreenSize;
CCPoint m_obFullScreenSize; CCPoint m_obFullScreenSize;
// world boundaries // world boundaries
float m_fLeftBoundary; float m_fLeftBoundary;
float m_fRightBoundary; float m_fRightBoundary;
float m_fTopBoundary; float m_fTopBoundary;
float m_fBottomBoundary; float m_fBottomBoundary;
}; };
}//namespace cocos2d
// end of actions group
/// @}
NS_CC_END
#endif // __ACTIONS_CCACTION_H__ #endif // __ACTIONS_CCACTION_H__
 End of changes. 38 change blocks. 
147 lines changed or deleted 165 lines changed or added


 CCActionCamera.h   CCActionCamera.h 
skipping to change at line 28 skipping to change at line 28
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CCCAMERA_ACTION_H__ #ifndef __CCCAMERA_ACTION_H__
#define __CCCAMERA_ACTION_H__ #define __CCCAMERA_ACTION_H__
#include "CCActionInterval.h" #include "CCActionInterval.h"
namespace cocos2d { NS_CC_BEGIN
class CCCamera;
class CCCamera;
/**
* @addtogroup actions
* @{
*/
/**
@brief Base class for CCCamera actions
@ingroup Actions
*/
class CC_DLL CCActionCamera : public CCActionInterval //<NSCopying>
{
public:
CCActionCamera()
:m_fCenterXOrig(0)
,m_fCenterYOrig(0)
,m_fCenterZOrig(0)
,m_fEyeXOrig(0)
,m_fEyeYOrig(0)
,m_fEyeZOrig(0)
,m_fUpXOrig(0)
,m_fUpYOrig(0)
,m_fUpZOrig(0)
{}
virtual ~CCActionCamera(){}
// super methods
virtual void startWithTarget(CCNode *pTarget);
virtual CCActionInterval * reverse();
protected:
float m_fCenterXOrig;
float m_fCenterYOrig;
float m_fCenterZOrig;
float m_fEyeXOrig;
float m_fEyeYOrig;
float m_fEyeZOrig;
float m_fUpXOrig;
float m_fUpYOrig;
float m_fUpZOrig;
};
/**
@brief CCOrbitCamera action
Orbits the camera around the center of the screen using spherical coordinat
es
@ingroup Actions
*/
class CC_DLL CCOrbitCamera : public CCActionCamera //<NSCopying>
{
public:
CCOrbitCamera()
: m_fRadius(0.0)
, m_fDeltaRadius(0.0)
, m_fAngleZ(0.0)
, m_fDeltaAngleZ(0.0)
, m_fAngleX(0.0)
, m_fDeltaAngleX(0.0)
, m_fRadZ(0.0)
, m_fRadDeltaZ(0.0)
, m_fRadX(0.0)
, m_fRadDeltaX(0.0)
{}
~CCOrbitCamera(){}
/** creates a CCOrbitCamera action with radius, delta-radius, z, delta
Z, x, deltaX
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCOrbitCamera* actionWithDuration(float
t, float radius, float deltaRadius, float angleZ, float deltaAngleZ, float
angleX, float deltaAngleX);
/** creates a CCOrbitCamera action with radius, delta-radius, z, delta
Z, x, deltaX */
static CCOrbitCamera* create(float t, float radius, float deltaRadius,
float angleZ, float deltaAngleZ, float angleX, float deltaAngleX);
/** initializes a CCOrbitCamera action with radius, delta-radius, z, d
eltaZ, x, deltaX */
bool initWithDuration(float t, float radius, float deltaRadius, float a
ngleZ, float deltaAngleZ, float angleX, float deltaAngleX);
/** positions the camera according to spherical coordinates */
void sphericalRadius(float *r, float *zenith, float *azimuth);
// super methods
virtual CCObject* copyWithZone(CCZone* pZone);
virtual void startWithTarget(CCNode *pTarget);
virtual void update(float time);
protected:
float m_fRadius;
float m_fDeltaRadius;
float m_fAngleZ;
float m_fDeltaAngleZ;
float m_fAngleX;
float m_fDeltaAngleX;
float m_fRadZ;
float m_fRadDeltaZ;
float m_fRadX;
float m_fRadDeltaX;
};
/** // end of actions group
@brief Base class for CCCamera actions /// @}
*/
class CC_DLL CCActionCamera : public CCActionInterval //<NSCopying>
{
public:
CCActionCamera()
:m_fCenterXOrig(0)
,m_fCenterYOrig(0)
,m_fCenterZOrig(0)
,m_fEyeXOrig(0)
,m_fEyeYOrig(0)
,m_fEyeZOrig(0)
,m_fUpXOrig(0)
,m_fUpYOrig(0)
,m_fUpZOrig(0)
{}
virtual ~CCActionCamera(){}
// super methods
virtual void startWithTarget(CCNode *pTarget);
virtual CCActionInterval * reverse();
protected:
float m_fCenterXOrig;
float m_fCenterYOrig;
float m_fCenterZOrig;
float m_fEyeXOrig;
float m_fEyeYOrig;
float m_fEyeZOrig;
float m_fUpXOrig;
float m_fUpYOrig;
float m_fUpZOrig;
};
/**
@brief CCOrbitCamera action
Orbits the camera around the center of the screen using spherical co
ordinates
*/
class CC_DLL CCOrbitCamera : public CCActionCamera //<NSCopying>
{
public:
CCOrbitCamera()
: m_fRadius(0.0)
, m_fDeltaRadius(0.0)
, m_fAngleZ(0.0)
, m_fDeltaAngleZ(0.0)
, m_fAngleX(0.0)
, m_fDeltaAngleX(0.0)
, m_fRadZ(0.0)
, m_fRadDeltaZ(0.0)
, m_fRadX(0.0)
, m_fRadDeltaX(0.0)
{}
~CCOrbitCamera(){}
/** creates a CCOrbitCamera action with radius, delta-radius
, z, deltaZ, x, deltaX */
static CCOrbitCamera * actionWithDuration(float t, float rad
ius, float deltaRadius, float angleZ, float deltaAngleZ, float angleX, floa
t deltaAngleX);
/** initializes a CCOrbitCamera action with radius, delta-ra
dius, z, deltaZ, x, deltaX */
bool initWithDuration(float t, float radius, float deltaRadi
us, float angleZ, float deltaAngleZ, float angleX, float deltaAngleX);
/** positions the camera according to spherical coordinates
*/
void sphericalRadius(float *r, float *zenith, float *azimuth
);
// super methods
virtual CCObject* copyWithZone(CCZone* pZone);
virtual void startWithTarget(CCNode *pTarget);
virtual void update(ccTime time);
protected:
float m_fRadius;
float m_fDeltaRadius;
float m_fAngleZ;
float m_fDeltaAngleZ;
float m_fAngleX;
float m_fDeltaAngleX;
float m_fRadZ;
float m_fRadDeltaZ;
float m_fRadX;
float m_fRadDeltaX;
};
} // namespace cocos2d NS_CC_END
#endif //__CCCAMERA_ACTION_H__ #endif //__CCCAMERA_ACTION_H__
 End of changes. 4 change blocks. 
90 lines changed or deleted 108 lines changed or added


 CCActionEase.h   CCActionEase.h 
skipping to change at line 31 skipping to change at line 31
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __ACTION_CCEASE_ACTION_H__ #ifndef __ACTION_CCEASE_ACTION_H__
#define __ACTION_CCEASE_ACTION_H__ #define __ACTION_CCEASE_ACTION_H__
#include "CCActionInterval.h" #include "CCActionInterval.h"
namespace cocos2d { NS_CC_BEGIN
class CCObject; class CCObject;
class CCZone; class CCZone;
/** /**
* @addtogroup actions
* @{
*/
/**
@brief Base class for Easing actions @brief Base class for Easing actions
@ingroup Actions
*/ */
class CC_DLL CCActionEase : public CCActionInterval class CC_DLL CCActionEase : public CCActionInterval
{ {
public: public:
virtual ~CCActionEase(void); virtual ~CCActionEase(void);
/** initializes the action */ /** initializes the action */
bool initWithAction(CCActionInterval *pAction); bool initWithAction(CCActionInterval *pAction);
virtual CCObject* copyWithZone(CCZone* pZone); virtual CCObject* copyWithZone(CCZone* pZone);
virtual void startWithTarget(CCNode *pTarget); virtual void startWithTarget(CCNode *pTarget);
virtual void stop(void); virtual void stop(void);
virtual void update(ccTime time); virtual void update(float time);
virtual CCActionInterval* reverse(void); virtual CCActionInterval* reverse(void);
public: public:
/** creates the action */ /** creates the action
static CCActionEase* actionWithAction(CCActionInterval *pAction); @deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCActionEase* actionWithAction(CCActionI
nterval *pAction);
/** creates the action */
static CCActionEase* create(CCActionInterval *pAction);
protected: protected:
CCActionInterval *m_pOther; CCActionInterval *m_pOther;
}; };
/** /**
@brief Base class for Easing actions with rate parameters @brief Base class for Easing actions with rate parameters
@ingroup Actions
*/ */
class CC_DLL CCEaseRateAction : public CCActionEase class CC_DLL CCEaseRateAction : public CCActionEase
{ {
public: public:
virtual ~CCEaseRateAction(void); virtual ~CCEaseRateAction(void);
/** set rate value for the actions */ /** set rate value for the actions */
inline void setRate(float rate) { m_fRate = rate; } inline void setRate(float rate) { m_fRate = rate; }
/** get rate value for the actions */ /** get rate value for the actions */
inline float getRate(void) { return m_fRate; } inline float getRate(void) { return m_fRate; }
/** Initializes the action with the inner action and the rate parame /** Initializes the action with the inner action and the rate parameter
ter */ */
bool initWithAction(CCActionInterval *pAction, float fRate); bool initWithAction(CCActionInterval *pAction, float fRate);
virtual CCObject* copyWithZone(CCZone* pZone); virtual CCObject* copyWithZone(CCZone* pZone);
virtual CCActionInterval* reverse(void); virtual CCActionInterval* reverse(void);
public: public:
/** Creates the action with the inner action and the rate parameter /** Creates the action with the inner action and the rate parameter
*/ @deprecated: This interface will be deprecated sooner or later.
static CCEaseRateAction* actionWithAction(CCActionInterval* pAction, */
float fRate); CC_DEPRECATED_ATTRIBUTE static CCEaseRateAction* actionWithAction(CCAct
ionInterval* pAction, float fRate);
/** Creates the action with the inner action and the rate parameter */
static CCEaseRateAction* create(CCActionInterval* pAction, float fRate)
;
protected: protected:
float m_fRate; float m_fRate;
}; };
/** /**
@brief CCEaseIn action with a rate @brief CCEaseIn action with a rate
@ingroup Actions
*/ */
class CC_DLL CCEaseIn : public CCEaseRateAction class CC_DLL CCEaseIn : public CCEaseRateAction
{ {
public: public:
virtual void update(ccTime time); virtual void update(float time);
virtual CCObject* copyWithZone(CCZone* pZone); virtual CCActionInterval* reverse(void);
public: virtual CCObject* copyWithZone(CCZone* pZone);
/** Creates the action with the inner action and the rate parameter public:
*/ /** Creates the action with the inner action and the rate parameter
static CCEaseIn* actionWithAction(CCActionInterval* pAction, float f @deprecated: This interface will be deprecated sooner or later.
Rate); */
CC_DEPRECATED_ATTRIBUTE static CCEaseIn* actionWithAction(CCActionInter
val* pAction, float fRate);
/** Creates the action with the inner action and the rate parameter */
static CCEaseIn* create(CCActionInterval* pAction, float fRate);
}; };
/** /**
@brief CCEaseOut action with a rate @brief CCEaseOut action with a rate
@ingroup Actions
*/ */
class CC_DLL CCEaseOut : public CCEaseRateAction class CC_DLL CCEaseOut : public CCEaseRateAction
{ {
public: public:
virtual void update(ccTime time); virtual void update(float time);
virtual CCObject* copyWithZone(CCZone* pZone); virtual CCActionInterval* reverse();
virtual CCObject* copyWithZone(CCZone* pZone);
public: public:
/** Creates the action with the inner action and the rate parameter /** Creates the action with the inner action and the rate parameter
*/ @deprecated: This interface will be deprecated sooner or later.
static CCEaseOut* actionWithAction(CCActionInterval* pAction, float fRa */
te); CC_DEPRECATED_ATTRIBUTE static CCEaseOut* actionWithAction(CCActionInte
rval* pAction, float fRate);
/** Creates the action with the inner action and the rate parameter */
static CCEaseOut* create(CCActionInterval* pAction, float fRate);
}; };
/** /**
@brief CCEaseInOut action with a rate @brief CCEaseInOut action with a rate
@ingroup Actions
*/ */
class CC_DLL CCEaseInOut : public CCEaseRateAction class CC_DLL CCEaseInOut : public CCEaseRateAction
{ {
public: public:
virtual void update(ccTime time); virtual void update(float time);
virtual CCObject* copyWithZone(CCZone* pZone); virtual CCObject* copyWithZone(CCZone* pZone);
virtual CCActionInterval* reverse(void); virtual CCActionInterval* reverse(void);
public: public:
/** Creates the action with the inner action and the rate parameter /** Creates the action with the inner action and the rate parameter
*/ @deprecated: This interface will be deprecated sooner or later.
static CCEaseInOut* actionWithAction(CCActionInterval* pAction, floa */
t fRate); CC_DEPRECATED_ATTRIBUTE static CCEaseInOut* actionWithAction(CCActionIn
terval* pAction, float fRate);
/** Creates the action with the inner action and the rate parameter */
static CCEaseInOut* create(CCActionInterval* pAction, float fRate);
}; };
/** /**
@brief CCEase Exponential In @brief CCEase Exponential In
@ingroup Actions
*/ */
class CC_DLL CCEaseExponentialIn : public CCActionEase class CC_DLL CCEaseExponentialIn : public CCActionEase
{ {
public: public:
virtual void update(ccTime time); virtual void update(float time);
virtual CCActionInterval* reverse(void); virtual CCActionInterval* reverse(void);
virtual CCObject* copyWithZone(CCZone* pZone); virtual CCObject* copyWithZone(CCZone* pZone);
public: public:
/** creates the action */ /** creates the action
static CCEaseExponentialIn* actionWithAction(CCActionInterval* pActi @deprecated: This interface will be deprecated sooner or later.
on); */
CC_DEPRECATED_ATTRIBUTE static CCEaseExponentialIn* actionWithAction(CC
ActionInterval* pAction);
/** creates the action */
static CCEaseExponentialIn* create(CCActionInterval* pAction);
}; };
/** /**
@brief Ease Exponential Out @brief Ease Exponential Out
@ingroup Actions
*/ */
class CC_DLL CCEaseExponentialOut : public CCActionEase class CC_DLL CCEaseExponentialOut : public CCActionEase
{ {
public: public:
virtual void update(ccTime time); virtual void update(float time);
virtual CCActionInterval* reverse(void); virtual CCActionInterval* reverse(void);
virtual CCObject* copyWithZone(CCZone* pZone); virtual CCObject* copyWithZone(CCZone* pZone);
public: public:
/** creates the action */ /** creates the action
static CCEaseExponentialOut* actionWithAction(CCActionInterval* pAct @deprecated: This interface will be deprecated sooner or later.
ion); */
CC_DEPRECATED_ATTRIBUTE static CCEaseExponentialOut* actionWithAction(C
CActionInterval* pAction);
/** creates the action */
static CCEaseExponentialOut* create(CCActionInterval* pAction);
}; };
/** /**
@brief Ease Exponential InOut @brief Ease Exponential InOut
@ingroup Actions
*/ */
class CC_DLL CCEaseExponentialInOut : public CCActionEase class CC_DLL CCEaseExponentialInOut : public CCActionEase
{ {
public: public:
virtual void update(ccTime time); virtual void update(float time);
virtual CCObject* copyWithZone(CCZone* pZone); virtual CCObject* copyWithZone(CCZone* pZone);
virtual CCActionInterval* reverse();
public: public:
/** creates the action */ /** creates the action
static CCEaseExponentialInOut* actionWithAction(CCActionInterval* pA @deprecated: This interface will be deprecated sooner or later.
ction); */
CC_DEPRECATED_ATTRIBUTE static CCEaseExponentialInOut* actionWithAction
(CCActionInterval* pAction);
/** creates the action */
static CCEaseExponentialInOut* create(CCActionInterval* pAction);
}; };
/** /**
@brief Ease Sine In @brief Ease Sine In
@ingroup Actions
*/ */
class CC_DLL CCEaseSineIn : public CCActionEase class CC_DLL CCEaseSineIn : public CCActionEase
{ {
public: public:
virtual void update(ccTime time); virtual void update(float time);
virtual CCActionInterval* reverse(void); virtual CCActionInterval* reverse(void);
virtual CCObject* copyWithZone(CCZone* pZone); virtual CCObject* copyWithZone(CCZone* pZone);
public: public:
/** creates the action */ /** creates the action
static CCEaseSineIn* actionWithAction(CCActionInterval* pAction); @deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCEaseSineIn* actionWithAction(CCActionI
nterval* pAction);
/** creates the action */
static CCEaseSineIn* create(CCActionInterval* pAction);
}; };
/** /**
@brief Ease Sine Out @brief Ease Sine Out
@ingroup Actions
*/ */
class CC_DLL CCEaseSineOut : public CCActionEase class CC_DLL CCEaseSineOut : public CCActionEase
{ {
public: public:
virtual void update(ccTime time); virtual void update(float time);
virtual CCActionInterval* reverse(void); virtual CCActionInterval* reverse(void);
virtual CCObject* copyWithZone(CCZone* pZone); virtual CCObject* copyWithZone(CCZone* pZone);
public: public:
/** creates the action */ /** creates the action
static CCEaseSineOut* actionWithAction(CCActionInterval* pAction); @deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCEaseSineOut* actionWithAction(CCAction
Interval* pAction);
/** creates the action */
static CCEaseSineOut* create(CCActionInterval* pAction);
}; };
/** /**
@brief Ease Sine InOut @brief Ease Sine InOut
@ingroup Actions
*/ */
class CC_DLL CCEaseSineInOut : public CCActionEase class CC_DLL CCEaseSineInOut : public CCActionEase
{ {
public: public:
virtual void update(ccTime time); virtual void update(float time);
virtual CCObject* copyWithZone(CCZone* pZone); virtual CCObject* copyWithZone(CCZone* pZone);
virtual CCActionInterval* reverse();
public: public:
/** creates the action */ /** creates the action
static CCEaseSineInOut* actionWithAction(CCActionInterval* pAction); @deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCEaseSineInOut* actionWithAction(CCActi
onInterval* pAction);
/** creates the action */
static CCEaseSineInOut* create(CCActionInterval* pAction);
}; };
/** /**
@brief Ease Elastic abstract class @brief Ease Elastic abstract class
@since v0.8.2 @since v0.8.2
@ingroup Actions
*/ */
class CC_DLL CCEaseElastic : public CCActionEase class CC_DLL CCEaseElastic : public CCActionEase
{ {
public: public:
/** get period of the wave in radians. default is 0.3 */ /** get period of the wave in radians. default is 0.3 */
inline float getPeriod(void) { return m_fPeriod; } inline float getPeriod(void) { return m_fPeriod; }
/** set period of the wave in radians. */ /** set period of the wave in radians. */
inline void setPeriod(float fPeriod) { m_fPeriod = fPeriod; } inline void setPeriod(float fPeriod) { m_fPeriod = fPeriod; }
/** Initializes the action with the inner action and the period in r /** Initializes the action with the inner action and the period in radi
adians (default is 0.3) */ ans (default is 0.3) */
bool initWithAction(CCActionInterval *pAction, float fPeriod); bool initWithAction(CCActionInterval *pAction, float fPeriod = 0.3f);
/** initializes the action */
bool initWithAction(CCActionInterval *pAction); virtual CCActionInterval* reverse(void);
virtual CCObject* copyWithZone(CCZone* pZone);
virtual CCActionInterval* reverse(void);
virtual CCObject* copyWithZone(CCZone* pZone); public:
/** Creates the action with the inner action and the period in radians
public: (default is 0.3)
/** creates the action */ @deprecated: This interface will be deprecated sooner or later.
static CCEaseElastic* actionWithAction(CCActionInterval *pAction); */
/** Creates the action with the inner action and the period in radia CC_DEPRECATED_ATTRIBUTE static CCEaseElastic* actionWithAction(CCAction
ns (default is 0.3) */ Interval *pAction, float fPeriod = 0.3f);
static CCEaseElastic* actionWithAction(CCActionInterval *pAction, fl /** Creates the action with the inner action and the period in radians
oat fPeriod); (default is 0.3) */
static CCEaseElastic* create(CCActionInterval *pAction, float fPeriod =
0.3f);
protected: protected:
float m_fPeriod; float m_fPeriod;
}; };
/** /**
@brief Ease Elastic In action. @brief Ease Elastic In action.
@warning This action doesn't use a bijective fucntion. Actions like Sequen ce might have an unexpected result when used with this action. @warning This action doesn't use a bijective fucntion. Actions like Sequen ce might have an unexpected result when used with this action.
@since v0.8.2 @since v0.8.2
@ingroup Actions
*/ */
class CC_DLL CCEaseElasticIn : public CCEaseElastic class CC_DLL CCEaseElasticIn : public CCEaseElastic
{ {
public: public:
virtual void update(ccTime time); virtual void update(float time);
virtual CCActionInterval* reverse(void); virtual CCActionInterval* reverse(void);
virtual CCObject* copyWithZone(CCZone* pZone); virtual CCObject* copyWithZone(CCZone* pZone);
public: public:
/** creates the action */ /** Creates the action with the inner action and the period in radians
static CCEaseElasticIn* actionWithAction(CCActionInterval *pAction); (default is 0.3)
/** Creates the action with the inner action and the period in radia @deprecated: This interface will be deprecated sooner or later.
ns (default is 0.3) */ */
static CCEaseElasticIn* actionWithAction(CCActionInterval *pAction, CC_DEPRECATED_ATTRIBUTE static CCEaseElasticIn* actionWithAction(CCActi
float fPeriod); onInterval *pAction, float fPeriod = 0.3f);
/** Creates the action with the inner action and the period in radians
(default is 0.3) */
static CCEaseElasticIn* create(CCActionInterval *pAction, float fPeriod
= 0.3f);
}; };
/** /**
@brief Ease Elastic Out action. @brief Ease Elastic Out action.
@warning This action doesn't use a bijective fucntion. Actions like Sequen ce might have an unexpected result when used with this action. @warning This action doesn't use a bijective fucntion. Actions like Sequen ce might have an unexpected result when used with this action.
@since v0.8.2 @since v0.8.2
@ingroup Actions
*/ */
class CC_DLL CCEaseElasticOut : public CCEaseElastic class CC_DLL CCEaseElasticOut : public CCEaseElastic
{ {
public: public:
virtual void update(ccTime time); virtual void update(float time);
virtual CCActionInterval* reverse(void); virtual CCActionInterval* reverse(void);
virtual CCObject* copyWithZone(CCZone* pZone); virtual CCObject* copyWithZone(CCZone* pZone);
public: public:
/** creates the action */ /** Creates the action with the inner action and the period in radians
static CCEaseElasticOut* actionWithAction(CCActionInterval *pAction) (default is 0.3)
; @deprecated: This interface will be deprecated sooner or later.
/** Creates the action with the inner action and the period in radia */
ns (default is 0.3) */ CC_DEPRECATED_ATTRIBUTE static CCEaseElasticOut* actionWithAction(CCAct
static CCEaseElasticOut* actionWithAction(CCActionInterval *pAction, ionInterval *pAction, float fPeriod = 0.3f);
float fPeriod);
/** Creates the action with the inner action and the period in radians
(default is 0.3) */
static CCEaseElasticOut* create(CCActionInterval *pAction, float fPerio
d = 0.3f);
}; };
/** /**
@brief Ease Elastic InOut action. @brief Ease Elastic InOut action.
@warning This action doesn't use a bijective fucntion. Actions like Sequen ce might have an unexpected result when used with this action. @warning This action doesn't use a bijective fucntion. Actions like Sequen ce might have an unexpected result when used with this action.
@since v0.8.2 @since v0.8.2
@ingroup Actions
*/ */
class CC_DLL CCEaseElasticInOut : public CCEaseElastic class CC_DLL CCEaseElasticInOut : public CCEaseElastic
{ {
public: public:
virtual void update(ccTime time); virtual void update(float time);
virtual CCActionInterval* reverse(void); virtual CCActionInterval* reverse(void);
virtual CCObject* copyWithZone(CCZone* pZone); virtual CCObject* copyWithZone(CCZone* pZone);
public: public:
/** creates the action */ /** Creates the action with the inner action and the period in radians
static CCEaseElasticInOut* actionWithAction(CCActionInterval *pActio (default is 0.3)
n); @deprecated: This interface will be deprecated sooner or later.
/** Creates the action with the inner action and the period in radia */
ns (default is 0.3) */ CC_DEPRECATED_ATTRIBUTE static CCEaseElasticInOut* actionWithAction(CCA
static CCEaseElasticInOut* actionWithAction(CCActionInterval *pActio ctionInterval *pAction, float fPeriod = 0.3f);
n, float fPeriod);
/** Creates the action with the inner action and the period in radians
(default is 0.3) */
static CCEaseElasticInOut* create(CCActionInterval *pAction, float fPer
iod = 0.3f);
}; };
/** /**
@brief CCEaseBounce abstract class. @brief CCEaseBounce abstract class.
@since v0.8.2 @since v0.8.2
@ingroup Actions
*/ */
class CC_DLL CCEaseBounce : public CCActionEase class CC_DLL CCEaseBounce : public CCActionEase
{ {
public: public:
ccTime bounceTime(ccTime time); float bounceTime(float time);
virtual CCObject* copyWithZone(CCZone* pZone); virtual CCObject* copyWithZone(CCZone* pZone);
virtual CCActionInterval* reverse();
public: public:
/** creates the action */ /** creates the action
static CCEaseBounce* actionWithAction(CCActionInterval* pAction); @deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCEaseBounce* actionWithAction(CCActionI
nterval* pAction);
/** creates the action */
static CCEaseBounce* create(CCActionInterval* pAction);
}; };
/** /**
@brief CCEaseBounceIn action. @brief CCEaseBounceIn action.
@warning This action doesn't use a bijective function. Actions like Sequen ce might have an unexpected result when used with this action. @warning This action doesn't use a bijective function. Actions like Sequen ce might have an unexpected result when used with this action.
@since v0.8.2 @since v0.8.2
@ingroup Actions
*/ */
class CC_DLL CCEaseBounceIn : public CCEaseBounce class CC_DLL CCEaseBounceIn : public CCEaseBounce
{ {
public: public:
virtual void update(ccTime time); virtual void update(float time);
virtual CCActionInterval* reverse(void); virtual CCActionInterval* reverse(void);
virtual CCObject* copyWithZone(CCZone* pZone); virtual CCObject* copyWithZone(CCZone* pZone);
public: public:
/** creates the action */ /** creates the action
static CCEaseBounceIn* actionWithAction(CCActionInterval* pAction); @deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCEaseBounceIn* actionWithAction(CCActio
nInterval* pAction);
/** creates the action */
static CCEaseBounceIn* create(CCActionInterval* pAction);
}; };
/** /**
@brief EaseBounceOut action. @brief EaseBounceOut action.
@warning This action doesn't use a bijective fucntion. Actions like Sequen ce might have an unexpected result when used with this action. @warning This action doesn't use a bijective fucntion. Actions like Sequen ce might have an unexpected result when used with this action.
@since v0.8.2 @since v0.8.2
@ingroup Actions
*/ */
class CC_DLL CCEaseBounceOut : public CCEaseBounce class CC_DLL CCEaseBounceOut : public CCEaseBounce
{ {
public: public:
virtual void update(ccTime time); virtual void update(float time);
virtual CCActionInterval* reverse(void); virtual CCActionInterval* reverse(void);
virtual CCObject* copyWithZone(CCZone* pZone); virtual CCObject* copyWithZone(CCZone* pZone);
public: public:
/** creates the action */ /** creates the action
static CCEaseBounceOut* actionWithAction(CCActionInterval* pAction); @deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCEaseBounceOut* actionWithAction(CCActi
onInterval* pAction);
/** creates the action */
static CCEaseBounceOut* create(CCActionInterval* pAction);
}; };
/** /**
@brief CCEaseBounceInOut action. @brief CCEaseBounceInOut action.
@warning This action doesn't use a bijective fucntion. Actions like Sequen ce might have an unexpected result when used with this action. @warning This action doesn't use a bijective fucntion. Actions like Sequen ce might have an unexpected result when used with this action.
@since v0.8.2 @since v0.8.2
@ingroup Actions
*/ */
class CC_DLL CCEaseBounceInOut : public CCEaseBounce class CC_DLL CCEaseBounceInOut : public CCEaseBounce
{ {
public: public:
virtual void update(ccTime time); virtual void update(float time);
virtual CCObject* copyWithZone(CCZone* pZone); virtual CCObject* copyWithZone(CCZone* pZone);
virtual CCActionInterval* reverse();
public: public:
/** creates the action */ /** creates the action
static CCEaseBounceInOut* actionWithAction(CCActionInterval* pAction @deprecated: This interface will be deprecated sooner or later.
); */
CC_DEPRECATED_ATTRIBUTE static CCEaseBounceInOut* actionWithAction(CCAc
tionInterval* pAction);
/** creates the action */
static CCEaseBounceInOut* create(CCActionInterval* pAction);
}; };
/** /**
@brief CCEaseBackIn action. @brief CCEaseBackIn action.
@warning This action doesn't use a bijective fucntion. Actions like Sequen ce might have an unexpected result when used with this action. @warning This action doesn't use a bijective fucntion. Actions like Sequen ce might have an unexpected result when used with this action.
@since v0.8.2 @since v0.8.2
@ingroup Actions
*/ */
class CC_DLL CCEaseBackIn : public CCActionEase class CC_DLL CCEaseBackIn : public CCActionEase
{ {
public: public:
virtual void update(ccTime time); virtual void update(float time);
virtual CCActionInterval* reverse(void); virtual CCActionInterval* reverse(void);
virtual CCObject* copyWithZone(CCZone* pZone); virtual CCObject* copyWithZone(CCZone* pZone);
public: public:
/** creates the action */ /** creates the action
static CCEaseBackIn* actionWithAction(CCActionInterval* pAction); @deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCEaseBackIn* actionWithAction(CCActionI
nterval* pAction);
/** creates the action */
static CCEaseBackIn* create(CCActionInterval* pAction);
}; };
/** /**
@brief CCEaseBackOut action. @brief CCEaseBackOut action.
@warning This action doesn't use a bijective fucntion. Actions like Sequen ce might have an unexpected result when used with this action. @warning This action doesn't use a bijective fucntion. Actions like Sequen ce might have an unexpected result when used with this action.
@since v0.8.2 @since v0.8.2
@ingroup Actions
*/ */
class CC_DLL CCEaseBackOut : public CCActionEase class CC_DLL CCEaseBackOut : public CCActionEase
{ {
public: public:
virtual void update(ccTime time); virtual void update(float time);
virtual CCActionInterval* reverse(void); virtual CCActionInterval* reverse(void);
virtual CCObject* copyWithZone(CCZone* pZone); virtual CCObject* copyWithZone(CCZone* pZone);
public: public:
/** creates the action */ /** creates the action
static CCEaseBackOut* actionWithAction(CCActionInterval* pAction); @deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCEaseBackOut* actionWithAction(CCAction
Interval* pAction);
/** creates the action */
static CCEaseBackOut* create(CCActionInterval* pAction);
}; };
/** /**
@brief CCEaseBackInOut action. @brief CCEaseBackInOut action.
@warning This action doesn't use a bijective fucntion. Actions like Sequen ce might have an unexpected result when used with this action. @warning This action doesn't use a bijective fucntion. Actions like Sequen ce might have an unexpected result when used with this action.
@since v0.8.2 @since v0.8.2
@ingroup Actions
*/ */
class CC_DLL CCEaseBackInOut : public CCActionEase class CC_DLL CCEaseBackInOut : public CCActionEase
{ {
public: public:
virtual void update(ccTime time); virtual void update(float time);
virtual CCObject* copyWithZone(CCZone* pZone); virtual CCObject* copyWithZone(CCZone* pZone);
virtual CCActionInterval* reverse();
public: public:
/** creates the action */ /** creates the action
static CCEaseBackInOut* actionWithAction(CCActionInterval* pAction); @deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCEaseBackInOut* actionWithAction(CCActi
onInterval* pAction);
/** creates the action */
static CCEaseBackInOut* create(CCActionInterval* pAction);
}; };
} // end of actions group
/// @}
NS_CC_END
#endif // __ACTION_CCEASE_ACTION_H__ #endif // __ACTION_CCEASE_ACTION_H__
 End of changes. 76 change blocks. 
164 lines changed or deleted 297 lines changed or added


 CCActionGrid.h   CCActionGrid.h 
skipping to change at line 31 skipping to change at line 31
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __ACTION_CCGRID_ACTION_H__ #ifndef __ACTION_CCGRID_ACTION_H__
#define __ACTION_CCGRID_ACTION_H__ #define __ACTION_CCGRID_ACTION_H__
#include "CCActionInterval.h" #include "CCActionInterval.h"
#include "CCActionInstant.h" #include "CCActionInstant.h"
namespace cocos2d NS_CC_BEGIN
class CCGridBase;
/**
* @addtogroup actions
* @{
*/
/** @brief Base class for Grid actions */
class CC_DLL CCGridAction : public CCActionInterval
{
public:
virtual CCObject* copyWithZone(CCZone* pZone);
virtual void startWithTarget(CCNode *pTarget);
virtual CCActionInterval* reverse(void);
/** initializes the action with size and duration */
virtual bool initWithSize(const ccGridSize& gridSize, float duration);
/** returns the grid */
virtual CCGridBase* getGrid(void);
public:
/** creates the action with size and duration
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCGridAction* actionWithSize(const ccGri
dSize& gridSize, float duration);
/** creates the action with size and duration */
static CCGridAction* create(const ccGridSize& gridSize, float duration)
;
protected:
ccGridSize m_sGridSize;
};
/**
@brief Base class for CCGrid3D actions.
Grid3D actions can modify a non-tiled grid.
*/
class CC_DLL CCGrid3DAction : public CCGridAction
{
public:
/** returns the grid */
virtual CCGridBase* getGrid(void);
/** returns the vertex than belongs to certain position in the grid */
ccVertex3F vertex(const ccGridSize& pos);
/** returns the non-transformed vertex than belongs to certain position
in the grid */
ccVertex3F originalVertex(const ccGridSize& pos);
/** sets a new vertex to a certain position of the grid */
void setVertex(const ccGridSize& pos, const ccVertex3F& vertex);
public:
/** creates the action with size and duration
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCGrid3DAction* actionWithSize(const ccG
ridSize& gridSize, float duration);
/** creates the action with size and duration */
static CCGrid3DAction* create(const ccGridSize& gridSize, float duratio
n);
};
/** @brief Base class for CCTiledGrid3D actions */
class CC_DLL CCTiledGrid3DAction : public CCGridAction
{
public:
/** returns the tile that belongs to a certain position of the grid */
ccQuad3 tile(const ccGridSize& pos);
/** returns the non-transformed tile that belongs to a certain position
of the grid */
ccQuad3 originalTile(const ccGridSize& pos);
/** sets a new tile to a certain position of the grid */
void setTile(const ccGridSize& pos, const ccQuad3& coords);
/** returns the grid */
virtual CCGridBase* getGrid(void);
public:
/** creates the action with size and duration
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCTiledGrid3DAction* actionWithSize(cons
t ccGridSize& gridSize, float duration);
/** creates the action with size and duration */
static CCTiledGrid3DAction* create(const ccGridSize& gridSize, float du
ration);
};
/** @brief CCAccelDeccelAmplitude action */
class CC_DLL CCAccelDeccelAmplitude : public CCActionInterval
{
public:
virtual ~CCAccelDeccelAmplitude(void);
/** initializes the action with an inner action that has the amplitude
property, and a duration time */
bool initWithAction(CCAction *pAction, float duration);
virtual void startWithTarget(CCNode *pTarget);
virtual void update(float time);
virtual CCActionInterval* reverse(void);
/** get amplitude rate */
inline float getRate(void) { return m_fRate; }
/** set amplitude rate */
inline void setRate(float fRate) { m_fRate = fRate; }
public:
/** creates the action with an inner action that has the amplitude prop
erty, and a duration time
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCAccelDeccelAmplitude* actionWithAction
(CCAction *pAction, float duration);
/** creates the action with an inner action that has the amplitude prop
erty, and a duration time */
static CCAccelDeccelAmplitude* create(CCAction *pAction, float duration
);
protected:
float m_fRate;
CCActionInterval *m_pOther;
};
/** @brief CCAccelAmplitude action */
class CC_DLL CCAccelAmplitude : public CCActionInterval
{
public:
~CCAccelAmplitude(void);
/** initializes the action with an inner action that has the amplitude
property, and a duration time */
bool initWithAction(CCAction *pAction, float duration);
/** get amplitude rate */
inline float getRate(void) { return m_fRate; }
/** set amplitude rate */
inline void setRate(float fRate) { m_fRate = fRate; }
virtual void startWithTarget(CCNode *pTarget);
virtual void update(float time);
virtual CCActionInterval* reverse(void);
public:
/** creates the action with an inner action that has the amplitude prop
erty, and a duration time
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCAccelAmplitude* actionWithAction(CCAct
ion *pAction, float duration);
/** creates the action with an inner action that has the amplitude prop
erty, and a duration time */
static CCAccelAmplitude* create(CCAction *pAction, float duration);
protected:
float m_fRate;
CCActionInterval *m_pOther;
};
/** @brief CCDeccelAmplitude action */
class CC_DLL CCDeccelAmplitude : public CCActionInterval
{
public:
~CCDeccelAmplitude(void);
/** initializes the action with an inner action that has the amplitude
property, and a duration time */
bool initWithAction(CCAction *pAction, float duration);
/** get amplitude rate */
inline float getRate(void) { return m_fRate; }
/** set amplitude rate */
inline void setRate(float fRate) { m_fRate = fRate; }
virtual void startWithTarget(CCNode *pTarget);
virtual void update(float time);
virtual CCActionInterval* reverse(void);
public:
/** creates the action with an inner action that has the amplitude prop
erty, and a duration time
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCDeccelAmplitude* actionWithAction(CCAc
tion *pAction, float duration);
/** creates the action with an inner action that has the amplitude prop
erty, and a duration time */
static CCDeccelAmplitude* create(CCAction *pAction, float duration);
protected:
float m_fRate;
CCActionInterval *m_pOther;
};
/** @brief CCStopGrid action.
@warning Don't call this action if another grid action is active.
Call if you want to remove the the grid effect. Example:
CCSequence::actions(Lens::action(...), CCStopGrid::action(...), NULL);
*/
class CC_DLL CCStopGrid : public CCActionInstant
{
public:
virtual void startWithTarget(CCNode *pTarget);
public:
/** Allocates and initializes the action
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCStopGrid* action(void);
/** Allocates and initializes the action */
static CCStopGrid* create(void);
};
/** @brief CCReuseGrid action */
class CC_DLL CCReuseGrid : public CCActionInstant
{ {
class CCGridBase; public:
/** initializes an action with the number of times that the current gri
d will be reused */
bool initWithTimes(int times);
virtual void startWithTarget(CCNode *pTarget);
public:
/** creates an action with the number of times that the current grid wi
ll be reused
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCReuseGrid* actionWithTimes(int times);
/** creates an action with the number of times that the current grid wi
ll be reused */
static CCReuseGrid* create(int times);
protected:
int m_nTimes;
};
/** @brief Base class for Grid actions */ // end of actions group
class CC_DLL CCGridAction : public CCActionInterval /// @}
{
public:
virtual CCObject* copyWithZone(CCZone* pZone);
virtual void startWithTarget(CCNode *pTarget);
virtual CCActionInterval* reverse(void);
/** initializes the action with size and duration */
virtual bool initWithSize(const ccGridSize& gridSize, ccTime
duration);
/** returns the grid */
virtual CCGridBase* getGrid(void);
public:
/** creates the action with size and duration */
static CCGridAction* actionWithSize(const ccGridSize& gridSi
ze, ccTime duration);
protected:
ccGridSize m_sGridSize;
};
/**
@brief Base class for CCGrid3D actions.
Grid3D actions can modify a non-tiled grid.
*/
class CC_DLL CCGrid3DAction : public CCGridAction
{
public:
/** returns the grid */
virtual CCGridBase* getGrid(void);
/** returns the vertex than belongs to certain position in t
he grid */
ccVertex3F vertex(const ccGridSize& pos);
/** returns the non-transformed vertex than belongs to certa
in position in the grid */
ccVertex3F originalVertex(const ccGridSize& pos);
/** sets a new vertex to a certain position of the grid */
void setVertex(const ccGridSize& pos, const ccVertex3F& vert
ex);
public:
/** creates the action with size and duration */
static CCGrid3DAction* actionWithSize(const ccGridSize& gridSize, c
cTime duration);
};
/** @brief Base class for CCTiledGrid3D actions */
class CC_DLL CCTiledGrid3DAction : public CCGridAction
{
public:
/** returns the tile that belongs to a certain position of t
he grid */
ccQuad3 tile(const ccGridSize& pos);
/** returns the non-transformed tile that belongs to a certa
in position of the grid */
ccQuad3 originalTile(const ccGridSize& pos);
/** sets a new tile to a certain position of the grid */
void setTile(const ccGridSize& pos, const ccQuad3& coords);
/** returns the grid */
virtual CCGridBase* getGrid(void);
public:
/** creates the action with size and duration */
static CCTiledGrid3DAction* actionWithSize(const ccGridSize& gridSi
ze, ccTime duration);
};
/** @brief CCAccelDeccelAmplitude action */
class CC_DLL CCAccelDeccelAmplitude : public CCActionInterval
{
public:
virtual ~CCAccelDeccelAmplitude(void);
/** initializes the action with an inner action that has the
amplitude property, and a duration time */
bool initWithAction(CCAction *pAction, ccTime duration);
virtual void startWithTarget(CCNode *pTarget);
virtual void update(ccTime time);
virtual CCActionInterval* reverse(void);
/** get amplitude rate */
inline float getRate(void) { return m_fRate; }
/** set amplitude rate */
inline void setRate(float fRate) { m_fRate = fRate; }
public:
/** creates the action with an inner action that has the amp
litude property, and a duration time */
static CCAccelDeccelAmplitude* actionWithAction(CCAction *pA
ction, ccTime duration);
protected:
float m_fRate;
CCActionInterval *m_pOther;
};
/** @brief CCAccelAmplitude action */
class CC_DLL CCAccelAmplitude : public CCActionInterval
{
public:
~CCAccelAmplitude(void);
/** initializes the action with an inner action that has the
amplitude property, and a duration time */
bool initWithAction(CCAction *pAction, ccTime duration);
/** get amplitude rate */
inline float getRate(void) { return m_fRate; }
/** set amplitude rate */
inline void setRate(float fRate) { m_fRate = fRate; }
virtual void startWithTarget(CCNode *pTarget);
virtual void update(ccTime time);
virtual CCActionInterval* reverse(void);
public:
/** creates the action with an inner action that has the amp
litude property, and a duration time */
static CCAccelAmplitude* actionWithAction(CCAction *pAction,
ccTime duration);
protected:
float m_fRate;
CCActionInterval *m_pOther;
};
/** @brief CCDeccelAmplitude action */
class CC_DLL CCDeccelAmplitude : public CCActionInterval
{
public:
~CCDeccelAmplitude(void);
/** initializes the action with an inner action that has the
amplitude property, and a duration time */
bool initWithAction(CCAction *pAction, ccTime duration);
/** get amplitude rate */
inline float getRate(void) { return m_fRate; }
/** set amplitude rate */
inline void setRate(float fRate) { m_fRate = fRate; }
virtual void startWithTarget(CCNode *pTarget);
virtual void update(ccTime time);
virtual CCActionInterval* reverse(void);
public:
/** creates the action with an inner action that has the amp
litude property, and a duration time */
static CCDeccelAmplitude* actionWithAction(CCAction *pAction, ccTim
e duration);
protected:
float m_fRate;
CCActionInterval *m_pOther;
};
/** @brief CCStopGrid action.
@warning Don't call this action if another grid action is active.
Call if you want to remove the the grid effect. Example:
CCSequence::actions(Lens::action(...), CCStopGrid::action(...), NUL
L);
*/
class CC_DLL CCStopGrid : public CCActionInstant
{
public:
virtual void startWithTarget(CCNode *pTarget);
public:
/** Allocates and initializes the action */
static CCStopGrid* action(void);
};
/** @brief CCReuseGrid action */
class CC_DLL CCReuseGrid : public CCActionInstant
{
public:
/** initializes an action with the number of times that the
current grid will be reused */
bool initWithTimes(int times);
virtual void startWithTarget(CCNode *pTarget);
public:
/** creates an action with the number of times that the curr
ent grid will be reused */
static CCReuseGrid* actionWithTimes(int times);
protected:
int m_nTimes;
};
} // end of namespace cocos2d NS_CC_END
#endif // __ACTION_CCGRID_ACTION_H__ #endif // __ACTION_CCGRID_ACTION_H__
 End of changes. 4 change blocks. 
194 lines changed or deleted 234 lines changed or added


 CCActionGrid3D.h   CCActionGrid3D.h 
/************************************************************************** ** /************************************************************************** **
Copyright (c) 2010-2011 cocos2d-x.org Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2009 On-Core Copyright (c) 2009 On-Core
http://www.cocos2d-x.org http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a cop y Permission is hereby granted, free of charge, to any person obtaining a cop y
of this software and associated documentation files (the "Software"), to de al of this software and associated documentation files (the "Software"), to de al
in the Software without restriction, including without limitation the right s in the Software without restriction, including without limitation the right s
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
skipping to change at line 30 skipping to change at line 30
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __ACTION_CCGRID3D_ACTION_H__ #ifndef __ACTION_CCGRID3D_ACTION_H__
#define __ACTION_CCGRID3D_ACTION_H__ #define __ACTION_CCGRID3D_ACTION_H__
#include "CCActionGrid.h" #include "CCActionGrid.h"
namespace cocos2d NS_CC_BEGIN
/**
* @addtogroup actions
* @{
*/
/**
@brief CCWaves3D action
*/
class CC_DLL CCWaves3D : public CCGrid3DAction
{
public:
inline float getAmplitude(void) { return m_fAmplitude; }
inline void setAmplitude(float fAmplitude) { m_fAmplitude = fAmplitude;
}
inline float getAmplitudeRate(void) { return m_fAmplitudeRate; }
inline void setAmplitudeRate(float fAmplitudeRate) { m_fAmplitudeRate =
fAmplitudeRate; }
/** init the action */
bool initWithWaves(int wav, float amp, const ccGridSize& gridSize, floa
t duration);
virtual CCObject* copyWithZone(CCZone* pZone);
virtual void update(float time);
public:
/** create the action
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCWaves3D* actionWithWaves(int wav, floa
t amp, const ccGridSize& gridSize, float duration);
/** create the action */
static CCWaves3D* create(int wav, float amp, const ccGridSize& gridSize
, float duration);
protected:
int m_nWaves;
float m_fAmplitude;
float m_fAmplitudeRate;
};
/** @brief CCFlipX3D action */
class CC_DLL CCFlipX3D : public CCGrid3DAction
{
public:
/** initializes the action with duration */
bool initWithDuration(float duration);
virtual bool initWithSize(const ccGridSize& gridSize, float duration);
virtual CCObject* copyWithZone(CCZone* pZone);
virtual void update(float time);
public:
/** creates the action with duration
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCFlipX3D* actionWithDuration(float dura
tion);
/** creates the action with duration */
static CCFlipX3D* create(float duration);
};
/** @brief CCFlipY3D action */
class CC_DLL CCFlipY3D : public CCFlipX3D
{
public:
virtual void update(float time);
virtual CCObject* copyWithZone(CCZone* pZone);
public:
/** creates the action with duration
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCFlipY3D* actionWithDuration(float dura
tion);
/** creates the action with duration */
static CCFlipY3D* create(float duration);
};
/** @brief CCLens3D action */
class CC_DLL CCLens3D : public CCGrid3DAction
{
public:
/** Get lens center position */
inline float getLensEffect(void) { return m_fLensEffect; }
/** Set lens center position */
inline void setLensEffect(float fLensEffect) { m_fLensEffect = fLensEff
ect; }
inline const CCPoint& getPosition(void) { return m_position; }
void setPosition(const CCPoint& position);
/** initializes the action with center position, radius, a grid size an
d duration */
bool initWithPosition(const CCPoint& pos, float r, const ccGridSize& gr
idSize, float duration);
virtual CCObject* copyWithZone(CCZone* pZone);
virtual void update(float time);
public:
/** creates the action with center position, radius, a grid size and du
ration
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCLens3D* actionWithPosition(const CCPoi
nt& pos, float r, const ccGridSize& gridSize, float duration);
/** creates the action with center position, radius, a grid size and du
ration */
static CCLens3D* create(const CCPoint& pos, float r, const ccGridSize&
gridSize, float duration);
protected:
/* lens center position */
CCPoint m_position;
float m_fRadius;
/** lens effect. Defaults to 0.7 - 0 means no effect, 1 is very strong
effect */
float m_fLensEffect;
bool m_bDirty;
};
/** @brief CCRipple3D action */
class CC_DLL CCRipple3D : public CCGrid3DAction
{ {
/** public:
@brief CCWaves3D action /** get center position */
*/ inline const CCPoint& getPosition(void) { return m_position; }
class CC_DLL CCWaves3D : public CCGrid3DAction /** set center position */
{ void setPosition(const CCPoint& position);
public:
inline float getAmplitude(void) { return m_fAmplitude; } inline float getAmplitude(void) { return m_fAmplitude; }
inline void setAmplitude(float fAmplitude) { m_fAmplitude = inline void setAmplitude(float fAmplitude) { m_fAmplitude = fAmplitude;
fAmplitude; } }
inline float getAmplitudeRate(void) { return m_fAmplitudeRat inline float getAmplitudeRate(void) { return m_fAmplitudeRate; }
e; } inline void setAmplitudeRate(float fAmplitudeRate) { m_fAmplitudeRate =
inline void setAmplitudeRate(float fAmplitudeRate) { m_fAmpl fAmplitudeRate; }
itudeRate = fAmplitudeRate; }
/** initializes the action with radius, number of waves, amplitude, a g
/** init the action */ rid size and duration */
bool initWithWaves(int wav, float amp, const ccGridSize& gri bool initWithPosition(const CCPoint& pos, float r, int wav, float amp,
dSize, ccTime duration); const ccGridSize& gridSize, float duration);
virtual CCObject* copyWithZone(CCZone* pZone);
virtual CCObject* copyWithZone(CCZone* pZone); virtual void update(float time);
virtual void update(ccTime time);
public:
public: /** creates the action with radius, number of waves, amplitude, a grid
/** create the action */ size and duration
static CCWaves3D* actionWithWaves(int wav, float amp, const @deprecated: This interface will be deprecated sooner or later.
ccGridSize& gridSize, ccTime duration); */
CC_DEPRECATED_ATTRIBUTE static CCRipple3D* actionWithPosition(const CCP
protected: oint& pos, float r, int wav, float amp,
int m_nWaves; const ccGridSize& gridSize, float duration);
float m_fAmplitude; /** creates the action with radius, number of waves, amplitude, a grid
float m_fAmplitudeRate; size and duration */
}; static CCRipple3D* create(const CCPoint& pos, float r, int wav, float a
mp,
/** @brief CCFlipX3D action */ const ccGridSize& gridSize, float duration);
class CC_DLL CCFlipX3D : public CCGrid3DAction protected:
{ /* center position */
public: CCPoint m_position;
/** initializes the action with duration */ float m_fRadius;
bool initWithDuration(ccTime duration); int m_nWaves;
virtual bool initWithSize(const ccGridSize& gridSize, ccTime float m_fAmplitude;
duration); float m_fAmplitudeRate;
virtual CCObject* copyWithZone(CCZone* pZone); };
virtual void update(ccTime time);
/** @brief CCShaky3D action */
public: class CC_DLL CCShaky3D : public CCGrid3DAction
/** creates the action with duration */ {
static CCFlipX3D* actionWithDuration(ccTime duration); public:
}; /** initializes the action with a range, shake Z vertices, a grid and d
uration */
/** @brief CCFlipY3D action */ bool initWithRange(int range, bool shakeZ, const ccGridSize& gridSize,
class CC_DLL CCFlipY3D : public CCFlipX3D float duration);
{ virtual CCObject* copyWithZone(CCZone* pZone);
public: virtual void update(float time);
virtual void update(ccTime time);
virtual CCObject* copyWithZone(CCZone* pZone); public:
/** creates the action with a range, shake Z vertices, a grid and durat
public: ion
/** creates the action with duration */ @deprecated: This interface will be deprecated sooner or later.
static CCFlipY3D* actionWithDuration(ccTime duration); */
}; CC_DEPRECATED_ATTRIBUTE static CCShaky3D* actionWithRange(int range, bo
ol shakeZ, const ccGridSize& gridSize, float duration);
/** @brief CCLens3D action */ /** creates the action with a range, shake Z vertices, a grid and durat
class CC_DLL CCLens3D : public CCGrid3DAction ion */
{ static CCShaky3D* create(int range, bool shakeZ, const ccGridSize& grid
public: Size, float duration);
/** Get lens center position */ protected:
inline float getLensEffect(void) { return m_fLensEffect; } int m_nRandrange;
/** Set lens center position */ bool m_bShakeZ;
inline void setLensEffect(float fLensEffect) { m_fLensEffect };
= fLensEffect; }
/** @brief CCLiquid action */
inline const CCPoint& getPosition(void) { return m_position; class CC_DLL CCLiquid : public CCGrid3DAction
} {
void setPosition(const CCPoint& position); public:
inline float getAmplitude(void) { return m_fAmplitude; }
/** initializes the action with center position, radius, a g inline void setAmplitude(float fAmplitude) { m_fAmplitude = fAmplitude;
rid size and duration */ }
bool initWithPosition(const CCPoint& pos, float r, const ccG
ridSize& gridSize, ccTime duration); inline float getAmplitudeRate(void) { return m_fAmplitudeRate; }
virtual CCObject* copyWithZone(CCZone* pZone); inline void setAmplitudeRate(float fAmplitudeRate) { m_fAmplitudeRate =
virtual void update(ccTime time); fAmplitudeRate; }
public: /** initializes the action with amplitude, a grid and duration */
/** creates the action with center position, radius, a grid bool initWithWaves(int wav, float amp, const ccGridSize& gridSize, floa
size and duration */ t duration);
static CCLens3D* actionWithPosition(const CCPoint& pos, float r, co virtual CCObject* copyWithZone(CCZone* pZone);
nst ccGridSize& gridSize, ccTime duration); virtual void update(float time);
protected:
/* lens center position */ public:
CCPoint m_position; /** creates the action with amplitude, a grid and duration
float m_fRadius; @deprecated: This interface will be deprecated sooner or later.
/** lens effect. Defaults to 0.7 - 0 means no effect, 1 is v */
ery strong effect */ CC_DEPRECATED_ATTRIBUTE static CCLiquid* actionWithWaves(int wav, float
float m_fLensEffect; amp, const ccGridSize& gridSize, float duration);
/** creates the action with amplitude, a grid and duration */
/* @since v0.99.5 */ static CCLiquid* create(int wav, float amp, const ccGridSize& gridSize,
// CCPoint m_lastPosition; float duration);
CCPoint m_positionInPixels; protected:
bool m_bDirty; int m_nWaves;
}; float m_fAmplitude;
float m_fAmplitudeRate;
/** @brief CCRipple3D action */ };
class CC_DLL CCRipple3D : public CCGrid3DAction
{ /** @brief CCWaves action */
public: class CC_DLL CCWaves : public CCGrid3DAction
/** get center position */ {
inline const CCPoint& getPosition(void) { return m_position; public:
} inline float getAmplitude(void) { return m_fAmplitude; }
/** set center position */ inline void setAmplitude(float fAmplitude) { m_fAmplitude = fAmplitude;
void setPosition(const CCPoint& position); }
inline float getAmplitude(void) { return m_fAmplitude; } inline float getAmplitudeRate(void) { return m_fAmplitudeRate; }
inline void setAmplitude(float fAmplitude) { m_fAmplitude = inline void setAmplitudeRate(float fAmplitudeRate) { m_fAmplitudeRate =
fAmplitude; } fAmplitudeRate; }
inline float getAmplitudeRate(void) { return m_fAmplitudeRat /** initializes the action with amplitude, horizontal sin, vertical sin
e; } , a grid and duration */
inline void setAmplitudeRate(float fAmplitudeRate) { m_fAmpl bool initWithWaves(int wav, float amp, bool h, bool v, const ccGridSize
itudeRate = fAmplitudeRate; } & gridSize,
float duration);
/** initializes the action with radius, number of waves, amp virtual CCObject* copyWithZone(CCZone* pZone);
litude, a grid size and duration */ virtual void update(float time);
bool initWithPosition(const CCPoint& pos, float r, int wav,
float amp, public:
const ccGridSize& gridSize, ccTime duration); /** initializes the action with amplitude, horizontal sin, vertical sin
virtual CCObject* copyWithZone(CCZone* pZone); , a grid and duration
virtual void update(ccTime time); @deprecated: This interface will be deprecated sooner or later.
*/
public: CC_DEPRECATED_ATTRIBUTE static CCWaves* actionWithWaves(int wav, float
/** creates the action with radius, number of waves, amplitu amp, bool h, bool v, const ccGridSize& gridSize,
de, a grid size and duration */ float duration);
static CCRipple3D* actionWithPosition(const CCPoint& pos, fl
oat r, int wav, float amp, /** initializes the action with amplitude, horizontal sin, vertical sin
const ccGridSize& gridSize, ccTime duration); , a grid and duration */
protected: static CCWaves* create(int wav, float amp, bool h, bool v, const ccGrid
/* center position */ Size& gridSize,
CCPoint m_position; float duration);
float m_fRadius; protected:
int m_nWaves; int m_nWaves;
float m_fAmplitude; float m_fAmplitude;
float m_fAmplitudeRate; float m_fAmplitudeRate;
bool m_bVertical;
/*@since v0.99.5*/ bool m_bHorizontal;
CCPoint m_positionInPixels; };
};
/** @brief CCTwirl action */
/** @brief CCShaky3D action */ class CC_DLL CCTwirl : public CCGrid3DAction
class CC_DLL CCShaky3D : public CCGrid3DAction {
{ public:
public: /** get twirl center */
/** initializes the action with a range, shake Z vertices, a inline const CCPoint& getPosition(void) { return m_position; }
grid and duration */ /** set twirl center */
bool initWithRange(int range, bool shakeZ, const ccGridSize& void setPosition(const CCPoint& position);
gridSize, ccTime duration);
virtual CCObject* copyWithZone(CCZone* pZone); inline float getAmplitude(void) { return m_fAmplitude; }
virtual void update(ccTime time); inline void setAmplitude(float fAmplitude) { m_fAmplitude = fAmplitude;
}
public:
/** creates the action with a range, shake Z vertices, a gri inline float getAmplitudeRate(void) { return m_fAmplitudeRate; }
d and duration */ inline void setAmplitudeRate(float fAmplitudeRate) { m_fAmplitudeRate =
static CCShaky3D* actionWithRange(int range, bool shakeZ, const ccG fAmplitudeRate; }
ridSize& gridSize, ccTime duration);
/** initializes the action with center position, number of twirls, ampl
protected: itude, a grid size and duration */
int m_nRandrange; bool initWithPosition(const CCPoint& pos, int t, float amp, const ccGri
bool m_bShakeZ; dSize& gridSize,
}; float duration);
virtual CCObject* copyWithZone(CCZone* pZone);
/** @brief CCLiquid action */ virtual void update(float time);
class CC_DLL CCLiquid : public CCGrid3DAction
{ public:
public: /** creates the action with center position, number of twirls, amplitud
inline float getAmplitude(void) { return m_fAmplitude; } e, a grid size and duration
inline void setAmplitude(float fAmplitude) { m_fAmplitude = @deprecated: This interface will be deprecated sooner or later.
fAmplitude; } */
CC_DEPRECATED_ATTRIBUTE static CCTwirl* actionWithPosition(CCPoint pos,
inline float getAmplitudeRate(void) { return m_fAmplitudeRat int t, float amp, const ccGridSize& gridSize,
e; } float duration);
inline void setAmplitudeRate(float fAmplitudeRate) { m_fAmpl
itudeRate = fAmplitudeRate; } /** creates the action with center position, number of twirls, amplitud
e, a grid size and duration */
/** initializes the action with amplitude, a grid and durati static CCTwirl* create(CCPoint pos, int t, float amp, const ccGridSize&
on */ gridSize,
bool initWithWaves(int wav, float amp, const ccGridSize& gri float duration);
dSize, ccTime duration); protected:
virtual CCObject* copyWithZone(CCZone* pZone); /* twirl center */
virtual void update(ccTime time); CCPoint m_position;
int m_nTwirls;
public: float m_fAmplitude;
/** creates the action with amplitude, a grid and duration * float m_fAmplitudeRate;
/ };
static CCLiquid* actionWithWaves(int wav, float amp, const c
cGridSize& gridSize, ccTime duration); // end of actions group
/// @}
protected:
int m_nWaves; NS_CC_END
float m_fAmplitude;
float m_fAmplitudeRate;
};
/** @brief CCWaves action */
class CC_DLL CCWaves : public CCGrid3DAction
{
public:
inline float getAmplitude(void) { return m_fAmplitude; }
inline void setAmplitude(float fAmplitude) { m_fAmplitude =
fAmplitude; }
inline float getAmplitudeRate(void) { return m_fAmplitudeRat
e; }
inline void setAmplitudeRate(float fAmplitudeRate) { m_fAmpl
itudeRate = fAmplitudeRate; }
/** initializes the action with amplitude, horizontal sin, v
ertical sin, a grid and duration */
bool initWithWaves(int wav, float amp, bool h, bool v, const
ccGridSize& gridSize,
ccTime duration);
virtual CCObject* copyWithZone(CCZone* pZone);
virtual void update(ccTime time);
public:
/** initializes the action with amplitude, horizontal sin, v
ertical sin, a grid and duration */
static CCWaves* actionWithWaves(int wav, float amp, bool h, bool v,
const ccGridSize& gridSize,
ccTime duration);
protected:
int m_nWaves;
float m_fAmplitude;
float m_fAmplitudeRate;
bool m_bVertical;
bool m_bHorizontal;
};
/** @brief CCTwirl action */
class CC_DLL CCTwirl : public CCGrid3DAction
{
public:
/** get twirl center */
inline const CCPoint& getPosition(void) { return m_position;
}
/** set twirl center */
void setPosition(const CCPoint& position);
inline float getAmplitude(void) { return m_fAmplitude; }
inline void setAmplitude(float fAmplitude) { m_fAmplitude =
fAmplitude; }
inline float getAmplitudeRate(void) { return m_fAmplitudeRat
e; }
inline void setAmplitudeRate(float fAmplitudeRate) { m_fAmpl
itudeRate = fAmplitudeRate; }
/** initializes the action with center position, number of t
wirls, amplitude, a grid size and duration */
bool initWithPosition(const CCPoint& pos, int t, float amp,
const ccGridSize& gridSize,
ccTime duration);
virtual CCObject* copyWithZone(CCZone* pZone);
virtual void update(ccTime time);
public:
/** creates the action with center position, number of twirl
s, amplitude, a grid size and duration */
static CCTwirl* actionWithPosition(CCPoint pos, int t, float
amp, const ccGridSize& gridSize,
ccTime duration);
protected:
/* twirl center */
CCPoint m_position;
int m_nTwirls;
float m_fAmplitude;
float m_fAmplitudeRate;
/*@since v0.99.5 */
CCPoint m_positionInPixels;
};
}
#endif // __ACTION_CCGRID3D_ACTION_H__ #endif // __ACTION_CCGRID3D_ACTION_H__
 End of changes. 3 change blocks. 
281 lines changed or deleted 321 lines changed or added


 CCActionInstant.h   CCActionInstant.h 
/************************************************************************** ** /************************************************************************** **
Copyright (c) 2010-2011 cocos2d-x.org Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011 Zynga Inc. Copyright (c) 2011 Zynga Inc.
http://www.cocos2d-x.org http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a cop y Permission is hereby granted, free of charge, to any person obtaining a cop y
of this software and associated documentation files (the "Software"), to de al of this software and associated documentation files (the "Software"), to de al
in the Software without restriction, including without limitation the right s in the Software without restriction, including without limitation the right s
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
skipping to change at line 33 skipping to change at line 33
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CCINSTANT_ACTION_H__ #ifndef __CCINSTANT_ACTION_H__
#define __CCINSTANT_ACTION_H__ #define __CCINSTANT_ACTION_H__
#include <string> #include <string>
#include "CCAction.h" #include "CCAction.h"
namespace cocos2d { NS_CC_BEGIN
/** /**
@brief Instant actions are immediate actions. They don't have a dura * @addtogroup actions
tion like * @{
the CCIntervalAction actions. */
*/
class CC_DLL CCActionInstant : public CCFiniteTimeAction //<NSCopyin /**
g> @brief Instant actions are immediate actions. They don't have a duration li
{ ke
public: the CCIntervalAction actions.
CCActionInstant(); */
virtual ~CCActionInstant(){} class CC_DLL CCActionInstant : public CCFiniteTimeAction //<NSCopying>
// CCAction methods {
virtual CCObject* copyWithZone(CCZone *pZone); public:
virtual bool isDone(void); CCActionInstant();
virtual void step(ccTime dt); virtual ~CCActionInstant(){}
virtual void update(ccTime time); // CCAction methods
//CCFiniteTimeAction method virtual CCObject* copyWithZone(CCZone *pZone);
virtual CCFiniteTimeAction * reverse(void); virtual bool isDone(void);
}; virtual void step(float dt);
virtual void update(float time);
/** @brief Show the node //CCFiniteTimeAction method
*/ virtual CCFiniteTimeAction * reverse(void);
class CC_DLL CCShow : public CCActionInstant };
{
public: /** @brief Show the node
CCShow(){} */
virtual ~CCShow(){} class CC_DLL CCShow : public CCActionInstant
//super methods {
virtual void startWithTarget(CCNode *pTarget); public:
virtual CCFiniteTimeAction * reverse(void); CCShow(){}
virtual CCObject* copyWithZone(CCZone *pZone); virtual ~CCShow(){}
public: //super methods
//override static method virtual void update(float time);
/** Allocates and initializes the action */ virtual CCFiniteTimeAction * reverse(void);
static CCShow * action(); virtual CCObject* copyWithZone(CCZone *pZone);
}; public:
//override static method
/** /** Allocates and initializes the action
@brief Hide the node @deprecated: This interface will be deprecated sooner or later.
*/ */
class CC_DLL CCHide : public CCActionInstant CC_DEPRECATED_ATTRIBUTE static CCShow * action();
{
public:
CCHide(){}
virtual ~CCHide(){}
//super methods
virtual void startWithTarget(CCNode *pTarget);
virtual CCFiniteTimeAction * reverse(void);
virtual CCObject* copyWithZone(CCZone *pZone);
public:
//override static method
/** Allocates and initializes the action */
static CCHide * action();
};
/** @brief Toggles the visibility of a node
*/
class CC_DLL CCToggleVisibility : public CCActionInstant
{
public:
CCToggleVisibility(){}
virtual ~CCToggleVisibility(){}
//super method
virtual void startWithTarget(CCNode *pTarget);
public:
//override static method
/** Allocates and initializes the action */
static CCToggleVisibility * action();
};
/**
@brief Flips the sprite horizontally
@since v0.99.0
*/
class CC_DLL CCFlipX : public CCActionInstant
{
public:
CCFlipX()
:m_bFlipX(false)
{}
virtual ~CCFlipX(){}
/** create the action */
static CCFlipX * actionWithFlipX(bool x);
/** init the action */
bool initWithFlipX(bool x);
//super methods
virtual void startWithTarget(CCNode *pTarget);
virtual CCFiniteTimeAction * reverse(void);
virtual CCObject* copyWithZone(CCZone *pZone);
protected:
bool m_bFlipX;
};
/**
@brief Flips the sprite vertically
@since v0.99.0
*/
class CC_DLL CCFlipY : public CCActionInstant
{
public:
CCFlipY()
:m_bFlipY(false)
{}
virtual ~CCFlipY(){}
/** create the action */
static CCFlipY * actionWithFlipY(bool y);
/** init the action */
bool initWithFlipY(bool y);
//super methods
virtual void startWithTarget(CCNode *pTarget);
virtual CCFiniteTimeAction * reverse(void);
virtual CCObject* copyWithZone(CCZone *pZone);
protected:
bool m_bFlipY;
};
/** @brief Places the node in a certain position
*/
class CC_DLL CCPlace : public CCActionInstant //<NSCopying>
{
public:
CCPlace(){}
virtual ~CCPlace(){}
/** creates a Place action with a position */
static CCPlace * actionWithPosition(const CCPoint& pos);
/** Initializes a Place action with a position */
bool initWithPosition(const CCPoint& pos);
//super methods
virtual void startWithTarget(CCNode *pTarget);
virtual CCObject* copyWithZone(CCZone *pZone);
protected:
CCPoint m_tPosition;
};
/** @brief Calls a 'callback'
*/
class CC_DLL CCCallFunc : public CCActionInstant //<NSCopying>
{
public:
CCCallFunc()
: m_pSelectorTarget(NULL)
, m_pCallFunc(NULL)
{ /** Allocates and initializes the action */
} static CCShow * create();
virtual ~CCCallFunc() };
{
if (m_pSelectorTarget) /**
{ @brief Hide the node
m_pSelectorTarget->release(); */
} class CC_DLL CCHide : public CCActionInstant
} {
/** creates the action with the callback public:
CCHide(){}
typedef void (CCObject::*SEL_CallFunc)(); virtual ~CCHide(){}
*/ //super methods
static CCCallFunc * actionWithTarget(CCObject* pSelectorTarg virtual void update(float time);
et, SEL_CallFunc selector); virtual CCFiniteTimeAction * reverse(void);
/** initializes the action with the callback virtual CCObject* copyWithZone(CCZone *pZone);
public:
typedef void (CCObject::*SEL_CallFunc)(); //override static method
*/ /** Allocates and initializes the action
virtual bool initWithTarget(CCObject* pSelectorTarget); @deprecated: This interface will be deprecated sooner or later.
/** executes the callback */ */
virtual void execute(); CC_DEPRECATED_ATTRIBUTE static CCHide * action();
//super methods
virtual void startWithTarget(CCNode *pTarget); /** Allocates and initializes the action */
CCObject * copyWithZone(CCZone *pZone); static CCHide * create();
};
inline CCObject* getTargetCallback()
{ /** @brief Toggles the visibility of a node
return m_pSelectorTarget; */
} class CC_DLL CCToggleVisibility : public CCActionInstant
{
inline void setTargetCallback(CCObject* pSel) public:
{ CCToggleVisibility(){}
if (pSel != m_pSelectorTarget) virtual ~CCToggleVisibility(){}
{ //super method
if (m_pSelectorTarget) virtual void update(float time);
{ virtual CCObject* copyWithZone(CCZone *pZone);
m_pSelectorTarget->release(); public:
} //override static method
/** Allocates and initializes the action
m_pSelectorTarget = pSel; @deprecated: This interface will be deprecated sooner or later.
if (m_pSelectorTarget)
{
m_pSelectorTarget->retain();
}
}
}
protected:
/** Target that will be called */
CCObject* m_pSelectorTarget;
union
{
SEL_CallFunc m_pCallFunc;
SEL_CallFuncN m_pCallFuncN;
SEL_CallFuncND m_pCallFuncND;
SEL_CallFuncO m_pCallFuncO;
};
};
/**
@brief Calls a 'callback' with the node as the first argument
N means Node
*/
class CC_DLL CCCallFuncN : public CCCallFunc
{
public:
CCCallFuncN(){}
virtual ~CCCallFuncN(){}
/** creates the action with the callback
typedef void (CCObject::*SEL_CallFuncN)(CCNode*);
*/
static CCCallFuncN * actionWithTarget(CCObject* pSelectorTar
get, SEL_CallFuncN selector);
/** initializes the action with the callback
typedef void (CCObject::*SEL_CallFuncN)(CCNode*);
*/
virtual bool initWithTarget(CCObject* pSelectorTarget, SEL_C
allFuncN selector);
// super methods
virtual CCObject* copyWithZone(CCZone *pZone);
virtual void execute();
};
/**
@brief Calls a 'callback' with the node as the first argument and th
e 2nd argument is data
* ND means: Node and Data. Data is void *, so it could be anything.
*/
class CC_DLL CCCallFuncND : public CCCallFuncN
{
public:
/** creates the action with the callback and the data to pas
s as an argument */
static CCCallFuncND * actionWithTarget(CCObject* pSelectorTa
rget, SEL_CallFuncND selector, void* d);
/** initializes the action with the callback and the data to
pass as an argument */
virtual bool initWithTarget(CCObject* pSelectorTarget, SEL_C
allFuncND selector, void* d);
// super methods
virtual CCObject* copyWithZone(CCZone *pZone);
virtual void execute();
protected:
void *m_pData;
};
/**
@brief Calls a 'callback' with an object as the first argument.
O means Object.
@since v0.99.5
*/ */
class CC_DLL CCCallFuncO : public CCCallFunc CC_DEPRECATED_ATTRIBUTE static CCToggleVisibility * action();
/** Allocates and initializes the action */
static CCToggleVisibility * create();
};
/**
@brief Flips the sprite horizontally
@since v0.99.0
*/
class CC_DLL CCFlipX : public CCActionInstant
{
public:
CCFlipX()
:m_bFlipX(false)
{}
virtual ~CCFlipX(){}
/** create the action
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCFlipX * actionWithFlipX(bool x);
/** create the action */
static CCFlipX * create(bool x);
/** init the action */
bool initWithFlipX(bool x);
//super methods
virtual void update(float time);
virtual CCFiniteTimeAction * reverse(void);
virtual CCObject* copyWithZone(CCZone *pZone);
protected:
bool m_bFlipX;
};
/**
@brief Flips the sprite vertically
@since v0.99.0
*/
class CC_DLL CCFlipY : public CCActionInstant
{
public:
CCFlipY()
:m_bFlipY(false)
{}
virtual ~CCFlipY(){}
/** create the action
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCFlipY * actionWithFlipY(bool y);
/** create the action */
static CCFlipY * create(bool y);
/** init the action */
bool initWithFlipY(bool y);
//super methods
virtual void update(float time);
virtual CCFiniteTimeAction * reverse(void);
virtual CCObject* copyWithZone(CCZone *pZone);
protected:
bool m_bFlipY;
};
/** @brief Places the node in a certain position
*/
class CC_DLL CCPlace : public CCActionInstant //<NSCopying>
{
public:
CCPlace(){}
virtual ~CCPlace(){}
/** creates a Place action with a position
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCPlace * actionWithPosition(const CCPoi
nt& pos);
/** creates a Place action with a position */
static CCPlace * create(const CCPoint& pos);
/** Initializes a Place action with a position */
bool initWithPosition(const CCPoint& pos);
//super methods
virtual void update(float time);
virtual CCObject* copyWithZone(CCZone *pZone);
protected:
CCPoint m_tPosition;
};
/** @brief Calls a 'callback'
*/
class CC_DLL CCCallFunc : public CCActionInstant //<NSCopying>
{
public:
CCCallFunc()
: m_pSelectorTarget(NULL)
, m_pCallFunc(NULL)
, m_nScriptHandler(0)
{
}
virtual ~CCCallFunc()
{ {
public: CC_SAFE_RELEASE(m_pSelectorTarget);
CCCallFuncO(); }
virtual ~CCCallFuncO(); /** creates the action with the callback
/** creates the action with the callback @deprecated: This interface will be deprecated sooner or later.
typedef void (CCObject::*SEL_CallFunc)();
typedef void (CCObject::*SEL_CallFuncO)(CCObject*); */
*/ CC_DEPRECATED_ATTRIBUTE static CCCallFunc * actionWithTarget(CCObject*
static CCCallFuncO * actionWithTarget(CCObject* pSelectorTarget, SE pSelectorTarget, SEL_CallFunc selector);
L_CallFuncO selector, CCObject* pObject);
/** initializes the action with the callback /** creates the action with the callback
typedef void (CCObject::*SEL_CallFuncO)(CCObject*); typedef void (CCObject::*SEL_CallFunc)();
*/ */
virtual bool initWithTarget(CCObject* pSelectorTarget, SEL_CallFunc static CCCallFunc * create(CCObject* pSelectorTarget, SEL_CallFunc sele
O selector, CCObject* pObject); ctor);
// super methods
virtual CCObject* copyWithZone(CCZone *pZone); /** creates the action with the handler script function */
virtual void execute(); static CCCallFunc * create(int nHandler);
inline CCObject* getObject() /** initializes the action with the callback
{
return m_pObject; typedef void (CCObject::*SEL_CallFunc)();
} */
virtual bool initWithTarget(CCObject* pSelectorTarget);
inline void setObject(CCObject* pObj) /** executes the callback */
{ virtual void execute();
if (pObj != m_pObject) //super methods
{ virtual void update(float time);
CC_SAFE_RELEASE(m_pObject); CCObject * copyWithZone(CCZone *pZone);
m_pObject = pObj;
CC_SAFE_RETAIN(m_pObject); inline CCObject* getTargetCallback()
} {
} return m_pSelectorTarget;
}
protected:
/** object to be passed as argument */ inline void setTargetCallback(CCObject* pSel)
CCObject* m_pObject; {
if (pSel != m_pSelectorTarget)
{
CC_SAFE_RETAIN(pSel);
CC_SAFE_RELEASE(m_pSelectorTarget);
m_pSelectorTarget = pSel;
}
}
protected:
/** Target that will be called */
CCObject* m_pSelectorTarget;
int m_nScriptHandler;
union
{
SEL_CallFunc m_pCallFunc;
SEL_CallFuncN m_pCallFuncN;
SEL_CallFuncND m_pCallFuncND;
SEL_CallFuncO m_pCallFuncO;
}; };
};
/**
@brief Calls a 'callback' with the node as the first argument
N means Node
*/
class CC_DLL CCCallFuncN : public CCCallFunc
{
public:
CCCallFuncN(){}
virtual ~CCCallFuncN(){}
/** creates the action with the callback
@deprecated: This interface will be deprecated sooner or later.
typedef void (CCObject::*SEL_CallFuncN)(CCNode*);
*/
CC_DEPRECATED_ATTRIBUTE static CCCallFuncN * actionWithTarget(CCObject*
pSelectorTarget, SEL_CallFuncN selector);
/** creates the action with the callback
typedef void (CCObject::*SEL_CallFuncN)(CCNode*);
*/
static CCCallFuncN * create(CCObject* pSelectorTarget, SEL_CallFuncN se
lector);
/** creates the action with the handler script function */
static CCCallFuncN * create(int nHandler);
/** initializes the action with the callback
typedef void (CCObject::*SEL_CallFuncN)(CCNode*);
*/
virtual bool initWithTarget(CCObject* pSelectorTarget, SEL_CallFuncN se
lector);
// super methods
virtual CCObject* copyWithZone(CCZone *pZone);
virtual void execute();
};
/**
@brief Calls a 'callback' with the node as the first argument and the 2nd a
rgument is data
* ND means: Node and Data. Data is void *, so it could be anything.
*/
class CC_DLL CCCallFuncND : public CCCallFuncN
{
public:
/** creates the action with the callback and the data to pass as an arg
ument
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCCallFuncND * actionWithTarget(CCObject
* pSelectorTarget, SEL_CallFuncND selector, void* d);
/** creates the action with the callback and the data to pass as an arg
ument */
static CCCallFuncND * create(CCObject* pSelectorTarget, SEL_CallFuncND
selector, void* d);
/** initializes the action with the callback and the data to pass as an
argument */
virtual bool initWithTarget(CCObject* pSelectorTarget, SEL_CallFuncND s
elector, void* d);
// super methods
virtual CCObject* copyWithZone(CCZone *pZone);
virtual void execute();
protected:
void *m_pData;
};
/**
@brief Calls a 'callback' with an object as the first argument.
O means Object.
@since v0.99.5
*/
class CC_DLL CCCallFuncO : public CCCallFunc
{
public:
CCCallFuncO();
virtual ~CCCallFuncO();
/** creates the action with the callback
@deprecated: This interface will be deprecated sooner or later.
typedef void (CCObject::*SEL_CallFuncO)(CCObject*);
*/
CC_DEPRECATED_ATTRIBUTE static CCCallFuncO * actionWithTarget(CCObject*
pSelectorTarget, SEL_CallFuncO selector, CCObject* pObject);
/** creates the action with the callback
typedef void (CCObject::*SEL_CallFuncO)(CCObject*);
*/
static CCCallFuncO * create(CCObject* pSelectorTarget, SEL_CallFuncO se
lector, CCObject* pObject);
/** initializes the action with the callback
typedef void (CCObject::*SEL_CallFuncO)(CCObject*);
*/
virtual bool initWithTarget(CCObject* pSelectorTarget, SEL_CallFuncO se
lector, CCObject* pObject);
// super methods
virtual CCObject* copyWithZone(CCZone *pZone);
virtual void execute();
inline CCObject* getObject()
{
return m_pObject;
}
inline void setObject(CCObject* pObj)
{
if (pObj != m_pObject)
{
CC_SAFE_RELEASE(m_pObject);
m_pObject = pObj;
CC_SAFE_RETAIN(m_pObject);
}
}
protected:
/** object to be passed as argument */
CCObject* m_pObject;
};
// end of actions group
/// @}
} NS_CC_END
#endif //__CCINSTANT_ACTION_H__ #endif //__CCINSTANT_ACTION_H__
 End of changes. 8 change blocks. 
304 lines changed or deleted 373 lines changed or added


 CCActionInterval.h   CCActionInterval.h 
skipping to change at line 30 skipping to change at line 30
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __ACTION_CCINTERVAL_ACTION_H__ #ifndef __ACTION_CCINTERVAL_ACTION_H__
#define __ACTION_CCINTERVAL_ACTION_H__ #define __ACTION_CCINTERVAL_ACTION_H__
#include "CCNode.h" #include "base_nodes/CCNode.h"
#include "CCAction.h" #include "CCAction.h"
#include "CCProtocols.h" #include "CCProtocols.h"
#include "CCSpriteFrame.h" #include "sprite_nodes/CCSpriteFrame.h"
#include "CCAnimation.h" #include "sprite_nodes/CCAnimation.h"
#include <vector>
namespace cocos2d { NS_CC_BEGIN
/**
* @addtogroup actions
* @{
*/
/** /**
@brief An interval action is an action that takes place within a certain pe riod of time. @brief An interval action is an action that takes place within a certain pe riod of time.
It has an start time, and a finish time. The finish time is the parameter It has an start time, and a finish time. The finish time is the parameter
duration plus the start time. duration plus the start time.
These CCActionInterval actions have some interesting properties, like: These CCActionInterval actions have some interesting properties, like:
- They can run normally (default) - They can run normally (default)
- They can run reversed with the reverse method - They can run reversed with the reverse method
- They can run with the time altered with the Accelerate, AccelDeccel and S peed actions. - They can run with the time altered with the Accelerate, AccelDeccel and S peed actions.
skipping to change at line 58 skipping to change at line 64
For example, you can simulate a Ping Pong effect running the action normall y and For example, you can simulate a Ping Pong effect running the action normall y and
then running it again in Reverse mode. then running it again in Reverse mode.
Example: Example:
CCAction *pingPongAction = CCSequence::actions(action, action->reverse(), N ULL); CCAction *pingPongAction = CCSequence::actions(action, action->reverse(), N ULL);
*/ */
class CC_DLL CCActionInterval : public CCFiniteTimeAction class CC_DLL CCActionInterval : public CCFiniteTimeAction
{ {
public: public:
/** how many seconds had elapsed since the actions started to run. * /** how many seconds had elapsed since the actions started to run. */
/ inline float getElapsed(void) { return m_elapsed; }
inline ccTime getElapsed(void) { return m_elapsed; }
/** initializes the action */ /** initializes the action */
bool initWithDuration(ccTime d); bool initWithDuration(float d);
/** returns true if the action has finished */ /** returns true if the action has finished */
virtual bool isDone(void); virtual bool isDone(void);
virtual CCObject* copyWithZone(CCZone* pZone); virtual CCObject* copyWithZone(CCZone* pZone);
virtual void step(ccTime dt); virtual void step(float dt);
virtual void startWithTarget(CCNode *pTarget); virtual void startWithTarget(CCNode *pTarget);
/** returns a reversed action */ /** returns a reversed action */
virtual CCActionInterval* reverse(void); virtual CCActionInterval* reverse(void);
public: public:
/** creates the action */ /** creates the action
static CCActionInterval* actionWithDuration(ccTime d); @deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCActionInterval* actionWithDuration(flo
at d);
/** creates the action */
static CCActionInterval* create(float d);
public: public:
//extension in CCGridAction //extension in CCGridAction
void setAmplitudeRate(CGFloat amp); void setAmplitudeRate(float amp);
CGFloat getAmplitudeRate(void); float getAmplitudeRate(void);
protected: protected:
ccTime m_elapsed; float m_elapsed;
bool m_bFirstTick; bool m_bFirstTick;
}; };
/** @brief Runs actions sequentially, one after another /** @brief Runs actions sequentially, one after another
*/ */
class CC_DLL CCSequence : public CCActionInterval class CC_DLL CCSequence : public CCActionInterval
{ {
public: public:
~CCSequence(void); ~CCSequence(void);
/** initializes the action */ /** initializes the action */
bool initOneTwo(CCFiniteTimeAction *pActionOne, CCFiniteTimeAction *pAc bool initWithTwoActions(CCFiniteTimeAction *pActionOne, CCFiniteTimeAct
tionTwo); ion *pActionTwo);
virtual CCObject* copyWithZone(CCZone* pZone); virtual CCObject* copyWithZone(CCZone* pZone);
virtual void startWithTarget(CCNode *pTarget); virtual void startWithTarget(CCNode *pTarget);
virtual void stop(void); virtual void stop(void);
virtual void update(ccTime time); virtual void update(float t);
virtual CCActionInterval* reverse(void); virtual CCActionInterval* reverse(void);
public: public:
/** helper constructor to create an array of sequenceable actions */ /** helper constructor to create an array of sequenceable actions
static CCFiniteTimeAction* actions(CCFiniteTimeAction *pAction1, ... @deprecated: This interface will be deprecated sooner or later.
); */
/** helper contructor to create an array of sequenceable actions giv CC_DEPRECATED_ATTRIBUTE static CCFiniteTimeAction* actions(CCFiniteTime
en an array */ Action *pAction1, ...);
static CCFiniteTimeAction* actionsWithArray(CCArray *actions); /** helper contructor to create an array of sequenceable actions given
an array
/** creates the action */ @deprecated: This interface will be deprecated sooner or later.
static CCSequence* actionOneTwo(CCFiniteTimeAction *pActionOne, CCFi */
niteTimeAction *pActionTwo); CC_DEPRECATED_ATTRIBUTE static CCFiniteTimeAction* actionWithArray(CCAr
protected: ray *arrayOfActions);
CCFiniteTimeAction *m_pActions[2]; /** creates the action
ccTime m_split; @deprecated: This interface will be deprecated sooner or later.
int m_last; */
CC_DEPRECATED_ATTRIBUTE static CCSequence* actionOneTwo(CCFiniteTimeAct
ion *pActionOne, CCFiniteTimeAction *pActionTwo);
/** helper constructor to create an array of sequenceable actions */
static CCFiniteTimeAction* create(CCFiniteTimeAction *pAction1, ...);
/** helper contructor to create an array of sequenceable actions given
an array */
static CCFiniteTimeAction* create(CCArray *arrayOfActions);
/** creates the action */
static CCSequence* createWithTwoActions(CCFiniteTimeAction *pActionOne,
CCFiniteTimeAction *pActionTwo);
protected:
CCFiniteTimeAction *m_pActions[2];
float m_split;
int m_last;
}; };
/** @brief Repeats an action a number of times. /** @brief Repeats an action a number of times.
* To repeat an action forever use the CCRepeatForever action. * To repeat an action forever use the CCRepeatForever action.
*/ */
class CC_DLL CCRepeat : public CCActionInterval class CC_DLL CCRepeat : public CCActionInterval
{ {
public: public:
~CCRepeat(void); ~CCRepeat(void);
/** initializes a CCRepeat action. Times is an unsigned integer betw /** initializes a CCRepeat action. Times is an unsigned integer between
een 1 and pow(2,30) */ 1 and pow(2,30) */
bool initWithAction(CCFiniteTimeAction *pAction, unsigned int times) bool initWithAction(CCFiniteTimeAction *pAction, unsigned int times);
;
virtual CCObject* copyWithZone(CCZone* pZone); virtual CCObject* copyWithZone(CCZone* pZone);
virtual void startWithTarget(CCNode *pTarget); virtual void startWithTarget(CCNode *pTarget);
virtual void stop(void); virtual void stop(void);
virtual void update(ccTime time); virtual void update(float dt);
virtual bool isDone(void); virtual bool isDone(void);
virtual CCActionInterval* reverse(void); virtual CCActionInterval* reverse(void);
inline void setInnerAction(CCFiniteTimeAction *pAction) inline void setInnerAction(CCFiniteTimeAction *pAction)
{ {
if (m_pInnerAction != pAction) if (m_pInnerAction != pAction)
{ {
CC_SAFE_RELEASE(m_pInnerAction); CC_SAFE_RETAIN(pAction);
m_pInnerAction = pAction; CC_SAFE_RELEASE(m_pInnerAction);
CC_SAFE_RETAIN(m_pInnerAction); m_pInnerAction = pAction;
} }
} }
inline CCFiniteTimeAction* getInnerAction() inline CCFiniteTimeAction* getInnerAction()
{ {
return m_pInnerAction; return m_pInnerAction;
} }
public: public:
/** creates a CCRepeat action. Times is an unsigned integer between /** creates a CCRepeat action. Times is an unsigned integer between 1 a
1 and pow(2,30) */ nd pow(2,30)
static CCRepeat* actionWithAction(CCFiniteTimeAction *pAction, unsig @deprecated: This interface will be deprecated sooner or later.
ned int times); */
CC_DEPRECATED_ATTRIBUTE static CCRepeat* actionWithAction(CCFiniteTimeA
protected: ction *pAction, unsigned int times);
unsigned int m_uTimes;
unsigned int m_uTotal; /** creates a CCRepeat action. Times is an unsigned integer between 1 a
/** Inner action */ nd pow(2,30) */
CCFiniteTimeAction *m_pInnerAction; static CCRepeat* create(CCFiniteTimeAction *pAction, unsigned int times
);
protected:
unsigned int m_uTimes;
unsigned int m_uTotal;
float m_fNextDt;
bool m_bActionInstant;
/** Inner action */
CCFiniteTimeAction *m_pInnerAction;
}; };
/** @brief Repeats an action for ever. /** @brief Repeats an action for ever.
To repeat the an action for a limited number of times use the Repeat action . To repeat the an action for a limited number of times use the Repeat action .
@warning This action can't be Sequenceable because it is not an IntervalAct ion @warning This action can't be Sequenceable because it is not an IntervalAct ion
*/ */
class CC_DLL CCRepeatForever : public CCActionInterval class CC_DLL CCRepeatForever : public CCActionInterval
{ {
public: public:
CCRepeatForever() CCRepeatForever()
: m_pInnerAction(NULL) : m_pInnerAction(NULL)
{} {}
virtual ~CCRepeatForever(); virtual ~CCRepeatForever();
/** initializes the action */ /** initializes the action */
bool initWithAction(CCActionInterval *pAction); bool initWithAction(CCActionInterval *pAction);
virtual CCObject* copyWithZone(CCZone *pZone); virtual CCObject* copyWithZone(CCZone *pZone);
virtual void startWithTarget(CCNode* pTarget); virtual void startWithTarget(CCNode* pTarget);
virtual void step(ccTime dt); virtual void step(float dt);
virtual bool isDone(void); virtual bool isDone(void);
virtual CCActionInterval* reverse(void); virtual CCActionInterval* reverse(void);
inline void setInnerAction(CCActionInterval *pAction) inline void setInnerAction(CCActionInterval *pAction)
{ {
if (m_pInnerAction != pAction) if (m_pInnerAction != pAction)
{ {
CC_SAFE_RELEASE(m_pInnerAction); CC_SAFE_RELEASE(m_pInnerAction);
m_pInnerAction = pAction; m_pInnerAction = pAction;
CC_SAFE_RETAIN(m_pInnerAction); CC_SAFE_RETAIN(m_pInnerAction);
} }
} }
inline CCActionInterval* getInnerAction() inline CCActionInterval* getInnerAction()
{ {
return m_pInnerAction; return m_pInnerAction;
} }
public: public:
/** creates the action */ /** creates the action
static CCRepeatForever* actionWithAction(CCActionInterval *pAction); @deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCRepeatForever* actionWithAction(CCActi
onInterval *pAction);
/** creates the action */
static CCRepeatForever* create(CCActionInterval *pAction);
protected: protected:
/** Inner action */ /** Inner action */
CCActionInterval *m_pInnerAction; CCActionInterval *m_pInnerAction;
}; };
/** @brief Spawn a new action immediately /** @brief Spawn a new action immediately
*/ */
class CC_DLL CCSpawn : public CCActionInterval class CC_DLL CCSpawn : public CCActionInterval
{ {
public: public:
~CCSpawn(void); ~CCSpawn(void);
/** initializes the Spawn action with the 2 actions to spawn */ /** initializes the Spawn action with the 2 actions to spawn */
bool initOneTwo(CCFiniteTimeAction *pAction1, CCFiniteTimeAction *pA bool initWithTwoActions(CCFiniteTimeAction *pAction1, CCFiniteTimeActio
ction2); n *pAction2);
virtual CCObject* copyWithZone(CCZone* pZone); virtual CCObject* copyWithZone(CCZone* pZone);
virtual void startWithTarget(CCNode *pTarget); virtual void startWithTarget(CCNode *pTarget);
virtual void stop(void); virtual void stop(void);
virtual void update(ccTime time); virtual void update(float time);
virtual CCActionInterval* reverse(void); virtual CCActionInterval* reverse(void);
public: public:
/** helper constructor to create an array of spawned actions */ /** helper constructor to create an array of spawned actions
static CCFiniteTimeAction* actions(CCFiniteTimeAction *pAction1, ... @deprecated: This interface will be deprecated sooner or later.
); */
CC_DEPRECATED_ATTRIBUTE static CCFiniteTimeAction* actions(CCFiniteTime
Action *pAction1, ...);
/** helper contructor to create an array of spawned actions given an ar
ray
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCFiniteTimeAction* actionWithArray(CCAr
ray *arrayOfActions);
/** creates the Spawn action
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCSpawn* actionOneTwo(CCFiniteTimeAction
*pAction1, CCFiniteTimeAction *pAction2);
/** helper contructor to create an array of spawned actions given an /** helper constructor to create an array of spawned actions */
array */ static CCFiniteTimeAction* create(CCFiniteTimeAction *pAction1, ...);
static CCFiniteTimeAction* actionsWithArray(CCArray *actions);
/** creates the Spawn action */ /** helper contructor to create an array of spawned actions given an ar
static CCSpawn* actionOneTwo(CCFiniteTimeAction *pAction1, CCFiniteT ray */
imeAction *pAction2); static CCFiniteTimeAction* create(CCArray *arrayOfActions);
/** creates the Spawn action */
static CCSpawn* createWithTwoActions(CCFiniteTimeAction *pAction1, CCFi
niteTimeAction *pAction2);
protected: protected:
CCFiniteTimeAction *m_pOne; CCFiniteTimeAction *m_pOne;
CCFiniteTimeAction *m_pTwo; CCFiniteTimeAction *m_pTwo;
}; };
/** @brief Rotates a CCNode object to a certain angle by modifying it's /** @brief Rotates a CCNode object to a certain angle by modifying it's
rotation attribute. rotation attribute.
The direction will be decided by the shortest angle. The direction will be decided by the shortest angle.
*/ */
class CC_DLL CCRotateTo : public CCActionInterval class CC_DLL CCRotateTo : public CCActionInterval
{ {
public: public:
/** initializes the action */ /** initializes the action */
bool initWithDuration(ccTime duration, float fDeltaAngle); bool initWithDuration(float duration, float fDeltaAngle);
virtual CCObject* copyWithZone(CCZone* pZone); virtual CCObject* copyWithZone(CCZone* pZone);
virtual void startWithTarget(CCNode *pTarget); virtual void startWithTarget(CCNode *pTarget);
virtual void update(ccTime time); virtual void update(float time);
public: public:
/** creates the action */ /** creates the action
static CCRotateTo* actionWithDuration(ccTime duration, float fDeltaA @deprecated: This interface will be deprecated sooner or later.
ngle); */
CC_DEPRECATED_ATTRIBUTE static CCRotateTo* actionWithDuration(float dur
protected: ation, float fDeltaAngle);
float m_fDstAngle; /** creates the action */
float m_fStartAngle; static CCRotateTo* create(float duration, float fDeltaAngle);
float m_fDiffAngle; protected:
float m_fDstAngle;
float m_fStartAngle;
float m_fDiffAngle;
}; };
/** @brief Rotates a CCNode object clockwise a number of degrees by modifyi ng it's rotation attribute. /** @brief Rotates a CCNode object clockwise a number of degrees by modifyi ng it's rotation attribute.
*/ */
class CC_DLL CCRotateBy : public CCActionInterval class CC_DLL CCRotateBy : public CCActionInterval
{ {
public: public:
/** initializes the action */ /** initializes the action */
bool initWithDuration(ccTime duration, float fDeltaAngle); bool initWithDuration(float duration, float fDeltaAngle);
virtual CCObject* copyWithZone(CCZone* pZone); virtual CCObject* copyWithZone(CCZone* pZone);
virtual void startWithTarget(CCNode *pTarget); virtual void startWithTarget(CCNode *pTarget);
virtual void update(ccTime time); virtual void update(float time);
virtual CCActionInterval* reverse(void); virtual CCActionInterval* reverse(void);
public: public:
/** creates the action */ /** creates the action
static CCRotateBy* actionWithDuration(ccTime duration, float fDeltaA @deprecated: This interface will be deprecated sooner or later.
ngle); */
CC_DEPRECATED_ATTRIBUTE static CCRotateBy* actionWithDuration(float dur
ation, float fDeltaAngle);
/** creates the action */
static CCRotateBy* create(float duration, float fDeltaAngle);
protected: protected:
float m_fAngle; float m_fAngle;
float m_fStartAngle; float m_fStartAngle;
}; };
/** @brief Moves a CCNode object to the position x,y. x and y are absolute coordinates by modifying it's position attribute. /** @brief Moves a CCNode object to the position x,y. x and y are absolute coordinates by modifying it's position attribute.
*/ */
class CC_DLL CCMoveTo : public CCActionInterval class CC_DLL CCMoveTo : public CCActionInterval
{ {
public: public:
/** initializes the action */ /** initializes the action */
bool initWithDuration(ccTime duration, const CCPoint& position); bool initWithDuration(float duration, const CCPoint& position);
virtual CCObject* copyWithZone(CCZone* pZone); virtual CCObject* copyWithZone(CCZone* pZone);
virtual void startWithTarget(CCNode *pTarget); virtual void startWithTarget(CCNode *pTarget);
virtual void update(ccTime time); virtual void update(float time);
public: public:
/** creates the action */ /** creates the action
static CCMoveTo* actionWithDuration(ccTime duration, const CCPoint& @deprecated: This interface will be deprecated sooner or later.
position); */
CC_DEPRECATED_ATTRIBUTE static CCMoveTo* actionWithDuration(float durat
protected: ion, const CCPoint& position);
CCPoint m_endPosition; /** creates the action */
CCPoint m_startPosition; static CCMoveTo* create(float duration, const CCPoint& position);
CCPoint m_delta; protected:
CCPoint m_endPosition;
CCPoint m_startPosition;
CCPoint m_delta;
}; };
/** @brief Moves a CCNode object x,y pixels by modifying it's position attr ibute. /** @brief Moves a CCNode object x,y pixels by modifying it's position attr ibute.
x and y are relative to the position of the object. x and y are relative to the position of the object.
Duration is is seconds. Duration is is seconds.
*/ */
class CC_DLL CCMoveBy : public CCMoveTo class CC_DLL CCMoveBy : public CCMoveTo
{ {
public: public:
/** initializes the action */ /** initializes the action */
bool initWithDuration(ccTime duration, const CCPoint& position); bool initWithDuration(float duration, const CCPoint& position);
virtual CCObject* copyWithZone(CCZone* pZone); virtual CCObject* copyWithZone(CCZone* pZone);
virtual void startWithTarget(CCNode *pTarget); virtual void startWithTarget(CCNode *pTarget);
virtual CCActionInterval* reverse(void); virtual CCActionInterval* reverse(void);
public: public:
/** creates the action */ /** creates the action
static CCMoveBy* actionWithDuration(ccTime duration, const CCPoint& @deprecated: This interface will be deprecated sooner or later.
position); */
CC_DEPRECATED_ATTRIBUTE static CCMoveBy* actionWithDuration(float durat
ion, const CCPoint& position);
/** creates the action */
static CCMoveBy* create(float duration, const CCPoint& position);
}; };
/** Skews a CCNode object to given angles by modifying it's skewX and skewY attributes /** Skews a CCNode object to given angles by modifying it's skewX and skewY attributes
@since v1.0 @since v1.0
*/ */
class CC_DLL CCSkewTo : public CCActionInterval class CC_DLL CCSkewTo : public CCActionInterval
{ {
public: public:
CCSkewTo(); CCSkewTo();
virtual bool initWithDuration(ccTime t, float sx, float sy); virtual bool initWithDuration(float t, float sx, float sy);
virtual CCObject* copyWithZone(CCZone* pZone); virtual CCObject* copyWithZone(CCZone* pZone);
virtual void startWithTarget(CCNode *pTarget); virtual void startWithTarget(CCNode *pTarget);
virtual void update(ccTime time); virtual void update(float time);
public: public:
static CCSkewTo* actionWithDuration(ccTime t, float sx, float sy); /** creates the action
@deprecated: This interface will be deprecated sooner or later.
protected: */
float m_fSkewX; CC_DEPRECATED_ATTRIBUTE static CCSkewTo* actionWithDuration(float t, fl
float m_fSkewY; oat sx, float sy);
float m_fStartSkewX;
float m_fStartSkewY; /** creates the action */
float m_fEndSkewX; static CCSkewTo* create(float t, float sx, float sy);
float m_fEndSkewY; protected:
float m_fDeltaX; float m_fSkewX;
float m_fDeltaY; float m_fSkewY;
float m_fStartSkewX;
float m_fStartSkewY;
float m_fEndSkewX;
float m_fEndSkewY;
float m_fDeltaX;
float m_fDeltaY;
}; };
/** Skews a CCNode object by skewX and skewY degrees /** Skews a CCNode object by skewX and skewY degrees
@since v1.0 @since v1.0
*/ */
class CC_DLL CCSkewBy : public CCSkewTo class CC_DLL CCSkewBy : public CCSkewTo
{ {
public: public:
virtual bool initWithDuration(ccTime t, float sx, float sy); virtual bool initWithDuration(float t, float sx, float sy);
virtual void startWithTarget(CCNode *pTarget); virtual void startWithTarget(CCNode *pTarget);
virtual CCActionInterval* reverse(void); virtual CCActionInterval* reverse(void);
public: public:
static CCSkewBy* actionWithDuration(ccTime t, float deltaSkewX, floa /** creates the action
t deltaSkewY); @deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCSkewBy* actionWithDuration(float t, fl
oat deltaSkewX, float deltaSkewY);
/** creates the action */
static CCSkewBy* create(float t, float deltaSkewX, float deltaSkewY);
}; };
/** @brief Moves a CCNode object simulating a parabolic jump movement by mo difying it's position attribute. /** @brief Moves a CCNode object simulating a parabolic jump movement by mo difying it's position attribute.
*/ */
class CC_DLL CCJumpBy : public CCActionInterval class CC_DLL CCJumpBy : public CCActionInterval
{ {
public: public:
/** initializes the action */ /** initializes the action */
bool initWithDuration(ccTime duration, const CCPoint& position, ccTi bool initWithDuration(float duration, const CCPoint& position, float he
me height, unsigned int jumps); ight, unsigned int jumps);
virtual CCObject* copyWithZone(CCZone* pZone); virtual CCObject* copyWithZone(CCZone* pZone);
virtual void startWithTarget(CCNode *pTarget); virtual void startWithTarget(CCNode *pTarget);
virtual void update(ccTime time); virtual void update(float time);
virtual CCActionInterval* reverse(void); virtual CCActionInterval* reverse(void);
public: public:
/** creates the action */ /** creates the action
static CCJumpBy* actionWithDuration(ccTime duration, const CCPoint& @deprecated: This interface will be deprecated sooner or later.
position, ccTime height, unsigned int jumps); */
CC_DEPRECATED_ATTRIBUTE static CCJumpBy* actionWithDuration(float durat
protected: ion, const CCPoint& position, float height, unsigned int jumps);
CCPoint m_startPosition; /** creates the action */
CCPoint m_delta; static CCJumpBy* create(float duration, const CCPoint& position, float
ccTime m_height; height, unsigned int jumps);
unsigned int m_nJumps; protected:
CCPoint m_startPosition;
CCPoint m_delta;
float m_height;
unsigned int m_nJumps;
}; };
/** @brief Moves a CCNode object to a parabolic position simulating a jump movement by modifying it's position attribute. /** @brief Moves a CCNode object to a parabolic position simulating a jump movement by modifying it's position attribute.
*/ */
class CC_DLL CCJumpTo : public CCJumpBy class CC_DLL CCJumpTo : public CCJumpBy
{ {
public: public:
virtual void startWithTarget(CCNode *pTarget); virtual void startWithTarget(CCNode *pTarget);
virtual CCObject* copyWithZone(CCZone* pZone); virtual CCObject* copyWithZone(CCZone* pZone);
public: public:
/** creates the action */ /** creates the action
static CCJumpTo* actionWithDuration(ccTime duration, const CCPoint& @deprecated: This interface will be deprecated sooner or later.
position, ccTime height, int jumps); */
CC_DEPRECATED_ATTRIBUTE static CCJumpTo* actionWithDuration(float durat
ion, const CCPoint& position, float height, int jumps);
/** creates the action */
static CCJumpTo* create(float duration, const CCPoint& position, float
height, int jumps);
}; };
/** @typedef bezier configuration structure /** @typedef bezier configuration structure
*/ */
typedef struct _ccBezierConfig { typedef struct _ccBezierConfig {
//! end position of the bezier //! end position of the bezier
CCPoint endPosition; CCPoint endPosition;
//! Bezier control point 1 //! Bezier control point 1
CCPoint controlPoint_1; CCPoint controlPoint_1;
//! Bezier control point 2 //! Bezier control point 2
CCPoint controlPoint_2; CCPoint controlPoint_2;
} ccBezierConfig; } ccBezierConfig;
/** @brief An action that moves the target with a cubic Bezier curve by a c ertain distance. /** @brief An action that moves the target with a cubic Bezier curve by a c ertain distance.
*/ */
class CC_DLL CCBezierBy : public CCActionInterval class CC_DLL CCBezierBy : public CCActionInterval
{ {
public: public:
/** initializes the action with a duration and a bezier configuratio /** initializes the action with a duration and a bezier configuration *
n */ /
bool initWithDuration(ccTime t, const ccBezierConfig& c); bool initWithDuration(float t, const ccBezierConfig& c);
virtual CCObject* copyWithZone(CCZone* pZone); virtual CCObject* copyWithZone(CCZone* pZone);
virtual void startWithTarget(CCNode *pTarget); virtual void startWithTarget(CCNode *pTarget);
virtual void update(ccTime time); virtual void update(float time);
virtual CCActionInterval* reverse(void); virtual CCActionInterval* reverse(void);
public: public:
/** creates the action with a duration and a bezier configuration */ /** creates the action with a duration and a bezier configuration
static CCBezierBy* actionWithDuration(ccTime t, const ccBezierConfig @deprecated: This interface will be deprecated sooner or later.
& c); */
CC_DEPRECATED_ATTRIBUTE static CCBezierBy* actionWithDuration(float t,
const ccBezierConfig& c);
/** creates the action with a duration and a bezier configuration */
static CCBezierBy* create(float t, const ccBezierConfig& c);
protected: protected:
ccBezierConfig m_sConfig; ccBezierConfig m_sConfig;
CCPoint m_startPosition; CCPoint m_startPosition;
}; };
/** @brief An action that moves the target with a cubic Bezier curve to a d estination point. /** @brief An action that moves the target with a cubic Bezier curve to a d estination point.
@since v0.8.2 @since v0.8.2
*/ */
class CC_DLL CCBezierTo : public CCBezierBy class CC_DLL CCBezierTo : public CCBezierBy
{ {
public: public:
virtual void startWithTarget(CCNode *pTarget); virtual void startWithTarget(CCNode *pTarget);
virtual CCObject* copyWithZone(CCZone* pZone); virtual CCObject* copyWithZone(CCZone* pZone);
public: public:
/** creates the action with a duration and a bezier configuration */ /** creates the action with a duration and a bezier configuration
static CCBezierTo* actionWithDuration(ccTime t, const ccBezierConfig& c @deprecated: This interface will be deprecated sooner or later.
); */
CC_DEPRECATED_ATTRIBUTE static CCBezierTo* actionWithDuration(float t,
const ccBezierConfig& c);
/** creates the action with a duration and a bezier configuration */
static CCBezierTo* create(float t, const ccBezierConfig& c);
}; };
/** @brief Scales a CCNode object to a zoom factor by modifying it's scale attribute. /** @brief Scales a CCNode object to a zoom factor by modifying it's scale attribute.
@warning This action doesn't support "reverse" @warning This action doesn't support "reverse"
*/ */
class CC_DLL CCScaleTo : public CCActionInterval class CC_DLL CCScaleTo : public CCActionInterval
{ {
public: public:
/** initializes the action with the same scale factor for X and Y */ /** initializes the action with the same scale factor for X and Y */
bool initWithDuration(ccTime duration, float s); bool initWithDuration(float duration, float s);
/** initializes the action with and X factor and a Y factor */ /** initializes the action with and X factor and a Y factor */
bool initWithDuration(ccTime duration, float sx, float sy); bool initWithDuration(float duration, float sx, float sy);
virtual CCObject* copyWithZone(CCZone* pZone); virtual CCObject* copyWithZone(CCZone* pZone);
virtual void startWithTarget(CCNode *pTarget); virtual void startWithTarget(CCNode *pTarget);
virtual void update(ccTime time); virtual void update(float time);
public: public:
/** creates the action with the same scale factor for X and Y */ /** creates the action with the same scale factor for X and Y
static CCScaleTo* actionWithDuration(ccTime duration, float s); @deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCScaleTo* actionWithDuration(float dura
tion, float s);
/** creates the action with and X factor and a Y factor
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCScaleTo* actionWithDuration(float dura
tion, float sx, float sy);
/** creates the action with and X factor and a Y factor */ /** creates the action with the same scale factor for X and Y */
static CCScaleTo* actionWithDuration(ccTime duration, float sx, floa static CCScaleTo* create(float duration, float s);
t sy);
/** creates the action with and X factor and a Y factor */
static CCScaleTo* create(float duration, float sx, float sy);
protected: protected:
float m_fScaleX; float m_fScaleX;
float m_fScaleY; float m_fScaleY;
float m_fStartScaleX; float m_fStartScaleX;
float m_fStartScaleY; float m_fStartScaleY;
float m_fEndScaleX; float m_fEndScaleX;
float m_fEndScaleY; float m_fEndScaleY;
float m_fDeltaX; float m_fDeltaX;
float m_fDeltaY; float m_fDeltaY;
}; };
/** @brief Scales a CCNode object a zoom factor by modifying it's scale att ribute. /** @brief Scales a CCNode object a zoom factor by modifying it's scale att ribute.
*/ */
class CC_DLL CCScaleBy : public CCScaleTo class CC_DLL CCScaleBy : public CCScaleTo
{ {
public: public:
virtual void startWithTarget(CCNode *pTarget); virtual void startWithTarget(CCNode *pTarget);
virtual CCActionInterval* reverse(void); virtual CCActionInterval* reverse(void);
virtual CCObject* copyWithZone(CCZone* pZone); virtual CCObject* copyWithZone(CCZone* pZone);
public: public:
/** creates the action with the same scale factor for X and Y */ /** creates the action with the same scale factor for X and Y
static CCScaleBy* actionWithDuration(ccTime duration, float s); @deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCScaleBy* actionWithDuration(float dura
tion, float s);
/** creates the action with and X factor and a Y factor
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCScaleBy* actionWithDuration(float dura
tion, float sx, float sy);
/** creates the action with and X factor and a Y factor */ /** creates the action with the same scale factor for X and Y */
static CCScaleBy* actionWithDuration(ccTime duration, float sx, floa static CCScaleBy* create(float duration, float s);
t sy);
/** creates the action with and X factor and a Y factor */
static CCScaleBy* create(float duration, float sx, float sy);
}; };
/** @brief Blinks a CCNode object by modifying it's visible attribute /** @brief Blinks a CCNode object by modifying it's visible attribute
*/ */
class CC_DLL CCBlink : public CCActionInterval class CC_DLL CCBlink : public CCActionInterval
{ {
public: public:
/** initializes the action */ /** initializes the action */
bool initWithDuration(ccTime duration, unsigned int uBlinks); bool initWithDuration(float duration, unsigned int uBlinks);
virtual CCObject* copyWithZone(CCZone* pZone);
virtual void update(ccTime time);
virtual CCActionInterval* reverse(void);
public: virtual CCObject* copyWithZone(CCZone* pZone);
/** creates the action */ virtual void update(float time);
static CCBlink* actionWithDuration(ccTime duration, unsigned int uBl virtual CCActionInterval* reverse(void);
inks);
public:
/** creates the action
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCBlink* actionWithDuration(float durati
on, unsigned int uBlinks);
/** creates the action */
static CCBlink* create(float duration, unsigned int uBlinks);
protected: protected:
unsigned int m_nTimes; unsigned int m_nTimes;
}; };
/** @brief Fades In an object that implements the CCRGBAProtocol protocol. It modifies the opacity from 0 to 255. /** @brief Fades In an object that implements the CCRGBAProtocol protocol. It modifies the opacity from 0 to 255.
The "reverse" of this action is FadeOut The "reverse" of this action is FadeOut
*/ */
class CC_DLL CCFadeIn : public CCActionInterval class CC_DLL CCFadeIn : public CCActionInterval
{ {
public: public:
virtual void update(ccTime time); virtual void update(float time);
virtual CCActionInterval* reverse(void); virtual CCActionInterval* reverse(void);
virtual CCObject* copyWithZone(CCZone* pZone); virtual CCObject* copyWithZone(CCZone* pZone);
public: public:
/** creates the action */ /** creates the action
static CCFadeIn* actionWithDuration(ccTime d); @deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCFadeIn* actionWithDuration(float d);
/** creates the action */
static CCFadeIn* create(float d);
}; };
/** @brief Fades Out an object that implements the CCRGBAProtocol protocol. It modifies the opacity from 255 to 0. /** @brief Fades Out an object that implements the CCRGBAProtocol protocol. It modifies the opacity from 255 to 0.
The "reverse" of this action is FadeIn The "reverse" of this action is FadeIn
*/ */
class CC_DLL CCFadeOut : public CCActionInterval class CC_DLL CCFadeOut : public CCActionInterval
{ {
public: public:
virtual void update(ccTime time); virtual void update(float time);
virtual CCActionInterval* reverse(void); virtual CCActionInterval* reverse(void);
virtual CCObject* copyWithZone(CCZone* pZone); virtual CCObject* copyWithZone(CCZone* pZone);
public: public:
/** creates the action */ /** creates the action
static CCFadeOut* actionWithDuration(ccTime d); @deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCFadeOut* actionWithDuration(float d);
/** creates the action */
static CCFadeOut* create(float d);
}; };
/** @brief Fades an object that implements the CCRGBAProtocol protocol. It modifies the opacity from the current value to a custom one. /** @brief Fades an object that implements the CCRGBAProtocol protocol. It modifies the opacity from the current value to a custom one.
@warning This action doesn't support "reverse" @warning This action doesn't support "reverse"
*/ */
class CC_DLL CCFadeTo : public CCActionInterval class CC_DLL CCFadeTo : public CCActionInterval
{ {
public: public:
/** initializes the action with duration and opacity */ /** initializes the action with duration and opacity */
bool initWithDuration(ccTime duration, GLubyte opacity); bool initWithDuration(float duration, GLubyte opacity);
virtual CCObject* copyWithZone(CCZone* pZone); virtual CCObject* copyWithZone(CCZone* pZone);
virtual void startWithTarget(CCNode *pTarget); virtual void startWithTarget(CCNode *pTarget);
virtual void update(ccTime time); virtual void update(float time);
public: public:
/** creates an action with duration and opacity */ /** creates an action with duration and opacity
static CCFadeTo* actionWithDuration(ccTime duration, GLubyte opacity @deprecated: This interface will be deprecated sooner or later.
); */
CC_DEPRECATED_ATTRIBUTE static CCFadeTo* actionWithDuration(float durat
ion, GLubyte opacity);
/** creates an action with duration and opacity */
static CCFadeTo* create(float duration, GLubyte opacity);
protected: protected:
GLubyte m_toOpacity; GLubyte m_toOpacity;
GLubyte m_fromOpacity; GLubyte m_fromOpacity;
}; };
/** @brief Tints a CCNode that implements the CCNodeRGB protocol from curre nt tint to a custom one. /** @brief Tints a CCNode that implements the CCNodeRGB protocol from curre nt tint to a custom one.
@warning This action doesn't support "reverse" @warning This action doesn't support "reverse"
@since v0.7.2 @since v0.7.2
*/ */
class CC_DLL CCTintTo : public CCActionInterval class CC_DLL CCTintTo : public CCActionInterval
{ {
public: public:
/** initializes the action with duration and color */ /** initializes the action with duration and color */
bool initWithDuration(ccTime duration, GLubyte red, GLubyte green, G bool initWithDuration(float duration, GLubyte red, GLubyte green, GLuby
Lubyte blue); te blue);
virtual CCObject* copyWithZone(CCZone* pZone); virtual CCObject* copyWithZone(CCZone* pZone);
virtual void startWithTarget(CCNode *pTarget); virtual void startWithTarget(CCNode *pTarget);
virtual void update(ccTime time); virtual void update(float time);
public: public:
/** creates an action with duration and color */ /** creates an action with duration and color
static CCTintTo* actionWithDuration(ccTime duration, GLubyte red, GL @deprecated: This interface will be deprecated sooner or later.
ubyte green, GLubyte blue); */
CC_DEPRECATED_ATTRIBUTE static CCTintTo* actionWithDuration(float durat
ion, GLubyte red, GLubyte green, GLubyte blue);
/** creates an action with duration and color */
static CCTintTo* create(float duration, GLubyte red, GLubyte green, GLu
byte blue);
protected: protected:
ccColor3B m_to; ccColor3B m_to;
ccColor3B m_from; ccColor3B m_from;
}; };
/** @brief Tints a CCNode that implements the CCNodeRGB protocol from curre nt tint to a custom one. /** @brief Tints a CCNode that implements the CCNodeRGB protocol from curre nt tint to a custom one.
@since v0.7.2 @since v0.7.2
*/ */
class CC_DLL CCTintBy : public CCActionInterval class CC_DLL CCTintBy : public CCActionInterval
{ {
public: public:
/** initializes the action with duration and color */ /** initializes the action with duration and color */
bool initWithDuration(ccTime duration, GLshort deltaRed, GLshort del bool initWithDuration(float duration, GLshort deltaRed, GLshort deltaGr
taGreen, GLshort deltaBlue); een, GLshort deltaBlue);
virtual CCObject* copyWithZone(CCZone* pZone); virtual CCObject* copyWithZone(CCZone* pZone);
virtual void startWithTarget(CCNode *pTarget); virtual void startWithTarget(CCNode *pTarget);
virtual void update(ccTime time); virtual void update(float time);
virtual CCActionInterval* reverse(void); virtual CCActionInterval* reverse(void);
public: public:
/** creates an action with duration and color */ /** creates an action with duration and color
static CCTintBy* actionWithDuration(ccTime duration, GLshort deltaRe @deprecated: This interface will be deprecated sooner or later.
d, GLshort deltaGreen, GLshort deltaBlue); */
CC_DEPRECATED_ATTRIBUTE static CCTintBy* actionWithDuration(float durat
protected: ion, GLshort deltaRed, GLshort deltaGreen, GLshort deltaBlue);
GLshort m_deltaR; /** creates an action with duration and color */
GLshort m_deltaG; static CCTintBy* create(float duration, GLshort deltaRed, GLshort delta
GLshort m_deltaB; Green, GLshort deltaBlue);
protected:
GLshort m_fromR; GLshort m_deltaR;
GLshort m_fromG; GLshort m_deltaG;
GLshort m_fromB; GLshort m_deltaB;
GLshort m_fromR;
GLshort m_fromG;
GLshort m_fromB;
}; };
/** @brief Delays the action a certain amount of seconds /** @brief Delays the action a certain amount of seconds
*/ */
class CC_DLL CCDelayTime : public CCActionInterval class CC_DLL CCDelayTime : public CCActionInterval
{ {
public: public:
virtual void update(ccTime time); virtual void update(float time);
virtual CCActionInterval* reverse(void); virtual CCActionInterval* reverse(void);
virtual CCObject* copyWithZone(CCZone* pZone); virtual CCObject* copyWithZone(CCZone* pZone);
public: public:
/** creates the action */ /** creates the action
static CCDelayTime* actionWithDuration(ccTime d); @deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCDelayTime* actionWithDuration(float d)
;
/** creates the action */
static CCDelayTime* create(float d);
}; };
/** @brief Executes an action in reverse order, from time=duration to time= 0 /** @brief Executes an action in reverse order, from time=duration to time= 0
@warning Use this action carefully. This action is not @warning Use this action carefully. This action is not
sequenceable. Use it as the default "reversed" method sequenceable. Use it as the default "reversed" method
of your own actions, but using it outside the "reversed" of your own actions, but using it outside the "reversed"
scope is not recommended. scope is not recommended.
*/ */
class CC_DLL CCReverseTime : public CCActionInterval class CC_DLL CCReverseTime : public CCActionInterval
{ {
public: public:
~CCReverseTime(void); ~CCReverseTime(void);
CCReverseTime(); CCReverseTime();
/** initializes the action */ /** initializes the action */
bool initWithAction(CCFiniteTimeAction *pAction); bool initWithAction(CCFiniteTimeAction *pAction);
virtual CCObject* copyWithZone(CCZone* pZone); virtual CCObject* copyWithZone(CCZone* pZone);
virtual void startWithTarget(CCNode *pTarget); virtual void startWithTarget(CCNode *pTarget);
virtual void stop(void); virtual void stop(void);
virtual void update(ccTime time); virtual void update(float time);
virtual CCActionInterval* reverse(void); virtual CCActionInterval* reverse(void);
public: public:
/** creates the action */ /** creates the action
static CCReverseTime* actionWithAction(CCFiniteTimeAction *pAction); @deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCReverseTime* actionWithAction(CCFinite
TimeAction *pAction);
/** creates the action */
static CCReverseTime* create(CCFiniteTimeAction *pAction);
protected: protected:
CCFiniteTimeAction *m_pOther; CCFiniteTimeAction *m_pOther;
}; };
class CCTexture2D; class CCTexture2D;
/** @brief Animates a sprite given the name of an Animation */ /** @brief Animates a sprite given the name of an Animation */
class CC_DLL CCAnimate : public CCActionInterval class CC_DLL CCAnimate : public CCActionInterval
{ {
public: public:
~CCAnimate(void); CCAnimate();
~CCAnimate();
/** Get animation used for the animate */
inline CCAnimation* getAnimation(void) { return m_pAnimation; }
/** Set animation used for the animate, the object is retained */
inline void setAnimation(CCAnimation *pAnimation)
{
CC_SAFE_RETAIN(pAnimation);
CC_SAFE_RELEASE(m_pAnimation);
m_pAnimation = pAnimation;
}
/** initializes the action with an Animation and will restore the or iginal frame when the animation is over */ /** initializes the action with an Animation and will restore the origi nal frame when the animation is over */
bool initWithAnimation(CCAnimation *pAnimation); bool initWithAnimation(CCAnimation *pAnimation);
/** initializes the action with an Animation */ virtual CCObject* copyWithZone(CCZone* pZone);
bool initWithAnimation(CCAnimation *pAnimation, bool bRestoreOrigina virtual void startWithTarget(CCNode *pTarget);
lFrame); virtual void stop(void);
virtual void update(float t);
/** initializes an action with a duration, animation and depending o virtual CCActionInterval* reverse(void);
f the restoreOriginalFrame, it will restore the original frame or not.
The 'delay' parameter of the animation will be overridden by the du public:
ration parameter. /** creates the action with an Animation and will restore the original
@since v0.99.0 frame when the animation is over
*/ @deprecated: This interface will be deprecated sooner or later.
bool initWithDuration(ccTime duration, CCAnimation *pAnimation, bool */
bRestoreOriginalFrame); CC_DEPRECATED_ATTRIBUTE static CCAnimate* actionWithAnimation(CCAnimati
on *pAnimation);
virtual CCObject* copyWithZone(CCZone* pZone); /** creates the action with an Animation and will restore the original
virtual void startWithTarget(CCNode *pTarget); frame when the animation is over */
virtual void stop(void); static CCAnimate* create(CCAnimation *pAnimation);
virtual void update(ccTime time); CC_SYNTHESIZE_RETAIN(CCAnimation*, m_pAnimation, Animation)
virtual CCActionInterval* reverse(void); protected:
std::vector<float>* m_pSplitTimes;
int m_nNextFrame;
CCSpriteFrame* m_pOrigFrame;
unsigned int m_uExecutedLoops;
};
/** Overrides the target of an action so that it always runs on the target
* specified at action creation rather than the one specified by runAction.
*/
class CC_DLL CCTargetedAction : public CCActionInterval
{
public: public:
/** creates the action with an Animation and will restore the origin CCTargetedAction();
al frame when the animation is over */ virtual ~CCTargetedAction();
static CCAnimate* actionWithAnimation(CCAnimation *pAnimation); /** Create an action with the specified action and forced target
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCTargetedAction* actionWithTarget(CCNod
e* pTarget, CCFiniteTimeAction* pAction);
/** Create an action with the specified action and forced target */
static CCTargetedAction* create(CCNode* pTarget, CCFiniteTimeAction* pA
ction);
/** creates the action with an Animation */ /** Init an action with the specified action and forced target */
static CCAnimate* actionWithAnimation(CCAnimation *pAnimation, bool bool initWithTarget(CCNode* pTarget, CCFiniteTimeAction* pAction);
bRestoreOriginalFrame);
/** creates an action with a duration, animation and depending of th virtual CCObject* copyWithZone(CCZone* pZone);
e restoreOriginalFrame, it will restore the original frame or not. virtual void startWithTarget(CCNode *pTarget);
The 'delay' parameter of the animation will be overridden by the du virtual void stop(void);
ration parameter. virtual void update(float time);
@since v0.99.0
*/ /** This is the target that the action will be forced to run with */
static CCAnimate* actionWithDuration(ccTime duration, CCAnimation *pAn CC_SYNTHESIZE_RETAIN(CCNode*, m_pForcedTarget, ForcedTarget);
imation, bool bRestoreOriginalFrame); private:
protected: CCFiniteTimeAction* m_pAction;
CCAnimation *m_pAnimation;
CCSpriteFrame *m_pOrigFrame;
bool m_bRestoreOriginalFrame;
}; };
} // end of actions group
/// @}
NS_CC_END
#endif //__ACTION_CCINTERVAL_ACTION_H__ #endif //__ACTION_CCINTERVAL_ACTION_H__
 End of changes. 96 change blocks. 
406 lines changed or deleted 566 lines changed or added


 CCActionManager.h   CCActionManager.h 
skipping to change at line 32 skipping to change at line 32
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __ACTION_CCACTION_MANAGER_H__ #ifndef __ACTION_CCACTION_MANAGER_H__
#define __ACTION_CCACTION_MANAGER_H__ #define __ACTION_CCACTION_MANAGER_H__
#include "CCAction.h" #include "CCAction.h"
#include "CCMutableArray.h" #include "cocoa/CCArray.h"
#include "CCObject.h" #include "cocoa/CCObject.h"
namespace cocos2d { NS_CC_BEGIN
class CCSet;
struct _hashElement; struct _hashElement;
/**
* @addtogroup actions
* @{
*/
/** /**
@brief CCActionManager is a singleton that manages all the actions. @brief CCActionManager is a singleton that manages all the actions.
Normally you won't need to use this singleton directly. 99% of the cases y ou will use the CCNode interface, Normally you won't need to use this singleton directly. 99% of the cases y ou will use the CCNode interface,
which uses this singleton. which uses this singleton.
But there are some cases where you might need to use this singleton. But there are some cases where you might need to use this singleton.
Examples: Examples:
- When you want to run an action where the target is different from - When you want to run an action where the target is different from a C
a CCNode. CNode.
- When you want to pause / resume the actions - When you want to pause / resume the actions
@since v0.8 @since v0.8
*/ */
class CC_DLL CCActionManager : public CCObject class CC_DLL CCActionManager : public CCObject
{ {
public: public:
CCActionManager(void); CCActionManager(void);
~CCActionManager(void); ~CCActionManager(void);
bool init(void);
// actions // actions
/** Adds an action with a target. /** Adds an action with a target.
If the target is already present, then the action will be added to If the target is already present, then the action will be added to the
the existing target. existing target.
If the target is not present, a new instance of this target will be If the target is not present, a new instance of this target will be cr
created either paused or not, and the action will be added to the newly cr eated either paused or not, and the action will be added to the newly creat
eated target. ed target.
When the target is paused, the queued actions won't be 'ticked'. When the target is paused, the queued actions won't be 'ticked'.
*/ */
void addAction(CCAction *pAction, CCNode *pTarget, bool paused); void addAction(CCAction *pAction, CCNode *pTarget, bool paused);
/** Removes all actions from all the targets. /** Removes all actions from all the targets.
*/ */
void removeAllActions(void); void removeAllActions(void);
/** Removes all actions from a certain target. /** Removes all actions from a certain target.
All the actions that belongs to the target will be removed. All the actions that belongs to the target will be removed.
*/ */
void removeAllActionsFromTarget(CCObject *pTarget); void removeAllActionsFromTarget(CCObject *pTarget);
/** Removes an action given an action reference. /** Removes an action given an action reference.
*/ */
void removeAction(CCAction *pAction); void removeAction(CCAction *pAction);
/** Removes an action given its tag and the target */ /** Removes an action given its tag and the target */
void removeActionByTag(unsigned int tag, CCObject *pTarget); void removeActionByTag(unsigned int tag, CCObject *pTarget);
/** Gets an action given its tag an a target /** Gets an action given its tag an a target
@return the Action the with the given tag @return the Action the with the given tag
*/ */
CCAction* getActionByTag(unsigned int tag, CCObject *pTarget); CCAction* getActionByTag(unsigned int tag, CCObject *pTarget);
/** Returns the numbers of actions that are running in a certain target . /** Returns the numbers of actions that are running in a certain target .
* Composable actions are counted as 1 action. Example: * Composable actions are counted as 1 action. Example:
* - If you are running 1 Sequence of 7 actions, it will return 1. * - If you are running 1 Sequence of 7 actions, it will return 1.
* - If you are running 7 Sequences of 2 actions, it will return 7. * - If you are running 7 Sequences of 2 actions, it will return 7.
*/ */
unsigned int numberOfRunningActionsInTarget(CCObject *pTarget); unsigned int numberOfRunningActionsInTarget(CCObject *pTarget);
/** Pauses the target: all running actions and newly added actions will be paused. /** Pauses the target: all running actions and newly added actions will be paused.
*/ */
void pauseTarget(CCObject *pTarget); void pauseTarget(CCObject *pTarget);
/** Resumes the target. All queued actions will be resumed. /** Resumes the target. All queued actions will be resumed.
*/ */
void resumeTarget(CCObject *pTarget); void resumeTarget(CCObject *pTarget);
/** purges the shared action manager. It releases the retained insta /** Pauses all running actions, returning a list of targets whose actio
nce. ns were paused.
* because it uses this, so it can not be static */
@since v0.99.0 CCSet* pauseAllRunningActions();
*/
void purgeSharedManager(void); /** Resume a set of targets (convenience function to reverse a pauseAll
RunningActions call)
public: */
/** returns a shared instance of the CCActionManager */ void resumeTargets(CCSet *targetsToResume);
static CCActionManager* sharedManager(void);
protected: protected:
// declared in CCActionManager.m // declared in CCActionManager.m
void removeActionAtIndex(unsigned int uIndex, struct _hashElement *p Element); void removeActionAtIndex(unsigned int uIndex, struct _hashElement *pEle ment);
void deleteHashElement(struct _hashElement *pElement); void deleteHashElement(struct _hashElement *pElement);
void actionAllocWithHashElement(struct _hashElement *pElement); void actionAllocWithHashElement(struct _hashElement *pElement);
void update(ccTime dt); void update(float dt);
protected: protected:
struct _hashElement *m_pTargets; struct _hashElement *m_pTargets;
struct _hashElement *m_pCurrentTarget; struct _hashElement *m_pCurrentTarget;
bool m_bCurrentTargetSalvaged; bool m_bCurrentTargetSalvaged;
}; };
} // end of actions group
/// @}
NS_CC_END
#endif // __ACTION_CCACTION_MANAGER_H__ #endif // __ACTION_CCACTION_MANAGER_H__
 End of changes. 20 change blocks. 
55 lines changed or deleted 64 lines changed or added


 CCActionPageTurn3D.h   CCActionPageTurn3D.h 
skipping to change at line 30 skipping to change at line 30
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __ACTION_CCPAGETURN3D_ACTION_H__ #ifndef __ACTION_CCPAGETURN3D_ACTION_H__
#define __ACTION_CCPAGETURN3D_ACTION_H__ #define __ACTION_CCPAGETURN3D_ACTION_H__
#include "CCActionGrid3D.h" #include "CCActionGrid3D.h"
namespace cocos2d NS_CC_BEGIN
/**
* @addtogroup actions
* @{
*/
/**
@brief This action simulates a page turn from the bottom right hand corner
of the screen.
It's not much use by itself but is used by the PageTurnTransition.
Based on an original paper by L Hong et al.
http://www.parc.com/publication/1638/turning-pages-of-3d-electronic-books.
html
@since v0.8.2
*/
class CC_DLL CCPageTurn3D : public CCGrid3DAction
{ {
/** public:
@brief This action simulates a page turn from the bottom right hand virtual void update(float time);
corner of the screen.
It's not much use by itself but is used by the PageTurnTransition. public:
/** create the action
Based on an original paper by L Hong et al. @deprecated: This interface will be deprecated sooner or later.
http://www.parc.com/publication/1638/turning-pages-of-3d-electronic */
-books.html CC_DEPRECATED_ATTRIBUTE static CCPageTurn3D* actionWithSize(const ccGri
dSize& gridSize, float time);
@since v0.8.2 /** create the action */
*/ static CCPageTurn3D* create(const ccGridSize& gridSize, float time);
class CC_DLL CCPageTurn3D : public CCGrid3DAction };
{
public: // end of actions group
virtual void update(ccTime time); /// @}
public: NS_CC_END
/** create the action */
static CCPageTurn3D* actionWithSize(const ccGridSize& gridSi
ze, ccTime time);
};
}
#endif // __ACTION_CCPAGETURN3D_ACTION_H__ #endif // __ACTION_CCPAGETURN3D_ACTION_H__
 End of changes. 2 change blocks. 
23 lines changed or deleted 36 lines changed or added


 CCActionProgressTimer.h   CCActionProgressTimer.h 
skipping to change at line 30 skipping to change at line 30
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __ACTION_CCPROGRESS_TIMER_H__ #ifndef __ACTION_CCPROGRESS_TIMER_H__
#define __ACTION_CCPROGRESS_TIMER_H__ #define __ACTION_CCPROGRESS_TIMER_H__
#include "CCActionInterval.h" #include "CCActionInterval.h"
namespace cocos2d NS_CC_BEGIN
{
/**
* @addtogroup actions
* @{
*/
/** /**
@brief Progress to percentage @brief Progress to percentage
@since v0.99.1 @since v0.99.1
*/ */
class CC_DLL CCProgressTo : public CCActionInterval class CC_DLL CCProgressTo : public CCActionInterval
{ {
public: public:
/** Initializes with a duration and a percent */ /** Initializes with a duration and a percent */
bool initWithDuration(ccTime duration, float fPercent); bool initWithDuration(float duration, float fPercent);
virtual CCObject* copyWithZone(CCZone *pZone); virtual CCObject* copyWithZone(CCZone *pZone);
virtual void startWithTarget(CCNode *pTarget); virtual void startWithTarget(CCNode *pTarget);
virtual void update(ccTime time); virtual void update(float time);
public: public:
/** Creates and initializes with a duration and a percent */ /** Creates and initializes with a duration and a percent
static CCProgressTo* actionWithDuration(ccTime duration, float fPerc @deprecated: This interface will be deprecated sooner or later.
ent); */
CC_DEPRECATED_ATTRIBUTE static CCProgressTo* actionWithDuration(float d
uration, float fPercent);
/** Creates and initializes with a duration and a percent */
static CCProgressTo* create(float duration, float fPercent);
protected: protected:
float m_fTo; float m_fTo;
float m_fFrom; float m_fFrom;
}; };
/** /**
@brief Progress from a percentage to another percentage @brief Progress from a percentage to another percentage
@since v0.99.1 @since v0.99.1
*/ */
class CC_DLL CCProgressFromTo : public CCActionInterval class CC_DLL CCProgressFromTo : public CCActionInterval
{ {
public: public:
/** Initializes the action with a duration, a "from" percentage and /** Initializes the action with a duration, a "from" percentage and a "
a "to" percentage */ to" percentage */
bool initWithDuration(ccTime duration, float fFromPercentage, float fTo bool initWithDuration(float duration, float fFromPercentage, float fToP
Percentage); ercentage);
virtual CCObject* copyWithZone(CCZone *pZone); virtual CCObject* copyWithZone(CCZone *pZone);
virtual CCActionInterval* reverse(void); virtual CCActionInterval* reverse(void);
virtual void startWithTarget(CCNode *pTarget); virtual void startWithTarget(CCNode *pTarget);
virtual void update(ccTime time); virtual void update(float time);
public: public:
/** Creates and initializes the action with a duration, a "from" per /** Creates and initializes the action with a duration, a "from" percen
centage and a "to" percentage */ tage and a "to" percentage
static CCProgressFromTo* actionWithDuration(ccTime duration, float f @deprecated: This interface will be deprecated sooner or later.
FromPercentage, float fToPercentage); */
CC_DEPRECATED_ATTRIBUTE static CCProgressFromTo* actionWithDuration(flo
at duration, float fFromPercentage, float fToPercentage);
/** Creates and initializes the action with a duration, a "from" percen
tage and a "to" percentage */
static CCProgressFromTo* create(float duration, float fFromPercentage,
float fToPercentage);
protected: protected:
float m_fTo; float m_fTo;
float m_fFrom; float m_fFrom;
}; };
} // end of namespace cocos2d // end of actions group
/// @}
NS_CC_END
#endif // __ACTION_CCPROGRESS_TIMER_H__ #endif // __ACTION_CCPROGRESS_TIMER_H__
 End of changes. 10 change blocks. 
29 lines changed or deleted 44 lines changed or added


 CCActionTiledGrid.h   CCActionTiledGrid.h 
skipping to change at line 30 skipping to change at line 30
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __ACTION_CCTILEDGRID_ACTION_H__ #ifndef __ACTION_CCTILEDGRID_ACTION_H__
#define __ACTION_CCTILEDGRID_ACTION_H__ #define __ACTION_CCTILEDGRID_ACTION_H__
#include "CCActionGrid.h" #include "CCActionGrid.h"
namespace cocos2d NS_CC_BEGIN
/**
* @addtogroup actions
* @{
*/
/** @brief CCShakyTiles3D action */
class CC_DLL CCShakyTiles3D : public CCTiledGrid3DAction
{
public:
/** initializes the action with a range, whether or not to shake Z vert
ices, a grid size, and duration */
bool initWithRange(int nRange, bool bShakeZ, const ccGridSize& gridSize
,
float duration);
virtual CCObject* copyWithZone(CCZone* pZone);
virtual void update(float time);
public:
/** creates the action with a range, whether or not to shake Z vertices
, a grid size, and duration
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCShakyTiles3D* actionWithRange(int nRan
ge, bool bShakeZ, const ccGridSize& gridSize, float duration);
/** creates the action with a range, whether or not to shake Z vertices
, a grid size, and duration */
static CCShakyTiles3D* create(int nRange, bool bShakeZ, const ccGridSiz
e& gridSize, float duration);
protected:
int m_nRandrange;
bool m_bShakeZ;
};
/** @brief CCShatteredTiles3D action */
class CC_DLL CCShatteredTiles3D : public CCTiledGrid3DAction
{
public:
/** initializes the action with a range, whether or not to shatter Z ve
rtices, a grid size and duration */
bool initWithRange(int nRange, bool bShatterZ, const ccGridSize& gridSi
ze,
float duration);
virtual CCObject* copyWithZone(CCZone* pZone);
virtual void update(float time);
public:
/** creates the action with a range, whether of not to shatter Z vertic
es, a grid size and duration
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCShatteredTiles3D* actionWithRange(int
nRange, bool bShatterZ, const ccGridSize& gridSize,
float duration);
/** creates the action with a range, whether of not to shatter Z vertic
es, a grid size and duration */
static CCShatteredTiles3D* create(int nRange, bool bShatterZ, const ccG
ridSize& gridSize,
float duration);
protected:
int m_nRandrange;
bool m_bOnce;
bool m_bShatterZ;
};
struct Tile;
/** @brief CCShuffleTiles action
Shuffle the tiles in random order
*/
class CC_DLL CCShuffleTiles : public CCTiledGrid3DAction
{
public:
~CCShuffleTiles(void);
/** initializes the action with a random seed, the grid size and the du
ration */
bool initWithSeed(int s, const ccGridSize& gridSize, float duration);
void shuffle(int *pArray, unsigned int nLen);
ccGridSize getDelta(const ccGridSize& pos);
void placeTile(const ccGridSize& pos, Tile *t);
virtual void startWithTarget(CCNode *pTarget);
virtual void update(float time);
virtual CCObject* copyWithZone(CCZone* pZone);
public:
/** creates the action with a random seed, the grid size and the durati
on
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCShuffleTiles* actionWithSeed(int s, co
nst ccGridSize& gridSize, float duration);
/** creates the action with a random seed, the grid size and the durati
on */
static CCShuffleTiles* create(int s, const ccGridSize& gridSize, float
duration);
protected:
int m_nSeed;
unsigned int m_nTilesCount;
int *m_pTilesOrder;
Tile *m_pTiles;
};
/** @brief CCFadeOutTRTiles action
Fades out the tiles in a Top-Right direction
*/
class CC_DLL CCFadeOutTRTiles : public CCTiledGrid3DAction
{ {
/** @brief CCShakyTiles3D action */ public:
class CC_DLL CCShakyTiles3D : public CCTiledGrid3DAction virtual float testFunc(const ccGridSize& pos, float time);
{ void turnOnTile(const ccGridSize& pos);
public: void turnOffTile(const ccGridSize& pos);
/** initializes the action with a range, whether or not to s virtual void transformTile(const ccGridSize& pos, float distance);
hake Z vertices, a grid size, and duration */ virtual void update(float time);
bool initWithRange(int nRange, bool bShakeZ, const ccGridSiz
e& gridSize, public:
ccTime duration); /** creates the action with the grid size and the duration
@deprecated: This interface will be deprecated sooner or later.
virtual CCObject* copyWithZone(CCZone* pZone); */
virtual void update(ccTime time); CC_DEPRECATED_ATTRIBUTE static CCFadeOutTRTiles* actionWithSize(const c
cGridSize& gridSize, float time);
public:
/** creates the action with a range, whether or not to shake /** creates the action with the grid size and the duration */
Z vertices, a grid size, and duration */ static CCFadeOutTRTiles* create(const ccGridSize& gridSize, float time)
static CCShakyTiles3D* actionWithRange(int nRange, bool bSha ;
keZ, const ccGridSize& gridSize, };
ccTime duration);
/** @brief CCFadeOutBLTiles action.
protected: Fades out the tiles in a Bottom-Left direction
int m_nRandrange; */
bool m_bShakeZ; class CC_DLL CCFadeOutBLTiles : public CCFadeOutTRTiles
}; {
public:
/** @brief CCShatteredTiles3D action */ virtual float testFunc(const ccGridSize& pos, float time);
class CC_DLL CCShatteredTiles3D : public CCTiledGrid3DAction
{ public:
public: /** creates the action with the grid size and the duration
/** initializes the action with a range, whether or not to s @deprecated: This interface will be deprecated sooner or later.
hatter Z vertices, a grid size and duration */ */
bool initWithRange(int nRange, bool bShatterZ, const ccGridSize& gr CC_DEPRECATED_ATTRIBUTE static CCFadeOutBLTiles* actionWithSize(const c
idSize, cGridSize& gridSize, float time);
ccTime duration);
/** creates the action with the grid size and the duration */
virtual CCObject* copyWithZone(CCZone* pZone); static CCFadeOutBLTiles* create(const ccGridSize& gridSize, float time)
virtual void update(ccTime time); ;
};
public:
/** creates the action with a range, whether of not to shatt /** @brief CCFadeOutUpTiles action.
er Z vertices, a grid size and duration */ Fades out the tiles in upwards direction
static CCShatteredTiles3D* actionWithRange(int nRange, bool */
bShatterZ, const ccGridSize& gridSize, class CC_DLL CCFadeOutUpTiles : public CCFadeOutTRTiles
ccTime duration); {
public:
protected: virtual float testFunc(const ccGridSize& pos, float time);
int m_nRandrange; virtual void transformTile(const ccGridSize& pos, float distance);
bool m_bOnce;
bool m_bShatterZ; public:
}; /** creates the action with the grid size and the duration
@deprecated: This interface will be deprecated sooner or later.
struct Tile; */
/** @brief CCShuffleTiles action CC_DEPRECATED_ATTRIBUTE static CCFadeOutUpTiles* actionWithSize(const c
Shuffle the tiles in random order cGridSize& gridSize, float time);
*/ /** creates the action with the grid size and the duration */
class CC_DLL CCShuffleTiles : public CCTiledGrid3DAction static CCFadeOutUpTiles* create(const ccGridSize& gridSize, float time)
{ ;
public:
~CCShuffleTiles(void); };
/** initializes the action with a random seed, the grid size
and the duration */ /** @brief CCFadeOutDownTiles action.
bool initWithSeed(int s, const ccGridSize& gridSize, ccTime Fades out the tiles in downwards direction
duration); */
void shuffle(int *pArray, unsigned int nLen); class CC_DLL CCFadeOutDownTiles : public CCFadeOutUpTiles
ccGridSize getDelta(const ccGridSize& pos); {
void placeTile(const ccGridSize& pos, Tile *t); public:
virtual float testFunc(const ccGridSize& pos, float time);
virtual void startWithTarget(CCNode *pTarget);
virtual void update(ccTime time); public:
virtual CCObject* copyWithZone(CCZone* pZone); /** creates the action with the grid size and the duration
@deprecated: This interface will be deprecated sooner or later.
public: */
/** creates the action with a random seed, the grid size and CC_DEPRECATED_ATTRIBUTE static CCFadeOutDownTiles* actionWithSize(const
the duration */ ccGridSize& gridSize, float time);
static CCShuffleTiles* actionWithSeed(int s, const ccGridSiz
e& gridSize, ccTime duration); /** creates the action with the grid size and the duration */
static CCFadeOutDownTiles* create(const ccGridSize& gridSize, float tim
protected: e);
int m_nSeed; };
unsigned int m_nTilesCount;
int *m_pTilesOrder; /** @brief CCTurnOffTiles action.
Tile *m_pTiles; Turn off the files in random order
}; */
class CC_DLL CCTurnOffTiles : public CCTiledGrid3DAction
/** @brief CCFadeOutTRTiles action {
Fades out the tiles in a Top-Right direction public:
*/ ~CCTurnOffTiles(void);
class CC_DLL CCFadeOutTRTiles : public CCTiledGrid3DAction /** initializes the action with a random seed, the grid size and the du
{ ration */
public: bool initWithSeed(int s, const ccGridSize& gridSize, float duration);
virtual float testFunc(const ccGridSize& pos, ccTime time); void shuffle(int *pArray, unsigned int nLen);
void turnOnTile(const ccGridSize& pos); void turnOnTile(const ccGridSize& pos);
void turnOffTile(const ccGridSize& pos); void turnOffTile(const ccGridSize& pos);
virtual void transformTile(const ccGridSize& pos, float dist
ance); virtual CCObject* copyWithZone(CCZone* pZone);
virtual void update(ccTime time); virtual void startWithTarget(CCNode *pTarget);
virtual void update(float time);
public:
/** creates the action with the grid size and the duration * public:
/ /** creates the action with the grid size and the duration
static CCFadeOutTRTiles* actionWithSize(const ccGridSize& gr @deprecated: This interface will be deprecated sooner or later.
idSize, ccTime time); */
}; CC_DEPRECATED_ATTRIBUTE static CCTurnOffTiles* actionWithSize(const ccG
ridSize& size, float d);
/** @brief CCFadeOutBLTiles action. /** creates the action with a random seed, the grid size and the durati
Fades out the tiles in a Bottom-Left direction on
*/ @deprecated: This interface will be deprecated sooner or later.
class CC_DLL CCFadeOutBLTiles : public CCFadeOutTRTiles */
{ CC_DEPRECATED_ATTRIBUTE static CCTurnOffTiles* actionWithSeed(int s, co
public: nst ccGridSize& gridSize, float duration);
virtual float testFunc(const ccGridSize& pos, ccTime time);
/** creates the action with the grid size and the duration */
public: static CCTurnOffTiles* create(const ccGridSize& size, float d);
/** creates the action with the grid size and the duration * /** creates the action with a random seed, the grid size and the durati
/ on */
static CCFadeOutBLTiles* actionWithSize(const ccGridSize& gridSize, static CCTurnOffTiles* create(int s, const ccGridSize& gridSize, float
ccTime time); duration);
};
protected:
/** @brief CCFadeOutUpTiles action. int m_nSeed;
Fades out the tiles in upwards direction unsigned int m_nTilesCount;
*/ int *m_pTilesOrder;
class CC_DLL CCFadeOutUpTiles : public CCFadeOutTRTiles };
{
public: /** @brief CCWavesTiles3D action. */
virtual float testFunc(const ccGridSize& pos, ccTime time); class CC_DLL CCWavesTiles3D : public CCTiledGrid3DAction
virtual void transformTile(const ccGridSize& pos, float dist {
ance); public:
/** waves amplitude */
public: inline float getAmplitude(void) { return m_fAmplitude; }
/** creates the action with the grid size and the duration * inline void setAmplitude(float fAmplitude) { m_fAmplitude = fAmplitude;
/ }
static CCFadeOutUpTiles* actionWithSize(const ccGridSize& gridSize,
ccTime time); /** waves amplitude rate */
}; inline float getAmplitudeRate(void) { return m_fAmplitudeRate; }
inline void setAmplitudeRate(float fAmplitudeRate) { m_fAmplitudeRate =
/** @brief CCFadeOutDownTiles action. fAmplitudeRate; }
Fades out the tiles in downwards direction
*/ /** initializes the action with a number of waves, the waves amplitude,
class CC_DLL CCFadeOutDownTiles : public CCFadeOutUpTiles the grid size and the duration */
{ bool initWithWaves(int wav, float amp, const ccGridSize& gridSize, floa
public: t duration);
virtual float testFunc(const ccGridSize& pos, ccTime time);
virtual CCObject* copyWithZone(CCZone* pZone);
public: virtual void update(float time);
/** creates the action with the grid size and the duration *
/ public:
static CCFadeOutDownTiles* actionWithSize(const ccGridSize& gridSiz /** creates the action with a number of waves, the waves amplitude, the
e, ccTime time); grid size and the duration
}; @deprecated: This interface will be deprecated sooner or later.
*/
/** @brief CCTurnOffTiles action. CC_DEPRECATED_ATTRIBUTE static CCWavesTiles3D* actionWithWaves(int wav,
Turn off the files in random order float amp, const ccGridSize& gridSize, float duration);
*/ /** creates the action with a number of waves, the waves amplitude, the
class CC_DLL CCTurnOffTiles : public CCTiledGrid3DAction grid size and the duration */
{ static CCWavesTiles3D* create(int wav, float amp, const ccGridSize& gri
public: dSize, float duration);
~CCTurnOffTiles(void); protected:
/** initializes the action with a random seed, the grid size int m_nWaves;
and the duration */ float m_fAmplitude;
bool initWithSeed(int s, const ccGridSize& gridSize, ccTime float m_fAmplitudeRate;
duration); };
void shuffle(int *pArray, unsigned int nLen);
void turnOnTile(const ccGridSize& pos); /** @brief CCJumpTiles3D action.
void turnOffTile(const ccGridSize& pos); A sin function is executed to move the tiles across the Z axis
*/
virtual CCObject* copyWithZone(CCZone* pZone); class CC_DLL CCJumpTiles3D : public CCTiledGrid3DAction
virtual void startWithTarget(CCNode *pTarget); {
virtual void update(ccTime time); public:
/** amplitude of the sin*/
public: inline float getAmplitude(void) { return m_fAmplitude; }
/** creates the action with the grid size and the duration * inline void setAmplitude(float fAmplitude) { m_fAmplitude = fAmplitude;
/ }
static CCTurnOffTiles* actionWithSize(const ccGridSize& size
, ccTime d); /** amplitude rate */
/** creates the action with a random seed, the grid size and inline float getAmplitudeRate(void) { return m_fAmplitudeRate; }
the duration */ inline void setAmplitudeRate(float fAmplitudeRate) { m_fAmplitudeRate =
static CCTurnOffTiles* actionWithSeed(int s, const ccGridSiz fAmplitudeRate; }
e& gridSize, ccTime duration);
/** initializes the action with the number of jumps, the sin amplitude,
protected: the grid size and the duration */
int m_nSeed; bool initWithJumps(int j, float amp, const ccGridSize& gridSize, float
unsigned int m_nTilesCount; duration);
int *m_pTilesOrder; virtual CCObject* copyWithZone(CCZone* pZone);
}; virtual void update(float time);
/** @brief CCWavesTiles3D action. */ public:
class CC_DLL CCWavesTiles3D : public CCTiledGrid3DAction /** creates the action with the number of jumps, the sin amplitude, the
{ grid size and the duration
public: @deprecated: This interface will be deprecated sooner or later.
/** waves amplitude */ */
inline float getAmplitude(void) { return m_fAmplitude; } CC_DEPRECATED_ATTRIBUTE static CCJumpTiles3D* actionWithJumps(int j, fl
inline void setAmplitude(float fAmplitude) { m_fAmplitude = oat amp, const ccGridSize& gridSize, float duration);
fAmplitude; } /** creates the action with the number of jumps, the sin amplitude, the
grid size and the duration */
/** waves amplitude rate */ static CCJumpTiles3D* create(int j, float amp, const ccGridSize& gridSi
inline float getAmplitudeRate(void) { return m_fAmplitudeRat ze, float duration);
e; } protected:
inline void setAmplitudeRate(float fAmplitudeRate) { m_fAmpl int m_nJumps;
itudeRate = fAmplitudeRate; } float m_fAmplitude;
float m_fAmplitudeRate;
/** initializes the action with a number of waves, the waves };
amplitude, the grid size and the duration */
bool initWithWaves(int wav, float amp, const ccGridSize& gri /** @brief CCSplitRows action */
dSize, ccTime duration); class CC_DLL CCSplitRows : public CCTiledGrid3DAction
{
virtual CCObject* copyWithZone(CCZone* pZone); public :
virtual void update(ccTime time); /** initializes the action with the number of rows to split and the dur
ation */
public: bool initWithRows(int nRows, float duration);
/** creates the action with a number of waves, the waves amp
litude, the grid size and the duration */ virtual CCObject* copyWithZone(CCZone* pZone);
static CCWavesTiles3D* actionWithWaves(int wav, float amp, c virtual void update(float time);
onst ccGridSize& gridSize, ccTime duration); virtual void startWithTarget(CCNode *pTarget);
protected: public:
int m_nWaves; /** creates the action with the number of rows to split and the duratio
float m_fAmplitude; n
float m_fAmplitudeRate; @deprecated: This interface will be deprecated sooner or later.
}; */
CC_DEPRECATED_ATTRIBUTE static CCSplitRows* actionWithRows(int nRows, f
/** @brief CCJumpTiles3D action. loat duration);
A sin function is executed to move the tiles across the Z axis /** creates the action with the number of rows to split and the duratio
*/ n */
class CC_DLL CCJumpTiles3D : public CCTiledGrid3DAction static CCSplitRows* create(int nRows, float duration);
{ protected:
public: int m_nRows;
/** amplitude of the sin*/ CCSize m_winSize;
inline float getAmplitude(void) { return m_fAmplitude; } };
inline void setAmplitude(float fAmplitude) { m_fAmplitude =
fAmplitude; } /** @brief CCSplitCols action */
class CC_DLL CCSplitCols : public CCTiledGrid3DAction
/** amplitude rate */ {
inline float getAmplitudeRate(void) { return m_fAmplitudeRat public:
e; } /** initializes the action with the number of columns to split and the
inline void setAmplitudeRate(float fAmplitudeRate) { m_fAmpl duration */
itudeRate = fAmplitudeRate; } bool initWithCols(int nCols, float duration);
/** initializes the action with the number of jumps, the sin virtual CCObject* copyWithZone(CCZone* pZone);
amplitude, the grid size and the duration */ virtual void update(float time);
bool initWithJumps(int j, float amp, const ccGridSize& gridS virtual void startWithTarget(CCNode *pTarget);
ize, ccTime duration);
virtual CCObject* copyWithZone(CCZone* pZone); public:
virtual void update(ccTime time); /** creates the action with the number of columns to split and the dura
tion
public: @deprecated: This interface will be deprecated sooner or later.
/** creates the action with the number of jumps, the sin amp */
litude, the grid size and the duration */ CC_DEPRECATED_ATTRIBUTE static CCSplitCols* actionWithCols(int nCols, f
static CCJumpTiles3D* actionWithJumps(int j, float amp, const ccGri loat duration);
dSize& gridSize, ccTime duration); /** creates the action with the number of columns to split and the dura
tion */
protected: static CCSplitCols* create(int nCols, float duration);
int m_nJumps; protected:
float m_fAmplitude; int m_nCols;
float m_fAmplitudeRate; CCSize m_winSize;
}; };
/** @brief CCSplitRows action */ // end of actions group
class CC_DLL CCSplitRows : public CCTiledGrid3DAction /// @}
{
public : NS_CC_END
/** initializes the action with the number of rows to split
and the duration */
bool initWithRows(int nRows, ccTime duration);
virtual CCObject* copyWithZone(CCZone* pZone);
virtual void update(ccTime time);
virtual void startWithTarget(CCNode *pTarget);
public:
/** creates the action with the number of rows to split and
the duration */
static CCSplitRows* actionWithRows(int nRows, ccTime duratio
n);
protected:
int m_nRows;
CCSize m_winSize;
};
/** @brief CCSplitCols action */
class CC_DLL CCSplitCols : public CCTiledGrid3DAction
{
public:
/** initializes the action with the number of columns to spl
it and the duration */
bool initWithCols(int nCols, ccTime duration);
virtual CCObject* copyWithZone(CCZone* pZone);
virtual void update(ccTime time);
virtual void startWithTarget(CCNode *pTarget);
public:
/** creates the action with the number of columns to split a
nd the duration */
static CCSplitCols* actionWithCols(int nCols, ccTime duratio
n);
protected:
int m_nCols;
CCSize m_winSize;
};
} // end of namespace cocos2d
#endif // __ACTION_CCTILEDGRID_ACTION_H__ #endif // __ACTION_CCTILEDGRID_ACTION_H__
 End of changes. 2 change blocks. 
304 lines changed or deleted 373 lines changed or added


 CCAffineTransform.h   CCAffineTransform.h 
skipping to change at line 29 skipping to change at line 29
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __COCOA_CGAFFINETRANSFORM_H__ #ifndef __COCOA_CGAFFINETRANSFORM_H__
#define __COCOA_CGAFFINETRANSFORM_H__ #define __COCOA_CGAFFINETRANSFORM_H__
#include "CCGeometry.h" #include "CCGeometry.h"
#include "CCPlatformMacros.h" #include "platform/CCPlatformMacros.h"
namespace cocos2d { NS_CC_BEGIN
struct CCAffineTransform { struct CCAffineTransform {
CGFloat a, b, c, d; float a, b, c, d;
CGFloat tx, ty; float tx, ty;
}; };
CC_DLL CCAffineTransform __CCAffineTransformMake(CGFloat a, CGFloat b, CGFl oat c, CGFloat d, CGFloat tx, CGFloat ty); CC_DLL CCAffineTransform __CCAffineTransformMake(float a, float b, float c, float d, float tx, float ty);
#define CCAffineTransformMake __CCAffineTransformMake #define CCAffineTransformMake __CCAffineTransformMake
CC_DLL CCPoint __CCPointApplyAffineTransform(const CCPoint& point, const CC AffineTransform& t); CC_DLL CCPoint __CCPointApplyAffineTransform(const CCPoint& point, const CC AffineTransform& t);
#define CCPointApplyAffineTransform __CCPointApplyAffineTransform #define CCPointApplyAffineTransform __CCPointApplyAffineTransform
CC_DLL CCSize __CCSizeApplyAffineTransform(const CCSize& size, const CCAffi neTransform& t); CC_DLL CCSize __CCSizeApplyAffineTransform(const CCSize& size, const CCAffi neTransform& t);
#define CCSizeApplyAffineTransform __CCSizeApplyAffineTransform #define CCSizeApplyAffineTransform __CCSizeApplyAffineTransform
CC_DLL CCAffineTransform CCAffineTransformMakeIdentity(); CC_DLL CCAffineTransform CCAffineTransformMakeIdentity();
CC_DLL CCRect CCRectApplyAffineTransform(const CCRect& rect, const CCAffine Transform& anAffineTransform); CC_DLL CCRect CCRectApplyAffineTransform(const CCRect& rect, const CCAffine Transform& anAffineTransform);
CC_DLL CCAffineTransform CCAffineTransformTranslate(const CCAffineTransform & t, float tx, float ty); CC_DLL CCAffineTransform CCAffineTransformTranslate(const CCAffineTransform & t, float tx, float ty);
CC_DLL CCAffineTransform CCAffineTransformRotate(const CCAffineTransform& a CC_DLL CCAffineTransform CCAffineTransformRotate(const CCAffineTransform& a
Transform, CGFloat anAngle); Transform, float anAngle);
CC_DLL CCAffineTransform CCAffineTransformScale(const CCAffineTransform& t, CC_DLL CCAffineTransform CCAffineTransformScale(const CCAffineTransform& t,
CGFloat sx, CGFloat sy); float sx, float sy);
CC_DLL CCAffineTransform CCAffineTransformConcat(const CCAffineTransform& t 1, const CCAffineTransform& t2); CC_DLL CCAffineTransform CCAffineTransformConcat(const CCAffineTransform& t 1, const CCAffineTransform& t2);
CC_DLL bool CCAffineTransformEqualToTransform(const CCAffineTransform& t1, const CCAffineTransform& t2); CC_DLL bool CCAffineTransformEqualToTransform(const CCAffineTransform& t1, const CCAffineTransform& t2);
CC_DLL CCAffineTransform CCAffineTransformInvert(const CCAffineTransform& t ); CC_DLL CCAffineTransform CCAffineTransformInvert(const CCAffineTransform& t );
extern const CCAffineTransform CCAffineTransformIdentity; extern CC_DLL const CCAffineTransform CCAffineTransformIdentity;
}//namespace cocos2d
NS_CC_END
#endif // __COCOA_CGAFFINETRANSFORM_H__ #endif // __COCOA_CGAFFINETRANSFORM_H__
 End of changes. 6 change blocks. 
11 lines changed or deleted 12 lines changed or added


 CCAnimation.h   CCAnimation.h 
skipping to change at line 29 skipping to change at line 29
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CC_ANIMATION_H__ #ifndef __CC_ANIMATION_H__
#define __CC_ANIMATION_H__ #define __CC_ANIMATION_H__
#include "CCPlatformConfig.h" #include "platform/CCPlatformConfig.h"
#include "CCObject.h" #include "cocoa/CCObject.h"
#include "CCMutableArray.h" #include "cocoa/CCArray.h"
#include "CCGeometry.h" #include "cocoa/CCDictionary.h"
#include "cocoa/CCGeometry.h"
#include "CCSpriteFrame.h"
#include <string> #include <string>
namespace cocos2d { NS_CC_BEGIN
class CCSpriteFrame;
class CCTexture2D; class CCTexture2D;
/** A CCAnimation object is used to perform animations on the CCSpri class CCSpriteFrame;
te objects.
/**
The CCAnimation object contains CCSpriteFrame objects, and a possibl * @addtogroup sprite_nodes
e delay between the frames. * @{
You can animate a CCAnimation object by using the CCAnimate action. */
Example:
/** CCAnimationFrame
[sprite runAction:[CCAnimate actionWithAnimation:animation]]; A frame of the animation. It contains information like:
- sprite frame name
*/ - # of delay units.
class CC_DLL CCAnimation : public CCObject - offset
{
protected: @since v2.0
std::string m_nameStr; */
float m_fDelay; class CC_DLL CCAnimationFrame : public CCObject
CCMutableArray<CCSpriteFrame*> *m_pobFrames; {
public:
public: CCAnimationFrame();
// attributes virtual ~CCAnimationFrame();
virtual CCObject* copyWithZone(CCZone* pZone);
/** get name of the animation */ /** initializes the animation frame with a spriteframe, number of delay
inline const char* getName(void) { return m_nameStr.c_str(); units and a notification user info */
} bool initWithSpriteFrame(CCSpriteFrame* spriteFrame, float delayUnits,
/** set name of the animation */ CCDictionary* userInfo);
inline void setName(const char *pszName){ m_nameStr = pszNam
e; } /** CCSpriteFrameName to be used */
CC_SYNTHESIZE_RETAIN(CCSpriteFrame*, m_pSpriteFrame, SpriteFrame)
/** get delay between frames in seconds */
inline float getDelay(void) { return m_fDelay; } /** how many units of time the frame takes */
/** set delay between frames in seconds */ CC_SYNTHESIZE(float, m_fDelayUnits, DelayUnits)
inline void setDelay(float fDelay) { m_fDelay = fDelay; }
/** A CCAnimationFrameDisplayedNotification notification will be broad
/** get array of frames */ casted when the frame is displayed with this dictionary as UserInfo. If Use
inline CCMutableArray<CCSpriteFrame*>* getFrames(void) { ret rInfo is nil, then no notification will be broadcasted. */
urn m_pobFrames; } CC_SYNTHESIZE_RETAIN(CCDictionary*, m_pUserInfo, UserInfo)
/** set array of frames, the Frames is retained */ };
inline void setFrames(CCMutableArray<CCSpriteFrame*> *pFrame
s) /** A CCAnimation object is used to perform animations on the CCSprite obje
{ cts.
CC_SAFE_RETAIN(pFrames);
CC_SAFE_RELEASE(m_pobFrames); The CCAnimation object contains CCAnimationFrame objects, and a possible de
m_pobFrames = pFrames; lay between the frames.
} You can animate a CCAnimation object by using the CCAnimate action. Example
:
public:
~CCAnimation(void); [sprite runAction:[CCAnimate actionWithAnimation:animation]];
/** Initializes a CCAnimation with frames. */
@since v0.99.5 class CC_DLL CCAnimation : public CCObject
*/ {
bool initWithFrames(CCMutableArray<CCSpriteFrame*> *pFrames) public:
; CCAnimation();
~CCAnimation(void);
/** Initializes a CCAnimation with frames and a delay betwee public:
n frames /** Creates an animation
@since v0.99.5 @deprecated: This interface will be deprecated sooner or later.
*/ @since v0.99.5
bool initWithFrames(CCMutableArray<CCSpriteFrame*> *pFrames, */
float delay); CC_DEPRECATED_ATTRIBUTE static CCAnimation* animation(void);
/** adds a frame to a CCAnimation */ /* Creates an animation with an array of CCSpriteFrame and a delay betw
void addFrame(CCSpriteFrame *pFrame); een frames in seconds.
The frames will be added with one "delay unit".
/** Adds a frame with an image filename. Internally it will @deprecated: This interface will be deprecated sooner or later.
create a CCSpriteFrame and it will add it. @since v0.99.5
Added to facilitate the migration from v0.8 to v0.9. */
*/ CC_DEPRECATED_ATTRIBUTE static CCAnimation* animationWithSpriteFrames(C
void addFrameWithFileName(const char *pszFileName); CArray* arrayOfSpriteFrameNames, float delay = 0.0f);
/** Adds a frame with a texture and a rect. Internally it wi /* Creates an animation with an array of CCAnimationFrame, the delay pe
ll create a CCSpriteFrame and it will add it. r units in seconds and and how many times it should be executed.
Added to facilitate the migration from v0.8 to v0.9. @deprecated: This interface will be deprecated sooner or later.
*/ @since v2.0
void addFrameWithTexture(CCTexture2D* pobTexture, const CCRe */
ct& rect); CC_DEPRECATED_ATTRIBUTE static CCAnimation* animationWithAnimationFrame
s(CCArray *arrayOfAnimationFrameNames, float delayPerUnit, unsigned int loo
bool init(void); ps);
public: /** Creates an animation
/** Creates an animation @since v0.99.5
@since v0.99.5 */
*/ static CCAnimation* create(void);
static CCAnimation* animation(void);
/* Creates an animation with an array of CCSpriteFrame and a delay betw
/** Creates an animation with frames. een frames in seconds.
@since v0.99.5 The frames will be added with one "delay unit".
*/ @since v0.99.5
static CCAnimation* animationWithFrames(CCMutableArray<CCSpr */
iteFrame*> *frames); static CCAnimation* createWithSpriteFrames(CCArray* arrayOfSpriteFrameN
ames, float delay = 0.0f);
/* Creates an animation with frames and a delay between fram
es. /* Creates an animation with an array of CCAnimationFrame, the delay pe
@since v0.99.5 r units in seconds and and how many times it should be executed.
*/ @since v2.0
static CCAnimation* animationWithFrames(CCMutableArray<CCSpr */
iteFrame*> *frames, float delay); static CCAnimation* create(CCArray *arrayOfAnimationFrameNames, float d
}; elayPerUnit, unsigned int loops);
} // end of name sapce cocos2d
/** Adds a CCSpriteFrame to a CCAnimation.
The frame will be added with one "delay unit".
*/
void addSpriteFrame(CCSpriteFrame *pFrame);
/** Adds a frame with an image filename. Internally it will create a CC
SpriteFrame and it will add it.
The frame will be added with one "delay unit".
Added to facilitate the migration from v0.8 to v0.9.
*/
void addSpriteFrameWithFileName(const char *pszFileName);
/** Adds a frame with a texture and a rect. Internally it will create a
CCSpriteFrame and it will add it.
The frame will be added with one "delay unit".
Added to facilitate the migration from v0.8 to v0.9.
*/
void addSpriteFrameWithTexture(CCTexture2D* pobTexture, const CCRect& r
ect);
bool init();
/** Initializes a CCAnimation with frames and a delay between frames
@since v0.99.5
*/
bool initWithSpriteFrames(CCArray *pFrames, float delay = 0.0f);
/** Initializes a CCAnimation with CCAnimationFrame
@since v2.0
*/
bool initWithAnimationFrames(CCArray* arrayOfAnimationFrames, float del
ayPerUnit, unsigned int loops);
virtual CCObject* copyWithZone(CCZone* pZone);
/** total Delay units of the CCAnimation. */
CC_SYNTHESIZE_READONLY(float, m_fTotalDelayUnits, TotalDelayUnits)
/** Delay in seconds of the "delay unit" */
CC_SYNTHESIZE(float, m_fDelayPerUnit, DelayPerUnit)
/** duration in seconds of the whole animation. It is the result of tot
alDelayUnits * delayPerUnit */
CC_PROPERTY_READONLY(float, m_fDuration, Duration)
/** array of CCAnimationFrames */
CC_SYNTHESIZE_RETAIN(CCArray*, m_pFrames, Frames)
/** whether or not it shall restore the original frame when the animati
on finishes */
CC_SYNTHESIZE(bool, m_bRestoreOriginalFrame, RestoreOriginalFrame)
/** how many times the animation is going to loop. 0 means animation is
not animated. 1, animation is executed one time, ... */
CC_SYNTHESIZE(unsigned int, m_uLoops, Loops)
};
// end of sprite_nodes group
/// @}
NS_CC_END
#endif // __CC_ANIMATION_H__ #endif // __CC_ANIMATION_H__
 End of changes. 2 change blocks. 
106 lines changed or deleted 169 lines changed or added


 CCAnimationCache.h   CCAnimationCache.h 
skipping to change at line 29 skipping to change at line 29
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CC_ANIMATION_CACHE_H__ #ifndef __CC_ANIMATION_CACHE_H__
#define __CC_ANIMATION_CACHE_H__ #define __CC_ANIMATION_CACHE_H__
#include "CCObject.h" #include "cocoa/CCObject.h"
#include "CCMutableDictionary.h" #include "cocoa/CCDictionary.h"
#include <string> #include <string>
namespace cocos2d NS_CC_BEGIN
{
class CCAnimation; class CCAnimation;
/**
* @addtogroup sprite_nodes
* @{
*/
/** Singleton that manages the Animations. /** Singleton that manages the Animations.
It saves in a cache the animations. You should use this class if you It saves in a cache the animations. You should use this class if you want t
want to save your animations in a cache. o save your animations in a cache.
Before v0.99.5, the recommend way was to save them on the CCSprite. Since v
0.99.5, you should use this class instead.
@since v0.99.5
*/
class CC_DLL CCAnimationCache : public CCObject
{
public:
CCAnimationCache();
~CCAnimationCache();
/** Retruns ths shared instance of the Animation cache */
static CCAnimationCache* sharedAnimationCache(void);
/** Purges the cache. It releases all the CCAnimation objects and the s
hared instance.
*/
static void purgeSharedAnimationCache(void);
/** Adds a CCAnimation with a name.
*/
void addAnimation(CCAnimation *animation, const char * name);
/** Deletes a CCAnimation from the cache.
*/
void removeAnimationByName(const char* name);
/** Returns a CCAnimation that was previously added.
If the name is not found it will return nil.
You should retain the returned copy if you are going to use it.
*/
CCAnimation* animationByName(const char* name);
/** Adds an animation from an NSDictionary
Make sure that the frames were previously loaded in the CCSpriteFrameC
ache.
@since v1.1
*/
void addAnimationsWithDictionary(CCDictionary* dictionary);
/** Adds an animation from a plist file.
Make sure that the frames were previously loaded in the CCSpriteFrameC
ache.
@since v1.1
*/
void addAnimationsWithFile(const char* plist);
bool init(void);
private:
void parseVersion1(CCDictionary* animations);
void parseVersion2(CCDictionary* animations);
private:
CCDictionary* m_pAnimations;
static CCAnimationCache* s_pSharedAnimationCache;
};
Before v0.99.5, the recommend way was to save them on the CCSprite. // end of sprite_nodes group
Since v0.99.5, you should use this class instead. /// @}
@since v0.99.5 NS_CC_END
*/
class CC_DLL CCAnimationCache : public CCObject
{
public:
~CCAnimationCache();
CCAnimationCache();
/** Retruns ths shared instance of the Animation cache */
static CCAnimationCache* sharedAnimationCache(void);
/** Purges the cache. It releases all the CCAnimation object
s and the shared instance.
*/
static void purgeSharedAnimationCache(void);
/** Adds a CCAnimation with a name.
*/
void addAnimation(CCAnimation *animation, const char * name)
;
/** Deletes a CCAnimation from the cache.
*/
void removeAnimationByName(const char* name);
/** Returns a CCAnimation that was previously added.
If the name is not found it will return nil.
You should retain the returned copy if you are going to use
it.
*/
CCAnimation* animationByName(const char* name);
bool init(void);
private:
CCMutableDictionary<std::string, CCAnimation*> *m_pAnimation
s;
static CCAnimationCache *s_pSharedAnimationCache;
};
}
#endif // __CC_ANIMATION_CACHE_H__ #endif // __CC_ANIMATION_CACHE_H__
 End of changes. 5 change blocks. 
50 lines changed or deleted 72 lines changed or added


 CCApplication.h   CCApplication.h 
skipping to change at line 25 skipping to change at line 25
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CC_APPLICATION_H__ #ifndef __CC_APPLICATION_IOS_H__
#define __CC_APPLICATION_H__ #define __CC_APPLICATION_IOS_H__
#include "platform/CCApplication_platform.h" #include "platform/CCCommon.h"
#include "platform/CCApplicationProtocol.h"
#endif // __CC_APPLICATION_H__ NS_CC_BEGIN
class CCRect;
class CC_DLL CCApplication : public CCApplicationProtocol
{
public:
CCApplication();
virtual ~CCApplication();
/**
@brief Run the message loop.
*/
int run();
/**
@brief Get current applicaiton instance.
@return Current application instance pointer.
*/
static CCApplication* sharedApplication();
/**
@brief Callback by CCDirector for limit FPS.
@interval The time, which expressed in second in second, between
current frame and next.
*/
virtual void setAnimationInterval(double interval);
/**
@brief Get current language config
@return Current language config
*/
virtual ccLanguageType getCurrentLanguage();
/**
@brief Get target platform
*/
virtual TargetPlatform getTargetPlatform();
protected:
static CCApplication * sm_pSharedApplication;
};
NS_CC_END
#endif // end of __CC_APPLICATION_IOS_H__
 End of changes. 3 change blocks. 
3 lines changed or deleted 4 lines changed or added


 CCArray.h   CCArray.h 
skipping to change at line 30 skipping to change at line 30
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CCARRAY_H__ #ifndef __CCARRAY_H__
#define __CCARRAY_H__ #define __CCARRAY_H__
#include "support/data_support/ccCArray.h" #include "support/data_support/ccCArray.h"
/**
* @addtogroup data_structures
* @{
*/
/** @def CCARRAY_FOREACH /** @def CCARRAY_FOREACH
A convience macro to iterate over a CCArray using. It is faster than the "f ast enumeration" interface. A convience macro to iterate over a CCArray using. It is faster than the "f ast enumeration" interface.
@since v0.99.4 @since v0.99.4
*/ */
/* /*
In cocos2d-iphone 1.0.0, This macro have been update to like this: In cocos2d-iphone 1.0.0, This macro have been update to like this:
#define CCARRAY_FOREACH(__array__, __object__) #define CCARRAY_FOREACH(__array__, __object__)
\ \
if (__array__ && __array__->data->num > 0) if (__array__ && __array__->data->num > 0)
\ \
for(id *__arr__ = __array__->data->arr, *end = __array__->data->arr + __arr for(id *__arr__ = __array__->data->arr, *end = __array__->data->arr + __arr
ay__->data->num-1; \ ay__->data->num-1; \
__arr__ <= end && ((__object__ = *__arr__) != nil || true); __arr__ <= end && ((__object__ = *__arr__) != nil || true);
\ \
__arr__++) __arr__++)
I found that it's not work in C++. So it keep what it's look like in versio n 1.0.0-rc3. ---By Bin I found that it's not work in C++. So it keep what it's look like in versio n 1.0.0-rc3. ---By Bin
*/ */
#define CCARRAY_FOREACH(__array__, __object__) #define CCARRAY_FOREACH(__array__, __object__)
\ \
if (__array__ && __array__->data->num > 0) if ((__array__) && (__array__)->data->num > 0)
\ \
for(CCObject** arr = __array__->data->arr, **end = __array__->data->arr for(CCObject** arr = (__array__)->data->arr, **end = (__array__)->data-
+ __array__->data->num-1; \ >arr + (__array__)->data->num-1; \
arr <= end && ((__object__ = *arr) != NULL/* || true*/); arr <= end && (((__object__) = *arr) != NULL/* || true*/);
\ \
arr++) arr++)
namespace cocos2d #define CCARRAY_FOREACH_REVERSE(__array__, __object__)
{ \
if ((__array__) && (__array__)->data->num > 0)
\
for(CCObject** arr = (__array__)->data->arr + (__array__)->data->num-1,
**end = (__array__)->data->arr; \
arr >= end && (((__object__) = *arr) != NULL/* || true*/);
\
arr--)
#if defined(COCOS2D_DEBUG) && (COCOS2D_DEBUG > 0)
#define CCARRAY_VERIFY_TYPE(__array__, __type__)
\
do {
\
if ((__array__) && (__array__)->data->num > 0)
\
for(CCObject** arr = (__array__)->data->arr,
\
**end = (__array__)->data->arr + (__array__)->data->num-1;
arr <= end; arr++) \
CCAssert(dynamic_cast<__type__>(*arr), "element type is wro
ng!"); \
} while(false)
#else
#define CCARRAY_VERIFY_TYPE(__array__, __type__) void(0)
#endif
#define arrayMakeObjectsPerformSelector(pArray, func, elementType) \
do { \
if(pArray && pArray->count() > 0) \
{ \
CCObject* child; \
CCARRAY_FOREACH(pArray, child) \
{ \
elementType pNode = (elementType) child; \
if(pNode) \
{ \
pNode->func(); \
} \
} \
} \
} \
while(false)
#define arrayMakeObjectsPerformSelectorWithObject(pArray, func, pObject, el
ementType) \
do { \
if(pArray && pArray->count() > 0) \
{ \
CCObject* child = NULL; \
CCARRAY_FOREACH(pArray, child) \
{ \
elementType pNode = (elementType) child; \
if(pNode) \
{ \
pNode->func(pObject); \
} \
} \
} \
} \
while(false)
NS_CC_BEGIN
class CC_DLL CCArray : public CCObject class CC_DLL CCArray : public CCObject
{ {
public: public:
~CCArray(); ~CCArray();
/** Create an array */
static CCArray* array();
/** Create an array with capacity */
static CCArray* arrayWithCapacity(unsigned int capacity);
/** Create an array with an existing array */
static CCArray* arrayWithArray(CCArray* otherArray);
/** Initializes an array */ /* static functions */
/** Create an array
@deprecated: Please use create() instead. This interface will be deprec
ated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCArray* array();
/** Create an array with one object
@deprecated: Please use createWithObject(CCObject*) instead. This inter
face will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCArray* arrayWithObject(CCObject* pObje
ct);
/** Create an array with some objects
@deprecated: Please use create(CCObject*, ...) instead. This interface
will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCArray* arrayWithObjects(CCObject* pObj
ect, ...);
/** Create an array with capacity
@deprecated: Please use createWithCapacity(unsigned int) instead. This
interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCArray* arrayWithCapacity(unsigned int
capacity);
/** Create an array with an existing array
@deprecated: Please use createWithArray(CCArray*) instead. This interfa
ce will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCArray* arrayWithArray(CCArray* otherAr
ray);
/**
@brief Generate a CCArray pointer by file
@param pFileName The file name of *.plist file
@return The CCArray pointer generated from the file
@deprecated: Please use createWithContentsOfFile(const char*) intead.
This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCArray* arrayWithContentsOfFile(const
char* pFileName);
/*
@brief The same meaning as arrayWithContentsOfFile(), but it doesn't c
all autorelease, so the
invoker should call release().
@deprecated: Please use createWithContentsOfFileThreadSafe(const char*
) instead. This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCArray* arrayWithContentsOfFileThreadSa
fe(const char* pFileName);
/** Create an array */
static CCArray* create();
/** Create an array with some objects */
static CCArray* create(CCObject* pObject, ...);
/** Create an array with one object */
static CCArray* createWithObject(CCObject* pObject);
/** Create an array with capacity */
static CCArray* createWithCapacity(unsigned int capacity);
/** Create an array with an existing array */
static CCArray* createWithArray(CCArray* otherArray);
/**
@brief Generate a CCArray pointer by file
@param pFileName The file name of *.plist file
@return The CCArray pointer generated from the file
*/
static CCArray* createWithContentsOfFile(const char* pFileName);
/*
@brief The same meaning as arrayWithContentsOfFile(), but it doesn't c
all autorelease, so the
invoker should call release().
*/
static CCArray* createWithContentsOfFileThreadSafe(const char* pFileNam
e);
/** Initializes an array */
bool init(); bool init();
/** Initializes an array with capacity */ /** Initializes an array with one object */
bool initWithObject(CCObject* pObject);
/** Initializes an array with some objects */
bool initWithObjects(CCObject* pObject, ...);
/** Initializes an array with capacity */
bool initWithCapacity(unsigned int capacity); bool initWithCapacity(unsigned int capacity);
/** Initializes an array with an existing array */ /** Initializes an array with an existing array */
bool initWithArray(CCArray* otherArray); bool initWithArray(CCArray* otherArray);
// Querying an Array // Querying an Array
/** Returns element count of the array */ /** Returns element count of the array */
unsigned int count(); unsigned int count();
/** Returns capacity of the array */ /** Returns capacity of the array */
unsigned int capacity(); unsigned int capacity();
/** Returns index of a certain object, return UINT_MAX if doesn't co ntain the object */ /** Returns index of a certain object, return UINT_MAX if doesn't conta in the object */
unsigned int indexOfObject(CCObject* object); unsigned int indexOfObject(CCObject* object);
/** Returns an element with a certain index */ /** Returns an element with a certain index */
CCObject* objectAtIndex(unsigned int index); CCObject* objectAtIndex(unsigned int index);
/** Returns last element */ /** Returns last element */
CCObject* lastObject(); CCObject* lastObject();
/** Returns a random element */ /** Returns a random element */
CCObject* randomObject(); CCObject* randomObject();
/** Returns a Boolean value that indicates whether object is present in array. */ /** Returns a Boolean value that indicates whether object is present in array. */
bool containsObject(CCObject* object); bool containsObject(CCObject* object);
/** @since 1.1 */
bool isEqualToArray(CCArray* pOtherArray);
// Adding Objects // Adding Objects
/** Add a certain object */ /** Add a certain object */
void addObject(CCObject* object); void addObject(CCObject* object);
/** Add all elements of an existing array */ /** Add all elements of an existing array */
void addObjectsFromArray(CCArray* otherArray); void addObjectsFromArray(CCArray* otherArray);
/** Insert a certain object at a certain index */ /** Insert a certain object at a certain index */
void insertObject(CCObject* object, unsigned int index); void insertObject(CCObject* object, unsigned int index);
// Removing Objects // Removing Objects
/** Remove last object */ /** Remove last object */
void removeLastObject(); void removeLastObject(bool bReleaseObj = true);
/** Remove a certain object */ /** Remove a certain object */
void removeObject(CCObject* object); void removeObject(CCObject* object, bool bReleaseObj = true);
/** Remove an element with a certain index */ /** Remove an element with a certain index */
void removeObjectAtIndex(unsigned int index); void removeObjectAtIndex(unsigned int index, bool bReleaseObj = true);
/** Remove all elements */ /** Remove all elements */
void removeObjectsInArray(CCArray* otherArray); void removeObjectsInArray(CCArray* otherArray);
/** Remove all objects */ /** Remove all objects */
void removeAllObjects(); void removeAllObjects();
/** Fast way to remove a certain object */ /** Fast way to remove a certain object */
void fastRemoveObject(CCObject* object); void fastRemoveObject(CCObject* object);
/** Fast way to remove an element with a certain index */ /** Fast way to remove an element with a certain index */
void fastRemoveObjectAtIndex(unsigned int index); void fastRemoveObjectAtIndex(unsigned int index);
// Rearranging Content // Rearranging Content
/** Swap two elements */ /** Swap two elements */
void exchangeObject(CCObject* object1, CCObject* object2); void exchangeObject(CCObject* object1, CCObject* object2);
/** Swap two elements with certain indexes */ /** Swap two elements with certain indexes */
void exchangeObjectAtIndex(unsigned int index1, unsigned int index2); void exchangeObjectAtIndex(unsigned int index1, unsigned int index2);
/** Revers the array */
/** Replace object at index with another object. */
void replaceObjectAtIndex(unsigned int uIndex, CCObject* pObject, bool
bReleaseObject = true);
/** Revers the array */
void reverseObjects(); void reverseObjects();
/* Shrinks the array so the memory footprint corresponds with the nu mber of items */ /* Shrinks the array so the memory footprint corresponds with the numbe r of items */
void reduceMemoryFootprint(); void reduceMemoryFootprint();
/* override functions */
virtual CCObject* copyWithZone(CCZone* pZone);
public: public:
ccArray* data; ccArray* data;
CCArray();
private: CCArray(unsigned int capacity);
CCArray() : data(NULL) {};
}; };
} // end of data_structure group
/// @}
NS_CC_END
#endif // __CCARRAY_H__ #endif // __CCARRAY_H__
 End of changes. 30 change blocks. 
56 lines changed or deleted 207 lines changed or added


 CCAtlasNode.h   CCAtlasNode.h 
skipping to change at line 34 skipping to change at line 34
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CCATLAS_NODE_H__ #ifndef __CCATLAS_NODE_H__
#define __CCATLAS_NODE_H__ #define __CCATLAS_NODE_H__
#include "CCNode.h" #include "CCNode.h"
#include "CCProtocols.h" #include "CCProtocols.h"
#include "ccTypes.h" #include "ccTypes.h"
namespace cocos2d { NS_CC_BEGIN
/**
* @addtogroup base_nodes
* @{
*/
class CCTextureAtlas; class CCTextureAtlas;
/** @brief CCAtlasNode is a subclass of CCNode that implements the CCRGBAPr otocol and /** @brief CCAtlasNode is a subclass of CCNode that implements the CCRGBAPr otocol and
CCTextureProtocol protocol CCTextureProtocol protocol
It knows how to render a TextureAtlas object. It knows how to render a TextureAtlas object.
If you are going to render a TextureAtlas consider subclassing CCAtlasNode (or a subclass of CCAtlasNode) If you are going to render a TextureAtlas consider subclassing CCAtlasNode (or a subclass of CCAtlasNode)
All features from CCNode are valid, plus the following features: All features from CCNode are valid, plus the following features:
- opacity and RGB colors - opacity and RGB colors
*/ */
class CC_DLL CCAtlasNode : public CCNode, public CCRGBAProtocol, public CCT extureProtocol class CC_DLL CCAtlasNode : public CCNode, public CCRGBAProtocol, public CCT extureProtocol
{ {
protected: protected:
//! chars per row //! chars per row
unsigned int m_uItemsPerRow; unsigned int m_uItemsPerRow;
//! chars per column //! chars per column
unsigned int m_uItemsPerColumn; unsigned int m_uItemsPerColumn;
//! width of each char //! width of each char
unsigned int m_uItemWidth; unsigned int m_uItemWidth;
//! height of each char //! height of each char
unsigned int m_uItemHeight; unsigned int m_uItemHeight;
ccColor3B m_tColorUnmodified; ccColor3B m_tColorUnmodified;
CC_PROPERTY(CCTextureAtlas*, m_pTextureAtlas, TextureAtlas); CC_PROPERTY(CCTextureAtlas*, m_pTextureAtlas, TextureAtlas);
// protocol variables // protocol variables
CC_PROPERTY(bool, m_bIsOpacityModifyRGB, IsOpacityModifyRGB) bool m_bIsOpacityModifyRGB;
CC_PROPERTY(ccBlendFunc, m_tBlendFunc, BlendFunc); bool isOpacityModifyRGB();
CC_PROPERTY(GLubyte, m_cOpacity, Opacity); void setOpacityModifyRGB(bool isOpacityModifyRGB);
CC_PROPERTY_PASS_BY_REF(ccColor3B, m_tColor, Color);
CC_PROPERTY(ccBlendFunc, m_tBlendFunc, BlendFunc);
// quads to draw CC_PROPERTY(GLubyte, m_cOpacity, Opacity);
CC_PROPERTY(unsigned int, m_uQuadsToDraw, QuadsToDraw); CC_PROPERTY_PASS_BY_REF(ccColor3B, m_tColor, Color);
// quads to draw
CC_PROPERTY(unsigned int, m_uQuadsToDraw, QuadsToDraw);
// color uniform
GLint m_nUniformColor;
public: public:
CCAtlasNode(); CCAtlasNode();
virtual ~CCAtlasNode(); virtual ~CCAtlasNode();
/** creates a CCAtlasNode with an Atlas file the width and height of e
ach item and the quantity of items to render
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCAtlasNode * atlasWithTileFile(const ch
ar* tile,unsigned int tileWidth, unsigned int tileHeight,
unsigned int itemsToRender);
/** creates a CCAtlasNode with an Atlas file the width and height o f each item and the quantity of items to render*/ /** creates a CCAtlasNode with an Atlas file the width and height o f each item and the quantity of items to render*/
static CCAtlasNode * atlasWithTileFile(const char* tile,unsigned int tileWidth, unsigned int tileHeight, static CCAtlasNode * create(const char* tile,unsigned int tileWidth, unsigned int tileHeight,
unsigned int itemsToRender); unsigned int itemsToRender);
/** initializes an CCAtlasNode with an Atlas file the width and hei /** initializes an CCAtlasNode with an Atlas file the width and height
ght of each item and the quantity of items to render*/ of each item and the quantity of items to render*/
bool initWithTileFile(const char* tile, unsigned int tileWidth, unsi bool initWithTileFile(const char* tile, unsigned int tileWidth, unsigne
gned int tileHeight, unsigned int itemsToRender); d int tileHeight, unsigned int itemsToRender);
/** updates the Atlas (indexed vertex array). /** updates the Atlas (indexed vertex array).
* Shall be overriden in subclasses * Shall be overriden in subclasses
*/ */
virtual void updateAtlasValues(); virtual void updateAtlasValues();
virtual void draw(); virtual void draw(void);
// CC Texture protocol // CC Texture protocol
/** returns the used texture*/ /** returns the used texture*/
virtual CCTexture2D* getTexture(void); virtual CCTexture2D* getTexture(void);
/** sets a new texture. it will be retained*/ /** sets a new texture. it will be retained*/
virtual void setTexture(CCTexture2D *texture); virtual void setTexture(CCTexture2D *texture);
private : private :
void calculateMaxItems(); void calculateMaxItems();
void updateBlendFunc(); void updateBlendFunc();
void updateOpacityModifyRGB(); void updateOpacityModifyRGB();
}; };
}//namespace cocos2d
// end of base_node group
/// @}
NS_CC_END
#endif // __CCATLAS_NODE_H__ #endif // __CCATLAS_NODE_H__
 End of changes. 12 change blocks. 
45 lines changed or deleted 67 lines changed or added


 CCAutoreleasePool.h   CCAutoreleasePool.h 
skipping to change at line 28 skipping to change at line 28
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __AUTORELEASEPOOL_H__ #ifndef __AUTORELEASEPOOL_H__
#define __AUTORELEASEPOOL_H__ #define __AUTORELEASEPOOL_H__
#include "CCObject.h" #include "CCObject.h"
#include "CCMutableArray.h" #include "CCArray.h"
NS_CC_BEGIN
/**
* @addtogroup base_nodes
* @{
*/
namespace cocos2d {
class CC_DLL CCAutoreleasePool : public CCObject class CC_DLL CCAutoreleasePool : public CCObject
{ {
CCMutableArray<CCObject*>* m_pManagedObjectArray; CCArray* m_pManagedObjectArray;
public: public:
CCAutoreleasePool(void); CCAutoreleasePool(void);
~CCAutoreleasePool(void); ~CCAutoreleasePool(void);
void addObject(CCObject *pObject); void addObject(CCObject *pObject);
void removeObject(CCObject *pObject); void removeObject(CCObject *pObject);
void clear(); void clear();
}; };
class CC_DLL CCPoolManager class CC_DLL CCPoolManager
{ {
CCMutableArray<CCAutoreleasePool*>* m_pReleasePoolStack; CCArray* m_pReleasePoolStack;
CCAutoreleasePool* m_pCurReleas CCAutoreleasePool* m_pCurReleasePool;
ePool;
CCAutoreleasePool* getCurReleasePool(); CCAutoreleasePool* getCurReleasePool();
public: public:
CCPoolManager(); CCPoolManager();
~CCPoolManager(); ~CCPoolManager();
void finalize(); void finalize();
void push(); void push();
void pop(); void pop();
void removeObject(CCObject* pObject); void removeObject(CCObject* pObject);
void addObject(CCObject* pObject); void addObject(CCObject* pObject);
static CCPoolManager* getInstance(); static CCPoolManager* sharedPoolManager();
static void purgePoolManager();
friend class CCAutoreleasePool; friend class CCAutoreleasePool;
}; };
} // end of base_nodes group
/// @}
NS_CC_END
#endif //__AUTORELEASEPOOL_H__ #endif //__AUTORELEASEPOOL_H__
 End of changes. 13 change blocks. 
22 lines changed or deleted 31 lines changed or added


 CCCamera.h   CCCamera.h 
skipping to change at line 30 skipping to change at line 30
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CCCAMERA_H__ #ifndef __CCCAMERA_H__
#define __CCCAMERA_H__ #define __CCCAMERA_H__
#include "CCObject.h" #include "cocoa/CCObject.h"
#include "ccMacros.h" #include "ccMacros.h"
#include "kazmath/mat4.h"
#include <string> #include <string>
namespace cocos2d {
/**
A CCCamera is used in every CCNode.
Useful to look at the object from different views.
The OpenGL gluLookAt() function is used to locate the
camera.
If the object is transformed by any of the scale, rotation or
position attributes, then they will override the camera.
IMPORTANT: Either your use the camera or the rotation/scale/position
properties. You can't use both.
World coordinates won't work if you use the camera.
Limitations:
- Some nodes, like CCParallaxNode, CCParticle uses world node coordi
nates, and they won't work properly if you move them (or any of their ances
tors)
using the camera.
- It doesn't work on batched nodes like CCSprite objects when they a
re parented to a CCSpriteBatchNode object.
- It is recommended to use it ONLY if you are going to create 3D eff
ects. For 2D effecs, use the action CCFollow or position/scale/rotate.
*/
class CC_DLL CCCamera : public CCObject
{
protected:
float m_fEyeX;
float m_fEyeY;
float m_fEyeZ;
float m_fCenterX;
float m_fCenterY;
float m_fCenterZ;
float m_fUpX;
float m_fUpY;
float m_fUpZ;
bool m_bDirty;
public:
CCCamera(void);
~CCCamera(void);
void init(void);
char * description(void);
/** sets the dirty value */
inline void setDirty(bool bValue) { m_bDirty = bValue; }
/** get the dirty value */
inline bool getDirty(void) { return m_bDirty; }
/** sets the camera in the default position */
void restore(void);
/** Sets the camera using gluLookAt using its eye, center an
d up_vector */
void locate(void);
/** sets the eye values in points */
void setEyeXYZ(float fEyeX, float fEyeY, float fEyeZ);
/** sets the center values in points */
void setCenterXYZ(float fCenterX, float fCenterY, float fCen
terZ);
/** sets the up values */
void setUpXYZ(float fUpX, float fUpY, float fUpZ);
/** get the eye vector values in points */
void getEyeXYZ(float *pEyeX, float *pEyeY, float *pEyeZ);
/** get the center vector values int points */
void getCenterXYZ(float *pCenterX, float *pCenterY, float *p
CenterZ);
/** get the up vector values */
void getUpXYZ(float *pUpX, float *pUpY, float *pUpZ);
public:
/** returns the Z eye */
static float getZEye();
private:
DISALLOW_COPY_AND_ASSIGN(CCCamera);
};
}//namespace cocos2d NS_CC_BEGIN
/**
* @addtogroup base_nodes
* @{
*/
/**
A CCCamera is used in every CCNode.
Useful to look at the object from different views.
The OpenGL gluLookAt() function is used to locate the
camera.
If the object is transformed by any of the scale, rotation or
position attributes, then they will override the camera.
IMPORTANT: Either your use the camera or the rotation/scale/position proper
ties. You can't use both.
World coordinates won't work if you use the camera.
Limitations:
- Some nodes, like CCParallaxNode, CCParticle uses world node coordinates,
and they won't work properly if you move them (or any of their ancestors)
using the camera.
- It doesn't work on batched nodes like CCSprite objects when they are pare
nted to a CCSpriteBatchNode object.
- It is recommended to use it ONLY if you are going to create 3D effects. F
or 2D effecs, use the action CCFollow or position/scale/rotate.
*/
class CC_DLL CCCamera : public CCObject
{
protected:
float m_fEyeX;
float m_fEyeY;
float m_fEyeZ;
float m_fCenterX;
float m_fCenterY;
float m_fCenterZ;
float m_fUpX;
float m_fUpY;
float m_fUpZ;
bool m_bDirty;
kmMat4 m_lookupMatrix;
public:
CCCamera(void);
~CCCamera(void);
void init(void);
const char* description(void);
/** sets the dirty value */
inline void setDirty(bool bValue) { m_bDirty = bValue; }
/** get the dirty value */
inline bool isDirty(void) { return m_bDirty; }
/** sets the camera in the default position */
void restore(void);
/** Sets the camera using gluLookAt using its eye, center and up_vector
*/
void locate(void);
/** sets the eye values in points */
void setEyeXYZ(float fEyeX, float fEyeY, float fEyeZ);
/** sets the center values in points */
void setCenterXYZ(float fCenterX, float fCenterY, float fCenterZ);
/** sets the up values */
void setUpXYZ(float fUpX, float fUpY, float fUpZ);
/** get the eye vector values in points */
void getEyeXYZ(float *pEyeX, float *pEyeY, float *pEyeZ);
/** get the center vector values int points */
void getCenterXYZ(float *pCenterX, float *pCenterY, float *pCenterZ);
/** get the up vector values */
void getUpXYZ(float *pUpX, float *pUpY, float *pUpZ);
public:
/** returns the Z eye */
static float getZEye();
private:
DISALLOW_COPY_AND_ASSIGN(CCCamera);
};
// end of base_node group
/// @}
NS_CC_END
#endif // __CCCAMERA_H__ #endif // __CCCAMERA_H__
 End of changes. 4 change blocks. 
86 lines changed or deleted 95 lines changed or added


 CCCommon.h   CCCommon.h 
skipping to change at line 30 skipping to change at line 30
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CC_COMMON_H__ #ifndef __CC_COMMON_H__
#define __CC_COMMON_H__ #define __CC_COMMON_H__
#include "CCPlatformMacros.h" #include "CCPlatformMacros.h"
NS_CC_BEGIN; NS_CC_BEGIN
/**
* @addtogroup platform
* @{
*/
/// The max length of CCLog message. /// The max length of CCLog message.
static const int kMaxLogLen = 16*1024; static const int kMaxLogLen = 16*1024;
/** /**
@brief Output Debug message. @brief Output Debug message.
*/ */
void CC_DLL CCLog(const char * pszFormat, ...); void CC_DLL CCLog(const char * pszFormat, ...);
/** /**
* lua can not deal with ... * lua can not deal with ...
*/ */
inline void CC_DLL CCLuaLog(const char * pszFormat) void CC_DLL CCLuaLog(const char * pszFormat);
{
CCLog(pszFormat);
}
/** /**
@brief Pop out a message box @brief Pop out a message box
*/ */
void CC_DLL CCMessageBox(const char * pszMsg, const char * pszTitle); void CC_DLL CCMessageBox(const char * pszMsg, const char * pszTitle);
/** /**
@brief Enum the language type supportted now @brief Enum the language type supportted now
*/ */
typedef enum LanguageType typedef enum LanguageType
{ {
kLanguageEnglish = 0, kLanguageEnglish = 0,
kLanguageChinese, kLanguageChinese,
kLanguageFrench, kLanguageFrench,
kLanguageItalian, kLanguageItalian,
kLanguageGerman, kLanguageGerman,
kLanguageSpanish, kLanguageSpanish,
kLanguageRussian kLanguageRussian
} ccLanguageType; } ccLanguageType;
NS_CC_END; // end of platform group
/// @}
NS_CC_END
#endif // __CC_COMMON_H__ #endif // __CC_COMMON_H__
 End of changes. 4 change blocks. 
6 lines changed or deleted 11 lines changed or added


 CCConfiguration.h   CCConfiguration.h 
/************************************************************************** ** /************************************************************************** **
Copyright (c) 2010-2011 cocos2d-x.org Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2010 Ricardo Quesada Copyright (c) 2010 Ricardo Quesada
http://www.cocos2d-x.org http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a cop y Permission is hereby granted, free of charge, to any person obtaining a cop y
of this software and associated documentation files (the "Software"), to de al of this software and associated documentation files (the "Software"), to de al
in the Software without restriction, including without limitation the right s in the Software without restriction, including without limitation the right s
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
skipping to change at line 29 skipping to change at line 29
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CCCONFIGURATION_H__ #ifndef __CCCONFIGURATION_H__
#define __CCCONFIGURATION_H__ #define __CCCONFIGURATION_H__
#include "CCObject.h" #include "cocoa/CCObject.h"
#include <string>
#include "CCGL.h" #include "CCGL.h"
#include <string>
namespace cocos2d { NS_CC_BEGIN
/** OS version definitions.
*/
enum {
kCCiOSVersion_3_0 = 0x03000000,
kCCiOSVersion_3_1 = 0x03010000,
kCCiOSVersion_3_1_1 = 0x03010100,
kCCiOSVersion_3_1_2 = 0x03010200,
kCCiOSVersion_3_1_3 = 0x03010300,
kCCiOSVersion_3_2 = 0x03020000,
kCCiOSVersion_3_2_1 = 0x03020100,
kCCiOSVersion_4_0 = 0x04000000,
kCCiOSVersion_4_0_1 = 0x04000100,
kCCiOSVersion_4_1 = 0x04010000,
kCCiOSVersion_4_2 = 0x04020000,
kCCiOSVersion_4_3 = 0x04030000,
kCCiOSVersion_4_3_1 = 0x04030100,
kCCiOSVersion_4_3_2 = 0x04030200,
kCCiOSVersion_4_3_3 = 0x04030300,
};
typedef enum
{
GLES_VER_INVALID,
GLES_VER_1_0,
GLES_VER_1_1,
GLES_VER_2_0,
} CCGlesVersion;
/** /**
* @addtogroup global
* @{
*/
/**
@brief CCConfiguration contains some openGL variables @brief CCConfiguration contains some openGL variables
@since v0.99.0 @since v0.99.0
*/ */
class CC_DLL CCConfiguration : public CCObject class CC_DLL CCConfiguration : public CCObject
{ {
protected: public:
GLint m_nMaxTextureSize; /** returns a shared instance of CCConfiguration */
GLint m_nMaxModelviewStackDepth; static CCConfiguration *sharedConfiguration(void);
bool m_bSupportsPVRTC; /** purge the shared instance of CCConfiguration */
bool m_bSupportsNPOT; static void purgeConfiguration(void);
bool m_bSupportsBGRA8888;
bool m_bSupportsDiscardFramebuffer;
bool m_bInited;
unsigned int m_uOSVersion;
GLint m_nMaxSamplesAllowed;
char * m_pGlExtensions;
private:
CCConfiguration(void);
public: public:
CCGlesVersion getGlesVersion(); /** OpenGL Max texture size. */
inline int getMaxTextureSize(void)
{
return m_nMaxTextureSize;
}
/** OpenGL Max Modelview Stack Depth. */
inline int getMaxModelviewStackDepth(void)
{
return m_nMaxModelviewStackDepth;
}
/** returns the maximum texture units
@since v2.0.0
*/
inline int getMaxTextureUnits(void)
{
return m_nMaxTextureUnits;
}
/** Whether or not the GPU supports NPOT (Non Power Of Two) textures.
OpenGL ES 2.0 already supports NPOT (iOS).
@since v0.99.2
*/
inline bool supportsNPOT(void)
{
return m_bSupportsNPOT;
}
/** Whether or not PVR Texture Compressed is supported */
inline bool supportsPVRTC(void)
{
return m_bSupportsPVRTC;
}
/** Whether or not BGRA8888 textures are supported.
@since v0.99.2
*/
inline bool supportsBGRA8888(void)
{
return m_bSupportsBGRA8888;
}
/** Whether or not glDiscardFramebufferEXT is supported
@since v0.99.2
*/
inline bool supportsDiscardFramebuffer(void)
{
return m_bSupportsDiscardFramebuffer;
}
/** Whether or not shareable VAOs are supported.
@since v2.0.0
*/
inline bool supportsShareableVAO(void)
{
return m_bSupportsShareableVAO;
}
/** OpenGL Max texture size. */ /** returns whether or not an OpenGL is supported */
inline int getMaxTextureSize(void) bool checkForGLExtension(const std::string &searchName);
{
return m_nMaxTextureSize;
}
/** OpenGL Max Modelview Stack Depth */
inline int getMaxModelviewStackDepth(void)
{
return m_nMaxModelviewStackDepth;
}
/** Whether or not the GPU supports NPOT (Non Power Of Two) textures
.
NPOT textures have the following limitations:
- They can't have mipmaps
- They only accept GL_CLAMP_TO_EDGE in GL_TEXTURE_WRAP_{S,T}
@since v0.99.2
*/
inline bool isSupportsNPOT(void)
{
return m_bSupportsNPOT;
}
/** Whether or not PVR Texture Compressed is supported */
inline bool isSupportsPVRTC(void)
{
return m_bSupportsPVRTC;
}
/** Whether or not BGRA8888 textures are supported.
@since v0.99.2
*/
inline bool isSupportsBGRA8888(void)
{
return m_bSupportsBGRA8888;
}
/** Whether or not glDiscardFramebufferEXT is supported
@since v0.99.2
*/
inline bool isSupportsDiscardFramebuffer(void)
{
return m_bSupportsDiscardFramebuffer;
}
/** returns the OS version.
- On iOS devices it returns the firmware version.
- On Mac returns the OS version
@since v0.99.5
*/
inline unsigned int getOSVersion() { return m_uOSVersion; }
/** returns whether or not an OpenGL is supported */ bool init(void);
bool checkForGLExtension(const std::string &searchName);
bool init(void); private:
CCConfiguration(void);
static CCConfiguration *s_gSharedConfiguration;
public: protected:
/** returns a shared instance of the CCConfiguration */ GLint m_nMaxTextureSize;
static CCConfiguration *sharedConfiguration(void); GLint m_nMaxModelviewStackDepth;
bool m_bSupportsPVRTC;
bool m_bSupportsNPOT;
bool m_bSupportsBGRA8888;
bool m_bSupportsDiscardFramebuffer;
bool m_bSupportsShareableVAO;
GLint m_nMaxSamplesAllowed;
GLint m_nMaxTextureUnits;
char * m_pGlExtensions;
}; };
}//namespace cocos2d
// end of global group
/// @}
NS_CC_END
#endif // __CCCONFIGURATION_H__ #endif // __CCCONFIGURATION_H__
 End of changes. 12 change blocks. 
110 lines changed or deleted 94 lines changed or added


 CCDirector.h   CCDirector.h 
skipping to change at line 31 skipping to change at line 31
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CCDIRECTOR_H__ #ifndef __CCDIRECTOR_H__
#define __CCDIRECTOR_H__ #define __CCDIRECTOR_H__
#include "platform/CCPlatformMacros.h" #include "platform/CCPlatformMacros.h"
#include "CCObject.h" #include "cocoa/CCObject.h"
#include "ccTypes.h" #include "ccTypes.h"
#include "CCGeometry.h" #include "cocoa/CCGeometry.h"
#include "CCMutableArray.h" #include "cocoa/CCArray.h"
#include "CCGeometry.h"
#include "CCEGLView.h"
#include "CCGL.h" #include "CCGL.h"
#include "kazmath/mat4.h"
#include "label_nodes/CCLabelTTF.h"
namespace cocos2d { NS_CC_BEGIN
/**
* @addtogroup base_nodes
* @{
*/
/** @typedef ccDirectorProjection /** @typedef ccDirectorProjection
Possible OpenGL projections used by director Possible OpenGL projections used by director
*/ */
typedef enum { typedef enum {
/// sets a 2D projection (orthogonal projection) /// sets a 2D projection (orthogonal projection)
kCCDirectorProjection2D, kCCDirectorProjection2D,
/// sets a 3D projection with a fovy=60, znear=0.5f and zfar=1500. /// sets a 3D projection with a fovy=60, znear=0.5f and zfar=1500.
kCCDirectorProjection3D, kCCDirectorProjection3D,
/// it calls "updateProjection" on the projection delegate. /// it calls "updateProjection" on the projection delegate.
kCCDirectorProjectionCustom, kCCDirectorProjectionCustom,
/// Detault projection is 3D projection /// Detault projection is 3D projection
kCCDirectorProjectionDefault = kCCDirectorProjection3D, kCCDirectorProjectionDefault = kCCDirectorProjection3D,
// backward compatibility stuff
CCDirectorProjection2D = kCCDirectorProjection2D,
CCDirectorProjection3D = kCCDirectorProjection3D,
CCDirectorProjectionCustom = kCCDirectorProjectionCustom,
} ccDirectorProjection; } ccDirectorProjection;
/** @typedef ccDirectorType /* Forward declarations. */
Possible Director Types. class CCLabelAtlas;
@since v0.8.2
*/
typedef enum {
/** Will use a Director that triggers the main loop from an NSTimer
object
*
* Features and Limitations:
* - Integrates OK with UIKit objects
* - It the slowest director
* - The interval update is customizable from 1 to 60
*/
kCCDirectorTypeNSTimer,
/** will use a Director that triggers the main loop from a custom ma
in loop.
*
* Features and Limitations:
* - Faster than NSTimer Director
* - It doesn't integrate well with UIKit objects
* - The interval update can't be customizable
*/
kCCDirectorTypeMainLoop,
/** Will use a Director that triggers the main loop from a thread, b
ut the main loop will be executed on the main thread.
*
* Features and Limitations:
* - Faster than NSTimer Director
* - It doesn't integrate well with UIKit objects
* - The interval update can't be customizable
*/
kCCDirectorTypeThreadMainLoop,
/** Will use a Director that synchronizes timers with the refresh ra
te of the display.
*
* Features and Limitations:
* - Faster than NSTimer Director
* - Only available on 3.1+
* - Scheduled timers & drawing are synchronizes with the refresh ra
te of the display
* - Integrates OK with UIKit objects
* - The interval update can be 1/60, 1/30, 1/15
*/
kCCDirectorTypeDisplayLink,
/** Default director is the NSTimer directory */
kCCDirectorTypeDefault = kCCDirectorTypeNSTimer,
// backward compatibility stuff
CCDirectorTypeNSTimer = kCCDirectorTypeNSTimer,
CCDirectorTypeMainLoop = kCCDirectorTypeMainLoop,
CCDirectorTypeThreadMainLoop = kCCDirectorTypeThreadMainLoop,
CCDirectorTypeDisplayLink = kCCDirectorTypeDisplayLink,
CCDirectorTypeDefault =kCCDirectorTypeDefault,
} ccDirectorType;
/** @typedef ccDeviceOrientation
Possible device orientations
*/
typedef enum {
/// Device oriented vertically, home button on the bottom
kCCDeviceOrientationPortrait = 0, // UIDeviceOrientationPortrait,
/// Device oriented vertically, home button on the top
kCCDeviceOrientationPortraitUpsideDown = 1, // UIDeviceOrientationPortr
aitUpsideDown,
/// Device oriented horizontally, home button on the right
kCCDeviceOrientationLandscapeLeft = 2, // UIDeviceOrientationLandscapeL
eft,
/// Device oriented horizontally, home button on the left
kCCDeviceOrientationLandscapeRight = 3, // UIDeviceOrientationLandscape
Right,
// Backward compatibility stuff
CCDeviceOrientationPortrait = kCCDeviceOrientationPortrait,
CCDeviceOrientationPortraitUpsideDown = kCCDeviceOrientationPortrait
UpsideDown,
CCDeviceOrientationLandscapeLeft = kCCDeviceOrientationLandscapeLeft
,
CCDeviceOrientationLandscapeRight = kCCDeviceOrientationLandscapeRig
ht,
} ccDeviceOrientation;
class CCLabelTTF;
class CCScene; class CCScene;
class CCEGLView; class CCEGLView;
class CCProjectionProtocol; class CCDirectorDelegate;
class CCNode; class CCNode;
class CCScheduler;
class CCActionManager;
class CCTouchDispatcher;
class CCKeypadDispatcher;
class CCAccelerometer;
/** /**
@brief Class that creates and handle the main Window and manages how @brief Class that creates and handle the main Window and manages how
and when to execute the Scenes. and when to execute the Scenes.
The CCDirector is also responsible for: The CCDirector is also responsible for:
- initializing the OpenGL context - initializing the OpenGL context
- setting the OpenGL pixel format (default on is RGB565) - setting the OpenGL pixel format (default on is RGB565)
- setting the OpenGL buffer depth (default one is 0-bit) - setting the OpenGL buffer depth (default one is 0-bit)
- setting the projection (default one is 3D) - setting the projection (default one is 3D)
skipping to change at line 166 skipping to change at line 98
The CCDirector also sets the default OpenGL context: The CCDirector also sets the default OpenGL context:
- GL_TEXTURE_2D is enabled - GL_TEXTURE_2D is enabled
- GL_VERTEX_ARRAY is enabled - GL_VERTEX_ARRAY is enabled
- GL_COLOR_ARRAY is enabled - GL_COLOR_ARRAY is enabled
- GL_TEXTURE_COORD_ARRAY is enabled - GL_TEXTURE_COORD_ARRAY is enabled
*/ */
class CC_DLL CCDirector : public CCObject class CC_DLL CCDirector : public CCObject
{ {
public: public:
virtual bool init(void); CCDirector(void);
virtual ~CCDirector(void); virtual ~CCDirector(void);
CCDirector(void) {} virtual bool init(void);
// attribute // attribute
/** Get current running Scene. Director can only run one Scene at th /** Get current running Scene. Director can only run one Scene at the t
e time */ ime */
inline CCScene* getRunningScene(void) { return m_pRunningScene; } inline CCScene* getRunningScene(void) { return m_pRunningScene; }
/** Get the FPS value */ /** Get the FPS value */
inline double getAnimationInterval(void) { return m_dAnimationInterv inline double getAnimationInterval(void) { return m_dAnimationInterval;
al; } }
/** Set the FPS value. */ /** Set the FPS value. */
virtual void setAnimationInterval(double dValue) = 0; virtual void setAnimationInterval(double dValue) = 0;
/** Whether or not to display the FPS on the bottom-left corner */
inline bool isDisplayFPS(void) { return m_bDisplayFPS; }
/** Display the FPS on the bottom-left corner */
inline void setDisplayFPS(bool bDisplayFPS) { m_bDisplayFPS = bDispl
ayFPS; }
/** Get the CCEGLView, where everything is rendered */
inline CC_GLVIEW* getOpenGLView(void) { return m_pobOpenGLView; }
void setOpenGLView(CC_GLVIEW *pobOpenGLView);
inline bool isNextDeltaTimeZero(void) { return m_bNextDeltaTimeZero; /** Whether or not to display the FPS on the bottom-left corner */
} inline bool isDisplayStats(void) { return m_bDisplayStats; }
void setNextDeltaTimeZero(bool bNextDeltaTimeZero); /** Display the FPS on the bottom-left corner */
inline void setDisplayStats(bool bDisplayStats) { m_bDisplayStats = bDi
splayStats; }
/** Whether or not the Director is paused */ /** seconds per frame */
inline bool isPaused(void) { return m_bPaused; } inline float getSecondsPerFrame() { return m_fSecondsPerFrame; }
/** Get the CCEGLView, where everything is rendered */
inline CCEGLView* getOpenGLView(void) { return m_pobOpenGLView; }
void setOpenGLView(CCEGLView *pobOpenGLView);
inline bool isNextDeltaTimeZero(void) { return m_bNextDeltaTimeZero; }
void setNextDeltaTimeZero(bool bNextDeltaTimeZero);
/** Whether or not the Director is paused */
inline bool isPaused(void) { return m_bPaused; }
/** How many frames were called since the director started */ /** How many frames were called since the director started */
inline unsigned int getFrames(void) { return m_uFrames; } inline unsigned int getTotalFrames(void) { return m_uTotalFrames; }
/** Sets an OpenGL projection /** Sets an OpenGL projection
@since v0.8.2 @since v0.8.2
*/ */
inline ccDirectorProjection getProjection(void) { return m_eProjecti inline ccDirectorProjection getProjection(void) { return m_eProjection;
on; } }
void setProjection(ccDirectorProjection kProjection); void setProjection(ccDirectorProjection kProjection);
/** How many frames were called since the director started */ /** How many frames were called since the director started */
/** Whether or not the replaced scene will receive the cleanup messa /** Whether or not the replaced scene will receive the cleanup message.
ge. If the new scene is pushed, then the old scene won't receive the "clea
If the new scene is pushed, then the old scene won't receive the "c nup" message.
leanup" message. If the new scene replaces the old one, the it will receive the "cleanu
If the new scene replaces the old one, the it will receive the "cle p" message.
anup" message. @since v0.99.0
@since v0.99.0 */
*/ inline bool isSendCleanupToScene(void) { return m_bSendCleanupToScene;
inline bool isSendCleanupToScene(void) { return m_bSendCleanupToScen }
e; }
/** This object will be visited after the main scene is visited.
/** This object will be visited after the main scene is visited. This object MUST implement the "visit" selector.
This object MUST implement the "visit" selector. Useful to hook a notification object, like CCNotifications (http://git
Useful to hook a notification object, like CCNotifications (http:// hub.com/manucorporat/CCNotifications)
github.com/manucorporat/CCNotifications) @since v0.99.5
@since v0.99.5 */
*/ CCNode* getNotificationNode();
CCNode* getNotificationNode(); void setNotificationNode(CCNode *node);
void setNotificationNode(CCNode *node);
bool enableRetinaDisplay(bool bEnabelRetina);
// window size
// window size
/** returns the size of the OpenGL view in points.
It takes into account any possible rotation (device orientation) of /** returns the size of the OpenGL view in points.
the window */
*/ CCSize getWinSize(void);
CCSize getWinSize(void);
/** returns the size of the OpenGL view in pixels.
/** returns the size of the OpenGL view in pixels. */
It takes into account any possible rotation (device orientation) of CCSize getWinSizeInPixels(void);
the window.
On Mac winSize and winSizeInPixels return the same value. /** returns visible size of the OpenGL view in points.
*/ * the value is equal to getWinSize if don't invoke
CCSize getWinSizeInPixels(void); * CCEGLView::setDesignResolutionSize()
*/
/** returns the display size of the OpenGL view in pixels. CCSize getVisibleSize();
It doesn't take into account any possible rotation of the window.
*/ /** returns visible origin of the OpenGL view in points.
CCSize getDisplaySizeInPixels(void); */
CCPoint getVisibleOrigin();
/** changes the projection size */
void reshapeProjection(const CCSize& newWindowSize); /** changes the projection size */
void reshapeProjection(const CCSize& newWindowSize);
/** converts a UIKit coordinate to an OpenGL coordinate
Useful to convert (multi) touches coordinates to the current layout /** converts a UIKit coordinate to an OpenGL coordinate
(portrait or landscape) Useful to convert (multi) touches coordinates to the current layout (p
*/ ortrait or landscape)
CCPoint convertToGL(const CCPoint& obPoint); */
CCPoint convertToGL(const CCPoint& obPoint);
/** converts an OpenGL coordinate to a UIKit coordinate
Useful to convert node points to window points for calls such as gl /** converts an OpenGL coordinate to a UIKit coordinate
Scissor Useful to convert node points to window points for calls such as glSci
*/ ssor
CCPoint convertToUI(const CCPoint& obPoint); */
CCPoint convertToUI(const CCPoint& obPoint);
/// XXX: missing description
float getZEye(void); /// XXX: missing description
float getZEye(void);
// Scene Management
// Scene Management
/**Enters the Director's main loop with the given Scene.
* Call it to run only your FIRST scene. /**Enters the Director's main loop with the given Scene.
* Don't call it if there is already a running scene. * Call it to run only your FIRST scene.
*/ * Don't call it if there is already a running scene.
void runWithScene(CCScene *pScene); *
* It will call pushScene: and then it will call startAnimation
/**Suspends the execution of the running scene, pushing it on the st */
ack of suspended scenes. void runWithScene(CCScene *pScene);
* The new scene will be executed.
* Try to avoid big stacks of pushed scenes to reduce memory allocat /**Suspends the execution of the running scene, pushing it on the stack
ion. of suspended scenes.
* ONLY call it if there is a running scene. * The new scene will be executed.
*/ * Try to avoid big stacks of pushed scenes to reduce memory allocation
void pushScene(CCScene *pScene); .
* ONLY call it if there is a running scene.
/**Pops out a scene from the queue. */
* This scene will replace the running one. void pushScene(CCScene *pScene);
* The running scene will be deleted. If there are no more scenes in
the stack the execution is terminated. /**Pops out a scene from the queue.
* ONLY call it if there is a running scene. * This scene will replace the running one.
*/ * The running scene will be deleted. If there are no more scenes in th
void popScene(void); e stack the execution is terminated.
* ONLY call it if there is a running scene.
/** Replaces the running scene with a new one. The running scene is */
terminated. void popScene(void);
* ONLY call it if there is a running scene.
*/ /**Pops out all scenes from the queue until the root scene in the queue
void replaceScene(CCScene *pScene); .
* This scene will replace the running one.
/** Ends the execution, releases the running scene. * The running scene will be deleted. If there are no more scenes in th
It doesn't remove the OpenGL view from its parent. You have to do i e stack the execution is terminated.
t manually. * ONLY call it if there is a running scene.
*/ */
void popToRootScene(void);
/* end is key word of lua, use other name to export to lua. */
inline void endToLua(void){end();} /** Replaces the running scene with a new one. The running scene is ter
minated.
void end(void); * ONLY call it if there is a running scene.
*/
/** Pauses the running scene. void replaceScene(CCScene *pScene);
The running scene will be _drawed_ but all scheduled timers will be
paused /** Ends the execution, releases the running scene.
While paused, the draw rate will be 4 FPS to reduce CPU consumption It doesn't remove the OpenGL view from its parent. You have to do it m
*/ anually.
void pause(void); */
void end(void);
/** Resumes the paused scene
The scheduled timers will be activated again. /** Pauses the running scene.
The "delta time" will be 0 (as if the game wasn't paused) The running scene will be _drawed_ but all scheduled timers will be pa
*/ used
void resume(void); While paused, the draw rate will be 4 FPS to reduce CPU consumption
*/
/** Stops the animation. Nothing will be drawn. The main loop won't void pause(void);
be triggered anymore.
If you don't want to pause your animation call [pause] instead. /** Resumes the paused scene
*/ The scheduled timers will be activated again.
virtual void stopAnimation(void) = 0; The "delta time" will be 0 (as if the game wasn't paused)
*/
/** The main loop is triggered again. void resume(void);
Call this function only if [stopAnimation] was called earlier
@warning Don't call this function to start the main loop. To run th /** Stops the animation. Nothing will be drawn. The main loop won't be
e main loop call runWithScene triggered anymore.
*/ If you don't want to pause your animation call [pause] instead.
virtual void startAnimation(void) = 0; */
virtual void stopAnimation(void) = 0;
/** Draw the scene.
This method is called every frame. Don't call it manually. /** The main loop is triggered again.
*/ Call this function only if [stopAnimation] was called earlier
void drawScene(void); @warning Don't call this function to start the main loop. To run the m
ain loop call runWithScene
// Memory Helper */
virtual void startAnimation(void) = 0;
/** Removes cached all cocos2d cached data.
It will purge the CCTextureCache, CCSpriteFrameCache, CCLabelBMFont /** Draw the scene.
cache This method is called every frame. Don't call it manually.
@since v0.99.3 */
*/ void drawScene(void);
void purgeCachedData(void);
// Memory Helper
// OpenGL Helper
/** Removes cached all cocos2d cached data.
/** sets the OpenGL default values */ It will purge the CCTextureCache, CCSpriteFrameCache, CCLabelBMFont ca
void setGLDefaultValues(void); che
@since v0.99.3
/** enables/disables OpenGL alpha blending */ */
void setAlphaBlending(bool bOn); void purgeCachedData(void);
/** enables/disables OpenGL depth test */ // OpenGL Helper
void setDepthTest(bool bOn);
/** sets the OpenGL default values */
virtual void mainLoop(void) = 0; void setGLDefaultValues(void);
// Profiler /** enables/disables OpenGL alpha blending */
void showProfilers(void); void setAlphaBlending(bool bOn);
/** rotates the screen if an orientation different than Portrait is /** enables/disables OpenGL depth test */
used */ void setDepthTest(bool bOn);
void applyOrientation(void);
virtual void mainLoop(void) = 0;
ccDeviceOrientation getDeviceOrientation(void);
void setDeviceOrientation(ccDeviceOrientation kDeviceOrientation); /** The size in pixels of the surface. It could be different than the s
creen size.
/** The size in pixels of the surface. It could be different than th High-res devices might have a higher surface size than the screen size.
e screen size. Only available when compiled using SDK >= 4.0.
High-res devices might have a higher surface size than the screen si @since v0.99.4
ze. */
Only available when compiled using SDK >= 4.0. void setContentScaleFactor(float scaleFactor);
@since v0.99.4 float getContentScaleFactor(void);
*/
void setContentScaleFactor(CGFloat scaleFactor);
CGFloat getContentScaleFactor(void);
/** Will enable Retina Display on devices that supports it.
It will enable Retina Display on iPhone4 and iPod Touch 4.
It will return YES, if it could enabled it, otherwise it will return
NO.
This is the recommened way to enable Retina Display.
@since v0.99.5
*/
bool enableRetinaDisplay(bool enabled);
bool isRetinaDisplay() { return m_bRetinaDisplay; }
/** There are 4 types of Director.
- kCCDirectorTypeNSTimer (default)
- kCCDirectorTypeMainLoop
- kCCDirectorTypeThreadMainLoop
- kCCDirectorTypeDisplayLink
Each Director has it's own benefits, limitations.
Now we only support DisplayLink director, so it has not effect.
This method should be called before any other call to the director.
@since v0.8.2
*/
static bool setDirectorType(ccDirectorType obDirectorType);
public: public:
/** returns a shared instance of the director */ /** CCScheduler associated with this director
static CCDirector* sharedDirector(void); @since v2.0
void resetDirector(); */
CC_PROPERTY(CCScheduler*, m_pScheduler, Scheduler);
/** CCActionManager associated with this director
@since v2.0
*/
CC_PROPERTY(CCActionManager*, m_pActionManager, ActionManager);
/** CCTouchDispatcher associated with this director
@since v2.0
*/
CC_PROPERTY(CCTouchDispatcher*, m_pTouchDispatcher, TouchDispatcher);
/** CCKeypadDispatcher associated with this director
@since v2.0
*/
CC_PROPERTY(CCKeypadDispatcher*, m_pKeypadDispatcher, KeypadDispatcher)
;
/** CCAccelerometer associated with this director
@since v2.0
*/
CC_PROPERTY(CCAccelerometer*, m_pAccelerometer, Accelerometer);
/** returns a shared instance of the director */
static CCDirector* sharedDirector(void);
protected:
void purgeDirector();
bool m_bPurgeDirecotorInNextLoop; // this flag will be set to true in e
nd()
void updateContentScaleFactor(void);
void setNextScene(void);
void showStats();
void createStatsLabel();
void calculateMPF();
/** calculates delta time since last time it was called */
void calculateDeltaTime();
protected: protected:
/* The CCEGLView, where everything is rendered */
CCEGLView *m_pobOpenGLView;
void purgeDirector(); double m_dAnimationInterval;
bool m_bPurgeDirecotorInNextLoop; // this flag will be set to true i double m_dOldAnimationInterval;
n end()
void updateContentScaleFactor(void); /* landscape mode ? */
bool m_bLandscape;
void setNextScene(void); bool m_bDisplayStats;
float m_fAccumDt;
float m_fFrameRate;
#if CC_DIRECTOR_FAST_FPS CCLabelTTF *m_pFPSLabel;
/** shows the FPS in the screen */ CCLabelTTF *m_pSPFLabel;
void showFPS(void); CCLabelTTF *m_pDrawsLabel;
#else
void showFPS(void) {}
#endif // CC_DIRECTOR_FAST_FPS
/** calculates delta time since last time it was called */ void calcula
teDeltaTime();protected:
/* The CCEGLView, where everything is rendered */
CC_GLVIEW *m_pobOpenGLView;
double m_dAnimationInterval;
double m_dOldAnimationInterval;
/* landscape mode ? */
bool m_bLandscape;
bool m_bDisplayFPS;
ccTime m_fAccumDt;
ccTime m_fFrameRate;
#if CC_DIRECTOR_FAST_FPS
CCLabelTTF *m_pFPSLabel;
#endif
/* is the running scene paused */ /** Whether or not the Director is paused */
bool m_bPaused; bool m_bPaused;
/* How many frames were called since the director started */ /* How many frames were called since the director started */
unsigned int m_uTotalFrames; unsigned int m_uTotalFrames;
unsigned int m_uFrames; unsigned int m_uFrames;
float m_fSecondsPerFrame;
/* The running scene */ /* The running scene */
CCScene *m_pRunningScene; CCScene *m_pRunningScene;
/* will be the next 'runningScene' in the next frame
nextScene is a weak reference. */
CCScene *m_pNextScene;
/* If YES, then "old" scene will receive the cleanup message */ /* will be the next 'runningScene' in the next frame
bool m_bSendCleanupToScene; nextScene is a weak reference. */
CCScene *m_pNextScene;
/* scheduled scenes */ /* If YES, then "old" scene will receive the cleanup message */
CCMutableArray<CCScene*> *m_pobScenesStack; bool m_bSendCleanupToScene;
/* last time the main loop was updated */ /* scheduled scenes */
struct cc_timeval *m_pLastUpdate; CCArray* m_pobScenesStack;
/* delta time since last tick to main loop */ /* last time the main loop was updated */
ccTime m_fDeltaTime; struct cc_timeval *m_pLastUpdate;
/* whether or not the next delta time will be zero */ /* delta time since last tick to main loop */
bool m_bNextDeltaTimeZero; float m_fDeltaTime;
/* projection used */ /* whether or not the next delta time will be zero */
ccDirectorProjection m_eProjection; bool m_bNextDeltaTimeZero;
/* window size in points */ /* projection used */
CCSize m_obWinSizeInPoints; ccDirectorProjection m_eProjection;
/* window size in pixels */ /* window size in points */
CCSize m_obWinSizeInPixels; CCSize m_obWinSizeInPoints;
/* content scale factor */ /* window size in pixels */
CGFloat m_fContentScaleFactor; CCSize m_obWinSizeInPixels;
/* store the fps string */ /* content scale factor */
char *m_pszFPS; float m_fContentScaleFactor;
/* This object will be visited after the scene. Useful to hook a not /* store the fps string */
ification node */ char *m_pszFPS;
CCNode *m_pNotificationNode;
/* Projection protocol delegate */ /* This object will be visited after the scene. Useful to hook a notifi
CCProjectionProtocol *m_pProjectionDelegate; cation node */
CCNode *m_pNotificationNode;
/* The device orientation */ /* Projection protocol delegate */
ccDeviceOrientation m_eDeviceOrientation; CCDirectorDelegate *m_pProjectionDelegate;
/* contentScaleFactor could be simulated */
bool m_bIsContentScaleSupported;
bool m_bRetinaDisplay; /* contentScaleFactor could be simulated */
bool m_bIsContentScaleSupported;
#if CC_ENABLE_PROFILERS // CCEGLViewProtocol will recreate stats labels to fit visible rect
ccTime m_fAccumDtForProfiler; friend class CCEGLViewProtocol;
#endif
}; };
/** /**
@brief DisplayLinkDirector is a Director that synchronizes timers with the refresh rate of the display. @brief DisplayLinkDirector is a Director that synchronizes timers with the refresh rate of the display.
Features and Limitations: Features and Limitations:
- Scheduled timers & drawing are synchronizes with the refresh rate of th e display - Scheduled timers & drawing are synchronizes with the refresh rate of th e display
- Only supports animation intervals of 1/60 1/30 & 1/15 - Only supports animation intervals of 1/60 1/30 & 1/15
@since v0.8.2 @since v0.8.2
*/ */
class CCDisplayLinkDirector : public CCDirector class CCDisplayLinkDirector : public CCDirector
{ {
public: public:
CCDisplayLinkDirector(void) CCDisplayLinkDirector(void)
: m_bInvalid(false) : m_bInvalid(false)
{} {}
virtual void mainLoop(void); virtual void mainLoop(void);
virtual void setAnimationInterval(double dValue); virtual void setAnimationInterval(double dValue);
virtual void startAnimation(void); virtual void startAnimation(void);
virtual void stopAnimation(); virtual void stopAnimation();
protected: protected:
bool m_bInvalid; bool m_bInvalid;
}; };
}//namespace cocos2d // end of base_node group
/// @}
NS_CC_END
#endif // __CCDIRECTOR_H__ #endif // __CCDIRECTOR_H__
 End of changes. 46 change blocks. 
424 lines changed or deleted 341 lines changed or added


 CCDrawingPrimitives.h   CCDrawingPrimitives.h 
/************************************************************************** ** /************************************************************************** **
Copyright (c) 2010-2011 cocos2d-x.org Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011 Zynga Inc. Copyright (c) 2011 Zynga Inc.
http://www.cocos2d-x.org http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a cop y Permission is hereby granted, free of charge, to any person obtaining a cop y
of this software and associated documentation files (the "Software"), to de al of this software and associated documentation files (the "Software"), to de al
in the Software without restriction, including without limitation the right s in the Software without restriction, including without limitation the right s
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
skipping to change at line 45 skipping to change at line 45
- ccDrawPoly - ccDrawPoly
- ccDrawCircle - ccDrawCircle
- ccDrawQuadBezier - ccDrawQuadBezier
- ccDrawCubicBezier - ccDrawCubicBezier
You can change the color, width and other property by calling the You can change the color, width and other property by calling the
glColor4ub(), glLineWidth(), glPointSize(). glColor4ub(), glLineWidth(), glPointSize().
@warning These functions draws the Line, Point, Polygon, immediately. They aren't batched. If you are going to make a game that depends on these prim itives, I suggest creating a batch. @warning These functions draws the Line, Point, Polygon, immediately. They aren't batched. If you are going to make a game that depends on these prim itives, I suggest creating a batch.
*/ */
#include "ccTypes.h"
#include "ccMacros.h"
#include "cocoa/CCGeometry.h" // for CCPoint
#include "CCGeometry.h" // for CCPoint NS_CC_BEGIN
namespace cocos2d {
/**
* @addtogroup global
* @{
*/
class CCPointArray;
/** initlialize context */
void CC_DLL ccDrawInit();
/** draws a point given x and y coordinate measured in points */ /** draws a point given x and y coordinate measured in points */
void CC_DLL ccDrawPoint( const CCPoint& point ); void CC_DLL ccDrawPoint( const CCPoint& point );
/** draws an array of points. /** draws an array of points.
@since v0.7.2 @since v0.7.2
*/ */
void CC_DLL ccDrawPoints( const CCPoint *points, unsigned int numberOfPoint s ); void CC_DLL ccDrawPoints( const CCPoint *points, unsigned int numberOfPoint s );
/** draws a line given the origin and destination point measured in points */ /** draws a line given the origin and destination point measured in points */
void CC_DLL ccDrawLine( const CCPoint& origin, const CCPoint& destination ) ; void CC_DLL ccDrawLine( const CCPoint& origin, const CCPoint& destination ) ;
/** draws a rectangle given the origin and destination point measured in po
ints. */
void CC_DLL ccDrawRect( CCPoint origin, CCPoint destination );
/** draws a solid rectangle given the origin and destination point measured
in points.
@since 1.1
*/
void CC_DLL ccDrawSolidRect( CCPoint origin, CCPoint destination, ccColor4F
color );
/** draws a poligon given a pointer to CCPoint coordiantes and the number o f vertices measured in points. /** draws a poligon given a pointer to CCPoint coordiantes and the number o f vertices measured in points.
The polygon can be closed or open The polygon can be closed or open
*/ */
void CC_DLL ccDrawPoly( const CCPoint *vertices, int numOfVertices, bool cl osePolygon ); void CC_DLL ccDrawPoly( const CCPoint *vertices, unsigned int numOfVertices , bool closePolygon );
/** draws a poligon given a pointer to CCPoint coordiantes and the number o /** draws a solid polygon given a pointer to CGPoint coordiantes, the numbe
f vertices measured in points. r of vertices measured in points, and a color.
The polygon can be closed or open and optionally filled with current GL col */
or void CC_DLL ccDrawSolidPoly( const CCPoint *poli, unsigned int numberOfPoin
*/ ts, ccColor4F color );
void CC_DLL ccDrawPoly( const CCPoint *vertices, int numOfVertices, bool cl
osePolygon , bool fill);
/** draws a circle given the center, radius and number of segments. */ /** draws a circle given the center, radius and number of segments. */
void CC_DLL ccDrawCircle( const CCPoint& center, float radius, float angle, int segments, bool drawLineToCenter); void CC_DLL ccDrawCircle( const CCPoint& center, float radius, float angle, unsigned int segments, bool drawLineToCenter);
/** draws a quad bezier path /** draws a quad bezier path
@warning This function could be pretty slow. Use it only for debugging pur poses.
@since v0.8 @since v0.8
*/ */
void CC_DLL ccDrawQuadBezier(const CCPoint& origin, const CCPoint& control, const CCPoint& destination, int segments); void CC_DLL ccDrawQuadBezier(const CCPoint& origin, const CCPoint& control, const CCPoint& destination, unsigned int segments);
/** draws a cubic bezier path /** draws a cubic bezier path
@warning This function could be pretty slow. Use it only for debugging pur poses.
@since v0.8 @since v0.8
*/ */
void CC_DLL ccDrawCubicBezier(const CCPoint& origin, const CCPoint& control void CC_DLL ccDrawCubicBezier(const CCPoint& origin, const CCPoint& control
1, const CCPoint& control2, const CCPoint& destination, int segments); 1, const CCPoint& control2, const CCPoint& destination, unsigned int segmen
}//namespace cocos2d ts);
/** draws a Catmull Rom path.
@warning This function could be pretty slow. Use it only for debugging pur
poses.
@since v2.0
*/
void CC_DLL ccDrawCatmullRom( CCPointArray *arrayOfControlPoints, unsigned
int segments );
/** draws a Cardinal Spline path.
@warning This function could be pretty slow. Use it only for debugging pur
poses.
@since v2.0
*/
void CC_DLL ccDrawCardinalSpline( CCPointArray *config, float tension, uns
igned int segments );
/** set the drawing color with 4 unsigned bytes
@since v2.0
*/
void CC_DLL ccDrawColor4B( GLubyte r, GLubyte g, GLubyte b, GLubyte a );
/** set the drawing color with 4 floats
@since v2.0
*/
void CC_DLL ccDrawColor4F( GLfloat r, GLfloat g, GLfloat b, GLfloat a );
/** set the point size in points. Default 1.
@since v2.0
*/
void CC_DLL ccPointSize( GLfloat pointSize );
// end of global group
/// @}
NS_CC_END
#endif // __CCDRAWING_PRIMITIVES__ #endif // __CCDRAWING_PRIMITIVES__
 End of changes. 11 change blocks. 
16 lines changed or deleted 75 lines changed or added


 CCEGLView.h   CCEGLView.h 
skipping to change at line 25 skipping to change at line 25
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CC_EGLVIEW_H__ #ifndef __CC_EGLVIEW_MAC_H__
#define __CC_EGLVIEW_H__ #define __CC_EGLVIEW_MAC_H__
#include "../platform/CCEGLView_platform.h" #include "platform/CCCommon.h"
#include "platform/CCEGLViewProtocol.h"
#endif // end of __CC_EGLVIEW_H__ namespace cocos2d {
class CCSet;
class CCTouch;
class CCSize;
class CC_DLL CCEGLView : public CCEGLViewProtocol
{
public:
CCEGLView();
virtual ~CCEGLView();
bool isOpenGLReady();
virtual bool setContentScaleFactor(float contentScaleFactor);
void end();
void swapBuffers();
void setIMEKeyboardState(bool bOpen);
void setMultiTouchMask(bool mask);
static CCEGLView* sharedOpenGLView();
};
} // end of namespace cocos2d
#endif // end of __CC_EGLVIEW_MAC_H__
 End of changes. 3 change blocks. 
3 lines changed or deleted 4 lines changed or added


 CCFileUtils.h   CCFileUtils.h 
skipping to change at line 28 skipping to change at line 28
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CC_FILEUTILS_PLATFORM_H__ #ifndef __CC_FILEUTILS_PLATFORM_H__
#define __CC_FILEUTILS_PLATFORM_H__ #define __CC_FILEUTILS_PLATFORM_H__
#include <string> #include <string>
#include "CCMutableDictionary.h" #include "CCPlatformMacros.h"
#include "ccTypes.h"
NS_CC_BEGIN; NS_CC_BEGIN
/**
* @addtogroup platform
* @{
*/
//! @brief Helper class to handle file operations //! @brief Helper class to handle file operations
class CC_DLL CCFileUtils class CC_DLL CCFileUtils
{ {
public: public:
static CCFileUtils* sharedFileUtils();
static void purgeFileUtils();
void purgeCachedEntries();
/** /**
@brief Get resource file data @brief Get resource file data
@param[in] pszFileName The resource file name which contain the path @param[in] pszFileName The resource file name which contain the path
@param[in] pszMode The read mode of the file @param[in] pszMode The read mode of the file
@param[out] pSize If get the file data succeed the it will be the data size,or it will be 0 @param[out] pSize If get the file data succeed the it will be the data size,or it will be 0
@return if success,the pointer of data will be returned,or NULL is retu rned @return if success,the pointer of data will be returned,or NULL is retu rned
@warning If you get the file data succeed,you must delete it after used . @warning If you get the file data succeed,you must delete[] it after us ed.
*/ */
static unsigned char* getFileData(const char* pszFileName, const char* pszMode, unsigned long * pSize); unsigned char* getFileData(const char* pszFileName, const char* pszMode , unsigned long * pSize);
/** /**
@brief Get resource file data from zip file @brief Get resource file data from zip file
@param[in] pszFileName The resource file name which contain the relati ve path of zip file @param[in] pszFileName The resource file name which contain the relati ve path of zip file
@param[out] pSize If get the file data succeed the it will be the data size,or it will be 0 @param[out] pSize If get the file data succeed the it will be the data size,or it will be 0
@return if success,the pointer of data will be returned,or NULL is retu rned @return if success,the pointer of data will be returned,or NULL is retu rned
@warning If you get the file data succeed,you must delete it after used @warning If you get the file data succeed,you must delete[] it after us
. ed.
*/
static unsigned char* getFileDataFromZip(const char* pszZipFilePath, co
nst char* pszFileName, unsigned long * pSize);
/** removes the HD suffix from a path
@returns const char * without the HD suffix
@since v0.99.5
*/ */
static std::string& ccRemoveHDSuffixFromFile(std::string& path); unsigned char* getFileDataFromZip(const char* pszZipFilePath, const cha r* pszFileName, unsigned long * pSize);
/** /**
@brief Generate the absolute path of the file. @brief Generate the absolute path of the file.
@param pszRelativePath The relative path of the file. @param pszRelativePath The relative path of the file.
@return The absolute path of the file. @return The absolute path of the file.
@warning We only add the ResourcePath before the relative path of the f ile. @warning We only add the ResourcePath before the relative path of the f ile.
If you have not set the ResourcePath,the function add "/NEWPLUS/TDA_DAT A/UserData/" as default. If you have not set the ResourcePath,the function add "/NEWPLUS/TDA_DAT A/UserData/" as default.
You can set ResourcePath by function void setResourcePath(const char *p szResourcePath); You can set ResourcePath by function void setResourcePath(const char *p szResourcePath);
*/ */
static const char* fullPathFromRelativePath(const char *pszRelativePath ); const char* fullPathFromRelativePath(const char *pszRelativePath);
/// @cond /// @cond
static const char* fullPathFromRelativeFile(const char *pszFilename, co nst char *pszRelativeFile); const char* fullPathFromRelativeFile(const char *pszFilename, const cha r *pszRelativeFile);
/// @endcond /// @endcond
/** /**
@brief Set the ResourcePath,we will find resource in this path @brief Set the resource directory,we will find resource relative to th
@param pszResourcePath The absolute resource path is directory
@warning Don't call this function in android and iOS, it has not eff @param pszDirectoryName Relative path to root
ect. */
In android, if you want to read file other than apk, you shoud use i void setResourceDirectory(const char *pszDirectoryName);
nvoke getFileData(), and pass the
absolute path.
*/
static void setResourcePath(const char *pszResourcePath);
/**
@brief Generate a CCDictionary pointer by file
@param pFileName The file name of *.plist file
@return The CCDictionary pointer generated from the file
*/
static CCDictionary<std::string, CCObject*> *dictionaryWithContentsOfFi
le(const char *pFileName);
/*
@brief The same meaning as dictionaryWithContentsOfFile(), but it do
esn't call autorelease, so the
invoker should call release().
*/
static CCDictionary<std::string, CCObject*> *dictionaryWithContentsO
fFileThreadSafe(const char *pFileName);
/**
@brief Get the writeable path
@return The path that can write/read file
*/
static std::string getWriteablePath();
/** /**
@brief Set/Get whether pop-up a message box when the image load failed @brief Get the resource directory
*/ */
static void setIsPopupNotify(bool bNotify); const char* getResourceDirectory();
static bool getIsPopupNotify();
/////////////////////////////////////////////////// /**
// interfaces on wophone @brief Get the writeable path
/////////////////////////////////////////////////// @return The path that can write/read file
/** */
@brief Set the resource zip file name std::string getWriteablePath();
@param pszZipFileName The relative path of the .zip file
*/
static void setResource(const char* pszZipFileName);
///////////////////////////////////////////////////
// interfaces on ios
///////////////////////////////////////////////////
static int ccLoadFileIntoMemory(const char *filename, unsigned char **o
ut);
};
class CCFileData /**
{ @brief Set/Get whether pop-up a message box when the image load failed
public: */
CCFileData(const char* pszFileName, const char* pszMode) void setPopupNotify(bool bNotify);
: m_pBuffer(0) bool isPopupNotify();
, m_uSize(0)
{
m_pBuffer = CCFileUtils::getFileData(pszFileName, pszMode, &m_uSize
);
}
~CCFileData()
{
CC_SAFE_DELETE_ARRAY(m_pBuffer);
}
bool reset(const char* pszFileName, const char* pszMode)
{
CC_SAFE_DELETE_ARRAY(m_pBuffer);
m_uSize = 0;
m_pBuffer = CCFileUtils::getFileData(pszFileName, pszMode, &m_uSize
);
return (m_pBuffer) ? true : false;
}
CC_SYNTHESIZE_READONLY(unsigned char *, m_pBuffer, Buffer); protected:
CC_SYNTHESIZE_READONLY(unsigned long , m_uSize, Size); std::string m_obDirectory;
}; };
NS_CC_END; // end of platform group
/// @}
NS_CC_END
#endif // end of __CC_EGLVIEW_PLATFORM_H__ #endif // __CC_FILEUTILS_PLATFORM_H__
 End of changes. 18 change blocks. 
91 lines changed or deleted 41 lines changed or added


 CCGL.h   CCGL.h 
/************************************************************************** ** /************************************************************************** **
Copyright (c) 2010-2011 cocos2d-x.org Copyright (c) 2010 cocos2d-x.org
Copyright (c) 2010 Ricardo Quesada
http://www.cocos2d-x.org http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a cop y Permission is hereby granted, free of charge, to any person obtaining a cop y
of this software and associated documentation files (the "Software"), to de al of this software and associated documentation files (the "Software"), to de al
in the Software without restriction, including without limitation the right s in the Software without restriction, including without limitation the right s
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
skipping to change at line 25 skipping to change at line 24
all copies or substantial portions of the Software. all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#include "platform/CCGL.h"
#ifndef __CCGL_H__
#define __CCGL_H__
#define glClearDepth glClearDepthf
#define glDeleteVertexArrays glDeleteVertexArraysOES
#define glGenVertexArrays glGenVertexArraysOES
#define glBindVertexArray glBindVertexArrayOES
#define CC_GL_DEPTH24_STENCIL8 GL_DEPTH24_STENCIL8_OES
#include <OpenGLES/ES2/gl.h>
#include <OPenGLES/ES2/glext.h>
#endif // __CCGL_H__
 End of changes. 2 change blocks. 
2 lines changed or deleted 1 lines changed or added


 CCGeometry.h   CCGeometry.h 
skipping to change at line 25 skipping to change at line 25
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __COCOS_CGGEMETRY_H__ #ifndef __CCGEMETRY_H__
#define __COCOS_CGGEMETRY_H__ #define __CCGEMETRY_H__
#include "CCCommon.h" #include "platform/CCPlatformMacros.h"
#include "CCObject.h"
namespace cocos2d { NS_CC_BEGIN
typedef float CGFloat; /**
* @addtogroup data_structures
* @{
*/
class CC_DLL CCPoint class CC_DLL CCPoint : public CCObject
{ {
public: public:
float x; float x;
float y; float y;
public: public:
CCPoint();
CCPoint(); CCPoint(float x, float y);
CCPoint(float x, float y); CCPoint(const CCPoint& other);
CCPoint& operator= (const CCPoint& other);
public: void setPoint(float x, float y);
static bool CCPointEqualToPoint(const CCPoint& point1, const CCPoint virtual CCObject* copyWithZone(CCZone* pZone);
& point2); bool equals(const CCPoint& target) const;
public:
/** @deprecated use CCPoint::equals(const CCPoint&) instead, like p1.eq
uals(p2)
*/
CC_DEPRECATED_ATTRIBUTE static bool CCPointEqualToPoint(const CCPoint&
point1, const CCPoint& point2);
}; };
class CC_DLL CCSize class CC_DLL CCSize : public CCObject
{ {
public: public:
float width; float width;
float height; float height;
public: public:
CCSize(); CCSize();
CCSize(float width, float height); CCSize(float width, float height);
CCSize(const CCSize& other);
CCSize& operator= (const CCSize& other);
void setSize(float width, float height);
virtual CCObject* copyWithZone(CCZone* pZone);
bool equals(const CCSize& target) const;
public: public:
static bool CCSizeEqualToSize(const CCSize& size1, const CCSize& siz /** @deprecated use CCSize::equals(const CCSize&) instead, like size1.e
e2); quals(size2) */
CC_DEPRECATED_ATTRIBUTE static bool CCSizeEqualToSize(const CCSize& siz
e1, const CCSize& size2);
}; };
class CC_DLL CCRect class CC_DLL CCRect : public CCObject
{ {
public: public:
CCPoint origin; CCPoint origin;
CCSize size; CCSize size;
public: public:
CCRect(); CCRect();
CCRect(float x, float y, float width, float height); CCRect(float x, float y, float width, float height);
CCRect(const CCRect& other);
public: CCRect& operator= (const CCRect& other);
//! return the leftmost x-value of 'rect' void setRect(float x, float y, float width, float height);
static CGFloat CCRectGetMinX(const CCRect& rect); virtual CCObject* copyWithZone(CCZone* pZone);
float getMinX() const; /// return the leftmost x-value of current rect
//! return the rightmost x-value of 'rect' float getMidX() const; /// return the midpoint x-value of current rect
static CGFloat CCRectGetMaxX(const CCRect& rect); float getMaxX() const; /// return the rightmost x-value of current rect
float getMinY() const; /// return the bottommost y-value of current rec
//! return the midpoint x-value of 'rect' t
static CGFloat CCRectGetMidX(const CCRect& rect); float getMidY() const; /// return the midpoint y-value of current rect
float getMaxY() const; /// return the topmost y-value of current rect
//! Return the bottommost y-value of `rect' bool equals(const CCRect& rect) const;
static CGFloat CCRectGetMinY(const CCRect& rect); bool containsPoint(const CCPoint& point) const;
bool intersectsRect(const CCRect& rect) const;
//! Return the topmost y-value of `rect'
static CGFloat CCRectGetMaxY(const CCRect& rect); public:
/** @deprecated use CCRect::equals(const CCRect&) instead, like r1.equa
//! Return the midpoint y-value of `rect' ls(r2) */
static CGFloat CCRectGetMidY(const CCRect& rect); CC_DEPRECATED_ATTRIBUTE static bool CCRectEqualToRect(const CCRect& rec
t1, const CCRect& rect2);
static bool CCRectEqualToRect(const CCRect& rect1, const CCRect& rec /** @deprecated use CCRect::containsPoint(const CCPoint&) instead, like
t2); rect.containsPoint(point) */
CC_DEPRECATED_ATTRIBUTE static bool CCRectContainsPoint(const CCRect& r
static bool CCRectContainsPoint(const CCRect& rect, const CCPoint& poin ect, const CCPoint& point);
t); /** @deprecated use CCRect::intersectsRect(const CCRect&) instead, like
r1.intersectsRect(r2) */
static bool CCRectIntersectsRect(const CCRect& rectA, const CCRect& CC_DEPRECATED_ATTRIBUTE static bool CCRectIntersectsRect(const CCRect&
rectB); rectA, const CCRect& rectB);
}; };
#define CCPointMake(x, y) CCPoint((x), (y)) #define CCPointMake(x, y) CCPoint((float)(x), (float)(y))
#define CCSizeMake(width, height) CCSize((width), (height)) #define CCSizeMake(width, height) CCSize((float)(width), (float)(height))
#define CCRectMake(x, y, width, height) CCRect((x), (y), (width), (height)) #define CCRectMake(x, y, width, height) CCRect((float)(x), (float)(y), (flo
at)(width), (float)(height))
const CCPoint CCPointZero = CCPointMake(0,0); const CCPoint CCPointZero = CCPointMake(0,0);
/* The "zero" size -- equivalent to CCSizeMake(0, 0). */ /* The "zero" size -- equivalent to CCSizeMake(0, 0). */
const CCSize CCSizeZero = CCSizeMake(0,0); const CCSize CCSizeZero = CCSizeMake(0,0);
/* The "zero" rectangle -- equivalent to CCRectMake(0, 0, 0, 0). */ /* The "zero" rectangle -- equivalent to CCRectMake(0, 0, 0, 0). */
const CCRect CCRectZero = CCRectMake(0,0,0,0); const CCRect CCRectZero = CCRectMake(0,0,0,0);
}//namespace cocos2d // end of data_structure group
/// @}
NS_CC_END
#endif // __COCOS_CGGEMETRY_H__ #endif // __CCGEMETRY_H__
 End of changes. 17 change blocks. 
59 lines changed or deleted 81 lines changed or added


 CCGrabber.h   CCGrabber.h 
skipping to change at line 29 skipping to change at line 29
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __EFFECTS_CCGRABBER_H__ #ifndef __EFFECTS_CCGRABBER_H__
#define __EFFECTS_CCGRABBER_H__ #define __EFFECTS_CCGRABBER_H__
#include "CCConfiguration.h" #include "CCConfiguration.h"
#include "CCObject.h" #include "cocoa/CCObject.h"
#include "CCGL.h" #include "CCGL.h"
namespace cocos2d NS_CC_BEGIN
class CCTexture2D;
/**
* @addtogroup effects
* @{
*/
/** FBO class that grabs the the contents of the screen */
class CCGrabber : public CCObject
{ {
class CCTexture2D; public:
CCGrabber(void);
~CCGrabber(void);
void grab(CCTexture2D *pTexture);
void beforeRender(CCTexture2D *pTexture);
void afterRender(CCTexture2D *pTexture);
protected:
GLuint m_fbo;
GLint m_oldFBO;
GLfloat m_oldClearColor[4];
};
/** FBO class that grabs the the contents of the screen */ // end of effects group
class CCGrabber : public CCObject /// @}
{
public:
CCGrabber(void);
~CCGrabber(void);
void grab(CCTexture2D *pTexture);
void beforeRender(CCTexture2D *pTexture);
void afterRender(CCTexture2D *pTexture);
protected:
GLuint m_fbo;
GLint m_oldFBO;
CCGlesVersion m_eGlesVersion;
};
} // end of namespace cocos2d NS_CC_END
#endif // __EFFECTS_CCGRABBER_H__ #endif // __EFFECTS_CCGRABBER_H__
 End of changes. 5 change blocks. 
20 lines changed or deleted 28 lines changed or added


 CCGrid.h   CCGrid.h 
skipping to change at line 28 skipping to change at line 28
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __EFFECTS_CCGRID_H__ #ifndef __EFFECTS_CCGRID_H__
#define __EFFECTS_CCGRID_H__ #define __EFFECTS_CCGRID_H__
#include "CCObject.h" #include "cocoa/CCObject.h"
#include "CCNode.h" #include "base_nodes/CCNode.h"
#include "CCCamera.h" #include "CCCamera.h"
#include "ccTypes.h" #include "ccTypes.h"
#include "CCTexture2D.h" #include "textures/CCTexture2D.h"
#include "CCDirector.h"
#include "kazmath/mat4.h"
NS_CC_BEGIN
class CCTexture2D;
class CCGrabber;
class CCGLProgram;
/**
* @addtogroup effects
* @{
*/
/** Base class for other
*/
class CC_DLL CCGridBase : public CCObject
{
public:
virtual ~CCGridBase(void);
namespace cocos2d /** wheter or not the grid is active */
inline bool isActive(void) { return m_bActive; }
void setActive(bool bActive);
/** number of times that the grid will be reused */
inline int getReuseGrid(void) { return m_nReuseGrid; }
inline void setReuseGrid(int nReuseGrid) { m_nReuseGrid = nReuseGrid; }
/** size of the grid */
inline const ccGridSize& getGridSize(void) { return m_sGridSize; }
inline void setGridSize(const ccGridSize& gridSize) { m_sGridSize = gri
dSize; }
/** pixels between the grids */
inline const CCPoint& getStep(void) { return m_obStep; }
inline void setStep(const CCPoint& step) { m_obStep = step; }
/** is texture flipped */
inline bool isTextureFlipped(void) { return m_bIsTextureFlipped; }
void setTextureFlipped(bool bFlipped);
bool initWithSize(const ccGridSize& gridSize, CCTexture2D *pTexture, bo
ol bFlipped);
bool initWithSize(const ccGridSize& gridSize);
void beforeDraw(void);
void afterDraw(CCNode *pTarget);
virtual void blit(void);
virtual void reuse(void);
virtual void calculateVertexPoints(void);
public:
/** create one Grid
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCGridBase* gridWithSize(const ccGridSiz
e& gridSize, CCTexture2D *texture, bool flipped);
/** create one Grid
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCGridBase* gridWithSize(const ccGridSiz
e& gridSize);
/** create one Grid */
static CCGridBase* create(const ccGridSize& gridSize, CCTexture2D *text
ure, bool flipped);
/** create one Grid */
static CCGridBase* create(const ccGridSize& gridSize);
void set2DProjection(void);
protected:
bool m_bActive;
int m_nReuseGrid;
ccGridSize m_sGridSize;
CCTexture2D *m_pTexture;
CCPoint m_obStep;
CCGrabber *m_pGrabber;
bool m_bIsTextureFlipped;
CCGLProgram* m_pShaderProgram;
ccDirectorProjection m_directorProjection;
};
/**
CCGrid3D is a 3D grid implementation. Each vertex has 3 dimensions: x,y,z
*/
class CC_DLL CCGrid3D : public CCGridBase
{
public:
CCGrid3D();
~CCGrid3D(void);
/** returns the vertex at a given position */
ccVertex3F vertex(const ccGridSize& pos);
/** returns the original (non-transformed) vertex at a given position *
/
ccVertex3F originalVertex(const ccGridSize& pos);
/** sets a new vertex at a given position */
void setVertex(const ccGridSize& pos, const ccVertex3F& vertex);
virtual void blit(void);
virtual void reuse(void);
virtual void calculateVertexPoints(void);
public:
/** @deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCGrid3D* gridWithSize(const ccGridSize&
gridSize, CCTexture2D *pTexture, bool bFlipped);
/** @deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCGrid3D* gridWithSize(const ccGridSize&
gridSize);
/** create one Grid */
static CCGrid3D* create(const ccGridSize& gridSize, CCTexture2D *pTextu
re, bool bFlipped);
/** create one Grid */
static CCGrid3D* create(const ccGridSize& gridSize);
protected:
GLvoid *m_pTexCoordinates;
GLvoid *m_pVertices;
GLvoid *m_pOriginalVertices;
GLushort *m_pIndices;
};
/**
CCTiledGrid3D is a 3D grid implementation. It differs from Grid3D in that
the tiles can be separated from the grid.
*/
class CC_DLL CCTiledGrid3D : public CCGridBase
{ {
class CCTexture2D; public:
class CCGrabber; CCTiledGrid3D();
~CCTiledGrid3D(void);
/** returns the tile at the given position */
ccQuad3 tile(const ccGridSize& pos);
/** returns the original tile (untransformed) at the given position */
ccQuad3 originalTile(const ccGridSize& pos);
/** sets a new tile */
void setTile(const ccGridSize& pos, const ccQuad3& coords);
virtual void blit(void);
virtual void reuse(void);
virtual void calculateVertexPoints(void);
public:
CC_DEPRECATED_ATTRIBUTE static CCTiledGrid3D* gridWithSize(const ccGrid
Size& gridSize, CCTexture2D *pTexture, bool bFlipped);
CC_DEPRECATED_ATTRIBUTE static CCTiledGrid3D* gridWithSize(const ccGrid
Size& gridSize);
/** create one Grid */
static CCTiledGrid3D* create(const ccGridSize& gridSize, CCTexture2D *p
Texture, bool bFlipped);
/** create one Grid */
static CCTiledGrid3D* create(const ccGridSize& gridSize);
protected:
GLvoid *m_pTexCoordinates;
GLvoid *m_pVertices;
GLvoid *m_pOriginalVertices;
GLushort *m_pIndices;
};
// end of effects group
/// @}
/** Base class for other NS_CC_END
*/
class CCGridBase : public CCObject
{
public:
virtual ~CCGridBase(void);
/** wheter or not the grid is active */
inline bool isActive(void) { return m_bActive; }
void setActive(bool bActive);
/** number of times that the grid will be reused */
inline int getReuseGrid(void) { return m_nReuseGrid; }
inline void setReuseGrid(int nReuseGrid) { m_nReuseGrid = nR
euseGrid; }
/** size of the grid */
inline const ccGridSize& getGridSize(void) { return m_sGridS
ize; }
inline void setGridSize(const ccGridSize& gridSize) { m_sGri
dSize = gridSize; }
/** pixels between the grids */
inline const CCPoint& getStep(void) { return m_obStep; }
inline void setStep(const CCPoint& step) { m_obStep = step;
}
/** is texture flipped */
inline bool isTextureFlipped(void) { return m_bIsTextureFlip
ped; }
void setIsTextureFlipped(bool bFlipped);
bool initWithSize(const ccGridSize& gridSize, CCTexture2D *p
Texture, bool bFlipped);
bool initWithSize(const ccGridSize& gridSize);
void beforeDraw(void);
void afterDraw(CCNode *pTarget);
virtual void blit(void);
virtual void reuse(void);
virtual void calculateVertexPoints(void);
public:
static CCGridBase* gridWithSize(const ccGridSize& gridSize,
CCTexture2D *texture, bool flipped);
static CCGridBase* gridWithSize(const ccGridSize& gridSize);
void set2DProjection(void);
void set3DProjection(void);
protected:
void applyLandscape(void);
protected:
bool m_bActive;
int m_nReuseGrid;
ccGridSize m_sGridSize;
CCTexture2D *m_pTexture;
CCPoint m_obStep;
CCGrabber *m_pGrabber;
bool m_bIsTextureFlipped;
};
/**
CCGrid3D is a 3D grid implementation. Each vertex has 3 dimensions:
x,y,z
*/
class CCGrid3D : public CCGridBase
{
public:
~CCGrid3D(void);
/** returns the vertex at a given position */
ccVertex3F vertex(const ccGridSize& pos);
/** returns the original (non-transformed) vertex at a given
position */
ccVertex3F originalVertex(const ccGridSize& pos);
/** sets a new vertex at a given position */
void setVertex(const ccGridSize& pos, const ccVertex3F& vert
ex);
virtual void blit(void);
virtual void reuse(void);
virtual void calculateVertexPoints(void);
public:
static CCGrid3D* gridWithSize(const ccGridSize& gridSize, CC
Texture2D *pTexture, bool bFlipped);
static CCGrid3D* gridWithSize(const ccGridSize& gridSize);
protected:
GLvoid *m_pTexCoordinates;
GLvoid *m_pVertices;
GLvoid *m_pOriginalVertices;
GLushort *m_pIndices;
};
/**
CCTiledGrid3D is a 3D grid implementation. It differs from Grid3D i
n that
the tiles can be separated from the grid.
*/
class CCTiledGrid3D : public CCGridBase
{
public:
~CCTiledGrid3D(void);
/** returns the tile at the given position */
ccQuad3 tile(const ccGridSize& pos);
/** returns the original tile (untransformed) at the given p
osition */
ccQuad3 originalTile(const ccGridSize& pos);
/** sets a new tile */
void setTile(const ccGridSize& pos, const ccQuad3& coords);
virtual void blit(void);
virtual void reuse(void);
virtual void calculateVertexPoints(void);
public:
static CCTiledGrid3D* gridWithSize(const ccGridSize& gridSiz
e, CCTexture2D *pTexture, bool bFlipped);
static CCTiledGrid3D* gridWithSize(const ccGridSize& gridSiz
e);
protected:
GLvoid *m_pTexCoordinates;
GLvoid *m_pVertices;
GLvoid *m_pOriginalVertices;
GLushort *m_pIndices;
};
}
#endif // __EFFECTS_CCGRID_H__ #endif // __EFFECTS_CCGRID_H__
 End of changes. 5 change blocks. 
137 lines changed or deleted 171 lines changed or added


 CCIMEDelegate.h   CCIMEDelegate.h 
skipping to change at line 28 skipping to change at line 28
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CC_IME_DELEGATE_H__ #ifndef __CC_IME_DELEGATE_H__
#define __CC_IME_DELEGATE_H__ #define __CC_IME_DELEGATE_H__
#include "CCGeometry.h" #include "cocoa/CCGeometry.h"
NS_CC_BEGIN; NS_CC_BEGIN
/**
* @addtogroup input
* @{
*/
typedef struct typedef struct
{ {
CCRect begin; // the soft keyboard rectangle when animati n begin CCRect begin; // the soft keyboard rectangle when animati n begin
CCRect end; // the soft keyboard rectangle when animati n end CCRect end; // the soft keyboard rectangle when animati n end
float duration; // the soft keyboard animation duration float duration; // the soft keyboard animation duration
} CCIMEKeyboardNotificationInfo; } CCIMEKeyboardNotificationInfo;
/** /**
@brief Input method editor delegate. @brief Input method editor delegate.
*/ */
class CC_DLL CCIMEDelegate class CC_DLL CCIMEDelegate
{ {
public: public:
virtual ~CCIMEDelegate(); virtual ~CCIMEDelegate();
virtual bool attachWithIME(); virtual bool attachWithIME();
virtual bool detachWithIME(); virtual bool detachWithIME();
protected: protected:
friend class CCIMEDispatcher; friend class CCIMEDispatcher;
/** /**
@brief Decide the delegate instance is ready for receive ime messag e or not. @brief Decide the delegate instance is ready for receive ime message or not.
Called by CCIMEDispatcher. Called by CCIMEDispatcher.
*/ */
virtual bool canAttachWithIME() { return false; } virtual bool canAttachWithIME() { return false; }
/** /**
@brief When the delegate detach with IME, this method call by CCIME Dispatcher. @brief When the delegate detach with IME, this method call by CCIMED ispatcher.
*/ */
virtual void didAttachWithIME() {} virtual void didAttachWithIME() {}
/** /**
@brief Decide the delegate instance can stop receive ime message or not. @brief Decide the delegate instance can stop receive ime message or not.
*/ */
virtual bool canDetachWithIME() { return false; } virtual bool canDetachWithIME() { return false; }
/** /**
@brief When the delegate detach with IME, this method call by CCIME Dispatcher. @brief When the delegate detach with IME, this method call by CCIMED ispatcher.
*/ */
virtual void didDetachWithIME() {} virtual void didDetachWithIME() {}
/** /**
@brief Called by CCIMEDispatcher when some text input from IME. @brief Called by CCIMEDispatcher when some text input from IME.
*/ */
virtual void insertText(const char * text, int len) {CC_UNUSED_PARAM(te xt);CC_UNUSED_PARAM(len);} virtual void insertText(const char * text, int len) {CC_UNUSED_PARAM(te xt);CC_UNUSED_PARAM(len);}
/** /**
@brief Called by CCIMEDispatcher when user clicked the backward key . @brief Called by CCIMEDispatcher when user clicked the backward key.
*/ */
virtual void deleteBackward() {} virtual void deleteBackward() {}
/** /**
@brief Called by CCIMEDispatcher for get text which delegate alread y has. @brief Called by CCIMEDispatcher for get text which delegate already has.
*/ */
virtual const char * getContentText() { return 0; } virtual const char * getContentText() { return 0; }
/////////////////////////////////////////////////////////////////////// /// /////////////////////////////////////////////////////////////////////// ///
// keyboard show/hide notification // keyboard show/hide notification
/////////////////////////////////////////////////////////////////////// /// /////////////////////////////////////////////////////////////////////// ///
virtual void keyboardWillShow(CCIMEKeyboardNotificationInfo& info) {C C_UNUSED_PARAM(info);} virtual void keyboardWillShow(CCIMEKeyboardNotificationInfo& info) {C C_UNUSED_PARAM(info);}
virtual void keyboardDidShow(CCIMEKeyboardNotificationInfo& info) {C C_UNUSED_PARAM(info);} virtual void keyboardDidShow(CCIMEKeyboardNotificationInfo& info) {C C_UNUSED_PARAM(info);}
virtual void keyboardWillHide(CCIMEKeyboardNotificationInfo& info) {C C_UNUSED_PARAM(info);} virtual void keyboardWillHide(CCIMEKeyboardNotificationInfo& info) {C C_UNUSED_PARAM(info);}
virtual void keyboardDidHide(CCIMEKeyboardNotificationInfo& info) {C C_UNUSED_PARAM(info);} virtual void keyboardDidHide(CCIMEKeyboardNotificationInfo& info) {C C_UNUSED_PARAM(info);}
protected: protected:
CCIMEDelegate(); CCIMEDelegate();
}; };
NS_CC_END; // end of input group
/// @}
NS_CC_END
#endif // __CC_IME_DELEGATE_H__ #endif // __CC_IME_DELEGATE_H__
 End of changes. 12 change blocks. 
11 lines changed or deleted 19 lines changed or added


 CCIMEDispatcher.h   CCIMEDispatcher.h 
skipping to change at line 30 skipping to change at line 30
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CC_IME_DISPATCHER_H__ #ifndef __CC_IME_DISPATCHER_H__
#define __CC_IME_DISPATCHER_H__ #define __CC_IME_DISPATCHER_H__
#include "CCIMEDelegate.h" #include "CCIMEDelegate.h"
NS_CC_BEGIN; NS_CC_BEGIN
/** /**
@brief Input Method Edit Message Dispatcher. * @addtogroup input
* @{
*/
/**
@brief Input Method Edit Message Dispatcher.
*/ */
class CC_DLL CCIMEDispatcher class CC_DLL CCIMEDispatcher
{ {
public: public:
~CCIMEDispatcher(); ~CCIMEDispatcher();
/** /**
@brief Returns the shared CCIMEDispatcher object for the system. @brief Returns the shared CCIMEDispatcher object for the system.
*/ */
static CCIMEDispatcher* sharedDispatcher(); static CCIMEDispatcher* sharedDispatcher();
skipping to change at line 56 skipping to change at line 61
// @brief Release all CCIMEDelegates from shared dispatcher. // @brief Release all CCIMEDelegates from shared dispatcher.
// */ // */
// static void purgeSharedDispatcher(); // static void purgeSharedDispatcher();
/** /**
@brief dispatch the input text from ime @brief dispatch the input text from ime
*/ */
void dispatchInsertText(const char * pText, int nLen); void dispatchInsertText(const char * pText, int nLen);
/** /**
@brief dispatch the delete backward operation @brief dispatch the delete backward operation
*/ */
void dispatchDeleteBackward(); void dispatchDeleteBackward();
/** /**
@brief get the content text, which current CCIMEDelegate which atta ched with IME has. @brief get the content text, which current CCIMEDelegate which attac hed with IME has.
*/ */
const char * getContentText(); const char * getContentText();
/////////////////////////////////////////////////////////////////////// /// /////////////////////////////////////////////////////////////////////// ///
// dispatch keyboard notification // dispatch keyboard notification
/////////////////////////////////////////////////////////////////////// /// /////////////////////////////////////////////////////////////////////// ///
void dispatchKeyboardWillShow(CCIMEKeyboardNotificationInfo& info); void dispatchKeyboardWillShow(CCIMEKeyboardNotificationInfo& info);
void dispatchKeyboardDidShow(CCIMEKeyboardNotificationInfo& info); void dispatchKeyboardDidShow(CCIMEKeyboardNotificationInfo& info);
void dispatchKeyboardWillHide(CCIMEKeyboardNotificationInfo& info); void dispatchKeyboardWillHide(CCIMEKeyboardNotificationInfo& info);
void dispatchKeyboardDidHide(CCIMEKeyboardNotificationInfo& info); void dispatchKeyboardDidHide(CCIMEKeyboardNotificationInfo& info);
protected: protected:
friend class CCIMEDelegate; friend class CCIMEDelegate;
/** /**
@brief add delegate to concern ime msg @brief add delegate to concern ime msg
*/ */
void addDelegate(CCIMEDelegate * pDelegate); void addDelegate(CCIMEDelegate * pDelegate);
/** /**
@brief attach the pDeleate with ime. @brief attach the pDeleate with ime.
@return If the old delegate can detattach with ime and the new delegate @return If the old delegate can detattach with ime and the new delegate
can attach with ime, return true, otherwise return false. can attach with ime, return true, otherwise return false.
*/ */
bool attachDelegateWithIME(CCIMEDelegate * pDelegate); bool attachDelegateWithIME(CCIMEDelegate * pDelegate);
bool detachDelegateWithIME(CCIMEDelegate * pDelegate); bool detachDelegateWithIME(CCIMEDelegate * pDelegate);
/** /**
@brief remove the delegate from the delegates who concern ime msg @brief remove the delegate from the delegates who concern ime msg
*/ */
void removeDelegate(CCIMEDelegate * pDelegate); void removeDelegate(CCIMEDelegate * pDelegate);
private: private:
CCIMEDispatcher(); CCIMEDispatcher();
class Impl; class Impl;
Impl * m_pImpl; Impl * m_pImpl;
}; };
NS_CC_END; // end of input group
/// @}
NS_CC_END
#endif // __CC_IME_DISPATCHER_H__ #endif // __CC_IME_DISPATCHER_H__
 End of changes. 7 change blocks. 
6 lines changed or deleted 14 lines changed or added


 CCImage.h   CCImage.h 
skipping to change at line 25 skipping to change at line 25
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CC_IMAGE_H_YANGWS_20110115__ #ifndef __CC_IMAGE_H__
#define __CC_IMAGE_H_YANGWS_20110115__ #define __CC_IMAGE_H__
#include "CCCommon.h" #include "cocoa/CCObject.h"
NS_CC_BEGIN; NS_CC_BEGIN
class CC_DLL CCImage /**
* @addtogroup platform
* @{
*/
class CC_DLL CCImage : public CCObject
{ {
public: public:
CCImage(); CCImage();
~CCImage(); ~CCImage();
typedef enum typedef enum
{ {
kFmtJpg = 0, kFmtJpg = 0,
kFmtPng, kFmtPng,
kFmtRawData, kFmtTiff,
kFmtUnKnown kFmtRawData,
kFmtUnKnown
}EImageFormat; }EImageFormat;
typedef enum typedef enum
{ {
kAlignCenter = 0x33, ///< Horizontal center and vertical cen ter. kAlignCenter = 0x33, ///< Horizontal center and vertical cen ter.
kAlignTop = 0x13, ///< Horizontal center and vertical top . kAlignTop = 0x13, ///< Horizontal center and vertical top .
kAlignTopRight = 0x12, ///< Horizontal right and vertical top. kAlignTopRight = 0x12, ///< Horizontal right and vertical top.
kAlignRight = 0x32, ///< Horizontal right and vertical cent er. kAlignRight = 0x32, ///< Horizontal right and vertical cent er.
kAlignBottomRight = 0x22, ///< Horizontal right and vertical bott om. kAlignBottomRight = 0x22, ///< Horizontal right and vertical bott om.
kAlignBottom = 0x23, ///< Horizontal center and vertical bot tom. kAlignBottom = 0x23, ///< Horizontal center and vertical bot tom.
skipping to change at line 67 skipping to change at line 73
}ETextAlign; }ETextAlign;
/** /**
@brief Load the image from the specified path. @brief Load the image from the specified path.
@param strPath the absolute file path @param strPath the absolute file path
@param imageType the type of image, now only support tow types. @param imageType the type of image, now only support tow types.
@return true if load correctly @return true if load correctly
*/ */
bool initWithImageFile(const char * strPath, EImageFormat imageType = k FmtPng); bool initWithImageFile(const char * strPath, EImageFormat imageType = k FmtPng);
/* /*
@brief The same meaning as initWithImageFile, but it is thread safe @brief The same meaning as initWithImageFile, but it is thread safe. I
. It is casued by t is casued by
loadImage() in CCTextureCache.cpp. loadImage() in CCTextureCache.cpp.
@param fullpath full path of the file @param fullpath full path of the file
@param imageType the type of image, now only support tow types. @param imageType the type of image, now only support tow types.
@return true if load correctly @return true if load correctly
*/ */
bool initWithImageFileThreadSafe(const char *fullpath, EImageFormat bool initWithImageFileThreadSafe(const char *fullpath, EImageFormat ima
imageType = kFmtPng); geType = kFmtPng);
/** /**
@brief Load image from stream buffer. @brief Load image from stream buffer.
@warning kFmtRawData only support RGBA8888 @warning kFmtRawData only support RGBA8888
@param pBuffer stream buffer that hold the image data @param pBuffer stream buffer that hold the image data
@param nLength the length of data(managed in byte) @param nLength the length of data(managed in byte)
@param nWidth, nHeight, nBitsPerComponent are used for kFmtRawData @param nWidth, nHeight, nBitsPerComponent are used for kFmtRawData
@return true if load correctly @return true if load correctly
*/ */
bool initWithImageData(void * pData, bool initWithImageData(void * pData,
int nDataLen, int nDataLen,
EImageFormat eFmt = kFmtP EImageFormat eFmt = kFmtUnKnown,
ng, int nWidth = 0,
int nWidth = 0, int nHeight = 0,
int nHeight = 0, int nBitsPerComponent = 8);
int nBitsPerComponent = 8
);
/** /**
@brief Create image with specified string. @brief Create image with specified string.
@param pText the text which the image show, nil cause init fail @param pText the text which the image show, nil cause init fail
@param nWidth the image width, if 0, the width match the text's w idth @param nWidth the image width, if 0, the width match the text's w idth
@param nHeight the image height, if 0, the height match the text's height @param nHeight the image height, if 0, the height match the text's height
@param eAlignMask the test Alignment @param eAlignMask the test Alignment
@param pFontName the name of the font which use to draw the text. If nil, use the default system font. @param pFontName the name of the font which use to draw the text. If nil, use the default system font.
@param nSize the font size, if 0, use the system default size. @param nSize the font size, if 0, use the system default size.
*/ */
bool initWithString( bool initWithString(
const char * pText, const char * pText,
int nWidth = 0, int nWidth = 0,
skipping to change at line 115 skipping to change at line 121
ETextAlign eAlignMask = kAlignCenter, ETextAlign eAlignMask = kAlignCenter,
const char * pFontName = 0, const char * pFontName = 0,
int nSize = 0); int nSize = 0);
unsigned char * getData() { return m_pData; } unsigned char * getData() { return m_pData; }
int getDataLen() { return m_nWidth * m_nHeight; } int getDataLen() { return m_nWidth * m_nHeight; }
bool hasAlpha() { return m_bHasAlpha; } bool hasAlpha() { return m_bHasAlpha; }
bool isPremultipliedAlpha() { return m_bPreMulti; } bool isPremultipliedAlpha() { return m_bPreMulti; }
void release();
/** /**
@brief Save the CCImage data to specified file with specified forma @brief Save the CCImage data to specified file with specified format
t. .
@param pszFilePath the file's absolute path, including @param pszFilePath the file's absolute path, including file s
file subfix ubfix
@param bIsToRGB if the image is saved as RGB format @param bIsToRGB if the image is saved as RGB format
*/ */
bool saveToFile(const char *pszFilePath, bool bIsToRGB = true); bool saveToFile(const char *pszFilePath, bool bIsToRGB = true);
CC_SYNTHESIZE_READONLY(short, m_nWidth, Width); CC_SYNTHESIZE_READONLY(unsigned short, m_nWidth, Width);
CC_SYNTHESIZE_READONLY(short, m_nHeight, Height); CC_SYNTHESIZE_READONLY(unsigned short, m_nHeight, Height);
CC_SYNTHESIZE_READONLY(int, m_nBitsPerComponent, BitsPerComponent ); CC_SYNTHESIZE_READONLY(int, m_nBitsPerComponent, BitsPerComponent );
protected: protected:
bool _initWithJpgData(void *pData, int nDatalen); bool _initWithJpgData(void *pData, int nDatalen);
bool _initWithPngData(void *pData, int nDatalen); bool _initWithPngData(void *pData, int nDatalen);
bool _initWithTiffData(void* pData, int nDataLen);
// @warning kFmtRawData only support RGBA8888
bool _initWithRawData(void *pData, int nDatalen, int nWidth, int nHeigh
t, int nBitsPerComponent);
// @warning kFmtRawData only support RGBA8888 bool _saveImageToPNG(const char *pszFilePath, bool bIsToRGB = true);
bool _initWithRawData(void *pData, int nDatalen, int nWidth, int nHe bool _saveImageToJPG(const char *pszFilePath);
ight, int nBitsPerComponent);
bool _saveImageToPNG(const char *pszFilePath, bool bIsToRGB = true);
bool _saveImageToJPG(const char *pszFilePath);
unsigned char *m_pData; unsigned char *m_pData;
bool m_bHasAlpha; bool m_bHasAlpha;
bool m_bPreMulti; bool m_bPreMulti;
private: private:
// noncopyable // noncopyable
CCImage(const CCImage& rImg); CCImage(const CCImage& rImg);
CCImage & operator=(const CCImage&); CCImage & operator=(const CCImage&);
}; };
NS_CC_END; // end of platform group
/// @}
NS_CC_END
#endif // __CC_IMAGE_H_YANGWS_20110115__ #endif // __CC_IMAGE_H__
 End of changes. 18 change blocks. 
41 lines changed or deleted 46 lines changed or added


 CCKeypadDelegate.h   CCKeypadDelegate.h 
skipping to change at line 28 skipping to change at line 28
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CCKEYPAD_DELEGATE_H__ #ifndef __CCKEYPAD_DELEGATE_H__
#define __CCKEYPAD_DELEGATE_H__ #define __CCKEYPAD_DELEGATE_H__
#include "CCObject.h" #include "cocoa/CCObject.h"
namespace cocos2d { NS_CC_BEGIN
/**
* @addtogroup input
* @{
*/
class CC_DLL CCKeypadDelegate class CC_DLL CCKeypadDelegate
{ {
public: public:
// The back key clicked // The back key clicked
virtual void keyBackClicked() {} virtual void keyBackClicked() {}
// The menu key clicked. only avialble on wophone & android // The menu key clicked. only avialble on wophone & android
virtual void keyMenuClicked() {}; virtual void keyMenuClicked() {};
}; };
skipping to change at line 67 skipping to change at line 72
virtual bool initWithDelegate(CCKeypadDelegate *pDelegate); virtual bool initWithDelegate(CCKeypadDelegate *pDelegate);
public: public:
/** allocates a CCKeypadHandler with a delegate */ /** allocates a CCKeypadHandler with a delegate */
static CCKeypadHandler* handlerWithDelegate(CCKeypadDelegate *pDelegate ); static CCKeypadHandler* handlerWithDelegate(CCKeypadDelegate *pDelegate );
protected: protected:
CCKeypadDelegate* m_pDelegate; CCKeypadDelegate* m_pDelegate;
}; };
} //namespace cocos2d // end of input group
/// @}
NS_CC_END
#endif // __CCKEYPAD_DELEGATE_H__ #endif // __CCKEYPAD_DELEGATE_H__
 End of changes. 3 change blocks. 
3 lines changed or deleted 11 lines changed or added


 CCKeypadDispatcher.h   CCKeypadDispatcher.h 
skipping to change at line 29 skipping to change at line 29
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CCKEYPAD_DISPATCHER_H__ #ifndef __CCKEYPAD_DISPATCHER_H__
#define __CCKEYPAD_DISPATCHER_H__ #define __CCKEYPAD_DISPATCHER_H__
#include "CCKeypadDelegate.h" #include "CCKeypadDelegate.h"
#include "CCMutableArray.h" #include "cocoa/CCArray.h"
namespace cocos2d { NS_CC_BEGIN
/**
* @addtogroup input
* @{
*/
typedef enum { typedef enum {
// the back key clicked msg // the back key clicked msg
kTypeBackClicked = 1, kTypeBackClicked = 1,
kTypeMenuClicked, kTypeMenuClicked,
} ccKeypadMSGType; } ccKeypadMSGType;
struct _ccCArray; struct _ccCArray;
/** /**
@class CCKeypadDispatcher @class CCKeypadDispatcher
@brief Dispatch the keypad message from the phone @brief Dispatch the keypad message from the phone
*/ */
class CC_DLL CCKeypadDispatcher : public CCObject class CC_DLL CCKeypadDispatcher : public CCObject
{ {
public: public:
CCKeypadDispatcher(); CCKeypadDispatcher();
~CCKeypadDispatcher(); ~CCKeypadDispatcher();
/** /**
@brief Returns the shared CCKeypadDispatcher object for the system.
*/
static CCKeypadDispatcher* sharedDispatcher();
/**
@brief Release the shared CCKeypadDispatcher object from the system.
*/
static void purgeSharedDispatcher();
/**
@brief add delegate to concern keypad msg @brief add delegate to concern keypad msg
*/ */
void addDelegate(CCKeypadDelegate* pDelegate); void addDelegate(CCKeypadDelegate* pDelegate);
/** /**
@brief remove the delegate from the delegates who concern keypad msg @brief remove the delegate from the delegates who concern keypad msg
*/ */
void removeDelegate(CCKeypadDelegate* pDelegate); void removeDelegate(CCKeypadDelegate* pDelegate);
/** /**
skipping to change at line 87 skipping to change at line 82
*/ */
void forceRemoveDelegate(CCKeypadDelegate* pDelegate); void forceRemoveDelegate(CCKeypadDelegate* pDelegate);
/** /**
@brief dispatch the key pad msg @brief dispatch the key pad msg
*/ */
bool dispatchKeypadMSG(ccKeypadMSGType nMsgType); bool dispatchKeypadMSG(ccKeypadMSGType nMsgType);
protected: protected:
typedef CCMutableArray<CCKeypadHandler*> KeypadDelegateArray; CCArray* m_pDelegates;
KeypadDelegateArray* m_pDelegates;
bool m_bLocked; bool m_bLocked;
bool m_bToAdd; bool m_bToAdd;
bool m_bToRemove; bool m_bToRemove;
struct _ccCArray *m_pHandlersToAdd; struct _ccCArray *m_pHandlersToAdd;
struct _ccCArray *m_pHandlersToRemove; struct _ccCArray *m_pHandlersToRemove;
}; };
} // namespace cocos2d // end of input group
/// @}
NS_CC_END
#endif //__CCKEYPAD_DISPATCHER_H__ #endif //__CCKEYPAD_DISPATCHER_H__
 End of changes. 5 change blocks. 
16 lines changed or deleted 12 lines changed or added


 CCLabelAtlas.h   CCLabelAtlas.h 
skipping to change at line 28 skipping to change at line 28
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CCLABEL_ATLAS_H__ #ifndef __CCLABEL_ATLAS_H__
#define __CCLABEL_ATLAS_H__ #define __CCLABEL_ATLAS_H__
#include "CCAtlasNode.h"
namespace cocos2d{
/** @brief CCLabelAtlas is a subclass of CCAtlasNode. #include "base_nodes/CCAtlasNode.h"
It can be as a replacement of CCLabel since it is MUCH faster. NS_CC_BEGIN
CCLabelAtlas versus CCLabel: /**
- CCLabelAtlas is MUCH faster than CCLabel * @addtogroup GUI
- CCLabelAtlas "characters" have a fixed height and width * @{
- CCLabelAtlas "characters" can be anything you want since they are * @addtogroup label
taken from an image file * @{
*/
A more flexible class is CCLabelBMFont. It supports variable width c
haracters and it also has a nice editor. /** @brief CCLabelAtlas is a subclass of CCAtlasNode.
*/
class CC_DLL CCLabelAtlas : public CCAtlasNode, public CCLabelProtoc It can be as a replacement of CCLabel since it is MUCH faster.
ol
{ CCLabelAtlas versus CCLabel:
public: - CCLabelAtlas is MUCH faster than CCLabel
CCLabelAtlas() - CCLabelAtlas "characters" have a fixed height and width
:m_sString("") - CCLabelAtlas "characters" can be anything you want since they are taken f
{} rom an image file
virtual ~CCLabelAtlas()
{ A more flexible class is CCLabelBMFont. It supports variable width characte
m_sString.clear(); rs and it also has a nice editor.
} */
/** creates the CCLabelAtlas with a string, a char map file( class CC_DLL CCLabelAtlas : public CCAtlasNode, public CCLabelProtocol
the atlas), the width and height of each element and the starting char of t {
he atlas */ public:
static CCLabelAtlas * labelWithString(const char *label, con CCLabelAtlas()
st char *charMapFile, unsigned int itemWidth, unsigned int itemHeight, unsi :m_sString("")
gned char startCharMap); {}
virtual ~CCLabelAtlas()
/** initializes the CCLabelAtlas with a string, a char map f {
ile(the atlas), the width and height of each element and the starting char m_sString.clear();
of the atlas */ }
bool initWithString(const char *label, const char *charMapFi /** creates the CCLabelAtlas with a string, a char map file(the atlas),
le, unsigned int itemWidth, unsigned int itemHeight, unsigned char startCha the width and height of each element and the starting char of the atlas
rMap); @deprecated: This interface will be deprecated sooner or later.
// super methods */
virtual void updateAtlasValues(); CC_DEPRECATED_ATTRIBUTE static CCLabelAtlas * labelWithString(const cha
virtual void setString(const char *label); r *string, const char *charMapFile, unsigned int itemWidth, unsigned int it
virtual const char* getString(void); emHeight, unsigned int startCharMap);
/** creates the CCLabelAtlas with a string and a configuration file
@deprecated: This interface will be deprecated sooner or later.
@since v2.0
*/
CC_DEPRECATED_ATTRIBUTE static CCLabelAtlas* labelWithString(const char
*string, const char *fntFile);
/** creates the CCLabelAtlas with a string, a char map file(the atlas),
the width and height of each element and the starting char of the atlas */
static CCLabelAtlas * create(const char *string, const char *charMapFil
e, unsigned int itemWidth, unsigned int itemHeight, unsigned int startCharM
ap);
/** creates the CCLabelAtlas with a string and a configuration file
@since v2.0
*/
static CCLabelAtlas* create(const char *string, const char *fntFile);
/** initializes the CCLabelAtlas with a string, a char map file(the atl
as), the width and height of each element and the starting char of the atla
s */
bool initWithString(const char *string, const char *charMapFile, unsign
ed int itemWidth, unsigned int itemHeight, unsigned int startCharMap);
/** initializes the CCLabelAtlas with a string and a configuration file
@since v2.0
*/
bool initWithString(const char *string, const char *fntFile);
// super methods
virtual void updateAtlasValues();
virtual void setString(const char *label);
virtual const char* getString(void);
#if CC_LABELATLAS_DEBUG_DRAW #if CC_LABELATLAS_DEBUG_DRAW
virtual void draw(); virtual void draw();
#endif #endif
virtual CCLabelProtocol* convertToLabelProtocol() { return ( protected:
CCLabelProtocol*)this; } // string to render
protected: std::string m_sString;
// string to render // the first char in the charmap
std::string m_sString; unsigned int m_uMapStartChar;
// the first char in the charmap };
unsigned char m_cMapStartChar;
}; // end of GUI group
}// namespace cocos2d /// @}
/// @}
NS_CC_END
#endif //__CCLABEL_ATLAS_H__ #endif //__CCLABEL_ATLAS_H__
 End of changes. 6 change blocks. 
51 lines changed or deleted 85 lines changed or added


 CCLabelBMFont.h   CCLabelBMFont.h 
skipping to change at line 35 skipping to change at line 35
Use any of these editors to generate BMFonts: Use any of these editors to generate BMFonts:
http://glyphdesigner.71squared.com/ (Commercial, Mac OS X) http://glyphdesigner.71squared.com/ (Commercial, Mac OS X)
http://www.n4te.com/hiero/hiero.jnlp (Free, Java) http://www.n4te.com/hiero/hiero.jnlp (Free, Java)
http://slick.cokeandcode.com/demos/hiero.jnlp (Free, Java) http://slick.cokeandcode.com/demos/hiero.jnlp (Free, Java)
http://www.angelcode.com/products/bmfont/ (Free, Windows only) http://www.angelcode.com/products/bmfont/ (Free, Windows only)
*************************************************************************** */ *************************************************************************** */
#ifndef __CCBITMAP_FONT_ATLAS_H__ #ifndef __CCBITMAP_FONT_ATLAS_H__
#define __CCBITMAP_FONT_ATLAS_H__ #define __CCBITMAP_FONT_ATLAS_H__
#include "CCSpriteBatchNode.h"
#include <map>
namespace cocos2d{
struct _KerningHashElement;
/** #include "sprite_nodes/CCSpriteBatchNode.h"
@struct ccBMFontDef #include <map>
BMFont definition #include <sstream>
*/ #include <iostream>
typedef struct _BMFontDef { #include <vector>
//! ID of the character
unsigned int charID; NS_CC_BEGIN
//! origin and size of the font
CCRect rect; /**
//! The X amount the image should be offset when drawing the * @addtogroup GUI
image (in pixels) * @{
int xOffset; * @addtogroup label
//! The Y amount the image should be offset when drawing the * @{
image (in pixels) */
int yOffset;
//! The amount to move the current position after drawing th enum {
e character (in pixels) kCCLabelAutomaticWidth = -1,
int xAdvance; };
} ccBMFontDef;
struct _KerningHashElement;
/** @struct ccBMFontPadding struct _FontDefHashElement;
BMFont padding
@since v0.8.2 /**
*/ @struct ccBMFontDef
typedef struct _BMFontPadding { BMFont definition
/// padding left */
int left; typedef struct _BMFontDef {
/// padding top //! ID of the character
int top; unsigned int charID;
/// padding right //! origin and size of the font
int right; CCRect rect;
/// padding bottom //! The X amount the image should be offset when drawing the image (in
int bottom; pixels)
} ccBMFontPadding; short xOffset;
//! The Y amount the image should be offset when drawing the image (in
/** @brief CCBMFontConfiguration has parsed configuration of the the pixels)
.fnt file short yOffset;
@since v0.8 //! The amount to move the current position after drawing the character
*/ (in pixels)
class CC_DLL CCBMFontConfiguration : public CCObject short xAdvance;
{ } ccBMFontDef;
// XXX: Creating a public interface so that the bitmapFontAr
ray[] is accesible /** @struct ccBMFontPadding
public://@public BMFont padding
//! The characters building up the font @since v0.8.2
std::map<unsigned int, ccBMFontDef>* m_pBitmapFontArray; */
typedef struct _BMFontPadding {
//! FNTConfig: Common Height /// padding left
unsigned int m_uCommonHeight; int left;
//! Padding /// padding top
ccBMFontPadding m_tPadding; int top;
//! atlas name /// padding right
std::string m_sAtlasName; int right;
//! values for kerning /// padding bottom
struct _KerningHashElement *m_pKerningDictionary; int bottom;
public: } ccBMFontPadding;
CCBMFontConfiguration();
virtual ~CCBMFontConfiguration(); /** @brief CCBMFontConfiguration has parsed configuration of the the .fnt f
char * description(); ile
/** allocates a CCBMFontConfiguration with a FNT file */ @since v0.8
static CCBMFontConfiguration * configurationWithFNTFile(cons */
t char *FNTfile); class CC_DLL CCBMFontConfiguration : public CCObject
/** initializes a BitmapFontConfiguration with a FNT file */ {
bool initWithFNTfile(const char *FNTfile); // XXX: Creating a public interface so that the bitmapFontArray[] is ac
private: cesible
void parseConfigFile(const char *controlFile); public://@public
void parseCharacterDefinition(std::string line, ccBMFontDef // BMFont definitions
*characterDefinition); struct _FontDefHashElement* m_pFontDefDictionary;
void parseInfoArguments(std::string line);
void parseCommonArguments(std::string line); //! FNTConfig: Common Height Should be signed (issue #1343)
void parseImageFileName(std::string line, const char *fntFil int m_nCommonHeight;
e); //! Padding
void parseKerningCapacity(std::string line); ccBMFontPadding m_tPadding;
void parseKerningEntry(std::string line); //! atlas name
void purgeKerningDictionary(); std::string m_sAtlasName;
}; //! values for kerning
struct _KerningHashElement *m_pKerningDictionary;
/** @brief CCLabelBMFont is a subclass of CCSpriteSheet. public:
CCBMFontConfiguration();
Features: virtual ~CCBMFontConfiguration();
- Treats each character like a CCSprite. This means that each indivi const char * description();
dual character can be: /** allocates a CCBMFontConfiguration with a FNT file
- rotated @deprecated: This interface will be deprecated sooner or later.
- scaled */
- translated CC_DEPRECATED_ATTRIBUTE static CCBMFontConfiguration * configurationWit
- tinted hFNTFile(const char *FNTfile);
- chage the opacity
- It can be used as part of a menu item. /** allocates a CCBMFontConfiguration with a FNT file */
- anchorPoint can be used to align the "label" static CCBMFontConfiguration * create(const char *FNTfile);
- Supports AngelCode text format
/** initializes a BitmapFontConfiguration with a FNT file */
Limitations: bool initWithFNTfile(const char *FNTfile);
- All inner characters are using an anchorPoint of (0.5f, 0.5f) and
it is not recommend to change it inline const char* getAtlasName(){ return m_sAtlasName.c_str(); }
because it might affect the rendering inline void setAtlasName(const char* atlasName) { m_sAtlasName = atlasN
ame; }
CCLabelBMFont implements the protocol CCLabelProtocol, like CCLabel private:
and CCLabelAtlas. bool parseConfigFile(const char *controlFile);
CCLabelBMFont has the flexibility of CCLabel, the speed of CCLabelAt void parseCharacterDefinition(std::string line, ccBMFontDef *characterD
las and all the features of CCSprite. efinition);
If in doubt, use CCLabelBMFont instead of CCLabelAtlas / CCLabel. void parseInfoArguments(std::string line);
void parseCommonArguments(std::string line);
Supported editors: void parseImageFileName(std::string line, const char *fntFile);
http://glyphdesigner.71squared.com/ (Commercial, Mac OS X) void parseKerningEntry(std::string line);
http://www.n4te.com/hiero/hiero.jnlp (Free, Java) void purgeKerningDictionary();
http://slick.cokeandcode.com/demos/hiero.jnlp (Free, Java) void purgeFontDefDictionary();
http://www.angelcode.com/products/bmfont/ (Free, Windows only) };
@since v0.8 /** @brief CCLabelBMFont is a subclass of CCSpriteSheet.
*/
Features:
class CC_DLL CCLabelBMFont : public CCSpriteBatchNode, public CCLabe - Treats each character like a CCSprite. This means that each individual ch
lProtocol, public CCRGBAProtocol aracter can be:
{ - rotated
/** conforms to CCRGBAProtocol protocol */ - scaled
CC_PROPERTY(GLubyte, m_cOpacity, Opacity) - translated
/** conforms to CCRGBAProtocol protocol */ - tinted
CC_PROPERTY_PASS_BY_REF(ccColor3B, m_tColor, Color) - chage the opacity
/** conforms to CCRGBAProtocol protocol */ - It can be used as part of a menu item.
CC_PROPERTY(bool, m_bIsOpacityModifyRGB, IsOpacityModifyRGB) - anchorPoint can be used to align the "label"
protected: - Supports AngelCode text format
// string to render
std::string m_sString; Limitations:
CCBMFontConfiguration *m_pConfiguration; - All inner characters are using an anchorPoint of (0.5f, 0.5f) and it is n
public: ot recommend to change it
CCLabelBMFont() because it might affect the rendering
: m_cOpacity(0)
, m_bIsOpacityModifyRGB(false) CCLabelBMFont implements the protocol CCLabelProtocol, like CCLabel and CCL
, m_sString("") abelAtlas.
, m_pConfiguration(NULL) CCLabelBMFont has the flexibility of CCLabel, the speed of CCLabelAtlas and
{} all the features of CCSprite.
virtual ~CCLabelBMFont(); If in doubt, use CCLabelBMFont instead of CCLabelAtlas / CCLabel.
/** Purges the cached data.
Removes from memory the cached configurations and the atlas Supported editors:
name dictionary. http://glyphdesigner.71squared.com/ (Commercial, Mac OS X)
@since v0.99.3 http://www.n4te.com/hiero/hiero.jnlp (Free, Java)
*/ http://slick.cokeandcode.com/demos/hiero.jnlp (Free, Java)
static void purgeCachedData(); http://www.angelcode.com/products/bmfont/ (Free, Windows only)
/** creates a bitmap font altas with an initial string and t
he FNT file */ @since v0.8
static CCLabelBMFont * labelWithString(const char *str, cons */
t char *fntFile);
class CC_DLL CCLabelBMFont : public CCSpriteBatchNode, public CCLabelProtoc
/** init a bitmap font altas with an initial string and the ol, public CCRGBAProtocol
FNT file */ {
bool initWithString(const char *str, const char *fntFile); /** conforms to CCRGBAProtocol protocol */
/** updates the font chars based on the string to render */ CC_PROPERTY(GLubyte, m_cOpacity, Opacity)
void createFontChars(); /** conforms to CCRGBAProtocol protocol */
// super method CC_PROPERTY_PASS_BY_REF(ccColor3B, m_tColor, Color)
virtual void setString(const char *label); /** conforms to CCRGBAProtocol protocol */
virtual const char* getString(void); bool m_bIsOpacityModifyRGB;
virtual void setCString(const char *label); bool isOpacityModifyRGB();
virtual void setAnchorPoint(const CCPoint& var); void setOpacityModifyRGB(bool isOpacityModifyRGB);
protected:
// string to render
unsigned short* m_sString;
// name of fntFile
std::string m_sFntFile;
// initial string without line breaks
std::string m_sInitialString;
// alignment of all lines
CCTextAlignment m_pAlignment;
// max width until a line break is added
float m_fWidth;
CCBMFontConfiguration *m_pConfiguration;
bool m_bLineBreakWithoutSpaces;
// offset of the texture atlas
CCPoint m_tImageOffset;
public:
CCLabelBMFont();
virtual ~CCLabelBMFont();
/** Purges the cached data.
Removes from memory the cached configurations and the atlas name dictio
nary.
@since v0.99.3
*/
static void purgeCachedData();
/** creates a bitmap font altas with an initial string and the FNT file
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCLabelBMFont * labelWithString(const ch
ar *str, const char *fntFile, float width = kCCLabelAutomaticWidth, CCTextA
lignment alignment = kCCTextAlignmentLeft, CCPoint imageOffset = CCPointZer
o);
/** creates a bitmap font altas with an initial string and the FNT file
*/
static CCLabelBMFont * create(const char *str, const char *fntFile, flo
at width = kCCLabelAutomaticWidth, CCTextAlignment alignment = kCCTextAlign
mentLeft, CCPoint imageOffset = CCPointZero);
/** Creates an label.
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCLabelBMFont * node();
/** Creates an label.
*/
static CCLabelBMFont * create();
bool init();
/** init a bitmap font altas with an initial string and the FNT file */
bool initWithString(const char *str, const char *fntFile, float width =
kCCLabelAutomaticWidth, CCTextAlignment alignment = kCCTextAlignmentLeft,
CCPoint imageOffset = CCPointZero);
/** updates the font chars based on the string to render */
void createFontChars();
// super method
virtual void setString(const char *label);
virtual void setString(const char *label, bool fromUpdate);
virtual void updateString(bool fromUpdate);
virtual const char* getString(void);
virtual void setCString(const char *label);
virtual void setAnchorPoint(const CCPoint& var);
virtual void updateLabel();
virtual void setAlignment(CCTextAlignment alignment);
virtual void setWidth(float width);
virtual void setLineBreakWithoutSpace(bool breakWithoutSpace);
virtual void setScale(float scale);
virtual void setScaleX(float scaleX);
virtual void setScaleY(float scaleY);
void setFntFile(const char* fntFile);
const char* getFntFile();
#if CC_LABELBMFONT_DEBUG_DRAW #if CC_LABELBMFONT_DEBUG_DRAW
virtual void draw(); virtual void draw();
#endif // CC_LABELBMFONT_DEBUG_DRAW #endif // CC_LABELBMFONT_DEBUG_DRAW
private: private:
char * atlasNameFromFntFile(const char *fntFile); char * atlasNameFromFntFile(const char *fntFile);
int kerningAmountForFirst(unsigned short first, unsigned sho int kerningAmountForFirst(unsigned short first, unsigned short second);
rt second); float getLetterPosXLeft( CCSprite* characterSprite );
float getLetterPosXRight( CCSprite* characterSprite );
};
};
/** Free function that parses a FNT file a place it on the cache
*/ /** Free function that parses a FNT file a place it on the cache
CC_DLL CCBMFontConfiguration * FNTConfigLoadFile( const char *file ) */
; CC_DLL CCBMFontConfiguration * FNTConfigLoadFile( const char *file );
/** Purges the FNT config cache /** Purges the FNT config cache
*/ */
CC_DLL void FNTConfigRemoveCache( void ); CC_DLL void FNTConfigRemoveCache( void );
}// namespace cocos2d
// end of GUI group
/// @}
/// @}
NS_CC_END
#endif //__CCBITMAP_FONT_ATLAS_H__ #endif //__CCBITMAP_FONT_ATLAS_H__
 End of changes. 5 change blocks. 
175 lines changed or deleted 249 lines changed or added


 CCLabelTTF.h   CCLabelTTF.h 
skipping to change at line 25 skipping to change at line 25
all copies or substantial portions of the Software. all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CCLABEL_H__ #ifndef __CCLABELTTF_H__
#define __CCLABEL_H__ #define __CCLABELTTF_H__
#include "CCSprite.h"
#include "CCTexture2D.h" #include "sprite_nodes/CCSprite.h"
#include "textures/CCTexture2D.h"
namespace cocos2d{
NS_CC_BEGIN
/** @brief CCLabelTTF is a subclass of CCTextureNode that knows how
to render text labels /**
* * @addtogroup GUI
* All features from CCTextureNode are valid in CCLabelTTF * @{
* * @addtogroup label
* CCLabelTTF objects are slow. Consider using CCLabelAtlas or CCLabe * @{
lBMFont instead. */
*/
class CC_DLL CCLabelTTF : public CCSprite, public CCLabelProtocol /** @brief CCLabelTTF is a subclass of CCTextureNode that knows how to rend
{ er text labels
public: *
CCLabelTTF(); * All features from CCTextureNode are valid in CCLabelTTF
virtual ~CCLabelTTF(); *
char * description(); * CCLabelTTF objects are slow. Consider using CCLabelAtlas or CCLabelBMFont
/** creates a CCLabelTTF from a fontname, alignment, dimensi instead.
on and font size */ */
static CCLabelTTF * labelWithString(const char *label, const class CC_DLL CCLabelTTF : public CCSprite, public CCLabelProtocol
CCSize& dimensions, CCTextAlignment alignment, const char *fontName, float {
fontSize); public:
/** creates a CCLabelTTF from a fontname and font size */ CCLabelTTF();
static CCLabelTTF * labelWithString(const char *label, const virtual ~CCLabelTTF();
char *fontName, float fontSize); const char* description();
/** initializes the CCLabelTTF with a font name, alignment,
dimension and font size */ /** creates a CCLabelTTF with a font name and font size in points
bool initWithString(const char *label, const CCSize& dimensi @deprecated: This interface will be deprecated sooner or later.
ons, CCTextAlignment alignment, const char *fontName, float fontSize); */
/** initializes the CCLabelTTF with a font name and font siz CC_DEPRECATED_ATTRIBUTE static CCLabelTTF * labelWithString(const char
e */ *string, const char *fontName, float fontSize);
bool initWithString(const char *label, const char *fontName,
float fontSize); /** creates a CCLabelTTF from a fontname, horizontal alignment, dimensi
on in points, and font size in points.
/** changes the string to render @deprecated: This interface will be deprecated sooner or later.
* @warning Changing the string is as expensive as creating a @since v1.0
new CCLabelTTF. To obtain better performance use CCLabelAtlas */
*/ CC_DEPRECATED_ATTRIBUTE static CCLabelTTF * labelWithString(const char
virtual void setString(const char *label); *string, const CCSize& dimensions, CCTextAlignment hAlignment, const char *
virtual const char* getString(void); fontName, float fontSize);
virtual CCLabelProtocol* convertToLabelProtocol() { return ( /** creates a CCLabel from a fontname, alignment, dimension in points a
CCLabelProtocol*)this; } nd font size in points
protected: @deprecated: This interface will be deprecated sooner or later.
CCSize m_tDimensions; */
CCTextAlignment m_eAlignment; CC_DEPRECATED_ATTRIBUTE static CCLabelTTF * labelWithString(const char
std::string * m_pFontName; *string, const CCSize& dimensions, CCTextAlignment hAlignment, CCVerticalTe
float m_fFontSize; xtAlignment vAlignment, const char *fontName, float fontSize);
std::string * m_pString;
}; /** creates a CCLabelTTF with a font name and font size in points
@since v2.0.1
*/
static CCLabelTTF * create(const char *string, const char *fontName, fl
oat fontSize);
/** creates a CCLabelTTF from a fontname, horizontal alignment, dimensi
on in points, and font size in points.
@since v2.0.1
*/
static CCLabelTTF * create(const char *string, const char *fontName, fl
oat fontSize,
const CCSize& dimensions, CCTextAlignment hA
lignment);
/** creates a CCLabel from a fontname, alignment, dimension in points a
nd font size in points
@since v2.0.1
*/
static CCLabelTTF * create(const char *string, const char *fontName, fl
oat fontSize,
const CCSize& dimensions, CCTextAlignment hA
lignment,
CCVerticalTextAlignment vAlignment);
/** initializes the CCLabelTTF with a font name and font size */
bool initWithString(const char *string, const char *fontName, float fon
tSize);
/** initializes the CCLabelTTF with a font name, alignment, dimension a
nd font size */
bool initWithString(const char *string, const char *fontName, float fon
tSize,
const CCSize& dimensions, CCTextAlignment hAlignmen
t);
/** initializes the CCLabelTTF with a font name, alignment, dimension a
nd font size */
bool initWithString(const char *string, const char *fontName, float fon
tSize,
const CCSize& dimensions, CCTextAlignment hAlignmen
t,
CCVerticalTextAlignment vAlignment);
/** initializes the CCLabelTTF */
bool init();
/** Creates an label.
*/
static CCLabelTTF * node();
/** Creates an label.
*/
static CCLabelTTF * create();
/** changes the string to render
* @warning Changing the string is as expensive as creating a new CCLabe
lTTF. To obtain better performance use CCLabelAtlas
*/
virtual void setString(const char *label);
virtual const char* getString(void);
CCTextAlignment getHorizontalAlignment();
void setHorizontalAlignment(CCTextAlignment alignment);
CCVerticalTextAlignment getVerticalAlignment();
void setVerticalAlignment(CCVerticalTextAlignment verticalAlignment);
CCSize getDimensions();
void setDimensions(const CCSize &dim);
float getFontSize();
void setFontSize(float fontSize);
const char* getFontName();
void setFontName(const char *fontName);
private:
void updateTexture();
protected:
/** Dimensions of the label in Points */
CCSize m_tDimensions;
/** The alignment of the label */
CCTextAlignment m_hAlignment;
/** The vertical alignment of the label */
CCVerticalTextAlignment m_vAlignment;
/** Font name used in the label */
std::string * m_pFontName;
/** Font size of the label */
float m_fFontSize;
std::string m_string;
};
// end of GUI group
/// @}
/// @}
NS_CC_END
} //namespace cocos2d
#endif //__CCLABEL_H__ #endif //__CCLABEL_H__
 End of changes. 2 change blocks. 
55 lines changed or deleted 151 lines changed or added


 CCLayer.h   CCLayer.h 
/************************************************************************** ** /************************************************************************** **
Copyright (c) 2010-2011 cocos2d-x.org Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011 Zynga Inc. Copyright (c) 2011 Zynga Inc.
http://www.cocos2d-x.org http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a cop y Permission is hereby granted, free of charge, to any person obtaining a cop y
of this software and associated documentation files (the "Software"), to de al of this software and associated documentation files (the "Software"), to de al
in the Software without restriction, including without limitation the right s in the Software without restriction, including without limitation the right s
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
skipping to change at line 30 skipping to change at line 30
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CCLAYER_H__ #ifndef __CCLAYER_H__
#define __CCLAYER_H__ #define __CCLAYER_H__
#include "CCNode.h" #include "base_nodes/CCNode.h"
#include "CCProtocols.h" #include "CCProtocols.h"
#include "CCTouchDelegateProtocol.h" #include "touch_dispatcher/CCTouchDelegateProtocol.h"
#include "CCAccelerometerDelegate.h" #include "platform/CCAccelerometerDelegate.h"
#include "CCKeypadDelegate.h" #include "keypad_dispatcher/CCKeypadDelegate.h"
#include "CCMutableArray.h" #include "cocoa/CCArray.h"
namespace cocos2d { NS_CC_BEGIN
/**
* @addtogroup layer
* @{
*/
class CCTouchScriptHandlerEntry; class CCTouchScriptHandlerEntry;
// //
// CCLayer // CCLayer
// //
/** @brief CCLayer is a subclass of CCNode that implements the TouchEventsD elegate protocol. /** @brief CCLayer is a subclass of CCNode that implements the TouchEventsD elegate protocol.
All features from CCNode are valid, plus the following new features: All features from CCNode are valid, plus the following new features:
- It can receive iPhone Touches - It can receive iPhone Touches
- It can receive Accelerometer input - It can receive Accelerometer input
*/ */
class CC_DLL CCLayer : public CCNode, public CCTouchDelegate, public CCAcce lerometerDelegate, public CCKeypadDelegate class CC_DLL CCLayer : public CCNode, public CCTouchDelegate, public CCAcce lerometerDelegate, public CCKeypadDelegate
{ {
public: public:
CCLayer(); CCLayer();
virtual ~CCLayer(); virtual ~CCLayer();
bool init(); bool init();
static CCLayer *node(void);
// @deprecated: This interface will be deprecated sooner or later.
CC_DEPRECATED_ATTRIBUTE static CCLayer *node(void);
/** create one layer */
static CCLayer *create(void);
virtual void onEnter(); virtual void onEnter();
virtual void onExit(); virtual void onExit();
virtual void onEnterTransitionDidFinish(); virtual void onEnterTransitionDidFinish();
// default implements are used to call script callback if exist // default implements are used to call script callback if exist
virtual bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent); virtual bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent);
virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent); virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent);
virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent); virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent);
virtual void ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent); virtual void ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent);
// default implements are used to call script callback if exist // default implements are used to call script callback if exist
virtual void ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent); virtual void ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent);
virtual void ccTouchesMoved(CCSet *pTouches, CCEvent *pEvent); virtual void ccTouchesMoved(CCSet *pTouches, CCEvent *pEvent);
virtual void ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent); virtual void ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent);
virtual void ccTouchesCancelled(CCSet *pTouches, CCEvent *pEvent); virtual void ccTouchesCancelled(CCSet *pTouches, CCEvent *pEvent);
virtual void didAccelerate(CCAcceleration* pAccelerationValue) {CC_UNUS ED_PARAM(pAccelerationValue);} virtual void didAccelerate(CCAcceleration* pAccelerationValue) {CC_UNUS ED_PARAM(pAccelerationValue);}
/** If isTouchEnabled, this method is called onEnter. Override it to /** If isTouchEnabled, this method is called onEnter. Override it to ch
change the ange the
way CCLayer receives touch events. way CCLayer receives touch events.
( Default: CCTouchDispatcher::sharedDispatcher()->addStandardDelegat ( Default: CCTouchDispatcher::sharedDispatcher()->addStandardDelegate(t
e(this,0); ) his,0); )
Example: Example:
void CCLayer::registerWithTouchDispatcher() void CCLayer::registerWithTouchDispatcher()
{ {
CCTouchDispatcher::sharedDispatcher()->addTargetedDelegate(this,INT_ CCTouchDispatcher::sharedDispatcher()->addTargetedDelegate(this,INT_MIN
MIN+1,true); +1,true);
} }
@since v0.8.0 @since v0.8.0
*/ */
virtual void registerWithTouchDispatcher(void); virtual void registerWithTouchDispatcher(void);
/** Register script touch events handler */ /** Register script touch events handler */
void registerScriptTouchHandler(int nHandler, bool bIsMultiTouches = fa lse, int nPriority = INT_MIN, bool bSwallowsTouches = false); void registerScriptTouchHandler(int nHandler, bool bIsMultiTouches = fa lse, int nPriority = INT_MIN, bool bSwallowsTouches = false);
/** Unregister script touch events handler */ /** Unregister script touch events handler */
void unregisterScriptTouchHandler(void); void unregisterScriptTouchHandler(void);
/** whether or not it will receive Touch events. /** whether or not it will receive Touch events.
You can enable / disable touch events with this property. You can enable / disable touch events with this property.
Only the touches of this node will be affected. This "method" is not Only the touches of this node will be affected. This "method" is not pr
propagated to it's children. opagated to it's children.
@since v0.8.1 @since v0.8.1
*/ */
CC_PROPERTY(bool, m_bIsTouchEnabled, IsTouchEnabled) bool isTouchEnabled();
/** whether or not it will receive Accelerometer events void setTouchEnabled(bool value);
You can enable / disable accelerometer events with this property. /** whether or not it will receive Accelerometer events
@since v0.8.1 You can enable / disable accelerometer events with this property.
*/ @since v0.8.1
CC_PROPERTY(bool, m_bIsAccelerometerEnabled, IsAccelerometerEnabled) */
bool isAccelerometerEnabled();
void setAccelerometerEnabled(bool value);
/** whether or not it will receive keypad events /** whether or not it will receive keypad events
You can enable / disable accelerometer events with this property. You can enable / disable accelerometer events with this property.
it's new in cocos2d-x it's new in cocos2d-x
*/ */
CC_PROPERTY(bool, m_bIsKeypadEnabled, IsKeypadEnabled) bool isKeypadEnabled();
void setKeypadEnabled(bool value);
protected:
bool m_bIsTouchEnabled;
bool m_bIsAccelerometerEnabled;
bool m_bIsKeypadEnabled;
private: private:
// Script touch events handler // Script touch events handler
CCTouchScriptHandlerEntry* m_pScriptHandlerEntry; CCTouchScriptHandlerEntry* m_pScriptHandlerEntry;
int excuteScriptTouchHandler(int nEventType, CCTouch *pTouch); int excuteScriptTouchHandler(int nEventType, CCTouch *pTouch);
int excuteScriptTouchHandler(int nEventType, CCSet *pTouches); int excuteScriptTouchHandler(int nEventType, CCSet *pTouches);
}; };
// for the subclass of CCLayer, each has to implement the static "node" met
hod
#define LAYER_NODE_FUNC(layer) \
static layer* node() \
{ \
layer *pRet = new layer(); \
if (pRet && pRet->init()) \
{ \
pRet->autorelease(); \
return pRet; \
} \
else \
{ \
delete pRet; \
pRet = NULL; \
return NULL; \
} \
};
#define LAYER_NODE_FUNC_PARAM(layer,__PARAMTYPE__,__PARAM__) \
static layer* node(__PARAMTYPE__ __PARAM__) \
{ \
layer *pRet = new layer(); \
if (pRet && pRet->init(__PARAM__)) \
{ \
pRet->autorelease(); \
return pRet; \
} \
else \
{ \
delete pRet; \
pRet = NULL; \
return NULL; \
} \
};
// //
// CCLayerColor // CCLayerColor
// //
/** @brief CCLayerColor is a subclass of CCLayer that implements the CCRGBA Protocol protocol. /** @brief CCLayerColor is a subclass of CCLayer that implements the CCRGBA Protocol protocol.
All features from CCLayer are valid, plus the following new features: All features from CCLayer are valid, plus the following new features:
- opacity - opacity
- RGB colors - RGB colors
*/ */
class CC_DLL CCLayerColor : public CCLayer , public CCRGBAProtocol, public CCBlendProtocol class CC_DLL CCLayerColor : public CCLayer , public CCRGBAProtocol, public CCBlendProtocol
{ {
protected: protected:
ccVertex2F m_pSquareVertices[4]; ccVertex2F m_pSquareVertices[4];
ccColor4B m_pSquareColors[4]; ccColor4F m_pSquareColors[4];
public: public:
CCLayerColor(); CCLayerColor();
virtual ~CCLayerColor(); virtual ~CCLayerColor();
virtual void draw(); virtual void draw();
virtual void setContentSize(const CCSize& var); virtual void setContentSize(const CCSize & var);
/** creates a CCLayer with color, width and height in Points */ /** creates a CCLayer with color, width and height in Points
static CCLayerColor * layerWithColorWidthHeight(const ccColor4B& col @deprecated: This interface will be deprecated sooner or later.
or, GLfloat width, GLfloat height); */
/** creates a CCLayer with color. Width and height are the window si CC_DEPRECATED_ATTRIBUTE static CCLayerColor * layerWithColor(const ccCo
ze. */ lor4B& color, GLfloat width, GLfloat height);
static CCLayerColor * layerWithColor(const ccColor4B& color); /** creates a CCLayer with color. Width and height are the window size.
@deprecated: This interface will be deprecated sooner or later.
/** initializes a CCLayer with color, width and height in Points */ */
virtual bool initWithColorWidthHeight(const ccColor4B& color, GLfloa CC_DEPRECATED_ATTRIBUTE static CCLayerColor * layerWithColor(const ccCo
t width, GLfloat height); lor4B& color);
/** initializes a CCLayer with color. Width and height are the windo
w size. */ /** creates a CCLayer with color, width and height in Points */
virtual bool initWithColor(const ccColor4B& color); static CCLayerColor * create(const ccColor4B& color, GLfloat width, GLf
loat height);
/** change width in Points*/ /** creates a CCLayer with color. Width and height are the window size.
void changeWidth(GLfloat w); */
/** change height in Points*/ static CCLayerColor * create(const ccColor4B& color);
void changeHeight(GLfloat h);
/** change width and height in Points virtual bool init();
@since v0.8 /** initializes a CCLayer with color, width and height in Points */
*/ virtual bool initWithColor(const ccColor4B& color, GLfloat width, GLflo
void changeWidthAndHeight(GLfloat w ,GLfloat h); at height);
/** initializes a CCLayer with color. Width and height are the window s
/** Opacity: conforms to CCRGBAProtocol protocol */ ize. */
CC_PROPERTY(GLubyte, m_cOpacity, Opacity) virtual bool initWithColor(const ccColor4B& color);
/** Color: conforms to CCRGBAProtocol protocol */
CC_PROPERTY_PASS_BY_REF(ccColor3B, m_tColor, Color) /** change width in Points*/
/** BlendFunction. Conforms to CCBlendProtocol protocol */ void changeWidth(GLfloat w);
CC_PROPERTY(ccBlendFunc, m_tBlendFunc, BlendFunc) /** change height in Points*/
void changeHeight(GLfloat h);
virtual void setIsOpacityModifyRGB(bool bValue) {CC_UNUSED_PARAM(bVa /** change width and height in Points
lue);} @since v0.8
virtual bool getIsOpacityModifyRGB(void) { return false;} */
LAYER_NODE_FUNC(CCLayerColor); void changeWidthAndHeight(GLfloat w ,GLfloat h);
/** Opacity: conforms to CCRGBAProtocol protocol */
CC_PROPERTY(GLubyte, m_cOpacity, Opacity)
/** Color: conforms to CCRGBAProtocol protocol */
CC_PROPERTY_PASS_BY_REF(ccColor3B, m_tColor, Color)
/** BlendFunction. Conforms to CCBlendProtocol protocol */
CC_PROPERTY(ccBlendFunc, m_tBlendFunc, BlendFunc)
virtual void setOpacityModifyRGB(bool bValue) {CC_UNUSED_PARAM(bValue);
}
virtual bool isOpacityModifyRGB(void) { return false;}
//@deprecated: This interface will be deprecated sooner or later.
CREATE_FUNC(CCLayerColor)
NODE_FUNC(CCLayerColor)
protected: protected:
virtual void updateColor(); virtual void updateColor();
}; };
// //
// CCLayerGradient // CCLayerGradient
// //
/** CCLayerGradient is a subclass of CCLayerColor that draws gradients acro ss /** CCLayerGradient is a subclass of CCLayerColor that draws gradients acro ss
the background. the background.
All features from CCLayerColor are valid, plus the following new features: All features from CCLayerColor are valid, plus the following new features:
- direction - direction
skipping to change at line 235 skipping to change at line 228
non-cardinal vectors; a smooth gradient implying both end points will be st ill non-cardinal vectors; a smooth gradient implying both end points will be st ill
be drawn, however. be drawn, however.
If ' compressedInterpolation' is enabled (default mode) you will see both t he start and end colors of the gradient. If ' compressedInterpolation' is enabled (default mode) you will see both t he start and end colors of the gradient.
@since v0.99.5 @since v0.99.5
*/ */
class CC_DLL CCLayerGradient : public CCLayerColor class CC_DLL CCLayerGradient : public CCLayerColor
{ {
public: public:
/** Creates a full-screen CCLayer with a gradient between start and end
.
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCLayerGradient* layerWithColor(const cc
Color4B& start, const ccColor4B& end);
/** Creates a full-screen CCLayer with a gradient between start and end
in the direction of v.
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCLayerGradient* layerWithColor(const cc
Color4B& start, const ccColor4B& end, const CCPoint& v);
/** Creates a full-screen CCLayer with a gradient between start and end . */ /** Creates a full-screen CCLayer with a gradient between start and end . */
static CCLayerGradient* layerWithColor(const ccColor4B& start, const cc Color4B& end); static CCLayerGradient* create(const ccColor4B& start, const ccColor4B& end);
/** Creates a full-screen CCLayer with a gradient between start and end in the direction of v. */ /** Creates a full-screen CCLayer with a gradient between start and end in the direction of v. */
static CCLayerGradient* layerWithColor(const ccColor4B& start, const cc Color4B& end, const CCPoint& v); static CCLayerGradient* create(const ccColor4B& start, const ccColor4B& end, const CCPoint& v);
/** Initializes the CCLayer with a gradient between start and end. */ /** Initializes the CCLayer with a gradient between start and end. */
virtual bool initWithColor(const ccColor4B& start, const ccColor4B& end ); virtual bool initWithColor(const ccColor4B& start, const ccColor4B& end );
/** Initializes the CCLayer with a gradient between start and end in th e direction of v. */ /** Initializes the CCLayer with a gradient between start and end in th e direction of v. */
virtual bool initWithColor(const ccColor4B& start, const ccColor4B& end , const CCPoint& v); virtual bool initWithColor(const ccColor4B& start, const ccColor4B& end , const CCPoint& v);
CC_PROPERTY_PASS_BY_REF(ccColor3B, m_startColor, StartColor) CC_PROPERTY_PASS_BY_REF(ccColor3B, m_startColor, StartColor)
CC_PROPERTY_PASS_BY_REF(ccColor3B, m_endColor, EndColor) CC_PROPERTY_PASS_BY_REF(ccColor3B, m_endColor, EndColor)
CC_PROPERTY(GLubyte, m_cStartOpacity, StartOpacity) CC_PROPERTY(GLubyte, m_cStartOpacity, StartOpacity)
CC_PROPERTY(GLubyte, m_cEndOpacity, EndOpacity) CC_PROPERTY(GLubyte, m_cEndOpacity, EndOpacity)
CC_PROPERTY_PASS_BY_REF(CCPoint, m_AlongVector, Vector) CC_PROPERTY_PASS_BY_REF(CCPoint, m_AlongVector, Vector)
/** Whether or not the interpolation will be compressed in order to dis play all the colors of the gradient both in canonical and non canonical vec tors /** Whether or not the interpolation will be compressed in order to dis play all the colors of the gradient both in canonical and non canonical vec tors
Default: YES Default: YES
*/ */
CC_PROPERTY(bool, m_bCompressedInterpolation, IsCompressedInterpolation protected:
) bool m_bCompressedInterpolation;
public:
virtual void setCompressedInterpolation(bool bCompressedInterpolation);
virtual bool isCompressedInterpolation();
LAYER_NODE_FUNC(CCLayerGradient); // @deprecated: This interface will be deprecated sooner or later.
NODE_FUNC(CCLayerGradient)
CREATE_FUNC(CCLayerGradient)
protected: protected:
virtual void updateColor(); virtual void updateColor();
}; };
/** @brief CCMultipleLayer is a CCLayer with the ability to multiplex it's children. /** @brief CCMultipleLayer is a CCLayer with the ability to multiplex it's children.
Features: Features:
- It supports one or more children - It supports one or more children
- Only one children will be active a time - Only one children will be active a time
*/ */
class CC_DLL CCLayerMultiplex : public CCLayer class CC_DLL CCLayerMultiplex : public CCLayer
{ {
protected: protected:
unsigned int m_nEnabledLayer; unsigned int m_nEnabledLayer;
CCMutableArray<CCLayer *> * m_pLayers; CCArray* m_pLayers;
public: public:
CCLayerMultiplex(); CCLayerMultiplex();
virtual ~CCLayerMultiplex(); virtual ~CCLayerMultiplex();
/** creates a CCLayerMultiplex with one or more layers using a varia /** creates a CCLayerMultiplex with one or more layers using a variable
ble argument list. */ argument list.
static CCLayerMultiplex * layerWithLayers(CCLayer* layer, ... ); @deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCLayerMultiplex * layerWithLayers(CCLay
er* layer, ... );
/** /**
* lua script can not init with undetermined number of variables * lua script can not init with undetermined number of variables
* so add these functinons to be used with lua. * so add these functinons to be used with lua.
*/ @deprecated: This interface will be deprecated sooner or later.
static CCLayerMultiplex * layerWithLayer(CCLayer* layer); */
void addLayer(CCLayer* layer); CC_DEPRECATED_ATTRIBUTE static CCLayerMultiplex * layerWithLayer(CCLaye
bool initWithLayer(CCLayer* layer); r* layer);
/** initializes a MultiplexLayer with one or more layers using a var
iable argument list. */
bool initWithLayers(CCLayer* layer, va_list params);
/** switches to a certain layer indexed by n.
The current (old) layer will be removed from it's parent with 'clean
up:YES'.
*/
void switchTo(unsigned int n);
/** release the current layer and switches to another layer indexed
by n.
The current (old) layer will be removed from it's parent with 'clean
up:YES'.
*/
void switchToAndReleaseMe(unsigned int n);
LAYER_NODE_FUNC(CCLayerMultiplex); /** creates a CCLayerMultiplex with one or more layers using a variable
argument list. */
static CCLayerMultiplex * create(CCLayer* layer, ... );
/**
* lua script can not init with undetermined number of variables
* so add these functinons to be used with lua.
*/
static CCLayerMultiplex * createWithLayer(CCLayer* layer);
void addLayer(CCLayer* layer);
/** initializes a MultiplexLayer with one or more layers using a variab
le argument list. */
bool initWithLayers(CCLayer* layer, va_list params);
/** switches to a certain layer indexed by n.
The current (old) layer will be removed from it's parent with 'cleanup:
YES'.
*/
void switchTo(unsigned int n);
/** release the current layer and switches to another layer indexed by
n.
The current (old) layer will be removed from it's parent with 'cleanup:
YES'.
*/
void switchToAndReleaseMe(unsigned int n);
//@deprecated: This interface will be deprecated sooner or later.
NODE_FUNC(CCLayerMultiplex)
CREATE_FUNC(CCLayerMultiplex)
}; };
}//namespace cocos2d // end of layer group
/// @}
NS_CC_END
#endif // __CCLAYER_H__ #endif // __CCLAYER_H__
 End of changes. 30 change blocks. 
162 lines changed or deleted 196 lines changed or added


 CCLock.h   CCLock.h 
skipping to change at line 28 skipping to change at line 28
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __PLATFORM_IPHONE_PLATFORM_CCLOCK_H__ #ifndef __PLATFORM_IPHONE_PLATFORM_CCLOCK_H__
#define __PLATFORM_IPHONE_PLATFORM_CCLOCK_H__ #define __PLATFORM_IPHONE_PLATFORM_CCLOCK_H__
namespace cocos2d { #include "CCPlatformMacros.h"
NS_CC_BEGIN
class CCLock class CCLock
{ {
public: public:
CCLock(void); CCLock(void);
~CCLock(void); ~CCLock(void);
void lock(void); void lock(void);
void unlock(void); void unlock(void);
}; };
}//namespace cocos2d
NS_CC_END
#endif // __PLATFORM_IPHONE_PLATFORM_CCLOCK_H__ #endif // __PLATFORM_IPHONE_PLATFORM_CCLOCK_H__
 End of changes. 4 change blocks. 
6 lines changed or deleted 9 lines changed or added


 CCLuaEngine.h   CCLuaEngine.h 
skipping to change at line 33 skipping to change at line 33
************************************************************************** **/ ************************************************************************** **/
#ifndef __CC_LUA_ENGINE_H__ #ifndef __CC_LUA_ENGINE_H__
#define __CC_LUA_ENGINE_H__ #define __CC_LUA_ENGINE_H__
extern "C" { extern "C" {
#include "lua.h" #include "lua.h"
} }
#include "ccTypes.h" #include "ccTypes.h"
#include "CCObject.h" #include "cocoa/CCObject.h"
#include "CCTouch.h" #include "touch_dispatcher/CCTouch.h"
#include "CCSet.h" #include "cocoa/CCSet.h"
#include "CCNode.h" #include "base_nodes/CCNode.h"
#include "CCScriptSupport.h" #include "script_support/CCScriptSupport.h"
NS_CC_BEGIN NS_CC_BEGIN
// Lua support for cocos2d-x // Lua support for cocos2d-x
class CCLuaEngine : public CCScriptEngineProtocol class CCLuaEngine : public CCScriptEngineProtocol
{ {
public: public:
~CCLuaEngine(); ~CCLuaEngine();
/** /**
skipping to change at line 100 skipping to change at line 100
@return The integer value returned from the script function. @return The integer value returned from the script function.
*/ */
virtual int executeGlobalFunction(const char* functionName); virtual int executeGlobalFunction(const char* functionName);
/** /**
@brief Execute a function by ref id @brief Execute a function by ref id
@param The function ref id @param The function ref id
@param Number of parameters @param Number of parameters
@return The integer value returned from the script function. @return The integer value returned from the script function.
*/ */
virtual int executeFunctionByRefID(int nHandler, int numArgs = 0); virtual int executeFunctionByHandler(int nHandler, int numArgs = 0);
virtual int executeFunctionWithIntegerData(int nHandler, int data); virtual int executeFunctionWithIntegerData(int nHandler, int data);
virtual int executeFunctionWithFloatData(int nHandler, float data); virtual int executeFunctionWithFloatData(int nHandler, float data);
virtual int executeFunctionWithBooleanData(int nHandler, bool data); virtual int executeFunctionWithBooleanData(int nHandler, bool data);
virtual int executeFunctionWithCCObject(int nHandler, CCObject* pObject
, const char* typeName);
virtual int pushIntegerToLuaStack(int data);
virtual int pushFloatToLuaStack(int data);
virtual int pushBooleanToLuaStack(int data);
virtual int pushCCObjectToLuaStack(CCObject* pObject, const char* typeN
ame);
// functions for excute touch event // functions for excute touch event
virtual int executeTouchEvent(int nHandler, int eventType, cocos2d::CCT ouch *pTouch); virtual int executeTouchEvent(int nHandler, int eventType, cocos2d::CCT ouch *pTouch);
virtual int executeTouchesEvent(int nHandler, int eventType, cocos2d::C CSet *pTouches); virtual int executeTouchesEvent(int nHandler, int eventType, cocos2d::C CSet *pTouches);
// execute a schedule function // execute a schedule function
virtual int executeSchedule(int nHandler, cocos2d::ccTime dt); virtual int executeSchedule(int nHandler, float dt);
// Add lua loader, now it is used on android // Add lua loader, now it is used on android
virtual void addLuaLoader(lua_CFunction func); virtual void addLuaLoader(lua_CFunction func);
static CCLuaEngine* engine(); static CCLuaEngine* engine();
private: private:
CCLuaEngine(void) CCLuaEngine(void)
: m_state(NULL) : m_state(NULL)
{ {
} }
bool init(void); bool init(void);
bool pushFunctionByHandler(int nHandler);
lua_State* m_state; lua_State* m_state;
}; };
NS_CC_END NS_CC_END
#endif // __CC_LUA_ENGINE_H__ #endif // __CC_LUA_ENGINE_H__
 End of changes. 5 change blocks. 
7 lines changed or deleted 15 lines changed or added


 CCMenu.h   CCMenu.h 
/************************************************************************** ** /************************************************************************** **
Copyright (c) 2010-2011 cocos2d-x.org Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2008-2010 Ricardo Quesada
http://www.cocos2d-x.org http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a cop y Permission is hereby granted, free of charge, to any person obtaining a cop y
of this software and associated documentation files (the "Software"), to de al of this software and associated documentation files (the "Software"), to de al
in the Software without restriction, including without limitation the right s in the Software without restriction, including without limitation the right s
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
skipping to change at line 29 skipping to change at line 29
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CCMENU_H_ #ifndef __CCMENU_H_
#define __CCMENU_H_ #define __CCMENU_H_
#include "CCMenuItem.h" #include "CCMenuItem.h"
#include "CCLayer.h" #include "layers_scenes_transitions_nodes/CCLayer.h"
namespace cocos2d{ NS_CC_BEGIN
typedef enum /**
{ * @addtogroup GUI
kCCMenuStateWaiting, * @{
kCCMenuStateTrackingTouch * @addtogroup menu
} tCCMenuState; * @{
*/
enum { typedef enum
//* priority used by the menu {
kCCMenuTouchPriority = -128, kCCMenuStateWaiting,
}; kCCMenuStateTrackingTouch
} tCCMenuState;
/** @brief A CCMenu
* enum {
* Features and Limitation: //* priority used by the menu for the event handler
* - You can add MenuItem objects in runtime using addChild: kCCMenuHandlerPriority = -128,
* - But the only accecpted children are MenuItem objects };
*/
class CC_DLL CCMenu : public CCLayer, public CCRGBAProtocol /** @brief A CCMenu
{ *
/** Color: conforms with CCRGBAProtocol protocol */ * Features and Limitation:
CC_PROPERTY_PASS_BY_REF(ccColor3B, m_tColor, Color); * - You can add MenuItem objects in runtime using addChild:
/** Opacity: conforms with CCRGBAProtocol protocol */ * - But the only accecpted children are MenuItem objects
CC_PROPERTY(GLubyte, m_cOpacity, Opacity); */
public: class CC_DLL CCMenu : public CCLayer, public CCRGBAProtocol
CCMenu() {
: m_cOpacity(0) /** Color: conforms with CCRGBAProtocol protocol */
, m_pSelectedItem(NULL) CC_PROPERTY_PASS_BY_REF(ccColor3B, m_tColor, Color);
{} /** Opacity: conforms with CCRGBAProtocol protocol */
virtual ~CCMenu(){} CC_PROPERTY(GLubyte, m_cOpacity, Opacity);
/** whether or not the menu will receive events */
/** creates an empty CCMenu */ bool m_bEnabled;
static CCMenu* node();
public:
/** creates a CCMenu with it's items */ CCMenu()
static CCMenu* menuWithItems(CCMenuItem* item, ...); : m_cOpacity(0)
, m_pSelectedItem(NULL)
/** creates a CCMenu with it's item, then use addChild() to {}
add virtual ~CCMenu(){}
* other items. It is used for script, it can't init with u
ndetermined /** creates an empty CCMenu
* number of variables. @deprecated: This interface will be deprecated sooner or later.
*/ */
static CCMenu* menuWithItem(CCMenuItem* item); CC_DEPRECATED_ATTRIBUTE static CCMenu* node();
/** initializes an empty CCMenu */ /** creates a CCMenu with it's items
bool init(); @deprecated: This interface will be deprecated sooner or later.
*/
/** initializes a CCMenu with it's items */ CC_DEPRECATED_ATTRIBUTE static CCMenu* menuWithItems(CCMenuItem* item,
bool initWithItems(CCMenuItem* item, va_list args); ...);
/** align items vertically */ /** creates a CCMenu with a NSArray of CCMenuItem objects
void alignItemsVertically(); @deprecated: This interface will be deprecated sooner or later.
/** align items vertically with padding */
@since v0.7.2 CC_DEPRECATED_ATTRIBUTE static CCMenu* menuWithArray(CCArray* pArrayOfI
*/ tems);
void alignItemsVerticallyWithPadding(float padding);
/** creates a CCMenu with it's item, then use addChild() to add
/** align items horizontally */ * other items. It is used for script, it can't init with undetermined
void alignItemsHorizontally(); * number of variables.
/** align items horizontally with padding @deprecated: This interface will be deprecated sooner or later.
@since v0.7.2 */
*/ CC_DEPRECATED_ATTRIBUTE static CCMenu* menuWithItem(CCMenuItem* item);
void alignItemsHorizontallyWithPadding(float padding);
/** creates an empty CCMenu */
/** align items in rows of columns */ static CCMenu* create();
void alignItemsInColumns(unsigned int columns, ...);
void alignItemsInColumns(unsigned int columns, va_list args) /** creates a CCMenu with it's items */
; static CCMenu* create(CCMenuItem* item, ...);
/** align items in columns of rows */ /** creates a CCMenu with a CCArray of CCMenuItem objects */
void alignItemsInRows(unsigned int rows, ...); static CCMenu* createWithArray(CCArray* pArrayOfItems);
void alignItemsInRows(unsigned int rows, va_list args);
/** creates a CCMenu with it's item, then use addChild() to add
//super methods * other items. It is used for script, it can't init with undetermined
virtual void addChild(CCNode * child, int zOrder); * number of variables.
virtual void addChild(CCNode * child, int zOrder, int tag); */
virtual void registerWithTouchDispatcher(); static CCMenu* createWithItem(CCMenuItem* item);
/** /** initializes an empty CCMenu */
@brief For phone event handle functions bool init();
*/
virtual bool ccTouchBegan(CCTouch* touch, CCEvent* event); /** initializes a CCMenu with it's items */
virtual void ccTouchEnded(CCTouch* touch, CCEvent* event); bool initWithItems(CCMenuItem* item, va_list args);
virtual void ccTouchCancelled(CCTouch *touch, CCEvent* event
); /** initializes a CCMenu with a NSArray of CCMenuItem objects */
virtual void ccTouchMoved(CCTouch* touch, CCEvent* event); bool initWithArray(CCArray* pArrayOfItems);
/** /** align items vertically */
@since v0.99.5 void alignItemsVertically();
override onExit /** align items vertically with padding
*/ @since v0.7.2
virtual void onExit(); */
void alignItemsVerticallyWithPadding(float padding);
virtual void setIsOpacityModifyRGB(bool bValue) {CC_UNUSED_P
ARAM(bValue);} /** align items horizontally */
virtual bool getIsOpacityModifyRGB(void) { return false;} void alignItemsHorizontally();
/** align items horizontally with padding
protected: @since v0.7.2
CCMenuItem* itemForTouch(CCTouch * touch); */
tCCMenuState m_eState; void alignItemsHorizontallyWithPadding(float padding);
CCMenuItem *m_pSelectedItem;
}; /** align items in rows of columns */
} void alignItemsInColumns(unsigned int columns, ...);
void alignItemsInColumns(unsigned int columns, va_list args);
/** align items in columns of rows */
void alignItemsInRows(unsigned int rows, ...);
void alignItemsInRows(unsigned int rows, va_list args);
/** set event handler priority. By default it is: kCCMenuTouchPriority
*/
void setHandlerPriority(int newPriority);
//super methods
virtual void addChild(CCNode * child);
virtual void addChild(CCNode * child, int zOrder);
virtual void addChild(CCNode * child, int zOrder, int tag);
virtual void registerWithTouchDispatcher();
/**
@brief For phone event handle functions
*/
virtual bool ccTouchBegan(CCTouch* touch, CCEvent* event);
virtual void ccTouchEnded(CCTouch* touch, CCEvent* event);
virtual void ccTouchCancelled(CCTouch *touch, CCEvent* event);
virtual void ccTouchMoved(CCTouch* touch, CCEvent* event);
/**
@since v0.99.5
override onExit
*/
virtual void onExit();
virtual void setOpacityModifyRGB(bool bValue) {CC_UNUSED_PARAM(bValue);
}
virtual bool isOpacityModifyRGB(void) { return false;}
virtual bool isEnabled() { return m_bEnabled; }
virtual void setEnabled(bool value) { m_bEnabled = value; };
protected:
CCMenuItem* itemForTouch(CCTouch * touch);
tCCMenuState m_eState;
CCMenuItem *m_pSelectedItem;
};
// end of GUI group
/// @}
/// @}
NS_CC_END
#endif//__CCMENU_H_ #endif//__CCMENU_H_
 End of changes. 4 change blocks. 
106 lines changed or deleted 154 lines changed or added


 CCMenuItem.h   CCMenuItem.h 
/************************************************************************** ** /************************************************************************** **
Copyright (c) 2010-2011 cocos2d-x.org Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2008-2011 Ricardo Quesada Copyright (c) 2008-2011 Ricardo Quesada
Copyright (c) 2011 Zynga Inc. Copyright (c) 2011 Zynga Inc.
http://www.cocos2d-x.org http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a cop y Permission is hereby granted, free of charge, to any person obtaining a cop y
of this software and associated documentation files (the "Software"), to de al of this software and associated documentation files (the "Software"), to de al
in the Software without restriction, including without limitation the right s in the Software without restriction, including without limitation the right s
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
skipping to change at line 30 skipping to change at line 30
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CCMENU_ITEM_H__ #ifndef __CCMENU_ITEM_H__
#define __CCMENU_ITEM_H__ #define __CCMENU_ITEM_H__
#include "CCNode.h" #include "base_nodes/CCNode.h"
#include "CCProtocols.h" #include "CCProtocols.h"
#include "CCMutableArray.h" #include "cocoa/CCArray.h"
namespace cocos2d{ NS_CC_BEGIN
class CCLabelTTF;
class CCLabelAtlas;
class CCSprite;
class CCLabelTTF;
class CCLabelAtlas;
class CCSprite;
class CCSpriteFrame;
#define kCCItemSize 32 #define kCCItemSize 32
/** @brief CCMenuItem base class /**
* * @addtogroup GUI
* Subclass CCMenuItem (or any subclass) to create your custom CCMenuI * @{
tem objects. * @addtogroup menu
*/ * @{
class CC_DLL CCMenuItem : public CCNode */
{
/** whether or not the item is selected /** @brief CCMenuItem base class
@since v0.8.2 *
*/ * Subclass CCMenuItem (or any subclass) to create your custom CCMenuItem
CC_PROPERTY_READONLY(bool, m_bIsSelected, IsSelected); objects.
CC_PROPERTY(bool, m_bIsEnabled, IsEnabled); */
public: class CC_DLL CCMenuItem : public CCNode
CCMenuItem() {
: m_bIsSelected(false) protected:
, m_bIsEnabled(false) /** whether or not the item is selected
, m_pListener(NULL) @since v0.8.2
, m_pfnSelector(NULL)
, m_nScriptHandler(0)
{}
virtual ~CCMenuItem();
/** Creates a CCMenuItem with a target/selector */
static CCMenuItem * itemWithTarget(CCObject *rec, SEL_MenuHandler s
elector);
/** Initializes a CCMenuItem with a target/selector */
bool initWithTarget(CCObject *rec, SEL_MenuHandler selector);
/** Returns the outside box */
CCRect rect();
/** Activate the item */
virtual void activate();
/** The item was selected (not activated), similar to "mouse-over"
*/
virtual void selected();
/** The item was unselected */
virtual void unselected();
/** Register menu handler script function */
virtual void registerScriptHandler(int nHandler);
virtual void unregisterScriptHandler(void);
/** set the target/selector of the menu item*/
void setTarget(CCObject *rec, SEL_MenuHandler selector);
protected:
CCObject* m_pListener;
SEL_MenuHandler m_pfnSelector;
int m_nScriptHandler;
};
/** @brief An abstract class for "label" CCMenuItemLabel items
Any CCNode that supports the CCLabelProtocol protocol can be added.
Supported nodes:
- CCBitmapFontAtlas
- CCLabelAtlas
- CCLabelTTF
*/ */
class CC_DLL CCMenuItemLabel : public CCMenuItem, public CCRGBAProtocol bool m_bIsSelected;
{ bool m_bIsEnabled;
/** the color that will be used to disable the item */
CC_PROPERTY_PASS_BY_REF(ccColor3B, m_tDisabledColor, DisabledColor)
;
/** Label that is rendered. It can be any CCNode that implements th
e CCLabelProtocol */
CC_PROPERTY(CCNode*, m_pLabel, Label);
public:
CCMenuItemLabel()
: m_pLabel(NULL)
, m_fOriginalScale(0.0)
{}
virtual ~CCMenuItemLabel();
/** creates a CCMenuItemLabel with a Label, target and selector */
static CCMenuItemLabel * itemWithLabel(CCNode*label, CCObject* targ
et, SEL_MenuHandler selector);
/** creates a CCMenuItemLabel with a Label. Target and selector wil
l be nill */
static CCMenuItemLabel* itemWithLabel(CCNode *label);
/** initializes a CCMenuItemLabel with a Label, target and selector
*/
bool initWithLabel(CCNode* label, CCObject* target, SEL_MenuHandler
selector);
/** sets a new string to the inner label */
void setString(const char * label);
// super methods
virtual void activate();
virtual void selected();
virtual void unselected();
/** Enable or disabled the CCMenuItemFont
@warning setIsEnabled changes the RGB color of the font
*/
virtual void setIsEnabled(bool enabled);
virtual void setOpacity(GLubyte opacity);
virtual GLubyte getOpacity();
virtual void setColor(const ccColor3B& color);
virtual const ccColor3B& getColor();
virtual void setIsOpacityModifyRGB(bool bValue) {CC_UNUSED_PARAM(bV
alue);}
virtual bool getIsOpacityModifyRGB(void) { return false;}
protected:
ccColor3B m_tColorBackup;
float m_fOriginalScale;
};
/** @brief A CCMenuItemAtlasFont public:
Helper class that creates a MenuItemLabel class with a LabelAtlas CCMenuItem()
: m_bIsSelected(false)
, m_bIsEnabled(false)
, m_pListener(NULL)
, m_pfnSelector(NULL)
, m_nScriptHandler(0)
{}
virtual ~CCMenuItem();
/** Creates a CCMenuItem with a target/selector
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCMenuItem * itemWithTarget(CCObject *re
c, SEL_MenuHandler selector);
/** Creates a CCMenuItem with a target/selector */
static CCMenuItem * create(CCObject *rec, SEL_MenuHandler selector);
/** Initializes a CCMenuItem with a target/selector */
bool initWithTarget(CCObject *rec, SEL_MenuHandler selector);
/** Returns the outside box */
CCRect rect();
/** Activate the item */
virtual void activate();
/** The item was selected (not activated), similar to "mouse-over" */
virtual void selected();
/** The item was unselected */
virtual void unselected();
/** Register menu handler script function */
virtual void registerScriptHandler(int nHandler);
virtual void unregisterScriptHandler(void);
virtual bool isEnabled();
//@note: It's 'setIsEnable' in cocos2d-iphone.
virtual void setEnabled(bool value);
virtual bool isSelected();
/** set the target/selector of the menu item*/
void setTarget(CCObject *rec, SEL_MenuHandler selector);
protected:
CCObject* m_pListener;
SEL_MenuHandler m_pfnSelector;
int m_nScriptHandler;
};
/** @brief An abstract class for "label" CCMenuItemLabel items
Any CCNode that supports the CCLabelProtocol protocol can be added.
Supported nodes:
- CCBitmapFontAtlas
- CCLabelAtlas
- CCLabelTTF
*/
class CC_DLL CCMenuItemLabel : public CCMenuItem, public CCRGBAProtocol
{
/** the color that will be used to disable the item */
CC_PROPERTY_PASS_BY_REF(ccColor3B, m_tDisabledColor, DisabledColor);
/** Label that is rendered. It can be any CCNode that implements the CC
LabelProtocol */
CC_PROPERTY(CCNode*, m_pLabel, Label);
public:
CCMenuItemLabel()
: m_pLabel(NULL)
, m_fOriginalScale(0.0)
{}
virtual ~CCMenuItemLabel();
/** creates a CCMenuItemLabel with a Label, target and selector
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCMenuItemLabel * itemWithLabel(CCNode*l
abel, CCObject* target, SEL_MenuHandler selector);
/** creates a CCMenuItemLabel with a Label. Target and selector will be
nill
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCMenuItemLabel* itemWithLabel(CCNode *l
abel);
/** creates a CCMenuItemLabel with a Label, target and selector */
static CCMenuItemLabel * create(CCNode*label, CCObject* target, SEL_Men
uHandler selector);
/** creates a CCMenuItemLabel with a Label. Target and selector will be
nill */
static CCMenuItemLabel* create(CCNode *label);
/** initializes a CCMenuItemLabel with a Label, target and selector */
bool initWithLabel(CCNode* label, CCObject* target, SEL_MenuHandler sel
ector);
/** sets a new string to the inner label */
void setString(const char * label);
// super methods
virtual void activate();
virtual void selected();
virtual void unselected();
/** Enable or disabled the CCMenuItemFont
@warning setEnabled changes the RGB color of the font
*/
virtual void setEnabled(bool enabled);
virtual void setOpacity(GLubyte opacity);
virtual GLubyte getOpacity();
virtual void setColor(const ccColor3B& color);
virtual const ccColor3B& getColor();
virtual void setOpacityModifyRGB(bool bValue) {CC_UNUSED_PARAM(bValue);
}
virtual bool isOpacityModifyRGB(void) { return false;}
protected:
ccColor3B m_tColorBackup;
float m_fOriginalScale;
};
/** @brief A CCMenuItemAtlasFont
Helper class that creates a MenuItemLabel class with a LabelAtlas
*/
class CC_DLL CCMenuItemAtlasFont : public CCMenuItemLabel
{
public:
CCMenuItemAtlasFont(){}
virtual ~CCMenuItemAtlasFont(){}
/** creates a menu item from a string and atlas with a target/selector
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCMenuItemAtlasFont* itemWithString(cons
t char *value, const char *charMapFile, int itemWidth, int itemHeight, char
startCharMap);
/** creates a menu item from a string and atlas. Use it with MenuItemTo
ggle
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCMenuItemAtlasFont* itemWithString(cons
t char *value, const char *charMapFile, int itemWidth, int itemHeight, char
startCharMap, CCObject* target, SEL_MenuHandler selector);
/** creates a menu item from a string and atlas with a target/selector
*/
static CCMenuItemAtlasFont* create(const char *value, const char *charM
apFile, int itemWidth, int itemHeight, char startCharMap);
/** creates a menu item from a string and atlas. Use it with MenuItemTo
ggle */
static CCMenuItemAtlasFont* create(const char *value, const char *charM
apFile, int itemWidth, int itemHeight, char startCharMap, CCObject* target,
SEL_MenuHandler selector);
/** initializes a menu item from a string and atlas with a target/selec
tor */
bool initWithString(const char *value, const char *charMapFile, int ite
mWidth, int itemHeight, char startCharMap, CCObject* target, SEL_MenuHandle
r selector);
};
/** @brief A CCMenuItemFont
Helper class that creates a CCMenuItemLabel class with a Label
*/
class CC_DLL CCMenuItemFont : public CCMenuItemLabel
{
public:
CCMenuItemFont() : m_uFontSize(0), m_strFontName(""){}
virtual ~CCMenuItemFont(){}
/** set default font size */
static void setFontSize(unsigned int s);
/** get default font size */
static unsigned int fontSize();
/** set the default font name */
static void setFontName(const char *name);
/** get the default font name */
static const char *fontName();
/** creates a menu item from a string without target/selector. To be us
ed with CCMenuItemToggle
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCMenuItemFont * itemWithString(const ch
ar *value);
/** creates a menu item from a string with a target/selector
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCMenuItemFont * itemWithString(const ch
ar *value, CCObject* target, SEL_MenuHandler selector);
/** creates a menu item from a string without target/selector. To be us
ed with CCMenuItemToggle */
static CCMenuItemFont * create(const char *value);
/** creates a menu item from a string with a target/selector */
static CCMenuItemFont * create(const char *value, CCObject* target, SEL
_MenuHandler selector);
/** initializes a menu item from a string with a target/selector */
bool initWithString(const char *value, CCObject* target, SEL_MenuHandle
r selector);
/** set font size
* c++ can not overload static and non-static member functions with the
same parameter types
* so change the name to setFontSizeObj
*/ */
class CC_DLL CCMenuItemAtlasFont : public CCMenuItemLabel void setFontSizeObj(unsigned int s);
{
public:
CCMenuItemAtlasFont(){}
virtual ~CCMenuItemAtlasFont(){}
/** creates a menu item from a string and atlas with a target/selec
tor */
static CCMenuItemAtlasFont* itemFromString(const char *value, const
char *charMapFile, int itemWidth, int itemHeight, char startCharMap);
/** creates a menu item from a string and atlas. Use it with MenuIt
emToggle */
static CCMenuItemAtlasFont* itemFromString(const char *value, const
char *charMapFile, int itemWidth, int itemHeight, char startCharMap, CCObj
ect* target, SEL_MenuHandler selector);
/** initializes a menu item from a string and atlas with a target/s
elector */
bool initFromString(const char *value, const char *charMapFile, int
itemWidth, int itemHeight, char startCharMap, CCObject* target, SEL_MenuHa
ndler selector);
};
/** @brief A CCMenuItemFont /** get font size */
Helper class that creates a CCMenuItemLabel class with a Label unsigned int fontSizeObj();
/** set the font name
* c++ can not overload static and non-static member functions with the
same parameter types
* so change the name to setFontNameObj
*/ */
class CC_DLL CCMenuItemFont : public CCMenuItemLabel void setFontNameObj(const char* name);
{
public: const char* fontNameObj();
CCMenuItemFont() : m_uFontSize(0), m_strFontName(""){}
virtual ~CCMenuItemFont(){}
/** set default font size */
static void setFontSize(unsigned int s);
/** get default font size */
static unsigned int fontSize();
/** set the default font name */
static void setFontName(const char *name);
/** get the default font name */
static const char *fontName();
/** creates a menu item from a string without target/selector. To b
e used with CCMenuItemToggle */
static CCMenuItemFont * itemFromString(const char *value);
/** creates a menu item from a string with a target/selector */
static CCMenuItemFont * itemFromString(const char *value, CCObject*
target, SEL_MenuHandler selector);
/** initializes a menu item from a string with a target/selector */
bool initFromString(const char *value, CCObject* target, SEL_MenuHa
ndler selector);
/** set font size
* c++ can not overload static and non-static member functions with
the same parameter types
* so change the name to setFontSizeObj
*/
void setFontSizeObj(unsigned int s);
/** get font size */
unsigned int fontSizeObj();
/** set the font name
* c++ can not overload static and non-static member functions with
the same parameter types
* so change the name to setFontNameObj
*/
void setFontNameObj(const char* name);
const char* fontNameObj();
protected:
void recreateLabel();
unsigned int m_uFontSize;
std::string m_strFontName;
};
/** @brief CCMenuItemSprite accepts CCNode<CCRGBAProtocol> objects as i
tems.
The images has 3 different states:
- unselected image
- selected image
- disabled image
@since v0.8.0 protected:
void recreateLabel();
unsigned int m_uFontSize;
std::string m_strFontName;
};
/** @brief CCMenuItemSprite accepts CCNode<CCRGBAProtocol> objects as items
.
The images has 3 different states:
- unselected image
- selected image
- disabled image
@since v0.8.0
*/
class CC_DLL CCMenuItemSprite : public CCMenuItem, public CCRGBAProtocol
{
/** the image used when the item is not selected */
CC_PROPERTY(CCNode*, m_pNormalImage, NormalImage);
/** the image used when the item is selected */
CC_PROPERTY(CCNode*, m_pSelectedImage, SelectedImage);
/** the image used when the item is disabled */
CC_PROPERTY(CCNode*, m_pDisabledImage, DisabledImage);
public:
CCMenuItemSprite()
:m_pNormalImage(NULL)
,m_pSelectedImage(NULL)
,m_pDisabledImage(NULL)
{}
/** creates a menu item with a normal, selected and disabled image
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCMenuItemSprite * itemWithNormalSprite(
CCNode* normalSprite, CCNode* selectedSprite, CCNode* disabledSprite = NULL
);
/** creates a menu item with a normal and selected image with target/se
lector
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCMenuItemSprite * itemWithNormalSprite(
CCNode* normalSprite, CCNode* selectedSprite, CCObject* target, SEL_MenuHan
dler selector);
/** creates a menu item with a normal,selected and disabled image with
target/selector
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCMenuItemSprite * itemWithNormalSprite(
CCNode* normalSprite, CCNode* selectedSprite, CCNode* disabledSprite, CCObj
ect* target, SEL_MenuHandler selector);
/** creates a menu item with a normal, selected and disabled image*/
static CCMenuItemSprite * create(CCNode* normalSprite, CCNode* selected
Sprite, CCNode* disabledSprite = NULL);
/** creates a menu item with a normal and selected image with target/se
lector */
static CCMenuItemSprite * create(CCNode* normalSprite, CCNode* selected
Sprite, CCObject* target, SEL_MenuHandler selector);
/** creates a menu item with a normal,selected and disabled image with
target/selector */
static CCMenuItemSprite * create(CCNode* normalSprite, CCNode* selected
Sprite, CCNode* disabledSprite, CCObject* target, SEL_MenuHandler selector)
;
/** initializes a menu item with a normal, selected and disabled image
with target/selector */
bool initWithNormalSprite(CCNode* normalSprite, CCNode* selectedSprite,
CCNode* disabledSprite, CCObject* target, SEL_MenuHandler selector);
// super methods
virtual void setColor(const ccColor3B& color);
virtual const ccColor3B& getColor();
virtual void setOpacity(GLubyte opacity);
virtual GLubyte getOpacity();
/**
@since v0.99.5
*/ */
class CC_DLL CCMenuItemSprite : public CCMenuItem, public CCRGBAProtoco virtual void selected();
l virtual void unselected();
{ virtual void setEnabled(bool bEnabled);
/** the image used when the item is not selected */
CC_PROPERTY(CCNode*, m_pNormalImage, NormalImage); virtual void setOpacityModifyRGB(bool bValue) {CC_UNUSED_PARAM(bValue);
/** the image used when the item is selected */ }
CC_PROPERTY(CCNode*, m_pSelectedImage, SelectedImage); virtual bool isOpacityModifyRGB(void) { return false;}
/** the image used when the item is disabled */ protected:
CC_PROPERTY(CCNode*, m_pDisabledImage, DisabledImage); virtual void updateImagesVisibility();
public: };
CCMenuItemSprite()
:m_pNormalImage(NULL) /** @brief CCMenuItemImage accepts images as items.
,m_pSelectedImage(NULL) The images has 3 different states:
,m_pDisabledImage(NULL) - unselected image
{} - selected image
/** creates a menu item with a normal, selected and disabled image* - disabled image
/
static CCMenuItemSprite * itemFromNormalSprite(CCNode* normalSprite For best results try that all images are of the same size
, CCNode* selectedSprite, CCNode* disabledSprite = NULL); */
/** creates a menu item with a normal and selected image with targe class CC_DLL CCMenuItemImage : public CCMenuItemSprite
t/selector */ {
static CCMenuItemSprite * itemFromNormalSprite(CCNode* normalSprite public:
, CCNode* selectedSprite, CCObject* target, SEL_MenuHandler selector); CCMenuItemImage(){}
/** creates a menu item with a normal,selected and disabled image virtual ~CCMenuItemImage(){}
with target/selector */ /** creates a menu item with a normal and selected image
static CCMenuItemSprite * itemFromNormalSprite(CCNode* normalSprite @deprecated: This interface will be deprecated sooner or later.
, CCNode* selectedSprite, CCNode* disabledSprite, CCObject* target, SEL_Men */
uHandler selector); CC_DEPRECATED_ATTRIBUTE static CCMenuItemImage* itemWithNormalImage(con
/** initializes a menu item with a normal, selected and disabled i st char *normalImage, const char *selectedImage);
mage with target/selector */ /** creates a menu item with a normal,selected and disabled image
bool initFromNormalSprite(CCNode* normalSprite, CCNode* selectedSpr @deprecated: This interface will be deprecated sooner or later.
ite, CCNode* disabledSprite, CCObject* target, SEL_MenuHandler selector); */
// super methods CC_DEPRECATED_ATTRIBUTE static CCMenuItemImage* itemWithNormalImage(con
virtual void setColor(const ccColor3B& color); st char *normalImage, const char *selectedImage, const char *disabledImage)
virtual const ccColor3B& getColor(); ;
virtual void setOpacity(GLubyte opacity); /** creates a menu item with a normal and selected image with target/se
virtual GLubyte getOpacity(); lector
@deprecated: This interface will be deprecated sooner or later.
/** */
@since v0.99.5 CC_DEPRECATED_ATTRIBUTE static CCMenuItemImage* itemWithNormalImage(con
*/ st char *normalImage, const char *selectedImage, CCObject* target, SEL_Menu
virtual void selected(); Handler selector);
virtual void unselected(); /** creates a menu item with a normal,selected and disabled image with
virtual void setIsEnabled(bool bEnabled); target/selector
@deprecated: This interface will be deprecated sooner or later.
virtual void setIsOpacityModifyRGB(bool bValue) {CC_UNUSED_PARAM(bV */
alue);} CC_DEPRECATED_ATTRIBUTE static CCMenuItemImage* itemWithNormalImage(con
virtual bool getIsOpacityModifyRGB(void) { return false;} st char *normalImage, const char *selectedImage, const char *disabledImage,
}; CCObject* target, SEL_MenuHandler selector);
/** @brief CCMenuItemImage accepts images as items. /** creates a menu item with a normal and selected image*/
The images has 3 different states: static CCMenuItemImage* create(const char *normalImage, const char *sel
- unselected image ectedImage);
- selected image /** creates a menu item with a normal,selected and disabled image*/
- disabled image static CCMenuItemImage* create(const char *normalImage, const char *sel
ectedImage, const char *disabledImage);
/** creates a menu item with a normal and selected image with target/se
lector */
static CCMenuItemImage* create(const char *normalImage, const char *sel
ectedImage, CCObject* target, SEL_MenuHandler selector);
/** creates a menu item with a normal,selected and disabled image with
target/selector */
static CCMenuItemImage* create(const char *normalImage, const char *sel
ectedImage, const char *disabledImage, CCObject* target, SEL_MenuHandler se
lector);
bool init();
/** initializes a menu item with a normal, selected and disabled image
with target/selector */
bool initWithNormalImage(const char *normalImage, const char *selectedI
mage, const char *disabledImage, CCObject* target, SEL_MenuHandler selector
);
/** sets the sprite frame for the normal image */
void setNormalSpriteFrame(CCSpriteFrame* frame);
/** sets the sprite frame for the selected image */
void setSelectedSpriteFrame(CCSpriteFrame* frame);
/** sets the sprite frame for the disabled image */
void setDisabledSpriteFrame(CCSpriteFrame* frame);
/** Creates an CCMenuItemImage.
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCMenuItemImage* node();
For best results try that all images are of the same size /** Creates an CCMenuItemImage.
*/ */
class CC_DLL CCMenuItemImage : public CCMenuItemSprite static CCMenuItemImage* create();
{ };
public:
CCMenuItemImage(){} /** @brief A CCMenuItemToggle
virtual ~CCMenuItemImage(){} A simple container class that "toggles" it's inner items
/** creates a menu item with a normal and selected image*/ The inner itmes can be any MenuItem
static CCMenuItemImage* itemFromNormalImage(const char *normalImage */
, const char *selectedImage); class CC_DLL CCMenuItemToggle : public CCMenuItem, public CCRGBAProtocol
/** creates a menu item with a normal,selected and disabled image* {
/ /** conforms with CCRGBAProtocol protocol */
static CCMenuItemImage* itemFromNormalImage(const char *normalImage CC_PROPERTY(GLubyte, m_cOpacity, Opacity);
, const char *selectedImage, const char *disabledImage); /** conforms with CCRGBAProtocol protocol */
/** creates a menu item with a normal and selected image with targe CC_PROPERTY_PASS_BY_REF(ccColor3B, m_tColor, Color);
t/selector */ /** returns the selected item */
static CCMenuItemImage* itemFromNormalImage(const char *normalImage CC_PROPERTY(unsigned int, m_uSelectedIndex, SelectedIndex);
, const char *selectedImage, CCObject* target, SEL_MenuHandler selector); /** CCMutableArray that contains the subitems. You can add/remove items
/** creates a menu item with a normal,selected and disabled image in runtime, and you can replace the array with a new one.
with target/selector */ @since v0.7.2
static CCMenuItemImage* itemFromNormalImage(const char *normalImage
, const char *selectedImage, const char *disabledImage, CCObject* target, S
EL_MenuHandler selector);
/** initializes a menu item with a normal, selected and disabled i
mage with target/selector */
bool initFromNormalImage(const char *normalImage, const char *selec
tedImage, const char *disabledImage, CCObject* target, SEL_MenuHandler sele
ctor);
};
/** @brief A CCMenuItemToggle
A simple container class that "toggles" it's inner items
The inner itmes can be any MenuItem
*/ */
class CC_DLL CCMenuItemToggle : public CCMenuItem, public CCRGBAProtoco CC_PROPERTY(CCArray*, m_pSubItems, SubItems);
l public:
{ CCMenuItemToggle()
/** conforms with CCRGBAProtocol protocol */ : m_cOpacity(0)
CC_PROPERTY(GLubyte, m_cOpacity, Opacity); , m_uSelectedIndex(0)
/** conforms with CCRGBAProtocol protocol */ , m_pSubItems(NULL)
CC_PROPERTY_PASS_BY_REF(ccColor3B, m_tColor, Color); {}
/** returns the selected item */ virtual ~CCMenuItemToggle();
CC_PROPERTY(unsigned int, m_uSelectedIndex, SelectedIndex);
/** CCMutableArray that contains the subitems. You can add/remove i /** creates a menu item from a list of items with a target/selector
tems in runtime, and you can replace the array with a new one. @deprecated: This interface will be deprecated sooner or later.
@since v0.7.2 */
*/ CC_DEPRECATED_ATTRIBUTE static CCMenuItemToggle* itemWithTarget(CCObjec
CC_PROPERTY(CCMutableArray<CCMenuItem*>*, m_pSubItems, SubItems); t* target, SEL_MenuHandler selector, CCMenuItem* item, ...);
public:
CCMenuItemToggle() /** creates a menu item from a list of items with a target/selector */
: m_cOpacity(0) static CCMenuItemToggle* createWithTarget(CCObject* target, SEL_MenuHan
, m_uSelectedIndex(0) dler selector, CCMenuItem* item, ...);
, m_pSubItems(NULL)
{} /** initializes a menu item from a list of items with a target selector
virtual ~CCMenuItemToggle(); */
/** creates a menu item from a list of items with a target/selector bool initWithTarget(CCObject* target, SEL_MenuHandler selector, CCMenuI
*/ tem* item, va_list args);
static CCMenuItemToggle* itemWithTarget(CCObject* target, SEL_MenuH
andler selector, CCMenuItem* item, ...); // The follow methods offered to lua
/** initializes a menu item from a list of items with a target sele /** creates a menu item with a item
ctor */ @deprecated: This interface will be deprecated sooner or later.
bool initWithTarget(CCObject* target, SEL_MenuHandler selector, CCM */
enuItem* item, va_list args); CC_DEPRECATED_ATTRIBUTE static CCMenuItemToggle* itemWithItem(CCMenuIte
m *item);
// The follow methods offered to lua
/** creates a menu item with a item */ /** creates a menu item with a item */
static CCMenuItemToggle* itemWithItem(CCMenuItem *item); static CCMenuItemToggle* create(CCMenuItem *item);
/** initializes a menu item with a item */
bool initWithItem(CCMenuItem *item); /** initializes a menu item with a item */
/** add more menu item */ bool initWithItem(CCMenuItem *item);
void addSubItem(CCMenuItem *item); /** add more menu item */
void addSubItem(CCMenuItem *item);
/** return the selected item */
CCMenuItem* selectedItem(); /** return the selected item */
// super methods CCMenuItem* selectedItem();
virtual void activate(); // super methods
virtual void selected(); virtual void activate();
virtual void unselected(); virtual void selected();
virtual void setIsEnabled(bool var); virtual void unselected();
virtual void setEnabled(bool var);
virtual void setIsOpacityModifyRGB(bool bValue) {CC_UNUSED_PARAM(bV
alue);} virtual void setOpacityModifyRGB(bool bValue) {CC_UNUSED_PARAM(bValue);
virtual bool getIsOpacityModifyRGB(void) { return false;} }
}; virtual bool isOpacityModifyRGB(void) { return false;}
};
// end of GUI group
/// @}
/// @}
} NS_CC_END
#endif //__CCMENU_ITEM_H__ #endif //__CCMENU_ITEM_H__
 End of changes. 17 change blocks. 
326 lines changed or deleted 461 lines changed or added


 CCMotionStreak.h   CCMotionStreak.h 
/************************************************************************** ** /************************************************************************** **
Copyright (c) 2010-2011 cocos2d-x.org Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2008, 2009 Jason Booth Copyright (c) 2011 ForzeField Studios S.L.
http://www.cocos2d-x.org http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a cop y Permission is hereby granted, free of charge, to any person obtaining a cop y
of this software and associated documentation files (the "Software"), to de al of this software and associated documentation files (the "Software"), to de al
in the Software without restriction, including without limitation the right s in the Software without restriction, including without limitation the right s
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
skipping to change at line 28 skipping to change at line 28
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CCMOTION_STREAK_H__ #ifndef __CCMOTION_STREAK_H__
#define __CCMOTION_STREAK_H__ #define __CCMOTION_STREAK_H__
#include "CCNode.h"
#include "CCProtocols.h" #include "CCProtocols.h"
#include "textures/CCTexture2D.h"
#include "ccTypes.h"
#include "base_nodes/CCNode.h"
namespace cocos2d { NS_CC_BEGIN
class CCRibbon;
/** /**
* @brief CCMotionStreak manages a Ribbon based on it's motion in absolute s * @addtogroup misc_nodes
pace. * @{
* You construct it with a fadeTime, minimum segment size, texture path, tex */
ture
* length and color. The fadeTime controls how long it takes each vertex in /** MotionStreak.
* the streak to fade out, the minimum segment size it how many pixels the Creates a trailing path.
* streak will move before adding a new ribbon segement, and the texture */
* length is the how many pixels the texture is stretched across. The textur class CC_DLL CCMotionStreak : public CCNode, public CCTextureProtocol, publ
e ic CCRGBAProtocol
* is vertically aligned along the streak segemnts.
*
* Limitations:
* CCMotionStreak, by default, will use the GL_SRC_ALPHA, GL_ONE_MINUS_SRC
_ALPHA blending function.
* This blending function might not be the correct one for certain texture
s.
* But you can change it by using:
* [obj setBlendFunc: (ccBlendfunc) {new_src_blend_func, new_dst_blend_f
unc}];
*
* @since v0.8.1
*/
class CC_DLL CCMotionStreak : public CCNode, public CCTextureProtocol
{ {
/** Ribbon used by MotionStreak (weak reference) */
CC_PROPERTY_READONLY(CCRibbon*, m_pRibbon, Ribbon)
//CCTextureProtocol methods
CC_PROPERTY(CCTexture2D*, m_pTexture, Texture)
CC_PROPERTY(ccBlendFunc, m_tBlendFunc, BlendFunc)
public: public:
CCMotionStreak() CCMotionStreak();
: m_pRibbon(NULL) virtual ~CCMotionStreak();
, m_pTexture(NULL) /** creates and initializes a motion streak with fade in seconds, minim
, m_fSegThreshold(0.0) um segments, stroke's width, color, texture filename
, m_fWidth(0.0) @deprecated: This interface will be deprecated sooner or later.
{} */
virtual ~CCMotionStreak(){} CC_DEPRECATED_ATTRIBUTE static CCMotionStreak* streakWithFade(float fad
/** creates the a MotionStreak. The image will be loaded using the T e, float minSeg, float stroke, ccColor3B color, const char* path);
extureMgr. */ /** creates and initializes a motion streak with fade in seconds, minim
static CCMotionStreak * streakWithFade(float fade, float seg, const um segments, stroke's width, color, texture
char *imagePath, float width, float length, const ccColor4B& color); @deprecated: This interface will be deprecated sooner or later.
*/
/** initializes a MotionStreak. The file will be loaded using the Te CC_DEPRECATED_ATTRIBUTE static CCMotionStreak* streakWithFade(float fad
xtureMgr. */ e, float minSeg, float stroke, ccColor3B color, CCTexture2D* texture);
bool initWithFade(float fade, float seg, const char *imagePath, floa
t width, float length, const ccColor4B& color); /** creates and initializes a motion streak with fade in seconds, minim
um segments, stroke's width, color, texture filename */
/** polling function */ static CCMotionStreak* create(float fade, float minSeg, float stroke, c
void update(ccTime delta); cColor3B color, const char* path);
/** creates and initializes a motion streak with fade in seconds, minim
um segments, stroke's width, color, texture */
static CCMotionStreak* create(float fade, float minSeg, float stroke, c
cColor3B color, CCTexture2D* texture);
/** initializes a motion streak with fade in seconds, minimum segments,
stroke's width, color and texture filename */
bool initWithFade(float fade, float minSeg, float stroke, ccColor3B col
or, const char* path);
/** initializes a motion streak with fade in seconds, minimum segments,
stroke's width, color and texture */
bool initWithFade(float fade, float minSeg, float stroke, ccColor3B col
or, CCTexture2D* texture);
/** color used for the tint */
void tintWithColor(ccColor3B colors);
/** Remove all living segments of the ribbon */
void reset();
/** Override super methods */
virtual void setPosition(const CCPoint& position);
virtual void draw();
virtual void update(float delta);
/* Implement interfaces */
virtual CCTexture2D* getTexture(void);
virtual void setTexture(CCTexture2D *texture);
virtual void setBlendFunc(ccBlendFunc blendFunc);
virtual ccBlendFunc getBlendFunc(void);
virtual void setColor(const ccColor3B& color);
virtual const ccColor3B& getColor(void);
virtual GLubyte getOpacity(void);
virtual void setOpacity(GLubyte opacity);
virtual void setOpacityModifyRGB(bool bValue);
virtual bool isOpacityModifyRGB(void);
/** When fast mode is enbled, new points are added faster but with lowe
r precision */
inline bool isFastMode() { return m_bFastMode; }
inline void setFastMode(bool bFastMode) { m_bFastMode = bFastMode; }
inline bool isStartingPositionInitialized() { return m_bStartingPositio
nInitialized; }
inline void setStartingPositionInitialized(bool bStartingPositionInitia
lized)
{
m_bStartingPositionInitialized = bStartingPositionInitialized;
}
protected: protected:
float m_fSegThreshold; bool m_bFastMode;
float m_fWidth; bool m_bStartingPositionInitialized;
CCPoint m_tLastLocation; private:
/** texture used for the motion streak */
CCTexture2D* m_pTexture;
ccBlendFunc m_tBlendFunc;
CCPoint m_tPositionR;
ccColor3B m_tColor;
float m_fStroke;
float m_fFadeDelta;
float m_fMinSeg;
unsigned int m_uMaxPoints;
unsigned int m_uNuPoints;
unsigned int m_uPreviousNuPoints;
/** Pointers */
CCPoint* m_pPointVertexes;
float* m_pPointState;
// Opengl
ccVertex2F* m_pVertices;
GLubyte* m_pColorPointer;
ccTex2F* m_pTexCoords;
}; };
} // namespace cocos2d // end of misc_nodes group
/// @}
NS_CC_END
#endif //__CCMOTION_STREAK_H__ #endif //__CCMOTION_STREAK_H__
 End of changes. 10 change blocks. 
56 lines changed or deleted 112 lines changed or added


 CCNS.h   CCNS.h 
skipping to change at line 30 skipping to change at line 30
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __PLATFOMR_CCNS_H__ #ifndef __PLATFOMR_CCNS_H__
#define __PLATFOMR_CCNS_H__ #define __PLATFOMR_CCNS_H__
#include "CCGeometry.h" #include "CCGeometry.h"
namespace cocos2d NS_CC_BEGIN
{
/** /**
@brief Returns a Core Graphics rectangle structure corresponding to the * @addtogroup data_structures
data in a given string. * @{
@param pszContent A string object whose contents are of the form "{{x */
,y},{w, h}}",
where x is the x coordinate, y is the y coordinate, /**
w is the width, and h is the height. @brief Returns a Core Graphics rectangle structure corresponding to the dat
These components can represent integer or float val a in a given string.
ues. @param pszContent A string object whose contents are of the form "{{x,y},
An example of a valid string is "{{3,2},{4,5}}". {w, h}}",
The string is not localized, so items are always se where x is the x coordinate, y is the y coordinate, w i
parated with a comma. s the width, and h is the height.
@return A Core Graphics structure that represents a rectangle. These components can represent integer or float values.
If the string is not well-formed, the function returns CCRectZe An example of a valid string is "{{3,2},{4,5}}".
ro. The string is not localized, so items are always separa
*/ ted with a comma.
CCRect CC_DLL CCRectFromString(const char* pszContent); @return A Core Graphics structure that represents a rectangle.
If the string is not well-formed, the function returns CCRectZero.
/** */
@brief Returns a Core Graphics point structure corresponding to the dat CCRect CC_DLL CCRectFromString(const char* pszContent);
a in a given string.
@param pszContent A string object whose contents are of the form "{x, /**
y}", @brief Returns a Core Graphics point structure corresponding to the data in
where x is the x coordinate and y is the y coordina a given string.
te. @param pszContent A string object whose contents are of the form "{x,y}",
The x and y values can represent integer or float v where x is the x coordinate and y is the y coordinate.
alues. The x and y values can represent integer or float value
An example of a valid string is "{3.0,2.5}". s.
The string is not localized, so items are always se An example of a valid string is "{3.0,2.5}".
parated with a comma. The string is not localized, so items are always separa
@return A Core Graphics structure that represents a point. ted with a comma.
If the string is not well-formed, the function returns CCPointZ @return A Core Graphics structure that represents a point.
ero. If the string is not well-formed, the function returns CCPointZero.
*/ */
CCPoint CC_DLL CCPointFromString(const char* pszContent); CCPoint CC_DLL CCPointFromString(const char* pszContent);
/** /**
@brief Returns a Core Graphics size structure corresponding to the data @brief Returns a Core Graphics size structure corresponding to the data in
in a given string. a given string.
@param pszContent A string object whose contents are of the form "{w, @param pszContent A string object whose contents are of the form "{w, h}"
h}", ,
where w is the width and h is the height. where w is the width and h is the height.
The w and h values can be integer or float values. The w and h values can be integer or float values.
An example of a valid string is "{3.0,2.5}". An example of a valid string is "{3.0,2.5}".
The string is not localized, so items are always se The string is not localized, so items are always separa
parated with a comma. ted with a comma.
@return A Core Graphics structure that represents a size. @return A Core Graphics structure that represents a size.
If the string is not well-formed, the function returns CCSizeZe If the string is not well-formed, the function returns CCSizeZero.
ro. */
*/ CCSize CC_DLL CCSizeFromString(const char* pszContent);
CCSize CC_DLL CCSizeFromString(const char* pszContent);
} // end of data_structure group
/// @}
NS_CC_END
#endif // __PLATFOMR_CCNS_H__ #endif // __PLATFOMR_CCNS_H__
 End of changes. 1 change blocks. 
54 lines changed or deleted 57 lines changed or added


 CCNode.h   CCNode.h 
/************************************************************************** ** /************************************************************************** **
Copyright (c) 2010-2011 cocos2d-x.org Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2009 Valentin Milea Copyright (c) 2009 Valentin Milea
Copyright (c) 2011 Zynga Inc. Copyright (c) 2011 Zynga Inc.
http://www.cocos2d-x.org http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a co py Permission is hereby granted, free of charge, to any person obtaining a co py
of this software and associated documentation files (the "Software"), to d eal of this software and associated documentation files (the "Software"), to d eal
in the Software without restriction, including without limitation the righ ts in the Software without restriction, including without limitation the righ ts
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
skipping to change at line 32 skipping to change at line 32
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FR OM, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FR OM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
************************************************************************** **/ ************************************************************************** **/
#ifndef __PLATFOMR_CCNODE_H__ #ifndef __PLATFOMR_CCNODE_H__
#define __PLATFOMR_CCNODE_H__ #define __PLATFOMR_CCNODE_H__
#include "ccMacros.h" #include "ccMacros.h"
#include "CCAffineTransform.h" #include "cocoa/CCAffineTransform.h"
#include "CCArray.h" #include "cocoa/CCArray.h"
#include "CCGL.h" #include "CCGL.h"
#include "shaders/ccGLStateCache.h"
#include "shaders/CCGLProgram.h"
#include "kazmath/kazmath.h"
NS_CC_BEGIN
class CCCamera;
class CCGridBase;
class CCPoint;
class CCTouch;
class CCAction;
class CCRGBAProtocol;
class CCLabelProtocol;
class CCScheduler;
class CCActionManager;
/**
* @addtogroup base_nodes
* @{
*/
enum {
kCCNodeTagInvalid = -1,
};
enum {
kCCNodeOnEnter,
kCCNodeOnExit
};
/** @brief CCNode is the main element. Anything thats gets drawn or contain
s things that get drawn is a CCNode.
The most popular CCNodes are: CCScene, CCLayer, CCSprite, CCMenu.
The main features of a CCNode are:
- They can contain other CCNode nodes (addChild, getChildByTag, removeChil
d, etc)
- They can schedule periodic callback (schedule, unschedule, etc)
- They can execute actions (runAction, stopAction, etc)
Some CCNode nodes provide extra functionality for them or their children.
Subclassing a CCNode usually means (one/all) of:
- overriding init to initialize resources and schedule callbacks
- create callbacks to handle the advancement of time
- overriding draw to render the node
Features of CCNode:
- position
- scale (x, y)
- rotation (in degrees, clockwise)
- CCCamera (an interface to gluLookAt )
- CCGridBase (to do mesh transformations)
- anchor point
- size
- visible
- z-order
- openGL z position
Default values:
- rotation: 0
- position: (x=0,y=0)
- scale: (x=1,y=1)
- contentSize: (x=0,y=0)
- anchorPoint: (x=0,y=0)
Limitations:
- A CCNode is a "void" object. It doesn't have a texture
Order in transformations with grid disabled
-# The node will be translated (position)
-# The node will be rotated (rotation)
-# The node will be scaled (scale)
-# The node will be moved according to the camera values (camera)
Order in transformations with grid enabled
-# The node will be translated (position)
-# The node will be rotated (rotation)
-# The node will be scaled (scale)
-# The grid will capture the screen
-# The node will be moved according to the camera values (camera)
-# The grid will render the captured screen
Camera:
- Each node has a camera. By default it points to the center of the CCNode
.
*/
class CC_DLL CCNode : public CCObject
{
// variable property
/** The z order of the node relative to it's "brothers": children of th
e same parent */
CC_PROPERTY_READONLY(int, m_nZOrder, ZOrder)
/** The real openGL Z vertex.
Differences between openGL Z vertex and cocos2d Z order:
- OpenGL Z modifies the Z vertex, and not the Z order in the relation
between parent-children
- OpenGL Z might require to set 2D projection
- cocos2d Z order works OK if all the nodes uses the same openGL Z ver
tex. eg: vertexZ = 0
@warning: Use it at your own risk since it might break the cocos2d par
ent-children z order
@since v0.8
*/
CC_PROPERTY(float, m_fVertexZ, VertexZ)
/** The rotation (angle) of the node in degrees. 0 is the default rotat
ion angle. Positive values rotate node CW. */
CC_PROPERTY(float, m_fRotation, Rotation)
/** Get the scale factor of the node.
@warning: Assert when m_fScaleX != m_fScaleY.
*/
float getScale();
/** The scale factor of the node. 1.0 is the default scale factor. It m
odifies the X and Y scale at the same time. */
void setScale(float scale);
/** The scale factor of the node. 1.0 is the default scale factor. It o
nly modifies the X scale factor. */
CC_PROPERTY(float, m_fScaleX, ScaleX)
/** The scale factor of the node. 1.0 is the default scale factor. It o
nly modifies the Y scale factor. */
CC_PROPERTY(float, m_fScaleY, ScaleY)
/** Position (x,y) of the node in OpenGL coordinates. (0,0) is the left
-bottom corner. */
CC_PROPERTY_PASS_BY_REF(CCPoint, m_tPosition, Position)
/** get/set Position for Lua (pass number faster than CCPoint object)
lua code:
local pos = node:getPositionLua() -- return CCPoint object from C++
local x, y = node:getPosition() -- return x, y values from C++
local x = node:getPositionX()
local y = node:getPositionY()
node:setPosition(x, y) -- pass x, y values to C++
node:setPositionX(x)
node:setPositionY(y)
node:setPositionInPixels(x, y) -- pass x, y values to C++
*/
const CCPoint& getPositionLua(void);
void getPosition(float* x, float* y);
float getPositionX(void);
float getPositionY(void);
void setPositionX(float x);
void setPositionY(float y);
void setPosition(float x, float y);
void _setZOrder(int z);
/** The X skew angle of the node in degrees.
This angle describes the shear distortion in the X direction.
Thus, it is the angle between the Y axis and the left edge of the shap
e
The default skewX angle is 0. Positive values distort the node in a CW
direction.
*/
CC_PROPERTY(float, m_fSkewX, SkewX)
/** The Y skew angle of the node in degrees.
This angle describes the shear distortion in the Y direction.
Thus, it is the angle between the X axis and the bottom edge of the sh
ape
The default skewY angle is 0. Positive values distort the node in a CC
W direction.
*/
CC_PROPERTY(float, m_fSkewY, SkewY)
CC_PROPERTY_READONLY(CCArray*, m_pChildren, Children)
/** Get children count */
unsigned int getChildrenCount(void);
/** A CCCamera object that lets you move the node using a gluLookAt
*/
CC_PROPERTY_READONLY(CCCamera *, m_pCamera, Camera)
/** A CCGrid object that is used when applying effects */
CC_PROPERTY(CCGridBase *, m_pGrid, Grid)
/** Whether of not the node is visible. Default is true */
protected:
bool m_bIsVisible;
public:
virtual bool isVisible();
virtual void setVisible(bool visible);
/** anchorPoint is the point around which all transformations and posit
ioning manipulations take place.
It's like a pin in the node where it is "attached" to its parent.
The anchorPoint is normalized, like a percentage. (0,0) means the bott
om-left corner and (1,1) means the top-right corner.
But you can use values higher than (1,1) and lower than (0,0) too.
The default anchorPoint is (0.5,0.5), so it starts in the center of th
e node.
@since v0.8
*/
CC_PROPERTY_PASS_BY_REF(CCPoint, m_tAnchorPoint, AnchorPoint)
/** The anchorPoint in absolute pixels.
Since v0.8 you can only read it. If you wish to modify it, use anchorP
oint instead
*/
CC_PROPERTY_READONLY_PASS_BY_REF(CCPoint, m_tAnchorPointInPoints, Ancho
rPointInPoints)
/** The untransformed size of the node.
The contentSize remains the same no matter the node is scaled or rotat
ed.
All nodes has a size. Layer and Scene has the same size of the screen.
@since v0.8
*/
CC_PROPERTY_PASS_BY_REF(CCSize, m_tContentSize, ContentSize)
/** whether or not the node is running */
bool m_bIsRunning;
bool isRunning();
/** A weak reference to the parent */
CC_PROPERTY(CCNode *, m_pParent, Parent)
// If ture, the Anchor Point will be (0,0) when you position the CCNode
.
// Used by CCLayer and CCScene
bool m_bIgnoreAnchorPointForPosition;
bool isIgnoreAnchorPointForPosition();
void ignoreAnchorPointForPosition(bool isIgnoreAnchorPointForPosition);
/** A tag used to identify the node easily */
CC_PROPERTY(int, m_nTag, Tag)
/** A custom user data pointer */
CC_PROPERTY(void *, m_pUserData, UserData)
/** Similar to userData, but instead of holding a void* it holds an id
*/
CC_SYNTHESIZE_RETAIN(CCObject*, m_pUserObject, UserObject);
/** Shader Program
@since v2.0
*/
CC_SYNTHESIZE_RETAIN(CCGLProgram*, m_pShaderProgram, ShaderProgram);
/** used internally for zOrder sorting, don't change this manually */
CC_SYNTHESIZE(int, m_nOrderOfArrival, OrderOfArrival);
/** GL server side state
@since v2.0
*/
CC_SYNTHESIZE(ccGLServerState, m_glServerState, GLServerState);
/** CCActionManager used by all the actions.
IMPORTANT: If you set a new CCActionManager, then previously created a
ctions are going to be removed.
@since v2.0
*/
CC_PROPERTY(CCActionManager*, m_pActionManager, ActionManager);
/** CCScheduler used to schedule all "updates" and timers.
IMPORTANT: If you set a new CCScheduler, then previously created timer
s/update are going to be removed.
@since v2.0
*/
CC_PROPERTY(CCScheduler*, m_pScheduler, Scheduler);
protected:
// transform
CCAffineTransform m_tTransform, m_tInverse;
// To reduce memory, place bools that are not properties here:
bool m_bIsTransformDirty;
bool m_bIsInverseDirty;
bool m_bReorderChildDirty;
int m_nScriptHandler;
private:
//! lazy allocs
void childrenAlloc(void);
//! helper that reorder a child
void insertChild(CCNode* child, int z);
//! used internally to alter the zOrder variable. DON'T call this metho
d manually
void setZOrder(int z);
void detachChild(CCNode *child, bool doCleanup);
CCPoint convertToWindowSpace(const CCPoint& nodePoint);
public:
CCNode(void);
virtual ~CCNode(void);
const char* description(void);
/** allocates and initializes a node.
The node will be created as "autorelease".
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCNode * node(void);
/** allocates and initializes a node.
The node will be created as "autorelease".
*/
static CCNode * create(void);
//scene managment
/** callback that is called every time the CCNode enters the 'stage'.
If the CCNode enters the 'stage' with a transition, this callback is c
alled when the transition starts.
During onEnter you can't a "sister/brother" node.
*/
virtual void onEnter();
/** callback that is called when the CCNode enters in the 'stage'.
If the CCNode enters the 'stage' with a transition, this callback is c
alled when the transition finishes.
@since v0.8
*/
virtual void onEnterTransitionDidFinish();
/** callback that is called every time the CCNode leaves the 'stage'.
If the CCNode leaves the 'stage' with a transition, this callback is c
alled when the transition finishes.
During onExit you can't access a sibling node.
*/
virtual void onExit();
/** callback that is called every time the CCNode leaves the 'stage'.
If the CCNode leaves the 'stage' with a transition, this callback is c
alled when the transition starts.
*/
virtual void onExitTransitionDidStart();
/** Register onEnter/onExit handler script function
Script handler auto unregister after onEnter().
*/
virtual void registerScriptHandler(int nHandler);
virtual void unregisterScriptHandler(void);
// composition: ADD
/** Adds a child to the container with z-order as 0.
If the child is added to a 'running' node, then 'onEnter' and 'onEnter
TransitionDidFinish' will be called immediately.
@since v0.7.1
*/
virtual void addChild(CCNode * child);
/** Adds a child to the container with a z-order
If the child is added to a 'running' node, then 'onEnter' and 'onEnter
TransitionDidFinish' will be called immediately.
@since v0.7.1
*/
virtual void addChild(CCNode * child, int zOrder);
/** Adds a child to the container with z order and tag
If the child is added to a 'running' node, then 'onEnter' and 'onEnter
TransitionDidFinish' will be called immediately.
@since v0.7.1
*/
virtual void addChild(CCNode * child, int zOrder, int tag);
// composition: REMOVE
/** Remove itself from its parent node. If cleanup is true, then also r
emove all actions and callbacks.
If the node orphan, then nothing happens.
@since v0.99.3
*/
void removeFromParentAndCleanup(bool cleanup);
/** Removes a child from the container. It will also cleanup all runnin
g actions depending on the cleanup parameter.
@since v0.7.1
*/
virtual void removeChild(CCNode* child, bool cleanup);
/** Removes a child from the container by tag value. It will also clean
up all running actions depending on the cleanup parameter
@since v0.7.1
*/
void removeChildByTag(int tag, bool cleanup);
/** Removes all children from the container and do a cleanup all runnin
g actions depending on the cleanup parameter.
@since v0.7.1
*/
virtual void removeAllChildrenWithCleanup(bool cleanup);
// composition: GET
/** Gets a child from the container given its tag
@return returns a CCNode object
@since v0.7.1
*/
CCNode * getChildByTag(int tag);
/** Reorders a child according to a new z value.
* The child MUST be already added.
*/
virtual void reorderChild(CCNode * child, int zOrder);
/** performance improvement, Sort the children array once before drawin
g, instead of every time when a child is added or reordered
don't call this manually unless a child added needs to be removed in t
he same frame */
virtual void sortAllChildren();
/** Stops all running actions and schedulers
@since v0.8
*/
virtual void cleanup(void);
// draw
/** Override this method to draw your own node.
The following GL states will be enabled by default:
- glEnableClientState(GL_VERTEX_ARRAY);
- glEnableClientState(GL_COLOR_ARRAY);
- glEnableClientState(GL_TEXTURE_COORD_ARRAY);
- glEnable(GL_TEXTURE_2D);
AND YOU SHOULD NOT DISABLE THEM AFTER DRAWING YOUR NODE
But if you enable any other GL state, you should disable it after draw
ing your node.
*/
virtual void draw(void);
/** recursive method that visit its children and draw them */
virtual void visit(void);
// transformations
/** performs OpenGL view-matrix transformation based on position, scale
, rotation and other attributes. */
void transform(void);
/** performs OpenGL view-matrix transformation of it's ancestors.
Generally the ancestors are already transformed, but in certain cases
(eg: attaching a FBO)
it's necessary to transform the ancestors again.
@since v0.7.2
*/
void transformAncestors(void);
/** returns a "local" axis aligned bounding box of the node.
The returned box is relative only to its parent.
@since v0.8.2
*/
CCRect boundingBox(void);
// actions
/** Executes an action, and returns the action that is executed.
The node becomes the action's target.
@warning Starting from v0.8 actions don't retain their target anymore.
@since v0.7.1
@return An Action pointer
*/
CCAction* runAction(CCAction* action);
/** Removes all actions from the running action list */
void stopAllActions(void);
/** Removes an action from the running action list */
void stopAction(CCAction* action);
/** Removes an action from the running action list given its tag
@since v0.7.1
*/
void stopActionByTag(int tag);
/** Gets an action from the running action list given its tag
@since v0.7.1
@return the Action the with the given tag
*/
CCAction* getActionByTag(int tag);
/** Returns the numbers of actions that are running plus the ones that
are schedule to run (actions in actionsToAdd and actions arrays).
* Composable actions are counted as 1 action. Example:
* If you are running 1 Sequence of 7 actions, it will return 1.
* If you are running 7 Sequences of 2 actions, it will return 7.
*/
unsigned int numberOfRunningActions(void);
// timers
/** check whether a selector is scheduled. */
bool isScheduled(SEL_SCHEDULE selector);
/** schedules the "update" method. It will use the order number 0. This
method will be called every frame.
Scheduled methods with a lower order value will be called before the o
nes that have a higher order value.
Only one "update" method could be scheduled per node.
@since v0.99.3
*/
void scheduleUpdate(void);
/** schedules the "update" selector with a custom priority. This select
or will be called every frame.
Scheduled selectors with a lower priority will be called before the on
es that have a higher value.
Only one "update" selector could be scheduled per node (You can't have
2 'update' selectors).
@since v0.99.3
*/
void scheduleUpdateWithPriority(int priority);
/* unschedules the "update" method.
@since v0.99.3
*/
void unscheduleUpdate(void);
/** schedules a selector.
The scheduled selector will be ticked every frame
*/
void schedule(SEL_SCHEDULE selector);
/** schedules a custom selector with an interval time in seconds.
If time is 0 it will be ticked every frame.
If time is 0, it is recommended to use 'scheduleUpdate' instead.
If the selector is already scheduled, then the interval parameter
will be updated without scheduling it again.
*/
void schedule(SEL_SCHEDULE selector, float interval);
/**
repeat will execute the action repeat + 1 times, for a continues actio
n use kCCRepeatForever
delay is the amount of time the action will wait before execution
*/
void schedule(SEL_SCHEDULE selector, float interval, unsigned int repea
t, float delay);
/**
Schedules a selector that runs only once, with a delay of 0 or larger
*/
void scheduleOnce(SEL_SCHEDULE selector, float delay);
/** unschedules a custom selector.*/
void unschedule(SEL_SCHEDULE selector);
/** unschedule all scheduled selectors: custom selectors, and the 'upda
te' selector.
Actions are not affected by this method.
@since v0.99.3
*/
void unscheduleAllSelectors(void);
/** resumes all scheduled selectors and actions.
Called internally by onEnter
*/
void resumeSchedulerAndActions(void);
/** pauses all scheduled selectors and actions.
Called internally by onExit
*/
void pauseSchedulerAndActions(void);
// transformation methods
/** Returns the matrix that transform the node's (local) space coordina
tes into the parent's space coordinates.
The matrix is in Pixels.
@since v0.7.1
*/
virtual CCAffineTransform nodeToParentTransform(void);
/** Returns the matrix that transform parent's space coordinates to the
node's (local) space coordinates.
The matrix is in Pixels.
@since v0.7.1
*/
virtual CCAffineTransform parentToNodeTransform(void);
/** Retrusn the world affine transform matrix. The matrix is in Pixels.
@since v0.7.1
*/
virtual CCAffineTransform nodeToWorldTransform(void);
/** Returns the inverse world affine transform matrix. The matrix is in
Pixels.
@since v0.7.1
*/
virtual CCAffineTransform worldToNodeTransform(void);
/** Converts a Point to node (local) space coordinates. The result is i
n Points.
@since v0.7.1
*/
CCPoint convertToNodeSpace(const CCPoint& worldPoint);
/** Converts a Point to world space coordinates. The result is in Point
s.
@since v0.7.1
*/
CCPoint convertToWorldSpace(const CCPoint& nodePoint);
/** Converts a Point to node (local) space coordinates. The result is i
n Points.
treating the returned/received node point as anchor relative.
@since v0.7.1
*/
CCPoint convertToNodeSpaceAR(const CCPoint& worldPoint);
/** Converts a local Point to world space coordinates.The result is in
Points.
treating the returned/received node point as anchor relative.
@since v0.7.1
*/
CCPoint convertToWorldSpaceAR(const CCPoint& nodePoint);
/** convenience methods which take a CCTouch instead of CCPoint
@since v0.7.1
*/
CCPoint convertTouchToNodeSpace(CCTouch * touch);
/** converts a CCTouch (world coordinates) into a local coordiante. Thi
s method is AR (Anchor Relative).
@since v0.7.1
*/
CCPoint convertTouchToNodeSpaceAR(CCTouch * touch);
};
// end of base_node group
/// @}
namespace cocos2d { NS_CC_END
class CCCamera;
class CCGridBase;
class CCPoint;
class CCTouch;
class CCAction;
class CCRGBAProtocol;
class CCLabelProtocol;
enum {
kCCNodeTagInvalid = -1,
};
enum {
kCCNodeOnEnter,
kCCNodeOnExit
};
/** @brief CCNode is the main element. Anything thats gets drawn or
contains things that get drawn is a CCNode.
The most popular CCNodes are: CCScene, CCLayer, CCSprite, CCMenu.
The main features of a CCNode are:
- They can contain other CCNode nodes (addChild, getChildByTag, remove
Child, etc)
- They can schedule periodic callback (schedule, unschedule, etc)
- They can execute actions (runAction, stopAction, etc)
Some CCNode nodes provide extra functionality for them or their childr
en.
Subclassing a CCNode usually means (one/all) of:
- overriding init to initialize resources and schedule callbacks
- create callbacks to handle the advancement of time
- overriding draw to render the node
Features of CCNode:
- position
- scale (x, y)
- rotation (in degrees, clockwise)
- CCCamera (an interface to gluLookAt )
- CCGridBase (to do mesh transformations)
- anchor point
- size
- visible
- z-order
- openGL z position
Default values:
- rotation: 0
- position: (x=0,y=0)
- scale: (x=1,y=1)
- contentSize: (x=0,y=0)
- anchorPoint: (x=0,y=0)
Limitations:
- A CCNode is a "void" object. It doesn't have a texture
Order in transformations with grid disabled
-# The node will be translated (position)
-# The node will be rotated (rotation)
-# The node will be scaled (scale)
-# The node will be moved according to the camera values (camera)
Order in transformations with grid enabled
-# The node will be translated (position)
-# The node will be rotated (rotation)
-# The node will be scaled (scale)
-# The grid will capture the screen
-# The node will be moved according to the camera values (camera)
-# The grid will render the captured screen
Camera:
- Each node has a camera. By default it points to the center of the CC
Node.
*/
class CC_DLL CCNode : public CCObject
{
// variable property
/** The z order of the node relative to it's "brothers": chi
ldren of the same parent */
CC_PROPERTY_READONLY(int, m_nZOrder, ZOrder)
/** The real openGL Z vertex.
Differences between openGL Z vertex and cocos2d Z order:
- OpenGL Z modifies the Z vertex, and not the Z order in the relat
ion between parent-children
- OpenGL Z might require to set 2D projection
- cocos2d Z order works OK if all the nodes uses the same openGL Z
vertex. eg: vertexZ = 0
@warning: Use it at your own risk since it might break the cocos2d
parent-children z order
@since v0.8
*/
CC_PROPERTY(float, m_fVertexZ, VertexZ)
/** The rotation (angle) of the node in degrees. 0 is the default r
otation angle. Positive values rotate node CW. */
CC_PROPERTY(float, m_fRotation, Rotation)
/** Get the scale factor of the node.
@warning: Assert when m_fScaleX != m_fScaleY.
*/
float getScale();
/** The scale factor of the node. 1.0 is the default scale f
actor. It modifies the X and Y scale at the same time. */
void setScale(float scale);
/** The scale factor of the node. 1.0 is the default scale f
actor. It only modifies the X scale factor. */
CC_PROPERTY(float, m_fScaleX, ScaleX)
/** The scale factor of the node. 1.0 is the default scale factor.
It only modifies the Y scale factor. */
CC_PROPERTY(float, m_fScaleY, ScaleY)
/** Position (x,y) of the node in OpenGL coordinates. (0,0) is the
left-bottom corner. */
CC_PROPERTY_PASS_BY_REF(CCPoint, m_tPosition, Position)
CC_PROPERTY_PASS_BY_REF(CCPoint, m_tPositionInPixels, PositionInPix
els)
/** get/set Position for Lua (pass number faster than CCPoint objec
t)
lua code:
local pos = node:getPositionLua() -- return CCPoint object from C
++
local x, y = node:getPosition() -- return x, y values from C++
local x = node:getPositionX()
local y = node:getPositionY()
node:setPosition(x, y) -- pass x, y values to C++
node:setPositionX(x)
node:setPositionY(y)
node:setPositionInPixels(x, y) -- pass x, y values to C++
*/
const CCPoint& getPositionLua(void);
void getPosition(float* x, float* y);
float getPositionX(void);
float getPositionY(void);
void setPositionX(float x);
void setPositionY(float y);
void setPosition(float x, float y);
void setPositionInPixels(float x, float y);
/** The X skew angle of the node in degrees.
This angle describes the shear distortion in the X direction.
Thus, it is the angle between the Y axis and the left edge of the
shape
The default skewX angle is 0. Positive values distort the node in
a CW direction.
*/
CC_PROPERTY(float, m_fSkewX, SkewX)
/** The Y skew angle of the node in degrees.
This angle describes the shear distortion in the Y direction.
Thus, it is the angle between the X axis and the bottom edge of th
e shape
The default skewY angle is 0. Positive values distort the node in
a CCW direction.
*/
CC_PROPERTY(float, m_fSkewY, SkewY)
CC_PROPERTY_READONLY(CCArray*, m_pChildren, Children)
/** Get children count */
unsigned int getChildrenCount(void);
/** A CCCamera object that lets you move the node using a gluLookAt
*/
CC_PROPERTY_READONLY(CCCamera *, m_pCamera, Camera)
/** A CCGrid object that is used when applying effects */
CC_PROPERTY(CCGridBase *, m_pGrid, Grid)
/** Whether of not the node is visible. Default is true */
CC_PROPERTY(bool, m_bIsVisible, IsVisible)
/** anchorPoint is the point around which all transformations and p
ositioning manipulations take place.
It's like a pin in the node where it is "attached" to its parent.
The anchorPoint is normalized, like a percentage. (0,0) means the
bottom-left corner and (1,1) means the top-right corner.
But you can use values higher than (1,1) and lower than (0,0) too.
The default anchorPoint is (0.5,0.5), so it starts in the center o
f the node.
@since v0.8
*/
CC_PROPERTY_PASS_BY_REF(CCPoint, m_tAnchorPoint, AnchorPoint)
/** The anchorPoint in absolute pixels.
Since v0.8 you can only read it. If you wish to modify it, use anc
horPoint instead
*/
CC_PROPERTY_READONLY_PASS_BY_REF(CCPoint, m_tAnchorPointInPixels, A
nchorPointInPixels)
/** The untransformed size of the node.
The contentSize remains the same no matter the node is scaled or r
otated.
All nodes has a size. Layer and Scene has the same size of the scr
een.
@since v0.8
*/
CC_PROPERTY_PASS_BY_REF(CCSize, m_tContentSize, ContentSize)
/** The untransformed size of the node in Pixels
The contentSize remains the same no matter the node is scaled or r
otated.
All nodes has a size. Layer and Scene has the same size of the scr
een.
@since v0.8
*/
CC_PROPERTY_PASS_BY_REF(CCSize, m_tContentSizeInPixels, ContentSize
InPixels)
/** whether or not the node is running */
CC_PROPERTY_READONLY(bool, m_bIsRunning, IsRunning)
/** A weak reference to the parent */
CC_PROPERTY(CCNode *, m_pParent, Parent)
/** If true the transformtions will be relative to it's anchor poin
t.
* Sprites, Labels and any other sizeble object use it have it enab
led by default.
* Scenes, Layers and other "whole screen" object don't use it, hav
e it disabled by default.
*/
CC_PROPERTY(bool, m_bIsRelativeAnchorPoint, IsRelativeAnchorPoint)
/** A tag used to identify the node easily */
CC_PROPERTY(int, m_nTag, Tag)
/** A custom user data pointer */
CC_PROPERTY(void *, m_pUserData, UserData)
protected:
// transform
CCAffineTransform m_tTransform, m_tInverse;
#ifdef CC_NODE_TRANSFORM_USING_AFFINE_MATRIX
GLfloat m_pTransformGL[16];
#endif
// To reduce memory, place bools that are not properties her
e:
bool m_bIsTransformDirty;
bool m_bIsInverseDirty;
#ifdef CC_NODE_TRANSFORM_USING_AFFINE_MATRIX
bool m_bIsTransformGLDirty;
#endif
int m_nScriptHandler;
private:
//! lazy allocs
void childrenAlloc(void);
//! helper that reorder a child
void insertChild(CCNode* child, int z);
//! used internally to alter the zOrder variable. DON'T call
this method manually
void setZOrder(int z);
void detachChild(CCNode *child, bool doCleanup);
typedef void (CCNode::*callbackFunc)(void);
void arrayMakeObjectsPerformSelector(CCArray* pArray, callba
ckFunc func);
CCPoint convertToWindowSpace(const CCPoint& nodePoint);
public:
CCNode(void);
virtual ~CCNode(void);
char * description(void);
/** allocates and initializes a node.
The node will be created as "autorelease".
*/
static CCNode * node(void);
//scene managment
/** callback that is called every time the CCNode enters the
'stage'.
If the CCNode enters the 'stage' with a transition, this callback
is called when the transition starts.
During onEnter you can't a "sister/brother" node.
*/
virtual void onEnter();
/** callback that is called when the CCNode enters in the 's
tage'.
If the CCNode enters the 'stage' with a transition, this callback
is called when the transition finishes.
@since v0.8
*/
virtual void onEnterTransitionDidFinish();
/** callback that is called every time the CCNode leaves the
'stage'.
If the CCNode leaves the 'stage' with a transition, this callback
is called when the transition finishes.
During onExit you can't access a sibling node.
*/
virtual void onExit();
/** Register onEnter/onExit handler script function
Script handler auto unregister after onEnter().
*/
virtual void registerScriptHandler(int nHandler);
virtual void unregisterScriptHandler(void);
// composition: ADD
/** Adds a child to the container with z-order as 0.
If the child is added to a 'running' node, then 'onEnter' and 'onE
nterTransitionDidFinish' will be called immediately.
@since v0.7.1
*/
virtual void addChild(CCNode * child);
/** Adds a child to the container with a z-order
If the child is added to a 'running' node, then 'onEnter' and 'onE
nterTransitionDidFinish' will be called immediately.
@since v0.7.1
*/
virtual void addChild(CCNode * child, int zOrder);
/** Adds a child to the container with z order and tag
If the child is added to a 'running' node, then 'onEnter' and 'onE
nterTransitionDidFinish' will be called immediately.
@since v0.7.1
*/
virtual void addChild(CCNode * child, int zOrder, int tag);
// composition: REMOVE
/** Remove itself from its parent node. If cleanup is true,
then also remove all actions and callbacks.
If the node orphan, then nothing happens.
@since v0.99.3
*/
void removeFromParentAndCleanup(bool cleanup);
/** Removes a child from the container. It will also cleanup
all running actions depending on the cleanup parameter.
@since v0.7.1
*/
virtual void removeChild(CCNode* child, bool cleanup);
/** Removes a child from the container by tag value. It will
also cleanup all running actions depending on the cleanup parameter
@since v0.7.1
*/
void removeChildByTag(int tag, bool cleanup);
/** Removes all children from the container and do a cleanup
all running actions depending on the cleanup parameter.
@since v0.7.1
*/
virtual void removeAllChildrenWithCleanup(bool cleanup);
// composition: GET
/** Gets a child from the container given its tag
@return returns a CCNode object
@since v0.7.1
*/
CCNode * getChildByTag(int tag);
/** Reorders a child according to a new z value.
* The child MUST be already added.
*/
virtual void reorderChild(CCNode * child, int zOrder);
/** Stops all running actions and schedulers
@since v0.8
*/
virtual void cleanup(void);
// draw
/** Override this method to draw your own node.
The following GL states will be enabled by default:
- glEnableClientState(GL_VERTEX_ARRAY);
- glEnableClientState(GL_COLOR_ARRAY);
- glEnableClientState(GL_TEXTURE_COORD_ARRAY);
- glEnable(GL_TEXTURE_2D);
AND YOU SHOULD NOT DISABLE THEM AFTER DRAWING YOUR NODE
But if you enable any other GL state, you should disable it after
drawing your node.
*/
virtual void draw(void);
/** recursive method that visit its children and draw them *
/
virtual void visit(void);
// transformations
/** performs OpenGL view-matrix transformation based on posi
tion, scale, rotation and other attributes. */
void transform(void);
/** performs OpenGL view-matrix transformation of it's ances
tors.
Generally the ancestors are already transformed, but in certain ca
ses (eg: attaching a FBO)
it's necessary to transform the ancestors again.
@since v0.7.2
*/
void transformAncestors(void);
/** returns a "local" axis aligned bounding box of the node.
The returned box is relative only to its parent.
@since v0.8.2
*/
CCRect boundingBox(void);
/** returns a "local" axis aligned bounding box of the node
in pixels.
The returned box is relative only to its parent.
The returned box is in Points.
@since v0.99.5
*/
CCRect boundingBoxInPixels(void);
// actions
/** Executes an action, and returns the action that is execu
ted.
The node becomes the action's target.
@warning Starting from v0.8 actions don't retain their target anym
ore.
@since v0.7.1
@return An Action pointer
*/
CCAction* runAction(CCAction* action);
/** Removes all actions from the running action list */
void stopAllActions(void);
/** Removes an action from the running action list */
void stopAction(CCAction* action);
/** Removes an action from the running action list given its
tag
@since v0.7.1
*/
void stopActionByTag(int tag);
/** Gets an action from the running action list given its ta
g
@since v0.7.1
@return the Action the with the given tag
*/
CCAction* getActionByTag(int tag);
/** Returns the numbers of actions that are running plus the
ones that are schedule to run (actions in actionsToAdd and actions arrays)
.
* Composable actions are counted as 1 action. Example:
* If you are running 1 Sequence of 7 actions, it will return 1.
* If you are running 7 Sequences of 2 actions, it will return 7
.
*/
unsigned int numberOfRunningActions(void);
// timers
/** check whether a selector is scheduled. */
bool isScheduled(SEL_SCHEDULE selector);
/** schedules the "update" method. It will use the order num
ber 0. This method will be called every frame.
Scheduled methods with a lower order value will be called before t
he ones that have a higher order value.
Only one "update" method could be scheduled per node.
@since v0.99.3
*/
void scheduleUpdate(void);
/** schedules the "update" selector with a custom priority.
This selector will be called every frame.
Scheduled selectors with a lower priority will be called before th
e ones that have a higher value.
Only one "update" selector could be scheduled per node (You can't
have 2 'update' selectors).
@since v0.99.3
*/
void scheduleUpdateWithPriority(int priority);
/* unschedules the "update" method.
@since v0.99.3
*/
void unscheduleUpdate(void);
/** schedules a selector.
The scheduled selector will be ticked every frame
*/
void schedule(SEL_SCHEDULE selector);
/** schedules a custom selector with an interval time in sec
onds.
If time is 0 it will be ticked every frame.
If time is 0, it is recommended to use 'scheduleUpdate' instead.
If the selector is already scheduled, then the interval parameter
will be updated without scheduling it again.
*/
void schedule(SEL_SCHEDULE selector, ccTime interval);
/** unschedules a custom selector.*/
void unschedule(SEL_SCHEDULE selector);
/** unschedule all scheduled selectors: custom selectors, an
d the 'update' selector.
Actions are not affected by this method.
@since v0.99.3
*/
void unscheduleAllSelectors(void);
/** resumes all scheduled selectors and actions.
Called internally by onEnter
*/
void resumeSchedulerAndActions(void);
/** pauses all scheduled selectors and actions.
Called internally by onExit
*/
void pauseSchedulerAndActions(void);
// transformation methods
/** Returns the matrix that transform the node's (local) spa
ce coordinates into the parent's space coordinates.
The matrix is in Pixels.
@since v0.7.1
*/
CCAffineTransform nodeToParentTransform(void);
/** Returns the matrix that transform parent's space coordin
ates to the node's (local) space coordinates.
The matrix is in Pixels.
@since v0.7.1
*/
CCAffineTransform parentToNodeTransform(void);
/** Retrusn the world affine transform matrix. The matrix is
in Pixels.
@since v0.7.1
*/
CCAffineTransform nodeToWorldTransform(void);
/** Returns the inverse world affine transform matrix. The m
atrix is in Pixels.
@since v0.7.1
*/
CCAffineTransform worldToNodeTransform(void);
/** Converts a Point to node (local) space coordinates. The
result is in Points.
@since v0.7.1
*/
CCPoint convertToNodeSpace(const CCPoint& worldPoint);
/** Converts a Point to world space coordinates. The result
is in Points.
@since v0.7.1
*/
CCPoint convertToWorldSpace(const CCPoint& nodePoint);
/** Converts a Point to node (local) space coordinates. The
result is in Points.
treating the returned/received node point as anchor relative.
@since v0.7.1
*/
CCPoint convertToNodeSpaceAR(const CCPoint& worldPoint);
/** Converts a local Point to world space coordinates.The re
sult is in Points.
treating the returned/received node point as anchor relative.
@since v0.7.1
*/
CCPoint convertToWorldSpaceAR(const CCPoint& nodePoint);
/** convenience methods which take a CCTouch instead of CCPo
int
@since v0.7.1
*/
CCPoint convertTouchToNodeSpace(CCTouch * touch);
/** converts a CCTouch (world coordinates) into a local coor
diante. This method is AR (Anchor Relative).
@since v0.7.1
*/
CCPoint convertTouchToNodeSpaceAR(CCTouch * touch);
};
}//namespace cocos2d
#endif // __PLATFOMR_CCNODE_H__ #endif // __PLATFOMR_CCNODE_H__
 End of changes. 4 change blocks. 
618 lines changed or deleted 643 lines changed or added


 CCNotificationCenter.h   CCNotificationCenter.h 
skipping to change at line 28 skipping to change at line 28
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CCNOTIFICATIONCENTER_H__ #ifndef __CCNOTIFICATIONCENTER_H__
#define __CCNOTIFICATIONCENTER_H__ #define __CCNOTIFICATIONCENTER_H__
#include "cocos2d.h" #include "cocoa/CCObject.h"
#include "cocoa/CCArray.h"
NS_CC_BEGIN; NS_CC_BEGIN;
class CC_DLL CCNotificationCenter : public CCObject class CC_DLL CCNotificationCenter : public CCObject
{ {
public: public:
CCNotificationCenter(); CCNotificationCenter();
~CCNotificationCenter(); ~CCNotificationCenter();
static CCNotificationCenter *sharedNotifCenter(void); static CCNotificationCenter *sharedNotificationCenter(void);
static void purgeNotifCenter(void); static void purgeNotificationCenter(void);
void addObserver(CCObject *target, void addObserver(CCObject *target,
SEL_CallFuncO selector, SEL_CallFuncO selector,
const char *name, const char *name,
CCObject *obj); CCObject *obj);
void removeObserver(CCObject *target,const char *name); void removeObserver(CCObject *target,const char *name);
void postNotification(const char *name); void postNotification(const char *name);
void postNotification(const char *name, CCObject *object); void postNotification(const char *name, CCObject *object);
 End of changes. 2 change blocks. 
3 lines changed or deleted 4 lines changed or added


 CCObject.h   CCObject.h 
skipping to change at line 25 skipping to change at line 25
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __COCOA_NSOBJECT_H__ #ifndef __CCOBJECT_H__
#define __COCOA_NSOBJECT_H__ #define __CCOBJECT_H__
#include "CCCommon.h" #include "platform/CCPlatformMacros.h"
#include "ccTypes.h"
NS_CC_BEGIN
/**
* @addtogroup base_nodes
* @{
*/
namespace cocos2d {
class CCZone; class CCZone;
class CCObject; class CCObject;
class CCString;
class CCNode; class CCNode;
class CCEvent; class CCEvent;
class CC_DLL CCCopying class CC_DLL CCCopying
{ {
public: public:
virtual CCObject* copyWithZone(CCZone* pZone); virtual CCObject* copyWithZone(CCZone* pZone);
}; };
class CC_DLL CCObject : public CCCopying class CC_DLL CCObject : public CCCopying
{ {
public: public:
// object id, CCScriptSupport need public m_uID // object id, CCScriptSupport need public m_uID
unsigned int m_uID; unsigned int m_uID;
// Lua reference id // Lua reference id
int m_nLuaID; int m_nLuaID;
protected: protected:
// count of refrence // count of refrence
unsigned int m_uReference; unsigned int m_uReference;
// is the object autoreleased // is the object autoreleased
bool m_bManaged; bool m_bManaged;
public: public:
CCObject(void); CCObject(void);
virtual ~CCObject(void); virtual ~CCObject(void);
void release(void); void release(void);
void retain(void); void retain(void);
CCObject* autorelease(void); CCObject* autorelease(void);
CCObject* copy(void); CCObject* copy(void);
bool isSingleRefrence(void); bool isSingleReference(void);
unsigned int retainCount(void); unsigned int retainCount(void);
virtual bool isEqual(const CCObject* pObject); virtual bool isEqual(const CCObject* pObject);
virtual void update(ccTime dt) {CC_UNUSED_PARAM(dt);}; virtual void update(float dt) {CC_UNUSED_PARAM(dt);};
friend class CCAutoreleasePool; friend class CCAutoreleasePool;
}; };
typedef void (CCObject::*SEL_SCHEDULE)(ccTime); typedef void (CCObject::*SEL_SCHEDULE)(float);
typedef void (CCObject::*SEL_CallFunc)(); typedef void (CCObject::*SEL_CallFunc)();
typedef void (CCObject::*SEL_CallFuncN)(CCNode*); typedef void (CCObject::*SEL_CallFuncN)(CCNode*);
typedef void (CCObject::*SEL_CallFuncND)(CCNode*, void*); typedef void (CCObject::*SEL_CallFuncND)(CCNode*, void*);
typedef void (CCObject::*SEL_CallFuncO)(CCObject*); typedef void (CCObject::*SEL_CallFuncO)(CCObject*);
typedef void (CCObject::*SEL_MenuHandler)(CCObject*); typedef void (CCObject::*SEL_MenuHandler)(CCObject*);
typedef void (CCObject::*SEL_EventHandler)(CCEvent*); typedef void (CCObject::*SEL_EventHandler)(CCEvent*);
typedef int (CCObject::*SEL_Compare)(CCObject*);
#define schedule_selector(_SELECTOR) (SEL_SCHEDULE)(&_SELECTOR) #define schedule_selector(_SELECTOR) (SEL_SCHEDULE)(&_SELECTOR)
#define callfunc_selector(_SELECTOR) (SEL_CallFunc)(&_SELECTOR) #define callfunc_selector(_SELECTOR) (SEL_CallFunc)(&_SELECTOR)
#define callfuncN_selector(_SELECTOR) (SEL_CallFuncN)(&_SELECTOR) #define callfuncN_selector(_SELECTOR) (SEL_CallFuncN)(&_SELECTOR)
#define callfuncND_selector(_SELECTOR) (SEL_CallFuncND)(&_SELECTOR) #define callfuncND_selector(_SELECTOR) (SEL_CallFuncND)(&_SELECTOR)
#define callfuncO_selector(_SELECTOR) (SEL_CallFuncO)(&_SELECTOR) #define callfuncO_selector(_SELECTOR) (SEL_CallFuncO)(&_SELECTOR)
#define menu_selector(_SELECTOR) (SEL_MenuHandler)(&_SELECTOR) #define menu_selector(_SELECTOR) (SEL_MenuHandler)(&_SELECTOR)
#define event_selector(_SELECTOR) (SEL_EventHandler)(&_SELECTOR) #define event_selector(_SELECTOR) (SEL_EventHandler)(&_SELECTOR)
#define compare_selector(_SELECTOR) (SEL_Compare)(&_SELECTOR)
// end of base_nodes group
/// @}
}//namespace cocos2d NS_CC_END
#endif // __COCOA_NSOBJECT_H__ #endif // __CCOBJECT_H__
 End of changes. 14 change blocks. 
13 lines changed or deleted 22 lines changed or added


 CCParallaxNode.h   CCParallaxNode.h 
skipping to change at line 29 skipping to change at line 29
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CCPARALLAX_NODE_H__ #ifndef __CCPARALLAX_NODE_H__
#define __CCPARALLAX_NODE_H__ #define __CCPARALLAX_NODE_H__
#include "CCNode.h" #include "base_nodes/CCNode.h"
/*#include "support/data_support/ccArray.h"*/ /*#include "support/data_support/ccArray.h"*/
namespace cocos2d { NS_CC_BEGIN
struct _ccArray;
/** @brief CCParallaxNode: A node that simulates a parallax scroller struct _ccArray;
The children will be moved faster / slower than the parent according /**
the the parallax ratio. * @addtogroup tilemap_parallax_nodes
* @{
*/
/** @brief CCParallaxNode: A node that simulates a parallax scroller
The children will be moved faster / slower than the parent according the th
e parallax ratio.
*/
class CC_DLL CCParallaxNode : public CCNode
{
/** array that holds the offset / ratio of the children */
CC_SYNTHESIZE(struct _ccArray *, m_pParallaxArray, ParallaxArray)
public:
/** Adds a child to the container with a z-order, a parallax ratio and
a position offset
It returns self, so you can chain several addChilds.
@since v0.8
*/
CCParallaxNode();
virtual ~CCParallaxNode();
//@deprecated: This interface will be deprecated sooner or later.
CC_DEPRECATED_ATTRIBUTE static CCParallaxNode * node();
static CCParallaxNode * create();
virtual void addChild(CCNode * child, unsigned int z, const CCPoint& pa
rallaxRatio, const CCPoint& positionOffset);
// super methods
virtual void addChild(CCNode * child, unsigned int zOrder, int tag);
virtual void removeChild(CCNode* child, bool cleanup);
virtual void removeAllChildrenWithCleanup(bool cleanup);
virtual void visit(void);
private:
CCPoint absolutePosition();
protected:
CCPoint m_tLastPosition;
};
*/ // end of tilemap_parallax_nodes group
class CC_DLL CCParallaxNode : public CCNode /// @}
{
/** array that holds the offset / ratio of the children */ NS_CC_END
CC_SYNTHESIZE(struct _ccArray *, m_pParallaxArray, ParallaxA
rray)
public:
/** Adds a child to the container with a z-order, a parallax
ratio and a position offset
It returns self, so you can chain several addChilds.
@since v0.8
*/
CCParallaxNode();
virtual ~CCParallaxNode();
static CCParallaxNode * node();
virtual void addChild(CCNode * child, unsigned int z, const
CCPoint& parallaxRatio, const CCPoint& positionOffset);
// super methods
virtual void addChild(CCNode * child, unsigned int zOrder, i
nt tag);
virtual void removeChild(CCNode* child, bool cleanup);
virtual void removeAllChildrenWithCleanup(bool cleanup);
virtual void visit(void);
private:
CCPoint absolutePosition();
protected:
CCPoint m_tLastPosition;
};
} // namespace cocos2d
#endif //__CCPARALLAX_NODE_H__ #endif //__CCPARALLAX_NODE_H__
 End of changes. 6 change blocks. 
36 lines changed or deleted 46 lines changed or added


 CCParticleExamples.h   CCParticleExamples.h 
skipping to change at line 29 skipping to change at line 29
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CCPARTICLE_EXAMPLE_H__ #ifndef __CCPARTICLE_EXAMPLE_H__
#define __CCPARTICLE_EXAMPLE_H__ #define __CCPARTICLE_EXAMPLE_H__
#include "platform/CCArchOptimalParticleSystem.h" #include "CCParticleSystemQuad.h"
namespace cocos2d { NS_CC_BEGIN
/**
* @addtogroup particle_nodes
* @{
*/
//! @brief A fire particle system //! @brief A fire particle system
class CC_DLL CCParticleFire : public ARCH_OPTIMAL_PARTICLE_SYSTEM class CC_DLL CCParticleFire : public CCParticleSystemQuad
{ {
public: public:
CCParticleFire(){} CCParticleFire(){}
virtual ~CCParticleFire(){} virtual ~CCParticleFire(){}
bool init(){ return initWithTotalParticles(250); } bool init(){ return initWithTotalParticles(250); }
virtual bool initWithTotalParticles(unsigned int numberOfParticles); virtual bool initWithTotalParticles(unsigned int numberOfParticles);
static CCParticleFire * node() static CCParticleFire * node()
{ {
CCParticleFire *pRet = new CCParticleFire(); return create();
if (pRet->init()) }
{
pRet->autorelease(); static CCParticleFire * create()
return pRet; {
} CCParticleFire *pRet = new CCParticleFire();
CC_SAFE_DELETE(pRet) if (pRet->init())
return NULL; {
} pRet->autorelease();
return pRet;
}
CC_SAFE_DELETE(pRet);
return NULL;
}
}; };
//! @brief A fireworks particle system //! @brief A fireworks particle system
class CC_DLL CCParticleFireworks : public ARCH_OPTIMAL_PARTICLE_SYSTEM class CC_DLL CCParticleFireworks : public CCParticleSystemQuad
{ {
public: public:
CCParticleFireworks(){} CCParticleFireworks(){}
virtual ~CCParticleFireworks(){} virtual ~CCParticleFireworks(){}
bool init(){ return initWithTotalParticles(1500); } bool init(){ return initWithTotalParticles(1500); }
virtual bool initWithTotalParticles(unsigned int numberOfParticles); virtual bool initWithTotalParticles(unsigned int numberOfParticles);
static CCParticleFireworks * node() static CCParticleFireworks * node()
{ {
CCParticleFireworks *pRet = new CCParticleFireworks(); return create();
if (pRet->init()) }
{
pRet->autorelease(); static CCParticleFireworks * create()
return pRet; {
} CCParticleFireworks *pRet = new CCParticleFireworks();
CC_SAFE_DELETE(pRet) if (pRet->init())
return NULL; {
} pRet->autorelease();
return pRet;
}
CC_SAFE_DELETE(pRet);
return NULL;
}
}; };
//! @brief A sun particle system //! @brief A sun particle system
class CC_DLL CCParticleSun : public ARCH_OPTIMAL_PARTICLE_SYSTEM class CC_DLL CCParticleSun : public CCParticleSystemQuad
{ {
public: public:
CCParticleSun(){} CCParticleSun(){}
virtual ~CCParticleSun(){} virtual ~CCParticleSun(){}
bool init(){ return initWithTotalParticles(350); } bool init(){ return initWithTotalParticles(350); }
virtual bool initWithTotalParticles(unsigned int numberOfParticles); virtual bool initWithTotalParticles(unsigned int numberOfParticles);
static CCParticleSun * node() static CCParticleSun * node()
{ {
CCParticleSun *pRet = new CCParticleSun(); return create();
if (pRet->init()) }
{ static CCParticleSun * create()
pRet->autorelease(); {
return pRet; CCParticleSun *pRet = new CCParticleSun();
} if (pRet->init())
CC_SAFE_DELETE(pRet) {
return NULL; pRet->autorelease();
} return pRet;
}
CC_SAFE_DELETE(pRet);
return NULL;
}
}; };
//! @brief A galaxy particle system //! @brief A galaxy particle system
class CC_DLL CCParticleGalaxy : public ARCH_OPTIMAL_PARTICLE_SYSTEM class CC_DLL CCParticleGalaxy : public CCParticleSystemQuad
{ {
public: public:
CCParticleGalaxy(){} CCParticleGalaxy(){}
virtual ~CCParticleGalaxy(){} virtual ~CCParticleGalaxy(){}
bool init(){ return initWithTotalParticles(200); } bool init(){ return initWithTotalParticles(200); }
virtual bool initWithTotalParticles(unsigned int numberOfParticles); virtual bool initWithTotalParticles(unsigned int numberOfParticles);
static CCParticleGalaxy * node() static CCParticleGalaxy * node()
{ {
CCParticleGalaxy *pRet = new CCParticleGalaxy(); return create();
if (pRet->init()) }
{
pRet->autorelease(); static CCParticleGalaxy * create()
return pRet; {
} CCParticleGalaxy *pRet = new CCParticleGalaxy();
CC_SAFE_DELETE(pRet) if (pRet->init())
return NULL; {
} pRet->autorelease();
return pRet;
}
CC_SAFE_DELETE(pRet);
return NULL;
}
}; };
//! @brief A flower particle system //! @brief A flower particle system
class CC_DLL CCParticleFlower : public ARCH_OPTIMAL_PARTICLE_SYSTEM class CC_DLL CCParticleFlower : public CCParticleSystemQuad
{ {
public: public:
CCParticleFlower(){} CCParticleFlower(){}
virtual ~CCParticleFlower(){} virtual ~CCParticleFlower(){}
bool init(){ return initWithTotalParticles(250); } bool init(){ return initWithTotalParticles(250); }
virtual bool initWithTotalParticles(unsigned int numberOfParticles); virtual bool initWithTotalParticles(unsigned int numberOfParticles);
static CCParticleFlower * node() static CCParticleFlower * node()
{ {
CCParticleFlower *pRet = new CCParticleFlower(); return create();
if (pRet->init()) }
{
pRet->autorelease(); static CCParticleFlower * create()
return pRet; {
} CCParticleFlower *pRet = new CCParticleFlower();
CC_SAFE_DELETE(pRet) if (pRet->init())
return NULL; {
} pRet->autorelease();
return pRet;
}
CC_SAFE_DELETE(pRet);
return NULL;
}
}; };
//! @brief A meteor particle system //! @brief A meteor particle system
class CC_DLL CCParticleMeteor : public ARCH_OPTIMAL_PARTICLE_SYSTEM class CC_DLL CCParticleMeteor : public CCParticleSystemQuad
{ {
public: public:
CCParticleMeteor(){} CCParticleMeteor(){}
virtual ~CCParticleMeteor(){} virtual ~CCParticleMeteor(){}
bool init(){ return initWithTotalParticles(150); } bool init(){ return initWithTotalParticles(150); }
virtual bool initWithTotalParticles(unsigned int numberOfParticles); virtual bool initWithTotalParticles(unsigned int numberOfParticles);
static CCParticleMeteor * node() static CCParticleMeteor * node()
{ {
CCParticleMeteor *pRet = new CCParticleMeteor(); return create();
if (pRet->init()) }
{ static CCParticleMeteor * create()
pRet->autorelease(); {
return pRet; CCParticleMeteor *pRet = new CCParticleMeteor();
} if (pRet->init())
CC_SAFE_DELETE(pRet) {
return NULL; pRet->autorelease();
} return pRet;
}
CC_SAFE_DELETE(pRet);
return NULL;
}
}; };
//! @brief An spiral particle system //! @brief An spiral particle system
class CC_DLL CCParticleSpiral : public ARCH_OPTIMAL_PARTICLE_SYSTEM class CC_DLL CCParticleSpiral : public CCParticleSystemQuad
{ {
public: public:
CCParticleSpiral(){} CCParticleSpiral(){}
virtual ~CCParticleSpiral(){} virtual ~CCParticleSpiral(){}
bool init(){ return initWithTotalParticles(500); } bool init(){ return initWithTotalParticles(500); }
virtual bool initWithTotalParticles(unsigned int numberOfParticles); virtual bool initWithTotalParticles(unsigned int numberOfParticles);
static CCParticleSpiral * node() static CCParticleSpiral * node()
{ {
CCParticleSpiral *pRet = new CCParticleSpiral(); return create();
if (pRet->init()) }
{ static CCParticleSpiral * create()
pRet->autorelease(); {
return pRet; CCParticleSpiral *pRet = new CCParticleSpiral();
} if (pRet->init())
CC_SAFE_DELETE(pRet) {
return NULL; pRet->autorelease();
} return pRet;
}
CC_SAFE_DELETE(pRet);
return NULL;
}
}; };
//! @brief An explosion particle system //! @brief An explosion particle system
class CC_DLL CCParticleExplosion : public ARCH_OPTIMAL_PARTICLE_SYSTEM class CC_DLL CCParticleExplosion : public CCParticleSystemQuad
{ {
public: public:
CCParticleExplosion(){} CCParticleExplosion(){}
virtual ~CCParticleExplosion(){} virtual ~CCParticleExplosion(){}
bool init(){ return initWithTotalParticles(700); } bool init(){ return initWithTotalParticles(700); }
virtual bool initWithTotalParticles(unsigned int numberOfParticles); virtual bool initWithTotalParticles(unsigned int numberOfParticles);
static CCParticleExplosion * node() static CCParticleExplosion * node()
{ {
CCParticleExplosion *pRet = new CCParticleExplosion(); return create();
if (pRet->init()) }
{ static CCParticleExplosion * create()
pRet->autorelease(); {
return pRet; CCParticleExplosion *pRet = new CCParticleExplosion();
} if (pRet->init())
CC_SAFE_DELETE(pRet) {
return NULL; pRet->autorelease();
} return pRet;
}
CC_SAFE_DELETE(pRet);
return NULL;
}
}; };
//! @brief An smoke particle system //! @brief An smoke particle system
class CC_DLL CCParticleSmoke : public ARCH_OPTIMAL_PARTICLE_SYSTEM class CC_DLL CCParticleSmoke : public CCParticleSystemQuad
{ {
public: public:
CCParticleSmoke(){} CCParticleSmoke(){}
virtual ~CCParticleSmoke(){} virtual ~CCParticleSmoke(){}
bool init(){ return initWithTotalParticles(200); } bool init(){ return initWithTotalParticles(200); }
virtual bool initWithTotalParticles(unsigned int numberOfParticles); virtual bool initWithTotalParticles(unsigned int numberOfParticles);
static CCParticleSmoke * node() static CCParticleSmoke * node()
{ {
CCParticleSmoke *pRet = new CCParticleSmoke(); return create();
if (pRet->init()) }
{ static CCParticleSmoke * create()
pRet->autorelease(); {
return pRet; CCParticleSmoke *pRet = new CCParticleSmoke();
} if (pRet->init())
CC_SAFE_DELETE(pRet) {
return NULL; pRet->autorelease();
} return pRet;
}
CC_SAFE_DELETE(pRet);
return NULL;
}
}; };
//! @brief An snow particle system //! @brief An snow particle system
class CC_DLL CCParticleSnow : public ARCH_OPTIMAL_PARTICLE_SYSTEM class CC_DLL CCParticleSnow : public CCParticleSystemQuad
{ {
public: public:
CCParticleSnow(){} CCParticleSnow(){}
virtual ~CCParticleSnow(){} virtual ~CCParticleSnow(){}
bool init(){ return initWithTotalParticles(700); } bool init(){ return initWithTotalParticles(700); }
virtual bool initWithTotalParticles(unsigned int numberOfParticles); virtual bool initWithTotalParticles(unsigned int numberOfParticles);
static CCParticleSnow * node() static CCParticleSnow * node()
{ {
CCParticleSnow *pRet = new CCParticleSnow(); return create();
if (pRet->init()) }
{
pRet->autorelease(); static CCParticleSnow * create()
return pRet; {
} CCParticleSnow *pRet = new CCParticleSnow();
CC_SAFE_DELETE(pRet) if (pRet->init())
return NULL; {
} pRet->autorelease();
return pRet;
}
CC_SAFE_DELETE(pRet);
return NULL;
}
}; };
//! @brief A rain particle system //! @brief A rain particle system
class CC_DLL CCParticleRain : public ARCH_OPTIMAL_PARTICLE_SYSTEM class CC_DLL CCParticleRain : public CCParticleSystemQuad
{ {
public: public:
CCParticleRain(){} CCParticleRain(){}
virtual ~CCParticleRain(){} virtual ~CCParticleRain(){}
bool init(){ return initWithTotalParticles(1000); } bool init(){ return initWithTotalParticles(1000); }
virtual bool initWithTotalParticles(unsigned int numberOfParticles); virtual bool initWithTotalParticles(unsigned int numberOfParticles);
static CCParticleRain * node() static CCParticleRain * node()
{ {
CCParticleRain *pRet = new CCParticleRain(); return create();
if (pRet->init()) }
{ static CCParticleRain * create()
pRet->autorelease(); {
return pRet; CCParticleRain *pRet = new CCParticleRain();
} if (pRet->init())
CC_SAFE_DELETE(pRet) {
return NULL; pRet->autorelease();
} return pRet;
}
CC_SAFE_DELETE(pRet);
return NULL;
}
}; };
}// namespace cocos2d // end of particle_nodes group
/// @}
NS_CC_END
#endif //__CCPARTICLE_EXAMPLE_H__ #endif //__CCPARTICLE_EXAMPLE_H__
 End of changes. 25 change blocks. 
179 lines changed or deleted 236 lines changed or added


 CCParticleSystem.h   CCParticleSystem.h 
/************************************************************************** ** /************************************************************************** **
Copyright (c) 2010-2011 cocos2d-x.org Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011 Zynga Inc. Copyright (c) 2011 Zynga Inc.
http://www.cocos2d-x.org http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a cop y Permission is hereby granted, free of charge, to any person obtaining a cop y
of this software and associated documentation files (the "Software"), to de al of this software and associated documentation files (the "Software"), to de al
in the Software without restriction, including without limitation the right s in the Software without restriction, including without limitation the right s
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
skipping to change at line 30 skipping to change at line 30
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CCPARTICLE_SYSTEM_H__ #ifndef __CCPARTICLE_SYSTEM_H__
#define __CCPARTICLE_SYSTEM_H__ #define __CCPARTICLE_SYSTEM_H__
#include "CCProtocols.h" #include "CCProtocols.h"
#include "CCNode.h" #include "base_nodes/CCNode.h"
#include "CCMutableDictionary.h" #include "cocoa/CCDictionary.h"
#include "CCString.h" #include "cocoa/CCString.h"
namespace cocos2d { NS_CC_BEGIN
#if CC_ENABLE_PROFILERS /**
class CCProfilingTimer; * @addtogroup particle_nodes
#endif * @{
*/
class CCParticleBatchNode;
//* @enum //* @enum
enum { enum {
/** The Particle emitter lives forever */ /** The Particle emitter lives forever */
kCCParticleDurationInfinity = -1, kCCParticleDurationInfinity = -1,
/** The starting size of the particle is equal to the ending size */ /** The starting size of the particle is equal to the ending size */
kCCParticleStartSizeEqualToEndSize = -1, kCCParticleStartSizeEqualToEndSize = -1,
/** The starting radius of the particle is equal to the ending radiu /** The starting radius of the particle is equal to the ending radius *
s */ /
kCCParticleStartRadiusEqualToEndRadius = -1, kCCParticleStartRadiusEqualToEndRadius = -1,
// backward compatible // backward compatible
kParticleStartSizeEqualToEndSize = kCCParticleStartSizeEqualToEndSiz kParticleStartSizeEqualToEndSize = kCCParticleStartSizeEqualToEndSize,
e, kParticleDurationInfinity = kCCParticleDurationInfinity,
kParticleDurationInfinity = kCCParticleDurationInfinity,
}; };
//* @enum //* @enum
enum { enum {
/** Gravity mode (A mode) */ /** Gravity mode (A mode) */
kCCParticleModeGravity, kCCParticleModeGravity,
/** Radius mode (B mode) */ /** Radius mode (B mode) */
kCCParticleModeRadius, kCCParticleModeRadius,
}; };
/** @typedef tCCPositionType /** @typedef tCCPositionType
possible types of particle positions possible types of particle positions
*/ */
typedef enum { typedef enum {
/** Living particles are attached to the world and are unaffected by em itter repositioning. */ /** Living particles are attached to the world and are unaffected by em itter repositioning. */
kCCPositionTypeFree, kCCPositionTypeFree,
/** Living particles are attached to the world but will follow the emit ter repositioning. /** Living particles are attached to the world but will follow the emit ter repositioning.
Use case: Attach an emitter to an sprite, and you want that the emitter follows the sprite. Use case: Attach an emitter to an sprite, and you want that the emitter follows the sprite.
*/ */
kCCPositionTypeRelative, kCCPositionTypeRelative,
/** Living particles are attached to the emitter and are translated alo ng with it. */ /** Living particles are attached to the emitter and are translated alo ng with it. */
kCCPositionTypeGrouped, kCCPositionTypeGrouped,
}tCCPositionType; }tCCPositionType;
// backward compatible // backward compatible
enum { enum {
kPositionTypeFree = kCCPositionTypeFree, kPositionTypeFree = kCCPositionTypeFree,
kPositionTypeGrouped = kCCPositionTypeGrouped, kPositionTypeGrouped = kCCPositionTypeGrouped,
}; };
/** /**
Structure that contains the values of each particle Structure that contains the values of each particle
*/ */
typedef struct sCCParticle { typedef struct sCCParticle {
CCPoint pos; CCPoint pos;
CCPoint startPos; CCPoint startPos;
ccColor4F color; ccColor4F color;
ccColor4F deltaColor; ccColor4F deltaColor;
float size; float size;
float deltaSize; float deltaSize;
float rotation; float rotation;
float deltaRotation; float deltaRotation;
ccTime timeToLive; float timeToLive;
//! Mode A: gravity, direction, radial accel, tangential accel unsigned int atlasIndex;
struct {
CCPoint dir; //! Mode A: gravity, direction, radial accel, tangential accel
float radialAccel; struct {
float tangentialAccel; CCPoint dir;
} modeA; float radialAccel;
float tangentialAccel;
//! Mode B: radius mode } modeA;
struct {
float angle; //! Mode B: radius mode
float degreesPerSecond; struct {
float radius; float angle;
float deltaRadius; float degreesPerSecond;
} modeB; float radius;
float deltaRadius;
} modeB;
}tCCParticle; }tCCParticle;
//typedef void (*CC_UPDATE_PARTICLE_IMP)(id, SEL, tCCParticle*, CCPoint); //typedef void (*CC_UPDATE_PARTICLE_IMP)(id, SEL, tCCParticle*, CCPoint);
class CCTexture2D; class CCTexture2D;
/** @brief Particle System base class. /** @brief Particle System base class.
Attributes of a Particle System: Attributes of a Particle System:
- emmision rate of the particles - emmision rate of the particles
skipping to change at line 172 skipping to change at line 177
@code @code
emitter.radialAccel = 15; emitter.radialAccel = 15;
emitter.startSpin = 0; emitter.startSpin = 0;
@endcode @endcode
*/ */
class CC_DLL CCParticleSystem : public CCNode, public CCTextureProtocol class CC_DLL CCParticleSystem : public CCNode, public CCTextureProtocol
{ {
protected: protected:
std::string m_sPlistFile; std::string m_sPlistFile;
//! time elapsed since the start of the system (in seconds) //! time elapsed since the start of the system (in seconds)
float m_fElapsed; float m_fElapsed;
// Different modes // Different modes
//! Mode A:Gravity + Tangential Accel + Radial Accel //! Mode A:Gravity + Tangential Accel + Radial Accel
struct { struct {
/** Gravity value. Only available in 'Gravity' mode. */ /** Gravity value. Only available in 'Gravity' mode. */
CCPoint gravity; CCPoint gravity;
/** speed of each particle. Only available in 'Gravity' mode /** speed of each particle. Only available in 'Gravity' mode. */
. */ float speed;
float speed; /** speed variance of each particle. Only available in 'Gravity' mo
/** speed variance of each particle. Only available in 'Grav de. */
ity' mode. */ float speedVar;
float speedVar; /** tangential acceleration of each particle. Only available in 'Gr
/** tangential acceleration of each particle. Only available avity' mode. */
in 'Gravity' mode. */ float tangentialAccel;
float tangentialAccel; /** tangential acceleration variance of each particle. Only availab
/** tangential acceleration variance of each particle. Only le in 'Gravity' mode. */
available in 'Gravity' mode. */ float tangentialAccelVar;
float tangentialAccelVar; /** radial acceleration of each particle. Only available in 'Gravit
/** radial acceleration of each particle. Only available in y' mode. */
'Gravity' mode. */ float radialAccel;
float radialAccel; /** radial acceleration variance of each particle. Only available i
/** radial acceleration variance of each particle. Only avai n 'Gravity' mode. */
lable in 'Gravity' mode. */ float radialAccelVar;
float radialAccelVar; } modeA;
} modeA;
//! Mode B: circular movement (gravity, radial accel and tangential acc
//! Mode B: circular movement (gravity, radial accel and tangential el don't are not used in this mode)
accel don't are not used in this mode) struct {
struct { /** The starting radius of the particles. Only available in 'Radius
/** The starting radius of the particles. Only available in ' mode. */
'Radius' mode. */ float startRadius;
float startRadius; /** The starting radius variance of the particles. Only available i
/** The starting radius variance of the particles. Only avai n 'Radius' mode. */
lable in 'Radius' mode. */ float startRadiusVar;
float startRadiusVar; /** The ending radius of the particles. Only available in 'Radius'
/** The ending radius of the particles. Only available in 'R mode. */
adius' mode. */ float endRadius;
float endRadius; /** The ending radius variance of the particles. Only available in
/** The ending radius variance of the particles. Only availa 'Radius' mode. */
ble in 'Radius' mode. */ float endRadiusVar;
float endRadiusVar; /** Number of degress to rotate a particle around the source pos pe
/** Number of degress to rotate a particle around the source r second. Only available in 'Radius' mode. */
pos per second. Only available in 'Radius' mode. */ float rotatePerSecond;
float rotatePerSecond; /** Variance in degrees for rotatePerSecond. Only available in 'Rad
/** Variance in degrees for rotatePerSecond. Only available ius' mode. */
in 'Radius' mode. */ float rotatePerSecondVar;
float rotatePerSecondVar; } modeB;
} modeB;
//! Array of particles
//! Array of particles tCCParticle *m_pParticles;
tCCParticle *m_pParticles;
// color modulate
// color modulate // BOOL colorModulate;
// BOOL colorModulate;
//! How many particles can be emitted per second
//! How many particles can be emitted per second float m_fEmitCounter;
float m_fEmitCounter;
//! particle idx
//! particle idx unsigned int m_uParticleIdx;
unsigned int m_uParticleIdx;
// Optimization
// Optimization //CC_UPDATE_PARTICLE_IMP updateParticleImp;
//CC_UPDATE_PARTICLE_IMP updateParticleImp; //SEL updateParticleSel;
//SEL updateParticleSel;
/** weak reference to the CCSpriteBatchNode that renders the CCSprite *
// profiling /
#if CC_ENABLE_PROFILERS CC_PROPERTY(CCParticleBatchNode*, m_pBatchNode, BatchNode);
CCProfilingTimer* m_pProfilingTimer;
#endif // index of system in batch node array
CC_SYNTHESIZE(unsigned int, m_uAtlasIndex, AtlasIndex);
/** Is the emitter active */
CC_PROPERTY_READONLY(bool, m_bIsActive, IsActive) //true if scaled or rotated
/** Quantity of particles that are being simulated at the moment */ bool m_bTransformSystemDirty;
CC_PROPERTY_READONLY(unsigned int, m_uParticleCount, ParticleCount) // Number of allocated particles
/** How many seconds the emitter wil run. -1 means 'forever' */ unsigned int m_uAllocatedParticles;
CC_PROPERTY(float, m_fDuration, Duration)
/** sourcePosition of the emitter */ /** Is the emitter active */
CC_PROPERTY_PASS_BY_REF(CCPoint, m_tSourcePosition, SourcePosition) bool m_bIsActive;
/** Position variance of the emitter */ /** Quantity of particles that are being simulated at the moment */
CC_PROPERTY_PASS_BY_REF(CCPoint, m_tPosVar, PosVar) CC_PROPERTY_READONLY(unsigned int, m_uParticleCount, ParticleCount)
/** life, and life variation of each particle */ /** How many seconds the emitter wil run. -1 means 'forever' */
CC_PROPERTY(float, m_fLife, Life) CC_PROPERTY(float, m_fDuration, Duration)
/** life variance of each particle */ /** sourcePosition of the emitter */
CC_PROPERTY(float, m_fLifeVar, LifeVar) CC_PROPERTY_PASS_BY_REF(CCPoint, m_tSourcePosition, SourcePosition)
/** angle and angle variation of each particle */ /** Position variance of the emitter */
CC_PROPERTY(float, m_fAngle, Angle) CC_PROPERTY_PASS_BY_REF(CCPoint, m_tPosVar, PosVar)
/** angle variance of each particle */ /** life, and life variation of each particle */
CC_PROPERTY(float, m_fAngleVar, AngleVar) CC_PROPERTY(float, m_fLife, Life)
/** life variance of each particle */
CC_PROPERTY(float, m_fLifeVar, LifeVar)
/** angle and angle variation of each particle */
CC_PROPERTY(float, m_fAngle, Angle)
/** angle variance of each particle */
CC_PROPERTY(float, m_fAngleVar, AngleVar)
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
public: public:
// mode A // mode A
virtual const CCPoint& getGravity(); virtual const CCPoint& getGravity();
virtual void setGravity(const CCPoint& g); virtual void setGravity(const CCPoint& g);
virtual float getSpeed(); virtual float getSpeed();
virtual void setSpeed(float speed); virtual void setSpeed(float speed);
virtual float getSpeedVar(); virtual float getSpeedVar();
virtual void setSpeedVar(float speed); virtual void setSpeedVar(float speed);
virtual float getTangentialAccel(); virtual float getTangentialAccel();
virtual void setTangentialAccel(float t); virtual void setTangentialAccel(float t);
virtual float getTangentialAccelVar(); virtual float getTangentialAccelVar();
virtual void setTangentialAccelVar(float t); virtual void setTangentialAccelVar(float t);
virtual float getRadialAccel(); virtual float getRadialAccel();
virtual void setRadialAccel(float t); virtual void setRadialAccel(float t);
virtual float getRadialAccelVar(); virtual float getRadialAccelVar();
virtual void setRadialAccelVar(float t); virtual void setRadialAccelVar(float t);
// mode B // mode B
virtual float getStartRadius(); virtual float getStartRadius();
virtual void setStartRadius(float startRadius); virtual void setStartRadius(float startRadius);
virtual float getStartRadiusVar(); virtual float getStartRadiusVar();
virtual void setStartRadiusVar(float startRadiusVar); virtual void setStartRadiusVar(float startRadiusVar);
virtual float getEndRadius(); virtual float getEndRadius();
virtual void setEndRadius(float endRadius); virtual void setEndRadius(float endRadius);
virtual float getEndRadiusVar(); virtual float getEndRadiusVar();
virtual void setEndRadiusVar(float endRadiusVar); virtual void setEndRadiusVar(float endRadiusVar);
virtual float getRotatePerSecond(); virtual float getRotatePerSecond();
virtual void setRotatePerSecond(float degrees); virtual void setRotatePerSecond(float degrees);
virtual float getRotatePerSecondVar(); virtual float getRotatePerSecondVar();
virtual void setRotatePerSecondVar(float degrees); virtual void setRotatePerSecondVar(float degrees);
virtual void setScale(float s);
virtual void setRotation(float newRotation);
virtual void setScaleX(float newScaleX);
virtual void setScaleY(float newScaleY);
virtual bool isActive();
virtual bool isBlendAdditive();
virtual void setBlendAdditive(bool value);
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
/** start size in pixels of each particle */ /** start size in pixels of each particle */
CC_PROPERTY(float, m_fStartSize, StartSize) CC_PROPERTY(float, m_fStartSize, StartSize)
/** size variance in pixels of each particle */ /** size variance in pixels of each particle */
CC_PROPERTY(float, m_fStartSizeVar, StartSizeVar) CC_PROPERTY(float, m_fStartSizeVar, StartSizeVar)
/** end size in pixels of each particle */ /** end size in pixels of each particle */
CC_PROPERTY(float, m_fEndSize, EndSize) CC_PROPERTY(float, m_fEndSize, EndSize)
/** end size variance in pixels of each particle */ /** end size variance in pixels of each particle */
CC_PROPERTY(float, m_fEndSizeVar, EndSizeVar) CC_PROPERTY(float, m_fEndSizeVar, EndSizeVar)
/** start color of each particle */ /** start color of each particle */
CC_PROPERTY_PASS_BY_REF(ccColor4F, m_tStartColor, StartColor) CC_PROPERTY_PASS_BY_REF(ccColor4F, m_tStartColor, StartColor)
/** start color variance of each particle */ /** start color variance of each particle */
CC_PROPERTY_PASS_BY_REF(ccColor4F, m_tStartColorVar, StartColorVar) CC_PROPERTY_PASS_BY_REF(ccColor4F, m_tStartColorVar, StartColorVar)
/** end color and end color variation of each particle */ /** end color and end color variation of each particle */
CC_PROPERTY_PASS_BY_REF(ccColor4F, m_tEndColor, EndColor) CC_PROPERTY_PASS_BY_REF(ccColor4F, m_tEndColor, EndColor)
/** end color variance of each particle */ /** end color variance of each particle */
CC_PROPERTY_PASS_BY_REF(ccColor4F, m_tEndColorVar, EndColorVar) CC_PROPERTY_PASS_BY_REF(ccColor4F, m_tEndColorVar, EndColorVar)
//* initial angle of each particle //* initial angle of each particle
CC_PROPERTY(float, m_fStartSpin, StartSpin) CC_PROPERTY(float, m_fStartSpin, StartSpin)
//* initial angle of each particle //* initial angle of each particle
CC_PROPERTY(float, m_fStartSpinVar, StartSpinVar) CC_PROPERTY(float, m_fStartSpinVar, StartSpinVar)
//* initial angle of each particle //* initial angle of each particle
CC_PROPERTY(float, m_fEndSpin, EndSpin) CC_PROPERTY(float, m_fEndSpin, EndSpin)
//* initial angle of each particle //* initial angle of each particle
CC_PROPERTY(float, m_fEndSpinVar, EndSpinVar) CC_PROPERTY(float, m_fEndSpinVar, EndSpinVar)
/** emission rate of the particles */ /** emission rate of the particles */
CC_PROPERTY(float, m_fEmissionRate, EmissionRate) CC_PROPERTY(float, m_fEmissionRate, EmissionRate)
/** maximum particles of the system */ /** maximum particles of the system */
CC_PROPERTY(unsigned int, m_uTotalParticles, TotalParticles) CC_PROPERTY(unsigned int, m_uTotalParticles, TotalParticles)
/** conforms to CocosNodeTexture protocol */ /** conforms to CocosNodeTexture protocol */
CC_PROPERTY(CCTexture2D*, m_pTexture, Texture) CC_PROPERTY(CCTexture2D*, m_pTexture, Texture)
/** conforms to CocosNodeTexture protocol */ /** conforms to CocosNodeTexture protocol */
CC_PROPERTY(ccBlendFunc, m_tBlendFunc, BlendFunc) CC_PROPERTY(ccBlendFunc, m_tBlendFunc, BlendFunc)
/** whether or not the particles are using blend additive. /** does the alpha value modify color */
If enabled, the following blending function will be used. CC_PROPERTY(bool, m_bOpacityModifyRGB, OpacityModifyRGB)
@code
source blend function = GL_SRC_ALPHA; /** whether or not the particles are using blend additive.
dest blend function = GL_ONE; If enabled, the following blending function will be used.
@endcode @code
*/ source blend function = GL_SRC_ALPHA;
CC_PROPERTY(bool, m_bIsBlendAdditive, IsBlendAdditive) dest blend function = GL_ONE;
/** particles movement type: Free or Grouped @endcode
@since v0.8 */
*/ bool m_bIsBlendAdditive;
CC_PROPERTY(tCCPositionType, m_ePositionType, PositionType) /** particles movement type: Free or Grouped
/** whether or not the node will be auto-removed when it has no part @since v0.8
icles left. */
By default it is false. CC_PROPERTY(tCCPositionType, m_ePositionType, PositionType)
@since v0.8 /** whether or not the node will be auto-removed when it has no particl
*/ es left.
CC_PROPERTY(bool, m_bIsAutoRemoveOnFinish, IsAutoRemoveOnFinish) By default it is false.
/** Switch between different kind of emitter modes: @since v0.8
- kCCParticleModeGravity: uses gravity, speed, radial and tangential */
acceleration protected:
- kCCParticleModeRadius: uses radius movement + rotation bool m_bIsAutoRemoveOnFinish;
*/ public:
CC_PROPERTY(int, m_nEmitterMode, EmitterMode) virtual bool isAutoRemoveOnFinish();
virtual void setAutoRemoveOnFinish(bool var);
/** Switch between different kind of emitter modes:
- kCCParticleModeGravity: uses gravity, speed, radial and tangential ac
celeration
- kCCParticleModeRadius: uses radius movement + rotation
*/
CC_PROPERTY(int, m_nEmitterMode, EmitterMode)
public: public:
CCParticleSystem(); CCParticleSystem();
virtual ~CCParticleSystem(); virtual ~CCParticleSystem();
/** creates an initializes a CCParticleSystem from a plist file. /** creates an initializes a CCParticleSystem from a plist file.
This plist files can be creted manually or with Particle Designer: This plist files can be creted manually or with Particle Designer:
http://particledesigner.71squared.com/ http://particledesigner.71squared.com/
@since v0.99.3 @deprecated: This interface will be deprecated sooner or later.
*/ @since v0.99.3
static CCParticleSystem * particleWithFile(const char *plistFile); */
CC_DEPRECATED_ATTRIBUTE static CCParticleSystem * particleWithFile(cons
/** initializes a CCParticleSystem from a plist file. t char *plistFile);
This plist files can be creted manually or with Particle Designer:
http://particledesigner.71squared.com/ /** creates an initializes a CCParticleSystem from a plist file.
@since v0.99.3 This plist files can be creted manually or with Particle Designer:
*/ http://particledesigner.71squared.com/
bool initWithFile(const char *plistFile); @since v2.0
*/
/** initializes a CCQuadParticleSystem from a CCDictionary. static CCParticleSystem * create(const char *plistFile);
@since v0.99.3
*/ /** initializes a CCParticleSystem*/
bool initWithDictionary(CCDictionary<std::string, CCObject*> *dictio bool init();
nary); /** initializes a CCParticleSystem from a plist file.
This plist files can be creted manually or with Particle Designer:
//! Initializes a system with a fixed number of particles http://particledesigner.71squared.com/
virtual bool initWithTotalParticles(unsigned int numberOfParticles); @since v0.99.3
//! Add a particle to the emitter */
bool addParticle(); bool initWithFile(const char *plistFile);
//! Initializes a particle
void initParticle(tCCParticle* particle); /** initializes a CCQuadParticleSystem from a CCDictionary.
//! stop emitting particles. Running particles will continue to run @since v0.99.3
until they die */
void stopSystem(); bool initWithDictionary(CCDictionary *dictionary);
//! Kill all living particles.
void resetSystem(); //! Initializes a system with a fixed number of particles
//! whether or not the system is full virtual bool initWithTotalParticles(unsigned int numberOfParticles);
bool isFull(); //! Add a particle to the emitter
bool addParticle();
//! should be overriden by subclasses //! Initializes a particle
virtual void updateQuadWithParticle(tCCParticle* particle, const CCP void initParticle(tCCParticle* particle);
oint& newPosition); //! stop emitting particles. Running particles will continue to run unt
//! should be overriden by subclasses il they die
virtual void postStep(); void stopSystem();
//! Kill all living particles.
virtual void update(ccTime dt); void resetSystem();
private: //! whether or not the system is full
/** Private method, return the string found by key in dict. bool isFull();
@return "" if not found; return the string if found.
*/ //! should be overriden by subclasses
inline const char * valueForKey(const char *key, CCDictionary<std::s virtual void updateQuadWithParticle(tCCParticle* particle, const CCPoin
tring, CCObject*> *dict) t& newPosition);
{ //! should be overriden by subclasses
if (dict) virtual void postStep();
{
CCString *pString = (CCString*)dict->objectForKey(st virtual void update(float dt);
d::string(key)); virtual void updateWithNoTime(void);
return pString ? pString->m_sString.c_str() : "";
} protected:
return ""; virtual void updateBlendFunc();
}
}; };
}// namespace cocos2d // end of particle_nodes group
/// @}
NS_CC_END
#endif //__CCPARTICLE_SYSTEM_H__ #endif //__CCPARTICLE_SYSTEM_H__
 End of changes. 20 change blocks. 
288 lines changed or deleted 317 lines changed or added


 CCParticleSystemQuad.h   CCParticleSystemQuad.h 
/************************************************************************** ** /************************************************************************** **
Copyright (c) 2010-2011 cocos2d-x.org Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2009 Leonardo Kasperavičius Copyright (c) 2009 Leonardo Kasperavičius
Copyright (c) 2011 ynga Inc. Copyright (c) 2011 Zynga Inc.
http://www.cocos2d-x.org http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a cop y Permission is hereby granted, free of charge, to any person obtaining a cop y
of this software and associated documentation files (the "Software"), to de al of this software and associated documentation files (the "Software"), to de al
in the Software without restriction, including without limitation the right s in the Software without restriction, including without limitation the right s
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
skipping to change at line 32 skipping to change at line 32
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CC_PARTICLE_SYSTEM_QUAD_H__ #ifndef __CC_PARTICLE_SYSTEM_QUAD_H__
#define __CC_PARTICLE_SYSTEM_QUAD_H__ #define __CC_PARTICLE_SYSTEM_QUAD_H__
#include "CCParticleSystem.h" #include "CCParticleSystem.h"
namespace cocos2d { NS_CC_BEGIN
class CCSpriteFrame; class CCSpriteFrame;
/**
* @addtogroup particle_nodes
* @{
*/
/** @brief CCParticleSystemQuad is a subclass of CCParticleSystem /** @brief CCParticleSystemQuad is a subclass of CCParticleSystem
It includes all the features of ParticleSystem. It includes all the features of ParticleSystem.
Special features and Limitations: Special features and Limitations:
- Particle size can be any float number. - Particle size can be any float number.
- The system can be scaled - The system can be scaled
- The particles can be rotated - The particles can be rotated
- On 1st and 2nd gen iPhones: It is only a bit slower that CCParticleSystem
Point
- On 3rd gen iPhone and iPads: It is MUCH faster than CCParticleSystemPoint
- It consumes more RAM and more GPU memory than CCParticleSystemPoint
- It supports subrects - It supports subrects
- It supports batched rendering since 1.1
@since v0.8 @since v0.8
*/ */
class CC_DLL CCParticleSystemQuad : public CCParticleSystem class CC_DLL CCParticleSystemQuad : public CCParticleSystem
{ {
protected: protected:
ccV2F_C4B_T2F_Quad *m_pQuads; // quads to be rende ccV3F_C4B_T2F_Quad *m_pQuads; // quads to be rendered
red GLushort *m_pIndices; // indices
GLushort *m_pIndices; // indices
#if CC_USES_VBO #if CC_TEXTURE_ATLAS_USE_VAO
GLuint m_uQuadsID; // VBO id GLuint m_uVAOname;
#endif #endif
GLuint m_pBuffersVBO[2]; //0: vertex 1: indices
public: public:
CCParticleSystemQuad() CCParticleSystemQuad();
:m_pQuads(NULL) virtual ~CCParticleSystemQuad();
,m_pIndices(NULL)
{} /** creates an initializes a CCParticleSystemQuad from a plist file.
virtual ~CCParticleSystemQuad(); This plist files can be creted manually or with Particle Designer:
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCParticleSystemQuad * particleWithFile(
const char *plistFile);
/** creates an initializes a CCParticleSystemQuad from a plist file. /** creates an initializes a CCParticleSystemQuad from a plist file.
This plist files can be creted manually or with Particle Designer: This plist files can be creted manually or with Particle Designer:
*/ */
static CCParticleSystemQuad * particleWithFile(const char *plistFile); static CCParticleSystemQuad * create(const char *plistFile);
/** initialices the indices for the vertices*/ /** initialices the indices for the vertices*/
void initIndices(); void setupIndices();
/** initilizes the texture with a rectangle measured Points */ /** initilizes the texture with a rectangle measured Points */
void initTexCoordsWithRect(const CCRect& rect); void initTexCoordsWithRect(const CCRect& rect);
/** Sets a new CCSpriteFrame as particle. /** Sets a new CCSpriteFrame as particle.
WARNING: this method is experimental. Use setTexture:withRect instea WARNING: this method is experimental. Use setTexture:withRect instead.
d. @since v0.99.4
@since v0.99.4 */
*/ void setDisplayFrame(CCSpriteFrame *spriteFrame);
void setDisplayFrame(CCSpriteFrame *spriteFrame);
/** Sets a new texture with a rect. The rect is in Points. /** Sets a new texture with a rect. The rect is in Points.
@since v0.99.4 @since v0.99.4
*/ */
void setTextureWithRect(CCTexture2D *texture, const CCRect& rect); void setTextureWithRect(CCTexture2D *texture, const CCRect& rect);
// super methods // super methods
virtual bool initWithTotalParticles(unsigned int numberOfParticles); virtual bool initWithTotalParticles(unsigned int numberOfParticles);
virtual void setTexture(CCTexture2D* texture); virtual void setTexture(CCTexture2D* texture);
virtual void updateQuadWithParticle(tCCParticle* particle, const CCP virtual void updateQuadWithParticle(tCCParticle* particle, const CCPoin
oint& newPosition); t& newPosition);
virtual void postStep(); virtual void postStep();
virtual void draw(); virtual void draw();
virtual void setBatchNode(CCParticleBatchNode* batchNode);
virtual void setTotalParticles(unsigned int tp);
/** listen the event that coming to foreground on Android
*/
void listenBackToForeground(CCObject *obj);
//@deprecated: This interface will be deprecated sooner or later.
CC_DEPRECATED_ATTRIBUTE static CCParticleSystemQuad * node();
static CCParticleSystemQuad * create();
private:
#if CC_TEXTURE_ATLAS_USE_VAO
void setupVBOandVAO();
#else
void setupVBO();
#endif
bool allocMemory();
}; };
}// namespace cocos2d // end of particle_nodes group
/// @}
NS_CC_END
#endif //__CC_PARTICLE_SYSTEM_QUAD_H__ #endif //__CC_PARTICLE_SYSTEM_QUAD_H__
 End of changes. 15 change blocks. 
38 lines changed or deleted 67 lines changed or added


 CCPlatformConfig.h   CCPlatformConfig.h 
skipping to change at line 43 skipping to change at line 43
*/ */
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
// pre configure // pre configure
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
// define supported target platform macro which CC uses. // define supported target platform macro which CC uses.
#define CC_PLATFORM_UNKNOWN 0 #define CC_PLATFORM_UNKNOWN 0
#define CC_PLATFORM_IOS 1 #define CC_PLATFORM_IOS 1
#define CC_PLATFORM_ANDROID 2 #define CC_PLATFORM_ANDROID 2
#define CC_PLATFORM_WOPHONE 3 #define CC_PLATFORM_WIN32 3
#define CC_PLATFORM_WIN32 4 #define CC_PLATFORM_MARMALADE 4
#define CC_PLATFORM_MARMALADE 5 #define CC_PLATFORM_LINUX 5
#define CC_PLATFORM_LINUX 6 #define CC_PLATFORM_BADA 6
#define CC_PLATFORM_BADA 7 #define CC_PLATFORM_BLACKBERRY 7
#define CC_PLATFORM_QNX 8 #define CC_PLATFORM_MAC 8
// Determine tartet platform by compile environment macro. // Determine tartet platform by compile environment macro.
#define CC_TARGET_PLATFORM CC_PLATFORM_UNKNOWN #define CC_TARGET_PLATFORM CC_PLATFORM_UNKNOWN
// iphone // iphone
#if ! CC_TARGET_PLATFORM && (defined(TARGET_OS_IPHONE) || defined(TARGET_IP HONE_SIMULATOR)) #if ! CC_TARGET_PLATFORM && (defined(TARGET_OS_IPHONE) || defined(TARGET_IP HONE_SIMULATOR))
#undef CC_TARGET_PLATFORM #undef CC_TARGET_PLATFORM
#define CC_TARGET_PLATFORM CC_PLATFORM_IOS #define CC_TARGET_PLATFORM CC_PLATFORM_IOS
#define CC_SUPPORT_MULTITHREAD 0
#define CC_SUPPORT_UNICODE 0
#define CC_SUPPORT_PVRTC #define CC_SUPPORT_PVRTC
#endif #endif
// android // android
#if ! CC_TARGET_PLATFORM && defined(ANDROID) #if ! CC_TARGET_PLATFORM && defined(ANDROID)
#undef CC_TARGET_PLATFORM #undef CC_TARGET_PLATFORM
#define CC_TARGET_PLATFORM CC_PLATFORM_ANDROID #define CC_TARGET_PLATFORM CC_PLATFORM_ANDROID
#endif #endif
// wophone
#if ! CC_TARGET_PLATFORM && defined(_TRANZDA_VM_)
#undef CC_TARGET_PLATFORM
#define CC_TARGET_PLATFORM CC_PLATFORM_WOPHONE
#endif
// win32 // win32
#if ! CC_TARGET_PLATFORM && (defined(WIN32) && defined(_WINDOWS)) #if ! CC_TARGET_PLATFORM && (defined(WIN32) && defined(_WINDOWS))
#undef CC_TARGET_PLATFORM #undef CC_TARGET_PLATFORM
#define CC_TARGET_PLATFORM CC_PLATFORM_WIN32 #define CC_TARGET_PLATFORM CC_PLATFORM_WIN32
#define CC_SUPPORT_MULTITHREAD 1
#if defined(UNICODE)
#define CC_SUPPORT_UNICODE 1
#else
#define CC_SUPPORT_UNICODE 0
#endif
#endif #endif
// linux // linux
#if ! CC_TARGET_PLATFORM && defined(LINUX) #if ! CC_TARGET_PLATFORM && defined(LINUX)
#undef CC_TARGET_PLATFORM #undef CC_TARGET_PLATFORM
#define CC_TARGET_PLATFORM CC_PLATFORM_LINUX #define CC_TARGET_PLATFORM CC_PLATFORM_LINUX
#endif #endif
// marmalade // marmalade
#if ! CC_TARGET_PLATFORM && defined(MARMALADE) #if ! CC_TARGET_PLATFORM && defined(MARMALADE)
#undef CC_TARGET_PLATFORM #undef CC_TARGET_PLATFORM
#define CC_TARGET_PLATFORM CC_PLATFORM_MARMALADE #define CC_TARGET_PLATFORM CC_PLATFORM_MARMALADE
#endif #endif
// bada // bada
#if ! CC_TARGET_PLATFORM && defined(SHP) #if ! CC_TARGET_PLATFORM && defined(SHP)
#undef CC_TARGET_PLATFORM #undef CC_TARGET_PLATFORM
#define CC_TARGET_PLATFORM CC_PLATFORM_BADA #define CC_TARGET_PLATFORM CC_PLATFORM_BADA
#endif #endif
// qnx // qnx
#if ! CC_TARGET_PLATFORM && defined(__QNX__) #if ! CC_TARGET_PLATFORM && defined(__QNX__)
#undef CC_TARGET_PLATFORM #undef CC_TARGET_PLATFORM
#define CC_TARGET_PLATFORM CC_PLATFORM_QNX #define CC_TARGET_PLATFORM CC_PLATFORM_BLACKBERRY
#endif
//////////////////////////////////////////////////////////////////////////
// user configure
//////////////////////////////////////////////////////////////////////////
// Check user assigned target platform.
#if defined(CC_UNDER_IOS)
#undef CC_TARGET_PLATFORM
#define CC_TARGET_PLATFORM CC_PLATFORM_IOS
#endif
#if defined(CC_UNDER_ANDROID)
#undef CC_TARGET_PLATFORM
#define CC_TARGET_PLATFORM CC_PLATFORM_ANDROID
#endif
#if defined(CC_UNDER_WOPHONE)
#undef CC_TARGET_PLATFORM
#define CC_TARGET_PLATFORM CC_PLATFORM_WOPHONE
#endif #endif
#if defined(CC_UNDER_WIN32) // mac
#if ! CC_TARGET_PLATFORM && defined(TARGET_OS_MAC)
#undef CC_TARGET_PLATFORM #undef CC_TARGET_PLATFORM
#define CC_TARGET_PLATFORM CC_PLATFORM_WIN32 #define CC_TARGET_PLATFORM CC_PLATFORM_MAC
#endif //#define CC_SUPPORT_PVRTC
#if defined(CC_UNDER_MARMALADE)
#undef CC_TARGET_PLATFORM
#define CC_TARGET_PLATFORM CC_PLATFORM_MARMALADE
#endif
#if defined(CC_UNDER_LINUX)
#undef CC_TARGET_PLATFORM
#define CC_TARGET_PLATFORM CC_PLATFORM_LINUX
#endif
#if defined(CC_UNDER_BADA)
#undef CC_TARGET_PLATFORM
#define CC_TARGET_PLATFORM CC_PLATFORM_BADA
#endif
#if defined(CC_UNDER_QNX)
#undef CC_TARGET_PLATFORM
#define CC_TARGET_PLATFORM CC_PLATFORM_QNX
#endif
// Check user assigned supportive of multi-thread
#if defined(CC_ENABLE_MULTITHREAD)
#undef CC_SUPPORT_MULTITHREAD
#define CC_SUPPORT_MULTITHREAD 1
#elif defined(CC_DISABLE_MULTITHREAD)
#undef CC_SUPPORT_MULTITHREAD
#define CC_SUPPORT_MULTITHREAD 0
#endif
// Check user assigned supportive of unicode
#if defined(CC_ENABLE_UNICODE)
#undef CC_SUPPORT_UNICODE
#define CC_SUPPORT_UNICODE 1
#elif defined(CC_DISABLE_UNICODE)
#undef CC_SUPPORT_UNICODE
#define CC_SUPPORT_UNICODE 0
#endif #endif
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
// post configure // post configure
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
// check user set platform // check user set platform
#if ! CC_TARGET_PLATFORM #if ! CC_TARGET_PLATFORM
#error "Can not recognize the target platform, compling under a unsupp orted platform?" #error "Can not recognize the target platform, compling under a unsupp orted platform?"
#endif #endif
// cocos2d-x havn't support multi-thread yet
#undef CC_SUPPORT_MULTITHREAD
#define CC_SUPPORT_MULTITHREAD 0
// cocos2d-x havn't support unicode yet
#undef CC_SUPPORT_UNICODE
#define CC_SUPPORT_UNICODE 0
// Check the supportive of platform // Check the supportive of platform
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
#pragma warning (disable:4127) #pragma warning (disable:4127)
#endif // CC_PLATFORM_WIN32 #endif // CC_PLATFORM_WIN32
#endif // __CC_PLATFORM_CONFIG_H__ #endif // __CC_PLATFORM_CONFIG_H__
 End of changes. 9 change blocks. 
89 lines changed or deleted 12 lines changed or added


 CCPlatformMacros.h   CCPlatformMacros.h 
skipping to change at line 32 skipping to change at line 32
THE SOFTWARE. THE SOFTWARE.
************************************************************************** **/ ************************************************************************** **/
#ifndef __CC_PLATFORM_MACROS_H__ #ifndef __CC_PLATFORM_MACROS_H__
#define __CC_PLATFORM_MACROS_H__ #define __CC_PLATFORM_MACROS_H__
/** /**
* define some platform specific macros * define some platform specific macros
*/ */
#include "ccConfig.h" #include "ccConfig.h"
#include "CCPlatformConfig.h" #include "CCPlatformConfig.h"
#include "CCPlatformDefine.h"
#define MacGLView void /**
#define NSWindow void * define a create function for a specific type, such as CCLayer
* @__TYPE__ class type to add create(), such as CCLayer
*/
#define CREATE_FUNC(__TYPE__) \
static __TYPE__* create() \
{ \
__TYPE__ *pRet = new __TYPE__(); \
if (pRet && pRet->init()) \
{ \
pRet->autorelease(); \
return pRet; \
} \
else \
{ \
delete pRet; \
pRet = NULL; \
return NULL; \
} \
}
/**
* define a node function for a specific type, such as CCLayer
* @__TYPE__ class type to add node(), such as CCLayer
* @deprecated: This interface will be deprecated sooner or later.
*/
#define NODE_FUNC(__TYPE__) \
CC_DEPRECATED_ATTRIBUTE static __TYPE__* node() \
{ \
__TYPE__ *pRet = new __TYPE__(); \
if (pRet && pRet->init()) \
{ \
pRet->autorelease(); \
return pRet; \
} \
else \
{ \
delete pRet; \
pRet = NULL; \
return NULL; \
} \
}
/** @def CC_ENABLE_CACHE_TEXTTURE_DATA /** @def CC_ENABLE_CACHE_TEXTURE_DATA
Enable it if you want to cache the texture data. Enable it if you want to cache the texture data.
Basically,it's only enabled in android Basically,it's only enabled in android
It's new in cocos2d-x since v0.99.5 It's new in cocos2d-x since v0.99.5
*/ */
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#define CC_ENABLE_CACHE_TEXTTURE_DATA 1 #define CC_ENABLE_CACHE_TEXTURE_DATA 1
#else
#define CC_ENABLE_CACHE_TEXTURE_DATA 0
#endif
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == C
C_PLATFORM_WIN32)
/* Application will crash in glDrawElements function on some win32 comp
uters and some android devices.
Indices should be bound again while drawing to avoid this bug.
*/
#define CC_REBIND_INDICES_BUFFER 1
#else #else
#define CC_ENABLE_CACHE_TEXTTURE_DATA 0 #define CC_REBIND_INDICES_BUFFER 0
#endif #endif
// generic macros // generic macros
// namespace cocos2d {} // namespace cocos2d {}
#define NS_CC_BEGIN namespace cocos2d { #ifdef __cplusplus
#define NS_CC_END } #define NS_CC_BEGIN namespace cocos2d {
#define USING_NS_CC using namespace cocos2d #define NS_CC_END }
#define USING_NS_CC using namespace cocos2d
#else
#define NS_CC_BEGIN
#define NS_CC_END
#define USING_NS_CC
#endif
/** CC_PROPERTY_READONLY is used to declare a protected variable. /** CC_PROPERTY_READONLY is used to declare a protected variable.
We can use getter to read the variable. We can use getter to read the variable.
@param varType : the type of variable. @param varType : the type of variable.
@param varName : variable name. @param varName : variable name.
@param funName : "get + funName" is the name of the getter. @param funName : "get + funName" is the name of the getter.
@warning : The getter is a public virtual function, you should rewrite it first. @warning : The getter is a public virtual function, you should rewrite it first.
The variables and methods declared after CC_PROPERTY_READONLY are all publ ic. The variables and methods declared after CC_PROPERTY_READONLY are all publ ic.
If you need protected or private, please declare. If you need protected or private, please declare.
*/ */
skipping to change at line 130 skipping to change at line 186
protected: varType varName;\ protected: varType varName;\
public: virtual varType get##funName(void) const { return varName; }\ public: virtual varType get##funName(void) const { return varName; }\
public: virtual void set##funName(varType var){ varName = var; } public: virtual void set##funName(varType var){ varName = var; }
#define CC_SYNTHESIZE_PASS_BY_REF(varType, varName, funName)\ #define CC_SYNTHESIZE_PASS_BY_REF(varType, varName, funName)\
protected: varType varName;\ protected: varType varName;\
public: virtual const varType& get##funName(void) const { return varName; } \ public: virtual const varType& get##funName(void) const { return varName; } \
public: virtual void set##funName(const varType& var){ varName = var; } public: virtual void set##funName(const varType& var){ varName = var; }
#define CC_SYNTHESIZE_RETAIN(varType, varName, funName) \ #define CC_SYNTHESIZE_RETAIN(varType, varName, funName) \
protected: varType varName; \ private: varType varName; \
public: virtual varType get##funName(void) const { return varName; } \ public: virtual varType get##funName(void) const { return varName; } \
public: virtual void set##funName(varType var) \ public: virtual void set##funName(varType var) \
{ \ { \
CC_SAFE_RETAIN(var); \ if (varName != var) \
CC_SAFE_RELEASE(varName); \ { \
varName = var; \ CC_SAFE_RETAIN(var); \
CC_SAFE_RELEASE(varName); \
varName = var; \
} \
} }
#define CC_SAFE_DELETE(p) if(p) { delete (p); (p) = 0; #define CC_SAFE_DELETE(p) do { if(p) { delete (p); (p) = 0; } }
} while(0)
#define CC_SAFE_DELETE_ARRAY(p) if(p) { delete[] (p); (p) = 0; } #define CC_SAFE_DELETE_ARRAY(p) do { if(p) { delete[] (p); (p) = 0; } }
#define CC_SAFE_FREE(p) if(p) { free(p); (p) = 0; } while(0)
#define CC_SAFE_RELEASE(p) if(p) { (p)->release(); } #define CC_SAFE_FREE(p) do { if(p) { free(p); (p) = 0; } } w
#define CC_SAFE_RELEASE_NULL(p) if(p) { (p)->release(); (p) = 0; } hile(0)
#define CC_SAFE_RETAIN(p) if(p) { (p)->retain(); } #define CC_SAFE_RELEASE(p) do { if(p) { (p)->release(); } } whil
#define CC_BREAK_IF(cond) if(cond) break; e(0)
#define CC_SAFE_RELEASE_NULL(p) do { if(p) { (p)->release(); (p) = 0
; } } while(0)
#define CC_SAFE_RETAIN(p) do { if(p) { (p)->retain(); } } while(
0)
#define CC_BREAK_IF(cond) if(cond) break
#define __CCLOGWITHFUNCTION(s, ...) \
CCLog("%s : %s",__FUNCTION__, CCString::createWithFormat(s, ##__VA_ARGS
__)->getCString())
// cocos2d debug // cocos2d debug
#if !defined(COCOS2D_DEBUG) || COCOS2D_DEBUG == 0 #if !defined(COCOS2D_DEBUG) || COCOS2D_DEBUG == 0
#define CCLOG(...) #define CCLOG(...) do {} while (0)
#define CCLOGINFO(...) #define CCLOGINFO(...) do {} while (0)
#define CCLOGERROR(...) #define CCLOGERROR(...) do {} while (0)
#define CCLOGWARN(...) do {} while (0)
#elif COCOS2D_DEBUG == 1 #elif COCOS2D_DEBUG == 1
#define CCLOG(format, ...) cocos2d::CCLog(format, ##__VA_ARGS__) #define CCLOG(format, ...) cocos2d::CCLog(format, ##__VA_ARGS__)
#define CCLOGERROR(format,...) cocos2d::CCLog(format, ##__VA_ARGS__) #define CCLOGERROR(format,...) cocos2d::CCLog(format, ##__VA_ARGS__)
#define CCLOGINFO(format,...) do {} while (0) #define CCLOGINFO(format,...) do {} while (0)
#define CCLOGWARN(...) __CCLOGWITHFUNCTION(__VA_ARGS__)
#elif COCOS2D_DEBUG > 1 #elif COCOS2D_DEBUG > 1
#define CCLOG(format, ...) cocos2d::CCLog(format, ##__VA_ARGS__) #define CCLOG(format, ...) cocos2d::CCLog(format, ##__VA_ARGS__)
#define CCLOGERROR(format,...) cocos2d::CCLog(format, ##__VA_ARGS__) #define CCLOGERROR(format,...) cocos2d::CCLog(format, ##__VA_ARGS__)
#define CCLOGINFO(format,...) cocos2d::CCLog(format, ##__VA_ARGS__) #define CCLOGINFO(format,...) cocos2d::CCLog(format, ##__VA_ARGS__)
#define CCLOGWARN(...) __CCLOGWITHFUNCTION(__VA_ARGS__)
#endif // COCOS2D_DEBUG #endif // COCOS2D_DEBUG
// Lua engine debug // Lua engine debug
#if !defined(COCOS2D_DEBUG) || COCOS2D_DEBUG == 0 || CC_LUA_ENGINE_DEBUG == 0 #if !defined(COCOS2D_DEBUG) || COCOS2D_DEBUG == 0 || CC_LUA_ENGINE_DEBUG == 0
#define LUALOG(...) #define LUALOG(...)
#else #else
#define LUALOG(format, ...) cocos2d::CCLog(format, ##__VA_ARGS__) #define LUALOG(format, ...) cocos2d::CCLog(format, ##__VA_ARGS__)
#endif // Lua engine debug #endif // Lua engine debug
// shared library declartor /*
#define CC_DLL * only certain compilers support __attribute__((deprecated))
*/
#if (CC_TARGET_PLATFORM != CC_PLATFORM_BADA) #if defined(__GNUC__) && ((__GNUC__ >= 4) || ((__GNUC__ == 3) && (__GNUC_MI
// assertion NOR__ >= 1)))
#include <assert.h> #define CC_DEPRECATED_ATTRIBUTE __attribute__((deprecated))
#define CC_ASSERT(cond) assert(cond) #elif _MSC_VER >= 1400 //vs 2005 or higher
#else #define CC_DEPRECATED_ATTRIBUTE __declspec(deprecated)
// bada platform
#include <FBaseConfig.h>
#include <FBaseSys.h>
#undef CC_DLL
#define CC_DLL _EXPORT_
#include "CCPlatformFunc_bada.h"
#ifdef _DEBUG
#define CC_ASSERT(cond) (void)( (!!(cond)) || (badaAssert(__PRETTY_FUNCTIO
N__ , __LINE__ , #cond),0) )
#else #else
#define CC_ASSERT(cond) void(0) #define CC_DEPRECATED_ATTRIBUTE
#endif /* _DEBUG */
#endif
#define CC_UNUSED_PARAM(unusedparam) (void)unusedparam
#if (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX)
#undef CC_UNUSED_PARAM
#define CC_UNUSED_PARAM(unusedparam) //unusedparam
#endif #endif
// platform depended macros
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
#undef CC_DLL
#if defined(_USRDLL)
#define CC_DLL __declspec(dllexport)
#else /* use a DLL library */
#define CC_DLL __declspec(dllimport)
#endif
#endif // CC_PLATFORM_WIN32
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WOPHONE && defined(_TRANZDA_VM_))
#undef CC_DLL
#if defined(SS_MAKEDLL)
#define CC_DLL __declspec(dllexport)
#else /* use a DLL library */
#define CC_DLL __declspec(dllimport)
#endif
#endif // wophone VM
#endif // __CC_PLATFORM_MACROS_H__ #endif // __CC_PLATFORM_MACROS_H__
 End of changes. 15 change blocks. 
77 lines changed or deleted 105 lines changed or added


 CCPointExtension.h   CCPointExtension.h 
skipping to change at line 46 skipping to change at line 46
Examples: Examples:
- ccpAdd( ccp(1,1), ccp(2,2) ); // preferred cocos2d way - ccpAdd( ccp(1,1), ccp(2,2) ); // preferred cocos2d way
- ccpAdd( CCPointMake(1,1), CCPointMake(2,2) ); // also ok but more verbo se - ccpAdd( CCPointMake(1,1), CCPointMake(2,2) ); // also ok but more verbo se
- cpvadd( cpv(1,1), cpv(2,2) ); // way of the chipmunk - cpvadd( cpv(1,1), cpv(2,2) ); // way of the chipmunk
- ccpAdd( cpv(1,1), cpv(2,2) ); // mixing chipmunk and cocos2d (avoid) - ccpAdd( cpv(1,1), cpv(2,2) ); // mixing chipmunk and cocos2d (avoid)
- cpvadd( CCPointMake(1,1), CCPointMake(2,2) ); // mixing chipmunk and CG (avoid) - cpvadd( CCPointMake(1,1), CCPointMake(2,2) ); // mixing chipmunk and CG (avoid)
*/ */
#include "CCGeometry.h" #include "cocoa/CCGeometry.h"
#include <math.h> #include <math.h>
namespace cocos2d {
NS_CC_BEGIN
/**
* @addtogroup data_structures
* @{
*/
/** Helper macro that creates a CCPoint /** Helper macro that creates a CCPoint
@return CCPoint @return CCPoint
@since v0.7.2 @since v0.7.2
*/ */
#define ccp(__X__,__Y__) cocos2d::CCPointMake((float)(__X__), (float)(__Y__ )) #define ccp(__X__,__Y__) cocos2d::CCPointMake((float)(__X__), (float)(__Y__ ))
/** Returns opposite of point. /** Returns opposite of point.
@return CCPoint @return CCPoint
@since v0.7.2 @since v0.7.2
*/ */
static inline CCPoint static inline CCPoint
ccpNeg(const CCPoint& v) ccpNeg(const CCPoint& v)
{ {
return ccp(-v.x, -v.y); return ccp(-v.x, -v.y);
} }
/** Calculates sum of two points. /** Calculates sum of two points.
@return CCPoint @return CCPoint
@since v0.7.2 @since v0.7.2
*/ */
static inline CCPoint static inline CCPoint
ccpAdd(const CCPoint& v1, const CCPoint& v2) ccpAdd(const CCPoint& v1, const CCPoint& v2)
{ {
return ccp(v1.x + v2.x, v1.y + v2.y); return ccp(v1.x + v2.x, v1.y + v2.y);
} }
/** Calculates difference of two points. /** Calculates difference of two points.
@return CCPoint @return CCPoint
@since v0.7.2 @since v0.7.2
*/ */
static inline CCPoint static inline CCPoint
ccpSub(const CCPoint& v1, const CCPoint& v2) ccpSub(const CCPoint& v1, const CCPoint& v2)
{ {
return ccp(v1.x - v2.x, v1.y - v2.y); return ccp(v1.x - v2.x, v1.y - v2.y);
} }
/** Returns point multiplied by given factor. /** Returns point multiplied by given factor.
@return CCPoint @return CCPoint
@since v0.7.2 @since v0.7.2
*/ */
static inline CCPoint static inline CCPoint
ccpMult(const CCPoint& v, const CGFloat s) ccpMult(const CCPoint& v, const float s)
{ {
return ccp(v.x*s, v.y*s); return ccp(v.x*s, v.y*s);
} }
/** Calculates midpoint between two points. /** Calculates midpoint between two points.
@return CCPoint @return CCPoint
@since v0.7.2 @since v0.7.2
*/ */
static inline CCPoint static inline CCPoint
ccpMidpoint(const CCPoint& v1, const CCPoint& v2) ccpMidpoint(const CCPoint& v1, const CCPoint& v2)
{ {
return ccpMult(ccpAdd(v1, v2), 0.5f); return ccpMult(ccpAdd(v1, v2), 0.5f);
} }
/** Calculates dot product of two points. /** Calculates dot product of two points.
@return CGFloat @return float
@since v0.7.2 @since v0.7.2
*/ */
static inline CGFloat static inline float
ccpDot(const CCPoint& v1, const CCPoint& v2) ccpDot(const CCPoint& v1, const CCPoint& v2)
{ {
return v1.x*v2.x + v1.y*v2.y; return v1.x*v2.x + v1.y*v2.y;
} }
/** Calculates cross product of two points. /** Calculates cross product of two points.
@return CGFloat @return float
@since v0.7.2 @since v0.7.2
*/ */
static inline CGFloat static inline float
ccpCross(const CCPoint& v1, const CCPoint& v2) ccpCross(const CCPoint& v1, const CCPoint& v2)
{ {
return v1.x*v2.y - v1.y*v2.x; return v1.x*v2.y - v1.y*v2.x;
} }
/** Calculates perpendicular of v, rotated 90 degrees counter-clockwise -- cross(v, perp(v)) >= 0 /** Calculates perpendicular of v, rotated 90 degrees counter-clockwise -- cross(v, perp(v)) >= 0
@return CCPoint @return CCPoint
@since v0.7.2 @since v0.7.2
*/ */
static inline CCPoint static inline CCPoint
ccpPerp(const CCPoint& v) ccpPerp(const CCPoint& v)
{ {
return ccp(-v.y, v.x); return ccp(-v.y, v.x);
} }
/** Calculates perpendicular of v, rotated 90 degrees clockwise -- cross(v, rperp(v)) <= 0 /** Calculates perpendicular of v, rotated 90 degrees clockwise -- cross(v, rperp(v)) <= 0
@return CCPoint @return CCPoint
@since v0.7.2 @since v0.7.2
*/ */
static inline CCPoint static inline CCPoint
ccpRPerp(const CCPoint& v) ccpRPerp(const CCPoint& v)
{ {
return ccp(v.y, -v.x); return ccp(v.y, -v.x);
} }
/** Calculates the projection of v1 over v2. /** Calculates the projection of v1 over v2.
@return CCPoint @return CCPoint
@since v0.7.2 @since v0.7.2
*/ */
static inline CCPoint static inline CCPoint
ccpProject(const CCPoint& v1, const CCPoint& v2) ccpProject(const CCPoint& v1, const CCPoint& v2)
{ {
return ccpMult(v2, ccpDot(v1, v2)/ccpDot(v2, v2)); return ccpMult(v2, ccpDot(v1, v2)/ccpDot(v2, v2));
} }
/** Rotates two points. /** Rotates two points.
@return CCPoint @return CCPoint
@since v0.7.2 @since v0.7.2
*/ */
static inline CCPoint static inline CCPoint
ccpRotate(const CCPoint& v1, const CCPoint& v2) ccpRotate(const CCPoint& v1, const CCPoint& v2)
{ {
return ccp(v1.x*v2.x - v1.y*v2.y, v1.x*v2.y + v1.y*v2.x); return ccp(v1.x*v2.x - v1.y*v2.y, v1.x*v2.y + v1.y*v2.x);
} }
/** Unrotates two points. /** Unrotates two points.
@return CCPoint @return CCPoint
@since v0.7.2 @since v0.7.2
*/ */
static inline CCPoint static inline CCPoint
ccpUnrotate(const CCPoint& v1, const CCPoint& v2) ccpUnrotate(const CCPoint& v1, const CCPoint& v2)
{ {
return ccp(v1.x*v2.x + v1.y*v2.y, v1.y*v2.x - v1.x*v2.y); return ccp(v1.x*v2.x + v1.y*v2.y, v1.y*v2.x - v1.x*v2.y);
} }
/** Calculates the square length of a CCPoint (not calling sqrt() ) /** Calculates the square length of a CCPoint (not calling sqrt() )
@return CGFloat @return float
@since v0.7.2 @since v0.7.2
*/ */
static inline CGFloat static inline float
ccpLengthSQ(const CCPoint& v) ccpLengthSQ(const CCPoint& v)
{ {
return ccpDot(v, v); return ccpDot(v, v);
}
/** Calculates the square distance between two points (not calling sqrt() )
@return float
@since v1.1
*/
static inline float
ccpDistanceSQ(const CCPoint p1, const CCPoint p2)
{
return ccpLengthSQ(ccpSub(p1, p2));
} }
/** Calculates distance between point an origin /** Calculates distance between point an origin
@return CGFloat @return float
@since v0.7.2 @since v0.7.2
*/ */
CGFloat CC_DLL ccpLength(const CCPoint& v); float CC_DLL ccpLength(const CCPoint& v);
/** Calculates the distance between two points /** Calculates the distance between two points
@return CGFloat @return float
@since v0.7.2 @since v0.7.2
*/ */
CGFloat CC_DLL ccpDistance(const CCPoint& v1, const CCPoint& v2); float CC_DLL ccpDistance(const CCPoint& v1, const CCPoint& v2);
/** Returns point multiplied to a length of 1. /** Returns point multiplied to a length of 1.
@return CCPoint @return CCPoint
@since v0.7.2 @since v0.7.2
*/ */
CCPoint CC_DLL ccpNormalize(const CCPoint& v); CCPoint CC_DLL ccpNormalize(const CCPoint& v);
/** Converts radians to a normalized vector. /** Converts radians to a normalized vector.
@return CCPoint @return CCPoint
@since v0.7.2 @since v0.7.2
*/ */
CCPoint CC_DLL ccpForAngle(const CGFloat a); CCPoint CC_DLL ccpForAngle(const float a);
/** Converts a vector to radians. /** Converts a vector to radians.
@return CGFloat @return float
@since v0.7.2 @since v0.7.2
*/ */
CGFloat CC_DLL ccpToAngle(const CCPoint& v); float CC_DLL ccpToAngle(const CCPoint& v);
/** Clamp a value between from and to. /** Clamp a value between from and to.
@since v0.99.1 @since v0.99.1
*/ */
float CC_DLL clampf(float value, float min_inclusive, float max_inclusive); float CC_DLL clampf(float value, float min_inclusive, float max_inclusive);
/** Clamp a point between from and to. /** Clamp a point between from and to.
@since v0.99.1 @since v0.99.1
*/ */
CCPoint CC_DLL ccpClamp(const CCPoint& p, const CCPoint& from, const CCPoin t& to); CCPoint CC_DLL ccpClamp(const CCPoint& p, const CCPoint& from, const CCPoin t& to);
skipping to change at line 243 skipping to change at line 258
* absf, fllorf, ceilf, roundf * absf, fllorf, ceilf, roundf
* any function that has the signature: float func(float); * any function that has the signature: float func(float);
* For example: let's try to take the floor of x,y * For example: let's try to take the floor of x,y
* ccpCompOp(p,floorf); * ccpCompOp(p,floorf);
@since v0.99.1 @since v0.99.1
*/ */
CCPoint CC_DLL ccpCompOp(const CCPoint& p, float (*opFunc)(float)); CCPoint CC_DLL ccpCompOp(const CCPoint& p, float (*opFunc)(float));
/** Linear Interpolation between two points a and b /** Linear Interpolation between two points a and b
@returns @returns
alpha == 0 ? a alpha == 0 ? a
alpha == 1 ? b alpha == 1 ? b
otherwise a value between a..b otherwise a value between a..b
@since v0.99.1 @since v0.99.1
*/ */
CCPoint CC_DLL ccpLerp(const CCPoint& a, const CCPoint& b, float alpha); CCPoint CC_DLL ccpLerp(const CCPoint& a, const CCPoint& b, float alpha);
/** @returns if points have fuzzy equality which means equal with some degr ee of variance. /** @returns if points have fuzzy equality which means equal with some degr ee of variance.
@since v0.99.1 @since v0.99.1
*/ */
bool CC_DLL ccpFuzzyEqual(const CCPoint& a, const CCPoint& b, float varianc e); bool CC_DLL ccpFuzzyEqual(const CCPoint& a, const CCPoint& b, float varianc e);
/** Multiplies a nd b components, a.x*b.x, a.y*b.y /** Multiplies a nd b components, a.x*b.x, a.y*b.y
skipping to change at line 282 skipping to change at line 297
@param v is the point to rotate @param v is the point to rotate
@param pivot is the pivot, naturally @param pivot is the pivot, naturally
@param angle is the angle of rotation cw in radians @param angle is the angle of rotation cw in radians
@returns the rotated point @returns the rotated point
@since v0.99.1 @since v0.99.1
*/ */
CCPoint CC_DLL ccpRotateByAngle(const CCPoint& v, const CCPoint& pivot, flo at angle); CCPoint CC_DLL ccpRotateByAngle(const CCPoint& v, const CCPoint& pivot, flo at angle);
/** A general line-line intersection test /** A general line-line intersection test
@param p1 @param p1
is the startpoint for the first line P1 = (p1 - p2) is the startpoint for the first line P1 = (p1 - p2)
@param p2 @param p2
is the endpoint for the first line P1 = (p1 - p2) is the endpoint for the first line P1 = (p1 - p2)
@param p3 @param p3
is the startpoint for the second line P2 = (p3 - p4) is the startpoint for the second line P2 = (p3 - p4)
@param p4 @param p4
is the endpoint for the second line P2 = (p3 - p4) is the endpoint for the second line P2 = (p3 - p4)
@param s @param s
is the range for a hitpoint in P1 (pa = p1 + s*(p2 - p1)) is the range for a hitpoint in P1 (pa = p1 + s*(p2 - p1))
@param t @param t
is the range for a hitpoint in P3 (pa = p2 + t*(p4 - p3)) is the range for a hitpoint in P3 (pa = p2 + t*(p4 - p3))
@return bool @return bool
indicating successful intersection of a line indicating successful intersection of a line
note that to truly test intersection for segments we have to make note that to truly test intersection for segments we have to make
sure that s & t lie within [0..1] and for rays, make sure s & t > 0 sure that s & t lie within [0..1] and for rays, make sure s & t > 0
the hit point is p3 + t * (p4 - p3); the hit point is p3 + t * (p4 - p3);
the hit point also is p1 + s * (p2 - p1); the hit point also is p1 + s * (p2 - p1);
@since v0.99.1 @since v0.99.1
*/ */
bool CC_DLL ccpLineIntersect(const CCPoint& p1, const CCPoint& p2, bool CC_DLL ccpLineIntersect(const CCPoint& p1, const CCPoint& p2,
const CCPoint& p3, const CCPoint& const CCPoint& p3, const CCPoint& p4,
p4, float *s, float *t);
float *s, float *t);
/* /*
ccpSegmentIntersect returns YES if Segment A-B intersects with segment C-D ccpSegmentIntersect returns YES if Segment A-B intersects with segment C-D
@since v1.0.0 @since v1.0.0
*/ */
bool CC_DLL ccpSegmentIntersect(const CCPoint& A, const CCPoint& B, const C CPoint& C, const CCPoint& D); bool CC_DLL ccpSegmentIntersect(const CCPoint& A, const CCPoint& B, const C CPoint& C, const CCPoint& D);
/* /*
ccpIntersectPoint returns the intersection point of line A-B, C-D ccpIntersectPoint returns the intersection point of line A-B, C-D
@since v1.0.0 @since v1.0.0
*/ */
CCPoint CC_DLL ccpIntersectPoint(const CCPoint& A, const CCPoint& B, const CCPoint& C, const CCPoint& D); CCPoint CC_DLL ccpIntersectPoint(const CCPoint& A, const CCPoint& B, const CCPoint& C, const CCPoint& D);
}//namespace cocos2d // end of data_structures group
/// @}
NS_CC_END
#endif // __SUPPORT_CGPOINTEXTENSION_H__ #endif // __SUPPORT_CGPOINTEXTENSION_H__
 End of changes. 39 change blocks. 
48 lines changed or deleted 65 lines changed or added


 CCProfiling.h   CCProfiling.h 
skipping to change at line 29 skipping to change at line 29
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __SUPPORT_CCPROFILING_H__ #ifndef __SUPPORT_CCPROFILING_H__
#define __SUPPORT_CCPROFILING_H__ #define __SUPPORT_CCPROFILING_H__
#include "ccConfig.h" #include "ccConfig.h"
#include "cocoa/CCObject.h"
#include "platform/platform.h"
#include "cocoa/CCDictionary.h"
#include <string>
#if CC_ENABLE_PROFILERS NS_CC_BEGIN
#include <string> /**
* @addtogroup global
* @{
*/
#include "CCObject.h" class CCProfilingTimer;
#include "platform/platform.h"
#include "CCArray.h"
namespace cocos2d /** CCProfiler
cocos2d builtin profiler.
To use it, enable set the CC_ENABLE_PROFILERS=1 in the ccConfig.h file
*/
class CC_DLL CCProfiler : public CCObject
{ {
class CCProfilingTimer; public:
~CCProfiler(void);
/** display the timers */
void displayTimers(void);
bool init(void);
public:
static CCProfiler* sharedProfiler(void);
/** Creates and adds a new timer */
CCProfilingTimer* createAndAddTimerWithName(const char* timerName);
/** releases a timer */
void releaseTimer(const char* timerName);
/** releases all timers */
void releaseAllTimers();
class CC_DLL CCProfiler : public CCObject CCDictionary* m_pActiveTimers;
{ };
public:
~CCProfiler(void); class CCProfilingTimer : public CCObject
void displayTimers(void); {
bool init(void); public:
bool initWithName(const char* timerName);
public: ~CCProfilingTimer(void);
static CCProfiler* sharedProfiler(void); const char* description(void);
static CCProfilingTimer* timerWithName(const char *pszTimerN inline struct cc_timeval * getStartTime(void) { return &m_sStartTime; }
ame, CCObject *pInstance); ;
static void releaseTimer(CCProfilingTimer *pTimer); inline void setAverageTime(double value) { m_dAverageTime = value; }
inline double getAverageTime(void) { return m_dAverageTime; }
protected: /** resets the timer properties */
CCArray *m_pActiveTimers; void reset();
};
std::string m_NameStr;
class CCProfilingTimer : public CCObject struct cc_timeval m_sStartTime;
{ double m_dAverageTime;
public: double minTime;
bool initWithName(const char* pszTimerName, CCObject *pInsta double maxTime;
nce); double totalTime;
~CCProfilingTimer(void); unsigned int numberOfCalls;
char* description(void); };
inline struct cc_timeval * getStartTime(void) { return &m_sS
tartTime; }; extern void CCProfilingBeginTimingBlock(const char *timerName);
inline void setAverageTime(double value) { m_dAverageTime = extern void CCProfilingEndTimingBlock(const char *timerName);
value; } extern void CCProfilingResetTimingBlock(const char *timerName);
inline double getAverageTime(void) { return m_dAverageTime;
} /*
* cocos2d profiling categories
protected: * used to enable / disable profilers with granularity
std::string m_NameStr; */
struct cc_timeval m_sStartTime;
double m_dAverageTime; extern bool kCCProfilerCategorySprite;
}; extern bool kCCProfilerCategoryBatchSprite;
extern bool kCCProfilerCategoryParticles;
void CC_DLL CCProfilingBeginTimingBlock(CCProfilingTimer *pTimer); // end of global group
void CC_DLL CCProfilingEndTimingBlock(CCProfilingTimer *pTimer); /// @}
} // end of namespace cocos2d NS_CC_END
#endif // CC_ENABLE_PROFILERS
#endif // __SUPPORT_CCPROFILING_H__ #endif // __SUPPORT_CCPROFILING_H__
 End of changes. 10 change blocks. 
47 lines changed or deleted 71 lines changed or added


 CCProgressTimer.h   CCProgressTimer.h 
/************************************************************************** ** /************************************************************************** **
Copyright (c) 2010-2011 cocos2d-x.org Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2010 Lam Pham Copyright (c) 2010 Lam Pham
http://www.cocos2d-x.org http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a cop y Permission is hereby granted, free of charge, to any person obtaining a cop y
of this software and associated documentation files (the "Software"), to de al of this software and associated documentation files (the "Software"), to de al
in the Software without restriction, including without limitation the right s in the Software without restriction, including without limitation the right s
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
skipping to change at line 28 skipping to change at line 28
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __MISC_NODE_CCPROGRESS_TIMER_H__ #ifndef __MISC_NODE_CCPROGRESS_TIMER_H__
#define __MISC_NODE_CCPROGRESS_TIMER_H__ #define __MISC_NODE_CCPROGRESS_TIMER_H__
#include "CCSprite.h" #include "sprite_nodes/CCSprite.h"
NS_CC_BEGIN
/**
* @addtogroup misc_nodes
* @{
*/
namespace cocos2d
{
/** Types of progress /** Types of progress
@since v0.99.1 @since v0.99.1
*/ */
typedef enum { typedef enum {
/// Radial Counter-Clockwise /// Radial Counter-Clockwise
kCCProgressTimerTypeRadialCCW, kCCProgressTimerTypeRadial,
/// Radial ClockWise /// Bar
kCCProgressTimerTypeRadialCW, kCCProgressTimerTypeBar,
/// Horizontal Left-Right
kCCProgressTimerTypeHorizontalBarLR,
/// Horizontal Right-Left
kCCProgressTimerTypeHorizontalBarRL,
/// Vertical Bottom-top
kCCProgressTimerTypeVerticalBarBT,
/// Vertical Top-Bottom
kCCProgressTimerTypeVerticalBarTB,
} CCProgressTimerType; } CCProgressTimerType;
/** /**
@brief CCProgresstimer is a subclass of CCNode. @brief CCProgresstimer is a subclass of CCNode.
It renders the inner sprite according to the percentage. It renders the inner sprite according to the percentage.
The progress can be Radial, Horizontal or vertical. The progress can be Radial, Horizontal or vertical.
@since v0.99.1 @since v0.99.1
*/ */
class CC_DLL CCProgressTimer : public CCNode class CC_DLL CCProgressTimer : public CCNode, public CCRGBAProtocol
{ {
public: public:
~CCProgressTimer(void); CCProgressTimer();
~CCProgressTimer(void);
/** Change the percentage to change progress. */ /** Change the percentage to change progress. */
inline CCProgressTimerType getType(void) { return m_eType; } inline CCProgressTimerType getType(void) { return m_eType; }
/** Percentages are from 0 to 100 */ /** Percentages are from 0 to 100 */
inline float getPercentage(void) {return m_fPercentage; } inline float getPercentage(void) {return m_fPercentage; }
/** The image to show the progress percentage, retain */ /** The image to show the progress percentage, retain */
inline CCSprite* getSprite(void) { return m_pSprite; } inline CCSprite* getSprite(void) { return m_pSprite; }
/** Initializes a progress timer with the sprite as the shape the timer
goes through */
bool initWithSprite(CCSprite* sp);
void setPercentage(float fPercentage);
void setSprite(CCSprite *pSprite);
void setType(CCProgressTimerType type);
void setReverseProgress(bool reverse);
virtual void draw(void);
void setAnchorPoint(CCPoint anchorPoint);
virtual void setColor(const ccColor3B& color);
virtual const ccColor3B& getColor(void);
virtual GLubyte getOpacity(void);
virtual void setOpacity(GLubyte opacity);
virtual void setOpacityModifyRGB(bool bValue);
virtual bool isOpacityModifyRGB(void);
bool initWithFile(const char *pszFileName); inline bool isReverseDirection() { return m_bReverseDirection; };
bool initWithTexture(CCTexture2D *pTexture); inline void setReverseDirection(bool value) { m_bReverseDirection = val
ue; };
void setPercentage(float fPercentage);
void setSprite(CCSprite *pSprite);
void setType(CCProgressTimerType type);
virtual void draw(void);
public: public:
static CCProgressTimer* progressWithFile(const char *pszFileName); /** Creates a progress timer with the sprite as the shape the timer goe
static CCProgressTimer* progressWithTexture(CCTexture2D *pTexture); s through
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCProgressTimer* progressWithSprite(CCSp
rite* sp);
/** Creates a progress timer with the sprite as the shape the timer goe
s through */
static CCProgressTimer* create(CCSprite* sp);
protected: protected:
ccVertex2F vertexFromTexCoord(const CCPoint& texCoord); ccTex2F textureCoordFromAlphaPoint(CCPoint alpha);
void updateProgress(void); ccVertex2F vertexFromAlphaPoint(CCPoint alpha);
void updateBar(void); void updateProgress(void);
void updateRadial(void); void updateBar(void);
void updateColor(void); void updateRadial(void);
CCPoint boundaryTexCoord(char index); void updateColor(void);
CCPoint boundaryTexCoord(char index);
protected: protected:
CCProgressTimerType m_eType; CCProgressTimerType m_eType;
float m_fPercentage; float m_fPercentage;
CCSprite *m_pSprite; CCSprite *m_pSprite;
int m_nVertexDataCount; int m_nVertexDataCount;
ccV2F_C4B_T2F *m_pVertexData; ccV2F_C4B_T2F *m_pVertexData;
/**
* Midpoint is used to modify the progress start position.
* If you're using radials type then the midpoint changes the center
point
* If you're using bar type the the midpoint changes the bar growth
* it expands from the center but clamps to the sprites edge so:
* you want a left to right then set the midpoint all the way to
ccp(0,y)
* you want a right to left then set the midpoint all the way to
ccp(1,y)
* you want a bottom to top then set the midpoint all the way to
ccp(x,0)
* you want a top to bottom then set the midpoint all the way to
ccp(x,1)
*/
CC_PROPERTY(CCPoint, m_tMidpoint, Midpoint);
/**
* This allows the bar type to move the component at a specific rate
* Set the component to 0 to make sure it stays at 100%.
* For example you want a left to right bar but not have the height
stay 100%
* Set the rate to be ccp(0,1); and set the midpoint to = ccp(0,.5f)
;
*/
CC_SYNTHESIZE(CCPoint, m_tBarChangeRate, BarChangeRate);
bool m_bReverseDirection;
}; };
} // end of misc_nodes group
/// @}
NS_CC_END
#endif //__MISC_NODE_CCPROGRESS_TIMER_H__ #endif //__MISC_NODE_CCPROGRESS_TIMER_H__
 End of changes. 14 change blocks. 
47 lines changed or deleted 98 lines changed or added


 CCProtocols.h   CCProtocols.h 
skipping to change at line 30 skipping to change at line 30
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CCPROTOCOLS_H__ #ifndef __CCPROTOCOLS_H__
#define __CCPROTOCOLS_H__ #define __CCPROTOCOLS_H__
#include "ccTypes.h" #include "ccTypes.h"
#include "CCTexture2D.h" #include "textures/CCTexture2D.h"
#include <string> #include <string>
namespace cocos2d {
NS_CC_BEGIN
//! @brief CC RGBA protocol //! @brief CC RGBA protocol
class CC_DLL CCRGBAProtocol class CC_DLL CCRGBAProtocol
{ {
public: public:
/** sets Color /** sets Color
@since v0.8 @since v0.8
*/ */
virtual void setColor(const ccColor3B& color) = 0; virtual void setColor(const ccColor3B& color) = 0;
/** returns the color /** returns the color
@since v0.8 @since v0.8
*/ */
virtual const ccColor3B& getColor(void) = 0; virtual const ccColor3B& getColor(void) = 0;
// returns the opacity // returns the opacity
virtual GLubyte getOpacity(void) = 0; virtual GLubyte getOpacity(void) = 0;
/** sets the opacity. /** sets the opacity.
@warning If the the texture has premultiplied alpha then, the R, G @warning If the the texture has premultiplied alpha then, the R, G and
and B channels will be modifed. B channels will be modifed.
Values goes from 0 to 255, where 255 means fully opaque. Values goes from 0 to 255, where 255 means fully opaque.
*/ */
virtual void setOpacity(GLubyte opacity) = 0; virtual void setOpacity(GLubyte opacity) = 0;
// optional // optional
/** sets the premultipliedAlphaOpacity property. /** sets the premultipliedAlphaOpacity property.
If set to NO then opacity will be applied as: glColor(R,G,B,opacity If set to NO then opacity will be applied as: glColor(R,G,B,opacity);
); If set to YES then oapcity will be applied as: glColor(opacity, opacit
If set to YES then oapcity will be applied as: glColor(opacity, opa y, opacity, opacity );
city, opacity, opacity ); Textures with premultiplied alpha will have this property by default o
Textures with premultiplied alpha will have this property by defaul n YES. Otherwise the default value is NO
t on YES. Otherwise the default value is NO @since v0.8
@since v0.8 */
*/ virtual void setOpacityModifyRGB(bool bValue) = 0;
virtual void setIsOpacityModifyRGB(bool bValue) = 0;
/** returns whether or not the opacity will be applied using glColor(R,
/** returns whether or not the opacity will be applied using glColor G,B,opacity) or glColor(opacity, opacity, opacity, opacity);
(R,G,B,opacity) or glColor(opacity, opacity, opacity, opacity); @since v0.8
@since v0.8 */
*/ virtual bool isOpacityModifyRGB(void) = 0;
virtual bool getIsOpacityModifyRGB(void) = 0;
}; };
/** /**
@brief You can specify the blending fuction. @brief You can specify the blending fuction.
@since v0.99.0 @since v0.99.0
*/ */
class CC_DLL CCBlendProtocol class CC_DLL CCBlendProtocol
{ {
public: public:
// set the source blending function for the texture // set the source blending function for the texture
virtual void setBlendFunc(ccBlendFunc blendFunc) = 0; virtual void setBlendFunc(ccBlendFunc blendFunc) = 0;
// returns the blending function used for the texture // returns the blending function used for the texture
virtual ccBlendFunc getBlendFunc(void) = 0; virtual ccBlendFunc getBlendFunc(void) = 0;
}; };
/** @brief CCNode objects that uses a Texture2D to render the images. /** @brief CCNode objects that uses a Texture2D to render the images.
The texture can have a blending function. The texture can have a blending function.
If the texture has alpha premultiplied the default blending function is: If the texture has alpha premultiplied the default blending function is:
src=GL_ONE dst= GL_ONE_MINUS_SRC_ALPHA src=GL_ONE dst= GL_ONE_MINUS_SRC_ALPHA
else else
src=GL_SRC_ALPHA dst= GL_ONE_MINUS_SRC_ALPHA src=GL_SRC_ALPHA dst= GL_ONE_MINUS_SRC_ALPHA
But you can change the blending funtion at any time. But you can change the blending funtion at any time.
@since v0.8.0 @since v0.8.0
*/ */
class CC_DLL CCTextureProtocol : public CCBlendProtocol class CC_DLL CCTextureProtocol : public CCBlendProtocol
{ {
public: public:
// returns the used texture // returns the used texture
virtual CCTexture2D* getTexture(void) = 0; virtual CCTexture2D* getTexture(void) = 0;
// sets a new texture. it will be retained // sets a new texture. it will be retained
virtual void setTexture(CCTexture2D *texture) = 0; virtual void setTexture(CCTexture2D *texture) = 0;
}; };
//! @brief Common interface for Labels //! @brief Common interface for Labels
class CC_DLL CCLabelProtocol class CC_DLL CCLabelProtocol
{ {
public: public:
// sets a new label using an string // sets a new label using an string
virtual void setString(const char *label) = 0; virtual void setString(const char *label) = 0;
/** returns the string that is rendered */ /** returns the string that is rendered */
virtual const char* getString(void) = 0; virtual const char* getString(void) = 0;
}; };
/** OpenGL projection protocol */ /** OpenGL projection protocol */
class CC_DLL CCProjectionProtocol class CC_DLL CCDirectorDelegate
{ {
public: public:
/** Called by CCDirector when the porjection is updated, and "custom /** Called by CCDirector when the porjection is updated, and "custom" p
" projection is used rojection is used
@since v0.99.5 @since v0.99.5
*/ */
virtual void updateProjection(void) = 0; virtual void updateProjection(void) = 0;
}; };
}//namespace cocos2d NS_CC_END
#endif // __CCPROTOCOLS_H__ #endif // __CCPROTOCOLS_H__
 End of changes. 14 change blocks. 
51 lines changed or deleted 50 lines changed or added


 CCRenderTexture.h   CCRenderTexture.h 
/************************************************************************** ** /************************************************************************** **
Copyright (c) 2010-2011 cocos2d-x.org Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2009 Jason Booth Copyright (c) 2009 Jason Booth
http://www.cocos2d-x.org http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a cop y Permission is hereby granted, free of charge, to any person obtaining a cop y
of this software and associated documentation files (the "Software"), to de al of this software and associated documentation files (the "Software"), to de al
in the Software without restriction, including without limitation the right s in the Software without restriction, including without limitation the right s
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
skipping to change at line 28 skipping to change at line 28
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CCRENDER_TEXTURE_H__ #ifndef __CCRENDER_TEXTURE_H__
#define __CCRENDER_TEXTURE_H__ #define __CCRENDER_TEXTURE_H__
#include "CCData.h" #include "base_nodes/CCNode.h"
#include "CCNode.h" #include "sprite_nodes/CCSprite.h"
#include "CCSprite.h" #include "kazmath/mat4.h"
namespace cocos2d { NS_CC_BEGIN
/**
* @addtogroup textures
* @{
*/
typedef enum eImageFormat typedef enum eImageFormat
{ {
kCCImageFormatJPG = 0, kCCImageFormatJPEG = 0,
kCCImageFormatPNG = 1, kCCImageFormatPNG = 1,
kCCImageFormatRawData = 2 } tCCImageFormat;
} tImageFormat;
/** /**
@brief CCRenderTexture is a generic rendering target. To render things into it, @brief CCRenderTexture is a generic rendering target. To render things into it,
simply construct a render target, call begin on it, call visit on any cocos simply construct a render target, call begin on it, call visit on any cocos
scenes or objects to render them, and call end. For convienience, render te xture scenes or objects to render them, and call end. For convienience, render te xture
adds a sprite as it's display child with the results, so you can simply add adds a sprite as it's display child with the results, so you can simply add
the render texture to your scene and treat it like any other CocosNode. the render texture to your scene and treat it like any other CocosNode.
There are also functions for saving the render texture to disk in PNG or JP G format. There are also functions for saving the render texture to disk in PNG or JP G format.
@since v0.8.1 @since v0.8.1
*/ */
class CC_DLL CCRenderTexture : public CCNode class CC_DLL CCRenderTexture : public CCNode
{ {
/** The CCSprite being used. /** The CCSprite being used.
The sprite, by default, will use the following blending function: GL_ON E, GL_ONE_MINUS_SRC_ALPHA. The sprite, by default, will use the following blending function: GL_ON E, GL_ONE_MINUS_SRC_ALPHA.
The blending function can be changed in runtime by calling: The blending function can be changed in runtime by calling:
- [[renderTexture sprite] setBlendFunc:(ccBlendFunc){GL_ONE, GL_ONE_MIN US_SRC_ALPHA}]; - [[renderTexture sprite] setBlendFunc:(ccBlendFunc){GL_ONE, GL_ONE_MIN US_SRC_ALPHA}];
*/ */
CC_PROPERTY(CCSprite*, m_pSprite, Sprite) CC_PROPERTY(CCSprite*, m_pSprite, Sprite)
public: public:
CCRenderTexture(); CCRenderTexture();
virtual ~CCRenderTexture(); virtual ~CCRenderTexture();
/** initializes a RenderTexture object with width and height in Points
and a pixel format( only RGB and RGBA formats are valid ) and depthStencil
format
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCRenderTexture * renderTextureWithWidth
AndHeight(int w ,int h, CCTexture2DPixelFormat eFormat, GLuint uDepthStenci
lFormat);
/** creates a RenderTexture object with width and height in Points and
a pixel format, only RGB and RGBA formats are valid
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCRenderTexture * renderTextureWithWidth
AndHeight(int w, int h, CCTexture2DPixelFormat eFormat);
/** creates a RenderTexture object with width and height in Points, pix
el format is RGBA8888
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCRenderTexture * renderTextureWithWidth
AndHeight(int w, int h);
/** initializes a RenderTexture object with width and height in Points
and a pixel format( only RGB and RGBA formats are valid ) and depthStencil
format*/
static CCRenderTexture * create(int w ,int h, CCTexture2DPixelFormat eF
ormat, GLuint uDepthStencilFormat);
/** creates a RenderTexture object with width and height in Points and a pixel format, only RGB and RGBA formats are valid */ /** creates a RenderTexture object with width and height in Points and a pixel format, only RGB and RGBA formats are valid */
static CCRenderTexture * renderTextureWithWidthAndHeight(int w, int h, CCTexture2DPixelFormat eFormat); static CCRenderTexture * create(int w, int h, CCTexture2DPixelFormat eF ormat);
/** creates a RenderTexture object with width and height in Points, pix el format is RGBA8888 */ /** creates a RenderTexture object with width and height in Points, pix el format is RGBA8888 */
static CCRenderTexture * renderTextureWithWidthAndHeight(int w, int h); static CCRenderTexture * create(int w, int h);
/** initializes a RenderTexture object with width and height in Points and a pixel format, only RGB and RGBA formats are valid */ /** initializes a RenderTexture object with width and height in Points and a pixel format, only RGB and RGBA formats are valid */
bool initWithWidthAndHeight(int w, int h, CCTexture2DPixelFormat eForma t); bool initWithWidthAndHeight(int w, int h, CCTexture2DPixelFormat eForma t);
/** initializes a RenderTexture object with width and height in Points
and a pixel format( only RGB and RGBA formats are valid ) and depthStencil
format*/
bool initWithWidthAndHeight(int w, int h, CCTexture2DPixelFormat eForma
t, GLuint uDepthStencilFormat);
/** starts grabbing */ /** starts grabbing */
void begin(); void begin();
/** starts rendering to the texture while clearing the texture first. /** starts rendering to the texture while clearing the texture first.
This is more efficient then calling -clear first and then -begin */ This is more efficient then calling -clear first and then -begin */
void beginWithClear(float r, float g, float b, float a); void beginWithClear(float r, float g, float b, float a);
/** starts rendering to the texture while clearing the texture first.
This is more efficient then calling -clear first and then -begin */
void beginWithClear(float r, float g, float b, float a, float depthValu
e);
/** starts rendering to the texture while clearing the texture first.
This is more efficient then calling -clear first and then -begin */
void beginWithClear(float r, float g, float b, float a, float depthValu
e, int stencilValue);
/** end is key word of lua, use other name to export to lua. */ /** end is key word of lua, use other name to export to lua. */
inline void endToLua(){ end();}; inline void endToLua(){ end();};
/** ends grabbing*/ /** ends grabbing*/
// para bIsTOCacheTexture the parameter is only used for andro void end();
id to cache the texture
void end(bool bIsTOCacheTexture = true);
/** clears the texture with a color */ /** clears the texture with a color */
void clear(float r, float g, float b, float a); void clear(float r, float g, float b, float a);
/** saves the texture into a file */ /** clears the texture with a specified depth value */
// para szFilePath the absolute path to save void clearDepth(float depthValue);
// para x,y the lower left corner coordinates of the buffer
to save /** clears the texture with a specified stencil value */
// pare nWidth,nHeight the size of the buffer to save void clearStencil(int stencilValue);
// when nWidth = 0 and nHeight = 0, the image /* creates a new CCImage from with the texture's data.
size to save equals to buffer texture size Caller is responsible for releasing it by calling delete.
bool saveBuffer(const char *szFilePath, int x = 0, int y = 0, int nW */
idth = 0, int nHeight = 0); CCImage* newCCImage();
/** saves the texture into a file. put format at the first argument, /** saves the texture into a file using JPEG format. The file will be s
or ti will be overloaded with aved in the Documents folder.
* saveBuffer(const char *szFilePath, int x = 0, int y = 0, int nWid Returns YES if the operation is successful.
th = 0, int nHeight = 0) */ */
// para name the file name to save bool saveToFile(const char *szFilePath);
// para format the image format to save, here it supports kCCIm
ageFormatPNG and kCCImageFormatJPG */ /** saves the texture into a file. The format could be JPG or PNG. The
// para x,y the lower left corner coordinates of the buffer file will be saved in the Documents folder.
to save Returns YES if the operation is successful.
// pare nWidth,nHeight the size of the buffer to save */
// when nWidth = 0 and nHeight = 0, the image bool saveToFile(const char *name, tCCImageFormat format);
size to save equals to buffer texture size
bool saveBuffer(int format, const char *name, int x = 0, int y = 0, /** Listen "come to background" message, and save render texture.
int nWidth = 0, int nHeight = 0); It only has effect on Android.
*/
/* get buffer as UIImage, can only save a render buffer which has a RGB void listenToBackground(CCObject *obj);
A8888 pixel format */
CCData *getUIImageAsDataFromBuffer(int format);
/** save the buffer data to a CCImage */
// para pImage the CCImage to save
// para x,y the lower left corner coordinates of the buffer
to save
// pare nWidth,nHeight the size of the buffer to save
// when nWidth = 0 and nHeight = 0, the image
size to save equals to buffer texture size
bool getUIImageFromBuffer(CCImage *pImage, int x = 0, int y = 0, int
nWidth = 0, int nHeight = 0);
protected: protected:
GLuint m_uFBO; GLuint m_uFBO;
GLint m_nOldFBO; GLuint m_uDepthRenderBufffer;
CCTexture2D *m_pTexture; GLint m_nOldFBO;
CCImage *m_pUITextureImage; CCTexture2D* m_pTexture;
GLenum m_ePixelFormat; CCImage* m_pUITextureImage;
GLenum m_ePixelFormat;
}; };
} // namespace cocos2d // end of textures group
/// @}
NS_CC_END
#endif //__CCRENDER_TEXTURE_H__ #endif //__CCRENDER_TEXTURE_H__
 End of changes. 16 change blocks. 
64 lines changed or deleted 104 lines changed or added


 CCSAXParser.h   CCSAXParser.h 
skipping to change at line 30 skipping to change at line 30
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
************************************************************************** **/ ************************************************************************** **/
#ifndef __CCSAXPARSER_H__ #ifndef __CCSAXPARSER_H__
#define __CCSAXPARSER_H__ #define __CCSAXPARSER_H__
#include "CCPlatformConfig.h" #include "CCPlatformConfig.h"
#include "CCCommon.h" #include "CCCommon.h"
NS_CC_BEGIN; NS_CC_BEGIN
/**
* @addtogroup platform
* @{
*/
typedef unsigned char CC_XML_CHAR; typedef unsigned char CC_XML_CHAR;
class CC_DLL CCSAXDelegator class CC_DLL CCSAXDelegator
{ {
public: public:
virtual void startElement(void *ctx, const char *name, const char ** virtual void startElement(void *ctx, const char *name, const char **att
atts) = 0; s) = 0;
virtual void endElement(void *ctx, const char *name) = 0; virtual void endElement(void *ctx, const char *name) = 0;
virtual void textHandler(void *ctx, const char *s, int len) = 0; virtual void textHandler(void *ctx, const char *s, int len) = 0;
}; };
class CC_DLL CCSAXParser class CC_DLL CCSAXParser
{ {
CCSAXDelegator* m_pDelegator; CCSAXDelegator* m_pDelegator;
public: public:
CCSAXParser(); CCSAXParser();
~CCSAXParser(void); ~CCSAXParser(void);
bool init(const char *pszEncoding); bool init(const char *pszEncoding);
bool parse(const char *pszFile); bool parse(const char* pXMLData, unsigned int uDataLength);
void setDelegator(CCSAXDelegator* pDelegator); bool parse(const char *pszFile);
void setDelegator(CCSAXDelegator* pDelegator);
static void startElement(void *ctx, const CC_XML_CHAR *name, const C
C_XML_CHAR **atts); static void startElement(void *ctx, const CC_XML_CHAR *name, const CC_X
static void endElement(void *ctx, const CC_XML_CHAR *name); ML_CHAR **atts);
static void textHandler(void *ctx, const CC_XML_CHAR *name, int len) static void endElement(void *ctx, const CC_XML_CHAR *name);
; static void textHandler(void *ctx, const CC_XML_CHAR *name, int len);
}; };
NS_CC_END;
// end of platform group
/// @}
NS_CC_END
#endif //__CCSAXPARSER_H__ #endif //__CCSAXPARSER_H__
 End of changes. 6 change blocks. 
18 lines changed or deleted 27 lines changed or added


 CCScene.h   CCScene.h 
/************************************************************************** ** /************************************************************************** **
Copyright (c) 2010-2011 cocos2d-x.org Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011 Zynga Inc. Copyright (c) 2011 Zynga Inc.
http://www.cocos2d-x.org http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a cop y Permission is hereby granted, free of charge, to any person obtaining a cop y
of this software and associated documentation files (the "Software"), to de al of this software and associated documentation files (the "Software"), to de al
in the Software without restriction, including without limitation the right s in the Software without restriction, including without limitation the right s
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
skipping to change at line 30 skipping to change at line 30
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CCSCENE_H__ #ifndef __CCSCENE_H__
#define __CCSCENE_H__ #define __CCSCENE_H__
#include "CCNode.h" #include "base_nodes/CCNode.h"
namespace cocos2d { NS_CC_BEGIN
/**
* @addtogroup scene
* @{
*/
/** @brief CCScene is a subclass of CCNode that is used only as an abstract concept. /** @brief CCScene is a subclass of CCNode that is used only as an abstract concept.
CCScene an CCNode are almost identical with the difference that CCScene has it's CCScene an CCNode are almost identical with the difference that CCScene has it's
anchor point (by default) at the center of the screen. anchor point (by default) at the center of the screen.
For the moment CCScene has no other logic than that, but in future releases it might have For the moment CCScene has no other logic than that, but in future releases it might have
additional logic. additional logic.
It is a good practice to use and CCScene as the parent of all your nodes. It is a good practice to use and CCScene as the parent of all your nodes.
*/ */
class CC_DLL CCScene : public CCNode class CC_DLL CCScene : public CCNode
{ {
public: public:
CCScene(); CCScene();
virtual ~CCScene(); virtual ~CCScene();
bool init(); bool init();
static CCScene *node(void); CC_DEPRECATED_ATTRIBUTE static CCScene *node(void);
static CCScene *create(void);
}; };
}//namespace cocos2d
// for the subclass of CCScene, each has to implement the static "node" met // end of scene group
hod /// @}
#define SCENE_NODE_FUNC(scene) \
static scene* node() \
{ \
scene *pRet = new scene(); \
if (pRet && pRet->init()) \
{ \
pRet->autorelease(); \
return pRet; \
} \
else \
{ \
delete pRet; \
pRet = NULL; \
return NULL; \
} \
};
#define SCENE_FUNC_PARAM(__TYPE__,__PARAMTYPE__,__PARAM__) \ NS_CC_END
static cocos2d::CCScene* node(__PARAMTYPE__ __PARAM__) \
{ \
cocos2d::CCScene * scene = NULL; \
do \
{ \
scene = cocos2d::CCScene::node(); \
CC_BREAK_IF(! scene); \
__TYPE__ *layer = __TYPE__::node(__PARAM__); \
CC_BREAK_IF(! layer); \
scene->addChild(layer); \
} while (0); \
return scene; \
};
#endif // __CCSCENE_H__ #endif // __CCSCENE_H__
 End of changes. 7 change blocks. 
40 lines changed or deleted 16 lines changed or added


 CCScheduler.h   CCScheduler.h 
skipping to change at line 30 skipping to change at line 30
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CCSCHEDULER_H__ #ifndef __CCSCHEDULER_H__
#define __CCSCHEDULER_H__ #define __CCSCHEDULER_H__
#include "CCObject.h" #include "cocoa/CCObject.h"
#include "support/data_support/uthash.h" #include "support/data_support/uthash.h"
namespace cocos2d { NS_CC_BEGIN
/**
* @addtogroup global
* @{
*/
// Priority level reserved for system services.
#define kCCPrioritySystem INT_MIN
// Minimum priority level for user scheduling.
#define kCCPriorityNonSystemMin (kCCPrioritySystem+1)
class CCSet;
// //
// CCTimer // CCTimer
// //
/** @brief Light weight timer */ /** @brief Light weight timer */
class CC_DLL CCTimer : public CCObject class CC_DLL CCTimer : public CCObject
{ {
public: public:
CCTimer(void); CCTimer(void);
/** get interval in seconds */ /** get interval in seconds */
inline ccTime getInterval(void) { return m_fInterval; } inline float getInterval(void) { return m_fInterval; }
/** set interval in seconds */ /** set interval in seconds */
inline void setInterval(ccTime fInterval){ m_fInterval = fInterval; inline void setInterval(float fInterval){ m_fInterval = fInterval; }
}
/** Initializes a timer with a target and a selector. */ /** Initializes a timer with a target and a selector. */
bool initWithTarget(CCObject *pTarget, SEL_SCHEDULE pfnSelector); bool initWithTarget(CCObject *pTarget, SEL_SCHEDULE pfnSelector);
/** Initializes a timer with a target, a selector and an interval in /** Initializes a timer with a target, a selector and an interval in se
seconds. */ conds, repeat in number of times to repeat, delay in seconds. */
bool initWithTarget(CCObject *pTarget, SEL_SCHEDULE pfnSelector, ccTime bool initWithTarget(CCObject *pTarget, SEL_SCHEDULE pfnSelector, float
fSeconds); fSeconds, unsigned int nRepeat, float fDelay);
/** Initializes a timer with a script callback function and an interval in seconds. */ /** Initializes a timer with a script callback function and an interval in seconds. */
bool initWithScriptHandler(int nHandler, ccTime fSeconds); bool initWithScriptHandler(int nHandler, float fSeconds);
/** triggers the timer */ /** triggers the timer */
void update(ccTime dt); void update(float dt);
public: public:
/** Allocates a timer with a target and a selector. */ /** Allocates a timer with a target and a selector. */
static CCTimer* timerWithTarget(CCObject *pTarget, SEL_SCHEDULE pfnS static CCTimer* timerWithTarget(CCObject *pTarget, SEL_SCHEDULE pfnSele
elector); ctor);
/** Allocates a timer with a target, a selector and an interval in s /** Allocates a timer with a target, a selector and an interval in seco
econds. */ nds. */
static CCTimer* timerWithTarget(CCObject *pTarget, SEL_SCHEDULE pfnS static CCTimer* timerWithTarget(CCObject *pTarget, SEL_SCHEDULE pfnSele
elector, ccTime fSeconds); ctor, float fSeconds);
/** Allocates a timer with a script callback function and an interval i n seconds. */ /** Allocates a timer with a script callback function and an interval i n seconds. */
static CCTimer* timerWithScriptHandler(int nHandler, ccTime fSeconds); static CCTimer* timerWithScriptHandler(int nHandler, float fSeconds);
public: public:
SEL_SCHEDULE m_pfnSelector; SEL_SCHEDULE m_pfnSelector;
ccTime m_fInterval; float m_fInterval;
protected: protected:
CCObject *m_pTarget; CCObject *m_pTarget;
ccTime m_fElapsed; float m_fElapsed;
bool m_bRunForever;
bool m_bUseDelay;
unsigned int m_nTimesExecuted;
unsigned int m_nRepeat; //0 = once, 1 is 2 x executed
float m_fDelay;
int m_nScriptHandler; int m_nScriptHandler;
}; };
// //
// CCScheduler // CCScheduler
// //
struct _listEntry; struct _listEntry;
struct _hashSelectorEntry; struct _hashSelectorEntry;
struct _hashUpdateEntry; struct _hashUpdateEntry;
skipping to change at line 104 skipping to change at line 122
- update selector: the 'update' selector will be called every frame. You ca n customize the priority. - update selector: the 'update' selector will be called every frame. You ca n customize the priority.
- custom selector: A custom selector will be called every frame, or with a custom interval of time - custom selector: A custom selector will be called every frame, or with a custom interval of time
The 'custom selectors' should be avoided when possible. It is faster, and c onsumes less memory to use the 'update selector'. The 'custom selectors' should be avoided when possible. It is faster, and c onsumes less memory to use the 'update selector'.
*/ */
class CC_DLL CCScheduler : public CCObject class CC_DLL CCScheduler : public CCObject
{ {
public: public:
CCScheduler();
~CCScheduler(void); ~CCScheduler(void);
inline ccTime getTimeScale(void) { return m_fTimeScale; } inline float getTimeScale(void) { return m_fTimeScale; }
/** Modifies the time of all scheduled callbacks. /** Modifies the time of all scheduled callbacks.
You can use this property to create a 'slow motion' or 'fast forward You can use this property to create a 'slow motion' or 'fast forward' e
' effect. ffect.
Default is 1.0. To create a 'slow motion' effect, use values below 1 Default is 1.0. To create a 'slow motion' effect, use values below 1.0.
.0. To create a 'fast forward' effect, use values higher than 1.0.
To create a 'fast forward' effect, use values higher than 1.0. @since v0.8
@since v0.8 @warning It will affect EVERY scheduled selector / action.
@warning It will affect EVERY scheduled selector / action. */
*/ inline void setTimeScale(float fTimeScale) { m_fTimeScale = fTimeScale;
inline void setTimeScale(ccTime fTimeScale) { m_fTimeScale = fTimeSc }
ale; }
/** 'update' the scheduler.
/** 'tick' the scheduler. You should NEVER call this method, unless you know what you are doing.
You should NEVER call this method, unless you know what you are doi */
ng. void update(float dt);
*/
void tick(ccTime dt); /** The scheduled method will be called every 'interval' seconds.
If paused is YES, then it won't be called until it is resumed.
/** The scheduled method will be called every 'interval' seconds. If 'interval' is 0, it will be called every frame, but if so, it recom
If paused is YES, then it won't be called until it is resumed. mened to use 'scheduleUpdateForTarget:' instead.
If 'interval' is 0, it will be called every frame, but if so, it re If the selector is already scheduled, then only the interval parameter
commened to use 'scheduleUpdateForTarget:' instead. will be updated without re-scheduling it again.
If the selector is already scheduled, then only the interval parame repeat let the action be repeated repeat + 1 times, use kCCRepeatForev
ter will be updated without re-scheduling it again. er to let the action run continiously
delay is the amount of time the action will wait before it'll start
@since v0.99.3
*/ @since v0.99.3, repeat and delay added in v1.1
void scheduleSelector(SEL_SCHEDULE pfnSelector, CCObject *pTarget, c */
cTime fInterval, bool bPaused); void scheduleSelector(SEL_SCHEDULE pfnSelector, CCObject *pTarget, floa
/** Schedules the 'update' selector for a given target with a given t fInterval, bool bPaused, unsigned int repeat, float delay);
priority.
The 'update' selector will be called every frame. /** calls scheduleSelector with kCCRepeatForever and a 0 delay */
The lower the priority, the earlier it is called. void scheduleSelector(SEL_SCHEDULE pfnSelector, CCObject *pTarget, floa
@since v0.99.3 t fInterval, bool bPaused);
*/ /** Schedules the 'update' selector for a given target with a given pri
void scheduleUpdateForTarget(CCObject *pTarget, int nPriority, bool ority.
bPaused); The 'update' selector will be called every frame.
The lower the priority, the earlier it is called.
/** Unschedule a selector for a given target. @since v0.99.3
If you want to unschedule the "update", use unscheudleUpdateForTarg */
et. void scheduleUpdateForTarget(CCObject *pTarget, int nPriority, bool bPa
@since v0.99.3 used);
*/
void unscheduleSelector(SEL_SCHEDULE pfnSelector, CCObject *pTarget) /** Unschedule a selector for a given target.
; If you want to unschedule the "update", use unscheudleUpdateForTarget.
@since v0.99.3
/** Unschedules the update selector for a given target */
@since v0.99.3 void unscheduleSelector(SEL_SCHEDULE pfnSelector, CCObject *pTarget);
*/
void unscheduleUpdateForTarget(const CCObject *pTarget); /** Unschedules the update selector for a given target
@since v0.99.3
/** Unschedules all selectors for a given target. */
This also includes the "update" selector. void unscheduleUpdateForTarget(const CCObject *pTarget);
@since v0.99.3
*/ /** Unschedules all selectors for a given target.
void unscheduleAllSelectorsForTarget(CCObject *pTarget); This also includes the "update" selector.
@since v0.99.3
/** Unschedules all selectors from all targets. */
You should NEVER call this method, unless you know what you are doi void unscheduleAllSelectorsForTarget(CCObject *pTarget);
ng.
/** Unschedules all selectors from all targets.
@since v0.99.3 You should NEVER call this method, unless you know what you are doing.
*/
void unscheduleAllSelectors(void); @since v0.99.3
*/
void unscheduleAllSelectors(void);
/** Unschedules all selectors from all targets with a minimum priority.
You should only call this with kCCPriorityNonSystemMin or higher.
@since v2.0.0
*/
void unscheduleAllSelectorsWithMinPriority(int nMinPriority);
/** The scheduled script callback will be called every 'interval' secon ds. /** The scheduled script callback will be called every 'interval' secon ds.
If paused is YES, then it won't be called until it is resumed. If paused is YES, then it won't be called until it is resumed.
If 'interval' is 0, it will be called every frame. If 'interval' is 0, it will be called every frame.
return schedule script entry ID, used for unscheduleScriptFunc(). return schedule script entry ID, used for unscheduleScriptFunc().
*/ */
unsigned int scheduleScriptFunc(unsigned int nHandler, ccTime fInterval , bool bPaused); unsigned int scheduleScriptFunc(unsigned int nHandler, float fInterval, bool bPaused);
/** Unschedule a script entry. */ /** Unschedule a script entry. */
void unscheduleScriptEntry(unsigned int uScheduleScriptEntryID); void unscheduleScriptEntry(unsigned int uScheduleScriptEntryID);
/** Pauses the target. /** Pauses the target.
All scheduled selectors/update for a given target won't be 'ticked' All scheduled selectors/update for a given target won't be 'ticked' un
until the target is resumed. til the target is resumed.
If the target is not present, nothing happens. If the target is not present, nothing happens.
@since v0.99.3 @since v0.99.3
*/ */
void pauseTarget(CCObject *pTarget); void pauseTarget(CCObject *pTarget);
/** Resumes the target. /** Resumes the target.
The 'target' will be unpaused, so all schedule selectors/update wil The 'target' will be unpaused, so all schedule selectors/update will b
l be 'ticked' again. e 'ticked' again.
If the target is not present, nothing happens. If the target is not present, nothing happens.
@since v0.99.3 @since v0.99.3
*/ */
void resumeTarget(CCObject *pTarget); void resumeTarget(CCObject *pTarget);
/** Returns whether or not the target is paused /** Returns whether or not the target is paused
@since v1.0.0 @since v1.0.0
*/ */
bool isTargetPaused(CCObject *pTarget); bool isTargetPaused(CCObject *pTarget);
public: /** Pause all selectors from all targets.
/** returns a shared instance of the Scheduler */ You should NEVER call this method, unless you know what you are doing
static CCScheduler* sharedScheduler(void); .
@since v2.0.0
/** purges the shared scheduler. It releases the retained instance. */
@since v0.99.0 CCSet* pauseAllTargets();
*/
static void purgeSharedScheduler(void); /** Pause all selectors from all targets with a minimum priority.
You should only call this with kCCPriorityNonSystemMin or higher.
@since v2.0.0
*/
CCSet* pauseAllTargetsWithMinPriority(int nMinPriority);
/** Resume selectors on a set of targets.
This can be useful for undoing a call to pauseAllSelectors.
@since v2.0.0
*/
void resumeTargets(CCSet* targetsToResume);
private: private:
void removeHashElement(struct _hashSelectorEntry *pElement); void removeHashElement(struct _hashSelectorEntry *pElement);
void removeUpdateFromHash(struct _listEntry *entry); void removeUpdateFromHash(struct _listEntry *entry);
CCScheduler();
bool init(void);
// update specific // update specific
void priorityIn(struct _listEntry **ppList, CCObject *pTarget, int n void priorityIn(struct _listEntry **ppList, CCObject *pTarget, int nPri
Priority, bool bPaused); ority, bool bPaused);
void appendIn(struct _listEntry **ppList, CCObject *pTarget, bool bP void appendIn(struct _listEntry **ppList, CCObject *pTarget, bool bPaus
aused); ed);
protected: protected:
ccTime m_fTimeScale; float m_fTimeScale;
// //
// "updates with priority" stuff // "updates with priority" stuff
// //
struct _listEntry *m_pUpdatesNegList; // list of priority struct _listEntry *m_pUpdatesNegList; // list of priority < 0
< 0 struct _listEntry *m_pUpdates0List; // list priority == 0
struct _listEntry *m_pUpdates0List; // list prio struct _listEntry *m_pUpdatesPosList; // list priority > 0
rity == 0 struct _hashUpdateEntry *m_pHashForUpdates; // hash used to fetch quick
struct _listEntry *m_pUpdatesPosList; // list priority > 0 ly the list entries for pause,delete,etc
struct _hashUpdateEntry *m_pHashForUpdates; // hash used to fetch qu
ickly the list entries for pause,delete,etc // Used for "selectors with interval"
struct _hashSelectorEntry *m_pHashForSelectors;
// Used for "selectors with interval" struct _hashSelectorEntry *m_pCurrentTarget;
struct _hashSelectorEntry *m_pHashForSelectors; bool m_bCurrentTargetSalvaged;
struct _hashSelectorEntry *m_pCurrentTarget; // If true unschedule will not remove anything from a hash. Elements wi
bool m_bCurrentTargetSalvaged; ll only be marked for deletion.
// If true unschedule will not remove anything from a hash. Elements bool m_bUpdateHashLocked;
will only be marked for deletion.
bool m_bUpdateHashLocked;
CCArray* m_pScriptHandlerEntries; CCArray* m_pScriptHandlerEntries;
}; };
}//namespace cocos2d
// end of global group
/// @}
NS_CC_END
#endif // __CCSCHEDULER_H__ #endif // __CCSCHEDULER_H__
 End of changes. 27 change blocks. 
149 lines changed or deleted 185 lines changed or added


 CCScriptSupport.h   CCScriptSupport.h 
skipping to change at line 28 skipping to change at line 28
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __SCRIPT_SUPPORT_H__ #ifndef __SCRIPT_SUPPORT_H__
#define __SCRIPT_SUPPORT_H__ #define __SCRIPT_SUPPORT_H__
#include "CCCommon.h" #include "platform/CCCommon.h"
#include "CCTouch.h" #include "touch_dispatcher/CCTouch.h"
#include "CCSet.h" #include "cocoa/CCSet.h"
typedef struct lua_State lua_State; typedef struct lua_State lua_State;
NS_CC_BEGIN NS_CC_BEGIN
class CCTimer; class CCTimer;
/**
* @addtogroup script_support
* @{
*/
// Lua support for CCScheduler // Lua support for CCScheduler
class CCSchedulerScriptHandlerEntry : public CCObject class CCSchedulerScriptHandlerEntry : public CCObject
{ {
public: public:
// nHandler return by tolua_ref_function(), called from LuaCocos2d.cpp // nHandler return by tolua_ref_function(), called from LuaCocos2d.cpp
static CCSchedulerScriptHandlerEntry* entryWithHandler(int nHandler, cc Time fInterval, bool bPaused); static CCSchedulerScriptHandlerEntry* entryWithHandler(int nHandler, fl oat fInterval, bool bPaused);
~CCSchedulerScriptHandlerEntry(void); ~CCSchedulerScriptHandlerEntry(void);
inline cocos2d::CCTimer* getTimer(void) { inline cocos2d::CCTimer* getTimer(void) {
return m_pTimer; return m_pTimer;
} }
inline bool isPaused(void) { inline bool isPaused(void) {
return m_bPaused; return m_bPaused;
} }
skipping to change at line 68 skipping to change at line 73
inline void markedForDeletion(void) { inline void markedForDeletion(void) {
m_bMarkedForDeletion = true; m_bMarkedForDeletion = true;
} }
inline bool isMarkedForDeletion(void) { inline bool isMarkedForDeletion(void) {
return m_bMarkedForDeletion; return m_bMarkedForDeletion;
} }
private: private:
CCSchedulerScriptHandlerEntry(void); CCSchedulerScriptHandlerEntry(void);
bool initWithHandler(int nHandler, ccTime fInterval, bool bPaused); bool initWithHandler(int nHandler, float fInterval, bool bPaused);
cocos2d::CCTimer* m_pTimer; cocos2d::CCTimer* m_pTimer;
bool m_bPaused; bool m_bPaused;
bool m_bMarkedForDeletion; bool m_bMarkedForDeletion;
int m_nHandler; int m_nHandler;
int m_nEntryID; int m_nEntryID;
}; };
// Lua support for touch events // Lua support for touch events
class CCTouchScriptHandlerEntry : public CCObject class CCTouchScriptHandlerEntry : public CCObject
{ {
public: public:
static CCTouchScriptHandlerEntry* entryWithHandler(int nHandler, bool b IsMultiTouches, int nPriority, bool bSwallowsTouches); static CCTouchScriptHandlerEntry* entryWithHandler(int nHandler, bool b IsMultiTouches, int nPriority, bool bSwallowsTouches);
~CCTouchScriptHandlerEntry(void); ~CCTouchScriptHandlerEntry(void);
inline int getHandler(void) { inline int getHandler(void) {
return m_nHandler; return m_nHandler;
} }
inline bool getIsMultiTouches(void) { inline bool isMultiTouches(void) {
return m_bIsMultiTouches; return m_bIsMultiTouches;
} }
inline int getPriority(void) { inline int getPriority(void) {
return m_nPriority; return m_nPriority;
} }
inline bool getSwallowsTouches(void) { inline bool getSwallowsTouches(void) {
return m_bSwallowsTouches; return m_bSwallowsTouches;
} }
skipping to change at line 126 skipping to change at line 131
*/ */
virtual lua_State* getLuaState(void) = 0; virtual lua_State* getLuaState(void) = 0;
/** /**
@brief Remove CCObject from lua state @brief Remove CCObject from lua state
@param object to remove @param object to remove
*/ */
virtual void removeCCObjectByID(int nLuaID) = 0; virtual void removeCCObjectByID(int nLuaID) = 0;
/** /**
@brief Remove Lua function reference @brief Remove Lua function handler
*/ */
virtual void removeLuaHandler(int nHandler) = 0; virtual void removeLuaHandler(int nHandler) = 0;
/** /**
@brief Add a path to find lua files in @brief Add a path to find lua files in
@param path to be added to the Lua path @param path to be added to the Lua path
*/ */
virtual void addSearchPath(const char* path) = 0; virtual void addSearchPath(const char* path) = 0;
/** /**
skipping to change at line 159 skipping to change at line 164
/** /**
@brief Execute a scripted global function. @brief Execute a scripted global function.
@brief The function should not take any parameters and should return a n integer. @brief The function should not take any parameters and should return a n integer.
@param functionName String object holding the name of the function, in the global script environment, that is to be executed. @param functionName String object holding the name of the function, in the global script environment, that is to be executed.
@return The integer value returned from the script function. @return The integer value returned from the script function.
*/ */
virtual int executeGlobalFunction(const char* functionName) = 0; virtual int executeGlobalFunction(const char* functionName) = 0;
/** /**
@brief Execute a function by ref id @brief Execute a function by handler
@param The function ref id @param The function handler
@param Number of parameters @param Number of parameters
@return The integer value returned from the script function. @return The integer value returned from the script function.
*/ */
virtual int executeFunctionByRefID(int nHandler, int numArgs = 0) = 0; virtual int executeFunctionByHandler(int nHandler, int numArgs = 0) = 0 ;
virtual int executeFunctionWithIntegerData(int nHandler, int data) = 0; virtual int executeFunctionWithIntegerData(int nHandler, int data) = 0;
virtual int executeFunctionWithFloatData(int nHandler, float data) = 0; virtual int executeFunctionWithFloatData(int nHandler, float data) = 0;
virtual int executeFunctionWithBooleanData(int nHandler, bool data) = 0 ; virtual int executeFunctionWithBooleanData(int nHandler, bool data) = 0 ;
virtual int executeFunctionWithCCObject(int nHandler, CCObject* pObject
, const char* typeName) = 0;
virtual int pushIntegerToLuaStack(int data) = 0;
virtual int pushFloatToLuaStack(int data) = 0;
virtual int pushBooleanToLuaStack(int data) = 0;
virtual int pushCCObjectToLuaStack(CCObject* pObject, const char* typeN
ame) = 0;
// functions for excute touch event // functions for excute touch event
virtual int executeTouchEvent(int nHandler, int eventType, CCTouch *pTo uch) = 0; virtual int executeTouchEvent(int nHandler, int eventType, CCTouch *pTo uch) = 0;
virtual int executeTouchesEvent(int nHandler, int eventType, CCSet *pTo uches) = 0; virtual int executeTouchesEvent(int nHandler, int eventType, CCSet *pTo uches) = 0;
// execute a schedule function // execute a schedule function
virtual int executeSchedule(int nHandler, ccTime dt) = 0; virtual int executeSchedule(int nHandler, float dt) = 0;
}; };
/** /**
CCScriptEngineManager is a singleton which holds an object instance of CCS criptEngineProtocl CCScriptEngineManager is a singleton which holds an object instance of CCS criptEngineProtocl
It helps cocos2d-x and the user code to find back LuaEngine object It helps cocos2d-x and the user code to find back LuaEngine object
@since v0.99.5-x-0.8.5 @since v0.99.5-x-0.8.5
*/ */
class CC_DLL CCScriptEngineManager class CC_DLL CCScriptEngineManager
{ {
public: public:
~CCScriptEngineManager(void); ~CCScriptEngineManager(void);
CCScriptEngineProtocol* getScriptEngine(void) { CCScriptEngineProtocol* getScriptEngine(void) {
return m_pScriptEngine; return m_pScriptEngine;
} }
void setScriptEngine(CCScriptEngineProtocol *pScriptEngine); void setScriptEngine(CCScriptEngineProtocol *pScriptEngine);
void removeScriptEngine(void); void removeScriptEngine(void);
static CCScriptEngineManager* sharedManager(void); static CCScriptEngineManager* sharedManager(void);
static void purgeSharedManager(void); static void purgeSharedManager(void);
private: private:
CCScriptEngineManager(void) CCScriptEngineManager(void)
: m_pScriptEngine(NULL) : m_pScriptEngine(NULL)
{ {
} }
CCScriptEngineProtocol *m_pScriptEngine; CCScriptEngineProtocol *m_pScriptEngine;
}; };
// end of script_support group
/// @}
NS_CC_END NS_CC_END
#endif // __SCRIPT_SUPPORT_H__ #endif // __SCRIPT_SUPPORT_H__
 End of changes. 15 change blocks. 
15 lines changed or deleted 30 lines changed or added


 CCSet.h   CCSet.h 
/************************************************************************** ** /************************************************************************** **
Copyright (c) 2010 cocos2d-x.org Copyright (c) 2010-2012 cocos2d-x.org
http://www.cocos2d-x.org http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a cop y Permission is hereby granted, free of charge, to any person obtaining a cop y
of this software and associated documentation files (the "Software"), to de al of this software and associated documentation files (the "Software"), to de al
in the Software without restriction, including without limitation the right s in the Software without restriction, including without limitation the right s
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
skipping to change at line 25 skipping to change at line 25
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __NS_SET_H__ #ifndef __CC_SET_H__
#define __NS_SET_H__ #define __CC_SET_H__
#include <set> #include <set>
#include "CCObject.h" #include "CCObject.h"
namespace cocos2d { NS_CC_BEGIN
/**
* @addtogroup data_structures
* @{
*/
typedef std::set<CCObject *>::iterator CCSetIterator; typedef std::set<CCObject *>::iterator CCSetIterator;
class CC_DLL CCSet : public CCObject class CC_DLL CCSet : public CCObject
{ {
public: public:
CCSet(void); CCSet(void);
CCSet(const CCSet &rSetObject); CCSet(const CCSet &rSetObject);
virtual ~CCSet(void); virtual ~CCSet(void);
/** /**
*@brief Return a copy of the CCSet, it will copy all the elelments. *@brief Return a copy of the CCSet, it will copy all the elelments.
*/ */
CCSet* copy(); CCSet* copy();
/** /**
*@brief It is the same as copy(). *@brief It is the same as copy().
*/ */
CCSet* mutableCopy(); CCSet* mutableCopy();
/** /**
*@brief Return the number of elements the CCSet contains. *@brief Return the number of elements the CCSet contains.
*/ */
int count(); int count();
/** /**
*@brief Add a element into CCSet, it will retain the element. *@brief Add a element into CCSet, it will retain the element.
*/ */
void addObject(CCObject *pObject); void addObject(CCObject *pObject);
/** /**
*@brief Remove the given element, nothing todo if no element equals *@brief Remove the given element, nothing todo if no element equals pOb
pObject. ject.
*/ */
void removeObject(CCObject *pObject); void removeObject(CCObject *pObject);
/** /**
*@brief Check if CCSet contains a element equals pObject. *@brief Check if CCSet contains a element equals pObject.
*/ */
bool containsObject(CCObject *pObject); bool containsObject(CCObject *pObject);
/** /**
*@brief Return the iterator that points to the first element. *@brief Return the iterator that points to the first element.
*/ */
CCSetIterator begin(); CCSetIterator begin();
/** /**
*@brief Return the iterator that points to the poisition after the l *@brief Return the iterator that points to the poisition after the last
ast element. element.
*/ */
CCSetIterator end(); CCSetIterator end();
/** /**
*@brief Return the first element if it contains elements, or null if *@brief Return the first element if it contains elements, or null if it
it doesn't contain any element. doesn't contain any element.
*/ */
CCObject* anyObject(); CCObject* anyObject();
private: private:
std::set<CCObject *> *m_pSet; std::set<CCObject *> *m_pSet;
}; };
}//namespace cocos2d // end of data_structure group
/// @}
NS_CC_END
#endif // __NS_SET_H__ #endif // __CC_SET_H__
 End of changes. 6 change blocks. 
47 lines changed or deleted 55 lines changed or added


 CCSprite.h   CCSprite.h 
skipping to change at line 30 skipping to change at line 30
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __SPITE_NODE_CCSPRITE_H__ #ifndef __SPITE_NODE_CCSPRITE_H__
#define __SPITE_NODE_CCSPRITE_H__ #define __SPITE_NODE_CCSPRITE_H__
#include "CCNode.h" #include "base_nodes/CCNode.h"
#include "CCProtocols.h" #include "CCProtocols.h"
#include "CCTextureAtlas.h" #include "textures/CCTextureAtlas.h"
#include "ccTypes.h" #include "ccTypes.h"
#include "CCMutableDictionary.h" #include "cocoa/CCDictionary.h"
#include <string> #include <string>
namespace cocos2d {
NS_CC_BEGIN
class CCSpriteBatchNode; class CCSpriteBatchNode;
class CCSpriteFrame; class CCSpriteFrame;
class CCAnimation; class CCAnimation;
class CCRect; class CCRect;
class CCPoint; class CCPoint;
class CCSize; class CCSize;
class CCTexture2D; class CCTexture2D;
struct transformValues_; struct transformValues_;
#define CCSpriteIndexNotInitialized 0xffffffff /// CCSprite invalid
index on the CCSpriteBatchode
/** /**
Whether or not an CCSprite will rotate, scale or translate with it's paren * @addtogroup sprite_nodes
t. * @{
Useful in health bars, when you want that the health bar translates with i
t's parent but you don't
want it to rotate with its parent.
@since v0.99.0
*/ */
typedef enum {
//! Translate with it's parent
CC_HONOR_PARENT_TRANSFORM_TRANSLATE = 1 << 0,
//! Rotate with it's parent
CC_HONOR_PARENT_TRANSFORM_ROTATE = 1 << 1,
//! Scale with it's parent
CC_HONOR_PARENT_TRANSFORM_SCALE = 1 << 2,
//! Skew with it's parent
CC_HONOR_PARENT_TRANSFORM_SKEW = 1 << 3,
//! All possible transformation enabled. Default value. #define CCSpriteIndexNotInitialized 0xffffffff /// CCSprite invalid ind
CC_HONOR_PARENT_TRANSFORM_ALL = CC_HONOR_PARENT_TRANSFORM ex on the CCSpriteBatchode
_TRANSLATE | CC_HONOR_PARENT_TRANSFORM_ROTATE | CC_HONOR_PARENT_TRANSFORM_S
CALE | CC_HONOR_PARENT_TRANSFORM_SKEW,
} ccHonorParentTransform;
/** CCSprite is a 2d image ( http://en.wikipedia.org/wiki/Sprite_(computer_ graphics) ) /** CCSprite is a 2d image ( http://en.wikipedia.org/wiki/Sprite_(computer_ graphics) )
* *
* CCSprite can be created with an image, or with a sub-rectangle of an imag e. * CCSprite can be created with an image, or with a sub-rectangle of an imag e.
* *
* If the parent or any of its ancestors is a CCSpriteBatchNode then the fol lowing features/limitations are valid * If the parent or any of its ancestors is a CCSpriteBatchNode then the fol lowing features/limitations are valid
* - Features when the parent is a CCBatchNode: * - Features when the parent is a CCBatchNode:
* - MUCH faster rendering, specially if the CCSpriteBatchNode * - MUCH faster rendering, specially if the CCSpriteBatchNode has ma
has many children. All the children will be drawn in a single batch. ny children. All the children will be drawn in a single batch.
* *
* - Limitations * - Limitations
* - Camera is not supported yet (eg: CCOrbitCamera action does * - Camera is not supported yet (eg: CCOrbitCamera action doesn't wo
n't work) rk)
* - GridBase actions are not supported (eg: CCLens, CCRipple, * - GridBase actions are not supported (eg: CCLens, CCRipple, CCTwir
CCTwirl) l)
* - The Alias/Antialias property belongs to CCSpriteBatchNode, * - The Alias/Antialias property belongs to CCSpriteBatchNode, so yo
so you can't individually set the aliased property. u can't individually set the aliased property.
* - The Blending function property belongs to CCSpriteBatchNod * - The Blending function property belongs to CCSpriteBatchNode, so
e, so you can't individually set the blending function property. you can't individually set the blending function property.
* - Parallax scroller is not supported, but can be simulated w * - Parallax scroller is not supported, but can be simulated with a
ith a "proxy" sprite. "proxy" sprite.
* *
* If the parent is an standard CCNode, then CCSprite behaves like any othe r CCNode: * If the parent is an standard CCNode, then CCSprite behaves like any othe r CCNode:
* - It supports blending functions * - It supports blending functions
* - It supports aliasing / antialiasing * - It supports aliasing / antialiasing
* - But the rendering will be slower: 1 draw per children. * - But the rendering will be slower: 1 draw per children.
* *
* The default anchorPoint in CCSprite is (0.5, 0.5). * The default anchorPoint in CCSprite is (0.5, 0.5).
*/ */
class CC_DLL CCSprite : public CCNode, public CCTextureProtocol, public CCR GBAProtocol class CC_DLL CCSprite : public CCNode, public CCTextureProtocol, public CCR GBAProtocol
{ {
/** Opacity: conforms to CCRGBAProtocol protocol */ /** Opacity: conforms to CCRGBAProtocol protocol */
CC_PROPERTY(GLubyte, m_nOpacity, Opacity) CC_PROPERTY(GLubyte, m_nOpacity, Opacity)
/** Color: conforms with CCRGBAProtocol protocol */ /** Color: conforms with CCRGBAProtocol protocol */
CC_PROPERTY_PASS_BY_REF(ccColor3B, m_sColor, Color); CC_PROPERTY_PASS_BY_REF(ccColor3B, m_sColor, Color);
public: public:
virtual void draw(void); virtual void draw(void);
public: public:
// attributes // attributes
/** whether or not the Sprite needs to be updated in the Atlas */ /** whether or not the Sprite needs to be updated in the Atlas */
inline bool isDirty(void) { return m_bDirty; } inline virtual bool isDirty(void) { return m_bDirty; }
/** make the Sprite to be updated in the Atlas. */ /** make the Sprite to be updated in the Atlas. */
inline void setDirty(bool bDirty) { m_bDirty = bDirty; } inline virtual void setDirty(bool bDirty) { m_bDirty = bDirty; }
/** get the quad (tex coords, vertex coords and color) information * /** get the quad (tex coords, vertex coords and color) information */
/ inline ccV3F_C4B_T2F_Quad getQuad(void) { return m_sQuad; }
inline ccV3F_C4B_T2F_Quad getQuad(void) { return m_sQuad; }
/** returns whether or not the texture rectangle is rotated */
/** returns whether or not the texture rectangle is rotated */ inline bool isTextureRectRotated(void) { return m_bRectRotated; }
inline bool isTextureRectRotated(void) { return m_bRectRotated; }
/** Set the index used on the TextureAtlas. */
/** Set the index used on the TextureAtlas. */ inline unsigned int getAtlasIndex(void) { return m_uAtlasIndex; }
inline unsigned int getAtlasIndex(void) { return m_uAtlasIndex; } /** Set the index used on the TextureAtlas.
/** Set the index used on the TextureAtlas. @warning Don't modify this value unless you know what you are doing
@warning Don't modify this value unless you know what you are doing */
*/ inline void setAtlasIndex(unsigned int uAtlasIndex) { m_uAtlasIndex = u
inline void setAtlasIndex(unsigned int uAtlasIndex) { m_uAtlasIndex AtlasIndex; }
= uAtlasIndex; }
/** returns the rect of the CCSprite in points */
/** returns the rect of the CCSprite in points */ inline const CCRect& getTextureRect(void) { return m_obRect; }
inline const CCRect& getTextureRect(void) { return m_obRect; }
inline CCTextureAtlas* getTextureAtlas(void) { return m_pobTextureAtlas
/** whether or not the Sprite is rendered using a CCSpriteBatchNode ; }
*/ inline void setTextureAtlas(CCTextureAtlas *pobTextureAtlas) { m_pobTex
inline bool isUsesBatchNode(void) { return m_bUsesBatchNode; } tureAtlas = pobTextureAtlas; }
/** make the Sprite been rendered using a CCSpriteBatchNode */
inline void setUsesSpriteBatchNode(bool bUsesSpriteBatchNode) { m_bU CCSpriteBatchNode* getSpriteBatchNode(void);
sesBatchNode = bUsesSpriteBatchNode; } void setSpriteBatchNode(CCSpriteBatchNode *pobSpriteBatchNode);
inline CCTextureAtlas* getTextureAtlas(void) { return m_pobTextureAt /** Get offset position of the sprite. Calculated automatically by edit
las; } ors like Zwoptex.
inline void setTextureAtlas(CCTextureAtlas *pobTextureAtlas) { m_pob @since v0.99.0
TextureAtlas = pobTextureAtlas; } */
inline const CCPoint& getOffsetPosition(void) { return m_obOffsetPositi
inline CCSpriteBatchNode* getSpriteBatchNode(void) { return m_pobBat on; }
chNode; }
inline void setSpriteBatchNode(CCSpriteBatchNode *pobSpriteBatchNode /** conforms to CCTextureProtocol protocol */
) { m_pobBatchNode = pobSpriteBatchNode; } inline ccBlendFunc getBlendFunc(void) { return m_sBlendFunc; }
/** conforms to CCTextureProtocol protocol */
/** whether or not to transform according to its parent transformati inline void setBlendFunc(ccBlendFunc blendFunc) { m_sBlendFunc = blendF
ons. unc; }
Useful for health bars. eg: Don't rotate the health bar, even if th
e parent rotates.
IMPORTANT: Only valid if it is rendered using an CCSpriteSheet.
@since v0.99.0
*/
inline ccHonorParentTransform getHonorParentTransform(void) { return
m_eHonorParentTransform; }
/** whether or not to transform according to its parent transformati
ons.
Useful for health bars. eg: Don't rotate the health bar, even if the
parent rotates.
IMPORTANT: Only valid if it is rendered using an CCSpriteSheet.
@since v0.99.0
*/
inline void setHonorParentTransform(ccHonorParentTransform eHonorPar
entTransform) { m_eHonorParentTransform = eHonorParentTransform; }
/** Get offset position of the sprite. Calculated automatically by e
ditors like Zwoptex.
@since v0.99.0
*/
inline const CCPoint& getOffsetPositionInPixels(void) { return m_obO
ffsetPositionInPixels; }
/** conforms to CCTextureProtocol protocol */
inline ccBlendFunc getBlendFunc(void) { return m_sBlendFunc; }
/** conforms to CCTextureProtocol protocol */
inline void setBlendFunc(ccBlendFunc blendFunc) { m_sBlendFunc = ble
ndFunc; }
public: public:
/** Creates an sprite with a texture. /** Creates an sprite with a texture.
The rect used will be the size of the texture. The rect used will be the size of the texture.
The offset will be (0,0). The offset will be (0,0).
*/ @deprecated: Please use createWithTexture(CCTexture2D*) instead. This
static CCSprite* spriteWithTexture(CCTexture2D *pTexture); interface will be deprecated sooner or later.
*/
/** Creates an sprite with a texture and a rect. CC_DEPRECATED_ATTRIBUTE static CCSprite* spriteWithTexture(CCTexture2D
The offset will be (0,0). *pTexture);
*/
static CCSprite* spriteWithTexture(CCTexture2D *pTexture, const CCRe /** Creates an sprite with a texture and a rect.
ct& rect); The offset will be (0,0).
@deprecated: Please use createWithTexture(CCTexture2D*, const CCRect&)
/** Creates an sprite with a texture, a rect and offset. */ instead, This interface will be deprecated sooner or later.
static CCSprite* spriteWithTexture(CCTexture2D *pTexture, const CCRect& */
rect, const CCPoint& offset); CC_DEPRECATED_ATTRIBUTE static CCSprite* spriteWithTexture(CCTexture2D
*pTexture, const CCRect& rect);
/** Creates an sprite with an sprite frame. */
static CCSprite* spriteWithSpriteFrame(CCSpriteFrame *pSpriteFrame); /** Creates an sprite with a texture.
The rect used will be the size of the texture.
/** Creates an sprite with an sprite frame name. The offset will be (0,0).
An CCSpriteFrame will be fetched from the CCSpriteFrameCache by nam */
e. static CCSprite* createWithTexture(CCTexture2D *pTexture);
If the CCSpriteFrame doesn't exist it will raise an exception.
@since v0.9 /** Creates an sprite with a texture and a rect.
*/ The offset will be (0,0).
static CCSprite* spriteWithSpriteFrameName(const char *pszSpriteFram */
eName); static CCSprite* createWithTexture(CCTexture2D *pTexture, const CCRect&
rect);
/** Creates an sprite with an image filename.
The rect used will be the size of the image. /** Creates an sprite with an sprite frame.
The offset will be (0,0). @deprecated: Please use createWithSpriteFrame(CCSpriteFrame*) instead.
*/ This interface will be deprecated sooner or later.
static CCSprite* spriteWithFile(const char *pszFileName); */
CC_DEPRECATED_ATTRIBUTE static CCSprite* spriteWithSpriteFrame(CCSprite
/** Creates an sprite with an image filename and a rect. Frame *pSpriteFrame);
The offset will be (0,0).
*/ /** Creates an sprite with an sprite frame name.
static CCSprite* spriteWithFile(const char *pszFileName, const CCRec An CCSpriteFrame will be fetched from the CCSpriteFrameCache by name.
t& rect); If the CCSpriteFrame doesn't exist it will raise an exception.
@deprecated: Please use createWithSpriteFrameName(const char*) instead
/** Creates an sprite with an CCBatchNode and a rect . This interface will be deprecated sooner or later.
*/ @since v0.9
static CCSprite* spriteWithBatchNode(CCSpriteBatchNode *batchNode, c */
onst CCRect& rect); CC_DEPRECATED_ATTRIBUTE static CCSprite* spriteWithSpriteFrameName(cons
t char *pszSpriteFrameName);
/** Creates an sprite with an sprite frame. */
static CCSprite* createWithSpriteFrame(CCSpriteFrame *pSpriteFrame);
/** Creates an sprite with an sprite frame name.
An CCSpriteFrame will be fetched from the CCSpriteFrameCache by name.
If the CCSpriteFrame doesn't exist it will raise an exception.
@since v0.9
*/
static CCSprite* createWithSpriteFrameName(const char *pszSpriteFrameNa
me);
/** Creates an sprite with an image filename.
The rect used will be the size of the image.
The offset will be (0,0).
@deprecated: Please use create(const char*) instead. This interface wi
ll be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCSprite* spriteWithFile(const char *psz
FileName);
/** Creates an sprite with an image filename and a rect.
The offset will be (0,0).
@deprecated: Please use create(const char*, const CCRect&) instead. Th
is interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCSprite* spriteWithFile(const char *psz
FileName, const CCRect& rect);
/** Creates an sprite with an image filename.
The rect used will be the size of the image.
The offset will be (0,0).
*/
static CCSprite* create(const char *pszFileName);
/** Creates an sprite with an image filename and a rect.
The offset will be (0,0).
*/
static CCSprite* create(const char *pszFileName, const CCRect& rect);
/** Creates an sprite.
@deprecated: Please use create() instead. This interface will be deprec
ated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCSprite* node();
/** Creates an sprite.
*/
static CCSprite* create();
public: public:
CCSprite(void); CCSprite(void);
virtual ~CCSprite(void); virtual ~CCSprite(void);
virtual bool init(void); virtual bool init(void);
virtual void removeChild(CCNode* pChild, bool bCleanup); virtual void removeChild(CCNode* pChild, bool bCleanup);
virtual void removeAllChildrenWithCleanup(bool bCleanup); virtual void removeAllChildrenWithCleanup(bool bCleanup);
virtual void reorderChild(CCNode *pChild, int zOrder); virtual void reorderChild(CCNode *pChild, int zOrder);
virtual void addChild(CCNode *pChild); virtual void addChild(CCNode *pChild);
virtual void addChild(CCNode *pChild, int zOrder); virtual void addChild(CCNode *pChild, int zOrder);
virtual void addChild(CCNode *pChild, int zOrder, int tag); virtual void addChild(CCNode *pChild, int zOrder, int tag);
virtual void sortAllChildren();
virtual void setDirtyRecursively(bool bValue);
virtual void setPosition(const CCPoint& pos); virtual void setDirtyRecursively(bool bValue);
virtual void setPositionInPixels(const CCPoint& pos); virtual void setPosition(const CCPoint& pos);
virtual void setRotation(float fRotation); virtual void setRotation(float fRotation);
virtual void setSkewX(float sx); virtual void setSkewX(float sx);
virtual void setSkewY(float sy); virtual void setSkewY(float sy);
virtual void setScaleX(float fScaleX); virtual void setScaleX(float fScaleX);
virtual void setScaleY(float fScaleY); virtual void setScaleY(float fScaleY);
virtual void setScale(float fScale); virtual void setScale(float fScale);
virtual void setVertexZ(float fVertexZ); virtual void setVertexZ(float fVertexZ);
virtual void setAnchorPoint(const CCPoint& anchor); virtual void setAnchorPoint(const CCPoint& anchor);
virtual void setIsRelativeAnchorPoint(bool bRelative); virtual void ignoreAnchorPointForPosition(bool value);
virtual void setIsVisible(bool bVisible); virtual void setVisible(bool bVisible);
void setFlipX(bool bFlipX); void setFlipX(bool bFlipX);
void setFlipY(bool bFlipY); void setFlipY(bool bFlipY);
/** whether or not the sprite is flipped horizontally. /** whether or not the sprite is flipped horizontally.
It only flips the texture of the sprite, and not the texture of the It only flips the texture of the sprite, and not the texture of the spr
sprite's children. ite's children.
Also, flipping the texture doesn't alter the anchorPoint. Also, flipping the texture doesn't alter the anchorPoint.
If you want to flip the anchorPoint too, and/or to flip the children If you want to flip the anchorPoint too, and/or to flip the children to
too use: o use:
sprite->setScaleX(sprite->getScaleX() * -1); sprite->setScaleX(sprite->getScaleX() * -1);
*/ */
bool isFlipX(void); bool isFlipX(void);
/** whether or not the sprite is flipped vertically. /** whether or not the sprite is flipped vertically.
It only flips the texture of the sprite, and not the texture of the It only flips the texture of the sprite, and not the texture of the spr
sprite's children. ite's children.
Also, flipping the texture doesn't alter the anchorPoint. Also, flipping the texture doesn't alter the anchorPoint.
If you want to flip the anchorPoint too, and/or to flip the children If you want to flip the anchorPoint too, and/or to flip the children to
too use: o use:
sprite->setScaleY(sprite->getScaleY() * -1); sprite->setScaleY(sprite->getScaleY() * -1);
*/ */
bool isFlipY(void); bool isFlipY(void);
void updateColor(void); void updateColor(void);
// RGBAProtocol // RGBAProtocol
/** opacity: conforms to CCRGBAProtocol protocol */ /** opacity: conforms to CCRGBAProtocol protocol */
virtual void setIsOpacityModifyRGB(bool bValue); virtual void setOpacityModifyRGB(bool bValue);
virtual bool getIsOpacityModifyRGB(void); virtual bool isOpacityModifyRGB(void);
// CCTextureProtocol // CCTextureProtocol
virtual void setTexture(CCTexture2D *texture); virtual void setTexture(CCTexture2D *texture);
virtual CCTexture2D* getTexture(void); virtual CCTexture2D* getTexture(void);
/** Initializes an sprite with a texture. /** Initializes an sprite with a texture.
The rect used will be the size of the texture. The rect used will be the size of the texture.
The offset will be (0,0). The offset will be (0,0).
*/ */
bool initWithTexture(CCTexture2D *pTexture); virtual bool initWithTexture(CCTexture2D *pTexture);
/** Initializes an sprite with a texture and a rect. /** Initializes an sprite with a texture and a rect.
The offset will be (0,0). The offset will be (0,0).
*/ */
bool initWithTexture(CCTexture2D *pTexture, const CCRect& rect); virtual bool initWithTexture(CCTexture2D *pTexture, const CCRect& rect)
;
// Initializes an sprite with an sprite frame.
bool initWithSpriteFrame(CCSpriteFrame *pSpriteFrame); /** Initializes an sprite with a texture and a rect in points, optional
ly rotated.
/** Initializes an sprite with an sprite frame name. The offset will be (0,0).
An CCSpriteFrame will be fetched from the CCSpriteFrameCache by nam IMPORTANT: This is the designated initializer.
e. */
If the CCSpriteFrame doesn't exist it will raise an exception. virtual bool initWithTexture(CCTexture2D *pTexture, const CCRect& rect,
@since v0.9 bool rotated);
*/
bool initWithSpriteFrameName(const char *pszSpriteFrameName); // Initializes an sprite with an sprite frame.
virtual bool initWithSpriteFrame(CCSpriteFrame *pSpriteFrame);
/** Initializes an sprite with an image filename.
The rect used will be the size of the image. /** Initializes an sprite with an sprite frame name.
The offset will be (0,0). An CCSpriteFrame will be fetched from the CCSpriteFrameCache by name.
*/ If the CCSpriteFrame doesn't exist it will raise an exception.
bool initWithFile(const char *pszFilename); @since v0.9
*/
/** Initializes an sprite with an image filename, and a rect. virtual bool initWithSpriteFrameName(const char *pszSpriteFrameName);
The offset will be (0,0).
*/ /** Initializes an sprite with an image filename.
bool initWithFile(const char *pszFilename, const CCRect& rect); The rect used will be the size of the image.
The offset will be (0,0).
/** Initializes an sprite with an CCSpriteBatchNode and a rect in po */
ints */ virtual bool initWithFile(const char *pszFilename);
bool initWithBatchNode(CCSpriteBatchNode *batchNode, const CCRect& r
ect); /** Initializes an sprite with an image filename, and a rect.
The offset will be (0,0).
/** Initializes an sprite with an CCSpriteBatchNode and a rect in pi */
xels virtual bool initWithFile(const char *pszFilename, const CCRect& rect);
@since v0.99.5
*/ // BatchNode methods
bool initWithBatchNodeRectInPixels(CCSpriteBatchNode *batchNode, con
st CCRect& rect); /** updates the quad according the the rotation, position, scale values
. */
// BatchNode methods virtual void updateTransform(void);
/** updates the quad according the the rotation, position, scale val /** updates the texture rect of the CCSprite in points.
ues. */ It will call setTextureRect:rotated:untrimmedSize with rotated = NO, an
void updateTransform(void); d utrimmedSize = rect.size.
*/
/** tell the sprite to use self-render. virtual void setTextureRect(const CCRect& rect);
@since v0.99.0
*/ /** set the texture rect, rectRotated and untrimmed size of the CCSpri
void useSelfRender(void); te in points.
It will update the texture coordinates and the vertex rectangle.
/** updates the texture rect of the CCSprite in points. */ */
void setTextureRect(const CCRect& rect); virtual void setTextureRect(const CCRect& rect, bool rotated, const CC
Size& untrimmedSize);
/** updates the texture rect, rectRotated and untrimmed size of the
CCSprite in pixels /** set the vertex rect.
*/ It will be called internally by setTextureRect. Useful if you want to
void setTextureRectInPixels(const CCRect& rect, bool rotated, const create 2x images from SD images in Retina Display.
CCSize& size); Do not call it manually. Use setTextureRect instead.
*/
/** tell the sprite to use batch node render. virtual void setVertexRect(const CCRect& rect);
@since v0.99.0
*/ // Frames
void useBatchNode(CCSpriteBatchNode *batchNode);
/** sets a new display frame to the CCSprite. */
// Frames virtual void setDisplayFrame(CCSpriteFrame *pNewFrame);
/** sets a new display frame to the CCSprite. */ /** returns whether or not a CCSpriteFrame is being displayed */
void setDisplayFrame(CCSpriteFrame *pNewFrame); virtual bool isFrameDisplayed(CCSpriteFrame *pFrame);
/** returns whether or not a CCSpriteFrame is being displayed */ /** returns the current displayed frame. */
bool isFrameDisplayed(CCSpriteFrame *pFrame); virtual CCSpriteFrame* displayFrame(void);
/** returns the current displayed frame. */ virtual CCSpriteBatchNode* getBatchNode(void);
CCSpriteFrame* displayedFrame(void); virtual void setBatchNode(CCSpriteBatchNode *pobSpriteBatchNode);
// Animation // Animation
/** changes the display frame with animation name and index. /** changes the display frame with animation name and index.
The animation name will be get from the CCAnimationCache The animation name will be get from the CCAnimationCache
@since v0.99.5 @since v0.99.5
*/ */
void setDisplayFrameWithAnimationName(const char *animationName, int virtual void setDisplayFrameWithAnimationName(const char *animationName
frameIndex); , int frameIndex);
protected: protected:
void updateTextureCoords(const CCRect& rect); virtual void setTextureCoords(CCRect rect);
void updateBlendFunc(void); virtual void updateBlendFunc(void);
void getTransformValues(struct transformValues_ *tv); // optimization virtual void setReorderChildDirtyRecursively(void);
protected: protected:
// //
// Data used when the sprite is rendered using a CCSpriteSheet // Data used when the sprite is rendered using a CCSpriteSheet
// //
CCTextureAtlas *m_pobTextureAtlas; // S CCTextureAtlas* m_pobTextureAtlas; // Sprite Sheet texture a
prite Sheet texture atlas (weak reference) tlas (weak reference)
unsigned int m_uAtlasIndex; // A unsigned int m_uAtlasIndex; // Absolute (real) Index
bsolute (real) Index on the SpriteSheet on the SpriteSheet
CCSpriteBatchNode *m_pobBatchNode; // Used batch node ( CCSpriteBatchNode* m_pobBatchNode; // Used batch node (weak ref
weak reference) erence)
ccHonorParentTransform m_eHonorParentTransform;// whether or not to
transform according to its parent transformations bool m_bDirty; // Sprite needs to be upda
bool m_bDirty; ted
// Sprite needs to be updated bool m_bRecursiveDirty; // Subchildren needs to b
bool m_bRecursiveDirty; e updated
// Subchildren needs to be updated bool m_bHasChildren; // optimization to check
bool m_bHasChildren; if it contain children
// optimization to check if it contain children bool m_bShouldBeHidden; // should not be drawn be
cause one of the ancestors is not visible
// CCAffineTransform m_transformToBatch; //
// Data used when the sprite is self-rendered
// //
ccBlendFunc m_sBlendFunc; // Needed for the texture pr // Data used when the sprite is self-rendered
otocol //
CCTexture2D *m_pobTexture;// Texture used to render the ccBlendFunc m_sBlendFunc; // Needed for the texture protocol
sprite CCTexture2D* m_pobTexture;// Texture used to render the sprite
// //
// Shared data // Shared data
// //
// whether or not it's parent is a CCSpriteBatchNode // texture
bool m_bUsesBatchNode; CCRect m_obRect;
bool m_bRectRotated;
// texture
CCRect m_obRect; // Offset Position (used by Zwoptex)
CCRect m_obRectInPixels; CCPoint m_obOffsetPosition;
bool m_bRectRotated; CCPoint m_obUnflippedOffsetPositionFromCenter;
// Offset Position (used by Zwoptex) // vertex coords, texture coords and color info
CCPoint m_obOffsetPositionInPixels; // absolute ccV3F_C4B_T2F_Quad m_sQuad;
CCPoint m_obUnflippedOffsetPositionFromCenter;
// opacity and RGB protocol
// vertex coords, texture coords and color info ccColor3B m_sColorUnmodified;
ccV3F_C4B_T2F_Quad m_sQuad; bool m_bOpacityModifyRGB;
// opacity and RGB protocol // image is flipped
ccColor3B m_sColorUnmodified; bool m_bFlipX;
bool m_bOpacityModifyRGB; bool m_bFlipY;
// image is flipped
bool m_bFlipX;
bool m_bFlipY;
}; };
}//namespace cocos2d
// end of sprite_nodes group
/// @}
NS_CC_END
#endif // __SPITE_NODE_CCSPRITE_H__ #endif // __SPITE_NODE_CCSPRITE_H__
 End of changes. 24 change blocks. 
359 lines changed or deleted 359 lines changed or added


 CCSpriteBatchNode.h   CCSpriteBatchNode.h 
/************************************************************************** ** /************************************************************************** **
Copyright (c) 2010-2011 cocos2d-x.org Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2009-2010 Ricardo Quesada Copyright (c) 2009-2010 Ricardo Quesada
Copyright (C) 2009 Matt Oswald Copyright (C) 2009 Matt Oswald
Copyright (c) 2011 Zynga Inc. Copyright (c) 2011 Zynga Inc.
http://www.cocos2d-x.org http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a cop y Permission is hereby granted, free of charge, to any person obtaining a cop y
of this software and associated documentation files (the "Software"), to de al of this software and associated documentation files (the "Software"), to de al
in the Software without restriction, including without limitation the right s in the Software without restriction, including without limitation the right s
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
skipping to change at line 31 skipping to change at line 31
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CC_SPRITE_BATCH_NODE_H__ #ifndef __CC_SPRITE_BATCH_NODE_H__
#define __CC_SPRITE_BATCH_NODE_H__ #define __CC_SPRITE_BATCH_NODE_H__
#include "CCNode.h" #include "base_nodes/CCNode.h"
#include "CCProtocols.h" #include "CCProtocols.h"
#include "CCTextureAtlas.h" #include "textures/CCTextureAtlas.h"
#include "ccMacros.h" #include "ccMacros.h"
#include "CCMutableArray.h" #include "cocoa/CCArray.h"
namespace cocos2d NS_CC_BEGIN
/**
* @addtogroup sprite_nodes
* @{
*/
#define kDefaultSpriteBatchCapacity 29
class CCSprite;
/** CCSpriteBatchNode is like a batch node: if it contains children, it wil
l draw them in 1 single OpenGL call
* (often known as "batch draw").
*
* A CCSpriteBatchNode can reference one and only one texture (one image fil
e, one texture atlas).
* Only the CCSprites that are contained in that texture can be added to the
CCSpriteBatchNode.
* All CCSprites added to a CCSpriteBatchNode are drawn in one OpenGL ES dra
w call.
* If the CCSprites are not added to a CCSpriteBatchNode then an OpenGL ES d
raw call will be needed for each one, which is less efficient.
*
*
* Limitations:
* - The only object that is accepted as child (or grandchild, grand-grandc
hild, etc...) is CCSprite or any subclass of CCSprite. eg: particles, label
s and layer can't be added to a CCSpriteBatchNode.
* - Either all its children are Aliased or Antialiased. It can't be a mix.
This is because "alias" is a property of the texture, and all the sprites
share the same texture.
*
* @since v0.7.1
*/
class CC_DLL CCSpriteBatchNode : public CCNode, public CCTextureProtocol
{ {
class CCSprite; public:
~CCSpriteBatchNode();
// property
// retain
inline CCTextureAtlas* getTextureAtlas(void) { return m_pobTextureAtlas
; }
inline void setTextureAtlas(CCTextureAtlas* textureAtlas)
{
if (textureAtlas != m_pobTextureAtlas)
{
CC_SAFE_RETAIN(textureAtlas);
CC_SAFE_RELEASE(m_pobTextureAtlas);
m_pobTextureAtlas = textureAtlas;
}
}
inline CCArray* getDescendants(void) { return m_pobDescendants; }
/** creates a CCSpriteBatchNode with a texture2d and capacity of childr
en.
The capacity will be increased in 33% in runtime if it run out of space
.
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCSpriteBatchNode* batchNodeWithTexture(
CCTexture2D* tex, unsigned int capacity = kDefaultSpriteBatchCapacity);
/** creates a CCSpriteBatchNode with a file image (.png, .jpeg, .pvr, e
tc) and capacity of children.
The capacity will be increased in 33% in runtime if it run out of space
.
The file will be loaded using the TextureMgr.
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCSpriteBatchNode* batchNodeWithFile(con
st char* fileImage, unsigned int capacity = kDefaultSpriteBatchCapacity);
/** creates a CCSpriteBatchNode with a texture2d and capacity of childr
en.
The capacity will be increased in 33% in runtime if it run out of space
.
*/
static CCSpriteBatchNode* createWithTexture(CCTexture2D* tex, unsigned
int capacity = kDefaultSpriteBatchCapacity);
/** creates a CCSpriteBatchNode with a file image (.png, .jpeg, .pvr, e
tc) and capacity of children.
The capacity will be increased in 33% in runtime if it run out of space
.
The file will be loaded using the TextureMgr.
*/
static CCSpriteBatchNode* create(const char* fileImage, unsigned int ca
pacity = kDefaultSpriteBatchCapacity);
/** initializes a CCSpriteBatchNode with a texture2d and capacity of ch
ildren.
The capacity will be increased in 33% in runtime if it run out of space
.
*/
bool initWithTexture(CCTexture2D *tex, unsigned int capacity);
/** initializes a CCSpriteBatchNode with a file image (.png, .jpeg, .pv
r, etc) and a capacity of children.
The capacity will be increased in 33% in runtime if it run out of space
.
The file will be loaded using the TextureMgr.
*/
bool initWithFile(const char* fileImage, unsigned int capacity);
bool init();
void increaseAtlasCapacity();
/** removes a child given a certain index. It will also cleanup the run
ning actions depending on the cleanup parameter.
@warning Removing a child from a CCSpriteBatchNode is very slow
*/
void removeChildAtIndex(unsigned int index, bool doCleanup);
void insertChild(CCSprite *child, unsigned int index);
void appendChild(CCSprite* sprite);
void removeSpriteFromAtlas(CCSprite *sprite);
unsigned int rebuildIndexInOrder(CCSprite *parent, unsigned int index);
unsigned int highestAtlasIndexInChild(CCSprite *sprite);
unsigned int lowestAtlasIndexInChild(CCSprite *sprite);
unsigned int atlasIndexForChild(CCSprite *sprite, int z);
/* Sprites use this to start sortChildren, don't call this manually */
void reorderBatch(bool reorder);
// CCTextureProtocol
virtual CCTexture2D* getTexture(void);
virtual void setTexture(CCTexture2D *texture);
virtual void setBlendFunc(ccBlendFunc blendFunc);
virtual ccBlendFunc getBlendFunc(void);
virtual void visit(void);
virtual void addChild(CCNode * child);
virtual void addChild(CCNode * child, int zOrder);
virtual void addChild(CCNode * child, int zOrder, int tag);
virtual void reorderChild(CCNode * child, int zOrder);
virtual void removeChild(CCNode* child, bool cleanup);
virtual void removeAllChildrenWithCleanup(bool cleanup);
virtual void sortAllChildren();
virtual void draw(void);
protected:
/* IMPORTANT XXX IMPORTNAT:
* These 2 methods can't be part of CCTMXLayer since they call [super ad
d...], and CCSpriteSheet#add SHALL not be called
*/
/* Adds a quad into the texture atlas but it won't be added into the ch
ildren array.
This method should be called only when you are dealing with very big At
lasSrite and when most of the CCSprite won't be updated.
For example: a tile map (CCTMXMap) or a label with lots of characters (
BitmapFontAtlas)
*/
void addQuadFromSprite(CCSprite *sprite, unsigned int index);
/* This is the opposite of "addQuadFromSprite.
It add the sprite to the children and descendants array, but it doesn't
update add it to the texture atlas
*/
CCSpriteBatchNode * addSpriteWithoutQuad(CCSprite*child, unsigned int z
, int aTag);
private:
void updateAtlasIndex(CCSprite* sprite, int* curIndex);
void swap(int oldIndex, int newIndex);
void updateBlendFunc();
protected:
CCTextureAtlas *m_pobTextureAtlas;
ccBlendFunc m_blendFunc;
// all descendants: chlidren, gran children, etc...
CCArray* m_pobDescendants;
};
// end of sprite_nodes group
/// @}
/** CCSpriteBatchNode is like a batch node: if it contains children, NS_CC_END
it will draw them in 1 single OpenGL call
* (often known as "batch draw").
*
* A CCSpriteBatchNode can reference one and only one texture (one im
age file, one texture atlas).
* Only the CCSprites that are contained in that texture can be added
to the CCSpriteBatchNode.
* All CCSprites added to a CCSpriteBatchNode are drawn in one OpenGL
ES draw call.
* If the CCSprites are not added to a CCSpriteBatchNode then an Open
GL ES draw call will be needed for each one, which is less efficient.
*
*
* Limitations:
* - The only object that is accepted as child (or grandchild, grand
-grandchild, etc...) is CCSprite or any subclass of CCSprite. eg: particles
, labels and layer can't be added to a CCSpriteBatchNode.
* - Either all its children are Aliased or Antialiased. It can't be
a mix. This is because "alias" is a property of the texture, and all the s
prites share the same texture.
*
* @since v0.7.1
*/
class CC_DLL CCSpriteBatchNode : public CCNode, public CCTextureProt
ocol
{
public:
~CCSpriteBatchNode();
// property
// retain
inline CCTextureAtlas* getTextureAtlas(void) { return m_pobT
extureAtlas; }
inline void setTextureAtlas(CCTextureAtlas* textureAtlas)
{
if (textureAtlas != m_pobTextureAtlas)
{
CC_SAFE_RETAIN(textureAtlas);
CC_SAFE_RELEASE(m_pobTextureAtlas);
m_pobTextureAtlas = textureAtlas;
}
}
inline CCArray* getDescendants(void) { return m_pobDescendan
ts; }
/** creates a CCSpriteBatchNode with a texture2d and a defau
lt capacity of 29 children.
The capacity will be increased in 33% in runtime if it run o
ut of space.
*/
static CCSpriteBatchNode* batchNodeWithTexture(CCTexture2D *
tex);
/** creates a CCSpriteBatchNode with a texture2d and capacit
y of children.
The capacity will be increased in 33% in runtime if it run o
ut of space.
*/
static CCSpriteBatchNode* batchNodeWithTexture(CCTexture2D*
tex, unsigned int capacity);
/** creates a CCSpriteBatchNode with a file image (.png, .jp
eg, .pvr, etc) with a default capacity of 29 children.
The capacity will be increased in 33% in runtime if it run o
ut of space.
The file will be loaded using the TextureMgr.
*/
static CCSpriteBatchNode* batchNodeWithFile(const char* file
Image);
/** creates a CCSpriteBatchNode with a file image (.png, .jp
eg, .pvr, etc) and capacity of children.
The capacity will be increased in 33% in runtime if it run o
ut of space.
The file will be loaded using the TextureMgr.
*/
static CCSpriteBatchNode* batchNodeWithFile(const char* file
Image, unsigned int capacity);
/** initializes a CCSpriteBatchNode with a texture2d and cap
acity of children.
The capacity will be increased in 33% in runtime if it run o
ut of space.
*/
bool initWithTexture(CCTexture2D *tex, unsigned int capacity
);
/** initializes a CCSpriteBatchNode with a file image (.png,
.jpeg, .pvr, etc) and a capacity of children.
The capacity will be increased in 33% in runtime if it run o
ut of space.
The file will be loaded using the TextureMgr.
*/
bool initWithFile(const char* fileImage, unsigned int capaci
ty);
void increaseAtlasCapacity();
/** removes a child given a certain index. It will also clea
nup the running actions depending on the cleanup parameter.
@warning Removing a child from a CCSpriteBatchNode is very s
low
*/
void removeChildAtIndex(unsigned int index, bool doCleanup);
void insertChild(CCSprite *child, unsigned int index);
void removeSpriteFromAtlas(CCSprite *sprite);
unsigned int rebuildIndexInOrder(CCSprite *parent, unsigned
int index);
unsigned int highestAtlasIndexInChild(CCSprite *sprite);
unsigned int lowestAtlasIndexInChild(CCSprite *sprite);
unsigned int atlasIndexForChild(CCSprite *sprite, int z);
// CCTextureProtocol
virtual CCTexture2D* getTexture(void);
virtual void setTexture(CCTexture2D *texture);
virtual void setBlendFunc(ccBlendFunc blendFunc);
virtual ccBlendFunc getBlendFunc(void);
virtual void visit(void);
virtual void addChild(CCNode * child);
virtual void addChild(CCNode * child, int zOrder);
virtual void addChild(CCNode * child, int zOrder, int tag);
virtual void reorderChild(CCNode * child, int zOrder);
virtual void removeChild(CCNode* child, bool cleanup);
virtual void removeAllChildrenWithCleanup(bool cleanup);
virtual void draw(void);
protected:
/* IMPORTANT XXX IMPORTNAT:
* These 2 methods can't be part of CCTMXLayer since they call [supe
r add...], and CCSpriteSheet#add SHALL not be called
*/
/* Adds a quad into the texture atlas but it won't be added into th
e children array.
This method should be called only when you are dealing with very bi
g AtlasSrite and when most of the CCSprite won't be updated.
For example: a tile map (CCTMXMap) or a label with lots of characte
rs (BitmapFontAtlas)
*/
void addQuadFromSprite(CCSprite *sprite, unsigned int index);
/* This is the opposite of "addQuadFromSprite.
It add the sprite to the children and descendants array, but it doe
sn't update add it to the texture atlas
*/
CCSpriteBatchNode * addSpriteWithoutQuad(CCSprite*child, unsigned i
nt z, int aTag);
private:
void updateBlendFunc();
protected:
CCTextureAtlas *m_pobTextureAtlas;
ccBlendFunc m_blendFunc;
// all descendants: chlidren, gran children, etc...
CCArray* m_pobDescendants;
};
}
#endif // __CC_SPRITE_BATCH_NODE_H__ #endif // __CC_SPRITE_BATCH_NODE_H__
 End of changes. 7 change blocks. 
170 lines changed or deleted 183 lines changed or added


 CCSpriteFrame.h   CCSpriteFrame.h 
skipping to change at line 30 skipping to change at line 30
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __SPRITE_CCSPRITE_FRAME_H__ #ifndef __SPRITE_CCSPRITE_FRAME_H__
#define __SPRITE_CCSPRITE_FRAME_H__ #define __SPRITE_CCSPRITE_FRAME_H__
#include "CCNode.h" #include "base_nodes/CCNode.h"
#include "CCProtocols.h" #include "CCProtocols.h"
#include "CCObject.h" #include "cocoa/CCObject.h"
#include "cocoa/CCGeometry.h"
NS_CC_BEGIN
namespace cocos2d {
class CCRect;
class CCPoint;
class CCSize;
class CCTexture2D; class CCTexture2D;
class CCZone; class CCZone;
/**
* @addtogroup sprite_nodes
* @{
*/
/** @brief A CCSpriteFrame has: /** @brief A CCSpriteFrame has:
- texture: A CCTexture2D that will be used by the CCSprite - texture: A CCTexture2D that will be used by the CCSprite
- rectangle: A rectangle of the texture - rectangle: A rectangle of the texture
You can modify the frame of a CCSprite by doing: You can modify the frame of a CCSprite by doing:
CCSpriteFrame *frame = CCSpriteFrame::frameWithTexture(texture, rect CCSpriteFrame *frame = CCSpriteFrame::frameWithTexture(texture, rect, o
, offset); ffset);
sprite->setDisplayFrame(frame); sprite->setDisplayFrame(frame);
*/ */
class CC_DLL CCSpriteFrame : public CCObject class CC_DLL CCSpriteFrame : public CCObject
{ {
public: public:
// attributes // attributes
inline const CCRect& getRectInPixels(void) { return m_obRectInPixels inline const CCRect& getRectInPixels(void) { return m_obRectInPixels; }
; } void setRectInPixels(const CCRect& rectInPixels);
void setRectInPixels(const CCRect& rectInPixels);
inline bool isRotated(void) { return m_bRotated; } inline bool isRotated(void) { return m_bRotated; }
inline void setRotated(bool bRotated) { m_bRotated = bRotated; } inline void setRotated(bool bRotated) { m_bRotated = bRotated; }
/** get rect of the frame */ /** get rect of the frame */
inline const CCRect& getRect(void) { return m_obRect; } inline const CCRect& getRect(void) { return m_obRect; }
/** set rect of the frame */ /** set rect of the frame */
void setRect(const CCRect& rect); void setRect(const CCRect& rect);
/** get offset of the frame */ /** get offset of the frame */
inline const CCPoint& getOffsetInPixels(void) { return m_obOffsetInP const CCPoint& getOffsetInPixels(void);
ixels; } /** set offset of the frame */
/** set offset of the frame */ void setOffsetInPixels(const CCPoint& offsetInPixels);
inline void setOffsetInPixels(const CCPoint& offsetInPixels) { m_obO
ffsetInPixels = offsetInPixels; } /** get original size of the trimmed image */
inline const CCSize& getOriginalSizeInPixels(void) { return m_obOrigina
/** get original size of the trimmed image */ lSizeInPixels; }
inline const CCSize& getOriginalSizeInPixels(void) { return m_obOrig /** set original size of the trimmed image */
inalSizeInPixels; } inline void setOriginalSizeInPixels(const CCSize& sizeInPixels) { m_obO
/** set original size of the trimmed image */ riginalSizeInPixels = sizeInPixels; }
inline void setOriginalSizeInPixels(const CCSize& sizeInPixels) { m_
obOriginalSizeInPixels = sizeInPixels; } /** get original size of the trimmed image */
inline const CCSize& getOriginalSize(void) { return m_obOriginalSize; }
/** get texture of the frame */ /** set original size of the trimmed image */
inline CCTexture2D* getTexture(void) { return m_pobTexture; } inline void setOriginalSize(const CCSize& sizeInPixels) { m_obOriginalS
/** set texture of the frame, the texture is retained */ ize = sizeInPixels; }
inline void setTexture(CCTexture2D* pobTexture)
{ /** get texture of the frame */
CC_SAFE_RETAIN(pobTexture); CCTexture2D* getTexture(void);
CC_SAFE_RELEASE(m_pobTexture); /** set texture of the frame, the texture is retained */
m_pobTexture = pobTexture; void setTexture(CCTexture2D* pobTexture);
}
const CCPoint& getOffset(void);
void setOffset(const CCPoint& offsets);
public: public:
~CCSpriteFrame(void); ~CCSpriteFrame(void);
virtual CCObject* copyWithZone(CCZone *pZone); virtual CCObject* copyWithZone(CCZone *pZone);
/** Create a CCSpriteFrame with a texture, rect in points. /** Create a CCSpriteFrame with a texture, rect in points.
It is assumed that the frame was not trimmed. @deprecated: This interface will be deprecated sooner or later.
*/ It is assumed that the frame was not trimmed.
static CCSpriteFrame* frameWithTexture(CCTexture2D* pobTexture, cons */
t CCRect& rect); CC_DEPRECATED_ATTRIBUTE static CCSpriteFrame* frameWithTexture(CCTextur
e2D* pobTexture, const CCRect& rect);
/** Create a CCSpriteFrame with a texture, rect, rotated, offset and
originalSize in pixels. /** Create a CCSpriteFrame with a texture filename, rect in points.
The originalSize is the size in points of the frame before being tr It is assumed that the frame was not trimmed.
immed. @deprecated: This interface will be deprecated sooner or later.
*/ */
static CCSpriteFrame* frameWithTexture(CCTexture2D* pobTexture, const C CC_DEPRECATED_ATTRIBUTE static CCSpriteFrame* frameWithTextureFilename(
CRect& rect, bool rotated, const CCPoint& offset, const CCSize& originalSiz const char* filename, const CCRect& rect);
e);
/** Create a CCSpriteFrame with a texture, rect, rotated, offset and or
iginalSize in pixels.
The originalSize is the size in points of the frame before being trimm
ed.
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCSpriteFrame* frameWithTexture(CCTextur
e2D* pobTexture, const CCRect& rect, bool rotated, const CCPoint& offset, c
onst CCSize& originalSize);
/** Create a CCSpriteFrame with a texture filename, rect, rotated, offs
et and originalSize in pixels.
The originalSize is the size in pixels of the frame before being trimm
ed.
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCSpriteFrame* frameWithTextureFilename(
const char* filename, const CCRect& rect, bool rotated, const CCPoint& offs
et, const CCSize& originalSize);
/** Create a CCSpriteFrame with a texture filename, rect in points.
It is assumed that the frame was not trimmed.
*/
static CCSpriteFrame* create(const char* filename, const CCRect& rect);
/** Create a CCSpriteFrame with a texture filename, rect, rotated, offs
et and originalSize in pixels.
The originalSize is the size in pixels of the frame before being trimm
ed.
*/
static CCSpriteFrame* create(const char* filename, const CCRect& rect,
bool rotated, const CCPoint& offset, const CCSize& originalSize);
/** Create a CCSpriteFrame with a texture, rect in points.
It is assumed that the frame was not trimmed.
*/
static CCSpriteFrame* createWithTexture(CCTexture2D* pobTexture, const
CCRect& rect);
/** Create a CCSpriteFrame with a texture, rect, rotated, offset and or
iginalSize in pixels.
The originalSize is the size in points of the frame before being trimm
ed.
*/
static CCSpriteFrame* createWithTexture(CCTexture2D* pobTexture, const
CCRect& rect, bool rotated, const CCPoint& offset, const CCSize& originalSi
ze);
public: public:
/** Initializes a CCSpriteFrame with a texture, rect in points. /** Initializes a CCSpriteFrame with a texture, rect in points.
It is assumed that the frame was not trimmed. It is assumed that the frame was not trimmed.
*/ */
bool initWithTexture(CCTexture2D* pobTexture, const CCRect& rect); bool initWithTexture(CCTexture2D* pobTexture, const CCRect& rect);
/** Initializes a CCSpriteFrame with a texture, rect, rotated, offse /** Initializes a CCSpriteFrame with a texture filename, rect in points
t and originalSize in pixels. ;
The originalSize is the size in points of the frame before being tri It is assumed that the frame was not trimmed.
mmed. */
*/ bool initWithTextureFilename(const char* filename, const CCRect& rect);
bool initWithTexture(CCTexture2D* pobTexture, const CCRect& rect, bo
ol rotated, const CCPoint& offset, const CCSize& originalSize); /** Initializes a CCSpriteFrame with a texture, rect, rotated, offset a
nd originalSize in pixels.
The originalSize is the size in points of the frame before being trimme
d.
*/
bool initWithTexture(CCTexture2D* pobTexture, const CCRect& rect, bool
rotated, const CCPoint& offset, const CCSize& originalSize);
/** Initializes a CCSpriteFrame with a texture, rect, rotated, offset a
nd originalSize in pixels.
The originalSize is the size in pixels of the frame before being trimm
ed.
@since v1.1
*/
bool initWithTextureFilename(const char* filename, const CCRect& rect,
bool rotated, const CCPoint& offset, const CCSize& originalSize);
protected: protected:
CCRect m_obRectInPixels; CCPoint m_obOffset;
bool m_bRotated; CCSize m_obOriginalSize;
CCRect m_obRect; CCRect m_obRectInPixels;
CCPoint m_obOffsetInPixels; bool m_bRotated;
CCSize m_obOriginalSizeInPixels; CCRect m_obRect;
CCTexture2D *m_pobTexture; CCPoint m_obOffsetInPixels;
CCSize m_obOriginalSizeInPixels;
CCTexture2D *m_pobTexture;
std::string m_strTextureFilename;
}; };
}//namespace cocos2d // end of sprite_nodes group
/// @}
NS_CC_END
#endif //__SPRITE_CCSPRITE_FRAME_H__ #endif //__SPRITE_CCSPRITE_FRAME_H__
 End of changes. 15 change blocks. 
80 lines changed or deleted 155 lines changed or added


 CCSpriteFrameCache.h   CCSpriteFrameCache.h 
/************************************************************************** ** /************************************************************************** **
Copyright (c) 2010-2011 cocos2d-x.org Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2009 Jason Booth Copyright (c) 2009 Jason Booth
Copyright (c) 2009 Robert J Payne Copyright (c) 2009 Robert J Payne
Copyright (c) 2011 Zynga Inc. Copyright (c) 2011 Zynga Inc.
http://www.cocos2d-x.org http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a cop y Permission is hereby granted, free of charge, to any person obtaining a cop y
of this software and associated documentation files (the "Software"), to de al of this software and associated documentation files (the "Software"), to de al
in the Software without restriction, including without limitation the right s in the Software without restriction, including without limitation the right s
skipping to change at line 37 skipping to change at line 37
*************************************************************************** */ *************************************************************************** */
#ifndef __SPRITE_CCSPRITE_FRAME_CACHE_H__ #ifndef __SPRITE_CCSPRITE_FRAME_CACHE_H__
#define __SPRITE_CCSPRITE_FRAME_CACHE_H__ #define __SPRITE_CCSPRITE_FRAME_CACHE_H__
/* /*
* To create sprite frames and texture atlas, use this tool: * To create sprite frames and texture atlas, use this tool:
* http://zwoptex.zwopple.com/ * http://zwoptex.zwopple.com/
*/ */
#include "sprite_nodes/CCSpriteFrame.h"
#include "textures/CCTexture2D.h"
#include "cocoa/CCObject.h"
#include <set>
#include <string> #include <string>
#include "CCSpriteFrame.h"
#include "CCTexture2D.h"
#include "CCObject.h"
#include "CCMutableDictionary.h"
namespace cocos2d { NS_CC_BEGIN
class CCDictionary;
class CCArray;
class CCSprite; class CCSprite;
/**
* @addtogroup sprite_nodes
* @{
*/
/** @brief Singleton that handles the loading of the sprite frames. /** @brief Singleton that handles the loading of the sprite frames.
It saves in a cache the sprite frames. It saves in a cache the sprite frames.
@since v0.9 @since v0.9
*/ */
class CC_DLL CCSpriteFrameCache : public CCObject class CC_DLL CCSpriteFrameCache : public CCObject
{ {
public: public:
bool init(void); bool init(void);
~CCSpriteFrameCache(void); ~CCSpriteFrameCache(void);
/*Adds multiple Sprite Frames with a dictionary. The texture will be private:
associated with the created sprite frames. /*Adds multiple Sprite Frames with a dictionary. The texture will be as
*/ sociated with the created sprite frames.
void addSpriteFramesWithDictionary(CCDictionary<std::string, CCObjec */
t*> *pobDictionary, CCTexture2D *pobTexture); void addSpriteFramesWithDictionary(CCDictionary* pobDictionary, CCTextu
re2D *pobTexture);
/** Adds multiple Sprite Frames from a plist file. public:
* A texture will be loaded automatically. The texture name will com /** Adds multiple Sprite Frames from a plist file.
posed by replacing the .plist suffix with .png * A texture will be loaded automatically. The texture name will compos
* If you want to use another texture, you should use the addSpriteF ed by replacing the .plist suffix with .png
ramesWithFile:texture method. * If you want to use another texture, you should use the addSpriteFram
*/ esWithFile:texture method.
void addSpriteFramesWithFile(const char *pszPlist); */
void addSpriteFramesWithFile(const char *pszPlist);
/** Adds multiple Sprite Frames from a plist file. The texture will
be associated with the created sprite frames. /** Adds multiple Sprite Frames from a plist file. The texture will be
@since v0.99.5 associated with the created sprite frames.
*/ @since v0.99.5
void addSpriteFramesWithFile(const char* plist, const char* textureF */
ileName); void addSpriteFramesWithFile(const char* plist, const char* textureFile
Name);
/** Adds multiple Sprite Frames from a plist file. The texture will
be associated with the created sprite frames. */ /** Adds multiple Sprite Frames from a plist file. The texture will be
void addSpriteFramesWithFile(const char *pszPlist, CCTexture2D *pobT associated with the created sprite frames. */
exture); void addSpriteFramesWithFile(const char *pszPlist, CCTexture2D *pobText
ure);
/** Adds an sprite frame with a given name.
If the name already exists, then the contents of the old name will /** Adds an sprite frame with a given name.
be replaced with the new one. If the name already exists, then the contents of the old name will be
*/ replaced with the new one.
void addSpriteFrame(CCSpriteFrame *pobFrame, const char *pszFrameNam */
e); void addSpriteFrame(CCSpriteFrame *pobFrame, const char *pszFrameName);
/** Purges the dictionary of loaded sprite frames. /** Purges the dictionary of loaded sprite frames.
* Call this method if you receive the "Memory Warning". * Call this method if you receive the "Memory Warning".
* In the short term: it will free some resources preventing your ap * In the short term: it will free some resources preventing your app f
p from being killed. rom being killed.
* In the medium term: it will allocate more resources. * In the medium term: it will allocate more resources.
* In the long term: it will be the same. * In the long term: it will be the same.
*/ */
void removeSpriteFrames(void); void removeSpriteFrames(void);
/** Removes unused sprite frames. /** Removes unused sprite frames.
* Sprite Frames that have a retain count of 1 will be deleted. * Sprite Frames that have a retain count of 1 will be deleted.
* It is convenient to call this method after when starting a new Sc * It is convenient to call this method after when starting a new Scene
ene. .
*/ */
void removeUnusedSpriteFrames(void); void removeUnusedSpriteFrames(void);
/** Deletes an sprite frame from the sprite frame cache. */ /** Deletes an sprite frame from the sprite frame cache. */
void removeSpriteFrameByName(const char *pszName); void removeSpriteFrameByName(const char *pszName);
/** Removes multiple Sprite Frames from a plist file. /** Removes multiple Sprite Frames from a plist file.
* Sprite Frames stored in this file will be removed. * Sprite Frames stored in this file will be removed.
* It is convinient to call this method when a specific texture needs * It is convinient to call this method when a specific texture needs to
to be removed. be removed.
* @since v0.99.5 * @since v0.99.5
*/ */
void removeSpriteFramesFromFile(const char* plist); void removeSpriteFramesFromFile(const char* plist);
/** Removes multiple Sprite Frames from CCDictionary.
* @since v0.99.5
*/
void removeSpriteFramesFromDictionary(CCDictionary<std::string, CCSp
riteFrame*> *dictionary);
/** Removes all Sprite Frames associated with the specified textures
.
* It is convinient to call this method when a specific texture needs
to be removed.
* @since v0.995.
*/
void removeSpriteFramesFromTexture(CCTexture2D* texture);
/** Returns an Sprite Frame that was previously added.
If the name is not found it will return nil.
You should retain the returned copy if you are going to use it.
*/
CCSpriteFrame* spriteFrameByName(const char *pszName);
private:
/** Removes multiple Sprite Frames from CCDictionary.
* @since v0.99.5
*/
void removeSpriteFramesFromDictionary(CCDictionary* dictionary);
public: public:
/** Returns the shared instance of the Sprite Frame cache */ /** Removes all Sprite Frames associated with the specified textures.
static CCSpriteFrameCache* sharedSpriteFrameCache(void); * It is convinient to call this method when a specific texture needs to
be removed.
* @since v0.995.
*/
void removeSpriteFramesFromTexture(CCTexture2D* texture);
/** Returns an Sprite Frame that was previously added.
If the name is not found it will return nil.
You should retain the returned copy if you are going to use it.
*/
CCSpriteFrame* spriteFrameByName(const char *pszName);
/** Purges the cache. It releases all the Sprite Frames and the reta public:
ined instance. */ /** Returns the shared instance of the Sprite Frame cache */
static void purgeSharedSpriteFrameCache(void); static CCSpriteFrameCache* sharedSpriteFrameCache(void);
private: /** Purges the cache. It releases all the Sprite Frames and the retaine
CCSpriteFrameCache(void) : m_pSpriteFrames(NULL), m_pSpriteFramesAli d instance. */
ases(NULL){} static void purgeSharedSpriteFrameCache(void);
const char * valueForKey(const char *key, CCDictionary<std::string,
CCObject*> *dict);
private:
CCSpriteFrameCache(void) : m_pSpriteFrames(NULL), m_pSpriteFramesAliase
s(NULL){}
protected: protected:
CCDictionary<std::string, CCSpriteFrame*> *m_pSpriteFrames; CCDictionary* m_pSpriteFrames;
CCDictionary<std::string, CCString*> *m_pSpriteFramesAliases; CCDictionary* m_pSpriteFramesAliases;
std::set<std::string>* m_pLoadedFileNames;
}; };
}//namespace cocos2d
// end of sprite_nodes group
/// @}
NS_CC_END
#endif // __SPRITE_CCSPRITE_FRAME_CACHE_H__ #endif // __SPRITE_CCSPRITE_FRAME_CACHE_H__
 End of changes. 14 change blocks. 
100 lines changed or deleted 109 lines changed or added


 CCStdC.h   CCStdC.h 
skipping to change at line 28 skipping to change at line 28
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CC_STD_C_H__ #ifndef __CC_STD_C_H__
#define __CC_STD_C_H__ #define __CC_STD_C_H__
#include "CCPlatformMacros.h" #include "platform/CCPlatformMacros.h"
#include <float.h> #include <float.h>
// for math.h on win32 platform
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
#if ! defined(_USE_MATH_DEFINES)
#define _USE_MATH_DEFINES // make M_PI can be use
#endif
#if ! defined(isnan)
#define isnan _isnan
#endif
#endif // CC_PLATFORM_WIN32
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WOPHONE && defined(_TRANZDA_VM_))
#if ! defined(_USE_MATH_DEFINES)
#define _USE_MATH_DEFINES // make M_PI can be use
#endif
#if ! defined(isnan)
#define isnan _isnan
#endif
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_WOPHONE && defined(_TRANZDA_VM_
)
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WOPHONE)
#include "TG3.h"
#endif // CC_PLATFORM_WOPHONE
#include <math.h> #include <math.h>
#include <string.h> #include <string.h>
#include <stdarg.h> #include <stdarg.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
// for MIN MAX and sys/time.h on win32 platform
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
#define MIN min
#define MAX max
// Structure timeval has define in winsock.h, include windows.h for it.
#include <Windows.h>
struct timezone
{
int tz_minuteswest;
int tz_dsttime;
};
int CC_DLL gettimeofday(struct timeval *, struct timezone *);
#endif // CC_PLATFORM_WIN32
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLAT
FORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_LINUX || CC_TARGET_PLATFO
RM == CC_PLATFORM_QNX)
#include <sys/time.h> #include <sys/time.h>
#ifndef MIN #ifndef MIN
#define MIN(x,y) (((x) > (y)) ? (y) : (x)) #define MIN(x,y) (((x) > (y)) ? (y) : (x))
#endif // MIN #endif // MIN
#ifndef MAX #ifndef MAX
#define MAX(x,y) (((x) < (y)) ? (y) : (x)) #define MAX(x,y) (((x) < (y)) ? (y) : (x))
#endif // MAX #endif // MAX
#if (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX)
// some function linux do not have
#define tanf tan
#define sqrtf sqrt
#define cosf cos
#define sinf sin
#endif
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == C
C_PLATFORM_ANDROID
#if (CC_TARGET_PLATFORM == CC_PLATFORM_MARMALADE)
#include <s3e.h>
#include <sys/time.h>
#ifndef MIN
#define MIN(x,y) (((x) > (y)) ? (y) : (x))
#endif // MIN
#ifndef MAX
#define MAX(x,y) (((x) < (y)) ? (y) : (x))
#endif // MAX
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_MARMALADE
#if (CC_TARGET_PLATFORM == CC_PLATFORM_BADA)
#include <FSysSystemTime.h>
struct timeval
{
long tv_sec; // seconds
long tv_usec; // microSeconds
};
struct timezone
{
int tz_minuteswest;
int tz_dsttime;
};
int CC_DLL gettimeofday(struct timeval *, struct timezone *);
#ifndef MIN
#define MIN(x,y) (((x) > (y)) ? (y) : (x))
#endif // MIN
#ifndef MAX
#define MAX(x,y) (((x) < (y)) ? (y) : (x))
#endif // MAX
#ifndef UINT_MAX
#define UINT_MAX 0xffffffff /* maximum unsigned int value */
#endif // UINT_MAX
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_BADA
#endif // __CC_STD_C_H__ #endif // __CC_STD_C_H__
 End of changes. 5 change blocks. 
120 lines changed or deleted 1 lines changed or added


 CCString.h   CCString.h 
skipping to change at line 26 skipping to change at line 26
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CCSTRING_H__ #ifndef __CCSTRING_H__
#define __CCSTRING_H__ #define __CCSTRING_H__
#if (CC_TARGET_PLATFORM == CC_PLATFORM_BLACKBERRY)
#include <string.h>
#endif
#include <stdarg.h>
#include <string> #include <string>
#include <stdlib.h> #include <functional>
#include "CCObject.h" #include "CCObject.h"
namespace cocos2d {
class CC_DLL CCString : public CCObject NS_CC_BEGIN
{
public: /**
std::string m_sString; * @addtogroup data_structures
public: * @{
CCString() */
:m_sString("")
{} class CC_DLL CCString : public CCObject
CCString(const char * str) {
{ public:
m_sString = str; CCString();
} CCString(const char* str);
virtual ~CCString(){ m_sString.clear(); } CCString(const std::string& str);
CCString(const CCString& str);
int toInt()
{ virtual ~CCString();
return atoi(m_sString.c_str());
} /* override assignment operator */
unsigned int toUInt() CCString& operator= (const CCString& other);
{
return (unsigned int)atoi(m_sString.c_str()); /** init a string with format, it's similar with the c function 'sprint
} f' */
float toFloat() bool initWithFormat(const char* format, ...);
{
return (float)atof(m_sString.c_str()); /** convert to int value */
} int intValue() const;
std::string toStdString()
{ /** convert to unsigned int value */
return m_sString; unsigned int uintValue() const;
}
/** convert to float value */
bool isEmpty() float floatValue() const;
{
return m_sString.empty(); /** convert to double value */
} double doubleValue() const;
virtual bool isEqual(const CCObject* pObject) /** convert to bool value */
{ bool boolValue() const;
bool bRet = false;
const CCString* pStr = dynamic_cast<const CCString*>(pObject); /** get the C string */
if (pStr != NULL) const char* getCString() const;
{
if (0 == m_sString.compare(pStr->m_sString)) /** get the length of string */
{ unsigned int length() const;
bRet = true;
} /** compare to a c string */
} int compare(const char *) const;
return bRet;
/* override functions */
virtual CCObject* copyWithZone(CCZone* pZone);
virtual bool isEqual(const CCObject* pObject);
/* static funcitons */
/** create a string with c string
* @return A CCString pointer which is an autorelease object pointer,
* it means that you needn't do a release operation unless you
retain it.
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCString* stringWithCString(const char*
pStr);
/** create a string with std::string
* @return A CCString pointer which is an autorelease object pointer,
* it means that you needn't do a release operation unless you
retain it.
*/
CC_DEPRECATED_ATTRIBUTE static CCString* stringWithString(const std::st
ring& str);
/** create a string with format, it's similar with the c function 'spri
ntf', the default buffer size is (1024*100) bytes,
* if you want to change it, you should modify the kMaxStringLen macro
in CCString.cpp file.
* @return A CCString pointer which is an autorelease object pointer,
* it means that you needn't do a release operation unless you
retain it.
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCString* stringWithFormat(const char* f
ormat, ...);
/** create a string with binary data
* @return A CCString pointer which is an autorelease object pointer,
* it means that you needn't do a release operation unless you
retain it.
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCString* stringWithData(const unsigned
char* pData, unsigned long nLen);
/** create a string with a file,
* @return A CCString pointer which is an autorelease object pointer,
* it means that you needn't do a release operation unless you
retain it.
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCString* stringWithContentsOfFile(const
char* pszFileName);
/** create a string with std string, you can also pass a c string point
er because the default constuctor of std::string can access a c string poin
ter.
* @return A CCString pointer which is an autorelease object pointer,
* it means that you needn't do a release operation unless you
retain it.
*/
static CCString* create(const std::string& str);
/** create a string with format, it's similar with the c function 'spri
ntf', the default buffer size is (1024*100) bytes,
* if you want to change it, you should modify the kMaxStringLen macro
in CCString.cpp file.
* @return A CCString pointer which is an autorelease object pointer,
* it means that you needn't do a release operation unless you
retain it.
*/
static CCString* createWithFormat(const char* format, ...);
/** create a string with binary data
* @return A CCString pointer which is an autorelease object pointer,
* it means that you needn't do a release operation unless you
retain it.
*/
static CCString* createWithData(const unsigned char* pData, unsigned lo
ng nLen);
/** create a string with a file,
* @return A CCString pointer which is an autorelease object pointer,
* it means that you needn't do a release operation unless you
retain it.
*/
static CCString* createWithContentsOfFile(const char* pszFileName);
private:
/** only for internal use */
bool initWithFormatAndValist(const char* format, va_list ap);
public:
std::string m_sString;
};
struct CCStringCompare : public std::binary_function<CCString *, CCString *
, bool> {
public:
bool operator() (CCString * a, CCString * b) const {
return strcmp(a->getCString(), b->getCString()) < 0;
} }
}; };
}// namespace cocos2d
#define CCStringMake(str) CCString::create(str)
#define ccs CCStringMake
// end of data_structure group
/// @}
NS_CC_END
#endif //__CCSTRING_H__ #endif //__CCSTRING_H__
 End of changes. 5 change blocks. 
52 lines changed or deleted 165 lines changed or added


 CCTMXLayer.h   CCTMXLayer.h 
skipping to change at line 28 skipping to change at line 28
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CCTMX_LAYER_H__ #ifndef __CCTMX_LAYER_H__
#define __CCTMX_LAYER_H__ #define __CCTMX_LAYER_H__
#include "CCTMXObjectGroup.h" #include "CCTMXObjectGroup.h"
#include "CCAtlasNode.h" #include "base_nodes/CCAtlasNode.h"
#include "CCSpriteBatchNode.h" #include "sprite_nodes/CCSpriteBatchNode.h"
namespace cocos2d { #include "CCTMXXMLParser.h"
NS_CC_BEGIN
class CCTMXMapInfo;
class CCTMXLayerInfo; class CCTMXMapInfo;
class CCTMXTilesetInfo; class CCTMXLayerInfo;
struct _ccCArray; class CCTMXTilesetInfo;
struct _ccCArray;
/** @brief CCTMXLayer represents the TMX layer.
/**
It is a subclass of CCSpriteBatchNode. By default the tiles are rend * @addtogroup tilemap_parallax_nodes
ered using a CCTextureAtlas. * @{
If you modify a tile on runtime, then, that tile will become a CCSpr */
ite, otherwise no CCSprite objects are created.
The benefits of using CCSprite objects as tiles are: /** @brief CCTMXLayer represents the TMX layer.
- tiles (CCSprite) can be rotated/scaled/moved with a nice API
It is a subclass of CCSpriteBatchNode. By default the tiles are rendered us
If the layer contains a property named "cc_vertexz" with an integer ing a CCTextureAtlas.
(in can be positive or negative), If you modify a tile on runtime, then, that tile will become a CCSprite, ot
then all the tiles belonging to the layer will use that value as the herwise no CCSprite objects are created.
ir OpenGL vertex Z for depth. The benefits of using CCSprite objects as tiles are:
- tiles (CCSprite) can be rotated/scaled/moved with a nice API
On the other hand, if the "cc_vertexz" property has the "automatic"
value, then the tiles will use an automatic vertex Z value. If the layer contains a property named "cc_vertexz" with an integer (in can
Also before drawing the tiles, GL_ALPHA_TEST will be enabled, and di be positive or negative),
sabled after drawin them. The used alpha func will be: then all the tiles belonging to the layer will use that value as their Open
GL vertex Z for depth.
glAlphaFunc( GL_GREATER, value )
On the other hand, if the "cc_vertexz" property has the "automatic" value,
"value" by default is 0, but you can change it from Tiled by adding then the tiles will use an automatic vertex Z value.
the "cc_alpha_func" property to the layer. Also before drawing the tiles, GL_ALPHA_TEST will be enabled, and disabled
The value 0 should work for most cases, but if you have tiles that a after drawin them. The used alpha func will be:
re semi-transparent, then you might want to use a differnt
value, like 0.5. glAlphaFunc( GL_GREATER, value )
For further information, please see the programming guide: "value" by default is 0, but you can change it from Tiled by adding the "cc
_alpha_func" property to the layer.
http://www.cocos2d-iphone.org/wiki/doku.php/prog_guide:tiled_maps The value 0 should work for most cases, but if you have tiles that are semi
-transparent, then you might want to use a differnt
@since v0.8.1 value, like 0.5.
*/
class CC_DLL CCTMXLayer : public CCSpriteBatchNode For further information, please see the programming guide:
{
/** size of the layer in tiles */ http://www.cocos2d-iphone.org/wiki/doku.php/prog_guide:tiled_maps
CC_SYNTHESIZE_PASS_BY_REF(CCSize, m_tLayerSize, LayerSize);
/** size of the map's tile (could be differnt from the tile' @since v0.8.1
s size) */ Tiles can have tile flags for additional properties. At the moment only fli
CC_SYNTHESIZE_PASS_BY_REF(CCSize, m_tMapTileSize, MapTileSiz p horizontal and flip vertical are used. These bit flags are defined in CCT
e); MXXMLParser.h.
/** pointer to the map of tiles */
CC_SYNTHESIZE(unsigned int*, m_pTiles, Tiles); @since 1.1
/** Tilset information for the layer */ */
CC_PROPERTY(CCTMXTilesetInfo*, m_pTileSet, TileSet);
/** Layer orientation, which is the same as the map orientat class CC_DLL CCTMXLayer : public CCSpriteBatchNode
ion */ {
CC_SYNTHESIZE(unsigned int, m_uLayerOrientation, LayerOrient /** size of the layer in tiles */
ation); CC_SYNTHESIZE_PASS_BY_REF(CCSize, m_tLayerSize, LayerSize);
/** properties from the layer. They can be added using Tiled /** size of the map's tile (could be differnt from the tile's size) */
*/ CC_SYNTHESIZE_PASS_BY_REF(CCSize, m_tMapTileSize, MapTileSize);
CC_PROPERTY(CCStringToStringDictionary*, m_pProperties, Prop /** pointer to the map of tiles */
erties); CC_SYNTHESIZE(unsigned int*, m_pTiles, Tiles);
public: /** Tilset information for the layer */
CCTMXLayer(); CC_PROPERTY(CCTMXTilesetInfo*, m_pTileSet, TileSet);
virtual ~CCTMXLayer(); /** Layer orientation, which is the same as the map orientation */
/** creates a CCTMXLayer with an tileset info, a layer info CC_SYNTHESIZE(unsigned int, m_uLayerOrientation, LayerOrientation);
and a map info */ /** properties from the layer. They can be added using Tiled */
static CCTMXLayer * layerWithTilesetInfo(CCTMXTilesetInfo *t CC_PROPERTY(CCDictionary*, m_pProperties, Properties);
ilesetInfo, CCTMXLayerInfo *layerInfo, CCTMXMapInfo *mapInfo); public:
/** initializes a CCTMXLayer with a tileset info, a layer in CCTMXLayer();
fo and a map info */ virtual ~CCTMXLayer();
bool initWithTilesetInfo(CCTMXTilesetInfo *tilesetInfo, CCTM /** creates a CCTMXLayer with an tileset info, a layer info and a map i
XLayerInfo *layerInfo, CCTMXMapInfo *mapInfo); nfo
@deprecated: This interface will be deprecated sooner or later.
/** dealloc the map that contains the tile position from mem */
ory. CC_DEPRECATED_ATTRIBUTE static CCTMXLayer * layerWithTilesetInfo(CCTMXT
Unless you want to know at runtime the tiles positions, you ilesetInfo *tilesetInfo, CCTMXLayerInfo *layerInfo, CCTMXMapInfo *mapInfo);
can safely call this method.
If you are going to call layer->tileGIDAt() then, don't rele /** creates a CCTMXLayer with an tileset info, a layer info and a map i
ase the map nfo */
*/ static CCTMXLayer * create(CCTMXTilesetInfo *tilesetInfo, CCTMXLayerInf
void releaseMap(); o *layerInfo, CCTMXMapInfo *mapInfo);
/** returns the tile (CCSprite) at a given a tile coordinate /** initializes a CCTMXLayer with a tileset info, a layer info and a ma
. p info */
The returned CCSprite will be already added to the CCTMXLaye bool initWithTilesetInfo(CCTMXTilesetInfo *tilesetInfo, CCTMXLayerInfo
r. Don't add it again. *layerInfo, CCTMXMapInfo *mapInfo);
The CCSprite can be treated like any other CCSprite: rotated
, scaled, translated, opacity, color, etc. /** dealloc the map that contains the tile position from memory.
You can remove either by calling: Unless you want to know at runtime the tiles positions, you can safely
- layer->removeChild(sprite, cleanup); call this method.
- or layer->removeTileAt(ccp(x,y)); If you are going to call layer->tileGIDAt() then, don't release the map
*/ */
CCSprite* tileAt(const CCPoint& tileCoordinate); void releaseMap();
/** returns the tile gid at a given tile coordinate. /** returns the tile (CCSprite) at a given a tile coordinate.
if it returns 0, it means that the tile is empty. The returned CCSprite will be already added to the CCTMXLayer. Don't ad
This method requires the the tile map has not been previousl d it again.
y released (eg. don't call layer->releaseMap()) The CCSprite can be treated like any other CCSprite: rotated, scaled, t
*/ ranslated, opacity, color, etc.
unsigned int tileGIDAt(const CCPoint& tileCoordinate); You can remove either by calling:
- layer->removeChild(sprite, cleanup);
/** sets the tile gid (gid = tile global id) at a given tile - or layer->removeTileAt(ccp(x,y));
coordinate. */
The Tile GID can be obtained by using the method "tileGIDAt" CCSprite* tileAt(const CCPoint& tileCoordinate);
or by using the TMX editor -> Tileset Mgr +1.
If a tile is already placed at that position, then it will b /** returns the tile gid at a given tile coordinate.
e removed. if it returns 0, it means that the tile is empty.
*/ This method requires the the tile map has not been previously released
void setTileGID(unsigned int gid, const CCPoint& tileCoordin (eg. don't call layer->releaseMap())
ate); */
unsigned int tileGIDAt(const CCPoint& tileCoordinate);
/** removes a tile at given tile coordinate */
void removeTileAt(const CCPoint& tileCoordinate); /** returns the tile gid at a given tile coordinate. It also returns th
e tile flags.
/** returns the position in pixels of a given tile coordinat This method requires the the tile map has not been previously released
e */ (eg. don't call [layer releaseMap])
CCPoint positionAt(const CCPoint& tileCoordinate); */
unsigned int tileGIDAt(const CCPoint& tileCoordinate, ccTMXTileFlags* f
/** return the value for the specific property name */ lags);
CCString *propertyNamed(const char *propertyName);
/** sets the tile gid (gid = tile global id) at a given tile coordinate
/** Creates the tiles */ .
void setupTiles(); The Tile GID can be obtained by using the method "tileGIDAt" or by usin
g the TMX editor -> Tileset Mgr +1.
/** CCTMXLayer doesn't support adding a CCSprite manually. If a tile is already placed at that position, then it will be removed.
@warning addchild(z, tag); is not supported on CCTMXLayer. I */
nstead of setTileGID. void setTileGID(unsigned int gid, const CCPoint& tileCoordinate);
*/
virtual void addChild(CCNode * child, int zOrder, int tag); /** sets the tile gid (gid = tile global id) at a given tile coordinate
// super method .
void removeChild(CCNode* child, bool cleanup); The Tile GID can be obtained by using the method "tileGIDAt" or by usi
void draw(); ng the TMX editor -> Tileset Mgr +1.
If a tile is already placed at that position, then it will be removed.
inline const char* getLayerName(){ return m_sLayerName.c_str
(); } Use withFlags if the tile flags need to be changed as well
inline void setLayerName(const char *layerName){ m_sLayerNam */
e = layerName; }
private: void setTileGID(unsigned int gid, const CCPoint& tileCoordinate, ccTMXT
CCPoint positionForIsoAt(const CCPoint& pos); ileFlags flags);
CCPoint positionForOrthoAt(const CCPoint& pos);
CCPoint positionForHexAt(const CCPoint& pos); /** removes a tile at given tile coordinate */
void removeTileAt(const CCPoint& tileCoordinate);
CCPoint calculateLayerOffset(const CCPoint& offset);
/** returns the position in points of a given tile coordinate */
/* optimization methos */ CCPoint positionAt(const CCPoint& tileCoordinate);
CCSprite* appendTileForGID(unsigned int gid, const CCPoint&
pos); /** return the value for the specific property name */
CCSprite* insertTileForGID(unsigned int gid, const CCPoint& CCString *propertyNamed(const char *propertyName);
pos);
CCSprite* updateTileForGID(unsigned int gid, const CCPoint& /** Creates the tiles */
pos); void setupTiles();
/* The layer recognizes some special properties, like cc_ver /** CCTMXLayer doesn't support adding a CCSprite manually.
tez */ @warning addchild(z, tag); is not supported on CCTMXLayer. Instead of s
void parseInternalProperties(); etTileGID.
int vertexZForPos(const CCPoint& pos); */
virtual void addChild(CCNode * child, int zOrder, int tag);
// index // super method
unsigned int atlasIndexForExistantZ(unsigned int z); void removeChild(CCNode* child, bool cleanup);
unsigned int atlasIndexForNewZ(int z);
protected: /** listen the event to invoke CCTexture2D::setAliasTexParameters() aft
//! name of the layer er
std::string m_sLayerName; comming to foreground on android
//! TMX Layer supports opacity */
unsigned char m_cOpacity; void listenBackToForeground(CCObject *sender);
unsigned int m_uMinGID; inline const char* getLayerName(){ return m_sLayerName.c_str(); }
unsigned int m_uMaxGID; inline void setLayerName(const char *layerName){ m_sLayerName = layerNa
me; }
//! Only used when vertexZ is used private:
int m_nVertexZvalue; CCPoint positionForIsoAt(const CCPoint& pos);
bool m_bUseAutomaticVertexZ; CCPoint positionForOrthoAt(const CCPoint& pos);
float m_fAlphaFuncValue; CCPoint positionForHexAt(const CCPoint& pos);
//! used for optimization CCPoint calculateLayerOffset(const CCPoint& offset);
CCSprite *m_pReusedTile;
_ccCArray *m_pAtlasIndexArray; /* optimization methos */
CCSprite* appendTileForGID(unsigned int gid, const CCPoint& pos);
// used for retina display CCSprite* insertTileForGID(unsigned int gid, const CCPoint& pos);
float m_fContentScaleFactor; CCSprite* updateTileForGID(unsigned int gid, const CCPoint& pos);
};
/* The layer recognizes some special properties, like cc_vertez */
void parseInternalProperties();
void setupTileSprite(CCSprite* sprite, CCPoint pos, unsigned int gid);
CCSprite* reusedTileWithRect(CCRect rect);
int vertexZForPos(const CCPoint& pos);
// index
unsigned int atlasIndexForExistantZ(unsigned int z);
unsigned int atlasIndexForNewZ(int z);
protected:
//! name of the layer
std::string m_sLayerName;
//! TMX Layer supports opacity
unsigned char m_cOpacity;
unsigned int m_uMinGID;
unsigned int m_uMaxGID;
//! Only used when vertexZ is used
int m_nVertexZvalue;
bool m_bUseAutomaticVertexZ;
//! used for optimization
CCSprite *m_pReusedTile;
ccCArray *m_pAtlasIndexArray;
// used for retina display
float m_fContentScaleFactor;
};
// end of tilemap_parallax_nodes group
/// @}
NS_CC_END
}// namespace cocos2d
#endif //__CCTMX_LAYER_H__ #endif //__CCTMX_LAYER_H__
 End of changes. 3 change blocks. 
183 lines changed or deleted 217 lines changed or added


 CCTMXObjectGroup.h   CCTMXObjectGroup.h 
skipping to change at line 30 skipping to change at line 30
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CCTMX_OBJECT_GROUP_H__ #ifndef __CCTMX_OBJECT_GROUP_H__
#define __CCTMX_OBJECT_GROUP_H__ #define __CCTMX_OBJECT_GROUP_H__
#include "CCGeometry.h" #include "cocoa/CCGeometry.h"
#include "CCString.h" #include "cocoa/CCString.h"
#include "CCMutableArray.h" #include "cocoa/CCArray.h"
#include "CCMutableDictionary.h" #include "cocoa/CCDictionary.h"
namespace cocos2d { NS_CC_BEGIN
/** @brief CCTMXObjectGroup represents the TMX object group. /**
@since v0.99.0 * @addtogroup tilemap_parallax_nodes
*/ * @{
class CC_DLL CCTMXObjectGroup : public CCObject */
{
/** offset position of child objects */ /** @brief CCTMXObjectGroup represents the TMX object group.
CC_SYNTHESIZE_PASS_BY_REF(CCPoint, m_tPositionOffset, Positi @since v0.99.0
onOffset); */
/** list of properties stored in a dictionary */ class CC_DLL CCTMXObjectGroup : public CCObject
CC_PROPERTY(CCStringToStringDictionary*, m_pProperties, Prop {
erties); /** offset position of child objects */
/** array of the objects */ CC_SYNTHESIZE_PASS_BY_REF(CCPoint, m_tPositionOffset, PositionOffset);
CC_PROPERTY(CCMutableArray<CCStringToStringDictionary*>*, m_ /** list of properties stored in a dictionary */
pObjects, Objects); CC_PROPERTY(CCDictionary*, m_pProperties, Properties);
public: /** array of the objects */
CCTMXObjectGroup(); CC_PROPERTY(CCArray*, m_pObjects, Objects);
virtual ~CCTMXObjectGroup(); public:
CCTMXObjectGroup();
inline const char* getGroupName(){ return m_sGroupName.c_str virtual ~CCTMXObjectGroup();
(); }
inline void setGroupName(const char *groupName){ m_sGroupNam inline const char* getGroupName(){ return m_sGroupName.c_str(); }
e = groupName; } inline void setGroupName(const char *groupName){ m_sGroupName = groupNa
me; }
/** return the value for the specific property name */
CCString *propertyNamed(const char* propertyName); /** return the value for the specific property name */
CCString *propertyNamed(const char* propertyName);
/** return the dictionary for the specific object name.
It will return the 1st object found on the array for the giv /** return the dictionary for the specific object name.
en name. It will return the 1st object found on the array for the given name.
*/ */
CCStringToStringDictionary *objectNamed(const char *objectNa CCDictionary* objectNamed(const char *objectName);
me); protected:
protected: /** name of the group */
/** name of the group */ std::string m_sGroupName;
std::string m_sGroupName; };
};
// end of tilemap_parallax_nodes group
/// @}
NS_CC_END
}// namespace cocos2d
#endif //__CCTMX_OBJECT_GROUP_H__ #endif //__CCTMX_OBJECT_GROUP_H__
 End of changes. 2 change blocks. 
44 lines changed or deleted 47 lines changed or added


 CCTMXTiledMap.h   CCTMXTiledMap.h 
skipping to change at line 28 skipping to change at line 28
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CCTMX_TILE_MAP_H__ #ifndef __CCTMX_TILE_MAP_H__
#define __CCTMX_TILE_MAP_H__ #define __CCTMX_TILE_MAP_H__
#include "CCNode.h"
#include "base_nodes/CCNode.h"
#include "CCTMXObjectGroup.h" #include "CCTMXObjectGroup.h"
namespace cocos2d { NS_CC_BEGIN
class CCTMXObjectGroup;
class CCTMXLayer;
class CCTMXLayerInfo;
class CCTMXTilesetInfo;
class CCTMXMapInfo;
/**
* @addtogroup tilemap_parallax_nodes
* @{
*/
/** Possible oritentations of the TMX map */
enum
{
/** Orthogonal orientation */
CCTMXOrientationOrtho,
/** Hexagonal orientation */
CCTMXOrientationHex,
/** Isometric orientation */
CCTMXOrientationIso,
};
/** @brief CCTMXTiledMap knows how to parse and render a TMX map.
It adds support for the TMX tiled map format used by http://www.mapeditor.o
rg
It supports isometric, hexagonal and orthogonal tiles.
It also supports object groups, objects, and properties.
Features:
- Each tile will be treated as an CCSprite
- The sprites are created on demand. They will be created only when you cal
l "layer->tileAt(position)"
- Each tile can be rotated / moved / scaled / tinted / "opacitied", since e
ach tile is a CCSprite
- Tiles can be added/removed in runtime
- The z-order of the tiles can be modified in runtime
- Each tile has an anchorPoint of (0,0)
- The anchorPoint of the TMXTileMap is (0,0)
- The TMX layers will be added as a child
- The TMX layers will be aliased by default
- The tileset image will be loaded using the CCTextureCache
- Each tile will have a unique tag
- Each tile will have a unique z value. top-left: z=1, bottom-right: z=max
z
- Each object group will be treated as an CCMutableArray
- Object class which will contain all the properties in a dictionary
- Properties can be assigned to the Map, Layer, Object Group, and Object
Limitations:
- It only supports one tileset per layer.
- Embeded images are not supported
- It only supports the XML format (the JSON format is not supported)
Technical description:
Each layer is created using an CCTMXLayer (subclass of CCSpriteBatchNode).
If you have 5 layers, then 5 CCTMXLayer will be created,
unless the layer visibility is off. In that case, the layer won't be create
d at all.
You can obtain the layers (CCTMXLayer objects) at runtime by:
- map->getChildByTag(tag_number); // 0=1st layer, 1=2nd layer, 2=3rd layer
, etc...
- map->layerNamed(name_of_the_layer);
Each object group is created using a CCTMXObjectGroup which is a subclass o
f CCMutableArray.
You can obtain the object groups at runtime by:
- map->objectGroupNamed(name_of_the_object_group);
Each object is a CCTMXObject.
Each property is stored as a key-value pair in an CCMutableDictionary.
You can obtain the properties at runtime by:
map->propertyNamed(name_of_the_property);
layer->propertyNamed(name_of_the_property);
objectGroup->propertyNamed(name_of_the_property);
object->propertyNamed(name_of_the_property);
@since v0.8.1
*/
class CC_DLL CCTMXTiledMap : public CCNode
{
/** the map's size property measured in tiles */
CC_SYNTHESIZE_PASS_BY_REF(CCSize, m_tMapSize, MapSize);
/** the tiles's size property measured in pixels */
CC_SYNTHESIZE_PASS_BY_REF(CCSize, m_tTileSize, TileSize);
/** map orientation */
CC_SYNTHESIZE(int, m_nMapOrientation, MapOrientation);
/** object groups */
CC_PROPERTY(CCArray*, m_pObjectGroups, ObjectGroups);
/** properties */
CC_PROPERTY(CCDictionary*, m_pProperties, Properties);
public:
CCTMXTiledMap();
virtual ~CCTMXTiledMap();
/** creates a TMX Tiled Map with a TMX file.
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCTMXTiledMap* tiledMapWithTMXFile(const
char *tmxFile);
/** initializes a TMX Tiled Map with a TMX formatted XML string and a p
ath to TMX resources
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCTMXTiledMap* tiledMapWithXML(const cha
r* tmxString, const char* resourcePath);
/** creates a TMX Tiled Map with a TMX file.*/
static CCTMXTiledMap* create(const char *tmxFile);
/** initializes a TMX Tiled Map with a TMX formatted XML string and a p
ath to TMX resources */
static CCTMXTiledMap* createWithXML(const char* tmxString, const char*
resourcePath);
/** initializes a TMX Tiled Map with a TMX file */
bool initWithTMXFile(const char *tmxFile);
/** initializes a TMX Tiled Map with a TMX formatted XML string and a p
ath to TMX resources */
bool initWithXML(const char* tmxString, const char* resourcePath);
/** return the TMXLayer for the specific layer */
CCTMXLayer* layerNamed(const char *layerName);
/** return the TMXObjectGroup for the secific group */
CCTMXObjectGroup* objectGroupNamed(const char *groupName);
/** return the value for the specific property name */
CCString *propertyNamed(const char *propertyName);
/** return properties dictionary for tile GID */
CCDictionary* propertiesForGID(int GID);
private:
CCTMXLayer * parseLayer(CCTMXLayerInfo *layerInfo, CCTMXMapInfo *mapInf
o);
CCTMXTilesetInfo * tilesetForLayer(CCTMXLayerInfo *layerInfo, CCTMXMapI
nfo *mapInfo);
void buildWithMapInfo(CCTMXMapInfo* mapInfo);
protected:
//! tile properties
CCDictionary* m_pTileProperties;
};
class CCTMXObjectGroup; // end of tilemap_parallax_nodes group
class CCTMXLayer; /// @}
class CCTMXLayerInfo;
class CCTMXTilesetInfo;
class CCTMXMapInfo;
/** Possible oritentations of the TMX map */
enum
{
/** Orthogonal orientation */
CCTMXOrientationOrtho,
/** Hexagonal orientation */
CCTMXOrientationHex,
/** Isometric orientation */
CCTMXOrientationIso,
};
/** @brief CCTMXTiledMap knows how to parse and render a TMX map.
It adds support for the TMX tiled map format used by http://www.mape
ditor.org
It supports isometric, hexagonal and orthogonal tiles.
It also supports object groups, objects, and properties.
Features:
- Each tile will be treated as an CCSprite
- The sprites are created on demand. They will be created only when
you call "layer->tileAt(position)"
- Each tile can be rotated / moved / scaled / tinted / "opacitied",
since each tile is a CCSprite
- Tiles can be added/removed in runtime
- The z-order of the tiles can be modified in runtime
- Each tile has an anchorPoint of (0,0)
- The anchorPoint of the TMXTileMap is (0,0)
- The TMX layers will be added as a child
- The TMX layers will be aliased by default
- The tileset image will be loaded using the CCTextureCache
- Each tile will have a unique tag
- Each tile will have a unique z value. top-left: z=1, bottom-right:
z=max z
- Each object group will be treated as an CCMutableArray
- Object class which will contain all the properties in a dictionary
- Properties can be assigned to the Map, Layer, Object Group, and Ob
ject
Limitations:
- It only supports one tileset per layer.
- Embeded images are not supported
- It only supports the XML format (the JSON format is not supported)
Technical description:
Each layer is created using an CCTMXLayer (subclass of CCSpriteBatch
Node). If you have 5 layers, then 5 CCTMXLayer will be created,
unless the layer visibility is off. In that case, the layer won't be
created at all.
You can obtain the layers (CCTMXLayer objects) at runtime by:
- map->getChildByTag(tag_number); // 0=1st layer, 1=2nd layer, 2=3r
d layer, etc...
- map->layerNamed(name_of_the_layer);
Each object group is created using a CCTMXObjectGroup which is a sub
class of CCMutableArray.
You can obtain the object groups at runtime by:
- map->objectGroupNamed(name_of_the_object_group);
Each object is a CCTMXObject.
Each property is stored as a key-value pair in an CCMutableDictionar
y.
You can obtain the properties at runtime by:
map->propertyNamed(name_of_the_property);
layer->propertyNamed(name_of_the_property);
objectGroup->propertyNamed(name_of_the_property);
object->propertyNamed(name_of_the_property);
@since v0.8.1
*/
class CC_DLL CCTMXTiledMap : public CCNode
{
/** the map's size property measured in tiles */
CC_SYNTHESIZE_PASS_BY_REF(CCSize, m_tMapSize, MapSize);
/** the tiles's size property measured in pixels */
CC_SYNTHESIZE_PASS_BY_REF(CCSize, m_tTileSize, TileSize);
/** map orientation */
CC_SYNTHESIZE(int, m_nMapOrientation, MapOrientation);
/** object groups */
CC_PROPERTY(CCMutableArray<CCTMXObjectGroup*>*, m_pObjectGro
ups, ObjectGroups);
/** properties */
CC_PROPERTY(CCStringToStringDictionary*, m_pProperties, Prop
erties);
public:
CCTMXTiledMap();
virtual ~CCTMXTiledMap();
/** creates a TMX Tiled Map with a TMX file.*/
static CCTMXTiledMap * tiledMapWithTMXFile(const char *tmxFi
le);
/** initializes a TMX Tiled Map with a TMX file */
bool initWithTMXFile(const char *tmxFile);
/** return the TMXLayer for the specific layer */
CCTMXLayer* layerNamed(const char *layerName);
/** return the TMXObjectGroup for the secific group */
CCTMXObjectGroup* objectGroupNamed(const char *groupName);
/** return the value for the specific property name */
CCString *propertyNamed(const char *propertyName);
/** return properties dictionary for tile GID */
CCDictionary<std::string, CCString*> *propertiesForGID(int G
ID);
private:
CCTMXLayer * parseLayer(CCTMXLayerInfo *layerInfo, CCTMXMapI
nfo *mapInfo);
CCTMXTilesetInfo * tilesetForLayer(CCTMXLayerInfo *layerInfo
, CCTMXMapInfo *mapInfo);
protected:
//! tile properties
CCDictionary<int, CCStringToStringDictionary*> *m_pTileProperties;
CCDictionary<std::string, CCTMXLayer*> *m_pTMXLayers;
}; NS_CC_END
}// namespace cocos2d
#endif //__CCTMX_TILE_MAP_H__ #endif //__CCTMX_TILE_MAP_H__
 End of changes. 5 change blocks. 
132 lines changed or deleted 157 lines changed or added


 CCTMXXMLParser.h   CCTMXXMLParser.h 
skipping to change at line 29 skipping to change at line 29
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CC_TM_XML_PARSER__ #ifndef __CC_TM_XML_PARSER__
#define __CC_TM_XML_PARSER__ #define __CC_TM_XML_PARSER__
#include "CCMutableArray.h"
#include "CCMutableDictionary.h"
#include "CCGeometry.h"
#include "../platform/CCSAXParser.h"
namespace cocos2d {
class CCTMXObjectGroup;
/** @file
* Internal TMX parser
*
* IMPORTANT: These classed should not be documented using doxygen st
rings
* since the user should not use them.
*
*/
enum {
TMXLayerAttribNone = 1 << 0,
TMXLayerAttribBase64 = 1 << 1,
TMXLayerAttribGzip = 1 << 2,
TMXLayerAttribZlib = 1 << 3,
};
enum {
TMXPropertyNone,
TMXPropertyMap,
TMXPropertyLayer,
TMXPropertyObjectGroup,
TMXPropertyObject,
TMXPropertyTile
};
/** @brief CCTMXLayerInfo contains the information about the layers
like:
- Layer name
- Layer size
- Layer opacity at creation time (it can be modified at runtime)
- Whether the layer is visible (if it's not visible, then the CocosN
ode won't be created)
This information is obtained from the TMX file.
*/
class CC_DLL CCTMXLayerInfo : public CCObject
{
CC_PROPERTY(CCStringToStringDictionary*, m_pProperties, Prop
erties);
public:
std::string m_sName;
CCSize m_tLayerSize;
unsigned int *m_pTiles;
bool m_bVisible;
unsigned char m_cOpacity;
bool m_bOwnTiles;
unsigned int m_uMinGID;
unsigned int m_uMaxGID;
CCPoint m_tOffset;
public:
CCTMXLayerInfo();
virtual ~CCTMXLayerInfo();
};
/** @brief CCTMXTilesetInfo contains the information about the tiles
ets like:
- Tileset name
- Tilset spacing
- Tileset margin
- size of the tiles
- Image used for the tiles
- Image size
This information is obtained from the TMX file.
*/
class CC_DLL CCTMXTilesetInfo : public CCObject
{
public:
std::string m_sName;
unsigned int m_uFirstGid;
CCSize m_tTileSize;
unsigned int m_uSpacing;
unsigned int m_uMargin;
//! filename containing the tiles (should be spritesheet / t
exture atlas)
std::string m_sSourceImage;
//! size in pixels of the image
CCSize m_tImageSize;
public:
CCTMXTilesetInfo();
virtual ~CCTMXTilesetInfo();
CCRect rectForGID(unsigned int gid);
};
/** @brief CCTMXMapInfo contains the information about the map like:
- Map orientation (hexagonal, isometric or orthogonal)
- Tile size
- Map size
And it also contains:
- Layers (an array of TMXLayerInfo objects)
- Tilesets (an array of TMXTilesetInfo objects)
- ObjectGroups (an array of TMXObjectGroupInfo objects)
This information is obtained from the TMX file.
*/
class CC_DLL CCTMXMapInfo : public CCObject, public CCSAXDelegator
{
public:
/// map orientation
CC_SYNTHESIZE(int, m_nOrientation, Orientation);
/// map width & height
CC_SYNTHESIZE_PASS_BY_REF(CCSize, m_tMapSize, MapSize);
/// tiles width & height
CC_SYNTHESIZE_PASS_BY_REF(CCSize, m_tTileSize, TileSize);
/// Layers
CC_PROPERTY(CCMutableArray<CCTMXLayerInfo*>*, m_pLayers, Lay
ers);
/// tilesets
CC_PROPERTY(CCMutableArray<CCTMXTilesetInfo*>*, m_pTilesets,
Tilesets);
/// ObjectGroups
CC_PROPERTY(CCMutableArray<CCTMXObjectGroup*>*, m_pObjectGro
ups, ObjectGroups);
/// parent element
CC_SYNTHESIZE(int, m_nParentElement, ParentElement);
/// parent GID
CC_SYNTHESIZE(unsigned int, m_uParentGID, ParentGID);
/// layer attribs
CC_SYNTHESIZE(int, m_nLayerAttribs, LayerAttribs);
/// is stroing characters?
CC_SYNTHESIZE(bool, m_bStoringCharacters, StoringCharacters)
;
/// properties
CC_PROPERTY(CCStringToStringDictionary*, m_pProperties, Prop
erties);
public:
CCTMXMapInfo();
virtual ~CCTMXMapInfo();
/** creates a TMX Format with a tmx file */
static CCTMXMapInfo * formatWithTMXFile(const char *tmxFile)
;
/** initializes a TMX format witha tmx file */
bool initWithTMXFile(const char *tmxFile);
/** initalises parsing of an XML file, either a tmx (Map) fi
le or tsx (Tileset) file */
bool parseXMLFile(const char *xmlFilename);
CCDictionary<int, CCStringToStringDictionary*> * getTileProp
erties();
void setTileProperties(CCDictionary<int, CCStringToStringDic
tionary*> * tileProperties);
// implement pure virtual methods of CCSAXDelegator
void startElement(void *ctx, const char *name, const char **
atts);
void endElement(void *ctx, const char *name);
void textHandler(void *ctx, const char *ch, int len);
inline const char* getCurrentString(){ return m_sCurrentStri
ng.c_str(); }
inline void setCurrentString(const char *currentString){ m_s
CurrentString = currentString; }
inline const char* getTMXFileName(){ return m_sTMXFileName.c
_str(); }
inline void setTMXFileName(const char *fileName){ m_sTMXFile
Name = fileName; }
protected:
//! tmx filename
std::string m_sTMXFileName;
//! current string
std::string m_sCurrentString;
//! tile properties
CCDictionary<int, CCStringToStringDictionary*>* m_pTilePrope
rties;
};
}// namespace cocos2d #include "cocoa/CCArray.h"
#include "cocoa/CCDictionary.h"
#include "cocoa/CCGeometry.h"
#include "platform/CCSAXParser.h"
#include <string>
NS_CC_BEGIN
class CCTMXObjectGroup;
/** @file
* Internal TMX parser
*
* IMPORTANT: These classed should not be documented using doxygen strings
* since the user should not use them.
*
*/
/**
* @addtogroup tilemap_parallax_nodes
* @{
*/
enum {
TMXLayerAttribNone = 1 << 0,
TMXLayerAttribBase64 = 1 << 1,
TMXLayerAttribGzip = 1 << 2,
TMXLayerAttribZlib = 1 << 3,
};
enum {
TMXPropertyNone,
TMXPropertyMap,
TMXPropertyLayer,
TMXPropertyObjectGroup,
TMXPropertyObject,
TMXPropertyTile
};
typedef enum ccTMXTileFlags_ {
kCCTMXTileHorizontalFlag = 0x80000000,
kCCTMXTileVerticalFlag = 0x40000000,
kCCTMXTileDiagonalFlag = 0x20000000,
kCCFlipedAll = (kCCTMXTileHorizontalFlag|kCCTMXTileV
erticalFlag|kCCTMXTileDiagonalFlag),
kCCFlippedMask = ~(kCCFlipedAll)
} ccTMXTileFlags;
// Bits on the far end of the 32-bit global tile ID (GID's) are used for ti
le flags
/** @brief CCTMXLayerInfo contains the information about the layers like:
- Layer name
- Layer size
- Layer opacity at creation time (it can be modified at runtime)
- Whether the layer is visible (if it's not visible, then the CocosNode won
't be created)
This information is obtained from the TMX file.
*/
class CC_DLL CCTMXLayerInfo : public CCObject
{
CC_PROPERTY(CCDictionary*, m_pProperties, Properties);
public:
std::string m_sName;
CCSize m_tLayerSize;
unsigned int *m_pTiles;
bool m_bVisible;
unsigned char m_cOpacity;
bool m_bOwnTiles;
unsigned int m_uMinGID;
unsigned int m_uMaxGID;
CCPoint m_tOffset;
public:
CCTMXLayerInfo();
virtual ~CCTMXLayerInfo();
};
/** @brief CCTMXTilesetInfo contains the information about the tilesets lik
e:
- Tileset name
- Tilset spacing
- Tileset margin
- size of the tiles
- Image used for the tiles
- Image size
This information is obtained from the TMX file.
*/
class CC_DLL CCTMXTilesetInfo : public CCObject
{
public:
std::string m_sName;
unsigned int m_uFirstGid;
CCSize m_tTileSize;
unsigned int m_uSpacing;
unsigned int m_uMargin;
//! filename containing the tiles (should be spritesheet / texture atla
s)
std::string m_sSourceImage;
//! size in pixels of the image
CCSize m_tImageSize;
public:
CCTMXTilesetInfo();
virtual ~CCTMXTilesetInfo();
CCRect rectForGID(unsigned int gid);
};
/** @brief CCTMXMapInfo contains the information about the map like:
- Map orientation (hexagonal, isometric or orthogonal)
- Tile size
- Map size
And it also contains:
- Layers (an array of TMXLayerInfo objects)
- Tilesets (an array of TMXTilesetInfo objects)
- ObjectGroups (an array of TMXObjectGroupInfo objects)
This information is obtained from the TMX file.
*/
class CC_DLL CCTMXMapInfo : public CCObject, public CCSAXDelegator
{
public:
/// map orientation
CC_SYNTHESIZE(int, m_nOrientation, Orientation);
/// map width & height
CC_SYNTHESIZE_PASS_BY_REF(CCSize, m_tMapSize, MapSize);
/// tiles width & height
CC_SYNTHESIZE_PASS_BY_REF(CCSize, m_tTileSize, TileSize);
/// Layers
CC_PROPERTY(CCArray*, m_pLayers, Layers);
/// tilesets
CC_PROPERTY(CCArray*, m_pTilesets, Tilesets);
/// ObjectGroups
CC_PROPERTY(CCArray*, m_pObjectGroups, ObjectGroups);
/// parent element
CC_SYNTHESIZE(int, m_nParentElement, ParentElement);
/// parent GID
CC_SYNTHESIZE(unsigned int, m_uParentGID, ParentGID);
/// layer attribs
CC_SYNTHESIZE(int, m_nLayerAttribs, LayerAttribs);
/// is stroing characters?
CC_SYNTHESIZE(bool, m_bStoringCharacters, StoringCharacters);
/// properties
CC_PROPERTY(CCDictionary*, m_pProperties, Properties);
public:
CCTMXMapInfo();
virtual ~CCTMXMapInfo();
/** creates a TMX Format with a tmx file */
static CCTMXMapInfo * formatWithTMXFile(const char *tmxFile);
/** creates a TMX Format with an XML string and a TMX resource path */
static CCTMXMapInfo * formatWithXML(const char* tmxString, const char*
resourcePath);
/** initializes a TMX format witha tmx file */
bool initWithTMXFile(const char *tmxFile);
/** initializes a TMX format with an XML string and a TMX resource path
*/
bool initWithXML(const char* tmxString, const char* resourcePath);
/** initalises parsing of an XML file, either a tmx (Map) file or tsx (
Tileset) file */
bool parseXMLFile(const char *xmlFilename);
/* initalises parsing of an XML string, either a tmx (Map) string or ts
x (Tileset) string */
bool parseXMLString(const char *xmlString);
CCDictionary* getTileProperties();
void setTileProperties(CCDictionary* tileProperties);
// implement pure virtual methods of CCSAXDelegator
void startElement(void *ctx, const char *name, const char **atts);
void endElement(void *ctx, const char *name);
void textHandler(void *ctx, const char *ch, int len);
inline const char* getCurrentString(){ return m_sCurrentString.c_str();
}
inline void setCurrentString(const char *currentString){ m_sCurrentStri
ng = currentString; }
inline const char* getTMXFileName(){ return m_sTMXFileName.c_str(); }
inline void setTMXFileName(const char *fileName){ m_sTMXFileName = file
Name; }
private:
void internalInit(const char* tmxFileName, const char* resourcePath);
protected:
//! tmx filename
std::string m_sTMXFileName;
// tmx resource path
std::string m_sResources;
//! current string
std::string m_sCurrentString;
//! tile properties
CCDictionary* m_pTileProperties;
};
// end of tilemap_parallax_nodes group
/// @}
NS_CC_END
#endif #endif
 End of changes. 2 change blocks. 
179 lines changed or deleted 199 lines changed or added


 CCTextFieldTTF.h   CCTextFieldTTF.h 
skipping to change at line 28 skipping to change at line 28
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CC_TEXT_FIELD_H__ #ifndef __CC_TEXT_FIELD_H__
#define __CC_TEXT_FIELD_H__ #define __CC_TEXT_FIELD_H__
#include "CCLabelTTF.h" #include "label_nodes/CCLabelTTF.h"
#include "CCIMEDelegate.h" #include "text_input_node/CCIMEDelegate.h"
#include "CCTouchDelegateProtocol.h" #include "touch_dispatcher/CCTouchDelegateProtocol.h"
NS_CC_BEGIN; NS_CC_BEGIN
class CCTextFieldTTF; class CCTextFieldTTF;
/**
* @addtogroup input
* @{
*/
class CC_DLL CCTextFieldDelegate class CC_DLL CCTextFieldDelegate
{ {
public: public:
/** /**
@brief If the sender doesn't want to attach with IME, return true; @brief If the sender doesn't want to attach with IME, return true;
*/ */
virtual bool onTextFieldAttachWithIME(CCTextFieldTTF * sender) virtual bool onTextFieldAttachWithIME(CCTextFieldTTF * sender)
{ {
CC_UNUSED_PARAM(sender); CC_UNUSED_PARAM(sender);
return false; return false;
} }
/** /**
@brief If the sender doesn't want to detach with IME, return true; @brief If the sender doesn't want to detach with IME, return true;
*/ */
virtual bool onTextFieldDetachWithIME(CCTextFieldTTF * sender) virtual bool onTextFieldDetachWithIME(CCTextFieldTTF * sender)
{ {
CC_UNUSED_PARAM(sender); CC_UNUSED_PARAM(sender);
return false; return false;
} }
/** /**
@brief If the sender doesn't want to insert the text, return true; @brief If the sender doesn't want to insert the text, return true;
*/ */
virtual bool onTextFieldInsertText(CCTextFieldTTF * sender, const char * text, int nLen) virtual bool onTextFieldInsertText(CCTextFieldTTF * sender, const char * text, int nLen)
{ {
CC_UNUSED_PARAM(sender); CC_UNUSED_PARAM(sender);
CC_UNUSED_PARAM(text); CC_UNUSED_PARAM(text);
CC_UNUSED_PARAM(nLen); CC_UNUSED_PARAM(nLen);
return false; return false;
} }
/** /**
@brief If the sender doesn't want to delete the delText, return tru e; @brief If the sender doesn't want to delete the delText, return true ;
*/ */
virtual bool onTextFieldDeleteBackward(CCTextFieldTTF * sender, const c har * delText, int nLen) virtual bool onTextFieldDeleteBackward(CCTextFieldTTF * sender, const c har * delText, int nLen)
{ {
CC_UNUSED_PARAM(sender); CC_UNUSED_PARAM(sender);
CC_UNUSED_PARAM(delText); CC_UNUSED_PARAM(delText);
CC_UNUSED_PARAM(nLen); CC_UNUSED_PARAM(nLen);
return false; return false;
} }
/** /**
@brief If doesn't want draw sender as default, return true. @brief If doesn't want draw sender as default, return true.
*/ */
virtual bool onDraw(CCTextFieldTTF * sender) virtual bool onDraw(CCTextFieldTTF * sender)
{ {
CC_UNUSED_PARAM(sender); CC_UNUSED_PARAM(sender);
return false; return false;
} }
}; };
/** /**
@brief A simple text input field with TTF font. @brief A simple text input field with TTF font.
*/ */
class CC_DLL CCTextFieldTTF : public CCLabelTTF, public CCIMEDelegate class CC_DLL CCTextFieldTTF : public CCLabelTTF, public CCIMEDelegate
{ {
public: public:
CCTextFieldTTF(); CCTextFieldTTF();
virtual ~CCTextFieldTTF(); virtual ~CCTextFieldTTF();
//char * description(); //char * description();
/** creates a CCTextFieldTTF from a fontname, alignment, dimension and font size */ /** creates a CCTextFieldTTF from a fontname, alignment, dimension and font size */
static CCTextFieldTTF * textFieldWithPlaceHolder(const char *placeholde r, const CCSize& dimensions, CCTextAlignment alignment, const char *fontNam e, float fontSize); static CCTextFieldTTF * textFieldWithPlaceHolder(const char *placeholde r, const CCSize& dimensions, CCTextAlignment alignment, const char *fontNam e, float fontSize);
/** creates a CCLabelTTF from a fontname and font size */ /** creates a CCLabelTTF from a fontname and font size */
static CCTextFieldTTF * textFieldWithPlaceHolder(const char *placeholde r, const char *fontName, float fontSize); static CCTextFieldTTF * textFieldWithPlaceHolder(const char *placeholde r, const char *fontName, float fontSize);
/** initializes the CCTextFieldTTF with a font name, alignment, dimensi on and font size */ /** initializes the CCTextFieldTTF with a font name, alignment, dimensi on and font size */
bool initWithPlaceHolder(const char *placeholder, const CCSize& dimensi ons, CCTextAlignment alignment, const char *fontName, float fontSize); bool initWithPlaceHolder(const char *placeholder, const CCSize& dimensi ons, CCTextAlignment alignment, const char *fontName, float fontSize);
/** initializes the CCTextFieldTTF with a font name and font size */ /** initializes the CCTextFieldTTF with a font name and font size */
bool initWithPlaceHolder(const char *placeholder, const char *fontName, float fontSize); bool initWithPlaceHolder(const char *placeholder, const char *fontName, float fontSize);
/** /**
@brief Open keyboard and receive input text. @brief Open keyboard and receive input text.
*/ */
virtual bool attachWithIME(); virtual bool attachWithIME();
/** /**
@brief End text input and close keyboard. @brief End text input and close keyboard.
*/ */
virtual bool detachWithIME(); virtual bool detachWithIME();
/////////////////////////////////////////////////////////////////////// /// /////////////////////////////////////////////////////////////////////// ///
// properties // properties
/////////////////////////////////////////////////////////////////////// /// /////////////////////////////////////////////////////////////////////// ///
CC_SYNTHESIZE(CCTextFieldDelegate *, m_pDelegate, Delegate); CC_SYNTHESIZE(CCTextFieldDelegate *, m_pDelegate, Delegate);
CC_SYNTHESIZE_READONLY(int, m_nCharCount, CharCount); CC_SYNTHESIZE_READONLY(int, m_nCharCount, CharCount);
CC_SYNTHESIZE_PASS_BY_REF(ccColor3B, m_ColorSpaceHolder, ColorSpaceH older); CC_SYNTHESIZE_PASS_BY_REF(ccColor3B, m_ColorSpaceHolder, ColorSpaceHold er);
// input text property // input text property
public: public:
virtual void setString(const char *text); virtual void setString(const char *text);
virtual const char* getString(void); virtual const char* getString(void);
protected: protected:
std::string * m_pInputText; std::string * m_pInputText;
// place holder text property // place holder text property
// place holder text displayed when there is no text in the text field. // place holder text displayed when there is no text in the text field.
skipping to change at line 159 skipping to change at line 164
virtual bool canAttachWithIME(); virtual bool canAttachWithIME();
virtual bool canDetachWithIME(); virtual bool canDetachWithIME();
virtual void insertText(const char * text, int len); virtual void insertText(const char * text, int len);
virtual void deleteBackward(); virtual void deleteBackward();
virtual const char * getContentText(); virtual const char * getContentText();
private: private:
class LengthStack; class LengthStack;
LengthStack * m_pLens; LengthStack * m_pLens;
}; };
NS_CC_END; // end of input group
/// @}
NS_CC_END
#endif // __CC_TEXT_FIELD_H__ #endif // __CC_TEXT_FIELD_H__
 End of changes. 14 change blocks. 
14 lines changed or deleted 22 lines changed or added


 CCTexture2D.h   CCTexture2D.h 
/************************************************************************** ** /************************************************************************** **
Copyright (c) 2010-2011 cocos2d-x.org Copyright (c) 2010-2012 cocos2d-x.org
Copyright (C) 2008 Apple Inc. All Rights Reserved. Copyright (C) 2008 Apple Inc. All Rights Reserved.
http://www.cocos2d-x.org http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a cop y Permission is hereby granted, free of charge, to any person obtaining a cop y
of this software and associated documentation files (the "Software"), to de al of this software and associated documentation files (the "Software"), to de al
in the Software without restriction, including without limitation the right s in the Software without restriction, including without limitation the right s
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
skipping to change at line 30 skipping to change at line 30
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CCTEXTURE2D_H__ #ifndef __CCTEXTURE2D_H__
#define __CCTEXTURE2D_H__ #define __CCTEXTURE2D_H__
#include <string> #include <string>
#include "CCObject.h" #include "cocoa/CCObject.h"
#include "CCGeometry.h" #include "cocoa/CCGeometry.h"
#include "ccTypes.h" #include "ccTypes.h"
namespace cocos2d { NS_CC_BEGIN
class CCImage; class CCImage;
/**
* @addtogroup textures
* @{
*/
//CONSTANTS: //CONSTANTS:
/** @typedef CCTexture2DPixelFormat /** @typedef CCTexture2DPixelFormat
Possible texture pixel formats Possible texture pixel formats
*/ */
typedef enum { typedef enum {
kCCTexture2DPixelFormat_Automatic = 0,
//! 32-bit texture: RGBA8888 //! 32-bit texture: RGBA8888
kCCTexture2DPixelFormat_RGBA8888, kCCTexture2DPixelFormat_RGBA8888,
//! 24-bit texture: RGBA888 //! 24-bit texture: RGBA888
kCCTexture2DPixelFormat_RGB888, kCCTexture2DPixelFormat_RGB888,
//! 16-bit texture without Alpha channel //! 16-bit texture without Alpha channel
kCCTexture2DPixelFormat_RGB565, kCCTexture2DPixelFormat_RGB565,
//! 8-bit textures used as masks //! 8-bit textures used as masks
kCCTexture2DPixelFormat_A8, kCCTexture2DPixelFormat_A8,
//! 8-bit intensity texture //! 8-bit intensity texture
kCCTexture2DPixelFormat_I8, kCCTexture2DPixelFormat_I8,
//! 16-bit textures used as masks //! 16-bit textures used as masks
kCCTexture2DPixelFormat_AI88, kCCTexture2DPixelFormat_AI88,
//! 16-bit textures: RGBA4444 //! 16-bit textures: RGBA4444
kCCTexture2DPixelFormat_RGBA4444, kCCTexture2DPixelFormat_RGBA4444,
//! 16-bit textures: RGB5A1 //! 16-bit textures: RGB5A1
kCCTexture2DPixelFormat_RGB5A1, kCCTexture2DPixelFormat_RGB5A1,
//! 4-bit PVRTC-compressed texture: PVRTC4 //! 4-bit PVRTC-compressed texture: PVRTC4
kCCTexture2DPixelFormat_PVRTC4, kCCTexture2DPixelFormat_PVRTC4,
//! 2-bit PVRTC-compressed texture: PVRTC2 //! 2-bit PVRTC-compressed texture: PVRTC2
kCCTexture2DPixelFormat_PVRTC2, kCCTexture2DPixelFormat_PVRTC2,
//! Default texture format: RGBA8888 //! Default texture format: RGBA8888
kCCTexture2DPixelFormat_Default = kCCTexture2DPixelFormat_RGBA8888, kCCTexture2DPixelFormat_Default = kCCTexture2DPixelFormat_RGBA8888,
// backward compatibility stuff // backward compatibility stuff
kTexture2DPixelFormat_Automatic = kCCTexture2DPixelFormat_Automatic, kTexture2DPixelFormat_RGBA8888 = kCCTexture2DPixelFormat_RGBA8888,
kTexture2DPixelFormat_RGBA8888 = kCCTexture2DPixelFormat_RGBA8888, kTexture2DPixelFormat_RGB888 = kCCTexture2DPixelFormat_RGB888,
kTexture2DPixelFormat_RGB888 = kCCTexture2DPixelFormat_RGB888, kTexture2DPixelFormat_RGB565 = kCCTexture2DPixelFormat_RGB565,
kTexture2DPixelFormat_RGB565 = kCCTexture2DPixelFormat_RGB565, kTexture2DPixelFormat_A8 = kCCTexture2DPixelFormat_A8,
kTexture2DPixelFormat_A8 = kCCTexture2DPixelFormat_A8, kTexture2DPixelFormat_RGBA4444 = kCCTexture2DPixelFormat_RGBA4444,
kTexture2DPixelFormat_RGBA4444 = kCCTexture2DPixelFormat_RGBA4444, kTexture2DPixelFormat_RGB5A1 = kCCTexture2DPixelFormat_RGB5A1,
kTexture2DPixelFormat_RGB5A1 = kCCTexture2DPixelFormat_RGB5A1, kTexture2DPixelFormat_Default = kCCTexture2DPixelFormat_Default
kTexture2DPixelFormat_Default = kCCTexture2DPixelFormat_Default
} CCTexture2DPixelFormat; } CCTexture2DPixelFormat;
class CCGLProgram;
/** /**
Extension to set the Min / Mag filter Extension to set the Min / Mag filter
*/ */
typedef struct _ccTexParams { typedef struct _ccTexParams {
GLuint minFilter; GLuint minFilter;
GLuint magFilter; GLuint magFilter;
GLuint wrapS; GLuint wrapS;
GLuint wrapT; GLuint wrapT;
} ccTexParams; } ccTexParams;
//CLASS INTERFACES: //CLASS INTERFACES:
/** @brief CCTexture2D class. /** @brief CCTexture2D class.
* This class allows to easily create OpenGL 2D textures from images, text o r raw data. * This class allows to easily create OpenGL 2D textures from images, text o r raw data.
* The created CCTexture2D object will always have power-of-two dimensions. * The created CCTexture2D object will always have power-of-two dimensions.
* Depending on how you create the CCTexture2D object, the actual image area of the texture might be smaller than the texture dimensions i.e. "contentS ize" != (pixelsWide, pixelsHigh) and (maxS, maxT) != (1.0, 1.0). * Depending on how you create the CCTexture2D object, the actual image area of the texture might be smaller than the texture dimensions i.e. "contentS ize" != (pixelsWide, pixelsHigh) and (maxS, maxT) != (1.0, 1.0).
* Be aware that the content of the generated textures will be upside-down! * Be aware that the content of the generated textures will be upside-down!
*/ */
class CC_DLL CCTexture2D : public CCObject class CC_DLL CCTexture2D : public CCObject
{ {
/** pixel format of the texture */
CC_PROPERTY_READONLY(CCTexture2DPixelFormat, m_ePixelFormat, PixelFo
rmat)
/** width in pixels */
CC_PROPERTY_READONLY(unsigned int, m_uPixelsWide, PixelsWide)
/** hight in pixels */
CC_PROPERTY_READONLY(unsigned int, m_uPixelsHigh, PixelsHigh)
/** texture name */
CC_PROPERTY_READONLY(GLuint, m_uName, Name)
/** content size */
CC_PROPERTY_READONLY_PASS_BY_REF(CCSize, m_tContentSize, ContentSize
InPixels)
/** texture max S */
CC_PROPERTY(GLfloat, m_fMaxS, MaxS)
/** texture max T */
CC_PROPERTY(GLfloat, m_fMaxT, MaxT)
/** whether or not the texture has their Alpha premultiplied */
CC_PROPERTY_READONLY(bool, m_bHasPremultipliedAlpha, HasPremultiplie
dAlpha);
public: public:
CCTexture2D(); CCTexture2D();
virtual ~CCTexture2D(); virtual ~CCTexture2D();
char * description(void); const char* description(void);
/** These functions are needed to create mutable textures */ /** These functions are needed to create mutable textures */
void releaseData(void *data); void releaseData(void *data);
void* keepData(void *data, unsigned int length); void* keepData(void *data, unsigned int length);
/** Intializes with a texture2d with data */ /** Intializes with a texture2d with data */
bool initWithData(const void* data, CCTexture2DPixelFormat pixelForm bool initWithData(const void* data, CCTexture2DPixelFormat pixelFormat,
at, unsigned int pixelsWide, unsigned int pixelsHigh, const CCSize& content unsigned int pixelsWide, unsigned int pixelsHigh, const CCSize& contentSiz
Size); e);
/** /**
Drawing extensions to make it easy to draw basic quads using a CCTex Drawing extensions to make it easy to draw basic quads using a CCTextur
ture2D object. e2D object.
These functions require GL_TEXTURE_2D and both GL_VERTEX_ARRAY and G These functions require GL_TEXTURE_2D and both GL_VERTEX_ARRAY and GL_T
L_TEXTURE_COORD_ARRAY client states to be enabled. EXTURE_COORD_ARRAY client states to be enabled.
*/ */
/** draws a texture at a given point */ /** draws a texture at a given point */
void drawAtPoint(const CCPoint& point); void drawAtPoint(const CCPoint& point);
/** draws a texture inside a rect */ /** draws a texture inside a rect */
void drawInRect(const CCRect& rect); void drawInRect(const CCRect& rect);
/** /**
Extensions to make it easy to create a CCTexture2D object from an im Extensions to make it easy to create a CCTexture2D object from an image
age file. file.
Note that RGBA type textures will have their alpha premultiplied - u Note that RGBA type textures will have their alpha premultiplied - use
se the blending mode (GL_ONE, GL_ONE_MINUS_SRC_ALPHA). the blending mode (GL_ONE, GL_ONE_MINUS_SRC_ALPHA).
*/ */
/** Initializes a texture from a UIImage object */ /** Initializes a texture from a UIImage object */
bool initWithImage(CCImage * uiImage);
bool initWithImage(CCImage * uiImage);
/**
Extensions to make it easy to create a CCTexture2D object from a str /** Initializes a texture from a string with dimensions, alignment, fon
ing of text. t name and font size */
Note that the generated textures are of type A8 - use the blending m bool initWithString(const char *text, const CCSize& dimensions, CCTextA
ode (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA). lignment hAlignment, CCVerticalTextAlignment vAlignment, const char *fontNa
*/ me, float fontSize);
/** Initializes a texture from a string with dimensions, alignment, /** Initializes a texture from a string with font name and font size */
font name and font size */ bool initWithString(const char *text, const char *fontName, float fontS
bool initWithString(const char *text, const CCSize& dimensions, CCTe ize);
xtAlignment alignment, const char *fontName, float fontSize);
/** Initializes a texture from a string with font name and font size
*/
bool initWithString(const char *text, const char *fontName, float fo
ntSize);
/** returns the content size of the texture in points */
CCSize getContentSize(void);
#ifdef CC_SUPPORT_PVRTC #ifdef CC_SUPPORT_PVRTC
/** /**
Extensions to make it easy to create a CCTexture2D object from a PVR Extensions to make it easy to create a CCTexture2D object from a PVRTC
TC file file
Note that the generated textures don't have their alpha premultiplie Note that the generated textures don't have their alpha premultiplied -
d - use the blending mode (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA). use the blending mode (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA).
*/ */
/** Initializes a texture from a PVRTC buffer */ /** Initializes a texture from a PVRTC buffer */
bool initWithPVRTCData(const void *data, int level, int bpp, bool hasAl pha, int length, CCTexture2DPixelFormat pixelFormat); bool initWithPVRTCData(const void *data, int level, int bpp, bool hasAl pha, int length, CCTexture2DPixelFormat pixelFormat);
#endif // CC_SUPPORT_PVRTC #endif // CC_SUPPORT_PVRTC
/** Initializes a texture from a PVR file */ /** Initializes a texture from a PVR file */
bool initWithPVRFile(const char* file); bool initWithPVRFile(const char* file);
/** sets the min filter, mag filter, wrap s and wrap t texture paramete
rs.
If the texture size is NPOT (non power of 2), then in can only use GL_C
LAMP_TO_EDGE in GL_TEXTURE_WRAP_{S,T}.
@warning Calling this method could allocate additional texture memory.
@since v0.8
*/
void setTexParameters(ccTexParams* texParams);
/** sets antialias texture parameters:
- GL_TEXTURE_MIN_FILTER = GL_LINEAR
- GL_TEXTURE_MAG_FILTER = GL_LINEAR
@warning Calling this method could allocate additional texture memory.
/** sets the min filter, mag filter, wrap s and wrap t texture param @since v0.8
eters. */
If the texture size is NPOT (non power of 2), then in can only use G void setAntiAliasTexParameters();
L_CLAMP_TO_EDGE in GL_TEXTURE_WRAP_{S,T}.
@since v0.8 /** sets alias texture parameters:
*/ - GL_TEXTURE_MIN_FILTER = GL_NEAREST
void setTexParameters(ccTexParams* texParams); - GL_TEXTURE_MAG_FILTER = GL_NEAREST
/** sets antialias texture parameters: @warning Calling this method could allocate additional texture memory.
- GL_TEXTURE_MIN_FILTER = GL_LINEAR
- GL_TEXTURE_MAG_FILTER = GL_LINEAR @since v0.8
*/
@since v0.8 void setAliasTexParameters();
*/
void setAntiAliasTexParameters(); /** Generates mipmap images for the texture.
It only works if the texture size is POT (power of 2).
/** sets alias texture parameters: @since v0.99.0
- GL_TEXTURE_MIN_FILTER = GL_NEAREST */
- GL_TEXTURE_MAG_FILTER = GL_NEAREST void generateMipmap();
@since v0.8 /** returns the pixel format.
*/ @since v2.0
void setAliasTexParameters(); */
const char* stringForFormat();
/** Generates mipmap images for the texture.
It only works if the texture size is POT (power of 2). /** returns the bits-per-pixel of the in-memory OpenGL texture
@since v0.99.0 @since v1.0
*/ */
void generateMipmap();
/** returns the bits-per-pixel of the in-memory OpenGL texture
@since v1.0
*/
unsigned int bitsPerPixelForFormat(); unsigned int bitsPerPixelForFormat();
/** sets the default pixel format for UIImagescontains alpha channel /** Helper functions that returns bits per pixels for a given format.
. @since v2.0
If the UIImage contains alpha channel, then the options are: */
- generate 32-bit textures: kCCTexture2DPixelFormat_RGBA8888 (defaul unsigned int bitsPerPixelForFormat(CCTexture2DPixelFormat format);
t one)
- generate 24-bit textures: kCCTexture2DPixelFormat_RGB888 /** sets the default pixel format for UIImagescontains alpha channel.
- generate 16-bit textures: kCCTexture2DPixelFormat_RGBA4444 If the UIImage contains alpha channel, then the options are:
- generate 16-bit textures: kCCTexture2DPixelFormat_RGB5A1 - generate 32-bit textures: kCCTexture2DPixelFormat_RGBA8888 (default o
- generate 16-bit textures: kCCTexture2DPixelFormat_RGB565 ne)
- generate 8-bit textures: kCCTexture2DPixelFormat_A8 (only use it i - generate 24-bit textures: kCCTexture2DPixelFormat_RGB888
f you use just 1 color) - generate 16-bit textures: kCCTexture2DPixelFormat_RGBA4444
- generate 16-bit textures: kCCTexture2DPixelFormat_RGB5A1
How does it work ? - generate 16-bit textures: kCCTexture2DPixelFormat_RGB565
- If the image is an RGBA (with Alpha) then the default pixel format - generate 8-bit textures: kCCTexture2DPixelFormat_A8 (only use it if y
will be used (it can be a 8-bit, 16-bit or 32-bit texture) ou use just 1 color)
- If the image is an RGB (without Alpha) then an RGB565 or RGB888 te
xture will be used (16-bit texture) How does it work ?
- If the image is an RGBA (with Alpha) then the default pixel format wi
@since v0.8 ll be used (it can be a 8-bit, 16-bit or 32-bit texture)
*/ - If the image is an RGB (without Alpha) then: If the default pixel for
static void setDefaultAlphaPixelFormat(CCTexture2DPixelFormat format mat is RGBA8888 then a RGBA8888 (32-bit) will be used. Otherwise a RGB565 (
); 16-bit texture) will be used.
/** returns the alpha pixel format This parameter is not valid for PVR / PVR.CCZ images.
@since v0.8
*/ @since v0.8
static CCTexture2DPixelFormat defaultAlphaPixelFormat(); */
static void setDefaultAlphaPixelFormat(CCTexture2DPixelFormat format);
/** treats (or not) PVR files as if they have alpha premultiplied.
Since it is impossible to know at runtime if the PVR images have th /** returns the alpha pixel format
e alpha channel premultiplied, it is @since v0.8
possible load them as if they have (or not) the alpha channel premu */
ltiplied. static CCTexture2DPixelFormat defaultAlphaPixelFormat();
By default it is disabled. /** treats (or not) PVR files as if they have alpha premultiplied.
Since it is impossible to know at runtime if the PVR images have the a
@since v0.99.5 lpha channel premultiplied, it is
*/ possible load them as if they have (or not) the alpha channel premulti
static void PVRImagesHavePremultipliedAlpha(bool haveAlphaPremultipl plied.
ied);
By default it is disabled.
@since v0.99.5
*/
static void PVRImagesHavePremultipliedAlpha(bool haveAlphaPremultiplied
);
/** content size */
const CCSize& getContentSizeInPixels();
bool hasPremultipliedAlpha();
bool hasMipmaps();
private: private:
bool initPremultipliedATextureWithImage(CCImage * image, unsigned in t pixelsWide, unsigned int pixelsHigh); bool initPremultipliedATextureWithImage(CCImage * image, unsigned int p ixelsWide, unsigned int pixelsHigh);
// By default PVR images are treated as if they don't have the alpha ch annel premultiplied // By default PVR images are treated as if they don't have the alpha ch annel premultiplied
bool m_bPVRHaveAlphaPremultiplied; bool m_bPVRHaveAlphaPremultiplied;
/** pixel format of the texture */
CC_PROPERTY_READONLY(CCTexture2DPixelFormat, m_ePixelFormat, PixelForma
t)
/** width in pixels */
CC_PROPERTY_READONLY(unsigned int, m_uPixelsWide, PixelsWide)
/** hight in pixels */
CC_PROPERTY_READONLY(unsigned int, m_uPixelsHigh, PixelsHigh)
/** texture name */
CC_PROPERTY_READONLY(GLuint, m_uName, Name)
/** texture max S */
CC_PROPERTY(GLfloat, m_fMaxS, MaxS)
/** texture max T */
CC_PROPERTY(GLfloat, m_fMaxT, MaxT)
/** content size */
CC_PROPERTY_READONLY(CCSize, m_tContentSize, ContentSize)
/** whether or not the texture has their Alpha premultiplied */
bool m_bHasPremultipliedAlpha;
bool m_bHasMipmaps;
/** shader program used by drawAtPoint and drawInRect */
CC_PROPERTY(CCGLProgram*, m_pShaderProgram, ShaderProgram);
}; };
}//namespace cocos2d
// end of textures group
/// @}
NS_CC_END
#endif //__CCTEXTURE2D_H__ #endif //__CCTEXTURE2D_H__
 End of changes. 19 change blocks. 
196 lines changed or deleted 225 lines changed or added


 CCTextureAtlas.h   CCTextureAtlas.h 
skipping to change at line 30 skipping to change at line 30
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CCTEXTURE_ATLAS_H__ #ifndef __CCTEXTURE_ATLAS_H__
#define __CCTEXTURE_ATLAS_H__ #define __CCTEXTURE_ATLAS_H__
#include <string>
#include "ccTypes.h" #include "ccTypes.h"
#include "CCObject.h" #include "cocoa/CCObject.h"
#include "ccConfig.h" #include "ccConfig.h"
#include <string>
NS_CC_BEGIN
namespace cocos2d {
class CCTexture2D; class CCTexture2D;
/**
* @addtogroup textures
* @{
*/
/** @brief A class that implements a Texture Atlas. /** @brief A class that implements a Texture Atlas.
Supported features: Supported features:
* The atlas file can be a PVRTC, PNG or any other fomrat supported by Textu re2D * The atlas file can be a PVRTC, PNG or any other fomrat supported by Textu re2D
* Quads can be udpated in runtime * Quads can be udpated in runtime
* Quads can be added in runtime * Quads can be added in runtime
* Quads can be removed in runtime * Quads can be removed in runtime
* Quads can be re-ordered in runtime * Quads can be re-ordered in runtime
* The TextureAtlas capacity can be increased or decreased in runtime * The TextureAtlas capacity can be increased or decreased in runtime
* OpenGL component: V3F, C4B, T2F. * OpenGL component: V3F, C4B, T2F.
The quads are rendered using an OpenGL ES VBO. The quads are rendered using an OpenGL ES VBO.
To render the quads using an interleaved vertex array list, you should modi fy the ccConfig.h file To render the quads using an interleaved vertex array list, you should modi fy the ccConfig.h file
*/ */
class CC_DLL CCTextureAtlas : public CCObject class CC_DLL CCTextureAtlas : public CCObject
{ {
protected: protected:
GLushort *m_pIndices; GLushort* m_pIndices;
#if CC_USES_VBO #if CC_TEXTURE_ATLAS_USE_VAO
GLuint m_pBuffersVBO[2]; //0: vertex 1: in GLuint m_uVAOname;
dices #endif
bool m_bDirty; //indicates whether or not GLuint m_pBuffersVBO[2]; //0: vertex 1: indices
the array buffer of the VBO needs to be updated bool m_bDirty; //indicates whether or not the array buff
#endif // CC_USES_VBO er of the VBO needs to be updated
/** quantity of quads that are going to be drawn */ /** quantity of quads that are going to be drawn */
CC_PROPERTY_READONLY(unsigned int, m_uTotalQuads, TotalQuads) CC_PROPERTY_READONLY(unsigned int, m_uTotalQuads, TotalQuads)
/** quantity of quads that can be stored with the current texture at /** quantity of quads that can be stored with the current texture atlas
las size */ size */
CC_PROPERTY_READONLY(unsigned int, m_uCapacity, Capacity) CC_PROPERTY_READONLY(unsigned int, m_uCapacity, Capacity)
/** Texture of the texture atlas */ /** Texture of the texture atlas */
CC_PROPERTY(CCTexture2D *, m_pTexture, Texture) CC_PROPERTY(CCTexture2D *, m_pTexture, Texture)
/** Quads that are going to be rendered */ /** Quads that are going to be rendered */
CC_PROPERTY(ccV3F_C4B_T2F_Quad *, m_pQuads, Quads) CC_PROPERTY(ccV3F_C4B_T2F_Quad *, m_pQuads, Quads)
public: public:
CCTextureAtlas(); CCTextureAtlas();
virtual ~CCTextureAtlas(); virtual ~CCTextureAtlas();
char * description(); const char* description();
/** creates a TextureAtlas with an filename and with an initial capa /** creates a TextureAtlas with an filename and with an initial capacit
city for Quads. y for Quads.
* The TextureAtlas capacity can be increased in runtime. * The TextureAtlas capacity can be increased in runtime.
*/ @deprecated: This interface will be deprecated sooner or later.
static CCTextureAtlas * textureAtlasWithFile(const char* file , unsi */
gned int capacity); CC_DEPRECATED_ATTRIBUTE static CCTextureAtlas * textureAtlasWithFile(co
nst char* file , unsigned int capacity);
/** initializes a TextureAtlas with a filename and with a certain ca
pacity for Quads. /** creates a TextureAtlas with an filename and with an initial capacit
* The TextureAtlas capacity can be increased in runtime. y for Quads.
* * The TextureAtlas capacity can be increased in runtime.
* WARNING: Do not reinitialize the TextureAtlas because it will leak */
memory (issue #706) static CCTextureAtlas* create(const char* file , unsigned int capacity)
*/ ;
bool initWithFile(const char* file, unsigned int capacity);
/** initializes a TextureAtlas with a filename and with a certain capac
/** creates a TextureAtlas with a previously initialized Texture2D o ity for Quads.
bject, and * The TextureAtlas capacity can be increased in runtime.
* with an initial capacity for n Quads. *
* The TextureAtlas capacity can be increased in runtime. * WARNING: Do not reinitialize the TextureAtlas because it will leak me
*/ mory (issue #706)
static CCTextureAtlas * textureAtlasWithTexture(CCTexture2D *texture */
, unsigned int capacity); bool initWithFile(const char* file, unsigned int capacity);
/** initializes a TextureAtlas with a previously initialized Texture /** creates a TextureAtlas with a previously initialized Texture2D obje
2D object, and ct, and
* with an initial capacity for Quads. * with an initial capacity for n Quads.
* The TextureAtlas capacity can be increased in runtime. * The TextureAtlas capacity can be increased in runtime.
* @deprecated: This interface will be deprecated sooner or later.
* WARNING: Do not reinitialize the TextureAtlas because it will leak */
memory (issue #706) CC_DEPRECATED_ATTRIBUTE static CCTextureAtlas * textureAtlasWithTexture
*/ (CCTexture2D *texture, unsigned int capacity);
bool initWithTexture(CCTexture2D *texture, unsigned int capacity);
/** creates a TextureAtlas with a previously initialized Texture2D objec
/** updates a Quad (texture, vertex and color) at a certain index t, and
* index must be between 0 and the atlas capacity - 1 * with an initial capacity for n Quads.
@since v0.8 * The TextureAtlas capacity can be increased in runtime.
*/ */
void updateQuad(ccV3F_C4B_T2F_Quad* quad, unsigned int index); static CCTextureAtlas* createWithTexture(CCTexture2D *texture, unsigned
int capacity);
/** Inserts a Quad (texture, vertex and color) at a certain index
index must be between 0 and the atlas capacity - 1 /** initializes a TextureAtlas with a previously initialized Texture2D
@since v0.8 object, and
*/ * with an initial capacity for Quads.
void insertQuad(ccV3F_C4B_T2F_Quad* quad, unsigned int index); * The TextureAtlas capacity can be increased in runtime.
*
/** Removes the quad that is located at a certain index and inserts * WARNING: Do not reinitialize the TextureAtlas because it will leak me
it at a new index mory (issue #706)
This operation is faster than removing and inserting in a quad in 2 */
different steps bool initWithTexture(CCTexture2D *texture, unsigned int capacity);
@since v0.7.2
*/ /** updates a Quad (texture, vertex and color) at a certain index
void insertQuadFromIndex(unsigned int fromIndex, unsigned int newInd * index must be between 0 and the atlas capacity - 1
ex); @since v0.8
*/
/** removes a quad at a given index number. void updateQuad(ccV3F_C4B_T2F_Quad* quad, unsigned int index);
The capacity remains the same, but the total number of quads to be d
rawn is reduced in 1 /** Inserts a Quad (texture, vertex and color) at a certain index
@since v0.7.2 index must be between 0 and the atlas capacity - 1
*/ @since v0.8
void removeQuadAtIndex(unsigned int index); */
void insertQuad(ccV3F_C4B_T2F_Quad* quad, unsigned int index);
/** removes all Quads.
The TextureAtlas capacity remains untouched. No memory is freed. /** Inserts a c array of quads at a given index
The total number of quads to be drawn will be 0 index must be between 0 and the atlas capacity - 1
@since v0.7.2 this method doesn't enlarge the array when amount + index > totalQuads
*/ @since v1.1
void removeAllQuads(); */
void insertQuads(ccV3F_C4B_T2F_Quad* quads, unsigned int index, unsigne
/** resize the capacity of the CCTextureAtlas. d int amount);
* The new capacity can be lower or higher than the current one
* It returns YES if the resize was successful. /** Removes the quad that is located at a certain index and inserts it
* If it fails to resize the capacity it will return NO with a new ca at a new index
pacity of 0. This operation is faster than removing and inserting in a quad in 2 dif
*/ ferent steps
bool resizeCapacity(unsigned int n); @since v0.7.2
*/
/** draws n quads void insertQuadFromIndex(unsigned int fromIndex, unsigned int newIndex)
* n can't be greater than the capacity of the Atlas ;
*/
void drawNumberOfQuads(unsigned int n); /** removes a quad at a given index number.
The capacity remains the same, but the total number of quads to be draw
/** draws n quads from an index (offset). n is reduced in 1
n + start can't be greater than the capacity of the atlas @since v0.7.2
*/
@since v1.0 void removeQuadAtIndex(unsigned int index);
*/
void drawNumberOfQuads(unsigned int n, unsigned int start); /** removes a amount of quads starting from index
@since 1.1
/** draws all the Atlas's Quads */
*/ void removeQuadsAtIndex(unsigned int index, unsigned int amount);
void drawQuads(); /** removes all Quads.
The TextureAtlas capacity remains untouched. No memory is freed.
The total number of quads to be drawn will be 0
@since v0.7.2
*/
void removeAllQuads();
/** resize the capacity of the CCTextureAtlas.
* The new capacity can be lower or higher than the current one
* It returns YES if the resize was successful.
* If it fails to resize the capacity it will return NO with a new capac
ity of 0.
*/
bool resizeCapacity(unsigned int n);
/**
Used internally by CCParticleBatchNode
don't use this unless you know what you're doing
@since 1.1
*/
void increaseTotalQuadsWith(unsigned int amount);
/** Moves an amount of quads from oldIndex at newIndex
@since v1.1
*/
void moveQuadsFromIndex(unsigned int oldIndex, unsigned int amount, uns
igned int newIndex);
/**
Moves quads from index till totalQuads to the newIndex
Used internally by CCParticleBatchNode
This method doesn't enlarge the array if newIndex + quads to be moved
> capacity
@since 1.1
*/
void moveQuadsFromIndex(unsigned int index, unsigned int newIndex);
/**
Ensures that after a realloc quads are still empty
Used internally by CCParticleBatchNode
@since 1.1
*/
void fillWithEmptyQuadsFromIndex(unsigned int index, unsigned int amoun
t);
/** draws n quads
* n can't be greater than the capacity of the Atlas
*/
void drawNumberOfQuads(unsigned int n);
/** draws n quads from an index (offset).
n + start can't be greater than the capacity of the atlas
@since v1.0
*/
void drawNumberOfQuads(unsigned int n, unsigned int start);
/** draws all the Atlas's Quads
*/
void drawQuads();
/** listen the event that coming to foreground on Android
*/
void listenBackToForeground(CCObject *obj);
private: private:
void initIndices(); void setupIndices();
void mapBuffers();
#if CC_TEXTURE_ATLAS_USE_VAO
void setupVBOandVAO();
#else
void setupVBO();
#endif
}; };
}//namespace cocos2d
// end of textures group
/// @}
NS_CC_END
#endif //__CCTEXTURE_ATLAS_H__ #endif //__CCTEXTURE_ATLAS_H__
 End of changes. 11 change blocks. 
117 lines changed or deleted 195 lines changed or added


 CCTextureCache.h   CCTextureCache.h 
skipping to change at line 30 skipping to change at line 30
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CCTEXTURE_CACHE_H__ #ifndef __CCTEXTURE_CACHE_H__
#define __CCTEXTURE_CACHE_H__ #define __CCTEXTURE_CACHE_H__
#include "cocoa/CCObject.h"
#include "cocoa/CCDictionary.h"
#include "textures/CCTexture2D.h"
#include <string> #include <string>
#include "CCObject.h"
#include "CCMutableDictionary.h"
#include "CCTexture2D.h"
#if CC_ENABLE_CACHE_TEXTTURE_DATA #if CC_ENABLE_CACHE_TEXTURE_DATA
#include "CCImage.h" #include "platform/CCImage.h"
#include <list> #include <list>
#endif #endif
namespace cocos2d { NS_CC_BEGIN
class CCLock; class CCLock;
class CCImage; class CCImage;
/**
* @addtogroup textures
* @{
*/
/** @brief Singleton that handles the loading of textures /** @brief Singleton that handles the loading of textures
* Once the texture is loaded, the next time it will return * Once the texture is loaded, the next time it will return
* a reference of the previously loaded texture reducing GPU & CPU memory * a reference of the previously loaded texture reducing GPU & CPU memory
*/ */
class CC_DLL CCTextureCache : public CCObject class CC_DLL CCTextureCache : public CCObject
{ {
protected: protected:
CCMutableDictionary<std::string, CCTexture2D*> * m_pTextures; CCDictionary* m_pTextures;
//pthread_mutex_t *m_pDictLock; //pthread_mutex_t *m_pDictLock;
private: private:
// @todo void addImageWithAsyncObject(CCAsyncObject* async); /// todo: void addImageWithAsyncObject(CCAsyncObject* async);
void addImageAsyncCallBack(ccTime dt); void addImageAsyncCallBack(float dt);
public: public:
CCTextureCache(); CCTextureCache();
virtual ~CCTextureCache(); virtual ~CCTextureCache();
const char* description(void);
CCDictionary* snapshotTextures();
char * description(void); /** Retruns ths shared instance of the cache */
static CCTextureCache * sharedTextureCache();
/** Retruns ths shared instance of the cache */ /** purges the cache. It releases the retained instance.
static CCTextureCache * sharedTextureCache(); @since v0.99.0
*/
static void purgeSharedTextureCache();
/** Returns a Texture2D object given an file image
* If the file image was not previously loaded, it will create a new CCT
exture2D
* object and it will return it. It will use the filename as a key.
* Otherwise it will return a reference of a previosly loaded image.
* Supported image extensions: .png, .bmp, .tiff, .jpeg, .pvr, .gif
*/
CCTexture2D* addImage(const char* fileimage);
/** purges the cache. It releases the retained instance. /* Returns a Texture2D object given a file image
@since v0.99.0 * If the file image was not previously loaded, it will create a new CCT
*/ exture2D object and it will return it.
static void purgeSharedTextureCache(); * Otherwise it will load a texture in a new thread, and when the image
is loaded, the callback will be called with the Texture2D as a parameter.
/** Returns a Texture2D object given an file image * The callback will be called from the main thread, so it is safe to cr
* If the file image was not previously loaded, it will create a new eate any cocos2d object from the callback.
CCTexture2D * Supported image extensions: .png, .jpg
* object and it will return it. It will use the filename as a key. * @since v0.8
* Otherwise it will return a reference of a previosly loaded image. */
* Supported image extensions: .png, .bmp, .tiff, .jpeg, .pvr, .gif
*/ void addImageAsync(const char *path, CCObject *target, SEL_CallFuncO se
CCTexture2D* addImage(const char* fileimage); lector);
/* Returns a Texture2D object given a file image /* Returns a Texture2D object given an CGImageRef image
* If the file image was not previously loaded, it will create a new * If the image was not previously loaded, it will create a new CCTextur
CCTexture2D object and it will return it. e2D object and it will return it.
* Otherwise it will load a texture in a new thread, and when the ima * Otherwise it will return a reference of a previously loaded image
ge is loaded, the callback will be called with the Texture2D as a parameter * The "key" parameter will be used as the "key" for the cache.
. * If "key" is nil, then a new texture will be created each time.
* The callback will be called from the main thread, so it is safe to * @since v0.8
create any cocos2d object from the callback. */
* Supported image extensions: .png, .jpg // todo: CGImageRef CCTexture2D* addCGImage(CGImageRef image, string &
* @since v0.8 key);
*/ /** Returns a Texture2D object given an UIImage image
* If the image was not previously loaded, it will create a new CCTextur
void addImageAsync(const char *path, CCObject *target, SEL_CallFuncO e2D object and it will return it.
selector); * Otherwise it will return a reference of a previously loaded image
* The "key" parameter will be used as the "key" for the cache.
/* Returns a Texture2D object given an CGImageRef image * If "key" is nil, then a new texture will be created each time.
* If the image was not previously loaded, it will create a new CCTex */
ture2D object and it will return it. CCTexture2D* addUIImage(CCImage *image, const char *key);
* Otherwise it will return a reference of a previously loaded image
* The "key" parameter will be used as the "key" for the cache. /** Returns an already created texture. Returns nil if the texture does
* If "key" is nil, then a new texture will be created each time. n't exist.
* @since v0.8 @since v0.99.5
*/ */
// @todo CGImageRef CCTexture2D* addCGImage(CGImageRef image, string CCTexture2D* textureForKey(const char* key);
& key); /** Purges the dictionary of loaded textures.
/** Returns a Texture2D object given an UIImage image * Call this method if you receive the "Memory Warning"
* If the image was not previously loaded, it will create a new CCTex * In the short term: it will free some resources preventing your app fr
ture2D object and it will return it. om being killed
* Otherwise it will return a reference of a previously loaded image * In the medium term: it will allocate more resources
* The "key" parameter will be used as the "key" for the cache. * In the long term: it will be the same
* If "key" is nil, then a new texture will be created each time. */
*/ void removeAllTextures();
CCTexture2D* addUIImage(CCImage *image, const char *key);
/** Removes unused textures
/** Returns an already created texture. Returns nil if the texture d * Textures that have a retain count of 1 will be deleted
oesn't exist. * It is convinient to call this method after when starting a new Scene
@since v0.99.5 * @since v0.8
*/ */
CCTexture2D* textureForKey(const char* key); void removeUnusedTextures();
/** Purges the dictionary of loaded textures.
* Call this method if you receive the "Memory Warning" /** Deletes a texture from the cache given a texture
* In the short term: it will free some resources preventing your app */
from being killed void removeTexture(CCTexture2D* texture);
* In the medium term: it will allocate more resources
* In the long term: it will be the same /** Deletes a texture from the cache given a its key name
*/ @since v0.99.4
void removeAllTextures(); */
void removeTextureForKey(const char *textureKeyName);
/** Removes unused textures
* Textures that have a retain count of 1 will be deleted /** Output to CCLOG the current contents of this CCTextureCache
* It is convinient to call this method after when starting a new Sce * This will attempt to calculate the size of each texture, and the tota
ne l texture memory in use
* @since v0.8 *
*/ * @since v1.0
void removeUnusedTextures(); */
void dumpCachedTextureInfo();
/** Deletes a texture from the cache given a texture
*/
void removeTexture(CCTexture2D* texture);
/** Deletes a texture from the cache given a its key name
@since v0.99.4
*/
void removeTextureForKey(const char *textureKeyName);
/** Output to CCLOG the current contents of this CCTextureCache
* This will attempt to calculate the size of each texture, and the t
otal texture memory in use
*
* @since v1.0
*/
void dumpCachedTextureInfo();
#ifdef CC_SUPPORT_PVRTC #ifdef CC_SUPPORT_PVRTC
/** Returns a Texture2D object given an PVRTC RAW filename /** Returns a Texture2D object given an PVRTC RAW filename
* If the file image was not previously loaded, it will create a new * If the file image was not previously loaded, it will create a new CCT
CCTexture2D exture2D
* object and it will return it. Otherwise it will return a referenc * object and it will return it. Otherwise it will return a reference o
e of a previosly loaded image f a previosly loaded image
* *
* It can only load square images: width == height, and it must be a * It can only load square images: width == height, and it must be a pow
power of 2 (128,256,512...) er of 2 (128,256,512...)
* bpp can only be 2 or 4. 2 means more compression but lower quality * bpp can only be 2 or 4. 2 means more compression but lower quality.
. * hasAlpha: whether or not the image contains alpha channel
* hasAlpha: whether or not the image contains alpha channel */
*/ CCTexture2D* addPVRTCImage(const char* fileimage, int bpp, bool hasAlph
CCTexture2D* addPVRTCImage(const char* fileimage, int bpp, bool hasA a, int width);
lpha, int width);
#endif // CC_SUPPORT_PVRTC #endif // CC_SUPPORT_PVRTC
/** Returns a Texture2D object given an PVR filename /** Returns a Texture2D object given an PVR filename
* If the file image was not previously loaded, it will create a new * If the file image was not previously loaded, it will create a new CCT
CCTexture2D exture2D
* object and it will return it. Otherwise it will return a referenc * object and it will return it. Otherwise it will return a reference o
e of a previosly loaded image f a previosly loaded image
*/ */
CCTexture2D* addPVRImage(const char* filename); CCTexture2D* addPVRImage(const char* filename);
/** Reload all textures /** Reload all textures
It's only useful when the value of CC_ENABLE_CACHE_TEXTTURE_DATA is 1 It's only useful when the value of CC_ENABLE_CACHE_TEXTURE_DATA is 1
*/ */
static void reloadAllTextures(); static void reloadAllTextures();
}; };
#if CC_ENABLE_CACHE_TEXTTURE_DATA #if CC_ENABLE_CACHE_TEXTURE_DATA
class VolatileTexture class VolatileTexture
{ {
typedef enum { typedef enum {
kInvalid = 0, kInvalid = 0,
kImageFile, kImageFile,
kImageData, kImageData,
kString, kString,
kImage,
}ccCachedImageType; }ccCachedImageType;
public: public:
VolatileTexture(CCTexture2D *t); VolatileTexture(CCTexture2D *t);
~VolatileTexture(); ~VolatileTexture();
static void addImageTexture(CCTexture2D *tt, const char* imageFileName, CCImage::EImageFormat format); static void addImageTexture(CCTexture2D *tt, const char* imageFileName, CCImage::EImageFormat format);
static void addStringTexture(CCTexture2D *tt, const char* text, const C static void addStringTexture(CCTexture2D *tt, const char* text, const C
CSize& dimensions, CCTextAlignment alignment, const char *fontName, float f CSize& dimensions, CCTextAlignment alignment,
ontSize); CCVerticalTextAlignment vAlignment, const
static void addDataTexture(CCTexture2D *tt, void* data, CCTexture2DP char *fontName, float fontSize);
ixelFormat pixelFormat, const CCSize& contentSize); static void addDataTexture(CCTexture2D *tt, void* data, CCTexture2DPixe
lFormat pixelFormat, const CCSize& contentSize);
static void addCCImage(CCTexture2D *tt, CCImage *image);
static void removeTexture(CCTexture2D *t); static void removeTexture(CCTexture2D *t);
static void reloadAllTextures(); static void reloadAllTextures();
public: public:
static std::list<VolatileTexture*> textures; static std::list<VolatileTexture*> textures;
static bool isReloading; static bool isReloading;
private:
// find VolatileTexture by CCTexture2D*
// if not found, create a new one
static VolatileTexture* findVolotileTexture(CCTexture2D *tt);
protected: protected:
CCTexture2D *texture; CCTexture2D *texture;
ccCachedImageType m_eCashedImageType; CCImage *uiImage;
ccCachedImageType m_eCashedImageType;
void *m_pTextureData; void *m_pTextureData;
CCSize m_TextureSize; CCSize m_TextureSize;
CCTexture2DPixelFormat m_PixelFormat; CCTexture2DPixelFormat m_PixelFormat;
std::string m_strFileName; std::string m_strFileName;
CCImage::EImageFormat m_FmtImage; CCImage::EImageFormat m_FmtImage;
CCSize m_size; CCSize m_size;
CCTextAlignment m_alignment; CCTextAlignment m_alignment;
CCVerticalTextAlignment m_vAlignment;
std::string m_strFontName; std::string m_strFontName;
std::string m_strText; std::string m_strText;
float m_fFontSize; float m_fFontSize;
}; };
#endif #endif
}//namespace cocos2d // end of textures group
/// @}
NS_CC_END
#endif //__CCTEXTURE_CACHE_H__ #endif //__CCTEXTURE_CACHE_H__
 End of changes. 22 change blocks. 
138 lines changed or deleted 157 lines changed or added


 CCTexturePVR.h   CCTexturePVR.h 
skipping to change at line 30 skipping to change at line 30
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CCPVRTEXTURE_H__ #ifndef __CCPVRTEXTURE_H__
#define __CCPVRTEXTURE_H__ #define __CCPVRTEXTURE_H__
#include "CCStdC.h" #include "CCStdC.h"
#include "CCGL.h" #include "CCGL.h"
#include "CCObject.h" #include "cocoa/CCObject.h"
#include "CCMutableArray.h" #include "cocoa/CCArray.h"
namespace cocos2d { NS_CC_BEGIN
//Forward definition for CCData /**
class CCData; * @addtogroup textures
* @{
*/
/** /**
@brief Structure which can tell where mimap begins and how long is it @brief Structure which can tell where mimap begins and how long is it
*/ */
struct CCPVRMipmap { struct CCPVRMipmap {
unsigned char *address; unsigned char *address;
unsigned int len; unsigned int len;
}; };
/** /**
@brief Detemine how many mipmaps can we have. @brief Detemine how many mipmaps can we have.
Its same as define but it respects namespaces Its same as define but it respects namespaces
*/ */
enum { enum {
CC_PVRMIPMAP_MAX = 16, CC_PVRMIPMAP_MAX = 16,
}; };
/** CCTexturePVR /** CCTexturePVR
Object that loads PVR images. Object that loads PVR images.
Supported PVR formats: Supported PVR formats:
- RGBA8888 - RGBA8888
- BGRA8888 - BGRA8888
- RGBA4444 - RGBA4444
skipping to change at line 81 skipping to change at line 82
Limitations: Limitations:
Pre-generated mipmaps, such as PVR textures with mipmap levels embedded in file, Pre-generated mipmaps, such as PVR textures with mipmap levels embedded in file,
are only supported if all individual sprites are of _square_ size. are only supported if all individual sprites are of _square_ size.
To use mipmaps with non-square textures, instead call CCTexture2D#gener ateMipmap on the sheet texture itself To use mipmaps with non-square textures, instead call CCTexture2D#gener ateMipmap on the sheet texture itself
(and to save space, save the PVR sprite sheet without mip maps included ). (and to save space, save the PVR sprite sheet without mip maps included ).
*/ */
class CCTexturePVR : public CCObject class CCTexturePVR : public CCObject
{ {
public: public:
CCTexturePVR();
virtual ~CCTexturePVR();
CCTexturePVR(); /** initializes a CCTexturePVR with a path */
virtual ~CCTexturePVR(); bool initWithContentsOfFile(const char* path);
/** initializes a CCTexturePVR with a path */
bool initWithContentsOfFile(const char* path);
/** creates and initializes a CCTexturePVR with a path */ /** creates and initializes a CCTexturePVR with a path
static CCTexturePVR * pvrTextureWithContentsOfFile(const char* path) @deprecated This interface will be deprecated when js-binding is stabl
; e. */
CC_DEPRECATED_ATTRIBUTE static CCTexturePVR* pvrTextureWithContentsOfFi
le(const char* path);
/** creates and initializes a CCTexturePVR with a path */
static CCTexturePVR* create(const char* path);
// properties
inline unsigned int getName() { return m_uName; }
inline unsigned int getWidth() { return m_uWidth; }
inline unsigned int getHeight() { return m_uHeight; }
inline bool hasAlpha() { return m_bHasAlpha; }
inline unsigned int getNumberOfMipmaps() { return m_uNumberOfMipmaps; }
inline CCTexture2DPixelFormat getFormat() { return m_eFormat; }
inline bool isRetainName() { return m_bRetainName; }
inline void setRetainName(bool retainName) { m_bRetainName = retainName
; }
CC_PROPERTY_READONLY(GLuint, m_uName, Name) private:
CC_PROPERTY_READONLY(unsigned int, m_uWidth, Width) bool unpackPVRData(unsigned char* data, unsigned int len);
CC_PROPERTY_READONLY(unsigned int, m_uHeight, Height) bool createGLTexture();
CC_PROPERTY_READONLY(CCTexture2DPixelFormat, m_eFormat, Format)
CC_PROPERTY_READONLY(bool, m_bHasAlpha, HasAlpha)
// cocos2d integration
CC_PROPERTY(bool, m_bRetainName, RetainName);
protected: protected:
struct CCPVRMipmap m_asMipmaps[CC_PVRMIPMAP_MAX]; // pointer to mipma
p images
unsigned int m_uNumberOfMipmaps; // number of mipmap
used
/* unsigned int m_uTableFormatIndex;
Unpacks data (data of pvr texture file) and determine unsigned int m_uWidth, m_uHeight;
how many mipmaps it uses (m_uNumberOfMipmaps). Adresses GLuint m_uName;
of mimaps (m_asMipmaps). And basic data like size, format bool m_bHasAlpha;
and alpha presence
*/ // cocos2d integration
bool unpackPVRData(unsigned char* data, unsigned int len); bool m_bRetainName;
CCTexture2DPixelFormat m_eFormat;
/*
Binds all mipmaps to the GL state machine as separate
textures
*/
bool createGLTexture();
/*
Index to the tableFormats array. Which tells us what exact
format is file which initializes this object.
*/
unsigned int m_uTableFormatIndex;
/*
How many mipmaps do we have. It must be at least one
when proper initialization finishes
*/
unsigned int m_uNumberOfMipmaps;
/*
Makrs for mipmaps. Each entry contains position in file
and lenght of data which represents one mipmap.
*/
struct CCPVRMipmap m_asMipmaps[CC_PVRMIPMAP_MAX];
}; };
}//namespace cocos2d
// end of textures group
/// @}
NS_CC_END
#endif //__CCPVRTEXTURE_H__ #endif //__CCPVRTEXTURE_H__
 End of changes. 13 change blocks. 
57 lines changed or deleted 53 lines changed or added


 CCThread.h   CCThread.h 
skipping to change at line 31 skipping to change at line 31
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CC_PLATFORM_THREAD_H__ #ifndef __CC_PLATFORM_THREAD_H__
#define __CC_PLATFORM_THREAD_H__ #define __CC_PLATFORM_THREAD_H__
#include "CCCommon.h" #include "CCCommon.h"
#include "CCPlatformMacros.h" #include "CCPlatformMacros.h"
NS_CC_BEGIN; NS_CC_BEGIN
/**
* @addtogroup platform
* @{
*/
/* On iOS, should create autorelease pool when create a new thread /* On iOS, should create autorelease pool when create a new thread
* and release it when the thread end. * and release it when the thread end.
*/ */
class CC_DLL CCThread class CC_DLL CCThread
{ {
public: public:
CCThread() : m_pAutoreasePool(0) {} CCThread() : m_pAutoreasePool(0) {}
~CCThread(); ~CCThread();
void createAutoreleasePool(); void createAutoreleasePool();
private: private:
void *m_pAutoreasePool; void *m_pAutoreasePool;
}; };
NS_CC_END; // end of platform group
/// @}
NS_CC_END
#endif // __CC_PLATFORM_THREAD_H__ #endif // __CC_PLATFORM_THREAD_H__
 End of changes. 6 change blocks. 
6 lines changed or deleted 14 lines changed or added


 CCTileMapAtlas.h   CCTileMapAtlas.h 
skipping to change at line 28 skipping to change at line 28
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CCTILE_MAP_ATLAS__ #ifndef __CCTILE_MAP_ATLAS__
#define __CCTILE_MAP_ATLAS__ #define __CCTILE_MAP_ATLAS__
#include <string>
#include <map>
#include "CCAtlasNode.h"
namespace cocos2d {
typedef std::map<std::string, int> StringToIntegerDictionary;
typedef std::pair<std::string, int> StringToIntegerPair;
struct sImageTGA;
/** @brief CCTileMapAtlas is a subclass of CCAtlasNode.
It knows how to render a map based of tiles.
The tiles must be in a .PNG format while the map must be a .TGA file
.
For more information regarding the format, please see this post:
http://www.cocos2d-iphone.org/archives/27
All features from CCAtlasNode are valid in CCTileMapAtlas
IMPORTANT:
This class is deprecated. It is maintained for compatibility reasons
only.
You SHOULD not use this class.
Instead, use the newer TMX file format: CCTMXTiledMap
*/
class CC_DLL CCTileMapAtlas : public CCAtlasNode
{
/** TileMap info */
CC_PROPERTY(struct sImageTGA*, m_pTGAInfo, TGAInfo);
public:
CCTileMapAtlas();
virtual ~CCTileMapAtlas();
/** creates a CCTileMap with a tile file (atlas) with a map
file and the width and height of each tile in points.
The tile file will be loaded using the TextureMgr.
*/
static CCTileMapAtlas * tileMapAtlasWithTileFile(const char
*tile, const char *mapFile, int tileWidth, int tileHeight);
/** initializes a CCTileMap with a tile file (atlas) with a
map file and the width and height of each tile in points.
The file will be loaded using the TextureMgr.
*/
bool initWithTileFile(const char *tile, const char *mapFile,
int tileWidth, int tileHeight);
/** returns a tile from position x,y.
For the moment only channel R is used
*/
ccColor3B tileAt(const ccGridSize& position);
/** sets a tile at position x,y.
For the moment only channel R is used
*/
void setTile(const ccColor3B& tile, const ccGridSize& positi
on);
/** dealloc the map from memory */
void releaseMap();
private:
void loadTGAfile(const char *file);
void calculateItemsToRender();
void updateAtlasValueAt(const ccGridSize& pos, const ccColor
3B& value, unsigned int index);
void updateAtlasValues();
protected:
//! x,y to altas dicctionary
StringToIntegerDictionary *m_pPosToAtlasIndex;
//! numbers of tiles to render
int m_nItemsToRender;
};
}// namespace cocos2d #include "base_nodes/CCAtlasNode.h"
NS_CC_BEGIN
struct sImageTGA;
class CCDictionary;
/**
* @addtogroup tilemap_parallax_nodes
* @{
*/
/** @brief CCTileMapAtlas is a subclass of CCAtlasNode.
It knows how to render a map based of tiles.
The tiles must be in a .PNG format while the map must be a .TGA file.
For more information regarding the format, please see this post:
http://www.cocos2d-iphone.org/archives/27
All features from CCAtlasNode are valid in CCTileMapAtlas
IMPORTANT:
This class is deprecated. It is maintained for compatibility reasons only.
You SHOULD not use this class.
Instead, use the newer TMX file format: CCTMXTiledMap
*/
class CC_DLL CCTileMapAtlas : public CCAtlasNode
{
/** TileMap info */
CC_PROPERTY(struct sImageTGA*, m_pTGAInfo, TGAInfo);
public:
CCTileMapAtlas();
virtual ~CCTileMapAtlas();
/** creates a CCTileMap with a tile file (atlas) with a map file and th
e width and height of each tile in points.
The tile file will be loaded using the TextureMgr.
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCTileMapAtlas * tileMapAtlasWithTileFil
e(const char *tile, const char *mapFile, int tileWidth, int tileHeight);
/** creates a CCTileMap with a tile file (atlas) with a map file and th
e width and height of each tile in points.
The tile file will be loaded using the TextureMgr.
*/
static CCTileMapAtlas * create(const char *tile, const char *mapFile, i
nt tileWidth, int tileHeight);
/** initializes a CCTileMap with a tile file (atlas) with a map file an
d the width and height of each tile in points.
The file will be loaded using the TextureMgr.
*/
bool initWithTileFile(const char *tile, const char *mapFile, int tileWi
dth, int tileHeight);
/** returns a tile from position x,y.
For the moment only channel R is used
*/
ccColor3B tileAt(const ccGridSize& position);
/** sets a tile at position x,y.
For the moment only channel R is used
*/
void setTile(const ccColor3B& tile, const ccGridSize& position);
/** dealloc the map from memory */
void releaseMap();
private:
void loadTGAfile(const char *file);
void calculateItemsToRender();
void updateAtlasValueAt(const ccGridSize& pos, const ccColor3B& value,
unsigned int index);
void updateAtlasValues();
protected:
//! x,y to altas dicctionary
CCDictionary* m_pPosToAtlasIndex;
//! numbers of tiles to render
int m_nItemsToRender;
};
// end of tilemap_parallax_nodes group
/// @}
NS_CC_END
#endif //__CCTILE_MAP_ATLAS__ #endif //__CCTILE_MAP_ATLAS__
 End of changes. 2 change blocks. 
69 lines changed or deleted 84 lines changed or added


 CCTouch.h   CCTouch.h 
skipping to change at line 28 skipping to change at line 28
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CC_TOUCH_H__ #ifndef __CC_TOUCH_H__
#define __CC_TOUCH_H__ #define __CC_TOUCH_H__
#include "CCObject.h" #include "cocoa/CCObject.h"
#include "CCGeometry.h" #include "cocoa/CCGeometry.h"
namespace cocos2d { NS_CC_BEGIN
class CCTouch : public CCObject /**
* @addtogroup input
* @{
*/
class CC_DLL CCTouch : public CCObject
{ {
public: public:
CCTouch() {} CCTouch()
CCTouch(int nViewId, float x, float y) : m_nViewId(nViewId), m_point(x, : m_nId(0)
y), m_prevPoint(x, y) {} {}
CCPoint locationInView(int nViewId) {CC_UNUSED_PARAM(nViewId); return m /** returns the current touch location in OpenGL coordinates */
_point; } CCPoint getLocation() const;
CCPoint previousLocationInView(int nViewId) {CC_UNUSED_PARAM(nViewId); /** returns the previous touch location in OpenGL coordinates */
return m_prevPoint; } CCPoint getPreviousLocation() const;
int view() { return m_nViewId; } /** returns the current touch location in screen coordinates */
int id(){ return m_iID; } CCPoint getDelta() const;
/** returns the current touch location in screen coordinates */
CCPoint getLocationInView() const;
/** returns the previous touch location in screen coordinates */
CCPoint getPreviousLocationInView() const;
/** returns the current touch location in screen coordinates
@deprecated: use CCTouch::getLocationInView() instead.
CCTouch::getLocation() is recommended, it will return OpenGL coordinat
e.
*/
CC_DEPRECATED_ATTRIBUTE CCPoint locationInView() { return m_point; }
/** returns the current previous location in screen coordinates
@deprecated: use CCTouch::getPreviousLocationInView() instead.
CCTouch::getPreviousLocation() is recommended, it will return OpenGL c
oordinate.
*/
CC_DEPRECATED_ATTRIBUTE CCPoint previousLocationInView() { return m_pre
vPoint; }
void SetTouchInfo(int nViewId, float x, float y, int iID=0) void setTouchInfo(int id, float x, float y)
{ {
m_nViewId = nViewId; m_nId = id;
m_prevPoint = m_point; m_prevPoint = m_point;
m_point.x = x; m_point.x = x;
m_point.y = y; m_point.y = y;
m_iID = iID; }
int getID() const
{
return m_nId;
} }
private: private:
int m_nViewId; int m_nId;
CCPoint m_point; CCPoint m_point;
CCPoint m_prevPoint; CCPoint m_prevPoint;
int m_iID;
}; };
class CCEvent : public CCObject class CC_DLL CCEvent : public CCObject
{ {
}; };
} // end of namespace cocos2d // end of input group
/// @}
NS_CC_END
#endif // __PLATFORM_TOUCH_H__ #endif // __PLATFORM_TOUCH_H__
 End of changes. 11 change blocks. 
22 lines changed or deleted 52 lines changed or added


 CCTouchDelegateProtocol.h   CCTouchDelegateProtocol.h 
skipping to change at line 29 skipping to change at line 29
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __TOUCH_DISPATHCHER_CCTOUCH_DELEGATE_PROTOCOL_H__ #ifndef __TOUCH_DISPATHCHER_CCTOUCH_DELEGATE_PROTOCOL_H__
#define __TOUCH_DISPATHCHER_CCTOUCH_DELEGATE_PROTOCOL_H__ #define __TOUCH_DISPATHCHER_CCTOUCH_DELEGATE_PROTOCOL_H__
#include "CCObject.h" #include "cocoa/CCObject.h"
#include "ccConfig.h" #include "ccConfig.h"
namespace cocos2d { NS_CC_BEGIN
class CCTouch; class CCTouch;
class CCEvent; class CCEvent;
class CCSet; class CCSet;
class CCTouchDispatcher; class CCTouchDispatcher;
/**
* @addtogroup input
* @{
*/
class CC_DLL CCTouchDelegate class CC_DLL CCTouchDelegate
{ {
public: public:
CCTouchDelegate() {} CCTouchDelegate() {}
virtual ~CCTouchDelegate() virtual ~CCTouchDelegate()
{ {
} }
virtual bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent) {CC_UNUS virtual bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent) {CC_UNUSED_
ED_PARAM(pTouch); CC_UNUSED_PARAM(pEvent); return false;}; PARAM(pTouch); CC_UNUSED_PARAM(pEvent); return false;};
// optional // optional
virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent) {CC_UNUS virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent) {CC_UNUSED_
ED_PARAM(pTouch); CC_UNUSED_PARAM(pEvent);} PARAM(pTouch); CC_UNUSED_PARAM(pEvent);}
virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent) {CC_UNUS virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent) {CC_UNUSED_
ED_PARAM(pTouch); CC_UNUSED_PARAM(pEvent);} PARAM(pTouch); CC_UNUSED_PARAM(pEvent);}
virtual void ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent) {CC_ virtual void ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent) {CC_UNU
UNUSED_PARAM(pTouch); CC_UNUSED_PARAM(pEvent);} SED_PARAM(pTouch); CC_UNUSED_PARAM(pEvent);}
// optional // optional
virtual void ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent) {CC_UN virtual void ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent) {CC_UNUS
USED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);} ED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);}
virtual void ccTouchesMoved(CCSet *pTouches, CCEvent *pEvent) {CC_UN virtual void ccTouchesMoved(CCSet *pTouches, CCEvent *pEvent) {CC_UNUS
USED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);} ED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);}
virtual void ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent) {CC_UN virtual void ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent) {CC_UNUS
USED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);} ED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);}
virtual void ccTouchesCancelled(CCSet *pTouches, CCEvent *pEvent) {C virtual void ccTouchesCancelled(CCSet *pTouches, CCEvent *pEvent) {CC_
C_UNUSED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);} UNUSED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);}
}; };
/** /**
@brief @brief
Using this type of delegate results in two benefits: Using this type of delegate results in two benefits:
- 1. You don't need to deal with CCSets, the dispatcher does the job of sp litting - 1. You don't need to deal with CCSets, the dispatcher does the job of sp litting
them. You get exactly one UITouch per call. them. You get exactly one UITouch per call.
- 2. You can *claim* a UITouch by returning YES in ccTouchBegan. Updates o f claimed - 2. You can *claim* a UITouch by returning YES in ccTouchBegan. Updates o f claimed
touches are sent only to the delegate(s) that claimed them. So if you get a move/ touches are sent only to the delegate(s) that claimed them. So if you get a move/
ended/cancelled update you're sure it's your touch. This frees you from do ing a ended/cancelled update you're sure it's your touch. This frees you from do ing a
lot of checks when doing multi-touch. lot of checks when doing multi-touch.
(The name TargetedTouchDelegate relates to updates "targeting" their speci fic (The name TargetedTouchDelegate relates to updates "targeting" their speci fic
handler, without bothering the other handlers.) handler, without bothering the other handlers.)
@since v0.8 @since v0.8
*/ */
class CC_DLL CCTargetedTouchDelegate : public CCTouchDelegate class CC_DLL CCTargetedTouchDelegate : public CCTouchDelegate
{ {
public: public:
/** Return YES to claim the touch. /** Return YES to claim the touch.
@since v0 @since v0
*/ */
virtual bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent) { CC_UNU virtual bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent) { CC_UNUSE
SED_PARAM(pTouch); CC_UNUSED_PARAM(pEvent);return false;}; D_PARAM(pTouch); CC_UNUSED_PARAM(pEvent);return false;};
// optional // optional
virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent) {CC_UNUS virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent) {CC_UNUSED
ED_PARAM(pTouch); CC_UNUSED_PARAM(pEvent);} _PARAM(pTouch); CC_UNUSED_PARAM(pEvent);}
virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent) {CC_UNUS virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent) {CC_UNUSED
ED_PARAM(pTouch); CC_UNUSED_PARAM(pEvent);} _PARAM(pTouch); CC_UNUSED_PARAM(pEvent);}
virtual void ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent) {CC_ virtual void ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent) {CC_UN
UNUSED_PARAM(pTouch); CC_UNUSED_PARAM(pEvent);} USED_PARAM(pTouch); CC_UNUSED_PARAM(pEvent);}
}; };
/** @brief /** @brief
This type of delegate is the same one used by CocoaTouch. You will receive all the events (Began,Moved,Ended,Cancelled). This type of delegate is the same one used by CocoaTouch. You will receive all the events (Began,Moved,Ended,Cancelled).
@since v0.8 @since v0.8
*/ */
class CC_DLL CCStandardTouchDelegate : public CCTouchDelegate class CC_DLL CCStandardTouchDelegate : public CCTouchDelegate
{ {
public: public:
// optional // optional
virtual void ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent) {CC_UN virtual void ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent) {CC_UNUS
USED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);} ED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);}
virtual void ccTouchesMoved(CCSet *pTouches, CCEvent *pEvent) {CC_UN virtual void ccTouchesMoved(CCSet *pTouches, CCEvent *pEvent) {CC_UNUS
USED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);} ED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);}
virtual void ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent) {CC_UN virtual void ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent) {CC_UNUS
USED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);} ED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);}
virtual void ccTouchesCancelled(CCSet *pTouches, CCEvent *pEvent) {CC_U NUSED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);} virtual void ccTouchesCancelled(CCSet *pTouches, CCEvent *pEvent) {CC_U NUSED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);}
}; };
}//namespace cocos2d // end of input group
/// @}
NS_CC_END
#endif // __TOUCH_DISPATHCHER_CCTOUCH_DELEGATE_PROTOCOL_H__ #endif // __TOUCH_DISPATHCHER_CCTOUCH_DELEGATE_PROTOCOL_H__
 End of changes. 8 change blocks. 
48 lines changed or deleted 56 lines changed or added


 CCTouchDispatcher.h   CCTouchDispatcher.h 
skipping to change at line 30 skipping to change at line 30
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __TOUCH_DISPATCHER_CCTOUCH_DISPATCHER_H__ #ifndef __TOUCH_DISPATCHER_CCTOUCH_DISPATCHER_H__
#define __TOUCH_DISPATCHER_CCTOUCH_DISPATCHER_H__ #define __TOUCH_DISPATCHER_CCTOUCH_DISPATCHER_H__
#include "CCTouchDelegateProtocol.h" #include "CCTouchDelegateProtocol.h"
#include "CCObject.h" #include "cocoa/CCObject.h"
#include "CCMutableArray.h" #include "cocoa/CCArray.h"
namespace cocos2d {
NS_CC_BEGIN
/**
* @addtogroup input
* @{
*/
typedef enum typedef enum
{ {
ccTouchSelectorBeganBit = 1 << 0, ccTouchSelectorBeganBit = 1 << 0,
ccTouchSelectorMovedBit = 1 << 1, ccTouchSelectorMovedBit = 1 << 1,
ccTouchSelectorEndedBit = 1 << 2, ccTouchSelectorEndedBit = 1 << 2,
ccTouchSelectorCancelledBit = 1 << 3, ccTouchSelectorCancelledBit = 1 << 3,
ccTouchSelectorAllBits = ( ccTouchSelectorBeganBit | ccTouchSelector ccTouchSelectorAllBits = ( ccTouchSelectorBeganBit | ccTouchSelectorMov
MovedBit | ccTouchSelectorEndedBit | ccTouchSelectorCancelledBit), edBit | ccTouchSelectorEndedBit | ccTouchSelectorCancelledBit),
} ccTouchSelectorFlag; } ccTouchSelectorFlag;
enum { enum {
CCTOUCHBEGAN, CCTOUCHBEGAN,
CCTOUCHMOVED, CCTOUCHMOVED,
CCTOUCHENDED, CCTOUCHENDED,
CCTOUCHCANCELLED, CCTOUCHCANCELLED,
ccTouchMax, ccTouchMax,
}; };
class CCSet; class CCSet;
class CCEvent; class CCEvent;
struct ccTouchHandlerHelperData { struct ccTouchHandlerHelperData {
// we only use the type // we only use the type
// void (StandardTouchDelegate::*touchesSel)(CCSet*, CCEvent*); // void (StandardTouchDelegate::*touchesSel)(CCSet*, CCEvent*);
// void (TargetedTouchDelegate::*touchSel)(NSTouch*, CCEvent*); // void (TargetedTouchDelegate::*touchSel)(NSTouch*, CCEvent*);
int m_type; int m_type;
}; };
class CC_DLL EGLTouchDelegate class CC_DLL EGLTouchDelegate
{ {
public: public:
virtual void touchesBegan(CCSet* touches, CCEvent* pEvent) = 0; virtual void touchesBegan(CCSet* touches, CCEvent* pEvent) = 0;
virtual void touchesMoved(CCSet* touches, CCEvent* pEvent) = 0; virtual void touchesMoved(CCSet* touches, CCEvent* pEvent) = 0;
virtual void touchesEnded(CCSet* touches, CCEvent* pEvent) = 0; virtual void touchesEnded(CCSet* touches, CCEvent* pEvent) = 0;
virtual void touchesCancelled(CCSet* touches, CCEvent* pEvent) = 0; virtual void touchesCancelled(CCSet* touches, CCEvent* pEvent) = 0;
virtual ~EGLTouchDelegate() {} virtual ~EGLTouchDelegate() {}
}; };
class CCTouchHandler; class CCTouchHandler;
struct _ccCArray; struct _ccCArray;
/** @brief CCTouchDispatcher. /** @brief CCTouchDispatcher.
Singleton that handles all the touch events. Singleton that handles all the touch events.
The dispatcher dispatches events to the registered TouchHandlers. The dispatcher dispatches events to the registered TouchHandlers.
There are 2 different type of touch handlers: There are 2 different type of touch handlers:
skipping to change at line 94 skipping to change at line 100
Firstly, the dispatcher sends the received touches to the targeted touches . Firstly, the dispatcher sends the received touches to the targeted touches .
These touches can be swallowed by the Targeted Touch Handlers. If there ar e still remaining touches, then the remaining touches will be sent These touches can be swallowed by the Targeted Touch Handlers. If there ar e still remaining touches, then the remaining touches will be sent
to the Standard Touch Handlers. to the Standard Touch Handlers.
@since v0.8.0 @since v0.8.0
*/ */
class CC_DLL CCTouchDispatcher : public CCObject, public EGLTouchDelegate class CC_DLL CCTouchDispatcher : public CCObject, public EGLTouchDelegate
{ {
public: public:
~CCTouchDispatcher(); ~CCTouchDispatcher();
bool init(void); bool init(void);
CCTouchDispatcher() CCTouchDispatcher()
: m_pTargetedHandlers(NULL) : m_pTargetedHandlers(NULL)
, m_pStandardHandlers(NULL) , m_pStandardHandlers(NULL)
, m_pHandlersToAdd(NULL) , m_pHandlersToAdd(NULL)
, m_pHandlersToRemove(NULL) , m_pHandlersToRemove(NULL)
{} {}
public: public:
/** Whether or not the events are going to be dispatched. Default: t rue */ /** Whether or not the events are going to be dispatched. Default: true */
bool isDispatchEvents(void); bool isDispatchEvents(void);
void setDispatchEvents(bool bDispatchEvents); void setDispatchEvents(bool bDispatchEvents);
/** Adds a standard touch delegate to the dispatcher's list. /** Adds a standard touch delegate to the dispatcher's list.
See StandardTouchDelegate description. See StandardTouchDelegate description.
IMPORTANT: The delegate will be retained. IMPORTANT: The delegate will be retained.
*/ */
void addStandardDelegate(CCTouchDelegate *pDelegate, int nPriority); void addStandardDelegate(CCTouchDelegate *pDelegate, int nPriority);
/** Adds a targeted touch delegate to the dispatcher's list. /** Adds a targeted touch delegate to the dispatcher's list.
See TargetedTouchDelegate description. See TargetedTouchDelegate description.
IMPORTANT: The delegate will be retained. IMPORTANT: The delegate will be retained.
*/ */
void addTargetedDelegate(CCTouchDelegate *pDelegate, int nPriority, void addTargetedDelegate(CCTouchDelegate *pDelegate, int nPriority, boo
bool bSwallowsTouches); l bSwallowsTouches);
/** Removes a touch delegate. /** Removes a touch delegate.
The delegate will be released The delegate will be released
*/ */
void removeDelegate(CCTouchDelegate *pDelegate); void removeDelegate(CCTouchDelegate *pDelegate);
/** Removes all touch delegates, releasing all the delegates */ /** Removes all touch delegates, releasing all the delegates */
void removeAllDelegates(void); void removeAllDelegates(void);
/** Changes the priority of a previously added delegate. The lower t he number, /** Changes the priority of a previously added delegate. The lower the number,
the higher the priority */ the higher the priority */
void setPriority(int nPriority, CCTouchDelegate *pDelegate); void setPriority(int nPriority, CCTouchDelegate *pDelegate);
void touches(CCSet *pTouches, CCEvent *pEvent, unsigned int uIndex); void touches(CCSet *pTouches, CCEvent *pEvent, unsigned int uIndex);
virtual void touchesBegan(CCSet* touches, CCEvent* pEvent); virtual void touchesBegan(CCSet* touches, CCEvent* pEvent);
virtual void touchesMoved(CCSet* touches, CCEvent* pEvent); virtual void touchesMoved(CCSet* touches, CCEvent* pEvent);
virtual void touchesEnded(CCSet* touches, CCEvent* pEvent); virtual void touchesEnded(CCSet* touches, CCEvent* pEvent);
virtual void touchesCancelled(CCSet* touches, CCEvent* pEvent); virtual void touchesCancelled(CCSet* touches, CCEvent* pEvent);
public: public:
/** singleton of the CCTouchDispatcher */ CCTouchHandler* findHandler(CCTouchDelegate *pDelegate);
static CCTouchDispatcher* sharedDispatcher();
CCTouchHandler* findHandler(CCTouchDelegate *pDelegate);
protected: protected:
void forceRemoveDelegate(CCTouchDelegate *pDelegate); void forceRemoveDelegate(CCTouchDelegate *pDelegate);
void forceAddHandler(CCTouchHandler *pHandler, CCMutableArray<CCTouc void forceAddHandler(CCTouchHandler *pHandler, CCArray* pArray);
hHandler*> *pArray); void forceRemoveAllDelegates(void);
void forceRemoveAllDelegates(void); void rearrangeHandlers(CCArray* pArray);
void rearrangeHandlers(CCMutableArray<CCTouchHandler*> *pArray); CCTouchHandler* findHandler(CCArray* pArray, CCTouchDelegate *pDelegate
CCTouchHandler* findHandler(CCMutableArray<CCTouchHandler*> *pArray, );
CCTouchDelegate *pDelegate);
protected: protected:
CCMutableArray<CCTouchHandler*> *m_pTargetedHandlers; CCArray* m_pTargetedHandlers;
CCMutableArray<CCTouchHandler*> *m_pStandardHandlers; CCArray* m_pStandardHandlers;
bool m_bLocked; bool m_bLocked;
bool m_bToAdd; bool m_bToAdd;
bool m_bToRemove; bool m_bToRemove;
CCMutableArray<CCTouchHandler*> *m_pHandlersToAdd; CCArray* m_pHandlersToAdd;
struct _ccCArray *m_pHandlersToRemove; struct _ccCArray *m_pHandlersToRemove;
bool m_bToQuit; bool m_bToQuit;
bool m_bDispatchEvents; bool m_bDispatchEvents;
// 4, 1 for each type of event // 4, 1 for each type of event
struct ccTouchHandlerHelperData m_sHandlerHelperData[ccTouchMax]; struct ccTouchHandlerHelperData m_sHandlerHelperData[ccTouchMax];
}; };
}//namespace cocos2d
// end of input group
/// @}
NS_CC_END
#endif // __TOUCH_DISPATCHER_CCTOUCH_DISPATCHER_H__ #endif // __TOUCH_DISPATCHER_CCTOUCH_DISPATCHER_H__
 End of changes. 23 change blocks. 
79 lines changed or deleted 85 lines changed or added


 CCTouchHandler.h   CCTouchHandler.h 
skipping to change at line 31 skipping to change at line 31
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __TOUCH_DISPATCHER_CCTOUCH_HANDLER_H__ #ifndef __TOUCH_DISPATCHER_CCTOUCH_HANDLER_H__
#define __TOUCH_DISPATCHER_CCTOUCH_HANDLER_H__ #define __TOUCH_DISPATCHER_CCTOUCH_HANDLER_H__
#include "CCTouchDelegateProtocol.h" #include "CCTouchDelegateProtocol.h"
#include "CCTouchDispatcher.h" #include "CCTouchDispatcher.h"
#include "CCObject.h" #include "cocoa/CCObject.h"
#include "CCSet.h" #include "cocoa/CCSet.h"
namespace cocos2d {
NS_CC_BEGIN
/**
* @addtogroup input
* @{
*/
/** /**
CCTouchHandler CCTouchHandler
Object than contains the delegate and priority of the event handler. Object than contains the delegate and priority of the event handler.
*/ */
class CC_DLL CCTouchHandler : public CCObject class CC_DLL CCTouchHandler : public CCObject
{ {
public: public:
virtual ~CCTouchHandler(void); virtual ~CCTouchHandler(void);
/** delegate */ /** delegate */
CCTouchDelegate* getDelegate(); CCTouchDelegate* getDelegate();
void setDelegate(CCTouchDelegate *pDelegate); void setDelegate(CCTouchDelegate *pDelegate);
/** priority */ /** priority */
int getPriority(void); int getPriority(void);
void setPriority(int nPriority); void setPriority(int nPriority);
/** enabled selectors */ /** enabled selectors */
int getEnabledSelectors(void); int getEnabledSelectors(void);
void setEnalbedSelectors(int nValue); void setEnalbedSelectors(int nValue);
/** initializes a TouchHandler with a delegate and a priority */ /** initializes a TouchHandler with a delegate and a priority */
virtual bool initWithDelegate(CCTouchDelegate *pDelegate, int nPrior virtual bool initWithDelegate(CCTouchDelegate *pDelegate, int nPriority
ity); );
public: public:
/** allocates a TouchHandler with a delegate and a priority */ /** allocates a TouchHandler with a delegate and a priority */
static CCTouchHandler* handlerWithDelegate(CCTouchDelegate *pDelegat static CCTouchHandler* handlerWithDelegate(CCTouchDelegate *pDelegate,
e, int nPriority); int nPriority);
protected: protected:
CCTouchDelegate *m_pDelegate; CCTouchDelegate *m_pDelegate;
int m_nPriority; int m_nPriority;
int m_nEnabledSelectors; int m_nEnabledSelectors;
}; };
/** CCStandardTouchHandler /** CCStandardTouchHandler
It forwardes each event to the delegate. It forwardes each event to the delegate.
*/ */
class CC_DLL CCStandardTouchHandler : public CCTouchHandler class CC_DLL CCStandardTouchHandler : public CCTouchHandler
{ {
public: public:
/** initializes a TouchHandler with a delegate and a priority */ /** initializes a TouchHandler with a delegate and a priority */
virtual bool initWithDelegate(CCTouchDelegate *pDelegate, int nPrior virtual bool initWithDelegate(CCTouchDelegate *pDelegate, int nPriority
ity); );
public: public:
/** allocates a TouchHandler with a delegate and a priority */ /** allocates a TouchHandler with a delegate and a priority */
static CCStandardTouchHandler* handlerWithDelegate(CCTouchDelegate * static CCStandardTouchHandler* handlerWithDelegate(CCTouchDelegate *pDe
pDelegate, int nPriority); legate, int nPriority);
}; };
/** /**
CCTargetedTouchHandler CCTargetedTouchHandler
Object than contains the claimed touches and if it swallos touches. Object than contains the claimed touches and if it swallos touches.
Used internally by TouchDispatcher Used internally by TouchDispatcher
*/ */
class CC_DLL CCTargetedTouchHandler : public CCTouchHandler class CC_DLL CCTargetedTouchHandler : public CCTouchHandler
{ {
public: public:
~CCTargetedTouchHandler(void); ~CCTargetedTouchHandler(void);
/** whether or not the touches are swallowed */ /** whether or not the touches are swallowed */
bool isSwallowsTouches(void); bool isSwallowsTouches(void);
void setSwallowsTouches(bool bSwallowsTouches); void setSwallowsTouches(bool bSwallowsTouches);
/** MutableSet that contains the claimed touches */ /** MutableSet that contains the claimed touches */
CCSet* getClaimedTouches(void); CCSet* getClaimedTouches(void);
/** initializes a TargetedTouchHandler with a delegate, a priority a /** initializes a TargetedTouchHandler with a delegate, a priority and
nd whether or not it swallows touches or not */ whether or not it swallows touches or not */
bool initWithDelegate(CCTouchDelegate *pDelegate, int nPriority, boo bool initWithDelegate(CCTouchDelegate *pDelegate, int nPriority, bool b
l bSwallow); Swallow);
public: public:
/** allocates a TargetedTouchHandler with a delegate, a priority and /** allocates a TargetedTouchHandler with a delegate, a priority and wh
whether or not it swallows touches or not */ ether or not it swallows touches or not */
static CCTargetedTouchHandler* handlerWithDelegate(CCTouchDelegate * static CCTargetedTouchHandler* handlerWithDelegate(CCTouchDelegate *pDe
pDelegate, int nPriority, bool bSwallow); legate, int nPriority, bool bSwallow);
protected: protected:
bool m_bSwallowsTouches; bool m_bSwallowsTouches;
CCSet *m_pClaimedTouches; CCSet *m_pClaimedTouches;
}; };
}//namespace cocos2d
// end of input group
/// @}
NS_CC_END
#endif // __TOUCH_DISPATCHER_CCTOUCH_HANDLER_H__ #endif // __TOUCH_DISPATCHER_CCTOUCH_HANDLER_H__
 End of changes. 16 change blocks. 
43 lines changed or deleted 53 lines changed or added


 CCTransition.h   CCTransition.h 
skipping to change at line 31 skipping to change at line 31
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CCTRANSITION_H__ #ifndef __CCTRANSITION_H__
#define __CCTRANSITION_H__ #define __CCTRANSITION_H__
#include "CCScene.h" #include "CCScene.h"
namespace cocos2d { #include "ccTypes.h"
NS_CC_BEGIN
/**
* @addtogroup transition
* @{
*/
//static creation function macro //static creation function macro
//c/c++ don't support object creation of using class name //c/c++ don't support object creation of using class name
//so, all classes need creation method. //so, all classes need creation method.
#define DECLEAR_TRANSITIONWITHDURATION(_Type)\
static _Type* transitionWithDuration(ccTime t, CCScene* scene); #define OLD_TRANSITION_CREATE_FUNC(_Type) \
CC_DEPRECATED_ATTRIBUTE static _Type* transitionWithDuration(float t, C
CScene* scene) \
{ \
_Type* pScene = new _Type(); \
if(pScene && pScene->initWithDuration(t, scene)) \
{ \
pScene->autorelease(); \
return pScene; \
} \
CC_SAFE_DELETE(pScene); \
return NULL; \
}
#define TRANSITION_CREATE_FUNC(_Type) \
static _Type* create(float t, CCScene* scene) \
{ \
_Type* pScene = new _Type(); \
if(pScene && pScene->initWithDuration(t, scene)) \
{ \
pScene->autorelease(); \
return pScene; \
} \
CC_SAFE_DELETE(pScene); \
return NULL; \
}
class CCActionInterval; class CCActionInterval;
class CCNode; class CCNode;
/** @brief CCTransitionEaseScene can ease the actions of the scene protocol . /** @brief CCTransitionEaseScene can ease the actions of the scene protocol .
@since v0.8.2 @since v0.8.2
*/ */
class CC_DLL CCTransitionEaseScene// : public CCObject class CC_DLL CCTransitionEaseScene// : public CCObject
{ {
public: public:
/** returns the Ease action that will be performed on a linear actio /** returns the Ease action that will be performed on a linear action.
n. @since v0.8.2
@since v0.8.2 */
*/ virtual CCActionInterval * easeActionWithAction(CCActionInterval * acti
virtual CCActionInterval * easeActionWithAction(CCActionInterval * a on) = 0;
ction) = 0;
}; };
/** Orientation Type used by some transitions /** Orientation Type used by some transitions
*/ */
typedef enum { typedef enum {
/// An horizontal orientation where the Left is nearer /// An horizontal orientation where the Left is nearer
kOrientationLeftOver = 0, kOrientationLeftOver = 0,
/// An horizontal orientation where the Right is nearer /// An horizontal orientation where the Right is nearer
kOrientationRightOver = 1, kOrientationRightOver = 1,
/// A vertical orientation where the Up is nearer /// A vertical orientation where the Up is nearer
kOrientationUpOver = 0, kOrientationUpOver = 0,
/// A vertical orientation where the Bottom is nearer /// A vertical orientation where the Bottom is nearer
kOrientationDownOver = 1, kOrientationDownOver = 1,
} tOrientation; } tOrientation;
/** @brief Base class for CCTransition scenes /** @brief Base class for CCTransition scenes
*/ */
class CC_DLL CCTransitionScene : public CCScene class CC_DLL CCTransitionScene : public CCScene
{ {
protected: protected:
CCScene * m_pInScene; CCScene * m_pInScene;
CCScene * m_pOutScene; CCScene * m_pOutScene;
ccTime m_fDuration; float m_fDuration;
bool m_bIsInSceneOnTop; bool m_bIsInSceneOnTop;
bool m_bIsSendCleanupToScene; bool m_bIsSendCleanupToScene;
public: public:
CCTransitionScene(); CCTransitionScene();
virtual ~CCTransitionScene(); virtual ~CCTransitionScene();
virtual void draw(); virtual void draw();
virtual void onEnter(); virtual void onEnter();
virtual void onExit(); virtual void onExit();
virtual void cleanup(); virtual void cleanup();
/** creates a base transition with duration and incoming scene
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCTransitionScene * transitionWithDurati
on(float t, CCScene *scene);
/** creates a base transition with duration and incoming scene */ /** creates a base transition with duration and incoming scene */
static CCTransitionScene * transitionWithDuration(ccTime t, CCScene static CCTransitionScene * create(float t, CCScene *scene);
*scene);
/** initializes a transition with duration and incoming scene */ /** initializes a transition with duration and incoming scene */
virtual bool initWithDuration(ccTime t,CCScene* scene); virtual bool initWithDuration(float t,CCScene* scene);
/** called after the transition finishes */ /** called after the transition finishes */
void finish(void); void finish(void);
/** used by some transitions to hide the outter scene */ /** used by some transitions to hide the outter scene */
void hideOutShowIn(void); void hideOutShowIn(void);
protected: protected:
virtual void sceneOrder(); virtual void sceneOrder();
private: private:
void setNewScene(ccTime dt); void setNewScene(float dt);
}; };
/** @brief A CCTransition that supports orientation like. /** @brief A CCTransition that supports orientation like.
* Possible orientation: LeftOver, RightOver, UpOver, DownOver * Possible orientation: LeftOver, RightOver, UpOver, DownOver
*/ */
class CC_DLL CCTransitionSceneOriented : public CCTransitionScene class CC_DLL CCTransitionSceneOriented : public CCTransitionScene
{ {
protected: protected:
tOrientation m_eOrientation; tOrientation m_eOrientation;
public: public:
CCTransitionSceneOriented(); CCTransitionSceneOriented();
virtual ~CCTransitionSceneOriented(); virtual ~CCTransitionSceneOriented();
/** creates a base transition with duration and incoming scene
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCTransitionSceneOriented * transitionWi
thDuration(float t,CCScene* scene, tOrientation orientation);
/** creates a base transition with duration and incoming scene */ /** creates a base transition with duration and incoming scene */
static CCTransitionSceneOriented * transitionWithDuration(ccTime t,C static CCTransitionSceneOriented * create(float t,CCScene* scene, tOrie
CScene* scene, tOrientation orientation); ntation orientation);
/** initializes a transition with duration and incoming scene */
virtual bool initWithDuration(ccTime t,CCScene* scene,tOrientation o /** initializes a transition with duration and incoming scene */
rientation); virtual bool initWithDuration(float t,CCScene* scene,tOrientation orien
tation);
}; };
/** @brief CCTransitionRotoZoom: /** @brief CCTransitionRotoZoom:
Rotate and zoom out the outgoing scene, and then rotate and zoom in the inc oming Rotate and zoom out the outgoing scene, and then rotate and zoom in the inc oming
*/ */
class CC_DLL CCTransitionRotoZoom : public CCTransitionScene class CC_DLL CCTransitionRotoZoom : public CCTransitionScene
{ {
public: public:
CCTransitionRotoZoom(); CCTransitionRotoZoom();
virtual ~CCTransitionRotoZoom(); virtual ~CCTransitionRotoZoom();
virtual void onEnter(); virtual void onEnter();
DECLEAR_TRANSITIONWITHDURATION(CCTransitionRotoZoom); TRANSITION_CREATE_FUNC(CCTransitionRotoZoom);
OLD_TRANSITION_CREATE_FUNC(CCTransitionRotoZoom);
}; };
/** @brief CCTransitionJumpZoom: /** @brief CCTransitionJumpZoom:
Zoom out and jump the outgoing scene, and then jump and zoom in the incomin g Zoom out and jump the outgoing scene, and then jump and zoom in the incomin g
*/ */
class CC_DLL CCTransitionJumpZoom : public CCTransitionScene class CC_DLL CCTransitionJumpZoom : public CCTransitionScene
{ {
public: public:
CCTransitionJumpZoom(); CCTransitionJumpZoom();
virtual ~CCTransitionJumpZoom(); virtual ~CCTransitionJumpZoom();
virtual void onEnter(); virtual void onEnter();
DECLEAR_TRANSITIONWITHDURATION(CCTransitionJumpZoom); TRANSITION_CREATE_FUNC(CCTransitionJumpZoom);
OLD_TRANSITION_CREATE_FUNC(CCTransitionJumpZoom);
}; };
/** @brief CCTransitionMoveInL: /** @brief CCTransitionMoveInL:
Move in from to the left the incoming scene. Move in from to the left the incoming scene.
*/ */
class CC_DLL CCTransitionMoveInL : public CCTransitionScene, public CCTrans itionEaseScene class CC_DLL CCTransitionMoveInL : public CCTransitionScene, public CCTrans itionEaseScene
{ {
public: public:
CCTransitionMoveInL(); CCTransitionMoveInL();
virtual ~CCTransitionMoveInL(); virtual ~CCTransitionMoveInL();
/** initializes the scenes */ /** initializes the scenes */
virtual void initScenes(void); virtual void initScenes(void);
/** returns the action that will be performed */ /** returns the action that will be performed */
virtual CCActionInterval* action(void); virtual CCActionInterval* action(void);
virtual CCActionInterval* easeActionWithAction(CCActionInterval * ac tion); virtual CCActionInterval* easeActionWithAction(CCActionInterval * actio n);
virtual void onEnter(); virtual void onEnter();
DECLEAR_TRANSITIONWITHDURATION(CCTransitionMoveInL); TRANSITION_CREATE_FUNC(CCTransitionMoveInL);
OLD_TRANSITION_CREATE_FUNC(CCTransitionMoveInL);
}; };
/** @brief CCTransitionMoveInR: /** @brief CCTransitionMoveInR:
Move in from to the right the incoming scene. Move in from to the right the incoming scene.
*/ */
class CC_DLL CCTransitionMoveInR : public CCTransitionMoveInL class CC_DLL CCTransitionMoveInR : public CCTransitionMoveInL
{ {
public: public:
CCTransitionMoveInR(); CCTransitionMoveInR();
virtual ~CCTransitionMoveInR(); virtual ~CCTransitionMoveInR();
virtual void initScenes(); virtual void initScenes();
DECLEAR_TRANSITIONWITHDURATION(CCTransitionMoveInR); TRANSITION_CREATE_FUNC(CCTransitionMoveInR);
OLD_TRANSITION_CREATE_FUNC(CCTransitionMoveInR);
}; };
/** @brief CCTransitionMoveInT: /** @brief CCTransitionMoveInT:
Move in from to the top the incoming scene. Move in from to the top the incoming scene.
*/ */
class CC_DLL CCTransitionMoveInT : public CCTransitionMoveInL class CC_DLL CCTransitionMoveInT : public CCTransitionMoveInL
{ {
public: public:
CCTransitionMoveInT(); CCTransitionMoveInT();
virtual ~CCTransitionMoveInT(); virtual ~CCTransitionMoveInT();
virtual void initScenes(); virtual void initScenes();
DECLEAR_TRANSITIONWITHDURATION(CCTransitionMoveInT); TRANSITION_CREATE_FUNC(CCTransitionMoveInT);
OLD_TRANSITION_CREATE_FUNC(CCTransitionMoveInT);
}; };
/** @brief CCTransitionMoveInB: /** @brief CCTransitionMoveInB:
Move in from to the bottom the incoming scene. Move in from to the bottom the incoming scene.
*/ */
class CC_DLL CCTransitionMoveInB : public CCTransitionMoveInL class CC_DLL CCTransitionMoveInB : public CCTransitionMoveInL
{ {
public: public:
CCTransitionMoveInB(); CCTransitionMoveInB();
virtual ~CCTransitionMoveInB(); virtual ~CCTransitionMoveInB();
virtual void initScenes(); virtual void initScenes();
DECLEAR_TRANSITIONWITHDURATION(CCTransitionMoveInB); TRANSITION_CREATE_FUNC(CCTransitionMoveInB);
OLD_TRANSITION_CREATE_FUNC(CCTransitionMoveInB);
}; };
/** @brief CCTransitionSlideInL: /** @brief CCTransitionSlideInL:
Slide in the incoming scene from the left border. Slide in the incoming scene from the left border.
*/ */
class CC_DLL CCTransitionSlideInL : public CCTransitionScene, public CCTran sitionEaseScene class CC_DLL CCTransitionSlideInL : public CCTransitionScene, public CCTran sitionEaseScene
{ {
public: public:
CCTransitionSlideInL(); CCTransitionSlideInL();
virtual ~CCTransitionSlideInL(); virtual ~CCTransitionSlideInL();
/** initializes the scenes */ /** initializes the scenes */
virtual void initScenes(void); virtual void initScenes(void);
/** returns the action that will be performed by the incomming and o /** returns the action that will be performed by the incomming and outg
utgoing scene */ oing scene */
virtual CCActionInterval* action(void); virtual CCActionInterval* action(void);
virtual void onEnter(); virtual void onEnter();
virtual CCActionInterval* easeActionWithAction(CCActionInterval * ac tion); virtual CCActionInterval* easeActionWithAction(CCActionInterval * actio n);
DECLEAR_TRANSITIONWITHDURATION(CCTransitionSlideInL); TRANSITION_CREATE_FUNC(CCTransitionSlideInL);
OLD_TRANSITION_CREATE_FUNC(CCTransitionSlideInL);
protected: protected:
virtual void sceneOrder(); virtual void sceneOrder();
}; };
/** @brief CCTransitionSlideInR: /** @brief CCTransitionSlideInR:
Slide in the incoming scene from the right border. Slide in the incoming scene from the right border.
*/ */
class CC_DLL CCTransitionSlideInR : public CCTransitionSlideInL class CC_DLL CCTransitionSlideInR : public CCTransitionSlideInL
{ {
public: public:
CCTransitionSlideInR(); CCTransitionSlideInR();
virtual ~CCTransitionSlideInR(); virtual ~CCTransitionSlideInR();
/** initializes the scenes */ /** initializes the scenes */
virtual void initScenes(void); virtual void initScenes(void);
/** returns the action that will be performed by the incomming and o /** returns the action that will be performed by the incomming and outg
utgoing scene */ oing scene */
virtual CCActionInterval* action(void); virtual CCActionInterval* action(void);
DECLEAR_TRANSITIONWITHDURATION(CCTransitionSlideInR); TRANSITION_CREATE_FUNC(CCTransitionSlideInR);
OLD_TRANSITION_CREATE_FUNC(CCTransitionSlideInR);
protected: protected:
virtual void sceneOrder(); virtual void sceneOrder();
}; };
/** @brief CCTransitionSlideInB: /** @brief CCTransitionSlideInB:
Slide in the incoming scene from the bottom border. Slide in the incoming scene from the bottom border.
*/ */
class CC_DLL CCTransitionSlideInB : public CCTransitionSlideInL class CC_DLL CCTransitionSlideInB : public CCTransitionSlideInL
{ {
public: public:
CCTransitionSlideInB(); CCTransitionSlideInB();
virtual ~CCTransitionSlideInB(); virtual ~CCTransitionSlideInB();
/** initializes the scenes */ /** initializes the scenes */
virtual void initScenes(void); virtual void initScenes(void);
/** returns the action that will be performed by the incomming and o /** returns the action that will be performed by the incomming and outg
utgoing scene */ oing scene */
virtual CCActionInterval* action(void); virtual CCActionInterval* action(void);
DECLEAR_TRANSITIONWITHDURATION(CCTransitionSlideInB); TRANSITION_CREATE_FUNC(CCTransitionSlideInB);
OLD_TRANSITION_CREATE_FUNC(CCTransitionSlideInB);
protected: protected:
virtual void sceneOrder(); virtual void sceneOrder();
}; };
/** @brief CCTransitionSlideInT: /** @brief CCTransitionSlideInT:
Slide in the incoming scene from the top border. Slide in the incoming scene from the top border.
*/ */
class CC_DLL CCTransitionSlideInT : public CCTransitionSlideInL class CC_DLL CCTransitionSlideInT : public CCTransitionSlideInL
{ {
public: public:
CCTransitionSlideInT(); CCTransitionSlideInT();
virtual ~CCTransitionSlideInT(); virtual ~CCTransitionSlideInT();
/** initializes the scenes */ /** initializes the scenes */
virtual void initScenes(void); virtual void initScenes(void);
/** returns the action that will be performed by the incomming and o /** returns the action that will be performed by the incomming and outg
utgoing scene */ oing scene */
virtual CCActionInterval* action(void); virtual CCActionInterval* action(void);
DECLEAR_TRANSITIONWITHDURATION(CCTransitionSlideInT); TRANSITION_CREATE_FUNC(CCTransitionSlideInT);
OLD_TRANSITION_CREATE_FUNC(CCTransitionSlideInT);
protected: protected:
virtual void sceneOrder(); virtual void sceneOrder();
}; };
/** /**
@brief Shrink the outgoing scene while grow the incoming scene @brief Shrink the outgoing scene while grow the incoming scene
*/ */
class CC_DLL CCTransitionShrinkGrow : public CCTransitionScene , public CCT ransitionEaseScene class CC_DLL CCTransitionShrinkGrow : public CCTransitionScene , public CCT ransitionEaseScene
{ {
public: public:
CCTransitionShrinkGrow(); CCTransitionShrinkGrow();
virtual ~CCTransitionShrinkGrow(); virtual ~CCTransitionShrinkGrow();
virtual void onEnter(); virtual void onEnter();
virtual CCActionInterval* easeActionWithAction(CCActionInterval * ac virtual CCActionInterval* easeActionWithAction(CCActionInterval * actio
tion); n);
DECLEAR_TRANSITIONWITHDURATION(CCTransitionShrinkGrow); TRANSITION_CREATE_FUNC(CCTransitionShrinkGrow);
OLD_TRANSITION_CREATE_FUNC(CCTransitionShrinkGrow);
}; };
/** @brief CCTransitionFlipX: /** @brief CCTransitionFlipX:
Flips the screen horizontally. Flips the screen horizontally.
The front face is the outgoing scene and the back face is the incoming scen e. The front face is the outgoing scene and the back face is the incoming scen e.
*/ */
class CC_DLL CCTransitionFlipX : public CCTransitionSceneOriented class CC_DLL CCTransitionFlipX : public CCTransitionSceneOriented
{ {
public: public:
CCTransitionFlipX(); CCTransitionFlipX();
virtual ~CCTransitionFlipX(); virtual ~CCTransitionFlipX();
virtual void onEnter(); virtual void onEnter();
static CCTransitionFlipX* transitionWithDuration(ccTime t, CCScene* s, // @deprecated: This interface will be deprecated sooner or later.
tOrientation o = kOrientationRightOver); CC_DEPRECATED_ATTRIBUTE static CCTransitionFlipX* transitionWithDuratio
n(float t, CCScene* s, tOrientation o = kOrientationRightOver);
static CCTransitionFlipX* create(float t, CCScene* s, tOrientation o =
kOrientationRightOver);
}; };
/** @brief CCTransitionFlipY: /** @brief CCTransitionFlipY:
Flips the screen vertically. Flips the screen vertically.
The front face is the outgoing scene and the back face is the incoming scen e. The front face is the outgoing scene and the back face is the incoming scen e.
*/ */
class CC_DLL CCTransitionFlipY : public CCTransitionSceneOriented class CC_DLL CCTransitionFlipY : public CCTransitionSceneOriented
{ {
public: public:
CCTransitionFlipY(); CCTransitionFlipY();
virtual ~CCTransitionFlipY(); virtual ~CCTransitionFlipY();
virtual void onEnter(); virtual void onEnter();
static CCTransitionFlipY* transitionWithDuration(ccTime t, CCScene* s, //@deprecated: This interface will be deprecated sooner or later.
tOrientation o = kOrientationUpOver); CC_DEPRECATED_ATTRIBUTE static CCTransitionFlipY* transitionWithDuratio
n(float t, CCScene* s, tOrientation o = kOrientationUpOver);
static CCTransitionFlipY* create(float t, CCScene* s, tOrientation o =
kOrientationUpOver);
}; };
/** @brief CCTransitionFlipAngular: /** @brief CCTransitionFlipAngular:
Flips the screen half horizontally and half vertically. Flips the screen half horizontally and half vertically.
The front face is the outgoing scene and the back face is the incoming scen e. The front face is the outgoing scene and the back face is the incoming scen e.
*/ */
class CC_DLL CCTransitionFlipAngular : public CCTransitionSceneOriented class CC_DLL CCTransitionFlipAngular : public CCTransitionSceneOriented
{ {
public: public:
CCTransitionFlipAngular(); CCTransitionFlipAngular();
virtual ~CCTransitionFlipAngular(); virtual ~CCTransitionFlipAngular();
virtual void onEnter(); virtual void onEnter();
static CCTransitionFlipAngular* transitionWithDuration(ccTime t, CCScen //@deprecated: This interface will be deprecated sooner or later.
e* s, tOrientation o = kOrientationRightOver); CC_DEPRECATED_ATTRIBUTE static CCTransitionFlipAngular* transitionWithD
uration(float t, CCScene* s, tOrientation o = kOrientationRightOver);
static CCTransitionFlipAngular* create(float t, CCScene* s, tOrientatio
n o = kOrientationRightOver);
}; };
/** @brief CCTransitionZoomFlipX: /** @brief CCTransitionZoomFlipX:
Flips the screen horizontally doing a zoom out/in Flips the screen horizontally doing a zoom out/in
The front face is the outgoing scene and the back face is the incoming scen e. The front face is the outgoing scene and the back face is the incoming scen e.
*/ */
class CC_DLL CCTransitionZoomFlipX : public CCTransitionSceneOriented class CC_DLL CCTransitionZoomFlipX : public CCTransitionSceneOriented
{ {
public: public:
CCTransitionZoomFlipX(); CCTransitionZoomFlipX();
virtual ~CCTransitionZoomFlipX(); virtual ~CCTransitionZoomFlipX();
virtual void onEnter(); virtual void onEnter();
static CCTransitionZoomFlipX* transitionWithDuration(ccTime t, CCScene* //@deprecated: This interface will be deprecated sooner or later.
s, tOrientation o = kOrientationRightOver); CC_DEPRECATED_ATTRIBUTE static CCTransitionZoomFlipX* transitionWithDur
ation(float t, CCScene* s, tOrientation o = kOrientationRightOver);
static CCTransitionZoomFlipX* create(float t, CCScene* s, tOrientation
o = kOrientationRightOver);
}; };
/** @brief CCTransitionZoomFlipY: /** @brief CCTransitionZoomFlipY:
Flips the screen vertically doing a little zooming out/in Flips the screen vertically doing a little zooming out/in
The front face is the outgoing scene and the back face is the incoming scen e. The front face is the outgoing scene and the back face is the incoming scen e.
*/ */
class CC_DLL CCTransitionZoomFlipY : public CCTransitionSceneOriented class CC_DLL CCTransitionZoomFlipY : public CCTransitionSceneOriented
{ {
public: public:
CCTransitionZoomFlipY(); CCTransitionZoomFlipY();
virtual ~CCTransitionZoomFlipY(); virtual ~CCTransitionZoomFlipY();
virtual void onEnter(); virtual void onEnter();
static CCTransitionZoomFlipY* transitionWithDuration(ccTime t, CCScene* //@deprecated: This interface will be deprecated sooner or later.
s, tOrientation o = kOrientationUpOver); CC_DEPRECATED_ATTRIBUTE static CCTransitionZoomFlipY* transitionWithDur
ation(float t, CCScene* s, tOrientation o = kOrientationUpOver);
static CCTransitionZoomFlipY* create(float t, CCScene* s, tOrientation
o = kOrientationUpOver);
}; };
/** @brief CCTransitionZoomFlipAngular: /** @brief CCTransitionZoomFlipAngular:
Flips the screen half horizontally and half vertically doing a little zoomi ng out/in. Flips the screen half horizontally and half vertically doing a little zoomi ng out/in.
The front face is the outgoing scene and the back face is the incoming scen e. The front face is the outgoing scene and the back face is the incoming scen e.
*/ */
class CC_DLL CCTransitionZoomFlipAngular : public CCTransitionSceneOriented class CC_DLL CCTransitionZoomFlipAngular : public CCTransitionSceneOriented
{ {
public: public:
CCTransitionZoomFlipAngular(); CCTransitionZoomFlipAngular();
virtual ~CCTransitionZoomFlipAngular(); virtual ~CCTransitionZoomFlipAngular();
virtual void onEnter(); virtual void onEnter();
static CCTransitionZoomFlipAngular* transitionWithDuration(ccTime t, CC //@deprecated: This interface will be deprecated sooner or later.
Scene* s, tOrientation o = kOrientationRightOver); CC_DEPRECATED_ATTRIBUTE static CCTransitionZoomFlipAngular* transitionW
ithDuration(float t, CCScene* s, tOrientation o = kOrientationRightOver);
static CCTransitionZoomFlipAngular* create(float t, CCScene* s, tOrient
ation o = kOrientationRightOver);
}; };
/** @brief CCTransitionFade: /** @brief CCTransitionFade:
Fade out the outgoing scene and then fade in the incoming scene.''' Fade out the outgoing scene and then fade in the incoming scene.'''
*/ */
class CC_DLL CCTransitionFade : public CCTransitionScene class CC_DLL CCTransitionFade : public CCTransitionScene
{ {
protected: protected:
ccColor4B m_tColor; ccColor4B m_tColor;
public: public:
CCTransitionFade(); CCTransitionFade();
virtual ~CCTransitionFade(); virtual ~CCTransitionFade();
/** creates the transition with a duration and with an RGB color
* Example: FadeTransition::transitionWithDuration(2, scene, ccc3(255,0,
0); // red color
@deprecated: This interface will be deprecated sooner or later.
*/
CC_DEPRECATED_ATTRIBUTE static CCTransitionFade* transitionWithDuration
(float duration,CCScene* scene, const ccColor3B& color = ccBLACK);
/** creates the transition with a duration and with an RGB color
* Example: FadeTransition::create(2, scene, ccc3(255,0,0); // red color
*/
static CCTransitionFade* create(float duration,CCScene* scene, const cc
Color3B& color = ccBLACK);
/** creates the transition with a duration and with an RGB color /** initializes the transition with a duration and with an RGB color */
* Example: FadeTransition::transitionWithDuration(2, scene, ccc3(255 virtual bool initWithDuration(float t, CCScene*scene ,const ccColor3B&
,0,0); // red color color);
*/
static CCTransitionFade* transitionWithDuration(ccTime duration,CCSc
ene* scene, const ccColor3B& color = ccBLACK);
/** initializes the transition with a duration and with an RGB color
*/
virtual bool initWithDuration(ccTime t, CCScene*scene ,const ccColor
3B& color);
virtual bool initWithDuration(ccTime t,CCScene* scene); virtual bool initWithDuration(float t,CCScene* scene);
virtual void onEnter(); virtual void onEnter();
virtual void onExit(); virtual void onExit();
}; };
class CCRenderTexture; class CCRenderTexture;
/** /**
@brief CCTransitionCrossFade: @brief CCTransitionCrossFade:
Cross fades two scenes using the CCRenderTexture object. Cross fades two scenes using the CCRenderTexture object.
*/ */
class CC_DLL CCTransitionCrossFade : public CCTransitionScene class CC_DLL CCTransitionCrossFade : public CCTransitionScene
{ {
public : public :
CCTransitionCrossFade(); CCTransitionCrossFade();
virtual ~CCTransitionCrossFade(); virtual ~CCTransitionCrossFade();
virtual void draw(); virtual void draw();
virtual void onEnter(); virtual void onEnter();
virtual void onExit(); virtual void onExit();
public: public:
DECLEAR_TRANSITIONWITHDURATION(CCTransitionCrossFade); TRANSITION_CREATE_FUNC(CCTransitionCrossFade);
OLD_TRANSITION_CREATE_FUNC(CCTransitionCrossFade);
}; };
/** @brief CCTransitionTurnOffTiles: /** @brief CCTransitionTurnOffTiles:
Turn off the tiles of the outgoing scene in random order Turn off the tiles of the outgoing scene in random order
*/ */
class CC_DLL CCTransitionTurnOffTiles : public CCTransitionScene ,public CC TransitionEaseScene class CC_DLL CCTransitionTurnOffTiles : public CCTransitionScene ,public CC TransitionEaseScene
{ {
public : public :
CCTransitionTurnOffTiles(); CCTransitionTurnOffTiles();
virtual ~CCTransitionTurnOffTiles(); virtual ~CCTransitionTurnOffTiles();
virtual void onEnter(); virtual void onEnter();
virtual CCActionInterval * easeActionWithAction(CCActionInterval * a virtual CCActionInterval * easeActionWithAction(CCActionInterval * acti
ction); on);
public: public:
DECLEAR_TRANSITIONWITHDURATION(CCTransitionTurnOffTiles); TRANSITION_CREATE_FUNC(CCTransitionTurnOffTiles);
OLD_TRANSITION_CREATE_FUNC(CCTransitionTurnOffTiles);
protected: protected:
virtual void sceneOrder(); virtual void sceneOrder();
}; };
/** @brief CCTransitionSplitCols: /** @brief CCTransitionSplitCols:
The odd columns goes upwards while the even columns goes downwards. The odd columns goes upwards while the even columns goes downwards.
*/ */
class CC_DLL CCTransitionSplitCols : public CCTransitionScene , public CCTr ansitionEaseScene class CC_DLL CCTransitionSplitCols : public CCTransitionScene , public CCTr ansitionEaseScene
{ {
public: public:
CCTransitionSplitCols(); CCTransitionSplitCols();
virtual ~CCTransitionSplitCols(); virtual ~CCTransitionSplitCols();
virtual CCActionInterval* action(void); virtual CCActionInterval* action(void);
virtual void onEnter(); virtual void onEnter();
virtual CCActionInterval * easeActionWithAction(CCActionInterval * a virtual CCActionInterval * easeActionWithAction(CCActionInterval * acti
ction); on);
public: public:
DECLEAR_TRANSITIONWITHDURATION(CCTransitionSplitCols); TRANSITION_CREATE_FUNC(CCTransitionSplitCols);
OLD_TRANSITION_CREATE_FUNC(CCTransitionSplitCols);
}; };
/** @brief CCTransitionSplitRows: /** @brief CCTransitionSplitRows:
The odd rows goes to the left while the even rows goes to the right. The odd rows goes to the left while the even rows goes to the right.
*/ */
class CC_DLL CCTransitionSplitRows : public CCTransitionSplitCols class CC_DLL CCTransitionSplitRows : public CCTransitionSplitCols
{ {
public: public:
CCTransitionSplitRows(); CCTransitionSplitRows();
virtual ~CCTransitionSplitRows(); virtual ~CCTransitionSplitRows();
virtual CCActionInterval* action(void); virtual CCActionInterval* action(void);
public: public:
DECLEAR_TRANSITIONWITHDURATION(CCTransitionSplitRows) TRANSITION_CREATE_FUNC(CCTransitionSplitRows)
OLD_TRANSITION_CREATE_FUNC(CCTransitionSplitRows)
}; };
/** @brief CCTransitionFadeTR: /** @brief CCTransitionFadeTR:
Fade the tiles of the outgoing scene from the left-bottom corner the to top -right corner. Fade the tiles of the outgoing scene from the left-bottom corner the to top -right corner.
*/ */
class CC_DLL CCTransitionFadeTR : public CCTransitionScene , public CCTrans itionEaseScene class CC_DLL CCTransitionFadeTR : public CCTransitionScene , public CCTrans itionEaseScene
{ {
public: public:
CCTransitionFadeTR(); CCTransitionFadeTR();
virtual ~CCTransitionFadeTR(); virtual ~CCTransitionFadeTR();
virtual CCActionInterval* actionWithSize(const ccGridSize& size); virtual CCActionInterval* actionWithSize(const ccGridSize& size);
virtual void onEnter(); virtual void onEnter();
virtual CCActionInterval* easeActionWithAction(CCActionInterval * ac virtual CCActionInterval* easeActionWithAction(CCActionInterval * actio
tion); n);
public: public:
DECLEAR_TRANSITIONWITHDURATION(CCTransitionFadeTR) TRANSITION_CREATE_FUNC(CCTransitionFadeTR)
OLD_TRANSITION_CREATE_FUNC(CCTransitionFadeTR)
protected: protected:
virtual void sceneOrder(); virtual void sceneOrder();
}; };
/** @brief CCTransitionFadeBL: /** @brief CCTransitionFadeBL:
Fade the tiles of the outgoing scene from the top-right corner to the botto m-left corner. Fade the tiles of the outgoing scene from the top-right corner to the botto m-left corner.
*/ */
class CC_DLL CCTransitionFadeBL : public CCTransitionFadeTR class CC_DLL CCTransitionFadeBL : public CCTransitionFadeTR
{ {
public: public:
CCTransitionFadeBL(); CCTransitionFadeBL();
virtual ~CCTransitionFadeBL(); virtual ~CCTransitionFadeBL();
virtual CCActionInterval* actionWithSize(const ccGridSize& size); virtual CCActionInterval* actionWithSize(const ccGridSize& size);
public: public:
DECLEAR_TRANSITIONWITHDURATION(CCTransitionFadeBL) TRANSITION_CREATE_FUNC(CCTransitionFadeBL)
OLD_TRANSITION_CREATE_FUNC(CCTransitionFadeBL)
}; };
/** @brief CCTransitionFadeUp: /** @brief CCTransitionFadeUp:
* Fade the tiles of the outgoing scene from the bottom to the top. * Fade the tiles of the outgoing scene from the bottom to the top.
*/ */
class CC_DLL CCTransitionFadeUp : public CCTransitionFadeTR class CC_DLL CCTransitionFadeUp : public CCTransitionFadeTR
{ {
public: public:
CCTransitionFadeUp(); CCTransitionFadeUp();
virtual ~CCTransitionFadeUp(); virtual ~CCTransitionFadeUp();
virtual CCActionInterval* actionWithSize(const ccGridSize& size); virtual CCActionInterval* actionWithSize(const ccGridSize& size);
public: public:
DECLEAR_TRANSITIONWITHDURATION(CCTransitionFadeUp) TRANSITION_CREATE_FUNC(CCTransitionFadeUp)
OLD_TRANSITION_CREATE_FUNC(CCTransitionFadeUp)
}; };
/** @brief CCTransitionFadeDown: /** @brief CCTransitionFadeDown:
* Fade the tiles of the outgoing scene from the top to the bottom. * Fade the tiles of the outgoing scene from the top to the bottom.
*/ */
class CC_DLL CCTransitionFadeDown : public CCTransitionFadeTR class CC_DLL CCTransitionFadeDown : public CCTransitionFadeTR
{ {
public: public:
CCTransitionFadeDown(); CCTransitionFadeDown();
virtual ~CCTransitionFadeDown(); virtual ~CCTransitionFadeDown();
virtual CCActionInterval* actionWithSize(const ccGridSize& size); virtual CCActionInterval* actionWithSize(const ccGridSize& size);
public: public:
DECLEAR_TRANSITIONWITHDURATION(CCTransitionFadeDown) TRANSITION_CREATE_FUNC(CCTransitionFadeDown)
OLD_TRANSITION_CREATE_FUNC(CCTransitionFadeDown)
}; };
}//namespace cocos2d
// end of transition group
/// @}
NS_CC_END
#endif // __CCTRANSITION_H__ #endif // __CCTRANSITION_H__
 End of changes. 95 change blocks. 
212 lines changed or deleted 303 lines changed or added


 CCTransitionPageTurn.h   CCTransitionPageTurn.h 
skipping to change at line 30 skipping to change at line 30
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CCPAGE_TURN_TRANSITION_H__ #ifndef __CCPAGE_TURN_TRANSITION_H__
#define __CCPAGE_TURN_TRANSITION_H__ #define __CCPAGE_TURN_TRANSITION_H__
#include "CCTransition.h" #include "CCTransition.h"
namespace cocos2d {
NS_CC_BEGIN
/**
* @addtogroup transition
* @{
*/
/** /**
@brief A transition which peels back the bottom right hand corner of a scen e @brief A transition which peels back the bottom right hand corner of a scen e
to transition to the scene beneath it simulating a page turn. to transition to the scene beneath it simulating a page turn.
This uses a 3DAction so it's strongly recommended that depth buffering This uses a 3DAction so it's strongly recommended that depth buffering
is turned on in CCDirector using: is turned on in CCDirector using:
CCDirector::sharedDirector()->setDepthBufferFormat(kDepthBuffer16); CCDirector::sharedDirector()->setDepthBufferFormat(kDepthBuffer16);
@since v0.8.2 @since v0.8.2
*/ */
class CC_DLL CCTransitionPageTurn : public CCTransitionScene class CC_DLL CCTransitionPageTurn : public CCTransitionScene
{ {
protected: protected:
bool m_bBack; bool m_bBack;
public: public:
CCTransitionPageTurn(); CCTransitionPageTurn();
virtual ~CCTransitionPageTurn(); virtual ~CCTransitionPageTurn();
/** /**
* Creates a base transition with duration and incoming scene. * Creates a base transition with duration and incoming scene.
* If back is true then the effect is reversed to appear as if the in * If back is true then the effect is reversed to appear as if the incom
coming ing
* scene is being turned from left over the outgoing scene. * scene is being turned from left over the outgoing scene.
*/ @deprecated: This interface will be deprecated sooner or later.
static CCTransitionPageTurn* transitionWithDuration(ccTime t,CCScene */
* scene,bool backwards); CC_DEPRECATED_ATTRIBUTE static CCTransitionPageTurn* transitionWithDura
tion(float t,CCScene* scene,bool backwards);
/**
* Creates a base transition with duration and incoming scene. /**
* If back is true then the effect is reversed to appear as if the in * Creates a base transition with duration and incoming scene.
coming * If back is true then the effect is reversed to appear as if the incom
* scene is being turned from left over the outgoing scene. ing
*/ * scene is being turned from left over the outgoing scene.
virtual bool initWithDuration(ccTime t,CCScene* scene,bool backwards */
); static CCTransitionPageTurn* create(float t,CCScene* scene,bool backwar
ds);
/**
* Creates a base transition with duration and incoming scene.
* If back is true then the effect is reversed to appear as if the incom
ing
* scene is being turned from left over the outgoing scene.
*/
virtual bool initWithDuration(float t,CCScene* scene,bool backwards);
CCActionInterval* actionWithSize(const ccGridSize& vector); CCActionInterval* actionWithSize(const ccGridSize& vector);
virtual void onEnter(); virtual void onEnter();
protected: protected:
virtual void sceneOrder(); virtual void sceneOrder();
}; };
}//namespace cocos2d
// end of transition group
/// @}
NS_CC_END
#endif // __CCPAGE_TURN_TRANSITION_H__ #endif // __CCPAGE_TURN_TRANSITION_H__
 End of changes. 8 change blocks. 
25 lines changed or deleted 44 lines changed or added


 CCUserDefault.h   CCUserDefault.h 
skipping to change at line 27 skipping to change at line 27
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __SUPPORT_CCUSERDEFAULT_H__ #ifndef __SUPPORT_CCUSERDEFAULT_H__
#define __SUPPORT_CCUSERDEFAULT_H__ #define __SUPPORT_CCUSERDEFAULT_H__
#include "CCPlatformMacros.h" #include "platform/CCPlatformMacros.h"
#include <string> #include <string>
NS_CC_BEGIN; NS_CC_BEGIN
/**
* @addtogroup data_storage
* @{
*/
/** /**
* CCUserDefault acts as a tiny database. You can save and get base type va lues by it. * CCUserDefault acts as a tiny database. You can save and get base type va lues by it.
* For example, setBoolForKey("played", true) will add a bool value true in to the database. * For example, setBoolForKey("played", true) will add a bool value true in to the database.
* Its key is "played". You can get the value of the key by getBoolForKey(" played"). * Its key is "played". You can get the value of the key by getBoolForKey(" played").
* *
* It supports the following base types: * It supports the following base types:
* bool, int, float, double, string * bool, int, float, double, string
*/ */
class CC_DLL CCUserDefault class CC_DLL CCUserDefault
{ {
public: public:
~CCUserDefault(); ~CCUserDefault();
// get value methods // get value methods
/** /**
@brief Get bool value by key, if the key doesn't exist, a default va @brief Get bool value by key, if the key doesn't exist, a default value
lue will return. will return.
You can set the default value, or it is false. You can set the default value, or it is false.
*/ */
bool getBoolForKey(const char* pKey, bool defaultValue = false); bool getBoolForKey(const char* pKey, bool defaultValue = false);
/** /**
@brief Get integer value by key, if the key doesn't exist, a default @brief Get integer value by key, if the key doesn't exist, a default va
value will return. lue will return.
You can set the default value, or it is 0. You can set the default value, or it is 0.
*/ */
int getIntegerForKey(const char* pKey, int defaultValue int getIntegerForKey(const char* pKey, int defaultValue = 0);
= 0); /**
/** @brief Get float value by key, if the key doesn't exist, a default valu
@brief Get float value by key, if the key doesn't exist, a default v e will return.
alue will return. You can set the default value, or it is 0.0f.
You can set the default value, or it is 0.0f. */
*/ float getFloatForKey(const char* pKey, float defaultValue=0.0f);
float getFloatForKey(const char* pKey, float defaultValue=0.0f); /**
/** @brief Get double value by key, if the key doesn't exist, a default val
@brief Get double value by key, if the key doesn't exist, a default ue will return.
value will return. You can set the default value, or it is 0.0.
You can set the default value, or it is 0.0. */
*/ double getDoubleForKey(const char* pKey, double defaultValue=0.0);
double getDoubleForKey(const char* pKey, double defaultValue=0.0); /**
/** @brief Get string value by key, if the key doesn't exist, a default val
@brief Get string value by key, if the key doesn't exist, a default ue will return.
value will return. You can set the default value, or it is "".
You can set the default value, or it is "". */
*/ std::string getStringForKey(const char* pKey, const std::string & defau
std::string getStringForKey(const char* pKey, const std::string & de ltValue = "");
faultValue = "");
// set value methods
// set value methods
/**
/** @brief Set bool value by key.
@brief Set bool value by key. */
*/ void setBoolForKey(const char* pKey, bool value);
void setBoolForKey(const char* pKey, bool value); /**
/** @brief Set integer value by key.
@brief Set integer value by key. */
*/ void setIntegerForKey(const char* pKey, int value);
void setIntegerForKey(const char* pKey, int value); /**
/** @brief Set float value by key.
@brief Set float value by key. */
*/ void setFloatForKey(const char* pKey, float value);
void setFloatForKey(const char* pKey, float value); /**
/** @brief Set double value by key.
@brief Set double value by key. */
*/ void setDoubleForKey(const char* pKey, double value);
void setDoubleForKey(const char* pKey, double value); /**
/** @brief Set string value by key.
@brief Set string value by key. */
*/ void setStringForKey(const char* pKey, const std::string & value);
void setStringForKey(const char* pKey, const std::string & value) /**
; @brief Save content to xml file
/** */
@brief Save content to xml file void flush();
*/
void flush(); static CCUserDefault* sharedUserDefault();
static void purgeSharedUserDefault();
static CCUserDefault* sharedUserDefault(); const static std::string& getXMLFilePath();
static void purgeSharedUserDefault();
const static std::string& getXMLFilePath();
private: private:
CCUserDefault(); CCUserDefault();
static bool createXMLFile(); static bool createXMLFile();
static bool isXMLFileExist(); static bool isXMLFileExist();
static void initXMLFilePath(); static void initXMLFilePath();
static CCUserDefault* m_spUserDefault; static CCUserDefault* m_spUserDefault;
static std::string m_sFilePath; static std::string m_sFilePath;
static bool m_sbIsFilePathInitialized; static bool m_sbIsFilePathInitialized;
}; };
NS_CC_END; // end of data_storage group
/// @}
NS_CC_END
#endif // __SUPPORT_CCUSERDEFAULT_H__ #endif // __SUPPORT_CCUSERDEFAULT_H__
 End of changes. 7 change blocks. 
78 lines changed or deleted 83 lines changed or added


 CCZone.h   CCZone.h 
skipping to change at line 27 skipping to change at line 27
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CC_ZONE_H__ #ifndef __CC_ZONE_H__
#define __CC_ZONE_H__ #define __CC_ZONE_H__
#include "platform/CCPlatformMacros.h"
#include <stdio.h> #include <stdio.h>
namespace cocos2d { NS_CC_BEGIN
/**
* @addtogroup data_structures
* @{
*/
class CCObject; class CCObject;
class CCZone class CC_DLL CCZone
{ {
public: public:
CCZone(CCObject *pObject = NULL); CCZone(CCObject *pObject = NULL);
public: public:
CCObject *m_pCopyObject; CCObject *m_pCopyObject;
}; };
}//namespace cocos2d
// end of data_structure group
/// @}
NS_CC_END
#endif // __CC_ZONE_H__ #endif // __CC_ZONE_H__
 End of changes. 6 change blocks. 
5 lines changed or deleted 16 lines changed or added


 CDAudioManager.h   CDAudioManager.h 
skipping to change at line 34 skipping to change at line 34
#import "CocosDenshion.h" #import "CocosDenshion.h"
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 30000 #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 30000
#import <AVFoundation/AVFoundation.h> #import <AVFoundation/AVFoundation.h>
#else #else
#import "CDXMacOSXSupport.h" #import "CDXMacOSXSupport.h"
#endif #endif
/** Different modes of the engine */ /** Different modes of the engine */
typedef enum { typedef enum {
kAMM_FxOnly, //!Other apps will b kAMM_FxOnly, //!Other apps will be able to play audi
e able to play audio o
kAMM_FxPlusMusic, //!Only this app wil kAMM_FxPlusMusic, //!Only this app will play audio
l play audio kAMM_FxPlusMusicIfNoOtherAudio, //!If another app is playing audio a
kAMM_FxPlusMusicIfNoOtherAudio, //!If another app is playing audio a t start up then allow it to continue and don't play music
t start up then allow it to continue and don't play music kAMM_MediaPlayback, //!This app takes over audio e.g mus
kAMM_MediaPlayback, //!This app takes ov ic player app
er audio e.g music player app kAMM_PlayAndRecord //!App takes over audio and has input
kAMM_PlayAndRecord //!App takes over au and output
dio and has input and output
} tAudioManagerMode; } tAudioManagerMode;
/** Possible states of the engine */ /** Possible states of the engine */
typedef enum { typedef enum {
kAMStateUninitialised, //!Audio manager has not been initialised - d kAMStateUninitialised, //!Audio manager has not been initialised - do n
o not use ot use
kAMStateInitialising, //!Audio manager is in the process of initial kAMStateInitialising, //!Audio manager is in the process of initialisi
ising - do not use ng - do not use
kAMStateInitialised //!Audio manager is initialised - safe to kAMStateInitialised //!Audio manager is initialised - safe to use
use
} tAudioManagerState; } tAudioManagerState;
typedef enum { typedef enum {
kAMRBDoNothing, //Audio manager will not do anyt kAMRBDoNothing, //Audio manager will not do anything on
hing on resign or becoming active resign or becoming active
kAMRBStopPlay, //Background music is stoppe kAMRBStopPlay, //Background music is stopped on resign a
d on resign and resumed on become active nd resumed on become active
kAMRBStop //Background music i kAMRBStop //Background music is stopped on resign bu
s stopped on resign but not resumed - maybe because you want to do this fro t not resumed - maybe because you want to do this from within your game
m within your game
} tAudioManagerResignBehavior; } tAudioManagerResignBehavior;
/** Notifications */ /** Notifications */
extern NSString * const kCDN_AudioManagerInitialised; extern NSString * const kCDN_AudioManagerInitialised;
@interface CDAsynchInitialiser : NSOperation {} @interface CDAsynchInitialiser : NSOperation {}
@end @end
/** CDAudioManager supports two long audio source channels called left and right*/ /** CDAudioManager supports two long audio source channels called left and right*/
typedef enum { typedef enum {
kASC_Left = 0, kASC_Left = 0,
kASC_Right = 1 kASC_Right = 1
} tAudioSourceChannel; } tAudioSourceChannel;
typedef enum { typedef enum {
kLAS_Init, kLAS_Init,
kLAS_Loaded, kLAS_Loaded,
kLAS_Playing, kLAS_Playing,
kLAS_Paused, kLAS_Paused,
kLAS_Stopped, kLAS_Stopped,
} tLongAudioSourceState; } tLongAudioSourceState;
@class CDLongAudioSource; @class CDLongAudioSource;
@protocol CDLongAudioSourceDelegate <NSObject> @protocol CDLongAudioSourceDelegate <NSObject>
@optional @optional
/** The audio source completed playing */ /** The audio source completed playing */
- (void) cdAudioSourceDidFinishPlaying:(CDLongAudioSource *) audioSource; - (void) cdAudioSourceDidFinishPlaying:(CDLongAudioSource *) audioSource;
/** The file used to load the audio source has changed */ /** The file used to load the audio source has changed */
- (void) cdAudioSourceFileDidChange:(CDLongAudioSource *) audioSource; - (void) cdAudioSourceFileDidChange:(CDLongAudioSource *) audioSource;
@end @end
skipping to change at line 93 skipping to change at line 93
/** /**
CDLongAudioSource represents an audio source that has a long duration whic h makes CDLongAudioSource represents an audio source that has a long duration whic h makes
it costly to load into memory for playback as an effect using CDSoundEngin e. Examples it costly to load into memory for playback as an effect using CDSoundEngin e. Examples
include background music and narration tracks. The audio file may or may n ot be compressed. include background music and narration tracks. The audio file may or may n ot be compressed.
Bear in mind that current iDevices can only use hardware to decode a singl e compressed Bear in mind that current iDevices can only use hardware to decode a singl e compressed
audio file at a time and playing multiple compressed files will result in a performance drop audio file at a time and playing multiple compressed files will result in a performance drop
as software decompression will take place. as software decompression will take place.
@since v0.99 @since v0.99
*/ */
@interface CDLongAudioSource : NSObject <AVAudioPlayerDelegate, CDAudioInte rruptProtocol>{ @interface CDLongAudioSource : NSObject <AVAudioPlayerDelegate, CDAudioInte rruptProtocol>{
AVAudioPlayer *audioSourcePlayer; AVAudioPlayer *audioSourcePlayer;
NSString *audioSourceFilePath; NSString *audioSourceFilePath;
NSInteger numberOfLoops; NSInteger numberOfLoops;
float volume; float volume;
id<CDLongAudioSourceDelegate> delegate; id<CDLongAudioSourceDelegate> delegate;
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
@protected @protected
tLongAudioSourceState state; tLongAudioSourceState state;
} }
@property (readonly) AVAudioPlayer *audioSourcePlayer; @property (readonly) AVAudioPlayer *audioSourcePlayer;
@property (readonly) NSString *audioSourceFilePath; @property (readonly) NSString *audioSourceFilePath;
@property (readwrite, nonatomic) NSInteger numberOfLoops; @property (readwrite, nonatomic) NSInteger numberOfLoops;
@property (readwrite, nonatomic) float volume; @property (readwrite, nonatomic) float volume;
@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;
/** Plays the audio source */ /** Plays the audio source */
-(void) play; -(void) play;
/** Stops playing the audio soruce */ /** Stops playing the audio soruce */
-(void) stop; -(void) stop;
/** Pauses the audio source */ /** Pauses the audio source */
-(void) pause; -(void) pause;
/** Rewinds the audio source */ /** Rewinds the audio source */
skipping to change at line 146 skipping to change at line 149
the audio session to take care of things like audio session interruption a nd interacting with the audio the audio session to take care of things like audio session interruption a nd interacting with the audio
of other apps that are running on the device. of other apps that are running on the device.
Requirements: Requirements:
- Firmware: OS 2.2 or greater - Firmware: OS 2.2 or greater
- Files: CDAudioManager.*, CocosDenshion.* - Files: CDAudioManager.*, CocosDenshion.*
- Frameworks: OpenAL, AudioToolbox, AVFoundation - Frameworks: OpenAL, AudioToolbox, AVFoundation
@since v0.8 @since v0.8
*/ */
@interface CDAudioManager : NSObject <CDLongAudioSourceDelegate, CDAudioInt erruptProtocol, AVAudioSessionDelegate> { @interface CDAudioManager : NSObject <CDLongAudioSourceDelegate, CDAudioInt erruptProtocol, AVAudioSessionDelegate> {
CDSoundEngine *soundEngine; CDSoundEngine *soundEngine;
CDLongAudioSource *backgroundMusic; CDLongAudioSource *backgroundMusic;
NSMutableArray *audioSourceChannels; NSMutableArray *audioSourceChannels;
NSString* _audioSessionCategory; NSString* _audioSessionCategory;
BOOL _audioWasPlayingAtStartup; BOOL _audioWasPlayingAtStartup;
tAudioManagerMode _mode; tAudioManagerMode _mode;
SEL backgroundMusicCompletionSelector; SEL backgroundMusicCompletionSelector;
id backgroundMusicCompletionListener; id backgroundMusicCompletionListener;
BOOL willPlayBackgroundMusic; BOOL willPlayBackgroundMusic;
BOOL _mute; BOOL _mute;
BOOL _resigned; BOOL _resigned;
BOOL _interrupted; BOOL _interrupted;
BOOL _audioSessionActive; BOOL _audioSessionActive;
BOOL enabled_; BOOL enabled_;
//For handling resign/become active //For handling resign/become active
BOOL _isObservingAppEvents; BOOL _isObservingAppEvents;
tAudioManagerResignBehavior _resignBehavior; tAudioManagerResignBehavior _resignBehavior;
} }
@property (readonly) CDSoundEngine *soundEngine; @property (readonly) CDSoundEngine *soundEngine;
@property (readonly) CDLongAudioSource *backgroundMusic; @property (readonly) CDLongAudioSource *backgroundMusic;
@property (readonly) BOOL willPlayBackgroundMusic; @property (readonly) BOOL willPlayBackgroundMusic;
/** Returns the shared singleton */ /** Returns the shared singleton */
+ (CDAudioManager *) sharedManager; + (CDAudioManager *) sharedManager;
+ (tAudioManagerState) sharedManagerState; + (tAudioManagerState) sharedManagerState;
/** Configures the shared singleton with a mode*/ /** Configures the shared singleton with a mode*/
skipping to change at line 232 skipping to change at line 235
@end @end
/** Fader for long audio source objects */ /** Fader for long audio source objects */
@interface CDLongAudioSourceFader : CDPropertyModifier{} @interface CDLongAudioSourceFader : CDPropertyModifier{}
@end @end
static const int kCDNoBuffer = -1; static const int kCDNoBuffer = -1;
/** Allows buffers to be associated with file names */ /** Allows buffers to be associated with file names */
@interface CDBufferManager:NSObject{ @interface CDBufferManager:NSObject{
NSMutableDictionary* loadedBuffers; NSMutableDictionary* loadedBuffers;
NSMutableArray *freedBuffers; NSMutableArray *freedBuffers;
CDSoundEngine *soundEngine; CDSoundEngine *soundEngine;
int nextBufferId; int nextBufferId;
} }
-(id) initWithEngine:(CDSoundEngine *) theSoundEngine; -(id) initWithEngine:(CDSoundEngine *) theSoundEngine;
-(int) bufferForFile:(NSString*) filePath create:(BOOL) create; -(int) bufferForFile:(NSString*) filePath create:(BOOL) create;
-(void) releaseBufferForFile:(NSString *) filePath; -(void) releaseBufferForFile:(NSString *) filePath;
@end @end
 End of changes. 11 change blocks. 
63 lines changed or deleted 63 lines changed or added


 CDOpenALSupport.h   CDOpenALSupport.h 
skipping to change at line 65 skipping to change at line 65
#ifdef __cplusplus #ifdef __cplusplus
extern "C" { extern "C" {
#endif #endif
#import <OpenAL/al.h> #import <OpenAL/al.h>
#import <OpenAL/alc.h> #import <OpenAL/alc.h>
#import <CoreFoundation/CFURL.h> #import <CoreFoundation/CFURL.h>
//Taken from oalTouch MyOpenALSupport 1.1 //Taken from oalTouch MyOpenALSupport 1.1
void* CDloadWaveAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDataFormat, ALsizei* outSampleRate); void* CDloadWaveAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDataFormat, ALsizei* outSampleRate);
void* CDloadCafAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum * outDataFormat, ALsizei* outSampleRate); void* CDloadCafAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum * outDataFormat, ALsizei* outSampleRate);
void* CDGetOpenALAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDataFormat, ALsizei* outSampleRate); void* CDGetOpenALAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDataFormat, ALsizei* outSampleRate);
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif
#endif #endif
 End of changes. 1 change blocks. 
1 lines changed or deleted 1 lines changed or added


 Cantilever.h   Cantilever.h 
skipping to change at line 30 skipping to change at line 30
#define CANTILEVER_H #define CANTILEVER_H
// It is difficult to make a cantilever made of links completely rigid with weld joints. // It is difficult to make a cantilever made of links completely rigid with weld joints.
// You will have to use a high number of iterations to make them stiff. // You will have to use a high number of iterations to make them stiff.
// So why not go ahead and use soft weld joints? They behave like a revolut e // So why not go ahead and use soft weld joints? They behave like a revolut e
// joint with a rotational spring. // joint with a rotational spring.
class Cantilever : public Test class Cantilever : public Test
{ {
public: public:
enum enum
{ {
e_count = 8 e_count = 8
}; };
Cantilever() Cantilever()
{ {
b2Body* ground = NULL; b2Body* ground = NULL;
{ {
b2BodyDef bd; b2BodyDef bd;
ground = m_world->CreateBody(&bd); ground = m_world->CreateBody(&bd);
b2EdgeShape shape; b2EdgeShape shape;
shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)) shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f));
; ground->CreateFixture(&shape, 0.0f);
ground->CreateFixture(&shape, 0.0f); }
}
{
{ b2PolygonShape shape;
b2PolygonShape shape; shape.SetAsBox(0.5f, 0.125f);
shape.SetAsBox(0.5f, 0.125f);
b2FixtureDef fd;
b2FixtureDef fd; fd.shape = &shape;
fd.shape = &shape; fd.density = 20.0f;
fd.density = 20.0f;
b2WeldJointDef jd;
b2WeldJointDef jd;
b2Body* prevBody = ground;
b2Body* prevBody = ground; for (int32 i = 0; i < e_count; ++i)
for (int32 i = 0; i < e_count; ++i) {
{ b2BodyDef bd;
b2BodyDef bd; bd.type = b2_dynamicBody;
bd.type = b2_dynamicBody; bd.position.Set(-14.5f + 1.0f * i, 5.0f);
bd.position.Set(-14.5f + 1.0f * i, 5.0f); b2Body* body = m_world->CreateBody(&bd);
b2Body* body = m_world->CreateBody(&bd); body->CreateFixture(&fd);
body->CreateFixture(&fd);
b2Vec2 anchor(-15.0f + 1.0f * i, 5.0f);
b2Vec2 anchor(-15.0f + 1.0f * i, 5.0f); jd.Initialize(prevBody, body, anchor);
jd.Initialize(prevBody, body, anchor); m_world->CreateJoint(&jd);
m_world->CreateJoint(&jd);
prevBody = body;
prevBody = body; }
} }
}
{
{ b2PolygonShape shape;
b2PolygonShape shape; shape.SetAsBox(1.0f, 0.125f);
shape.SetAsBox(1.0f, 0.125f);
b2FixtureDef fd;
b2FixtureDef fd; fd.shape = &shape;
fd.shape = &shape; fd.density = 20.0f;
fd.density = 20.0f;
b2WeldJointDef jd;
b2WeldJointDef jd; jd.frequencyHz = 5.0f;
jd.frequencyHz = 5.0f; jd.dampingRatio = 0.7f;
jd.dampingRatio = 0.7f;
b2Body* prevBody = ground;
b2Body* prevBody = ground; for (int32 i = 0; i < 3; ++i)
for (int32 i = 0; i < 3; ++i) {
{ b2BodyDef bd;
b2BodyDef bd; bd.type = b2_dynamicBody;
bd.type = b2_dynamicBody; bd.position.Set(-14.0f + 2.0f * i, 15.0f);
bd.position.Set(-14.0f + 2.0f * i, 15.0f); b2Body* body = m_world->CreateBody(&bd);
b2Body* body = m_world->CreateBody(&bd); body->CreateFixture(&fd);
body->CreateFixture(&fd);
b2Vec2 anchor(-15.0f + 2.0f * i, 15.0f);
b2Vec2 anchor(-15.0f + 2.0f * i, 15.0f); jd.Initialize(prevBody, body, anchor);
jd.Initialize(prevBody, body, anchor); m_world->CreateJoint(&jd);
m_world->CreateJoint(&jd);
prevBody = body;
prevBody = body; }
} }
}
{
{ b2PolygonShape shape;
b2PolygonShape shape; shape.SetAsBox(0.5f, 0.125f);
shape.SetAsBox(0.5f, 0.125f);
b2FixtureDef fd;
b2FixtureDef fd; fd.shape = &shape;
fd.shape = &shape; fd.density = 20.0f;
fd.density = 20.0f;
b2WeldJointDef jd;
b2WeldJointDef jd;
b2Body* prevBody = ground;
b2Body* prevBody = ground; for (int32 i = 0; i < e_count; ++i)
for (int32 i = 0; i < e_count; ++i) {
{ b2BodyDef bd;
b2BodyDef bd; bd.type = b2_dynamicBody;
bd.type = b2_dynamicBody; bd.position.Set(-4.5f + 1.0f * i, 5.0f);
bd.position.Set(-4.5f + 1.0f * i, 5.0f); b2Body* body = m_world->CreateBody(&bd);
b2Body* body = m_world->CreateBody(&bd); body->CreateFixture(&fd);
body->CreateFixture(&fd);
if (i > 0)
if (i > 0) {
{ b2Vec2 anchor(-5.0f + 1.0f * i, 5.0f);
b2Vec2 anchor(-5.0f + 1.0f * i, 5.0f jd.Initialize(prevBody, body, anchor);
); m_world->CreateJoint(&jd);
jd.Initialize(prevBody, body, anchor }
);
m_world->CreateJoint(&jd); prevBody = body;
} }
}
prevBody = body;
} {
} b2PolygonShape shape;
shape.SetAsBox(0.5f, 0.125f);
{
b2PolygonShape shape; b2FixtureDef fd;
shape.SetAsBox(0.5f, 0.125f); fd.shape = &shape;
fd.density = 20.0f;
b2FixtureDef fd;
fd.shape = &shape; b2WeldJointDef jd;
fd.density = 20.0f; jd.frequencyHz = 8.0f;
jd.dampingRatio = 0.7f;
b2WeldJointDef jd;
jd.frequencyHz = 8.0f; b2Body* prevBody = ground;
jd.dampingRatio = 0.7f; for (int32 i = 0; i < e_count; ++i)
{
b2Body* prevBody = ground; b2BodyDef bd;
for (int32 i = 0; i < e_count; ++i) bd.type = b2_dynamicBody;
{ bd.position.Set(5.5f + 1.0f * i, 10.0f);
b2BodyDef bd; b2Body* body = m_world->CreateBody(&bd);
bd.type = b2_dynamicBody; body->CreateFixture(&fd);
bd.position.Set(5.5f + 1.0f * i, 10.0f);
b2Body* body = m_world->CreateBody(&bd); if (i > 0)
body->CreateFixture(&fd); {
b2Vec2 anchor(5.0f + 1.0f * i, 10.0f);
if (i > 0) jd.Initialize(prevBody, body, anchor);
{ m_world->CreateJoint(&jd);
b2Vec2 anchor(5.0f + 1.0f * i, 10.0f }
);
jd.Initialize(prevBody, body, anchor prevBody = body;
); }
m_world->CreateJoint(&jd); }
}
for (int32 i = 0; i < 2; ++i)
prevBody = body; {
} b2Vec2 vertices[3];
} vertices[0].Set(-0.5f, 0.0f);
vertices[1].Set(0.5f, 0.0f);
for (int32 i = 0; i < 2; ++i) vertices[2].Set(0.0f, 1.5f);
{
b2Vec2 vertices[3]; b2PolygonShape shape;
vertices[0].Set(-0.5f, 0.0f); shape.Set(vertices, 3);
vertices[1].Set(0.5f, 0.0f);
vertices[2].Set(0.0f, 1.5f); b2FixtureDef fd;
fd.shape = &shape;
b2PolygonShape shape; fd.density = 1.0f;
shape.Set(vertices, 3);
b2BodyDef bd;
b2FixtureDef fd; bd.type = b2_dynamicBody;
fd.shape = &shape; bd.position.Set(-8.0f + 8.0f * i, 12.0f);
fd.density = 1.0f; b2Body* body = m_world->CreateBody(&bd);
body->CreateFixture(&fd);
b2BodyDef bd; }
bd.type = b2_dynamicBody;
bd.position.Set(-8.0f + 8.0f * i, 12.0f); for (int32 i = 0; i < 2; ++i)
b2Body* body = m_world->CreateBody(&bd); {
body->CreateFixture(&fd); b2CircleShape shape;
} shape.m_radius = 0.5f;
for (int32 i = 0; i < 2; ++i) b2FixtureDef fd;
{ fd.shape = &shape;
b2CircleShape shape; fd.density = 1.0f;
shape.m_radius = 0.5f;
b2BodyDef bd;
b2FixtureDef fd; bd.type = b2_dynamicBody;
fd.shape = &shape; bd.position.Set(-6.0f + 6.0f * i, 10.0f);
fd.density = 1.0f; b2Body* body = m_world->CreateBody(&bd);
body->CreateFixture(&fd);
b2BodyDef bd; }
bd.type = b2_dynamicBody; }
bd.position.Set(-6.0f + 6.0f * i, 10.0f);
b2Body* body = m_world->CreateBody(&bd); static Test* Create()
body->CreateFixture(&fd); {
} return new Cantilever;
} }
static Test* Create()
{
return new Cantilever;
}
b2Body* m_middle; b2Body* m_middle;
}; };
#endif #endif
 End of changes. 2 change blocks. 
183 lines changed or deleted 178 lines changed or added


 Car.h   Car.h 
skipping to change at line 26 skipping to change at line 26
* 3. This notice may not be removed or altered from any source distribution . * 3. This notice may not be removed or altered from any source distribution .
*/ */
#ifndef CAR_H #ifndef CAR_H
#define CAR_H #define CAR_H
// This is a fun demo that shows off the wheel joint // This is a fun demo that shows off the wheel joint
class Car : public Test class Car : public Test
{ {
public: public:
Car() Car()
{ {
m_hz = 4.0f; m_hz = 4.0f;
m_zeta = 0.7f; m_zeta = 0.7f;
m_speed = 50.0f; m_speed = 50.0f;
b2Body* ground = NULL; b2Body* ground = NULL;
{ {
b2BodyDef bd; b2BodyDef bd;
ground = m_world->CreateBody(&bd); ground = m_world->CreateBody(&bd);
b2EdgeShape shape; b2EdgeShape shape;
b2FixtureDef fd; b2FixtureDef fd;
fd.shape = &shape; fd.shape = &shape;
fd.density = 0.0f; fd.density = 0.0f;
fd.friction = 0.6f; fd.friction = 0.6f;
shape.Set(b2Vec2(-20.0f, 0.0f), b2Vec2(20.0f, 0.0f)) shape.Set(b2Vec2(-20.0f, 0.0f), b2Vec2(20.0f, 0.0f));
; ground->CreateFixture(&fd);
ground->CreateFixture(&fd);
float32 hs[10] = {0.25f, 1.0f, 4.0f, 0.0f, 0.0f, -1.0f, -2.0f,
float32 hs[10] = {0.25f, 1.0f, 4.0f, 0.0f, 0.0f, -1. -2.0f, -1.25f, 0.0f};
0f, -2.0f, -2.0f, -1.25f, 0.0f};
float32 x = 20.0f, y1 = 0.0f, dx = 5.0f;
float32 x = 20.0f, y1 = 0.0f, dx = 5.0f;
for (int32 i = 0; i < 10; ++i)
for (int32 i = 0; i < 10; ++i) {
{ float32 y2 = hs[i];
float32 y2 = hs[i]; shape.Set(b2Vec2(x, y1), b2Vec2(x + dx, y2));
shape.Set(b2Vec2(x, y1), b2Vec2(x + dx, y2)) ground->CreateFixture(&fd);
; y1 = y2;
ground->CreateFixture(&fd); x += dx;
y1 = y2; }
x += dx;
} for (int32 i = 0; i < 10; ++i)
{
for (int32 i = 0; i < 10; ++i) float32 y2 = hs[i];
{ shape.Set(b2Vec2(x, y1), b2Vec2(x + dx, y2));
float32 y2 = hs[i]; ground->CreateFixture(&fd);
shape.Set(b2Vec2(x, y1), b2Vec2(x + dx, y2)) y1 = y2;
; x += dx;
ground->CreateFixture(&fd); }
y1 = y2;
x += dx; shape.Set(b2Vec2(x, 0.0f), b2Vec2(x + 40.0f, 0.0f));
} ground->CreateFixture(&fd);
shape.Set(b2Vec2(x, 0.0f), b2Vec2(x + 40.0f, 0.0f)); x += 80.0f;
ground->CreateFixture(&fd); shape.Set(b2Vec2(x, 0.0f), b2Vec2(x + 40.0f, 0.0f));
ground->CreateFixture(&fd);
x += 80.0f;
shape.Set(b2Vec2(x, 0.0f), b2Vec2(x + 40.0f, 0.0f)); x += 40.0f;
ground->CreateFixture(&fd); shape.Set(b2Vec2(x, 0.0f), b2Vec2(x + 10.0f, 5.0f));
ground->CreateFixture(&fd);
x += 40.0f;
shape.Set(b2Vec2(x, 0.0f), b2Vec2(x + 10.0f, 5.0f)); x += 20.0f;
ground->CreateFixture(&fd); shape.Set(b2Vec2(x, 0.0f), b2Vec2(x + 40.0f, 0.0f));
ground->CreateFixture(&fd);
x += 20.0f;
shape.Set(b2Vec2(x, 0.0f), b2Vec2(x + 40.0f, 0.0f)); x += 40.0f;
ground->CreateFixture(&fd); shape.Set(b2Vec2(x, 0.0f), b2Vec2(x, 20.0f));
ground->CreateFixture(&fd);
x += 40.0f; }
shape.Set(b2Vec2(x, 0.0f), b2Vec2(x, 20.0f));
ground->CreateFixture(&fd); // Teeter
} {
b2BodyDef bd;
// Teeter bd.position.Set(140.0f, 1.0f);
{ bd.type = b2_dynamicBody;
b2BodyDef bd; b2Body* body = m_world->CreateBody(&bd);
bd.position.Set(140.0f, 1.0f);
bd.type = b2_dynamicBody; b2PolygonShape box;
b2Body* body = m_world->CreateBody(&bd); box.SetAsBox(10.0f, 0.25f);
body->CreateFixture(&box, 1.0f);
b2PolygonShape box;
box.SetAsBox(10.0f, 0.25f); b2RevoluteJointDef jd;
body->CreateFixture(&box, 1.0f); jd.Initialize(ground, body, body->GetPosition());
jd.lowerAngle = -8.0f * b2_pi / 180.0f;
b2RevoluteJointDef jd; jd.upperAngle = 8.0f * b2_pi / 180.0f;
jd.Initialize(ground, body, body->GetPosition()); jd.enableLimit = true;
jd.lowerAngle = -8.0f * b2_pi / 180.0f; m_world->CreateJoint(&jd);
jd.upperAngle = 8.0f * b2_pi / 180.0f;
jd.enableLimit = true; body->ApplyAngularImpulse(100.0f);
m_world->CreateJoint(&jd); }
body->ApplyAngularImpulse(100.0f); // Bridge
} {
int32 N = 20;
// Bridge b2PolygonShape shape;
{ shape.SetAsBox(1.0f, 0.125f);
int32 N = 20;
b2PolygonShape shape; b2FixtureDef fd;
shape.SetAsBox(1.0f, 0.125f); fd.shape = &shape;
fd.density = 1.0f;
b2FixtureDef fd; fd.friction = 0.6f;
fd.shape = &shape;
fd.density = 1.0f; b2RevoluteJointDef jd;
fd.friction = 0.6f;
b2Body* prevBody = ground;
b2RevoluteJointDef jd; for (int32 i = 0; i < N; ++i)
{
b2Body* prevBody = ground; b2BodyDef bd;
for (int32 i = 0; i < N; ++i) bd.type = b2_dynamicBody;
{ bd.position.Set(161.0f + 2.0f * i, -0.125f);
b2BodyDef bd; b2Body* body = m_world->CreateBody(&bd);
bd.type = b2_dynamicBody; body->CreateFixture(&fd);
bd.position.Set(161.0f + 2.0f * i, -0.125f);
b2Body* body = m_world->CreateBody(&bd); b2Vec2 anchor(160.0f + 2.0f * i, -0.125f);
body->CreateFixture(&fd); jd.Initialize(prevBody, body, anchor);
m_world->CreateJoint(&jd);
b2Vec2 anchor(160.0f + 2.0f * i, -0.125f);
jd.Initialize(prevBody, body, anchor); prevBody = body;
m_world->CreateJoint(&jd); }
prevBody = body; b2Vec2 anchor(160.0f + 2.0f * N, -0.125f);
} jd.Initialize(prevBody, ground, anchor);
m_world->CreateJoint(&jd);
b2Vec2 anchor(160.0f + 2.0f * N, -0.125f); }
jd.Initialize(prevBody, ground, anchor);
m_world->CreateJoint(&jd); // Boxes
} {
b2PolygonShape box;
// Boxes box.SetAsBox(0.5f, 0.5f);
{
b2PolygonShape box; b2Body* body = NULL;
box.SetAsBox(0.5f, 0.5f); b2BodyDef bd;
bd.type = b2_dynamicBody;
b2Body* body = NULL;
b2BodyDef bd; bd.position.Set(230.0f, 0.5f);
bd.type = b2_dynamicBody; body = m_world->CreateBody(&bd);
body->CreateFixture(&box, 0.5f);
bd.position.Set(230.0f, 0.5f);
body = m_world->CreateBody(&bd); bd.position.Set(230.0f, 1.5f);
body->CreateFixture(&box, 0.5f); body = m_world->CreateBody(&bd);
body->CreateFixture(&box, 0.5f);
bd.position.Set(230.0f, 1.5f);
body = m_world->CreateBody(&bd); bd.position.Set(230.0f, 2.5f);
body->CreateFixture(&box, 0.5f); body = m_world->CreateBody(&bd);
body->CreateFixture(&box, 0.5f);
bd.position.Set(230.0f, 2.5f);
body = m_world->CreateBody(&bd); bd.position.Set(230.0f, 3.5f);
body->CreateFixture(&box, 0.5f); body = m_world->CreateBody(&bd);
body->CreateFixture(&box, 0.5f);
bd.position.Set(230.0f, 3.5f);
body = m_world->CreateBody(&bd); bd.position.Set(230.0f, 4.5f);
body->CreateFixture(&box, 0.5f); body = m_world->CreateBody(&bd);
body->CreateFixture(&box, 0.5f);
bd.position.Set(230.0f, 4.5f); }
body = m_world->CreateBody(&bd);
body->CreateFixture(&box, 0.5f); // Car
} {
b2PolygonShape chassis;
// Car b2Vec2 vertices[8];
{ vertices[0].Set(-1.5f, -0.5f);
b2PolygonShape chassis; vertices[1].Set(1.5f, -0.5f);
b2Vec2 vertices[8]; vertices[2].Set(1.5f, 0.0f);
vertices[0].Set(-1.5f, -0.5f); vertices[3].Set(0.0f, 0.9f);
vertices[1].Set(1.5f, -0.5f); vertices[4].Set(-1.15f, 0.9f);
vertices[2].Set(1.5f, 0.0f); vertices[5].Set(-1.5f, 0.2f);
vertices[3].Set(0.0f, 0.9f); chassis.Set(vertices, 6);
vertices[4].Set(-1.15f, 0.9f);
vertices[5].Set(-1.5f, 0.2f); b2CircleShape circle;
chassis.Set(vertices, 6); circle.m_radius = 0.4f;
b2CircleShape circle; b2BodyDef bd;
circle.m_radius = 0.4f; bd.type = b2_dynamicBody;
bd.position.Set(0.0f, 1.0f);
b2BodyDef bd; m_car = m_world->CreateBody(&bd);
bd.type = b2_dynamicBody; m_car->CreateFixture(&chassis, 1.0f);
bd.position.Set(0.0f, 1.0f);
m_car = m_world->CreateBody(&bd); b2FixtureDef fd;
m_car->CreateFixture(&chassis, 1.0f); fd.shape = &circle;
fd.density = 1.0f;
b2FixtureDef fd; fd.friction = 0.9f;
fd.shape = &circle;
fd.density = 1.0f; bd.position.Set(-1.0f, 0.35f);
fd.friction = 0.9f; m_wheel1 = m_world->CreateBody(&bd);
m_wheel1->CreateFixture(&fd);
bd.position.Set(-1.0f, 0.35f);
m_wheel1 = m_world->CreateBody(&bd); bd.position.Set(1.0f, 0.4f);
m_wheel1->CreateFixture(&fd); m_wheel2 = m_world->CreateBody(&bd);
m_wheel2->CreateFixture(&fd);
bd.position.Set(1.0f, 0.4f);
m_wheel2 = m_world->CreateBody(&bd); b2WheelJointDef jd;
m_wheel2->CreateFixture(&fd); b2Vec2 axis(0.0f, 1.0f);
b2WheelJointDef jd; jd.Initialize(m_car, m_wheel1, m_wheel1->GetPosition(), axis);
b2Vec2 axis(0.0f, 1.0f); jd.motorSpeed = 0.0f;
jd.maxMotorTorque = 20.0f;
jd.Initialize(m_car, m_wheel1, m_wheel1->GetPosition jd.enableMotor = true;
(), axis); jd.frequencyHz = m_hz;
jd.motorSpeed = 0.0f; jd.dampingRatio = m_zeta;
jd.maxMotorTorque = 20.0f; m_spring1 = (b2WheelJoint*)m_world->CreateJoint(&jd);
jd.enableMotor = true;
jd.frequencyHz = m_hz; jd.Initialize(m_car, m_wheel2, m_wheel2->GetPosition(), axis);
jd.dampingRatio = m_zeta; jd.motorSpeed = 0.0f;
m_spring1 = (b2WheelJoint*)m_world->CreateJoint(&jd) jd.maxMotorTorque = 10.0f;
; jd.enableMotor = false;
jd.frequencyHz = m_hz;
jd.Initialize(m_car, m_wheel2, m_wheel2->GetPosition jd.dampingRatio = m_zeta;
(), axis); m_spring2 = (b2WheelJoint*)m_world->CreateJoint(&jd);
jd.motorSpeed = 0.0f; }
jd.maxMotorTorque = 10.0f; }
jd.enableMotor = false;
jd.frequencyHz = m_hz; void Keyboard(unsigned char key)
jd.dampingRatio = m_zeta; {
m_spring2 = (b2WheelJoint*)m_world->CreateJoint(&jd) switch (key)
; {
} case 'a':
} m_spring1->SetMotorSpeed(m_speed);
break;
void Keyboard(unsigned char key)
{ case 's':
switch (key) m_spring1->SetMotorSpeed(0.0f);
{ break;
case 'a':
m_spring1->SetMotorSpeed(m_speed); case 'd':
break; m_spring1->SetMotorSpeed(-m_speed);
break;
case 's':
m_spring1->SetMotorSpeed(0.0f); case 'q':
break; m_hz = b2Max(0.0f, m_hz - 1.0f);
m_spring1->SetSpringFrequencyHz(m_hz);
case 'd': m_spring2->SetSpringFrequencyHz(m_hz);
m_spring1->SetMotorSpeed(-m_speed); break;
break;
case 'e':
case 'q': m_hz += 1.0f;
m_hz = b2Max(0.0f, m_hz - 1.0f); m_spring1->SetSpringFrequencyHz(m_hz);
m_spring1->SetSpringFrequencyHz(m_hz); m_spring2->SetSpringFrequencyHz(m_hz);
m_spring2->SetSpringFrequencyHz(m_hz); break;
break; }
}
case 'e':
m_hz += 1.0f; void Step(Settings* settings)
m_spring1->SetSpringFrequencyHz(m_hz); {
m_spring2->SetSpringFrequencyHz(m_hz); m_debugDraw.DrawString(5, m_textLine, "Keys: left = a, brake = s, r
break; ight = d, hz down = q, hz up = e");
} m_textLine += 15;
} m_debugDraw.DrawString(5, m_textLine, "frequency = %g hz, damping r
atio = %g", m_hz, m_zeta);
void Step(Settings* settings) m_textLine += 15;
{
m_debugDraw.DrawString(5, m_textLine, "Keys: left = a, brake settings->viewCenter.x = m_car->GetPosition().x;
= s, right = d, hz down = q, hz up = e"); Test::Step(settings);
m_textLine += 15; }
m_debugDraw.DrawString(5, m_textLine, "frequency = %g hz, da
mping ratio = %g", m_hz, m_zeta); static Test* Create()
m_textLine += 15; {
return new Car;
settings->viewCenter.x = m_car->GetPosition().x; }
Test::Step(settings);
} b2Body* m_car;
b2Body* m_wheel1;
static Test* Create() b2Body* m_wheel2;
{
return new Car; float32 m_hz;
} float32 m_zeta;
float32 m_speed;
b2Body* m_car; b2WheelJoint* m_spring1;
b2Body* m_wheel1; b2WheelJoint* m_spring2;
b2Body* m_wheel2;
float32 m_hz;
float32 m_zeta;
float32 m_speed;
b2WheelJoint* m_spring1;
b2WheelJoint* m_spring2;
}; };
#endif #endif
 End of changes. 1 change blocks. 
268 lines changed or deleted 261 lines changed or added


 Chain.h   Chain.h 
skipping to change at line 25 skipping to change at line 25
* misrepresented as being the original software. * misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution . * 3. This notice may not be removed or altered from any source distribution .
*/ */
#ifndef CHAIN_H #ifndef CHAIN_H
#define CHAIN_H #define CHAIN_H
class Chain : public Test class Chain : public Test
{ {
public: public:
Chain() Chain()
{ {
b2Body* ground = NULL; b2Body* ground = NULL;
{ {
b2BodyDef bd; b2BodyDef bd;
ground = m_world->CreateBody(&bd); ground = m_world->CreateBody(&bd);
b2EdgeShape shape; b2EdgeShape shape;
shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)) shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f));
; ground->CreateFixture(&shape, 0.0f);
ground->CreateFixture(&shape, 0.0f); }
}
{
{ b2PolygonShape shape;
b2PolygonShape shape; shape.SetAsBox(0.6f, 0.125f);
shape.SetAsBox(0.6f, 0.125f);
b2FixtureDef fd;
b2FixtureDef fd; fd.shape = &shape;
fd.shape = &shape; fd.density = 20.0f;
fd.density = 20.0f; fd.friction = 0.2f;
fd.friction = 0.2f;
b2RevoluteJointDef jd;
b2RevoluteJointDef jd; jd.collideConnected = false;
jd.collideConnected = false;
const float32 y = 25.0f;
const float32 y = 25.0f; b2Body* prevBody = ground;
b2Body* prevBody = ground; for (int32 i = 0; i < 30; ++i)
for (int32 i = 0; i < 30; ++i) {
{ b2BodyDef bd;
b2BodyDef bd; bd.type = b2_dynamicBody;
bd.type = b2_dynamicBody; bd.position.Set(0.5f + i, y);
bd.position.Set(0.5f + i, y); b2Body* body = m_world->CreateBody(&bd);
b2Body* body = m_world->CreateBody(&bd); body->CreateFixture(&fd);
body->CreateFixture(&fd);
b2Vec2 anchor(float32(i), y);
b2Vec2 anchor(float32(i), y); jd.Initialize(prevBody, body, anchor);
jd.Initialize(prevBody, body, anchor); m_world->CreateJoint(&jd);
m_world->CreateJoint(&jd);
prevBody = body;
prevBody = body; }
} }
} }
}
static Test* Create()
static Test* Create() {
{ return new Chain;
return new Chain; }
}
}; };
#endif #endif
 End of changes. 1 change blocks. 
48 lines changed or deleted 47 lines changed or added


 CharacterCollision.h   CharacterCollision.h 
skipping to change at line 28 skipping to change at line 28
#ifndef CHARACTER_COLLISION_H #ifndef CHARACTER_COLLISION_H
#define CHARACTER_COLLISION_H #define CHARACTER_COLLISION_H
/// This is a test of typical character collision scenarios. This does not /// This is a test of typical character collision scenarios. This does not
/// show how you should implement a character in your application. /// show how you should implement a character in your application.
/// Instead this is used to test smooth collision on edge chains. /// Instead this is used to test smooth collision on edge chains.
class CharacterCollision : public Test class CharacterCollision : public Test
{ {
public: public:
CharacterCollision() CharacterCollision()
{ {
// Ground body // Ground body
{ {
b2BodyDef bd; b2BodyDef bd;
b2Body* ground = m_world->CreateBody(&bd); b2Body* ground = m_world->CreateBody(&bd);
b2EdgeShape shape; b2EdgeShape shape;
shape.Set(b2Vec2(-20.0f, 0.0f), b2Vec2(20.0f, 0.0f)) shape.Set(b2Vec2(-20.0f, 0.0f), b2Vec2(20.0f, 0.0f));
; ground->CreateFixture(&shape, 0.0f);
ground->CreateFixture(&shape, 0.0f); }
}
// Collinear edges with no adjacency information.
// Collinear edges with no adjacency information. // This shows the problematic case where a box shape can hit
// This shows the problematic case where a box shape can hit // an internal vertex.
// an internal vertex. {
{ b2BodyDef bd;
b2BodyDef bd; b2Body* ground = m_world->CreateBody(&bd);
b2Body* ground = m_world->CreateBody(&bd);
b2EdgeShape shape;
b2EdgeShape shape; shape.Set(b2Vec2(-8.0f, 1.0f), b2Vec2(-6.0f, 1.0f));
shape.Set(b2Vec2(-8.0f, 1.0f), b2Vec2(-6.0f, 1.0f)); ground->CreateFixture(&shape, 0.0f);
ground->CreateFixture(&shape, 0.0f); shape.Set(b2Vec2(-6.0f, 1.0f), b2Vec2(-4.0f, 1.0f));
shape.Set(b2Vec2(-6.0f, 1.0f), b2Vec2(-4.0f, 1.0f)); ground->CreateFixture(&shape, 0.0f);
ground->CreateFixture(&shape, 0.0f); shape.Set(b2Vec2(-4.0f, 1.0f), b2Vec2(-2.0f, 1.0f));
shape.Set(b2Vec2(-4.0f, 1.0f), b2Vec2(-2.0f, 1.0f)); ground->CreateFixture(&shape, 0.0f);
ground->CreateFixture(&shape, 0.0f); }
}
// Chain shape
// Chain shape {
{ b2BodyDef bd;
b2BodyDef bd; bd.angle = 0.25f * b2_pi;
bd.angle = 0.25f * b2_pi; b2Body* ground = m_world->CreateBody(&bd);
b2Body* ground = m_world->CreateBody(&bd);
b2Vec2 vs[4];
b2Vec2 vs[4]; vs[0].Set(5.0f, 7.0f);
vs[0].Set(5.0f, 7.0f); vs[1].Set(6.0f, 8.0f);
vs[1].Set(6.0f, 8.0f); vs[2].Set(7.0f, 8.0f);
vs[2].Set(7.0f, 8.0f); vs[3].Set(8.0f, 7.0f);
vs[3].Set(8.0f, 7.0f); b2ChainShape shape;
b2ChainShape shape; shape.CreateChain(vs, 4);
shape.CreateChain(vs, 4); ground->CreateFixture(&shape, 0.0f);
ground->CreateFixture(&shape, 0.0f); }
}
// Square tiles. This shows that adjacency shapes may
// Square tiles. This shows that adjacency shapes may // have non-smooth collision. There is no solution
// have non-smooth collision. There is no solution // to this problem.
// to this problem. {
{ b2BodyDef bd;
b2BodyDef bd; b2Body* ground = m_world->CreateBody(&bd);
b2Body* ground = m_world->CreateBody(&bd);
b2PolygonShape shape;
b2PolygonShape shape; shape.SetAsBox(1.0f, 1.0f, b2Vec2(4.0f, 3.0f), 0.0f);
shape.SetAsBox(1.0f, 1.0f, b2Vec2(4.0f, 3.0f), 0.0f) ground->CreateFixture(&shape, 0.0f);
; shape.SetAsBox(1.0f, 1.0f, b2Vec2(6.0f, 3.0f), 0.0f);
ground->CreateFixture(&shape, 0.0f); ground->CreateFixture(&shape, 0.0f);
shape.SetAsBox(1.0f, 1.0f, b2Vec2(6.0f, 3.0f), 0.0f) shape.SetAsBox(1.0f, 1.0f, b2Vec2(8.0f, 3.0f), 0.0f);
; ground->CreateFixture(&shape, 0.0f);
ground->CreateFixture(&shape, 0.0f); }
shape.SetAsBox(1.0f, 1.0f, b2Vec2(8.0f, 3.0f), 0.0f)
; // Square made from an edge loop. Collision should be smooth.
ground->CreateFixture(&shape, 0.0f); {
} b2BodyDef bd;
b2Body* ground = m_world->CreateBody(&bd);
// Square made from an edge loop. Collision should be smooth
. b2Vec2 vs[4];
{ vs[0].Set(-1.0f, 3.0f);
b2BodyDef bd; vs[1].Set(1.0f, 3.0f);
b2Body* ground = m_world->CreateBody(&bd); vs[2].Set(1.0f, 5.0f);
vs[3].Set(-1.0f, 5.0f);
b2Vec2 vs[4]; b2ChainShape shape;
vs[0].Set(-1.0f, 3.0f); shape.CreateLoop(vs, 4);
vs[1].Set(1.0f, 3.0f); ground->CreateFixture(&shape, 0.0f);
vs[2].Set(1.0f, 5.0f); }
vs[3].Set(-1.0f, 5.0f);
b2ChainShape shape; // Edge loop. Collision should be smooth.
shape.CreateLoop(vs, 4); {
ground->CreateFixture(&shape, 0.0f); b2BodyDef bd;
} bd.position.Set(-10.0f, 4.0f);
b2Body* ground = m_world->CreateBody(&bd);
// Edge loop. Collision should be smooth.
{ b2Vec2 vs[10];
b2BodyDef bd; vs[0].Set(0.0f, 0.0f);
bd.position.Set(-10.0f, 4.0f); vs[1].Set(6.0f, 0.0f);
b2Body* ground = m_world->CreateBody(&bd); vs[2].Set(6.0f, 2.0f);
vs[3].Set(4.0f, 1.0f);
b2Vec2 vs[10]; vs[4].Set(2.0f, 2.0f);
vs[0].Set(0.0f, 0.0f); vs[5].Set(0.0f, 2.0f);
vs[1].Set(6.0f, 0.0f); vs[6].Set(-2.0f, 2.0f);
vs[2].Set(6.0f, 2.0f); vs[7].Set(-4.0f, 3.0f);
vs[3].Set(4.0f, 1.0f); vs[8].Set(-6.0f, 2.0f);
vs[4].Set(2.0f, 2.0f); vs[9].Set(-6.0f, 0.0f);
vs[5].Set(0.0f, 2.0f); b2ChainShape shape;
vs[6].Set(-2.0f, 2.0f); shape.CreateLoop(vs, 10);
vs[7].Set(-4.0f, 3.0f); ground->CreateFixture(&shape, 0.0f);
vs[8].Set(-6.0f, 2.0f); }
vs[9].Set(-6.0f, 0.0f);
b2ChainShape shape; // Square character 1
shape.CreateLoop(vs, 10); {
ground->CreateFixture(&shape, 0.0f); b2BodyDef bd;
} bd.position.Set(-3.0f, 8.0f);
bd.type = b2_dynamicBody;
// Square character 1 bd.fixedRotation = true;
{ bd.allowSleep = false;
b2BodyDef bd;
bd.position.Set(-3.0f, 8.0f); b2Body* body = m_world->CreateBody(&bd);
bd.type = b2_dynamicBody;
bd.fixedRotation = true; b2PolygonShape shape;
bd.allowSleep = false; shape.SetAsBox(0.5f, 0.5f);
b2Body* body = m_world->CreateBody(&bd); b2FixtureDef fd;
fd.shape = &shape;
b2PolygonShape shape; fd.density = 20.0f;
shape.SetAsBox(0.5f, 0.5f); body->CreateFixture(&fd);
}
b2FixtureDef fd;
fd.shape = &shape; // Square character 2
fd.density = 20.0f; {
body->CreateFixture(&fd); b2BodyDef bd;
} bd.position.Set(-5.0f, 5.0f);
bd.type = b2_dynamicBody;
// Square character 2 bd.fixedRotation = true;
{ bd.allowSleep = false;
b2BodyDef bd;
bd.position.Set(-5.0f, 5.0f); b2Body* body = m_world->CreateBody(&bd);
bd.type = b2_dynamicBody;
bd.fixedRotation = true; b2PolygonShape shape;
bd.allowSleep = false; shape.SetAsBox(0.25f, 0.25f);
b2Body* body = m_world->CreateBody(&bd); b2FixtureDef fd;
fd.shape = &shape;
b2PolygonShape shape; fd.density = 20.0f;
shape.SetAsBox(0.25f, 0.25f); body->CreateFixture(&fd);
}
b2FixtureDef fd;
fd.shape = &shape; // Hexagon character
fd.density = 20.0f; {
body->CreateFixture(&fd); b2BodyDef bd;
} bd.position.Set(-5.0f, 8.0f);
bd.type = b2_dynamicBody;
// Hexagon character bd.fixedRotation = true;
{ bd.allowSleep = false;
b2BodyDef bd;
bd.position.Set(-5.0f, 8.0f); b2Body* body = m_world->CreateBody(&bd);
bd.type = b2_dynamicBody;
bd.fixedRotation = true; float32 angle = 0.0f;
bd.allowSleep = false; float32 delta = b2_pi / 3.0f;
b2Vec2 vertices[6];
b2Body* body = m_world->CreateBody(&bd); for (int32 i = 0; i < 6; ++i)
{
float32 angle = 0.0f; vertices[i].Set(0.5f * cosf(angle), 0.5f * sinf(angle));
float32 delta = b2_pi / 3.0f; angle += delta;
b2Vec2 vertices[6]; }
for (int32 i = 0; i < 6; ++i)
{ b2PolygonShape shape;
vertices[i].Set(0.5f * cosf(angle), 0.5f * s shape.Set(vertices, 6);
inf(angle));
angle += delta; b2FixtureDef fd;
} fd.shape = &shape;
fd.density = 20.0f;
b2PolygonShape shape; body->CreateFixture(&fd);
shape.Set(vertices, 6); }
b2FixtureDef fd; // Circle character
fd.shape = &shape; {
fd.density = 20.0f; b2BodyDef bd;
body->CreateFixture(&fd); bd.position.Set(3.0f, 5.0f);
} bd.type = b2_dynamicBody;
bd.fixedRotation = true;
// Circle character bd.allowSleep = false;
{
b2BodyDef bd; b2Body* body = m_world->CreateBody(&bd);
bd.position.Set(3.0f, 5.0f);
bd.type = b2_dynamicBody; b2CircleShape shape;
bd.fixedRotation = true; shape.m_radius = 0.5f;
bd.allowSleep = false;
b2FixtureDef fd;
b2Body* body = m_world->CreateBody(&bd); fd.shape = &shape;
fd.density = 20.0f;
b2CircleShape shape; body->CreateFixture(&fd);
shape.m_radius = 0.5f; }
b2FixtureDef fd; // Circle character
fd.shape = &shape; {
fd.density = 20.0f; b2BodyDef bd;
body->CreateFixture(&fd); bd.position.Set(-7.0f, 6.0f);
} bd.type = b2_dynamicBody;
bd.allowSleep = false;
// Circle character
{ m_character = m_world->CreateBody(&bd);
b2BodyDef bd;
bd.position.Set(-7.0f, 6.0f); b2CircleShape shape;
bd.type = b2_dynamicBody; shape.m_radius = 0.25f;
bd.allowSleep = false;
b2FixtureDef fd;
m_character = m_world->CreateBody(&bd); fd.shape = &shape;
fd.density = 20.0f;
b2CircleShape shape; fd.friction = 1.0f;
shape.m_radius = 0.25f; m_character->CreateFixture(&fd);
}
b2FixtureDef fd; }
fd.shape = &shape;
fd.density = 20.0f; void Step(Settings* settings)
fd.friction = 1.0f; {
m_character->CreateFixture(&fd); b2Vec2 v = m_character->GetLinearVelocity();
} v.x = -5.0f;
} m_character->SetLinearVelocity(v);
void Step(Settings* settings) Test::Step(settings);
{ m_debugDraw.DrawString(5, m_textLine, "This tests various character
b2Vec2 v = m_character->GetLinearVelocity(); collision shapes.");
v.x = -5.0f; m_textLine += 15;
m_character->SetLinearVelocity(v); m_debugDraw.DrawString(5, m_textLine, "Limitation: square and hexag
on can snag on aligned boxes.");
Test::Step(settings); m_textLine += 15;
m_debugDraw.DrawString(5, m_textLine, "This tests various ch m_debugDraw.DrawString(5, m_textLine, "Feature: edge chains have sm
aracter collision shapes."); ooth collision inside and out.");
m_textLine += 15; m_textLine += 15;
m_debugDraw.DrawString(5, m_textLine, "Limitation: square an }
d hexagon can snag on aligned boxes.");
m_textLine += 15; static Test* Create()
m_debugDraw.DrawString(5, m_textLine, "Feature: edge chains {
have smooth collision inside and out."); return new CharacterCollision;
m_textLine += 15; }
}
static Test* Create()
{
return new CharacterCollision;
}
b2Body* m_character; b2Body* m_character;
}; };
#endif #endif
 End of changes. 2 change blocks. 
231 lines changed or deleted 225 lines changed or added


 ClickAndMoveTest.h   ClickAndMoveTest.h 
skipping to change at line 15 skipping to change at line 15
class ClickAndMoveTestScene : public TestScene class ClickAndMoveTestScene : public TestScene
{ {
public: public:
virtual void runThisTest(); virtual void runThisTest();
}; };
class MainLayer : public CCLayer class MainLayer : public CCLayer
{ {
public: public:
MainLayer(); MainLayer();
virtual void ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent); virtual void ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent);
}; };
#endif #endif
 End of changes. 1 change blocks. 
2 lines changed or deleted 2 lines changed or added


 CocosDenshion.h   CocosDenshion.h 
skipping to change at line 114 skipping to change at line 114
extern float const kCD_PitchDefault; extern float const kCD_PitchDefault;
extern float const kCD_PitchLowerOneOctave; extern float const kCD_PitchLowerOneOctave;
extern float const kCD_PitchHigherOneOctave; extern float const kCD_PitchHigherOneOctave;
extern float const kCD_PanDefault; extern float const kCD_PanDefault;
extern float const kCD_PanFullLeft; extern float const kCD_PanFullLeft;
extern float const kCD_PanFullRight; extern float const kCD_PanFullRight;
extern float const kCD_GainDefault; extern float const kCD_GainDefault;
enum bufferState { enum bufferState {
CD_BS_EMPTY = 0, CD_BS_EMPTY = 0,
CD_BS_LOADED = 1, CD_BS_LOADED = 1,
CD_BS_FAILED = 2 CD_BS_FAILED = 2
}; };
typedef struct _sourceGroup { typedef struct _sourceGroup {
int startIndex; int startIndex;
int currentIndex; int currentIndex;
int totalSources; int totalSources;
bool enabled; bool enabled;
bool nonInterruptible; bool nonInterruptible;
int *sourceStatuses;//pointer into array of source status informatio int *sourceStatuses;//pointer into array of source status information
n
} sourceGroup; } sourceGroup;
typedef struct _bufferInfo { typedef struct _bufferInfo {
ALuint bufferId; ALuint bufferId;
int bufferState; int bufferState;
void* bufferData; void* bufferData;
ALenum format; ALenum format;
ALsizei sizeInBytes; ALsizei sizeInBytes;
ALsizei frequencyInHertz; ALsizei frequencyInHertz;
} bufferInfo; } bufferInfo;
typedef struct _sourceInfo { typedef struct _sourceInfo {
bool usable; bool usable;
ALuint sourceId; ALuint sourceId;
ALuint attachedBufferId; ALuint attachedBufferId;
} sourceInfo; } sourceInfo;
#pragma mark CDAudioTransportProtocol #pragma mark CDAudioTransportProtocol
@protocol CDAudioTransportProtocol <NSObject> @protocol CDAudioTransportProtocol <NSObject>
/** Play the audio */ /** Play the audio */
-(BOOL) play; -(BOOL) play;
/** Pause the audio, retain resources */ /** Pause the audio, retain resources */
-(BOOL) pause; -(BOOL) pause;
/** Stop the audio, release resources */ /** Stop the audio, release resources */
skipping to change at line 201 skipping to change at line 201
Requirements: Requirements:
- Firmware: OS 2.0 or greater - Firmware: OS 2.0 or greater
- Files: CocosDenshion.* - Files: CocosDenshion.*
- Frameworks: OpenAL, AudioToolbox - Frameworks: OpenAL, AudioToolbox
@since v0.8 @since v0.8
*/ */
@class CDSoundSource; @class CDSoundSource;
@interface CDSoundEngine : NSObject <CDAudioInterruptProtocol> { @interface CDSoundEngine : NSObject <CDAudioInterruptProtocol> {
bufferInfo *_buffers; bufferInfo *_buffers;
sourceInfo *_sources; sourceInfo *_sources;
sourceGroup *_sourceGroups; sourceGroup *_sourceGroups;
ALCcontext *context; ALCcontext *context;
NSUInteger _sourceGroupTotal; NSUInteger _sourceGroupTotal;
UInt32 _audioSessionCategory; UInt32 _audioSessionCategory;
BOOL _handleAudioSession; BOOL _handleAudioSession;
ALfloat _preMuteGain; ALfloat _preMuteGain;
NSObject *_mutexBufferLoad; NSObject *_mutexBufferLoad;
BOOL mute_; BOOL mute_;
BOOL enabled_; BOOL enabled_;
ALenum lastErrorCode_; ALenum lastErrorCode_;
BOOL functioning_; BOOL functioning_;
float asynchLoadProgress_; float asynchLoadProgress_;
BOOL getGainWorks_; BOOL getGainWorks_;
//For managing dynamic allocation of sources and buffers //For managing dynamic allocation of sources and buffers
int sourceTotal_; int sourceTotal_;
int bufferTotal; int bufferTotal;
} }
@property (readwrite, nonatomic) ALfloat masterGain; @property (readwrite, nonatomic) ALfloat masterGain;
@property (readonly) ALenum lastErrorCode;//Last OpenAL error code that wa s generated @property (readonly) ALenum lastErrorCode;//Last OpenAL error code that wa s generated
@property (readonly) BOOL functioning;//Is the sound engine functioning @property (readonly) BOOL functioning;//Is the sound engine functioning
@property (readwrite) float asynchLoadProgress; @property (readwrite) float asynchLoadProgress;
@property (readonly) BOOL getGainWorks;//Does getting the gain for a sourc e work @property (readonly) BOOL getGainWorks;//Does getting the gain for a sourc e work
/** Total number of sources available */ /** Total number of sources available */
@property (readonly) int sourceTotal; @property (readonly) int sourceTotal;
skipping to change at line 293 skipping to change at line 293
#pragma mark CDSoundSource #pragma mark CDSoundSource
/** CDSoundSource is a wrapper around an OpenAL sound source. /** CDSoundSource is a wrapper around an OpenAL sound source.
It allows you to manipulate properties such as pitch, gain, pan and loopin g while the It allows you to manipulate properties such as pitch, gain, pan and loopin g while the
sound is playing. CDSoundSource is based on the old CDSourceWrapper class but with much sound is playing. CDSoundSource is based on the old CDSourceWrapper class but with much
added functionality. added functionality.
@since v1.0 @since v1.0
*/ */
@interface CDSoundSource : NSObject <CDAudioTransportProtocol, CDAudioInter ruptProtocol> { @interface CDSoundSource : NSObject <CDAudioTransportProtocol, CDAudioInter ruptProtocol> {
ALenum lastError; ALenum lastError;
@public @public
ALuint _sourceId; ALuint _sourceId;
ALuint _sourceIndex; ALuint _sourceIndex;
CDSoundEngine* _engine; CDSoundEngine* _engine;
int _soundId; int _soundId;
float _preMuteGain; float _preMuteGain;
BOOL enabled_; BOOL enabled_;
BOOL mute_; BOOL mute_;
} }
@property (readwrite, nonatomic) float pitch; @property (readwrite, nonatomic) float pitch;
@property (readwrite, nonatomic) float gain; @property (readwrite, nonatomic) float gain;
@property (readwrite, nonatomic) float pan; @property (readwrite, nonatomic) float pan;
@property (readwrite, nonatomic) BOOL looping; @property (readwrite, nonatomic) BOOL looping;
@property (readonly) BOOL isPlaying; @property (readonly) BOOL isPlaying;
@property (readwrite, nonatomic) int soundId; @property (readwrite, nonatomic) int soundId;
/** Returns the duration of the attached buffer in seconds or a negative va lue if the buffer is invalid */ /** Returns the duration of the attached buffer in seconds or a negative va lue if the buffer is invalid */
@property (readonly) float durationInSeconds; @property (readonly) float durationInSeconds;
skipping to change at line 326 skipping to change at line 326
@end @end
#pragma mark CDAudioInterruptTargetGroup #pragma mark CDAudioInterruptTargetGroup
/** Container for objects that implement audio interrupt protocol i.e. they can be muted and enabled. /** Container for objects that implement audio interrupt protocol i.e. they can be muted and enabled.
Setting mute and enabled for the group propagates to all children. Setting mute and enabled for the group propagates to all children.
Designed to be used with your CDSoundSource objects to get them to comply with global enabled and mute settings Designed to be used with your CDSoundSource objects to get them to comply with global enabled and mute settings
if that is what you want to do.*/ if that is what you want to do.*/
@interface CDAudioInterruptTargetGroup : NSObject <CDAudioInterruptProtocol > { @interface CDAudioInterruptTargetGroup : NSObject <CDAudioInterruptProtocol > {
BOOL mute_; BOOL mute_;
BOOL enabled_; BOOL enabled_;
NSMutableArray *children_; NSMutableArray *children_;
} }
-(void) addAudioInterruptTarget:(NSObject<CDAudioInterruptProtocol>*) inter ruptibleTarget; -(void) addAudioInterruptTarget:(NSObject<CDAudioInterruptProtocol>*) inter ruptibleTarget;
@end @end
#pragma mark CDAsynchBufferLoader #pragma mark CDAsynchBufferLoader
/** CDAsynchBufferLoader /** CDAsynchBufferLoader
TODO TODO
*/ */
@interface CDAsynchBufferLoader : NSOperation { @interface CDAsynchBufferLoader : NSOperation {
NSArray *_loadRequests; NSArray *_loadRequests;
CDSoundEngine *_soundEngine; CDSoundEngine *_soundEngine;
} }
-(id) init:(NSArray *)loadRequests soundEngine:(CDSoundEngine *) theSoundEn gine; -(id) init:(NSArray *)loadRequests soundEngine:(CDSoundEngine *) theSoundEn gine;
@end @end
#pragma mark CDBufferLoadRequest #pragma mark CDBufferLoadRequest
/** CDBufferLoadRequest */ /** CDBufferLoadRequest */
@interface CDBufferLoadRequest: NSObject @interface CDBufferLoadRequest: NSObject
{ {
NSString *filePath; NSString *filePath;
int soundId; int soundId;
//id loader; //id loader;
} }
@property (readonly) NSString *filePath; @property (readonly) NSString *filePath;
@property (readonly) int soundId; @property (readonly) int soundId;
- (id)init:(int) theSoundId filePath:(const NSString *) theFilePath; - (id)init:(int) theSoundId filePath:(const NSString *) theFilePath;
@end @end
/** Interpolation type */ /** Interpolation type */
typedef enum { typedef enum {
kIT_Linear, //!Straight linear interpolation fad kIT_Linear, //!Straight linear interpolation fade
e kIT_SCurve, //!S curved interpolation
kIT_SCurve, //!S curved interpolation kIT_Exponential //!Exponential interpolation
kIT_Exponential //!Exponential interpolation
} tCDInterpolationType; } tCDInterpolationType;
#pragma mark CDFloatInterpolator #pragma mark CDFloatInterpolator
@interface CDFloatInterpolator: NSObject @interface CDFloatInterpolator: NSObject
{ {
float start; float start;
float end; float end;
float lastValue; float lastValue;
tCDInterpolationType interpolationType; tCDInterpolationType interpolationType;
} }
@property (readwrite, nonatomic) float start; @property (readwrite, nonatomic) float start;
@property (readwrite, nonatomic) float end; @property (readwrite, nonatomic) float end;
@property (readwrite, nonatomic) tCDInterpolationType interpolationType; @property (readwrite, nonatomic) tCDInterpolationType interpolationType;
/** Return a value between min and max based on t which represents fraction al progress where 0 is the start /** Return a value between min and max based on t which represents fraction al progress where 0 is the start
and 1 is the end */ and 1 is the end */
-(float) interpolate:(float) t; -(float) interpolate:(float) t;
-(id) init:(tCDInterpolationType) type startVal:(float) startVal endVal:(fl oat) endVal; -(id) init:(tCDInterpolationType) type startVal:(float) startVal endVal:(fl oat) endVal;
@end @end
#pragma mark CDPropertyModifier #pragma mark CDPropertyModifier
/** Base class for classes that modify properties such as pitch, pan and ga in */ /** Base class for classes that modify properties such as pitch, pan and ga in */
@interface CDPropertyModifier: NSObject @interface CDPropertyModifier: NSObject
{ {
CDFloatInterpolator *interpolator; CDFloatInterpolator *interpolator;
float startValue; float startValue;
float endValue; float endValue;
id target; id target;
BOOL stopTargetWhenComplete; BOOL stopTargetWhenComplete;
} }
@property (readwrite, nonatomic) BOOL stopTargetWhenComplete; @property (readwrite, nonatomic) BOOL stopTargetWhenComplete;
@property (readwrite, nonatomic) float startValue; @property (readwrite, nonatomic) float startValue;
@property (readwrite, nonatomic) float endValue; @property (readwrite, nonatomic) float endValue;
@property (readwrite, nonatomic) tCDInterpolationType interpolationType; @property (readwrite, nonatomic) tCDInterpolationType interpolationType;
-(id) init:(id) theTarget interpolationType:(tCDInterpolationType) type sta rtVal:(float) startVal endVal:(float) endVal; -(id) init:(id) theTarget interpolationType:(tCDInterpolationType) type sta rtVal:(float) startVal endVal:(float) endVal;
/** Set to a fractional value between 0 and 1 where 0 equals the start and 1 equals the end*/ /** Set to a fractional value between 0 and 1 where 0 equals the start and 1 equals the end*/
-(void) modify:(float) t; -(void) modify:(float) t;
 End of changes. 13 change blocks. 
68 lines changed or deleted 66 lines changed or added


 CocosDenshionTest.h   CocosDenshionTest.h 
#ifndef __COCOS_DENSHION_TEST__ #ifndef __COCOS_DENSHION_TEST__
#define __COCOS_DENSHION_TEST__ #define __COCOS_DENSHION_TEST__
#include "../testBasic.h" #include "../testBasic.h"
class CocosDenshionTest : public CCLayer class CocosDenshionTest : public CCLayer
{ {
public: public:
CocosDenshionTest(void); CocosDenshionTest(void);
~CocosDenshionTest(void); ~CocosDenshionTest(void);
void menuCallback(CCObject * pSender); void menuCallback(CCObject * pSender);
virtual void ccTouchesMoved(CCSet *pTouches, CCEvent *pEvent); virtual void ccTouchesMoved(CCSet *pTouches, CCEvent *pEvent);
virtual void ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent); virtual void ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent);
virtual void onExit(); virtual void onExit();
private: private:
CCMenu* m_pItmeMenu; CCMenu* m_pItmeMenu;
CCPoint m_tBeginPos; CCPoint m_tBeginPos;
int m_nTestCount; int m_nTestCount;
unsigned int m_nSoundId; unsigned int m_nSoundId;
}; };
class CocosDenshionTestScene : public TestScene class CocosDenshionTestScene : public TestScene
{ {
public: public:
virtual void runThisTest(); virtual void runThisTest();
}; };
#endif //__COCOS_DENSHION_TEST__ #endif //__COCOS_DENSHION_TEST__
 End of changes. 4 change blocks. 
11 lines changed or deleted 11 lines changed or added


 CollisionFiltering.h   CollisionFiltering.h 
skipping to change at line 28 skipping to change at line 28
#ifndef COLLISION_FILTERING_H #ifndef COLLISION_FILTERING_H
#define COLLISION_FILTERING_H #define COLLISION_FILTERING_H
// This is a test of collision filtering. // This is a test of collision filtering.
// There is a triangle, a box, and a circle. // There is a triangle, a box, and a circle.
// There are 6 shapes. 3 large and 3 small. // There are 6 shapes. 3 large and 3 small.
// The 3 small ones always collide. // The 3 small ones always collide.
// The 3 large ones never collide. // The 3 large ones never collide.
// The boxes don't collide with triangles (except if both are small). // The boxes don't collide with triangles (except if both are small).
const int16 k_smallGroup = 1; const int16 k_smallGroup = 1;
const int16 k_largeGroup = -1; const int16 k_largeGroup = -1;
const uint16 k_defaultCategory = 0x0001; const uint16 k_defaultCategory = 0x0001;
const uint16 k_triangleCategory = 0x0002; const uint16 k_triangleCategory = 0x0002;
const uint16 k_boxCategory = 0x0004; const uint16 k_boxCategory = 0x0004;
const uint16 k_circleCategory = 0x0008; const uint16 k_circleCategory = 0x0008;
const uint16 k_triangleMask = 0xFFFF; const uint16 k_triangleMask = 0xFFFF;
const uint16 k_boxMask = 0xFFFF ^ k_triangleCategory; const uint16 k_boxMask = 0xFFFF ^ k_triangleCategory;
const uint16 k_circleMask = 0xFFFF; const uint16 k_circleMask = 0xFFFF;
class CollisionFiltering : public Test class CollisionFiltering : public Test
{ {
public: public:
CollisionFiltering() CollisionFiltering()
{ {
// Ground body // Ground body
{ {
b2EdgeShape shape; b2EdgeShape shape;
shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)) shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f));
;
b2FixtureDef sd;
b2FixtureDef sd; sd.shape = &shape;
sd.shape = &shape; sd.friction = 0.3f;
sd.friction = 0.3f;
b2BodyDef bd;
b2BodyDef bd; b2Body* ground = m_world->CreateBody(&bd);
b2Body* ground = m_world->CreateBody(&bd); ground->CreateFixture(&sd);
ground->CreateFixture(&sd); }
}
// Small triangle
// Small triangle b2Vec2 vertices[3];
b2Vec2 vertices[3]; vertices[0].Set(-1.0f, 0.0f);
vertices[0].Set(-1.0f, 0.0f); vertices[1].Set(1.0f, 0.0f);
vertices[1].Set(1.0f, 0.0f); vertices[2].Set(0.0f, 2.0f);
vertices[2].Set(0.0f, 2.0f); b2PolygonShape polygon;
b2PolygonShape polygon; polygon.Set(vertices, 3);
polygon.Set(vertices, 3);
b2FixtureDef triangleShapeDef;
b2FixtureDef triangleShapeDef; triangleShapeDef.shape = &polygon;
triangleShapeDef.shape = &polygon; triangleShapeDef.density = 1.0f;
triangleShapeDef.density = 1.0f;
triangleShapeDef.filter.groupIndex = k_smallGroup;
triangleShapeDef.filter.groupIndex = k_smallGroup; triangleShapeDef.filter.categoryBits = k_triangleCategory;
triangleShapeDef.filter.categoryBits = k_triangleCategory; triangleShapeDef.filter.maskBits = k_triangleMask;
triangleShapeDef.filter.maskBits = k_triangleMask;
b2BodyDef triangleBodyDef;
b2BodyDef triangleBodyDef; triangleBodyDef.type = b2_dynamicBody;
triangleBodyDef.type = b2_dynamicBody; triangleBodyDef.position.Set(-5.0f, 2.0f);
triangleBodyDef.position.Set(-5.0f, 2.0f);
b2Body* body1 = m_world->CreateBody(&triangleBodyDef);
b2Body* body1 = m_world->CreateBody(&triangleBodyDef); body1->CreateFixture(&triangleShapeDef);
body1->CreateFixture(&triangleShapeDef);
// Large triangle (recycle definitions)
// Large triangle (recycle definitions) vertices[0] *= 2.0f;
vertices[0] *= 2.0f; vertices[1] *= 2.0f;
vertices[1] *= 2.0f; vertices[2] *= 2.0f;
vertices[2] *= 2.0f; polygon.Set(vertices, 3);
polygon.Set(vertices, 3); triangleShapeDef.filter.groupIndex = k_largeGroup;
triangleShapeDef.filter.groupIndex = k_largeGroup; triangleBodyDef.position.Set(-5.0f, 6.0f);
triangleBodyDef.position.Set(-5.0f, 6.0f); triangleBodyDef.fixedRotation = true; // look at me!
triangleBodyDef.fixedRotation = true; // look at me!
b2Body* body2 = m_world->CreateBody(&triangleBodyDef);
b2Body* body2 = m_world->CreateBody(&triangleBodyDef); body2->CreateFixture(&triangleShapeDef);
body2->CreateFixture(&triangleShapeDef);
{
{ b2BodyDef bd;
b2BodyDef bd; bd.type = b2_dynamicBody;
bd.type = b2_dynamicBody; bd.position.Set(-5.0f, 10.0f);
bd.position.Set(-5.0f, 10.0f); b2Body* body = m_world->CreateBody(&bd);
b2Body* body = m_world->CreateBody(&bd);
b2PolygonShape p;
b2PolygonShape p; p.SetAsBox(0.5f, 1.0f);
p.SetAsBox(0.5f, 1.0f); body->CreateFixture(&p, 1.0f);
body->CreateFixture(&p, 1.0f);
b2PrismaticJointDef jd;
b2PrismaticJointDef jd; jd.bodyA = body2;
jd.bodyA = body2; jd.bodyB = body;
jd.bodyB = body; jd.enableLimit = true;
jd.enableLimit = true; jd.localAnchorA.Set(0.0f, 4.0f);
jd.localAnchorA.Set(0.0f, 4.0f); jd.localAnchorB.SetZero();
jd.localAnchorB.SetZero(); jd.localAxisA.Set(0.0f, 1.0f);
jd.localAxisA.Set(0.0f, 1.0f); jd.lowerTranslation = -1.0f;
jd.lowerTranslation = -1.0f; jd.upperTranslation = 1.0f;
jd.upperTranslation = 1.0f;
m_world->CreateJoint(&jd);
m_world->CreateJoint(&jd); }
}
// Small box
// Small box polygon.SetAsBox(1.0f, 0.5f);
polygon.SetAsBox(1.0f, 0.5f); b2FixtureDef boxShapeDef;
b2FixtureDef boxShapeDef; boxShapeDef.shape = &polygon;
boxShapeDef.shape = &polygon; boxShapeDef.density = 1.0f;
boxShapeDef.density = 1.0f; boxShapeDef.restitution = 0.1f;
boxShapeDef.restitution = 0.1f;
boxShapeDef.filter.groupIndex = k_smallGroup;
boxShapeDef.filter.groupIndex = k_smallGroup; boxShapeDef.filter.categoryBits = k_boxCategory;
boxShapeDef.filter.categoryBits = k_boxCategory; boxShapeDef.filter.maskBits = k_boxMask;
boxShapeDef.filter.maskBits = k_boxMask;
b2BodyDef boxBodyDef;
b2BodyDef boxBodyDef; boxBodyDef.type = b2_dynamicBody;
boxBodyDef.type = b2_dynamicBody; boxBodyDef.position.Set(0.0f, 2.0f);
boxBodyDef.position.Set(0.0f, 2.0f);
b2Body* body3 = m_world->CreateBody(&boxBodyDef);
b2Body* body3 = m_world->CreateBody(&boxBodyDef); body3->CreateFixture(&boxShapeDef);
body3->CreateFixture(&boxShapeDef);
// Large box (recycle definitions)
// Large box (recycle definitions) polygon.SetAsBox(2.0f, 1.0f);
polygon.SetAsBox(2.0f, 1.0f); boxShapeDef.filter.groupIndex = k_largeGroup;
boxShapeDef.filter.groupIndex = k_largeGroup; boxBodyDef.position.Set(0.0f, 6.0f);
boxBodyDef.position.Set(0.0f, 6.0f);
b2Body* body4 = m_world->CreateBody(&boxBodyDef);
b2Body* body4 = m_world->CreateBody(&boxBodyDef); body4->CreateFixture(&boxShapeDef);
body4->CreateFixture(&boxShapeDef);
// Small circle
// Small circle b2CircleShape circle;
b2CircleShape circle; circle.m_radius = 1.0f;
circle.m_radius = 1.0f;
b2FixtureDef circleShapeDef;
b2FixtureDef circleShapeDef; circleShapeDef.shape = &circle;
circleShapeDef.shape = &circle; circleShapeDef.density = 1.0f;
circleShapeDef.density = 1.0f;
circleShapeDef.filter.groupIndex = k_smallGroup;
circleShapeDef.filter.groupIndex = k_smallGroup; circleShapeDef.filter.categoryBits = k_circleCategory;
circleShapeDef.filter.categoryBits = k_circleCategory; circleShapeDef.filter.maskBits = k_circleMask;
circleShapeDef.filter.maskBits = k_circleMask;
b2BodyDef circleBodyDef;
b2BodyDef circleBodyDef; circleBodyDef.type = b2_dynamicBody;
circleBodyDef.type = b2_dynamicBody; circleBodyDef.position.Set(5.0f, 2.0f);
circleBodyDef.position.Set(5.0f, 2.0f);
b2Body* body5 = m_world->CreateBody(&circleBodyDef);
b2Body* body5 = m_world->CreateBody(&circleBodyDef); body5->CreateFixture(&circleShapeDef);
body5->CreateFixture(&circleShapeDef);
// Large circle
// Large circle circle.m_radius *= 2.0f;
circle.m_radius *= 2.0f; circleShapeDef.filter.groupIndex = k_largeGroup;
circleShapeDef.filter.groupIndex = k_largeGroup; circleBodyDef.position.Set(5.0f, 6.0f);
circleBodyDef.position.Set(5.0f, 6.0f);
b2Body* body6 = m_world->CreateBody(&circleBodyDef);
b2Body* body6 = m_world->CreateBody(&circleBodyDef); body6->CreateFixture(&circleShapeDef);
body6->CreateFixture(&circleShapeDef); }
} static Test* Create()
static Test* Create() {
{ return new CollisionFiltering;
return new CollisionFiltering; }
}
}; };
#endif #endif
 End of changes. 2 change blocks. 
133 lines changed or deleted 132 lines changed or added


 CollisionProcessing.h   CollisionProcessing.h 
skipping to change at line 29 skipping to change at line 29
#ifndef COLLISION_PROCESSING_H #ifndef COLLISION_PROCESSING_H
#define COLLISION_PROCESSING_H #define COLLISION_PROCESSING_H
#include <algorithm> #include <algorithm>
// This test shows collision processing and tests // This test shows collision processing and tests
// deferred body destruction. // deferred body destruction.
class CollisionProcessing : public Test class CollisionProcessing : public Test
{ {
public: public:
CollisionProcessing() CollisionProcessing()
{ {
// Ground body // Ground body
{ {
b2EdgeShape shape; b2EdgeShape shape;
shape.Set(b2Vec2(-50.0f, 0.0f), b2Vec2(50.0f, 0.0f)) shape.Set(b2Vec2(-50.0f, 0.0f), b2Vec2(50.0f, 0.0f));
;
b2FixtureDef sd;
b2FixtureDef sd; sd.shape = &shape;;
sd.shape = &shape;;
b2BodyDef bd;
b2BodyDef bd; b2Body* ground = m_world->CreateBody(&bd);
b2Body* ground = m_world->CreateBody(&bd); ground->CreateFixture(&sd);
ground->CreateFixture(&sd); }
}
float32 xLo = -5.0f, xHi = 5.0f;
float32 xLo = -5.0f, xHi = 5.0f; float32 yLo = 2.0f, yHi = 35.0f;
float32 yLo = 2.0f, yHi = 35.0f;
// Small triangle
// Small triangle b2Vec2 vertices[3];
b2Vec2 vertices[3]; vertices[0].Set(-1.0f, 0.0f);
vertices[0].Set(-1.0f, 0.0f); vertices[1].Set(1.0f, 0.0f);
vertices[1].Set(1.0f, 0.0f); vertices[2].Set(0.0f, 2.0f);
vertices[2].Set(0.0f, 2.0f);
b2PolygonShape polygon;
b2PolygonShape polygon; polygon.Set(vertices, 3);
polygon.Set(vertices, 3);
b2FixtureDef triangleShapeDef;
b2FixtureDef triangleShapeDef; triangleShapeDef.shape = &polygon;
triangleShapeDef.shape = &polygon; triangleShapeDef.density = 1.0f;
triangleShapeDef.density = 1.0f;
b2BodyDef triangleBodyDef;
b2BodyDef triangleBodyDef; triangleBodyDef.type = b2_dynamicBody;
triangleBodyDef.type = b2_dynamicBody; triangleBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloat(yLo
triangleBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFl , yHi));
oat(yLo, yHi));
b2Body* body1 = m_world->CreateBody(&triangleBodyDef);
b2Body* body1 = m_world->CreateBody(&triangleBodyDef); body1->CreateFixture(&triangleShapeDef);
body1->CreateFixture(&triangleShapeDef);
// Large triangle (recycle definitions)
// Large triangle (recycle definitions) vertices[0] *= 2.0f;
vertices[0] *= 2.0f; vertices[1] *= 2.0f;
vertices[1] *= 2.0f; vertices[2] *= 2.0f;
vertices[2] *= 2.0f; polygon.Set(vertices, 3);
polygon.Set(vertices, 3);
triangleBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloat(yLo
triangleBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFl , yHi));
oat(yLo, yHi));
b2Body* body2 = m_world->CreateBody(&triangleBodyDef);
b2Body* body2 = m_world->CreateBody(&triangleBodyDef); body2->CreateFixture(&triangleShapeDef);
body2->CreateFixture(&triangleShapeDef);
// Small box
// Small box polygon.SetAsBox(1.0f, 0.5f);
polygon.SetAsBox(1.0f, 0.5f);
b2FixtureDef boxShapeDef;
b2FixtureDef boxShapeDef; boxShapeDef.shape = &polygon;
boxShapeDef.shape = &polygon; boxShapeDef.density = 1.0f;
boxShapeDef.density = 1.0f;
b2BodyDef boxBodyDef;
b2BodyDef boxBodyDef; boxBodyDef.type = b2_dynamicBody;
boxBodyDef.type = b2_dynamicBody; boxBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloat(yLo, yHi
boxBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloat(y ));
Lo, yHi));
b2Body* body3 = m_world->CreateBody(&boxBodyDef);
b2Body* body3 = m_world->CreateBody(&boxBodyDef); body3->CreateFixture(&boxShapeDef);
body3->CreateFixture(&boxShapeDef);
// Large box (recycle definitions)
// Large box (recycle definitions) polygon.SetAsBox(2.0f, 1.0f);
polygon.SetAsBox(2.0f, 1.0f); boxBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloat(yLo, yHi
boxBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloat(y ));
Lo, yHi));
b2Body* body4 = m_world->CreateBody(&boxBodyDef);
b2Body* body4 = m_world->CreateBody(&boxBodyDef); body4->CreateFixture(&boxShapeDef);
body4->CreateFixture(&boxShapeDef);
// Small circle
// Small circle b2CircleShape circle;
b2CircleShape circle; circle.m_radius = 1.0f;
circle.m_radius = 1.0f;
b2FixtureDef circleShapeDef;
b2FixtureDef circleShapeDef; circleShapeDef.shape = &circle;
circleShapeDef.shape = &circle; circleShapeDef.density = 1.0f;
circleShapeDef.density = 1.0f;
b2BodyDef circleBodyDef;
b2BodyDef circleBodyDef; circleBodyDef.type = b2_dynamicBody;
circleBodyDef.type = b2_dynamicBody; circleBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloat(yLo,
circleBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloa yHi));
t(yLo, yHi));
b2Body* body5 = m_world->CreateBody(&circleBodyDef);
b2Body* body5 = m_world->CreateBody(&circleBodyDef); body5->CreateFixture(&circleShapeDef);
body5->CreateFixture(&circleShapeDef);
// Large circle
// Large circle circle.m_radius *= 2.0f;
circle.m_radius *= 2.0f; circleBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloat(yLo,
circleBodyDef.position.Set(RandomFloat(xLo, xHi), RandomFloa yHi));
t(yLo, yHi));
b2Body* body6 = m_world->CreateBody(&circleBodyDef);
b2Body* body6 = m_world->CreateBody(&circleBodyDef); body6->CreateFixture(&circleShapeDef);
body6->CreateFixture(&circleShapeDef); }
}
void Step(Settings* settings)
void Step(Settings* settings) {
{ Test::Step(settings);
Test::Step(settings);
// We are going to destroy some bodies according to contact
// We are going to destroy some bodies according to contact // points. We must buffer the bodies that should be destroyed
// points. We must buffer the bodies that should be destroye // because they may belong to multiple contact points.
d const int32 k_maxNuke = 6;
// because they may belong to multiple contact points. b2Body* nuke[k_maxNuke];
const int32 k_maxNuke = 6; int32 nukeCount = 0;
b2Body* nuke[k_maxNuke];
int32 nukeCount = 0; // Traverse the contact results. Destroy bodies that
// are touching heavier bodies.
// Traverse the contact results. Destroy bodies that for (int32 i = 0; i < m_pointCount; ++i)
// are touching heavier bodies. {
for (int32 i = 0; i < m_pointCount; ++i) ContactPoint* point = m_points + i;
{
ContactPoint* point = m_points + i; b2Body* body1 = point->fixtureA->GetBody();
b2Body* body2 = point->fixtureB->GetBody();
b2Body* body1 = point->fixtureA->GetBody(); float32 mass1 = body1->GetMass();
b2Body* body2 = point->fixtureB->GetBody(); float32 mass2 = body2->GetMass();
float32 mass1 = body1->GetMass();
float32 mass2 = body2->GetMass(); if (mass1 > 0.0f && mass2 > 0.0f)
{
if (mass1 > 0.0f && mass2 > 0.0f) if (mass2 > mass1)
{ {
if (mass2 > mass1) nuke[nukeCount++] = body1;
{ }
nuke[nukeCount++] = body1; else
} {
else nuke[nukeCount++] = body2;
{ }
nuke[nukeCount++] = body2;
} if (nukeCount == k_maxNuke)
{
if (nukeCount == k_maxNuke) break;
{ }
break; }
} }
}
} // Sort the nuke array to group duplicates.
std::sort(nuke, nuke + nukeCount);
// Sort the nuke array to group duplicates.
std::sort(nuke, nuke + nukeCount); // Destroy the bodies, skipping duplicates.
int32 i = 0;
// Destroy the bodies, skipping duplicates. while (i < nukeCount)
int32 i = 0; {
while (i < nukeCount) b2Body* b = nuke[i++];
{ while (i < nukeCount && nuke[i] == b)
b2Body* b = nuke[i++]; {
while (i < nukeCount && nuke[i] == b) ++i;
{ }
++i;
} if (b != m_bomb)
{
if (b != m_bomb) m_world->DestroyBody(b);
{ }
m_world->DestroyBody(b); }
} }
}
} static Test* Create()
{
static Test* Create() return new CollisionProcessing;
{ }
return new CollisionProcessing;
}
}; };
#endif #endif
 End of changes. 1 change blocks. 
165 lines changed or deleted 163 lines changed or added


 CompoundShapes.h   CompoundShapes.h 
skipping to change at line 26 skipping to change at line 26
* 3. This notice may not be removed or altered from any source distribution . * 3. This notice may not be removed or altered from any source distribution .
*/ */
#ifndef COMPOUND_SHAPES_H #ifndef COMPOUND_SHAPES_H
#define COMPOUND_SHAPES_H #define COMPOUND_SHAPES_H
// TODO_ERIN test joints on compounds. // TODO_ERIN test joints on compounds.
class CompoundShapes : public Test class CompoundShapes : public Test
{ {
public: public:
CompoundShapes() CompoundShapes()
{ {
{ {
b2BodyDef bd; b2BodyDef bd;
bd.position.Set(0.0f, 0.0f); bd.position.Set(0.0f, 0.0f);
b2Body* body = m_world->CreateBody(&bd); b2Body* body = m_world->CreateBody(&bd);
b2EdgeShape shape; b2EdgeShape shape;
shape.Set(b2Vec2(50.0f, 0.0f), b2Vec2(-50.0f, 0.0f)) shape.Set(b2Vec2(50.0f, 0.0f), b2Vec2(-50.0f, 0.0f));
;
body->CreateFixture(&shape, 0.0f);
body->CreateFixture(&shape, 0.0f); }
}
{
{ b2CircleShape circle1;
b2CircleShape circle1; circle1.m_radius = 0.5f;
circle1.m_radius = 0.5f; circle1.m_p.Set(-0.5f, 0.5f);
circle1.m_p.Set(-0.5f, 0.5f);
b2CircleShape circle2;
b2CircleShape circle2; circle2.m_radius = 0.5f;
circle2.m_radius = 0.5f; circle2.m_p.Set(0.5f, 0.5f);
circle2.m_p.Set(0.5f, 0.5f);
for (int i = 0; i < 10; ++i)
for (int i = 0; i < 10; ++i) {
{ float32 x = RandomFloat(-0.1f, 0.1f);
float32 x = RandomFloat(-0.1f, 0.1f); b2BodyDef bd;
b2BodyDef bd; bd.type = b2_dynamicBody;
bd.type = b2_dynamicBody; bd.position.Set(x + 5.0f, 1.05f + 2.5f * i);
bd.position.Set(x + 5.0f, 1.05f + 2.5f * i); bd.angle = RandomFloat(-b2_pi, b2_pi);
bd.angle = RandomFloat(-b2_pi, b2_pi); b2Body* body = m_world->CreateBody(&bd);
b2Body* body = m_world->CreateBody(&bd); body->CreateFixture(&circle1, 2.0f);
body->CreateFixture(&circle1, 2.0f); body->CreateFixture(&circle2, 0.0f);
body->CreateFixture(&circle2, 0.0f); }
} }
}
{
{ b2PolygonShape polygon1;
b2PolygonShape polygon1; polygon1.SetAsBox(0.25f, 0.5f);
polygon1.SetAsBox(0.25f, 0.5f);
b2PolygonShape polygon2;
b2PolygonShape polygon2; polygon2.SetAsBox(0.25f, 0.5f, b2Vec2(0.0f, -0.5f), 0.5f * b2_p
polygon2.SetAsBox(0.25f, 0.5f, b2Vec2(0.0f, -0.5f), i);
0.5f * b2_pi);
for (int i = 0; i < 10; ++i)
for (int i = 0; i < 10; ++i) {
{ float32 x = RandomFloat(-0.1f, 0.1f);
float32 x = RandomFloat(-0.1f, 0.1f); b2BodyDef bd;
b2BodyDef bd; bd.type = b2_dynamicBody;
bd.type = b2_dynamicBody; bd.position.Set(x - 5.0f, 1.05f + 2.5f * i);
bd.position.Set(x - 5.0f, 1.05f + 2.5f * i); bd.angle = RandomFloat(-b2_pi, b2_pi);
bd.angle = RandomFloat(-b2_pi, b2_pi); b2Body* body = m_world->CreateBody(&bd);
b2Body* body = m_world->CreateBody(&bd); body->CreateFixture(&polygon1, 2.0f);
body->CreateFixture(&polygon1, 2.0f); body->CreateFixture(&polygon2, 2.0f);
body->CreateFixture(&polygon2, 2.0f); }
} }
}
{
{ b2Transform xf1;
b2Transform xf1; xf1.q.Set(0.3524f * b2_pi);
xf1.q.Set(0.3524f * b2_pi); xf1.p = xf1.q.GetXAxis();
xf1.p = xf1.q.GetXAxis();
b2Vec2 vertices[3];
b2Vec2 vertices[3];
b2PolygonShape triangle1;
b2PolygonShape triangle1; vertices[0] = b2Mul(xf1, b2Vec2(-1.0f, 0.0f));
vertices[0] = b2Mul(xf1, b2Vec2(-1.0f, 0.0f)); vertices[1] = b2Mul(xf1, b2Vec2(1.0f, 0.0f));
vertices[1] = b2Mul(xf1, b2Vec2(1.0f, 0.0f)); vertices[2] = b2Mul(xf1, b2Vec2(0.0f, 0.5f));
vertices[2] = b2Mul(xf1, b2Vec2(0.0f, 0.5f)); triangle1.Set(vertices, 3);
triangle1.Set(vertices, 3);
b2Transform xf2;
b2Transform xf2; xf2.q.Set(-0.3524f * b2_pi);
xf2.q.Set(-0.3524f * b2_pi); xf2.p = -xf2.q.GetXAxis();
xf2.p = -xf2.q.GetXAxis();
b2PolygonShape triangle2;
b2PolygonShape triangle2; vertices[0] = b2Mul(xf2, b2Vec2(-1.0f, 0.0f));
vertices[0] = b2Mul(xf2, b2Vec2(-1.0f, 0.0f)); vertices[1] = b2Mul(xf2, b2Vec2(1.0f, 0.0f));
vertices[1] = b2Mul(xf2, b2Vec2(1.0f, 0.0f)); vertices[2] = b2Mul(xf2, b2Vec2(0.0f, 0.5f));
vertices[2] = b2Mul(xf2, b2Vec2(0.0f, 0.5f)); triangle2.Set(vertices, 3);
triangle2.Set(vertices, 3);
for (int32 i = 0; i < 10; ++i)
for (int32 i = 0; i < 10; ++i) {
{ float32 x = RandomFloat(-0.1f, 0.1f);
float32 x = RandomFloat(-0.1f, 0.1f); b2BodyDef bd;
b2BodyDef bd; bd.type = b2_dynamicBody;
bd.type = b2_dynamicBody; bd.position.Set(x, 2.05f + 2.5f * i);
bd.position.Set(x, 2.05f + 2.5f * i); bd.angle = 0.0f;
bd.angle = 0.0f; b2Body* body = m_world->CreateBody(&bd);
b2Body* body = m_world->CreateBody(&bd); body->CreateFixture(&triangle1, 2.0f);
body->CreateFixture(&triangle1, 2.0f); body->CreateFixture(&triangle2, 2.0f);
body->CreateFixture(&triangle2, 2.0f); }
} }
}
{
{ b2PolygonShape bottom;
b2PolygonShape bottom; bottom.SetAsBox( 1.5f, 0.15f );
bottom.SetAsBox( 1.5f, 0.15f );
b2PolygonShape left;
b2PolygonShape left; left.SetAsBox(0.15f, 2.7f, b2Vec2(-1.45f, 2.35f), 0.2f);
left.SetAsBox(0.15f, 2.7f, b2Vec2(-1.45f, 2.35f), 0.
2f); b2PolygonShape right;
right.SetAsBox(0.15f, 2.7f, b2Vec2(1.45f, 2.35f), -0.2f);
b2PolygonShape right;
right.SetAsBox(0.15f, 2.7f, b2Vec2(1.45f, 2.35f), -0 b2BodyDef bd;
.2f); bd.type = b2_dynamicBody;
bd.position.Set( 0.0f, 2.0f );
b2BodyDef bd; b2Body* body = m_world->CreateBody(&bd);
bd.type = b2_dynamicBody; body->CreateFixture(&bottom, 4.0f);
bd.position.Set( 0.0f, 2.0f ); body->CreateFixture(&left, 4.0f);
b2Body* body = m_world->CreateBody(&bd); body->CreateFixture(&right, 4.0f);
body->CreateFixture(&bottom, 4.0f); }
body->CreateFixture(&left, 4.0f); }
body->CreateFixture(&right, 4.0f);
} static Test* Create()
} {
return new CompoundShapes;
static Test* Create() }
{
return new CompoundShapes;
}
}; };
#endif #endif
 End of changes. 1 change blocks. 
119 lines changed or deleted 116 lines changed or added


 Confined.h   Confined.h 
skipping to change at line 26 skipping to change at line 26
* 3. This notice may not be removed or altered from any source distribution . * 3. This notice may not be removed or altered from any source distribution .
*/ */
#ifndef CONFINED_H #ifndef CONFINED_H
#define CONFINED_H #define CONFINED_H
class Confined : public Test class Confined : public Test
{ {
public: public:
enum enum
{ {
e_columnCount = 0, e_columnCount = 0,
e_rowCount = 0 e_rowCount = 0
}; };
Confined() Confined()
{ {
{ {
b2BodyDef bd; b2BodyDef bd;
b2Body* ground = m_world->CreateBody(&bd); b2Body* ground = m_world->CreateBody(&bd);
b2EdgeShape shape; b2EdgeShape shape;
// Floor // Floor
shape.Set(b2Vec2(-10.0f, 0.0f), b2Vec2(10.0f, 0.0f)) shape.Set(b2Vec2(-10.0f, 0.0f), b2Vec2(10.0f, 0.0f));
; ground->CreateFixture(&shape, 0.0f);
ground->CreateFixture(&shape, 0.0f);
// Left wall
// Left wall shape.Set(b2Vec2(-10.0f, 0.0f), b2Vec2(-10.0f, 20.0f));
shape.Set(b2Vec2(-10.0f, 0.0f), b2Vec2(-10.0f, 20.0f ground->CreateFixture(&shape, 0.0f);
));
ground->CreateFixture(&shape, 0.0f); // Right wall
shape.Set(b2Vec2(10.0f, 0.0f), b2Vec2(10.0f, 20.0f));
// Right wall ground->CreateFixture(&shape, 0.0f);
shape.Set(b2Vec2(10.0f, 0.0f), b2Vec2(10.0f, 20.0f))
; // Roof
ground->CreateFixture(&shape, 0.0f); shape.Set(b2Vec2(-10.0f, 20.0f), b2Vec2(10.0f, 20.0f));
ground->CreateFixture(&shape, 0.0f);
// Roof }
shape.Set(b2Vec2(-10.0f, 20.0f), b2Vec2(10.0f, 20.0f
)); float32 radius = 0.5f;
ground->CreateFixture(&shape, 0.0f); b2CircleShape shape;
} shape.m_p.SetZero();
shape.m_radius = radius;
float32 radius = 0.5f;
b2CircleShape shape; b2FixtureDef fd;
shape.m_p.SetZero(); fd.shape = &shape;
shape.m_radius = radius; fd.density = 1.0f;
fd.friction = 0.1f;
b2FixtureDef fd;
fd.shape = &shape; for (int32 j = 0; j < e_columnCount; ++j)
fd.density = 1.0f; {
fd.friction = 0.1f; for (int i = 0; i < e_rowCount; ++i)
{
for (int32 j = 0; j < e_columnCount; ++j) b2BodyDef bd;
{ bd.type = b2_dynamicBody;
for (int i = 0; i < e_rowCount; ++i) bd.position.Set(-10.0f + (2.1f * j + 1.0f + 0.01f * i) * ra
{ dius, (2.0f * i + 1.0f) * radius);
b2BodyDef bd; b2Body* body = m_world->CreateBody(&bd);
bd.type = b2_dynamicBody;
bd.position.Set(-10.0f + (2.1f * j + 1.0f + body->CreateFixture(&fd);
0.01f * i) * radius, (2.0f * i + 1.0f) * radius); }
b2Body* body = m_world->CreateBody(&bd); }
body->CreateFixture(&fd); m_world->SetGravity(b2Vec2(0.0f, 0.0f));
} }
}
void CreateCircle()
m_world->SetGravity(b2Vec2(0.0f, 0.0f)); {
} float32 radius = 2.0f;
b2CircleShape shape;
void CreateCircle() shape.m_p.SetZero();
{ shape.m_radius = radius;
float32 radius = 2.0f;
b2CircleShape shape; b2FixtureDef fd;
shape.m_p.SetZero(); fd.shape = &shape;
shape.m_radius = radius; fd.density = 1.0f;
fd.friction = 0.0f;
b2FixtureDef fd;
fd.shape = &shape; b2Vec2 p(RandomFloat(), 3.0f + RandomFloat());
fd.density = 1.0f; b2BodyDef bd;
fd.friction = 0.0f; bd.type = b2_dynamicBody;
bd.position = p;
b2Vec2 p(RandomFloat(), 3.0f + RandomFloat()); //bd.allowSleep = false;
b2BodyDef bd; b2Body* body = m_world->CreateBody(&bd);
bd.type = b2_dynamicBody;
bd.position = p; body->CreateFixture(&fd);
//bd.allowSleep = false; }
b2Body* body = m_world->CreateBody(&bd);
void Keyboard(unsigned char key)
body->CreateFixture(&fd); {
} switch (key)
{
void Keyboard(unsigned char key) case 'c':
{ CreateCircle();
switch (key) break;
{ }
case 'c': }
CreateCircle();
break; void Step(Settings* settings)
} {
} bool sleeping = true;
for (b2Body* b = m_world->GetBodyList(); b; b = b->GetNext())
void Step(Settings* settings) {
{ if (b->GetType() != b2_dynamicBody)
bool sleeping = true; {
for (b2Body* b = m_world->GetBodyList(); b; b = b->GetNext() continue;
) }
{
if (b->GetType() != b2_dynamicBody) if (b->IsAwake())
{ {
continue; sleeping = false;
} }
}
if (b->IsAwake())
{ if (m_stepCount == 180)
sleeping = false; {
} m_stepCount += 0;
} }
if (m_stepCount == 180) //if (sleeping)
{ //{
m_stepCount += 0; // CreateCircle();
} //}
//if (sleeping) Test::Step(settings);
//{
// CreateCircle(); for (b2Body* b = m_world->GetBodyList(); b; b = b->GetNext())
//} {
if (b->GetType() != b2_dynamicBody)
Test::Step(settings); {
continue;
for (b2Body* b = m_world->GetBodyList(); b; b = b->GetNext() }
)
{ b2Vec2 p = b->GetPosition();
if (b->GetType() != b2_dynamicBody) if (p.x <= -10.0f || 10.0f <= p.x || p.y <= 0.0f || 20.0f <= p.
{ y)
continue; {
} p.x += 0.0;
}
b2Vec2 p = b->GetPosition(); }
if (p.x <= -10.0f || 10.0f <= p.x || p.y <= 0.0f ||
20.0f <= p.y) m_debugDraw.DrawString(5, m_textLine, "Press 'c' to create a circle
{ .");
p.x += 0.0; m_textLine += 15;
} }
}
static Test* Create()
m_debugDraw.DrawString(5, m_textLine, "Press 'c' to create a {
circle."); return new Confined;
m_textLine += 15; }
}
static Test* Create()
{
return new Confined;
}
}; };
#endif #endif
 End of changes. 1 change blocks. 
148 lines changed or deleted 142 lines changed or added


 ContinuousTest.h   ContinuousTest.h 
skipping to change at line 26 skipping to change at line 26
* 3. This notice may not be removed or altered from any source distribution . * 3. This notice may not be removed or altered from any source distribution .
*/ */
#ifndef CONTINUOUS_TEST_H #ifndef CONTINUOUS_TEST_H
#define CONTINUOUS_TEST_H #define CONTINUOUS_TEST_H
class ContinuousTest : public Test class ContinuousTest : public Test
{ {
public: public:
ContinuousTest() ContinuousTest()
{ {
{ {
b2BodyDef bd; b2BodyDef bd;
bd.position.Set(0.0f, 0.0f); bd.position.Set(0.0f, 0.0f);
b2Body* body = m_world->CreateBody(&bd); b2Body* body = m_world->CreateBody(&bd);
b2EdgeShape edge; b2EdgeShape edge;
edge.Set(b2Vec2(-10.0f, 0.0f), b2Vec2(10.0f, 0.0f)); edge.Set(b2Vec2(-10.0f, 0.0f), b2Vec2(10.0f, 0.0f));
body->CreateFixture(&edge, 0.0f); body->CreateFixture(&edge, 0.0f);
b2PolygonShape shape; b2PolygonShape shape;
shape.SetAsBox(0.2f, 1.0f, b2Vec2(0.5f, 1.0f), 0.0f) shape.SetAsBox(0.2f, 1.0f, b2Vec2(0.5f, 1.0f), 0.0f);
; body->CreateFixture(&shape, 0.0f);
body->CreateFixture(&shape, 0.0f); }
}
#if 1 #if 1
{ {
b2BodyDef bd; b2BodyDef bd;
bd.type = b2_dynamicBody; bd.type = b2_dynamicBody;
bd.position.Set(0.0f, 20.0f); bd.position.Set(0.0f, 20.0f);
//bd.angle = 0.1f; //bd.angle = 0.1f;
b2PolygonShape shape; b2PolygonShape shape;
shape.SetAsBox(2.0f, 0.1f); shape.SetAsBox(2.0f, 0.1f);
m_body = m_world->CreateBody(&bd); m_body = m_world->CreateBody(&bd);
m_body->CreateFixture(&shape, 1.0f); m_body->CreateFixture(&shape, 1.0f);
m_angularVelocity = RandomFloat(-50.0f, 50.0f); m_angularVelocity = RandomFloat(-50.0f, 50.0f);
//m_angularVelocity = 46.661274f; //m_angularVelocity = 46.661274f;
m_body->SetLinearVelocity(b2Vec2(0.0f, -100.0f)); m_body->SetLinearVelocity(b2Vec2(0.0f, -100.0f));
m_body->SetAngularVelocity(m_angularVelocity); m_body->SetAngularVelocity(m_angularVelocity);
} }
#else #else
{ {
b2BodyDef bd; b2BodyDef bd;
bd.type = b2_dynamicBody; bd.type = b2_dynamicBody;
bd.position.Set(0.0f, 2.0f); bd.position.Set(0.0f, 2.0f);
b2Body* body = m_world->CreateBody(&bd); b2Body* body = m_world->CreateBody(&bd);
b2CircleShape shape; b2CircleShape shape;
shape.m_p.SetZero(); shape.m_p.SetZero();
shape.m_radius = 0.5f; shape.m_radius = 0.5f;
body->CreateFixture(&shape, 1.0f); body->CreateFixture(&shape, 1.0f);
bd.bullet = true; bd.bullet = true;
bd.position.Set(0.0f, 10.0f); bd.position.Set(0.0f, 10.0f);
body = m_world->CreateBody(&bd); body = m_world->CreateBody(&bd);
body->CreateFixture(&shape, 1.0f); body->CreateFixture(&shape, 1.0f);
body->SetLinearVelocity(b2Vec2(0.0f, -100.0f)); body->SetLinearVelocity(b2Vec2(0.0f, -100.0f));
} }
#endif #endif
} }
void Launch() void Launch()
{ {
m_body->SetTransform(b2Vec2(0.0f, 20.0f), 0.0f); m_body->SetTransform(b2Vec2(0.0f, 20.0f), 0.0f);
m_angularVelocity = RandomFloat(-50.0f, 50.0f); m_angularVelocity = RandomFloat(-50.0f, 50.0f);
m_body->SetLinearVelocity(b2Vec2(0.0f, -100.0f)); m_body->SetLinearVelocity(b2Vec2(0.0f, -100.0f));
m_body->SetAngularVelocity(m_angularVelocity); m_body->SetAngularVelocity(m_angularVelocity);
} }
void Step(Settings* settings) void Step(Settings* settings)
{ {
if (m_stepCount == 12) if (m_stepCount == 12)
{ {
m_stepCount += 0; m_stepCount += 0;
} }
Test::Step(settings); Test::Step(settings);
extern int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters; extern int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters;
if (b2_gjkCalls > 0) if (b2_gjkCalls > 0)
{ {
m_debugDraw.DrawString(5, m_textLine, "gjk calls = % m_debugDraw.DrawString(5, m_textLine, "gjk calls = %d, ave gjk
d, ave gjk iters = %3.1f, max gjk iters = %d", iters = %3.1f, max gjk iters = %d",
b2_gjkCalls, b2_gjkIters / float32(b2_gjkCal b2_gjkCalls, b2_gjkIters / float32(b2_gjkCalls), b2_gjkMaxI
ls), b2_gjkMaxIters); ters);
m_textLine += 15; m_textLine += 15;
} }
extern int32 b2_toiCalls, b2_toiIters; extern int32 b2_toiCalls, b2_toiIters;
extern int32 b2_toiRootIters, b2_toiMaxRootIters; extern int32 b2_toiRootIters, b2_toiMaxRootIters;
if (b2_toiCalls > 0) if (b2_toiCalls > 0)
{ {
m_debugDraw.DrawString(5, m_textLine, "toi calls = % m_debugDraw.DrawString(5, m_textLine, "toi calls = %d, ave toi
d, ave toi iters = %3.1f, max toi iters = %d", iters = %3.1f, max toi iters = %d",
b2_toiCalls, b2_toiCalls, b2_toiIters / float32(b2_toiCa
b2_toiIters / float32(b2_toiCalls), b2_toiMaxRootIters); lls), b2_toiMaxRootIters);
m_textLine += 15; m_textLine += 15;
m_debugDraw.DrawString(5, m_textLine, "ave toi root m_debugDraw.DrawString(5, m_textLine, "ave toi root iters = %3.
iters = %3.1f, max toi root iters = %d", 1f, max toi root iters = %d",
b2_toiRootIters / float32(b2_toiCalls), b2_t b2_toiRootIters / float32(b2_toiCalls), b2_toiMaxRootIters)
oiMaxRootIters); ;
m_textLine += 15; m_textLine += 15;
} }
if (m_stepCount % 60 == 0) if (m_stepCount % 60 == 0)
{ {
//Launch(); //Launch();
} }
} }
static Test* Create() static Test* Create()
{ {
return new ContinuousTest; return new ContinuousTest;
} }
b2Body* m_body; b2Body* m_body;
float32 m_angularVelocity; float32 m_angularVelocity;
}; };
#endif #endif
 End of changes. 6 change blocks. 
110 lines changed or deleted 109 lines changed or added


 CurlTest.h   CurlTest.h 
#ifndef _CURL_TEST_H_ #ifndef _CURL_TEST_H_
#define _CURL_TEST_H_ #define _CURL_TEST_H_
#include "cocos2d.h" #include "cocos2d.h"
#include "../testBasic.h" #include "../testBasic.h"
class CurlTest : public CCLayer class CurlTest : public CCLayer
{ {
public: public:
CurlTest(); CurlTest();
~CurlTest(); ~CurlTest();
virtual void ccTouchesEnded(cocos2d::CCSet *pTouches, cocos2d::CCEve nt *pEvent); virtual void ccTouchesEnded(cocos2d::CCSet *pTouches, cocos2d::CCEvent *pEvent);
private: private:
cocos2d::CCLabelTTF* m_pLabel; cocos2d::CCLabelTTF* m_pLabel;
}; };
class CurlTestScene : public TestScene class CurlTestScene : public TestScene
{ {
public: public:
virtual void runThisTest(); virtual void runThisTest();
}; };
#endif // _CURL_TEST_H_ #endif // _CURL_TEST_H_
 End of changes. 3 change blocks. 
4 lines changed or deleted 4 lines changed or added


 CurrentLanguageTest.h   CurrentLanguageTest.h 
#ifndef _CURRENT_LANGUAGE_TEST_H_ #ifndef _CURRENT_LANGUAGE_TEST_H_
#define _CURRENT_LANGUAGE_TEST_H_ #define _CURRENT_LANGUAGE_TEST_H_
#include "cocos2d.h" #include "cocos2d.h"
#include "../testBasic.h" #include "../testBasic.h"
class CurrentLanguageTest : public CCLayer class CurrentLanguageTest : public CCLayer
{ {
public: public:
CurrentLanguageTest(); CurrentLanguageTest();
}; };
class CurrentLanguageTestScene : public TestScene class CurrentLanguageTestScene : public TestScene
{ {
public: public:
virtual void runThisTest(); virtual void runThisTest();
}; };
#endif // _CURRENT_LANGUAGE_TEST_H_ #endif // _CURRENT_LANGUAGE_TEST_H_
 End of changes. 1 change blocks. 
1 lines changed or deleted 1 lines changed or added


 DistanceTest.h   DistanceTest.h 
skipping to change at line 25 skipping to change at line 25
* misrepresented as being the original software. * misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution . * 3. This notice may not be removed or altered from any source distribution .
*/ */
#ifndef DISTANCE_TEST_H #ifndef DISTANCE_TEST_H
#define DISTANCE_TEST_H #define DISTANCE_TEST_H
class DistanceTest : public Test class DistanceTest : public Test
{ {
public: public:
DistanceTest() DistanceTest()
{ {
{ {
m_transformA.SetIdentity(); m_transformA.SetIdentity();
m_transformA.p.Set(0.0f, -0.2f); m_transformA.p.Set(0.0f, -0.2f);
m_polygonA.SetAsBox(10.0f, 0.2f); m_polygonA.SetAsBox(10.0f, 0.2f);
} }
{ {
m_positionB.Set(12.017401f, 0.13678508f); m_positionB.Set(12.017401f, 0.13678508f);
m_angleB = -0.0109265f; m_angleB = -0.0109265f;
m_transformB.Set(m_positionB, m_angleB); m_transformB.Set(m_positionB, m_angleB);
m_polygonB.SetAsBox(2.0f, 0.1f); m_polygonB.SetAsBox(2.0f, 0.1f);
} }
} }
static Test* Create() static Test* Create()
{ {
return new DistanceTest; return new DistanceTest;
} }
void Step(Settings* settings) void Step(Settings* settings)
{ {
Test::Step(settings); Test::Step(settings);
b2DistanceInput input; b2DistanceInput input;
input.proxyA.Set(&m_polygonA, 0); input.proxyA.Set(&m_polygonA, 0);
input.proxyB.Set(&m_polygonB, 0); input.proxyB.Set(&m_polygonB, 0);
input.transformA = m_transformA; input.transformA = m_transformA;
input.transformB = m_transformB; input.transformB = m_transformB;
input.useRadii = true; input.useRadii = true;
b2SimplexCache cache; b2SimplexCache cache;
cache.count = 0; cache.count = 0;
b2DistanceOutput output; b2DistanceOutput output;
b2Distance(&output, &cache, &input); b2Distance(&output, &cache, &input);
m_debugDraw.DrawString(5, m_textLine, "distance = %g", outpu m_debugDraw.DrawString(5, m_textLine, "distance = %g", output.dista
t.distance); nce);
m_textLine += 15; m_textLine += 15;
m_debugDraw.DrawString(5, m_textLine, "iterations = %d", out m_debugDraw.DrawString(5, m_textLine, "iterations = %d", output.ite
put.iterations); rations);
m_textLine += 15; m_textLine += 15;
{ {
b2Color color(0.9f, 0.9f, 0.9f); b2Color color(0.9f, 0.9f, 0.9f);
b2Vec2 v[b2_maxPolygonVertices]; b2Vec2 v[b2_maxPolygonVertices];
for (int32 i = 0; i < m_polygonA.m_vertexCount; ++i) for (int32 i = 0; i < m_polygonA.m_vertexCount; ++i)
{ {
v[i] = b2Mul(m_transformA, m_polygonA.m_vert v[i] = b2Mul(m_transformA, m_polygonA.m_vertices[i]);
ices[i]); }
} m_debugDraw.DrawPolygon(v, m_polygonA.m_vertexCount, color);
m_debugDraw.DrawPolygon(v, m_polygonA.m_vertexCount,
color); for (int32 i = 0; i < m_polygonB.m_vertexCount; ++i)
{
for (int32 i = 0; i < m_polygonB.m_vertexCount; ++i) v[i] = b2Mul(m_transformB, m_polygonB.m_vertices[i]);
{ }
v[i] = b2Mul(m_transformB, m_polygonB.m_vert m_debugDraw.DrawPolygon(v, m_polygonB.m_vertexCount, color);
ices[i]); }
}
m_debugDraw.DrawPolygon(v, m_polygonB.m_vertexCount, b2Vec2 x1 = output.pointA;
color); b2Vec2 x2 = output.pointB;
}
b2Color c1(1.0f, 0.0f, 0.0f);
b2Vec2 x1 = output.pointA; m_debugDraw.DrawPoint(x1, 4.0f, c1);
b2Vec2 x2 = output.pointB;
b2Color c2(1.0f, 1.0f, 0.0f);
b2Color c1(1.0f, 0.0f, 0.0f); m_debugDraw.DrawPoint(x2, 4.0f, c2);
m_debugDraw.DrawPoint(x1, 4.0f, c1); }
b2Color c2(1.0f, 1.0f, 0.0f); void Keyboard(unsigned char key)
m_debugDraw.DrawPoint(x2, 4.0f, c2); {
} switch (key)
{
void Keyboard(unsigned char key) case 'a':
{ m_positionB.x -= 0.1f;
switch (key) break;
{
case 'a': case 'd':
m_positionB.x -= 0.1f; m_positionB.x += 0.1f;
break; break;
case 'd': case 's':
m_positionB.x += 0.1f; m_positionB.y -= 0.1f;
break; break;
case 's': case 'w':
m_positionB.y -= 0.1f; m_positionB.y += 0.1f;
break; break;
case 'w': case 'q':
m_positionB.y += 0.1f; m_angleB += 0.1f * b2_pi;
break; break;
case 'q': case 'e':
m_angleB += 0.1f * b2_pi; m_angleB -= 0.1f * b2_pi;
break; break;
}
case 'e':
m_angleB -= 0.1f * b2_pi; m_transformB.Set(m_positionB, m_angleB);
break; }
}
b2Vec2 m_positionB;
m_transformB.Set(m_positionB, m_angleB); float32 m_angleB;
}
b2Transform m_transformA;
b2Vec2 m_positionB; b2Transform m_transformB;
float32 m_angleB; b2PolygonShape m_polygonA;
b2PolygonShape m_polygonB;
b2Transform m_transformA;
b2Transform m_transformB;
b2PolygonShape m_polygonA;
b2PolygonShape m_polygonB;
}; };
#endif #endif
 End of changes. 1 change blocks. 
114 lines changed or deleted 110 lines changed or added


 Dominos.h   Dominos.h 
skipping to change at line 26 skipping to change at line 26
* 3. This notice may not be removed or altered from any source distribution . * 3. This notice may not be removed or altered from any source distribution .
*/ */
#ifndef DOMINOS_H #ifndef DOMINOS_H
#define DOMINOS_H #define DOMINOS_H
class Dominos : public Test class Dominos : public Test
{ {
public: public:
Dominos() Dominos()
{ {
b2Body* b1; b2Body* b1;
{ {
b2EdgeShape shape; b2EdgeShape shape;
shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)) shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f));
;
b2BodyDef bd;
b2BodyDef bd; b1 = m_world->CreateBody(&bd);
b1 = m_world->CreateBody(&bd); b1->CreateFixture(&shape, 0.0f);
b1->CreateFixture(&shape, 0.0f); }
}
{
{ b2PolygonShape shape;
b2PolygonShape shape; shape.SetAsBox(6.0f, 0.25f);
shape.SetAsBox(6.0f, 0.25f);
b2BodyDef bd;
b2BodyDef bd; bd.position.Set(-1.5f, 10.0f);
bd.position.Set(-1.5f, 10.0f); b2Body* ground = m_world->CreateBody(&bd);
b2Body* ground = m_world->CreateBody(&bd); ground->CreateFixture(&shape, 0.0f);
ground->CreateFixture(&shape, 0.0f); }
}
{
{ b2PolygonShape shape;
b2PolygonShape shape; shape.SetAsBox(0.1f, 1.0f);
shape.SetAsBox(0.1f, 1.0f);
b2FixtureDef fd;
b2FixtureDef fd; fd.shape = &shape;
fd.shape = &shape; fd.density = 20.0f;
fd.density = 20.0f; fd.friction = 0.1f;
fd.friction = 0.1f;
for (int i = 0; i < 10; ++i)
for (int i = 0; i < 10; ++i) {
{ b2BodyDef bd;
b2BodyDef bd; bd.type = b2_dynamicBody;
bd.type = b2_dynamicBody; bd.position.Set(-6.0f + 1.0f * i, 11.25f);
bd.position.Set(-6.0f + 1.0f * i, 11.25f); b2Body* body = m_world->CreateBody(&bd);
b2Body* body = m_world->CreateBody(&bd); body->CreateFixture(&fd);
body->CreateFixture(&fd); }
} }
}
{
{ b2PolygonShape shape;
b2PolygonShape shape; shape.SetAsBox(7.0f, 0.25f, b2Vec2_zero, 0.3f);
shape.SetAsBox(7.0f, 0.25f, b2Vec2_zero, 0.3f);
b2BodyDef bd;
b2BodyDef bd; bd.position.Set(1.0f, 6.0f);
bd.position.Set(1.0f, 6.0f); b2Body* ground = m_world->CreateBody(&bd);
b2Body* ground = m_world->CreateBody(&bd); ground->CreateFixture(&shape, 0.0f);
ground->CreateFixture(&shape, 0.0f); }
}
b2Body* b2;
b2Body* b2; {
{ b2PolygonShape shape;
b2PolygonShape shape; shape.SetAsBox(0.25f, 1.5f);
shape.SetAsBox(0.25f, 1.5f);
b2BodyDef bd;
b2BodyDef bd; bd.position.Set(-7.0f, 4.0f);
bd.position.Set(-7.0f, 4.0f); b2 = m_world->CreateBody(&bd);
b2 = m_world->CreateBody(&bd); b2->CreateFixture(&shape, 0.0f);
b2->CreateFixture(&shape, 0.0f); }
}
b2Body* b3;
b2Body* b3; {
{ b2PolygonShape shape;
b2PolygonShape shape; shape.SetAsBox(6.0f, 0.125f);
shape.SetAsBox(6.0f, 0.125f);
b2BodyDef bd;
b2BodyDef bd; bd.type = b2_dynamicBody;
bd.type = b2_dynamicBody; bd.position.Set(-0.9f, 1.0f);
bd.position.Set(-0.9f, 1.0f); bd.angle = -0.15f;
bd.angle = -0.15f;
b3 = m_world->CreateBody(&bd);
b3 = m_world->CreateBody(&bd); b3->CreateFixture(&shape, 10.0f);
b3->CreateFixture(&shape, 10.0f); }
}
b2RevoluteJointDef jd;
b2RevoluteJointDef jd; b2Vec2 anchor;
b2Vec2 anchor;
anchor.Set(-2.0f, 1.0f);
anchor.Set(-2.0f, 1.0f); jd.Initialize(b1, b3, anchor);
jd.Initialize(b1, b3, anchor); jd.collideConnected = true;
jd.collideConnected = true; m_world->CreateJoint(&jd);
m_world->CreateJoint(&jd);
b2Body* b4;
b2Body* b4; {
{ b2PolygonShape shape;
b2PolygonShape shape; shape.SetAsBox(0.25f, 0.25f);
shape.SetAsBox(0.25f, 0.25f);
b2BodyDef bd;
b2BodyDef bd; bd.type = b2_dynamicBody;
bd.type = b2_dynamicBody; bd.position.Set(-10.0f, 15.0f);
bd.position.Set(-10.0f, 15.0f); b4 = m_world->CreateBody(&bd);
b4 = m_world->CreateBody(&bd); b4->CreateFixture(&shape, 10.0f);
b4->CreateFixture(&shape, 10.0f); }
}
anchor.Set(-7.0f, 15.0f);
anchor.Set(-7.0f, 15.0f); jd.Initialize(b2, b4, anchor);
jd.Initialize(b2, b4, anchor); m_world->CreateJoint(&jd);
m_world->CreateJoint(&jd);
b2Body* b5;
b2Body* b5; {
{ b2BodyDef bd;
b2BodyDef bd; bd.type = b2_dynamicBody;
bd.type = b2_dynamicBody; bd.position.Set(6.5f, 3.0f);
bd.position.Set(6.5f, 3.0f); b5 = m_world->CreateBody(&bd);
b5 = m_world->CreateBody(&bd);
b2PolygonShape shape;
b2PolygonShape shape; b2FixtureDef fd;
b2FixtureDef fd;
fd.shape = &shape;
fd.shape = &shape; fd.density = 10.0f;
fd.density = 10.0f; fd.friction = 0.1f;
fd.friction = 0.1f;
shape.SetAsBox(1.0f, 0.1f, b2Vec2(0.0f, -0.9f), 0.0f);
shape.SetAsBox(1.0f, 0.1f, b2Vec2(0.0f, -0.9f), 0.0f b5->CreateFixture(&fd);
);
b5->CreateFixture(&fd); shape.SetAsBox(0.1f, 1.0f, b2Vec2(-0.9f, 0.0f), 0.0f);
b5->CreateFixture(&fd);
shape.SetAsBox(0.1f, 1.0f, b2Vec2(-0.9f, 0.0f), 0.0f
); shape.SetAsBox(0.1f, 1.0f, b2Vec2(0.9f, 0.0f), 0.0f);
b5->CreateFixture(&fd); b5->CreateFixture(&fd);
}
shape.SetAsBox(0.1f, 1.0f, b2Vec2(0.9f, 0.0f), 0.0f)
; anchor.Set(6.0f, 2.0f);
b5->CreateFixture(&fd); jd.Initialize(b1, b5, anchor);
} m_world->CreateJoint(&jd);
anchor.Set(6.0f, 2.0f); b2Body* b6;
jd.Initialize(b1, b5, anchor); {
m_world->CreateJoint(&jd); b2PolygonShape shape;
shape.SetAsBox(1.0f, 0.1f);
b2Body* b6;
{ b2BodyDef bd;
b2PolygonShape shape; bd.type = b2_dynamicBody;
shape.SetAsBox(1.0f, 0.1f); bd.position.Set(6.5f, 4.1f);
b6 = m_world->CreateBody(&bd);
b2BodyDef bd; b6->CreateFixture(&shape, 30.0f);
bd.type = b2_dynamicBody; }
bd.position.Set(6.5f, 4.1f);
b6 = m_world->CreateBody(&bd); anchor.Set(7.5f, 4.0f);
b6->CreateFixture(&shape, 30.0f); jd.Initialize(b5, b6, anchor);
} m_world->CreateJoint(&jd);
anchor.Set(7.5f, 4.0f); b2Body* b7;
jd.Initialize(b5, b6, anchor); {
m_world->CreateJoint(&jd); b2PolygonShape shape;
shape.SetAsBox(0.1f, 1.0f);
b2Body* b7;
{ b2BodyDef bd;
b2PolygonShape shape; bd.type = b2_dynamicBody;
shape.SetAsBox(0.1f, 1.0f); bd.position.Set(7.4f, 1.0f);
b2BodyDef bd; b7 = m_world->CreateBody(&bd);
bd.type = b2_dynamicBody; b7->CreateFixture(&shape, 10.0f);
bd.position.Set(7.4f, 1.0f); }
b7 = m_world->CreateBody(&bd); b2DistanceJointDef djd;
b7->CreateFixture(&shape, 10.0f); djd.bodyA = b3;
} djd.bodyB = b7;
djd.localAnchorA.Set(6.0f, 0.0f);
b2DistanceJointDef djd; djd.localAnchorB.Set(0.0f, -1.0f);
djd.bodyA = b3; b2Vec2 d = djd.bodyB->GetWorldPoint(djd.localAnchorB) - djd.bodyA->
djd.bodyB = b7; GetWorldPoint(djd.localAnchorA);
djd.localAnchorA.Set(6.0f, 0.0f); djd.length = d.Length();
djd.localAnchorB.Set(0.0f, -1.0f); m_world->CreateJoint(&djd);
b2Vec2 d = djd.bodyB->GetWorldPoint(djd.localAnchorB) - djd.
bodyA->GetWorldPoint(djd.localAnchorA); {
djd.length = d.Length(); float32 radius = 0.2f;
m_world->CreateJoint(&djd);
b2CircleShape shape;
{ shape.m_radius = radius;
float32 radius = 0.2f;
for (int32 i = 0; i < 4; ++i)
b2CircleShape shape; {
shape.m_radius = radius; b2BodyDef bd;
bd.type = b2_dynamicBody;
for (int32 i = 0; i < 4; ++i) bd.position.Set(5.9f + 2.0f * radius * i, 2.4f);
{ b2Body* body = m_world->CreateBody(&bd);
b2BodyDef bd; body->CreateFixture(&shape, 10.0f);
bd.type = b2_dynamicBody; }
bd.position.Set(5.9f + 2.0f * radius * i, 2. }
4f); }
b2Body* body = m_world->CreateBody(&bd);
body->CreateFixture(&shape, 10.0f); static Test* Create()
} {
} return new Dominos;
} }
static Test* Create()
{
return new Dominos;
}
}; };
#endif #endif
 End of changes. 1 change blocks. 
193 lines changed or deleted 188 lines changed or added


 DrawPrimitivesTest.h   DrawPrimitivesTest.h 
#ifndef _DRAW_PRIMITIVES_TEST_H_ #ifndef _DRAW_PRIMITIVES_TEST_H_
#define _DRAW_PRIMITIVES_TEST_H_ #define _DRAW_PRIMITIVES_TEST_H_
////----#include "cocos2d.h" ////----#include "cocos2d.h"
#include "../testBasic.h" #include "../testBasic.h"
class DrawPrimitivesTest : public CCLayer class DrawPrimitivesTest : public CCLayer
{ {
public: public:
DrawPrimitivesTest(); DrawPrimitivesTest();
virtual void draw(); virtual void draw();
}; };
class DrawPrimitivesTestScene : public TestScene class DrawPrimitivesTestScene : public TestScene
{ {
public: public:
virtual void runThisTest(); virtual void runThisTest();
}; };
#endif #endif
 End of changes. 1 change blocks. 
2 lines changed or deleted 2 lines changed or added


 DumpShell.h   DumpShell.h 
skipping to change at line 27 skipping to change at line 27
*/ */
#ifndef DUMP_SHELL_H #ifndef DUMP_SHELL_H
#define DUMP_SHELL_H #define DUMP_SHELL_H
// This test holds worlds dumped using b2World::Dump. // This test holds worlds dumped using b2World::Dump.
class DumpShell : public Test class DumpShell : public Test
{ {
public: public:
DumpShell() DumpShell()
{ {
b2Vec2 g(0.000000000000000e+00f, 0.000000000000000e+00f); b2Vec2 g(0.000000000000000e+00f, 0.000000000000000e+00f);
m_world->SetGravity(g); m_world->SetGravity(g);
b2Body** bodies = (b2Body**)b2Alloc(3 * sizeof(b2Body*)); b2Body** bodies = (b2Body**)b2Alloc(3 * sizeof(b2Body*));
b2Joint** joints = (b2Joint**)b2Alloc(2 * sizeof(b2Joint*)); b2Joint** joints = (b2Joint**)b2Alloc(2 * sizeof(b2Joint*));
{ {
b2BodyDef bd; b2BodyDef bd;
bd.type = b2BodyType(2); bd.type = b2BodyType(2);
bd.position.Set(1.304347801208496e+01f, 2.500000000000000e+00f); bd.position.Set(1.304347801208496e+01f, 2.500000000000000e+00f);
bd.angle = 0.000000000000000e+00f; bd.angle = 0.000000000000000e+00f;
skipping to change at line 258 skipping to change at line 258
jd.enableMotor = bool(0); jd.enableMotor = bool(0);
jd.motorSpeed = 0.000000000000000e+00f; jd.motorSpeed = 0.000000000000000e+00f;
jd.maxMotorTorque = 0.000000000000000e+00f; jd.maxMotorTorque = 0.000000000000000e+00f;
joints[1] = m_world->CreateJoint(&jd); joints[1] = m_world->CreateJoint(&jd);
} }
b2Free(joints); b2Free(joints);
b2Free(bodies); b2Free(bodies);
joints = NULL; joints = NULL;
bodies = NULL; bodies = NULL;
} }
static Test* Create() static Test* Create()
{ {
return new DumpShell; return new DumpShell;
} }
}; };
#endif #endif
 End of changes. 3 change blocks. 
7 lines changed or deleted 7 lines changed or added


 DynamicTreeTest.h   DynamicTreeTest.h 
skipping to change at line 26 skipping to change at line 26
* 3. This notice may not be removed or altered from any source distribution . * 3. This notice may not be removed or altered from any source distribution .
*/ */
#ifndef DYNAMIC_TREE_TEST_H #ifndef DYNAMIC_TREE_TEST_H
#define DYNAMIC_TREE_TEST_H #define DYNAMIC_TREE_TEST_H
class DynamicTreeTest : public Test class DynamicTreeTest : public Test
{ {
public: public:
enum enum
{ {
e_actorCount = 128 e_actorCount = 128
}; };
DynamicTreeTest() DynamicTreeTest()
{ {
m_worldExtent = 15.0f; m_worldExtent = 15.0f;
m_proxyExtent = 0.5f; m_proxyExtent = 0.5f;
srand(888); srand(888);
for (int32 i = 0; i < e_actorCount; ++i) for (int32 i = 0; i < e_actorCount; ++i)
{ {
Actor* actor = m_actors + i; Actor* actor = m_actors + i;
GetRandomAABB(&actor->aabb); GetRandomAABB(&actor->aabb);
actor->proxyId = m_tree.CreateProxy(actor->aabb, act actor->proxyId = m_tree.CreateProxy(actor->aabb, actor);
or); }
}
m_stepCount = 0;
m_stepCount = 0;
float32 h = m_worldExtent;
float32 h = m_worldExtent; m_queryAABB.lowerBound.Set(-3.0f, -4.0f + h);
m_queryAABB.lowerBound.Set(-3.0f, -4.0f + h); m_queryAABB.upperBound.Set(5.0f, 6.0f + h);
m_queryAABB.upperBound.Set(5.0f, 6.0f + h);
m_rayCastInput.p1.Set(-5.0, 5.0f + h);
m_rayCastInput.p1.Set(-5.0, 5.0f + h); m_rayCastInput.p2.Set(7.0f, -4.0f + h);
m_rayCastInput.p2.Set(7.0f, -4.0f + h); //m_rayCastInput.p1.Set(0.0f, 2.0f + h);
//m_rayCastInput.p1.Set(0.0f, 2.0f + h); //m_rayCastInput.p2.Set(0.0f, -2.0f + h);
//m_rayCastInput.p2.Set(0.0f, -2.0f + h); m_rayCastInput.maxFraction = 1.0f;
m_rayCastInput.maxFraction = 1.0f;
m_automated = false;
m_automated = false; }
}
static Test* Create()
static Test* Create() {
{ return new DynamicTreeTest;
return new DynamicTreeTest; }
}
void Step(Settings* settings)
void Step(Settings* settings) {
{ B2_NOT_USED(settings);
B2_NOT_USED(settings);
m_rayActor = NULL;
m_rayActor = NULL; for (int32 i = 0; i < e_actorCount; ++i)
for (int32 i = 0; i < e_actorCount; ++i) {
{ m_actors[i].fraction = 1.0f;
m_actors[i].fraction = 1.0f; m_actors[i].overlap = false;
m_actors[i].overlap = false; }
}
if (m_automated == true)
if (m_automated == true) {
{ int32 actionCount = b2Max(1, e_actorCount >> 2);
int32 actionCount = b2Max(1, e_actorCount >> 2);
for (int32 i = 0; i < actionCount; ++i)
for (int32 i = 0; i < actionCount; ++i) {
{ Action();
Action(); }
} }
}
Query();
Query(); RayCast();
RayCast();
for (int32 i = 0; i < e_actorCount; ++i)
for (int32 i = 0; i < e_actorCount; ++i) {
{ Actor* actor = m_actors + i;
Actor* actor = m_actors + i; if (actor->proxyId == b2_nullNode)
if (actor->proxyId == b2_nullNode) continue;
continue;
b2Color c(0.9f, 0.9f, 0.9f);
b2Color c(0.9f, 0.9f, 0.9f); if (actor == m_rayActor && actor->overlap)
if (actor == m_rayActor && actor->overlap) {
{ c.Set(0.9f, 0.6f, 0.6f);
c.Set(0.9f, 0.6f, 0.6f); }
} else if (actor == m_rayActor)
else if (actor == m_rayActor) {
{ c.Set(0.6f, 0.9f, 0.6f);
c.Set(0.6f, 0.9f, 0.6f); }
} else if (actor->overlap)
else if (actor->overlap) {
{ c.Set(0.6f, 0.6f, 0.9f);
c.Set(0.6f, 0.6f, 0.9f); }
}
m_debugDraw.DrawAABB(&actor->aabb, c);
m_debugDraw.DrawAABB(&actor->aabb, c); }
}
b2Color c(0.7f, 0.7f, 0.7f);
b2Color c(0.7f, 0.7f, 0.7f); m_debugDraw.DrawAABB(&m_queryAABB, c);
m_debugDraw.DrawAABB(&m_queryAABB, c);
m_debugDraw.DrawSegment(m_rayCastInput.p1, m_rayCastInput.p2, c);
m_debugDraw.DrawSegment(m_rayCastInput.p1, m_rayCastInput.p2
, c); b2Color c1(0.2f, 0.9f, 0.2f);
b2Color c2(0.9f, 0.2f, 0.2f);
b2Color c1(0.2f, 0.9f, 0.2f); m_debugDraw.DrawPoint(m_rayCastInput.p1, 6.0f, c1);
b2Color c2(0.9f, 0.2f, 0.2f); m_debugDraw.DrawPoint(m_rayCastInput.p2, 6.0f, c2);
m_debugDraw.DrawPoint(m_rayCastInput.p1, 6.0f, c1);
m_debugDraw.DrawPoint(m_rayCastInput.p2, 6.0f, c2); if (m_rayActor)
{
if (m_rayActor) b2Color cr(0.2f, 0.2f, 0.9f);
{ b2Vec2 p = m_rayCastInput.p1 + m_rayActor->fraction * (m_rayCas
b2Color cr(0.2f, 0.2f, 0.9f); tInput.p2 - m_rayCastInput.p1);
b2Vec2 p = m_rayCastInput.p1 + m_rayActor->fraction m_debugDraw.DrawPoint(p, 6.0f, cr);
* (m_rayCastInput.p2 - m_rayCastInput.p1); }
m_debugDraw.DrawPoint(p, 6.0f, cr);
} {
int32 height = m_tree.GetHeight();
{ m_debugDraw.DrawString(5, m_textLine, "dynamic tree height = %d
int32 height = m_tree.GetHeight(); ", height);
m_debugDraw.DrawString(5, m_textLine, "dynamic tree m_textLine += 15;
height = %d", height); }
m_textLine += 15;
} ++m_stepCount;
}
++m_stepCount;
} void Keyboard(unsigned char key)
{
void Keyboard(unsigned char key) switch (key)
{ {
switch (key) case 'a':
{ m_automated = !m_automated;
case 'a': break;
m_automated = !m_automated;
break; case 'c':
CreateProxy();
case 'c': break;
CreateProxy();
break; case 'd':
DestroyProxy();
case 'd': break;
DestroyProxy();
break; case 'm':
MoveProxy();
case 'm': break;
MoveProxy(); }
break; }
}
} bool QueryCallback(int32 proxyId)
{
bool QueryCallback(int32 proxyId) Actor* actor = (Actor*)m_tree.GetUserData(proxyId);
{ actor->overlap = b2TestOverlap(m_queryAABB, actor->aabb);
Actor* actor = (Actor*)m_tree.GetUserData(proxyId); return true;
actor->overlap = b2TestOverlap(m_queryAABB, actor->aabb); }
return true;
} float32 RayCastCallback(const b2RayCastInput& input, int32 proxyId)
{
float32 RayCastCallback(const b2RayCastInput& input, int32 proxyId) Actor* actor = (Actor*)m_tree.GetUserData(proxyId);
{
Actor* actor = (Actor*)m_tree.GetUserData(proxyId); b2RayCastOutput output;
bool hit = actor->aabb.RayCast(&output, input);
b2RayCastOutput output;
bool hit = actor->aabb.RayCast(&output, input); if (hit)
{
if (hit) m_rayCastOutput = output;
{ m_rayActor = actor;
m_rayCastOutput = output; m_rayActor->fraction = output.fraction;
m_rayActor = actor; return output.fraction;
m_rayActor->fraction = output.fraction; }
return output.fraction;
}
return input.maxFraction; return input.maxFraction;
} }
private: private:
struct Actor struct Actor
{ {
b2AABB aabb; b2AABB aabb;
float32 fraction; float32 fraction;
bool overlap; bool overlap;
int32 proxyId; int32 proxyId;
}; };
void GetRandomAABB(b2AABB* aabb) void GetRandomAABB(b2AABB* aabb)
{ {
b2Vec2 w; w.Set(2.0f * m_proxyExtent, 2.0f * m_proxyExtent); b2Vec2 w; w.Set(2.0f * m_proxyExtent, 2.0f * m_proxyExtent);
//aabb->lowerBound.x = -m_proxyExtent; //aabb->lowerBound.x = -m_proxyExtent;
//aabb->lowerBound.y = -m_proxyExtent + m_worldExtent; //aabb->lowerBound.y = -m_proxyExtent + m_worldExtent;
aabb->lowerBound.x = RandomFloat(-m_worldExtent, m_worldExte aabb->lowerBound.x = RandomFloat(-m_worldExtent, m_worldExtent);
nt); aabb->lowerBound.y = RandomFloat(0.0f, 2.0f * m_worldExtent);
aabb->lowerBound.y = RandomFloat(0.0f, 2.0f * m_worldExtent) aabb->upperBound = aabb->lowerBound + w;
; }
aabb->upperBound = aabb->lowerBound + w;
} void MoveAABB(b2AABB* aabb)
{
void MoveAABB(b2AABB* aabb) b2Vec2 d;
{ d.x = RandomFloat(-0.5f, 0.5f);
b2Vec2 d; d.y = RandomFloat(-0.5f, 0.5f);
d.x = RandomFloat(-0.5f, 0.5f); //d.x = 2.0f;
d.y = RandomFloat(-0.5f, 0.5f); //d.y = 0.0f;
//d.x = 2.0f; aabb->lowerBound += d;
//d.y = 0.0f; aabb->upperBound += d;
aabb->lowerBound += d;
aabb->upperBound += d; b2Vec2 c0 = 0.5f * (aabb->lowerBound + aabb->upperBound);
b2Vec2 min; min.Set(-m_worldExtent, 0.0f);
b2Vec2 c0 = 0.5f * (aabb->lowerBound + aabb->upperBound); b2Vec2 max; max.Set(m_worldExtent, 2.0f * m_worldExtent);
b2Vec2 min; min.Set(-m_worldExtent, 0.0f); b2Vec2 c = b2Clamp(c0, min, max);
b2Vec2 max; max.Set(m_worldExtent, 2.0f * m_worldExtent);
b2Vec2 c = b2Clamp(c0, min, max); aabb->lowerBound += c - c0;
aabb->upperBound += c - c0;
aabb->lowerBound += c - c0; }
aabb->upperBound += c - c0;
} void CreateProxy()
{
void CreateProxy() for (int32 i = 0; i < e_actorCount; ++i)
{ {
for (int32 i = 0; i < e_actorCount; ++i) int32 j = rand() % e_actorCount;
{ Actor* actor = m_actors + j;
int32 j = rand() % e_actorCount; if (actor->proxyId == b2_nullNode)
Actor* actor = m_actors + j; {
if (actor->proxyId == b2_nullNode) GetRandomAABB(&actor->aabb);
{ actor->proxyId = m_tree.CreateProxy(actor->aabb, actor);
GetRandomAABB(&actor->aabb); return;
actor->proxyId = m_tree.CreateProxy(actor->a }
abb, actor); }
return; }
}
} void DestroyProxy()
} {
for (int32 i = 0; i < e_actorCount; ++i)
void DestroyProxy() {
{ int32 j = rand() % e_actorCount;
for (int32 i = 0; i < e_actorCount; ++i) Actor* actor = m_actors + j;
{ if (actor->proxyId != b2_nullNode)
int32 j = rand() % e_actorCount; {
Actor* actor = m_actors + j; m_tree.DestroyProxy(actor->proxyId);
if (actor->proxyId != b2_nullNode) actor->proxyId = b2_nullNode;
{ return;
m_tree.DestroyProxy(actor->proxyId); }
actor->proxyId = b2_nullNode; }
return; }
}
} void MoveProxy()
} {
for (int32 i = 0; i < e_actorCount; ++i)
void MoveProxy() {
{ int32 j = rand() % e_actorCount;
for (int32 i = 0; i < e_actorCount; ++i) Actor* actor = m_actors + j;
{ if (actor->proxyId == b2_nullNode)
int32 j = rand() % e_actorCount; {
Actor* actor = m_actors + j; continue;
if (actor->proxyId == b2_nullNode) }
{
continue; b2AABB aabb0 = actor->aabb;
} MoveAABB(&actor->aabb);
b2Vec2 displacement = actor->aabb.GetCenter() - aabb0.GetCenter
b2AABB aabb0 = actor->aabb; ();
MoveAABB(&actor->aabb); m_tree.MoveProxy(actor->proxyId, actor->aabb, displacement);
b2Vec2 displacement = actor->aabb.GetCenter() - aabb return;
0.GetCenter(); }
m_tree.MoveProxy(actor->proxyId, actor->aabb, displa }
cement);
return; void Action()
} {
} int32 choice = rand() % 20;
void Action() switch (choice)
{ {
int32 choice = rand() % 20; case 0:
CreateProxy();
switch (choice) break;
{
case 0: case 1:
CreateProxy(); DestroyProxy();
break; break;
case 1: default:
DestroyProxy(); MoveProxy();
break; }
}
default:
MoveProxy(); void Query()
} {
} m_tree.Query(this, m_queryAABB);
void Query() for (int32 i = 0; i < e_actorCount; ++i)
{ {
m_tree.Query(this, m_queryAABB); if (m_actors[i].proxyId == b2_nullNode)
{
for (int32 i = 0; i < e_actorCount; ++i) continue;
{ }
if (m_actors[i].proxyId == b2_nullNode)
{ bool overlap = b2TestOverlap(m_queryAABB, m_actors[i].aabb);
continue; B2_NOT_USED(overlap);
} b2Assert(overlap == m_actors[i].overlap);
}
bool overlap = b2TestOverlap(m_queryAABB, m_actors[i }
].aabb);
B2_NOT_USED(overlap); void RayCast()
b2Assert(overlap == m_actors[i].overlap); {
} m_rayActor = NULL;
}
b2RayCastInput input = m_rayCastInput;
void RayCast()
{ // Ray cast against the dynamic tree.
m_rayActor = NULL; m_tree.RayCast(this, input);
b2RayCastInput input = m_rayCastInput; // Brute force ray cast.
Actor* bruteActor = NULL;
// Ray cast against the dynamic tree. b2RayCastOutput bruteOutput;
m_tree.RayCast(this, input); for (int32 i = 0; i < e_actorCount; ++i)
{
// Brute force ray cast. if (m_actors[i].proxyId == b2_nullNode)
Actor* bruteActor = NULL; {
b2RayCastOutput bruteOutput; continue;
for (int32 i = 0; i < e_actorCount; ++i) }
{
if (m_actors[i].proxyId == b2_nullNode) b2RayCastOutput output;
{ bool hit = m_actors[i].aabb.RayCast(&output, input);
continue; if (hit)
} {
bruteActor = m_actors + i;
b2RayCastOutput output; bruteOutput = output;
bool hit = m_actors[i].aabb.RayCast(&output, input); input.maxFraction = output.fraction;
if (hit) }
{ }
bruteActor = m_actors + i;
bruteOutput = output; if (bruteActor != NULL)
input.maxFraction = output.fraction; {
} b2Assert(bruteOutput.fraction == m_rayCastOutput.fraction);
} }
}
if (bruteActor != NULL)
{ float32 m_worldExtent;
b2Assert(bruteOutput.fraction == m_rayCastOutput.fra float32 m_proxyExtent;
ction);
} b2DynamicTree m_tree;
} b2AABB m_queryAABB;
b2RayCastInput m_rayCastInput;
float32 m_worldExtent; b2RayCastOutput m_rayCastOutput;
float32 m_proxyExtent; Actor* m_rayActor;
Actor m_actors[e_actorCount];
b2DynamicTree m_tree; int32 m_stepCount;
b2AABB m_queryAABB; bool m_automated;
b2RayCastInput m_rayCastInput;
b2RayCastOutput m_rayCastOutput;
Actor* m_rayActor;
Actor m_actors[e_actorCount];
int32 m_stepCount;
bool m_automated;
}; };
#endif #endif
 End of changes. 3 change blocks. 
336 lines changed or deleted 328 lines changed or added


 EAGLView.h   EAGLView.h 
skipping to change at line 67 skipping to change at line 67
CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF
APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Copyright (C) 2008 Apple Inc. All Rights Reserved. Copyright (C) 2008 Apple Inc. All Rights Reserved.
*/ */
#import <UIKit/UIKit.h> #import <UIKit/UIKit.h>
#import <OpenGLES/EAGL.h> #import <OpenGLES/EAGL.h>
#import <OpenGLES/EAGLDrawable.h> #import <OpenGLES/EAGLDrawable.h>
#import <OpenGLES/ES1/gl.h> #import <OpenGLES/ES2/gl.h>
#import <OpenGLES/ES1/glext.h> #import <OpenGLES/ES2/glext.h>
#import <CoreFoundation/CoreFoundation.h> #import <CoreFoundation/CoreFoundation.h>
#import "ESRenderer.h" #import "CCESRenderer.h"
//CLASS INTERFACE: //CLASS INTERFACE:
/** EAGLView Class. /** EAGLView Class.
* This class wraps the CAEAGLLayer from CoreAnimation into a convenient UI View subclass. * This class wraps the CAEAGLLayer from CoreAnimation into a convenient UI View subclass.
* The view content is basically an EAGL surface you render your OpenGL sce ne into. * The view content is basically an EAGL surface you render your OpenGL sce ne into.
* Note that setting the view non-opaque will only work if the EAGL surface has an alpha channel. * Note that setting the view non-opaque will only work if the EAGL surface has an alpha channel.
*/ */
@interface EAGLView : UIView <UIKeyInput, UITextInput> @interface EAGLView : UIView <UIKeyInput, UITextInput>
{ {
id <ESRenderer> renderer_; id <CCESRenderer> renderer_;
EAGLContext *context_; // weak ref EAGLContext *context_; // weak ref
NSString *pixelformat_; NSString *pixelformat_;
GLuint depthFormat_; GLuint depthFormat_;
BOOL preserveBackbuffer_; BOOL preserveBackbuffer_;
CGSize size_; CGSize size_;
BOOL discardFramebufferSupported_ BOOL discardFramebufferSupported_;
;
//fsaa addition
//fsaa addition BOOL multisampling_;
BOOL multisampling_; unsigned int requestedSamples_;
unsigned int requestedSamples_; BOOL isUseUITextField;
@private @private
CFMutableDictionaryRef touchesIntergerDict;
unsigned int indexBitsUsed;
NSString * markedText_; NSString * markedText_;
CGRect caretRect_; CGRect caretRect_;
CGRect originalRect_;
NSNotification* keyboardShowNotification_;
BOOL isKeyboardShown_;
} }
@property(nonatomic, readonly) UITextPosition *beginningOfDocument; @property(nonatomic, readonly) UITextPosition *beginningOfDocument;
@property(nonatomic, readonly) UITextPosition *endOfDocument; @property(nonatomic, readonly) UITextPosition *endOfDocument;
@property(nonatomic, assign) id<UITextInputDelegate> inputDelegate; @property(nonatomic, assign) id<UITextInputDelegate> inputDelegate;
@property(nonatomic, readonly) UITextRange *markedTextRange; @property(nonatomic, readonly) UITextRange *markedTextRange;
@property (nonatomic, copy) NSDictionary *markedTextStyle; @property (nonatomic, copy) NSDictionary *markedTextStyle;
@property(readwrite, copy) UITextRange *selectedTextRange; @property(readwrite, copy) UITextRange *selectedTextRange;
@property(nonatomic, readonly) id<UITextInputTokenizer> tokenizer; @property(nonatomic, readonly) id<UITextInputTokenizer> tokenizer;
@property(nonatomic, readonly, getter = isKeyboardShown) BOOL isKeyboardSho
wn;
@property(nonatomic, copy) NSNotification* keyboardShowNotification;
/** creates an initializes an EAGLView with a frame and 0-bit depth buffer, and a RGB565 color buffer */ /** creates an initializes an EAGLView with a frame and 0-bit depth buffer, and a RGB565 color buffer */
+ (id) viewWithFrame:(CGRect)frame; + (id) viewWithFrame:(CGRect)frame;
/** creates an initializes an EAGLView with a frame, a color buffer format, and 0-bit depth buffer */ /** creates an initializes an EAGLView with a frame, a color buffer format, and 0-bit depth buffer */
+ (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format; + (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format;
/** creates an initializes an EAGLView with a frame, a color buffer format, and a depth buffer format */ /** creates an initializes an EAGLView with a frame, a color buffer format, and a depth buffer format */
+ (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthForma t:(GLuint)depth; + (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthForma t:(GLuint)depth;
/** creates an initializes an EAGLView with a frame, a color buffer format, a depth buffer format, a sharegroup, and multisamping */ /** creates an initializes an EAGLView with a frame, a color buffer format, a depth buffer format, a sharegroup, and multisamping */
+ (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthForma t:(GLuint)depth preserveBackbuffer:(BOOL)retained sharegroup:(EAGLSharegrou p*)sharegroup multiSampling:(BOOL)multisampling numberOfSamples:(unsigned i nt)samples; + (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthForma t:(GLuint)depth preserveBackbuffer:(BOOL)retained sharegroup:(EAGLSharegrou p*)sharegroup multiSampling:(BOOL)multisampling numberOfSamples:(unsigned i nt)samples;
// get the view object // get the view object
skipping to change at line 142 skipping to change at line 145
@property(nonatomic,readonly) GLuint depthFormat; @property(nonatomic,readonly) GLuint depthFormat;
/** returns surface size in pixels */ /** returns surface size in pixels */
@property(nonatomic,readonly) CGSize surfaceSize; @property(nonatomic,readonly) CGSize surfaceSize;
/** OpenGL context */ /** OpenGL context */
@property(nonatomic,readonly) EAGLContext *context; @property(nonatomic,readonly) EAGLContext *context;
@property(nonatomic,readwrite) BOOL multiSampling; @property(nonatomic,readwrite) BOOL multiSampling;
@property(readonly) CFMutableDictionaryRef touchesIntergerDict;
@property(readwrite) unsigned int indexBitsUsed;
/** EAGLView uses double-buffer. This method swaps the buffers */ /** EAGLView uses double-buffer. This method swaps the buffers */
-(void) swapBuffers; -(void) swapBuffers;
- (CGRect) convertRectFromViewToSurface:(CGRect)rect; - (CGRect) convertRectFromViewToSurface:(CGRect)rect;
- (CGPoint) convertPointFromViewToSurface:(CGPoint)point; - (CGPoint) convertPointFromViewToSurface:(CGPoint)point;
-(int) getWidth; -(int) getWidth;
-(int) getHeight; -(int) getHeight;
-(int) getUnUsedIndex;
-(void) removeUsedIndexBit:(int) index;
-(void) doAnimationWhenKeyboardMoveWithDuration:(float) duration distance:(
float) dis;
-(void) doAnimationWhenAnotherEditBeClicked;
@end @end
 End of changes. 10 change blocks. 
24 lines changed or deleted 25 lines changed or added


 EdgeShapes.h   EdgeShapes.h 
skipping to change at line 25 skipping to change at line 25
* misrepresented as being the original software. * misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution . * 3. This notice may not be removed or altered from any source distribution .
*/ */
#ifndef EDGE_SHAPES_H #ifndef EDGE_SHAPES_H
#define EDGE_SHAPES_H #define EDGE_SHAPES_H
class EdgeShapesCallback : public b2RayCastCallback class EdgeShapesCallback : public b2RayCastCallback
{ {
public: public:
EdgeShapesCallback() EdgeShapesCallback()
{ {
m_fixture = NULL; m_fixture = NULL;
} }
float32 ReportFixture( b2Fixture* fixture, const b2Vec2& point, float32 ReportFixture( b2Fixture* fixture, const b2Vec2& point,
const b2Vec2& normal, float32 fraction) const b2Vec2& normal, float32 fraction)
{ {
m_fixture = fixture; m_fixture = fixture;
m_point = point; m_point = point;
m_normal = normal; m_normal = normal;
return fraction; return fraction;
} }
b2Fixture* m_fixture; b2Fixture* m_fixture;
b2Vec2 m_point; b2Vec2 m_point;
b2Vec2 m_normal; b2Vec2 m_normal;
}; };
class EdgeShapes : public Test class EdgeShapes : public Test
{ {
public: public:
enum enum
{ {
e_maxBodies = 256 e_maxBodies = 256
}; };
EdgeShapes() EdgeShapes()
{ {
// Ground body // Ground body
{ {
b2BodyDef bd; b2BodyDef bd;
b2Body* ground = m_world->CreateBody(&bd); b2Body* ground = m_world->CreateBody(&bd);
float32 x1 = -20.0f; float32 x1 = -20.0f;
float32 y1 = 2.0f * cosf(x1 / 10.0f * b2_pi); float32 y1 = 2.0f * cosf(x1 / 10.0f * b2_pi);
for (int32 i = 0; i < 80; ++i) for (int32 i = 0; i < 80; ++i)
{ {
float32 x2 = x1 + 0.5f; float32 x2 = x1 + 0.5f;
float32 y2 = 2.0f * cosf(x2 / 10.0f * b2_pi) float32 y2 = 2.0f * cosf(x2 / 10.0f * b2_pi);
;
b2EdgeShape shape;
b2EdgeShape shape; shape.Set(b2Vec2(x1, y1), b2Vec2(x2, y2));
shape.Set(b2Vec2(x1, y1), b2Vec2(x2, y2)); ground->CreateFixture(&shape, 0.0f);
ground->CreateFixture(&shape, 0.0f);
x1 = x2;
x1 = x2; y1 = y2;
y1 = y2; }
} }
}
{
{ b2Vec2 vertices[3];
b2Vec2 vertices[3]; vertices[0].Set(-0.5f, 0.0f);
vertices[0].Set(-0.5f, 0.0f); vertices[1].Set(0.5f, 0.0f);
vertices[1].Set(0.5f, 0.0f); vertices[2].Set(0.0f, 1.5f);
vertices[2].Set(0.0f, 1.5f); m_polygons[0].Set(vertices, 3);
m_polygons[0].Set(vertices, 3); }
}
{
{ b2Vec2 vertices[3];
b2Vec2 vertices[3]; vertices[0].Set(-0.1f, 0.0f);
vertices[0].Set(-0.1f, 0.0f); vertices[1].Set(0.1f, 0.0f);
vertices[1].Set(0.1f, 0.0f); vertices[2].Set(0.0f, 1.5f);
vertices[2].Set(0.0f, 1.5f); m_polygons[1].Set(vertices, 3);
m_polygons[1].Set(vertices, 3); }
}
{
{ float32 w = 1.0f;
float32 w = 1.0f; float32 b = w / (2.0f + b2Sqrt(2.0f));
float32 b = w / (2.0f + b2Sqrt(2.0f)); float32 s = b2Sqrt(2.0f) * b;
float32 s = b2Sqrt(2.0f) * b;
b2Vec2 vertices[8];
b2Vec2 vertices[8]; vertices[0].Set(0.5f * s, 0.0f);
vertices[0].Set(0.5f * s, 0.0f); vertices[1].Set(0.5f * w, b);
vertices[1].Set(0.5f * w, b); vertices[2].Set(0.5f * w, b + s);
vertices[2].Set(0.5f * w, b + s); vertices[3].Set(0.5f * s, w);
vertices[3].Set(0.5f * s, w); vertices[4].Set(-0.5f * s, w);
vertices[4].Set(-0.5f * s, w); vertices[5].Set(-0.5f * w, b + s);
vertices[5].Set(-0.5f * w, b + s); vertices[6].Set(-0.5f * w, b);
vertices[6].Set(-0.5f * w, b); vertices[7].Set(-0.5f * s, 0.0f);
vertices[7].Set(-0.5f * s, 0.0f);
m_polygons[2].Set(vertices, 8);
m_polygons[2].Set(vertices, 8); }
}
{
{ m_polygons[3].SetAsBox(0.5f, 0.5f);
m_polygons[3].SetAsBox(0.5f, 0.5f); }
}
{
{ m_circle.m_radius = 0.5f;
m_circle.m_radius = 0.5f; }
}
m_bodyIndex = 0;
m_bodyIndex = 0; memset(m_bodies, 0, sizeof(m_bodies));
memset(m_bodies, 0, sizeof(m_bodies));
m_angle = 0.0f;
m_angle = 0.0f; }
}
void Create(int32 index)
void Create(int32 index) {
{ if (m_bodies[m_bodyIndex] != NULL)
if (m_bodies[m_bodyIndex] != NULL) {
{ m_world->DestroyBody(m_bodies[m_bodyIndex]);
m_world->DestroyBody(m_bodies[m_bodyIndex]); m_bodies[m_bodyIndex] = NULL;
m_bodies[m_bodyIndex] = NULL; }
}
b2BodyDef bd;
b2BodyDef bd;
float32 x = RandomFloat(-10.0f, 10.0f);
float32 x = RandomFloat(-10.0f, 10.0f); float32 y = RandomFloat(10.0f, 20.0f);
float32 y = RandomFloat(10.0f, 20.0f); bd.position.Set(x, y);
bd.position.Set(x, y); bd.angle = RandomFloat(-b2_pi, b2_pi);
bd.angle = RandomFloat(-b2_pi, b2_pi); bd.type = b2_dynamicBody;
bd.type = b2_dynamicBody;
if (index == 4)
if (index == 4) {
{ bd.angularDamping = 0.02f;
bd.angularDamping = 0.02f; }
}
m_bodies[m_bodyIndex] = m_world->CreateBody(&bd);
m_bodies[m_bodyIndex] = m_world->CreateBody(&bd);
if (index < 4)
if (index < 4) {
{ b2FixtureDef fd;
b2FixtureDef fd; fd.shape = m_polygons + index;
fd.shape = m_polygons + index; fd.friction = 0.3f;
fd.friction = 0.3f; fd.density = 20.0f;
fd.density = 20.0f; m_bodies[m_bodyIndex]->CreateFixture(&fd);
m_bodies[m_bodyIndex]->CreateFixture(&fd); }
} else
else {
{ b2FixtureDef fd;
b2FixtureDef fd; fd.shape = &m_circle;
fd.shape = &m_circle; fd.friction = 0.3f;
fd.friction = 0.3f; fd.density = 20.0f;
fd.density = 20.0f; m_bodies[m_bodyIndex]->CreateFixture(&fd);
m_bodies[m_bodyIndex]->CreateFixture(&fd); }
}
m_bodyIndex = (m_bodyIndex + 1) % e_maxBodies;
m_bodyIndex = (m_bodyIndex + 1) % e_maxBodies; }
}
void DestroyBody()
void DestroyBody() {
{ for (int32 i = 0; i < e_maxBodies; ++i)
for (int32 i = 0; i < e_maxBodies; ++i) {
{ if (m_bodies[i] != NULL)
if (m_bodies[i] != NULL) {
{ m_world->DestroyBody(m_bodies[i]);
m_world->DestroyBody(m_bodies[i]); m_bodies[i] = NULL;
m_bodies[i] = NULL; return;
return; }
} }
} }
}
void Keyboard(unsigned char key)
void Keyboard(unsigned char key) {
{ switch (key)
switch (key) {
{ case '1':
case '1': case '2':
case '2': case '3':
case '3': case '4':
case '4': case '5':
case '5': Create(key - '1');
Create(key - '1'); break;
break;
case 'd':
case 'd': DestroyBody();
DestroyBody(); break;
break; }
} }
}
void Step(Settings* settings)
void Step(Settings* settings) {
{ bool advanceRay = settings->pause == 0 || settings->singleStep;
bool advanceRay = settings->pause == 0 || settings->singleSt
ep; Test::Step(settings);
m_debugDraw.DrawString(5, m_textLine, "Press 1-5 to drop stuff");
Test::Step(settings); m_textLine += 15;
m_debugDraw.DrawString(5, m_textLine, "Press 1-5 to drop stu
ff"); float32 L = 25.0f;
m_textLine += 15; b2Vec2 point1(0.0f, 10.0f);
b2Vec2 d(L * cosf(m_angle), -L * b2Abs(sinf(m_angle)));
float32 L = 25.0f; b2Vec2 point2 = point1 + d;
b2Vec2 point1(0.0f, 10.0f);
b2Vec2 d(L * cosf(m_angle), -L * b2Abs(sinf(m_angle))); EdgeShapesCallback callback;
b2Vec2 point2 = point1 + d;
m_world->RayCast(&callback, point1, point2);
EdgeShapesCallback callback;
if (callback.m_fixture)
m_world->RayCast(&callback, point1, point2); {
m_debugDraw.DrawPoint(callback.m_point, 5.0f, b2Color(0.4f, 0.9
if (callback.m_fixture) f, 0.4f));
{
m_debugDraw.DrawPoint(callback.m_point, 5.0f, b2Colo m_debugDraw.DrawSegment(point1, callback.m_point, b2Color(0.8f,
r(0.4f, 0.9f, 0.4f)); 0.8f, 0.8f));
m_debugDraw.DrawSegment(point1, callback.m_point, b2 b2Vec2 head = callback.m_point + 0.5f * callback.m_normal;
Color(0.8f, 0.8f, 0.8f)); m_debugDraw.DrawSegment(callback.m_point, head, b2Color(0.9f, 0
.9f, 0.4f));
b2Vec2 head = callback.m_point + 0.5f * callback.m_n }
ormal; else
m_debugDraw.DrawSegment(callback.m_point, head, b2Co {
lor(0.9f, 0.9f, 0.4f)); m_debugDraw.DrawSegment(point1, point2, b2Color(0.8f, 0.8f, 0.8
} f));
else }
{
m_debugDraw.DrawSegment(point1, point2, b2Color(0.8f if (advanceRay)
, 0.8f, 0.8f)); {
} m_angle += 0.25f * b2_pi / 180.0f;
}
if (advanceRay) }
{
m_angle += 0.25f * b2_pi / 180.0f; static Test* Create()
} {
} return new EdgeShapes;
}
static Test* Create()
{ int32 m_bodyIndex;
return new EdgeShapes; b2Body* m_bodies[e_maxBodies];
} b2PolygonShape m_polygons[4];
b2CircleShape m_circle;
int32 m_bodyIndex;
b2Body* m_bodies[e_maxBodies];
b2PolygonShape m_polygons[4];
b2CircleShape m_circle;
float32 m_angle; float32 m_angle;
}; };
#endif #endif
 End of changes. 3 change blocks. 
223 lines changed or deleted 219 lines changed or added


 EdgeTest.h   EdgeTest.h 
skipping to change at line 26 skipping to change at line 26
* 3. This notice may not be removed or altered from any source distribution . * 3. This notice may not be removed or altered from any source distribution .
*/ */
#ifndef EDGE_TEST_H #ifndef EDGE_TEST_H
#define EDGE_TEST_H #define EDGE_TEST_H
class EdgeTest : public Test class EdgeTest : public Test
{ {
public: public:
EdgeTest() EdgeTest()
{ {
{ {
b2BodyDef bd; b2BodyDef bd;
b2Body* ground = m_world->CreateBody(&bd); b2Body* ground = m_world->CreateBody(&bd);
b2Vec2 v1(-10.0f, 0.0f), v2(-7.0f, -2.0f), v3(-4.0f, b2Vec2 v1(-10.0f, 0.0f), v2(-7.0f, -2.0f), v3(-4.0f, 0.0f);
0.0f); b2Vec2 v4(0.0f, 0.0f), v5(4.0f, 0.0f), v6(7.0f, 2.0f), v7(10.0f
b2Vec2 v4(0.0f, 0.0f), v5(4.0f, 0.0f), v6(7.0f, 2.0f , 0.0f);
), v7(10.0f, 0.0f);
b2EdgeShape shape;
b2EdgeShape shape;
shape.Set(v1, v2);
shape.Set(v1, v2); shape.m_hasVertex3 = true;
shape.m_hasVertex3 = true; shape.m_vertex3 = v3;
shape.m_vertex3 = v3; ground->CreateFixture(&shape, 0.0f);
ground->CreateFixture(&shape, 0.0f);
shape.Set(v2, v3);
shape.Set(v2, v3); shape.m_hasVertex0 = true;
shape.m_hasVertex0 = true; shape.m_hasVertex3 = true;
shape.m_hasVertex3 = true; shape.m_vertex0 = v1;
shape.m_vertex0 = v1; shape.m_vertex3 = v4;
shape.m_vertex3 = v4; ground->CreateFixture(&shape, 0.0f);
ground->CreateFixture(&shape, 0.0f);
shape.Set(v3, v4);
shape.Set(v3, v4); shape.m_hasVertex0 = true;
shape.m_hasVertex0 = true; shape.m_hasVertex3 = true;
shape.m_hasVertex3 = true; shape.m_vertex0 = v2;
shape.m_vertex0 = v2; shape.m_vertex3 = v5;
shape.m_vertex3 = v5; ground->CreateFixture(&shape, 0.0f);
ground->CreateFixture(&shape, 0.0f);
shape.Set(v4, v5);
shape.Set(v4, v5); shape.m_hasVertex0 = true;
shape.m_hasVertex0 = true; shape.m_hasVertex3 = true;
shape.m_hasVertex3 = true; shape.m_vertex0 = v3;
shape.m_vertex0 = v3; shape.m_vertex3 = v6;
shape.m_vertex3 = v6; ground->CreateFixture(&shape, 0.0f);
ground->CreateFixture(&shape, 0.0f);
shape.Set(v5, v6);
shape.Set(v5, v6); shape.m_hasVertex0 = true;
shape.m_hasVertex0 = true; shape.m_hasVertex3 = true;
shape.m_hasVertex3 = true; shape.m_vertex0 = v4;
shape.m_vertex0 = v4; shape.m_vertex3 = v7;
shape.m_vertex3 = v7; ground->CreateFixture(&shape, 0.0f);
ground->CreateFixture(&shape, 0.0f);
shape.Set(v6, v7);
shape.Set(v6, v7); shape.m_hasVertex0 = true;
shape.m_hasVertex0 = true; shape.m_vertex0 = v5;
shape.m_vertex0 = v5; ground->CreateFixture(&shape, 0.0f);
ground->CreateFixture(&shape, 0.0f); }
}
{
{ b2BodyDef bd;
b2BodyDef bd; bd.type = b2_dynamicBody;
bd.type = b2_dynamicBody; bd.position.Set(-0.5f, 0.6f);
bd.position.Set(-0.5f, 0.6f); bd.allowSleep = false;
bd.allowSleep = false; b2Body* body = m_world->CreateBody(&bd);
b2Body* body = m_world->CreateBody(&bd);
b2CircleShape shape;
b2CircleShape shape; shape.m_radius = 0.5f;
shape.m_radius = 0.5f;
body->CreateFixture(&shape, 1.0f);
body->CreateFixture(&shape, 1.0f); }
}
{
{ b2BodyDef bd;
b2BodyDef bd; bd.type = b2_dynamicBody;
bd.type = b2_dynamicBody; bd.position.Set(1.0f, 0.6f);
bd.position.Set(1.0f, 0.6f); bd.allowSleep = false;
bd.allowSleep = false; b2Body* body = m_world->CreateBody(&bd);
b2Body* body = m_world->CreateBody(&bd);
b2PolygonShape shape;
b2PolygonShape shape; shape.SetAsBox(0.5f, 0.5f);
shape.SetAsBox(0.5f, 0.5f);
body->CreateFixture(&shape, 1.0f);
body->CreateFixture(&shape, 1.0f); }
} }
}
static Test* Create()
static Test* Create() {
{ return new EdgeTest;
return new EdgeTest; }
}
}; };
#endif #endif
 End of changes. 1 change blocks. 
83 lines changed or deleted 82 lines changed or added


 EffectsAdvancedTest.h   EffectsAdvancedTest.h 
skipping to change at line 12 skipping to change at line 12
#define _EFFECT_ADVANCED_TEST_H_ #define _EFFECT_ADVANCED_TEST_H_
#include "cocos2d.h" #include "cocos2d.h"
#include "../testBasic.h" #include "../testBasic.h"
class EffectAdvanceTextLayer: public CCLayer class EffectAdvanceTextLayer: public CCLayer
{ {
protected: protected:
CCTextureAtlas* m_atlas; CCTextureAtlas* m_atlas;
std::string m_strTitle; std::string m_strTitle;
public: public:
virtual void onEnter(); virtual void onEnter();
~EffectAdvanceTextLayer(void); ~EffectAdvanceTextLayer(void);
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
void restartCallback(CCObject* pSender); void restartCallback(CCObject* pSender);
void nextCallback(CCObject* pSender); void nextCallback(CCObject* pSender);
void backCallback(CCObject* pSender); void backCallback(CCObject* pSender);
}; };
class Effect1 : public EffectAdvanceTextLayer class Effect1 : public EffectAdvanceTextLayer
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
virtual std::string title(); virtual std::string title();
}; };
class Effect2 : public EffectAdvanceTextLayer class Effect2 : public EffectAdvanceTextLayer
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
virtual std::string title(); virtual std::string title();
}; };
class Effect3 : public EffectAdvanceTextLayer class Effect3 : public EffectAdvanceTextLayer
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
virtual std::string title(); virtual std::string title();
}; };
class Effect4 : public EffectAdvanceTextLayer class Effect4 : public EffectAdvanceTextLayer
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
virtual std::string title(); virtual std::string title();
}; };
class Effect5 : public EffectAdvanceTextLayer class Effect5 : public EffectAdvanceTextLayer
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
virtual void onExit(); virtual void onExit();
virtual std::string title(); virtual std::string title();
}; };
class Issue631 : public EffectAdvanceTextLayer class Issue631 : public EffectAdvanceTextLayer
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
}; };
class EffectAdvanceScene : public TestScene class EffectAdvanceScene : public TestScene
{ {
public: public:
virtual void runThisTest(); virtual void runThisTest();
}; };
#endif #endif
 End of changes. 10 change blocks. 
22 lines changed or deleted 22 lines changed or added


 EffectsTest.h   EffectsTest.h 
skipping to change at line 15 skipping to change at line 15
class EffectTestScene : public TestScene class EffectTestScene : public TestScene
{ {
public: public:
virtual void runThisTest(); virtual void runThisTest();
}; };
class TextLayer : public CCLayerColor class TextLayer : public CCLayerColor
{ {
protected: protected:
//UxString m_strTitle; //UxString m_strTitle;
public: public:
TextLayer(void); TextLayer(void);
~TextLayer(void); ~TextLayer(void);
void checkAnim(ccTime dt); void checkAnim(float dt);
virtual void onEnter(); virtual void onEnter();
void restartCallback(CCObject* pSender); void restartCallback(CCObject* pSender);
void nextCallback(CCObject* pSender); void nextCallback(CCObject* pSender);
void backCallback(CCObject* pSender); void backCallback(CCObject* pSender);
void newOrientation(); void newScene();
void newScene();
static TextLayer* node(); static TextLayer* create();
}; };
#endif #endif
 End of changes. 7 change blocks. 
11 lines changed or deleted 10 lines changed or added


 Export.h   Export.h 
#ifndef __EXPORT_COMMON__ #ifndef __EXPORT_COMMON__
#define __EXPORT_COMMON__ #define __EXPORT_COMMON__
#if defined(SHP) #if defined(SHP)
#include <FBaseConfig.h> #include <FBaseConfig.h>
#define EXPORT_DLL _EXPORT_ #define EXPORT_DLL _EXPORT_
#elif defined(_WIN32) #elif defined(_WIN32)
#if defined(_EXPORT_DLL_) #if defined(_EXPORT_DLL_)
#define EXPORT_DLL __declspec(dllexport) #define EXPORT_DLL __declspec(dllexport)
#elif defined(IGNORE_EXPORT) #elif defined(IGNORE_EXPORT)
#define EXPORT_DLL #define EXPORT_DLL
#else /* use a DLL library */ #else /* use a DLL library */
#define EXPORT_DLL __declspec(dllimport) #define EXPORT_DLL __declspec(dllimport)
#endif #endif
#else #else
#if defined(_SHARED_) #if defined(_SHARED_)
#define EXPORT_DLL __attribute__((visibility("default"))) #define EXPORT_DLL __attribute__((visibility("default")))
#elif defined(IGNORE_EXPORT) #elif defined(IGNORE_EXPORT)
#define EXPORT_DLL #define EXPORT_DLL
#else #else
#define EXPORT_DLL #define EXPORT_DLL
#endif #endif
#endif #endif
#endif // end of __EXPORT_COMMON__ #endif // end of __EXPORT_COMMON__
 End of changes. 3 change blocks. 
3 lines changed or deleted 3 lines changed or added


 FontLabel.h   FontLabel.h 
skipping to change at line 29 skipping to change at line 29
// limitations under the License. // limitations under the License.
// //
#import <Foundation/Foundation.h> #import <Foundation/Foundation.h>
#import <UIKit/UIKit.h> #import <UIKit/UIKit.h>
@class ZFont; @class ZFont;
@class ZAttributedString; @class ZAttributedString;
@interface FontLabel : UILabel { @interface FontLabel : UILabel {
void *reserved; // works around a bug in UILabel void *reserved; // works around a bug in UILabel
ZFont *zFont; ZFont *zFont;
ZAttributedString *zAttributedText; ZAttributedString *zAttributedText;
} }
@property (nonatomic, setter=setCGFont:) CGFontRef cgFont __AVAILABILITY_IN TERNAL_DEPRECATED; @property (nonatomic, setter=setCGFont:) CGFontRef cgFont __AVAILABILITY_IN TERNAL_DEPRECATED;
@property (nonatomic, assign) CGFloat pointSize __AVAILABILITY_INTERNAL_DEP RECATED; @property (nonatomic, assign) CGFloat pointSize __AVAILABILITY_INTERNAL_DEP RECATED;
@property (nonatomic, retain, setter=setZFont:) ZFont *zFont; @property (nonatomic, retain, setter=setZFont:) ZFont *zFont;
// if attributedText is nil, fall back on using the inherited UILabel prope rties // if attributedText is nil, fall back on using the inherited UILabel prope rties
// if attributedText is non-nil, the font/text/textColor // if attributedText is non-nil, the font/text/textColor
// in addition, adjustsFontSizeToFitWidth does not work with attributed tex t // in addition, adjustsFontSizeToFitWidth does not work with attributed tex t
@property (nonatomic, copy) ZAttributedString *zAttributedText; @property (nonatomic, copy) ZAttributedString *zAttributedText;
// -initWithFrame:fontName:pointSize: uses FontManager to look up the font name // -initWithFrame:fontName:pointSize: uses FontManager to look up the font name
- (id)initWithFrame:(CGRect)frame fontName:(NSString *)fontName pointSize:( CGFloat)pointSize; - (id)initWithFrame:(CGRect)frame fontName:(NSString *)fontName pointSize:( CGFloat)pointSize;
 End of changes. 1 change blocks. 
3 lines changed or deleted 3 lines changed or added


 FontLabelStringDrawing.h   FontLabelStringDrawing.h 
skipping to change at line 33 skipping to change at line 33
#import <UIKit/UIKit.h> #import <UIKit/UIKit.h>
#import "ZAttributedString.h" #import "ZAttributedString.h"
@class ZFont; @class ZFont;
@interface NSString (FontLabelStringDrawing) @interface NSString (FontLabelStringDrawing)
// CGFontRef-based methods // CGFontRef-based methods
- (CGSize)sizeWithCGFont:(CGFontRef)font pointSize:(CGFloat)pointSize __AVA ILABILITY_INTERNAL_DEPRECATED; - (CGSize)sizeWithCGFont:(CGFontRef)font pointSize:(CGFloat)pointSize __AVA ILABILITY_INTERNAL_DEPRECATED;
- (CGSize)sizeWithCGFont:(CGFontRef)font pointSize:(CGFloat)pointSize const rainedToSize:(CGSize)size __AVAILABILITY_INTERNAL_DEPRECATED; - (CGSize)sizeWithCGFont:(CGFontRef)font pointSize:(CGFloat)pointSize const rainedToSize:(CGSize)size __AVAILABILITY_INTERNAL_DEPRECATED;
- (CGSize)sizeWithCGFont:(CGFontRef)font pointSize:(CGFloat)pointSize const rainedToSize:(CGSize)size - (CGSize)sizeWithCGFont:(CGFontRef)font pointSize:(CGFloat)pointSize const rainedToSize:(CGSize)size
lineBreakMode:(UILineBreakMode)lineBreakMode __AVAILABILI TY_INTERNAL_DEPRECATED; lineBreakMode:(UILineBreakMode)lineBreakMode __AVAILABILITY_INTE RNAL_DEPRECATED;
- (CGSize)drawAtPoint:(CGPoint)point withCGFont:(CGFontRef)font pointSize:( CGFloat)pointSize __AVAILABILITY_INTERNAL_DEPRECATED; - (CGSize)drawAtPoint:(CGPoint)point withCGFont:(CGFontRef)font pointSize:( CGFloat)pointSize __AVAILABILITY_INTERNAL_DEPRECATED;
- (CGSize)drawInRect:(CGRect)rect withCGFont:(CGFontRef)font pointSize:(CGF loat)pointSize __AVAILABILITY_INTERNAL_DEPRECATED; - (CGSize)drawInRect:(CGRect)rect withCGFont:(CGFontRef)font pointSize:(CGF loat)pointSize __AVAILABILITY_INTERNAL_DEPRECATED;
- (CGSize)drawInRect:(CGRect)rect withCGFont:(CGFontRef)font pointSize:(CGF loat)pointSize - (CGSize)drawInRect:(CGRect)rect withCGFont:(CGFontRef)font pointSize:(CGF loat)pointSize
lineBreakMode:(UILineBreakMode)lineBreakMode __AVAILABILITY_INTER NAL_DEPRECATED; lineBreakMode:(UILineBreakMode)lineBreakMode __AVAILABILITY_INTERNAL _DEPRECATED;
- (CGSize)drawInRect:(CGRect)rect withCGFont:(CGFontRef)font pointSize:(CGF loat)pointSize - (CGSize)drawInRect:(CGRect)rect withCGFont:(CGFontRef)font pointSize:(CGF loat)pointSize
lineBreakMode:(UILineBreakMode)lineBreakMode alignment:(UITextAli gnment)alignment __AVAILABILITY_INTERNAL_DEPRECATED; lineBreakMode:(UILineBreakMode)lineBreakMode alignment:(UITextAlignm ent)alignment __AVAILABILITY_INTERNAL_DEPRECATED;
// ZFont-based methods // ZFont-based methods
- (CGSize)sizeWithZFont:(ZFont *)font; - (CGSize)sizeWithZFont:(ZFont *)font;
- (CGSize)sizeWithZFont:(ZFont *)font constrainedToSize:(CGSize)size; - (CGSize)sizeWithZFont:(ZFont *)font constrainedToSize:(CGSize)size;
- (CGSize)sizeWithZFont:(ZFont *)font constrainedToSize:(CGSize)size lineBr eakMode:(UILineBreakMode)lineBreakMode; - (CGSize)sizeWithZFont:(ZFont *)font constrainedToSize:(CGSize)size lineBr eakMode:(UILineBreakMode)lineBreakMode;
- (CGSize)sizeWithZFont:(ZFont *)font constrainedToSize:(CGSize)size lineBr eakMode:(UILineBreakMode)lineBreakMode - (CGSize)sizeWithZFont:(ZFont *)font constrainedToSize:(CGSize)size lineBr eakMode:(UILineBreakMode)lineBreakMode
numberOfLines:(NSUInteger)numberOfLines; numberOfLines:(NSUInteger)numberOfLines;
- (CGSize)drawAtPoint:(CGPoint)point withZFont:(ZFont *)font; - (CGSize)drawAtPoint:(CGPoint)point withZFont:(ZFont *)font;
- (CGSize)drawAtPoint:(CGPoint)point forWidth:(CGFloat)width withZFont:(ZFo nt *)font lineBreakMode:(UILineBreakMode)lineBreakMode; - (CGSize)drawAtPoint:(CGPoint)point forWidth:(CGFloat)width withZFont:(ZFo nt *)font lineBreakMode:(UILineBreakMode)lineBreakMode;
- (CGSize)drawInRect:(CGRect)rect withZFont:(ZFont *)font; - (CGSize)drawInRect:(CGRect)rect withZFont:(ZFont *)font;
- (CGSize)drawInRect:(CGRect)rect withZFont:(ZFont *)font lineBreakMode:(UI LineBreakMode)lineBreakMode; - (CGSize)drawInRect:(CGRect)rect withZFont:(ZFont *)font lineBreakMode:(UI LineBreakMode)lineBreakMode;
- (CGSize)drawInRect:(CGRect)rect withZFont:(ZFont *)font lineBreakMode:(UI LineBreakMode)lineBreakMode - (CGSize)drawInRect:(CGRect)rect withZFont:(ZFont *)font lineBreakMode:(UI LineBreakMode)lineBreakMode
alignment:(UITextAlignment)alignment; alignment:(UITextAlignment)alignment;
- (CGSize)drawInRect:(CGRect)rect withZFont:(ZFont *)font lineBreakMode:(UI LineBreakMode)lineBreakMode - (CGSize)drawInRect:(CGRect)rect withZFont:(ZFont *)font lineBreakMode:(UI LineBreakMode)lineBreakMode
alignment:(UITextAlignment)alignment numberOfLines:(NSUIn teger)numberOfLines; alignment:(UITextAlignment)alignment numberOfLines:(NSUInteger)n umberOfLines;
@end @end
@interface ZAttributedString (ZAttributedStringDrawing) @interface ZAttributedString (ZAttributedStringDrawing)
- (CGSize)size; - (CGSize)size;
- (CGSize)sizeConstrainedToSize:(CGSize)size; - (CGSize)sizeConstrainedToSize:(CGSize)size;
- (CGSize)sizeConstrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode )lineBreakMode; - (CGSize)sizeConstrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode )lineBreakMode;
- (CGSize)sizeConstrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode )lineBreakMode - (CGSize)sizeConstrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode )lineBreakMode
numberOfLines:(NSUInteger)numberOfLines; numberOfLines:(NSUInteger)numberOfLines;
- (CGSize)drawAtPoint:(CGPoint)point; - (CGSize)drawAtPoint:(CGPoint)point;
- (CGSize)drawAtPoint:(CGPoint)point forWidth:(CGFloat)width lineBreakMode: (UILineBreakMode)lineBreakMode; - (CGSize)drawAtPoint:(CGPoint)point forWidth:(CGFloat)width lineBreakMode: (UILineBreakMode)lineBreakMode;
- (CGSize)drawInRect:(CGRect)rect; - (CGSize)drawInRect:(CGRect)rect;
- (CGSize)drawInRect:(CGRect)rect withLineBreakMode:(UILineBreakMode)lineBr eakMode; - (CGSize)drawInRect:(CGRect)rect withLineBreakMode:(UILineBreakMode)lineBr eakMode;
- (CGSize)drawInRect:(CGRect)rect withLineBreakMode:(UILineBreakMode)lineBr eakMode alignment:(UITextAlignment)alignment; - (CGSize)drawInRect:(CGRect)rect withLineBreakMode:(UILineBreakMode)lineBr eakMode alignment:(UITextAlignment)alignment;
- (CGSize)drawInRect:(CGRect)rect withLineBreakMode:(UILineBreakMode)lineBr eakMode alignment:(UITextAlignment)alignment - (CGSize)drawInRect:(CGRect)rect withLineBreakMode:(UILineBreakMode)lineBr eakMode alignment:(UITextAlignment)alignment
numberOfLines:(NSUInteger)numberOfLines; numberOfLines:(NSUInteger)numberOfLines;
@end @end
// This class is used to invoke in .mm file. // This class is used to invoke in .mm file.
// Can not invoke FontLabelStringDrawing directly in .mm. // Can not invoke FontLabelStringDrawing directly in .mm.
// It seems that, in .mm it can not support category. // It seems that, in .mm it can not support category.
@interface FontLabelStringDrawingHelper : NSObject { @interface FontLabelStringDrawingHelper : NSObject {
} }
+ (CGSize)sizeWithZFont:(NSString*)string zfont:(ZFont *)font; + (CGSize)sizeWithZFont:(NSString*)string zfont:(ZFont *)font;
+ (CGSize)sizeWithZFont:(NSString *)string zfont:(ZFont *)font constrainedT oSize:(CGSize)size; + (CGSize)sizeWithZFont:(NSString *)string zfont:(ZFont *)font constrainedT oSize:(CGSize)size;
+ (CGSize)drawInRect:(NSString*)string rect:(CGRect)rect withZFont:(ZFont * )font + (CGSize)drawInRect:(NSString*)string rect:(CGRect)rect withZFont:(ZFont * )font
 End of changes. 8 change blocks. 
8 lines changed or deleted 8 lines changed or added


 FontManager.h   FontManager.h 
skipping to change at line 28 skipping to change at line 28
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
// //
#import <Foundation/Foundation.h> #import <Foundation/Foundation.h>
#import <CoreGraphics/CoreGraphics.h> #import <CoreGraphics/CoreGraphics.h>
@class ZFont; @class ZFont;
@interface FontManager : NSObject { @interface FontManager : NSObject {
CFMutableDictionaryRef fonts; CFMutableDictionaryRef fonts;
NSMutableDictionary *urls; NSMutableDictionary *urls;
} }
+ (FontManager *)sharedManager; + (FontManager *)sharedManager;
/*! /*!
@method @method
@abstract Loads a TTF font from the main bundle @abstract Loads a TTF font from the main bundle
@param filename The name of the font file to load (with or without e @param filename The name of the font file to load (with or without exte
xtension). nsion).
@return YES if the font was loaded, NO if an error occurred @return YES if the font was loaded, NO if an error occurred
@discussion If the font has already been loaded, this method does nothi ng and returns YES. @discussion If the font has already been loaded, this method does nothi ng and returns YES.
This method first attempts to load the font This method first attempts to load the font by appending .t
by appending .ttf to the filename. tf to the filename.
If that file does not exist, it tries the fi If that file does not exist, it tries the filename exactly
lename exactly as given. as given.
*/ */
- (BOOL)loadFont:(NSString *)filename; - (BOOL)loadFont:(NSString *)filename;
/*! /*!
@method @method
@abstract Loads a font from the given file URL @abstract Loads a font from the given file URL
@param url A file URL that points to a font file @param url A file URL that points to a font file
@return YES if the font was loaded, NO if an error occurred @return YES if the font was loaded, NO if an error occurred
@discussion If the font has already been loaded, this method does no @discussion If the font has already been loaded, this method does nothi
thing and returns YES. ng and returns YES.
*/ */
- (BOOL)loadFontURL:(NSURL *)url; - (BOOL)loadFontURL:(NSURL *)url;
/*! /*!
@method @method
@abstract Returns the loaded font with the given filename @abstract Returns the loaded font with the given filename
@param filename The name of the font file that was given to -loadFon @param filename The name of the font file that was given to -loadFont:
t: @return A CGFontRef, or NULL if the specified font cannot be found
@return A CGFontRef, or NULL if the specified font cannot be found
@discussion If the font has not been loaded yet, -loadFont: will be @discussion If the font has not been loaded yet, -loadFont: will be
called with the given name first. called with the given name first.
*/ */
- (CGFontRef)fontWithName:(NSString *)filename __AVAILABILITY_INTERNAL_DEPR ECATED; - (CGFontRef)fontWithName:(NSString *)filename __AVAILABILITY_INTERNAL_DEPR ECATED;
/*! /*!
@method @method
@abstract Returns a ZFont object corresponding to the loaded f @abstract Returns a ZFont object corresponding to the loaded font wi
ont with the given filename and point size th the given filename and point size
@param filename The name of the font file that was given to -loadFon @param filename The name of the font file that was given to -loadFont:
t: @param pointSize The point size of the font
@param pointSize The point size of the font @return A ZFont, or NULL if the specified font cannot be found
@return A ZFont, or NULL if the specified font cannot be found @discussion If the font has not been loaded yet, -loadFont: will be
@discussion If the font has not been loaded yet, -loadFont: will be called with the given name first.
called with the given name first.
*/ */
- (ZFont *)zFontWithName:(NSString *)filename pointSize:(CGFloat)pointSize; - (ZFont *)zFontWithName:(NSString *)filename pointSize:(CGFloat)pointSize;
/*! /*!
@method @method
@abstract Returns a ZFont object corresponding to the loaded f @abstract Returns a ZFont object corresponding to the loaded font wi
ont with the given file URL and point size th the given file URL and point size
@param url A file URL that points to a font file @param url A file URL that points to a font file
@param pointSize The point size of the font @param pointSize The point size of the font
@return A ZFont, or NULL if the specified font cannot be loaded @return A ZFont, or NULL if the specified font cannot be loaded
@discussion If the font has not been loaded yet, -loadFontURL: will @discussion If the font has not been loaded yet, -loadFontURL: will be
be called with the given URL first. called with the given URL first.
*/ */
- (ZFont *)zFontWithURL:(NSURL *)url pointSize:(CGFloat)pointSize; - (ZFont *)zFontWithURL:(NSURL *)url pointSize:(CGFloat)pointSize;
/*! /*!
@method @method
@abstract Returns a CFArrayRef of all loaded CGFont objects @abstract Returns a CFArrayRef of all loaded CGFont objects
@return A CFArrayRef of all loaded CGFont objects @return A CFArrayRef of all loaded CGFont objects
@description You are responsible for releasing the CFArrayRef @description You are responsible for releasing the CFArrayRef
*/ */
- (CFArrayRef)copyAllFonts; - (CFArrayRef)copyAllFonts;
@end @end
 End of changes. 8 change blocks. 
39 lines changed or deleted 37 lines changed or added


 FontTest.h   FontTest.h 
skipping to change at line 16 skipping to change at line 16
class FontTestScene : public TestScene class FontTestScene : public TestScene
{ {
public: public:
virtual void runThisTest(); virtual void runThisTest();
}; };
class FontTest : public cocos2d::CCLayer class FontTest : public cocos2d::CCLayer
{ {
public: public:
FontTest(); FontTest();
void showFont(const char *pFont); void showFont(const char *pFont);
void restartCallback(CCObject* pSender); void restartCallback(CCObject* pSender);
void nextCallback(CCObject* pSender); void nextCallback(CCObject* pSender);
void backCallback(CCObject* pSender); void backCallback(CCObject* pSender);
virtual std::string title(); virtual std::string title();
LAYER_NODE_FUNC(FontTest); CREATE_FUNC(FontTest);
}; };
#endif // _FONT_TEST_H_ #endif // _FONT_TEST_H_
 End of changes. 3 change blocks. 
7 lines changed or deleted 7 lines changed or added


 GLES-Render.h   GLES-Render.h 
/*
* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com
*
* iPhone port by Simon Oliver - http://www.simonoliver.com - http://www.han
dcircus.com
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not b
e
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution
.
*/
#ifndef RENDER_H #ifndef RENDER_H
#define RENDER_H #define RENDER_H
//#import <UIKit/UIKit.h>
//#import <OpenGLES/EAGL.h>
//#import <OpenGLES/ES1/gl.h>
//#import <OpenGLES/ES1/glext.h>
#include "Box2D/Box2D.h" #include "Box2D/Box2D.h"
#include "cocos2d.h"
struct b2AABB; struct b2AABB;
// This class implements debug drawing callbacks that are invoked // This class implements debug drawing callbacks that are invoked
// inside b2World::Step. // inside b2World::Step.
class GLESDebugDraw : public b2Draw class GLESDebugDraw : public b2Draw
{ {
float32 mRatio; float32 mRatio;
cocos2d::CCGLProgram* mShaderProgram;
GLint mColorLocation;
void initShader( void );
public: public:
GLESDebugDraw(); GLESDebugDraw();
GLESDebugDraw( float32 ratio ); GLESDebugDraw( float32 ratio );
virtual void DrawPolygon(const b2Vec2* vertices, int vertexCount, co nst b2Color& color); virtual void DrawPolygon(const b2Vec2* vertices, int vertexCount, const b2Color& color);
virtual void DrawSolidPolygon(const b2Vec2* vertices, int vertexCoun t, const b2Color& color); virtual void DrawSolidPolygon(const b2Vec2* vertices, int vertexCount, const b2Color& color);
virtual void DrawCircle(const b2Vec2& center, float32 radius, const b2Color& color); virtual void DrawCircle(const b2Vec2& center, float32 radius, const b2C olor& color);
virtual void DrawSolidCircle(const b2Vec2& center, float32 radius, c onst b2Vec2& axis, const b2Color& color); virtual void DrawSolidCircle(const b2Vec2& center, float32 radius, cons t b2Vec2& axis, const b2Color& color);
virtual void DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b 2Color& color); virtual void DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Co lor& color);
virtual void DrawTransform(const b2Transform& xf); virtual void DrawTransform(const b2Transform& xf);
virtual void DrawPoint(const b2Vec2& p, float32 size, const b2Color& co lor); virtual void DrawPoint(const b2Vec2& p, float32 size, const b2Color& co lor);
virtual void DrawString(int x, int y, const char* string, ...); virtual void DrawString(int x, int y, const char* string, ...);
virtual void DrawAABB(b2AABB* aabb, const b2Color& color); virtual void DrawAABB(b2AABB* aabb, const b2Color& color);
}; };
#endif #endif
 End of changes. 12 change blocks. 
14 lines changed or deleted 37 lines changed or added


 Gears.h   Gears.h 
skipping to change at line 25 skipping to change at line 25
* misrepresented as being the original software. * misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution . * 3. This notice may not be removed or altered from any source distribution .
*/ */
#ifndef GEARS_H #ifndef GEARS_H
#define GEARS_H #define GEARS_H
class Gears : public Test class Gears : public Test
{ {
public: public:
Gears() Gears()
{ {
b2Body* ground = NULL; b2Body* ground = NULL;
{ {
b2BodyDef bd; b2BodyDef bd;
ground = m_world->CreateBody(&bd); ground = m_world->CreateBody(&bd);
b2EdgeShape shape; b2EdgeShape shape;
shape.Set(b2Vec2(50.0f, 0.0f), b2Vec2(-50.0f, 0.0f)) shape.Set(b2Vec2(50.0f, 0.0f), b2Vec2(-50.0f, 0.0f));
; ground->CreateFixture(&shape, 0.0f);
ground->CreateFixture(&shape, 0.0f); }
}
// Gears co
// Gears co {
{ b2CircleShape circle1;
b2CircleShape circle1; circle1.m_radius = 1.0f;
circle1.m_radius = 1.0f;
b2PolygonShape box;
b2PolygonShape box; box.SetAsBox(0.5f, 5.0f);
box.SetAsBox(0.5f, 5.0f);
b2CircleShape circle2;
b2CircleShape circle2; circle2.m_radius = 2.0f;
circle2.m_radius = 2.0f;
b2BodyDef bd1;
b2BodyDef bd1; bd1.type = b2_staticBody;
bd1.type = b2_staticBody; bd1.position.Set(10.0f, 9.0f);
bd1.position.Set(10.0f, 9.0f); b2Body* body1 = m_world->CreateBody(&bd1);
b2Body* body1 = m_world->CreateBody(&bd1); body1->CreateFixture(&circle1, 0.0f);
body1->CreateFixture(&circle1, 0.0f);
b2BodyDef bd2;
b2BodyDef bd2; bd2.type = b2_dynamicBody;
bd2.type = b2_dynamicBody; bd2.position.Set(10.0f, 8.0f);
bd2.position.Set(10.0f, 8.0f); b2Body* body2 = m_world->CreateBody(&bd2);
b2Body* body2 = m_world->CreateBody(&bd2); body2->CreateFixture(&box, 5.0f);
body2->CreateFixture(&box, 5.0f);
b2BodyDef bd3;
b2BodyDef bd3; bd3.type = b2_dynamicBody;
bd3.type = b2_dynamicBody; bd3.position.Set(10.0f, 6.0f);
bd3.position.Set(10.0f, 6.0f); b2Body* body3 = m_world->CreateBody(&bd3);
b2Body* body3 = m_world->CreateBody(&bd3); body3->CreateFixture(&circle2, 5.0f);
body3->CreateFixture(&circle2, 5.0f);
b2RevoluteJointDef jd1;
b2RevoluteJointDef jd1; jd1.Initialize(body2, body1, bd1.position);
jd1.Initialize(body2, body1, bd1.position); b2Joint* joint1 = m_world->CreateJoint(&jd1);
b2Joint* joint1 = m_world->CreateJoint(&jd1);
b2RevoluteJointDef jd2;
b2RevoluteJointDef jd2; jd2.Initialize(body2, body3, bd3.position);
jd2.Initialize(body2, body3, bd3.position); b2Joint* joint2 = m_world->CreateJoint(&jd2);
b2Joint* joint2 = m_world->CreateJoint(&jd2);
b2GearJointDef jd4;
b2GearJointDef jd4; jd4.bodyA = body1;
jd4.bodyA = body1; jd4.bodyB = body3;
jd4.bodyB = body3; jd4.joint1 = joint1;
jd4.joint1 = joint1; jd4.joint2 = joint2;
jd4.joint2 = joint2; jd4.ratio = circle2.m_radius / circle1.m_radius;
jd4.ratio = circle2.m_radius / circle1.m_radius; m_world->CreateJoint(&jd4);
m_world->CreateJoint(&jd4); }
}
{
{ b2CircleShape circle1;
b2CircleShape circle1; circle1.m_radius = 1.0f;
circle1.m_radius = 1.0f;
b2CircleShape circle2;
b2CircleShape circle2; circle2.m_radius = 2.0f;
circle2.m_radius = 2.0f;
b2PolygonShape box;
b2PolygonShape box; box.SetAsBox(0.5f, 5.0f);
box.SetAsBox(0.5f, 5.0f);
b2BodyDef bd1;
b2BodyDef bd1; bd1.type = b2_dynamicBody;
bd1.type = b2_dynamicBody; bd1.position.Set(-3.0f, 12.0f);
bd1.position.Set(-3.0f, 12.0f); b2Body* body1 = m_world->CreateBody(&bd1);
b2Body* body1 = m_world->CreateBody(&bd1); body1->CreateFixture(&circle1, 5.0f);
body1->CreateFixture(&circle1, 5.0f);
b2RevoluteJointDef jd1;
b2RevoluteJointDef jd1; jd1.bodyA = ground;
jd1.bodyA = ground; jd1.bodyB = body1;
jd1.bodyB = body1; jd1.localAnchorA = ground->GetLocalPoint(bd1.position);
jd1.localAnchorA = ground->GetLocalPoint(bd1.positio jd1.localAnchorB = body1->GetLocalPoint(bd1.position);
n); jd1.referenceAngle = body1->GetAngle() - ground->GetAngle();
jd1.localAnchorB = body1->GetLocalPoint(bd1.position m_joint1 = (b2RevoluteJoint*)m_world->CreateJoint(&jd1);
);
jd1.referenceAngle = body1->GetAngle() - ground->Get b2BodyDef bd2;
Angle(); bd2.type = b2_dynamicBody;
m_joint1 = (b2RevoluteJoint*)m_world->CreateJoint(&j bd2.position.Set(0.0f, 12.0f);
d1); b2Body* body2 = m_world->CreateBody(&bd2);
body2->CreateFixture(&circle2, 5.0f);
b2BodyDef bd2;
bd2.type = b2_dynamicBody; b2RevoluteJointDef jd2;
bd2.position.Set(0.0f, 12.0f); jd2.Initialize(ground, body2, bd2.position);
b2Body* body2 = m_world->CreateBody(&bd2); m_joint2 = (b2RevoluteJoint*)m_world->CreateJoint(&jd2);
body2->CreateFixture(&circle2, 5.0f);
b2BodyDef bd3;
b2RevoluteJointDef jd2; bd3.type = b2_dynamicBody;
jd2.Initialize(ground, body2, bd2.position); bd3.position.Set(2.5f, 12.0f);
m_joint2 = (b2RevoluteJoint*)m_world->CreateJoint(&j b2Body* body3 = m_world->CreateBody(&bd3);
d2); body3->CreateFixture(&box, 5.0f);
b2BodyDef bd3; b2PrismaticJointDef jd3;
bd3.type = b2_dynamicBody; jd3.Initialize(ground, body3, bd3.position, b2Vec2(0.0f, 1.0f))
bd3.position.Set(2.5f, 12.0f); ;
b2Body* body3 = m_world->CreateBody(&bd3); jd3.lowerTranslation = -5.0f;
body3->CreateFixture(&box, 5.0f); jd3.upperTranslation = 5.0f;
jd3.enableLimit = true;
b2PrismaticJointDef jd3;
jd3.Initialize(ground, body3, bd3.position, b2Vec2(0 m_joint3 = (b2PrismaticJoint*)m_world->CreateJoint(&jd3);
.0f, 1.0f));
jd3.lowerTranslation = -5.0f; b2GearJointDef jd4;
jd3.upperTranslation = 5.0f; jd4.bodyA = body1;
jd3.enableLimit = true; jd4.bodyB = body2;
jd4.joint1 = m_joint1;
m_joint3 = (b2PrismaticJoint*)m_world->CreateJoint(& jd4.joint2 = m_joint2;
jd3); jd4.ratio = circle2.m_radius / circle1.m_radius;
m_joint4 = (b2GearJoint*)m_world->CreateJoint(&jd4);
b2GearJointDef jd4;
jd4.bodyA = body1; b2GearJointDef jd5;
jd4.bodyB = body2; jd5.bodyA = body2;
jd4.joint1 = m_joint1; jd5.bodyB = body3;
jd4.joint2 = m_joint2; jd5.joint1 = m_joint2;
jd4.ratio = circle2.m_radius / circle1.m_radius; jd5.joint2 = m_joint3;
m_joint4 = (b2GearJoint*)m_world->CreateJoint(&jd4); jd5.ratio = -1.0f / circle2.m_radius;
m_joint5 = (b2GearJoint*)m_world->CreateJoint(&jd5);
b2GearJointDef jd5; }
jd5.bodyA = body2; }
jd5.bodyB = body3;
jd5.joint1 = m_joint2; void Keyboard(unsigned char key)
jd5.joint2 = m_joint3; {
jd5.ratio = -1.0f / circle2.m_radius; switch (key)
m_joint5 = (b2GearJoint*)m_world->CreateJoint(&jd5); {
} case 0:
} break;
}
void Keyboard(unsigned char key) }
{
switch (key) void Step(Settings* settings)
{ {
case 0: Test::Step(settings);
break;
} float32 ratio, value;
}
ratio = m_joint4->GetRatio();
void Step(Settings* settings) value = m_joint1->GetJointAngle() + ratio * m_joint2->GetJointAngle
{ ();
Test::Step(settings); m_debugDraw.DrawString(5, m_textLine, "theta1 + %4.2f * theta2 = %4
.2f", (float) ratio, (float) value);
float32 ratio, value; m_textLine += 15;
ratio = m_joint4->GetRatio(); ratio = m_joint5->GetRatio();
value = m_joint1->GetJointAngle() + ratio * m_joint2->GetJoi value = m_joint2->GetJointAngle() + ratio * m_joint3->GetJointTrans
ntAngle(); lation();
m_debugDraw.DrawString(5, m_textLine, "theta1 + %4.2f * thet m_debugDraw.DrawString(5, m_textLine, "theta2 + %4.2f * delta = %4.
a2 = %4.2f", (float) ratio, (float) value); 2f", (float) ratio, (float) value);
m_textLine += 15; m_textLine += 15;
}
ratio = m_joint5->GetRatio();
value = m_joint2->GetJointAngle() + ratio * m_joint3->GetJoi static Test* Create()
ntTranslation(); {
m_debugDraw.DrawString(5, m_textLine, "theta2 + %4.2f * delt return new Gears;
a = %4.2f", (float) ratio, (float) value); }
m_textLine += 15;
} b2RevoluteJoint* m_joint1;
b2RevoluteJoint* m_joint2;
static Test* Create() b2PrismaticJoint* m_joint3;
{ b2GearJoint* m_joint4;
return new Gears; b2GearJoint* m_joint5;
}
b2RevoluteJoint* m_joint1;
b2RevoluteJoint* m_joint2;
b2PrismaticJoint* m_joint3;
b2GearJoint* m_joint4;
b2GearJoint* m_joint5;
}; };
#endif #endif
 End of changes. 1 change blocks. 
172 lines changed or deleted 165 lines changed or added


 HTMLparser.h   HTMLparser.h 
skipping to change at line 180 skipping to change at line 180
* New set of simpler/more flexible APIs * New set of simpler/more flexible APIs
*/ */
/** /**
* xmlParserOption: * xmlParserOption:
* *
* This is the set of XML parser options that can be passed down * This is the set of XML parser options that can be passed down
* to the xmlReadDoc() and similar calls. * to the xmlReadDoc() and similar calls.
*/ */
typedef enum { typedef enum {
HTML_PARSE_RECOVER = 1<<0, /* Relaxed parsing */ HTML_PARSE_RECOVER = 1<<0, /* Relaxed parsing */
HTML_PARSE_NODEFDTD = 1<<2, /* do not default a doctype if not found */
HTML_PARSE_NOERROR = 1<<5, /* suppress error reports */ HTML_PARSE_NOERROR = 1<<5, /* suppress error reports */
HTML_PARSE_NOWARNING= 1<<6, /* suppress warning reports */ HTML_PARSE_NOWARNING= 1<<6, /* suppress warning reports */
HTML_PARSE_PEDANTIC = 1<<7, /* pedantic error reporting */ HTML_PARSE_PEDANTIC = 1<<7, /* pedantic error reporting */
HTML_PARSE_NOBLANKS = 1<<8, /* remove blank nodes */ HTML_PARSE_NOBLANKS = 1<<8, /* remove blank nodes */
HTML_PARSE_NONET = 1<<11,/* Forbid network access */ HTML_PARSE_NONET = 1<<11,/* Forbid network access */
HTML_PARSE_NOIMPLIED= 1<<13,/* Do not add implied html/body... elements */ HTML_PARSE_NOIMPLIED= 1<<13,/* Do not add implied html/body... elements */
HTML_PARSE_COMPACT = 1<<16 /* compact small text nodes */ HTML_PARSE_COMPACT = 1<<16 /* compact small text nodes */
} htmlParserOption; } htmlParserOption;
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
 End of changes. 1 change blocks. 
0 lines changed or deleted 1 lines changed or added


 HelloWorldScene.h   HelloWorldScene.h 
#ifndef __HELLOWORLD_SCENE_H__ #ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__ #define __HELLOWORLD_SCENE_H__
#include "cocos2d.h" #include "cocos2d.h"
class HelloWorld : public cocos2d::CCLayer class HelloWorld : public cocos2d::CCLayer
{ {
public: public:
// Here's a difference. Method 'init' in cocos2d-x returns bool, ins // Here's a difference. Method 'init' in cocos2d-x returns bool, instea
tead of returning 'id' in cocos2d-iphone d of returning 'id' in cocos2d-iphone
virtual bool init(); virtual bool init();
// there's no 'id' in cpp, so we recommand to return the exactly cla // there's no 'id' in cpp, so we recommand to return the exactly class
ss pointer pointer
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); CREATE_FUNC(HelloWorld);
}; };
#endif // __HELLOWORLD_SCENE_H__ #endif // __HELLOWORLD_SCENE_H__
 End of changes. 4 change blocks. 
10 lines changed or deleted 10 lines changed or added


 IntervalTest.h   IntervalTest.h 
#ifndef _INTERVAL_TEST_H_ #ifndef _INTERVAL_TEST_H_
#define _INTERVAL_TEST_H_ #define _INTERVAL_TEST_H_
#include "../testBasic.h" #include "../testBasic.h"
class IntervalLayer : public CCLayer class IntervalLayer : public CCLayer
{ {
protected: protected:
CCLabelBMFont* m_label0; CCLabelBMFont* m_label0;
CCLabelBMFont* m_label1; CCLabelBMFont* m_label1;
CCLabelBMFont* m_label2; CCLabelBMFont* m_label2;
CCLabelBMFont* m_label3; CCLabelBMFont* m_label3;
CCLabelBMFont* m_label4; CCLabelBMFont* m_label4;
ccTime m_time0, m_time1, m_time2, m_time3, m_time4; float m_time0, m_time1, m_time2, m_time3, m_time4;
public: public:
IntervalLayer(void); IntervalLayer(void);
virtual ~IntervalLayer(); virtual ~IntervalLayer();
public: public:
void onPause(CCObject* pSender); void onPause(CCObject* pSender);
void step1(ccTime dt); void step1(float dt);
void step2(ccTime dt); void step2(float dt);
void step3(ccTime dt); void step3(float dt);
void step4(ccTime dt); void step4(float dt);
void update(ccTime dt); void update(float dt);
//CREATE_NODE(IntervalLayer); //CREATE_NODE(IntervalLayer);
}; };
class IntervalTestScene : public TestScene class IntervalTestScene : public TestScene
{ {
public: public:
virtual void runThisTest(); virtual void runThisTest();
}; };
#endif #endif
 End of changes. 6 change blocks. 
14 lines changed or deleted 14 lines changed or added


 JniHelper.h   JniHelper.h 
skipping to change at line 29 skipping to change at line 29
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __ANDROID_JNI_HELPER_H__ #ifndef __ANDROID_JNI_HELPER_H__
#define __ANDROID_JNI_HELPER_H__ #define __ANDROID_JNI_HELPER_H__
#include <jni.h> #include <jni.h>
#include <string> #include <string>
#include "CCPlatformMacros.h" #include "platform/CCPlatformMacros.h"
namespace cocos2d { NS_CC_BEGIN
typedef struct JniMethodInfo_ typedef struct JniMethodInfo_
{ {
JNIEnv * env; JNIEnv * env;
jclass classID; jclass classID;
jmethodID methodID; jmethodID methodID;
} JniMethodInfo; } JniMethodInfo;
class CC_DLL JniHelper class CC_DLL JniHelper
{ {
public: public:
static JavaVM* getJavaVM(); static JavaVM* getJavaVM();
static void setJavaVM(JavaVM *javaVM); static void setJavaVM(JavaVM *javaVM);
static jclass getClassID(const char *className, JNIEnv *env= static jclass getClassID(const char *className, JNIEnv *env=0);
0); static bool getStaticMethodInfo(JniMethodInfo &methodinfo, const char *
static bool getStaticMethodInfo(JniMethodInfo &methodinfo, c className, const char *methodName, const char *paramCode);
onst char *className, const char *methodName, const char *paramCode); static bool getMethodInfo(JniMethodInfo &methodinfo, const char *classN
static bool getMethodInfo(JniMethodInfo &methodinfo, const c ame, const char *methodName, const char *paramCode);
har *className, const char *methodName, const char *paramCode); static std::string jstring2string(jstring str);
static std::string jstring2string(jstring str);
private:
private: static JavaVM *m_psJavaVM;
static JavaVM *m_psJavaVM; };
};
} NS_CC_END
#endif // __ANDROID_JNI_HELPER_H__ #endif // __ANDROID_JNI_HELPER_H__
 End of changes. 3 change blocks. 
26 lines changed or deleted 26 lines changed or added


 KeypadTest.h   KeypadTest.h 
#ifndef _KEYPAD_TEST_H_ #ifndef _KEYPAD_TEST_H_
#define _KEYPAD_TEST_H_ #define _KEYPAD_TEST_H_
#include "cocos2d.h" #include "cocos2d.h"
#include "../testBasic.h" #include "../testBasic.h"
class KeypadTest : public CCLayer class KeypadTest : public CCLayer
{ {
public: public:
KeypadTest(); KeypadTest();
~KeypadTest(); ~KeypadTest();
virtual void keyBackClicked(); virtual void keyBackClicked();
virtual void keyMenuClicked(); virtual void keyMenuClicked();
private: private:
CCLabelTTF* m_pLabel; CCLabelTTF* m_pLabel;
bool m_bShow; bool m_bShow;
}; };
class KeypadTestScene : public TestScene class KeypadTestScene : public TestScene
{ {
public: public:
virtual void runThisTest(); virtual void runThisTest();
}; };
#endif #endif
 End of changes. 3 change blocks. 
4 lines changed or deleted 4 lines changed or added


 LabelTest.h   LabelTest.h 
#ifndef _ATLAS_TEST_H_ #ifndef _ATLAS_TEST_H_
#define _ATLAS_TEST_H_ #define _ATLAS_TEST_H_
#include "../testBasic.h" #include "../testBasic.h"
class AtlasDemo : public CCLayer class AtlasDemo : public CCLayer
{ {
protected: protected:
public: public:
AtlasDemo(void); AtlasDemo(void);
~AtlasDemo(void); ~AtlasDemo(void);
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
virtual void onEnter(); virtual void onEnter();
void restartCallback(CCObject* pSender); void restartCallback(CCObject* pSender);
void nextCallback(CCObject* pSender); void nextCallback(CCObject* pSender);
void backCallback(CCObject* pSender); void backCallback(CCObject* pSender);
}; };
class Atlas1 : public AtlasDemo class Atlas1 : public AtlasDemo
{ {
CCTextureAtlas* m_textureAtlas; CCTextureAtlas* m_textureAtlas;
public: public:
Atlas1(); Atlas1();
~Atlas1(); ~Atlas1();
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
virtual void draw(); virtual void draw();
}; };
class LabelAtlasTest : public AtlasDemo class LabelAtlasTest : public AtlasDemo
{ {
ccTime m_time; float m_time;
public: public:
LabelAtlasTest(); LabelAtlasTest();
virtual void step(ccTime dt); virtual void step(float dt);
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
}; };
class LabelAtlasColorTest : public AtlasDemo class LabelAtlasColorTest : public AtlasDemo
{ {
ccTime m_time; float m_time;
public: public:
LabelAtlasColorTest(); LabelAtlasColorTest();
virtual void step(ccTime dt); virtual void step(float dt);
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
};
class LabelTTFAlignment : public AtlasDemo
{
public:
LabelTTFAlignment();
virtual std::string title();
virtual std::string subtitle();
}; };
class Atlas3 : public AtlasDemo class Atlas3 : public AtlasDemo
{ {
ccTime m_time; float m_time;
public: public:
Atlas3(); Atlas3();
virtual void step(ccTime dt); virtual void step(float dt);
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
}; };
class Atlas4 : public AtlasDemo class Atlas4 : public AtlasDemo
{ {
ccTime m_time; float m_time;
public: public:
Atlas4(); Atlas4();
virtual void step(ccTime dt); virtual void step(float dt);
virtual void draw(); virtual void draw();
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
}; };
class Atlas5 : public AtlasDemo class Atlas5 : public AtlasDemo
{ {
public: public:
Atlas5(); Atlas5();
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
}; };
class Atlas6 : public AtlasDemo class Atlas6 : public AtlasDemo
{ {
public: public:
Atlas6(); Atlas6();
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
}; };
class AtlasBitmapColor : public AtlasDemo class AtlasBitmapColor : public AtlasDemo
{ {
public: public:
AtlasBitmapColor(); AtlasBitmapColor();
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
}; };
class AtlasFastBitmap : public AtlasDemo class AtlasFastBitmap : public AtlasDemo
{ {
public: public:
AtlasFastBitmap(); AtlasFastBitmap();
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
}; };
class BitmapFontMultiLine : public AtlasDemo class BitmapFontMultiLine : public AtlasDemo
{ {
public: public:
BitmapFontMultiLine(); BitmapFontMultiLine();
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
}; };
class LabelsEmpty : public AtlasDemo class LabelsEmpty : public AtlasDemo
{ {
public: public:
LabelsEmpty(); LabelsEmpty();
void updateStrings(ccTime dt); void updateStrings(float dt);
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
private: private:
bool setEmpty; bool setEmpty;
}; };
class LabelBMFontHD : public AtlasDemo class LabelBMFontHD : public AtlasDemo
{ {
public: public:
skipping to change at line 166 skipping to change at line 174
class AtlasTestScene : public TestScene class AtlasTestScene : public TestScene
{ {
public: public:
virtual void runThisTest(); virtual void runThisTest();
}; };
class LabelTTFTest : public AtlasDemo class LabelTTFTest : public AtlasDemo
{ {
public: public:
LabelTTFTest(); LabelTTFTest();
virtual std::string title(); virtual ~LabelTTFTest();
virtual std::string subtitle(); virtual std::string title();
virtual std::string subtitle();
private:
void setAlignmentLeft(CCObject* pSender);
void setAlignmentCenter(CCObject* pSender);
void setAlignmentRight(CCObject* pSender);
void setAlignmentTop(CCObject* pSender);
void setAlignmentMiddle(CCObject* pSender);
void setAlignmentBottom(CCObject* pSender);
void updateAlignment();
const char* getCurrentAlignment();
private:
CCLabelTTF* m_plabel;
CCTextAlignment m_eHorizAlign;
CCVerticalTextAlignment m_eVertAlign;
}; };
class LabelTTFMultiline : public AtlasDemo class LabelTTFMultiline : public AtlasDemo
{ {
public: public:
LabelTTFMultiline(); LabelTTFMultiline();
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
}; };
class LabelTTFChinese : public AtlasDemo class LabelTTFChinese : public AtlasDemo
{ {
public: public:
LabelTTFChinese(); LabelTTFChinese();
virtual std::string title(); virtual std::string title();
}; };
class LabelBMFontChinese : public AtlasDemo class LabelBMFontChinese : public AtlasDemo
{ {
public: public:
LabelBMFontChinese(); LabelBMFontChinese();
virtual std::string title(); virtual std::string title();
}; };
class BitmapFontMultiLineAlignment : public AtlasDemo
{
public:
BitmapFontMultiLineAlignment();
~BitmapFontMultiLineAlignment();
void snapArrowsToEdge();
virtual std::string title();
virtual std::string subtitle();
void stringChanged(CCObject *sender);
void alignmentChanged(CCObject *sender);
virtual void ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent);
virtual void ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent);
virtual void ccTouchesMoved(CCSet *pTouches, CCEvent *pEvent);
public:
CCLabelBMFont *m_pLabelShouldRetain;
CCSprite *m_pArrowsBarShouldRetain;
CCSprite *m_pArrowsShouldRetain;
CCMenuItemFont *m_pLastSentenceItem, *m_pLastAlignmentItem;
bool m_drag;
};
class LabelTTFA8Test : public AtlasDemo
{
public:
LabelTTFA8Test();
virtual std::string title();
virtual std::string subtitle();
};
class BMFontOneAtlas : public AtlasDemo
{
public:
BMFontOneAtlas();
virtual std::string title();
virtual std::string subtitle();
};
class BMFontUnicode : public AtlasDemo
{
public:
BMFontUnicode();
virtual std::string title();
virtual std::string subtitle();
};
class BMFontInit : public AtlasDemo
{
public:
BMFontInit();
virtual std::string title();
virtual std::string subtitle();
};
class TTFFontInit : public AtlasDemo
{
public:
TTFFontInit();
virtual std::string title();
virtual std::string subtitle();
};
class Issue1343 : public AtlasDemo
{
public:
Issue1343();
virtual std::string title();
virtual std::string subtitle();
};
// we don't support linebreak mode // we don't support linebreak mode
#endif #endif
 End of changes. 27 change blocks. 
57 lines changed or deleted 155 lines changed or added


 LayerTest.h   LayerTest.h 
#ifndef _LAYER_TEST_H_ #ifndef _LAYER_TEST_H_
#define _LAYER_TEST_H_ #define _LAYER_TEST_H_
////----#include "cocos2d.h" ////----#include "cocos2d.h"
#include "../testBasic.h" #include "../testBasic.h"
class LayerTest : public CCLayer class LayerTest : public CCLayer
{ {
protected: protected:
std::string m_strTitle; std::string m_strTitle;
public: public:
LayerTest(void); LayerTest(void);
~LayerTest(void); ~LayerTest(void);
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
virtual void onEnter(); virtual void onEnter();
void restartCallback(CCObject* pSender); void restartCallback(CCObject* pSender);
void nextCallback(CCObject* pSender); void nextCallback(CCObject* pSender);
void backCallback(CCObject* pSender); void backCallback(CCObject* pSender);
}; };
class LayerTest1 : public LayerTest class LayerTest1 : public LayerTest
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
virtual std::string title(); virtual std::string title();
void registerWithTouchDispatcher(); void registerWithTouchDispatcher();
void updateSize(CCTouch*touch); void updateSize(CCPoint &touchLocation);
virtual bool ccTouchBegan(CCTouch* touche, CCEvent* event); virtual bool ccTouchBegan(CCTouch* touche, CCEvent* event);
virtual void ccTouchMoved(CCTouch* touche, CCEvent* event); virtual void ccTouchMoved(CCTouch* touche, CCEvent* event);
virtual void ccTouchEnded(CCTouch* touche, CCEvent* event); virtual void ccTouchEnded(CCTouch* touche, CCEvent* event);
}; };
class LayerTest2 : public LayerTest class LayerTest2 : public LayerTest
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
virtual std::string title(); virtual std::string title();
}; };
class LayerTestBlend : public LayerTest class LayerTestBlend : public LayerTest
{ {
public: public:
LayerTestBlend(); LayerTestBlend();
void newBlend(ccTime dt); void newBlend(float dt);
virtual std::string title(); virtual std::string title();
}; };
class LayerGradient : public LayerTest class LayerGradient : public LayerTest
{ {
public: public:
LayerGradient(); LayerGradient();
virtual void ccTouchesMoved(CCSet * touches, CCEvent *event); virtual void ccTouchesMoved(CCSet * touches, CCEvent *event);
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
void toggleItem(cocos2d::CCObject *sender); void toggleItem(cocos2d::CCObject *sender);
};
class LayerIgnoreAnchorPointPos : public LayerTest
{
public:
virtual void onEnter();
void onToggle(CCObject* pObject);
virtual std::string title();
virtual std::string subtitle();
};
class LayerIgnoreAnchorPointRot : public LayerTest
{
public:
virtual void onEnter();
void onToggle(CCObject* pObject);
virtual std::string title();
virtual std::string subtitle();
};
class LayerIgnoreAnchorPointScale : public LayerTest
{
public:
virtual void onEnter();
void onToggle(CCObject* pObject);
virtual std::string title();
virtual std::string subtitle();
}; };
class LayerTestScene : public TestScene class LayerTestScene : public TestScene
{ {
public: public:
virtual void runThisTest(); virtual void runThisTest();
}; };
#endif #endif
 End of changes. 10 change blocks. 
23 lines changed or deleted 50 lines changed or added


 MciPlayer.h   MciPlayer.h 
skipping to change at line 24 skipping to change at line 24
void Close(); void Close();
/** /**
@brief @brief
@param pFileName @param pFileName
@param nTimes @param nTimes
*/ */
void Open(const char* pFileName, UINT uId); void Open(const char* pFileName, UINT uId);
void Play(UINT uTimes = 1); void Play(UINT uTimes = 1);
/** /**
@brief @brief
*/ */
void Pause(); void Pause();
/** /**
@brief @brief
*/ */
void Resume(); void Resume();
skipping to change at line 58 skipping to change at line 58
*/ */
bool IsPlaying(); bool IsPlaying();
/** /**
@brief @brief
@return @return
*/ */
UINT GetSoundID(); UINT GetSoundID();
private: private:
friend LRESULT WINAPI _SoundPlayProc(HWND hWnd, UINT Msg, WPARAM wPa ram, LPARAM lParam); friend LRESULT WINAPI _SoundPlayProc(HWND hWnd, UINT Msg, WPARAM wParam , LPARAM lParam);
void _SendGenericCommand(int nCommand); void _SendGenericCommand(int nCommand);
HWND m_hWnd; HWND m_hWnd;
MCIDEVICEID m_hDev; MCIDEVICEID m_hDev;
UINT m_nSoundID; UINT m_nSoundID;
UINT m_uTimes; UINT m_uTimes;
bool m_bPlaying; bool m_bPlaying;
}; };
} // end of namespace CocosDenshion } // end of namespace CocosDenshion
#endif #endif
 End of changes. 4 change blocks. 
8 lines changed or deleted 8 lines changed or added


 MenuTest.h   MenuTest.h 
#ifndef _MENU_TEST_H_ #ifndef _MENU_TEST_H_
#define _MENU_TEST_H_ #define _MENU_TEST_H_
////----#include "cocos2d.h" ////----#include "cocos2d.h"
#include "../testBasic.h" #include "../testBasic.h"
class MenuLayer1 : public CCLayer class MenuLayerMainMenu : public CCLayer
{ {
protected: protected:
CCMenuItem* m_disabledItem; CCMenuItem* m_disabledItem;
public: public:
MenuLayer1(void); MenuLayerMainMenu(void);
~MenuLayer1(); ~MenuLayerMainMenu();
public: public:
virtual void registerWithTouchDispatcher(); virtual void registerWithTouchDispatcher();
virtual bool ccTouchBegan(CCTouch *touch, CCEvent * pEvent); virtual bool ccTouchBegan(CCTouch *touch, CCEvent * pEvent);
virtual void ccTouchEnded(CCTouch *touch, CCEvent * pEvent); virtual void ccTouchEnded(CCTouch *touch, CCEvent * pEvent);
virtual void ccTouchCancelled(CCTouch *touch, CCEvent * pEvent); virtual void ccTouchCancelled(CCTouch *touch, CCEvent * pEvent);
virtual void ccTouchMoved(CCTouch *touch, CCEvent * pEvent); virtual void ccTouchMoved(CCTouch *touch, CCEvent * pEvent);
void allowTouches(ccTime dt); void allowTouches(float dt);
void menuCallback(CCObject* pSender); void menuCallback(CCObject* pSender);
void menuCallbackConfig(CCObject* pSender); void menuCallbackConfig(CCObject* pSender);
void menuCallbackDisabled(CCObject* pSender); void menuCallbackDisabled(CCObject* pSender);
void menuCallbackEnable(CCObject* pSender); void menuCallbackEnable(CCObject* pSender);
void menuCallback2(CCObject* pSender); void menuCallback2(CCObject* pSender);
void onQuit(CCObject* pSender); void menuCallbackPriorityTest(CCObject* pSender);
void onQuit(CCObject* pSender);
//CREATE_NODE(MenuLayer1); //CREATE_NODE(MenuLayer1);
}; };
class MenuLayer2 : public CCLayer class MenuLayer2 : public CCLayer
{ {
protected: protected:
CCPoint m_centeredMenu; CCPoint m_centeredMenu;
bool m_alignedH; bool m_alignedH;
void alignMenusH(); void alignMenusH();
void alignMenusV(); void alignMenusV();
public: public:
MenuLayer2(void); MenuLayer2(void);
~MenuLayer2(); ~MenuLayer2();
public: public:
void menuCallback(CCObject* pSender); void menuCallback(CCObject* pSender);
void menuCallbackOpacity(CCObject* pSender); void menuCallbackOpacity(CCObject* pSender);
void menuCallbackAlign(CCObject* pSender); void menuCallbackAlign(CCObject* pSender);
//CREATE_NODE(MenuLayer2); //CREATE_NODE(MenuLayer2);
}; };
class MenuLayer3 : public CCLayer class MenuLayer3 : public CCLayer
{ {
protected: protected:
CCMenuItem* m_disabledItem; CCMenuItem* m_disabledItem;
public: public:
MenuLayer3(void); MenuLayer3(void);
~MenuLayer3(); ~MenuLayer3();
public: public:
void menuCallback(CCObject* pSender); void menuCallback(CCObject* pSender);
void menuCallback2(CCObject* pSender); void menuCallback2(CCObject* pSender);
void menuCallback3(CCObject* pSender); void menuCallback3(CCObject* pSender);
//CREATE_NODE(MenuLayer3); //CREATE_NODE(MenuLayer3);
}; };
class MenuLayer4 : public CCLayer class MenuLayer4 : public CCLayer
{ {
public: public:
MenuLayer4(void); MenuLayer4(void);
~MenuLayer4(); ~MenuLayer4();
public: public:
void menuCallback(CCObject* pSender); void menuCallback(CCObject* pSender);
void backCallback(CCObject* pSender); void backCallback(CCObject* pSender);
//CREATE_NODE(MenuLayer4); //CREATE_NODE(MenuLayer4);
};
class MenuLayerPriorityTest : public CCLayer
{
public:
MenuLayerPriorityTest();
~MenuLayerPriorityTest();
void menuCallback(CCObject* pSender);
void disableMenuCallback(CCObject* pSender);
void enableMenuCallback();
void togglePriorityCallback(CCObject* pSender);
private:
CCMenu* m_pMenu1;
CCMenu* m_pMenu2;
bool m_bPriority;
}; };
class MenuTestScene : public TestScene class MenuTestScene : public TestScene
{ {
public: public:
virtual void runThisTest(); virtual void runThisTest();
}; };
#endif #endif
 End of changes. 17 change blocks. 
34 lines changed or deleted 51 lines changed or added


 MessageJni.h   MessageJni.h 
skipping to change at line 30 skipping to change at line 30
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __ANDROID_MESSAGE_JNI_H__ #ifndef __ANDROID_MESSAGE_JNI_H__
#define __ANDROID_MESSAGE_JNI_H__ #define __ANDROID_MESSAGE_JNI_H__
extern "C" extern "C"
{ {
extern void showMessageBoxJNI(const char * pszMsg, const char * pszT extern void showMessageBoxJNI(const char * pszMsg, const char * pszTitl
itle); e);
extern void terminateProcessJNI(); extern void terminateProcessJNI();
extern char* getApkPath();
} }
#endif // __ANDROID_MESSAGE_JNI_H__ #endif // __ANDROID_MESSAGE_JNI_H__
 End of changes. 1 change blocks. 
3 lines changed or deleted 4 lines changed or added


 MotionStreakTest.h   MotionStreakTest.h 
#ifndef _MOTION_STREAK_TEST_H_ #ifndef _MOTION_STREAK_TEST_H_
#define _MOTION_STREAK_TEST_H_ #define _MOTION_STREAK_TEST_H_
////----#include "cocos2d.h" ////----#include "cocos2d.h"
#include "../testBasic.h" #include "../testBasic.h"
//using namespace cocos2d; //USING_NS_CC;
class MotionStreakTest : public CCLayer class MotionStreakTest : public CCLayer
{ {
public: public:
MotionStreakTest(void); MotionStreakTest(void);
~MotionStreakTest(void); ~MotionStreakTest(void);
virtual std::string title(); virtual std::string title();
virtual void onEnter(); virtual std::string subtitle();
virtual void onEnter();
void restartCallback(CCObject* pSender);
void nextCallback(CCObject* pSender); void restartCallback(CCObject* pSender);
void backCallback(CCObject* pSender); void nextCallback(CCObject* pSender);
void backCallback(CCObject* pSender);
void modeCallback(CCObject* pSender);
protected:
CCMotionStreak *streak;
}; };
class MotionStreakTest1 : public MotionStreakTest class MotionStreakTest1 : public MotionStreakTest
{ {
protected: protected:
CCNode* m_root; CCNode* m_root;
CCNode* m_target; CCNode* m_target;
CCMotionStreak* m_streak;
public: public:
virtual void onEnter(); virtual void onEnter();
void onUpdate(ccTime delta); void onUpdate(float delta);
virtual std::string title(); virtual std::string title();
}; };
class MotionStreakTest2 : public MotionStreakTest class MotionStreakTest2 : public MotionStreakTest
{ {
protected: protected:
CCNode* m_root; CCNode* m_root;
CCNode* m_target; CCNode* m_target;
CCMotionStreak* m_streak;
public:
virtual void onEnter();
void ccTouchesMoved(CCSet* touches, CCEvent* event);
virtual std::string title();
};
class Issue1358 : public MotionStreakTest
{
public: public:
virtual void onEnter(); virtual std::string title();
void ccTouchesMoved(CCSet* touches, CCEvent* event); virtual std::string subtitle();
virtual std::string title(); virtual void onEnter();
virtual void update(float dt);
private:
CCPoint m_center;
float m_fRadius;
float m_fAngle;
}; };
class MotionStreakTestScene : public TestScene class MotionStreakTestScene : public TestScene
{ {
public: public:
virtual void runThisTest(); virtual void runThisTest();
}; };
//CCLayer* nextAction(); //CCLayer* nextAction();
 End of changes. 8 change blocks. 
21 lines changed or deleted 36 lines changed or added


 NotificationCenterTest.h   NotificationCenterTest.h 
#ifndef __NOTIFICATIONCENTERTEST_H__ #ifndef __NOTIFICATIONCENTERTEST_H__
#define __NOTIFICATIONCENTERTEST_H__ #define __NOTIFICATIONCENTERTEST_H__
#include "cocos2d.h" #include "cocos2d.h"
#include "ExtensionsTest.h"
class NotificationCenterTest : public cocos2d::CCLayer class NotificationCenterTest : public cocos2d::CCLayer
{ {
public: public:
NotificationCenterTest(); NotificationCenterTest();
void toExtensionsMainLayer(cocos2d::CCObject* sender); void toExtensionsMainLayer(cocos2d::CCObject* sender);
void toggleSwitch(cocos2d::CCObject *sender); void toggleSwitch(cocos2d::CCObject *sender);
void connectToSwitch(cocos2d::CCObject *sender); void connectToSwitch(cocos2d::CCObject *sender);
private: private:
bool m_bShowImage; bool m_bShowImage;
 End of changes. 1 change blocks. 
1 lines changed or deleted 0 lines changed or added


 OneSidedPlatform.h   OneSidedPlatform.h 
skipping to change at line 26 skipping to change at line 26
* 3. This notice may not be removed or altered from any source distribution . * 3. This notice may not be removed or altered from any source distribution .
*/ */
#ifndef ONE_SIDED_PLATFORM_H #ifndef ONE_SIDED_PLATFORM_H
#define ONE_SIDED_PLATFORM_H #define ONE_SIDED_PLATFORM_H
class OneSidedPlatform : public Test class OneSidedPlatform : public Test
{ {
public: public:
enum State enum State
{ {
e_unknown, e_unknown,
e_above, e_above,
e_below e_below
}; };
OneSidedPlatform() OneSidedPlatform()
{ {
// Ground // Ground
{ {
b2BodyDef bd; b2BodyDef bd;
b2Body* ground = m_world->CreateBody(&bd); b2Body* ground = m_world->CreateBody(&bd);
b2EdgeShape shape; b2EdgeShape shape;
shape.Set(b2Vec2(-20.0f, 0.0f), b2Vec2(20.0f, 0.0f)) shape.Set(b2Vec2(-20.0f, 0.0f), b2Vec2(20.0f, 0.0f));
; ground->CreateFixture(&shape, 0.0f);
ground->CreateFixture(&shape, 0.0f); }
}
// Platform
// Platform {
{ b2BodyDef bd;
b2BodyDef bd; bd.position.Set(0.0f, 10.0f);
bd.position.Set(0.0f, 10.0f); b2Body* body = m_world->CreateBody(&bd);
b2Body* body = m_world->CreateBody(&bd);
b2PolygonShape shape;
b2PolygonShape shape; shape.SetAsBox(3.0f, 0.5f);
shape.SetAsBox(3.0f, 0.5f); m_platform = body->CreateFixture(&shape, 0.0f);
m_platform = body->CreateFixture(&shape, 0.0f);
m_bottom = 10.0f - 0.5f;
m_bottom = 10.0f - 0.5f; m_top = 10.0f + 0.5f;
m_top = 10.0f + 0.5f; }
}
// Actor
// Actor {
{ b2BodyDef bd;
b2BodyDef bd; bd.type = b2_dynamicBody;
bd.type = b2_dynamicBody; bd.position.Set(0.0f, 12.0f);
bd.position.Set(0.0f, 12.0f); b2Body* body = m_world->CreateBody(&bd);
b2Body* body = m_world->CreateBody(&bd);
m_radius = 0.5f;
m_radius = 0.5f; b2CircleShape shape;
b2CircleShape shape; shape.m_radius = m_radius;
shape.m_radius = m_radius; m_character = body->CreateFixture(&shape, 20.0f);
m_character = body->CreateFixture(&shape, 20.0f);
body->SetLinearVelocity(b2Vec2(0.0f, -50.0f));
body->SetLinearVelocity(b2Vec2(0.0f, -50.0f));
m_state = e_unknown;
m_state = e_unknown; }
} }
}
void PreSolve(b2Contact* contact, const b2Manifold* oldManifold)
void PreSolve(b2Contact* contact, const b2Manifold* oldManifold) {
{ Test::PreSolve(contact, oldManifold);
Test::PreSolve(contact, oldManifold);
b2Fixture* fixtureA = contact->GetFixtureA();
b2Fixture* fixtureA = contact->GetFixtureA(); b2Fixture* fixtureB = contact->GetFixtureB();
b2Fixture* fixtureB = contact->GetFixtureB();
if (fixtureA != m_platform && fixtureA != m_character)
if (fixtureA != m_platform && fixtureA != m_character) {
{ return;
return; }
}
if (fixtureB != m_platform && fixtureB != m_character)
if (fixtureB != m_platform && fixtureB != m_character) {
{ return;
return; }
}
b2Vec2 position = m_character->GetBody()->GetPosition();
b2Vec2 position = m_character->GetBody()->GetPosition();
if (position.y < m_top + m_radius - 3.0f * b2_linearSlop)
if (position.y < m_top + m_radius - 3.0f * b2_linearSlop) {
{ contact->SetEnabled(false);
contact->SetEnabled(false); }
} }
}
void Step(Settings* settings)
void Step(Settings* settings) {
{ Test::Step(settings);
Test::Step(settings); m_debugDraw.DrawString(5, m_textLine, "Press: (c) create a shape, (
m_debugDraw.DrawString(5, m_textLine, "Press: (c) create a s d) destroy a shape.");
hape, (d) destroy a shape."); m_textLine += 15;
m_textLine += 15; }
}
static Test* Create()
static Test* Create() {
{ return new OneSidedPlatform;
return new OneSidedPlatform; }
}
float32 m_radius, m_top, m_bottom;
float32 m_radius, m_top, m_bottom; State m_state;
State m_state; b2Fixture* m_platform;
b2Fixture* m_platform; b2Fixture* m_character;
b2Fixture* m_character;
}; };
#endif #endif
 End of changes. 1 change blocks. 
94 lines changed or deleted 93 lines changed or added


 OpenGL_Internal.h   OpenGL_Internal.h 
skipping to change at line 70 skipping to change at line 70
Copyright (C) 2008 Apple Inc. All Rights Reserved. Copyright (C) 2008 Apple Inc. All Rights Reserved.
*/ */
/* Generic error reporting */ /* Generic error reporting */
#define REPORT_ERROR(__FORMAT__, ...) printf("%s: %s\n", __FUNCTION__, [[NS String stringWithFormat:__FORMAT__, __VA_ARGS__] UTF8String]) #define REPORT_ERROR(__FORMAT__, ...) printf("%s: %s\n", __FUNCTION__, [[NS String stringWithFormat:__FORMAT__, __VA_ARGS__] UTF8String])
/* EAGL and GL functions calling wrappers that log on error */ /* EAGL and GL functions calling wrappers that log on error */
#define CALL_EAGL_FUNCTION(__FUNC__, ...) ({ EAGLError __error = __FUNC__( __VA_ARGS__ ); if(__error != kEAGLErrorSuccess) printf("%s() called from %s returned error %i\n", #__FUNC__, __FUNCTION__, __error); (__error ? NO : Y ES); }) #define CALL_EAGL_FUNCTION(__FUNC__, ...) ({ EAGLError __error = __FUNC__( __VA_ARGS__ ); if(__error != kEAGLErrorSuccess) printf("%s() called from %s returned error %i\n", #__FUNC__, __FUNCTION__, __error); (__error ? NO : Y ES); })
//#define CHECK_GL_ERROR() ({ GLenum __error = glGetError(); if(__error) pr intf("OpenGL error 0x%04X in %s\n", __error, __FUNCTION__); (__error ? NO : YES); }) //#define CHECK_GL_ERROR() ({ GLenum __error = glGetError(); if(__error) pr intf("OpenGL error 0x%04X in %s\n", __error, __FUNCTION__); (__error ? NO : YES); })
#define CHECK_GL_ERROR() ({ GLenum __error = glGetError(); if(__error) prin tf("OpenGL error 0x%04X in %s\n", __error, __FUNCTION__); }) #define CHECK_GL_ERROR() ({ GLenum __error = glGetError(); if(__error) prin tf("OpenGL error 0x%04X in %s %d\n", __error, __FUNCTION__, __LINE__); })
/* Optional delegate methods support */ /* Optional delegate methods support */
#ifndef __DELEGATE_IVAR__ #ifndef __DELEGATE_IVAR__
#define __DELEGATE_IVAR__ _delegate #define __DELEGATE_IVAR__ _delegate
#endif #endif
#ifndef __DELEGATE_METHODS_IVAR__ #ifndef __DELEGATE_METHODS_IVAR__
#define __DELEGATE_METHODS_IVAR__ _delegateMethods #define __DELEGATE_METHODS_IVAR__ _delegateMethods
#endif #endif
#define TEST_DELEGATE_METHOD_BIT(__BIT__) (self->__DELEGATE_METHODS_IVAR__ & (1 << __BIT__)) #define TEST_DELEGATE_METHOD_BIT(__BIT__) (self->__DELEGATE_METHODS_IVAR__ & (1 << __BIT__))
#define SET_DELEGATE_METHOD_BIT(__BIT__, __NAME__) { if([self->__DELEGATE_I VAR__ respondsToSelector:@selector(__NAME__)]) self->__DELEGATE_METHODS_IVA R__ |= (1 << __BIT__); else self->__DELEGATE_METHODS_IVAR__ &= ~(1 << __BIT __); } #define SET_DELEGATE_METHOD_BIT(__BIT__, __NAME__) { if([self->__DELEGATE_I VAR__ respondsToSelector:@selector(__NAME__)]) self->__DELEGATE_METHODS_IVA R__ |= (1 << __BIT__); else self->__DELEGATE_METHODS_IVAR__ &= ~(1 << __BIT __); }
 End of changes. 1 change blocks. 
1 lines changed or deleted 1 lines changed or added


 Paddle.h   Paddle.h 
#ifndef _PADDLE_H_ #ifndef _PADDLE_H_
#define _PADDLE_H_ #define _PADDLE_H_
#include "cocos2d.h" #include "cocos2d.h"
using namespace cocos2d; USING_NS_CC;
typedef enum tagPaddleState typedef enum tagPaddleState
{ {
kPaddleStateGrabbed, kPaddleStateGrabbed,
kPaddleStateUngrabbed kPaddleStateUngrabbed
} PaddleState; } PaddleState;
class Paddle : public CCSprite, public CCTargetedTouchDelegate class Paddle : public CCSprite, public CCTargetedTouchDelegate
{ {
PaddleState m_state; PaddleState m_state;
public: public:
Paddle(void); Paddle(void);
virtual ~Paddle(void); virtual ~Paddle(void);
CCRect rect(); CCRect rect();
bool initWithTexture(CCTexture2D* aTexture); bool initWithTexture(CCTexture2D* aTexture);
virtual void onEnter(); virtual void onEnter();
virtual void onExit(); virtual void onExit();
bool containsTouchLocation(CCTouch* touch); bool containsTouchLocation(CCTouch* touch);
virtual bool ccTouchBegan(CCTouch* touch, CCEvent* event); virtual bool ccTouchBegan(CCTouch* touch, CCEvent* event);
virtual void ccTouchMoved(CCTouch* touch, CCEvent* event); virtual void ccTouchMoved(CCTouch* touch, CCEvent* event);
virtual void ccTouchEnded(CCTouch* touch, CCEvent* event); virtual void ccTouchEnded(CCTouch* touch, CCEvent* event);
virtual CCObject* copyWithZone(CCZone *pZone);
virtual void touchDelegateRetain(); virtual void touchDelegateRetain();
virtual void touchDelegateRelease(); virtual void touchDelegateRelease();
static Paddle* paddleWithTexture(CCTexture2D* aTexture); static Paddle* paddleWithTexture(CCTexture2D* aTexture);
}; };
#endif #endif
 End of changes. 7 change blocks. 
17 lines changed or deleted 18 lines changed or added


 ParallaxTest.h   ParallaxTest.h 
skipping to change at line 12 skipping to change at line 12
#define _PARALLAX_TEST_H_ #define _PARALLAX_TEST_H_
#include "../testBasic.h" #include "../testBasic.h"
class ParallaxDemo : public CCLayer class ParallaxDemo : public CCLayer
{ {
protected: protected:
CCTextureAtlas* m_atlas; CCTextureAtlas* m_atlas;
public: public:
ParallaxDemo(void); ParallaxDemo(void);
~ParallaxDemo(void); ~ParallaxDemo(void);
virtual std::string title(); virtual std::string title();
virtual void onEnter(); virtual void onEnter();
void restartCallback(CCObject* pSender); void restartCallback(CCObject* pSender);
void nextCallback(CCObject* pSender); void nextCallback(CCObject* pSender);
void backCallback(CCObject* pSender); void backCallback(CCObject* pSender);
}; };
class Parallax1 : public ParallaxDemo class Parallax1 : public ParallaxDemo
{ {
protected: protected:
CCNode* m_root; CCNode* m_root;
CCNode* m_target; CCNode* m_target;
CCMotionStreak* m_streak; CCMotionStreak* m_streak;
public: public:
Parallax1(); Parallax1();
virtual std::string title(); virtual std::string title();
}; };
class Parallax2 : public ParallaxDemo class Parallax2 : public ParallaxDemo
{ {
protected: protected:
CCNode* m_root; CCNode* m_root;
CCNode* m_target; CCNode* m_target;
CCMotionStreak* m_streak; CCMotionStreak* m_streak;
public: public:
Parallax2(); Parallax2();
virtual void registerWithTouchDispatcher(); virtual void registerWithTouchDispatcher();
virtual bool ccTouchBegan(CCTouch* touch, CCEvent* event); virtual bool ccTouchBegan(CCTouch* touch, CCEvent* event);
virtual void ccTouchEnded(CCTouch* touch, CCEvent* event); virtual void ccTouchEnded(CCTouch* touch, CCEvent* event);
virtual void ccTouchCancelled(CCTouch* touch, CCEvent* event); virtual void ccTouchCancelled(CCTouch* touch, CCEvent* event);
virtual void ccTouchMoved(CCTouch* touch, CCEvent* event); virtual void ccTouchMoved(CCTouch* touch, CCEvent* event);
virtual std::string title(); virtual std::string title();
}; };
class ParallaxTestScene : public TestScene class ParallaxTestScene : public TestScene
{ {
public: public:
virtual void runThisTest(); virtual void runThisTest();
}; };
#endif #endif
 End of changes. 9 change blocks. 
22 lines changed or deleted 22 lines changed or added


 ParticleTest.h   ParticleTest.h 
skipping to change at line 18 skipping to change at line 18
class ParticleTestScene : public TestScene class ParticleTestScene : public TestScene
{ {
public: public:
virtual void runThisTest(); virtual void runThisTest();
}; };
class ParticleDemo : public CCLayerColor class ParticleDemo : public CCLayerColor
{ {
protected: protected:
CCParticleSystem* m_emitter; CCParticleSystem* m_emitter;
CCSprite* m_background; CCSprite* m_background;
public: public:
ParticleDemo(void); ~ParticleDemo(void);
~ParticleDemo(void);
virtual void onEnter(void); virtual void onEnter(void);
virtual std::string title(); virtual std::string title();
virtual std::string subtitle();
void restartCallback(CCObject* pSender);
void nextCallback(CCObject* pSender);
void backCallback(CCObject* pSender);
void toggleCallback(CCObject* pSender);
virtual void registerWithTouchDispatcher(); void restartCallback(CCObject* pSender);
virtual bool ccTouchBegan(CCTouch* touch, CCEvent* event); void nextCallback(CCObject* pSender);
virtual void ccTouchMoved(CCTouch* touch, CCEvent* event); void backCallback(CCObject* pSender);
virtual void ccTouchEnded(CCTouch* touch, CCEvent* event); void toggleCallback(CCObject* pSender);
virtual void registerWithTouchDispatcher();
virtual bool ccTouchBegan(CCTouch* touch, CCEvent* event);
virtual void ccTouchMoved(CCTouch* touch, CCEvent* event);
virtual void ccTouchEnded(CCTouch* touch, CCEvent* event);
void step(ccTime dt); virtual void update(float dt);
void setEmitterPosition(); void setEmitterPosition();
}; };
class DemoFirework : public ParticleDemo class DemoFirework : public ParticleDemo
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
virtual std::string title(); virtual std::string title();
}; };
class DemoFire : public ParticleDemo class DemoFire : public ParticleDemo
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
virtual std::string title(); virtual std::string title();
}; };
class DemoSun : public ParticleDemo class DemoSun : public ParticleDemo
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
virtual std::string title(); virtual std::string title();
}; };
class DemoGalaxy : public ParticleDemo class DemoGalaxy : public ParticleDemo
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
virtual std::string title(); virtual std::string title();
}; };
class DemoFlower : public ParticleDemo class DemoFlower : public ParticleDemo
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
virtual std::string title(); virtual std::string title();
}; };
class DemoBigFlower : public ParticleDemo class DemoBigFlower : public ParticleDemo
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
virtual std::string title(); virtual std::string title();
}; };
class DemoRotFlower : public ParticleDemo class DemoRotFlower : public ParticleDemo
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
virtual std::string title(); virtual std::string title();
}; };
class DemoMeteor : public ParticleDemo class DemoMeteor : public ParticleDemo
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
virtual std::string title(); virtual std::string title();
}; };
class DemoSpiral : public ParticleDemo class DemoSpiral : public ParticleDemo
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
virtual std::string title(); virtual std::string title();
}; };
class DemoExplosion : public ParticleDemo class DemoExplosion : public ParticleDemo
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
virtual std::string title(); virtual std::string title();
}; };
class DemoSmoke : public ParticleDemo class DemoSmoke : public ParticleDemo
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
virtual std::string title(); virtual std::string title();
}; };
class DemoSnow : public ParticleDemo class DemoSnow : public ParticleDemo
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
virtual std::string title(); virtual std::string title();
}; };
class DemoRain : public ParticleDemo class DemoRain : public ParticleDemo
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
virtual std::string title(); virtual std::string title();
}; };
class DemoModernArt : public ParticleDemo class DemoModernArt : public ParticleDemo
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
virtual std::string title(); virtual std::string title();
}; };
class DemoRing : public ParticleDemo class DemoRing : public ParticleDemo
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
virtual std::string title(); virtual std::string title();
}; };
class ParallaxParticle : public ParticleDemo class ParallaxParticle : public ParticleDemo
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
virtual std::string title(); virtual std::string title();
}; };
class DemoParticleFromFile : public ParticleDemo class DemoParticleFromFile : public ParticleDemo
{ {
public: public:
std::string m_title; std::string m_title;
DemoParticleFromFile(const char *file) DemoParticleFromFile(const char *file)
{ {
m_title = file; m_title = file;
} }
skipping to change at line 198 skipping to change at line 198
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
}; };
class Issue870 : public ParticleDemo class Issue870 : public ParticleDemo
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
void updateQuads(ccTime dt); void updateQuads(float dt);
private: private:
int m_nIndex; int m_nIndex;
}; };
class Issue1201 : public ParticleDemo
{
public:
virtual void onEnter();
virtual std::string title();
virtual std::string subtitle();
};
class ParticleBatchHybrid : public ParticleDemo
{
public:
virtual void onEnter();
void switchRender(float dt);
virtual std::string title();
virtual std::string subtitle();
private:
CCNode* m_pParent1;
CCNode* m_pParent2;
};
class ParticleBatchMultipleEmitters : public ParticleDemo
{
public:
virtual void onEnter();
virtual std::string title();
virtual std::string subtitle();
};
class ParticleReorder : public ParticleDemo
{
public:
virtual void onEnter();
void reorderParticles(float dt);
virtual std::string title();
virtual std::string subtitle();
private:
unsigned int m_nOrder;
};
class MultipleParticleSystems : public ParticleDemo
{
public:
virtual void onEnter();
virtual std::string title();
virtual std::string subtitle();
virtual void update(float dt);
};
class MultipleParticleSystemsBatched : public ParticleDemo
{
public:
virtual void onEnter();
virtual void update(float dt);
virtual std::string title();
virtual std::string subtitle();
private:
CCParticleBatchNode* m_pBatchNode;
};
class AddAndDeleteParticleSystems : public ParticleDemo
{
public:
virtual void onEnter();
virtual void update(float dt);
void removeSystem(float dt);
virtual std::string title();
virtual std::string subtitle();
private:
CCParticleBatchNode* m_pBatchNode;
};
class ReorderParticleSystems : public ParticleDemo
{
public:
virtual void onEnter();
void reorderSystem(float time);
virtual void update(float dt);
virtual std::string title();
virtual std::string subtitle();
private:
CCParticleBatchNode* m_pBatchNode;
};
class PremultipliedAlphaTest : public ParticleDemo
{
public:
virtual void onEnter();
virtual std::string title();
virtual std::string subtitle();
};
class PremultipliedAlphaTest2 : public ParticleDemo
{
public:
virtual void onEnter();
virtual std::string title();
virtual std::string subtitle();
};
#endif #endif
 End of changes. 24 change blocks. 
50 lines changed or deleted 149 lines changed or added


 PerformanceNodeChildrenTest.h   PerformanceNodeChildrenTest.h 
skipping to change at line 29 skipping to change at line 29
virtual std::string subtitle(); virtual std::string subtitle();
virtual void updateQuantityOfNodes() = 0; virtual void updateQuantityOfNodes() = 0;
void onDecrease(CCObject* pSender); void onDecrease(CCObject* pSender);
void onIncrease(CCObject* pSender); void onIncrease(CCObject* pSender);
void updateQuantityLabel(); void updateQuantityLabel();
int getQuantityOfNodes() { return quantityOfNodes; } int getQuantityOfNodes() { return quantityOfNodes; }
protected: protected:
int lastRenderedCount; int lastRenderedCount;
int quantityOfNodes; int quantityOfNodes;
int currentQuantityOfNodes; int currentQuantityOfNodes;
}; };
class IterateSpriteSheet : public NodeChildrenMainScene class IterateSpriteSheet : public NodeChildrenMainScene
{ {
public: public:
~IterateSpriteSheet(); ~IterateSpriteSheet();
virtual void updateQuantityOfNodes(); virtual void updateQuantityOfNodes();
virtual void initWithQuantityOfNodes(unsigned int nNodes); virtual void initWithQuantityOfNodes(unsigned int nNodes);
virtual void update(ccTime dt) = 0; virtual void update(float dt) = 0;
virtual std::string profilerName(); virtual std::string profilerName();
protected: protected:
CCSpriteBatchNode *batchNode; CCSpriteBatchNode *batchNode;
#if CC_ENABLE_PROFILERS #if CC_ENABLE_PROFILERS
CCProfilingTimer *_profilingTimer; CCProfilingTimer *_profilingTimer;
#endif #endif
}; };
class IterateSpriteSheetFastEnum : public IterateSpriteSheet class IterateSpriteSheetFastEnum : public IterateSpriteSheet
{ {
public: public:
virtual void update(ccTime dt); virtual void update(float dt);
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
virtual std::string profilerName(); virtual std::string profilerName();
}; };
class IterateSpriteSheetCArray : public IterateSpriteSheet class IterateSpriteSheetCArray : public IterateSpriteSheet
{ {
public: public:
virtual void update(ccTime dt); virtual void update(float dt);
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
virtual std::string profilerName(); virtual std::string profilerName();
}; };
class AddRemoveSpriteSheet : public NodeChildrenMainScene class AddRemoveSpriteSheet : public NodeChildrenMainScene
{ {
public: public:
~AddRemoveSpriteSheet(); ~AddRemoveSpriteSheet();
virtual void updateQuantityOfNodes(); virtual void updateQuantityOfNodes();
virtual void initWithQuantityOfNodes(unsigned int nNodes); virtual void initWithQuantityOfNodes(unsigned int nNodes);
virtual void update(ccTime dt) = 0; virtual void update(float dt) = 0;
virtual std::string profilerName(); virtual std::string profilerName();
protected: protected:
CCSpriteBatchNode *batchNode; CCSpriteBatchNode *batchNode;
#if CC_ENABLE_PROFILERS #if CC_ENABLE_PROFILERS
CCProfilingTimer* _profilingTimer; CCProfilingTimer* _profilingTimer;
#endif #endif
}; };
class AddSpriteSheet : public AddRemoveSpriteSheet class AddSpriteSheet : public AddRemoveSpriteSheet
{ {
public: public:
virtual void update(ccTime dt); virtual void update(float dt);
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
virtual std::string profilerName(); virtual std::string profilerName();
}; };
class RemoveSpriteSheet : public AddRemoveSpriteSheet class RemoveSpriteSheet : public AddRemoveSpriteSheet
{ {
public: public:
virtual void update(ccTime dt); virtual void update(float dt);
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
virtual std::string profilerName(); virtual std::string profilerName();
}; };
class ReorderSpriteSheet : public AddRemoveSpriteSheet class ReorderSpriteSheet : public AddRemoveSpriteSheet
{ {
public: public:
virtual void update(ccTime dt); virtual void update(float dt);
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
virtual std::string profilerName(); virtual std::string profilerName();
}; };
void runNodeChildrenTest(); void runNodeChildrenTest();
#endif // __PERFORMANCE_NODE_CHILDREN_TEST_H__ #endif // __PERFORMANCE_NODE_CHILDREN_TEST_H__
 End of changes. 10 change blocks. 
12 lines changed or deleted 12 lines changed or added


 PerformanceParticleTest.h   PerformanceParticleTest.h 
skipping to change at line 19 skipping to change at line 19
ParticleMenuLayer(bool bControlMenuVisible, int nMaxCases = 0, int nCur Case = 0); ParticleMenuLayer(bool bControlMenuVisible, int nMaxCases = 0, int nCur Case = 0);
virtual void showCurrentTest(); virtual void showCurrentTest();
}; };
class ParticleMainScene : public CCScene class ParticleMainScene : public CCScene
{ {
public: public:
virtual void initWithSubTest(int subtest, int particles); virtual void initWithSubTest(int subtest, int particles);
virtual std::string title(); virtual std::string title();
void step(ccTime dt); void step(float dt);
void createParticleSystem(); void createParticleSystem();
void onDecrease(CCObject* pSender); void onDecrease(CCObject* pSender);
void onIncrease(CCObject* pSender); void onIncrease(CCObject* pSender);
void testNCallback(CCObject* pSender); void testNCallback(CCObject* pSender);
void updateQuantityLabel(); void updateQuantityLabel();
int getSubTestNum() { return subtestNumber; } int getSubTestNum() { return subtestNumber; }
int getParticlesNum() { return quantityParticles; } int getParticlesNum() { return quantityParticles; }
virtual void doTest() = 0; virtual void doTest() = 0;
protected: protected:
int lastRenderedCount; int lastRenderedCount;
int quantityParticles; int quantityParticles;
int subtestNumber; int subtestNumber;
}; };
class ParticlePerformTest1 : public ParticleMainScene class ParticlePerformTest1 : public ParticleMainScene
{ {
public: public:
virtual std::string title(); virtual std::string title();
virtual void doTest(); virtual void doTest();
}; };
class ParticlePerformTest2 : public ParticleMainScene class ParticlePerformTest2 : public ParticleMainScene
 End of changes. 2 change blocks. 
4 lines changed or deleted 4 lines changed or added


 PerformanceSpriteTest.h   PerformanceSpriteTest.h 
skipping to change at line 15 skipping to change at line 15
class SubTest class SubTest
{ {
public: public:
~SubTest(); ~SubTest();
void removeByTag(int tag); void removeByTag(int tag);
CCSprite* createSpriteWithTag(int tag); CCSprite* createSpriteWithTag(int tag);
void initWithSubTest(int nSubTest, CCNode* parent); void initWithSubTest(int nSubTest, CCNode* parent);
protected: protected:
int subtestNumber; int subtestNumber;
CCSpriteBatchNode *batchNode; CCSpriteBatchNode *batchNode;
CCNode* parent; CCNode* parent;
}; };
class SpriteMenuLayer : public PerformBasicLayer class SpriteMenuLayer : public PerformBasicLayer
{ {
public: public:
SpriteMenuLayer(bool bControlMenuVisible, int nMaxCases = 0, int nCurCa se = 0) SpriteMenuLayer(bool bControlMenuVisible, int nMaxCases = 0, int nCurCa se = 0)
: PerformBasicLayer(bControlMenuVisible, nMaxCases, nCurCase) : PerformBasicLayer(bControlMenuVisible, nMaxCases, nCurCase)
{ {
} }
skipping to change at line 50 skipping to change at line 50
void testNCallback(CCObject* pSender); void testNCallback(CCObject* pSender);
void onIncrease(CCObject* pSender); void onIncrease(CCObject* pSender);
void onDecrease(CCObject* pSender); void onDecrease(CCObject* pSender);
virtual void doTest(CCSprite* sprite) = 0; virtual void doTest(CCSprite* sprite) = 0;
int getSubTestNum() { return subtestNumber; } int getSubTestNum() { return subtestNumber; }
int getNodesNum() { return quantityNodes; } int getNodesNum() { return quantityNodes; }
protected: protected:
int lastRenderedCount; int lastRenderedCount;
int quantityNodes; int quantityNodes;
SubTest *m_pSubTest; SubTest *m_pSubTest;
int subtestNumber; int subtestNumber;
}; };
class SpritePerformTest1 : public SpriteMainScene class SpritePerformTest1 : public SpriteMainScene
{ {
public: public:
virtual void doTest(CCSprite* sprite); virtual void doTest(CCSprite* sprite);
virtual std::string title(); virtual std::string title();
}; };
class SpritePerformTest2 : public SpriteMainScene class SpritePerformTest2 : public SpriteMainScene
 End of changes. 2 change blocks. 
7 lines changed or deleted 7 lines changed or added


 PerformanceTouchesTest.h   PerformanceTouchesTest.h 
skipping to change at line 17 skipping to change at line 17
{ {
public: public:
TouchesMainScene(bool bControlMenuVisible, int nMaxCases = 0, int nCurC ase = 0) TouchesMainScene(bool bControlMenuVisible, int nMaxCases = 0, int nCurC ase = 0)
: PerformBasicLayer(bControlMenuVisible, nMaxCases, nCurCase) : PerformBasicLayer(bControlMenuVisible, nMaxCases, nCurCase)
{ {
} }
virtual void showCurrentTest(); virtual void showCurrentTest();
virtual void onEnter(); virtual void onEnter();
virtual std::string title(); virtual std::string title();
virtual void update(ccTime dt); virtual void update(float dt);
protected: protected:
CCLabelBMFont * m_plabel; CCLabelBMFont * m_plabel;
int numberOfTouchesB; int numberOfTouchesB;
int numberOfTouchesM; int numberOfTouchesM;
int numberOfTouchesE; int numberOfTouchesE;
int numberOfTouchesC; int numberOfTouchesC;
ccTime elapsedTime; float elapsedTime;
}; };
class TouchesPerformTest1 : public TouchesMainScene class TouchesPerformTest1 : public TouchesMainScene
{ {
public: public:
TouchesPerformTest1(bool bControlMenuVisible, int nMaxCases = 0, int nC urCase = 0) TouchesPerformTest1(bool bControlMenuVisible, int nMaxCases = 0, int nC urCase = 0)
: TouchesMainScene(bControlMenuVisible, nMaxCases, nCurCase) : TouchesMainScene(bControlMenuVisible, nMaxCases, nCurCase)
{ {
} }
 End of changes. 2 change blocks. 
6 lines changed or deleted 6 lines changed or added


 Pinball.h   Pinball.h 
skipping to change at line 27 skipping to change at line 27
*/ */
#ifndef PINBALL_H #ifndef PINBALL_H
#define PINBALL_H #define PINBALL_H
/// This tests bullet collision and provides an example of a gameplay scena rio. /// This tests bullet collision and provides an example of a gameplay scena rio.
/// This also uses a loop shape. /// This also uses a loop shape.
class Pinball : public Test class Pinball : public Test
{ {
public: public:
Pinball() Pinball()
{ {
// Ground body // Ground body
b2Body* ground = NULL; b2Body* ground = NULL;
{ {
b2BodyDef bd; b2BodyDef bd;
ground = m_world->CreateBody(&bd); ground = m_world->CreateBody(&bd);
b2Vec2 vs[5]; b2Vec2 vs[5];
vs[0].Set(0.0f, -2.0f); vs[0].Set(0.0f, -2.0f);
vs[1].Set(8.0f, 6.0f); vs[1].Set(8.0f, 6.0f);
vs[2].Set(8.0f, 20.0f); vs[2].Set(8.0f, 20.0f);
vs[3].Set(-8.0f, 20.0f); vs[3].Set(-8.0f, 20.0f);
vs[4].Set(-8.0f, 6.0f); vs[4].Set(-8.0f, 6.0f);
b2ChainShape loop; b2ChainShape loop;
loop.CreateLoop(vs, 5); loop.CreateLoop(vs, 5);
b2FixtureDef fd; b2FixtureDef fd;
fd.shape = &loop; fd.shape = &loop;
fd.density = 0.0f; fd.density = 0.0f;
ground->CreateFixture(&fd); ground->CreateFixture(&fd);
} }
// Flippers // Flippers
{ {
b2Vec2 p1(-2.0f, 0.0f), p2(2.0f, 0.0f); b2Vec2 p1(-2.0f, 0.0f), p2(2.0f, 0.0f);
b2BodyDef bd; b2BodyDef bd;
bd.type = b2_dynamicBody; bd.type = b2_dynamicBody;
bd.position = p1; bd.position = p1;
b2Body* leftFlipper = m_world->CreateBody(&bd); b2Body* leftFlipper = m_world->CreateBody(&bd);
bd.position = p2; bd.position = p2;
b2Body* rightFlipper = m_world->CreateBody(&bd); b2Body* rightFlipper = m_world->CreateBody(&bd);
b2PolygonShape box; b2PolygonShape box;
box.SetAsBox(1.75f, 0.1f); box.SetAsBox(1.75f, 0.1f);
b2FixtureDef fd; b2FixtureDef fd;
fd.shape = &box; fd.shape = &box;
fd.density = 1.0f; fd.density = 1.0f;
leftFlipper->CreateFixture(&fd); leftFlipper->CreateFixture(&fd);
rightFlipper->CreateFixture(&fd); rightFlipper->CreateFixture(&fd);
b2RevoluteJointDef jd; b2RevoluteJointDef jd;
jd.bodyA = ground; jd.bodyA = ground;
jd.localAnchorB.SetZero(); jd.localAnchorB.SetZero();
jd.enableMotor = true; jd.enableMotor = true;
jd.maxMotorTorque = 1000.0f; jd.maxMotorTorque = 1000.0f;
jd.enableLimit = true; jd.enableLimit = true;
jd.motorSpeed = 0.0f; jd.motorSpeed = 0.0f;
jd.localAnchorA = p1; jd.localAnchorA = p1;
jd.bodyB = leftFlipper; jd.bodyB = leftFlipper;
jd.lowerAngle = -30.0f * b2_pi / 180.0f; jd.lowerAngle = -30.0f * b2_pi / 180.0f;
jd.upperAngle = 5.0f * b2_pi / 180.0f; jd.upperAngle = 5.0f * b2_pi / 180.0f;
m_leftJoint = (b2RevoluteJoint*)m_world->CreateJoint m_leftJoint = (b2RevoluteJoint*)m_world->CreateJoint(&jd);
(&jd);
jd.motorSpeed = 0.0f;
jd.motorSpeed = 0.0f; jd.localAnchorA = p2;
jd.localAnchorA = p2; jd.bodyB = rightFlipper;
jd.bodyB = rightFlipper; jd.lowerAngle = -5.0f * b2_pi / 180.0f;
jd.lowerAngle = -5.0f * b2_pi / 180.0f; jd.upperAngle = 30.0f * b2_pi / 180.0f;
jd.upperAngle = 30.0f * b2_pi / 180.0f; m_rightJoint = (b2RevoluteJoint*)m_world->CreateJoint(&jd);
m_rightJoint = (b2RevoluteJoint*)m_world->CreateJoin }
t(&jd);
} // Circle character
{
// Circle character b2BodyDef bd;
{ bd.position.Set(1.0f, 15.0f);
b2BodyDef bd; bd.type = b2_dynamicBody;
bd.position.Set(1.0f, 15.0f); bd.bullet = true;
bd.type = b2_dynamicBody;
bd.bullet = true; m_ball = m_world->CreateBody(&bd);
m_ball = m_world->CreateBody(&bd); b2CircleShape shape;
shape.m_radius = 0.2f;
b2CircleShape shape;
shape.m_radius = 0.2f; b2FixtureDef fd;
fd.shape = &shape;
b2FixtureDef fd; fd.density = 1.0f;
fd.shape = &shape; m_ball->CreateFixture(&fd);
fd.density = 1.0f; }
m_ball->CreateFixture(&fd);
} m_button = false;
}
m_button = false;
} void Step(Settings* settings)
{
void Step(Settings* settings) if (m_button)
{ {
if (m_button) m_leftJoint->SetMotorSpeed(20.0f);
{ m_rightJoint->SetMotorSpeed(-20.0f);
m_leftJoint->SetMotorSpeed(20.0f); }
m_rightJoint->SetMotorSpeed(-20.0f); else
} {
else m_leftJoint->SetMotorSpeed(-10.0f);
{ m_rightJoint->SetMotorSpeed(10.0f);
m_leftJoint->SetMotorSpeed(-10.0f); }
m_rightJoint->SetMotorSpeed(10.0f);
} Test::Step(settings);
Test::Step(settings); m_debugDraw.DrawString(5, m_textLine, "Press 'a' to control the fli
ppers");
m_debugDraw.DrawString(5, m_textLine, "Press 'a' to control m_textLine += 15;
the flippers");
m_textLine += 15; }
} void Keyboard(unsigned char key)
{
void Keyboard(unsigned char key) switch (key)
{ {
switch (key) case 'a':
{ case 'A':
case 'a': m_button = true;
case 'A': break;
m_button = true; }
break; }
}
} void KeyboardUp(unsigned char key)
{
void KeyboardUp(unsigned char key) switch (key)
{ {
switch (key) case 'a':
{ case 'A':
case 'a': m_button = false;
case 'A': break;
m_button = false; }
break; }
}
} static Test* Create()
{
static Test* Create() return new Pinball;
{ }
return new Pinball;
} b2RevoluteJoint* m_leftJoint;
b2RevoluteJoint* m_rightJoint;
b2RevoluteJoint* m_leftJoint; b2Body* m_ball;
b2RevoluteJoint* m_rightJoint; bool m_button;
b2Body* m_ball;
bool m_button;
}; };
#endif #endif
 End of changes. 1 change blocks. 
143 lines changed or deleted 141 lines changed or added


 PolyCollision.h   PolyCollision.h 
skipping to change at line 25 skipping to change at line 25
* misrepresented as being the original software. * misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution . * 3. This notice may not be removed or altered from any source distribution .
*/ */
#ifndef POLYCOLLISION_H #ifndef POLYCOLLISION_H
#define POLYCOLLISION_H #define POLYCOLLISION_H
class PolyCollision : public Test class PolyCollision : public Test
{ {
public: public:
PolyCollision() PolyCollision()
{ {
{ {
m_polygonA.SetAsBox(0.2f, 0.4f); m_polygonA.SetAsBox(0.2f, 0.4f);
m_transformA.Set(b2Vec2(0.0f, 0.0f), 0.0f); m_transformA.Set(b2Vec2(0.0f, 0.0f), 0.0f);
} }
{ {
m_polygonB.SetAsBox(0.5f, 0.5f); m_polygonB.SetAsBox(0.5f, 0.5f);
m_positionB.Set(19.345284f, 1.5632932f); m_positionB.Set(19.345284f, 1.5632932f);
m_angleB = 1.9160721f; m_angleB = 1.9160721f;
m_transformB.Set(m_positionB, m_angleB); m_transformB.Set(m_positionB, m_angleB);
} }
} }
static Test* Create() static Test* Create()
{ {
return new PolyCollision; return new PolyCollision;
} }
void Step(Settings* settings) void Step(Settings* settings)
{ {
B2_NOT_USED(settings); B2_NOT_USED(settings);
b2Manifold manifold; b2Manifold manifold;
b2CollidePolygons(&manifold, &m_polygonA, m_transformA, &m_p b2CollidePolygons(&manifold, &m_polygonA, m_transformA, &m_polygonB
olygonB, m_transformB); , m_transformB);
b2WorldManifold worldManifold; b2WorldManifold worldManifold;
worldManifold.Initialize(&manifold, m_transformA, m_polygonA worldManifold.Initialize(&manifold, m_transformA, m_polygonA.m_radi
.m_radius, m_transformB, m_polygonB.m_radius); us, m_transformB, m_polygonB.m_radius);
m_debugDraw.DrawString(5, m_textLine, "point count = %d", ma m_debugDraw.DrawString(5, m_textLine, "point count = %d", manifold.
nifold.pointCount); pointCount);
m_textLine += 15; m_textLine += 15;
{ {
b2Color color(0.9f, 0.9f, 0.9f); b2Color color(0.9f, 0.9f, 0.9f);
b2Vec2 v[b2_maxPolygonVertices]; b2Vec2 v[b2_maxPolygonVertices];
for (int32 i = 0; i < m_polygonA.m_vertexCount; ++i) for (int32 i = 0; i < m_polygonA.m_vertexCount; ++i)
{ {
v[i] = b2Mul(m_transformA, m_polygonA.m_vert v[i] = b2Mul(m_transformA, m_polygonA.m_vertices[i]);
ices[i]); }
} m_debugDraw.DrawPolygon(v, m_polygonA.m_vertexCount, color);
m_debugDraw.DrawPolygon(v, m_polygonA.m_vertexCount,
color); for (int32 i = 0; i < m_polygonB.m_vertexCount; ++i)
{
for (int32 i = 0; i < m_polygonB.m_vertexCount; ++i) v[i] = b2Mul(m_transformB, m_polygonB.m_vertices[i]);
{ }
v[i] = b2Mul(m_transformB, m_polygonB.m_vert m_debugDraw.DrawPolygon(v, m_polygonB.m_vertexCount, color);
ices[i]); }
}
m_debugDraw.DrawPolygon(v, m_polygonB.m_vertexCount, for (int32 i = 0; i < manifold.pointCount; ++i)
color); {
} m_debugDraw.DrawPoint(worldManifold.points[i], 4.0f, b2Color(0.
9f, 0.3f, 0.3f));
for (int32 i = 0; i < manifold.pointCount; ++i) }
{ }
m_debugDraw.DrawPoint(worldManifold.points[i], 4.0f,
b2Color(0.9f, 0.3f, 0.3f)); void Keyboard(unsigned char key)
} {
} switch (key)
{
void Keyboard(unsigned char key) case 'a':
{ m_positionB.x -= 0.1f;
switch (key) break;
{
case 'a': case 'd':
m_positionB.x -= 0.1f; m_positionB.x += 0.1f;
break; break;
case 'd': case 's':
m_positionB.x += 0.1f; m_positionB.y -= 0.1f;
break; break;
case 's': case 'w':
m_positionB.y -= 0.1f; m_positionB.y += 0.1f;
break; break;
case 'w': case 'q':
m_positionB.y += 0.1f; m_angleB += 0.1f * b2_pi;
break; break;
case 'q': case 'e':
m_angleB += 0.1f * b2_pi; m_angleB -= 0.1f * b2_pi;
break; break;
}
case 'e':
m_angleB -= 0.1f * b2_pi; m_transformB.Set(m_positionB, m_angleB);
break; }
}
m_transformB.Set(m_positionB, m_angleB);
}
b2PolygonShape m_polygonA; b2PolygonShape m_polygonA;
b2PolygonShape m_polygonB; b2PolygonShape m_polygonB;
b2Transform m_transformA; b2Transform m_transformA;
b2Transform m_transformB; b2Transform m_transformB;
b2Vec2 m_positionB; b2Vec2 m_positionB;
float32 m_angleB; float32 m_angleB;
}; };
#endif #endif
 End of changes. 4 change blocks. 
100 lines changed or deleted 96 lines changed or added


 PolyShapes.h   PolyShapes.h 
skipping to change at line 34 skipping to change at line 34
const int32 k_maxBodies = 256; const int32 k_maxBodies = 256;
/// This callback is called by b2World::QueryAABB. We find all the fixtures /// This callback is called by b2World::QueryAABB. We find all the fixtures
/// that overlap an AABB. Of those, we use b2TestOverlap to determine which fixtures /// that overlap an AABB. Of those, we use b2TestOverlap to determine which fixtures
/// overlap a circle. Up to 4 overlapped fixtures will be highlighted with a yellow border. /// overlap a circle. Up to 4 overlapped fixtures will be highlighted with a yellow border.
class PolyShapesCallback : public b2QueryCallback class PolyShapesCallback : public b2QueryCallback
{ {
public: public:
enum enum
{ {
e_maxCount = 4 e_maxCount = 4
}; };
PolyShapesCallback() PolyShapesCallback()
{ {
m_count = 0; m_count = 0;
} }
void DrawFixture(b2Fixture* fixture) void DrawFixture(b2Fixture* fixture)
{ {
b2Color color(0.95f, 0.95f, 0.6f); b2Color color(0.95f, 0.95f, 0.6f);
const b2Transform& xf = fixture->GetBody()->GetTransform(); const b2Transform& xf = fixture->GetBody()->GetTransform();
switch (fixture->GetType()) switch (fixture->GetType())
{ {
case b2Shape::e_circle: case b2Shape::e_circle:
{ {
b2CircleShape* circle = (b2CircleShape*)fixt b2CircleShape* circle = (b2CircleShape*)fixture->GetShape()
ure->GetShape(); ;
b2Vec2 center = b2Mul(xf, circle->m_p); b2Vec2 center = b2Mul(xf, circle->m_p);
float32 radius = circle->m_radius; float32 radius = circle->m_radius;
m_debugDraw->DrawCircle(center, radius, colo m_debugDraw->DrawCircle(center, radius, color);
r); }
} break;
break;
case b2Shape::e_polygon:
case b2Shape::e_polygon: {
{ b2PolygonShape* poly = (b2PolygonShape*)fixture->GetShape()
b2PolygonShape* poly = (b2PolygonShape*)fixt ;
ure->GetShape(); int32 vertexCount = poly->m_vertexCount;
int32 vertexCount = poly->m_vertexCount; b2Assert(vertexCount <= b2_maxPolygonVertices);
b2Assert(vertexCount <= b2_maxPolygonVertice b2Vec2 vertices[b2_maxPolygonVertices];
s);
b2Vec2 vertices[b2_maxPolygonVertices]; for (int32 i = 0; i < vertexCount; ++i)
{
for (int32 i = 0; i < vertexCount; ++i) vertices[i] = b2Mul(xf, poly->m_vertices[i]);
{ }
vertices[i] = b2Mul(xf, poly->m_vert
ices[i]); m_debugDraw->DrawPolygon(vertices, vertexCount, color);
} }
break;
m_debugDraw->DrawPolygon(vertices, vertexCou
nt, color); default:
} break;
break; }
}
default:
break; /// Called for each fixture found in the query AABB.
} /// @return false to terminate the query.
} bool ReportFixture(b2Fixture* fixture)
{
/// Called for each fixture found in the query AABB. if (m_count == e_maxCount)
/// @return false to terminate the query. {
bool ReportFixture(b2Fixture* fixture) return false;
{ }
if (m_count == e_maxCount)
{ b2Body* body = fixture->GetBody();
return false; b2Shape* shape = fixture->GetShape();
}
bool overlap = b2TestOverlap(shape, 0, &m_circle, 0, body->GetTrans
b2Body* body = fixture->GetBody(); form(), m_transform);
b2Shape* shape = fixture->GetShape();
if (overlap)
bool overlap = b2TestOverlap(shape, 0, &m_circle, 0, body->G {
etTransform(), m_transform); DrawFixture(fixture);
++m_count;
if (overlap) }
{
DrawFixture(fixture); return true;
++m_count; }
}
b2CircleShape m_circle;
return true; b2Transform m_transform;
} b2Draw* m_debugDraw;
int32 m_count;
b2CircleShape m_circle;
b2Transform m_transform;
b2Draw* m_debugDraw;
int32 m_count;
}; };
class PolyShapes : public Test class PolyShapes : public Test
{ {
public: public:
PolyShapes() PolyShapes()
{ {
// Ground body // Ground body
{ {
b2BodyDef bd; b2BodyDef bd;
b2Body* ground = m_world->CreateBody(&bd); b2Body* ground = m_world->CreateBody(&bd);
b2EdgeShape shape; b2EdgeShape shape;
shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)) shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f));
; ground->CreateFixture(&shape, 0.0f);
ground->CreateFixture(&shape, 0.0f); }
}
{
{ b2Vec2 vertices[3];
b2Vec2 vertices[3]; vertices[0].Set(-0.5f, 0.0f);
vertices[0].Set(-0.5f, 0.0f); vertices[1].Set(0.5f, 0.0f);
vertices[1].Set(0.5f, 0.0f); vertices[2].Set(0.0f, 1.5f);
vertices[2].Set(0.0f, 1.5f); m_polygons[0].Set(vertices, 3);
m_polygons[0].Set(vertices, 3); }
}
{
{ b2Vec2 vertices[3];
b2Vec2 vertices[3]; vertices[0].Set(-0.1f, 0.0f);
vertices[0].Set(-0.1f, 0.0f); vertices[1].Set(0.1f, 0.0f);
vertices[1].Set(0.1f, 0.0f); vertices[2].Set(0.0f, 1.5f);
vertices[2].Set(0.0f, 1.5f); m_polygons[1].Set(vertices, 3);
m_polygons[1].Set(vertices, 3); }
}
{
{ float32 w = 1.0f;
float32 w = 1.0f; float32 b = w / (2.0f + b2Sqrt(2.0f));
float32 b = w / (2.0f + b2Sqrt(2.0f)); float32 s = b2Sqrt(2.0f) * b;
float32 s = b2Sqrt(2.0f) * b;
b2Vec2 vertices[8];
b2Vec2 vertices[8]; vertices[0].Set(0.5f * s, 0.0f);
vertices[0].Set(0.5f * s, 0.0f); vertices[1].Set(0.5f * w, b);
vertices[1].Set(0.5f * w, b); vertices[2].Set(0.5f * w, b + s);
vertices[2].Set(0.5f * w, b + s); vertices[3].Set(0.5f * s, w);
vertices[3].Set(0.5f * s, w); vertices[4].Set(-0.5f * s, w);
vertices[4].Set(-0.5f * s, w); vertices[5].Set(-0.5f * w, b + s);
vertices[5].Set(-0.5f * w, b + s); vertices[6].Set(-0.5f * w, b);
vertices[6].Set(-0.5f * w, b); vertices[7].Set(-0.5f * s, 0.0f);
vertices[7].Set(-0.5f * s, 0.0f);
m_polygons[2].Set(vertices, 8);
m_polygons[2].Set(vertices, 8); }
}
{
{ m_polygons[3].SetAsBox(0.5f, 0.5f);
m_polygons[3].SetAsBox(0.5f, 0.5f); }
}
{
{ m_circle.m_radius = 0.5f;
m_circle.m_radius = 0.5f; }
}
m_bodyIndex = 0;
m_bodyIndex = 0; memset(m_bodies, 0, sizeof(m_bodies));
memset(m_bodies, 0, sizeof(m_bodies)); }
}
void Create(int32 index)
void Create(int32 index) {
{ if (m_bodies[m_bodyIndex] != NULL)
if (m_bodies[m_bodyIndex] != NULL) {
{ m_world->DestroyBody(m_bodies[m_bodyIndex]);
m_world->DestroyBody(m_bodies[m_bodyIndex]); m_bodies[m_bodyIndex] = NULL;
m_bodies[m_bodyIndex] = NULL; }
}
b2BodyDef bd;
b2BodyDef bd; bd.type = b2_dynamicBody;
bd.type = b2_dynamicBody;
float32 x = RandomFloat(-2.0f, 2.0f);
float32 x = RandomFloat(-2.0f, 2.0f); bd.position.Set(x, 10.0f);
bd.position.Set(x, 10.0f); bd.angle = RandomFloat(-b2_pi, b2_pi);
bd.angle = RandomFloat(-b2_pi, b2_pi);
if (index == 4)
if (index == 4) {
{ bd.angularDamping = 0.02f;
bd.angularDamping = 0.02f; }
}
m_bodies[m_bodyIndex] = m_world->CreateBody(&bd);
m_bodies[m_bodyIndex] = m_world->CreateBody(&bd);
if (index < 4)
if (index < 4) {
{ b2FixtureDef fd;
b2FixtureDef fd; fd.shape = m_polygons + index;
fd.shape = m_polygons + index; fd.density = 1.0f;
fd.density = 1.0f; fd.friction = 0.3f;
fd.friction = 0.3f; m_bodies[m_bodyIndex]->CreateFixture(&fd);
m_bodies[m_bodyIndex]->CreateFixture(&fd); }
} else
else {
{ b2FixtureDef fd;
b2FixtureDef fd; fd.shape = &m_circle;
fd.shape = &m_circle; fd.density = 1.0f;
fd.density = 1.0f; fd.friction = 0.3f;
fd.friction = 0.3f;
m_bodies[m_bodyIndex]->CreateFixture(&fd);
m_bodies[m_bodyIndex]->CreateFixture(&fd); }
}
m_bodyIndex = (m_bodyIndex + 1) % k_maxBodies;
m_bodyIndex = (m_bodyIndex + 1) % k_maxBodies; }
}
void DestroyBody()
void DestroyBody() {
{ for (int32 i = 0; i < k_maxBodies; ++i)
for (int32 i = 0; i < k_maxBodies; ++i) {
{ if (m_bodies[i] != NULL)
if (m_bodies[i] != NULL) {
{ m_world->DestroyBody(m_bodies[i]);
m_world->DestroyBody(m_bodies[i]); m_bodies[i] = NULL;
m_bodies[i] = NULL; return;
return; }
} }
} }
}
void Keyboard(unsigned char key)
void Keyboard(unsigned char key) {
{ switch (key)
switch (key) {
{ case '1':
case '1': case '2':
case '2': case '3':
case '3': case '4':
case '4': case '5':
case '5': Create(key - '1');
Create(key - '1'); break;
break;
case 'a':
case 'a': for (int32 i = 0; i < k_maxBodies; i += 2)
for (int32 i = 0; i < k_maxBodies; i += 2) {
{ if (m_bodies[i])
if (m_bodies[i]) {
{ bool active = m_bodies[i]->IsActive();
bool active = m_bodies[i]->IsActive( m_bodies[i]->SetActive(!active);
); }
m_bodies[i]->SetActive(!active); }
} break;
}
break; case 'd':
DestroyBody();
case 'd': break;
DestroyBody(); }
break; }
}
} void Step(Settings* settings)
{
void Step(Settings* settings) Test::Step(settings);
{
Test::Step(settings); PolyShapesCallback callback;
callback.m_circle.m_radius = 2.0f;
PolyShapesCallback callback; callback.m_circle.m_p.Set(0.0f, 1.1f);
callback.m_circle.m_radius = 2.0f; callback.m_transform.SetIdentity();
callback.m_circle.m_p.Set(0.0f, 1.1f); callback.m_debugDraw = &m_debugDraw;
callback.m_transform.SetIdentity();
callback.m_debugDraw = &m_debugDraw; b2AABB aabb;
callback.m_circle.ComputeAABB(&aabb, callback.m_transform, 0);
b2AABB aabb;
callback.m_circle.ComputeAABB(&aabb, callback.m_transform, 0 m_world->QueryAABB(&callback, aabb);
);
b2Color color(0.4f, 0.7f, 0.8f);
m_world->QueryAABB(&callback, aabb); m_debugDraw.DrawCircle(callback.m_circle.m_p, callback.m_circle.m_r
adius, color);
b2Color color(0.4f, 0.7f, 0.8f);
m_debugDraw.DrawCircle(callback.m_circle.m_p, callback.m_cir m_debugDraw.DrawString(5, m_textLine, "Press 1-5 to drop stuff");
cle.m_radius, color); m_textLine += 15;
m_debugDraw.DrawString(5, m_textLine, "Press 'a' to (de)activate so
m_debugDraw.DrawString(5, m_textLine, "Press 1-5 to drop stu me bodies");
ff"); m_textLine += 15;
m_textLine += 15; m_debugDraw.DrawString(5, m_textLine, "Press 'd' to destroy a body"
m_debugDraw.DrawString(5, m_textLine, "Press 'a' to (de)acti );
vate some bodies"); m_textLine += 15;
m_textLine += 15; }
m_debugDraw.DrawString(5, m_textLine, "Press 'd' to destroy
a body"); static Test* Create()
m_textLine += 15; {
} return new PolyShapes;
}
static Test* Create()
{ int32 m_bodyIndex;
return new PolyShapes; b2Body* m_bodies[k_maxBodies];
} b2PolygonShape m_polygons[4];
b2CircleShape m_circle;
int32 m_bodyIndex;
b2Body* m_bodies[k_maxBodies];
b2PolygonShape m_polygons[4];
b2CircleShape m_circle;
}; };
#endif #endif
 End of changes. 2 change blocks. 
268 lines changed or deleted 260 lines changed or added


 Prismatic.h   Prismatic.h 
skipping to change at line 26 skipping to change at line 26
* 3. This notice may not be removed or altered from any source distribution . * 3. This notice may not be removed or altered from any source distribution .
*/ */
#ifndef PRISMATIC_H #ifndef PRISMATIC_H
#define PRISMATIC_H #define PRISMATIC_H
// The motor in this test gets smoother with higher velocity iterations. // The motor in this test gets smoother with higher velocity iterations.
class Prismatic : public Test class Prismatic : public Test
{ {
public: public:
Prismatic() Prismatic()
{ {
b2Body* ground = NULL; b2Body* ground = NULL;
{ {
b2BodyDef bd; b2BodyDef bd;
ground = m_world->CreateBody(&bd); ground = m_world->CreateBody(&bd);
b2EdgeShape shape; b2EdgeShape shape;
shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)) shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f));
; ground->CreateFixture(&shape, 0.0f);
ground->CreateFixture(&shape, 0.0f); }
}
{
{ b2PolygonShape shape;
b2PolygonShape shape; shape.SetAsBox(2.0f, 0.5f);
shape.SetAsBox(2.0f, 0.5f);
b2BodyDef bd;
b2BodyDef bd; bd.type = b2_dynamicBody;
bd.type = b2_dynamicBody; bd.position.Set(-10.0f, 10.0f);
bd.position.Set(-10.0f, 10.0f); bd.angle = 0.5f * b2_pi;
bd.angle = 0.5f * b2_pi; bd.allowSleep = false;
bd.allowSleep = false; b2Body* body = m_world->CreateBody(&bd);
b2Body* body = m_world->CreateBody(&bd); body->CreateFixture(&shape, 5.0f);
body->CreateFixture(&shape, 5.0f);
b2PrismaticJointDef pjd;
b2PrismaticJointDef pjd;
// Bouncy limit
// Bouncy limit b2Vec2 axis(2.0f, 1.0f);
b2Vec2 axis(2.0f, 1.0f); axis.Normalize();
axis.Normalize(); pjd.Initialize(ground, body, b2Vec2(0.0f, 0.0f), axis);
pjd.Initialize(ground, body, b2Vec2(0.0f, 0.0f), axi
s); // Non-bouncy limit
//pjd.Initialize(ground, body, b2Vec2(-10.0f, 10.0f), b2Vec2(1.
// Non-bouncy limit 0f, 0.0f));
//pjd.Initialize(ground, body, b2Vec2(-10.0f, 10.0f)
, b2Vec2(1.0f, 0.0f)); pjd.motorSpeed = 10.0f;
pjd.maxMotorForce = 10000.0f;
pjd.motorSpeed = 10.0f; pjd.enableMotor = true;
pjd.maxMotorForce = 10000.0f; pjd.lowerTranslation = 0.0f;
pjd.enableMotor = true; pjd.upperTranslation = 20.0f;
pjd.lowerTranslation = 0.0f; pjd.enableLimit = true;
pjd.upperTranslation = 20.0f;
pjd.enableLimit = true; m_joint = (b2PrismaticJoint*)m_world->CreateJoint(&pjd);
}
m_joint = (b2PrismaticJoint*)m_world->CreateJoint(&p }
jd);
} void Keyboard(unsigned char key)
} {
switch (key)
void Keyboard(unsigned char key) {
{ case 'l':
switch (key) m_joint->EnableLimit(!m_joint->IsLimitEnabled());
{ break;
case 'l':
m_joint->EnableLimit(!m_joint->IsLimitEnabled()); case 'm':
break; m_joint->EnableMotor(!m_joint->IsMotorEnabled());
break;
case 'm':
m_joint->EnableMotor(!m_joint->IsMotorEnabled()); case 's':
break; m_joint->SetMotorSpeed(-m_joint->GetMotorSpeed());
break;
case 's': }
m_joint->SetMotorSpeed(-m_joint->GetMotorSpeed()); }
break;
} void Step(Settings* settings)
} {
Test::Step(settings);
void Step(Settings* settings) m_debugDraw.DrawString(5, m_textLine, "Keys: (l) limits, (m) motors
{ , (s) speed");
Test::Step(settings); m_textLine += 15;
m_debugDraw.DrawString(5, m_textLine, "Keys: (l) limits, (m) float32 force = m_joint->GetMotorForce(settings->hz);
motors, (s) speed"); m_debugDraw.DrawString(5, m_textLine, "Motor Force = %4.0f", (float
m_textLine += 15; ) force);
float32 force = m_joint->GetMotorForce(settings->hz); m_textLine += 15;
m_debugDraw.DrawString(5, m_textLine, "Motor Force = %4.0f", }
(float) force);
m_textLine += 15; static Test* Create()
} {
return new Prismatic;
static Test* Create() }
{
return new Prismatic;
}
b2PrismaticJoint* m_joint; b2PrismaticJoint* m_joint;
}; };
#endif #endif
 End of changes. 2 change blocks. 
84 lines changed or deleted 81 lines changed or added


 Pulleys.h   Pulleys.h 
skipping to change at line 25 skipping to change at line 25
* misrepresented as being the original software. * misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution . * 3. This notice may not be removed or altered from any source distribution .
*/ */
#ifndef PULLEYS_H #ifndef PULLEYS_H
#define PULLEYS_H #define PULLEYS_H
class Pulleys : public Test class Pulleys : public Test
{ {
public: public:
Pulleys() Pulleys()
{ {
float32 y = 16.0f; float32 y = 16.0f;
float32 L = 12.0f; float32 L = 12.0f;
float32 a = 1.0f; float32 a = 1.0f;
float32 b = 2.0f; float32 b = 2.0f;
b2Body* ground = NULL; b2Body* ground = NULL;
{ {
b2BodyDef bd; b2BodyDef bd;
ground = m_world->CreateBody(&bd); ground = m_world->CreateBody(&bd);
b2EdgeShape edge; b2EdgeShape edge;
edge.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); edge.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f));
//ground->CreateFixture(&shape, 0.0f); //ground->CreateFixture(&shape, 0.0f);
b2CircleShape circle; b2CircleShape circle;
circle.m_radius = 2.0f; circle.m_radius = 2.0f;
circle.m_p.Set(-10.0f, y + b + L); circle.m_p.Set(-10.0f, y + b + L);
ground->CreateFixture(&circle, 0.0f); ground->CreateFixture(&circle, 0.0f);
circle.m_p.Set(10.0f, y + b + L); circle.m_p.Set(10.0f, y + b + L);
ground->CreateFixture(&circle, 0.0f); ground->CreateFixture(&circle, 0.0f);
} }
{ {
b2PolygonShape shape; b2PolygonShape shape;
shape.SetAsBox(a, b); shape.SetAsBox(a, b);
b2BodyDef bd; b2BodyDef bd;
bd.type = b2_dynamicBody; bd.type = b2_dynamicBody;
//bd.fixedRotation = true; //bd.fixedRotation = true;
bd.position.Set(-10.0f, y); bd.position.Set(-10.0f, y);
b2Body* body1 = m_world->CreateBody(&bd); b2Body* body1 = m_world->CreateBody(&bd);
body1->CreateFixture(&shape, 5.0f); body1->CreateFixture(&shape, 5.0f);
bd.position.Set(10.0f, y); bd.position.Set(10.0f, y);
b2Body* body2 = m_world->CreateBody(&bd); b2Body* body2 = m_world->CreateBody(&bd);
body2->CreateFixture(&shape, 5.0f); body2->CreateFixture(&shape, 5.0f);
b2PulleyJointDef pulleyDef; b2PulleyJointDef pulleyDef;
b2Vec2 anchor1(-10.0f, y + b); b2Vec2 anchor1(-10.0f, y + b);
b2Vec2 anchor2(10.0f, y + b); b2Vec2 anchor2(10.0f, y + b);
b2Vec2 groundAnchor1(-10.0f, y + b + L); b2Vec2 groundAnchor1(-10.0f, y + b + L);
b2Vec2 groundAnchor2(10.0f, y + b + L); b2Vec2 groundAnchor2(10.0f, y + b + L);
pulleyDef.Initialize(body1, body2, groundAnchor1, gr pulleyDef.Initialize(body1, body2, groundAnchor1, groundAnchor2
oundAnchor2, anchor1, anchor2, 1.5f); , anchor1, anchor2, 1.5f);
m_joint1 = (b2PulleyJoint*)m_world->CreateJoint(&pul m_joint1 = (b2PulleyJoint*)m_world->CreateJoint(&pulleyDef);
leyDef); }
} }
}
void Keyboard(unsigned char key)
void Keyboard(unsigned char key) {
{ switch (key)
switch (key) {
{ case 0:
case 0: break;
break; }
} }
}
void Step(Settings* settings)
void Step(Settings* settings) {
{ Test::Step(settings);
Test::Step(settings);
float32 ratio = m_joint1->GetRatio();
float32 ratio = m_joint1->GetRatio(); float32 L = m_joint1->GetLengthA() + ratio * m_joint1->GetLengthB()
float32 L = m_joint1->GetLengthA() + ratio * m_joint1->GetLe ;
ngthB(); m_debugDraw.DrawString(5, m_textLine, "L1 + %4.2f * L2 = %4.2f", (f
m_debugDraw.DrawString(5, m_textLine, "L1 + %4.2f * L2 = %4. loat) ratio, (float) L);
2f", (float) ratio, (float) L); m_textLine += 15;
m_textLine += 15; }
}
static Test* Create()
static Test* Create() {
{ return new Pulleys;
return new Pulleys; }
}
b2PulleyJoint* m_joint1; b2PulleyJoint* m_joint1;
}; };
#endif #endif
 End of changes. 2 change blocks. 
82 lines changed or deleted 81 lines changed or added


 Pyramid.h   Pyramid.h 
skipping to change at line 25 skipping to change at line 25
* misrepresented as being the original software. * misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution . * 3. This notice may not be removed or altered from any source distribution .
*/ */
#ifndef PYRAMID_H #ifndef PYRAMID_H
#define PYRAMID_H #define PYRAMID_H
class Pyramid : public Test class Pyramid : public Test
{ {
public: public:
enum enum
{ {
e_count = 20 e_count = 20
}; };
Pyramid() Pyramid()
{ {
{ {
b2BodyDef bd; b2BodyDef bd;
b2Body* ground = m_world->CreateBody(&bd); b2Body* ground = m_world->CreateBody(&bd);
b2EdgeShape shape; b2EdgeShape shape;
shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)) shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f));
; ground->CreateFixture(&shape, 0.0f);
ground->CreateFixture(&shape, 0.0f); }
}
{
{ float32 a = 0.5f;
float32 a = 0.5f; b2PolygonShape shape;
b2PolygonShape shape; shape.SetAsBox(a, a);
shape.SetAsBox(a, a);
b2Vec2 x(-7.0f, 0.75f);
b2Vec2 x(-7.0f, 0.75f); b2Vec2 y;
b2Vec2 y; b2Vec2 deltaX(0.5625f, 1.25f);
b2Vec2 deltaX(0.5625f, 1.25f); b2Vec2 deltaY(1.125f, 0.0f);
b2Vec2 deltaY(1.125f, 0.0f);
for (int32 i = 0; i < e_count; ++i)
for (int32 i = 0; i < e_count; ++i) {
{ y = x;
y = x;
for (int32 j = i; j < e_count; ++j)
for (int32 j = i; j < e_count; ++j) {
{ b2BodyDef bd;
b2BodyDef bd; bd.type = b2_dynamicBody;
bd.type = b2_dynamicBody; bd.position = y;
bd.position = y; b2Body* body = m_world->CreateBody(&bd);
b2Body* body = m_world->CreateBody(& body->CreateFixture(&shape, 5.0f);
bd);
body->CreateFixture(&shape, 5.0f); y += deltaY;
}
y += deltaY;
} x += deltaX;
}
x += deltaX; }
} }
}
} void Step(Settings* settings)
{
void Step(Settings* settings) Test::Step(settings);
{
Test::Step(settings); //b2DynamicTree* tree = &m_world->m_contactManager.m_broadPhase.m_t
ree;
//b2DynamicTree* tree = &m_world->m_contactManager.m_broadPh
ase.m_tree; //if (m_stepCount == 400)
//{
//if (m_stepCount == 400) // tree->RebuildBottomUp();
//{ //}
// tree->RebuildBottomUp(); }
//}
} static Test* Create()
{
static Test* Create() return new Pyramid;
{ }
return new Pyramid;
}
}; };
#endif #endif
 End of changes. 1 change blocks. 
65 lines changed or deleted 63 lines changed or added


 RayCast.h   RayCast.h 
skipping to change at line 30 skipping to change at line 30
#define RAY_CAST_H #define RAY_CAST_H
// This test demonstrates how to use the world ray-cast feature. // This test demonstrates how to use the world ray-cast feature.
// NOTE: we are intentionally filtering one of the polygons, therefore // NOTE: we are intentionally filtering one of the polygons, therefore
// the ray will always miss one type of polygon. // the ray will always miss one type of polygon.
// This callback finds the closest hit. Polygon 0 is filtered. // This callback finds the closest hit. Polygon 0 is filtered.
class RayCastClosestCallback : public b2RayCastCallback class RayCastClosestCallback : public b2RayCastCallback
{ {
public: public:
RayCastClosestCallback() RayCastClosestCallback()
{ {
m_hit = false; m_hit = false;
} }
float32 ReportFixture( b2Fixture* fixture, const b2Vec2& point, float32 ReportFixture( b2Fixture* fixture, const b2Vec2& point,
const b2Vec2& normal, float32 fraction) const b2Vec2& normal, float32 fraction)
{ {
b2Body* body = fixture->GetBody(); b2Body* body = fixture->GetBody();
void* userData = body->GetUserData(); void* userData = body->GetUserData();
if (userData) if (userData)
{ {
int32 index = *(int32*)userData; int32 index = *(int32*)userData;
if (index == 0) if (index == 0)
{ {
// filter // filter
return -1.0f; return -1.0f;
} }
} }
m_hit = true; m_hit = true;
m_point = point; m_point = point;
m_normal = normal; m_normal = normal;
return fraction; return fraction;
} }
bool m_hit; bool m_hit;
b2Vec2 m_point; b2Vec2 m_point;
b2Vec2 m_normal; b2Vec2 m_normal;
}; };
// This callback finds any hit. Polygon 0 is filtered. // This callback finds any hit. Polygon 0 is filtered.
class RayCastAnyCallback : public b2RayCastCallback class RayCastAnyCallback : public b2RayCastCallback
{ {
public: public:
RayCastAnyCallback() RayCastAnyCallback()
{ {
m_hit = false; m_hit = false;
} }
float32 ReportFixture( b2Fixture* fixture, const b2Vec2& point, float32 ReportFixture( b2Fixture* fixture, const b2Vec2& point,
const b2Vec2& normal, float32 fraction) const b2Vec2& normal, float32 fraction)
{ {
b2Body* body = fixture->GetBody(); b2Body* body = fixture->GetBody();
void* userData = body->GetUserData(); void* userData = body->GetUserData();
if (userData) if (userData)
{ {
int32 index = *(int32*)userData; int32 index = *(int32*)userData;
if (index == 0) if (index == 0)
{ {
// filter // filter
return -1.0f; return -1.0f;
} }
} }
m_hit = true; m_hit = true;
m_point = point; m_point = point;
m_normal = normal; m_normal = normal;
return 0.0f; return 0.0f;
} }
bool m_hit; bool m_hit;
b2Vec2 m_point; b2Vec2 m_point;
b2Vec2 m_normal; b2Vec2 m_normal;
}; };
// This ray cast collects multiple hits along the ray. Polygon 0 is filtere d. // This ray cast collects multiple hits along the ray. Polygon 0 is filtere d.
class RayCastMultipleCallback : public b2RayCastCallback class RayCastMultipleCallback : public b2RayCastCallback
{ {
public: public:
enum enum
{ {
e_maxCount = 3 e_maxCount = 3
}; };
RayCastMultipleCallback() RayCastMultipleCallback()
{ {
m_count = 0; m_count = 0;
} }
float32 ReportFixture( b2Fixture* fixture, const b2Vec2& point, float32 ReportFixture( b2Fixture* fixture, const b2Vec2& point,
const b2Vec2& normal, float32 fraction) const b2Vec2& normal, float32 fraction)
{ {
b2Body* body = fixture->GetBody(); b2Body* body = fixture->GetBody();
void* userData = body->GetUserData(); void* userData = body->GetUserData();
if (userData) if (userData)
{ {
int32 index = *(int32*)userData; int32 index = *(int32*)userData;
if (index == 0) if (index == 0)
{ {
// filter // filter
return -1.0f; return -1.0f;
} }
} }
b2Assert(m_count < e_maxCount); b2Assert(m_count < e_maxCount);
m_points[m_count] = point; m_points[m_count] = point;
m_normals[m_count] = normal; m_normals[m_count] = normal;
++m_count; ++m_count;
if (m_count == e_maxCount) if (m_count == e_maxCount)
{ {
return 0.0f; return 0.0f;
} }
return 1.0f; return 1.0f;
} }
b2Vec2 m_points[e_maxCount]; b2Vec2 m_points[e_maxCount];
b2Vec2 m_normals[e_maxCount]; b2Vec2 m_normals[e_maxCount];
int32 m_count; int32 m_count;
}; };
class RayCast : public Test class RayCast : public Test
{ {
public: public:
enum enum
{ {
e_maxBodies = 256 e_maxBodies = 256
}; };
enum Mode enum Mode
{ {
e_closest, e_closest,
e_any, e_any,
e_multiple e_multiple
}; };
RayCast() RayCast()
{ {
// Ground body // Ground body
{ {
b2BodyDef bd; b2BodyDef bd;
b2Body* ground = m_world->CreateBody(&bd); b2Body* ground = m_world->CreateBody(&bd);
b2EdgeShape shape; b2EdgeShape shape;
shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)) shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f));
; ground->CreateFixture(&shape, 0.0f);
ground->CreateFixture(&shape, 0.0f); }
}
{
{ b2Vec2 vertices[3];
b2Vec2 vertices[3]; vertices[0].Set(-0.5f, 0.0f);
vertices[0].Set(-0.5f, 0.0f); vertices[1].Set(0.5f, 0.0f);
vertices[1].Set(0.5f, 0.0f); vertices[2].Set(0.0f, 1.5f);
vertices[2].Set(0.0f, 1.5f); m_polygons[0].Set(vertices, 3);
m_polygons[0].Set(vertices, 3); }
}
{
{ b2Vec2 vertices[3];
b2Vec2 vertices[3]; vertices[0].Set(-0.1f, 0.0f);
vertices[0].Set(-0.1f, 0.0f); vertices[1].Set(0.1f, 0.0f);
vertices[1].Set(0.1f, 0.0f); vertices[2].Set(0.0f, 1.5f);
vertices[2].Set(0.0f, 1.5f); m_polygons[1].Set(vertices, 3);
m_polygons[1].Set(vertices, 3); }
}
{
{ float32 w = 1.0f;
float32 w = 1.0f; float32 b = w / (2.0f + b2Sqrt(2.0f));
float32 b = w / (2.0f + b2Sqrt(2.0f)); float32 s = b2Sqrt(2.0f) * b;
float32 s = b2Sqrt(2.0f) * b;
b2Vec2 vertices[8];
b2Vec2 vertices[8]; vertices[0].Set(0.5f * s, 0.0f);
vertices[0].Set(0.5f * s, 0.0f); vertices[1].Set(0.5f * w, b);
vertices[1].Set(0.5f * w, b); vertices[2].Set(0.5f * w, b + s);
vertices[2].Set(0.5f * w, b + s); vertices[3].Set(0.5f * s, w);
vertices[3].Set(0.5f * s, w); vertices[4].Set(-0.5f * s, w);
vertices[4].Set(-0.5f * s, w); vertices[5].Set(-0.5f * w, b + s);
vertices[5].Set(-0.5f * w, b + s); vertices[6].Set(-0.5f * w, b);
vertices[6].Set(-0.5f * w, b); vertices[7].Set(-0.5f * s, 0.0f);
vertices[7].Set(-0.5f * s, 0.0f);
m_polygons[2].Set(vertices, 8);
m_polygons[2].Set(vertices, 8); }
}
{
{ m_polygons[3].SetAsBox(0.5f, 0.5f);
m_polygons[3].SetAsBox(0.5f, 0.5f); }
}
{
{ m_circle.m_radius = 0.5f;
m_circle.m_radius = 0.5f; }
}
m_bodyIndex = 0;
m_bodyIndex = 0; memset(m_bodies, 0, sizeof(m_bodies));
memset(m_bodies, 0, sizeof(m_bodies));
m_angle = 0.0f;
m_angle = 0.0f;
m_mode = e_closest;
m_mode = e_closest; }
}
void Create(int32 index)
void Create(int32 index) {
{ if (m_bodies[m_bodyIndex] != NULL)
if (m_bodies[m_bodyIndex] != NULL) {
{ m_world->DestroyBody(m_bodies[m_bodyIndex]);
m_world->DestroyBody(m_bodies[m_bodyIndex]); m_bodies[m_bodyIndex] = NULL;
m_bodies[m_bodyIndex] = NULL; }
}
b2BodyDef bd;
b2BodyDef bd;
float32 x = RandomFloat(-10.0f, 10.0f);
float32 x = RandomFloat(-10.0f, 10.0f); float32 y = RandomFloat(0.0f, 20.0f);
float32 y = RandomFloat(0.0f, 20.0f); bd.position.Set(x, y);
bd.position.Set(x, y); bd.angle = RandomFloat(-b2_pi, b2_pi);
bd.angle = RandomFloat(-b2_pi, b2_pi);
m_userData[m_bodyIndex] = index;
m_userData[m_bodyIndex] = index; bd.userData = m_userData + m_bodyIndex;
bd.userData = m_userData + m_bodyIndex;
if (index == 4)
if (index == 4) {
{ bd.angularDamping = 0.02f;
bd.angularDamping = 0.02f; }
}
m_bodies[m_bodyIndex] = m_world->CreateBody(&bd);
m_bodies[m_bodyIndex] = m_world->CreateBody(&bd);
if (index < 4)
if (index < 4) {
{ b2FixtureDef fd;
b2FixtureDef fd; fd.shape = m_polygons + index;
fd.shape = m_polygons + index; fd.friction = 0.3f;
fd.friction = 0.3f; m_bodies[m_bodyIndex]->CreateFixture(&fd);
m_bodies[m_bodyIndex]->CreateFixture(&fd); }
} else
else {
{ b2FixtureDef fd;
b2FixtureDef fd; fd.shape = &m_circle;
fd.shape = &m_circle; fd.friction = 0.3f;
fd.friction = 0.3f;
m_bodies[m_bodyIndex]->CreateFixture(&fd);
m_bodies[m_bodyIndex]->CreateFixture(&fd); }
}
m_bodyIndex = (m_bodyIndex + 1) % e_maxBodies;
m_bodyIndex = (m_bodyIndex + 1) % e_maxBodies; }
}
void DestroyBody()
void DestroyBody() {
{ for (int32 i = 0; i < e_maxBodies; ++i)
for (int32 i = 0; i < e_maxBodies; ++i) {
{ if (m_bodies[i] != NULL)
if (m_bodies[i] != NULL) {
{ m_world->DestroyBody(m_bodies[i]);
m_world->DestroyBody(m_bodies[i]); m_bodies[i] = NULL;
m_bodies[i] = NULL; return;
return; }
} }
} }
}
void Keyboard(unsigned char key)
void Keyboard(unsigned char key) {
{ switch (key)
switch (key) {
{ case '1':
case '1': case '2':
case '2': case '3':
case '3': case '4':
case '4': case '5':
case '5': Create(key - '1');
Create(key - '1'); break;
break;
case 'd':
case 'd': DestroyBody();
DestroyBody(); break;
break;
case 'm':
case 'm': if (m_mode == e_closest)
if (m_mode == e_closest) {
{ m_mode = e_any;
m_mode = e_any; }
} else if (m_mode == e_any)
else if (m_mode == e_any) {
{ m_mode = e_multiple;
m_mode = e_multiple; }
} else if (m_mode == e_multiple)
else if (m_mode == e_multiple) {
{ m_mode = e_closest;
m_mode = e_closest; }
} }
} }
}
void Step(Settings* settings)
void Step(Settings* settings) {
{ bool advanceRay = settings->pause == 0 || settings->singleStep;
bool advanceRay = settings->pause == 0 || settings->singleSt
ep; Test::Step(settings);
m_debugDraw.DrawString(5, m_textLine, "Press 1-5 to drop stuff, m t
Test::Step(settings); o change the mode");
m_debugDraw.DrawString(5, m_textLine, "Press 1-5 to drop stu m_textLine += 15;
ff, m to change the mode"); m_debugDraw.DrawString(5, m_textLine, "Mode = %d", m_mode);
m_textLine += 15; m_textLine += 15;
m_debugDraw.DrawString(5, m_textLine, "Mode = %d", m_mode);
m_textLine += 15; float32 L = 11.0f;
b2Vec2 point1(0.0f, 10.0f);
float32 L = 11.0f; b2Vec2 d(L * cosf(m_angle), L * sinf(m_angle));
b2Vec2 point1(0.0f, 10.0f); b2Vec2 point2 = point1 + d;
b2Vec2 d(L * cosf(m_angle), L * sinf(m_angle));
b2Vec2 point2 = point1 + d; if (m_mode == e_closest)
{
if (m_mode == e_closest) RayCastClosestCallback callback;
{ m_world->RayCast(&callback, point1, point2);
RayCastClosestCallback callback;
m_world->RayCast(&callback, point1, point2); if (callback.m_hit)
{
if (callback.m_hit) m_debugDraw.DrawPoint(callback.m_point, 5.0f, b2Color(0.4f,
{ 0.9f, 0.4f));
m_debugDraw.DrawPoint(callback.m_point, 5.0f m_debugDraw.DrawSegment(point1, callback.m_point, b2Color(0
, b2Color(0.4f, 0.9f, 0.4f)); .8f, 0.8f, 0.8f));
m_debugDraw.DrawSegment(point1, callback.m_p b2Vec2 head = callback.m_point + 0.5f * callback.m_normal;
oint, b2Color(0.8f, 0.8f, 0.8f)); m_debugDraw.DrawSegment(callback.m_point, head, b2Color(0.9
b2Vec2 head = callback.m_point + 0.5f * call f, 0.9f, 0.4f));
back.m_normal; }
m_debugDraw.DrawSegment(callback.m_point, he else
ad, b2Color(0.9f, 0.9f, 0.4f)); {
} m_debugDraw.DrawSegment(point1, point2, b2Color(0.8f, 0.8f,
else 0.8f));
{ }
m_debugDraw.DrawSegment(point1, point2, b2Co }
lor(0.8f, 0.8f, 0.8f)); else if (m_mode == e_any)
} {
} RayCastAnyCallback callback;
else if (m_mode == e_any) m_world->RayCast(&callback, point1, point2);
{
RayCastAnyCallback callback; if (callback.m_hit)
m_world->RayCast(&callback, point1, point2); {
m_debugDraw.DrawPoint(callback.m_point, 5.0f, b2Color(0.4f,
if (callback.m_hit) 0.9f, 0.4f));
{ m_debugDraw.DrawSegment(point1, callback.m_point, b2Color(0
m_debugDraw.DrawPoint(callback.m_point, 5.0f .8f, 0.8f, 0.8f));
, b2Color(0.4f, 0.9f, 0.4f)); b2Vec2 head = callback.m_point + 0.5f * callback.m_normal;
m_debugDraw.DrawSegment(point1, callback.m_p m_debugDraw.DrawSegment(callback.m_point, head, b2Color(0.9
oint, b2Color(0.8f, 0.8f, 0.8f)); f, 0.9f, 0.4f));
b2Vec2 head = callback.m_point + 0.5f * call }
back.m_normal; else
m_debugDraw.DrawSegment(callback.m_point, he {
ad, b2Color(0.9f, 0.9f, 0.4f)); m_debugDraw.DrawSegment(point1, point2, b2Color(0.8f, 0.8f,
} 0.8f));
else }
{ }
m_debugDraw.DrawSegment(point1, point2, b2Co else if (m_mode == e_multiple)
lor(0.8f, 0.8f, 0.8f)); {
} RayCastMultipleCallback callback;
} m_world->RayCast(&callback, point1, point2);
else if (m_mode == e_multiple) m_debugDraw.DrawSegment(point1, point2, b2Color(0.8f, 0.8f, 0.8
{ f));
RayCastMultipleCallback callback;
m_world->RayCast(&callback, point1, point2); for (int32 i = 0; i < callback.m_count; ++i)
m_debugDraw.DrawSegment(point1, point2, b2Color(0.8f {
, 0.8f, 0.8f)); b2Vec2 p = callback.m_points[i];
b2Vec2 n = callback.m_normals[i];
for (int32 i = 0; i < callback.m_count; ++i) m_debugDraw.DrawPoint(p, 5.0f, b2Color(0.4f, 0.9f, 0.4f));
{ m_debugDraw.DrawSegment(point1, p, b2Color(0.8f, 0.8f, 0.8f
b2Vec2 p = callback.m_points[i]; ));
b2Vec2 n = callback.m_normals[i]; b2Vec2 head = p + 0.5f * n;
m_debugDraw.DrawPoint(p, 5.0f, b2Color(0.4f, m_debugDraw.DrawSegment(p, head, b2Color(0.9f, 0.9f, 0.4f))
0.9f, 0.4f)); ;
m_debugDraw.DrawSegment(point1, p, b2Color(0 }
.8f, 0.8f, 0.8f)); }
b2Vec2 head = p + 0.5f * n;
m_debugDraw.DrawSegment(p, head, b2Color(0.9 if (advanceRay)
f, 0.9f, 0.4f)); {
} m_angle += 0.25f * b2_pi / 180.0f;
} }
if (advanceRay)
{
m_angle += 0.25f * b2_pi / 180.0f;
}
#if 0 #if 0
// This case was failing. // This case was failing.
{ {
b2Vec2 vertices[4]; b2Vec2 vertices[4];
//vertices[0].Set(-22.875f, -3.0f); //vertices[0].Set(-22.875f, -3.0f);
//vertices[1].Set(22.875f, -3.0f); //vertices[1].Set(22.875f, -3.0f);
//vertices[2].Set(22.875f, 3.0f); //vertices[2].Set(22.875f, 3.0f);
//vertices[3].Set(-22.875f, 3.0f); //vertices[3].Set(-22.875f, 3.0f);
b2PolygonShape shape; b2PolygonShape shape;
//shape.Set(vertices, 4); //shape.Set(vertices, 4);
shape.SetAsBox(22.875f, 3.0f); shape.SetAsBox(22.875f, 3.0f);
b2RayCastInput input; b2RayCastInput input;
input.p1.Set(10.2725f,1.71372f); input.p1.Set(10.2725f,1.71372f);
input.p2.Set(10.2353f,2.21807f); input.p2.Set(10.2353f,2.21807f);
//input.maxFraction = 0.567623f; //input.maxFraction = 0.567623f;
input.maxFraction = 0.56762173f; input.maxFraction = 0.56762173f;
b2Transform xf; b2Transform xf;
xf.SetIdentity(); xf.SetIdentity();
xf.position.Set(23.0f, 5.0f); xf.position.Set(23.0f, 5.0f);
b2RayCastOutput output; b2RayCastOutput output;
bool hit; bool hit;
hit = shape.RayCast(&output, input, xf); hit = shape.RayCast(&output, input, xf);
hit = false; hit = false;
b2Color color(1.0f, 1.0f, 1.0f); b2Color color(1.0f, 1.0f, 1.0f);
b2Vec2 vs[4]; b2Vec2 vs[4];
for (int32 i = 0; i < 4; ++i) for (int32 i = 0; i < 4; ++i)
{ {
vs[i] = b2Mul(xf, shape.m_vertices[i]); vs[i] = b2Mul(xf, shape.m_vertices[i]);
} }
m_debugDraw.DrawPolygon(vs, 4, color); m_debugDraw.DrawPolygon(vs, 4, color);
m_debugDraw.DrawSegment(input.p1, input.p2, color); m_debugDraw.DrawSegment(input.p1, input.p2, color);
} }
#endif #endif
} }
static Test* Create() static Test* Create()
{ {
return new RayCast; return new RayCast;
} }
int32 m_bodyIndex; int32 m_bodyIndex;
b2Body* m_bodies[e_maxBodies]; b2Body* m_bodies[e_maxBodies];
int32 m_userData[e_maxBodies]; int32 m_userData[e_maxBodies];
b2PolygonShape m_polygons[4]; b2PolygonShape m_polygons[4];
b2CircleShape m_circle; b2CircleShape m_circle;
float32 m_angle; float32 m_angle;
Mode m_mode; Mode m_mode;
}; };
#endif #endif
 End of changes. 9 change blocks. 
400 lines changed or deleted 395 lines changed or added


 RenderTextureTest.h   RenderTextureTest.h 
#ifndef _RENDERTEXTURE_TEST_H_ #ifndef _RENDERTEXTURE_TEST_H_
#define _RENDERTEXTURE_TEST_H_ #define _RENDERTEXTURE_TEST_H_
#include "cocos2d.h" #include "cocos2d.h"
#include "../testBasic.h" #include "../testBasic.h"
class RenderTextureTestDemo : public CCLayer class RenderTextureTest : public CCLayer
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
void restartCallback(CCObject* pSender); void restartCallback(CCObject* pSender);
void nextCallback(CCObject* pSender); void nextCallback(CCObject* pSender);
void backCallback(CCObject* pSender); void backCallback(CCObject* pSender);
}; };
/** class RenderTextureSave : public RenderTextureTest
@todo refactor the save image feature
*/
class RenderTextureTest : public RenderTextureTestDemo
{ {
public: public:
RenderTextureTest(); RenderTextureSave();
~RenderTextureTest(); ~RenderTextureSave();
virtual std::string title();
virtual std::string subtitle();
virtual void ccTouchesMoved(CCSet* touches, CCEvent* event); virtual void ccTouchesMoved(CCSet* touches, CCEvent* event);
virtual void ccTouchesEnded(CCSet* touches, CCEvent* event); void clearImage(CCObject *pSender);
void saveImage(CCObject *pSender);
private: private:
CCRenderTexture* m_target; CCRenderTexture *m_pTarget;
CCSprite* m_brush; CCSprite *m_pBrush;
}; };
class RenderTextureSave : public RenderTextureTestDemo class RenderTextureIssue937 : public RenderTextureTest
{
public:
RenderTextureSave();
~RenderTextureSave();
virtual std::string title();
virtual std::string subtitle();
virtual void ccTouchesMoved(CCSet* touches, CCEvent* event);
void clearImage(CCObject *pSender);
void saveImage(CCObject *pSender);
private:
CCRenderTexture *m_pTarget;
CCSprite *m_pBrush;
};
class RenderTextureIssue937 : public RenderTextureTestDemo
{ {
public: public:
RenderTextureIssue937(); RenderTextureIssue937();
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
}; };
class RenderTextureScene : public TestScene class RenderTextureScene : public TestScene
{ {
public: public:
virtual void runThisTest(); virtual void runThisTest();
}; };
class RenderTextureZbuffer : public RenderTextureTestDemo class RenderTextureZbuffer : public RenderTextureTest
{ {
public: public:
RenderTextureZbuffer(); RenderTextureZbuffer();
virtual void ccTouchesMoved(CCSet* touches, CCEvent* event); virtual void ccTouchesMoved(CCSet* touches, CCEvent* event);
virtual void ccTouchesBegan(CCSet* touches, CCEvent* event); virtual void ccTouchesBegan(CCSet* touches, CCEvent* event);
virtual void ccTouchesEnded(CCSet* touches, CCEvent* event); virtual void ccTouchesEnded(CCSet* touches, CCEvent* event);
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
void renderScreenShot(); void renderScreenShot();
private: private:
cocos2d::CCSpriteBatchNode *mgr;; cocos2d::CCSpriteBatchNode *mgr;;
cocos2d::CCSprite *sp1;
cocos2d::CCSprite *sp2;
cocos2d::CCSprite *sp3;
cocos2d::CCSprite *sp4;
cocos2d::CCSprite *sp5;
cocos2d::CCSprite *sp6;
cocos2d::CCSprite *sp7;
cocos2d::CCSprite *sp8;
cocos2d::CCSprite *sp9;
};
cocos2d::CCSprite *sp1; class RenderTextureTestDepthStencil : public RenderTextureTest
cocos2d::CCSprite *sp2; {
cocos2d::CCSprite *sp3; public:
cocos2d::CCSprite *sp4; RenderTextureTestDepthStencil();
cocos2d::CCSprite *sp5; virtual std::string title();
cocos2d::CCSprite *sp6; virtual std::string subtitle();
cocos2d::CCSprite *sp7;
cocos2d::CCSprite *sp8;
cocos2d::CCSprite *sp9;
}; };
#endif #endif
 End of changes. 13 change blocks. 
46 lines changed or deleted 38 lines changed or added


 Revolute.h   Revolute.h 
skipping to change at line 25 skipping to change at line 25
* misrepresented as being the original software. * misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution . * 3. This notice may not be removed or altered from any source distribution .
*/ */
#ifndef REVOLUTE_H #ifndef REVOLUTE_H
#define REVOLUTE_H #define REVOLUTE_H
class Revolute : public Test class Revolute : public Test
{ {
public: public:
Revolute() Revolute()
{ {
b2Body* ground = NULL; b2Body* ground = NULL;
{ {
b2BodyDef bd; b2BodyDef bd;
ground = m_world->CreateBody(&bd); ground = m_world->CreateBody(&bd);
b2EdgeShape shape; b2EdgeShape shape;
shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)) shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f));
;
b2FixtureDef fd;
b2FixtureDef fd; fd.shape = &shape;
fd.shape = &shape; //fd.filter.categoryBits = 2;
//fd.filter.categoryBits = 2;
ground->CreateFixture(&fd);
ground->CreateFixture(&fd); }
}
{
{ b2CircleShape shape;
b2CircleShape shape; shape.m_radius = 0.5f;
shape.m_radius = 0.5f;
b2BodyDef bd;
b2BodyDef bd; bd.type = b2_dynamicBody;
bd.type = b2_dynamicBody;
b2RevoluteJointDef rjd;
b2RevoluteJointDef rjd;
bd.position.Set(-10.0f, 20.0f);
bd.position.Set(-10.0f, 20.0f); b2Body* body = m_world->CreateBody(&bd);
b2Body* body = m_world->CreateBody(&bd); body->CreateFixture(&shape, 5.0f);
body->CreateFixture(&shape, 5.0f);
float32 w = 100.0f;
float32 w = 100.0f; body->SetAngularVelocity(w);
body->SetAngularVelocity(w); body->SetLinearVelocity(b2Vec2(-8.0f * w, 0.0f));
body->SetLinearVelocity(b2Vec2(-8.0f * w, 0.0f));
rjd.Initialize(ground, body, b2Vec2(-10.0f, 12.0f));
rjd.Initialize(ground, body, b2Vec2(-10.0f, 12.0f)); rjd.motorSpeed = 1.0f * b2_pi;
rjd.motorSpeed = 1.0f * b2_pi; rjd.maxMotorTorque = 10000.0f;
rjd.maxMotorTorque = 10000.0f; rjd.enableMotor = false;
rjd.enableMotor = false; rjd.lowerAngle = -0.25f * b2_pi;
rjd.lowerAngle = -0.25f * b2_pi; rjd.upperAngle = 0.5f * b2_pi;
rjd.upperAngle = 0.5f * b2_pi; rjd.enableLimit = true;
rjd.enableLimit = true; rjd.collideConnected = true;
rjd.collideConnected = true;
m_joint = (b2RevoluteJoint*)m_world->CreateJoint(&rjd);
m_joint = (b2RevoluteJoint*)m_world->CreateJoint(&rj }
d);
} {
b2CircleShape circle_shape;
{ circle_shape.m_radius = 3.0f;
b2CircleShape circle_shape;
circle_shape.m_radius = 3.0f; b2BodyDef circle_bd;
circle_bd.type = b2_dynamicBody;
b2BodyDef circle_bd; circle_bd.position.Set(5.0f, 30.0f);
circle_bd.type = b2_dynamicBody;
circle_bd.position.Set(5.0f, 30.0f); b2FixtureDef fd;
fd.density = 5.0f;
b2FixtureDef fd; fd.filter.maskBits = 1;
fd.density = 5.0f; fd.shape = &circle_shape;
fd.filter.maskBits = 1;
fd.shape = &circle_shape; m_ball = m_world->CreateBody(&circle_bd);
m_ball->CreateFixture(&fd);
m_ball = m_world->CreateBody(&circle_bd);
m_ball->CreateFixture(&fd); b2PolygonShape polygon_shape;
polygon_shape.SetAsBox(10.0f, 0.2f, b2Vec2 (-10.0f, 0.0f), 0.0f
b2PolygonShape polygon_shape; );
polygon_shape.SetAsBox(10.0f, 0.2f, b2Vec2 (-10.0f,
0.0f), 0.0f); b2BodyDef polygon_bd;
polygon_bd.position.Set(20.0f, 10.0f);
b2BodyDef polygon_bd; polygon_bd.type = b2_dynamicBody;
polygon_bd.position.Set(20.0f, 10.0f); polygon_bd.bullet = true;
polygon_bd.type = b2_dynamicBody; b2Body* polygon_body = m_world->CreateBody(&polygon_bd);
polygon_bd.bullet = true; polygon_body->CreateFixture(&polygon_shape, 2.0f);
b2Body* polygon_body = m_world->CreateBody(&polygon_
bd); b2RevoluteJointDef rjd;
polygon_body->CreateFixture(&polygon_shape, 2.0f); rjd.Initialize(ground, polygon_body, b2Vec2(20.0f, 10.0f));
rjd.lowerAngle = -0.25f * b2_pi;
b2RevoluteJointDef rjd; rjd.upperAngle = 0.0f * b2_pi;
rjd.Initialize(ground, polygon_body, b2Vec2(20.0f, 1 rjd.enableLimit = true;
0.0f)); m_world->CreateJoint(&rjd);
rjd.lowerAngle = -0.25f * b2_pi; }
rjd.upperAngle = 0.0f * b2_pi;
rjd.enableLimit = true; // Tests mass computation of a small object far from the origin
m_world->CreateJoint(&rjd); {
} b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
// Tests mass computation of a small object far from the ori b2Body* body = m_world->CreateBody(&bodyDef);
gin
{ b2PolygonShape polyShape;
b2BodyDef bodyDef; b2Vec2 verts[3];
bodyDef.type = b2_dynamicBody; verts[0].Set( 17.63f, 36.31f );
b2Body* body = m_world->CreateBody(&bodyDef); verts[1].Set( 17.52f, 36.69f );
verts[2].Set( 17.19f, 36.36f );
b2PolygonShape polyShape; polyShape.Set(verts, 3);
b2Vec2 verts[3];
verts[0].Set( 17.63f, 36.31f ); b2FixtureDef polyFixtureDef;
verts[1].Set( 17.52f, 36.69f ); polyFixtureDef.shape = &polyShape;
verts[2].Set( 17.19f, 36.36f ); polyFixtureDef.density = 1;
polyShape.Set(verts, 3);
body->CreateFixture(&polyFixtureDef); //assertion hits insid
b2FixtureDef polyFixtureDef; e here
polyFixtureDef.shape = &polyShape; }
polyFixtureDef.density = 1;
}
body->CreateFixture(&polyFixtureDef); //assertion
hits inside here void Keyboard(unsigned char key)
} {
switch (key)
} {
case 'l':
void Keyboard(unsigned char key) m_joint->EnableLimit(!m_joint->IsLimitEnabled());
{ break;
switch (key)
{ case 'm':
case 'l': m_joint->EnableMotor(!m_joint->IsMotorEnabled());
m_joint->EnableLimit(!m_joint->IsLimitEnabled()); break;
break; }
}
case 'm':
m_joint->EnableMotor(!m_joint->IsMotorEnabled()); void Step(Settings* settings)
break; {
} Test::Step(settings);
} m_debugDraw.DrawString(5, m_textLine, "Keys: (l) limits, (m) motor"
);
void Step(Settings* settings) m_textLine += 15;
{
Test::Step(settings); //if (m_stepCount == 360)
m_debugDraw.DrawString(5, m_textLine, "Keys: (l) limits, (m) //{
motor"); // m_ball->SetTransform(b2Vec2(0.0f, 0.5f), 0.0f);
m_textLine += 15; //}
//if (m_stepCount == 360) //float32 torque1 = m_joint1->GetMotorTorque();
//{ //m_debugDraw.DrawString(5, m_textLine, "Motor Torque = %4.0f, %4.0
// m_ball->SetTransform(b2Vec2(0.0f, 0.5f), 0.0f); f : Motor Force = %4.0f", (float) torque1, (float) torque2, (float) force3)
//} ;
//m_textLine += 15;
//float32 torque1 = m_joint1->GetMotorTorque(); }
//m_debugDraw.DrawString(5, m_textLine, "Motor Torque = %4.0
f, %4.0f : Motor Force = %4.0f", (float) torque1, (float) torque2, (float) static Test* Create()
force3); {
//m_textLine += 15; return new Revolute;
} }
static Test* Create()
{
return new Revolute;
}
b2Body* m_ball; b2Body* m_ball;
b2RevoluteJoint* m_joint; b2RevoluteJoint* m_joint;
}; };
#endif #endif
 End of changes. 2 change blocks. 
148 lines changed or deleted 143 lines changed or added


 Rope.h   Rope.h 
skipping to change at line 26 skipping to change at line 26
* 3. This notice may not be removed or altered from any source distribution . * 3. This notice may not be removed or altered from any source distribution .
*/ */
#ifndef ROPE_H #ifndef ROPE_H
#define ROPE_H #define ROPE_H
/// ///
class Rope : public Test class Rope : public Test
{ {
public: public:
Rope() Rope()
{ {
const int32 N = 40; const int32 N = 40;
b2Vec2 vertices[N]; b2Vec2 vertices[N];
float32 masses[N]; float32 masses[N];
for (int32 i = 0; i < N; ++i) for (int32 i = 0; i < N; ++i)
{ {
vertices[i].Set(0.0f, 20.0f - 0.25f * i); vertices[i].Set(0.0f, 20.0f - 0.25f * i);
masses[i] = 1.0f; masses[i] = 1.0f;
} }
masses[0] = 0.0f; masses[0] = 0.0f;
masses[1] = 0.0f; masses[1] = 0.0f;
b2RopeDef def; b2RopeDef def;
def.vertices = vertices; def.vertices = vertices;
def.count = N; def.count = N;
def.gravity.Set(0.0f, -10.0f); def.gravity.Set(0.0f, -10.0f);
def.masses = masses; def.masses = masses;
def.damping = 0.1f; def.damping = 0.1f;
def.k2 = 1.0f; def.k2 = 1.0f;
def.k3 = 0.5f; def.k3 = 0.5f;
m_rope.Initialize(&def); m_rope.Initialize(&def);
m_angle = 0.0f; m_angle = 0.0f;
m_rope.SetAngle(m_angle); m_rope.SetAngle(m_angle);
} }
void Keyboard(unsigned char key) void Keyboard(unsigned char key)
{ {
switch (key) switch (key)
{ {
case 'q': case 'q':
m_angle = b2Max(-b2_pi, m_angle - 0.05f * b2_pi); m_angle = b2Max(-b2_pi, m_angle - 0.05f * b2_pi);
m_rope.SetAngle(m_angle); m_rope.SetAngle(m_angle);
break; break;
case 'e': case 'e':
m_angle = b2Min(b2_pi, m_angle + 0.05f * b2_pi); m_angle = b2Min(b2_pi, m_angle + 0.05f * b2_pi);
m_rope.SetAngle(m_angle); m_rope.SetAngle(m_angle);
break; break;
} }
} }
void Step(Settings* settings) void Step(Settings* settings)
{ {
float32 dt = settings->hz > 0.0f ? 1.0f / settings->hz : 0.0 float32 dt = settings->hz > 0.0f ? 1.0f / settings->hz : 0.0f;
f;
if (settings->pause == 1 && settings->singleStep == 0)
if (settings->pause == 1 && settings->singleStep == 0) {
{ dt = 0.0f;
dt = 0.0f; }
}
m_rope.Step(dt, 1);
m_rope.Step(dt, 1);
Test::Step(settings);
Test::Step(settings);
m_rope.Draw(&m_debugDraw);
m_rope.Draw(&m_debugDraw);
m_debugDraw.DrawString(5, m_textLine, "Press (q,e) to adjust target
m_debugDraw.DrawString(5, m_textLine, "Press (q,e) to adjust angle");
target angle"); m_textLine += 15;
m_textLine += 15; m_debugDraw.DrawString(5, m_textLine, "Target angle = %g degrees",
m_debugDraw.DrawString(5, m_textLine, "Target angle = %g deg m_angle * 180.0f / b2_pi);
rees", m_angle * 180.0f / b2_pi); m_textLine += 15;
m_textLine += 15; }
}
static Test* Create()
static Test* Create() {
{ return new Rope;
return new Rope; }
}
b2Rope m_rope; b2Rope m_rope;
float32 m_angle; float32 m_angle;
}; };
#endif #endif
 End of changes. 2 change blocks. 
75 lines changed or deleted 74 lines changed or added


 RopeJoint.h   RopeJoint.h 
skipping to change at line 33 skipping to change at line 33
/// bodies with a heavy payload. Notice that the rope joint just prevents /// bodies with a heavy payload. Notice that the rope joint just prevents
/// excessive stretching and has no other effect. /// excessive stretching and has no other effect.
/// By disabling the rope joint you can see that the Box2D solver has troub le /// By disabling the rope joint you can see that the Box2D solver has troub le
/// supporting heavy bodies with light bodies. Try playing around with the /// supporting heavy bodies with light bodies. Try playing around with the
/// densities, time step, and iterations to see how they affect stability. /// densities, time step, and iterations to see how they affect stability.
/// This test also shows how to use contact filtering. Filtering is configu red /// This test also shows how to use contact filtering. Filtering is configu red
/// so that the payload does not collide with the chain. /// so that the payload does not collide with the chain.
class RopeJoint : public Test class RopeJoint : public Test
{ {
public: public:
RopeJoint() RopeJoint()
{ {
b2Body* ground = NULL; b2Body* ground = NULL;
{ {
b2BodyDef bd; b2BodyDef bd;
ground = m_world->CreateBody(&bd); ground = m_world->CreateBody(&bd);
b2EdgeShape shape; b2EdgeShape shape;
shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)) shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f));
; ground->CreateFixture(&shape, 0.0f);
ground->CreateFixture(&shape, 0.0f); }
}
{
{ b2PolygonShape shape;
b2PolygonShape shape; shape.SetAsBox(0.5f, 0.125f);
shape.SetAsBox(0.5f, 0.125f);
b2FixtureDef fd;
b2FixtureDef fd; fd.shape = &shape;
fd.shape = &shape; fd.density = 20.0f;
fd.density = 20.0f; fd.friction = 0.2f;
fd.friction = 0.2f; fd.filter.categoryBits = 0x0001;
fd.filter.categoryBits = 0x0001; fd.filter.maskBits = 0xFFFF & ~0x0002;
fd.filter.maskBits = 0xFFFF & ~0x0002;
b2RevoluteJointDef jd;
b2RevoluteJointDef jd; jd.collideConnected = false;
jd.collideConnected = false;
const int32 N = 10;
const int32 N = 10; const float32 y = 15.0f;
const float32 y = 15.0f; m_ropeDef.localAnchorA.Set(0.0f, y);
m_ropeDef.localAnchorA.Set(0.0f, y);
b2Body* prevBody = ground;
b2Body* prevBody = ground; for (int32 i = 0; i < N; ++i)
for (int32 i = 0; i < N; ++i) {
{ b2BodyDef bd;
b2BodyDef bd; bd.type = b2_dynamicBody;
bd.type = b2_dynamicBody; bd.position.Set(0.5f + 1.0f * i, y);
bd.position.Set(0.5f + 1.0f * i, y); if (i == N - 1)
if (i == N - 1) {
{ shape.SetAsBox(1.5f, 1.5f);
shape.SetAsBox(1.5f, 1.5f); fd.density = 100.0f;
fd.density = 100.0f; fd.filter.categoryBits = 0x0002;
fd.filter.categoryBits = 0x0002; bd.position.Set(1.0f * i, y);
bd.position.Set(1.0f * i, y); bd.angularDamping = 0.4f;
bd.angularDamping = 0.4f; }
}
b2Body* body = m_world->CreateBody(&bd);
b2Body* body = m_world->CreateBody(&bd);
body->CreateFixture(&fd);
body->CreateFixture(&fd);
b2Vec2 anchor(float32(i), y);
b2Vec2 anchor(float32(i), y); jd.Initialize(prevBody, body, anchor);
jd.Initialize(prevBody, body, anchor); m_world->CreateJoint(&jd);
m_world->CreateJoint(&jd);
prevBody = body;
prevBody = body; }
}
m_ropeDef.localAnchorB.SetZero();
m_ropeDef.localAnchorB.SetZero();
float32 extraLength = 0.01f;
float32 extraLength = 0.01f; m_ropeDef.maxLength = N - 1.0f + extraLength;
m_ropeDef.maxLength = N - 1.0f + extraLength; m_ropeDef.bodyB = prevBody;
m_ropeDef.bodyB = prevBody; }
}
{
{ m_ropeDef.bodyA = ground;
m_ropeDef.bodyA = ground; m_rope = m_world->CreateJoint(&m_ropeDef);
m_rope = m_world->CreateJoint(&m_ropeDef); }
} }
}
void Keyboard(unsigned char key)
void Keyboard(unsigned char key) {
{ switch (key)
switch (key) {
{ case 'j':
case 'j': if (m_rope)
if (m_rope) {
{ m_world->DestroyJoint(m_rope);
m_world->DestroyJoint(m_rope); m_rope = NULL;
m_rope = NULL; }
} else
else {
{ m_rope = m_world->CreateJoint(&m_ropeDef);
m_rope = m_world->CreateJoint(&m_ropeDef); }
} break;
break; }
} }
}
void Step(Settings* settings)
void Step(Settings* settings) {
{ Test::Step(settings);
Test::Step(settings); m_debugDraw.DrawString(5, m_textLine, "Press (j) to toggle the rope
m_debugDraw.DrawString(5, m_textLine, "Press (j) to toggle t joint.");
he rope joint."); m_textLine += 15;
m_textLine += 15; if (m_rope)
if (m_rope) {
{ m_debugDraw.DrawString(5, m_textLine, "Rope ON");
m_debugDraw.DrawString(5, m_textLine, "Rope ON"); }
} else
else {
{ m_debugDraw.DrawString(5, m_textLine, "Rope OFF");
m_debugDraw.DrawString(5, m_textLine, "Rope OFF"); }
} m_textLine += 15;
m_textLine += 15; }
}
static Test* Create()
static Test* Create() {
{ return new RopeJoint;
return new RopeJoint; }
}
b2RopeJointDef m_ropeDef; b2RopeJointDef m_ropeDef;
b2Joint* m_rope; b2Joint* m_rope;
}; };
#endif #endif
 End of changes. 2 change blocks. 
111 lines changed or deleted 110 lines changed or added


 RotateWorldTest.h   RotateWorldTest.h 
skipping to change at line 15 skipping to change at line 15
class RotateWorldTestScene : public TestScene class RotateWorldTestScene : public TestScene
{ {
public: public:
virtual void runThisTest(); virtual void runThisTest();
}; };
class SpriteLayer : public CCLayer class SpriteLayer : public CCLayer
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
static SpriteLayer* node() CREATE_FUNC(SpriteLayer)
{
SpriteLayer* pNode = new SpriteLayer();
pNode->autorelease();
return pNode;
}
}; };
class TestLayer : public CCLayer class TestLayer : public CCLayer
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
static TestLayer* node()
{
TestLayer* pNode = new TestLayer();
pNode->autorelease();
return pNode; CREATE_FUNC(TestLayer)
}
}; };
class RotateWorldMainLayer : public CCLayer class RotateWorldMainLayer : public CCLayer
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
static RotateWorldMainLayer* node()
{
RotateWorldMainLayer* pNode = new RotateWorldMainLayer();
pNode->autorelease();
return pNode; CREATE_FUNC(RotateWorldMainLayer)
}
}; };
#endif #endif
 End of changes. 5 change blocks. 
24 lines changed or deleted 6 lines changed or added


 SceneTest.h   SceneTest.h 
#ifndef _SCENE_TEST_H_ #ifndef _SCENE_TEST_H_
#define _SCENE_TEST_H_ #define _SCENE_TEST_H_
////----#include "cocos2d.h" ////----#include "cocos2d.h"
#include "../testBasic.h" #include "../testBasic.h"
class SceneTestLayer1 : public CCLayer class SceneTestLayer1 : public CCLayer
{ {
public: public:
SceneTestLayer1(); SceneTestLayer1();
~SceneTestLayer1(); ~SceneTestLayer1();
virtual void onEnter(); virtual void onEnter();
virtual void onEnterTransitionDidFinish(); virtual void onEnterTransitionDidFinish();
void testDealloc(ccTime dt); void testDealloc(float dt);
void onPushScene(CCObject* pSender); void onPushScene(CCObject* pSender);
void onPushSceneTran(CCObject* pSender); void onPushSceneTran(CCObject* pSender);
void onQuit(CCObject* pSender); void onQuit(CCObject* pSender);
//CREATE_NODE(SceneTestLayer1); //CREATE_NODE(SceneTestLayer1);
} ; } ;
class SceneTestLayer2 : public CCLayer class SceneTestLayer2 : public CCLayer
{ {
float m_timeCounter; float m_timeCounter;
public: public:
SceneTestLayer2(); SceneTestLayer2();
void testDealloc(ccTime dt); void testDealloc(float dt);
void onGoBack(CCObject* pSender); void onGoBack(CCObject* pSender);
void onReplaceScene(CCObject* pSender); void onReplaceScene(CCObject* pSender);
void onReplaceSceneTran(CCObject* pSender); void onReplaceSceneTran(CCObject* pSender);
//CREATE_NODE(SceneTestLayer2); //CREATE_NODE(SceneTestLayer2);
} ; } ;
class SceneTestLayer3 : public CCLayerColor class SceneTestLayer3 : public CCLayerColor
{ {
public: public:
SceneTestLayer3(); SceneTestLayer3();
bool init();
virtual void testDealloc(ccTime dt); virtual void testDealloc(float dt);
void item0Clicked(CCObject* pSender);
virtual void ccTouchesEnded(CCSet* touches, CCEvent* event); void item1Clicked(CCObject* pSender);
void item2Clicked(CCObject* pSender);
//CREATE_NODE(SceneTestLayer3); CREATE_FUNC(SceneTestLayer3)
} ; } ;
class SceneTestScene : public TestScene class SceneTestScene : public TestScene
{ {
public: public:
virtual void runThisTest(); virtual void runThisTest();
}; };
#endif #endif
 End of changes. 8 change blocks. 
21 lines changed or deleted 21 lines changed or added


 SchedulerTest.h   SchedulerTest.h 
#ifndef _SCHEDULER_TEST_H_ #ifndef _SCHEDULER_TEST_H_
#define _SCHEDULER_TEST_H_ #define _SCHEDULER_TEST_H_
#include "cocos2d.h" #include "cocos2d.h"
#include "cocos-ext.h"
#include "../testBasic.h" #include "../testBasic.h"
//#import "cocos2d.h"
USING_NS_CC_EXT;
class SchedulerTestLayer : public CCLayer class SchedulerTestLayer : public CCLayer
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
void backCallback(CCObject* pSender); void backCallback(CCObject* pSender);
skipping to change at line 39 skipping to change at line 41
// -(void) restartCallback:(id) sender; // -(void) restartCallback:(id) sender;
// //
class SchedulerAutoremove : public SchedulerTestLayer class SchedulerAutoremove : public SchedulerTestLayer
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
void autoremove(ccTime dt); void autoremove(float dt);
void tick(ccTime dt); void tick(float dt);
private: private:
ccTime accum; float accum;
}; };
class SchedulerPauseResume : public SchedulerTestLayer class SchedulerPauseResume : public SchedulerTestLayer
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
void tick1(ccTime dt); void tick1(float dt);
void tick2(ccTime dt); void tick2(float dt);
void pause(ccTime dt); void pause(float dt);
};
class SchedulerPauseResumeAll : public SchedulerTestLayer
{
public:
SchedulerPauseResumeAll();
virtual ~SchedulerPauseResumeAll();
virtual void onEnter();
virtual void onExit();
virtual std::string title();
virtual std::string subtitle();
void tick1(float dt);
void tick2(float dt);
void pause(float dt);
void resume(float dt);
private:
CCSet* m_pPausedTargets;
};
class SchedulerPauseResumeAllUser : public SchedulerTestLayer
{
public:
SchedulerPauseResumeAllUser();
virtual ~SchedulerPauseResumeAllUser();
virtual void onEnter();
virtual void onExit();
virtual std::string title();
virtual std::string subtitle();
void tick1(float dt);
void tick2(float dt);
void pause(float dt);
void resume(float dt);
private:
CCSet* m_pPausedTargets;
}; };
class SchedulerUnscheduleAll : public SchedulerTestLayer class SchedulerUnscheduleAll : public SchedulerTestLayer
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
void tick1(ccTime dt); void tick1(float dt);
void tick2(ccTime dt); void tick2(float dt);
void tick3(ccTime dt); void tick3(float dt);
void tick4(ccTime dt); void tick4(float dt);
void unscheduleAll(ccTime dt); void unscheduleAll(float dt);
}; };
class SchedulerUnscheduleAllHard : public SchedulerTestLayer class SchedulerUnscheduleAllHard : public SchedulerTestLayer
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
virtual void onExit();
virtual std::string title();
virtual std::string subtitle();
void tick1(float dt);
void tick2(float dt);
void tick3(float dt);
void tick4(float dt);
void unscheduleAll(float dt);
private:
bool m_bActionManagerActive;
};
class SchedulerUnscheduleAllUserLevel : public SchedulerTestLayer
{
public:
virtual void onEnter();
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
void tick1(ccTime dt); void tick1(float dt);
void tick2(ccTime dt); void tick2(float dt);
void tick3(ccTime dt); void tick3(float dt);
void tick4(ccTime dt); void tick4(float dt);
void unscheduleAll(ccTime dt); void unscheduleAll(float dt);
}; };
class SchedulerSchedulesAndRemove : public SchedulerTestLayer class SchedulerSchedulesAndRemove : public SchedulerTestLayer
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
void tick1(ccTime dt); void tick1(float dt);
void tick2(ccTime dt); void tick2(float dt);
void tick3(ccTime dt); void tick3(float dt);
void tick4(ccTime dt); void tick4(float dt);
void scheduleAndUnschedule(ccTime dt); void scheduleAndUnschedule(float dt);
}; };
class SchedulerUpdate : public SchedulerTestLayer class SchedulerUpdate : public SchedulerTestLayer
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
void removeUpdates(ccTime dt); void removeUpdates(float dt);
}; };
class SchedulerUpdateAndCustom : public SchedulerTestLayer class SchedulerUpdateAndCustom : public SchedulerTestLayer
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
void update(ccTime dt); void update(float dt);
void tick(ccTime dt); void tick(float dt);
void stopSelectors(ccTime dt); void stopSelectors(float dt);
}; };
class SchedulerUpdateFromCustom : public SchedulerTestLayer class SchedulerUpdateFromCustom : public SchedulerTestLayer
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
void update(ccTime dt); void update(float dt);
void schedUpdate(ccTime dt); void schedUpdate(float dt);
void stopUpdate(ccTime dt); void stopUpdate(float dt);
}; };
class TestNode : public CCNode class TestNode : public CCNode
{ {
public: public:
~TestNode(); ~TestNode();
void initWithString(CCString* pStr, int priority); void initWithString(CCString* pStr, int priority);
private: private:
CCString* m_pstring; CCString* m_pstring;
}; };
class RescheduleSelector : public SchedulerTestLayer class RescheduleSelector : public SchedulerTestLayer
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
void schedUpdate(ccTime dt); void schedUpdate(float dt);
private: private:
float m_fInterval; float m_fInterval;
int m_nTicks; int m_nTicks;
}; };
class SchedulerDelayAndRepeat : public SchedulerTestLayer
{
public:
virtual void onEnter();
virtual std::string title();
virtual std::string subtitle();
void update(float dt);
};
class SchedulerTimeScale : public SchedulerTestLayer
{
public:
void onEnter();
void onExit();
virtual std::string title();
virtual std::string subtitle();
CCControlSlider* sliderCtl();
void sliderAction(CCObject* pSender, CCControlEvent controlEvent);
CCControlSlider* m_pSliderCtl;
};
class TwoSchedulers : public SchedulerTestLayer
{
public:
virtual ~TwoSchedulers();
virtual std::string title();
virtual std::string subtitle();
void onEnter();
CCControlSlider* sliderCtl();
void sliderAction(CCObject* sender, CCControlEvent controlEvent);
CCScheduler *sched1;
CCScheduler *sched2;
CCActionManager *actionManager1;
CCActionManager *actionManager2;
CCControlSlider *sliderCtl1;
CCControlSlider *sliderCtl2;
};
class SchedulerTestScene : public TestScene class SchedulerTestScene : public TestScene
{ {
public: public:
virtual void runThisTest(); virtual void runThisTest();
}; };
#endif #endif
 End of changes. 14 change blocks. 
30 lines changed or deleted 124 lines changed or added


 SensorJni.h   SensorJni.h 
skipping to change at line 30 skipping to change at line 30
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __ANDROID_SENSOR_JNI_H__ #ifndef __ANDROID_SENSOR_JNI_H__
#define __ANDROID_SENSOR_JNI_H__ #define __ANDROID_SENSOR_JNI_H__
extern "C" extern "C"
{ {
extern void enableAccelerometerJNI(); extern void enableAccelerometerJNI();
extern void disableAccelerometerJNI(); extern void disableAccelerometerJNI();
} }
#endif // __ANDROID_SENSOR_JNI_H__ #endif // __ANDROID_SENSOR_JNI_H__
 End of changes. 1 change blocks. 
2 lines changed or deleted 2 lines changed or added


 SensorTest.h   SensorTest.h 
skipping to change at line 27 skipping to change at line 27
*/ */
#ifndef SENSOR_TEST_H #ifndef SENSOR_TEST_H
#define SENSOR_TEST_H #define SENSOR_TEST_H
// This is used to test sensor shapes. // This is used to test sensor shapes.
class SensorTest : public Test class SensorTest : public Test
{ {
public: public:
enum enum
{ {
e_count = 7 e_count = 7
}; };
SensorTest() SensorTest()
{ {
{ {
b2BodyDef bd; b2BodyDef bd;
b2Body* ground = m_world->CreateBody(&bd); b2Body* ground = m_world->CreateBody(&bd);
{ {
b2EdgeShape shape; b2EdgeShape shape;
shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f));
, 0.0f)); ground->CreateFixture(&shape, 0.0f);
ground->CreateFixture(&shape, 0.0f); }
}
#if 0 #if 0
{ {
b2FixtureDef sd; b2FixtureDef sd;
sd.SetAsBox(10.0f, 2.0f, b2Vec2(0.0f, 20.0f) sd.SetAsBox(10.0f, 2.0f, b2Vec2(0.0f, 20.0f), 0.0f);
, 0.0f); sd.isSensor = true;
sd.isSensor = true; m_sensor = ground->CreateFixture(&sd);
m_sensor = ground->CreateFixture(&sd); }
}
#else #else
{ {
b2CircleShape shape; b2CircleShape shape;
shape.m_radius = 5.0f; shape.m_radius = 5.0f;
shape.m_p.Set(0.0f, 10.0f); shape.m_p.Set(0.0f, 10.0f);
b2FixtureDef fd; b2FixtureDef fd;
fd.shape = &shape; fd.shape = &shape;
fd.isSensor = true; fd.isSensor = true;
m_sensor = ground->CreateFixture(&fd); m_sensor = ground->CreateFixture(&fd);
} }
#endif #endif
} }
{ {
b2CircleShape shape; b2CircleShape shape;
shape.m_radius = 1.0f; shape.m_radius = 1.0f;
for (int32 i = 0; i < e_count; ++i) for (int32 i = 0; i < e_count; ++i)
{ {
b2BodyDef bd; b2BodyDef bd;
bd.type = b2_dynamicBody; bd.type = b2_dynamicBody;
bd.position.Set(-10.0f + 3.0f * i, 20.0f); bd.position.Set(-10.0f + 3.0f * i, 20.0f);
bd.userData = m_touching + i; bd.userData = m_touching + i;
m_touching[i] = false; m_touching[i] = false;
m_bodies[i] = m_world->CreateBody(&bd); m_bodies[i] = m_world->CreateBody(&bd);
m_bodies[i]->CreateFixture(&shape, 1.0f); m_bodies[i]->CreateFixture(&shape, 1.0f);
} }
} }
} }
// Implement contact listener. // Implement contact listener.
void BeginContact(b2Contact* contact) void BeginContact(b2Contact* contact)
{ {
b2Fixture* fixtureA = contact->GetFixtureA(); b2Fixture* fixtureA = contact->GetFixtureA();
b2Fixture* fixtureB = contact->GetFixtureB(); b2Fixture* fixtureB = contact->GetFixtureB();
if (fixtureA == m_sensor) if (fixtureA == m_sensor)
{ {
void* userData = fixtureB->GetBody()->GetUserData(); void* userData = fixtureB->GetBody()->GetUserData();
if (userData) if (userData)
{ {
bool* touching = (bool*)userData; bool* touching = (bool*)userData;
*touching = true; *touching = true;
} }
} }
if (fixtureB == m_sensor) if (fixtureB == m_sensor)
{ {
void* userData = fixtureA->GetBody()->GetUserData(); void* userData = fixtureA->GetBody()->GetUserData();
if (userData) if (userData)
{ {
bool* touching = (bool*)userData; bool* touching = (bool*)userData;
*touching = true; *touching = true;
} }
} }
} }
// Implement contact listener. // Implement contact listener.
void EndContact(b2Contact* contact) void EndContact(b2Contact* contact)
{ {
b2Fixture* fixtureA = contact->GetFixtureA(); b2Fixture* fixtureA = contact->GetFixtureA();
b2Fixture* fixtureB = contact->GetFixtureB(); b2Fixture* fixtureB = contact->GetFixtureB();
if (fixtureA == m_sensor) if (fixtureA == m_sensor)
{ {
void* userData = fixtureB->GetBody()->GetUserData(); void* userData = fixtureB->GetBody()->GetUserData();
if (userData) if (userData)
{ {
bool* touching = (bool*)userData; bool* touching = (bool*)userData;
*touching = false; *touching = false;
} }
} }
if (fixtureB == m_sensor) if (fixtureB == m_sensor)
{ {
void* userData = fixtureA->GetBody()->GetUserData(); void* userData = fixtureA->GetBody()->GetUserData();
if (userData) if (userData)
{ {
bool* touching = (bool*)userData; bool* touching = (bool*)userData;
*touching = false; *touching = false;
} }
} }
} }
void Step(Settings* settings) void Step(Settings* settings)
{ {
Test::Step(settings); Test::Step(settings);
// Traverse the contact results. Apply a force on shapes // Traverse the contact results. Apply a force on shapes
// that overlap the sensor. // that overlap the sensor.
for (int32 i = 0; i < e_count; ++i) for (int32 i = 0; i < e_count; ++i)
{ {
if (m_touching[i] == false) if (m_touching[i] == false)
{ {
continue; continue;
} }
b2Body* body = m_bodies[i]; b2Body* body = m_bodies[i];
b2Body* ground = m_sensor->GetBody(); b2Body* ground = m_sensor->GetBody();
b2CircleShape* circle = (b2CircleShape*)m_sensor->Ge b2CircleShape* circle = (b2CircleShape*)m_sensor->GetShape();
tShape(); b2Vec2 center = ground->GetWorldPoint(circle->m_p);
b2Vec2 center = ground->GetWorldPoint(circle->m_p);
b2Vec2 position = body->GetPosition();
b2Vec2 position = body->GetPosition();
b2Vec2 d = center - position;
b2Vec2 d = center - position; if (d.LengthSquared() < FLT_EPSILON * FLT_EPSILON)
if (d.LengthSquared() < FLT_EPSILON * FLT_EPSILON) {
{ continue;
continue; }
}
d.Normalize();
d.Normalize(); b2Vec2 F = 100.0f * d;
b2Vec2 F = 100.0f * d; body->ApplyForce(F, position);
body->ApplyForce(F, position); }
} }
}
static Test* Create()
static Test* Create() {
{ return new SensorTest;
return new SensorTest; }
}
b2Fixture* m_sensor;
b2Fixture* m_sensor; b2Body* m_bodies[e_count];
b2Body* m_bodies[e_count]; bool m_touching[e_count];
bool m_touching[e_count];
}; };
#endif #endif
 End of changes. 5 change blocks. 
150 lines changed or deleted 147 lines changed or added


 ShapeEditing.h   ShapeEditing.h 
skipping to change at line 26 skipping to change at line 26
* 3. This notice may not be removed or altered from any source distribution . * 3. This notice may not be removed or altered from any source distribution .
*/ */
#ifndef SHAPE_EDITING_H #ifndef SHAPE_EDITING_H
#define SHAPE_EDITING_H #define SHAPE_EDITING_H
class ShapeEditing : public Test class ShapeEditing : public Test
{ {
public: public:
ShapeEditing() ShapeEditing()
{ {
{ {
b2BodyDef bd; b2BodyDef bd;
b2Body* ground = m_world->CreateBody(&bd); b2Body* ground = m_world->CreateBody(&bd);
b2EdgeShape shape; b2EdgeShape shape;
shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)) shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f));
; ground->CreateFixture(&shape, 0.0f);
ground->CreateFixture(&shape, 0.0f); }
}
b2BodyDef bd;
b2BodyDef bd; bd.type = b2_dynamicBody;
bd.type = b2_dynamicBody; bd.position.Set(0.0f, 10.0f);
bd.position.Set(0.0f, 10.0f); m_body = m_world->CreateBody(&bd);
m_body = m_world->CreateBody(&bd);
b2PolygonShape shape;
b2PolygonShape shape; shape.SetAsBox(4.0f, 4.0f, b2Vec2(0.0f, 0.0f), 0.0f);
shape.SetAsBox(4.0f, 4.0f, b2Vec2(0.0f, 0.0f), 0.0f); m_fixture1 = m_body->CreateFixture(&shape, 10.0f);
m_fixture1 = m_body->CreateFixture(&shape, 10.0f);
m_fixture2 = NULL;
m_fixture2 = NULL;
m_sensor = false;
m_sensor = false; }
}
void Keyboard(unsigned char key)
void Keyboard(unsigned char key) {
{ switch (key)
switch (key) {
{ case 'c':
case 'c': if (m_fixture2 == NULL)
if (m_fixture2 == NULL) {
{ b2CircleShape shape;
b2CircleShape shape; shape.m_radius = 3.0f;
shape.m_radius = 3.0f; shape.m_p.Set(0.5f, -4.0f);
shape.m_p.Set(0.5f, -4.0f); m_fixture2 = m_body->CreateFixture(&shape, 10.0f);
m_fixture2 = m_body->CreateFixture(&shape, 1 m_body->SetAwake(true);
0.0f); }
m_body->SetAwake(true); break;
}
break; case 'd':
if (m_fixture2 != NULL)
case 'd': {
if (m_fixture2 != NULL) m_body->DestroyFixture(m_fixture2);
{ m_fixture2 = NULL;
m_body->DestroyFixture(m_fixture2); m_body->SetAwake(true);
m_fixture2 = NULL; }
m_body->SetAwake(true); break;
}
break; case 's':
if (m_fixture2 != NULL)
case 's': {
if (m_fixture2 != NULL) m_sensor = !m_sensor;
{ m_fixture2->SetSensor(m_sensor);
m_sensor = !m_sensor; }
m_fixture2->SetSensor(m_sensor); break;
} }
break; }
}
} void Step(Settings* settings)
{
void Step(Settings* settings) Test::Step(settings);
{ m_debugDraw.DrawString(5, m_textLine, "Press: (c) create a shape, (
Test::Step(settings); d) destroy a shape.");
m_debugDraw.DrawString(5, m_textLine, "Press: (c) create a s m_textLine += 15;
hape, (d) destroy a shape."); m_debugDraw.DrawString(5, m_textLine, "sensor = %d", m_sensor);
m_textLine += 15; m_textLine += 15;
m_debugDraw.DrawString(5, m_textLine, "sensor = %d", m_senso }
r);
m_textLine += 15; static Test* Create()
} {
return new ShapeEditing;
static Test* Create() }
{
return new ShapeEditing; b2Body* m_body;
} b2Fixture* m_fixture1;
b2Fixture* m_fixture2;
b2Body* m_body; bool m_sensor;
b2Fixture* m_fixture1;
b2Fixture* m_fixture2;
bool m_sensor;
}; };
#endif #endif
 End of changes. 1 change blocks. 
81 lines changed or deleted 78 lines changed or added


 SimpleAudioEngine.h   SimpleAudioEngine.h 
skipping to change at line 36 skipping to change at line 36
#ifndef _SIMPLE_AUDIO_ENGINE_H_ #ifndef _SIMPLE_AUDIO_ENGINE_H_
#define _SIMPLE_AUDIO_ENGINE_H_ #define _SIMPLE_AUDIO_ENGINE_H_
#include "Export.h" #include "Export.h"
#include <stddef.h> #include <stddef.h>
namespace CocosDenshion { namespace CocosDenshion {
/** /**
@class SimpleAudioEngine @class SimpleAudioEngine
@brief offer a VERY simple interface to play background mus ic & sound effect @brief offer a VERY simple interface to play background music & so und effect
*/ */
class EXPORT_DLL SimpleAudioEngine class EXPORT_DLL SimpleAudioEngine
{ {
public: public:
SimpleAudioEngine(); SimpleAudioEngine();
~SimpleAudioEngine(); ~SimpleAudioEngine();
/** /**
@brief Get the shared Engine object,it will new one when first time be called @brief Get the shared Engine object,it will new one when first time be called
*/ */
static SimpleAudioEngine* sharedEngine(); static SimpleAudioEngine* sharedEngine();
/** /**
@brief Release the shared Engine object @brief Release the shared Engine object
@warning It must be called before the application exit, or a memroy lea k will be casued. @warning It must be called before the application exit, or a memroy lea k will be casued.
*/ */
static void end(); static void end();
/**
@brief Set the zip file name
@param pszZipFileName The relative path of the .zip file
*/
static void setResource(const char* pszZipFileName);
/** /**
@brief Preload background music @brief Preload background music
@param pszFilePath The path of the background music file,or the FileNa me of T_SoundResInfo @param pszFilePath The path of the background music file,or the FileNa me of T_SoundResInfo
*/ */
void preloadBackgroundMusic(const char* pszFilePath); void preloadBackgroundMusic(const char* pszFilePath);
/** /**
@brief Play background music @brief Play background music
@param pszFilePath The path of the background music file,or the FileNam e of T_SoundResInfo @param pszFilePath The path of the background music file,or the FileNam e of T_SoundResInfo
skipping to change at line 130 skipping to change at line 124
/** /**
@brief set the volume of sound effecs @brief set the volume of sound effecs
@param volume must be in 0.0~1.0 @param volume must be in 0.0~1.0
*/ */
void setEffectsVolume(float volume); void setEffectsVolume(float volume);
// for sound effects // for sound effects
/** /**
@brief Play sound effect @brief Play sound effect
@param pszFilePath The path of the effect file,or the FileName of T_Sou ndResInfo @param pszFilePath The path of the effect file,or the FileName of T_Sou ndResInfo
@bLoop Whether to loop the effect playing, default value is false @bLoop Whether to loop the effect playing, default value is false
*/ */
unsigned int playEffect(const char* pszFilePath, bool bLoop = false); unsigned int playEffect(const char* pszFilePath, bool bLoop = false);
/** /**
@brief Pause playing sound effect @brief Pause playing sound effect
@param nSoundId The return value of function playEffect @param nSoundId The return value of function playEffect
*/ */
void pauseEffect(unsigned int nSoundId); void pauseEffect(unsigned int nSoundId);
/** /**
@brief Pause all playing sound effect @brief Pause all playing sound effect
@param nSoundId The return value of function playEffect @param nSoundId The return value of function playEffect
*/ */
void pauseAllEffects(); void pauseAllEffects();
/** /**
@brief Resume playing sound effect @brief Resume playing sound effect
@param nSoundId The return value of function playEffect @param nSoundId The return value of function playEffect
*/ */
void resumeEffect(unsigned int nSoundId); void resumeEffect(unsigned int nSoundId);
/** /**
@brief Resume all playing sound effect @brief Resume all playing sound effect
@param nSoundId The return value of function playEffect @param nSoundId The return value of function playEffect
*/ */
void resumeAllEffects(); void resumeAllEffects();
/** /**
@brief Stop playing sound effect @brief Stop playing sound effect
@param nSoundId The return value of function playEffect @param nSoundId The return value of function playEffect
*/ */
void stopEffect(unsigned int nSoundId); void stopEffect(unsigned int nSoundId);
/** /**
@brief Stop all playing sound effects @brief Stop all playing sound effects
*/ */
void stopAllEffects(); void stopAllEffects();
/** /**
@brief preload a compressed audio file @brief preload a compressed audio file
@details the compressed audio will be decode to wave, then write @details the compressed audio will be decode to wave, then write
into an into an
internal buffer in SimpleaudioEngine internal buffer in SimpleaudioEngine
*/ */
void preloadEffect(const char* pszFilePath); void preloadEffect(const char* pszFilePath);
/** /**
@brief unload the preloaded effect from internal buffer @brief unload the preloaded effect from internal buffer
@param[in] pszFilePath The path of the effect file, @param[in] pszFilePath The path of the effect file,or the
or the FileName of T_SoundResInfo FileName of T_SoundResInfo
*/ */
void unloadEffect(const char* pszFilePath); void unloadEffect(const char* pszFilePath);
}; };
} // end of namespace CocosDenshion } // end of namespace CocosDenshion
#endif // _SIMPLE_AUDIO_ENGINE_H_ #endif // _SIMPLE_AUDIO_ENGINE_H_
 End of changes. 13 change blocks. 
23 lines changed or deleted 17 lines changed or added


 SimpleAudioEngineJni.h   SimpleAudioEngineJni.h 
#ifndef __SIMPLE_AUDIO_ENGINE_JNI__ #ifndef __SIMPLE_AUDIO_ENGINE_JNI__
#define __SIMPLE_AUDIO_ENGINE_JNI__ #define __SIMPLE_AUDIO_ENGINE_JNI__
#include <jni.h> #include <jni.h>
extern "C" extern "C"
{ {
extern void preloadBackgroundMusicJNI(const char *path); extern void preloadBackgroundMusicJNI(const char *path);
extern void playBackgroundMusicJNI(const char *path, bool isLoop); extern void playBackgroundMusicJNI(const char *path, bool isLoop);
extern void stopBackgroundMusicJNI(); extern void stopBackgroundMusicJNI();
extern void pauseBackgroundMusicJNI(); extern void pauseBackgroundMusicJNI();
extern void resumeBackgroundMusicJNI(); extern void resumeBackgroundMusicJNI();
extern void rewindBackgroundMusicJNI(); extern void rewindBackgroundMusicJNI();
extern bool isBackgroundMusicPlayingJNI(); extern bool isBackgroundMusicPlayingJNI();
extern float getBackgroundMusicVolumeJNI(); extern float getBackgroundMusicVolumeJNI();
extern void setBackgroundMusicVolumeJNI(float volume); extern void setBackgroundMusicVolumeJNI(float volume);
extern unsigned int playEffectJNI(const char* path, bool bLoop); extern unsigned int playEffectJNI(const char* path, bool bLoop);
extern void stopEffectJNI(unsigned int nSoundId); extern void stopEffectJNI(unsigned int nSoundId);
extern void endJNI(); extern void endJNI();
extern float getEffectsVolumeJNI(); extern float getEffectsVolumeJNI();
extern void setEffectsVolumeJNI(float volume); extern void setEffectsVolumeJNI(float volume);
extern void preloadEffectJNI(const char *path); extern void preloadEffectJNI(const char *path);
extern void unloadEffectJNI(const char* path); extern void unloadEffectJNI(const char* path);
extern void pauseEffectJNI(unsigned int nSoundId); extern void pauseEffectJNI(unsigned int nSoundId);
extern void pauseAllEffectsJNI(); extern void pauseAllEffectsJNI();
extern void resumeEffectJNI(unsigned int nSoundId); extern void resumeEffectJNI(unsigned int nSoundId);
extern void resumeAllEffectsJNI(); extern void resumeAllEffectsJNI();
extern void stopAllEffectsJNI(); extern void stopAllEffectsJNI();
} }
#endif // __SIMPLE_AUDIO_ENGINE_JNI__ #endif // __SIMPLE_AUDIO_ENGINE_JNI__
 End of changes. 1 change blocks. 
19 lines changed or deleted 19 lines changed or added


 SimpleAudioEngine_objc.h   SimpleAudioEngine_objc.h 
skipping to change at line 41 skipping to change at line 41
this is the interface to use. this is the interface to use.
Requirements: Requirements:
- Firmware: OS 2.2 or greater - Firmware: OS 2.2 or greater
- Files: SimpleAudioEngine.*, CocosDenshion.* - Files: SimpleAudioEngine.*, CocosDenshion.*
- Frameworks: OpenAL, AudioToolbox, AVFoundation - Frameworks: OpenAL, AudioToolbox, AVFoundation
@since v0.8 @since v0.8
*/ */
@interface SimpleAudioEngine : NSObject <CDAudioInterruptProtocol> { @interface SimpleAudioEngine : NSObject <CDAudioInterruptProtocol> {
BOOL mute_; BOOL mute_;
BOOL enabled_; BOOL enabled_;
} }
/** Background music volume. Range is 0.0f to 1.0f. This will only have an effect if willPlayBackgroundMusic returns YES */ /** Background music volume. Range is 0.0f to 1.0f. This will only have an effect if willPlayBackgroundMusic returns YES */
@property (readwrite) float backgroundMusicVolume; @property (readwrite) float backgroundMusicVolume;
/** Effects volume. Range is 0.0f to 1.0f */ /** Effects volume. Range is 0.0f to 1.0f */
@property (readwrite) float effectsVolume; @property (readwrite) float effectsVolume;
/** If NO it indicates background music will not be played either because n o background music is loaded or the audio session does not permit it.*/ /** If NO it indicates background music will not be played either because n o background music is loaded or the audio session does not permit it.*/
@property (readonly) BOOL willPlayBackgroundMusic; @property (readonly) BOOL willPlayBackgroundMusic;
/** returns the shared instance of the SimpleAudioEngine object */ /** returns the shared instance of the SimpleAudioEngine object */
 End of changes. 1 change blocks. 
2 lines changed or deleted 2 lines changed or added


 SliderCrank.h   SliderCrank.h 
skipping to change at line 27 skipping to change at line 27
*/ */
#ifndef SLIDER_CRANK_H #ifndef SLIDER_CRANK_H
#define SLIDER_CRANK_H #define SLIDER_CRANK_H
// A motor driven slider crank with joint friction. // A motor driven slider crank with joint friction.
class SliderCrank : public Test class SliderCrank : public Test
{ {
public: public:
SliderCrank() SliderCrank()
{ {
b2Body* ground = NULL; b2Body* ground = NULL;
{ {
b2BodyDef bd; b2BodyDef bd;
ground = m_world->CreateBody(&bd); ground = m_world->CreateBody(&bd);
b2EdgeShape shape; b2EdgeShape shape;
shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)) shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f));
; ground->CreateFixture(&shape, 0.0f);
ground->CreateFixture(&shape, 0.0f); }
}
{
{ b2Body* prevBody = ground;
b2Body* prevBody = ground;
// Define crank.
// Define crank. {
{ b2PolygonShape shape;
b2PolygonShape shape; shape.SetAsBox(0.5f, 2.0f);
shape.SetAsBox(0.5f, 2.0f);
b2BodyDef bd;
b2BodyDef bd; bd.type = b2_dynamicBody;
bd.type = b2_dynamicBody; bd.position.Set(0.0f, 7.0f);
bd.position.Set(0.0f, 7.0f); b2Body* body = m_world->CreateBody(&bd);
b2Body* body = m_world->CreateBody(&bd); body->CreateFixture(&shape, 2.0f);
body->CreateFixture(&shape, 2.0f);
b2RevoluteJointDef rjd;
b2RevoluteJointDef rjd; rjd.Initialize(prevBody, body, b2Vec2(0.0f, 5.0f));
rjd.Initialize(prevBody, body, b2Vec2(0.0f, rjd.motorSpeed = 1.0f * b2_pi;
5.0f)); rjd.maxMotorTorque = 10000.0f;
rjd.motorSpeed = 1.0f * b2_pi; rjd.enableMotor = true;
rjd.maxMotorTorque = 10000.0f; m_joint1 = (b2RevoluteJoint*)m_world->CreateJoint(&rjd);
rjd.enableMotor = true;
m_joint1 = (b2RevoluteJoint*)m_world->Create prevBody = body;
Joint(&rjd); }
prevBody = body; // Define follower.
} {
b2PolygonShape shape;
// Define follower. shape.SetAsBox(0.5f, 4.0f);
{
b2PolygonShape shape; b2BodyDef bd;
shape.SetAsBox(0.5f, 4.0f); bd.type = b2_dynamicBody;
bd.position.Set(0.0f, 13.0f);
b2BodyDef bd; b2Body* body = m_world->CreateBody(&bd);
bd.type = b2_dynamicBody; body->CreateFixture(&shape, 2.0f);
bd.position.Set(0.0f, 13.0f);
b2Body* body = m_world->CreateBody(&bd); b2RevoluteJointDef rjd;
body->CreateFixture(&shape, 2.0f); rjd.Initialize(prevBody, body, b2Vec2(0.0f, 9.0f));
rjd.enableMotor = false;
b2RevoluteJointDef rjd; m_world->CreateJoint(&rjd);
rjd.Initialize(prevBody, body, b2Vec2(0.0f,
9.0f)); prevBody = body;
rjd.enableMotor = false; }
m_world->CreateJoint(&rjd);
// Define piston
prevBody = body; {
} b2PolygonShape shape;
shape.SetAsBox(1.5f, 1.5f);
// Define piston
{ b2BodyDef bd;
b2PolygonShape shape; bd.type = b2_dynamicBody;
shape.SetAsBox(1.5f, 1.5f); bd.fixedRotation = true;
bd.position.Set(0.0f, 17.0f);
b2BodyDef bd; b2Body* body = m_world->CreateBody(&bd);
bd.type = b2_dynamicBody; body->CreateFixture(&shape, 2.0f);
bd.fixedRotation = true;
bd.position.Set(0.0f, 17.0f); b2RevoluteJointDef rjd;
b2Body* body = m_world->CreateBody(&bd); rjd.Initialize(prevBody, body, b2Vec2(0.0f, 17.0f));
body->CreateFixture(&shape, 2.0f); m_world->CreateJoint(&rjd);
b2RevoluteJointDef rjd; b2PrismaticJointDef pjd;
rjd.Initialize(prevBody, body, b2Vec2(0.0f, pjd.Initialize(ground, body, b2Vec2(0.0f, 17.0f), b2Vec2(0.
17.0f)); 0f, 1.0f));
m_world->CreateJoint(&rjd);
pjd.maxMotorForce = 1000.0f;
b2PrismaticJointDef pjd; pjd.enableMotor = true;
pjd.Initialize(ground, body, b2Vec2(0.0f, 17
.0f), b2Vec2(0.0f, 1.0f)); m_joint2 = (b2PrismaticJoint*)m_world->CreateJoint(&pjd);
}
pjd.maxMotorForce = 1000.0f;
pjd.enableMotor = true; // Create a payload
{
m_joint2 = (b2PrismaticJoint*)m_world->Creat b2PolygonShape shape;
eJoint(&pjd); shape.SetAsBox(1.5f, 1.5f);
}
b2BodyDef bd;
// Create a payload bd.type = b2_dynamicBody;
{ bd.position.Set(0.0f, 23.0f);
b2PolygonShape shape; b2Body* body = m_world->CreateBody(&bd);
shape.SetAsBox(1.5f, 1.5f); body->CreateFixture(&shape, 2.0f);
}
b2BodyDef bd; }
bd.type = b2_dynamicBody; }
bd.position.Set(0.0f, 23.0f);
b2Body* body = m_world->CreateBody(&bd); void Keyboard(unsigned char key)
body->CreateFixture(&shape, 2.0f); {
} switch (key)
} {
} case 'f':
m_joint2->EnableMotor(!m_joint2->IsMotorEnabled());
void Keyboard(unsigned char key) m_joint2->GetBodyB()->SetAwake(true);
{ break;
switch (key)
{ case 'm':
case 'f': m_joint1->EnableMotor(!m_joint1->IsMotorEnabled());
m_joint2->EnableMotor(!m_joint2->IsMotorEnabled()); m_joint1->GetBodyB()->SetAwake(true);
m_joint2->GetBodyB()->SetAwake(true); break;
break; }
}
case 'm':
m_joint1->EnableMotor(!m_joint1->IsMotorEnabled()); void Step(Settings* settings)
m_joint1->GetBodyB()->SetAwake(true); {
break; Test::Step(settings);
} m_debugDraw.DrawString(5, m_textLine, "Keys: (f) toggle friction, (
} m) toggle motor");
m_textLine += 15;
void Step(Settings* settings) float32 torque = m_joint1->GetMotorTorque(settings->hz);
{ m_debugDraw.DrawString(5, m_textLine, "Motor Torque = %5.0f", (floa
Test::Step(settings); t) torque);
m_debugDraw.DrawString(5, m_textLine, "Keys: (f) toggle fric m_textLine += 15;
tion, (m) toggle motor"); }
m_textLine += 15;
float32 torque = m_joint1->GetMotorTorque(settings->hz); static Test* Create()
m_debugDraw.DrawString(5, m_textLine, "Motor Torque = %5.0f" {
, (float) torque); return new SliderCrank;
m_textLine += 15; }
}
static Test* Create()
{
return new SliderCrank;
}
b2RevoluteJoint* m_joint1; b2RevoluteJoint* m_joint1;
b2PrismaticJoint* m_joint2; b2PrismaticJoint* m_joint2;
}; };
#endif #endif
 End of changes. 2 change blocks. 
135 lines changed or deleted 129 lines changed or added


 SphereStack.h   SphereStack.h 
skipping to change at line 26 skipping to change at line 26
* 3. This notice may not be removed or altered from any source distribution . * 3. This notice may not be removed or altered from any source distribution .
*/ */
#ifndef SPHERE_STACK_H #ifndef SPHERE_STACK_H
#define SPHERE_STACK_H #define SPHERE_STACK_H
class SphereStack : public Test class SphereStack : public Test
{ {
public: public:
enum enum
{ {
e_count = 10 e_count = 10
}; };
SphereStack() SphereStack()
{ {
{ {
b2BodyDef bd; b2BodyDef bd;
b2Body* ground = m_world->CreateBody(&bd); b2Body* ground = m_world->CreateBody(&bd);
b2EdgeShape shape; b2EdgeShape shape;
shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)) shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f));
; ground->CreateFixture(&shape, 0.0f);
ground->CreateFixture(&shape, 0.0f); }
}
{
{ b2CircleShape shape;
b2CircleShape shape; shape.m_radius = 1.0f;
shape.m_radius = 1.0f;
for (int32 i = 0; i < e_count; ++i)
for (int32 i = 0; i < e_count; ++i) {
{ b2BodyDef bd;
b2BodyDef bd; bd.type = b2_dynamicBody;
bd.type = b2_dynamicBody; bd.position.Set(0.0, 4.0f + 3.0f * i);
bd.position.Set(0.0, 4.0f + 3.0f * i);
m_bodies[i] = m_world->CreateBody(&bd);
m_bodies[i] = m_world->CreateBody(&bd);
m_bodies[i]->CreateFixture(&shape, 1.0f);
m_bodies[i]->CreateFixture(&shape, 1.0f);
m_bodies[i]->SetLinearVelocity(b2Vec2(0.0f, -50.0f));
m_bodies[i]->SetLinearVelocity(b2Vec2(0.0f, }
-50.0f)); }
} }
}
} void Step(Settings* settings)
{
void Step(Settings* settings) Test::Step(settings);
{
Test::Step(settings); //for (int32 i = 0; i < e_count; ++i)
//{
//for (int32 i = 0; i < e_count; ++i) // printf("%g ", m_bodies[i]->GetWorldCenter().y);
//{ //}
// printf("%g ", m_bodies[i]->GetWorldCenter().y);
//} //for (int32 i = 0; i < e_count; ++i)
//{
//for (int32 i = 0; i < e_count; ++i) // printf("%g ", m_bodies[i]->GetLinearVelocity().y);
//{ //}
// printf("%g ", m_bodies[i]->GetLinearVelocity().y);
//} //printf("\n");
}
//printf("\n");
} static Test* Create()
{
static Test* Create() return new SphereStack;
{ }
return new SphereStack;
}
b2Body* m_bodies[e_count]; b2Body* m_bodies[e_count];
}; };
#endif #endif
 End of changes. 2 change blocks. 
59 lines changed or deleted 57 lines changed or added


 SpriteTest.h   SpriteTest.h 
#ifndef _SPRITE_TEST_H_ #ifndef _SPRITE_TEST_H_
#define _SPRITE_TEST_H_ #define _SPRITE_TEST_H_
#include "cocos2d.h" #include "cocos2d.h"
#include "../testBasic.h" #include "../testBasic.h"
#include <string>
class SpriteTestDemo : public CCLayer class SpriteTestDemo : public CCLayer
{ {
protected: protected:
std::string m_strTitle; std::string m_strTitle;
public: public:
SpriteTestDemo(void); SpriteTestDemo(void);
~SpriteTestDemo(void); ~SpriteTestDemo(void);
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
virtual void onEnter(); virtual void onEnter();
void restartCallback(CCObject* pSender); void restartCallback(CCObject* pSender);
void nextCallback(CCObject* pSender); void nextCallback(CCObject* pSender);
void backCallback(CCObject* pSender); void backCallback(CCObject* pSender);
}; };
class Sprite1 : public SpriteTestDemo class Sprite1 : public SpriteTestDemo
{ {
public: public:
Sprite1(); Sprite1();
virtual std::string title(); virtual std::string title();
void addNewSpriteWithCoords(CCPoint p); void addNewSpriteWithCoords(CCPoint p);
void ccTouchesEnded(CCSet* touches, CCEvent* event); void ccTouchesEnded(CCSet* touches, CCEvent* event);
}; };
class SpriteBatchNode1: public SpriteTestDemo class SpriteBatchNode1: public SpriteTestDemo
{ {
public: public:
SpriteBatchNode1(); SpriteBatchNode1();
void addNewSpriteWithCoords(CCPoint p); void addNewSpriteWithCoords(CCPoint p);
virtual void ccTouchesEnded(CCSet* touches, CCEvent* event); virtual void ccTouchesEnded(CCSet* touches, CCEvent* event);
virtual std::string title(); virtual std::string title();
}; };
class SpriteColorOpacity : public SpriteTestDemo class SpriteColorOpacity : public SpriteTestDemo
{ {
public: public:
SpriteColorOpacity(); SpriteColorOpacity();
void removeAndAddSprite(ccTime dt); void removeAndAddSprite(float dt);
virtual std::string title(); virtual std::string title();
}; };
class SpriteBatchNodeColorOpacity : public SpriteTestDemo class SpriteBatchNodeColorOpacity : public SpriteTestDemo
{ {
public: public:
SpriteBatchNodeColorOpacity(); SpriteBatchNodeColorOpacity();
void removeAndAddSprite(ccTime dt); void removeAndAddSprite(float dt);
virtual std::string title(); virtual std::string title();
}; };
class SpriteZOrder : public SpriteTestDemo class SpriteZOrder : public SpriteTestDemo
{ {
int m_dir; int m_dir;
public: public:
SpriteZOrder(); SpriteZOrder();
void reorderSprite(ccTime dt); void reorderSprite(float dt);
virtual std::string title(); virtual std::string title();
}; };
class SpriteBatchNodeZOrder: public SpriteTestDemo class SpriteBatchNodeZOrder: public SpriteTestDemo
{ {
int m_dir; int m_dir;
public: public:
SpriteBatchNodeZOrder(); SpriteBatchNodeZOrder();
void reorderSprite(ccTime dt); void reorderSprite(float dt);
virtual std::string title(); virtual std::string title();
}; };
class SpriteBatchNodeReorder : public SpriteTestDemo class SpriteBatchNodeReorder : public SpriteTestDemo
{ {
public: public:
SpriteBatchNodeReorder(); SpriteBatchNodeReorder();
virtual std::string title(); virtual std::string title();
std::string subtitle(); std::string subtitle();
}; };
class SpriteBatchNodeReorderIssue744: public SpriteTestDemo class SpriteBatchNodeReorderIssue744: public SpriteTestDemo
{ {
public: public:
SpriteBatchNodeReorderIssue744(); SpriteBatchNodeReorderIssue744();
virtual std::string title(); virtual std::string title();
std::string subtitle(); std::string subtitle();
}; };
class SpriteBatchNodeReorderIssue766 : public SpriteTestDemo class SpriteBatchNodeReorderIssue766 : public SpriteTestDemo
{ {
public: public:
SpriteBatchNodeReorderIssue766(); SpriteBatchNodeReorderIssue766();
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
void reorderSprite(ccTime dt); void reorderSprite(float dt);
CCSprite* makeSpriteZ(int aZ); CCSprite* makeSpriteZ(int aZ);
private: private:
CCSpriteBatchNode *batchNode; CCSpriteBatchNode *batchNode;
CCSprite *sprite1; CCSprite *sprite1;
CCSprite *sprite2; CCSprite *sprite2;
CCSprite *sprite3; CCSprite *sprite3;
}; };
class SpriteBatchNodeReorderIssue767 : public SpriteTestDemo class SpriteBatchNodeReorderIssue767 : public SpriteTestDemo
{ {
public: public:
SpriteBatchNodeReorderIssue767(); SpriteBatchNodeReorderIssue767();
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
void reorderSprites(ccTime dt); void reorderSprites(float dt);
}; };
class SpriteZVertex: public SpriteTestDemo class SpriteZVertex: public SpriteTestDemo
{ {
int m_dir; int m_dir;
float m_time; float m_time;
public: public:
virtual void onEnter(); virtual void onEnter();
virtual void onExit(); virtual void onExit();
SpriteZVertex(); SpriteZVertex();
virtual std::string title(); virtual std::string title();
}; };
class SpriteBatchNodeZVertex: public SpriteTestDemo class SpriteBatchNodeZVertex: public SpriteTestDemo
{ {
int m_dir; int m_dir;
float m_time; float m_time;
public: public:
virtual void onEnter(); virtual void onEnter();
virtual void onExit(); virtual void onExit();
SpriteBatchNodeZVertex(); SpriteBatchNodeZVertex();
virtual std::string title(); virtual std::string title();
}; };
class SpriteAnchorPoint : public SpriteTestDemo class SpriteAnchorPoint : public SpriteTestDemo
{ {
public: public:
SpriteAnchorPoint(); SpriteAnchorPoint();
virtual std::string title(); virtual std::string title();
}; };
class SpriteBatchNodeAnchorPoint : public SpriteTestDemo class SpriteBatchNodeAnchorPoint : public SpriteTestDemo
{ {
public: public:
SpriteBatchNodeAnchorPoint(); SpriteBatchNodeAnchorPoint();
virtual std::string title(); virtual std::string title();
}; };
class Sprite6 : public SpriteTestDemo class Sprite6 : public SpriteTestDemo
{ {
public: public:
Sprite6(); Sprite6();
virtual std::string title(); virtual std::string title();
}; };
class SpriteFlip : public SpriteTestDemo class SpriteFlip : public SpriteTestDemo
{ {
public: public:
SpriteFlip(); SpriteFlip();
void flipSprites(ccTime dt); void flipSprites(float dt);
virtual std::string title(); virtual std::string title();
}; };
class SpriteBatchNodeFlip : public SpriteTestDemo class SpriteBatchNodeFlip : public SpriteTestDemo
{ {
public: public:
SpriteBatchNodeFlip(); SpriteBatchNodeFlip();
void flipSprites(ccTime dt); void flipSprites(float dt);
virtual std::string title(); virtual std::string title();
}; };
class SpriteAliased : public SpriteTestDemo class SpriteAliased : public SpriteTestDemo
{ {
public: public:
SpriteAliased(); SpriteAliased();
virtual void onEnter(); virtual void onEnter();
virtual void onExit(); virtual void onExit();
virtual std::string title(); virtual std::string title();
}; };
class SpriteBatchNodeAliased : public SpriteTestDemo class SpriteBatchNodeAliased : public SpriteTestDemo
{ {
public: public:
SpriteBatchNodeAliased(); SpriteBatchNodeAliased();
virtual void onEnter(); virtual void onEnter();
virtual void onExit(); virtual void onExit();
virtual std::string title(); virtual std::string title();
}; };
class SpriteNewTexture : public SpriteTestDemo class SpriteNewTexture : public SpriteTestDemo
{ {
bool m_usingTexture1; bool m_usingTexture1;
CCTexture2D* m_texture1; CCTexture2D* m_texture1;
CCTexture2D* m_texture2; CCTexture2D* m_texture2;
public: public:
SpriteNewTexture(); SpriteNewTexture();
virtual ~SpriteNewTexture(); virtual ~SpriteNewTexture();
void addNewSprite(); void addNewSprite();
void ccTouchesEnded(CCSet* touches, CCEvent* event); void ccTouchesEnded(CCSet* touches, CCEvent* event);
virtual std::string title(); virtual std::string title();
}; };
class SpriteBatchNodeNewTexture : public SpriteTestDemo class SpriteBatchNodeNewTexture : public SpriteTestDemo
{ {
CCTexture2D* m_texture1; CCTexture2D* m_texture1;
CCTexture2D* m_texture2; CCTexture2D* m_texture2;
public: public:
SpriteBatchNodeNewTexture(); SpriteBatchNodeNewTexture();
virtual ~SpriteBatchNodeNewTexture(); virtual ~SpriteBatchNodeNewTexture();
void addNewSprite(); void addNewSprite();
void ccTouchesEnded(CCSet* touches, CCEvent* event); void ccTouchesEnded(CCSet* touches, CCEvent* event);
virtual std::string title(); virtual std::string title();
}; };
class SpriteFrameTest: public SpriteTestDemo class SpriteFrameTest: public SpriteTestDemo
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
virtual void onExit(); virtual void onExit();
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
void startIn05Secs(ccTime dt); void startIn05Secs(float dt);
void flipSprites(ccTime dt); void flipSprites(float dt);
private: private:
CCSprite *m_pSprite1; CCSprite *m_pSprite1;
CCSprite *m_pSprite2; CCSprite *m_pSprite2;
int m_nCounter; int m_nCounter;
}; };
class SpriteFrameAliasNameTest : public SpriteTestDemo class SpriteFrameAliasNameTest : public SpriteTestDemo
{ {
public: public:
virtual void onEnter(); virtual void onEnter();
virtual void onExit(); virtual void onExit();
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
}; };
class SpriteOffsetAnchorRotation: public SpriteTestDemo class SpriteOffsetAnchorRotation: public SpriteTestDemo
{ {
public: public:
SpriteOffsetAnchorRotation(); SpriteOffsetAnchorRotation();
virtual void onExit(); virtual void onExit();
virtual std::string title(); virtual std::string title();
}; };
class SpriteBatchNodeOffsetAnchorRotation: public SpriteTestDemo class SpriteBatchNodeOffsetAnchorRotation: public SpriteTestDemo
{ {
public: public:
SpriteBatchNodeOffsetAnchorRotation(); SpriteBatchNodeOffsetAnchorRotation();
virtual void onExit(); virtual void onExit();
virtual std::string title(); virtual std::string title();
}; };
class SpriteOffsetAnchorScale: public SpriteTestDemo class SpriteOffsetAnchorScale: public SpriteTestDemo
{ {
public: public:
SpriteOffsetAnchorScale(); SpriteOffsetAnchorScale();
virtual void onExit(); virtual void onExit();
virtual std::string title(); virtual std::string title();
}; };
class SpriteBatchNodeOffsetAnchorScale: public SpriteTestDemo class SpriteBatchNodeOffsetAnchorScale: public SpriteTestDemo
{ {
public: public:
SpriteBatchNodeOffsetAnchorScale(); SpriteBatchNodeOffsetAnchorScale();
virtual void onExit(); virtual void onExit();
virtual std::string title(); virtual std::string title();
}; };
class SpriteOffsetAnchorSkew : public SpriteTestDemo class SpriteOffsetAnchorSkew : public SpriteTestDemo
{ {
public: public:
SpriteOffsetAnchorSkew(); SpriteOffsetAnchorSkew();
~SpriteOffsetAnchorSkew(); ~SpriteOffsetAnchorSkew();
virtual std::string title(); virtual std::string title();
}; };
class SpriteBatchNodeOffsetAnchorSkew : public SpriteTestDemo class SpriteBatchNodeOffsetAnchorSkew : public SpriteTestDemo
{ {
public: public:
SpriteBatchNodeOffsetAnchorSkew(); SpriteBatchNodeOffsetAnchorSkew();
~SpriteBatchNodeOffsetAnchorSkew(); ~SpriteBatchNodeOffsetAnchorSkew();
virtual std::string title(); virtual std::string title();
}; };
class SpriteOffsetAnchorSkewScale : public SpriteTestDemo class SpriteOffsetAnchorSkewScale : public SpriteTestDemo
{ {
public: public:
SpriteOffsetAnchorSkewScale(); SpriteOffsetAnchorSkewScale();
~SpriteOffsetAnchorSkewScale(); ~SpriteOffsetAnchorSkewScale();
virtual std::string title(); virtual std::string title();
}; };
class SpriteBatchNodeOffsetAnchorSkewScale : public SpriteTestDemo class SpriteBatchNodeOffsetAnchorSkewScale : public SpriteTestDemo
{ {
public: public:
SpriteBatchNodeOffsetAnchorSkewScale(); SpriteBatchNodeOffsetAnchorSkewScale();
~SpriteBatchNodeOffsetAnchorSkewScale(); ~SpriteBatchNodeOffsetAnchorSkewScale();
virtual std::string title(); virtual std::string title();
}; };
class SpriteOffsetAnchorFlip : public SpriteTestDemo class SpriteOffsetAnchorFlip : public SpriteTestDemo
{ {
public: public:
SpriteOffsetAnchorFlip(); SpriteOffsetAnchorFlip();
~SpriteOffsetAnchorFlip(); ~SpriteOffsetAnchorFlip();
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
}; };
class SpriteBatchNodeOffsetAnchorFlip : public SpriteTestDemo class SpriteBatchNodeOffsetAnchorFlip : public SpriteTestDemo
{ {
public: public:
SpriteBatchNodeOffsetAnchorFlip(); SpriteBatchNodeOffsetAnchorFlip();
~SpriteBatchNodeOffsetAnchorFlip(); ~SpriteBatchNodeOffsetAnchorFlip();
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
}; };
class SpriteAnimationSplit : public SpriteTestDemo class SpriteAnimationSplit : public SpriteTestDemo
{ {
public: public:
SpriteAnimationSplit(); SpriteAnimationSplit();
virtual void onExit(); virtual void onExit();
virtual std::string title(); virtual std::string title();
}; };
class SpriteHybrid: public SpriteTestDemo class SpriteHybrid: public SpriteTestDemo
{ {
bool m_usingSpriteBatchNode; bool m_usingSpriteBatchNode;
public: public:
SpriteHybrid(); SpriteHybrid();
void reparentSprite(ccTime dt); void reparentSprite(float dt);
virtual std::string title(); virtual std::string title();
virtual void onExit(); virtual void onExit();
}; };
class SpriteBatchNodeChildren: public SpriteTestDemo class SpriteBatchNodeChildren: public SpriteTestDemo
{ {
public: public:
SpriteBatchNodeChildren(); SpriteBatchNodeChildren();
virtual void onExit(); virtual void onExit();
virtual std::string title(); virtual std::string title();
};
class SpriteBatchNodeChildren2: public SpriteTestDemo
{
public:
SpriteBatchNodeChildren2();
virtual void onExit();
virtual std::string title();
}; };
class SpriteBatchNodeChildrenZ : public SpriteTestDemo class SpriteBatchNodeChildrenZ : public SpriteTestDemo
{ {
public: public:
SpriteBatchNodeChildrenZ(); SpriteBatchNodeChildrenZ();
virtual void onExit(); virtual void onExit();
virtual std::string title(); virtual std::string title();
}; };
class SpriteChildrenVisibility: public SpriteTestDemo class SpriteChildrenVisibility: public SpriteTestDemo
{ {
public: public:
SpriteChildrenVisibility(); SpriteChildrenVisibility();
virtual void onExit(); virtual void onExit();
virtual std::string title(); virtual std::string title();
}; };
class SpriteChildrenVisibilityIssue665 : public SpriteTestDemo class SpriteChildrenVisibilityIssue665 : public SpriteTestDemo
{ {
public: public:
SpriteChildrenVisibilityIssue665(); SpriteChildrenVisibilityIssue665();
~SpriteChildrenVisibilityIssue665(); ~SpriteChildrenVisibilityIssue665();
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
}; };
class SpriteChildrenAnchorPoint: public SpriteTestDemo class SpriteChildrenAnchorPoint: public SpriteTestDemo
{ {
public: public:
SpriteChildrenAnchorPoint(); SpriteChildrenAnchorPoint();
virtual void onExit(); virtual void onExit();
virtual std::string title(); virtual std::string title();
}; };
class SpriteBatchNodeChildrenAnchorPoint: public SpriteTestDemo class SpriteBatchNodeChildrenAnchorPoint: public SpriteTestDemo
{ {
public: public:
SpriteBatchNodeChildrenAnchorPoint(); SpriteBatchNodeChildrenAnchorPoint();
virtual void onExit(); virtual void onExit();
virtual std::string title(); virtual std::string title();
}; };
class SpriteBatchNodeChildrenScale: public SpriteTestDemo class SpriteBatchNodeChildrenScale: public SpriteTestDemo
{ {
public: public:
SpriteBatchNodeChildrenScale(); SpriteBatchNodeChildrenScale();
virtual std::string title(); virtual std::string title();
}; };
class SpriteChildrenChildren: public SpriteTestDemo class SpriteChildrenChildren: public SpriteTestDemo
{ {
public: public:
SpriteChildrenChildren(); SpriteChildrenChildren();
virtual std::string title(); virtual std::string title();
}; };
class SpriteBatchNodeChildrenChildren: public SpriteTestDemo class SpriteBatchNodeChildrenChildren: public SpriteTestDemo
{ {
public: public:
SpriteBatchNodeChildrenChildren(); SpriteBatchNodeChildrenChildren();
virtual std::string title(); virtual std::string title();
}; };
class SpriteNilTexture: public SpriteTestDemo class SpriteNilTexture: public SpriteTestDemo
{ {
public: public:
SpriteNilTexture(); SpriteNilTexture();
virtual std::string title(); virtual std::string title();
std::string subtitle(); std::string subtitle();
}; };
class SpriteSubclass : public SpriteTestDemo class SpriteSubclass : public SpriteTestDemo
{ {
public: public:
SpriteSubclass(); SpriteSubclass();
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
}; };
class AnimationCache : public SpriteTestDemo class AnimationCache : public SpriteTestDemo
{ {
public: public:
AnimationCache(); AnimationCache();
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
}; };
class NodeSort : public SpriteTestDemo
{
public:
NodeSort();
virtual std::string title();
virtual std::string subtitle();
void reorderSprite(float dt);
private:
CCNode *m_pNode;
CCSprite *m_pSprite1;
CCSprite *m_pSprite2;
CCSprite *m_pSprite3;
CCSprite *m_pSprite4;
CCSprite *m_pSprite5;
};
class SpriteBatchNodeReorderSameIndex : public SpriteTestDemo
{
public:
SpriteBatchNodeReorderSameIndex();
virtual std::string title();
virtual std::string subtitle();
void reorderSprite(float dt);
private:
CCSpriteBatchNode *m_pBatchNode;
CCSprite *m_pSprite1;
CCSprite *m_pSprite2;
CCSprite *m_pSprite3;
CCSprite *m_pSprite4;
CCSprite *m_pSprite5;
};
class SpriteBatchNodeReorderOneChild : public SpriteTestDemo
{
public:
SpriteBatchNodeReorderOneChild();
void reorderSprite(float dt);
virtual std::string title();
private:
CCSpriteBatchNode *m_pBatchNode;
CCSprite *m_pReorderSprite;
};
class SpriteBatchNodeSkewNegativeScaleChildren : public SpriteTestDemo
{
public:
SpriteBatchNodeSkewNegativeScaleChildren();
~SpriteBatchNodeSkewNegativeScaleChildren();
virtual std::string title();
virtual std::string subtitle();
};
class SpriteSkewNegativeScaleChildren : public SpriteTestDemo
{
public:
SpriteSkewNegativeScaleChildren();
~SpriteSkewNegativeScaleChildren();
virtual std::string title();
virtual std::string subtitle();
};
class SpriteDoubleResolution : public SpriteTestDemo
{
public:
SpriteDoubleResolution();
virtual std::string title();
virtual std::string subtitle();
};
class AnimationCacheFile : public SpriteTestDemo
{
public:
AnimationCacheFile();
virtual std::string title();
virtual std::string subtitle();
};
class SpriteBatchBug1217 : public SpriteTestDemo
{
public:
SpriteBatchBug1217();
virtual std::string title();
virtual std::string subtitle();
};
class SpriteTestScene : public TestScene class SpriteTestScene : public TestScene
{ {
public: public:
virtual void runThisTest(); virtual void runThisTest();
}; };
#endif #endif
 End of changes. 59 change blocks. 
161 lines changed or deleted 243 lines changed or added


 TGAlib.h   TGAlib.h 
skipping to change at line 28 skipping to change at line 28
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __SUPPORT_DATA_SUPPORT_TGALIB_H__ #ifndef __SUPPORT_DATA_SUPPORT_TGALIB_H__
#define __SUPPORT_DATA_SUPPORT_TGALIB_H__ #define __SUPPORT_DATA_SUPPORT_TGALIB_H__
namespace cocos2d { namespace cocos2d {
enum { enum {
TGA_OK, TGA_OK,
TGA_ERROR_FILE_OPEN, TGA_ERROR_FILE_OPEN,
TGA_ERROR_READING_FILE, TGA_ERROR_READING_FILE,
TGA_ERROR_INDEXED_COLOR, TGA_ERROR_INDEXED_COLOR,
TGA_ERROR_MEMORY, TGA_ERROR_MEMORY,
TGA_ERROR_COMPRESSED_FILE, TGA_ERROR_COMPRESSED_FILE,
}; };
/** TGA format */ /** TGA format */
typedef struct sImageTGA { typedef struct sImageTGA {
int status; int status;
unsigned char type, pixelDepth; unsigned char type, pixelDepth;
/** map width */ /** map width */
signed short width; signed short width;
/** map height */ /** map height */
signed short height; signed short height;
/** raw data */ /** raw data */
unsigned char *imageData; unsigned char *imageData;
int flipped; int flipped;
} tImageTGA; } tImageTGA;
/// load the image header fields. We only keep those that matter! /// load the image header fields. We only keep those that matter!
bool tgaLoadHeader(unsigned char *Buffer, unsigned long bufSize, tImageTGA *psInfo); bool tgaLoadHeader(unsigned char *Buffer, unsigned long bufSize, tImageTGA *psInfo);
/// loads the image pixels. You shouldn't call this function directly /// loads the image pixels. You shouldn't call this function directly
bool tgaLoadImageData(unsigned char *Buffer, unsigned long bufSize, tImageT GA *psInfo); bool tgaLoadImageData(unsigned char *Buffer, unsigned long bufSize, tImageT GA *psInfo);
/// this is the function to call when we want to load an image /// this is the function to call when we want to load an image
tImageTGA * tgaLoad(const char *pszFilename); tImageTGA * tgaLoad(const char *pszFilename);
// /converts RGB to greyscale // /converts RGB to greyscale
void tgaRGBtogreyscale(tImageTGA *psInfo); void tgaRGBtogreyscale(tImageTGA *psInfo);
/// releases the memory used for the image /// releases the memory used for the image
void tgaDestroy(tImageTGA *psInfo); void tgaDestroy(tImageTGA *psInfo);
}//namespace cocos2d
}//namespace cocos2d
#endif // __SUPPORT_DATA_SUPPORT_TGALIB_H__ #endif // __SUPPORT_DATA_SUPPORT_TGALIB_H__
 End of changes. 7 change blocks. 
17 lines changed or deleted 18 lines changed or added


 Test.h   Test.h 
skipping to change at line 32 skipping to change at line 32
#include <Box2D/Box2D.h> #include <Box2D/Box2D.h>
#include "GLES-Render.h" #include "GLES-Render.h"
#include <cstdlib> #include <cstdlib>
class Test; class Test;
struct Settings; struct Settings;
typedef Test* TestCreateFcn(); typedef Test* TestCreateFcn();
#define RAND_LIMIT 32767 #define RAND_LIMIT 32767
/// Random number in range [-1,1] /// Random number in range [-1,1]
inline float32 RandomFloat() inline float32 RandomFloat()
{ {
float32 r = (float32)(std::rand() & (RAND_LIMIT)); float32 r = (float32)(std::rand() & (RAND_LIMIT));
r /= RAND_LIMIT; r /= RAND_LIMIT;
r = 2.0f * r - 1.0f; r = 2.0f * r - 1.0f;
return r; return r;
} }
/// Random floating point number in range [lo, hi] /// Random floating point number in range [lo, hi]
inline float32 RandomFloat(float32 lo, float32 hi) inline float32 RandomFloat(float32 lo, float32 hi)
{ {
float32 r = (float32)(std::rand() & (RAND_LIMIT)); float32 r = (float32)(std::rand() & (RAND_LIMIT));
r /= RAND_LIMIT; r /= RAND_LIMIT;
r = (hi - lo) * r + lo; r = (hi - lo) * r + lo;
return r; return r;
} }
/// Test settings. Some can be controlled in the GUI. /// Test settings. Some can be controlled in the GUI.
struct Settings struct Settings
{ {
Settings() : Settings() :
viewCenter(0.0f, 20.0f), viewCenter(0.0f, 20.0f),
hz(60.0f), hz(60.0f),
velocityIterations(8), velocityIterations(8),
positionIterations(3), positionIterations(3),
drawShapes(1), drawShapes(1),
drawJoints(1), drawJoints(1),
drawAABBs(0), drawAABBs(0),
drawPairs(0), drawPairs(0),
drawContactPoints(0), drawContactPoints(0),
drawContactNormals(0), drawContactNormals(0),
drawContactForces(0), drawContactForces(0),
drawFrictionForces(0), drawFrictionForces(0),
drawCOMs(0), drawCOMs(0),
drawStats(0), drawStats(0),
drawProfile(0), drawProfile(0),
enableWarmStarting(1), enableWarmStarting(1),
enableContinuous(1), enableContinuous(1),
enableSubStepping(0), enableSubStepping(0),
pause(0), pause(0),
singleStep(0) singleStep(0)
{} {}
b2Vec2 viewCenter; b2Vec2 viewCenter;
float32 hz; float32 hz;
int32 velocityIterations; int32 velocityIterations;
int32 positionIterations; int32 positionIterations;
int32 drawShapes; int32 drawShapes;
int32 drawJoints; int32 drawJoints;
int32 drawAABBs; int32 drawAABBs;
int32 drawPairs; int32 drawPairs;
int32 drawContactPoints; int32 drawContactPoints;
int32 drawContactNormals; int32 drawContactNormals;
int32 drawContactForces; int32 drawContactForces;
int32 drawFrictionForces; int32 drawFrictionForces;
int32 drawCOMs; int32 drawCOMs;
int32 drawStats; int32 drawStats;
int32 drawProfile; int32 drawProfile;
int32 enableWarmStarting; int32 enableWarmStarting;
int32 enableContinuous; int32 enableContinuous;
int32 enableSubStepping; int32 enableSubStepping;
int32 pause; int32 pause;
int32 singleStep; int32 singleStep;
}; };
struct TestEntry struct TestEntry
{ {
const char *name; const char *name;
TestCreateFcn *createFcn; TestCreateFcn *createFcn;
}; };
extern TestEntry g_testEntries[]; extern TestEntry g_testEntries[];
// This is called when a joint in the world is implicitly destroyed // This is called when a joint in the world is implicitly destroyed
// because an attached body is destroyed. This gives us a chance to // because an attached body is destroyed. This gives us a chance to
// nullify the mouse joint. // nullify the mouse joint.
class DestructionListener : public b2DestructionListener class DestructionListener : public b2DestructionListener
{ {
public: public:
void SayGoodbye(b2Fixture* fixture) { B2_NOT_USED(fixture); } void SayGoodbye(b2Fixture* fixture) { B2_NOT_USED(fixture); }
void SayGoodbye(b2Joint* joint); void SayGoodbye(b2Joint* joint);
Test* test; Test* test;
}; };
const int32 k_maxContactPoints = 2048; const int32 k_maxContactPoints = 2048;
struct ContactPoint struct ContactPoint
{ {
b2Fixture* fixtureA; b2Fixture* fixtureA;
b2Fixture* fixtureB; b2Fixture* fixtureB;
b2Vec2 normal; b2Vec2 normal;
b2Vec2 position; b2Vec2 position;
b2PointState state; b2PointState state;
}; };
class Test : public b2ContactListener class Test : public b2ContactListener
{ {
public: public:
Test(); Test();
virtual ~Test(); virtual ~Test();
void SetTextLine(int32 line) { m_textLine = line; } void SetTextLine(int32 line) { m_textLine = line; }
void DrawTitle(int x, int y, const char *string); void DrawTitle(int x, int y, const char *string);
virtual void Step(Settings* settings); virtual void Step(Settings* settings);
virtual void Keyboard(unsigned char key) { B2_NOT_USED(key); } virtual void Keyboard(unsigned char key) { B2_NOT_USED(key); }
virtual void KeyboardUp(unsigned char key) { B2_NOT_USED(key); } virtual void KeyboardUp(unsigned char key) { B2_NOT_USED(key); }
void ShiftMouseDown(const b2Vec2& p); void ShiftMouseDown(const b2Vec2& p);
virtual bool MouseDown(const b2Vec2& p); virtual bool MouseDown(const b2Vec2& p);
virtual void MouseUp(const b2Vec2& p); virtual void MouseUp(const b2Vec2& p);
void MouseMove(const b2Vec2& p); void MouseMove(const b2Vec2& p);
void LaunchBomb(); void LaunchBomb();
void LaunchBomb(const b2Vec2& position, const b2Vec2& velocity); void LaunchBomb(const b2Vec2& position, const b2Vec2& velocity);
void SpawnBomb(const b2Vec2& worldPt); void SpawnBomb(const b2Vec2& worldPt);
void CompleteBombSpawn(const b2Vec2& p); void CompleteBombSpawn(const b2Vec2& p);
// Let derived tests know that a joint was destroyed. // Let derived tests know that a joint was destroyed.
virtual void JointDestroyed(b2Joint* joint) { B2_NOT_USED(joint); } virtual void JointDestroyed(b2Joint* joint) { B2_NOT_USED(joint); }
// Callbacks for derived classes. // Callbacks for derived classes.
virtual void BeginContact(b2Contact* contact) { B2_NOT_USED(contact) virtual void BeginContact(b2Contact* contact) { B2_NOT_USED(contact); }
; } virtual void EndContact(b2Contact* contact) { B2_NOT_USED(contact); }
virtual void EndContact(b2Contact* contact) { B2_NOT_USED(contact); virtual void PreSolve(b2Contact* contact, const b2Manifold* oldManifold
} );
virtual void PreSolve(b2Contact* contact, const b2Manifold* oldManif virtual void PostSolve(const b2Contact* contact, const b2ContactImpulse
old); * impulse)
virtual void PostSolve(const b2Contact* contact, const b2ContactImpu {
lse* impulse) B2_NOT_USED(contact);
{ B2_NOT_USED(impulse);
B2_NOT_USED(contact); }
B2_NOT_USED(impulse);
}
public: public:
friend class DestructionListener; friend class DestructionListener;
friend class BoundaryListener; friend class BoundaryListener;
friend class ContactListener; friend class ContactListener;
b2Body* m_groundBody; b2Body* m_groundBody;
b2AABB m_worldAABB; b2AABB m_worldAABB;
ContactPoint m_points[k_maxContactPoints]; ContactPoint m_points[k_maxContactPoints];
int32 m_pointCount; int32 m_pointCount;
DestructionListener m_destructionListener; DestructionListener m_destructionListener;
GLESDebugDraw m_debugDraw; GLESDebugDraw m_debugDraw;
int32 m_textLine; int32 m_textLine;
b2World* m_world; b2World* m_world;
b2Body* m_bomb; b2Body* m_bomb;
b2MouseJoint* m_mouseJoint; b2MouseJoint* m_mouseJoint;
b2Vec2 m_bombSpawnPoint; b2Vec2 m_bombSpawnPoint;
bool m_bombSpawning; bool m_bombSpawning;
b2Vec2 m_mouseWorld; b2Vec2 m_mouseWorld;
int32 m_stepCount; int32 m_stepCount;
b2Profile m_maxProfile; b2Profile m_maxProfile;
b2Profile m_totalProfile; b2Profile m_totalProfile;
}; };
#endif #endif
 End of changes. 13 change blocks. 
114 lines changed or deleted 112 lines changed or added


 TextInputTest.h   TextInputTest.h 
#ifndef __TEXT_INPUT_TEST_H__ #ifndef __TEXT_INPUT_TEST_H__
#define __TEXT_INPUT_TEST_H__ #define __TEXT_INPUT_TEST_H__
#include "../testBasic.h" #include "../testBasic.h"
class KeyboardNotificationLayer; class KeyboardNotificationLayer;
/** /**
@brief TextInputTest for retain prev, reset, next, main menu buttons. @brief TextInputTest for retain prev, reset, next, main menu buttons.
*/ */
class TextInputTest : public CCLayer class TextInputTest : public CCLayer
{ {
KeyboardNotificationLayer * m_pNotificationLayer; KeyboardNotificationLayer * m_pNotificationLayer;
public: public:
TextInputTest(); TextInputTest();
void restartCallback(CCObject* pSender); void restartCallback(CCObject* pSender);
void nextCallback(CCObject* pSender); void nextCallback(CCObject* pSender);
void backCallback(CCObject* pSender); void backCallback(CCObject* pSender);
skipping to change at line 102 skipping to change at line 102
virtual bool onTextFieldDeleteBackward(CCTextFieldTTF * pSender, const char * delText, int nLen); virtual bool onTextFieldDeleteBackward(CCTextFieldTTF * pSender, const char * delText, int nLen);
virtual bool onDraw(CCTextFieldTTF * pSender); virtual bool onDraw(CCTextFieldTTF * pSender);
}; };
class TextInputTestScene : public TestScene class TextInputTestScene : public TestScene
{ {
public: public:
virtual void runThisTest(); virtual void runThisTest();
}; };
#endif // __TEXT_INPUT_TEST_H__ #endif // __TEXT_INPUT_TEST_H__
 End of changes. 2 change blocks. 
1 lines changed or deleted 1 lines changed or added


 Texture2dTest.h   Texture2dTest.h 
skipping to change at line 19 skipping to change at line 19
virtual ~TextureDemo(); virtual ~TextureDemo();
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
virtual void onEnter(); virtual void onEnter();
void restartCallback(CCObject* pSender); void restartCallback(CCObject* pSender);
void nextCallback(CCObject* pSender); void nextCallback(CCObject* pSender);
void backCallback(CCObject* pSender); void backCallback(CCObject* pSender);
}; };
class TextureTIFF : public TextureDemo
{
public:
virtual std::string title();
virtual void onEnter();
};
class TexturePNG : public TextureDemo class TexturePNG : public TextureDemo
{ {
public: public:
virtual std::string title(); virtual std::string title();
virtual void onEnter(); virtual void onEnter();
}; };
class TextureJPEG : public TextureDemo class TextureJPEG : public TextureDemo
{ {
public: public:
skipping to change at line 122 skipping to change at line 129
}; };
class TexturePVRRGB565 : public TextureDemo class TexturePVRRGB565 : public TextureDemo
{ {
public: public:
virtual std::string title(); virtual std::string title();
virtual void onEnter(); virtual void onEnter();
}; };
class TexturePVRRGB888 : public TextureDemo
{
public:
virtual std::string title();
virtual void onEnter();
};
class TexturePVRA8 : public TextureDemo class TexturePVRA8 : public TextureDemo
{ {
public: public:
virtual std::string title(); virtual std::string title();
virtual void onEnter(); virtual void onEnter();
}; };
class TexturePVRI8 : public TextureDemo class TexturePVRI8 : public TextureDemo
{ {
skipping to change at line 194 skipping to change at line 208
}; };
class TexturePVRNPOT8888 : public TextureDemo class TexturePVRNPOT8888 : public TextureDemo
{ {
public: public:
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
virtual void onEnter(); virtual void onEnter();
}; };
class TexturePVRRaw : public TextureDemo class TextureAlias : public TextureDemo
{ {
public: public:
virtual std::string title(); virtual std::string title();
virtual std::string subtitle();
virtual void onEnter(); virtual void onEnter();
}; };
class TextureAlias : public TextureDemo class TexturePixelFormat : public TextureDemo
{ {
public: public:
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
virtual void onEnter(); virtual void onEnter();
}; };
class TexturePixelFormat : public TextureDemo class TextureBlend : public TextureDemo
{ {
public: public:
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
virtual void onEnter(); virtual void onEnter();
}; };
class TextureBlend : public TextureDemo class TextureAsync : public TextureDemo
{ {
public: public:
virtual ~TextureAsync();
void loadImages(float dt);
void imageLoaded(CCObject* pObj);
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
virtual void onEnter(); virtual void onEnter();
private:
int m_nImageOffset;
}; };
class TextureGlRepeat : public TextureDemo class TextureGlRepeat : public TextureDemo
{ {
public: public:
virtual ~TextureGlRepeat(); virtual ~TextureGlRepeat();
virtual std::string title(); virtual std::string title();
virtual void onEnter(); virtual void onEnter();
}; };
skipping to change at line 260 skipping to change at line 279
}; };
class TextureCache1 : public TextureDemo class TextureCache1 : public TextureDemo
{ {
public: public:
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
virtual void onEnter(); virtual void onEnter();
}; };
class TextureDrawAtPoint : public TextureDemo
{
public:
~TextureDrawAtPoint();
virtual std::string title();
virtual std::string subtitle();
virtual void onEnter();
virtual void draw();
private:
CCTexture2D* m_pTex1, *m_pTex2;
};
class TextureDrawInRect : public TextureDemo
{
public:
~TextureDrawInRect();
virtual std::string title();
virtual std::string subtitle();
virtual void onEnter();
virtual void draw();
private:
CCTexture2D* m_pTex1, *m_pTex2;
};
class TextureTestScene : public TestScene class TextureTestScene : public TestScene
{ {
public: public:
virtual void runThisTest(); virtual void runThisTest();
}; };
class TextureMemoryAlloc : public TextureDemo
{
public:
virtual void onEnter();
virtual std::string title();
virtual std::string subtitle();
void updateImage(CCObject *sender);
void changeBackgroundVisible(CCObject *sender);
private:
CCSprite *m_pBackground;
};
#endif // __TEXTURE2D_TEST_H__ #endif // __TEXTURE2D_TEST_H__
 End of changes. 11 change blocks. 
5 lines changed or deleted 60 lines changed or added


 TextureCacheTest.h   TextureCacheTest.h 
#ifndef _TEXTURECACHE_TEST_H_ #ifndef _TEXTURECACHE_TEST_H_
#define _TEXTURECACHE_TEST_H_ #define _TEXTURECACHE_TEST_H_
#include "cocos2d.h" #include "cocos2d.h"
#include "../testBasic.h" #include "../testBasic.h"
#include "platform/platform.h" #include "platform/platform.h"
class TextureCacheTest : public CCLayer class TextureCacheTest : public CCLayer
{ {
public: public:
TextureCacheTest(); TextureCacheTest();
void addSprite(); void addSprite();
void loadingCallBack(cocos2d::CCObject *obj); void loadingCallBack(cocos2d::CCObject *obj);
private: private:
cocos2d::CCLabelTTF *m_pLabelLoading; cocos2d::CCLabelTTF *m_pLabelLoading;
cocos2d::CCLabelTTF *m_pLabelPercent; cocos2d::CCLabelTTF *m_pLabelPercent;
int m_nNumberOfSprites; int m_nNumberOfSprites;
int m_nNumberOfLoadedSprites; int m_nNumberOfLoadedSprites;
}; };
class TextureCacheTestScene : public TestScene class TextureCacheTestScene : public TestScene
{ {
public: public:
virtual void runThisTest(); virtual void runThisTest();
}; };
#endif // _TEXTURECACHE_TEST_H_ #endif // _TEXTURECACHE_TEST_H_
 End of changes. 2 change blocks. 
7 lines changed or deleted 7 lines changed or added


 TheoJansen.h   TheoJansen.h 
skipping to change at line 29 skipping to change at line 29
// Inspired by a contribution by roman_m // Inspired by a contribution by roman_m
// Dimensions scooped from APE (http://www.cove.org/ape/index.htm) // Dimensions scooped from APE (http://www.cove.org/ape/index.htm)
#ifndef THEO_JANSEN_H #ifndef THEO_JANSEN_H
#define THEO_JANSEN_H #define THEO_JANSEN_H
class TheoJansen : public Test class TheoJansen : public Test
{ {
public: public:
void CreateLeg(float32 s, const b2Vec2& wheelAnchor) void CreateLeg(float32 s, const b2Vec2& wheelAnchor)
{ {
b2Vec2 p1(5.4f * s, -6.1f); b2Vec2 p1(5.4f * s, -6.1f);
b2Vec2 p2(7.2f * s, -1.2f); b2Vec2 p2(7.2f * s, -1.2f);
b2Vec2 p3(4.3f * s, -1.9f); b2Vec2 p3(4.3f * s, -1.9f);
b2Vec2 p4(3.1f * s, 0.8f); b2Vec2 p4(3.1f * s, 0.8f);
b2Vec2 p5(6.0f * s, 1.5f); b2Vec2 p5(6.0f * s, 1.5f);
b2Vec2 p6(2.5f * s, 3.7f); b2Vec2 p6(2.5f * s, 3.7f);
b2FixtureDef fd1, fd2; b2FixtureDef fd1, fd2;
fd1.filter.groupIndex = -1; fd1.filter.groupIndex = -1;
fd2.filter.groupIndex = -1; fd2.filter.groupIndex = -1;
fd1.density = 1.0f; fd1.density = 1.0f;
fd2.density = 1.0f; fd2.density = 1.0f;
b2PolygonShape poly1, poly2; b2PolygonShape poly1, poly2;
if (s > 0.0f) if (s > 0.0f)
{ {
b2Vec2 vertices[3]; b2Vec2 vertices[3];
vertices[0] = p1; vertices[0] = p1;
vertices[1] = p2; vertices[1] = p2;
vertices[2] = p3; vertices[2] = p3;
poly1.Set(vertices, 3); poly1.Set(vertices, 3);
vertices[0] = b2Vec2_zero; vertices[0] = b2Vec2_zero;
vertices[1] = p5 - p4; vertices[1] = p5 - p4;
vertices[2] = p6 - p4; vertices[2] = p6 - p4;
poly2.Set(vertices, 3); poly2.Set(vertices, 3);
} }
else else
{ {
b2Vec2 vertices[3]; b2Vec2 vertices[3];
vertices[0] = p1; vertices[0] = p1;
vertices[1] = p3; vertices[1] = p3;
vertices[2] = p2; vertices[2] = p2;
poly1.Set(vertices, 3); poly1.Set(vertices, 3);
vertices[0] = b2Vec2_zero; vertices[0] = b2Vec2_zero;
vertices[1] = p6 - p4; vertices[1] = p6 - p4;
vertices[2] = p5 - p4; vertices[2] = p5 - p4;
poly2.Set(vertices, 3); poly2.Set(vertices, 3);
} }
fd1.shape = &poly1; fd1.shape = &poly1;
fd2.shape = &poly2; fd2.shape = &poly2;
b2BodyDef bd1, bd2; b2BodyDef bd1, bd2;
bd1.type = b2_dynamicBody; bd1.type = b2_dynamicBody;
bd2.type = b2_dynamicBody; bd2.type = b2_dynamicBody;
bd1.position = m_offset; bd1.position = m_offset;
bd2.position = p4 + m_offset; bd2.position = p4 + m_offset;
bd1.angularDamping = 10.0f; bd1.angularDamping = 10.0f;
bd2.angularDamping = 10.0f; bd2.angularDamping = 10.0f;
b2Body* body1 = m_world->CreateBody(&bd1); b2Body* body1 = m_world->CreateBody(&bd1);
b2Body* body2 = m_world->CreateBody(&bd2); b2Body* body2 = m_world->CreateBody(&bd2);
body1->CreateFixture(&fd1); body1->CreateFixture(&fd1);
body2->CreateFixture(&fd2); body2->CreateFixture(&fd2);
b2DistanceJointDef djd; b2DistanceJointDef djd;
// Using a soft distance constraint can reduce some jitter. // Using a soft distance constraint can reduce some jitter.
// It also makes the structure seem a bit more fluid by // It also makes the structure seem a bit more fluid by
// acting like a suspension system. // acting like a suspension system.
djd.dampingRatio = 0.5f; djd.dampingRatio = 0.5f;
djd.frequencyHz = 10.0f; djd.frequencyHz = 10.0f;
djd.Initialize(body1, body2, p2 + m_offset, p5 + m_offset); djd.Initialize(body1, body2, p2 + m_offset, p5 + m_offset);
m_world->CreateJoint(&djd); m_world->CreateJoint(&djd);
djd.Initialize(body1, body2, p3 + m_offset, p4 + m_offset); djd.Initialize(body1, body2, p3 + m_offset, p4 + m_offset);
m_world->CreateJoint(&djd); m_world->CreateJoint(&djd);
djd.Initialize(body1, m_wheel, p3 + m_offset, wheelAnchor + djd.Initialize(body1, m_wheel, p3 + m_offset, wheelAnchor + m_offse
m_offset); t);
m_world->CreateJoint(&djd); m_world->CreateJoint(&djd);
djd.Initialize(body2, m_wheel, p6 + m_offset, wheelAnchor + djd.Initialize(body2, m_wheel, p6 + m_offset, wheelAnchor + m_offse
m_offset); t);
m_world->CreateJoint(&djd); m_world->CreateJoint(&djd);
b2RevoluteJointDef rjd; b2RevoluteJointDef rjd;
rjd.Initialize(body2, m_chassis, p4 + m_offset); rjd.Initialize(body2, m_chassis, p4 + m_offset);
m_world->CreateJoint(&rjd); m_world->CreateJoint(&rjd);
} }
TheoJansen() TheoJansen()
{ {
m_offset.Set(0.0f, 8.0f); m_offset.Set(0.0f, 8.0f);
m_motorSpeed = 2.0f; m_motorSpeed = 2.0f;
m_motorOn = true; m_motorOn = true;
b2Vec2 pivot(0.0f, 0.8f); b2Vec2 pivot(0.0f, 0.8f);
// Ground // Ground
{ {
b2BodyDef bd; b2BodyDef bd;
b2Body* ground = m_world->CreateBody(&bd); b2Body* ground = m_world->CreateBody(&bd);
b2EdgeShape shape; b2EdgeShape shape;
shape.Set(b2Vec2(-50.0f, 0.0f), b2Vec2(50.0f, 0.0f)) shape.Set(b2Vec2(-50.0f, 0.0f), b2Vec2(50.0f, 0.0f));
; ground->CreateFixture(&shape, 0.0f);
ground->CreateFixture(&shape, 0.0f);
shape.Set(b2Vec2(-50.0f, 0.0f), b2Vec2(-50.0f, 10.0f));
shape.Set(b2Vec2(-50.0f, 0.0f), b2Vec2(-50.0f, 10.0f ground->CreateFixture(&shape, 0.0f);
));
ground->CreateFixture(&shape, 0.0f); shape.Set(b2Vec2(50.0f, 0.0f), b2Vec2(50.0f, 10.0f));
ground->CreateFixture(&shape, 0.0f);
shape.Set(b2Vec2(50.0f, 0.0f), b2Vec2(50.0f, 10.0f)) }
;
ground->CreateFixture(&shape, 0.0f); // Balls
} for (int32 i = 0; i < 40; ++i)
{
// Balls b2CircleShape shape;
for (int32 i = 0; i < 40; ++i) shape.m_radius = 0.25f;
{
b2CircleShape shape; b2BodyDef bd;
shape.m_radius = 0.25f; bd.type = b2_dynamicBody;
bd.position.Set(-40.0f + 2.0f * i, 0.5f);
b2BodyDef bd;
bd.type = b2_dynamicBody; b2Body* body = m_world->CreateBody(&bd);
bd.position.Set(-40.0f + 2.0f * i, 0.5f); body->CreateFixture(&shape, 1.0f);
}
b2Body* body = m_world->CreateBody(&bd);
body->CreateFixture(&shape, 1.0f); // Chassis
} {
b2PolygonShape shape;
// Chassis shape.SetAsBox(2.5f, 1.0f);
{
b2PolygonShape shape; b2FixtureDef sd;
shape.SetAsBox(2.5f, 1.0f); sd.density = 1.0f;
sd.shape = &shape;
b2FixtureDef sd; sd.filter.groupIndex = -1;
sd.density = 1.0f; b2BodyDef bd;
sd.shape = &shape; bd.type = b2_dynamicBody;
sd.filter.groupIndex = -1; bd.position = pivot + m_offset;
b2BodyDef bd; m_chassis = m_world->CreateBody(&bd);
bd.type = b2_dynamicBody; m_chassis->CreateFixture(&sd);
bd.position = pivot + m_offset; }
m_chassis = m_world->CreateBody(&bd);
m_chassis->CreateFixture(&sd); {
} b2CircleShape shape;
shape.m_radius = 1.6f;
{
b2CircleShape shape; b2FixtureDef sd;
shape.m_radius = 1.6f; sd.density = 1.0f;
sd.shape = &shape;
b2FixtureDef sd; sd.filter.groupIndex = -1;
sd.density = 1.0f; b2BodyDef bd;
sd.shape = &shape; bd.type = b2_dynamicBody;
sd.filter.groupIndex = -1; bd.position = pivot + m_offset;
b2BodyDef bd; m_wheel = m_world->CreateBody(&bd);
bd.type = b2_dynamicBody; m_wheel->CreateFixture(&sd);
bd.position = pivot + m_offset; }
m_wheel = m_world->CreateBody(&bd);
m_wheel->CreateFixture(&sd); {
} b2RevoluteJointDef jd;
jd.Initialize(m_wheel, m_chassis, pivot + m_offset);
{ jd.collideConnected = false;
b2RevoluteJointDef jd; jd.motorSpeed = m_motorSpeed;
jd.Initialize(m_wheel, m_chassis, pivot + m_offset); jd.maxMotorTorque = 400.0f;
jd.collideConnected = false; jd.enableMotor = m_motorOn;
jd.motorSpeed = m_motorSpeed; m_motorJoint = (b2RevoluteJoint*)m_world->CreateJoint(&jd);
jd.maxMotorTorque = 400.0f; }
jd.enableMotor = m_motorOn;
m_motorJoint = (b2RevoluteJoint*)m_world->CreateJoin b2Vec2 wheelAnchor;
t(&jd);
} wheelAnchor = pivot + b2Vec2(0.0f, -0.8f);
b2Vec2 wheelAnchor; CreateLeg(-1.0f, wheelAnchor);
CreateLeg(1.0f, wheelAnchor);
wheelAnchor = pivot + b2Vec2(0.0f, -0.8f);
m_wheel->SetTransform(m_wheel->GetPosition(), 120.0f * b2_pi / 180.
CreateLeg(-1.0f, wheelAnchor); 0f);
CreateLeg(1.0f, wheelAnchor); CreateLeg(-1.0f, wheelAnchor);
CreateLeg(1.0f, wheelAnchor);
m_wheel->SetTransform(m_wheel->GetPosition(), 120.0f * b2_pi
/ 180.0f); m_wheel->SetTransform(m_wheel->GetPosition(), -120.0f * b2_pi / 180
CreateLeg(-1.0f, wheelAnchor); .0f);
CreateLeg(1.0f, wheelAnchor); CreateLeg(-1.0f, wheelAnchor);
CreateLeg(1.0f, wheelAnchor);
m_wheel->SetTransform(m_wheel->GetPosition(), -120.0f * b2_p }
i / 180.0f);
CreateLeg(-1.0f, wheelAnchor); void Step(Settings* settings)
CreateLeg(1.0f, wheelAnchor); {
} m_debugDraw.DrawString(5, m_textLine, "Keys: left = a, brake = s, r
ight = d, toggle motor = m");
void Step(Settings* settings) m_textLine += 15;
{
m_debugDraw.DrawString(5, m_textLine, "Keys: left = a, brake Test::Step(settings);
= s, right = d, toggle motor = m"); }
m_textLine += 15;
void Keyboard(unsigned char key)
Test::Step(settings); {
} switch (key)
{
void Keyboard(unsigned char key) case 'a':
{ m_motorJoint->SetMotorSpeed(-m_motorSpeed);
switch (key) break;
{
case 'a': case 's':
m_motorJoint->SetMotorSpeed(-m_motorSpeed); m_motorJoint->SetMotorSpeed(0.0f);
break; break;
case 's': case 'd':
m_motorJoint->SetMotorSpeed(0.0f); m_motorJoint->SetMotorSpeed(m_motorSpeed);
break; break;
case 'd': case 'm':
m_motorJoint->SetMotorSpeed(m_motorSpeed); m_motorJoint->EnableMotor(!m_motorJoint->IsMotorEnabled());
break; break;
}
case 'm': }
m_motorJoint->EnableMotor(!m_motorJoint->IsMotorEnab
led()); static Test* Create()
break; {
} return new TheoJansen;
} }
static Test* Create() b2Vec2 m_offset;
{ b2Body* m_chassis;
return new TheoJansen; b2Body* m_wheel;
} b2RevoluteJoint* m_motorJoint;
bool m_motorOn;
b2Vec2 m_offset; float32 m_motorSpeed;
b2Body* m_chassis;
b2Body* m_wheel;
b2RevoluteJoint* m_motorJoint;
bool m_motorOn;
float32 m_motorSpeed;
}; };
#endif // THEO_JANSEN_H #endif // THEO_JANSEN_H
 End of changes. 1 change blocks. 
235 lines changed or deleted 230 lines changed or added


 TileMapTest.h   TileMapTest.h 
#ifndef _TILEMAP_TEST_H_ #ifndef _TILEMAP_TEST_H_
#define _TILEMAP_TEST_H_ #define _TILEMAP_TEST_H_
#include "../testBasic.h" #include "../testBasic.h"
class TileDemo : public CCLayer class TileDemo : public CCLayer
{ {
protected: protected:
CCLabelTTF* m_label; CCLabelTTF* m_label;
CCLabelTTF* m_subtitle; CCLabelTTF* m_subtitle;
public: public:
TileDemo(void); TileDemo(void);
virtual ~TileDemo(void); virtual ~TileDemo(void);
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
virtual void onEnter(); virtual void onEnter();
void restartCallback(CCObject* pSender); void restartCallback(CCObject* pSender);
void nextCallback(CCObject* pSender); void nextCallback(CCObject* pSender);
void backCallback(CCObject* pSender); void backCallback(CCObject* pSender);
void registerWithTouchDispatcher(); void registerWithTouchDispatcher();
bool ccTouchBegan(CCTouch* touch, CCEvent* event); bool ccTouchBegan(CCTouch* touch, CCEvent* event);
void ccTouchEnded(CCTouch* touch, CCEvent* event); void ccTouchEnded(CCTouch* touch, CCEvent* event);
void ccTouchCancelled(CCTouch* touch, CCEvent* event); void ccTouchCancelled(CCTouch* touch, CCEvent* event);
void ccTouchMoved(CCTouch* touch, CCEvent* event); void ccTouchMoved(CCTouch* touch, CCEvent* event);
}; };
class TileMapTest : public TileDemo class TileMapTest : public TileDemo
{ {
public: public:
TileMapTest(void); TileMapTest(void);
virtual std::string title(); virtual std::string title();
}; };
class TileMapEditTest : public TileDemo class TileMapEditTest : public TileDemo
{ {
public: public:
TileMapEditTest (void); TileMapEditTest (void);
virtual std::string title(); virtual std::string title();
void updateMap(ccTime dt); void updateMap(float dt);
}; };
class TMXOrthoTest : public TileDemo class TMXOrthoTest : public TileDemo
{ {
public: public:
TMXOrthoTest(void); TMXOrthoTest(void);
virtual std::string title(); virtual std::string title();
virtual void onEnter(); virtual void onEnter();
virtual void onExit(); virtual void onExit();
}; };
class TMXOrthoTest2 : public TileDemo class TMXOrthoTest2 : public TileDemo
{ {
public: public:
TMXOrthoTest2(void); TMXOrthoTest2(void);
virtual std::string title(); virtual std::string title();
}; };
class TMXOrthoTest3 : public TileDemo class TMXOrthoTest3 : public TileDemo
{ {
public: public:
TMXOrthoTest3(void); TMXOrthoTest3(void);
virtual std::string title(); virtual std::string title();
}; };
class TMXOrthoTest4 : public TileDemo class TMXOrthoTest4 : public TileDemo
{ {
public: public:
TMXOrthoTest4(void); TMXOrthoTest4(void);
void removeSprite(ccTime dt); void removeSprite(float dt);
virtual std::string title(); virtual std::string title();
}; };
class TMXReadWriteTest : public TileDemo class TMXReadWriteTest : public TileDemo
{ {
unsigned int m_gid; unsigned int m_gid;
unsigned int m_gid2; unsigned int m_gid2;
public: public:
TMXReadWriteTest(void); TMXReadWriteTest(void);
virtual std::string title(); virtual std::string title();
void removeSprite(CCNode* sender); void removeSprite(CCNode* sender);
void updateCol(ccTime dt); void updateCol(float dt);
void repaintWithGID(ccTime dt); void repaintWithGID(float dt);
void removeTiles(ccTime dt); void removeTiles(float dt);
}; };
class TMXHexTest : public TileDemo class TMXHexTest : public TileDemo
{ {
public: public:
TMXHexTest(void); TMXHexTest(void);
virtual std::string title(); virtual std::string title();
}; };
class TMXIsoTest : public TileDemo class TMXIsoTest : public TileDemo
{ {
public: public:
TMXIsoTest(void); TMXIsoTest(void);
virtual std::string title(); virtual std::string title();
}; };
class TMXIsoTest1 : public TileDemo class TMXIsoTest1 : public TileDemo
{ {
public: public:
TMXIsoTest1(void); TMXIsoTest1(void);
virtual std::string title(); virtual std::string title();
}; };
class TMXIsoTest2 : public TileDemo class TMXIsoTest2 : public TileDemo
{ {
public: public:
TMXIsoTest2(void); TMXIsoTest2(void);
virtual std::string title(); virtual std::string title();
}; };
class TMXUncompressedTest : public TileDemo class TMXUncompressedTest : public TileDemo
{ {
public: public:
TMXUncompressedTest(void); TMXUncompressedTest(void);
virtual std::string title(); virtual std::string title();
}; };
class TMXTilesetTest : public TileDemo class TMXTilesetTest : public TileDemo
{ {
public: public:
TMXTilesetTest(void); TMXTilesetTest(void);
virtual std::string title(); virtual std::string title();
}; };
class TMXOrthoObjectsTest : public TileDemo class TMXOrthoObjectsTest : public TileDemo
{ {
public: public:
TMXOrthoObjectsTest(void); TMXOrthoObjectsTest(void);
virtual std::string title(); virtual std::string title();
virtual void draw(); virtual void draw();
virtual std::string subtitle(); virtual std::string subtitle();
}; };
class TMXIsoObjectsTest : public TileDemo class TMXIsoObjectsTest : public TileDemo
{ {
public: public:
TMXIsoObjectsTest(void); TMXIsoObjectsTest(void);
virtual std::string title(); virtual std::string title();
virtual void draw(); virtual void draw();
virtual std::string subtitle(); virtual std::string subtitle();
}; };
class TMXResizeTest : public TileDemo class TMXResizeTest : public TileDemo
{ {
public: public:
TMXResizeTest(void); TMXResizeTest(void);
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
}; };
class TMXIsoZorder : public TileDemo class TMXIsoZorder : public TileDemo
{ {
CCSprite* m_tamara; CCSprite* m_tamara;
public: public:
TMXIsoZorder(void); TMXIsoZorder(void);
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
virtual void onExit(void); virtual void onExit(void);
~TMXIsoZorder(); ~TMXIsoZorder();
void repositionSprite(ccTime dt); void repositionSprite(float dt);
}; };
class TMXOrthoZorder : public TileDemo class TMXOrthoZorder : public TileDemo
{ {
CCSprite* m_tamara; CCSprite* m_tamara;
public: public:
TMXOrthoZorder(void); TMXOrthoZorder(void);
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
virtual ~TMXOrthoZorder(); virtual ~TMXOrthoZorder();
void repositionSprite(ccTime dt); void repositionSprite(float dt);
}; };
class TMXIsoVertexZ : public TileDemo class TMXIsoVertexZ : public TileDemo
{ {
CCSprite* m_tamara; CCSprite* m_tamara;
public: public:
TMXIsoVertexZ(void); TMXIsoVertexZ(void);
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
~TMXIsoVertexZ(); ~TMXIsoVertexZ();
void repositionSprite(ccTime dt); void repositionSprite(float dt);
virtual void onEnter(); virtual void onEnter();
virtual void onExit(); virtual void onExit();
}; };
class TMXOrthoVertexZ : public TileDemo class TMXOrthoVertexZ : public TileDemo
{ {
CCSprite* m_tamara; CCSprite* m_tamara;
public: public:
TMXOrthoVertexZ(void); TMXOrthoVertexZ(void);
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
~TMXOrthoVertexZ(); ~TMXOrthoVertexZ();
void repositionSprite(ccTime dt); void repositionSprite(float dt);
virtual void onEnter(); virtual void onEnter();
virtual void onExit(); virtual void onExit();
}; };
class TMXIsoMoveLayer : public TileDemo class TMXIsoMoveLayer : public TileDemo
{ {
public: public:
TMXIsoMoveLayer(void); TMXIsoMoveLayer(void);
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
}; };
class TMXOrthoMoveLayer : public TileDemo class TMXOrthoMoveLayer : public TileDemo
{ {
public: public:
TMXOrthoMoveLayer(void); TMXOrthoMoveLayer(void);
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
};
class TMXTilePropertyTest : public TileDemo
{
public:
TMXTilePropertyTest();
virtual std::string title();
virtual std::string subtitle();
};
class TMXOrthoFlipTest : public TileDemo
{
public:
TMXOrthoFlipTest();
virtual std::string title();
};
class TMXOrthoFlipRunTimeTest : public TileDemo
{
public:
TMXOrthoFlipRunTimeTest();
virtual std::string title();
virtual std::string subtitle();
void flipIt(float dt);
};
class TMXOrthoFromXMLTest : public TileDemo
{
public:
TMXOrthoFromXMLTest();
virtual std::string title();
}; };
class TMXBug987 : public TileDemo class TMXBug987 : public TileDemo
{ {
public: public:
TMXBug987(); TMXBug987();
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
}; };
skipping to change at line 252 skipping to change at line 283
{ {
public: public:
TMXBug787(); TMXBug787();
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
}; };
class TMXGIDObjectsTest : public TileDemo class TMXGIDObjectsTest : public TileDemo
{ {
public: public:
TMXGIDObjectsTest(); TMXGIDObjectsTest();
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
virtual void draw(); virtual void draw();
}; };
class TileMapTestScene : public TestScene class TileMapTestScene : public TestScene
{ {
public: public:
virtual void runThisTest(); virtual void runThisTest();
}; };
#endif #endif
 End of changes. 39 change blocks. 
105 lines changed or deleted 136 lines changed or added


 Tiles.h   Tiles.h 
skipping to change at line 27 skipping to change at line 27
*/ */
#ifndef TILES_H #ifndef TILES_H
#define TILES_H #define TILES_H
/// This stress tests the dynamic tree broad-phase. This also shows that ti le /// This stress tests the dynamic tree broad-phase. This also shows that ti le
/// based collision is _not_ smooth due to Box2D not knowing about adjacenc y. /// based collision is _not_ smooth due to Box2D not knowing about adjacenc y.
class Tiles : public Test class Tiles : public Test
{ {
public: public:
enum enum
{ {
e_count = 20 e_count = 20
}; };
Tiles() Tiles()
{ {
m_fixtureCount = 0; m_fixtureCount = 0;
b2Timer timer; b2Timer timer;
{ {
float32 a = 0.5f; float32 a = 0.5f;
b2BodyDef bd; b2BodyDef bd;
bd.position.y = -a; bd.position.y = -a;
b2Body* ground = m_world->CreateBody(&bd); b2Body* ground = m_world->CreateBody(&bd);
#if 1 #if 1
int32 N = 200; int32 N = 200;
int32 M = 10; int32 M = 10;
b2Vec2 position; b2Vec2 position;
position.y = 0.0f; position.y = 0.0f;
for (int32 j = 0; j < M; ++j) for (int32 j = 0; j < M; ++j)
{ {
position.x = -N * a; position.x = -N * a;
for (int32 i = 0; i < N; ++i) for (int32 i = 0; i < N; ++i)
{ {
b2PolygonShape shape; b2PolygonShape shape;
shape.SetAsBox(a, a, position, 0.0f) shape.SetAsBox(a, a, position, 0.0f);
; ground->CreateFixture(&shape, 0.0f);
ground->CreateFixture(&shape, 0.0f); ++m_fixtureCount;
++m_fixtureCount; position.x += 2.0f * a;
position.x += 2.0f * a; }
} position.y -= 2.0f * a;
position.y -= 2.0f * a; }
}
#else #else
int32 N = 200; int32 N = 200;
int32 M = 10; int32 M = 10;
b2Vec2 position; b2Vec2 position;
position.x = -N * a; position.x = -N * a;
for (int32 i = 0; i < N; ++i) for (int32 i = 0; i < N; ++i)
{ {
position.y = 0.0f; position.y = 0.0f;
for (int32 j = 0; j < M; ++j) for (int32 j = 0; j < M; ++j)
{ {
b2PolygonShape shape; b2PolygonShape shape;
shape.SetAsBox(a, a, position, 0.0f) shape.SetAsBox(a, a, position, 0.0f);
; ground->CreateFixture(&shape, 0.0f);
ground->CreateFixture(&shape, 0.0f); position.y -= 2.0f * a;
position.y -= 2.0f * a; }
} position.x += 2.0f * a;
position.x += 2.0f * a; }
}
#endif #endif
} }
{ {
float32 a = 0.5f; float32 a = 0.5f;
b2PolygonShape shape; b2PolygonShape shape;
shape.SetAsBox(a, a); shape.SetAsBox(a, a);
b2Vec2 x(-7.0f, 0.75f); b2Vec2 x(-7.0f, 0.75f);
b2Vec2 y; b2Vec2 y;
b2Vec2 deltaX(0.5625f, 1.25f); b2Vec2 deltaX(0.5625f, 1.25f);
b2Vec2 deltaY(1.125f, 0.0f); b2Vec2 deltaY(1.125f, 0.0f);
for (int32 i = 0; i < e_count; ++i) for (int32 i = 0; i < e_count; ++i)
{ {
y = x; y = x;
for (int32 j = i; j < e_count; ++j) for (int32 j = i; j < e_count; ++j)
{ {
b2BodyDef bd; b2BodyDef bd;
bd.type = b2_dynamicBody; bd.type = b2_dynamicBody;
bd.position = y; bd.position = y;
//if (i == 0 && j == 0) //if (i == 0 && j == 0)
//{ //{
// bd.allowSleep = false; // bd.allowSleep = false;
//} //}
//else //else
//{ //{
// bd.allowSleep = true; // bd.allowSleep = true;
//} //}
b2Body* body = m_world->CreateBody(& b2Body* body = m_world->CreateBody(&bd);
bd); body->CreateFixture(&shape, 5.0f);
body->CreateFixture(&shape, 5.0f); ++m_fixtureCount;
++m_fixtureCount; y += deltaY;
y += deltaY; }
}
x += deltaX;
x += deltaX; }
} }
}
m_createTime = timer.GetMilliseconds();
m_createTime = timer.GetMilliseconds(); }
}
void Step(Settings* settings)
void Step(Settings* settings) {
{ const b2ContactManager& cm = m_world->GetContactManager();
const b2ContactManager& cm = m_world->GetContactManager(); int32 height = cm.m_broadPhase.GetTreeHeight();
int32 height = cm.m_broadPhase.GetTreeHeight(); int32 leafCount = cm.m_broadPhase.GetProxyCount();
int32 leafCount = cm.m_broadPhase.GetProxyCount(); int32 minimumNodeCount = 2 * leafCount - 1;
int32 minimumNodeCount = 2 * leafCount - 1; float32 minimumHeight = ceilf(logf(float32(minimumNodeCount)) / log
float32 minimumHeight = ceilf(logf(float32(minimumNodeCount) f(2.0f));
) / logf(2.0f)); m_debugDraw.DrawString(5, m_textLine, "dynamic tree height = %d, mi
m_debugDraw.DrawString(5, m_textLine, "dynamic tree height = n = %d", height, int32(minimumHeight));
%d, min = %d", height, int32(minimumHeight)); m_textLine += 15;
m_textLine += 15;
Test::Step(settings);
Test::Step(settings);
m_debugDraw.DrawString(5, m_textLine, "create time = %6.2f ms, fixt
m_debugDraw.DrawString(5, m_textLine, "create time = %6.2f m ure count = %d",
s, fixture count = %d", m_createTime, m_fixtureCount);
m_createTime, m_fixtureCount); m_textLine += 15;
m_textLine += 15;
//b2DynamicTree* tree = &m_world->m_contactManager.m_broadPhase.m_t
//b2DynamicTree* tree = &m_world->m_contactManager.m_broadPh ree;
ase.m_tree;
//if (m_stepCount == 400)
//if (m_stepCount == 400) //{
//{ // tree->RebuildBottomUp();
// tree->RebuildBottomUp(); //}
//} }
}
static Test* Create()
static Test* Create() {
{ return new Tiles;
return new Tiles; }
}
int32 m_fixtureCount; int32 m_fixtureCount;
float32 m_createTime; float32 m_createTime;
}; };
#endif #endif
 End of changes. 6 change blocks. 
128 lines changed or deleted 125 lines changed or added


 TimeOfImpact.h   TimeOfImpact.h 
skipping to change at line 25 skipping to change at line 25
* misrepresented as being the original software. * misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution . * 3. This notice may not be removed or altered from any source distribution .
*/ */
#ifndef TIME_OF_IMPACT_H #ifndef TIME_OF_IMPACT_H
#define TIME_OF_IMPACT_H #define TIME_OF_IMPACT_H
class TimeOfImpact : public Test class TimeOfImpact : public Test
{ {
public: public:
TimeOfImpact() TimeOfImpact()
{ {
m_shapeA.SetAsBox(25.0f, 5.0f); m_shapeA.SetAsBox(25.0f, 5.0f);
m_shapeB.SetAsBox(2.5f, 2.5f); m_shapeB.SetAsBox(2.5f, 2.5f);
} }
static Test* Create() static Test* Create()
{ {
return new TimeOfImpact; return new TimeOfImpact;
} }
void Step(Settings* settings) void Step(Settings* settings)
{ {
Test::Step(settings); Test::Step(settings);
b2Sweep sweepA; b2Sweep sweepA;
sweepA.c0.Set(24.0f, -60.0f); sweepA.c0.Set(24.0f, -60.0f);
sweepA.a0 = 2.95f; sweepA.a0 = 2.95f;
sweepA.c = sweepA.c0; sweepA.c = sweepA.c0;
sweepA.a = sweepA.a0; sweepA.a = sweepA.a0;
sweepA.localCenter.SetZero(); sweepA.localCenter.SetZero();
b2Sweep sweepB; b2Sweep sweepB;
sweepB.c0.Set(53.474274f, -50.252514f); sweepB.c0.Set(53.474274f, -50.252514f);
sweepB.a0 = 513.36676f; // - 162.0f * b2_pi; sweepB.a0 = 513.36676f; // - 162.0f * b2_pi;
sweepB.c.Set(54.595478f, -51.083473f); sweepB.c.Set(54.595478f, -51.083473f);
sweepB.a = 513.62781f; // - 162.0f * b2_pi; sweepB.a = 513.62781f; // - 162.0f * b2_pi;
sweepB.localCenter.SetZero(); sweepB.localCenter.SetZero();
//sweepB.a0 -= 300.0f * b2_pi; //sweepB.a0 -= 300.0f * b2_pi;
//sweepB.a -= 300.0f * b2_pi; //sweepB.a -= 300.0f * b2_pi;
b2TOIInput input; b2TOIInput input;
input.proxyA.Set(&m_shapeA, 0); input.proxyA.Set(&m_shapeA, 0);
input.proxyB.Set(&m_shapeB, 0); input.proxyB.Set(&m_shapeB, 0);
input.sweepA = sweepA; input.sweepA = sweepA;
input.sweepB = sweepB; input.sweepB = sweepB;
input.tMax = 1.0f; input.tMax = 1.0f;
b2TOIOutput output; b2TOIOutput output;
b2TimeOfImpact(&output, &input); b2TimeOfImpact(&output, &input);
m_debugDraw.DrawString(5, m_textLine, "toi = %g", output.t); m_debugDraw.DrawString(5, m_textLine, "toi = %g", output.t);
m_textLine += 15; m_textLine += 15;
extern int32 b2_toiMaxIters, b2_toiMaxRootIters; extern int32 b2_toiMaxIters, b2_toiMaxRootIters;
m_debugDraw.DrawString(5, m_textLine, "max toi iters = %d, m m_debugDraw.DrawString(5, m_textLine, "max toi iters = %d, max root
ax root iters = %d", b2_toiMaxIters, b2_toiMaxRootIters); iters = %d", b2_toiMaxIters, b2_toiMaxRootIters);
m_textLine += 15; m_textLine += 15;
b2Vec2 vertices[b2_maxPolygonVertices]; b2Vec2 vertices[b2_maxPolygonVertices];
b2Transform transformA; b2Transform transformA;
sweepA.GetTransform(&transformA, 0.0f); sweepA.GetTransform(&transformA, 0.0f);
for (int32 i = 0; i < m_shapeA.m_vertexCount; ++i) for (int32 i = 0; i < m_shapeA.m_vertexCount; ++i)
{ {
vertices[i] = b2Mul(transformA, m_shapeA.m_vertices[ vertices[i] = b2Mul(transformA, m_shapeA.m_vertices[i]);
i]); }
} m_debugDraw.DrawPolygon(vertices, m_shapeA.m_vertexCount, b2Color(0
m_debugDraw.DrawPolygon(vertices, m_shapeA.m_vertexCount, b2 .9f, 0.9f, 0.9f));
Color(0.9f, 0.9f, 0.9f));
b2Transform transformB;
b2Transform transformB; sweepB.GetTransform(&transformB, 0.0f);
sweepB.GetTransform(&transformB, 0.0f);
b2Vec2 localPoint(2.0f, -0.1f);
b2Vec2 localPoint(2.0f, -0.1f); b2Vec2 rB = b2Mul(transformB, localPoint) - sweepB.c0;
b2Vec2 rB = b2Mul(transformB, localPoint) - sweepB.c0; float32 wB = sweepB.a - sweepB.a0;
float32 wB = sweepB.a - sweepB.a0; b2Vec2 vB = sweepB.c - sweepB.c0;
b2Vec2 vB = sweepB.c - sweepB.c0; b2Vec2 v = vB + b2Cross(wB, rB);
b2Vec2 v = vB + b2Cross(wB, rB);
for (int32 i = 0; i < m_shapeB.m_vertexCount; ++i)
for (int32 i = 0; i < m_shapeB.m_vertexCount; ++i) {
{ vertices[i] = b2Mul(transformB, m_shapeB.m_vertices[i]);
vertices[i] = b2Mul(transformB, m_shapeB.m_vertices[ }
i]); m_debugDraw.DrawPolygon(vertices, m_shapeB.m_vertexCount, b2Color(0
} .5f, 0.9f, 0.5f));
m_debugDraw.DrawPolygon(vertices, m_shapeB.m_vertexCount, b2
Color(0.5f, 0.9f, 0.5f)); sweepB.GetTransform(&transformB, output.t);
for (int32 i = 0; i < m_shapeB.m_vertexCount; ++i)
sweepB.GetTransform(&transformB, output.t); {
for (int32 i = 0; i < m_shapeB.m_vertexCount; ++i) vertices[i] = b2Mul(transformB, m_shapeB.m_vertices[i]);
{ }
vertices[i] = b2Mul(transformB, m_shapeB.m_vertices[ m_debugDraw.DrawPolygon(vertices, m_shapeB.m_vertexCount, b2Color(0
i]); .5f, 0.7f, 0.9f));
}
m_debugDraw.DrawPolygon(vertices, m_shapeB.m_vertexCount, b2 sweepB.GetTransform(&transformB, 1.0f);
Color(0.5f, 0.7f, 0.9f)); for (int32 i = 0; i < m_shapeB.m_vertexCount; ++i)
{
sweepB.GetTransform(&transformB, 1.0f); vertices[i] = b2Mul(transformB, m_shapeB.m_vertices[i]);
for (int32 i = 0; i < m_shapeB.m_vertexCount; ++i) }
{ m_debugDraw.DrawPolygon(vertices, m_shapeB.m_vertexCount, b2Color(0
vertices[i] = b2Mul(transformB, m_shapeB.m_vertices[ .9f, 0.5f, 0.5f));
i]);
}
m_debugDraw.DrawPolygon(vertices, m_shapeB.m_vertexCount, b2
Color(0.9f, 0.5f, 0.5f));
#if 0 #if 0
for (float32 t = 0.0f; t < 1.0f; t += 0.1f) for (float32 t = 0.0f; t < 1.0f; t += 0.1f)
{ {
sweepB.GetTransform(&transformB, t); sweepB.GetTransform(&transformB, t);
for (int32 i = 0; i < m_shapeB.m_vertexCount; ++i) for (int32 i = 0; i < m_shapeB.m_vertexCount; ++i)
{ {
vertices[i] = b2Mul(transformB, m_shapeB.m_v vertices[i] = b2Mul(transformB, m_shapeB.m_vertices[i]);
ertices[i]); }
} m_debugDraw.DrawPolygon(vertices, m_shapeB.m_vertexCount, b2Col
m_debugDraw.DrawPolygon(vertices, m_shapeB.m_vertexC or(0.9f, 0.5f, 0.5f));
ount, b2Color(0.9f, 0.5f, 0.5f)); }
}
#endif #endif
} }
b2PolygonShape m_shapeA; b2PolygonShape m_shapeA;
b2PolygonShape m_shapeB; b2PolygonShape m_shapeB;
}; };
#endif #endif
 End of changes. 4 change blocks. 
111 lines changed or deleted 106 lines changed or added


 TouchesTest.h   TouchesTest.h 
#ifndef _TOUCHES_TEST__H_ #ifndef _TOUCHES_TEST__H_
#define _TOUCHES_TEST__H_ #define _TOUCHES_TEST__H_
////----#include "cocos2d.h" ////----#include "cocos2d.h"
#include "../testBasic.h" #include "../testBasic.h"
using namespace cocos2d; USING_NS_CC;
class PongScene : public TestScene class PongScene : public TestScene
{ {
public: public:
PongScene(); PongScene();
virtual void runThisTest(); virtual void runThisTest();
virtual void MainMenuCallback(CCObject* pSender); virtual void MainMenuCallback(CCObject* pSender);
}; };
class Ball; class Ball;
class PongLayer : public CCLayer class PongLayer : public CCLayer
{ {
Ball* m_ball; private:
CCMutableArray<CCObject *> *m_paddles; CCSize m_tWinSize;
CCPoint m_ballStartingVelocity; Ball* m_ball;
CCArray* m_paddles;
CCPoint m_ballStartingVelocity;
public: public:
PongLayer(); PongLayer();
~PongLayer(); ~PongLayer();
void resetAndScoreBallForPlayer(int player); void resetAndScoreBallForPlayer(int player);
void doStep(ccTime delta); void doStep(float delta);
}; };
#endif #endif
 End of changes. 4 change blocks. 
8 lines changed or deleted 10 lines changed or added


 TransformUtils.h   TransformUtils.h 
skipping to change at line 29 skipping to change at line 29
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __SUPPORT_TRANSFORM_UTILS_H__ #ifndef __SUPPORT_TRANSFORM_UTILS_H__
#define __SUPPORT_TRANSFORM_UTILS_H__ #define __SUPPORT_TRANSFORM_UTILS_H__
///@todo // todo:
// when in MAC or windows, it includes <OpenGL/gl.h> // when in MAC or windows, it includes <OpenGL/gl.h>
#include "CCGL.h" #include "CCGL.h"
namespace cocos2d { namespace cocos2d {
struct CCAffineTransform; struct CCAffineTransform;
void CGAffineToGL(const CCAffineTransform *t, GLfloat *m); void CGAffineToGL(const CCAffineTransform *t, GLfloat *m);
void GLToCGAffine(const GLfloat *m, CCAffineTransform *t); void GLToCGAffine(const GLfloat *m, CCAffineTransform *t);
}//namespace cocos2d }//namespace cocos2d
 End of changes. 1 change blocks. 
1 lines changed or deleted 1 lines changed or added


 TransitionsTest.h   TransitionsTest.h 
#ifndef _TRANSITIONS_TEST_H_ #ifndef _TRANSITIONS_TEST_H_
#define _TRANSITIONS_TEST_H_ #define _TRANSITIONS_TEST_H_
#include "../testBasic.h" #include "../testBasic.h"
using namespace cocos2d; USING_NS_CC;
class TransitionsTestScene : public TestScene class TransitionsTestScene : public TestScene
{ {
public: public:
virtual void runThisTest(); virtual void runThisTest();
}; };
class TestLayer1 : public CCLayer class TestLayer1 : public CCLayer
{ {
public: public:
TestLayer1(void); TestLayer1(void);
~TestLayer1(void); ~TestLayer1(void);
void restartCallback(CCObject* pSender); void restartCallback(CCObject* pSender);
void nextCallback(CCObject* pSender); void nextCallback(CCObject* pSender);
void backCallback(CCObject* pSender); void backCallback(CCObject* pSender);
void step(ccTime dt); void step(float dt);
virtual void onEnter();
virtual void onEnterTransitionDidFinish();
virtual void onExitTransitionDidStart();
virtual void onExit();
}; };
class TestLayer2 : public CCLayer class TestLayer2 : public CCLayer
{ {
public: public:
TestLayer2(void); TestLayer2(void);
~TestLayer2(void); ~TestLayer2(void);
void restartCallback(CCObject* pSender); void restartCallback(CCObject* pSender);
void nextCallback(CCObject* pSender); void nextCallback(CCObject* pSender);
void backCallback(CCObject* pSender); void backCallback(CCObject* pSender);
void step(ccTime dt); void step(float dt);
virtual void onEnter();
virtual void onEnterTransitionDidFinish();
virtual void onExitTransitionDidStart();
virtual void onExit();
}; };
#endif #endif
 End of changes. 3 change blocks. 
3 lines changed or deleted 13 lines changed or added


 Tumbler.h   Tumbler.h 
skipping to change at line 26 skipping to change at line 26
* 3. This notice may not be removed or altered from any source distribution . * 3. This notice may not be removed or altered from any source distribution .
*/ */
#ifndef TUMBLER_H #ifndef TUMBLER_H
#define TUMBLER_H #define TUMBLER_H
class Tumbler : public Test class Tumbler : public Test
{ {
public: public:
enum enum
{ {
e_count = 800 e_count = 800
}; };
Tumbler() Tumbler()
{ {
b2Body* ground = NULL; b2Body* ground = NULL;
{ {
b2BodyDef bd; b2BodyDef bd;
ground = m_world->CreateBody(&bd); ground = m_world->CreateBody(&bd);
} }
{ {
b2BodyDef bd; b2BodyDef bd;
bd.type = b2_dynamicBody; bd.type = b2_dynamicBody;
bd.allowSleep = false; bd.allowSleep = false;
bd.position.Set(0.0f, 10.0f); bd.position.Set(0.0f, 10.0f);
b2Body* body = m_world->CreateBody(&bd); b2Body* body = m_world->CreateBody(&bd);
b2PolygonShape shape; b2PolygonShape shape;
shape.SetAsBox(0.5f, 10.0f, b2Vec2( 10.0f, 0.0f), 0. shape.SetAsBox(0.5f, 10.0f, b2Vec2( 10.0f, 0.0f), 0.0);
0); body->CreateFixture(&shape, 5.0f);
body->CreateFixture(&shape, 5.0f); shape.SetAsBox(0.5f, 10.0f, b2Vec2(-10.0f, 0.0f), 0.0);
shape.SetAsBox(0.5f, 10.0f, b2Vec2(-10.0f, 0.0f), 0. body->CreateFixture(&shape, 5.0f);
0); shape.SetAsBox(10.0f, 0.5f, b2Vec2(0.0f, 10.0f), 0.0);
body->CreateFixture(&shape, 5.0f); body->CreateFixture(&shape, 5.0f);
shape.SetAsBox(10.0f, 0.5f, b2Vec2(0.0f, 10.0f), 0.0 shape.SetAsBox(10.0f, 0.5f, b2Vec2(0.0f, -10.0f), 0.0);
); body->CreateFixture(&shape, 5.0f);
body->CreateFixture(&shape, 5.0f);
shape.SetAsBox(10.0f, 0.5f, b2Vec2(0.0f, -10.0f), 0. b2RevoluteJointDef jd;
0); jd.bodyA = ground;
body->CreateFixture(&shape, 5.0f); jd.bodyB = body;
jd.localAnchorA.Set(0.0f, 10.0f);
b2RevoluteJointDef jd; jd.localAnchorB.Set(0.0f, 0.0f);
jd.bodyA = ground; jd.referenceAngle = 0.0f;
jd.bodyB = body; jd.motorSpeed = 0.05f * b2_pi;
jd.localAnchorA.Set(0.0f, 10.0f); jd.maxMotorTorque = 1e8f;
jd.localAnchorB.Set(0.0f, 0.0f); jd.enableMotor = true;
jd.referenceAngle = 0.0f; m_joint = (b2RevoluteJoint*)m_world->CreateJoint(&jd);
jd.motorSpeed = 0.05f * b2_pi; }
jd.maxMotorTorque = 1e8f;
jd.enableMotor = true; m_count = 0;
m_joint = (b2RevoluteJoint*)m_world->CreateJoint(&jd }
);
} void Step(Settings* settings)
{
m_count = 0; Test::Step(settings);
}
if (m_count < e_count)
void Step(Settings* settings) {
{ b2BodyDef bd;
Test::Step(settings); bd.type = b2_dynamicBody;
bd.position.Set(0.0f, 10.0f);
if (m_count < e_count) b2Body* body = m_world->CreateBody(&bd);
{
b2BodyDef bd; b2PolygonShape shape;
bd.type = b2_dynamicBody; shape.SetAsBox(0.125f, 0.125f);
bd.position.Set(0.0f, 10.0f); body->CreateFixture(&shape, 1.0f);
b2Body* body = m_world->CreateBody(&bd);
++m_count;
b2PolygonShape shape; }
shape.SetAsBox(0.125f, 0.125f); }
body->CreateFixture(&shape, 1.0f);
static Test* Create()
++m_count; {
} return new Tumbler;
} }
static Test* Create()
{
return new Tumbler;
}
b2RevoluteJoint* m_joint; b2RevoluteJoint* m_joint;
int32 m_count; int32 m_count;
}; };
#endif #endif
 End of changes. 2 change blocks. 
75 lines changed or deleted 70 lines changed or added


 UserDefaultTest.h   UserDefaultTest.h 
#ifndef _USERDEFAULT_TEST_H_ #ifndef _USERDEFAULT_TEST_H_
#define _USERDEFAULT_TEST_H_ #define _USERDEFAULT_TEST_H_
#include "cocos2d.h" #include "cocos2d.h"
#include "../testBasic.h" #include "../testBasic.h"
class UserDefaultTest : public CCLayer class UserDefaultTest : public CCLayer
{ {
public: public:
UserDefaultTest(); UserDefaultTest();
~UserDefaultTest(); ~UserDefaultTest();
private: private:
void doTest(); void doTest();
}; };
class UserDefaultTestScene : public TestScene class UserDefaultTestScene : public TestScene
{ {
public: public:
virtual void runThisTest(); virtual void runThisTest();
}; };
#endif // _USERDEFAULT_TEST_H_ #endif // _USERDEFAULT_TEST_H_
 End of changes. 2 change blocks. 
3 lines changed or deleted 3 lines changed or added


 VaryingFriction.h   VaryingFriction.h 
skipping to change at line 26 skipping to change at line 26
* 3. This notice may not be removed or altered from any source distribution . * 3. This notice may not be removed or altered from any source distribution .
*/ */
#ifndef VARYING_FRICTION_H #ifndef VARYING_FRICTION_H
#define VARYING_FRICTION_H #define VARYING_FRICTION_H
class VaryingFriction : public Test class VaryingFriction : public Test
{ {
public: public:
VaryingFriction() VaryingFriction()
{ {
{ {
b2BodyDef bd; b2BodyDef bd;
b2Body* ground = m_world->CreateBody(&bd); b2Body* ground = m_world->CreateBody(&bd);
b2EdgeShape shape; b2EdgeShape shape;
shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)) shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f));
; ground->CreateFixture(&shape, 0.0f);
ground->CreateFixture(&shape, 0.0f); }
}
{
{ b2PolygonShape shape;
b2PolygonShape shape; shape.SetAsBox(13.0f, 0.25f);
shape.SetAsBox(13.0f, 0.25f);
b2BodyDef bd;
b2BodyDef bd; bd.position.Set(-4.0f, 22.0f);
bd.position.Set(-4.0f, 22.0f); bd.angle = -0.25f;
bd.angle = -0.25f;
b2Body* ground = m_world->CreateBody(&bd);
b2Body* ground = m_world->CreateBody(&bd); ground->CreateFixture(&shape, 0.0f);
ground->CreateFixture(&shape, 0.0f); }
}
{
{ b2PolygonShape shape;
b2PolygonShape shape; shape.SetAsBox(0.25f, 1.0f);
shape.SetAsBox(0.25f, 1.0f);
b2BodyDef bd;
b2BodyDef bd; bd.position.Set(10.5f, 19.0f);
bd.position.Set(10.5f, 19.0f);
b2Body* ground = m_world->CreateBody(&bd);
b2Body* ground = m_world->CreateBody(&bd); ground->CreateFixture(&shape, 0.0f);
ground->CreateFixture(&shape, 0.0f); }
}
{
{ b2PolygonShape shape;
b2PolygonShape shape; shape.SetAsBox(13.0f, 0.25f);
shape.SetAsBox(13.0f, 0.25f);
b2BodyDef bd;
b2BodyDef bd; bd.position.Set(4.0f, 14.0f);
bd.position.Set(4.0f, 14.0f); bd.angle = 0.25f;
bd.angle = 0.25f;
b2Body* ground = m_world->CreateBody(&bd);
b2Body* ground = m_world->CreateBody(&bd); ground->CreateFixture(&shape, 0.0f);
ground->CreateFixture(&shape, 0.0f); }
}
{
{ b2PolygonShape shape;
b2PolygonShape shape; shape.SetAsBox(0.25f, 1.0f);
shape.SetAsBox(0.25f, 1.0f);
b2BodyDef bd;
b2BodyDef bd; bd.position.Set(-10.5f, 11.0f);
bd.position.Set(-10.5f, 11.0f);
b2Body* ground = m_world->CreateBody(&bd);
b2Body* ground = m_world->CreateBody(&bd); ground->CreateFixture(&shape, 0.0f);
ground->CreateFixture(&shape, 0.0f); }
}
{
{ b2PolygonShape shape;
b2PolygonShape shape; shape.SetAsBox(13.0f, 0.25f);
shape.SetAsBox(13.0f, 0.25f);
b2BodyDef bd;
b2BodyDef bd; bd.position.Set(-4.0f, 6.0f);
bd.position.Set(-4.0f, 6.0f); bd.angle = -0.25f;
bd.angle = -0.25f;
b2Body* ground = m_world->CreateBody(&bd);
b2Body* ground = m_world->CreateBody(&bd); ground->CreateFixture(&shape, 0.0f);
ground->CreateFixture(&shape, 0.0f); }
}
{
{ b2PolygonShape shape;
b2PolygonShape shape; shape.SetAsBox(0.5f, 0.5f);
shape.SetAsBox(0.5f, 0.5f);
b2FixtureDef fd;
b2FixtureDef fd; fd.shape = &shape;
fd.shape = &shape; fd.density = 25.0f;
fd.density = 25.0f;
float friction[5] = {0.75f, 0.5f, 0.35f, 0.1f, 0.0f};
float friction[5] = {0.75f, 0.5f, 0.35f, 0.1f, 0.0f}
; for (int i = 0; i < 5; ++i)
{
for (int i = 0; i < 5; ++i) b2BodyDef bd;
{ bd.type = b2_dynamicBody;
b2BodyDef bd; bd.position.Set(-15.0f + 4.0f * i, 28.0f);
bd.type = b2_dynamicBody; b2Body* body = m_world->CreateBody(&bd);
bd.position.Set(-15.0f + 4.0f * i, 28.0f);
b2Body* body = m_world->CreateBody(&bd); fd.friction = friction[i];
body->CreateFixture(&fd);
fd.friction = friction[i]; }
body->CreateFixture(&fd); }
} }
}
} static Test* Create()
{
static Test* Create() return new VaryingFriction;
{ }
return new VaryingFriction;
}
}; };
#endif #endif
 End of changes. 1 change blocks. 
98 lines changed or deleted 96 lines changed or added


 VaryingRestitution.h   VaryingRestitution.h 
skipping to change at line 28 skipping to change at line 28
#ifndef VARYING_RESTITUTION_H #ifndef VARYING_RESTITUTION_H
#define VARYING_RESTITUTION_H #define VARYING_RESTITUTION_H
// Note: even with a restitution of 1.0, there is some energy change // Note: even with a restitution of 1.0, there is some energy change
// due to position correction. // due to position correction.
class VaryingRestitution : public Test class VaryingRestitution : public Test
{ {
public: public:
VaryingRestitution() VaryingRestitution()
{ {
{ {
b2BodyDef bd; b2BodyDef bd;
b2Body* ground = m_world->CreateBody(&bd); b2Body* ground = m_world->CreateBody(&bd);
b2EdgeShape shape; b2EdgeShape shape;
shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)) shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f));
; ground->CreateFixture(&shape, 0.0f);
ground->CreateFixture(&shape, 0.0f); }
}
{
{ b2CircleShape shape;
b2CircleShape shape; shape.m_radius = 1.0f;
shape.m_radius = 1.0f;
b2FixtureDef fd;
b2FixtureDef fd; fd.shape = &shape;
fd.shape = &shape; fd.density = 1.0f;
fd.density = 1.0f;
float32 restitution[7] = {0.0f, 0.1f, 0.3f, 0.5f, 0.75f, 0.9f,
float32 restitution[7] = {0.0f, 0.1f, 0.3f, 0.5f, 0. 1.0f};
75f, 0.9f, 1.0f};
for (int32 i = 0; i < 7; ++i)
for (int32 i = 0; i < 7; ++i) {
{ b2BodyDef bd;
b2BodyDef bd; bd.type = b2_dynamicBody;
bd.type = b2_dynamicBody; bd.position.Set(-10.0f + 3.0f * i, 20.0f);
bd.position.Set(-10.0f + 3.0f * i, 20.0f);
b2Body* body = m_world->CreateBody(&bd);
b2Body* body = m_world->CreateBody(&bd);
fd.restitution = restitution[i];
fd.restitution = restitution[i]; body->CreateFixture(&fd);
body->CreateFixture(&fd); }
} }
} }
}
static Test* Create()
static Test* Create() {
{ return new VaryingRestitution;
return new VaryingRestitution; }
}
}; };
#endif #endif
 End of changes. 1 change blocks. 
41 lines changed or deleted 40 lines changed or added


 VerticalStack.h   VerticalStack.h 
skipping to change at line 26 skipping to change at line 26
* 3. This notice may not be removed or altered from any source distribution . * 3. This notice may not be removed or altered from any source distribution .
*/ */
#ifndef VERTICAL_STACK_H #ifndef VERTICAL_STACK_H
#define VERTICAL_STACK_H #define VERTICAL_STACK_H
class VerticalStack : public Test class VerticalStack : public Test
{ {
public: public:
enum enum
{ {
e_columnCount = 5, e_columnCount = 5,
e_rowCount = 16 e_rowCount = 16
//e_columnCount = 1, //e_columnCount = 1,
//e_rowCount = 1 //e_rowCount = 1
}; };
VerticalStack() VerticalStack()
{ {
{ {
b2BodyDef bd; b2BodyDef bd;
b2Body* ground = m_world->CreateBody(&bd); b2Body* ground = m_world->CreateBody(&bd);
b2EdgeShape shape; b2EdgeShape shape;
shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)) shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f));
; ground->CreateFixture(&shape, 0.0f);
ground->CreateFixture(&shape, 0.0f);
shape.Set(b2Vec2(20.0f, 0.0f), b2Vec2(20.0f, 20.0f));
shape.Set(b2Vec2(20.0f, 0.0f), b2Vec2(20.0f, 20.0f)) ground->CreateFixture(&shape, 0.0f);
; }
ground->CreateFixture(&shape, 0.0f);
} float32 xs[5] = {0.0f, -10.0f, -5.0f, 5.0f, 10.0f};
float32 xs[5] = {0.0f, -10.0f, -5.0f, 5.0f, 10.0f}; for (int32 j = 0; j < e_columnCount; ++j)
{
for (int32 j = 0; j < e_columnCount; ++j) b2PolygonShape shape;
{ shape.SetAsBox(0.5f, 0.5f);
b2PolygonShape shape;
shape.SetAsBox(0.5f, 0.5f); b2FixtureDef fd;
fd.shape = &shape;
b2FixtureDef fd; fd.density = 1.0f;
fd.shape = &shape; fd.friction = 0.3f;
fd.density = 1.0f;
fd.friction = 0.3f; for (int i = 0; i < e_rowCount; ++i)
{
for (int i = 0; i < e_rowCount; ++i) b2BodyDef bd;
{ bd.type = b2_dynamicBody;
b2BodyDef bd;
bd.type = b2_dynamicBody; int32 n = j * e_rowCount + i;
b2Assert(n < e_rowCount * e_columnCount);
int32 n = j * e_rowCount + i; m_indices[n] = n;
b2Assert(n < e_rowCount * e_columnCount); bd.userData = m_indices + n;
m_indices[n] = n;
bd.userData = m_indices + n; float32 x = 0.0f;
//float32 x = RandomFloat(-0.02f, 0.02f);
float32 x = 0.0f; //float32 x = i % 2 == 0 ? -0.025f : 0.025f;
//float32 x = RandomFloat(-0.02f, 0.02f); bd.position.Set(xs[j] + x, 0.752f + 1.54f * i);
//float32 x = i % 2 == 0 ? -0.025f : 0.025f; b2Body* body = m_world->CreateBody(&bd);
bd.position.Set(xs[j] + x, 0.752f + 1.54f *
i); m_bodies[n] = body;
b2Body* body = m_world->CreateBody(&bd);
body->CreateFixture(&fd);
m_bodies[n] = body; }
}
body->CreateFixture(&fd);
} m_bullet = NULL;
} }
m_bullet = NULL; void Keyboard(unsigned char key)
} {
switch (key)
void Keyboard(unsigned char key) {
{ case ',':
switch (key) if (m_bullet != NULL)
{ {
case ',': m_world->DestroyBody(m_bullet);
if (m_bullet != NULL) m_bullet = NULL;
{ }
m_world->DestroyBody(m_bullet);
m_bullet = NULL; {
} b2CircleShape shape;
shape.m_radius = 0.25f;
{
b2CircleShape shape; b2FixtureDef fd;
shape.m_radius = 0.25f; fd.shape = &shape;
fd.density = 20.0f;
b2FixtureDef fd; fd.restitution = 0.05f;
fd.shape = &shape;
fd.density = 20.0f; b2BodyDef bd;
fd.restitution = 0.05f; bd.type = b2_dynamicBody;
bd.bullet = true;
b2BodyDef bd; bd.position.Set(-31.0f, 5.0f);
bd.type = b2_dynamicBody;
bd.bullet = true; m_bullet = m_world->CreateBody(&bd);
bd.position.Set(-31.0f, 5.0f); m_bullet->CreateFixture(&fd);
m_bullet = m_world->CreateBody(&bd); m_bullet->SetLinearVelocity(b2Vec2(400.0f, 0.0f));
m_bullet->CreateFixture(&fd); }
break;
m_bullet->SetLinearVelocity(b2Vec2(400.0f, 0 }
.0f)); }
}
break; void Step(Settings* settings)
} {
} Test::Step(settings);
m_debugDraw.DrawString(5, m_textLine, "Press: (,) to launch a bulle
void Step(Settings* settings) t.");
{ m_textLine += 15;
Test::Step(settings);
m_debugDraw.DrawString(5, m_textLine, "Press: (,) to launch //if (m_stepCount == 300)
a bullet."); //{
m_textLine += 15; // if (m_bullet != NULL)
// {
//if (m_stepCount == 300) // m_world->DestroyBody(m_bullet);
//{ // m_bullet = NULL;
// if (m_bullet != NULL) // }
// {
// m_world->DestroyBody(m_bullet); // {
// m_bullet = NULL; // b2CircleShape shape;
// } // shape.m_radius = 0.25f;
// { // b2FixtureDef fd;
// b2CircleShape shape; // fd.shape = &shape;
// shape.m_radius = 0.25f; // fd.density = 20.0f;
// fd.restitution = 0.05f;
// b2FixtureDef fd;
// fd.shape = &shape; // b2BodyDef bd;
// fd.density = 20.0f; // bd.type = b2_dynamicBody;
// fd.restitution = 0.05f; // bd.bullet = true;
// bd.position.Set(-31.0f, 5.0f);
// b2BodyDef bd;
// bd.type = b2_dynamicBody; // m_bullet = m_world->CreateBody(&bd);
// bd.bullet = true; // m_bullet->CreateFixture(&fd);
// bd.position.Set(-31.0f, 5.0f);
// m_bullet->SetLinearVelocity(b2Vec2(400.0f, 0.0f));
// m_bullet = m_world->CreateBody(&bd); // }
// m_bullet->CreateFixture(&fd); //}
}
// m_bullet->SetLinearVelocity(b2Vec2(400.0f, 0
.0f)); static Test* Create()
// } {
//} return new VerticalStack;
} }
static Test* Create() b2Body* m_bullet;
{ b2Body* m_bodies[e_rowCount * e_columnCount];
return new VerticalStack; int32 m_indices[e_rowCount * e_columnCount];
}
b2Body* m_bullet;
b2Body* m_bodies[e_rowCount * e_columnCount];
int32 m_indices[e_rowCount * e_columnCount];
}; };
#endif #endif
 End of changes. 1 change blocks. 
143 lines changed or deleted 138 lines changed or added


 Web.h   Web.h 
skipping to change at line 26 skipping to change at line 26
* 3. This notice may not be removed or altered from any source distribution . * 3. This notice may not be removed or altered from any source distribution .
*/ */
#ifndef WEB_H #ifndef WEB_H
#define WEB_H #define WEB_H
// This tests distance joints, body destruction, and joint destruction. // This tests distance joints, body destruction, and joint destruction.
class Web : public Test class Web : public Test
{ {
public: public:
Web() Web()
{ {
b2Body* ground = NULL; b2Body* ground = NULL;
{ {
b2BodyDef bd; b2BodyDef bd;
ground = m_world->CreateBody(&bd); ground = m_world->CreateBody(&bd);
b2EdgeShape shape; b2EdgeShape shape;
shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)) shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f));
; ground->CreateFixture(&shape, 0.0f);
ground->CreateFixture(&shape, 0.0f); }
}
{
{ b2PolygonShape shape;
b2PolygonShape shape; shape.SetAsBox(0.5f, 0.5f);
shape.SetAsBox(0.5f, 0.5f);
b2BodyDef bd;
b2BodyDef bd; bd.type = b2_dynamicBody;
bd.type = b2_dynamicBody;
bd.position.Set(-5.0f, 5.0f);
bd.position.Set(-5.0f, 5.0f); m_bodies[0] = m_world->CreateBody(&bd);
m_bodies[0] = m_world->CreateBody(&bd); m_bodies[0]->CreateFixture(&shape, 5.0f);
m_bodies[0]->CreateFixture(&shape, 5.0f);
bd.position.Set(5.0f, 5.0f);
bd.position.Set(5.0f, 5.0f); m_bodies[1] = m_world->CreateBody(&bd);
m_bodies[1] = m_world->CreateBody(&bd); m_bodies[1]->CreateFixture(&shape, 5.0f);
m_bodies[1]->CreateFixture(&shape, 5.0f);
bd.position.Set(5.0f, 15.0f);
bd.position.Set(5.0f, 15.0f); m_bodies[2] = m_world->CreateBody(&bd);
m_bodies[2] = m_world->CreateBody(&bd); m_bodies[2]->CreateFixture(&shape, 5.0f);
m_bodies[2]->CreateFixture(&shape, 5.0f);
bd.position.Set(-5.0f, 15.0f);
bd.position.Set(-5.0f, 15.0f); m_bodies[3] = m_world->CreateBody(&bd);
m_bodies[3] = m_world->CreateBody(&bd); m_bodies[3]->CreateFixture(&shape, 5.0f);
m_bodies[3]->CreateFixture(&shape, 5.0f);
b2DistanceJointDef jd;
b2DistanceJointDef jd; b2Vec2 p1, p2, d;
b2Vec2 p1, p2, d;
jd.frequencyHz = 2.0f;
jd.frequencyHz = 2.0f; jd.dampingRatio = 0.0f;
jd.dampingRatio = 0.0f;
jd.bodyA = ground;
jd.bodyA = ground; jd.bodyB = m_bodies[0];
jd.bodyB = m_bodies[0]; jd.localAnchorA.Set(-10.0f, 0.0f);
jd.localAnchorA.Set(-10.0f, 0.0f); jd.localAnchorB.Set(-0.5f, -0.5f);
jd.localAnchorB.Set(-0.5f, -0.5f); p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA);
p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB);
p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); d = p2 - p1;
d = p2 - p1; jd.length = d.Length();
jd.length = d.Length(); m_joints[0] = m_world->CreateJoint(&jd);
m_joints[0] = m_world->CreateJoint(&jd);
jd.bodyA = ground;
jd.bodyA = ground; jd.bodyB = m_bodies[1];
jd.bodyB = m_bodies[1]; jd.localAnchorA.Set(10.0f, 0.0f);
jd.localAnchorA.Set(10.0f, 0.0f); jd.localAnchorB.Set(0.5f, -0.5f);
jd.localAnchorB.Set(0.5f, -0.5f); p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA);
p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB);
p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); d = p2 - p1;
d = p2 - p1; jd.length = d.Length();
jd.length = d.Length(); m_joints[1] = m_world->CreateJoint(&jd);
m_joints[1] = m_world->CreateJoint(&jd);
jd.bodyA = ground;
jd.bodyA = ground; jd.bodyB = m_bodies[2];
jd.bodyB = m_bodies[2]; jd.localAnchorA.Set(10.0f, 20.0f);
jd.localAnchorA.Set(10.0f, 20.0f); jd.localAnchorB.Set(0.5f, 0.5f);
jd.localAnchorB.Set(0.5f, 0.5f); p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA);
p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB);
p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); d = p2 - p1;
d = p2 - p1; jd.length = d.Length();
jd.length = d.Length(); m_joints[2] = m_world->CreateJoint(&jd);
m_joints[2] = m_world->CreateJoint(&jd);
jd.bodyA = ground;
jd.bodyA = ground; jd.bodyB = m_bodies[3];
jd.bodyB = m_bodies[3]; jd.localAnchorA.Set(-10.0f, 20.0f);
jd.localAnchorA.Set(-10.0f, 20.0f); jd.localAnchorB.Set(-0.5f, 0.5f);
jd.localAnchorB.Set(-0.5f, 0.5f); p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA);
p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB);
p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); d = p2 - p1;
d = p2 - p1; jd.length = d.Length();
jd.length = d.Length(); m_joints[3] = m_world->CreateJoint(&jd);
m_joints[3] = m_world->CreateJoint(&jd);
jd.bodyA = m_bodies[0];
jd.bodyA = m_bodies[0]; jd.bodyB = m_bodies[1];
jd.bodyB = m_bodies[1]; jd.localAnchorA.Set(0.5f, 0.0f);
jd.localAnchorA.Set(0.5f, 0.0f); jd.localAnchorB.Set(-0.5f, 0.0f);;
jd.localAnchorB.Set(-0.5f, 0.0f);; p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA);
p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB);
p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); d = p2 - p1;
d = p2 - p1; jd.length = d.Length();
jd.length = d.Length(); m_joints[4] = m_world->CreateJoint(&jd);
m_joints[4] = m_world->CreateJoint(&jd);
jd.bodyA = m_bodies[1];
jd.bodyA = m_bodies[1]; jd.bodyB = m_bodies[2];
jd.bodyB = m_bodies[2]; jd.localAnchorA.Set(0.0f, 0.5f);
jd.localAnchorA.Set(0.0f, 0.5f); jd.localAnchorB.Set(0.0f, -0.5f);
jd.localAnchorB.Set(0.0f, -0.5f); p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA);
p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB);
p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); d = p2 - p1;
d = p2 - p1; jd.length = d.Length();
jd.length = d.Length(); m_joints[5] = m_world->CreateJoint(&jd);
m_joints[5] = m_world->CreateJoint(&jd);
jd.bodyA = m_bodies[2];
jd.bodyA = m_bodies[2]; jd.bodyB = m_bodies[3];
jd.bodyB = m_bodies[3]; jd.localAnchorA.Set(-0.5f, 0.0f);
jd.localAnchorA.Set(-0.5f, 0.0f); jd.localAnchorB.Set(0.5f, 0.0f);
jd.localAnchorB.Set(0.5f, 0.0f); p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA);
p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB);
p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); d = p2 - p1;
d = p2 - p1; jd.length = d.Length();
jd.length = d.Length(); m_joints[6] = m_world->CreateJoint(&jd);
m_joints[6] = m_world->CreateJoint(&jd);
jd.bodyA = m_bodies[3];
jd.bodyA = m_bodies[3]; jd.bodyB = m_bodies[0];
jd.bodyB = m_bodies[0]; jd.localAnchorA.Set(0.0f, -0.5f);
jd.localAnchorA.Set(0.0f, -0.5f); jd.localAnchorB.Set(0.0f, 0.5f);
jd.localAnchorB.Set(0.0f, 0.5f); p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA);
p1 = jd.bodyA->GetWorldPoint(jd.localAnchorA); p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB);
p2 = jd.bodyB->GetWorldPoint(jd.localAnchorB); d = p2 - p1;
d = p2 - p1; jd.length = d.Length();
jd.length = d.Length(); m_joints[7] = m_world->CreateJoint(&jd);
m_joints[7] = m_world->CreateJoint(&jd); }
} }
}
void Keyboard(unsigned char key)
void Keyboard(unsigned char key) {
{ switch (key)
switch (key) {
{ case 'b':
case 'b': for (int32 i = 0; i < 4; ++i)
for (int32 i = 0; i < 4; ++i) {
{ if (m_bodies[i])
if (m_bodies[i]) {
{ m_world->DestroyBody(m_bodies[i]);
m_world->DestroyBody(m_bodies[i]); m_bodies[i] = NULL;
m_bodies[i] = NULL; break;
break; }
} }
} break;
break;
case 'j':
case 'j': for (int32 i = 0; i < 8; ++i)
for (int32 i = 0; i < 8; ++i) {
{ if (m_joints[i])
if (m_joints[i]) {
{ m_world->DestroyJoint(m_joints[i]);
m_world->DestroyJoint(m_joints[i]); m_joints[i] = NULL;
m_joints[i] = NULL; break;
break; }
} }
} break;
break; }
} }
}
void Step(Settings* settings)
void Step(Settings* settings) {
{ Test::Step(settings);
Test::Step(settings); m_debugDraw.DrawString(5, m_textLine, "This demonstrates a soft dis
m_debugDraw.DrawString(5, m_textLine, "This demonstrates a s tance joint.");
oft distance joint."); m_textLine += 15;
m_textLine += 15; m_debugDraw.DrawString(5, m_textLine, "Press: (b) to delete a body,
m_debugDraw.DrawString(5, m_textLine, "Press: (b) to delete (j) to delete a joint");
a body, (j) to delete a joint"); m_textLine += 15;
m_textLine += 15; }
}
void JointDestroyed(b2Joint* joint)
void JointDestroyed(b2Joint* joint) {
{ for (int32 i = 0; i < 8; ++i)
for (int32 i = 0; i < 8; ++i) {
{ if (m_joints[i] == joint)
if (m_joints[i] == joint) {
{ m_joints[i] = NULL;
m_joints[i] = NULL; break;
break; }
} }
} }
}
static Test* Create()
static Test* Create() {
{ return new Web;
return new Web; }
}
b2Body* m_bodies[4]; b2Body* m_bodies[4];
b2Joint* m_joints[8]; b2Joint* m_joints[8];
}; };
#endif #endif
 End of changes. 2 change blocks. 
183 lines changed or deleted 182 lines changed or added


 ZAttributedString.h   ZAttributedString.h 
skipping to change at line 20 skipping to change at line 20
#if NS_BLOCKS_AVAILABLE #if NS_BLOCKS_AVAILABLE
#define Z_BLOCKS 1 #define Z_BLOCKS 1
#else #else
// set this to 1 if you are using PLBlocks // set this to 1 if you are using PLBlocks
#define Z_BLOCKS 0 #define Z_BLOCKS 0
#endif #endif
#if Z_BLOCKS #if Z_BLOCKS
enum { enum {
ZAttributedStringEnumerationReverse = (1UL << 1), ZAttributedStringEnumerationReverse = (1UL << 1),
ZAttributedStringEnumerationLongestEffectiveRangeNotRequired = (1UL ZAttributedStringEnumerationLongestEffectiveRangeNotRequired = (1UL <<
<< 20) 20)
}; };
typedef NSUInteger ZAttributedStringEnumerationOptions; typedef NSUInteger ZAttributedStringEnumerationOptions;
#endif #endif
@interface ZAttributedString : NSObject <NSCoding, NSCopying, NSMutableCopy ing> { @interface ZAttributedString : NSObject <NSCoding, NSCopying, NSMutableCopy ing> {
NSMutableString *_buffer; NSMutableString *_buffer;
NSMutableArray *_attributes; NSMutableArray *_attributes;
} }
@property (nonatomic, readonly) NSUInteger length; @property (nonatomic, readonly) NSUInteger length;
@property (nonatomic, readonly) NSString *string; @property (nonatomic, readonly) NSString *string;
- (id)initWithAttributedString:(ZAttributedString *)attr; - (id)initWithAttributedString:(ZAttributedString *)attr;
- (id)initWithString:(NSString *)str; - (id)initWithString:(NSString *)str;
- (id)initWithString:(NSString *)str attributes:(NSDictionary *)attributes; - (id)initWithString:(NSString *)str attributes:(NSDictionary *)attributes;
- (id)attribute:(NSString *)attributeName atIndex:(NSUInteger)index effecti veRange:(NSRangePointer)aRange; - (id)attribute:(NSString *)attributeName atIndex:(NSUInteger)index effecti veRange:(NSRangePointer)aRange;
- (id)attribute:(NSString *)attributeName atIndex:(NSUInteger)index longest EffectiveRange:(NSRangePointer)aRange inRange:(NSRange)rangeLimit; - (id)attribute:(NSString *)attributeName atIndex:(NSUInteger)index longest EffectiveRange:(NSRangePointer)aRange inRange:(NSRange)rangeLimit;
- (ZAttributedString *)attributedSubstringFromRange:(NSRange)aRange; - (ZAttributedString *)attributedSubstringFromRange:(NSRange)aRange;
- (NSDictionary *)attributesAtIndex:(NSUInteger)index effectiveRange:(NSRan gePointer)aRange; - (NSDictionary *)attributesAtIndex:(NSUInteger)index effectiveRange:(NSRan gePointer)aRange;
- (NSDictionary *)attributesAtIndex:(NSUInteger)index longestEffectiveRange :(NSRangePointer)aRange inRange:(NSRange)rangeLimit; - (NSDictionary *)attributesAtIndex:(NSUInteger)index longestEffectiveRange :(NSRangePointer)aRange inRange:(NSRange)rangeLimit;
#if Z_BLOCKS #if Z_BLOCKS
- (void)enumerateAttribute:(NSString *)attrName inRange:(NSRange)enumeratio nRange options:(ZAttributedStringEnumerationOptions)opts - (void)enumerateAttribute:(NSString *)attrName inRange:(NSRange)enumeratio nRange options:(ZAttributedStringEnumerationOptions)opts
usingBlock:(void (^)(id value, NSRange range , BOOL *stop))block; usingBlock:(void (^)(id value, NSRange range, BOOL *stop))b lock;
- (void)enumerateAttributesInRange:(NSRange)enumerationRange options:(ZAttr ibutedStringEnumerationOptions)opts - (void)enumerateAttributesInRange:(NSRange)enumerationRange options:(ZAttr ibutedStringEnumerationOptions)opts
usingBlock:(void (^)(NSDicti onary *attrs, NSRange range, BOOL *stop))block; usingBlock:(void (^)(NSDictionary *attrs, NSRange r ange, BOOL *stop))block;
#endif #endif
- (BOOL)isEqualToAttributedString:(ZAttributedString *)otherString; - (BOOL)isEqualToAttributedString:(ZAttributedString *)otherString;
@end @end
@interface ZMutableAttributedString : ZAttributedString { @interface ZMutableAttributedString : ZAttributedString {
} }
- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range; - (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;
- (void)addAttributes:(NSDictionary *)attributes range:(NSRange)range; - (void)addAttributes:(NSDictionary *)attributes range:(NSRange)range;
- (void)appendAttributedString:(ZAttributedString *)str; - (void)appendAttributedString:(ZAttributedString *)str;
- (void)deleteCharactersInRange:(NSRange)range; - (void)deleteCharactersInRange:(NSRange)range;
skipping to change at line 69 skipping to change at line 69
- (void)setAttributedString:(ZAttributedString *)str; - (void)setAttributedString:(ZAttributedString *)str;
- (void)setAttributes:(NSDictionary *)attributes range:(NSRange)range; - (void)setAttributes:(NSDictionary *)attributes range:(NSRange)range;
@end @end
extern NSString * const ZFontAttributeName; extern NSString * const ZFontAttributeName;
extern NSString * const ZForegroundColorAttributeName; extern NSString * const ZForegroundColorAttributeName;
extern NSString * const ZBackgroundColorAttributeName; extern NSString * const ZBackgroundColorAttributeName;
extern NSString * const ZUnderlineStyleAttributeName; extern NSString * const ZUnderlineStyleAttributeName;
enum { enum {
ZUnderlineStyleNone = 0x00, ZUnderlineStyleNone = 0x00,
ZUnderlineStyleSingle = 0x01 ZUnderlineStyleSingle = 0x01
}; };
#define ZUnderlineStyleMask 0x00FF #define ZUnderlineStyleMask 0x00FF
enum { enum {
ZUnderlinePatternSolid = 0x0000 ZUnderlinePatternSolid = 0x0000
}; };
#define ZUnderlinePatternMask 0xFF00 #define ZUnderlinePatternMask 0xFF00
 End of changes. 6 change blocks. 
10 lines changed or deleted 10 lines changed or added


 ZAttributedStringPrivate.h   ZAttributedStringPrivate.h 
skipping to change at line 13 skipping to change at line 13
// FontLabel // FontLabel
// //
// Created by Kevin Ballard on 9/23/09. // Created by Kevin Ballard on 9/23/09.
// Copyright 2009 Zynga Game Networks. All rights reserved. // Copyright 2009 Zynga Game Networks. All rights reserved.
// //
#import <Foundation/Foundation.h> #import <Foundation/Foundation.h>
#import "ZAttributedString.h" #import "ZAttributedString.h"
@interface ZAttributeRun : NSObject <NSCopying, NSCoding> { @interface ZAttributeRun : NSObject <NSCopying, NSCoding> {
NSUInteger _index; NSUInteger _index;
NSMutableDictionary *_attributes; NSMutableDictionary *_attributes;
} }
@property (nonatomic, readonly) NSUInteger index; @property (nonatomic, readonly) NSUInteger index;
@property (nonatomic, readonly) NSMutableDictionary *attributes; @property (nonatomic, readonly) NSMutableDictionary *attributes;
+ (id)attributeRunWithIndex:(NSUInteger)idx attributes:(NSDictionary *)attr s; + (id)attributeRunWithIndex:(NSUInteger)idx attributes:(NSDictionary *)attr s;
- (id)initWithIndex:(NSUInteger)idx attributes:(NSDictionary *)attrs; - (id)initWithIndex:(NSUInteger)idx attributes:(NSDictionary *)attrs;
@end @end
@interface ZAttributedString (ZAttributedStringPrivate) @interface ZAttributedString (ZAttributedStringPrivate)
@property (nonatomic, readonly) NSArray *attributes; @property (nonatomic, readonly) NSArray *attributes;
@end @end
 End of changes. 1 change blocks. 
2 lines changed or deleted 2 lines changed or added


 ZFont.h   ZFont.h 
skipping to change at line 26 skipping to change at line 26
// distributed under the License is distributed on an "AS IS" BASIS, // distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
// //
#import <Foundation/Foundation.h> #import <Foundation/Foundation.h>
#import <UIKit/UIKit.h> #import <UIKit/UIKit.h>
@interface ZFont : NSObject { @interface ZFont : NSObject {
CGFontRef _cgFont; CGFontRef _cgFont;
CGFloat _pointSize; CGFloat _pointSize;
CGFloat _ratio; CGFloat _ratio;
NSString *_familyName; NSString *_familyName;
NSString *_fontName; NSString *_fontName;
NSString *_postScriptName; NSString *_postScriptName;
} }
@property (nonatomic, readonly) CGFontRef cgFont; @property (nonatomic, readonly) CGFontRef cgFont;
@property (nonatomic, readonly) CGFloat pointSize; @property (nonatomic, readonly) CGFloat pointSize;
@property (nonatomic, readonly) CGFloat ascender; @property (nonatomic, readonly) CGFloat ascender;
@property (nonatomic, readonly) CGFloat descender; @property (nonatomic, readonly) CGFloat descender;
@property (nonatomic, readonly) CGFloat leading; @property (nonatomic, readonly) CGFloat leading;
@property (nonatomic, readonly) CGFloat xHeight; @property (nonatomic, readonly) CGFloat xHeight;
@property (nonatomic, readonly) CGFloat capHeight; @property (nonatomic, readonly) CGFloat capHeight;
@property (nonatomic, readonly) NSString *familyName; @property (nonatomic, readonly) NSString *familyName;
@property (nonatomic, readonly) NSString *fontName; @property (nonatomic, readonly) NSString *fontName;
 End of changes. 1 change blocks. 
6 lines changed or deleted 6 lines changed or added


 ZipUtils.h   ZipUtils.h 
skipping to change at line 29 skipping to change at line 29
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __SUPPORT_ZIPUTILS_H__ #ifndef __SUPPORT_ZIPUTILS_H__
#define __SUPPORT_ZIPUTILS_H__ #define __SUPPORT_ZIPUTILS_H__
namespace cocos2d namespace cocos2d
{ {
/* XXX: pragma pack ??? */ /* XXX: pragma pack ??? */
/** @struct CCZHeader /** @struct CCZHeader
*/ */
struct CCZHeader { struct CCZHeader {
unsigned char sig[4]; unsigned char sig[4]; // signature. Shoul
// signature. Should be 'CCZ!' 4 bytes d be 'CCZ!' 4 bytes
unsigned short compression_type; // should 0 unsigned short compression_type; // should 0
unsigned short version; // s unsigned short version; // should be 2 (altho
hould be 2 (although version type==1 is also supported) ugh version type==1 is also supported)
unsigned int reserved; // R unsigned int reserved; // Reserverd for user
eserverd for users. s.
unsigned int len; unsigned int len; // size of the uncompre
// size of the uncompressed file ssed file
}; };
enum { enum {
CCZ_COMPRESSION_ZLIB, // zlib form CCZ_COMPRESSION_ZLIB, // zlib format.
at. CCZ_COMPRESSION_BZIP2, // bzip2 format (not supporte
CCZ_COMPRESSION_BZIP2, // bzip2 for d yet)
mat (not supported yet) CCZ_COMPRESSION_GZIP, // gzip format (not supported
CCZ_COMPRESSION_GZIP, // gzip form yet)
at (not supported yet) CCZ_COMPRESSION_NONE, // plain (not supported yet)
CCZ_COMPRESSION_NONE, // plain (no };
t supported yet)
};
class ZipUtils class ZipUtils
{ {
public: public:
/** /**
* Inflates either zlib or gzip deflated memory. The inflated * Inflates either zlib or gzip deflated memory. The inflated memory
memory is is
* expected to be freed by the caller. * expected to be freed by the caller.
* *
* It will allocate 256k for the destination buffer. If it is * It will allocate 256k for the destination buffer. If it is not en
not enought it will multiply the previous buffer size per 2, until there i ought it will multiply the previous buffer size per 2, until there is enoug
s enough memory. h memory.
* @returns the length of the deflated buffer * @returns the length of the deflated buffer
* *
@since v0.8.1 @since v0.8.1
*/ */
static int ccInflateMemory(unsigned char *in, unsigned int i static int ccInflateMemory(unsigned char *in, unsigned int inLength
nLength, unsigned char **out); , unsigned char **out);
/** /**
* Inflates either zlib or gzip deflated memory. The inflated * Inflates either zlib or gzip deflated memory. The inflated memory
memory is is
* expected to be freed by the caller. * expected to be freed by the caller.
* *
* outLenghtHint is assumed to be the needed room to allocate * outLenghtHint is assumed to be the needed room to allocate the in
the inflated buffer. flated buffer.
* *
* @returns the length of the deflated buffer * @returns the length of the deflated buffer
* *
@since v1.0.0 @since v1.0.0
*/ */
static int ccInflateMemoryWithHint(unsigned char *in, unsign static int ccInflateMemoryWithHint(unsigned char *in, unsigned int
ed int inLength, unsigned char **out, unsigned int outLenghtHint); inLength, unsigned char **out, unsigned int outLenghtHint);
/** inflates a GZip file into memory /** inflates a GZip file into memory
* *
* @returns the length of the deflated buffer * @returns the length of the deflated buffer
* *
* @since v0.99.5 * @since v0.99.5
*/ */
static int ccInflateGZipFile(const char *filename, unsigned static int ccInflateGZipFile(const char *filename, unsigned char **
char **out); out);
/** inflates a CCZ file into memory /** inflates a CCZ file into memory
* *
* @returns the length of the deflated buffer * @returns the length of the deflated buffer
* *
* @since v0.99.5 * @since v0.99.5
*/ */
static int ccInflateCCZFile(const char *filename, unsigned c static int ccInflateCCZFile(const char *filename, unsigned char **o
har **out); ut);
private: private:
static int ccInflateMemoryWithHint(unsigned char *in, unsign static int ccInflateMemoryWithHint(unsigned char *in, unsigned int
ed int inLength, unsigned char **out, unsigned int *outLength, inLength, unsigned char **out, unsigned int *outLength,
unsigned int outLenghtHint); unsigned int outLenghtHint);
}; };
} // end of namespace cocos2d } // end of namespace cocos2d
#endif // __PLATFORM_WOPHONE_ZIPUTILS_H__ #endif // __PLATFORM_WOPHONE_ZIPUTILS_H__
 End of changes. 2 change blocks. 
80 lines changed or deleted 78 lines changed or added


 ZwoptexTest.h   ZwoptexTest.h 
skipping to change at line 24 skipping to change at line 24
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
}; };
class ZwoptexGenericTest : public ZwoptexTest class ZwoptexGenericTest : public ZwoptexTest
{ {
public: public:
~ZwoptexGenericTest(); ~ZwoptexGenericTest();
virtual void onEnter(); virtual void onEnter();
void flipSprites(ccTime dt); void flipSprites(float dt);
void startIn05Secs(ccTime dt); void startIn05Secs(float dt);
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
protected: protected:
CCSprite * sprite1; CCSprite * sprite1;
CCSprite * sprite2; CCSprite * sprite2;
int counter; int counter;
}; };
class ZwoptexTestScene : public TestScene class ZwoptexTestScene : public TestScene
{ {
public: public:
virtual void runThisTest(); virtual void runThisTest();
SCENE_NODE_FUNC(ZwoptexTestScene); CREATE_FUNC(ZwoptexTestScene);
}; };
#endif // __ZWOPTEX_TEST_H__ #endif // __ZWOPTEX_TEST_H__
 End of changes. 4 change blocks. 
5 lines changed or deleted 5 lines changed or added


 b2BlockAllocator.h   b2BlockAllocator.h 
skipping to change at line 38 skipping to change at line 38
struct b2Block; struct b2Block;
struct b2Chunk; struct b2Chunk;
/// This is a small object allocator used for allocating small /// This is a small object allocator used for allocating small
/// objects that persist for more than one time step. /// objects that persist for more than one time step.
/// See: http://www.codeproject.com/useritems/Small_Block_Allocator.asp /// See: http://www.codeproject.com/useritems/Small_Block_Allocator.asp
class b2BlockAllocator class b2BlockAllocator
{ {
public: public:
b2BlockAllocator(); b2BlockAllocator();
~b2BlockAllocator(); ~b2BlockAllocator();
/// Allocate memory. This will use b2Alloc if the size is larger tha /// Allocate memory. This will use b2Alloc if the size is larger than b
n b2_maxBlockSize. 2_maxBlockSize.
void* Allocate(int32 size); void* Allocate(int32 size);
/// Free memory. This will use b2Free if the size is larger than b2_ /// Free memory. This will use b2Free if the size is larger than b2_max
maxBlockSize. BlockSize.
void Free(void* p, int32 size); void Free(void* p, int32 size);
void Clear(); void Clear();
private: private:
b2Chunk* m_chunks; b2Chunk* m_chunks;
int32 m_chunkCount; int32 m_chunkCount;
int32 m_chunkSpace; int32 m_chunkSpace;
b2Block* m_freeLists[b2_blockSizes]; b2Block* m_freeLists[b2_blockSizes];
static int32 s_blockSizes[b2_blockSizes]; static int32 s_blockSizes[b2_blockSizes];
static uint8 s_blockSizeLookup[b2_maxBlockSize + 1]; static uint8 s_blockSizeLookup[b2_maxBlockSize + 1];
static bool s_blockSizeLookupInitialized; static bool s_blockSizeLookupInitialized;
}; };
#endif #endif
 End of changes. 5 change blocks. 
18 lines changed or deleted 18 lines changed or added


 b2Body.h   b2Body.h 
skipping to change at line 41 skipping to change at line 41
struct b2FixtureDef; struct b2FixtureDef;
struct b2JointEdge; struct b2JointEdge;
struct b2ContactEdge; struct b2ContactEdge;
/// The body type. /// The body type.
/// static: zero mass, zero velocity, may be manually moved /// static: zero mass, zero velocity, may be manually moved
/// kinematic: zero mass, non-zero velocity set by user, moved by solver /// kinematic: zero mass, non-zero velocity set by user, moved by solver
/// dynamic: positive mass, non-zero velocity determined by forces, moved b y solver /// dynamic: positive mass, non-zero velocity determined by forces, moved b y solver
enum b2BodyType enum b2BodyType
{ {
b2_staticBody = 0, b2_staticBody = 0,
b2_kinematicBody, b2_kinematicBody,
b2_dynamicBody b2_dynamicBody
// TODO_ERIN // TODO_ERIN
//b2_bulletBody, //b2_bulletBody,
}; };
/// A body definition holds all the data needed to construct a rigid body. /// A body definition holds all the data needed to construct a rigid body.
/// You can safely re-use body definitions. Shapes are added to a body afte r construction. /// You can safely re-use body definitions. Shapes are added to a body afte r construction.
struct b2BodyDef struct b2BodyDef
{ {
/// This constructor sets the body definition default values. /// This constructor sets the body definition default values.
b2BodyDef() b2BodyDef()
{ {
userData = NULL; userData = NULL;
position.Set(0.0f, 0.0f); position.Set(0.0f, 0.0f);
angle = 0.0f; angle = 0.0f;
linearVelocity.Set(0.0f, 0.0f); linearVelocity.Set(0.0f, 0.0f);
angularVelocity = 0.0f; angularVelocity = 0.0f;
linearDamping = 0.0f; linearDamping = 0.0f;
angularDamping = 0.0f; angularDamping = 0.0f;
allowSleep = true; allowSleep = true;
awake = true; awake = true;
fixedRotation = false; fixedRotation = false;
bullet = false; bullet = false;
type = b2_staticBody; type = b2_staticBody;
active = true; active = true;
gravityScale = 1.0f; gravityScale = 1.0f;
} }
/// The body type: static, kinematic, or dynamic. /// The body type: static, kinematic, or dynamic.
/// Note: if a dynamic body would have zero mass, the mass is set to /// Note: if a dynamic body would have zero mass, the mass is set to on
one. e.
b2BodyType type; b2BodyType type;
/// The world position of the body. Avoid creating bodies at the ori /// The world position of the body. Avoid creating bodies at the origin
gin /// since this can lead to many overlapping shapes.
/// since this can lead to many overlapping shapes. b2Vec2 position;
b2Vec2 position;
/// The world angle of the body in radians.
/// The world angle of the body in radians. float32 angle;
float32 angle;
/// The linear velocity of the body's origin in world co-ordinates.
/// The linear velocity of the body's origin in world co-ordinates. b2Vec2 linearVelocity;
b2Vec2 linearVelocity;
/// The angular velocity of the body.
/// The angular velocity of the body. float32 angularVelocity;
float32 angularVelocity;
/// Linear damping is use to reduce the linear velocity. The damping pa
/// Linear damping is use to reduce the linear velocity. The damping rameter
parameter /// can be larger than 1.0f but the damping effect becomes sensitive to
/// can be larger than 1.0f but the damping effect becomes sensitive the
to the /// time step when the damping parameter is large.
/// time step when the damping parameter is large. float32 linearDamping;
float32 linearDamping;
/// Angular damping is use to reduce the angular velocity. The damping
/// Angular damping is use to reduce the angular velocity. The dampi parameter
ng parameter /// can be larger than 1.0f but the damping effect becomes sensitive to
/// can be larger than 1.0f but the damping effect becomes sensitive the
to the /// time step when the damping parameter is large.
/// time step when the damping parameter is large. float32 angularDamping;
float32 angularDamping;
/// Set this flag to false if this body should never fall asleep. Note
/// Set this flag to false if this body should never fall asleep. No that
te that /// this increases CPU usage.
/// this increases CPU usage. bool allowSleep;
bool allowSleep;
/// Is this body initially awake or sleeping?
/// Is this body initially awake or sleeping? bool awake;
bool awake;
/// Should this body be prevented from rotating? Useful for characters.
/// Should this body be prevented from rotating? Useful for characte bool fixedRotation;
rs.
bool fixedRotation; /// Is this a fast moving body that should be prevented from tunneling
through
/// Is this a fast moving body that should be prevented from tunneli /// other moving bodies? Note that all bodies are prevented from tunnel
ng through ing through
/// other moving bodies? Note that all bodies are prevented from tun /// kinematic and static bodies. This setting is only considered on dyn
neling through amic bodies.
/// kinematic and static bodies. This setting is only considered on /// @warning You should use this flag sparingly since it increases proc
dynamic bodies. essing time.
/// @warning You should use this flag sparingly since it increases p bool bullet;
rocessing time.
bool bullet;
/// Does this body start out active? /// Does this body start out active?
bool active; bool active;
/// Use this to store application specific body data. /// Use this to store application specific body data.
void* userData; void* userData;
/// Scale the gravity applied to this body. /// Scale the gravity applied to this body.
float32 gravityScale; float32 gravityScale;
}; };
/// A rigid body. These are created via b2World::CreateBody. /// A rigid body. These are created via b2World::CreateBody.
class b2Body class b2Body
{ {
public: public:
/// Creates a fixture and attach it to this body. Use this function /// Creates a fixture and attach it to this body. Use this function if
if you need you need
/// to set some fixture parameters, like friction. Otherwise you can /// to set some fixture parameters, like friction. Otherwise you can cr
create the eate the
/// fixture directly from a shape. /// fixture directly from a shape.
/// If the density is non-zero, this function automatically updates /// If the density is non-zero, this function automatically updates the
the mass of the body. mass of the body.
/// Contacts are not created until the next time step. /// Contacts are not created until the next time step.
/// @param def the fixture definition. /// @param def the fixture definition.
/// @warning This function is locked during callbacks. /// @warning This function is locked during callbacks.
b2Fixture* CreateFixture(const b2FixtureDef* def); b2Fixture* CreateFixture(const b2FixtureDef* def);
/// Creates a fixture from a shape and attach it to this body. /// Creates a fixture from a shape and attach it to this body.
/// This is a convenience function. Use b2FixtureDef if you need to /// This is a convenience function. Use b2FixtureDef if you need to set
set parameters parameters
/// like friction, restitution, user data, or filtering. /// like friction, restitution, user data, or filtering.
/// If the density is non-zero, this function automatically updates /// If the density is non-zero, this function automatically updates the
the mass of the body. mass of the body.
/// @param shape the shape to be cloned. /// @param shape the shape to be cloned.
/// @param density the shape density (set to zero for static bodies) /// @param density the shape density (set to zero for static bodies).
. /// @warning This function is locked during callbacks.
/// @warning This function is locked during callbacks. b2Fixture* CreateFixture(const b2Shape* shape, float32 density);
b2Fixture* CreateFixture(const b2Shape* shape, float32 density);
/// Destroy a fixture. This removes the fixture from the broad-phase an
/// Destroy a fixture. This removes the fixture from the broad-phase d
and /// destroys all contacts associated with this fixture. This will
/// destroys all contacts associated with this fixture. This will /// automatically adjust the mass of the body if the body is dynamic an
/// automatically adjust the mass of the body if the body is dynamic d the
and the /// fixture has positive density.
/// fixture has positive density. /// All fixtures attached to a body are implicitly destroyed when the b
/// All fixtures attached to a body are implicitly destroyed when th ody is destroyed.
e body is destroyed. /// @param fixture the fixture to be removed.
/// @param fixture the fixture to be removed. /// @warning This function is locked during callbacks.
/// @warning This function is locked during callbacks. void DestroyFixture(b2Fixture* fixture);
void DestroyFixture(b2Fixture* fixture);
/// Set the position of the body's origin and rotation.
/// Set the position of the body's origin and rotation. /// This breaks any contacts and wakes the other bodies.
/// This breaks any contacts and wakes the other bodies. /// Manipulating a body's transform may cause non-physical behavior.
/// Manipulating a body's transform may cause non-physical behavior. /// @param position the world position of the body's local origin.
/// @param position the world position of the body's local origin. /// @param angle the world rotation in radians.
/// @param angle the world rotation in radians. void SetTransform(const b2Vec2& position, float32 angle);
void SetTransform(const b2Vec2& position, float32 angle);
/// Get the body transform for the body's origin.
/// Get the body transform for the body's origin. /// @return the world transform of the body's origin.
/// @return the world transform of the body's origin. const b2Transform& GetTransform() const;
const b2Transform& GetTransform() const;
/// Get the world body origin position.
/// Get the world body origin position. /// @return the world position of the body's origin.
/// @return the world position of the body's origin. const b2Vec2& GetPosition() const;
const b2Vec2& GetPosition() const;
/// Get the angle in radians.
/// Get the angle in radians. /// @return the current world rotation angle in radians.
/// @return the current world rotation angle in radians. float32 GetAngle() const;
float32 GetAngle() const;
/// Get the world position of the center of mass.
/// Get the world position of the center of mass. const b2Vec2& GetWorldCenter() const;
const b2Vec2& GetWorldCenter() const;
/// Get the local position of the center of mass.
/// Get the local position of the center of mass. const b2Vec2& GetLocalCenter() const;
const b2Vec2& GetLocalCenter() const;
/// Set the linear velocity of the center of mass.
/// Set the linear velocity of the center of mass. /// @param v the new linear velocity of the center of mass.
/// @param v the new linear velocity of the center of mass. void SetLinearVelocity(const b2Vec2& v);
void SetLinearVelocity(const b2Vec2& v);
/// Get the linear velocity of the center of mass.
/// Get the linear velocity of the center of mass. /// @return the linear velocity of the center of mass.
/// @return the linear velocity of the center of mass. b2Vec2 GetLinearVelocity() const;
b2Vec2 GetLinearVelocity() const;
/// Set the angular velocity.
/// Set the angular velocity. /// @param omega the new angular velocity in radians/second.
/// @param omega the new angular velocity in radians/second. void SetAngularVelocity(float32 omega);
void SetAngularVelocity(float32 omega);
/// Get the angular velocity.
/// Get the angular velocity. /// @return the angular velocity in radians/second.
/// @return the angular velocity in radians/second. float32 GetAngularVelocity() const;
float32 GetAngularVelocity() const;
/// Apply a force at a world point. If the force is not
/// Apply a force at a world point. If the force is not /// applied at the center of mass, it will generate a torque and
/// applied at the center of mass, it will generate a torque and /// affect the angular velocity. This wakes up the body.
/// affect the angular velocity. This wakes up the body. /// @param force the world force vector, usually in Newtons (N).
/// @param force the world force vector, usually in Newtons (N). /// @param point the world position of the point of application.
/// @param point the world position of the point of application. void ApplyForce(const b2Vec2& force, const b2Vec2& point);
void ApplyForce(const b2Vec2& force, const b2Vec2& point);
/// Apply a force to the center of mass. This wakes up the body.
/// Apply a force to the center of mass. This wakes up the body. /// @param force the world force vector, usually in Newtons (N).
/// @param force the world force vector, usually in Newtons (N). void ApplyForceToCenter(const b2Vec2& force);
void ApplyForceToCenter(const b2Vec2& force);
/// Apply a torque. This affects the angular velocity
/// Apply a torque. This affects the angular velocity /// without affecting the linear velocity of the center of mass.
/// without affecting the linear velocity of the center of mass. /// This wakes up the body.
/// This wakes up the body. /// @param torque about the z-axis (out of the screen), usually in N-m.
/// @param torque about the z-axis (out of the screen), usually in N void ApplyTorque(float32 torque);
-m.
void ApplyTorque(float32 torque); /// Apply an impulse at a point. This immediately modifies the velocity
.
/// Apply an impulse at a point. This immediately modifies the veloc /// It also modifies the angular velocity if the point of application
ity. /// is not at the center of mass. This wakes up the body.
/// It also modifies the angular velocity if the point of applicatio /// @param impulse the world impulse vector, usually in N-seconds or kg
n -m/s.
/// is not at the center of mass. This wakes up the body. /// @param point the world position of the point of application.
/// @param impulse the world impulse vector, usually in N-seconds or void ApplyLinearImpulse(const b2Vec2& impulse, const b2Vec2& point);
kg-m/s.
/// @param point the world position of the point of application. /// Apply an angular impulse.
void ApplyLinearImpulse(const b2Vec2& impulse, const b2Vec2& point); /// @param impulse the angular impulse in units of kg*m*m/s
void ApplyAngularImpulse(float32 impulse);
/// Apply an angular impulse.
/// @param impulse the angular impulse in units of kg*m*m/s /// Get the total mass of the body.
void ApplyAngularImpulse(float32 impulse); /// @return the mass, usually in kilograms (kg).
float32 GetMass() const;
/// Get the total mass of the body.
/// @return the mass, usually in kilograms (kg). /// Get the rotational inertia of the body about the local origin.
float32 GetMass() const; /// @return the rotational inertia, usually in kg-m^2.
float32 GetInertia() const;
/// Get the rotational inertia of the body about the local origin.
/// @return the rotational inertia, usually in kg-m^2. /// Get the mass data of the body.
float32 GetInertia() const; /// @return a struct containing the mass, inertia and center of the bod
y.
/// Get the mass data of the body. void GetMassData(b2MassData* data) const;
/// @return a struct containing the mass, inertia and center of the
body. /// Set the mass properties to override the mass properties of the fixt
void GetMassData(b2MassData* data) const; ures.
/// Note that this changes the center of mass position.
/// Set the mass properties to override the mass properties of the f /// Note that creating or destroying fixtures can also alter the mass.
ixtures. /// This function has no effect if the body isn't dynamic.
/// Note that this changes the center of mass position. /// @param massData the mass properties.
/// Note that creating or destroying fixtures can also alter the mas void SetMassData(const b2MassData* data);
s.
/// This function has no effect if the body isn't dynamic. /// This resets the mass properties to the sum of the mass properties o
/// @param massData the mass properties. f the fixtures.
void SetMassData(const b2MassData* data); /// This normally does not need to be called unless you called SetMassD
ata to override
/// This resets the mass properties to the sum of the mass propertie /// the mass and you later want to reset the mass.
s of the fixtures. void ResetMassData();
/// This normally does not need to be called unless you called SetMa
ssData to override /// Get the world coordinates of a point given the local coordinates.
/// the mass and you later want to reset the mass. /// @param localPoint a point on the body measured relative the the bod
void ResetMassData(); y's origin.
/// @return the same point expressed in world coordinates.
/// Get the world coordinates of a point given the local coordinates b2Vec2 GetWorldPoint(const b2Vec2& localPoint) const;
.
/// @param localPoint a point on the body measured relative the the /// Get the world coordinates of a vector given the local coordinates.
body's origin. /// @param localVector a vector fixed in the body.
/// @return the same point expressed in world coordinates. /// @return the same vector expressed in world coordinates.
b2Vec2 GetWorldPoint(const b2Vec2& localPoint) const; b2Vec2 GetWorldVector(const b2Vec2& localVector) const;
/// Get the world coordinates of a vector given the local coordinate /// Gets a local point relative to the body's origin given a world poin
s. t.
/// @param localVector a vector fixed in the body. /// @param a point in world coordinates.
/// @return the same vector expressed in world coordinates. /// @return the corresponding local point relative to the body's origin
b2Vec2 GetWorldVector(const b2Vec2& localVector) const; .
b2Vec2 GetLocalPoint(const b2Vec2& worldPoint) const;
/// Gets a local point relative to the body's origin given a world p
oint. /// Gets a local vector given a world vector.
/// @param a point in world coordinates. /// @param a vector in world coordinates.
/// @return the corresponding local point relative to the body's ori /// @return the corresponding local vector.
gin. b2Vec2 GetLocalVector(const b2Vec2& worldVector) const;
b2Vec2 GetLocalPoint(const b2Vec2& worldPoint) const;
/// Get the world linear velocity of a world point attached to this bod
/// Gets a local vector given a world vector. y.
/// @param a vector in world coordinates. /// @param a point in world coordinates.
/// @return the corresponding local vector. /// @return the world velocity of a point.
b2Vec2 GetLocalVector(const b2Vec2& worldVector) const; b2Vec2 GetLinearVelocityFromWorldPoint(const b2Vec2& worldPoint) const;
/// Get the world linear velocity of a world point attached to this /// Get the world velocity of a local point.
body. /// @param a point in local coordinates.
/// @param a point in world coordinates. /// @return the world velocity of a point.
/// @return the world velocity of a point. b2Vec2 GetLinearVelocityFromLocalPoint(const b2Vec2& localPoint) const;
b2Vec2 GetLinearVelocityFromWorldPoint(const b2Vec2& worldPoint) con
st; /// Get the linear damping of the body.
float32 GetLinearDamping() const;
/// Get the world velocity of a local point.
/// @param a point in local coordinates. /// Set the linear damping of the body.
/// @return the world velocity of a point. void SetLinearDamping(float32 linearDamping);
b2Vec2 GetLinearVelocityFromLocalPoint(const b2Vec2& localPoint) con
st; /// Get the angular damping of the body.
float32 GetAngularDamping() const;
/// Get the linear damping of the body.
float32 GetLinearDamping() const; /// Set the angular damping of the body.
void SetAngularDamping(float32 angularDamping);
/// Set the linear damping of the body.
void SetLinearDamping(float32 linearDamping); /// Get the gravity scale of the body.
float32 GetGravityScale() const;
/// Get the angular damping of the body.
float32 GetAngularDamping() const; /// Set the gravity scale of the body.
void SetGravityScale(float32 scale);
/// Set the angular damping of the body.
void SetAngularDamping(float32 angularDamping); /// Set the type of this body. This may alter the mass and velocity.
void SetType(b2BodyType type);
/// Get the gravity scale of the body.
float32 GetGravityScale() const; /// Get the type of this body.
b2BodyType GetType() const;
/// Set the gravity scale of the body.
void SetGravityScale(float32 scale); /// Should this body be treated like a bullet for continuous collision
detection?
/// Set the type of this body. This may alter the mass and velocity. void SetBullet(bool flag);
void SetType(b2BodyType type);
/// Is this body treated like a bullet for continuous collision detecti
/// Get the type of this body. on?
b2BodyType GetType() const; bool IsBullet() const;
/// Should this body be treated like a bullet for continuous collisi /// You can disable sleeping on this body. If you disable sleeping, the
on detection? /// body will be woken.
void SetBullet(bool flag); void SetSleepingAllowed(bool flag);
/// Is this body treated like a bullet for continuous collision dete /// Is this body allowed to sleep
ction? bool IsSleepingAllowed() const;
bool IsBullet() const;
/// Set the sleep state of the body. A sleeping body has very
/// You can disable sleeping on this body. If you disable sleeping, /// low CPU cost.
the /// @param flag set to true to put body to sleep, false to wake it.
/// body will be woken. void SetAwake(bool flag);
void SetSleepingAllowed(bool flag);
/// Get the sleeping state of this body.
/// Is this body allowed to sleep /// @return true if the body is sleeping.
bool IsSleepingAllowed() const; bool IsAwake() const;
/// Set the sleep state of the body. A sleeping body has very /// Set the active state of the body. An inactive body is not
/// low CPU cost. /// simulated and cannot be collided with or woken up.
/// @param flag set to true to put body to sleep, false to wake it. /// If you pass a flag of true, all fixtures will be added to the
void SetAwake(bool flag); /// broad-phase.
/// If you pass a flag of false, all fixtures will be removed from
/// Get the sleeping state of this body. /// the broad-phase and all contacts will be destroyed.
/// @return true if the body is sleeping. /// Fixtures and joints are otherwise unaffected. You may continue
bool IsAwake() const; /// to create/destroy fixtures and joints on inactive bodies.
/// Fixtures on an inactive body are implicitly inactive and will
/// Set the active state of the body. An inactive body is not /// not participate in collisions, ray-casts, or queries.
/// simulated and cannot be collided with or woken up. /// Joints connected to an inactive body are implicitly inactive.
/// If you pass a flag of true, all fixtures will be added to the /// An inactive body is still owned by a b2World object and remains
/// broad-phase. /// in the body list.
/// If you pass a flag of false, all fixtures will be removed from void SetActive(bool flag);
/// the broad-phase and all contacts will be destroyed.
/// Fixtures and joints are otherwise unaffected. You may continue /// Get the active state of the body.
/// to create/destroy fixtures and joints on inactive bodies. bool IsActive() const;
/// Fixtures on an inactive body are implicitly inactive and will
/// not participate in collisions, ray-casts, or queries. /// Set this body to have fixed rotation. This causes the mass
/// Joints connected to an inactive body are implicitly inactive. /// to be reset.
/// An inactive body is still owned by a b2World object and remains void SetFixedRotation(bool flag);
/// in the body list.
void SetActive(bool flag); /// Does this body have fixed rotation?
bool IsFixedRotation() const;
/// Get the active state of the body.
bool IsActive() const; /// Get the list of all fixtures attached to this body.
b2Fixture* GetFixtureList();
/// Set this body to have fixed rotation. This causes the mass const b2Fixture* GetFixtureList() const;
/// to be reset.
void SetFixedRotation(bool flag); /// Get the list of all joints attached to this body.
b2JointEdge* GetJointList();
/// Does this body have fixed rotation? const b2JointEdge* GetJointList() const;
bool IsFixedRotation() const;
/// Get the list of all contacts attached to this body.
/// Get the list of all fixtures attached to this body. /// @warning this list changes during the time step and you may
b2Fixture* GetFixtureList(); /// miss some collisions if you don't use b2ContactListener.
const b2Fixture* GetFixtureList() const; b2ContactEdge* GetContactList();
const b2ContactEdge* GetContactList() const;
/// Get the list of all joints attached to this body.
b2JointEdge* GetJointList(); /// Get the next body in the world's body list.
const b2JointEdge* GetJointList() const; b2Body* GetNext();
const b2Body* GetNext() const;
/// Get the list of all contacts attached to this body.
/// @warning this list changes during the time step and you may /// Get the user data pointer that was provided in the body definition.
/// miss some collisions if you don't use b2ContactListener. void* GetUserData() const;
b2ContactEdge* GetContactList();
const b2ContactEdge* GetContactList() const; /// Set the user data. Use this to store your application specific data
.
/// Get the next body in the world's body list. void SetUserData(void* data);
b2Body* GetNext();
const b2Body* GetNext() const; /// Get the parent world of this body.
b2World* GetWorld();
/// Get the user data pointer that was provided in the body definiti const b2World* GetWorld() const;
on.
void* GetUserData() const;
/// Set the user data. Use this to store your application specific d
ata.
void SetUserData(void* data);
/// Get the parent world of this body.
b2World* GetWorld();
const b2World* GetWorld() const;
/// Dump this body to a log file /// Dump this body to a log file
void Dump(); void Dump();
private: private:
friend class b2World; friend class b2World;
friend class b2Island; friend class b2Island;
friend class b2ContactManager; friend class b2ContactManager;
friend class b2ContactSolver; friend class b2ContactSolver;
friend class b2Contact; friend class b2Contact;
friend class b2DistanceJoint; friend class b2DistanceJoint;
friend class b2GearJoint; friend class b2GearJoint;
friend class b2WheelJoint; friend class b2WheelJoint;
friend class b2MouseJoint; friend class b2MouseJoint;
friend class b2PrismaticJoint; friend class b2PrismaticJoint;
friend class b2PulleyJoint; friend class b2PulleyJoint;
friend class b2RevoluteJoint; friend class b2RevoluteJoint;
friend class b2WeldJoint; friend class b2WeldJoint;
friend class b2FrictionJoint; friend class b2FrictionJoint;
friend class b2RopeJoint; friend class b2RopeJoint;
// m_flags // m_flags
enum enum
{ {
e_islandFlag = 0x0001, e_islandFlag = 0x0001,
e_awakeFlag = 0x0002, e_awakeFlag = 0x0002,
e_autoSleepFlag = 0x0004, e_autoSleepFlag = 0x0004,
e_bulletFlag = 0x0008, e_bulletFlag = 0x0008,
e_fixedRotationFlag = 0x0010, e_fixedRotationFlag = 0x0010,
e_activeFlag = 0x0020, e_activeFlag = 0x0020,
e_toiFlag = 0x0040 e_toiFlag = 0x0040
}; };
b2Body(const b2BodyDef* bd, b2World* world); b2Body(const b2BodyDef* bd, b2World* world);
~b2Body(); ~b2Body();
void SynchronizeFixtures(); void SynchronizeFixtures();
void SynchronizeTransform(); void SynchronizeTransform();
// This is used to prevent connected bodies from colliding. // This is used to prevent connected bodies from colliding.
// It may lie, depending on the collideConnected flag. // It may lie, depending on the collideConnected flag.
bool ShouldCollide(const b2Body* other) const; bool ShouldCollide(const b2Body* other) const;
void Advance(float32 t); void Advance(float32 t);
b2BodyType m_type; b2BodyType m_type;
uint16 m_flags; uint16 m_flags;
int32 m_islandIndex; int32 m_islandIndex;
b2Transform m_xf; // the body origin transform b2Transform m_xf; // the body origin transform
b2Sweep m_sweep; // the swept motion for CCD b2Sweep m_sweep; // the swept motion for CCD
b2Vec2 m_linearVelocity; b2Vec2 m_linearVelocity;
float32 m_angularVelocity; float32 m_angularVelocity;
b2Vec2 m_force; b2Vec2 m_force;
float32 m_torque; float32 m_torque;
b2World* m_world; b2World* m_world;
b2Body* m_prev; b2Body* m_prev;
b2Body* m_next; b2Body* m_next;
b2Fixture* m_fixtureList; b2Fixture* m_fixtureList;
int32 m_fixtureCount; int32 m_fixtureCount;
b2JointEdge* m_jointList; b2JointEdge* m_jointList;
b2ContactEdge* m_contactList; b2ContactEdge* m_contactList;
float32 m_mass, m_invMass; float32 m_mass, m_invMass;
// Rotational inertia about the center of mass. // Rotational inertia about the center of mass.
float32 m_I, m_invI; float32 m_I, m_invI;
float32 m_linearDamping; float32 m_linearDamping;
float32 m_angularDamping; float32 m_angularDamping;
float32 m_gravityScale; float32 m_gravityScale;
float32 m_sleepTime; float32 m_sleepTime;
void* m_userData; void* m_userData;
}; };
inline b2BodyType b2Body::GetType() const inline b2BodyType b2Body::GetType() const
{ {
return m_type; return m_type;
} }
inline const b2Transform& b2Body::GetTransform() const inline const b2Transform& b2Body::GetTransform() const
{ {
return m_xf; return m_xf;
} }
inline const b2Vec2& b2Body::GetPosition() const inline const b2Vec2& b2Body::GetPosition() const
{ {
return m_xf.p; return m_xf.p;
} }
inline float32 b2Body::GetAngle() const inline float32 b2Body::GetAngle() const
{ {
return m_sweep.a; return m_sweep.a;
} }
inline const b2Vec2& b2Body::GetWorldCenter() const inline const b2Vec2& b2Body::GetWorldCenter() const
{ {
return m_sweep.c; return m_sweep.c;
} }
inline const b2Vec2& b2Body::GetLocalCenter() const inline const b2Vec2& b2Body::GetLocalCenter() const
{ {
return m_sweep.localCenter; return m_sweep.localCenter;
} }
inline void b2Body::SetLinearVelocity(const b2Vec2& v) inline void b2Body::SetLinearVelocity(const b2Vec2& v)
{ {
if (m_type == b2_staticBody) if (m_type == b2_staticBody)
{ {
return; return;
} }
if (b2Dot(v,v) > 0.0f) if (b2Dot(v,v) > 0.0f)
{ {
SetAwake(true); SetAwake(true);
} }
m_linearVelocity = v; m_linearVelocity = v;
} }
inline b2Vec2 b2Body::GetLinearVelocity() const inline b2Vec2 b2Body::GetLinearVelocity() const
{ {
return m_linearVelocity; return m_linearVelocity;
} }
inline void b2Body::SetAngularVelocity(float32 w) inline void b2Body::SetAngularVelocity(float32 w)
{ {
if (m_type == b2_staticBody) if (m_type == b2_staticBody)
{ {
return; return;
} }
if (w * w > 0.0f) if (w * w > 0.0f)
{ {
SetAwake(true); SetAwake(true);
} }
m_angularVelocity = w; m_angularVelocity = w;
} }
inline float32 b2Body::GetAngularVelocity() const inline float32 b2Body::GetAngularVelocity() const
{ {
return m_angularVelocity; return m_angularVelocity;
} }
inline float32 b2Body::GetMass() const inline float32 b2Body::GetMass() const
{ {
return m_mass; return m_mass;
} }
inline float32 b2Body::GetInertia() const inline float32 b2Body::GetInertia() const
{ {
return m_I + m_mass * b2Dot(m_sweep.localCenter, m_sweep.localCenter ); return m_I + m_mass * b2Dot(m_sweep.localCenter, m_sweep.localCenter);
} }
inline void b2Body::GetMassData(b2MassData* data) const inline void b2Body::GetMassData(b2MassData* data) const
{ {
data->mass = m_mass; data->mass = m_mass;
data->I = m_I + m_mass * b2Dot(m_sweep.localCenter, m_sweep.localCen data->I = m_I + m_mass * b2Dot(m_sweep.localCenter, m_sweep.localCenter
ter); );
data->center = m_sweep.localCenter; data->center = m_sweep.localCenter;
} }
inline b2Vec2 b2Body::GetWorldPoint(const b2Vec2& localPoint) const inline b2Vec2 b2Body::GetWorldPoint(const b2Vec2& localPoint) const
{ {
return b2Mul(m_xf, localPoint); return b2Mul(m_xf, localPoint);
} }
inline b2Vec2 b2Body::GetWorldVector(const b2Vec2& localVector) const inline b2Vec2 b2Body::GetWorldVector(const b2Vec2& localVector) const
{ {
return b2Mul(m_xf.q, localVector); return b2Mul(m_xf.q, localVector);
} }
inline b2Vec2 b2Body::GetLocalPoint(const b2Vec2& worldPoint) const inline b2Vec2 b2Body::GetLocalPoint(const b2Vec2& worldPoint) const
{ {
return b2MulT(m_xf, worldPoint); return b2MulT(m_xf, worldPoint);
} }
inline b2Vec2 b2Body::GetLocalVector(const b2Vec2& worldVector) const inline b2Vec2 b2Body::GetLocalVector(const b2Vec2& worldVector) const
{ {
return b2MulT(m_xf.q, worldVector); return b2MulT(m_xf.q, worldVector);
} }
inline b2Vec2 b2Body::GetLinearVelocityFromWorldPoint(const b2Vec2& worldPo int) const inline b2Vec2 b2Body::GetLinearVelocityFromWorldPoint(const b2Vec2& worldPo int) const
{ {
return m_linearVelocity + b2Cross(m_angularVelocity, worldPoint - m_ sweep.c); return m_linearVelocity + b2Cross(m_angularVelocity, worldPoint - m_swe ep.c);
} }
inline b2Vec2 b2Body::GetLinearVelocityFromLocalPoint(const b2Vec2& localPo int) const inline b2Vec2 b2Body::GetLinearVelocityFromLocalPoint(const b2Vec2& localPo int) const
{ {
return GetLinearVelocityFromWorldPoint(GetWorldPoint(localPoint)); return GetLinearVelocityFromWorldPoint(GetWorldPoint(localPoint));
} }
inline float32 b2Body::GetLinearDamping() const inline float32 b2Body::GetLinearDamping() const
{ {
return m_linearDamping; return m_linearDamping;
} }
inline void b2Body::SetLinearDamping(float32 linearDamping) inline void b2Body::SetLinearDamping(float32 linearDamping)
{ {
m_linearDamping = linearDamping; m_linearDamping = linearDamping;
} }
inline float32 b2Body::GetAngularDamping() const inline float32 b2Body::GetAngularDamping() const
{ {
return m_angularDamping; return m_angularDamping;
} }
inline void b2Body::SetAngularDamping(float32 angularDamping) inline void b2Body::SetAngularDamping(float32 angularDamping)
{ {
m_angularDamping = angularDamping; m_angularDamping = angularDamping;
} }
inline float32 b2Body::GetGravityScale() const inline float32 b2Body::GetGravityScale() const
{ {
return m_gravityScale; return m_gravityScale;
} }
inline void b2Body::SetGravityScale(float32 scale) inline void b2Body::SetGravityScale(float32 scale)
{ {
m_gravityScale = scale; m_gravityScale = scale;
} }
inline void b2Body::SetBullet(bool flag) inline void b2Body::SetBullet(bool flag)
{ {
if (flag) if (flag)
{ {
m_flags |= e_bulletFlag; m_flags |= e_bulletFlag;
} }
else else
{ {
m_flags &= ~e_bulletFlag; m_flags &= ~e_bulletFlag;
} }
} }
inline bool b2Body::IsBullet() const inline bool b2Body::IsBullet() const
{ {
return (m_flags & e_bulletFlag) == e_bulletFlag; return (m_flags & e_bulletFlag) == e_bulletFlag;
} }
inline void b2Body::SetAwake(bool flag) inline void b2Body::SetAwake(bool flag)
{ {
if (flag) if (flag)
{ {
if ((m_flags & e_awakeFlag) == 0) if ((m_flags & e_awakeFlag) == 0)
{ {
m_flags |= e_awakeFlag; m_flags |= e_awakeFlag;
m_sleepTime = 0.0f; m_sleepTime = 0.0f;
} }
} }
else else
{ {
m_flags &= ~e_awakeFlag; m_flags &= ~e_awakeFlag;
m_sleepTime = 0.0f; m_sleepTime = 0.0f;
m_linearVelocity.SetZero(); m_linearVelocity.SetZero();
m_angularVelocity = 0.0f; m_angularVelocity = 0.0f;
m_force.SetZero(); m_force.SetZero();
m_torque = 0.0f; m_torque = 0.0f;
} }
} }
inline bool b2Body::IsAwake() const inline bool b2Body::IsAwake() const
{ {
return (m_flags & e_awakeFlag) == e_awakeFlag; return (m_flags & e_awakeFlag) == e_awakeFlag;
} }
inline bool b2Body::IsActive() const inline bool b2Body::IsActive() const
{ {
return (m_flags & e_activeFlag) == e_activeFlag; return (m_flags & e_activeFlag) == e_activeFlag;
} }
inline void b2Body::SetFixedRotation(bool flag) inline void b2Body::SetFixedRotation(bool flag)
{ {
if (flag) if (flag)
{ {
m_flags |= e_fixedRotationFlag; m_flags |= e_fixedRotationFlag;
} }
else else
{ {
m_flags &= ~e_fixedRotationFlag; m_flags &= ~e_fixedRotationFlag;
} }
ResetMassData(); ResetMassData();
} }
inline bool b2Body::IsFixedRotation() const inline bool b2Body::IsFixedRotation() const
{ {
return (m_flags & e_fixedRotationFlag) == e_fixedRotationFlag; return (m_flags & e_fixedRotationFlag) == e_fixedRotationFlag;
} }
inline void b2Body::SetSleepingAllowed(bool flag) inline void b2Body::SetSleepingAllowed(bool flag)
{ {
if (flag) if (flag)
{ {
m_flags |= e_autoSleepFlag; m_flags |= e_autoSleepFlag;
} }
else else
{ {
m_flags &= ~e_autoSleepFlag; m_flags &= ~e_autoSleepFlag;
SetAwake(true); SetAwake(true);
} }
} }
inline bool b2Body::IsSleepingAllowed() const inline bool b2Body::IsSleepingAllowed() const
{ {
return (m_flags & e_autoSleepFlag) == e_autoSleepFlag; return (m_flags & e_autoSleepFlag) == e_autoSleepFlag;
} }
inline b2Fixture* b2Body::GetFixtureList() inline b2Fixture* b2Body::GetFixtureList()
{ {
return m_fixtureList; return m_fixtureList;
} }
inline const b2Fixture* b2Body::GetFixtureList() const inline const b2Fixture* b2Body::GetFixtureList() const
{ {
return m_fixtureList; return m_fixtureList;
} }
inline b2JointEdge* b2Body::GetJointList() inline b2JointEdge* b2Body::GetJointList()
{ {
return m_jointList; return m_jointList;
} }
inline const b2JointEdge* b2Body::GetJointList() const inline const b2JointEdge* b2Body::GetJointList() const
{ {
return m_jointList; return m_jointList;
} }
inline b2ContactEdge* b2Body::GetContactList() inline b2ContactEdge* b2Body::GetContactList()
{ {
return m_contactList; return m_contactList;
} }
inline const b2ContactEdge* b2Body::GetContactList() const inline const b2ContactEdge* b2Body::GetContactList() const
{ {
return m_contactList; return m_contactList;
} }
inline b2Body* b2Body::GetNext() inline b2Body* b2Body::GetNext()
{ {
return m_next; return m_next;
} }
inline const b2Body* b2Body::GetNext() const inline const b2Body* b2Body::GetNext() const
{ {
return m_next; return m_next;
} }
inline void b2Body::SetUserData(void* data) inline void b2Body::SetUserData(void* data)
{ {
m_userData = data; m_userData = data;
} }
inline void* b2Body::GetUserData() const inline void* b2Body::GetUserData() const
{ {
return m_userData; return m_userData;
} }
inline void b2Body::ApplyForce(const b2Vec2& force, const b2Vec2& point) inline void b2Body::ApplyForce(const b2Vec2& force, const b2Vec2& point)
{ {
if (m_type != b2_dynamicBody) if (m_type != b2_dynamicBody)
{ {
return; return;
} }
if (IsAwake() == false) if (IsAwake() == false)
{ {
SetAwake(true); SetAwake(true);
} }
m_force += force; m_force += force;
m_torque += b2Cross(point - m_sweep.c, force); m_torque += b2Cross(point - m_sweep.c, force);
} }
inline void b2Body::ApplyForceToCenter(const b2Vec2& force) inline void b2Body::ApplyForceToCenter(const b2Vec2& force)
{ {
if (m_type != b2_dynamicBody) if (m_type != b2_dynamicBody)
{ {
return; return;
} }
if (IsAwake() == false) if (IsAwake() == false)
{ {
SetAwake(true); SetAwake(true);
} }
m_force += force; m_force += force;
} }
inline void b2Body::ApplyTorque(float32 torque) inline void b2Body::ApplyTorque(float32 torque)
{ {
if (m_type != b2_dynamicBody) if (m_type != b2_dynamicBody)
{ {
return; return;
} }
if (IsAwake() == false) if (IsAwake() == false)
{ {
SetAwake(true); SetAwake(true);
} }
m_torque += torque; m_torque += torque;
} }
inline void b2Body::ApplyLinearImpulse(const b2Vec2& impulse, const b2Vec2& point) inline void b2Body::ApplyLinearImpulse(const b2Vec2& impulse, const b2Vec2& point)
{ {
if (m_type != b2_dynamicBody) if (m_type != b2_dynamicBody)
{ {
return; return;
} }
if (IsAwake() == false) if (IsAwake() == false)
{ {
SetAwake(true); SetAwake(true);
} }
m_linearVelocity += m_invMass * impulse; m_linearVelocity += m_invMass * impulse;
m_angularVelocity += m_invI * b2Cross(point - m_sweep.c, impulse); m_angularVelocity += m_invI * b2Cross(point - m_sweep.c, impulse);
} }
inline void b2Body::ApplyAngularImpulse(float32 impulse) inline void b2Body::ApplyAngularImpulse(float32 impulse)
{ {
if (m_type != b2_dynamicBody) if (m_type != b2_dynamicBody)
{ {
return; return;
} }
if (IsAwake() == false) if (IsAwake() == false)
{ {
SetAwake(true); SetAwake(true);
} }
m_angularVelocity += m_invI * impulse; m_angularVelocity += m_invI * impulse;
} }
inline void b2Body::SynchronizeTransform() inline void b2Body::SynchronizeTransform()
{ {
m_xf.q.Set(m_sweep.a); m_xf.q.Set(m_sweep.a);
m_xf.p = m_sweep.c - b2Mul(m_xf.q, m_sweep.localCenter); m_xf.p = m_sweep.c - b2Mul(m_xf.q, m_sweep.localCenter);
} }
inline void b2Body::Advance(float32 alpha) inline void b2Body::Advance(float32 alpha)
{ {
// Advance to the new safe time. This doesn't sync the broad-phase. // Advance to the new safe time. This doesn't sync the broad-phase.
m_sweep.Advance(alpha); m_sweep.Advance(alpha);
m_sweep.c = m_sweep.c0; m_sweep.c = m_sweep.c0;
m_sweep.a = m_sweep.a0; m_sweep.a = m_sweep.a0;
m_xf.q.Set(m_sweep.a); m_xf.q.Set(m_sweep.a);
m_xf.p = m_sweep.c - b2Mul(m_xf.q, m_sweep.localCenter); m_xf.p = m_sweep.c - b2Mul(m_xf.q, m_sweep.localCenter);
} }
inline b2World* b2Body::GetWorld() inline b2World* b2Body::GetWorld()
{ {
return m_world; return m_world;
} }
inline const b2World* b2Body::GetWorld() const inline const b2World* b2Body::GetWorld() const
{ {
return m_world; return m_world;
} }
#endif #endif
 End of changes. 88 change blocks. 
589 lines changed or deleted 577 lines changed or added


 b2BroadPhase.h   b2BroadPhase.h 
skipping to change at line 29 skipping to change at line 29
#ifndef B2_BROAD_PHASE_H #ifndef B2_BROAD_PHASE_H
#define B2_BROAD_PHASE_H #define B2_BROAD_PHASE_H
#include <Box2D/Common/b2Settings.h> #include <Box2D/Common/b2Settings.h>
#include <Box2D/Collision/b2Collision.h> #include <Box2D/Collision/b2Collision.h>
#include <Box2D/Collision/b2DynamicTree.h> #include <Box2D/Collision/b2DynamicTree.h>
#include <algorithm> #include <algorithm>
struct b2Pair struct b2Pair
{ {
int32 proxyIdA; int32 proxyIdA;
int32 proxyIdB; int32 proxyIdB;
int32 next; int32 next;
}; };
/// The broad-phase is used for computing pairs and performing volume queri es and ray casts. /// The broad-phase is used for computing pairs and performing volume queri es and ray casts.
/// This broad-phase does not persist pairs. Instead, this reports potentia lly new pairs. /// This broad-phase does not persist pairs. Instead, this reports potentia lly new pairs.
/// It is up to the client to consume the new pairs and to track subsequent overlap. /// It is up to the client to consume the new pairs and to track subsequent overlap.
class b2BroadPhase class b2BroadPhase
{ {
public: public:
enum enum
{ {
e_nullProxy = -1 e_nullProxy = -1
}; };
b2BroadPhase(); b2BroadPhase();
~b2BroadPhase(); ~b2BroadPhase();
/// Create a proxy with an initial AABB. Pairs are not reported unti /// Create a proxy with an initial AABB. Pairs are not reported until
l /// UpdatePairs is called.
/// UpdatePairs is called. int32 CreateProxy(const b2AABB& aabb, void* userData);
int32 CreateProxy(const b2AABB& aabb, void* userData);
/// Destroy a proxy. It is up to the client to remove any pairs.
/// Destroy a proxy. It is up to the client to remove any pairs. void DestroyProxy(int32 proxyId);
void DestroyProxy(int32 proxyId);
/// Call MoveProxy as many times as you like, then when you are done
/// Call MoveProxy as many times as you like, then when you are done /// call UpdatePairs to finalized the proxy pairs (for your time step).
/// call UpdatePairs to finalized the proxy pairs (for your time ste void MoveProxy(int32 proxyId, const b2AABB& aabb, const b2Vec2& displac
p). ement);
void MoveProxy(int32 proxyId, const b2AABB& aabb, const b2Vec2& disp
lacement); /// Call to trigger a re-processing of it's pairs on the next call to U
pdatePairs.
/// Call to trigger a re-processing of it's pairs on the next call t void TouchProxy(int32 proxyId);
o UpdatePairs.
void TouchProxy(int32 proxyId); /// Get the fat AABB for a proxy.
const b2AABB& GetFatAABB(int32 proxyId) const;
/// Get the fat AABB for a proxy.
const b2AABB& GetFatAABB(int32 proxyId) const; /// Get user data from a proxy. Returns NULL if the id is invalid.
void* GetUserData(int32 proxyId) const;
/// Get user data from a proxy. Returns NULL if the id is invalid.
void* GetUserData(int32 proxyId) const; /// Test overlap of fat AABBs.
bool TestOverlap(int32 proxyIdA, int32 proxyIdB) const;
/// Test overlap of fat AABBs.
bool TestOverlap(int32 proxyIdA, int32 proxyIdB) const; /// Get the number of proxies.
int32 GetProxyCount() const;
/// Get the number of proxies.
int32 GetProxyCount() const; /// Update the pairs. This results in pair callbacks. This can only add
pairs.
/// Update the pairs. This results in pair callbacks. This can only template <typename T>
add pairs. void UpdatePairs(T* callback);
template <typename T>
void UpdatePairs(T* callback); /// Query an AABB for overlapping proxies. The callback class
/// is called for each proxy that overlaps the supplied AABB.
/// Query an AABB for overlapping proxies. The callback class template <typename T>
/// is called for each proxy that overlaps the supplied AABB. void Query(T* callback, const b2AABB& aabb) const;
template <typename T>
void Query(T* callback, const b2AABB& aabb) const; /// Ray-cast against the proxies in the tree. This relies on the callba
ck
/// Ray-cast against the proxies in the tree. This relies on the cal /// to perform a exact ray-cast in the case were the proxy contains a s
lback hape.
/// to perform a exact ray-cast in the case were the proxy contains /// The callback also performs the any collision filtering. This has pe
a shape. rformance
/// The callback also performs the any collision filtering. This has /// roughly equal to k * log(n), where k is the number of collisions an
performance d n is the
/// roughly equal to k * log(n), where k is the number of collisions /// number of proxies in the tree.
and n is the /// @param input the ray-cast input data. The ray extends from p1 to p1
/// number of proxies in the tree. + maxFraction * (p2 - p1).
/// @param input the ray-cast input data. The ray extends from p1 to /// @param callback a callback class that is called for each proxy that
p1 + maxFraction * (p2 - p1). is hit by the ray.
/// @param callback a callback class that is called for each proxy t template <typename T>
hat is hit by the ray. void RayCast(T* callback, const b2RayCastInput& input) const;
template <typename T>
void RayCast(T* callback, const b2RayCastInput& input) const;
/// Get the height of the embedded tree. /// Get the height of the embedded tree.
int32 GetTreeHeight() const; int32 GetTreeHeight() const;
/// Get the balance of the embedded tree. /// Get the balance of the embedded tree.
int32 GetTreeBalance() const; int32 GetTreeBalance() const;
/// Get the quality metric of the embedded tree. /// Get the quality metric of the embedded tree.
float32 GetTreeQuality() const; float32 GetTreeQuality() const;
private: private:
friend class b2DynamicTree; friend class b2DynamicTree;
void BufferMove(int32 proxyId); void BufferMove(int32 proxyId);
void UnBufferMove(int32 proxyId); void UnBufferMove(int32 proxyId);
bool QueryCallback(int32 proxyId); bool QueryCallback(int32 proxyId);
b2DynamicTree m_tree; b2DynamicTree m_tree;
int32 m_proxyCount; int32 m_proxyCount;
int32* m_moveBuffer; int32* m_moveBuffer;
int32 m_moveCapacity; int32 m_moveCapacity;
int32 m_moveCount; int32 m_moveCount;
b2Pair* m_pairBuffer; b2Pair* m_pairBuffer;
int32 m_pairCapacity; int32 m_pairCapacity;
int32 m_pairCount; int32 m_pairCount;
int32 m_queryProxyId; int32 m_queryProxyId;
}; };
/// This is used to sort pairs. /// This is used to sort pairs.
inline bool b2PairLessThan(const b2Pair& pair1, const b2Pair& pair2) inline bool b2PairLessThan(const b2Pair& pair1, const b2Pair& pair2)
{ {
if (pair1.proxyIdA < pair2.proxyIdA) if (pair1.proxyIdA < pair2.proxyIdA)
{ {
return true; return true;
} }
if (pair1.proxyIdA == pair2.proxyIdA) if (pair1.proxyIdA == pair2.proxyIdA)
{ {
return pair1.proxyIdB < pair2.proxyIdB; return pair1.proxyIdB < pair2.proxyIdB;
} }
return false; return false;
} }
inline void* b2BroadPhase::GetUserData(int32 proxyId) const inline void* b2BroadPhase::GetUserData(int32 proxyId) const
{ {
return m_tree.GetUserData(proxyId); return m_tree.GetUserData(proxyId);
} }
inline bool b2BroadPhase::TestOverlap(int32 proxyIdA, int32 proxyIdB) const inline bool b2BroadPhase::TestOverlap(int32 proxyIdA, int32 proxyIdB) const
{ {
const b2AABB& aabbA = m_tree.GetFatAABB(proxyIdA); const b2AABB& aabbA = m_tree.GetFatAABB(proxyIdA);
const b2AABB& aabbB = m_tree.GetFatAABB(proxyIdB); const b2AABB& aabbB = m_tree.GetFatAABB(proxyIdB);
return b2TestOverlap(aabbA, aabbB); return b2TestOverlap(aabbA, aabbB);
} }
inline const b2AABB& b2BroadPhase::GetFatAABB(int32 proxyId) const inline const b2AABB& b2BroadPhase::GetFatAABB(int32 proxyId) const
{ {
return m_tree.GetFatAABB(proxyId); return m_tree.GetFatAABB(proxyId);
} }
inline int32 b2BroadPhase::GetProxyCount() const inline int32 b2BroadPhase::GetProxyCount() const
{ {
return m_proxyCount; return m_proxyCount;
} }
inline int32 b2BroadPhase::GetTreeHeight() const inline int32 b2BroadPhase::GetTreeHeight() const
{ {
return m_tree.GetHeight(); return m_tree.GetHeight();
} }
inline int32 b2BroadPhase::GetTreeBalance() const inline int32 b2BroadPhase::GetTreeBalance() const
{ {
return m_tree.GetMaxBalance(); return m_tree.GetMaxBalance();
} }
inline float32 b2BroadPhase::GetTreeQuality() const inline float32 b2BroadPhase::GetTreeQuality() const
{ {
return m_tree.GetAreaRatio(); return m_tree.GetAreaRatio();
} }
template <typename T> template <typename T>
void b2BroadPhase::UpdatePairs(T* callback) void b2BroadPhase::UpdatePairs(T* callback)
{ {
// Reset pair buffer // Reset pair buffer
m_pairCount = 0; m_pairCount = 0;
// Perform tree queries for all moving proxies. // Perform tree queries for all moving proxies.
for (int32 i = 0; i < m_moveCount; ++i) for (int32 i = 0; i < m_moveCount; ++i)
{ {
m_queryProxyId = m_moveBuffer[i]; m_queryProxyId = m_moveBuffer[i];
if (m_queryProxyId == e_nullProxy) if (m_queryProxyId == e_nullProxy)
{ {
continue; continue;
} }
// We have to query the tree with the fat AABB so that // We have to query the tree with the fat AABB so that
// we don't fail to create a pair that may touch later. // we don't fail to create a pair that may touch later.
const b2AABB& fatAABB = m_tree.GetFatAABB(m_queryProxyId); const b2AABB& fatAABB = m_tree.GetFatAABB(m_queryProxyId);
// Query tree, create pairs and add them pair buffer. // Query tree, create pairs and add them pair buffer.
m_tree.Query(this, fatAABB); m_tree.Query(this, fatAABB);
} }
// Reset move buffer // Reset move buffer
m_moveCount = 0; m_moveCount = 0;
// Sort the pair buffer to expose duplicates. // Sort the pair buffer to expose duplicates.
std::sort(m_pairBuffer, m_pairBuffer + m_pairCount, b2PairLessThan); std::sort(m_pairBuffer, m_pairBuffer + m_pairCount, b2PairLessThan);
// Send the pairs back to the client. // Send the pairs back to the client.
int32 i = 0; int32 i = 0;
while (i < m_pairCount) while (i < m_pairCount)
{ {
b2Pair* primaryPair = m_pairBuffer + i; b2Pair* primaryPair = m_pairBuffer + i;
void* userDataA = m_tree.GetUserData(primaryPair->proxyIdA); void* userDataA = m_tree.GetUserData(primaryPair->proxyIdA);
void* userDataB = m_tree.GetUserData(primaryPair->proxyIdB); void* userDataB = m_tree.GetUserData(primaryPair->proxyIdB);
callback->AddPair(userDataA, userDataB); callback->AddPair(userDataA, userDataB);
++i; ++i;
// Skip any duplicate pairs. // Skip any duplicate pairs.
while (i < m_pairCount) while (i < m_pairCount)
{ {
b2Pair* pair = m_pairBuffer + i; b2Pair* pair = m_pairBuffer + i;
if (pair->proxyIdA != primaryPair->proxyIdA || pair- if (pair->proxyIdA != primaryPair->proxyIdA || pair->proxyIdB !
>proxyIdB != primaryPair->proxyIdB) = primaryPair->proxyIdB)
{ {
break; break;
} }
++i; ++i;
} }
} }
// Try to keep the tree balanced. // Try to keep the tree balanced.
//m_tree.Rebalance(4); //m_tree.Rebalance(4);
} }
template <typename T> template <typename T>
inline void b2BroadPhase::Query(T* callback, const b2AABB& aabb) const inline void b2BroadPhase::Query(T* callback, const b2AABB& aabb) const
{ {
m_tree.Query(callback, aabb); m_tree.Query(callback, aabb);
} }
template <typename T> template <typename T>
inline void b2BroadPhase::RayCast(T* callback, const b2RayCastInput& input) const inline void b2BroadPhase::RayCast(T* callback, const b2RayCastInput& input) const
{ {
m_tree.RayCast(callback, input); m_tree.RayCast(callback, input);
} }
#endif #endif
 End of changes. 27 change blocks. 
156 lines changed or deleted 154 lines changed or added


 b2ChainAndCircleContact.h   b2ChainAndCircleContact.h 
skipping to change at line 29 skipping to change at line 29
#ifndef B2_CHAIN_AND_CIRCLE_CONTACT_H #ifndef B2_CHAIN_AND_CIRCLE_CONTACT_H
#define B2_CHAIN_AND_CIRCLE_CONTACT_H #define B2_CHAIN_AND_CIRCLE_CONTACT_H
#include <Box2D/Dynamics/Contacts/b2Contact.h> #include <Box2D/Dynamics/Contacts/b2Contact.h>
class b2BlockAllocator; class b2BlockAllocator;
class b2ChainAndCircleContact : public b2Contact class b2ChainAndCircleContact : public b2Contact
{ {
public: public:
static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, static b2Contact* Create( b2Fixture* fixtureA, int32 indexA,
b2Fixture* f b2Fixture* fixtureB, int32 indexB, b2BlockA
ixtureB, int32 indexB, b2BlockAllocator* allocator); llocator* allocator);
static void Destroy(b2Contact* contact, b2BlockAllocator* allocator) static void Destroy(b2Contact* contact, b2BlockAllocator* allocator);
;
b2ChainAndCircleContact(b2Fixture* fixtureA, int32 indexA, b2Fixture b2ChainAndCircleContact(b2Fixture* fixtureA, int32 indexA, b2Fixture* f
* fixtureB, int32 indexB); ixtureB, int32 indexB);
~b2ChainAndCircleContact() {} ~b2ChainAndCircleContact() {}
void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2 Transform& xfB); void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Tra nsform& xfB);
}; };
#endif #endif
 End of changes. 3 change blocks. 
9 lines changed or deleted 8 lines changed or added


 b2ChainAndPolygonContact.h   b2ChainAndPolygonContact.h 
skipping to change at line 29 skipping to change at line 29
#ifndef B2_CHAIN_AND_POLYGON_CONTACT_H #ifndef B2_CHAIN_AND_POLYGON_CONTACT_H
#define B2_CHAIN_AND_POLYGON_CONTACT_H #define B2_CHAIN_AND_POLYGON_CONTACT_H
#include <Box2D/Dynamics/Contacts/b2Contact.h> #include <Box2D/Dynamics/Contacts/b2Contact.h>
class b2BlockAllocator; class b2BlockAllocator;
class b2ChainAndPolygonContact : public b2Contact class b2ChainAndPolygonContact : public b2Contact
{ {
public: public:
static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, static b2Contact* Create( b2Fixture* fixtureA, int32 indexA,
b2Fixture* f b2Fixture* fixtureB, int32 indexB, b2BlockA
ixtureB, int32 indexB, b2BlockAllocator* allocator); llocator* allocator);
static void Destroy(b2Contact* contact, b2BlockAllocator* allocator) static void Destroy(b2Contact* contact, b2BlockAllocator* allocator);
;
b2ChainAndPolygonContact(b2Fixture* fixtureA, int32 indexA, b2Fixtur b2ChainAndPolygonContact(b2Fixture* fixtureA, int32 indexA, b2Fixture*
e* fixtureB, int32 indexB); fixtureB, int32 indexB);
~b2ChainAndPolygonContact() {} ~b2ChainAndPolygonContact() {}
void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2 Transform& xfB); void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Tra nsform& xfB);
}; };
#endif #endif
 End of changes. 3 change blocks. 
9 lines changed or deleted 8 lines changed or added


 b2ChainShape.h   b2ChainShape.h 
skipping to change at line 35 skipping to change at line 35
/// A chain shape is a free form sequence of line segments. /// A chain shape is a free form sequence of line segments.
/// The chain has two-sided collision, so you can use inside and outside co llision. /// The chain has two-sided collision, so you can use inside and outside co llision.
/// Therefore, you may use any winding order. /// Therefore, you may use any winding order.
/// Since there may be many vertices, they are allocated using b2Alloc. /// Since there may be many vertices, they are allocated using b2Alloc.
/// Connectivity information is used to create smooth collisions. /// Connectivity information is used to create smooth collisions.
/// WARNING: The chain will not collide properly if there are self-intersec tions. /// WARNING: The chain will not collide properly if there are self-intersec tions.
class b2ChainShape : public b2Shape class b2ChainShape : public b2Shape
{ {
public: public:
b2ChainShape(); b2ChainShape();
/// The destructor frees the vertices using b2Free. /// The destructor frees the vertices using b2Free.
~b2ChainShape(); ~b2ChainShape();
/// Create a loop. This automatically adjusts connectivity. /// Create a loop. This automatically adjusts connectivity.
/// @param vertices an array of vertices, these are copied /// @param vertices an array of vertices, these are copied
/// @param count the vertex count /// @param count the vertex count
void CreateLoop(const b2Vec2* vertices, int32 count); void CreateLoop(const b2Vec2* vertices, int32 count);
/// Create a chain with isolated end vertices. /// Create a chain with isolated end vertices.
/// @param vertices an array of vertices, these are copied /// @param vertices an array of vertices, these are copied
/// @param count the vertex count /// @param count the vertex count
void CreateChain(const b2Vec2* vertices, int32 count); void CreateChain(const b2Vec2* vertices, int32 count);
/// Establish connectivity to a vertex that precedes the first verte /// Establish connectivity to a vertex that precedes the first vertex.
x. /// Don't call this for loops.
/// Don't call this for loops. void SetPrevVertex(const b2Vec2& prevVertex);
void SetPrevVertex(const b2Vec2& prevVertex);
/// Establish connectivity to a vertex that follows the last vertex. /// Establish connectivity to a vertex that follows the last vertex.
/// Don't call this for loops. /// Don't call this for loops.
void SetNextVertex(const b2Vec2& nextVertex); void SetNextVertex(const b2Vec2& nextVertex);
/// Implement b2Shape. Vertices are cloned using b2Alloc. /// Implement b2Shape. Vertices are cloned using b2Alloc.
b2Shape* Clone(b2BlockAllocator* allocator) const; b2Shape* Clone(b2BlockAllocator* allocator) const;
/// @see b2Shape::GetChildCount /// @see b2Shape::GetChildCount
int32 GetChildCount() const; int32 GetChildCount() const;
/// Get a child edge. /// Get a child edge.
void GetChildEdge(b2EdgeShape* edge, int32 index) const; void GetChildEdge(b2EdgeShape* edge, int32 index) const;
/// This always return false. /// This always return false.
/// @see b2Shape::TestPoint /// @see b2Shape::TestPoint
bool TestPoint(const b2Transform& transform, const b2Vec2& p) const; bool TestPoint(const b2Transform& transform, const b2Vec2& p) const;
/// Implement b2Shape. /// Implement b2Shape.
bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input,
const b2Transform& transform, int32 const b2Transform& transform, int32 childIndex) const;
childIndex) const;
/// @see b2Shape::ComputeAABB /// @see b2Shape::ComputeAABB
void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 c void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 chil
hildIndex) const; dIndex) const;
/// Chains have zero mass. /// Chains have zero mass.
/// @see b2Shape::ComputeMass /// @see b2Shape::ComputeMass
void ComputeMass(b2MassData* massData, float32 density) const; void ComputeMass(b2MassData* massData, float32 density) const;
/// The vertices. Owned by this class. /// The vertices. Owned by this class.
b2Vec2* m_vertices; b2Vec2* m_vertices;
/// The vertex count. /// The vertex count.
int32 m_count; int32 m_count;
b2Vec2 m_prevVertex, m_nextVertex; b2Vec2 m_prevVertex, m_nextVertex;
bool m_hasPrevVertex, m_hasNextVertex; bool m_hasPrevVertex, m_hasNextVertex;
}; };
inline b2ChainShape::b2ChainShape() inline b2ChainShape::b2ChainShape()
{ {
m_type = e_chain; m_type = e_chain;
m_radius = b2_polygonRadius; m_radius = b2_polygonRadius;
m_vertices = NULL; m_vertices = NULL;
m_count = 0; m_count = 0;
m_hasPrevVertex = NULL; m_hasPrevVertex = NULL;
m_hasNextVertex = NULL; m_hasNextVertex = NULL;
} }
#endif #endif
 End of changes. 17 change blocks. 
49 lines changed or deleted 47 lines changed or added


 b2CircleContact.h   b2CircleContact.h 
skipping to change at line 29 skipping to change at line 29
#ifndef B2_CIRCLE_CONTACT_H #ifndef B2_CIRCLE_CONTACT_H
#define B2_CIRCLE_CONTACT_H #define B2_CIRCLE_CONTACT_H
#include <Box2D/Dynamics/Contacts/b2Contact.h> #include <Box2D/Dynamics/Contacts/b2Contact.h>
class b2BlockAllocator; class b2BlockAllocator;
class b2CircleContact : public b2Contact class b2CircleContact : public b2Contact
{ {
public: public:
static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, static b2Contact* Create( b2Fixture* fixtureA, int32 indexA,
b2Fixture* f b2Fixture* fixtureB, int32 indexB, b2BlockA
ixtureB, int32 indexB, b2BlockAllocator* allocator); llocator* allocator);
static void Destroy(b2Contact* contact, b2BlockAllocator* allocator) static void Destroy(b2Contact* contact, b2BlockAllocator* allocator);
;
b2CircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB); b2CircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB);
~b2CircleContact() {} ~b2CircleContact() {}
void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2 Transform& xfB); void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Tra nsform& xfB);
}; };
#endif #endif
 End of changes. 3 change blocks. 
8 lines changed or deleted 7 lines changed or added


 b2CircleShape.h   b2CircleShape.h 
skipping to change at line 28 skipping to change at line 28
#ifndef B2_CIRCLE_SHAPE_H #ifndef B2_CIRCLE_SHAPE_H
#define B2_CIRCLE_SHAPE_H #define B2_CIRCLE_SHAPE_H
#include <Box2D/Collision/Shapes/b2Shape.h> #include <Box2D/Collision/Shapes/b2Shape.h>
/// A circle shape. /// A circle shape.
class b2CircleShape : public b2Shape class b2CircleShape : public b2Shape
{ {
public: public:
b2CircleShape(); b2CircleShape();
/// Implement b2Shape. /// Implement b2Shape.
b2Shape* Clone(b2BlockAllocator* allocator) const; b2Shape* Clone(b2BlockAllocator* allocator) const;
/// @see b2Shape::GetChildCount /// @see b2Shape::GetChildCount
int32 GetChildCount() const; int32 GetChildCount() const;
/// Implement b2Shape. /// Implement b2Shape.
bool TestPoint(const b2Transform& transform, const b2Vec2& p) const; bool TestPoint(const b2Transform& transform, const b2Vec2& p) const;
/// Implement b2Shape. /// Implement b2Shape.
bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input,
const b2Transform& transform, int32 childInd const b2Transform& transform, int32 childIndex) const;
ex) const;
/// @see b2Shape::ComputeAABB /// @see b2Shape::ComputeAABB
void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 c void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 chil
hildIndex) const; dIndex) const;
/// @see b2Shape::ComputeMass /// @see b2Shape::ComputeMass
void ComputeMass(b2MassData* massData, float32 density) const; void ComputeMass(b2MassData* massData, float32 density) const;
/// Get the supporting vertex index in the given direction. /// Get the supporting vertex index in the given direction.
int32 GetSupport(const b2Vec2& d) const; int32 GetSupport(const b2Vec2& d) const;
/// Get the supporting vertex in the given direction. /// Get the supporting vertex in the given direction.
const b2Vec2& GetSupportVertex(const b2Vec2& d) const; const b2Vec2& GetSupportVertex(const b2Vec2& d) const;
/// Get the vertex count. /// Get the vertex count.
int32 GetVertexCount() const { return 1; } int32 GetVertexCount() const { return 1; }
/// Get a vertex by index. Used by b2Distance. /// Get a vertex by index. Used by b2Distance.
const b2Vec2& GetVertex(int32 index) const; const b2Vec2& GetVertex(int32 index) const;
/// Position /// Position
b2Vec2 m_p; b2Vec2 m_p;
}; };
inline b2CircleShape::b2CircleShape() inline b2CircleShape::b2CircleShape()
{ {
m_type = e_circle; m_type = e_circle;
m_radius = 0.0f; m_radius = 0.0f;
m_p.SetZero(); m_p.SetZero();
} }
inline int32 b2CircleShape::GetSupport(const b2Vec2 &d) const inline int32 b2CircleShape::GetSupport(const b2Vec2 &d) const
{ {
B2_NOT_USED(d); B2_NOT_USED(d);
return 0; return 0;
} }
inline const b2Vec2& b2CircleShape::GetSupportVertex(const b2Vec2 &d) const inline const b2Vec2& b2CircleShape::GetSupportVertex(const b2Vec2 &d) const
{ {
B2_NOT_USED(d); B2_NOT_USED(d);
return m_p; return m_p;
} }
inline const b2Vec2& b2CircleShape::GetVertex(int32 index) const inline const b2Vec2& b2CircleShape::GetVertex(int32 index) const
{ {
B2_NOT_USED(index); B2_NOT_USED(index);
b2Assert(index == 0); b2Assert(index == 0);
return m_p; return m_p;
} }
#endif #endif
 End of changes. 16 change blocks. 
36 lines changed or deleted 35 lines changed or added


 b2Collision.h   b2Collision.h 
skipping to change at line 40 skipping to change at line 40
class b2CircleShape; class b2CircleShape;
class b2EdgeShape; class b2EdgeShape;
class b2PolygonShape; class b2PolygonShape;
const uint8 b2_nullFeature = UCHAR_MAX; const uint8 b2_nullFeature = UCHAR_MAX;
/// The features that intersect to form the contact point /// The features that intersect to form the contact point
/// This must be 4 bytes or less. /// This must be 4 bytes or less.
struct b2ContactFeature struct b2ContactFeature
{ {
enum Type enum Type
{ {
e_vertex = 0, e_vertex = 0,
e_face = 1 e_face = 1
}; };
uint8 indexA; ///< Feature index on shapeA uint8 indexA; ///< Feature index on shapeA
uint8 indexB; ///< Feature index on shapeB uint8 indexB; ///< Feature index on shapeB
uint8 typeA; ///< The feature type on shapeA uint8 typeA; ///< The feature type on shapeA
uint8 typeB; ///< The feature type on shapeB uint8 typeB; ///< The feature type on shapeB
}; };
/// Contact ids to facilitate warm starting. /// Contact ids to facilitate warm starting.
union b2ContactID union b2ContactID
{ {
b2ContactFeature cf; b2ContactFeature cf;
uint32 key; ///< Used to quickly uint32 key; ///< Used to quickly compare contact ids
compare contact ids. .
}; };
/// A manifold point is a contact point belonging to a contact /// A manifold point is a contact point belonging to a contact
/// manifold. It holds details related to the geometry and dynamics /// manifold. It holds details related to the geometry and dynamics
/// of the contact points. /// of the contact points.
/// The local point usage depends on the manifold type: /// The local point usage depends on the manifold type:
/// -e_circles: the local center of circleB /// -e_circles: the local center of circleB
/// -e_faceA: the local center of cirlceB or the clip point of polygonB /// -e_faceA: the local center of cirlceB or the clip point of polygonB
/// -e_faceB: the clip point of polygonA /// -e_faceB: the clip point of polygonA
/// This structure is stored across time steps, so we keep it small. /// This structure is stored across time steps, so we keep it small.
/// Note: the impulses are used for internal caching and may not /// Note: the impulses are used for internal caching and may not
/// provide reliable contact forces, especially for high speed collisions. /// provide reliable contact forces, especially for high speed collisions.
struct b2ManifoldPoint struct b2ManifoldPoint
{ {
b2Vec2 localPoint; ///< usage depends on manifold type b2Vec2 localPoint; ///< usage depends on manifold type
float32 normalImpulse; ///< the non-penetration impulse float32 normalImpulse; ///< the non-penetration impulse
float32 tangentImpulse; ///< the friction impulse float32 tangentImpulse; ///< the friction impulse
b2ContactID id; ///< uniquely identifies a contact p b2ContactID id; ///< uniquely identifies a contact point bet
oint between two shapes ween two shapes
}; };
/// A manifold for two touching convex shapes. /// A manifold for two touching convex shapes.
/// Box2D supports multiple types of contact: /// Box2D supports multiple types of contact:
/// - clip point versus plane with radius /// - clip point versus plane with radius
/// - point versus point with radius (circles) /// - point versus point with radius (circles)
/// The local point usage depends on the manifold type: /// The local point usage depends on the manifold type:
/// -e_circles: the local center of circleA /// -e_circles: the local center of circleA
/// -e_faceA: the center of faceA /// -e_faceA: the center of faceA
/// -e_faceB: the center of faceB /// -e_faceB: the center of faceB
/// Similarly the local normal usage: /// Similarly the local normal usage:
/// -e_circles: not used /// -e_circles: not used
/// -e_faceA: the normal on polygonA /// -e_faceA: the normal on polygonA
/// -e_faceB: the normal on polygonB /// -e_faceB: the normal on polygonB
/// We store contacts in this way so that position correction can /// We store contacts in this way so that position correction can
/// account for movement, which is critical for continuous physics. /// account for movement, which is critical for continuous physics.
/// All contact scenarios must be expressed in one of these types. /// All contact scenarios must be expressed in one of these types.
/// This structure is stored across time steps, so we keep it small. /// This structure is stored across time steps, so we keep it small.
struct b2Manifold struct b2Manifold
{ {
enum Type enum Type
{ {
e_circles, e_circles,
e_faceA, e_faceA,
e_faceB e_faceB
}; };
b2ManifoldPoint points[b2_maxManifoldPoints]; ///< the points of c b2ManifoldPoint points[b2_maxManifoldPoints]; ///< the points of con
ontact tact
b2Vec2 localNormal; b2Vec2 localNormal; ///< not use for Typ
///< not use for Type::e_points e::e_points
b2Vec2 localPoint; b2Vec2 localPoint; ///< usage depends on
///< usage depends on manifold type manifold type
Type type; Type type;
int32 pointCount; int32 pointCount; ///< the number of man
///< the number of manifold points ifold points
}; };
/// This is used to compute the current state of a contact manifold. /// This is used to compute the current state of a contact manifold.
struct b2WorldManifold struct b2WorldManifold
{ {
/// Evaluate the manifold with supplied transforms. This assumes /// Evaluate the manifold with supplied transforms. This assumes
/// modest motion from the original state. This does not change the /// modest motion from the original state. This does not change the
/// point count, impulses, etc. The radii must come from the shapes /// point count, impulses, etc. The radii must come from the shapes
/// that generated the manifold. /// that generated the manifold.
void Initialize(const b2Manifold* manifold, void Initialize(const b2Manifold* manifold,
const b2Transform& xfA, float32 radi const b2Transform& xfA, float32 radiusA,
usA, const b2Transform& xfB, float32 radiusB);
const b2Transform& xfB, float32 radi
usB);
b2Vec2 normal; ///< b2Vec2 normal; ///< world vector pointing fr
world vector pointing from A to B om A to B
b2Vec2 points[b2_maxManifoldPoints]; ///< world contact point (po b2Vec2 points[b2_maxManifoldPoints]; ///< world contact point (point
int of intersection) of intersection)
}; };
/// This is used for determining the state of contact points. /// This is used for determining the state of contact points.
enum b2PointState enum b2PointState
{ {
b2_nullState, ///< point does not exist b2_nullState, ///< point does not exist
b2_addState, ///< point was added in the update b2_addState, ///< point was added in the update
b2_persistState, ///< point persisted across the update b2_persistState, ///< point persisted across the update
b2_removeState ///< point was removed in the update b2_removeState ///< point was removed in the update
}; };
/// Compute the point states given two manifolds. The states pertain to the transition from manifold1 /// Compute the point states given two manifolds. The states pertain to the transition from manifold1
/// to manifold2. So state1 is either persist or remove while state2 is eit her add or persist. /// to manifold2. So state1 is either persist or remove while state2 is eit her add or persist.
void b2GetPointStates(b2PointState state1[b2_maxManifoldPoints], b2PointSta te state2[b2_maxManifoldPoints], void b2GetPointStates(b2PointState state1[b2_maxManifoldPoints], b2PointSta te state2[b2_maxManifoldPoints],
const b2Manifold* manifold1, const b2Manifold* manifold2); const b2Manifold* manifold1, const b2Manifold* manifo ld2);
/// Used for computing contact manifolds. /// Used for computing contact manifolds.
struct b2ClipVertex struct b2ClipVertex
{ {
b2Vec2 v; b2Vec2 v;
b2ContactID id; b2ContactID id;
}; };
/// Ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1). /// Ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1).
struct b2RayCastInput struct b2RayCastInput
{ {
b2Vec2 p1, p2; b2Vec2 p1, p2;
float32 maxFraction; float32 maxFraction;
}; };
/// Ray-cast output data. The ray hits at p1 + fraction * (p2 - p1), where p1 and p2 /// Ray-cast output data. The ray hits at p1 + fraction * (p2 - p1), where p1 and p2
/// come from b2RayCastInput. /// come from b2RayCastInput.
struct b2RayCastOutput struct b2RayCastOutput
{ {
b2Vec2 normal; b2Vec2 normal;
float32 fraction; float32 fraction;
}; };
/// An axis aligned bounding box. /// An axis aligned bounding box.
struct b2AABB struct b2AABB
{ {
/// Verify that the bounds are sorted. /// Verify that the bounds are sorted.
bool IsValid() const; bool IsValid() const;
/// Get the center of the AABB. /// Get the center of the AABB.
b2Vec2 GetCenter() const b2Vec2 GetCenter() const
{ {
return 0.5f * (lowerBound + upperBound); return 0.5f * (lowerBound + upperBound);
} }
/// Get the extents of the AABB (half-widths). /// Get the extents of the AABB (half-widths).
b2Vec2 GetExtents() const b2Vec2 GetExtents() const
{ {
return 0.5f * (upperBound - lowerBound); return 0.5f * (upperBound - lowerBound);
} }
/// Get the perimeter length /// Get the perimeter length
float32 GetPerimeter() const float32 GetPerimeter() const
{ {
float32 wx = upperBound.x - lowerBound.x; float32 wx = upperBound.x - lowerBound.x;
float32 wy = upperBound.y - lowerBound.y; float32 wy = upperBound.y - lowerBound.y;
return 2.0f * (wx + wy); return 2.0f * (wx + wy);
} }
/// Combine an AABB into this one. /// Combine an AABB into this one.
void Combine(const b2AABB& aabb) void Combine(const b2AABB& aabb)
{ {
lowerBound = b2Min(lowerBound, aabb.lowerBound); lowerBound = b2Min(lowerBound, aabb.lowerBound);
upperBound = b2Max(upperBound, aabb.upperBound); upperBound = b2Max(upperBound, aabb.upperBound);
} }
/// Combine two AABBs into this one. /// Combine two AABBs into this one.
void Combine(const b2AABB& aabb1, const b2AABB& aabb2) void Combine(const b2AABB& aabb1, const b2AABB& aabb2)
{ {
lowerBound = b2Min(aabb1.lowerBound, aabb2.lowerBound); lowerBound = b2Min(aabb1.lowerBound, aabb2.lowerBound);
upperBound = b2Max(aabb1.upperBound, aabb2.upperBound); upperBound = b2Max(aabb1.upperBound, aabb2.upperBound);
} }
/// Does this aabb contain the provided AABB. /// Does this aabb contain the provided AABB.
bool Contains(const b2AABB& aabb) const bool Contains(const b2AABB& aabb) const
{ {
bool result = true; bool result = true;
result = result && lowerBound.x <= aabb.lowerBound.x; result = result && lowerBound.x <= aabb.lowerBound.x;
result = result && lowerBound.y <= aabb.lowerBound.y; result = result && lowerBound.y <= aabb.lowerBound.y;
result = result && aabb.upperBound.x <= upperBound.x; result = result && aabb.upperBound.x <= upperBound.x;
result = result && aabb.upperBound.y <= upperBound.y; result = result && aabb.upperBound.y <= upperBound.y;
return result; return result;
} }
bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input) c onst; bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input) cons t;
b2Vec2 lowerBound; ///< the lower vertex b2Vec2 lowerBound; ///< the lower vertex
b2Vec2 upperBound; ///< the upper vertex b2Vec2 upperBound; ///< the upper vertex
}; };
/// Compute the collision manifold between two circles. /// Compute the collision manifold between two circles.
void b2CollideCircles(b2Manifold* manifold, void b2CollideCircles(b2Manifold* manifold,
const b2CircleShape* circleA, cons const b2CircleShape* circleA, const b2Transform& xfA,
t b2Transform& xfA, const b2CircleShape* circleB, const b2Transform& xfB)
const b2CircleShape* circleB, cons ;
t b2Transform& xfB);
/// Compute the collision manifold between a polygon and a circle. /// Compute the collision manifold between a polygon and a circle.
void b2CollidePolygonAndCircle(b2Manifold* manifold, void b2CollidePolygonAndCircle(b2Manifold* manifold,
const b2PolygonSh const b2PolygonShape* polygonA, const b2Tran
ape* polygonA, const b2Transform& xfA, sform& xfA,
const b2CircleSha const b2CircleShape* circleB, const b2Transf
pe* circleB, const b2Transform& xfB); orm& xfB);
/// Compute the collision manifold between two polygons. /// Compute the collision manifold between two polygons.
void b2CollidePolygons(b2Manifold* manifold, void b2CollidePolygons(b2Manifold* manifold,
const b2PolygonShape* polygonA, c const b2PolygonShape* polygonA, const b2Transform& x
onst b2Transform& xfA, fA,
const b2PolygonShape* polygonB, c const b2PolygonShape* polygonB, const b2Transform& x
onst b2Transform& xfB); fB);
/// Compute the collision manifold between an edge and a circle. /// Compute the collision manifold between an edge and a circle.
void b2CollideEdgeAndCircle(b2Manifold* manifold, void b2CollideEdgeAndCircle(b2Manifold* manifold,
const b2EdgeShape const b2EdgeShape* polygonA, const b2Transfo
* polygonA, const b2Transform& xfA, rm& xfA,
const b2CircleSha const b2CircleShape* circleB, const b2Transf
pe* circleB, const b2Transform& xfB); orm& xfB);
/// Compute the collision manifold between an edge and a circle. /// Compute the collision manifold between an edge and a circle.
void b2CollideEdgeAndPolygon(b2Manifold* manifold, void b2CollideEdgeAndPolygon(b2Manifold* manifold,
const b2EdgeShape const b2EdgeShape* edgeA, const b2Transform&
* edgeA, const b2Transform& xfA, xfA,
const b2PolygonSh const b2PolygonShape* circleB, const b2Trans
ape* circleB, const b2Transform& xfB); form& xfB);
/// Clipping for contact manifolds. /// Clipping for contact manifolds.
int32 b2ClipSegmentToLine(b2ClipVertex vOut[2], const b2ClipVertex vIn[2], int32 b2ClipSegmentToLine(b2ClipVertex vOut[2], const b2ClipVertex vIn[2],
const b2Vec2& normal , float32 offset, int32 vertexIndexA); const b2Vec2& normal, float32 offset, int32 ver texIndexA);
/// Determine if two generic shapes overlap. /// Determine if two generic shapes overlap.
bool b2TestOverlap( const b2Shape* shapeA, int32 indexA, bool b2TestOverlap( const b2Shape* shapeA, int32 indexA,
const b2Shape* shapeB, int32 indexB, const b2Shape* shapeB, int32 indexB,
const b2Transform& xfA, const b2Tran const b2Transform& xfA, const b2Transform& xfB);
sform& xfB);
// ---------------- Inline Functions -------------------------------------- ---- // ---------------- Inline Functions -------------------------------------- ----
inline bool b2AABB::IsValid() const inline bool b2AABB::IsValid() const
{ {
b2Vec2 d = upperBound - lowerBound; b2Vec2 d = upperBound - lowerBound;
bool valid = d.x >= 0.0f && d.y >= 0.0f; bool valid = d.x >= 0.0f && d.y >= 0.0f;
valid = valid && lowerBound.IsValid() && upperBound.IsValid(); valid = valid && lowerBound.IsValid() && upperBound.IsValid();
return valid; return valid;
} }
inline bool b2TestOverlap(const b2AABB& a, const b2AABB& b) inline bool b2TestOverlap(const b2AABB& a, const b2AABB& b)
{ {
b2Vec2 d1, d2; b2Vec2 d1, d2;
d1 = b.lowerBound - a.upperBound; d1 = b.lowerBound - a.upperBound;
d2 = a.lowerBound - b.upperBound; d2 = a.lowerBound - b.upperBound;
if (d1.x > 0.0f || d1.y > 0.0f) if (d1.x > 0.0f || d1.y > 0.0f)
return false; return false;
if (d2.x > 0.0f || d2.y > 0.0f) if (d2.x > 0.0f || d2.y > 0.0f)
return false; return false;
return true; return true;
} }
#endif #endif
 End of changes. 27 change blocks. 
144 lines changed or deleted 140 lines changed or added


 b2Contact.h   b2Contact.h 
skipping to change at line 39 skipping to change at line 39
class b2Fixture; class b2Fixture;
class b2World; class b2World;
class b2BlockAllocator; class b2BlockAllocator;
class b2StackAllocator; class b2StackAllocator;
class b2ContactListener; class b2ContactListener;
/// Friction mixing law. The idea is to allow either fixture to drive the r estitution to zero. /// Friction mixing law. The idea is to allow either fixture to drive the r estitution to zero.
/// For example, anything slides on ice. /// For example, anything slides on ice.
inline float32 b2MixFriction(float32 friction1, float32 friction2) inline float32 b2MixFriction(float32 friction1, float32 friction2)
{ {
return std::sqrt(friction1 * friction2); return std::sqrt(friction1 * friction2);
} }
/// Restitution mixing law. The idea is allow for anything to bounce off an inelastic surface. /// Restitution mixing law. The idea is allow for anything to bounce off an inelastic surface.
/// For example, a superball bounces on anything. /// For example, a superball bounces on anything.
inline float32 b2MixRestitution(float32 restitution1, float32 restitution2) inline float32 b2MixRestitution(float32 restitution1, float32 restitution2)
{ {
return restitution1 > restitution2 ? restitution1 : restitution2; return restitution1 > restitution2 ? restitution1 : restitution2;
} }
typedef b2Contact* b2ContactCreateFcn( b2Fixture* fixtureA, int32 indexA, typedef b2Contact* b2ContactCreateFcn( b2Fixture* fixtureA, int32 indexA
,
b2Fixture* fixtureB, int32 indexB, b2Fixture* fixtureB, int32 indexB,
b2BlockAllocator* allocator);
b2BlockAllocator* allocator);
typedef void b2ContactDestroyFcn(b2Contact* contact, b2BlockAllocator* allo cator); typedef void b2ContactDestroyFcn(b2Contact* contact, b2BlockAllocator* allo cator);
struct b2ContactRegister struct b2ContactRegister
{ {
b2ContactCreateFcn* createFcn; b2ContactCreateFcn* createFcn;
b2ContactDestroyFcn* destroyFcn; b2ContactDestroyFcn* destroyFcn;
bool primary; bool primary;
}; };
/// A contact edge is used to connect bodies and contacts together /// A contact edge is used to connect bodies and contacts together
/// in a contact graph where each body is a node and each contact /// in a contact graph where each body is a node and each contact
/// is an edge. A contact edge belongs to a doubly linked list /// is an edge. A contact edge belongs to a doubly linked list
/// maintained in each attached body. Each contact has two contact /// maintained in each attached body. Each contact has two contact
/// nodes, one for each attached body. /// nodes, one for each attached body.
struct b2ContactEdge struct b2ContactEdge
{ {
b2Body* other; ///< provides quick access to the ot b2Body* other; ///< provides quick access to the other body
her body attached. attached.
b2Contact* contact; ///< the contact b2Contact* contact; ///< the contact
b2ContactEdge* prev; ///< the previous contact edge in the body's b2ContactEdge* prev; ///< the previous contact edge in the body's co
contact list ntact list
b2ContactEdge* next; ///< the next contact edge in the body's con b2ContactEdge* next; ///< the next contact edge in the body's contac
tact list t list
}; };
/// The class manages contact between two shapes. A contact exists for each overlapping /// The class manages contact between two shapes. A contact exists for each overlapping
/// AABB in the broad-phase (except if filtered). Therefore a contact objec t may exist /// AABB in the broad-phase (except if filtered). Therefore a contact objec t may exist
/// that has no contact points. /// that has no contact points.
class b2Contact class b2Contact
{ {
public: public:
/// Get the contact manifold. Do not modify the manifold unless you /// Get the contact manifold. Do not modify the manifold unless you und
understand the erstand the
/// internals of Box2D. /// internals of Box2D.
b2Manifold* GetManifold(); b2Manifold* GetManifold();
const b2Manifold* GetManifold() const; const b2Manifold* GetManifold() const;
/// Get the world manifold. /// Get the world manifold.
void GetWorldManifold(b2WorldManifold* worldManifold) const; void GetWorldManifold(b2WorldManifold* worldManifold) const;
/// Is this contact touching? /// Is this contact touching?
bool IsTouching() const; bool IsTouching() const;
/// Enable/disable this contact. This can be used inside the pre-sol /// Enable/disable this contact. This can be used inside the pre-solve
ve /// contact listener. The contact is only disabled for the current
/// contact listener. The contact is only disabled for the current /// time step (or sub-step in continuous collisions).
/// time step (or sub-step in continuous collisions). void SetEnabled(bool flag);
void SetEnabled(bool flag);
/// Has this contact been disabled? /// Has this contact been disabled?
bool IsEnabled() const; bool IsEnabled() const;
/// Get the next contact in the world's contact list. /// Get the next contact in the world's contact list.
b2Contact* GetNext(); b2Contact* GetNext();
const b2Contact* GetNext() const; const b2Contact* GetNext() const;
/// Get fixture A in this contact. /// Get fixture A in this contact.
b2Fixture* GetFixtureA(); b2Fixture* GetFixtureA();
const b2Fixture* GetFixtureA() const; const b2Fixture* GetFixtureA() const;
/// Get the child primitive index for fixture A. /// Get the child primitive index for fixture A.
int32 GetChildIndexA() const; int32 GetChildIndexA() const;
/// Get fixture B in this contact. /// Get fixture B in this contact.
b2Fixture* GetFixtureB(); b2Fixture* GetFixtureB();
const b2Fixture* GetFixtureB() const; const b2Fixture* GetFixtureB() const;
/// Get the child primitive index for fixture B. /// Get the child primitive index for fixture B.
int32 GetChildIndexB() const; int32 GetChildIndexB() const;
/// Override the default friction mixture. You can call this in b2Co /// Override the default friction mixture. You can call this in b2Conta
ntactListener::PreSolve. ctListener::PreSolve.
/// This value persists until set or reset. /// This value persists until set or reset.
void SetFriction(float32 friction); void SetFriction(float32 friction);
/// Get the friction. /// Get the friction.
float32 GetFriction() const; float32 GetFriction() const;
/// Reset the friction mixture to the default value. /// Reset the friction mixture to the default value.
void ResetFriction(); void ResetFriction();
/// Override the default restitution mixture. You can call this in b /// Override the default restitution mixture. You can call this in b2Co
2ContactListener::PreSolve. ntactListener::PreSolve.
/// The value persists until you set or reset. /// The value persists until you set or reset.
void SetRestitution(float32 restitution); void SetRestitution(float32 restitution);
/// Get the restitution. /// Get the restitution.
float32 GetRestitution() const; float32 GetRestitution() const;
/// Reset the restitution to the default value. /// Reset the restitution to the default value.
void ResetRestitution(); void ResetRestitution();
/// Evaluate this contact with your own manifold and transforms. /// Evaluate this contact with your own manifold and transforms.
virtual void Evaluate(b2Manifold* manifold, const b2Transform& xfA, virtual void Evaluate(b2Manifold* manifold, const b2Transform& xfA, con
const b2Transform& xfB) = 0; st b2Transform& xfB) = 0;
protected: protected:
friend class b2ContactManager; friend class b2ContactManager;
friend class b2World; friend class b2World;
friend class b2ContactSolver; friend class b2ContactSolver;
friend class b2Body; friend class b2Body;
friend class b2Fixture; friend class b2Fixture;
// Flags stored in m_flags // Flags stored in m_flags
enum enum
{ {
// Used when crawling contact graph when forming islands. // Used when crawling contact graph when forming islands.
e_islandFlag = 0x0001, e_islandFlag = 0x0001,
// Set when the shapes are touching. // Set when the shapes are touching.
e_touchingFlag = 0x0002, e_touchingFlag = 0x0002,
// This contact can be disabled (by user) // This contact can be disabled (by user)
e_enabledFlag = 0x0004, e_enabledFlag = 0x0004,
// This contact needs filtering because a fixture filter was // This contact needs filtering because a fixture filter was change
changed. d.
e_filterFlag = 0x0008, e_filterFlag = 0x0008,
// This bullet contact had a TOI event // This bullet contact had a TOI event
e_bulletHitFlag = 0x0010, e_bulletHitFlag = 0x0010,
// This contact has a valid TOI in m_toi // This contact has a valid TOI in m_toi
e_toiFlag = 0x0020 e_toiFlag = 0x0020
}; };
/// Flag this contact for filtering. Filtering will occur the next t /// Flag this contact for filtering. Filtering will occur the next time
ime step. step.
void FlagForFiltering(); void FlagForFiltering();
static void AddType(b2ContactCreateFcn* createFcn, b2ContactDestroyF static void AddType(b2ContactCreateFcn* createFcn, b2ContactDestroyFcn*
cn* destroyFcn, destroyFcn,
b2Shape::Type typeA, b2Shape b2Shape::Type typeA, b2Shape::Type typeB);
::Type typeB); static void InitializeRegisters();
static void InitializeRegisters(); static b2Contact* Create(b2Fixture* fixtureA, int32 indexA, b2Fixture*
static b2Contact* Create(b2Fixture* fixtureA, int32 indexA, b2Fixtur fixtureB, int32 indexB, b2BlockAllocator* allocator);
e* fixtureB, int32 indexB, b2BlockAllocator* allocator); static void Destroy(b2Contact* contact, b2Shape::Type typeA, b2Shape::T
static void Destroy(b2Contact* contact, b2Shape::Type typeA, b2Shape ype typeB, b2BlockAllocator* allocator);
::Type typeB, b2BlockAllocator* allocator); static void Destroy(b2Contact* contact, b2BlockAllocator* allocator);
static void Destroy(b2Contact* contact, b2BlockAllocator* allocator)
;
b2Contact() : m_fixtureA(NULL), m_fixtureB(NULL) {} b2Contact() : m_fixtureA(NULL), m_fixtureB(NULL) {}
b2Contact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, in b2Contact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32
t32 indexB); indexB);
virtual ~b2Contact() {} virtual ~b2Contact() {}
void Update(b2ContactListener* listener); void Update(b2ContactListener* listener);
static b2ContactRegister s_registers[b2Shape::e_typeCount][b2Shape:: static b2ContactRegister s_registers[b2Shape::e_typeCount][b2Shape::e_t
e_typeCount]; ypeCount];
static bool s_initialized; static bool s_initialized;
uint32 m_flags; uint32 m_flags;
// World pool and list pointers. // World pool and list pointers.
b2Contact* m_prev; b2Contact* m_prev;
b2Contact* m_next; b2Contact* m_next;
// Nodes for connecting bodies. // Nodes for connecting bodies.
b2ContactEdge m_nodeA; b2ContactEdge m_nodeA;
b2ContactEdge m_nodeB; b2ContactEdge m_nodeB;
b2Fixture* m_fixtureA; b2Fixture* m_fixtureA;
b2Fixture* m_fixtureB; b2Fixture* m_fixtureB;
int32 m_indexA; int32 m_indexA;
int32 m_indexB; int32 m_indexB;
b2Manifold m_manifold; b2Manifold m_manifold;
int32 m_toiCount; int32 m_toiCount;
float32 m_toi; float32 m_toi;
float32 m_friction; float32 m_friction;
float32 m_restitution; float32 m_restitution;
}; };
inline b2Manifold* b2Contact::GetManifold() inline b2Manifold* b2Contact::GetManifold()
{ {
return &m_manifold; return &m_manifold;
} }
inline const b2Manifold* b2Contact::GetManifold() const inline const b2Manifold* b2Contact::GetManifold() const
{ {
return &m_manifold; return &m_manifold;
} }
inline void b2Contact::GetWorldManifold(b2WorldManifold* worldManifold) con st inline void b2Contact::GetWorldManifold(b2WorldManifold* worldManifold) con st
{ {
const b2Body* bodyA = m_fixtureA->GetBody(); const b2Body* bodyA = m_fixtureA->GetBody();
const b2Body* bodyB = m_fixtureB->GetBody(); const b2Body* bodyB = m_fixtureB->GetBody();
const b2Shape* shapeA = m_fixtureA->GetShape(); const b2Shape* shapeA = m_fixtureA->GetShape();
const b2Shape* shapeB = m_fixtureB->GetShape(); const b2Shape* shapeB = m_fixtureB->GetShape();
worldManifold->Initialize(&m_manifold, bodyA->GetTransform(), shapeA ->m_radius, bodyB->GetTransform(), shapeB->m_radius); worldManifold->Initialize(&m_manifold, bodyA->GetTransform(), shapeA->m _radius, bodyB->GetTransform(), shapeB->m_radius);
} }
inline void b2Contact::SetEnabled(bool flag) inline void b2Contact::SetEnabled(bool flag)
{ {
if (flag) if (flag)
{ {
m_flags |= e_enabledFlag; m_flags |= e_enabledFlag;
} }
else else
{ {
m_flags &= ~e_enabledFlag; m_flags &= ~e_enabledFlag;
} }
} }
inline bool b2Contact::IsEnabled() const inline bool b2Contact::IsEnabled() const
{ {
return (m_flags & e_enabledFlag) == e_enabledFlag; return (m_flags & e_enabledFlag) == e_enabledFlag;
} }
inline bool b2Contact::IsTouching() const inline bool b2Contact::IsTouching() const
{ {
return (m_flags & e_touchingFlag) == e_touchingFlag; return (m_flags & e_touchingFlag) == e_touchingFlag;
} }
inline b2Contact* b2Contact::GetNext() inline b2Contact* b2Contact::GetNext()
{ {
return m_next; return m_next;
} }
inline const b2Contact* b2Contact::GetNext() const inline const b2Contact* b2Contact::GetNext() const
{ {
return m_next; return m_next;
} }
inline b2Fixture* b2Contact::GetFixtureA() inline b2Fixture* b2Contact::GetFixtureA()
{ {
return m_fixtureA; return m_fixtureA;
} }
inline const b2Fixture* b2Contact::GetFixtureA() const inline const b2Fixture* b2Contact::GetFixtureA() const
{ {
return m_fixtureA; return m_fixtureA;
} }
inline b2Fixture* b2Contact::GetFixtureB() inline b2Fixture* b2Contact::GetFixtureB()
{ {
return m_fixtureB; return m_fixtureB;
} }
inline int32 b2Contact::GetChildIndexA() const inline int32 b2Contact::GetChildIndexA() const
{ {
return m_indexA; return m_indexA;
} }
inline const b2Fixture* b2Contact::GetFixtureB() const inline const b2Fixture* b2Contact::GetFixtureB() const
{ {
return m_fixtureB; return m_fixtureB;
} }
inline int32 b2Contact::GetChildIndexB() const inline int32 b2Contact::GetChildIndexB() const
{ {
return m_indexB; return m_indexB;
} }
inline void b2Contact::FlagForFiltering() inline void b2Contact::FlagForFiltering()
{ {
m_flags |= e_filterFlag; m_flags |= e_filterFlag;
} }
inline void b2Contact::SetFriction(float32 friction) inline void b2Contact::SetFriction(float32 friction)
{ {
m_friction = friction; m_friction = friction;
} }
inline float32 b2Contact::GetFriction() const inline float32 b2Contact::GetFriction() const
{ {
return m_friction; return m_friction;
} }
inline void b2Contact::ResetFriction() inline void b2Contact::ResetFriction()
{ {
m_friction = b2MixFriction(m_fixtureA->m_friction, m_fixtureB->m_fri ction); m_friction = b2MixFriction(m_fixtureA->m_friction, m_fixtureB->m_fricti on);
} }
inline void b2Contact::SetRestitution(float32 restitution) inline void b2Contact::SetRestitution(float32 restitution)
{ {
m_restitution = restitution; m_restitution = restitution;
} }
inline float32 b2Contact::GetRestitution() const inline float32 b2Contact::GetRestitution() const
{ {
return m_restitution; return m_restitution;
} }
inline void b2Contact::ResetRestitution() inline void b2Contact::ResetRestitution()
{ {
m_restitution = b2MixRestitution(m_fixtureA->m_restitution, m_fixtur eB->m_restitution); m_restitution = b2MixRestitution(m_fixtureA->m_restitution, m_fixtureB- >m_restitution);
} }
#endif #endif
 End of changes. 63 change blocks. 
157 lines changed or deleted 153 lines changed or added


 b2ContactManager.h   b2ContactManager.h 
skipping to change at line 33 skipping to change at line 33
class b2Contact; class b2Contact;
class b2ContactFilter; class b2ContactFilter;
class b2ContactListener; class b2ContactListener;
class b2BlockAllocator; class b2BlockAllocator;
// Delegate of b2World. // Delegate of b2World.
class b2ContactManager class b2ContactManager
{ {
public: public:
b2ContactManager(); b2ContactManager();
// Broad-phase callback. // Broad-phase callback.
void AddPair(void* proxyUserDataA, void* proxyUserDataB); void AddPair(void* proxyUserDataA, void* proxyUserDataB);
void FindNewContacts(); void FindNewContacts();
void Destroy(b2Contact* c); void Destroy(b2Contact* c);
void Collide(); void Collide();
b2BroadPhase m_broadPhase; b2BroadPhase m_broadPhase;
b2Contact* m_contactList; b2Contact* m_contactList;
int32 m_contactCount; int32 m_contactCount;
b2ContactFilter* m_contactFilter; b2ContactFilter* m_contactFilter;
b2ContactListener* m_contactListener; b2ContactListener* m_contactListener;
b2BlockAllocator* m_allocator; b2BlockAllocator* m_allocator;
}; };
#endif #endif
 End of changes. 6 change blocks. 
12 lines changed or deleted 12 lines changed or added


 b2ContactSolver.h   b2ContactSolver.h 
skipping to change at line 33 skipping to change at line 33
#include <Box2D/Collision/b2Collision.h> #include <Box2D/Collision/b2Collision.h>
#include <Box2D/Dynamics/b2TimeStep.h> #include <Box2D/Dynamics/b2TimeStep.h>
class b2Contact; class b2Contact;
class b2Body; class b2Body;
class b2StackAllocator; class b2StackAllocator;
struct b2ContactPositionConstraint; struct b2ContactPositionConstraint;
struct b2VelocityConstraintPoint struct b2VelocityConstraintPoint
{ {
b2Vec2 rA; b2Vec2 rA;
b2Vec2 rB; b2Vec2 rB;
float32 normalImpulse; float32 normalImpulse;
float32 tangentImpulse; float32 tangentImpulse;
float32 normalMass; float32 normalMass;
float32 tangentMass; float32 tangentMass;
float32 velocityBias; float32 velocityBias;
}; };
struct b2ContactVelocityConstraint struct b2ContactVelocityConstraint
{ {
b2VelocityConstraintPoint points[b2_maxManifoldPoints]; b2VelocityConstraintPoint points[b2_maxManifoldPoints];
b2Vec2 normal; b2Vec2 normal;
b2Mat22 normalMass; b2Mat22 normalMass;
b2Mat22 K; b2Mat22 K;
int32 indexA; int32 indexA;
int32 indexB; int32 indexB;
float32 invMassA, invMassB; float32 invMassA, invMassB;
float32 invIA, invIB; float32 invIA, invIB;
float32 friction; float32 friction;
float32 restitution; float32 restitution;
int32 pointCount; int32 pointCount;
int32 contactIndex; int32 contactIndex;
}; };
struct b2ContactSolverDef struct b2ContactSolverDef
{ {
b2TimeStep step; b2TimeStep step;
b2Contact** contacts; b2Contact** contacts;
int32 count; int32 count;
b2Position* positions; b2Position* positions;
b2Velocity* velocities; b2Velocity* velocities;
b2StackAllocator* allocator; b2StackAllocator* allocator;
}; };
class b2ContactSolver class b2ContactSolver
{ {
public: public:
b2ContactSolver(b2ContactSolverDef* def); b2ContactSolver(b2ContactSolverDef* def);
~b2ContactSolver(); ~b2ContactSolver();
void InitializeVelocityConstraints(); void InitializeVelocityConstraints();
void WarmStart(); void WarmStart();
void SolveVelocityConstraints(); void SolveVelocityConstraints();
void StoreImpulses(); void StoreImpulses();
bool SolvePositionConstraints(); bool SolvePositionConstraints();
bool SolveTOIPositionConstraints(int32 toiIndexA, int32 toiIndexB); bool SolveTOIPositionConstraints(int32 toiIndexA, int32 toiIndexB);
b2TimeStep m_step; b2TimeStep m_step;
b2Position* m_positions; b2Position* m_positions;
b2Velocity* m_velocities; b2Velocity* m_velocities;
b2StackAllocator* m_allocator; b2StackAllocator* m_allocator;
b2ContactPositionConstraint* m_positionConstraints; b2ContactPositionConstraint* m_positionConstraints;
b2ContactVelocityConstraint* m_velocityConstraints; b2ContactVelocityConstraint* m_velocityConstraints;
b2Contact** m_contacts; b2Contact** m_contacts;
int m_count; int m_count;
}; };
#endif #endif
 End of changes. 6 change blocks. 
43 lines changed or deleted 43 lines changed or added


 b2Distance.h   b2Distance.h 
skipping to change at line 31 skipping to change at line 31
#define B2_DISTANCE_H #define B2_DISTANCE_H
#include <Box2D/Common/b2Math.h> #include <Box2D/Common/b2Math.h>
class b2Shape; class b2Shape;
/// A distance proxy is used by the GJK algorithm. /// A distance proxy is used by the GJK algorithm.
/// It encapsulates any shape. /// It encapsulates any shape.
struct b2DistanceProxy struct b2DistanceProxy
{ {
b2DistanceProxy() : m_vertices(NULL), m_count(0), m_radius(0.0f) {} b2DistanceProxy() : m_vertices(NULL), m_count(0), m_radius(0.0f) {}
/// Initialize the proxy using the given shape. The shape /// Initialize the proxy using the given shape. The shape
/// must remain in scope while the proxy is in use. /// must remain in scope while the proxy is in use.
void Set(const b2Shape* shape, int32 index); void Set(const b2Shape* shape, int32 index);
/// Get the supporting vertex index in the given direction. /// Get the supporting vertex index in the given direction.
int32 GetSupport(const b2Vec2& d) const; int32 GetSupport(const b2Vec2& d) const;
/// Get the supporting vertex in the given direction. /// Get the supporting vertex in the given direction.
const b2Vec2& GetSupportVertex(const b2Vec2& d) const; const b2Vec2& GetSupportVertex(const b2Vec2& d) const;
/// Get the vertex count. /// Get the vertex count.
int32 GetVertexCount() const; int32 GetVertexCount() const;
/// Get a vertex by index. Used by b2Distance. /// Get a vertex by index. Used by b2Distance.
const b2Vec2& GetVertex(int32 index) const; const b2Vec2& GetVertex(int32 index) const;
b2Vec2 m_buffer[2]; b2Vec2 m_buffer[2];
const b2Vec2* m_vertices; const b2Vec2* m_vertices;
int32 m_count; int32 m_count;
float32 m_radius; float32 m_radius;
}; };
/// Used to warm start b2Distance. /// Used to warm start b2Distance.
/// Set count to zero on first call. /// Set count to zero on first call.
struct b2SimplexCache struct b2SimplexCache
{ {
float32 metric; ///< length or area float32 metric; ///< length or area
uint16 count; uint16 count;
uint8 indexA[3]; ///< vertices on shape A uint8 indexA[3]; ///< vertices on shape A
uint8 indexB[3]; ///< vertices on shape B uint8 indexB[3]; ///< vertices on shape B
}; };
/// Input for b2Distance. /// Input for b2Distance.
/// You have to option to use the shape radii /// You have to option to use the shape radii
/// in the computation. Even /// in the computation. Even
struct b2DistanceInput struct b2DistanceInput
{ {
b2DistanceProxy proxyA; b2DistanceProxy proxyA;
b2DistanceProxy proxyB; b2DistanceProxy proxyB;
b2Transform transformA; b2Transform transformA;
b2Transform transformB; b2Transform transformB;
bool useRadii; bool useRadii;
}; };
/// Output for b2Distance. /// Output for b2Distance.
struct b2DistanceOutput struct b2DistanceOutput
{ {
b2Vec2 pointA; ///< closest point on shapeA b2Vec2 pointA; ///< closest point on shapeA
b2Vec2 pointB; ///< closest point on shapeB b2Vec2 pointB; ///< closest point on shapeB
float32 distance; float32 distance;
int32 iterations; ///< number of GJK iterations used int32 iterations; ///< number of GJK iterations used
}; };
/// Compute the closest points between two shapes. Supports any combination of: /// Compute the closest points between two shapes. Supports any combination of:
/// b2CircleShape, b2PolygonShape, b2EdgeShape. The simplex cache is input/ output. /// b2CircleShape, b2PolygonShape, b2EdgeShape. The simplex cache is input/ output.
/// On the first call set b2SimplexCache.count to zero. /// On the first call set b2SimplexCache.count to zero.
void b2Distance(b2DistanceOutput* output, void b2Distance(b2DistanceOutput* output,
b2SimplexCache* cache, b2SimplexCache* cache,
const b2DistanceInput* input); const b2DistanceInput* input);
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
inline int32 b2DistanceProxy::GetVertexCount() const inline int32 b2DistanceProxy::GetVertexCount() const
{ {
return m_count; return m_count;
} }
inline const b2Vec2& b2DistanceProxy::GetVertex(int32 index) const inline const b2Vec2& b2DistanceProxy::GetVertex(int32 index) const
{ {
b2Assert(0 <= index && index < m_count); b2Assert(0 <= index && index < m_count);
return m_vertices[index]; return m_vertices[index];
} }
inline int32 b2DistanceProxy::GetSupport(const b2Vec2& d) const inline int32 b2DistanceProxy::GetSupport(const b2Vec2& d) const
{ {
int32 bestIndex = 0; int32 bestIndex = 0;
float32 bestValue = b2Dot(m_vertices[0], d); float32 bestValue = b2Dot(m_vertices[0], d);
for (int32 i = 1; i < m_count; ++i) for (int32 i = 1; i < m_count; ++i)
{ {
float32 value = b2Dot(m_vertices[i], d); float32 value = b2Dot(m_vertices[i], d);
if (value > bestValue) if (value > bestValue)
{ {
bestIndex = i; bestIndex = i;
bestValue = value; bestValue = value;
} }
} }
return bestIndex; return bestIndex;
} }
inline const b2Vec2& b2DistanceProxy::GetSupportVertex(const b2Vec2& d) con st inline const b2Vec2& b2DistanceProxy::GetSupportVertex(const b2Vec2& d) con st
{ {
int32 bestIndex = 0; int32 bestIndex = 0;
float32 bestValue = b2Dot(m_vertices[0], d); float32 bestValue = b2Dot(m_vertices[0], d);
for (int32 i = 1; i < m_count; ++i) for (int32 i = 1; i < m_count; ++i)
{ {
float32 value = b2Dot(m_vertices[i], d); float32 value = b2Dot(m_vertices[i], d);
if (value > bestValue) if (value > bestValue)
{ {
bestIndex = i; bestIndex = i;
bestValue = value; bestValue = value;
} }
} }
return m_vertices[bestIndex]; return m_vertices[bestIndex];
} }
#endif #endif
 End of changes. 17 change blocks. 
58 lines changed or deleted 58 lines changed or added


 b2DistanceJoint.h   b2DistanceJoint.h 
skipping to change at line 32 skipping to change at line 32
#include <Box2D/Dynamics/Joints/b2Joint.h> #include <Box2D/Dynamics/Joints/b2Joint.h>
/// Distance joint definition. This requires defining an /// Distance joint definition. This requires defining an
/// anchor point on both bodies and the non-zero length of the /// anchor point on both bodies and the non-zero length of the
/// distance joint. The definition uses local anchor points /// distance joint. The definition uses local anchor points
/// so that the initial configuration can violate the constraint /// so that the initial configuration can violate the constraint
/// slightly. This helps when saving and loading a game. /// slightly. This helps when saving and loading a game.
/// @warning Do not use a zero or short length. /// @warning Do not use a zero or short length.
struct b2DistanceJointDef : public b2JointDef struct b2DistanceJointDef : public b2JointDef
{ {
b2DistanceJointDef() b2DistanceJointDef()
{ {
type = e_distanceJoint; type = e_distanceJoint;
localAnchorA.Set(0.0f, 0.0f); localAnchorA.Set(0.0f, 0.0f);
localAnchorB.Set(0.0f, 0.0f); localAnchorB.Set(0.0f, 0.0f);
length = 1.0f; length = 1.0f;
frequencyHz = 0.0f; frequencyHz = 0.0f;
dampingRatio = 0.0f; dampingRatio = 0.0f;
} }
/// Initialize the bodies, anchors, and length using the world /// Initialize the bodies, anchors, and length using the world
/// anchors. /// anchors.
void Initialize(b2Body* bodyA, b2Body* bodyB, void Initialize(b2Body* bodyA, b2Body* bodyB,
const b2Vec2& anchorA, const b2Vec2& const b2Vec2& anchorA, const b2Vec2& anchorB);
anchorB);
/// The local anchor point relative to bodyA's origin.
/// The local anchor point relative to bodyA's origin. b2Vec2 localAnchorA;
b2Vec2 localAnchorA;
/// The local anchor point relative to bodyB's origin.
/// The local anchor point relative to bodyB's origin. b2Vec2 localAnchorB;
b2Vec2 localAnchorB;
/// The natural length between the anchor points.
/// The natural length between the anchor points. float32 length;
float32 length;
/// The mass-spring-damper frequency in Hertz. A value of 0
/// The mass-spring-damper frequency in Hertz. A value of 0 /// disables softness.
/// disables softness. float32 frequencyHz;
float32 frequencyHz;
/// The damping ratio. 0 = no damping, 1 = critical damping. /// The damping ratio. 0 = no damping, 1 = critical damping.
float32 dampingRatio; float32 dampingRatio;
}; };
/// A distance joint constrains two points on two bodies /// A distance joint constrains two points on two bodies
/// to remain at a fixed distance from each other. You can view /// to remain at a fixed distance from each other. You can view
/// this as a massless, rigid rod. /// this as a massless, rigid rod.
class b2DistanceJoint : public b2Joint class b2DistanceJoint : public b2Joint
{ {
public: public:
b2Vec2 GetAnchorA() const; b2Vec2 GetAnchorA() const;
b2Vec2 GetAnchorB() const; b2Vec2 GetAnchorB() const;
/// Get the reaction force given the inverse time step. /// Get the reaction force given the inverse time step.
/// Unit is N. /// Unit is N.
b2Vec2 GetReactionForce(float32 inv_dt) const; b2Vec2 GetReactionForce(float32 inv_dt) const;
/// Get the reaction torque given the inverse time step. /// Get the reaction torque given the inverse time step.
/// Unit is N*m. This is always zero for a distance joint. /// Unit is N*m. This is always zero for a distance joint.
float32 GetReactionTorque(float32 inv_dt) const; float32 GetReactionTorque(float32 inv_dt) const;
/// The local anchor point relative to bodyA's origin. /// The local anchor point relative to bodyA's origin.
const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; }
/// The local anchor point relative to bodyB's origin. /// The local anchor point relative to bodyB's origin.
const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; }
/// Set/get the natural length. /// Set/get the natural length.
/// Manipulating the length can lead to non-physical behavior when t /// Manipulating the length can lead to non-physical behavior when the
he frequency is zero. frequency is zero.
void SetLength(float32 length); void SetLength(float32 length);
float32 GetLength() const; float32 GetLength() const;
/// Set/get frequency in Hz. /// Set/get frequency in Hz.
void SetFrequency(float32 hz); void SetFrequency(float32 hz);
float32 GetFrequency() const; float32 GetFrequency() const;
/// Set/get damping ratio. /// Set/get damping ratio.
void SetDampingRatio(float32 ratio); void SetDampingRatio(float32 ratio);
float32 GetDampingRatio() const; float32 GetDampingRatio() const;
/// Dump joint to dmLog /// Dump joint to dmLog
void Dump(); void Dump();
protected: protected:
friend class b2Joint; friend class b2Joint;
b2DistanceJoint(const b2DistanceJointDef* data); b2DistanceJoint(const b2DistanceJointDef* data);
void InitVelocityConstraints(const b2SolverData& data); void InitVelocityConstraints(const b2SolverData& data);
void SolveVelocityConstraints(const b2SolverData& data); void SolveVelocityConstraints(const b2SolverData& data);
bool SolvePositionConstraints(const b2SolverData& data); bool SolvePositionConstraints(const b2SolverData& data);
float32 m_frequencyHz; float32 m_frequencyHz;
float32 m_dampingRatio; float32 m_dampingRatio;
float32 m_bias; float32 m_bias;
// Solver shared // Solver shared
b2Vec2 m_localAnchorA; b2Vec2 m_localAnchorA;
b2Vec2 m_localAnchorB; b2Vec2 m_localAnchorB;
float32 m_gamma; float32 m_gamma;
float32 m_impulse; float32 m_impulse;
float32 m_length; float32 m_length;
// Solver temp // Solver temp
int32 m_indexA; int32 m_indexA;
int32 m_indexB; int32 m_indexB;
b2Vec2 m_u; b2Vec2 m_u;
b2Vec2 m_rA; b2Vec2 m_rA;
b2Vec2 m_rB; b2Vec2 m_rB;
b2Vec2 m_localCenterA; b2Vec2 m_localCenterA;
b2Vec2 m_localCenterB; b2Vec2 m_localCenterB;
float32 m_invMassA; float32 m_invMassA;
float32 m_invMassB; float32 m_invMassB;
float32 m_invIA; float32 m_invIA;
float32 m_invIB; float32 m_invIB;
float32 m_mass; float32 m_mass;
}; };
inline void b2DistanceJoint::SetLength(float32 length) inline void b2DistanceJoint::SetLength(float32 length)
{ {
m_length = length; m_length = length;
} }
inline float32 b2DistanceJoint::GetLength() const inline float32 b2DistanceJoint::GetLength() const
{ {
return m_length; return m_length;
} }
inline void b2DistanceJoint::SetFrequency(float32 hz) inline void b2DistanceJoint::SetFrequency(float32 hz)
{ {
m_frequencyHz = hz; m_frequencyHz = hz;
} }
inline float32 b2DistanceJoint::GetFrequency() const inline float32 b2DistanceJoint::GetFrequency() const
{ {
return m_frequencyHz; return m_frequencyHz;
} }
inline void b2DistanceJoint::SetDampingRatio(float32 ratio) inline void b2DistanceJoint::SetDampingRatio(float32 ratio)
{ {
m_dampingRatio = ratio; m_dampingRatio = ratio;
} }
inline float32 b2DistanceJoint::GetDampingRatio() const inline float32 b2DistanceJoint::GetDampingRatio() const
{ {
return m_dampingRatio; return m_dampingRatio;
} }
#endif #endif
 End of changes. 13 change blocks. 
97 lines changed or deleted 96 lines changed or added


 b2Draw.h   b2Draw.h 
skipping to change at line 24 skipping to change at line 24
* 2. Altered source versions must be plainly marked as such, and must not b e * 2. Altered source versions must be plainly marked as such, and must not b e
* misrepresented as being the original software. * misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution . * 3. This notice may not be removed or altered from any source distribution .
*/ */
#include <Box2D/Common/b2Math.h> #include <Box2D/Common/b2Math.h>
/// Color for debug drawing. Each value has the range [0,1]. /// Color for debug drawing. Each value has the range [0,1].
struct b2Color struct b2Color
{ {
b2Color() {} b2Color() {}
b2Color(float32 r, float32 g, float32 b) : r(r), g(g), b(b) {} b2Color(float32 r, float32 g, float32 b) : r(r), g(g), b(b) {}
void Set(float32 ri, float32 gi, float32 bi) { r = ri; g = gi; b = b void Set(float32 ri, float32 gi, float32 bi) { r = ri; g = gi; b = bi;
i; } }
float32 r, g, b; float32 r, g, b;
}; };
/// Implement and register this class with a b2World to provide debug drawi ng of physics /// Implement and register this class with a b2World to provide debug drawi ng of physics
/// entities in your game. /// entities in your game.
class b2Draw class b2Draw
{ {
public: public:
b2Draw(); b2Draw();
virtual ~b2Draw() {} virtual ~b2Draw() {}
enum enum
{ {
e_shapeBit = 0x0001, ///< e_shapeBit = 0x0001, ///< draw shapes
draw shapes e_jointBit = 0x0002, ///< draw joint connections
e_jointBit = 0x0002, ///< e_aabbBit = 0x0004, ///< draw axis aligned boundi
draw joint connections ng boxes
e_aabbBit = 0x0004, ///< e_pairBit = 0x0008, ///< draw broad-phase pairs
draw axis aligned bounding boxes e_centerOfMassBit = 0x0010 ///< draw center of mass frame
e_pairBit = 0x0008, ///< };
draw broad-phase pairs
e_centerOfMassBit = 0x0010 ///< draw ce
nter of mass frame
};
/// Set the drawing flags. /// Set the drawing flags.
void SetFlags(uint32 flags); void SetFlags(uint32 flags);
/// Get the drawing flags. /// Get the drawing flags.
uint32 GetFlags() const; uint32 GetFlags() const;
/// Append flags to the current flags. /// Append flags to the current flags.
void AppendFlags(uint32 flags); void AppendFlags(uint32 flags);
/// Clear flags from the current flags. /// Clear flags from the current flags.
void ClearFlags(uint32 flags); void ClearFlags(uint32 flags);
/// Draw a closed polygon provided in CCW order. /// Draw a closed polygon provided in CCW order.
virtual void DrawPolygon(const b2Vec2* vertices, int32 vertexCount, virtual void DrawPolygon(const b2Vec2* vertices, int32 vertexCount, con
const b2Color& color) = 0; st b2Color& color) = 0;
/// Draw a solid closed polygon provided in CCW order. /// Draw a solid closed polygon provided in CCW order.
virtual void DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCo virtual void DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount
unt, const b2Color& color) = 0; , const b2Color& color) = 0;
/// Draw a circle. /// Draw a circle.
virtual void DrawCircle(const b2Vec2& center, float32 radius, const virtual void DrawCircle(const b2Vec2& center, float32 radius, const b2C
b2Color& color) = 0; olor& color) = 0;
/// Draw a solid circle. /// Draw a solid circle.
virtual void DrawSolidCircle(const b2Vec2& center, float32 radius, c virtual void DrawSolidCircle(const b2Vec2& center, float32 radius, cons
onst b2Vec2& axis, const b2Color& color) = 0; t b2Vec2& axis, const b2Color& color) = 0;
/// Draw a line segment. /// Draw a line segment.
virtual void DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b virtual void DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Co
2Color& color) = 0; lor& color) = 0;
/// Draw a transform. Choose your own length scale. /// Draw a transform. Choose your own length scale.
/// @param xf a transform. /// @param xf a transform.
virtual void DrawTransform(const b2Transform& xf) = 0; virtual void DrawTransform(const b2Transform& xf) = 0;
protected: protected:
uint32 m_drawFlags; uint32 m_drawFlags;
}; };
 End of changes. 15 change blocks. 
47 lines changed or deleted 43 lines changed or added


 b2DynamicTree.h   b2DynamicTree.h 
skipping to change at line 30 skipping to change at line 30
#define B2_DYNAMIC_TREE_H #define B2_DYNAMIC_TREE_H
#include <Box2D/Collision/b2Collision.h> #include <Box2D/Collision/b2Collision.h>
#include <Box2D/Common/b2GrowableStack.h> #include <Box2D/Common/b2GrowableStack.h>
#define b2_nullNode (-1) #define b2_nullNode (-1)
/// A node in the dynamic tree. The client does not interact with this dire ctly. /// A node in the dynamic tree. The client does not interact with this dire ctly.
struct b2TreeNode struct b2TreeNode
{ {
bool IsLeaf() const bool IsLeaf() const
{ {
return child1 == b2_nullNode; return child1 == b2_nullNode;
} }
/// Enlarged AABB /// Enlarged AABB
b2AABB aabb; b2AABB aabb;
void* userData; void* userData;
union union
{ {
int32 parent; int32 parent;
int32 next; int32 next;
}; };
int32 child1; int32 child1;
int32 child2; int32 child2;
// leaf = 0, free node = -1 // leaf = 0, free node = -1
int32 height; int32 height;
}; };
/// A dynamic AABB tree broad-phase, inspired by Nathanael Presson's btDbvt . /// A dynamic AABB tree broad-phase, inspired by Nathanael Presson's btDbvt .
/// A dynamic tree arranges data in a binary tree to accelerate /// A dynamic tree arranges data in a binary tree to accelerate
/// queries such as volume queries and ray casts. Leafs are proxies /// queries such as volume queries and ray casts. Leafs are proxies
/// with an AABB. In the tree we expand the proxy AABB by b2_fatAABBFactor /// with an AABB. In the tree we expand the proxy AABB by b2_fatAABBFactor
/// so that the proxy AABB is bigger than the client object. This allows th e client /// so that the proxy AABB is bigger than the client object. This allows th e client
/// object to move by small amounts without triggering a tree update. /// object to move by small amounts without triggering a tree update.
/// ///
/// Nodes are pooled and relocatable, so we use node indices rather than po inters. /// Nodes are pooled and relocatable, so we use node indices rather than po inters.
class b2DynamicTree class b2DynamicTree
{ {
public: public:
/// Constructing the tree initializes the node pool. /// Constructing the tree initializes the node pool.
b2DynamicTree(); b2DynamicTree();
/// Destroy the tree, freeing the node pool. /// Destroy the tree, freeing the node pool.
~b2DynamicTree(); ~b2DynamicTree();
/// Create a proxy. Provide a tight fitting AABB and a userData poin /// Create a proxy. Provide a tight fitting AABB and a userData pointer
ter. .
int32 CreateProxy(const b2AABB& aabb, void* userData); int32 CreateProxy(const b2AABB& aabb, void* userData);
/// Destroy a proxy. This asserts if the id is invalid. /// Destroy a proxy. This asserts if the id is invalid.
void DestroyProxy(int32 proxyId); void DestroyProxy(int32 proxyId);
/// Move a proxy with a swepted AABB. If the proxy has moved outside /// Move a proxy with a swepted AABB. If the proxy has moved outside of
of its fattened AABB, its fattened AABB,
/// then the proxy is removed from the tree and re-inserted. Otherwi /// then the proxy is removed from the tree and re-inserted. Otherwise
se /// the function returns immediately.
/// the function returns immediately. /// @return true if the proxy was re-inserted.
/// @return true if the proxy was re-inserted. bool MoveProxy(int32 proxyId, const b2AABB& aabb1, const b2Vec2& displa
bool MoveProxy(int32 proxyId, const b2AABB& aabb1, const b2Vec2& dis cement);
placement);
/// Get proxy user data.
/// Get proxy user data. /// @return the proxy user data or 0 if the id is invalid.
/// @return the proxy user data or 0 if the id is invalid. void* GetUserData(int32 proxyId) const;
void* GetUserData(int32 proxyId) const;
/// Get the fat AABB for a proxy.
/// Get the fat AABB for a proxy. const b2AABB& GetFatAABB(int32 proxyId) const;
const b2AABB& GetFatAABB(int32 proxyId) const;
/// Query an AABB for overlapping proxies. The callback class
/// Query an AABB for overlapping proxies. The callback class /// is called for each proxy that overlaps the supplied AABB.
/// is called for each proxy that overlaps the supplied AABB. template <typename T>
template <typename T> void Query(T* callback, const b2AABB& aabb) const;
void Query(T* callback, const b2AABB& aabb) const;
/// Ray-cast against the proxies in the tree. This relies on the callba
/// Ray-cast against the proxies in the tree. This relies on the cal ck
lback /// to perform a exact ray-cast in the case were the proxy contains a s
/// to perform a exact ray-cast in the case were the proxy contains hape.
a shape. /// The callback also performs the any collision filtering. This has pe
/// The callback also performs the any collision filtering. This has rformance
performance /// roughly equal to k * log(n), where k is the number of collisions an
/// roughly equal to k * log(n), where k is the number of collisions d n is the
and n is the /// number of proxies in the tree.
/// number of proxies in the tree. /// @param input the ray-cast input data. The ray extends from p1 to p1
/// @param input the ray-cast input data. The ray extends from p1 to + maxFraction * (p2 - p1).
p1 + maxFraction * (p2 - p1). /// @param callback a callback class that is called for each proxy that
/// @param callback a callback class that is called for each proxy t is hit by the ray.
hat is hit by the ray. template <typename T>
template <typename T> void RayCast(T* callback, const b2RayCastInput& input) const;
void RayCast(T* callback, const b2RayCastInput& input) const;
/// Validate this tree. For testing.
/// Validate this tree. For testing. void Validate() const;
void Validate() const;
/// Compute the height of the binary tree in O(N) time. Should not be
/// Compute the height of the binary tree in O(N) time. Should not b /// called often.
e int32 GetHeight() const;
/// called often.
int32 GetHeight() const; /// Get the maximum balance of an node in the tree. The balance is the
difference
/// Get the maximum balance of an node in the tree. The balance is t /// in height of the two children of a node.
he difference int32 GetMaxBalance() const;
/// in height of the two children of a node.
int32 GetMaxBalance() const;
/// Get the ratio of the sum of the node areas to the root area. /// Get the ratio of the sum of the node areas to the root area.
float32 GetAreaRatio() const; float32 GetAreaRatio() const;
/// Build an optimal tree. Very expensive. For testing. /// Build an optimal tree. Very expensive. For testing.
void RebuildBottomUp(); void RebuildBottomUp();
private: private:
int32 AllocateNode(); int32 AllocateNode();
void FreeNode(int32 node); void FreeNode(int32 node);
void InsertLeaf(int32 node); void InsertLeaf(int32 node);
void RemoveLeaf(int32 node); void RemoveLeaf(int32 node);
int32 Balance(int32 index); int32 Balance(int32 index);
int32 ComputeHeight() const; int32 ComputeHeight() const;
int32 ComputeHeight(int32 nodeId) const; int32 ComputeHeight(int32 nodeId) const;
void ValidateStructure(int32 index) const; void ValidateStructure(int32 index) const;
void ValidateMetrics(int32 index) const; void ValidateMetrics(int32 index) const;
int32 m_root; int32 m_root;
b2TreeNode* m_nodes; b2TreeNode* m_nodes;
int32 m_nodeCount; int32 m_nodeCount;
int32 m_nodeCapacity; int32 m_nodeCapacity;
int32 m_freeList; int32 m_freeList;
/// This is used to incrementally traverse the tree for re-balancing /// This is used to incrementally traverse the tree for re-balancing.
. uint32 m_path;
uint32 m_path;
int32 m_insertionCount; int32 m_insertionCount;
}; };
inline void* b2DynamicTree::GetUserData(int32 proxyId) const inline void* b2DynamicTree::GetUserData(int32 proxyId) const
{ {
b2Assert(0 <= proxyId && proxyId < m_nodeCapacity); b2Assert(0 <= proxyId && proxyId < m_nodeCapacity);
return m_nodes[proxyId].userData; return m_nodes[proxyId].userData;
} }
inline const b2AABB& b2DynamicTree::GetFatAABB(int32 proxyId) const inline const b2AABB& b2DynamicTree::GetFatAABB(int32 proxyId) const
{ {
b2Assert(0 <= proxyId && proxyId < m_nodeCapacity); b2Assert(0 <= proxyId && proxyId < m_nodeCapacity);
return m_nodes[proxyId].aabb; return m_nodes[proxyId].aabb;
} }
template <typename T> template <typename T>
inline void b2DynamicTree::Query(T* callback, const b2AABB& aabb) const inline void b2DynamicTree::Query(T* callback, const b2AABB& aabb) const
{ {
b2GrowableStack<int32, 256> stack; b2GrowableStack<int32, 256> stack;
stack.Push(m_root); stack.Push(m_root);
while (stack.GetCount() > 0) while (stack.GetCount() > 0)
{ {
int32 nodeId = stack.Pop(); int32 nodeId = stack.Pop();
if (nodeId == b2_nullNode) if (nodeId == b2_nullNode)
{ {
continue; continue;
} }
const b2TreeNode* node = m_nodes + nodeId; const b2TreeNode* node = m_nodes + nodeId;
if (b2TestOverlap(node->aabb, aabb)) if (b2TestOverlap(node->aabb, aabb))
{ {
if (node->IsLeaf()) if (node->IsLeaf())
{ {
bool proceed = callback->QueryCallback(nodeI bool proceed = callback->QueryCallback(nodeId);
d); if (proceed == false)
if (proceed == false) {
{ return;
return; }
} }
} else
else {
{ stack.Push(node->child1);
stack.Push(node->child1); stack.Push(node->child2);
stack.Push(node->child2); }
} }
} }
}
} }
template <typename T> template <typename T>
inline void b2DynamicTree::RayCast(T* callback, const b2RayCastInput& input ) const inline void b2DynamicTree::RayCast(T* callback, const b2RayCastInput& input ) const
{ {
b2Vec2 p1 = input.p1; b2Vec2 p1 = input.p1;
b2Vec2 p2 = input.p2; b2Vec2 p2 = input.p2;
b2Vec2 r = p2 - p1; b2Vec2 r = p2 - p1;
b2Assert(r.LengthSquared() > 0.0f); b2Assert(r.LengthSquared() > 0.0f);
r.Normalize(); r.Normalize();
// v is perpendicular to the segment. // v is perpendicular to the segment.
b2Vec2 v = b2Cross(1.0f, r); b2Vec2 v = b2Cross(1.0f, r);
b2Vec2 abs_v = b2Abs(v); b2Vec2 abs_v = b2Abs(v);
// Separating axis for segment (Gino, p80). // Separating axis for segment (Gino, p80).
// |dot(v, p1 - c)| > dot(|v|, h) // |dot(v, p1 - c)| > dot(|v|, h)
float32 maxFraction = input.maxFraction; float32 maxFraction = input.maxFraction;
// Build a bounding box for the segment. // Build a bounding box for the segment.
b2AABB segmentAABB; b2AABB segmentAABB;
{ {
b2Vec2 t = p1 + maxFraction * (p2 - p1); b2Vec2 t = p1 + maxFraction * (p2 - p1);
segmentAABB.lowerBound = b2Min(p1, t); segmentAABB.lowerBound = b2Min(p1, t);
segmentAABB.upperBound = b2Max(p1, t); segmentAABB.upperBound = b2Max(p1, t);
} }
b2GrowableStack<int32, 256> stack; b2GrowableStack<int32, 256> stack;
stack.Push(m_root); stack.Push(m_root);
while (stack.GetCount() > 0) while (stack.GetCount() > 0)
{ {
int32 nodeId = stack.Pop(); int32 nodeId = stack.Pop();
if (nodeId == b2_nullNode) if (nodeId == b2_nullNode)
{ {
continue; continue;
} }
const b2TreeNode* node = m_nodes + nodeId; const b2TreeNode* node = m_nodes + nodeId;
if (b2TestOverlap(node->aabb, segmentAABB) == false) if (b2TestOverlap(node->aabb, segmentAABB) == false)
{ {
continue; continue;
} }
// Separating axis for segment (Gino, p80). // Separating axis for segment (Gino, p80).
// |dot(v, p1 - c)| > dot(|v|, h) // |dot(v, p1 - c)| > dot(|v|, h)
b2Vec2 c = node->aabb.GetCenter(); b2Vec2 c = node->aabb.GetCenter();
b2Vec2 h = node->aabb.GetExtents(); b2Vec2 h = node->aabb.GetExtents();
float32 separation = b2Abs(b2Dot(v, p1 - c)) - b2Dot(abs_v, float32 separation = b2Abs(b2Dot(v, p1 - c)) - b2Dot(abs_v, h);
h); if (separation > 0.0f)
if (separation > 0.0f) {
{ continue;
continue; }
}
if (node->IsLeaf())
if (node->IsLeaf()) {
{ b2RayCastInput subInput;
b2RayCastInput subInput; subInput.p1 = input.p1;
subInput.p1 = input.p1; subInput.p2 = input.p2;
subInput.p2 = input.p2; subInput.maxFraction = maxFraction;
subInput.maxFraction = maxFraction;
float32 value = callback->RayCastCallback(subInput, nodeId);
float32 value = callback->RayCastCallback(subInput,
nodeId); if (value == 0.0f)
{
if (value == 0.0f) // The client has terminated the ray cast.
{ return;
// The client has terminated the ray cast. }
return;
} if (value > 0.0f)
{
if (value > 0.0f) // Update segment bounding box.
{ maxFraction = value;
// Update segment bounding box. b2Vec2 t = p1 + maxFraction * (p2 - p1);
maxFraction = value; segmentAABB.lowerBound = b2Min(p1, t);
b2Vec2 t = p1 + maxFraction * (p2 - p1); segmentAABB.upperBound = b2Max(p1, t);
segmentAABB.lowerBound = b2Min(p1, t); }
segmentAABB.upperBound = b2Max(p1, t); }
} else
} {
else stack.Push(node->child1);
{ stack.Push(node->child2);
stack.Push(node->child1); }
stack.Push(node->child2); }
}
}
} }
#endif #endif
 End of changes. 24 change blocks. 
217 lines changed or deleted 211 lines changed or added


 b2EdgeAndCircleContact.h   b2EdgeAndCircleContact.h 
skipping to change at line 29 skipping to change at line 29
#ifndef B2_EDGE_AND_CIRCLE_CONTACT_H #ifndef B2_EDGE_AND_CIRCLE_CONTACT_H
#define B2_EDGE_AND_CIRCLE_CONTACT_H #define B2_EDGE_AND_CIRCLE_CONTACT_H
#include <Box2D/Dynamics/Contacts/b2Contact.h> #include <Box2D/Dynamics/Contacts/b2Contact.h>
class b2BlockAllocator; class b2BlockAllocator;
class b2EdgeAndCircleContact : public b2Contact class b2EdgeAndCircleContact : public b2Contact
{ {
public: public:
static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, static b2Contact* Create( b2Fixture* fixtureA, int32 indexA,
b2Fixture* f b2Fixture* fixtureB, int32 indexB, b2BlockA
ixtureB, int32 indexB, b2BlockAllocator* allocator); llocator* allocator);
static void Destroy(b2Contact* contact, b2BlockAllocator* allocator) static void Destroy(b2Contact* contact, b2BlockAllocator* allocator);
;
b2EdgeAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB); b2EdgeAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB);
~b2EdgeAndCircleContact() {} ~b2EdgeAndCircleContact() {}
void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2 Transform& xfB); void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Tra nsform& xfB);
}; };
#endif #endif
 End of changes. 3 change blocks. 
8 lines changed or deleted 7 lines changed or added


 b2EdgeAndPolygonContact.h   b2EdgeAndPolygonContact.h 
skipping to change at line 29 skipping to change at line 29
#ifndef B2_EDGE_AND_POLYGON_CONTACT_H #ifndef B2_EDGE_AND_POLYGON_CONTACT_H
#define B2_EDGE_AND_POLYGON_CONTACT_H #define B2_EDGE_AND_POLYGON_CONTACT_H
#include <Box2D/Dynamics/Contacts/b2Contact.h> #include <Box2D/Dynamics/Contacts/b2Contact.h>
class b2BlockAllocator; class b2BlockAllocator;
class b2EdgeAndPolygonContact : public b2Contact class b2EdgeAndPolygonContact : public b2Contact
{ {
public: public:
static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, static b2Contact* Create( b2Fixture* fixtureA, int32 indexA,
b2Fixture* f b2Fixture* fixtureB, int32 indexB, b2BlockA
ixtureB, int32 indexB, b2BlockAllocator* allocator); llocator* allocator);
static void Destroy(b2Contact* contact, b2BlockAllocator* allocator) static void Destroy(b2Contact* contact, b2BlockAllocator* allocator);
;
b2EdgeAndPolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB); b2EdgeAndPolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB);
~b2EdgeAndPolygonContact() {} ~b2EdgeAndPolygonContact() {}
void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2 Transform& xfB); void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Tra nsform& xfB);
}; };
#endif #endif
 End of changes. 3 change blocks. 
8 lines changed or deleted 7 lines changed or added


 b2EdgeShape.h   b2EdgeShape.h 
skipping to change at line 30 skipping to change at line 30
#define B2_EDGE_SHAPE_H #define B2_EDGE_SHAPE_H
#include <Box2D/Collision/Shapes/b2Shape.h> #include <Box2D/Collision/Shapes/b2Shape.h>
/// A line segment (edge) shape. These can be connected in chains or loops /// A line segment (edge) shape. These can be connected in chains or loops
/// to other edge shapes. The connectivity information is used to ensure /// to other edge shapes. The connectivity information is used to ensure
/// correct contact normals. /// correct contact normals.
class b2EdgeShape : public b2Shape class b2EdgeShape : public b2Shape
{ {
public: public:
b2EdgeShape(); b2EdgeShape();
/// Set this as an isolated edge. /// Set this as an isolated edge.
void Set(const b2Vec2& v1, const b2Vec2& v2); void Set(const b2Vec2& v1, const b2Vec2& v2);
/// Implement b2Shape. /// Implement b2Shape.
b2Shape* Clone(b2BlockAllocator* allocator) const; b2Shape* Clone(b2BlockAllocator* allocator) const;
/// @see b2Shape::GetChildCount /// @see b2Shape::GetChildCount
int32 GetChildCount() const; int32 GetChildCount() const;
/// @see b2Shape::TestPoint /// @see b2Shape::TestPoint
bool TestPoint(const b2Transform& transform, const b2Vec2& p) const; bool TestPoint(const b2Transform& transform, const b2Vec2& p) const;
/// Implement b2Shape. /// Implement b2Shape.
bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input,
const b2Transform& transform, int32 childInd const b2Transform& transform, int32 childIndex) const;
ex) const;
/// @see b2Shape::ComputeAABB /// @see b2Shape::ComputeAABB
void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 c void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 chil
hildIndex) const; dIndex) const;
/// @see b2Shape::ComputeMass /// @see b2Shape::ComputeMass
void ComputeMass(b2MassData* massData, float32 density) const; void ComputeMass(b2MassData* massData, float32 density) const;
/// These are the edge vertices /// These are the edge vertices
b2Vec2 m_vertex1, m_vertex2; b2Vec2 m_vertex1, m_vertex2;
/// Optional adjacent vertices. These are used for smooth collision. /// Optional adjacent vertices. These are used for smooth collision.
b2Vec2 m_vertex0, m_vertex3; b2Vec2 m_vertex0, m_vertex3;
bool m_hasVertex0, m_hasVertex3; bool m_hasVertex0, m_hasVertex3;
}; };
inline b2EdgeShape::b2EdgeShape() inline b2EdgeShape::b2EdgeShape()
{ {
m_type = e_edge; m_type = e_edge;
m_radius = b2_polygonRadius; m_radius = b2_polygonRadius;
m_vertex0.x = 0.0f; m_vertex0.x = 0.0f;
m_vertex0.y = 0.0f; m_vertex0.y = 0.0f;
m_vertex3.x = 0.0f; m_vertex3.x = 0.0f;
m_vertex3.y = 0.0f; m_vertex3.y = 0.0f;
m_hasVertex0 = false; m_hasVertex0 = false;
m_hasVertex3 = false; m_hasVertex3 = false;
} }
#endif #endif
 End of changes. 11 change blocks. 
31 lines changed or deleted 30 lines changed or added


 b2Fixture.h   b2Fixture.h 
skipping to change at line 34 skipping to change at line 34
#include <Box2D/Collision/Shapes/b2Shape.h> #include <Box2D/Collision/Shapes/b2Shape.h>
class b2BlockAllocator; class b2BlockAllocator;
class b2Body; class b2Body;
class b2BroadPhase; class b2BroadPhase;
class b2Fixture; class b2Fixture;
/// This holds contact filtering data. /// This holds contact filtering data.
struct b2Filter struct b2Filter
{ {
b2Filter() b2Filter()
{ {
categoryBits = 0x0001; categoryBits = 0x0001;
maskBits = 0xFFFF; maskBits = 0xFFFF;
groupIndex = 0; groupIndex = 0;
} }
/// The collision category bits. Normally you would just set one bit /// The collision category bits. Normally you would just set one bit.
. uint16 categoryBits;
uint16 categoryBits;
/// The collision mask bits. This states the categories that this
/// The collision mask bits. This states the categories that this /// shape would accept for collision.
/// shape would accept for collision. uint16 maskBits;
uint16 maskBits;
/// Collision groups allow a certain group of objects to never collide
/// Collision groups allow a certain group of objects to never colli (negative)
de (negative) /// or always collide (positive). Zero means no collision group. Non-ze
/// or always collide (positive). Zero means no collision group. Non ro group
-zero group /// filtering always wins against the mask bits.
/// filtering always wins against the mask bits. int16 groupIndex;
int16 groupIndex;
}; };
/// A fixture definition is used to create a fixture. This class defines an /// A fixture definition is used to create a fixture. This class defines an
/// abstract fixture definition. You can reuse fixture definitions safely. /// abstract fixture definition. You can reuse fixture definitions safely.
struct b2FixtureDef struct b2FixtureDef
{ {
/// The constructor sets the default fixture definition values. /// The constructor sets the default fixture definition values.
b2FixtureDef() b2FixtureDef()
{ {
shape = NULL; shape = NULL;
userData = NULL; userData = NULL;
friction = 0.2f; friction = 0.2f;
restitution = 0.0f; restitution = 0.0f;
density = 0.0f; density = 0.0f;
isSensor = false; isSensor = false;
} }
/// The shape, this must be set. The shape will be cloned, so you /// The shape, this must be set. The shape will be cloned, so you
/// can create the shape on the stack. /// can create the shape on the stack.
const b2Shape* shape; const b2Shape* shape;
/// Use this to store application specific fixture data. /// Use this to store application specific fixture data.
void* userData; void* userData;
/// The friction coefficient, usually in the range [0,1]. /// The friction coefficient, usually in the range [0,1].
float32 friction; float32 friction;
/// The restitution (elasticity) usually in the range [0,1]. /// The restitution (elasticity) usually in the range [0,1].
float32 restitution; float32 restitution;
/// The density, usually in kg/m^2. /// The density, usually in kg/m^2.
float32 density; float32 density;
/// A sensor shape collects contact information but never generates /// A sensor shape collects contact information but never generates a c
a collision ollision
/// response. /// response.
bool isSensor; bool isSensor;
/// Contact filtering data. /// Contact filtering data.
b2Filter filter; b2Filter filter;
}; };
/// This proxy is used internally to connect fixtures to the broad-phase. /// This proxy is used internally to connect fixtures to the broad-phase.
struct b2FixtureProxy struct b2FixtureProxy
{ {
b2AABB aabb; b2AABB aabb;
b2Fixture* fixture; b2Fixture* fixture;
int32 childIndex; int32 childIndex;
int32 proxyId; int32 proxyId;
}; };
/// A fixture is used to attach a shape to a body for collision detection. A fixture /// A fixture is used to attach a shape to a body for collision detection. A fixture
/// inherits its transform from its parent. Fixtures hold additional non-ge ometric data /// inherits its transform from its parent. Fixtures hold additional non-ge ometric data
/// such as friction, collision filters, etc. /// such as friction, collision filters, etc.
/// Fixtures are created via b2Body::CreateFixture. /// Fixtures are created via b2Body::CreateFixture.
/// @warning you cannot reuse fixtures. /// @warning you cannot reuse fixtures.
class b2Fixture class b2Fixture
{ {
public: public:
/// Get the type of the child shape. You can use this to down cast t /// Get the type of the child shape. You can use this to down cast to t
o the concrete shape. he concrete shape.
/// @return the shape type. /// @return the shape type.
b2Shape::Type GetType() const; b2Shape::Type GetType() const;
/// Get the child shape. You can modify the child shape, however you /// Get the child shape. You can modify the child shape, however you sh
should not change the ould not change the
/// number of vertices because this will crash some collision cachin /// number of vertices because this will crash some collision caching m
g mechanisms. echanisms.
/// Manipulating the shape may lead to non-physical behavior. /// Manipulating the shape may lead to non-physical behavior.
b2Shape* GetShape(); b2Shape* GetShape();
const b2Shape* GetShape() const; const b2Shape* GetShape() const;
/// Set if this fixture is a sensor. /// Set if this fixture is a sensor.
void SetSensor(bool sensor); void SetSensor(bool sensor);
/// Is this fixture a sensor (non-solid)? /// Is this fixture a sensor (non-solid)?
/// @return the true if the shape is a sensor. /// @return the true if the shape is a sensor.
bool IsSensor() const; bool IsSensor() const;
/// Set the contact filtering data. This will not update contacts un /// Set the contact filtering data. This will not update contacts until
til the next time the next time
/// step when either parent body is active and awake. /// step when either parent body is active and awake.
/// This automatically calls Refilter. /// This automatically calls Refilter.
void SetFilterData(const b2Filter& filter); void SetFilterData(const b2Filter& filter);
/// Get the contact filtering data. /// Get the contact filtering data.
const b2Filter& GetFilterData() const; const b2Filter& GetFilterData() const;
/// Call this if you want to establish collision that was previously /// Call this if you want to establish collision that was previously di
disabled by b2ContactFilter::ShouldCollide. sabled by b2ContactFilter::ShouldCollide.
void Refilter(); void Refilter();
/// Get the parent body of this fixture. This is NULL if the fixture /// Get the parent body of this fixture. This is NULL if the fixture is
is not attached. not attached.
/// @return the parent body. /// @return the parent body.
b2Body* GetBody(); b2Body* GetBody();
const b2Body* GetBody() const; const b2Body* GetBody() const;
/// Get the next fixture in the parent body's fixture list. /// Get the next fixture in the parent body's fixture list.
/// @return the next shape. /// @return the next shape.
b2Fixture* GetNext(); b2Fixture* GetNext();
const b2Fixture* GetNext() const; const b2Fixture* GetNext() const;
/// Get the user data that was assigned in the fixture definition. U /// Get the user data that was assigned in the fixture definition. Use
se this to this to
/// store your application specific data. /// store your application specific data.
void* GetUserData() const; void* GetUserData() const;
/// Set the user data. Use this to store your application specific d /// Set the user data. Use this to store your application specific data
ata. .
void SetUserData(void* data); void SetUserData(void* data);
/// Test a point for containment in this fixture. /// Test a point for containment in this fixture.
/// @param p a point in world coordinates. /// @param p a point in world coordinates.
bool TestPoint(const b2Vec2& p) const; bool TestPoint(const b2Vec2& p) const;
/// Cast a ray against this shape. /// Cast a ray against this shape.
/// @param output the ray-cast results. /// @param output the ray-cast results.
/// @param input the ray-cast input parameters. /// @param input the ray-cast input parameters.
bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, i bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, int3
nt32 childIndex) const; 2 childIndex) const;
/// Get the mass data for this fixture. The mass data is based on th /// Get the mass data for this fixture. The mass data is based on the d
e density and ensity and
/// the shape. The rotational inertia is about the shape's origin. T /// the shape. The rotational inertia is about the shape's origin. This
his operation operation
/// may be expensive. /// may be expensive.
void GetMassData(b2MassData* massData) const; void GetMassData(b2MassData* massData) const;
/// Set the density of this fixture. This will _not_ automatically a /// Set the density of this fixture. This will _not_ automatically adju
djust the mass st the mass
/// of the body. You must call b2Body::ResetMassData to update the b /// of the body. You must call b2Body::ResetMassData to update the body
ody's mass. 's mass.
void SetDensity(float32 density); void SetDensity(float32 density);
/// Get the density of this fixture. /// Get the density of this fixture.
float32 GetDensity() const; float32 GetDensity() const;
/// Get the coefficient of friction. /// Get the coefficient of friction.
float32 GetFriction() const; float32 GetFriction() const;
/// Set the coefficient of friction. This will _not_ change the fric /// Set the coefficient of friction. This will _not_ change the frictio
tion of n of
/// existing contacts. /// existing contacts.
void SetFriction(float32 friction); void SetFriction(float32 friction);
/// Get the coefficient of restitution. /// Get the coefficient of restitution.
float32 GetRestitution() const; float32 GetRestitution() const;
/// Set the coefficient of restitution. This will _not_ change the r /// Set the coefficient of restitution. This will _not_ change the rest
estitution of itution of
/// existing contacts. /// existing contacts.
void SetRestitution(float32 restitution); void SetRestitution(float32 restitution);
/// Get the fixture's AABB. This AABB may be enlarge and/or stale. /// Get the fixture's AABB. This AABB may be enlarge and/or stale.
/// If you need a more accurate AABB, compute it using the shape and /// If you need a more accurate AABB, compute it using the shape and
/// the body transform. /// the body transform.
const b2AABB& GetAABB(int32 childIndex) const; const b2AABB& GetAABB(int32 childIndex) const;
/// Dump this fixture to the log file. /// Dump this fixture to the log file.
void Dump(int32 bodyIndex); void Dump(int32 bodyIndex);
protected: protected:
friend class b2Body; friend class b2Body;
friend class b2World; friend class b2World;
friend class b2Contact; friend class b2Contact;
friend class b2ContactManager; friend class b2ContactManager;
b2Fixture(); b2Fixture();
// We need separation create/destroy functions from the constructor/ // We need separation create/destroy functions from the constructor/des
destructor because tructor because
// the destructor cannot access the allocator (no destructor argumen // the destructor cannot access the allocator (no destructor arguments
ts allowed by C++). allowed by C++).
void Create(b2BlockAllocator* allocator, b2Body* body, const b2Fixtu void Create(b2BlockAllocator* allocator, b2Body* body, const b2FixtureD
reDef* def); ef* def);
void Destroy(b2BlockAllocator* allocator); void Destroy(b2BlockAllocator* allocator);
// These support body activation/deactivation. // These support body activation/deactivation.
void CreateProxies(b2BroadPhase* broadPhase, const b2Transform& xf); void CreateProxies(b2BroadPhase* broadPhase, const b2Transform& xf);
void DestroyProxies(b2BroadPhase* broadPhase); void DestroyProxies(b2BroadPhase* broadPhase);
void Synchronize(b2BroadPhase* broadPhase, const b2Transform& xf1, c onst b2Transform& xf2); void Synchronize(b2BroadPhase* broadPhase, const b2Transform& xf1, cons t b2Transform& xf2);
float32 m_density; float32 m_density;
b2Fixture* m_next; b2Fixture* m_next;
b2Body* m_body; b2Body* m_body;
b2Shape* m_shape; b2Shape* m_shape;
float32 m_friction; float32 m_friction;
float32 m_restitution; float32 m_restitution;
b2FixtureProxy* m_proxies; b2FixtureProxy* m_proxies;
int32 m_proxyCount; int32 m_proxyCount;
b2Filter m_filter; b2Filter m_filter;
bool m_isSensor; bool m_isSensor;
void* m_userData; void* m_userData;
}; };
inline b2Shape::Type b2Fixture::GetType() const inline b2Shape::Type b2Fixture::GetType() const
{ {
return m_shape->GetType(); return m_shape->GetType();
} }
inline b2Shape* b2Fixture::GetShape() inline b2Shape* b2Fixture::GetShape()
{ {
return m_shape; return m_shape;
} }
inline const b2Shape* b2Fixture::GetShape() const inline const b2Shape* b2Fixture::GetShape() const
{ {
return m_shape; return m_shape;
} }
inline bool b2Fixture::IsSensor() const inline bool b2Fixture::IsSensor() const
{ {
return m_isSensor; return m_isSensor;
} }
inline const b2Filter& b2Fixture::GetFilterData() const inline const b2Filter& b2Fixture::GetFilterData() const
{ {
return m_filter; return m_filter;
} }
inline void* b2Fixture::GetUserData() const inline void* b2Fixture::GetUserData() const
{ {
return m_userData; return m_userData;
} }
inline void b2Fixture::SetUserData(void* data) inline void b2Fixture::SetUserData(void* data)
{ {
m_userData = data; m_userData = data;
} }
inline b2Body* b2Fixture::GetBody() inline b2Body* b2Fixture::GetBody()
{ {
return m_body; return m_body;
} }
inline const b2Body* b2Fixture::GetBody() const inline const b2Body* b2Fixture::GetBody() const
{ {
return m_body; return m_body;
} }
inline b2Fixture* b2Fixture::GetNext() inline b2Fixture* b2Fixture::GetNext()
{ {
return m_next; return m_next;
} }
inline const b2Fixture* b2Fixture::GetNext() const inline const b2Fixture* b2Fixture::GetNext() const
{ {
return m_next; return m_next;
} }
inline void b2Fixture::SetDensity(float32 density) inline void b2Fixture::SetDensity(float32 density)
{ {
b2Assert(b2IsValid(density) && density >= 0.0f); b2Assert(b2IsValid(density) && density >= 0.0f);
m_density = density; m_density = density;
} }
inline float32 b2Fixture::GetDensity() const inline float32 b2Fixture::GetDensity() const
{ {
return m_density; return m_density;
} }
inline float32 b2Fixture::GetFriction() const inline float32 b2Fixture::GetFriction() const
{ {
return m_friction; return m_friction;
} }
inline void b2Fixture::SetFriction(float32 friction) inline void b2Fixture::SetFriction(float32 friction)
{ {
m_friction = friction; m_friction = friction;
} }
inline float32 b2Fixture::GetRestitution() const inline float32 b2Fixture::GetRestitution() const
{ {
return m_restitution; return m_restitution;
} }
inline void b2Fixture::SetRestitution(float32 restitution) inline void b2Fixture::SetRestitution(float32 restitution)
{ {
m_restitution = restitution; m_restitution = restitution;
} }
inline bool b2Fixture::TestPoint(const b2Vec2& p) const inline bool b2Fixture::TestPoint(const b2Vec2& p) const
{ {
return m_shape->TestPoint(m_body->GetTransform(), p); return m_shape->TestPoint(m_body->GetTransform(), p);
} }
inline bool b2Fixture::RayCast(b2RayCastOutput* output, const b2RayCastInpu t& input, int32 childIndex) const inline bool b2Fixture::RayCast(b2RayCastOutput* output, const b2RayCastInpu t& input, int32 childIndex) const
{ {
return m_shape->RayCast(output, input, m_body->GetTransform(), child Index); return m_shape->RayCast(output, input, m_body->GetTransform(), childInd ex);
} }
inline void b2Fixture::GetMassData(b2MassData* massData) const inline void b2Fixture::GetMassData(b2MassData* massData) const
{ {
m_shape->ComputeMass(massData, m_density); m_shape->ComputeMass(massData, m_density);
} }
inline const b2AABB& b2Fixture::GetAABB(int32 childIndex) const inline const b2AABB& b2Fixture::GetAABB(int32 childIndex) const
{ {
b2Assert(0 <= childIndex && childIndex < m_proxyCount); b2Assert(0 <= childIndex && childIndex < m_proxyCount);
return m_proxies[childIndex].aabb; return m_proxies[childIndex].aabb;
} }
#endif #endif
 End of changes. 40 change blocks. 
209 lines changed or deleted 208 lines changed or added


 b2FrictionJoint.h   b2FrictionJoint.h 
skipping to change at line 27 skipping to change at line 27
*/ */
#ifndef B2_FRICTION_JOINT_H #ifndef B2_FRICTION_JOINT_H
#define B2_FRICTION_JOINT_H #define B2_FRICTION_JOINT_H
#include <Box2D/Dynamics/Joints/b2Joint.h> #include <Box2D/Dynamics/Joints/b2Joint.h>
/// Friction joint definition. /// Friction joint definition.
struct b2FrictionJointDef : public b2JointDef struct b2FrictionJointDef : public b2JointDef
{ {
b2FrictionJointDef() b2FrictionJointDef()
{ {
type = e_frictionJoint; type = e_frictionJoint;
localAnchorA.SetZero(); localAnchorA.SetZero();
localAnchorB.SetZero(); localAnchorB.SetZero();
maxForce = 0.0f; maxForce = 0.0f;
maxTorque = 0.0f; maxTorque = 0.0f;
} }
/// Initialize the bodies, anchors, axis, and reference angle using /// Initialize the bodies, anchors, axis, and reference angle using the
the world world
/// anchor and world axis. /// anchor and world axis.
void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor); void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor);
/// The local anchor point relative to bodyA's origin. /// The local anchor point relative to bodyA's origin.
b2Vec2 localAnchorA; b2Vec2 localAnchorA;
/// The local anchor point relative to bodyB's origin. /// The local anchor point relative to bodyB's origin.
b2Vec2 localAnchorB; b2Vec2 localAnchorB;
/// The maximum friction force in N. /// The maximum friction force in N.
float32 maxForce; float32 maxForce;
/// The maximum friction torque in N-m. /// The maximum friction torque in N-m.
float32 maxTorque; float32 maxTorque;
}; };
/// Friction joint. This is used for top-down friction. /// Friction joint. This is used for top-down friction.
/// It provides 2D translational friction and angular friction. /// It provides 2D translational friction and angular friction.
class b2FrictionJoint : public b2Joint class b2FrictionJoint : public b2Joint
{ {
public: public:
b2Vec2 GetAnchorA() const; b2Vec2 GetAnchorA() const;
b2Vec2 GetAnchorB() const; b2Vec2 GetAnchorB() const;
b2Vec2 GetReactionForce(float32 inv_dt) const; b2Vec2 GetReactionForce(float32 inv_dt) const;
float32 GetReactionTorque(float32 inv_dt) const; float32 GetReactionTorque(float32 inv_dt) const;
/// The local anchor point relative to bodyA's origin. /// The local anchor point relative to bodyA's origin.
const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; }
/// The local anchor point relative to bodyB's origin. /// The local anchor point relative to bodyB's origin.
const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; }
/// Set the maximum friction force in N. /// Set the maximum friction force in N.
void SetMaxForce(float32 force); void SetMaxForce(float32 force);
/// Get the maximum friction force in N. /// Get the maximum friction force in N.
float32 GetMaxForce() const; float32 GetMaxForce() const;
/// Set the maximum friction torque in N*m. /// Set the maximum friction torque in N*m.
void SetMaxTorque(float32 torque); void SetMaxTorque(float32 torque);
/// Get the maximum friction torque in N*m. /// Get the maximum friction torque in N*m.
float32 GetMaxTorque() const; float32 GetMaxTorque() const;
/// Dump joint to dmLog /// Dump joint to dmLog
void Dump(); void Dump();
protected: protected:
friend class b2Joint; friend class b2Joint;
b2FrictionJoint(const b2FrictionJointDef* def); b2FrictionJoint(const b2FrictionJointDef* def);
void InitVelocityConstraints(const b2SolverData& data); void InitVelocityConstraints(const b2SolverData& data);
void SolveVelocityConstraints(const b2SolverData& data); void SolveVelocityConstraints(const b2SolverData& data);
bool SolvePositionConstraints(const b2SolverData& data); bool SolvePositionConstraints(const b2SolverData& data);
b2Vec2 m_localAnchorA; b2Vec2 m_localAnchorA;
b2Vec2 m_localAnchorB; b2Vec2 m_localAnchorB;
// Solver shared // Solver shared
b2Vec2 m_linearImpulse; b2Vec2 m_linearImpulse;
float32 m_angularImpulse; float32 m_angularImpulse;
float32 m_maxForce; float32 m_maxForce;
float32 m_maxTorque; float32 m_maxTorque;
// Solver temp // Solver temp
int32 m_indexA; int32 m_indexA;
int32 m_indexB; int32 m_indexB;
b2Vec2 m_rA; b2Vec2 m_rA;
b2Vec2 m_rB; b2Vec2 m_rB;
b2Vec2 m_localCenterA; b2Vec2 m_localCenterA;
b2Vec2 m_localCenterB; b2Vec2 m_localCenterB;
float32 m_invMassA; float32 m_invMassA;
float32 m_invMassB; float32 m_invMassB;
float32 m_invIA; float32 m_invIA;
float32 m_invIB; float32 m_invIB;
b2Mat22 m_linearMass; b2Mat22 m_linearMass;
float32 m_angularMass; float32 m_angularMass;
}; };
#endif #endif
 End of changes. 16 change blocks. 
68 lines changed or deleted 68 lines changed or added


 b2GearJoint.h   b2GearJoint.h 
skipping to change at line 28 skipping to change at line 28
#ifndef B2_GEAR_JOINT_H #ifndef B2_GEAR_JOINT_H
#define B2_GEAR_JOINT_H #define B2_GEAR_JOINT_H
#include <Box2D/Dynamics/Joints/b2Joint.h> #include <Box2D/Dynamics/Joints/b2Joint.h>
/// Gear joint definition. This definition requires two existing /// Gear joint definition. This definition requires two existing
/// revolute or prismatic joints (any combination will work). /// revolute or prismatic joints (any combination will work).
struct b2GearJointDef : public b2JointDef struct b2GearJointDef : public b2JointDef
{ {
b2GearJointDef() b2GearJointDef()
{ {
type = e_gearJoint; type = e_gearJoint;
joint1 = NULL; joint1 = NULL;
joint2 = NULL; joint2 = NULL;
ratio = 1.0f; ratio = 1.0f;
} }
/// The first revolute/prismatic joint attached to the gear joint. /// The first revolute/prismatic joint attached to the gear joint.
b2Joint* joint1; b2Joint* joint1;
/// The second revolute/prismatic joint attached to the gear joint. /// The second revolute/prismatic joint attached to the gear joint.
b2Joint* joint2; b2Joint* joint2;
/// The gear ratio. /// The gear ratio.
/// @see b2GearJoint for explanation. /// @see b2GearJoint for explanation.
float32 ratio; float32 ratio;
}; };
/// A gear joint is used to connect two joints together. Either joint /// A gear joint is used to connect two joints together. Either joint
/// can be a revolute or prismatic joint. You specify a gear ratio /// can be a revolute or prismatic joint. You specify a gear ratio
/// to bind the motions together: /// to bind the motions together:
/// coordinate1 + ratio * coordinate2 = constant /// coordinate1 + ratio * coordinate2 = constant
/// The ratio can be negative or positive. If one joint is a revolute joint /// The ratio can be negative or positive. If one joint is a revolute joint
/// and the other joint is a prismatic joint, then the ratio will have unit s /// and the other joint is a prismatic joint, then the ratio will have unit s
/// of length or units of 1/length. /// of length or units of 1/length.
/// @warning You have to manually destroy the gear joint if joint1 or joint 2 /// @warning You have to manually destroy the gear joint if joint1 or joint 2
/// is destroyed. /// is destroyed.
class b2GearJoint : public b2Joint class b2GearJoint : public b2Joint
{ {
public: public:
b2Vec2 GetAnchorA() const; b2Vec2 GetAnchorA() const;
b2Vec2 GetAnchorB() const; b2Vec2 GetAnchorB() const;
b2Vec2 GetReactionForce(float32 inv_dt) const; b2Vec2 GetReactionForce(float32 inv_dt) const;
float32 GetReactionTorque(float32 inv_dt) const; float32 GetReactionTorque(float32 inv_dt) const;
/// Get the first joint. /// Get the first joint.
b2Joint* GetJoint1() { return m_joint1; } b2Joint* GetJoint1() { return m_joint1; }
/// Get the second joint. /// Get the second joint.
b2Joint* GetJoint2() { return m_joint2; } b2Joint* GetJoint2() { return m_joint2; }
/// Set/Get the gear ratio. /// Set/Get the gear ratio.
void SetRatio(float32 ratio); void SetRatio(float32 ratio);
float32 GetRatio() const; float32 GetRatio() const;
/// Dump joint to dmLog /// Dump joint to dmLog
void Dump(); void Dump();
protected: protected:
friend class b2Joint; friend class b2Joint;
b2GearJoint(const b2GearJointDef* data); b2GearJoint(const b2GearJointDef* data);
void InitVelocityConstraints(const b2SolverData& data); void InitVelocityConstraints(const b2SolverData& data);
void SolveVelocityConstraints(const b2SolverData& data); void SolveVelocityConstraints(const b2SolverData& data);
bool SolvePositionConstraints(const b2SolverData& data); bool SolvePositionConstraints(const b2SolverData& data);
b2Joint* m_joint1; b2Joint* m_joint1;
b2Joint* m_joint2; b2Joint* m_joint2;
b2JointType m_typeA; b2JointType m_typeA;
b2JointType m_typeB; b2JointType m_typeB;
// Body A is connected to body C // Body A is connected to body C
// Body B is connected to body D // Body B is connected to body D
b2Body* m_bodyC; b2Body* m_bodyC;
b2Body* m_bodyD; b2Body* m_bodyD;
// Solver shared // Solver shared
b2Vec2 m_localAnchorA; b2Vec2 m_localAnchorA;
b2Vec2 m_localAnchorB; b2Vec2 m_localAnchorB;
b2Vec2 m_localAnchorC; b2Vec2 m_localAnchorC;
b2Vec2 m_localAnchorD; b2Vec2 m_localAnchorD;
b2Vec2 m_localAxisC; b2Vec2 m_localAxisC;
b2Vec2 m_localAxisD; b2Vec2 m_localAxisD;
float32 m_referenceAngleA; float32 m_referenceAngleA;
float32 m_referenceAngleB; float32 m_referenceAngleB;
float32 m_constant; float32 m_constant;
float32 m_ratio; float32 m_ratio;
float32 m_impulse; float32 m_impulse;
// Solver temp // Solver temp
int32 m_indexA, m_indexB, m_indexC, m_indexD; int32 m_indexA, m_indexB, m_indexC, m_indexD;
b2Vec2 m_lcA, m_lcB, m_lcC, m_lcD; b2Vec2 m_lcA, m_lcB, m_lcC, m_lcD;
float32 m_mA, m_mB, m_mC, m_mD; float32 m_mA, m_mB, m_mC, m_mD;
float32 m_iA, m_iB, m_iC, m_iD; float32 m_iA, m_iB, m_iC, m_iD;
b2Vec2 m_JvAC, m_JvBD; b2Vec2 m_JvAC, m_JvBD;
float32 m_JwA, m_JwB, m_JwC, m_JwD; float32 m_JwA, m_JwB, m_JwC, m_JwD;
float32 m_mass; float32 m_mass;
}; };
#endif #endif
 End of changes. 9 change blocks. 
72 lines changed or deleted 72 lines changed or added


 b2GrowableStack.h   b2GrowableStack.h 
skipping to change at line 31 skipping to change at line 31
#include <Box2D/Common/b2Settings.h> #include <Box2D/Common/b2Settings.h>
#include <cstring> #include <cstring>
/// This is a growable LIFO stack with an initial capacity of N. /// This is a growable LIFO stack with an initial capacity of N.
/// If the stack size exceeds the initial capacity, the heap is used /// If the stack size exceeds the initial capacity, the heap is used
/// to increase the size of the stack. /// to increase the size of the stack.
template <typename T, int32 N> template <typename T, int32 N>
class b2GrowableStack class b2GrowableStack
{ {
public: public:
b2GrowableStack() b2GrowableStack()
{ {
m_stack = m_array; m_stack = m_array;
m_count = 0; m_count = 0;
m_capacity = N; m_capacity = N;
} }
~b2GrowableStack() ~b2GrowableStack()
{ {
if (m_stack != m_array) if (m_stack != m_array)
{ {
b2Free(m_stack); b2Free(m_stack);
m_stack = NULL; m_stack = NULL;
} }
} }
void Push(const T& element) void Push(const T& element)
{ {
if (m_count == m_capacity) if (m_count == m_capacity)
{ {
T* old = m_stack; T* old = m_stack;
m_capacity *= 2; m_capacity *= 2;
m_stack = (T*)b2Alloc(m_capacity * sizeof(T)); m_stack = (T*)b2Alloc(m_capacity * sizeof(T));
std::memcpy(m_stack, old, m_count * sizeof(T)); std::memcpy(m_stack, old, m_count * sizeof(T));
if (old != m_array) if (old != m_array)
{ {
b2Free(old); b2Free(old);
} }
} }
m_stack[m_count] = element; m_stack[m_count] = element;
++m_count; ++m_count;
} }
T Pop() T Pop()
{ {
b2Assert(m_count > 0); b2Assert(m_count > 0);
--m_count; --m_count;
return m_stack[m_count]; return m_stack[m_count];
} }
int32 GetCount() int32 GetCount()
{ {
return m_count; return m_count;
} }
private: private:
T* m_stack; T* m_stack;
T m_array[N]; T m_array[N];
int32 m_count; int32 m_count;
int32 m_capacity; int32 m_capacity;
}; };
#endif #endif
 End of changes. 2 change blocks. 
49 lines changed or deleted 49 lines changed or added


 b2Island.h   b2Island.h 
skipping to change at line 37 skipping to change at line 37
class b2Joint; class b2Joint;
class b2StackAllocator; class b2StackAllocator;
class b2ContactListener; class b2ContactListener;
struct b2ContactVelocityConstraint; struct b2ContactVelocityConstraint;
struct b2Profile; struct b2Profile;
/// This is an internal class. /// This is an internal class.
class b2Island class b2Island
{ {
public: public:
b2Island(int32 bodyCapacity, int32 contactCapacity, int32 jointCapac b2Island(int32 bodyCapacity, int32 contactCapacity, int32 jointCapacity
ity, ,
b2StackAllocator* allocator, b2ContactListener* list b2StackAllocator* allocator, b2ContactListener* listener);
ener); ~b2Island();
~b2Island();
void Clear()
void Clear() {
{ m_bodyCount = 0;
m_bodyCount = 0; m_contactCount = 0;
m_contactCount = 0; m_jointCount = 0;
m_jointCount = 0; }
}
void Solve(b2Profile* profile, const b2TimeStep& step, const b2Vec2& gr
void Solve(b2Profile* profile, const b2TimeStep& step, const b2Vec2& avity, bool allowSleep);
gravity, bool allowSleep);
void SolveTOI(const b2TimeStep& subStep, int32 toiIndexA, int32 toiInde
void SolveTOI(const b2TimeStep& subStep, int32 toiIndexA, int32 toiI xB);
ndexB);
void Add(b2Body* body)
void Add(b2Body* body) {
{ b2Assert(m_bodyCount < m_bodyCapacity);
b2Assert(m_bodyCount < m_bodyCapacity); body->m_islandIndex = m_bodyCount;
body->m_islandIndex = m_bodyCount; m_bodies[m_bodyCount] = body;
m_bodies[m_bodyCount] = body; ++m_bodyCount;
++m_bodyCount; }
}
void Add(b2Contact* contact)
void Add(b2Contact* contact) {
{ b2Assert(m_contactCount < m_contactCapacity);
b2Assert(m_contactCount < m_contactCapacity); m_contacts[m_contactCount++] = contact;
m_contacts[m_contactCount++] = contact; }
}
void Add(b2Joint* joint)
void Add(b2Joint* joint) {
{ b2Assert(m_jointCount < m_jointCapacity);
b2Assert(m_jointCount < m_jointCapacity); m_joints[m_jointCount++] = joint;
m_joints[m_jointCount++] = joint; }
}
void Report(const b2ContactVelocityConstraint* constraints);
void Report(const b2ContactVelocityConstraint* constraints);
b2StackAllocator* m_allocator;
b2StackAllocator* m_allocator; b2ContactListener* m_listener;
b2ContactListener* m_listener;
b2Body** m_bodies;
b2Body** m_bodies; b2Contact** m_contacts;
b2Contact** m_contacts; b2Joint** m_joints;
b2Joint** m_joints;
b2Position* m_positions;
b2Position* m_positions; b2Velocity* m_velocities;
b2Velocity* m_velocities;
int32 m_bodyCount;
int32 m_bodyCount; int32 m_jointCount;
int32 m_jointCount; int32 m_contactCount;
int32 m_contactCount;
int32 m_bodyCapacity;
int32 m_bodyCapacity; int32 m_contactCapacity;
int32 m_contactCapacity; int32 m_jointCapacity;
int32 m_jointCapacity;
}; };
#endif #endif
 End of changes. 1 change blocks. 
58 lines changed or deleted 57 lines changed or added


 b2Joint.h   b2Joint.h 
skipping to change at line 31 skipping to change at line 31
#include <Box2D/Common/b2Math.h> #include <Box2D/Common/b2Math.h>
class b2Body; class b2Body;
class b2Joint; class b2Joint;
struct b2SolverData; struct b2SolverData;
class b2BlockAllocator; class b2BlockAllocator;
enum b2JointType enum b2JointType
{ {
e_unknownJoint, e_unknownJoint,
e_revoluteJoint, e_revoluteJoint,
e_prismaticJoint, e_prismaticJoint,
e_distanceJoint, e_distanceJoint,
e_pulleyJoint, e_pulleyJoint,
e_mouseJoint, e_mouseJoint,
e_gearJoint, e_gearJoint,
e_wheelJoint, e_wheelJoint,
e_weldJoint, e_weldJoint,
e_frictionJoint, e_frictionJoint,
e_ropeJoint e_ropeJoint
}; };
enum b2LimitState enum b2LimitState
{ {
e_inactiveLimit, e_inactiveLimit,
e_atLowerLimit, e_atLowerLimit,
e_atUpperLimit, e_atUpperLimit,
e_equalLimits e_equalLimits
}; };
struct b2Jacobian struct b2Jacobian
{ {
b2Vec2 linear; b2Vec2 linear;
float32 angularA; float32 angularA;
float32 angularB; float32 angularB;
}; };
/// A joint edge is used to connect bodies and joints together /// A joint edge is used to connect bodies and joints together
/// in a joint graph where each body is a node and each joint /// in a joint graph where each body is a node and each joint
/// is an edge. A joint edge belongs to a doubly linked list /// is an edge. A joint edge belongs to a doubly linked list
/// maintained in each attached body. Each joint has two joint /// maintained in each attached body. Each joint has two joint
/// nodes, one for each attached body. /// nodes, one for each attached body.
struct b2JointEdge struct b2JointEdge
{ {
b2Body* other; ///< provides quick access to the ot b2Body* other; ///< provides quick access to the other body
her body attached. attached.
b2Joint* joint; ///< the joint b2Joint* joint; ///< the joint
b2JointEdge* prev; ///< the previous joint edge in the b2JointEdge* prev; ///< the previous joint edge in the body's jo
body's joint list int list
b2JointEdge* next; ///< the next joint edge in the body b2JointEdge* next; ///< the next joint edge in the body's joint
's joint list list
}; };
/// Joint definitions are used to construct joints. /// Joint definitions are used to construct joints.
struct b2JointDef struct b2JointDef
{ {
b2JointDef() b2JointDef()
{ {
type = e_unknownJoint; type = e_unknownJoint;
userData = NULL; userData = NULL;
bodyA = NULL; bodyA = NULL;
bodyB = NULL; bodyB = NULL;
collideConnected = false; collideConnected = false;
} }
/// The joint type is set automatically for concrete joint types. /// The joint type is set automatically for concrete joint types.
b2JointType type; b2JointType type;
/// Use this to attach application specific data to your joints. /// Use this to attach application specific data to your joints.
void* userData; void* userData;
/// The first attached body. /// The first attached body.
b2Body* bodyA; b2Body* bodyA;
/// The second attached body. /// The second attached body.
b2Body* bodyB; b2Body* bodyB;
/// Set this flag to true if the attached bodies should collide. /// Set this flag to true if the attached bodies should collide.
bool collideConnected; bool collideConnected;
}; };
/// The base joint class. Joints are used to constraint two bodies together in /// The base joint class. Joints are used to constraint two bodies together in
/// various fashions. Some joints also feature limits and motors. /// various fashions. Some joints also feature limits and motors.
class b2Joint class b2Joint
{ {
public: public:
/// Get the type of the concrete joint. /// Get the type of the concrete joint.
b2JointType GetType() const; b2JointType GetType() const;
/// Get the first body attached to this joint. /// Get the first body attached to this joint.
b2Body* GetBodyA(); b2Body* GetBodyA();
/// Get the second body attached to this joint. /// Get the second body attached to this joint.
b2Body* GetBodyB(); b2Body* GetBodyB();
/// Get the anchor point on bodyA in world coordinates. /// Get the anchor point on bodyA in world coordinates.
virtual b2Vec2 GetAnchorA() const = 0; virtual b2Vec2 GetAnchorA() const = 0;
/// Get the anchor point on bodyB in world coordinates. /// Get the anchor point on bodyB in world coordinates.
virtual b2Vec2 GetAnchorB() const = 0; virtual b2Vec2 GetAnchorB() const = 0;
/// Get the reaction force on bodyB at the joint anchor in Newtons. /// Get the reaction force on bodyB at the joint anchor in Newtons.
virtual b2Vec2 GetReactionForce(float32 inv_dt) const = 0; virtual b2Vec2 GetReactionForce(float32 inv_dt) const = 0;
/// Get the reaction torque on bodyB in N*m. /// Get the reaction torque on bodyB in N*m.
virtual float32 GetReactionTorque(float32 inv_dt) const = 0; virtual float32 GetReactionTorque(float32 inv_dt) const = 0;
/// Get the next joint the world joint list. /// Get the next joint the world joint list.
b2Joint* GetNext(); b2Joint* GetNext();
const b2Joint* GetNext() const; const b2Joint* GetNext() const;
/// Get the user data pointer. /// Get the user data pointer.
void* GetUserData() const; void* GetUserData() const;
/// Set the user data pointer. /// Set the user data pointer.
void SetUserData(void* data); void SetUserData(void* data);
/// Short-cut function to determine if either body is inactive. /// Short-cut function to determine if either body is inactive.
bool IsActive() const; bool IsActive() const;
/// Get collide connected. /// Get collide connected.
/// Note: modifying the collide connect flag won't work correctly be /// Note: modifying the collide connect flag won't work correctly becau
cause se
/// the flag is only checked when fixture AABBs begin to overlap. /// the flag is only checked when fixture AABBs begin to overlap.
bool GetCollideConnected() const; bool GetCollideConnected() const;
/// Dump this joint to the log file. /// Dump this joint to the log file.
virtual void Dump() { b2Log("// Dump is not supported for this joint virtual void Dump() { b2Log("// Dump is not supported for this joint ty
type.\n"); } pe.\n"); }
protected: protected:
friend class b2World; friend class b2World;
friend class b2Body; friend class b2Body;
friend class b2Island; friend class b2Island;
friend class b2GearJoint; friend class b2GearJoint;
static b2Joint* Create(const b2JointDef* def, b2BlockAllocator* allo static b2Joint* Create(const b2JointDef* def, b2BlockAllocator* allocat
cator); or);
static void Destroy(b2Joint* joint, b2BlockAllocator* allocator); static void Destroy(b2Joint* joint, b2BlockAllocator* allocator);
b2Joint(const b2JointDef* def); b2Joint(const b2JointDef* def);
virtual ~b2Joint() {} virtual ~b2Joint() {}
virtual void InitVelocityConstraints(const b2SolverData& data) = 0; virtual void InitVelocityConstraints(const b2SolverData& data) = 0;
virtual void SolveVelocityConstraints(const b2SolverData& data) = 0; virtual void SolveVelocityConstraints(const b2SolverData& data) = 0;
// This returns true if the position errors are within tolerance. // This returns true if the position errors are within tolerance.
virtual bool SolvePositionConstraints(const b2SolverData& data) = 0; virtual bool SolvePositionConstraints(const b2SolverData& data) = 0;
b2JointType m_type; b2JointType m_type;
b2Joint* m_prev; b2Joint* m_prev;
b2Joint* m_next; b2Joint* m_next;
b2JointEdge m_edgeA; b2JointEdge m_edgeA;
b2JointEdge m_edgeB; b2JointEdge m_edgeB;
b2Body* m_bodyA; b2Body* m_bodyA;
b2Body* m_bodyB; b2Body* m_bodyB;
int32 m_index; int32 m_index;
bool m_islandFlag; bool m_islandFlag;
bool m_collideConnected; bool m_collideConnected;
void* m_userData; void* m_userData;
}; };
inline b2JointType b2Joint::GetType() const inline b2JointType b2Joint::GetType() const
{ {
return m_type; return m_type;
} }
inline b2Body* b2Joint::GetBodyA() inline b2Body* b2Joint::GetBodyA()
{ {
return m_bodyA; return m_bodyA;
} }
inline b2Body* b2Joint::GetBodyB() inline b2Body* b2Joint::GetBodyB()
{ {
return m_bodyB; return m_bodyB;
} }
inline b2Joint* b2Joint::GetNext() inline b2Joint* b2Joint::GetNext()
{ {
return m_next; return m_next;
} }
inline const b2Joint* b2Joint::GetNext() const inline const b2Joint* b2Joint::GetNext() const
{ {
return m_next; return m_next;
} }
inline void* b2Joint::GetUserData() const inline void* b2Joint::GetUserData() const
{ {
return m_userData; return m_userData;
} }
inline void b2Joint::SetUserData(void* data) inline void b2Joint::SetUserData(void* data)
{ {
m_userData = data; m_userData = data;
} }
inline bool b2Joint::GetCollideConnected() const inline bool b2Joint::GetCollideConnected() const
{ {
return m_collideConnected; return m_collideConnected;
} }
#endif #endif
 End of changes. 39 change blocks. 
107 lines changed or deleted 107 lines changed or added


 b2Math.h   b2Math.h 
skipping to change at line 39 skipping to change at line 39
#endif #endif
#include <cstddef> #include <cstddef>
#include <limits> #include <limits>
using namespace std; using namespace std;
/// This function is used to ensure that a floating point number is /// This function is used to ensure that a floating point number is
/// not a NaN or infinity. /// not a NaN or infinity.
inline bool b2IsValid(float32 x) inline bool b2IsValid(float32 x)
{ {
if (x != x) if (x != x)
{ {
// NaN. // NaN.
return false; return false;
} }
float32 infinity = std::numeric_limits<float32>::infinity(); float32 infinity = std::numeric_limits<float32>::infinity();
return -infinity < x && x < infinity; return -infinity < x && x < infinity;
} }
/// This is a approximate yet fast inverse square-root. /// This is a approximate yet fast inverse square-root.
inline float32 b2InvSqrt(float32 x) inline float32 b2InvSqrt(float32 x)
{ {
union union
{ {
float32 x; float32 x;
int32 i; int32 i;
} convert; } convert;
convert.x = x; convert.x = x;
float32 xhalf = 0.5f * x; float32 xhalf = 0.5f * x;
convert.i = 0x5f3759df - (convert.i >> 1); convert.i = 0x5f3759df - (convert.i >> 1);
x = convert.x; x = convert.x;
x = x * (1.5f - xhalf * x * x); x = x * (1.5f - xhalf * x * x);
return x; return x;
} }
#define b2Sqrt(x) std::sqrt(x) #define b2Sqrt(x) std::sqrt(x)
#define b2Atan2(y, x) std::atan2(y, x) #define b2Atan2(y, x) std::atan2(y, x)
/// A 2D column vector. /// A 2D column vector.
struct b2Vec2 struct b2Vec2
{ {
/// Default constructor does nothing (for performance). /// Default constructor does nothing (for performance).
b2Vec2() {} b2Vec2() {}
/// Construct using coordinates. /// Construct using coordinates.
b2Vec2(float32 x, float32 y) : x(x), y(y) {} b2Vec2(float32 x, float32 y) : x(x), y(y) {}
/// Set this vector to all zeros. /// Set this vector to all zeros.
void SetZero() { x = 0.0f; y = 0.0f; } void SetZero() { x = 0.0f; y = 0.0f; }
/// Set this vector to some specified coordinates. /// Set this vector to some specified coordinates.
void Set(float32 x_, float32 y_) { x = x_; y = y_; } void Set(float32 x_, float32 y_) { x = x_; y = y_; }
/// Negate this vector. /// Negate this vector.
b2Vec2 operator -() const { b2Vec2 v; v.Set(-x, -y); return v; } b2Vec2 operator -() const { b2Vec2 v; v.Set(-x, -y); return v; }
/// Read from and indexed element. /// Read from and indexed element.
float32 operator () (int32 i) const float32 operator () (int32 i) const
{ {
return (&x)[i]; return (&x)[i];
} }
/// Write to an indexed element. /// Write to an indexed element.
float32& operator () (int32 i) float32& operator () (int32 i)
{ {
return (&x)[i]; return (&x)[i];
} }
/// Add a vector to this vector. /// Add a vector to this vector.
void operator += (const b2Vec2& v) void operator += (const b2Vec2& v)
{ {
x += v.x; y += v.y; x += v.x; y += v.y;
} }
/// Subtract a vector from this vector. /// Subtract a vector from this vector.
void operator -= (const b2Vec2& v) void operator -= (const b2Vec2& v)
{ {
x -= v.x; y -= v.y; x -= v.x; y -= v.y;
} }
/// Multiply this vector by a scalar. /// Multiply this vector by a scalar.
void operator *= (float32 a) void operator *= (float32 a)
{ {
x *= a; y *= a; x *= a; y *= a;
} }
/// Get the length of this vector (the norm). /// Get the length of this vector (the norm).
float32 Length() const float32 Length() const
{ {
return b2Sqrt(x * x + y * y); return b2Sqrt(x * x + y * y);
} }
/// Get the length squared. For performance, use this instead of /// Get the length squared. For performance, use this instead of
/// b2Vec2::Length (if possible). /// b2Vec2::Length (if possible).
float32 LengthSquared() const float32 LengthSquared() const
{ {
return x * x + y * y; return x * x + y * y;
} }
/// Convert this vector into a unit vector. Returns the length. /// Convert this vector into a unit vector. Returns the length.
float32 Normalize() float32 Normalize()
{ {
float32 length = Length(); float32 length = Length();
if (length < b2_epsilon) if (length < b2_epsilon)
{ {
return 0.0f; return 0.0f;
} }
float32 invLength = 1.0f / length; float32 invLength = 1.0f / length;
x *= invLength; x *= invLength;
y *= invLength; y *= invLength;
return length; return length;
} }
/// Does this vector contain finite coordinates? /// Does this vector contain finite coordinates?
bool IsValid() const bool IsValid() const
{ {
return b2IsValid(x) && b2IsValid(y); return b2IsValid(x) && b2IsValid(y);
} }
/// Get the skew vector such that dot(skew_vec, other) == cross(vec, /// Get the skew vector such that dot(skew_vec, other) == cross(vec, ot
other) her)
b2Vec2 Skew() const b2Vec2 Skew() const
{ {
return b2Vec2(-y, x); return b2Vec2(-y, x);
} }
float32 x, y; float32 x, y;
}; };
/// A 2D column vector with 3 elements. /// A 2D column vector with 3 elements.
struct b2Vec3 struct b2Vec3
{ {
/// Default constructor does nothing (for performance). /// Default constructor does nothing (for performance).
b2Vec3() {} b2Vec3() {}
/// Construct using coordinates. /// Construct using coordinates.
b2Vec3(float32 x, float32 y, float32 z) : x(x), y(y), z(z) {} b2Vec3(float32 x, float32 y, float32 z) : x(x), y(y), z(z) {}
/// Set this vector to all zeros. /// Set this vector to all zeros.
void SetZero() { x = 0.0f; y = 0.0f; z = 0.0f; } void SetZero() { x = 0.0f; y = 0.0f; z = 0.0f; }
/// Set this vector to some specified coordinates. /// Set this vector to some specified coordinates.
void Set(float32 x_, float32 y_, float32 z_) { x = x_; y = y_; z = z void Set(float32 x_, float32 y_, float32 z_) { x = x_; y = y_; z = z_;
_; } }
/// Negate this vector. /// Negate this vector.
b2Vec3 operator -() const { b2Vec3 v; v.Set(-x, -y, -z); return v; } b2Vec3 operator -() const { b2Vec3 v; v.Set(-x, -y, -z); return v; }
/// Add a vector to this vector. /// Add a vector to this vector.
void operator += (const b2Vec3& v) void operator += (const b2Vec3& v)
{ {
x += v.x; y += v.y; z += v.z; x += v.x; y += v.y; z += v.z;
} }
/// Subtract a vector from this vector. /// Subtract a vector from this vector.
void operator -= (const b2Vec3& v) void operator -= (const b2Vec3& v)
{ {
x -= v.x; y -= v.y; z -= v.z; x -= v.x; y -= v.y; z -= v.z;
} }
/// Multiply this vector by a scalar. /// Multiply this vector by a scalar.
void operator *= (float32 s) void operator *= (float32 s)
{ {
x *= s; y *= s; z *= s; x *= s; y *= s; z *= s;
} }
float32 x, y, z; float32 x, y, z;
}; };
/// A 2-by-2 matrix. Stored in column-major order. /// A 2-by-2 matrix. Stored in column-major order.
struct b2Mat22 struct b2Mat22
{ {
/// The default constructor does nothing (for performance). /// The default constructor does nothing (for performance).
b2Mat22() {} b2Mat22() {}
/// Construct this matrix using columns. /// Construct this matrix using columns.
b2Mat22(const b2Vec2& c1, const b2Vec2& c2) b2Mat22(const b2Vec2& c1, const b2Vec2& c2)
{ {
ex = c1; ex = c1;
ey = c2; ey = c2;
} }
/// Construct this matrix using scalars. /// Construct this matrix using scalars.
b2Mat22(float32 a11, float32 a12, float32 a21, float32 a22) b2Mat22(float32 a11, float32 a12, float32 a21, float32 a22)
{ {
ex.x = a11; ex.y = a21; ex.x = a11; ex.y = a21;
ey.x = a12; ey.y = a22; ey.x = a12; ey.y = a22;
} }
/// Initialize this matrix using columns. /// Initialize this matrix using columns.
void Set(const b2Vec2& c1, const b2Vec2& c2) void Set(const b2Vec2& c1, const b2Vec2& c2)
{ {
ex = c1; ex = c1;
ey = c2; ey = c2;
} }
/// Set this to the identity matrix. /// Set this to the identity matrix.
void SetIdentity() void SetIdentity()
{ {
ex.x = 1.0f; ey.x = 0.0f; ex.x = 1.0f; ey.x = 0.0f;
ex.y = 0.0f; ey.y = 1.0f; ex.y = 0.0f; ey.y = 1.0f;
} }
/// Set this matrix to all zeros. /// Set this matrix to all zeros.
void SetZero() void SetZero()
{ {
ex.x = 0.0f; ey.x = 0.0f; ex.x = 0.0f; ey.x = 0.0f;
ex.y = 0.0f; ey.y = 0.0f; ex.y = 0.0f; ey.y = 0.0f;
} }
b2Mat22 GetInverse() const b2Mat22 GetInverse() const
{ {
float32 a = ex.x, b = ey.x, c = ex.y, d = ey.y; float32 a = ex.x, b = ey.x, c = ex.y, d = ey.y;
b2Mat22 B; b2Mat22 B;
float32 det = a * d - b * c; float32 det = a * d - b * c;
if (det != 0.0f) if (det != 0.0f)
{ {
det = 1.0f / det; det = 1.0f / det;
} }
B.ex.x = det * d; B.ey.x = -det * b; B.ex.x = det * d; B.ey.x = -det * b;
B.ex.y = -det * c; B.ey.y = det * a; B.ex.y = -det * c; B.ey.y = det * a;
return B; return B;
} }
/// Solve A * x = b, where b is a column vector. This is more effici /// Solve A * x = b, where b is a column vector. This is more efficient
ent /// than computing the inverse in one-shot cases.
/// than computing the inverse in one-shot cases. b2Vec2 Solve(const b2Vec2& b) const
b2Vec2 Solve(const b2Vec2& b) const {
{ float32 a11 = ex.x, a12 = ey.x, a21 = ex.y, a22 = ey.y;
float32 a11 = ex.x, a12 = ey.x, a21 = ex.y, a22 = ey.y; float32 det = a11 * a22 - a12 * a21;
float32 det = a11 * a22 - a12 * a21; if (det != 0.0f)
if (det != 0.0f) {
{ det = 1.0f / det;
det = 1.0f / det; }
} b2Vec2 x;
b2Vec2 x; x.x = det * (a22 * b.x - a12 * b.y);
x.x = det * (a22 * b.x - a12 * b.y); x.y = det * (a11 * b.y - a21 * b.x);
x.y = det * (a11 * b.y - a21 * b.x); return x;
return x; }
}
b2Vec2 ex, ey; b2Vec2 ex, ey;
}; };
/// A 3-by-3 matrix. Stored in column-major order. /// A 3-by-3 matrix. Stored in column-major order.
struct b2Mat33 struct b2Mat33
{ {
/// The default constructor does nothing (for performance). /// The default constructor does nothing (for performance).
b2Mat33() {} b2Mat33() {}
/// Construct this matrix using columns. /// Construct this matrix using columns.
b2Mat33(const b2Vec3& c1, const b2Vec3& c2, const b2Vec3& c3) b2Mat33(const b2Vec3& c1, const b2Vec3& c2, const b2Vec3& c3)
{ {
ex = c1; ex = c1;
ey = c2; ey = c2;
ez = c3; ez = c3;
} }
/// Set this matrix to all zeros. /// Set this matrix to all zeros.
void SetZero() void SetZero()
{ {
ex.SetZero(); ex.SetZero();
ey.SetZero(); ey.SetZero();
ez.SetZero(); ez.SetZero();
} }
/// Solve A * x = b, where b is a column vector. This is more effici /// Solve A * x = b, where b is a column vector. This is more efficient
ent /// than computing the inverse in one-shot cases.
/// than computing the inverse in one-shot cases. b2Vec3 Solve33(const b2Vec3& b) const;
b2Vec3 Solve33(const b2Vec3& b) const;
/// Solve A * x = b, where b is a column vector. This is more efficient
/// Solve A * x = b, where b is a column vector. This is more effici /// than computing the inverse in one-shot cases. Solve only the upper
ent /// 2-by-2 matrix equation.
/// than computing the inverse in one-shot cases. Solve only the upp b2Vec2 Solve22(const b2Vec2& b) const;
er
/// 2-by-2 matrix equation. /// Get the inverse of this matrix as a 2-by-2.
b2Vec2 Solve22(const b2Vec2& b) const; /// Returns the zero matrix if singular.
void GetInverse22(b2Mat33* M) const;
/// Get the inverse of this matrix as a 2-by-2.
/// Returns the zero matrix if singular. /// Get the symmetric inverse of this matrix as a 3-by-3.
void GetInverse22(b2Mat33* M) const; /// Returns the zero matrix if singular.
void GetSymInverse33(b2Mat33* M) const;
/// Get the symmetric inverse of this matrix as a 3-by-3.
/// Returns the zero matrix if singular.
void GetSymInverse33(b2Mat33* M) const;
b2Vec3 ex, ey, ez; b2Vec3 ex, ey, ez;
}; };
/// Rotation /// Rotation
struct b2Rot struct b2Rot
{ {
b2Rot() {} b2Rot() {}
/// Initialize from an angle in radians /// Initialize from an angle in radians
explicit b2Rot(float32 angle) explicit b2Rot(float32 angle)
{ {
/// TODO_ERIN optimize /// TODO_ERIN optimize
s = sinf(angle); s = sinf(angle);
c = cosf(angle); c = cosf(angle);
} }
/// Set using an angle in radians. /// Set using an angle in radians.
void Set(float32 angle) void Set(float32 angle)
{ {
/// TODO_ERIN optimize /// TODO_ERIN optimize
s = sinf(angle); s = sinf(angle);
c = cosf(angle); c = cosf(angle);
} }
/// Set to the identity rotation /// Set to the identity rotation
void SetIdentity() void SetIdentity()
{ {
s = 0.0f; s = 0.0f;
c = 1.0f; c = 1.0f;
} }
/// Get the angle in radians /// Get the angle in radians
float32 GetAngle() const float32 GetAngle() const
{ {
return b2Atan2(s, c); return b2Atan2(s, c);
} }
/// Get the x-axis /// Get the x-axis
b2Vec2 GetXAxis() const b2Vec2 GetXAxis() const
{ {
return b2Vec2(c, s); return b2Vec2(c, s);
} }
/// Get the u-axis /// Get the u-axis
b2Vec2 GetYAxis() const b2Vec2 GetYAxis() const
{ {
return b2Vec2(-s, c); return b2Vec2(-s, c);
} }
/// Sine and cosine /// Sine and cosine
float32 s, c; float32 s, c;
}; };
/// A transform contains translation and rotation. It is used to represent /// A transform contains translation and rotation. It is used to represent
/// the position and orientation of rigid frames. /// the position and orientation of rigid frames.
struct b2Transform struct b2Transform
{ {
/// The default constructor does nothing. /// The default constructor does nothing.
b2Transform() {} b2Transform() {}
/// Initialize using a position vector and a rotation. /// Initialize using a position vector and a rotation.
b2Transform(const b2Vec2& position, const b2Rot& rotation) : p(posit b2Transform(const b2Vec2& position, const b2Rot& rotation) : p(position
ion), q(rotation) {} ), q(rotation) {}
/// Set this to the identity transform. /// Set this to the identity transform.
void SetIdentity() void SetIdentity()
{ {
p.SetZero(); p.SetZero();
q.SetIdentity(); q.SetIdentity();
} }
/// Set this based on the position and angle. /// Set this based on the position and angle.
void Set(const b2Vec2& position, float32 angle) void Set(const b2Vec2& position, float32 angle)
{ {
p = position; p = position;
q.Set(angle); q.Set(angle);
} }
b2Vec2 p; b2Vec2 p;
b2Rot q; b2Rot q;
}; };
/// This describes the motion of a body/shape for TOI computation. /// This describes the motion of a body/shape for TOI computation.
/// Shapes are defined with respect to the body origin, which may /// Shapes are defined with respect to the body origin, which may
/// no coincide with the center of mass. However, to support dynamics /// no coincide with the center of mass. However, to support dynamics
/// we must interpolate the center of mass position. /// we must interpolate the center of mass position.
struct b2Sweep struct b2Sweep
{ {
/// Get the interpolated transform at a specific time. /// Get the interpolated transform at a specific time.
/// @param beta is a factor in [0,1], where 0 indicates alpha0. /// @param beta is a factor in [0,1], where 0 indicates alpha0.
void GetTransform(b2Transform* xfb, float32 beta) const; void GetTransform(b2Transform* xfb, float32 beta) const;
/// Advance the sweep forward, yielding a new initial state. /// Advance the sweep forward, yielding a new initial state.
/// @param alpha the new initial time. /// @param alpha the new initial time.
void Advance(float32 alpha); void Advance(float32 alpha);
/// Normalize the angles. /// Normalize the angles.
void Normalize(); void Normalize();
b2Vec2 localCenter; ///< local center of mass position b2Vec2 localCenter; ///< local center of mass position
b2Vec2 c0, c; ///< center world positions b2Vec2 c0, c; ///< center world positions
float32 a0, a; ///< world angles float32 a0, a; ///< world angles
/// Fraction of the current time step in the range [0,1] /// Fraction of the current time step in the range [0,1]
/// c0 and a0 are the positions at alpha0. /// c0 and a0 are the positions at alpha0.
float32 alpha0; float32 alpha0;
}; };
/// Useful constant /// Useful constant
extern const b2Vec2 b2Vec2_zero; extern const b2Vec2 b2Vec2_zero;
/// Perform the dot product on two vectors. /// Perform the dot product on two vectors.
inline float32 b2Dot(const b2Vec2& a, const b2Vec2& b) inline float32 b2Dot(const b2Vec2& a, const b2Vec2& b)
{ {
return a.x * b.x + a.y * b.y; return a.x * b.x + a.y * b.y;
} }
/// Perform the cross product on two vectors. In 2D this produces a scalar. /// Perform the cross product on two vectors. In 2D this produces a scalar.
inline float32 b2Cross(const b2Vec2& a, const b2Vec2& b) inline float32 b2Cross(const b2Vec2& a, const b2Vec2& b)
{ {
return a.x * b.y - a.y * b.x; return a.x * b.y - a.y * b.x;
} }
/// Perform the cross product on a vector and a scalar. In 2D this produces /// Perform the cross product on a vector and a scalar. In 2D this produces
/// a vector. /// a vector.
inline b2Vec2 b2Cross(const b2Vec2& a, float32 s) inline b2Vec2 b2Cross(const b2Vec2& a, float32 s)
{ {
return b2Vec2(s * a.y, -s * a.x); return b2Vec2(s * a.y, -s * a.x);
} }
/// Perform the cross product on a scalar and a vector. In 2D this produces /// Perform the cross product on a scalar and a vector. In 2D this produces
/// a vector. /// a vector.
inline b2Vec2 b2Cross(float32 s, const b2Vec2& a) inline b2Vec2 b2Cross(float32 s, const b2Vec2& a)
{ {
return b2Vec2(-s * a.y, s * a.x); return b2Vec2(-s * a.y, s * a.x);
} }
/// Multiply a matrix times a vector. If a rotation matrix is provided, /// Multiply a matrix times a vector. If a rotation matrix is provided,
/// then this transforms the vector from one frame to another. /// then this transforms the vector from one frame to another.
inline b2Vec2 b2Mul(const b2Mat22& A, const b2Vec2& v) inline b2Vec2 b2Mul(const b2Mat22& A, const b2Vec2& v)
{ {
return b2Vec2(A.ex.x * v.x + A.ey.x * v.y, A.ex.y * v.x + A.ey.y * v .y); return b2Vec2(A.ex.x * v.x + A.ey.x * v.y, A.ex.y * v.x + A.ey.y * v.y) ;
} }
/// Multiply a matrix transpose times a vector. If a rotation matrix is pro vided, /// Multiply a matrix transpose times a vector. If a rotation matrix is pro vided,
/// then this transforms the vector from one frame to another (inverse tran sform). /// then this transforms the vector from one frame to another (inverse tran sform).
inline b2Vec2 b2MulT(const b2Mat22& A, const b2Vec2& v) inline b2Vec2 b2MulT(const b2Mat22& A, const b2Vec2& v)
{ {
return b2Vec2(b2Dot(v, A.ex), b2Dot(v, A.ey)); return b2Vec2(b2Dot(v, A.ex), b2Dot(v, A.ey));
} }
/// Add two vectors component-wise. /// Add two vectors component-wise.
inline b2Vec2 operator + (const b2Vec2& a, const b2Vec2& b) inline b2Vec2 operator + (const b2Vec2& a, const b2Vec2& b)
{ {
return b2Vec2(a.x + b.x, a.y + b.y); return b2Vec2(a.x + b.x, a.y + b.y);
} }
/// Subtract two vectors component-wise. /// Subtract two vectors component-wise.
inline b2Vec2 operator - (const b2Vec2& a, const b2Vec2& b) inline b2Vec2 operator - (const b2Vec2& a, const b2Vec2& b)
{ {
return b2Vec2(a.x - b.x, a.y - b.y); return b2Vec2(a.x - b.x, a.y - b.y);
} }
inline b2Vec2 operator * (float32 s, const b2Vec2& a) inline b2Vec2 operator * (float32 s, const b2Vec2& a)
{ {
return b2Vec2(s * a.x, s * a.y); return b2Vec2(s * a.x, s * a.y);
} }
inline bool operator == (const b2Vec2& a, const b2Vec2& b) inline bool operator == (const b2Vec2& a, const b2Vec2& b)
{ {
return a.x == b.x && a.y == b.y; return a.x == b.x && a.y == b.y;
} }
inline float32 b2Distance(const b2Vec2& a, const b2Vec2& b) inline float32 b2Distance(const b2Vec2& a, const b2Vec2& b)
{ {
b2Vec2 c = a - b; b2Vec2 c = a - b;
return c.Length(); return c.Length();
} }
inline float32 b2DistanceSquared(const b2Vec2& a, const b2Vec2& b) inline float32 b2DistanceSquared(const b2Vec2& a, const b2Vec2& b)
{ {
b2Vec2 c = a - b; b2Vec2 c = a - b;
return b2Dot(c, c); return b2Dot(c, c);
} }
inline b2Vec3 operator * (float32 s, const b2Vec3& a) inline b2Vec3 operator * (float32 s, const b2Vec3& a)
{ {
return b2Vec3(s * a.x, s * a.y, s * a.z); return b2Vec3(s * a.x, s * a.y, s * a.z);
} }
/// Add two vectors component-wise. /// Add two vectors component-wise.
inline b2Vec3 operator + (const b2Vec3& a, const b2Vec3& b) inline b2Vec3 operator + (const b2Vec3& a, const b2Vec3& b)
{ {
return b2Vec3(a.x + b.x, a.y + b.y, a.z + b.z); return b2Vec3(a.x + b.x, a.y + b.y, a.z + b.z);
} }
/// Subtract two vectors component-wise. /// Subtract two vectors component-wise.
inline b2Vec3 operator - (const b2Vec3& a, const b2Vec3& b) inline b2Vec3 operator - (const b2Vec3& a, const b2Vec3& b)
{ {
return b2Vec3(a.x - b.x, a.y - b.y, a.z - b.z); return b2Vec3(a.x - b.x, a.y - b.y, a.z - b.z);
} }
/// Perform the dot product on two vectors. /// Perform the dot product on two vectors.
inline float32 b2Dot(const b2Vec3& a, const b2Vec3& b) inline float32 b2Dot(const b2Vec3& a, const b2Vec3& b)
{ {
return a.x * b.x + a.y * b.y + a.z * b.z; return a.x * b.x + a.y * b.y + a.z * b.z;
} }
/// Perform the cross product on two vectors. /// Perform the cross product on two vectors.
inline b2Vec3 b2Cross(const b2Vec3& a, const b2Vec3& b) inline b2Vec3 b2Cross(const b2Vec3& a, const b2Vec3& b)
{ {
return b2Vec3(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b. y - a.y * b.x); return b2Vec3(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x);
} }
inline b2Mat22 operator + (const b2Mat22& A, const b2Mat22& B) inline b2Mat22 operator + (const b2Mat22& A, const b2Mat22& B)
{ {
return b2Mat22(A.ex + B.ex, A.ey + B.ey); return b2Mat22(A.ex + B.ex, A.ey + B.ey);
} }
// A * B // A * B
inline b2Mat22 b2Mul(const b2Mat22& A, const b2Mat22& B) inline b2Mat22 b2Mul(const b2Mat22& A, const b2Mat22& B)
{ {
return b2Mat22(b2Mul(A, B.ex), b2Mul(A, B.ey)); return b2Mat22(b2Mul(A, B.ex), b2Mul(A, B.ey));
} }
// A^T * B // A^T * B
inline b2Mat22 b2MulT(const b2Mat22& A, const b2Mat22& B) inline b2Mat22 b2MulT(const b2Mat22& A, const b2Mat22& B)
{ {
b2Vec2 c1(b2Dot(A.ex, B.ex), b2Dot(A.ey, B.ex)); b2Vec2 c1(b2Dot(A.ex, B.ex), b2Dot(A.ey, B.ex));
b2Vec2 c2(b2Dot(A.ex, B.ey), b2Dot(A.ey, B.ey)); b2Vec2 c2(b2Dot(A.ex, B.ey), b2Dot(A.ey, B.ey));
return b2Mat22(c1, c2); return b2Mat22(c1, c2);
} }
/// Multiply a matrix times a vector. /// Multiply a matrix times a vector.
inline b2Vec3 b2Mul(const b2Mat33& A, const b2Vec3& v) inline b2Vec3 b2Mul(const b2Mat33& A, const b2Vec3& v)
{ {
return v.x * A.ex + v.y * A.ey + v.z * A.ez; return v.x * A.ex + v.y * A.ey + v.z * A.ez;
} }
/// Multiply a matrix times a vector. /// Multiply a matrix times a vector.
inline b2Vec2 b2Mul22(const b2Mat33& A, const b2Vec2& v) inline b2Vec2 b2Mul22(const b2Mat33& A, const b2Vec2& v)
{ {
return b2Vec2(A.ex.x * v.x + A.ey.x * v.y, A.ex.y * v.x + A.ey.y * v .y); return b2Vec2(A.ex.x * v.x + A.ey.x * v.y, A.ex.y * v.x + A.ey.y * v.y) ;
} }
/// Multiply two rotations: q * r /// Multiply two rotations: q * r
inline b2Rot b2Mul(const b2Rot& q, const b2Rot& r) inline b2Rot b2Mul(const b2Rot& q, const b2Rot& r)
{ {
// [qc -qs] * [rc -rs] = [qc*rc-qs*rs -qc*rs-qs*rc] // [qc -qs] * [rc -rs] = [qc*rc-qs*rs -qc*rs-qs*rc]
// [qs qc] [rs rc] [qs*rc+qc*rs -qs*rs+qc*rc] // [qs qc] [rs rc] [qs*rc+qc*rs -qs*rs+qc*rc]
// s = qs * rc + qc * rs // s = qs * rc + qc * rs
// c = qc * rc - qs * rs // c = qc * rc - qs * rs
b2Rot qr; b2Rot qr;
qr.s = q.s * r.c + q.c * r.s; qr.s = q.s * r.c + q.c * r.s;
qr.c = q.c * r.c - q.s * r.s; qr.c = q.c * r.c - q.s * r.s;
return qr; return qr;
} }
/// Transpose multiply two rotations: qT * r /// Transpose multiply two rotations: qT * r
inline b2Rot b2MulT(const b2Rot& q, const b2Rot& r) inline b2Rot b2MulT(const b2Rot& q, const b2Rot& r)
{ {
// [ qc qs] * [rc -rs] = [qc*rc+qs*rs -qc*rs+qs*rc] // [ qc qs] * [rc -rs] = [qc*rc+qs*rs -qc*rs+qs*rc]
// [-qs qc] [rs rc] [-qs*rc+qc*rs qs*rs+qc*rc] // [-qs qc] [rs rc] [-qs*rc+qc*rs qs*rs+qc*rc]
// s = qc * rs - qs * rc // s = qc * rs - qs * rc
// c = qc * rc + qs * rs // c = qc * rc + qs * rs
b2Rot qr; b2Rot qr;
qr.s = q.c * r.s - q.s * r.c; qr.s = q.c * r.s - q.s * r.c;
qr.c = q.c * r.c + q.s * r.s; qr.c = q.c * r.c + q.s * r.s;
return qr; return qr;
} }
/// Rotate a vector /// Rotate a vector
inline b2Vec2 b2Mul(const b2Rot& q, const b2Vec2& v) inline b2Vec2 b2Mul(const b2Rot& q, const b2Vec2& v)
{ {
return b2Vec2(q.c * v.x - q.s * v.y, q.s * v.x + q.c * v.y); return b2Vec2(q.c * v.x - q.s * v.y, q.s * v.x + q.c * v.y);
} }
/// Inverse rotate a vector /// Inverse rotate a vector
inline b2Vec2 b2MulT(const b2Rot& q, const b2Vec2& v) inline b2Vec2 b2MulT(const b2Rot& q, const b2Vec2& v)
{ {
return b2Vec2(q.c * v.x + q.s * v.y, -q.s * v.x + q.c * v.y); return b2Vec2(q.c * v.x + q.s * v.y, -q.s * v.x + q.c * v.y);
} }
inline b2Vec2 b2Mul(const b2Transform& T, const b2Vec2& v) inline b2Vec2 b2Mul(const b2Transform& T, const b2Vec2& v)
{ {
float32 x = (T.q.c * v.x - T.q.s * v.y) + T.p.x; float32 x = (T.q.c * v.x - T.q.s * v.y) + T.p.x;
float32 y = (T.q.s * v.x + T.q.c * v.y) + T.p.y; float32 y = (T.q.s * v.x + T.q.c * v.y) + T.p.y;
return b2Vec2(x, y); return b2Vec2(x, y);
} }
inline b2Vec2 b2MulT(const b2Transform& T, const b2Vec2& v) inline b2Vec2 b2MulT(const b2Transform& T, const b2Vec2& v)
{ {
float32 px = v.x - T.p.x; float32 px = v.x - T.p.x;
float32 py = v.y - T.p.y; float32 py = v.y - T.p.y;
float32 x = (T.q.c * px + T.q.s * py); float32 x = (T.q.c * px + T.q.s * py);
float32 y = (-T.q.s * px + T.q.c * py); float32 y = (-T.q.s * px + T.q.c * py);
return b2Vec2(x, y); return b2Vec2(x, y);
} }
// v2 = A.q.Rot(B.q.Rot(v1) + B.p) + A.p // v2 = A.q.Rot(B.q.Rot(v1) + B.p) + A.p
// = (A.q * B.q).Rot(v1) + A.q.Rot(B.p) + A.p // = (A.q * B.q).Rot(v1) + A.q.Rot(B.p) + A.p
inline b2Transform b2Mul(const b2Transform& A, const b2Transform& B) inline b2Transform b2Mul(const b2Transform& A, const b2Transform& B)
{ {
b2Transform C; b2Transform C;
C.q = b2Mul(A.q, B.q); C.q = b2Mul(A.q, B.q);
C.p = b2Mul(A.q, B.p) + A.p; C.p = b2Mul(A.q, B.p) + A.p;
return C; return C;
} }
// v2 = A.q' * (B.q * v1 + B.p - A.p) // v2 = A.q' * (B.q * v1 + B.p - A.p)
// = A.q' * B.q * v1 + A.q' * (B.p - A.p) // = A.q' * B.q * v1 + A.q' * (B.p - A.p)
inline b2Transform b2MulT(const b2Transform& A, const b2Transform& B) inline b2Transform b2MulT(const b2Transform& A, const b2Transform& B)
{ {
b2Transform C; b2Transform C;
C.q = b2MulT(A.q, B.q); C.q = b2MulT(A.q, B.q);
C.p = b2MulT(A.q, B.p - A.p); C.p = b2MulT(A.q, B.p - A.p);
return C; return C;
} }
template <typename T> template <typename T>
inline T b2Abs(T a) inline T b2Abs(T a)
{ {
return a > T(0) ? a : -a; return a > T(0) ? a : -a;
} }
inline b2Vec2 b2Abs(const b2Vec2& a) inline b2Vec2 b2Abs(const b2Vec2& a)
{ {
return b2Vec2(b2Abs(a.x), b2Abs(a.y)); return b2Vec2(b2Abs(a.x), b2Abs(a.y));
} }
inline b2Mat22 b2Abs(const b2Mat22& A) inline b2Mat22 b2Abs(const b2Mat22& A)
{ {
return b2Mat22(b2Abs(A.ex), b2Abs(A.ey)); return b2Mat22(b2Abs(A.ex), b2Abs(A.ey));
} }
template <typename T> template <typename T>
inline T b2Min(T a, T b) inline T b2Min(T a, T b)
{ {
return a < b ? a : b; return a < b ? a : b;
} }
inline b2Vec2 b2Min(const b2Vec2& a, const b2Vec2& b) inline b2Vec2 b2Min(const b2Vec2& a, const b2Vec2& b)
{ {
return b2Vec2(b2Min(a.x, b.x), b2Min(a.y, b.y)); return b2Vec2(b2Min(a.x, b.x), b2Min(a.y, b.y));
} }
template <typename T> template <typename T>
inline T b2Max(T a, T b) inline T b2Max(T a, T b)
{ {
return a > b ? a : b; return a > b ? a : b;
} }
inline b2Vec2 b2Max(const b2Vec2& a, const b2Vec2& b) inline b2Vec2 b2Max(const b2Vec2& a, const b2Vec2& b)
{ {
return b2Vec2(b2Max(a.x, b.x), b2Max(a.y, b.y)); return b2Vec2(b2Max(a.x, b.x), b2Max(a.y, b.y));
} }
template <typename T> template <typename T>
inline T b2Clamp(T a, T low, T high) inline T b2Clamp(T a, T low, T high)
{ {
return b2Max(low, b2Min(a, high)); return b2Max(low, b2Min(a, high));
} }
inline b2Vec2 b2Clamp(const b2Vec2& a, const b2Vec2& low, const b2Vec2& hig h) inline b2Vec2 b2Clamp(const b2Vec2& a, const b2Vec2& low, const b2Vec2& hig h)
{ {
return b2Max(low, b2Min(a, high)); return b2Max(low, b2Min(a, high));
} }
template<typename T> inline void b2Swap(T& a, T& b) template<typename T> inline void b2Swap(T& a, T& b)
{ {
T tmp = a; T tmp = a;
a = b; a = b;
b = tmp; b = tmp;
} }
/// "Next Largest Power of 2 /// "Next Largest Power of 2
/// Given a binary integer value x, the next largest power of 2 can be comp uted by a SWAR algorithm /// Given a binary integer value x, the next largest power of 2 can be comp uted by a SWAR algorithm
/// that recursively "folds" the upper bits into the lower bits. This proce ss yields a bit vector with /// that recursively "folds" the upper bits into the lower bits. This proce ss yields a bit vector with
/// the same most significant 1 as x, but all 1's below it. Adding 1 to tha t value yields the next /// the same most significant 1 as x, but all 1's below it. Adding 1 to tha t value yields the next
/// largest power of 2. For a 32-bit value:" /// largest power of 2. For a 32-bit value:"
inline uint32 b2NextPowerOfTwo(uint32 x) inline uint32 b2NextPowerOfTwo(uint32 x)
{ {
x |= (x >> 1); x |= (x >> 1);
x |= (x >> 2); x |= (x >> 2);
x |= (x >> 4); x |= (x >> 4);
x |= (x >> 8); x |= (x >> 8);
x |= (x >> 16); x |= (x >> 16);
return x + 1; return x + 1;
} }
inline bool b2IsPowerOfTwo(uint32 x) inline bool b2IsPowerOfTwo(uint32 x)
{ {
bool result = x > 0 && (x & (x - 1)) == 0; bool result = x > 0 && (x & (x - 1)) == 0;
return result; return result;
} }
inline void b2Sweep::GetTransform(b2Transform* xf, float32 beta) const inline void b2Sweep::GetTransform(b2Transform* xf, float32 beta) const
{ {
xf->p = (1.0f - beta) * c0 + beta * c; xf->p = (1.0f - beta) * c0 + beta * c;
float32 angle = (1.0f - beta) * a0 + beta * a; float32 angle = (1.0f - beta) * a0 + beta * a;
xf->q.Set(angle); xf->q.Set(angle);
// Shift to origin // Shift to origin
xf->p -= b2Mul(xf->q, localCenter); xf->p -= b2Mul(xf->q, localCenter);
} }
inline void b2Sweep::Advance(float32 alpha) inline void b2Sweep::Advance(float32 alpha)
{ {
b2Assert(alpha0 < 1.0f); b2Assert(alpha0 < 1.0f);
float32 beta = (alpha - alpha0) / (1.0f - alpha0); float32 beta = (alpha - alpha0) / (1.0f - alpha0);
c0 = (1.0f - beta) * c0 + beta * c; c0 = (1.0f - beta) * c0 + beta * c;
a0 = (1.0f - beta) * a0 + beta * a; a0 = (1.0f - beta) * a0 + beta * a;
alpha0 = alpha; alpha0 = alpha;
} }
/// Normalize an angle in radians to be between -pi and pi /// Normalize an angle in radians to be between -pi and pi
inline void b2Sweep::Normalize() inline void b2Sweep::Normalize()
{ {
float32 twoPi = 2.0f * b2_pi; float32 twoPi = 2.0f * b2_pi;
float32 d = twoPi * floorf(a0 / twoPi); float32 d = twoPi * floorf(a0 / twoPi);
a0 -= d; a0 -= d;
a -= d; a -= d;
} }
#endif #endif
 End of changes. 76 change blocks. 
416 lines changed or deleted 412 lines changed or added


 b2MouseJoint.h   b2MouseJoint.h 
skipping to change at line 28 skipping to change at line 28
#ifndef B2_MOUSE_JOINT_H #ifndef B2_MOUSE_JOINT_H
#define B2_MOUSE_JOINT_H #define B2_MOUSE_JOINT_H
#include <Box2D/Dynamics/Joints/b2Joint.h> #include <Box2D/Dynamics/Joints/b2Joint.h>
/// Mouse joint definition. This requires a world target point, /// Mouse joint definition. This requires a world target point,
/// tuning parameters, and the time step. /// tuning parameters, and the time step.
struct b2MouseJointDef : public b2JointDef struct b2MouseJointDef : public b2JointDef
{ {
b2MouseJointDef() b2MouseJointDef()
{ {
type = e_mouseJoint; type = e_mouseJoint;
target.Set(0.0f, 0.0f); target.Set(0.0f, 0.0f);
maxForce = 0.0f; maxForce = 0.0f;
frequencyHz = 5.0f; frequencyHz = 5.0f;
dampingRatio = 0.7f; dampingRatio = 0.7f;
} }
/// The initial world target point. This is assumed /// The initial world target point. This is assumed
/// to coincide with the body anchor initially. /// to coincide with the body anchor initially.
b2Vec2 target; b2Vec2 target;
/// The maximum constraint force that can be exerted /// The maximum constraint force that can be exerted
/// to move the candidate body. Usually you will express /// to move the candidate body. Usually you will express
/// as some multiple of the weight (multiplier * mass * gravity). /// as some multiple of the weight (multiplier * mass * gravity).
float32 maxForce; float32 maxForce;
/// The response speed. /// The response speed.
float32 frequencyHz; float32 frequencyHz;
/// The damping ratio. 0 = no damping, 1 = critical damping. /// The damping ratio. 0 = no damping, 1 = critical damping.
float32 dampingRatio; float32 dampingRatio;
}; };
/// A mouse joint is used to make a point on a body track a /// A mouse joint is used to make a point on a body track a
/// specified world point. This a soft constraint with a maximum /// specified world point. This a soft constraint with a maximum
/// force. This allows the constraint to stretch and without /// force. This allows the constraint to stretch and without
/// applying huge forces. /// applying huge forces.
/// NOTE: this joint is not documented in the manual because it was /// NOTE: this joint is not documented in the manual because it was
/// developed to be used in the testbed. If you want to learn how to /// developed to be used in the testbed. If you want to learn how to
/// use the mouse joint, look at the testbed. /// use the mouse joint, look at the testbed.
class b2MouseJoint : public b2Joint class b2MouseJoint : public b2Joint
{ {
public: public:
/// Implements b2Joint. /// Implements b2Joint.
b2Vec2 GetAnchorA() const; b2Vec2 GetAnchorA() const;
/// Implements b2Joint. /// Implements b2Joint.
b2Vec2 GetAnchorB() const; b2Vec2 GetAnchorB() const;
/// Implements b2Joint. /// Implements b2Joint.
b2Vec2 GetReactionForce(float32 inv_dt) const; b2Vec2 GetReactionForce(float32 inv_dt) const;
/// Implements b2Joint. /// Implements b2Joint.
float32 GetReactionTorque(float32 inv_dt) const; float32 GetReactionTorque(float32 inv_dt) const;
/// Use this to update the target point. /// Use this to update the target point.
void SetTarget(const b2Vec2& target); void SetTarget(const b2Vec2& target);
const b2Vec2& GetTarget() const; const b2Vec2& GetTarget() const;
/// Set/get the maximum force in Newtons. /// Set/get the maximum force in Newtons.
void SetMaxForce(float32 force); void SetMaxForce(float32 force);
float32 GetMaxForce() const; float32 GetMaxForce() const;
/// Set/get the frequency in Hertz. /// Set/get the frequency in Hertz.
void SetFrequency(float32 hz); void SetFrequency(float32 hz);
float32 GetFrequency() const; float32 GetFrequency() const;
/// Set/get the damping ratio (dimensionless). /// Set/get the damping ratio (dimensionless).
void SetDampingRatio(float32 ratio); void SetDampingRatio(float32 ratio);
float32 GetDampingRatio() const; float32 GetDampingRatio() const;
/// The mouse joint does not support dumping. /// The mouse joint does not support dumping.
void Dump() { b2Log("Mouse joint dumping is not supported.\n"); } void Dump() { b2Log("Mouse joint dumping is not supported.\n"); }
protected: protected:
friend class b2Joint; friend class b2Joint;
b2MouseJoint(const b2MouseJointDef* def); b2MouseJoint(const b2MouseJointDef* def);
void InitVelocityConstraints(const b2SolverData& data); void InitVelocityConstraints(const b2SolverData& data);
void SolveVelocityConstraints(const b2SolverData& data); void SolveVelocityConstraints(const b2SolverData& data);
bool SolvePositionConstraints(const b2SolverData& data); bool SolvePositionConstraints(const b2SolverData& data);
b2Vec2 m_localAnchorB; b2Vec2 m_localAnchorB;
b2Vec2 m_targetA; b2Vec2 m_targetA;
float32 m_frequencyHz; float32 m_frequencyHz;
float32 m_dampingRatio; float32 m_dampingRatio;
float32 m_beta; float32 m_beta;
// Solver shared // Solver shared
b2Vec2 m_impulse; b2Vec2 m_impulse;
float32 m_maxForce; float32 m_maxForce;
float32 m_gamma; float32 m_gamma;
// Solver temp // Solver temp
int32 m_indexA; int32 m_indexA;
int32 m_indexB; int32 m_indexB;
b2Vec2 m_rB; b2Vec2 m_rB;
b2Vec2 m_localCenterB; b2Vec2 m_localCenterB;
float32 m_invMassB; float32 m_invMassB;
float32 m_invIB; float32 m_invIB;
b2Mat22 m_mass; b2Mat22 m_mass;
b2Vec2 m_C; b2Vec2 m_C;
}; };
#endif #endif
 End of changes. 15 change blocks. 
69 lines changed or deleted 69 lines changed or added


 b2PolygonAndCircleContact.h   b2PolygonAndCircleContact.h 
skipping to change at line 29 skipping to change at line 29
#ifndef B2_POLYGON_AND_CIRCLE_CONTACT_H #ifndef B2_POLYGON_AND_CIRCLE_CONTACT_H
#define B2_POLYGON_AND_CIRCLE_CONTACT_H #define B2_POLYGON_AND_CIRCLE_CONTACT_H
#include <Box2D/Dynamics/Contacts/b2Contact.h> #include <Box2D/Dynamics/Contacts/b2Contact.h>
class b2BlockAllocator; class b2BlockAllocator;
class b2PolygonAndCircleContact : public b2Contact class b2PolygonAndCircleContact : public b2Contact
{ {
public: public:
static b2Contact* Create(b2Fixture* fixtureA, int32 indexA, b2Fixtur static b2Contact* Create(b2Fixture* fixtureA, int32 indexA, b2Fixture*
e* fixtureB, int32 indexB, b2BlockAllocator* allocator); fixtureB, int32 indexB, b2BlockAllocator* allocator);
static void Destroy(b2Contact* contact, b2BlockAllocator* allocator) static void Destroy(b2Contact* contact, b2BlockAllocator* allocator);
;
b2PolygonAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB); b2PolygonAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB);
~b2PolygonAndCircleContact() {} ~b2PolygonAndCircleContact() {}
void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2 Transform& xfB); void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Tra nsform& xfB);
}; };
#endif #endif
 End of changes. 3 change blocks. 
7 lines changed or deleted 6 lines changed or added


 b2PolygonContact.h   b2PolygonContact.h 
skipping to change at line 29 skipping to change at line 29
#ifndef B2_POLYGON_CONTACT_H #ifndef B2_POLYGON_CONTACT_H
#define B2_POLYGON_CONTACT_H #define B2_POLYGON_CONTACT_H
#include <Box2D/Dynamics/Contacts/b2Contact.h> #include <Box2D/Dynamics/Contacts/b2Contact.h>
class b2BlockAllocator; class b2BlockAllocator;
class b2PolygonContact : public b2Contact class b2PolygonContact : public b2Contact
{ {
public: public:
static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, static b2Contact* Create( b2Fixture* fixtureA, int32 indexA,
b2Fixture* f b2Fixture* fixtureB, int32 indexB, b2BlockA
ixtureB, int32 indexB, b2BlockAllocator* allocator); llocator* allocator);
static void Destroy(b2Contact* contact, b2BlockAllocator* allocator) static void Destroy(b2Contact* contact, b2BlockAllocator* allocator);
;
b2PolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB); b2PolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB);
~b2PolygonContact() {} ~b2PolygonContact() {}
void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2 Transform& xfB); void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Tra nsform& xfB);
}; };
#endif #endif
 End of changes. 3 change blocks. 
8 lines changed or deleted 7 lines changed or added


 b2PolygonShape.h   b2PolygonShape.h 
skipping to change at line 31 skipping to change at line 31
#include <Box2D/Collision/Shapes/b2Shape.h> #include <Box2D/Collision/Shapes/b2Shape.h>
/// A convex polygon. It is assumed that the interior of the polygon is to /// A convex polygon. It is assumed that the interior of the polygon is to
/// the left of each edge. /// the left of each edge.
/// Polygons have a maximum number of vertices equal to b2_maxPolygonVertic es. /// Polygons have a maximum number of vertices equal to b2_maxPolygonVertic es.
/// In most cases you should not need many vertices for a convex polygon. /// In most cases you should not need many vertices for a convex polygon.
class b2PolygonShape : public b2Shape class b2PolygonShape : public b2Shape
{ {
public: public:
b2PolygonShape(); b2PolygonShape();
/// Implement b2Shape. /// Implement b2Shape.
b2Shape* Clone(b2BlockAllocator* allocator) const; b2Shape* Clone(b2BlockAllocator* allocator) const;
/// @see b2Shape::GetChildCount /// @see b2Shape::GetChildCount
int32 GetChildCount() const; int32 GetChildCount() const;
/// Copy vertices. This assumes the vertices define a convex polygon /// Copy vertices. This assumes the vertices define a convex polygon.
. /// It is assumed that the exterior is the the right of each edge.
/// It is assumed that the exterior is the the right of each edge. /// The count must be in the range [3, b2_maxPolygonVertices].
/// The count must be in the range [3, b2_maxPolygonVertices]. void Set(const b2Vec2* vertices, int32 vertexCount);
void Set(const b2Vec2* vertices, int32 vertexCount);
/// Build vertices to represent an axis-aligned box.
/// Build vertices to represent an axis-aligned box. /// @param hx the half-width.
/// @param hx the half-width. /// @param hy the half-height.
/// @param hy the half-height. void SetAsBox(float32 hx, float32 hy);
void SetAsBox(float32 hx, float32 hy);
/// Build vertices to represent an oriented box.
/// Build vertices to represent an oriented box. /// @param hx the half-width.
/// @param hx the half-width. /// @param hy the half-height.
/// @param hy the half-height. /// @param center the center of the box in local coordinates.
/// @param center the center of the box in local coordinates. /// @param angle the rotation of the box in local coordinates.
/// @param angle the rotation of the box in local coordinates. void SetAsBox(float32 hx, float32 hy, const b2Vec2& center, float32 ang
void SetAsBox(float32 hx, float32 hy, const b2Vec2& center, float32 le);
angle);
/// @see b2Shape::TestPoint
/// @see b2Shape::TestPoint bool TestPoint(const b2Transform& transform, const b2Vec2& p) const;
bool TestPoint(const b2Transform& transform, const b2Vec2& p) const;
/// Implement b2Shape.
/// Implement b2Shape. bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input,
bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, const b2Transform& transform, int32 childIndex) const;
const b2Transform& transform, int32
childIndex) const; /// @see b2Shape::ComputeAABB
void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 chil
/// @see b2Shape::ComputeAABB dIndex) const;
void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 c
hildIndex) const; /// @see b2Shape::ComputeMass
void ComputeMass(b2MassData* massData, float32 density) const;
/// @see b2Shape::ComputeMass
void ComputeMass(b2MassData* massData, float32 density) const; /// Get the vertex count.
int32 GetVertexCount() const { return m_vertexCount; }
/// Get the vertex count.
int32 GetVertexCount() const { return m_vertexCount; } /// Get a vertex by index.
const b2Vec2& GetVertex(int32 index) const;
/// Get a vertex by index.
const b2Vec2& GetVertex(int32 index) const; b2Vec2 m_centroid;
b2Vec2 m_vertices[b2_maxPolygonVertices];
b2Vec2 m_centroid; b2Vec2 m_normals[b2_maxPolygonVertices];
b2Vec2 m_vertices[b2_maxPolygonVertices]; int32 m_vertexCount;
b2Vec2 m_normals[b2_maxPolygonVertices];
int32 m_vertexCount;
}; };
inline b2PolygonShape::b2PolygonShape() inline b2PolygonShape::b2PolygonShape()
{ {
m_type = e_polygon; m_type = e_polygon;
m_radius = b2_polygonRadius; m_radius = b2_polygonRadius;
m_vertexCount = 0; m_vertexCount = 0;
m_centroid.SetZero(); m_centroid.SetZero();
} }
inline const b2Vec2& b2PolygonShape::GetVertex(int32 index) const inline const b2Vec2& b2PolygonShape::GetVertex(int32 index) const
{ {
b2Assert(0 <= index && index < m_vertexCount); b2Assert(0 <= index && index < m_vertexCount);
return m_vertices[index]; return m_vertices[index];
} }
#endif #endif
 End of changes. 6 change blocks. 
55 lines changed or deleted 53 lines changed or added


 b2PrismaticJoint.h   b2PrismaticJoint.h 
skipping to change at line 32 skipping to change at line 32
#include <Box2D/Dynamics/Joints/b2Joint.h> #include <Box2D/Dynamics/Joints/b2Joint.h>
/// Prismatic joint definition. This requires defining a line of /// Prismatic joint definition. This requires defining a line of
/// motion using an axis and an anchor point. The definition uses local /// motion using an axis and an anchor point. The definition uses local
/// anchor points and a local axis so that the initial configuration /// anchor points and a local axis so that the initial configuration
/// can violate the constraint slightly. The joint translation is zero /// can violate the constraint slightly. The joint translation is zero
/// when the local anchor points coincide in world space. Using local /// when the local anchor points coincide in world space. Using local
/// anchors and a local axis helps when saving and loading a game. /// anchors and a local axis helps when saving and loading a game.
struct b2PrismaticJointDef : public b2JointDef struct b2PrismaticJointDef : public b2JointDef
{ {
b2PrismaticJointDef() b2PrismaticJointDef()
{ {
type = e_prismaticJoint; type = e_prismaticJoint;
localAnchorA.SetZero(); localAnchorA.SetZero();
localAnchorB.SetZero(); localAnchorB.SetZero();
localAxisA.Set(1.0f, 0.0f); localAxisA.Set(1.0f, 0.0f);
referenceAngle = 0.0f; referenceAngle = 0.0f;
enableLimit = false; enableLimit = false;
lowerTranslation = 0.0f; lowerTranslation = 0.0f;
upperTranslation = 0.0f; upperTranslation = 0.0f;
enableMotor = false; enableMotor = false;
maxMotorForce = 0.0f; maxMotorForce = 0.0f;
motorSpeed = 0.0f; motorSpeed = 0.0f;
} }
/// Initialize the bodies, anchors, axis, and reference angle using /// Initialize the bodies, anchors, axis, and reference angle using the
the world world
/// anchor and unit world axis. /// anchor and unit world axis.
void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor, void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor, con
const b2Vec2& axis); st b2Vec2& axis);
/// The local anchor point relative to bodyA's origin. /// The local anchor point relative to bodyA's origin.
b2Vec2 localAnchorA; b2Vec2 localAnchorA;
/// The local anchor point relative to bodyB's origin. /// The local anchor point relative to bodyB's origin.
b2Vec2 localAnchorB; b2Vec2 localAnchorB;
/// The local translation unit axis in bodyA. /// The local translation unit axis in bodyA.
b2Vec2 localAxisA; b2Vec2 localAxisA;
/// The constrained angle between the bodies: bodyB_angle - bodyA_an /// The constrained angle between the bodies: bodyB_angle - bodyA_angle
gle. .
float32 referenceAngle; float32 referenceAngle;
/// Enable/disable the joint limit. /// Enable/disable the joint limit.
bool enableLimit; bool enableLimit;
/// The lower translation limit, usually in meters. /// The lower translation limit, usually in meters.
float32 lowerTranslation; float32 lowerTranslation;
/// The upper translation limit, usually in meters. /// The upper translation limit, usually in meters.
float32 upperTranslation; float32 upperTranslation;
/// Enable/disable the joint motor. /// Enable/disable the joint motor.
bool enableMotor; bool enableMotor;
/// The maximum motor torque, usually in N-m. /// The maximum motor torque, usually in N-m.
float32 maxMotorForce; float32 maxMotorForce;
/// The desired motor speed in radians per second. /// The desired motor speed in radians per second.
float32 motorSpeed; float32 motorSpeed;
}; };
/// A prismatic joint. This joint provides one degree of freedom: translati on /// A prismatic joint. This joint provides one degree of freedom: translati on
/// along an axis fixed in bodyA. Relative rotation is prevented. You can /// along an axis fixed in bodyA. Relative rotation is prevented. You can
/// use a joint limit to restrict the range of motion and a joint motor to /// use a joint limit to restrict the range of motion and a joint motor to
/// drive the motion or to model joint friction. /// drive the motion or to model joint friction.
class b2PrismaticJoint : public b2Joint class b2PrismaticJoint : public b2Joint
{ {
public: public:
b2Vec2 GetAnchorA() const; b2Vec2 GetAnchorA() const;
b2Vec2 GetAnchorB() const; b2Vec2 GetAnchorB() const;
b2Vec2 GetReactionForce(float32 inv_dt) const; b2Vec2 GetReactionForce(float32 inv_dt) const;
float32 GetReactionTorque(float32 inv_dt) const; float32 GetReactionTorque(float32 inv_dt) const;
/// The local anchor point relative to bodyA's origin. /// The local anchor point relative to bodyA's origin.
const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; }
/// The local anchor point relative to bodyB's origin. /// The local anchor point relative to bodyB's origin.
const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; }
/// The local joint axis relative to bodyA. /// The local joint axis relative to bodyA.
const b2Vec2& GetLocalAxisA() const { return m_localXAxisA; } const b2Vec2& GetLocalAxisA() const { return m_localXAxisA; }
/// Get the reference angle. /// Get the reference angle.
float32 GetReferenceAngle() const { return m_referenceAngle; } float32 GetReferenceAngle() const { return m_referenceAngle; }
/// Get the current joint translation, usually in meters. /// Get the current joint translation, usually in meters.
float32 GetJointTranslation() const; float32 GetJointTranslation() const;
/// Get the current joint translation speed, usually in meters per s /// Get the current joint translation speed, usually in meters per seco
econd. nd.
float32 GetJointSpeed() const; float32 GetJointSpeed() const;
/// Is the joint limit enabled? /// Is the joint limit enabled?
bool IsLimitEnabled() const; bool IsLimitEnabled() const;
/// Enable/disable the joint limit. /// Enable/disable the joint limit.
void EnableLimit(bool flag); void EnableLimit(bool flag);
/// Get the lower joint limit, usually in meters. /// Get the lower joint limit, usually in meters.
float32 GetLowerLimit() const; float32 GetLowerLimit() const;
/// Get the upper joint limit, usually in meters. /// Get the upper joint limit, usually in meters.
float32 GetUpperLimit() const; float32 GetUpperLimit() const;
/// Set the joint limits, usually in meters. /// Set the joint limits, usually in meters.
void SetLimits(float32 lower, float32 upper); void SetLimits(float32 lower, float32 upper);
/// Is the joint motor enabled? /// Is the joint motor enabled?
bool IsMotorEnabled() const; bool IsMotorEnabled() const;
/// Enable/disable the joint motor. /// Enable/disable the joint motor.
void EnableMotor(bool flag); void EnableMotor(bool flag);
/// Set the motor speed, usually in meters per second. /// Set the motor speed, usually in meters per second.
void SetMotorSpeed(float32 speed); void SetMotorSpeed(float32 speed);
/// Get the motor speed, usually in meters per second. /// Get the motor speed, usually in meters per second.
float32 GetMotorSpeed() const; float32 GetMotorSpeed() const;
/// Set the maximum motor force, usually in N. /// Set the maximum motor force, usually in N.
void SetMaxMotorForce(float32 force); void SetMaxMotorForce(float32 force);
float32 GetMaxMotorForce() const { return m_maxMotorForce; } float32 GetMaxMotorForce() const { return m_maxMotorForce; }
/// Get the current motor force given the inverse time step, usually /// Get the current motor force given the inverse time step, usually in
in N. N.
float32 GetMotorForce(float32 inv_dt) const; float32 GetMotorForce(float32 inv_dt) const;
/// Dump to b2Log /// Dump to b2Log
void Dump(); void Dump();
protected: protected:
friend class b2Joint; friend class b2Joint;
friend class b2GearJoint; friend class b2GearJoint;
b2PrismaticJoint(const b2PrismaticJointDef* def); b2PrismaticJoint(const b2PrismaticJointDef* def);
void InitVelocityConstraints(const b2SolverData& data); void InitVelocityConstraints(const b2SolverData& data);
void SolveVelocityConstraints(const b2SolverData& data); void SolveVelocityConstraints(const b2SolverData& data);
bool SolvePositionConstraints(const b2SolverData& data); bool SolvePositionConstraints(const b2SolverData& data);
// Solver shared // Solver shared
b2Vec2 m_localAnchorA; b2Vec2 m_localAnchorA;
b2Vec2 m_localAnchorB; b2Vec2 m_localAnchorB;
b2Vec2 m_localXAxisA; b2Vec2 m_localXAxisA;
b2Vec2 m_localYAxisA; b2Vec2 m_localYAxisA;
float32 m_referenceAngle; float32 m_referenceAngle;
b2Vec3 m_impulse; b2Vec3 m_impulse;
float32 m_motorImpulse; float32 m_motorImpulse;
float32 m_lowerTranslation; float32 m_lowerTranslation;
float32 m_upperTranslation; float32 m_upperTranslation;
float32 m_maxMotorForce; float32 m_maxMotorForce;
float32 m_motorSpeed; float32 m_motorSpeed;
bool m_enableLimit; bool m_enableLimit;
bool m_enableMotor; bool m_enableMotor;
b2LimitState m_limitState; b2LimitState m_limitState;
// Solver temp // Solver temp
int32 m_indexA; int32 m_indexA;
int32 m_indexB; int32 m_indexB;
b2Vec2 m_localCenterA; b2Vec2 m_localCenterA;
b2Vec2 m_localCenterB; b2Vec2 m_localCenterB;
float32 m_invMassA; float32 m_invMassA;
float32 m_invMassB; float32 m_invMassB;
float32 m_invIA; float32 m_invIA;
float32 m_invIB; float32 m_invIB;
b2Vec2 m_axis, m_perp; b2Vec2 m_axis, m_perp;
float32 m_s1, m_s2; float32 m_s1, m_s2;
float32 m_a1, m_a2; float32 m_a1, m_a2;
b2Mat33 m_K; b2Mat33 m_K;
float32 m_motorMass; float32 m_motorMass;
}; };
inline float32 b2PrismaticJoint::GetMotorSpeed() const inline float32 b2PrismaticJoint::GetMotorSpeed() const
{ {
return m_motorSpeed; return m_motorSpeed;
} }
#endif #endif
 End of changes. 26 change blocks. 
130 lines changed or deleted 130 lines changed or added


 b2PulleyJoint.h   b2PulleyJoint.h 
skipping to change at line 30 skipping to change at line 30
#define B2_PULLEY_JOINT_H #define B2_PULLEY_JOINT_H
#include <Box2D/Dynamics/Joints/b2Joint.h> #include <Box2D/Dynamics/Joints/b2Joint.h>
const float32 b2_minPulleyLength = 2.0f; const float32 b2_minPulleyLength = 2.0f;
/// Pulley joint definition. This requires two ground anchors, /// Pulley joint definition. This requires two ground anchors,
/// two dynamic body anchor points, and a pulley ratio. /// two dynamic body anchor points, and a pulley ratio.
struct b2PulleyJointDef : public b2JointDef struct b2PulleyJointDef : public b2JointDef
{ {
b2PulleyJointDef() b2PulleyJointDef()
{ {
type = e_pulleyJoint; type = e_pulleyJoint;
groundAnchorA.Set(-1.0f, 1.0f); groundAnchorA.Set(-1.0f, 1.0f);
groundAnchorB.Set(1.0f, 1.0f); groundAnchorB.Set(1.0f, 1.0f);
localAnchorA.Set(-1.0f, 0.0f); localAnchorA.Set(-1.0f, 0.0f);
localAnchorB.Set(1.0f, 0.0f); localAnchorB.Set(1.0f, 0.0f);
lengthA = 0.0f; lengthA = 0.0f;
lengthB = 0.0f; lengthB = 0.0f;
ratio = 1.0f; ratio = 1.0f;
collideConnected = true; collideConnected = true;
} }
/// Initialize the bodies, anchors, lengths, max lengths, and ratio /// Initialize the bodies, anchors, lengths, max lengths, and ratio usi
using the world anchors. ng the world anchors.
void Initialize(b2Body* bodyA, b2Body* bodyB, void Initialize(b2Body* bodyA, b2Body* bodyB,
const b2Vec2& groundAnchorA, const b const b2Vec2& groundAnchorA, const b2Vec2& groundAnchor
2Vec2& groundAnchorB, B,
const b2Vec2& anchorA, const b2Vec2& const b2Vec2& anchorA, const b2Vec2& anchorB,
anchorB, float32 ratio);
float32 ratio);
/// The first ground anchor in world coordinates. This point never move
/// The first ground anchor in world coordinates. This point never m s.
oves. b2Vec2 groundAnchorA;
b2Vec2 groundAnchorA;
/// The second ground anchor in world coordinates. This point never mov
/// The second ground anchor in world coordinates. This point never es.
moves. b2Vec2 groundAnchorB;
b2Vec2 groundAnchorB;
/// The local anchor point relative to bodyA's origin.
/// The local anchor point relative to bodyA's origin. b2Vec2 localAnchorA;
b2Vec2 localAnchorA;
/// The local anchor point relative to bodyB's origin.
/// The local anchor point relative to bodyB's origin. b2Vec2 localAnchorB;
b2Vec2 localAnchorB;
/// The a reference length for the segment attached to bodyA. /// The a reference length for the segment attached to bodyA.
float32 lengthA; float32 lengthA;
/// The a reference length for the segment attached to bodyB. /// The a reference length for the segment attached to bodyB.
float32 lengthB; float32 lengthB;
/// The pulley ratio, used to simulate a block-and-tackle. /// The pulley ratio, used to simulate a block-and-tackle.
float32 ratio; float32 ratio;
}; };
/// The pulley joint is connected to two bodies and two fixed ground points . /// The pulley joint is connected to two bodies and two fixed ground points .
/// The pulley supports a ratio such that: /// The pulley supports a ratio such that:
/// length1 + ratio * length2 <= constant /// length1 + ratio * length2 <= constant
/// Yes, the force transmitted is scaled by the ratio. /// Yes, the force transmitted is scaled by the ratio.
/// Warning: the pulley joint can get a bit squirrelly by itself. They ofte n /// Warning: the pulley joint can get a bit squirrelly by itself. They ofte n
/// work better when combined with prismatic joints. You should also cover the /// work better when combined with prismatic joints. You should also cover the
/// the anchor points with static shapes to prevent one side from going to /// the anchor points with static shapes to prevent one side from going to
/// zero length. /// zero length.
class b2PulleyJoint : public b2Joint class b2PulleyJoint : public b2Joint
{ {
public: public:
b2Vec2 GetAnchorA() const; b2Vec2 GetAnchorA() const;
b2Vec2 GetAnchorB() const; b2Vec2 GetAnchorB() const;
b2Vec2 GetReactionForce(float32 inv_dt) const; b2Vec2 GetReactionForce(float32 inv_dt) const;
float32 GetReactionTorque(float32 inv_dt) const; float32 GetReactionTorque(float32 inv_dt) const;
/// Get the first ground anchor. /// Get the first ground anchor.
b2Vec2 GetGroundAnchorA() const; b2Vec2 GetGroundAnchorA() const;
/// Get the second ground anchor. /// Get the second ground anchor.
b2Vec2 GetGroundAnchorB() const; b2Vec2 GetGroundAnchorB() const;
/// Get the current length of the segment attached to bodyA. /// Get the current length of the segment attached to bodyA.
float32 GetLengthA() const; float32 GetLengthA() const;
/// Get the current length of the segment attached to bodyB. /// Get the current length of the segment attached to bodyB.
float32 GetLengthB() const; float32 GetLengthB() const;
/// Get the pulley ratio. /// Get the pulley ratio.
float32 GetRatio() const; float32 GetRatio() const;
/// Dump joint to dmLog /// Dump joint to dmLog
void Dump(); void Dump();
protected: protected:
friend class b2Joint; friend class b2Joint;
b2PulleyJoint(const b2PulleyJointDef* data); b2PulleyJoint(const b2PulleyJointDef* data);
void InitVelocityConstraints(const b2SolverData& data); void InitVelocityConstraints(const b2SolverData& data);
void SolveVelocityConstraints(const b2SolverData& data); void SolveVelocityConstraints(const b2SolverData& data);
bool SolvePositionConstraints(const b2SolverData& data); bool SolvePositionConstraints(const b2SolverData& data);
b2Vec2 m_groundAnchorA; b2Vec2 m_groundAnchorA;
b2Vec2 m_groundAnchorB; b2Vec2 m_groundAnchorB;
float32 m_lengthA; float32 m_lengthA;
float32 m_lengthB; float32 m_lengthB;
// Solver shared // Solver shared
b2Vec2 m_localAnchorA; b2Vec2 m_localAnchorA;
b2Vec2 m_localAnchorB; b2Vec2 m_localAnchorB;
float32 m_constant; float32 m_constant;
float32 m_ratio; float32 m_ratio;
float32 m_impulse; float32 m_impulse;
// Solver temp // Solver temp
int32 m_indexA; int32 m_indexA;
int32 m_indexB; int32 m_indexB;
b2Vec2 m_uA; b2Vec2 m_uA;
b2Vec2 m_uB; b2Vec2 m_uB;
b2Vec2 m_rA; b2Vec2 m_rA;
b2Vec2 m_rB; b2Vec2 m_rB;
b2Vec2 m_localCenterA; b2Vec2 m_localCenterA;
b2Vec2 m_localCenterB; b2Vec2 m_localCenterB;
float32 m_invMassA; float32 m_invMassA;
float32 m_invMassB; float32 m_invMassB;
float32 m_invIA; float32 m_invIA;
float32 m_invIB; float32 m_invIB;
float32 m_mass; float32 m_mass;
}; };
#endif #endif
 End of changes. 14 change blocks. 
89 lines changed or deleted 88 lines changed or added


 b2RevoluteJoint.h   b2RevoluteJoint.h 
skipping to change at line 37 skipping to change at line 37
/// can violate the constraint slightly. You also need to /// can violate the constraint slightly. You also need to
/// specify the initial relative angle for joint limits. This /// specify the initial relative angle for joint limits. This
/// helps when saving and loading a game. /// helps when saving and loading a game.
/// The local anchor points are measured from the body's origin /// The local anchor points are measured from the body's origin
/// rather than the center of mass because: /// rather than the center of mass because:
/// 1. you might not know where the center of mass will be. /// 1. you might not know where the center of mass will be.
/// 2. if you add/remove shapes from a body and recompute the mass, /// 2. if you add/remove shapes from a body and recompute the mass,
/// the joints will be broken. /// the joints will be broken.
struct b2RevoluteJointDef : public b2JointDef struct b2RevoluteJointDef : public b2JointDef
{ {
b2RevoluteJointDef() b2RevoluteJointDef()
{ {
type = e_revoluteJoint; type = e_revoluteJoint;
localAnchorA.Set(0.0f, 0.0f); localAnchorA.Set(0.0f, 0.0f);
localAnchorB.Set(0.0f, 0.0f); localAnchorB.Set(0.0f, 0.0f);
referenceAngle = 0.0f; referenceAngle = 0.0f;
lowerAngle = 0.0f; lowerAngle = 0.0f;
upperAngle = 0.0f; upperAngle = 0.0f;
maxMotorTorque = 0.0f; maxMotorTorque = 0.0f;
motorSpeed = 0.0f; motorSpeed = 0.0f;
enableLimit = false; enableLimit = false;
enableMotor = false; enableMotor = false;
} }
/// Initialize the bodies, anchors, and reference angle using a worl /// Initialize the bodies, anchors, and reference angle using a world
d /// anchor point.
/// anchor point. void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor);
void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor);
/// The local anchor point relative to bodyA's origin.
/// The local anchor point relative to bodyA's origin. b2Vec2 localAnchorA;
b2Vec2 localAnchorA;
/// The local anchor point relative to bodyB's origin.
/// The local anchor point relative to bodyB's origin. b2Vec2 localAnchorB;
b2Vec2 localAnchorB;
/// The bodyB angle minus bodyA angle in the reference state (radians).
/// The bodyB angle minus bodyA angle in the reference state (radian float32 referenceAngle;
s).
float32 referenceAngle; /// A flag to enable joint limits.
bool enableLimit;
/// A flag to enable joint limits.
bool enableLimit; /// The lower angle for the joint limit (radians).
float32 lowerAngle;
/// The lower angle for the joint limit (radians).
float32 lowerAngle; /// The upper angle for the joint limit (radians).
float32 upperAngle;
/// The upper angle for the joint limit (radians).
float32 upperAngle; /// A flag to enable the joint motor.
bool enableMotor;
/// A flag to enable the joint motor.
bool enableMotor; /// The desired motor speed. Usually in radians per second.
float32 motorSpeed;
/// The desired motor speed. Usually in radians per second.
float32 motorSpeed; /// The maximum motor torque used to achieve the desired motor speed.
/// Usually in N-m.
/// The maximum motor torque used to achieve the desired motor speed float32 maxMotorTorque;
.
/// Usually in N-m.
float32 maxMotorTorque;
}; };
/// A revolute joint constrains two bodies to share a common point while th ey /// A revolute joint constrains two bodies to share a common point while th ey
/// are free to rotate about the point. The relative rotation about the sha red /// are free to rotate about the point. The relative rotation about the sha red
/// point is the joint angle. You can limit the relative rotation with /// point is the joint angle. You can limit the relative rotation with
/// a joint limit that specifies a lower and upper angle. You can use a mot or /// a joint limit that specifies a lower and upper angle. You can use a mot or
/// to drive the relative rotation about the shared point. A maximum motor torque /// to drive the relative rotation about the shared point. A maximum motor torque
/// is provided so that infinite forces are not generated. /// is provided so that infinite forces are not generated.
class b2RevoluteJoint : public b2Joint class b2RevoluteJoint : public b2Joint
{ {
public: public:
b2Vec2 GetAnchorA() const; b2Vec2 GetAnchorA() const;
b2Vec2 GetAnchorB() const; b2Vec2 GetAnchorB() const;
/// The local anchor point relative to bodyA's origin. /// The local anchor point relative to bodyA's origin.
const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; }
/// The local anchor point relative to bodyB's origin. /// The local anchor point relative to bodyB's origin.
const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; }
/// Get the reference angle. /// Get the reference angle.
float32 GetReferenceAngle() const { return m_referenceAngle; } float32 GetReferenceAngle() const { return m_referenceAngle; }
/// Get the current joint angle in radians. /// Get the current joint angle in radians.
float32 GetJointAngle() const; float32 GetJointAngle() const;
/// Get the current joint angle speed in radians per second. /// Get the current joint angle speed in radians per second.
float32 GetJointSpeed() const; float32 GetJointSpeed() const;
/// Is the joint limit enabled? /// Is the joint limit enabled?
bool IsLimitEnabled() const; bool IsLimitEnabled() const;
/// Enable/disable the joint limit. /// Enable/disable the joint limit.
void EnableLimit(bool flag); void EnableLimit(bool flag);
/// Get the lower joint limit in radians. /// Get the lower joint limit in radians.
float32 GetLowerLimit() const; float32 GetLowerLimit() const;
/// Get the upper joint limit in radians. /// Get the upper joint limit in radians.
float32 GetUpperLimit() const; float32 GetUpperLimit() const;
/// Set the joint limits in radians. /// Set the joint limits in radians.
void SetLimits(float32 lower, float32 upper); void SetLimits(float32 lower, float32 upper);
/// Is the joint motor enabled? /// Is the joint motor enabled?
bool IsMotorEnabled() const; bool IsMotorEnabled() const;
/// Enable/disable the joint motor. /// Enable/disable the joint motor.
void EnableMotor(bool flag); void EnableMotor(bool flag);
/// Set the motor speed in radians per second. /// Set the motor speed in radians per second.
void SetMotorSpeed(float32 speed); void SetMotorSpeed(float32 speed);
/// Get the motor speed in radians per second. /// Get the motor speed in radians per second.
float32 GetMotorSpeed() const; float32 GetMotorSpeed() const;
/// Set the maximum motor torque, usually in N-m. /// Set the maximum motor torque, usually in N-m.
void SetMaxMotorTorque(float32 torque); void SetMaxMotorTorque(float32 torque);
float32 GetMaxMotorTorque() const { return m_maxMotorTorque; } float32 GetMaxMotorTorque() const { return m_maxMotorTorque; }
/// Get the reaction force given the inverse time step. /// Get the reaction force given the inverse time step.
/// Unit is N. /// Unit is N.
b2Vec2 GetReactionForce(float32 inv_dt) const; b2Vec2 GetReactionForce(float32 inv_dt) const;
/// Get the reaction torque due to the joint limit given the inverse /// Get the reaction torque due to the joint limit given the inverse ti
time step. me step.
/// Unit is N*m. /// Unit is N*m.
float32 GetReactionTorque(float32 inv_dt) const; float32 GetReactionTorque(float32 inv_dt) const;
/// Get the current motor torque given the inverse time step. /// Get the current motor torque given the inverse time step.
/// Unit is N*m. /// Unit is N*m.
float32 GetMotorTorque(float32 inv_dt) const; float32 GetMotorTorque(float32 inv_dt) const;
/// Dump to b2Log. /// Dump to b2Log.
void Dump(); void Dump();
protected: protected:
friend class b2Joint; friend class b2Joint;
friend class b2GearJoint; friend class b2GearJoint;
b2RevoluteJoint(const b2RevoluteJointDef* def); b2RevoluteJoint(const b2RevoluteJointDef* def);
void InitVelocityConstraints(const b2SolverData& data); void InitVelocityConstraints(const b2SolverData& data);
void SolveVelocityConstraints(const b2SolverData& data); void SolveVelocityConstraints(const b2SolverData& data);
bool SolvePositionConstraints(const b2SolverData& data); bool SolvePositionConstraints(const b2SolverData& data);
// Solver shared // Solver shared
b2Vec2 m_localAnchorA; b2Vec2 m_localAnchorA;
b2Vec2 m_localAnchorB; b2Vec2 m_localAnchorB;
b2Vec3 m_impulse; b2Vec3 m_impulse;
float32 m_motorImpulse; float32 m_motorImpulse;
bool m_enableMotor; bool m_enableMotor;
float32 m_maxMotorTorque; float32 m_maxMotorTorque;
float32 m_motorSpeed; float32 m_motorSpeed;
bool m_enableLimit; bool m_enableLimit;
float32 m_referenceAngle; float32 m_referenceAngle;
float32 m_lowerAngle; float32 m_lowerAngle;
float32 m_upperAngle; float32 m_upperAngle;
// Solver temp // Solver temp
int32 m_indexA; int32 m_indexA;
int32 m_indexB; int32 m_indexB;
b2Vec2 m_rA; b2Vec2 m_rA;
b2Vec2 m_rB; b2Vec2 m_rB;
b2Vec2 m_localCenterA; b2Vec2 m_localCenterA;
b2Vec2 m_localCenterB; b2Vec2 m_localCenterB;
float32 m_invMassA; float32 m_invMassA;
float32 m_invMassB; float32 m_invMassB;
float32 m_invIA; float32 m_invIA;
float32 m_invIB; float32 m_invIB;
b2Mat33 m_mass; // effective mass for point-to-point b2Mat33 m_mass; // effective mass for point-to-point constra
constraint. int.
float32 m_motorMass; // effective mass for motor/limit angular co float32 m_motorMass; // effective mass for motor/limit angular const
nstraint. raint.
b2LimitState m_limitState; b2LimitState m_limitState;
}; };
inline float32 b2RevoluteJoint::GetMotorSpeed() const inline float32 b2RevoluteJoint::GetMotorSpeed() const
{ {
return m_motorSpeed; return m_motorSpeed;
} }
#endif #endif
 End of changes. 25 change blocks. 
132 lines changed or deleted 129 lines changed or added


 b2Rope.h   b2Rope.h 
skipping to change at line 29 skipping to change at line 29
#ifndef B2_ROPE_H #ifndef B2_ROPE_H
#define B2_ROPE_H #define B2_ROPE_H
#include <Box2D/Common/b2Math.h> #include <Box2D/Common/b2Math.h>
class b2Draw; class b2Draw;
/// ///
struct b2RopeDef struct b2RopeDef
{ {
b2RopeDef() b2RopeDef()
{ {
vertices = NULL; vertices = NULL;
count = 0; count = 0;
masses = NULL; masses = NULL;
gravity.SetZero(); gravity.SetZero();
damping = 0.1f; damping = 0.1f;
k2 = 0.9f; k2 = 0.9f;
k3 = 0.1f; k3 = 0.1f;
} }
/// ///
b2Vec2* vertices; b2Vec2* vertices;
/// ///
int32 count; int32 count;
/// ///
float32* masses; float32* masses;
/// ///
b2Vec2 gravity; b2Vec2 gravity;
/// ///
float32 damping; float32 damping;
/// Stretching stiffness /// Stretching stiffness
float32 k2; float32 k2;
/// Bending stiffness. Values above 0.5 can make the simulation blow /// Bending stiffness. Values above 0.5 can make the simulation blow up
up. .
float32 k3; float32 k3;
}; };
/// ///
class b2Rope class b2Rope
{ {
public: public:
b2Rope(); b2Rope();
~b2Rope(); ~b2Rope();
/// ///
void Initialize(const b2RopeDef* def); void Initialize(const b2RopeDef* def);
/// ///
void Step(float32 timeStep, int32 iterations); void Step(float32 timeStep, int32 iterations);
/// ///
int32 GetVertexCount() const int32 GetVertexCount() const
{ {
return m_count; return m_count;
} }
/// ///
const b2Vec2* GetVertices() const const b2Vec2* GetVertices() const
{ {
return m_ps; return m_ps;
} }
/// ///
void Draw(b2Draw* draw) const; void Draw(b2Draw* draw) const;
/// ///
void SetAngle(float32 angle); void SetAngle(float32 angle);
private: private:
void SolveC2(); void SolveC2();
void SolveC3(); void SolveC3();
int32 m_count; int32 m_count;
b2Vec2* m_ps; b2Vec2* m_ps;
b2Vec2* m_p0s; b2Vec2* m_p0s;
b2Vec2* m_vs; b2Vec2* m_vs;
float32* m_ims; float32* m_ims;
float32* m_Ls; float32* m_Ls;
float32* m_as; float32* m_as;
b2Vec2 m_gravity; b2Vec2 m_gravity;
float32 m_damping; float32 m_damping;
float32 m_k2; float32 m_k2;
float32 m_k3; float32 m_k3;
}; };
#endif #endif
 End of changes. 16 change blocks. 
63 lines changed or deleted 63 lines changed or added


 b2RopeJoint.h   b2RopeJoint.h 
skipping to change at line 30 skipping to change at line 30
#define B2_ROPE_JOINT_H #define B2_ROPE_JOINT_H
#include <Box2D/Dynamics/Joints/b2Joint.h> #include <Box2D/Dynamics/Joints/b2Joint.h>
/// Rope joint definition. This requires two body anchor points and /// Rope joint definition. This requires two body anchor points and
/// a maximum lengths. /// a maximum lengths.
/// Note: by default the connected objects will not collide. /// Note: by default the connected objects will not collide.
/// see collideConnected in b2JointDef. /// see collideConnected in b2JointDef.
struct b2RopeJointDef : public b2JointDef struct b2RopeJointDef : public b2JointDef
{ {
b2RopeJointDef() b2RopeJointDef()
{ {
type = e_ropeJoint; type = e_ropeJoint;
localAnchorA.Set(-1.0f, 0.0f); localAnchorA.Set(-1.0f, 0.0f);
localAnchorB.Set(1.0f, 0.0f); localAnchorB.Set(1.0f, 0.0f);
maxLength = 0.0f; maxLength = 0.0f;
} }
/// The local anchor point relative to bodyA's origin. /// The local anchor point relative to bodyA's origin.
b2Vec2 localAnchorA; b2Vec2 localAnchorA;
/// The local anchor point relative to bodyB's origin. /// The local anchor point relative to bodyB's origin.
b2Vec2 localAnchorB; b2Vec2 localAnchorB;
/// The maximum length of the rope. /// The maximum length of the rope.
/// Warning: this must be larger than b2_linearSlop or /// Warning: this must be larger than b2_linearSlop or
/// the joint will have no effect. /// the joint will have no effect.
float32 maxLength; float32 maxLength;
}; };
/// A rope joint enforces a maximum distance between two points /// A rope joint enforces a maximum distance between two points
/// on two bodies. It has no other effect. /// on two bodies. It has no other effect.
/// Warning: if you attempt to change the maximum length during /// Warning: if you attempt to change the maximum length during
/// the simulation you will get some non-physical behavior. /// the simulation you will get some non-physical behavior.
/// A model that would allow you to dynamically modify the length /// A model that would allow you to dynamically modify the length
/// would have some sponginess, so I chose not to implement it /// would have some sponginess, so I chose not to implement it
/// that way. See b2DistanceJoint if you want to dynamically /// that way. See b2DistanceJoint if you want to dynamically
/// control length. /// control length.
class b2RopeJoint : public b2Joint class b2RopeJoint : public b2Joint
{ {
public: public:
b2Vec2 GetAnchorA() const; b2Vec2 GetAnchorA() const;
b2Vec2 GetAnchorB() const; b2Vec2 GetAnchorB() const;
b2Vec2 GetReactionForce(float32 inv_dt) const; b2Vec2 GetReactionForce(float32 inv_dt) const;
float32 GetReactionTorque(float32 inv_dt) const; float32 GetReactionTorque(float32 inv_dt) const;
/// The local anchor point relative to bodyA's origin. /// The local anchor point relative to bodyA's origin.
const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; }
/// The local anchor point relative to bodyB's origin. /// The local anchor point relative to bodyB's origin.
const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; }
/// Set/Get the maximum length of the rope. /// Set/Get the maximum length of the rope.
void SetMaxLength(float32 length) { m_maxLength = length; } void SetMaxLength(float32 length) { m_maxLength = length; }
float32 GetMaxLength() const; float32 GetMaxLength() const;
b2LimitState GetLimitState() const; b2LimitState GetLimitState() const;
/// Dump joint to dmLog /// Dump joint to dmLog
void Dump(); void Dump();
protected: protected:
friend class b2Joint; friend class b2Joint;
b2RopeJoint(const b2RopeJointDef* data); b2RopeJoint(const b2RopeJointDef* data);
void InitVelocityConstraints(const b2SolverData& data); void InitVelocityConstraints(const b2SolverData& data);
void SolveVelocityConstraints(const b2SolverData& data); void SolveVelocityConstraints(const b2SolverData& data);
bool SolvePositionConstraints(const b2SolverData& data); bool SolvePositionConstraints(const b2SolverData& data);
// Solver shared // Solver shared
b2Vec2 m_localAnchorA; b2Vec2 m_localAnchorA;
b2Vec2 m_localAnchorB; b2Vec2 m_localAnchorB;
float32 m_maxLength; float32 m_maxLength;
float32 m_length; float32 m_length;
float32 m_impulse; float32 m_impulse;
// Solver temp // Solver temp
int32 m_indexA; int32 m_indexA;
int32 m_indexB; int32 m_indexB;
b2Vec2 m_u; b2Vec2 m_u;
b2Vec2 m_rA; b2Vec2 m_rA;
b2Vec2 m_rB; b2Vec2 m_rB;
b2Vec2 m_localCenterA; b2Vec2 m_localCenterA;
b2Vec2 m_localCenterB; b2Vec2 m_localCenterB;
float32 m_invMassA; float32 m_invMassA;
float32 m_invMassB; float32 m_invMassB;
float32 m_invIA; float32 m_invIA;
float32 m_invIB; float32 m_invIB;
float32 m_mass; float32 m_mass;
b2LimitState m_state; b2LimitState m_state;
}; };
#endif #endif
 End of changes. 10 change blocks. 
59 lines changed or deleted 59 lines changed or added


 b2Settings.h   b2Settings.h 
skipping to change at line 28 skipping to change at line 28
#ifndef B2_SETTINGS_H #ifndef B2_SETTINGS_H
#define B2_SETTINGS_H #define B2_SETTINGS_H
#include <cassert> #include <cassert>
#include <cmath> #include <cmath>
#define B2_NOT_USED(x) ((void)(x)) #define B2_NOT_USED(x) ((void)(x))
#define b2Assert(A) assert(A) #define b2Assert(A) assert(A)
typedef signed char int8; typedef signed char int8;
typedef signed short int16; typedef signed short int16;
typedef signed int int32; typedef signed int int32;
typedef unsigned char uint8; typedef unsigned char uint8;
typedef unsigned short uint16; typedef unsigned short uint16;
typedef unsigned int uint32; typedef unsigned int uint32;
typedef float float32; typedef float float32;
typedef double float64; typedef double float64;
#define b2_maxFloat FLT_MAX #define b2_maxFloat FLT_MAX
#define b2_epsilon FLT_EPSILON #define b2_epsilon FLT_EPSILON
#define b2_pi 3.14159265359f #define b2_pi 3.14159265359f
/// @file /// @file
/// Global tuning constants based on meters-kilograms-seconds (MKS) units. /// Global tuning constants based on meters-kilograms-seconds (MKS) units.
/// ///
// Collision // Collision
/// The maximum number of contact points between two convex shapes. Do /// The maximum number of contact points between two convex shapes. Do
/// not change this value. /// not change this value.
#define b2_maxManifoldPoints 2 #define b2_maxManifoldPoints 2
/// The maximum number of vertices on a convex polygon. You cannot increase /// The maximum number of vertices on a convex polygon. You cannot increase
/// this too much because b2BlockAllocator has a maximum object size. /// this too much because b2BlockAllocator has a maximum object size.
#define b2_maxPolygonVertices 8 #define b2_maxPolygonVertices 8
/// This is used to fatten AABBs in the dynamic tree. This allows proxies /// This is used to fatten AABBs in the dynamic tree. This allows proxies
/// to move by a small amount without triggering a tree adjustment. /// to move by a small amount without triggering a tree adjustment.
/// This is in meters. /// This is in meters.
#define b2_aabbExtension 0.1f #define b2_aabbExtension 0.1f
/// This is used to fatten AABBs in the dynamic tree. This is used to predi ct /// This is used to fatten AABBs in the dynamic tree. This is used to predi ct
/// the future position based on the current displacement. /// the future position based on the current displacement.
/// This is a dimensionless multiplier. /// This is a dimensionless multiplier.
#define b2_aabbMultiplier 2.0f #define b2_aabbMultiplier 2.0f
/// A small length used as a collision and constraint tolerance. Usually it is /// A small length used as a collision and constraint tolerance. Usually it is
/// chosen to be numerically significant, but visually insignificant. /// chosen to be numerically significant, but visually insignificant.
#define b2_linearSlop 0.005f #define b2_linearSlop 0.005f
/// A small angle used as a collision and constraint tolerance. Usually it is /// A small angle used as a collision and constraint tolerance. Usually it is
/// chosen to be numerically significant, but visually insignificant. /// chosen to be numerically significant, but visually insignificant.
#define b2_angularSlop (2.0f / 180.0f * b2_pi) #define b2_angularSlop (2.0f / 180.0f * b2_pi)
/// The radius of the polygon/edge shape skin. This should not be modified. Making /// The radius of the polygon/edge shape skin. This should not be modified. Making
/// this smaller means polygons will have an insufficient buffer for contin uous collision. /// this smaller means polygons will have an insufficient buffer for contin uous collision.
/// Making it larger may create artifacts for vertex collision. /// Making it larger may create artifacts for vertex collision.
#define b2_polygonRadius (2.0f * b2_linearSlop) #define b2_polygonRadius (2.0f * b2_linearSlop)
/// Maximum number of sub-steps per contact in continuous physics simulatio n. /// Maximum number of sub-steps per contact in continuous physics simulatio n.
#define b2_maxSubSteps 8 #define b2_maxSubSteps 8
// Dynamics // Dynamics
/// Maximum number of contacts to be handled to solve a TOI impact. /// Maximum number of contacts to be handled to solve a TOI impact.
#define b2_maxTOIContacts 32 #define b2_maxTOIContacts 32
/// A velocity threshold for elastic collisions. Any collision with a relat ive linear /// A velocity threshold for elastic collisions. Any collision with a relat ive linear
/// velocity below this threshold will be treated as inelastic. /// velocity below this threshold will be treated as inelastic.
#define b2_velocityThreshold 1.0f #define b2_velocityThreshold 1.0f
/// The maximum linear position correction used when solving constraints. T his helps to /// The maximum linear position correction used when solving constraints. T his helps to
/// prevent overshoot. /// prevent overshoot.
#define b2_maxLinearCorrection 0.2f #define b2_maxLinearCorrection 0.2f
/// The maximum angular position correction used when solving constraints. This helps to /// The maximum angular position correction used when solving constraints. This helps to
/// prevent overshoot. /// prevent overshoot.
#define b2_maxAngularCorrection (8.0f / 180.0f * b2_pi) #define b2_maxAngularCorrection (8.0f / 180.0f * b2_pi)
/// The maximum linear velocity of a body. This limit is very large and is used /// The maximum linear velocity of a body. This limit is very large and is used
/// to prevent numerical problems. You shouldn't need to adjust this. /// to prevent numerical problems. You shouldn't need to adjust this.
#define b2_maxTranslation 2.0f #define b2_maxTranslation 2.0f
#define b2_maxTranslationSquared (b2_maxTranslation * b2_maxTranslati #define b2_maxTranslationSquared (b2_maxTranslation * b2_maxTranslation)
on)
/// The maximum angular velocity of a body. This limit is very large and is used /// The maximum angular velocity of a body. This limit is very large and is used
/// to prevent numerical problems. You shouldn't need to adjust this. /// to prevent numerical problems. You shouldn't need to adjust this.
#define b2_maxRotation (0.5f * b2_pi) #define b2_maxRotation (0.5f * b2_pi)
#define b2_maxRotationSquared (b2_maxRotation * b2_maxRotation) #define b2_maxRotationSquared (b2_maxRotation * b2_maxRotation)
/// This scale factor controls how fast overlap is resolved. Ideally this w ould be 1 so /// This scale factor controls how fast overlap is resolved. Ideally this w ould be 1 so
/// that overlap is removed in one time step. However using values close to 1 often lead /// that overlap is removed in one time step. However using values close to 1 often lead
/// to overshoot. /// to overshoot.
#define b2_baumgarte 0.2f #define b2_baumgarte 0.2f
#define b2_toiBaugarte 0.75f #define b2_toiBaugarte 0.75f
// Sleep // Sleep
/// The time that a body must be still before it will go to sleep. /// The time that a body must be still before it will go to sleep.
#define b2_timeToSleep 0.5f #define b2_timeToSleep 0.5f
/// A body cannot sleep if its linear velocity is above this tolerance. /// A body cannot sleep if its linear velocity is above this tolerance.
#define b2_linearSleepTolerance 0.01f #define b2_linearSleepTolerance 0.01f
/// A body cannot sleep if its angular velocity is above this tolerance. /// A body cannot sleep if its angular velocity is above this tolerance.
#define b2_angularSleepTolerance (2.0f / 180.0f * b2_pi) #define b2_angularSleepTolerance (2.0f / 180.0f * b2_pi)
// Memory Allocation // Memory Allocation
/// Implement this function to use your own memory allocator. /// Implement this function to use your own memory allocator.
void* b2Alloc(int32 size); void* b2Alloc(int32 size);
/// If you implement b2Alloc, you should also implement this function. /// If you implement b2Alloc, you should also implement this function.
void b2Free(void* mem); void b2Free(void* mem);
/// Logging function. /// Logging function.
void b2Log(const char* string, ...); void b2Log(const char* string, ...);
/// Version numbering scheme. /// Version numbering scheme.
/// See http://en.wikipedia.org/wiki/Software_versioning /// See http://en.wikipedia.org/wiki/Software_versioning
struct b2Version struct b2Version
{ {
int32 major; ///< significant changes int32 major; ///< significant changes
int32 minor; ///< incremental changes int32 minor; ///< incremental changes
int32 revision; ///< bug fixes int32 revision; ///< bug fixes
}; };
/// Current version. /// Current version.
extern b2Version b2_version; extern b2Version b2_version;
#endif #endif
 End of changes. 21 change blocks. 
29 lines changed or deleted 28 lines changed or added


 b2Shape.h   b2Shape.h 
skipping to change at line 29 skipping to change at line 29
#ifndef B2_SHAPE_H #ifndef B2_SHAPE_H
#define B2_SHAPE_H #define B2_SHAPE_H
#include <Box2D/Common/b2BlockAllocator.h> #include <Box2D/Common/b2BlockAllocator.h>
#include <Box2D/Common/b2Math.h> #include <Box2D/Common/b2Math.h>
#include <Box2D/Collision/b2Collision.h> #include <Box2D/Collision/b2Collision.h>
/// This holds the mass data computed for a shape. /// This holds the mass data computed for a shape.
struct b2MassData struct b2MassData
{ {
/// The mass of the shape, usually in kilograms. /// The mass of the shape, usually in kilograms.
float32 mass; float32 mass;
/// The position of the shape's centroid relative to the shape's ori /// The position of the shape's centroid relative to the shape's origin
gin. .
b2Vec2 center; b2Vec2 center;
/// The rotational inertia of the shape about the local origin. /// The rotational inertia of the shape about the local origin.
float32 I; float32 I;
}; };
/// A shape is used for collision detection. You can create a shape however you like. /// A shape is used for collision detection. You can create a shape however you like.
/// Shapes used for simulation in b2World are created automatically when a b2Fixture /// Shapes used for simulation in b2World are created automatically when a b2Fixture
/// is created. Shapes may encapsulate a one or more child shapes. /// is created. Shapes may encapsulate a one or more child shapes.
class b2Shape class b2Shape
{ {
public: public:
enum Type enum Type
{ {
e_circle = 0, e_circle = 0,
e_edge = 1, e_edge = 1,
e_polygon = 2, e_polygon = 2,
e_chain = 3, e_chain = 3,
e_typeCount = 4 e_typeCount = 4
}; };
virtual ~b2Shape() {} virtual ~b2Shape() {}
/// Clone the concrete shape using the provided allocator. /// Clone the concrete shape using the provided allocator.
virtual b2Shape* Clone(b2BlockAllocator* allocator) const = 0; virtual b2Shape* Clone(b2BlockAllocator* allocator) const = 0;
/// Get the type of this shape. You can use this to down cast to the /// Get the type of this shape. You can use this to down cast to the co
concrete shape. ncrete shape.
/// @return the shape type. /// @return the shape type.
Type GetType() const; Type GetType() const;
/// Get the number of child primitives. /// Get the number of child primitives.
virtual int32 GetChildCount() const = 0; virtual int32 GetChildCount() const = 0;
/// Test a point for containment in this shape. This only works for /// Test a point for containment in this shape. This only works for con
convex shapes. vex shapes.
/// @param xf the shape world transform. /// @param xf the shape world transform.
/// @param p a point in world coordinates. /// @param p a point in world coordinates.
virtual bool TestPoint(const b2Transform& xf, const b2Vec2& p) const virtual bool TestPoint(const b2Transform& xf, const b2Vec2& p) const =
= 0; 0;
/// Cast a ray against a child shape. /// Cast a ray against a child shape.
/// @param output the ray-cast results. /// @param output the ray-cast results.
/// @param input the ray-cast input parameters. /// @param input the ray-cast input parameters.
/// @param transform the transform to be applied to the shape. /// @param transform the transform to be applied to the shape.
/// @param childIndex the child shape index /// @param childIndex the child shape index
virtual bool RayCast(b2RayCastOutput* output, const b2RayCastInput& virtual bool RayCast(b2RayCastOutput* output, const b2RayCastInput& inp
input, ut,
const b2Transform& transform const b2Transform& transform, int32 childIndex) con
, int32 childIndex) const = 0; st = 0;
/// Given a transform, compute the associated axis aligned bounding /// Given a transform, compute the associated axis aligned bounding box
box for a child shape. for a child shape.
/// @param aabb returns the axis aligned box. /// @param aabb returns the axis aligned box.
/// @param xf the world transform of the shape. /// @param xf the world transform of the shape.
/// @param childIndex the child shape /// @param childIndex the child shape
virtual void ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 virtual void ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 chi
childIndex) const = 0; ldIndex) const = 0;
/// Compute the mass properties of this shape using its dimensions a /// Compute the mass properties of this shape using its dimensions and
nd density. density.
/// The inertia tensor is computed about the local origin. /// The inertia tensor is computed about the local origin.
/// @param massData returns the mass data for this shape. /// @param massData returns the mass data for this shape.
/// @param density the density in kilograms per meter squared. /// @param density the density in kilograms per meter squared.
virtual void ComputeMass(b2MassData* massData, float32 density) cons virtual void ComputeMass(b2MassData* massData, float32 density) const =
t = 0; 0;
Type m_type; Type m_type;
float32 m_radius; float32 m_radius;
}; };
inline b2Shape::Type b2Shape::GetType() const inline b2Shape::Type b2Shape::GetType() const
{ {
return m_type; return m_type;
} }
#endif #endif
 End of changes. 6 change blocks. 
64 lines changed or deleted 64 lines changed or added


 b2StackAllocator.h   b2StackAllocator.h 
skipping to change at line 24 skipping to change at line 24
* 2. Altered source versions must be plainly marked as such, and must not b e * 2. Altered source versions must be plainly marked as such, and must not b e
* misrepresented as being the original software. * misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution . * 3. This notice may not be removed or altered from any source distribution .
*/ */
#ifndef B2_STACK_ALLOCATOR_H #ifndef B2_STACK_ALLOCATOR_H
#define B2_STACK_ALLOCATOR_H #define B2_STACK_ALLOCATOR_H
#include <Box2D/Common/b2Settings.h> #include <Box2D/Common/b2Settings.h>
const int32 b2_stackSize = 100 * 1024; // 100k const int32 b2_stackSize = 100 * 1024; // 100k
const int32 b2_maxStackEntries = 32; const int32 b2_maxStackEntries = 32;
struct b2StackEntry struct b2StackEntry
{ {
char* data; char* data;
int32 size; int32 size;
bool usedMalloc; bool usedMalloc;
}; };
// This is a stack allocator used for fast per step allocations. // This is a stack allocator used for fast per step allocations.
// You must nest allocate/free pairs. The code will assert // You must nest allocate/free pairs. The code will assert
// if you try to interleave multiple allocate/free pairs. // if you try to interleave multiple allocate/free pairs.
class b2StackAllocator class b2StackAllocator
{ {
public: public:
b2StackAllocator(); b2StackAllocator();
~b2StackAllocator(); ~b2StackAllocator();
void* Allocate(int32 size); void* Allocate(int32 size);
void Free(void* p); void Free(void* p);
int32 GetMaxAllocation() const; int32 GetMaxAllocation() const;
private: private:
char m_data[b2_stackSize]; char m_data[b2_stackSize];
int32 m_index; int32 m_index;
int32 m_allocation; int32 m_allocation;
int32 m_maxAllocation; int32 m_maxAllocation;
b2StackEntry m_entries[b2_maxStackEntries]; b2StackEntry m_entries[b2_maxStackEntries];
int32 m_entryCount; int32 m_entryCount;
}; };
#endif #endif
 End of changes. 8 change blocks. 
15 lines changed or deleted 15 lines changed or added


 b2TimeOfImpact.h   b2TimeOfImpact.h 
skipping to change at line 28 skipping to change at line 28
#ifndef B2_TIME_OF_IMPACT_H #ifndef B2_TIME_OF_IMPACT_H
#define B2_TIME_OF_IMPACT_H #define B2_TIME_OF_IMPACT_H
#include <Box2D/Common/b2Math.h> #include <Box2D/Common/b2Math.h>
#include <Box2D/Collision/b2Distance.h> #include <Box2D/Collision/b2Distance.h>
/// Input parameters for b2TimeOfImpact /// Input parameters for b2TimeOfImpact
struct b2TOIInput struct b2TOIInput
{ {
b2DistanceProxy proxyA; b2DistanceProxy proxyA;
b2DistanceProxy proxyB; b2DistanceProxy proxyB;
b2Sweep sweepA; b2Sweep sweepA;
b2Sweep sweepB; b2Sweep sweepB;
float32 tMax; // defines sweep interval [0, tMax] float32 tMax; // defines sweep interval [0, tMax]
}; };
// Output parameters for b2TimeOfImpact. // Output parameters for b2TimeOfImpact.
struct b2TOIOutput struct b2TOIOutput
{ {
enum State enum State
{ {
e_unknown, e_unknown,
e_failed, e_failed,
e_overlapped, e_overlapped,
e_touching, e_touching,
e_separated e_separated
}; };
State state; State state;
float32 t; float32 t;
}; };
/// Compute the upper bound on time before two shapes penetrate. Time is re presented as /// Compute the upper bound on time before two shapes penetrate. Time is re presented as
/// a fraction between [0,tMax]. This uses a swept separating axis and may miss some intermediate, /// a fraction between [0,tMax]. This uses a swept separating axis and may miss some intermediate,
/// non-tunneling collision. If you change the time interval, you should ca ll this function /// non-tunneling collision. If you change the time interval, you should ca ll this function
/// again. /// again.
/// Note: use b2Distance to compute the contact point and normal at the tim e of impact. /// Note: use b2Distance to compute the contact point and normal at the tim e of impact.
void b2TimeOfImpact(b2TOIOutput* output, const b2TOIInput* input); void b2TimeOfImpact(b2TOIOutput* output, const b2TOIInput* input);
#endif #endif
 End of changes. 3 change blocks. 
15 lines changed or deleted 15 lines changed or added


 b2TimeStep.h   b2TimeStep.h 
skipping to change at line 27 skipping to change at line 27
*/ */
#ifndef B2_TIME_STEP_H #ifndef B2_TIME_STEP_H
#define B2_TIME_STEP_H #define B2_TIME_STEP_H
#include <Box2D/Common/b2Math.h> #include <Box2D/Common/b2Math.h>
/// Profiling data. Times are in milliseconds. /// Profiling data. Times are in milliseconds.
struct b2Profile struct b2Profile
{ {
float32 step; float32 step;
float32 collide; float32 collide;
float32 solve; float32 solve;
float32 solveInit; float32 solveInit;
float32 solveVelocity; float32 solveVelocity;
float32 solvePosition; float32 solvePosition;
float32 broadphase; float32 broadphase;
float32 solveTOI; float32 solveTOI;
}; };
/// This is an internal structure. /// This is an internal structure.
struct b2TimeStep struct b2TimeStep
{ {
float32 dt; // time step float32 dt; // time step
float32 inv_dt; // inverse time step (0 if dt == 0). float32 inv_dt; // inverse time step (0 if dt == 0).
float32 dtRatio; // dt * inv_dt0 float32 dtRatio; // dt * inv_dt0
int32 velocityIterations; int32 velocityIterations;
int32 positionIterations; int32 positionIterations;
bool warmStarting; bool warmStarting;
}; };
/// This is an internal structure. /// This is an internal structure.
struct b2Position struct b2Position
{ {
b2Vec2 c; b2Vec2 c;
float32 a; float32 a;
}; };
/// This is an internal structure. /// This is an internal structure.
struct b2Velocity struct b2Velocity
{ {
b2Vec2 v; b2Vec2 v;
float32 w; float32 w;
}; };
/// Solver Data /// Solver Data
struct b2SolverData struct b2SolverData
{ {
b2TimeStep step; b2TimeStep step;
b2Position* positions; b2Position* positions;
b2Velocity* velocities; b2Velocity* velocities;
}; };
#endif #endif
 End of changes. 5 change blocks. 
21 lines changed or deleted 21 lines changed or added


 b2Timer.h   b2Timer.h 
skipping to change at line 27 skipping to change at line 27
*/ */
#include <Box2D/Common/b2Settings.h> #include <Box2D/Common/b2Settings.h>
/// Timer for profiling. This has platform specific code and may /// Timer for profiling. This has platform specific code and may
/// not work on every platform. /// not work on every platform.
class b2Timer class b2Timer
{ {
public: public:
/// Constructor /// Constructor
b2Timer(); b2Timer();
/// Reset the timer. /// Reset the timer.
void Reset(); void Reset();
/// Get the time since construction or the last reset. /// Get the time since construction or the last reset.
float32 GetMilliseconds() const; float32 GetMilliseconds() const;
private: private:
#if defined(_WIN32) #if defined(_WIN32)
float64 m_start; float64 m_start;
static float64 s_invFrequency; static float64 s_invFrequency;
#elif defined(__linux__) || defined (__APPLE__) #elif defined(__linux__) || defined (__APPLE__)
unsigned long m_start_sec; unsigned long m_start_sec;
unsigned long m_start_msec; unsigned long m_start_msec;
#endif #endif
}; };
 End of changes. 5 change blocks. 
10 lines changed or deleted 10 lines changed or added


 b2WeldJoint.h   b2WeldJoint.h 
skipping to change at line 29 skipping to change at line 29
#ifndef B2_WELD_JOINT_H #ifndef B2_WELD_JOINT_H
#define B2_WELD_JOINT_H #define B2_WELD_JOINT_H
#include <Box2D/Dynamics/Joints/b2Joint.h> #include <Box2D/Dynamics/Joints/b2Joint.h>
/// Weld joint definition. You need to specify local anchor points /// Weld joint definition. You need to specify local anchor points
/// where they are attached and the relative body angle. The position /// where they are attached and the relative body angle. The position
/// of the anchor points is important for computing the reaction torque. /// of the anchor points is important for computing the reaction torque.
struct b2WeldJointDef : public b2JointDef struct b2WeldJointDef : public b2JointDef
{ {
b2WeldJointDef() b2WeldJointDef()
{ {
type = e_weldJoint; type = e_weldJoint;
localAnchorA.Set(0.0f, 0.0f); localAnchorA.Set(0.0f, 0.0f);
localAnchorB.Set(0.0f, 0.0f); localAnchorB.Set(0.0f, 0.0f);
referenceAngle = 0.0f; referenceAngle = 0.0f;
frequencyHz = 0.0f; frequencyHz = 0.0f;
dampingRatio = 0.0f; dampingRatio = 0.0f;
} }
/// Initialize the bodies, anchors, and reference angle using a worl /// Initialize the bodies, anchors, and reference angle using a world
d /// anchor point.
/// anchor point. void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor);
void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor);
/// The local anchor point relative to bodyA's origin.
/// The local anchor point relative to bodyA's origin. b2Vec2 localAnchorA;
b2Vec2 localAnchorA;
/// The local anchor point relative to bodyB's origin.
/// The local anchor point relative to bodyB's origin. b2Vec2 localAnchorB;
b2Vec2 localAnchorB;
/// The bodyB angle minus bodyA angle in the reference state (radians).
/// The bodyB angle minus bodyA angle in the reference state (radian float32 referenceAngle;
s).
float32 referenceAngle; /// The mass-spring-damper frequency in Hertz. Rotation only.
/// Disable softness with a value of 0.
/// The mass-spring-damper frequency in Hertz. Rotation only. float32 frequencyHz;
/// Disable softness with a value of 0.
float32 frequencyHz;
/// The damping ratio. 0 = no damping, 1 = critical damping. /// The damping ratio. 0 = no damping, 1 = critical damping.
float32 dampingRatio; float32 dampingRatio;
}; };
/// A weld joint essentially glues two bodies together. A weld joint may /// A weld joint essentially glues two bodies together. A weld joint may
/// distort somewhat because the island constraint solver is approximate. /// distort somewhat because the island constraint solver is approximate.
class b2WeldJoint : public b2Joint class b2WeldJoint : public b2Joint
{ {
public: public:
b2Vec2 GetAnchorA() const; b2Vec2 GetAnchorA() const;
b2Vec2 GetAnchorB() const; b2Vec2 GetAnchorB() const;
b2Vec2 GetReactionForce(float32 inv_dt) const; b2Vec2 GetReactionForce(float32 inv_dt) const;
float32 GetReactionTorque(float32 inv_dt) const; float32 GetReactionTorque(float32 inv_dt) const;
/// The local anchor point relative to bodyA's origin. /// The local anchor point relative to bodyA's origin.
const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; }
/// The local anchor point relative to bodyB's origin. /// The local anchor point relative to bodyB's origin.
const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; }
/// Get the reference angle. /// Get the reference angle.
float32 GetReferenceAngle() const { return m_referenceAngle; } float32 GetReferenceAngle() const { return m_referenceAngle; }
/// Set/get frequency in Hz. /// Set/get frequency in Hz.
void SetFrequency(float32 hz) { m_frequencyHz = hz; } void SetFrequency(float32 hz) { m_frequencyHz = hz; }
float32 GetFrequency() const { return m_frequencyHz; } float32 GetFrequency() const { return m_frequencyHz; }
/// Set/get damping ratio. /// Set/get damping ratio.
void SetDampingRatio(float32 ratio) { m_dampingRatio = ratio; } void SetDampingRatio(float32 ratio) { m_dampingRatio = ratio; }
float32 GetDampingRatio() const { return m_dampingRatio; } float32 GetDampingRatio() const { return m_dampingRatio; }
/// Dump to b2Log /// Dump to b2Log
void Dump(); void Dump();
protected: protected:
friend class b2Joint; friend class b2Joint;
b2WeldJoint(const b2WeldJointDef* def); b2WeldJoint(const b2WeldJointDef* def);
void InitVelocityConstraints(const b2SolverData& data); void InitVelocityConstraints(const b2SolverData& data);
void SolveVelocityConstraints(const b2SolverData& data); void SolveVelocityConstraints(const b2SolverData& data);
bool SolvePositionConstraints(const b2SolverData& data); bool SolvePositionConstraints(const b2SolverData& data);
float32 m_frequencyHz; float32 m_frequencyHz;
float32 m_dampingRatio; float32 m_dampingRatio;
float32 m_bias; float32 m_bias;
// Solver shared // Solver shared
b2Vec2 m_localAnchorA; b2Vec2 m_localAnchorA;
b2Vec2 m_localAnchorB; b2Vec2 m_localAnchorB;
float32 m_referenceAngle; float32 m_referenceAngle;
float32 m_gamma; float32 m_gamma;
b2Vec3 m_impulse; b2Vec3 m_impulse;
// Solver temp // Solver temp
int32 m_indexA; int32 m_indexA;
int32 m_indexB; int32 m_indexB;
b2Vec2 m_rA; b2Vec2 m_rA;
b2Vec2 m_rB; b2Vec2 m_rB;
b2Vec2 m_localCenterA; b2Vec2 m_localCenterA;
b2Vec2 m_localCenterB; b2Vec2 m_localCenterB;
float32 m_invMassA; float32 m_invMassA;
float32 m_invMassB; float32 m_invMassB;
float32 m_invIA; float32 m_invIA;
float32 m_invIB; float32 m_invIB;
b2Mat33 m_mass; b2Mat33 m_mass;
}; };
#endif #endif
 End of changes. 13 change blocks. 
77 lines changed or deleted 75 lines changed or added


 b2WheelJoint.h   b2WheelJoint.h 
skipping to change at line 32 skipping to change at line 32
#include <Box2D/Dynamics/Joints/b2Joint.h> #include <Box2D/Dynamics/Joints/b2Joint.h>
/// Wheel joint definition. This requires defining a line of /// Wheel joint definition. This requires defining a line of
/// motion using an axis and an anchor point. The definition uses local /// motion using an axis and an anchor point. The definition uses local
/// anchor points and a local axis so that the initial configuration /// anchor points and a local axis so that the initial configuration
/// can violate the constraint slightly. The joint translation is zero /// can violate the constraint slightly. The joint translation is zero
/// when the local anchor points coincide in world space. Using local /// when the local anchor points coincide in world space. Using local
/// anchors and a local axis helps when saving and loading a game. /// anchors and a local axis helps when saving and loading a game.
struct b2WheelJointDef : public b2JointDef struct b2WheelJointDef : public b2JointDef
{ {
b2WheelJointDef() b2WheelJointDef()
{ {
type = e_wheelJoint; type = e_wheelJoint;
localAnchorA.SetZero(); localAnchorA.SetZero();
localAnchorB.SetZero(); localAnchorB.SetZero();
localAxisA.Set(1.0f, 0.0f); localAxisA.Set(1.0f, 0.0f);
enableMotor = false; enableMotor = false;
maxMotorTorque = 0.0f; maxMotorTorque = 0.0f;
motorSpeed = 0.0f; motorSpeed = 0.0f;
frequencyHz = 2.0f; frequencyHz = 2.0f;
dampingRatio = 0.7f; dampingRatio = 0.7f;
} }
/// Initialize the bodies, anchors, axis, and reference angle using /// Initialize the bodies, anchors, axis, and reference angle using the
the world world
/// anchor and world axis. /// anchor and world axis.
void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor, void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor, con
const b2Vec2& axis); st b2Vec2& axis);
/// The local anchor point relative to bodyA's origin. /// The local anchor point relative to bodyA's origin.
b2Vec2 localAnchorA; b2Vec2 localAnchorA;
/// The local anchor point relative to bodyB's origin. /// The local anchor point relative to bodyB's origin.
b2Vec2 localAnchorB; b2Vec2 localAnchorB;
/// The local translation axis in bodyA. /// The local translation axis in bodyA.
b2Vec2 localAxisA; b2Vec2 localAxisA;
/// Enable/disable the joint motor. /// Enable/disable the joint motor.
bool enableMotor; bool enableMotor;
/// The maximum motor torque, usually in N-m. /// The maximum motor torque, usually in N-m.
float32 maxMotorTorque; float32 maxMotorTorque;
/// The desired motor speed in radians per second. /// The desired motor speed in radians per second.
float32 motorSpeed; float32 motorSpeed;
/// Suspension frequency, zero indicates no suspension /// Suspension frequency, zero indicates no suspension
float32 frequencyHz; float32 frequencyHz;
/// Suspension damping ratio, one indicates critical damping /// Suspension damping ratio, one indicates critical damping
float32 dampingRatio; float32 dampingRatio;
}; };
/// A wheel joint. This joint provides two degrees of freedom: translation /// A wheel joint. This joint provides two degrees of freedom: translation
/// along an axis fixed in bodyA and rotation in the plane. You can use a /// along an axis fixed in bodyA and rotation in the plane. You can use a
/// joint limit to restrict the range of motion and a joint motor to drive /// joint limit to restrict the range of motion and a joint motor to drive
/// the rotation or to model rotational friction. /// the rotation or to model rotational friction.
/// This joint is designed for vehicle suspensions. /// This joint is designed for vehicle suspensions.
class b2WheelJoint : public b2Joint class b2WheelJoint : public b2Joint
{ {
public: public:
void GetDefinition(b2WheelJointDef* def) const; void GetDefinition(b2WheelJointDef* def) const;
b2Vec2 GetAnchorA() const; b2Vec2 GetAnchorA() const;
b2Vec2 GetAnchorB() const; b2Vec2 GetAnchorB() const;
b2Vec2 GetReactionForce(float32 inv_dt) const; b2Vec2 GetReactionForce(float32 inv_dt) const;
float32 GetReactionTorque(float32 inv_dt) const; float32 GetReactionTorque(float32 inv_dt) const;
/// The local anchor point relative to bodyA's origin. /// The local anchor point relative to bodyA's origin.
const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; }
/// The local anchor point relative to bodyB's origin. /// The local anchor point relative to bodyB's origin.
const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; }
/// The local joint axis relative to bodyA. /// The local joint axis relative to bodyA.
const b2Vec2& GetLocalAxisA() const { return m_localXAxisA; } const b2Vec2& GetLocalAxisA() const { return m_localXAxisA; }
/// Get the current joint translation, usually in meters. /// Get the current joint translation, usually in meters.
float32 GetJointTranslation() const; float32 GetJointTranslation() const;
/// Get the current joint translation speed, usually in meters per s /// Get the current joint translation speed, usually in meters per seco
econd. nd.
float32 GetJointSpeed() const; float32 GetJointSpeed() const;
/// Is the joint motor enabled? /// Is the joint motor enabled?
bool IsMotorEnabled() const; bool IsMotorEnabled() const;
/// Enable/disable the joint motor. /// Enable/disable the joint motor.
void EnableMotor(bool flag); void EnableMotor(bool flag);
/// Set the motor speed, usually in radians per second. /// Set the motor speed, usually in radians per second.
void SetMotorSpeed(float32 speed); void SetMotorSpeed(float32 speed);
/// Get the motor speed, usually in radians per second. /// Get the motor speed, usually in radians per second.
float32 GetMotorSpeed() const; float32 GetMotorSpeed() const;
/// Set/Get the maximum motor force, usually in N-m. /// Set/Get the maximum motor force, usually in N-m.
void SetMaxMotorTorque(float32 torque); void SetMaxMotorTorque(float32 torque);
float32 GetMaxMotorTorque() const; float32 GetMaxMotorTorque() const;
/// Get the current motor torque given the inverse time step, usuall /// Get the current motor torque given the inverse time step, usually i
y in N-m. n N-m.
float32 GetMotorTorque(float32 inv_dt) const; float32 GetMotorTorque(float32 inv_dt) const;
/// Set/Get the spring frequency in hertz. Setting the frequency to /// Set/Get the spring frequency in hertz. Setting the frequency to zer
zero disables the spring. o disables the spring.
void SetSpringFrequencyHz(float32 hz); void SetSpringFrequencyHz(float32 hz);
float32 GetSpringFrequencyHz() const; float32 GetSpringFrequencyHz() const;
/// Set/Get the spring damping ratio /// Set/Get the spring damping ratio
void SetSpringDampingRatio(float32 ratio); void SetSpringDampingRatio(float32 ratio);
float32 GetSpringDampingRatio() const; float32 GetSpringDampingRatio() const;
/// Dump to b2Log /// Dump to b2Log
void Dump(); void Dump();
protected: protected:
friend class b2Joint; friend class b2Joint;
b2WheelJoint(const b2WheelJointDef* def); b2WheelJoint(const b2WheelJointDef* def);
void InitVelocityConstraints(const b2SolverData& data); void InitVelocityConstraints(const b2SolverData& data);
void SolveVelocityConstraints(const b2SolverData& data); void SolveVelocityConstraints(const b2SolverData& data);
bool SolvePositionConstraints(const b2SolverData& data); bool SolvePositionConstraints(const b2SolverData& data);
float32 m_frequencyHz; float32 m_frequencyHz;
float32 m_dampingRatio; float32 m_dampingRatio;
// Solver shared // Solver shared
b2Vec2 m_localAnchorA; b2Vec2 m_localAnchorA;
b2Vec2 m_localAnchorB; b2Vec2 m_localAnchorB;
b2Vec2 m_localXAxisA; b2Vec2 m_localXAxisA;
b2Vec2 m_localYAxisA; b2Vec2 m_localYAxisA;
float32 m_impulse; float32 m_impulse;
float32 m_motorImpulse; float32 m_motorImpulse;
float32 m_springImpulse; float32 m_springImpulse;
float32 m_maxMotorTorque; float32 m_maxMotorTorque;
float32 m_motorSpeed; float32 m_motorSpeed;
bool m_enableMotor; bool m_enableMotor;
// Solver temp // Solver temp
int32 m_indexA; int32 m_indexA;
int32 m_indexB; int32 m_indexB;
b2Vec2 m_localCenterA; b2Vec2 m_localCenterA;
b2Vec2 m_localCenterB; b2Vec2 m_localCenterB;
float32 m_invMassA; float32 m_invMassA;
float32 m_invMassB; float32 m_invMassB;
float32 m_invIA; float32 m_invIA;
float32 m_invIB; float32 m_invIB;
b2Vec2 m_ax, m_ay; b2Vec2 m_ax, m_ay;
float32 m_sAx, m_sBx; float32 m_sAx, m_sBx;
float32 m_sAy, m_sBy; float32 m_sAy, m_sBy;
float32 m_mass; float32 m_mass;
float32 m_motorMass; float32 m_motorMass;
float32 m_springMass; float32 m_springMass;
float32 m_bias; float32 m_bias;
float32 m_gamma; float32 m_gamma;
}; };
inline float32 b2WheelJoint::GetMotorSpeed() const inline float32 b2WheelJoint::GetMotorSpeed() const
{ {
return m_motorSpeed; return m_motorSpeed;
} }
inline float32 b2WheelJoint::GetMaxMotorTorque() const inline float32 b2WheelJoint::GetMaxMotorTorque() const
{ {
return m_maxMotorTorque; return m_maxMotorTorque;
} }
inline void b2WheelJoint::SetSpringFrequencyHz(float32 hz) inline void b2WheelJoint::SetSpringFrequencyHz(float32 hz)
{ {
m_frequencyHz = hz; m_frequencyHz = hz;
} }
inline float32 b2WheelJoint::GetSpringFrequencyHz() const inline float32 b2WheelJoint::GetSpringFrequencyHz() const
{ {
return m_frequencyHz; return m_frequencyHz;
} }
inline void b2WheelJoint::SetSpringDampingRatio(float32 ratio) inline void b2WheelJoint::SetSpringDampingRatio(float32 ratio)
{ {
m_dampingRatio = ratio; m_dampingRatio = ratio;
} }
inline float32 b2WheelJoint::GetSpringDampingRatio() const inline float32 b2WheelJoint::GetSpringDampingRatio() const
{ {
return m_dampingRatio; return m_dampingRatio;
} }
#endif #endif
 End of changes. 30 change blocks. 
126 lines changed or deleted 126 lines changed or added


 b2World.h   b2World.h 
skipping to change at line 44 skipping to change at line 44
class b2Draw; class b2Draw;
class b2Fixture; class b2Fixture;
class b2Joint; class b2Joint;
/// The world class manages all physics entities, dynamic simulation, /// The world class manages all physics entities, dynamic simulation,
/// and asynchronous queries. The world also contains efficient memory /// and asynchronous queries. The world also contains efficient memory
/// management facilities. /// management facilities.
class b2World class b2World
{ {
public: public:
/// Construct a world object. /// Construct a world object.
/// @param gravity the world gravity vector. /// @param gravity the world gravity vector.
b2World(const b2Vec2& gravity); b2World(const b2Vec2& gravity);
/// Destruct the world. All physics entities are destroyed and all h /// Destruct the world. All physics entities are destroyed and all heap
eap memory is released. memory is released.
~b2World(); ~b2World();
/// Register a destruction listener. The listener is owned by you an /// Register a destruction listener. The listener is owned by you and m
d must ust
/// remain in scope. /// remain in scope.
void SetDestructionListener(b2DestructionListener* listener); void SetDestructionListener(b2DestructionListener* listener);
/// Register a contact filter to provide specific control over colli /// Register a contact filter to provide specific control over collisio
sion. n.
/// Otherwise the default filter is used (b2_defaultFilter). The lis /// Otherwise the default filter is used (b2_defaultFilter). The listen
tener is er is
/// owned by you and must remain in scope. /// owned by you and must remain in scope.
void SetContactFilter(b2ContactFilter* filter); void SetContactFilter(b2ContactFilter* filter);
/// Register a contact event listener. The listener is owned by you /// Register a contact event listener. The listener is owned by you and
and must must
/// remain in scope. /// remain in scope.
void SetContactListener(b2ContactListener* listener); void SetContactListener(b2ContactListener* listener);
/// Register a routine for debug drawing. The debug draw functions a /// Register a routine for debug drawing. The debug draw functions are
re called called
/// inside with b2World::DrawDebugData method. The debug draw object /// inside with b2World::DrawDebugData method. The debug draw object is
is owned owned
/// by you and must remain in scope. /// by you and must remain in scope.
void SetDebugDraw(b2Draw* debugDraw); void SetDebugDraw(b2Draw* debugDraw);
/// Create a rigid body given a definition. No reference to the defi /// Create a rigid body given a definition. No reference to the definit
nition ion
/// is retained. /// is retained.
/// @warning This function is locked during callbacks. /// @warning This function is locked during callbacks.
b2Body* CreateBody(const b2BodyDef* def); b2Body* CreateBody(const b2BodyDef* def);
/// Destroy a rigid body given a definition. No reference to the def /// Destroy a rigid body given a definition. No reference to the defini
inition tion
/// is retained. This function is locked during callbacks. /// is retained. This function is locked during callbacks.
/// @warning This automatically deletes all associated shapes and jo /// @warning This automatically deletes all associated shapes and joint
ints. s.
/// @warning This function is locked during callbacks. /// @warning This function is locked during callbacks.
void DestroyBody(b2Body* body); void DestroyBody(b2Body* body);
/// Create a joint to constrain bodies together. No reference to the /// Create a joint to constrain bodies together. No reference to the de
definition finition
/// is retained. This may cause the connected bodies to cease collid /// is retained. This may cause the connected bodies to cease colliding
ing. .
/// @warning This function is locked during callbacks. /// @warning This function is locked during callbacks.
b2Joint* CreateJoint(const b2JointDef* def); b2Joint* CreateJoint(const b2JointDef* def);
/// Destroy a joint. This may cause the connected bodies to begin co /// Destroy a joint. This may cause the connected bodies to begin colli
lliding. ding.
/// @warning This function is locked during callbacks. /// @warning This function is locked during callbacks.
void DestroyJoint(b2Joint* joint); void DestroyJoint(b2Joint* joint);
/// Take a time step. This performs collision detection, integration /// Take a time step. This performs collision detection, integration,
, /// and constraint solution.
/// and constraint solution. /// @param timeStep the amount of time to simulate, this should not var
/// @param timeStep the amount of time to simulate, this should not y.
vary. /// @param velocityIterations for the velocity constraint solver.
/// @param velocityIterations for the velocity constraint solver. /// @param positionIterations for the position constraint solver.
/// @param positionIterations for the position constraint solver. void Step( float32 timeStep,
void Step( float32 timeStep, int32 velocityIterations,
int32 velocityIterations, int32 positionIterations);
int32 positionIterations);
/// Manually clear the force buffer on all bodies. By default, forces a
/// Manually clear the force buffer on all bodies. By default, force re cleared automatically
s are cleared automatically /// after each call to Step. The default behavior is modified by callin
/// after each call to Step. The default behavior is modified by cal g SetAutoClearForces.
ling SetAutoClearForces. /// The purpose of this function is to support sub-stepping. Sub-steppi
/// The purpose of this function is to support sub-stepping. Sub-ste ng is often used to maintain
pping is often used to maintain /// a fixed sized time step under a variable frame-rate.
/// a fixed sized time step under a variable frame-rate. /// When you perform sub-stepping you will disable auto clearing of for
/// When you perform sub-stepping you will disable auto clearing of ces and instead call
forces and instead call /// ClearForces after all sub-steps are complete in one pass of your ga
/// ClearForces after all sub-steps are complete in one pass of your me loop.
game loop. /// @see SetAutoClearForces
/// @see SetAutoClearForces void ClearForces();
void ClearForces();
/// Call this to draw shapes and other debug draw data.
/// Call this to draw shapes and other debug draw data. void DrawDebugData();
void DrawDebugData();
/// Query the world for all fixtures that potentially overlap the
/// Query the world for all fixtures that potentially overlap the /// provided AABB.
/// provided AABB. /// @param callback a user implemented callback class.
/// @param callback a user implemented callback class. /// @param aabb the query box.
/// @param aabb the query box. void QueryAABB(b2QueryCallback* callback, const b2AABB& aabb) const;
void QueryAABB(b2QueryCallback* callback, const b2AABB& aabb) const;
/// Ray-cast the world for all fixtures in the path of the ray. Your ca
/// Ray-cast the world for all fixtures in the path of the ray. Your llback
callback /// controls whether you get the closest point, any point, or n-points.
/// controls whether you get the closest point, any point, or n-poin /// The ray-cast ignores shapes that contain the starting point.
ts. /// @param callback a user implemented callback class.
/// The ray-cast ignores shapes that contain the starting point. /// @param point1 the ray starting point
/// @param callback a user implemented callback class. /// @param point2 the ray ending point
/// @param point1 the ray starting point void RayCast(b2RayCastCallback* callback, const b2Vec2& point1, const b
/// @param point2 the ray ending point 2Vec2& point2) const;
void RayCast(b2RayCastCallback* callback, const b2Vec2& point1, cons
t b2Vec2& point2) const; /// Get the world body list. With the returned body, use b2Body::GetNex
t to get
/// Get the world body list. With the returned body, use b2Body::Get /// the next body in the world list. A NULL body indicates the end of t
Next to get he list.
/// the next body in the world list. A NULL body indicates the end o /// @return the head of the world body list.
f the list. b2Body* GetBodyList();
/// @return the head of the world body list. const b2Body* GetBodyList() const;
b2Body* GetBodyList();
const b2Body* GetBodyList() const; /// Get the world joint list. With the returned joint, use b2Joint::Get
Next to get
/// Get the world joint list. With the returned joint, use b2Joint:: /// the next joint in the world list. A NULL joint indicates the end of
GetNext to get the list.
/// the next joint in the world list. A NULL joint indicates the end /// @return the head of the world joint list.
of the list. b2Joint* GetJointList();
/// @return the head of the world joint list. const b2Joint* GetJointList() const;
b2Joint* GetJointList();
const b2Joint* GetJointList() const; /// Get the world contact list. With the returned contact, use b2Contac
t::GetNext to get
/// Get the world contact list. With the returned contact, use b2Con /// the next contact in the world list. A NULL contact indicates the en
tact::GetNext to get d of the list.
/// the next contact in the world list. A NULL contact indicates the /// @return the head of the world contact list.
end of the list. /// @warning contacts are created and destroyed in the middle of a time
/// @return the head of the world contact list. step.
/// @warning contacts are created and destroyed in the middle of a t /// Use b2ContactListener to avoid missing contacts.
ime step. b2Contact* GetContactList();
/// Use b2ContactListener to avoid missing contacts. const b2Contact* GetContactList() const;
b2Contact* GetContactList();
const b2Contact* GetContactList() const; /// Enable/disable sleep.
void SetAllowSleeping(bool flag);
/// Enable/disable sleep. bool GetAllowSleeping() const { return m_allowSleep; }
void SetAllowSleeping(bool flag);
bool GetAllowSleeping() const { return m_allowSleep; } /// Enable/disable warm starting. For testing.
void SetWarmStarting(bool flag) { m_warmStarting = flag; }
/// Enable/disable warm starting. For testing. bool GetWarmStarting() const { return m_warmStarting; }
void SetWarmStarting(bool flag) { m_warmStarting = flag; }
bool GetWarmStarting() const { return m_warmStarting; } /// Enable/disable continuous physics. For testing.
void SetContinuousPhysics(bool flag) { m_continuousPhysics = flag; }
/// Enable/disable continuous physics. For testing. bool GetContinuousPhysics() const { return m_continuousPhysics; }
void SetContinuousPhysics(bool flag) { m_continuousPhysics = flag; }
bool GetContinuousPhysics() const { return m_continuousPhysics; } /// Enable/disable single stepped continuous physics. For testing.
void SetSubStepping(bool flag) { m_subStepping = flag; }
/// Enable/disable single stepped continuous physics. For testing. bool GetSubStepping() const { return m_subStepping; }
void SetSubStepping(bool flag) { m_subStepping = flag; }
bool GetSubStepping() const { return m_subStepping; } /// Get the number of broad-phase proxies.
int32 GetProxyCount() const;
/// Get the number of broad-phase proxies.
int32 GetProxyCount() const; /// Get the number of bodies.
int32 GetBodyCount() const;
/// Get the number of bodies.
int32 GetBodyCount() const; /// Get the number of joints.
int32 GetJointCount() const;
/// Get the number of joints.
int32 GetJointCount() const; /// Get the number of contacts (each may have 0 or more contact points)
.
/// Get the number of contacts (each may have 0 or more contact poin int32 GetContactCount() const;
ts).
int32 GetContactCount() const; /// Get the height of the dynamic tree.
int32 GetTreeHeight() const;
/// Get the height of the dynamic tree.
int32 GetTreeHeight() const; /// Get the balance of the dynamic tree.
int32 GetTreeBalance() const;
/// Get the balance of the dynamic tree.
int32 GetTreeBalance() const; /// Get the quality metric of the dynamic tree. The smaller the better.
/// The minimum is 1.
/// Get the quality metric of the dynamic tree. The smaller the bett float32 GetTreeQuality() const;
er.
/// The minimum is 1. /// Change the global gravity vector.
float32 GetTreeQuality() const; void SetGravity(const b2Vec2& gravity);
/// Change the global gravity vector. /// Get the global gravity vector.
void SetGravity(const b2Vec2& gravity); b2Vec2 GetGravity() const;
/// Get the global gravity vector. /// Is the world locked (in the middle of a time step).
b2Vec2 GetGravity() const; bool IsLocked() const;
/// Is the world locked (in the middle of a time step). /// Set flag to control automatic clearing of forces after each time st
bool IsLocked() const; ep.
void SetAutoClearForces(bool flag);
/// Set flag to control automatic clearing of forces after each time
step. /// Get the flag that controls automatic clearing of forces after each
void SetAutoClearForces(bool flag); time step.
bool GetAutoClearForces() const;
/// Get the flag that controls automatic clearing of forces after ea
ch time step. /// Get the contact manager for testing.
bool GetAutoClearForces() const; const b2ContactManager& GetContactManager() const;
/// Get the contact manager for testing. /// Get the current profile.
const b2ContactManager& GetContactManager() const; const b2Profile& GetProfile() const;
/// Get the current profile. /// Dump the world into the log file.
const b2Profile& GetProfile() const; /// @warning this should be called outside of a time step.
void Dump();
/// Dump the world into the log file.
/// @warning this should be called outside of a time step.
void Dump();
private: private:
// m_flags // m_flags
enum enum
{ {
e_newFixture = 0x0001, e_newFixture = 0x0001,
e_locked = 0x0002, e_locked = 0x0002,
e_clearForces = 0x0004 e_clearForces = 0x0004
}; };
friend class b2Body; friend class b2Body;
friend class b2Fixture; friend class b2Fixture;
friend class b2ContactManager; friend class b2ContactManager;
friend class b2Controller; friend class b2Controller;
void Solve(const b2TimeStep& step); void Solve(const b2TimeStep& step);
void SolveTOI(const b2TimeStep& step); void SolveTOI(const b2TimeStep& step);
void DrawJoint(b2Joint* joint); void DrawJoint(b2Joint* joint);
void DrawShape(b2Fixture* shape, const b2Transform& xf, const b2Colo void DrawShape(b2Fixture* shape, const b2Transform& xf, const b2Color&
r& color); color);
b2BlockAllocator m_blockAllocator; b2BlockAllocator m_blockAllocator;
b2StackAllocator m_stackAllocator; b2StackAllocator m_stackAllocator;
int32 m_flags; int32 m_flags;
b2ContactManager m_contactManager; b2ContactManager m_contactManager;
b2Body* m_bodyList; b2Body* m_bodyList;
b2Joint* m_jointList; b2Joint* m_jointList;
int32 m_bodyCount; int32 m_bodyCount;
int32 m_jointCount; int32 m_jointCount;
b2Vec2 m_gravity; b2Vec2 m_gravity;
bool m_allowSleep; bool m_allowSleep;
b2DestructionListener* m_destructionListener; b2DestructionListener* m_destructionListener;
b2Draw* m_debugDraw; b2Draw* m_debugDraw;
// This is used to compute the time step ratio to // This is used to compute the time step ratio to
// support a variable time step. // support a variable time step.
float32 m_inv_dt0; float32 m_inv_dt0;
// These are for debugging the solver. // These are for debugging the solver.
bool m_warmStarting; bool m_warmStarting;
bool m_continuousPhysics; bool m_continuousPhysics;
bool m_subStepping; bool m_subStepping;
bool m_stepComplete; bool m_stepComplete;
b2Profile m_profile; b2Profile m_profile;
}; };
inline b2Body* b2World::GetBodyList() inline b2Body* b2World::GetBodyList()
{ {
return m_bodyList; return m_bodyList;
} }
inline const b2Body* b2World::GetBodyList() const inline const b2Body* b2World::GetBodyList() const
{ {
return m_bodyList; return m_bodyList;
} }
inline b2Joint* b2World::GetJointList() inline b2Joint* b2World::GetJointList()
{ {
return m_jointList; return m_jointList;
} }
inline const b2Joint* b2World::GetJointList() const inline const b2Joint* b2World::GetJointList() const
{ {
return m_jointList; return m_jointList;
} }
inline b2Contact* b2World::GetContactList() inline b2Contact* b2World::GetContactList()
{ {
return m_contactManager.m_contactList; return m_contactManager.m_contactList;
} }
inline const b2Contact* b2World::GetContactList() const inline const b2Contact* b2World::GetContactList() const
{ {
return m_contactManager.m_contactList; return m_contactManager.m_contactList;
} }
inline int32 b2World::GetBodyCount() const inline int32 b2World::GetBodyCount() const
{ {
return m_bodyCount; return m_bodyCount;
} }
inline int32 b2World::GetJointCount() const inline int32 b2World::GetJointCount() const
{ {
return m_jointCount; return m_jointCount;
} }
inline int32 b2World::GetContactCount() const inline int32 b2World::GetContactCount() const
{ {
return m_contactManager.m_contactCount; return m_contactManager.m_contactCount;
} }
inline void b2World::SetGravity(const b2Vec2& gravity) inline void b2World::SetGravity(const b2Vec2& gravity)
{ {
m_gravity = gravity; m_gravity = gravity;
} }
inline b2Vec2 b2World::GetGravity() const inline b2Vec2 b2World::GetGravity() const
{ {
return m_gravity; return m_gravity;
} }
inline bool b2World::IsLocked() const inline bool b2World::IsLocked() const
{ {
return (m_flags & e_locked) == e_locked; return (m_flags & e_locked) == e_locked;
} }
inline void b2World::SetAutoClearForces(bool flag) inline void b2World::SetAutoClearForces(bool flag)
{ {
if (flag) if (flag)
{ {
m_flags |= e_clearForces; m_flags |= e_clearForces;
} }
else else
{ {
m_flags &= ~e_clearForces; m_flags &= ~e_clearForces;
} }
} }
/// Get the flag that controls automatic clearing of forces after each time step. /// Get the flag that controls automatic clearing of forces after each time step.
inline bool b2World::GetAutoClearForces() const inline bool b2World::GetAutoClearForces() const
{ {
return (m_flags & e_clearForces) == e_clearForces; return (m_flags & e_clearForces) == e_clearForces;
} }
inline const b2ContactManager& b2World::GetContactManager() const inline const b2ContactManager& b2World::GetContactManager() const
{ {
return m_contactManager; return m_contactManager;
} }
inline const b2Profile& b2World::GetProfile() const inline const b2Profile& b2World::GetProfile() const
{ {
return m_profile; return m_profile;
} }
#endif #endif
 End of changes. 32 change blocks. 
256 lines changed or deleted 253 lines changed or added


 b2WorldCallbacks.h   b2WorldCallbacks.h 
skipping to change at line 39 skipping to change at line 39
class b2Contact; class b2Contact;
struct b2ContactResult; struct b2ContactResult;
struct b2Manifold; struct b2Manifold;
/// Joints and fixtures are destroyed when their associated /// Joints and fixtures are destroyed when their associated
/// body is destroyed. Implement this listener so that you /// body is destroyed. Implement this listener so that you
/// may nullify references to these joints and shapes. /// may nullify references to these joints and shapes.
class b2DestructionListener class b2DestructionListener
{ {
public: public:
virtual ~b2DestructionListener() {} virtual ~b2DestructionListener() {}
/// Called when any joint is about to be destroyed due /// Called when any joint is about to be destroyed due
/// to the destruction of one of its attached bodies. /// to the destruction of one of its attached bodies.
virtual void SayGoodbye(b2Joint* joint) = 0; virtual void SayGoodbye(b2Joint* joint) = 0;
/// Called when any fixture is about to be destroyed due /// Called when any fixture is about to be destroyed due
/// to the destruction of its parent body. /// to the destruction of its parent body.
virtual void SayGoodbye(b2Fixture* fixture) = 0; virtual void SayGoodbye(b2Fixture* fixture) = 0;
}; };
/// Implement this class to provide collision filtering. In other words, yo u can implement /// Implement this class to provide collision filtering. In other words, yo u can implement
/// this class if you want finer control over contact creation. /// this class if you want finer control over contact creation.
class b2ContactFilter class b2ContactFilter
{ {
public: public:
virtual ~b2ContactFilter() {} virtual ~b2ContactFilter() {}
/// Return true if contact calculations should be performed between /// Return true if contact calculations should be performed between the
these two shapes. se two shapes.
/// @warning for performance reasons this is only called when the AA /// @warning for performance reasons this is only called when the AABBs
BBs begin to overlap. begin to overlap.
virtual bool ShouldCollide(b2Fixture* fixtureA, b2Fixture* fixtureB) virtual bool ShouldCollide(b2Fixture* fixtureA, b2Fixture* fixtureB);
;
}; };
/// Contact impulses for reporting. Impulses are used instead of forces bec ause /// Contact impulses for reporting. Impulses are used instead of forces bec ause
/// sub-step forces may approach infinity for rigid body collisions. These /// sub-step forces may approach infinity for rigid body collisions. These
/// match up one-to-one with the contact points in b2Manifold. /// match up one-to-one with the contact points in b2Manifold.
struct b2ContactImpulse struct b2ContactImpulse
{ {
float32 normalImpulses[b2_maxManifoldPoints]; float32 normalImpulses[b2_maxManifoldPoints];
float32 tangentImpulses[b2_maxManifoldPoints]; float32 tangentImpulses[b2_maxManifoldPoints];
int32 count; int32 count;
}; };
/// Implement this class to get contact information. You can use these resu lts for /// Implement this class to get contact information. You can use these resu lts for
/// things like sounds and game logic. You can also get contact results by /// things like sounds and game logic. You can also get contact results by
/// traversing the contact lists after the time step. However, you might mi ss /// traversing the contact lists after the time step. However, you might mi ss
/// some contacts because continuous physics leads to sub-stepping. /// some contacts because continuous physics leads to sub-stepping.
/// Additionally you may receive multiple callbacks for the same contact in a /// Additionally you may receive multiple callbacks for the same contact in a
/// single time step. /// single time step.
/// You should strive to make your callbacks efficient because there may be /// You should strive to make your callbacks efficient because there may be
/// many callbacks per time step. /// many callbacks per time step.
/// @warning You cannot create/destroy Box2D entities inside these callback s. /// @warning You cannot create/destroy Box2D entities inside these callback s.
class b2ContactListener class b2ContactListener
{ {
public: public:
virtual ~b2ContactListener() {} virtual ~b2ContactListener() {}
/// Called when two fixtures begin to touch. /// Called when two fixtures begin to touch.
virtual void BeginContact(b2Contact* contact) { B2_NOT_USED(contact) virtual void BeginContact(b2Contact* contact) { B2_NOT_USED(contact); }
; }
/// Called when two fixtures cease to touch. /// Called when two fixtures cease to touch.
virtual void EndContact(b2Contact* contact) { B2_NOT_USED(contact); virtual void EndContact(b2Contact* contact) { B2_NOT_USED(contact); }
}
/// This is called after a contact is updated. This allows you to in /// This is called after a contact is updated. This allows you to inspe
spect a ct a
/// contact before it goes to the solver. If you are careful, you ca /// contact before it goes to the solver. If you are careful, you can m
n modify the odify the
/// contact manifold (e.g. disable contact). /// contact manifold (e.g. disable contact).
/// A copy of the old manifold is provided so that you can detect ch /// A copy of the old manifold is provided so that you can detect chang
anges. es.
/// Note: this is called only for awake bodies. /// Note: this is called only for awake bodies.
/// Note: this is called even when the number of contact points is z /// Note: this is called even when the number of contact points is zero
ero. .
/// Note: this is not called for sensors. /// Note: this is not called for sensors.
/// Note: if you set the number of contact points to zero, you will /// Note: if you set the number of contact points to zero, you will not
not /// get an EndContact callback. However, you may get a BeginContact cal
/// get an EndContact callback. However, you may get a BeginContact lback
callback /// the next step.
/// the next step. virtual void PreSolve(b2Contact* contact, const b2Manifold* oldManifold
virtual void PreSolve(b2Contact* contact, const b2Manifold* oldManif )
old) {
{ B2_NOT_USED(contact);
B2_NOT_USED(contact); B2_NOT_USED(oldManifold);
B2_NOT_USED(oldManifold); }
}
/// This lets you inspect a contact after the solver is finished. This
/// This lets you inspect a contact after the solver is finished. Th is useful
is is useful /// for inspecting impulses.
/// for inspecting impulses. /// Note: the contact manifold does not include time of impact impulses
/// Note: the contact manifold does not include time of impact impul , which can be
ses, which can be /// arbitrarily large if the sub-step is small. Hence the impulse is pr
/// arbitrarily large if the sub-step is small. Hence the impulse is ovided explicitly
provided explicitly /// in a separate data structure.
/// in a separate data structure. /// Note: this is only called for contacts that are touching, solid, an
/// Note: this is only called for contacts that are touching, solid, d awake.
and awake. virtual void PostSolve(b2Contact* contact, const b2ContactImpulse* impu
virtual void PostSolve(b2Contact* contact, const b2ContactImpulse* i lse)
mpulse) {
{ B2_NOT_USED(contact);
B2_NOT_USED(contact); B2_NOT_USED(impulse);
B2_NOT_USED(impulse); }
}
}; };
/// Callback class for AABB queries. /// Callback class for AABB queries.
/// See b2World::Query /// See b2World::Query
class b2QueryCallback class b2QueryCallback
{ {
public: public:
virtual ~b2QueryCallback() {} virtual ~b2QueryCallback() {}
/// Called for each fixture found in the query AABB. /// Called for each fixture found in the query AABB.
/// @return false to terminate the query. /// @return false to terminate the query.
virtual bool ReportFixture(b2Fixture* fixture) = 0; virtual bool ReportFixture(b2Fixture* fixture) = 0;
}; };
/// Callback class for ray casts. /// Callback class for ray casts.
/// See b2World::RayCast /// See b2World::RayCast
class b2RayCastCallback class b2RayCastCallback
{ {
public: public:
virtual ~b2RayCastCallback() {} virtual ~b2RayCastCallback() {}
/// Called for each fixture found in the query. You control how the /// Called for each fixture found in the query. You control how the ray
ray cast cast
/// proceeds by returning a float: /// proceeds by returning a float:
/// return -1: ignore this fixture and continue /// return -1: ignore this fixture and continue
/// return 0: terminate the ray cast /// return 0: terminate the ray cast
/// return fraction: clip the ray to this point /// return fraction: clip the ray to this point
/// return 1: don't clip the ray and continue /// return 1: don't clip the ray and continue
/// @param fixture the fixture hit by the ray /// @param fixture the fixture hit by the ray
/// @param point the point of initial intersection /// @param point the point of initial intersection
/// @param normal the normal vector at the point of intersection /// @param normal the normal vector at the point of intersection
/// @return -1 to filter, 0 to terminate, fraction to clip the ray f /// @return -1 to filter, 0 to terminate, fraction to clip the ray for
or /// closest hit, 1 to continue
/// closest hit, 1 to continue virtual float32 ReportFixture( b2Fixture* fixture, const b2Vec2& poi
virtual float32 ReportFixture( b2Fixture* fixture, const b2Vec2& po nt,
int, const b2Vec2& normal, float32 fraction)
cons = 0;
t b2Vec2& normal, float32 fraction) = 0;
}; };
#endif #endif
 End of changes. 13 change blocks. 
86 lines changed or deleted 81 lines changed or added


 base64.h   base64.h 
skipping to change at line 32 skipping to change at line 32
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __SUPPORT_BASE64_H__ #ifndef __SUPPORT_BASE64_H__
#define __SUPPORT_BASE64_H__ #define __SUPPORT_BASE64_H__
#ifdef __cplusplus #ifdef __cplusplus
extern "C" { extern "C" {
#endif #endif
namespace cocos2d { namespace cocos2d {
/** @file /** @file
base64 helper functions base64 helper functions
*/ */
/** /**
* Decodes a 64base encoded memory. The decoded memory is * Decodes a 64base encoded memory. The decoded memory is
* expected to be freed by the caller. * expected to be freed by the caller.
* *
* @returns the length of the out buffer * @returns the length of the out buffer
* *
@since v0.8.1 @since v0.8.1
*/ */
int base64Decode(unsigned char *in, unsigned int inLength, unsigned char ** out); int base64Decode(unsigned char *in, unsigned int inLength, unsigned char ** out);
}//namespace cocos2d }//namespace cocos2d
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif
#endif // __SUPPORT_BASE64_H__ #endif // __SUPPORT_BASE64_H__
 End of changes. 2 change blocks. 
1 lines changed or deleted 2 lines changed or added


 ccCArray.h   ccCArray.h 
/************************************************************************** ** /************************************************************************** **
Copyright (c) 2010-2011 cocos2d-x.org Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2007 Scott Lembcke Copyright (c) 2007 Scott Lembcke
http://www.cocos2d-x.org http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a cop y Permission is hereby granted, free of charge, to any person obtaining a cop y
of this software and associated documentation files (the "Software"), to de al of this software and associated documentation files (the "Software"), to de al
in the Software without restriction, including without limitation the right s in the Software without restriction, including without limitation the right s
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
skipping to change at line 28 skipping to change at line 28
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
/** /**
@file @file
Based on Chipmunk cpArray. based on Chipmunk cpArray.
ccArray is a faster alternative to CCMutableArray, it does pretty much the ccArray is a faster alternative to NSMutableArray, it does pretty much the
same thing (stores CCObjects and retains/releases them appropriately). It' same thing (stores NSObjects and retains/releases them appropriately). It'
s s
faster because: faster because:
- it uses a plain C interface so it doesn't incur Objective-c messaging ov erhead - it uses a plain C interface so it doesn't incur Objective-c messaging ov erhead
- it assumes you know what you're doing, so it doesn't spend time on safet y checks - it assumes you know what you're doing, so it doesn't spend time on safet y checks
(index out of bounds, required capacity etc.) (index out of bounds, required capacity etc.)
- comparisons are done using pointer equality instead of isEqual - comparisons are done using pointer equality instead of isEqual
There are 2 kind of functions:
- ccArray functions that manipulates objective-c objects (retain and relea
se are performanced)
- ccCArray functions that manipulates values like if they were standard C
structures (no retain/release is performed)
*/ */
#ifndef CC_ARRAY_H #ifndef CC_ARRAY_H
#define CC_ARRAY_H #define CC_ARRAY_H
#include "ccMacros.h"
#include "cocoa/CCObject.h"
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <limits.h> #include <limits.h>
#include "ccMacros.h"
#include "CCObject.h"
#include "ccMacros.h"
namespace cocos2d { NS_CC_BEGIN
#define CC_INVALID_INDEX 0xffffffff
// Easy integration // Easy integration
#define CCARRAYDATA_FOREACH(__array__, __object__) \ #define CCARRAYDATA_FOREACH(__array__, __object__) \
__object__=__array__->arr[0]; for(unsigned int i=0, num=__array__->n um; i<num; i++, __object__=__array__->arr[i]) \ __object__=__array__->arr[0]; for(unsigned int i=0, num=__array__->num; i<n um; i++, __object__=__array__->arr[i]) \
typedef struct _ccArray typedef struct _ccArray {
{
unsigned int num, max; unsigned int num, max;
CCObject** arr; //equals CCObject** arr; CCObject** arr;
} ccArray; } ccArray;
/** Allocates and initializes a new array with specified capacity */ /** Allocates and initializes a new array with specified capacity */
static inline ccArray* ccArrayNew(unsigned int capacity) ccArray* ccArrayNew(unsigned int capacity);
{
if (capacity == 0)
{
capacity = 1;
}
ccArray *arr = (ccArray*)malloc( sizeof(ccArray) );
arr->num = 0;
arr->arr = (CCObject**)malloc( capacity * sizeof(CCObject*) );
arr->max = capacity;
return arr;
}
static inline void ccArrayRemoveAllObjects(ccArray *arr);
/** Frees array after removing all remaining objects. Silently ignores nil arr. */ /** Frees array after removing all remaining objects. Silently ignores nil arr. */
static inline void ccArrayFree(ccArray *arr) void ccArrayFree(ccArray*& arr);
{
if( arr == NULL )
{
return;
}
ccArrayRemoveAllObjects(arr);
//delete arr->m_pObjectArray;
free(arr->arr);
free(arr);
}
/** Doubles array capacity */ /** Doubles array capacity */
static inline void ccArrayDoubleCapacity(ccArray *arr) void ccArrayDoubleCapacity(ccArray *arr);
{
arr->max *= 2;
CCObject** newArr = (CCObject**)realloc( arr->arr, arr->max * sizeof(CC
Object*) );
// will fail when there's not enough memory
CCAssert(newArr != NULL, "ccArrayDoubleCapacity failed. Not enough memo
ry");
arr->arr = newArr;
}
/** Increases array capacity such that max >= num + extra. */ /** Increases array capacity such that max >= num + extra. */
static inline void ccArrayEnsureExtraCapacity(ccArray *arr, unsigned int ex void ccArrayEnsureExtraCapacity(ccArray *arr, unsigned int extra);
tra)
{
while (arr->max < arr->num + extra)
{
ccArrayDoubleCapacity(arr);
}
}
/** shrinks the array so the memory footprint corresponds with the number o f items */ /** shrinks the array so the memory footprint corresponds with the number o f items */
static inline void ccArrayShrink(ccArray *arr) void ccArrayShrink(ccArray *arr);
{
unsigned int newSize;
//only resize when necessary
if (arr->max > arr->num && !(arr->num==0 && arr->max==1))
{
if (arr->num!=0)
{
newSize=arr->num;
arr->max=arr->num;
}
else
{//minimum capacity of 1, with 0 elements the array would be free'd
by realloc
newSize=1;
arr->max=1;
}
arr->arr = (CCObject**) realloc(arr->arr,newSize * sizeof(CCObject*
) );
CCAssert(arr->arr != NULL, "could not reallocate the memory");
}
}
/** Returns index of first occurence of object, UXNotFound if object not fo
und. */
static inline unsigned int ccArrayGetIndexOfObject(ccArray *arr, CCObject*
object)
{
for ( unsigned int i = 0; i < arr->num; i++)
{
if (arr->arr[i] == object)
{
return i;
}
}
return UINT_MAX; /** Returns index of first occurence of object, NSNotFound if object not fo
} und. */
unsigned int ccArrayGetIndexOfObject(ccArray *arr, CCObject* object);
/** Returns a Boolean value that indicates whether object is present in arr ay. */ /** Returns a Boolean value that indicates whether object is present in arr ay. */
static inline bool ccArrayContainsObject(ccArray *arr, CCObject* object) bool ccArrayContainsObject(ccArray *arr, CCObject* object);
{
return ccArrayGetIndexOfObject(arr, object) != UINT_MAX;
}
/** Appends an object. Bahaviour undefined if array doesn't have enough cap acity. */ /** Appends an object. Bahaviour undefined if array doesn't have enough cap acity. */
static inline void ccArrayAppendObject(ccArray *arr, CCObject* object) void ccArrayAppendObject(ccArray *arr, CCObject* object);
{
arr->arr[arr->num] = object; object->retain();
arr->num++;
}
/** Appends an object. Capacity of arr is increased if needed. */ /** Appends an object. Capacity of arr is increased if needed. */
static inline void ccArrayAppendObjectWithResize(ccArray *arr, CCObject* ob void ccArrayAppendObjectWithResize(ccArray *arr, CCObject* object);
ject)
{
ccArrayEnsureExtraCapacity(arr, 1);
ccArrayAppendObject(arr, object);
}
/** Appends objects from plusArr to arr. Behaviour undefined if arr doesn't /** Appends objects from plusArr to arr.
have Behaviour undefined if arr doesn't have enough capacity. */
enough capacity. */ void ccArrayAppendArray(ccArray *arr, ccArray *plusArr);
static inline void ccArrayAppendArray(ccArray *arr, ccArray *plusArr)
{
for( unsigned int i = 0; i < plusArr->num; i++)
{
ccArrayAppendObject(arr, plusArr->arr[i]);
}
}
/** Appends objects from plusArr to arr. Capacity of arr is increased if ne eded. */ /** Appends objects from plusArr to arr. Capacity of arr is increased if ne eded. */
static inline void ccArrayAppendArrayWithResize(ccArray *arr, ccArray *plus void ccArrayAppendArrayWithResize(ccArray *arr, ccArray *plusArr);
Arr)
{
ccArrayEnsureExtraCapacity(arr, plusArr->num);
ccArrayAppendArray(arr, plusArr);
}
/** Inserts an object at index */ /** Inserts an object at index */
static inline void ccArrayInsertObjectAtIndex(ccArray *arr, CCObject* objec void ccArrayInsertObjectAtIndex(ccArray *arr, CCObject* object, unsigned in
t, unsigned int index) t index);
{
CCAssert(index<=arr->num, "Invalid index. Out of bounds");
ccArrayEnsureExtraCapacity(arr, 1);
unsigned int remaining = arr->num - index;
if( remaining > 0)
memmove(&arr->arr[index+1], &arr->arr[index], sizeof(CCObject*) * r
emaining );
object->retain();
arr->arr[index] = object;
arr->num++;
}
/** Swaps two objects */ /** Swaps two objects */
static inline void ccArraySwapObjectsAtIndexes(ccArray *arr, unsigned int i void ccArraySwapObjectsAtIndexes(ccArray *arr, unsigned int index1, unsigne
ndex1, unsigned int index2) d int index2);
{
CCAssert(index1 < arr->num, "(1) Invalid index. Out of bounds");
CCAssert(index2 < arr->num, "(2) Invalid index. Out of bounds");
CCObject* object1 = arr->arr[index1];
arr->arr[index1] = arr->arr[index2];
arr->arr[index2] = object1;
}
/** Removes all objects from arr */ /** Removes all objects from arr */
static inline void ccArrayRemoveAllObjects(ccArray *arr) void ccArrayRemoveAllObjects(ccArray *arr);
{
while(arr->num > 0)
{
arr->arr[--arr->num]->release();
}
}
/** Removes object at specified index and pushes back all subsequent object s. /** Removes object at specified index and pushes back all subsequent object s.
Behaviour undefined if index outside [0, num-1]. */ Behaviour undefined if index outside [0, num-1]. */
static inline void ccArrayRemoveObjectAtIndex(ccArray *arr, unsigned int in void ccArrayRemoveObjectAtIndex(ccArray *arr, unsigned int index, bool bRel
dex) easeObj = true);
{
arr->arr[index]->release();
arr->num--;
unsigned int remaining = arr->num - index;
if (remaining > 0)
{
memmove(&arr->arr[index], &arr->arr[index+1], remain
ing * sizeof(void*));
}
}
/** Removes object at specified index and fills the gap with the last objec t, /** Removes object at specified index and fills the gap with the last objec t,
thereby avoiding the need to push back subsequent objects. thereby avoiding the need to push back subsequent objects.
Behaviour undefined if index outside [0, num-1]. */ Behaviour undefined if index outside [0, num-1]. */
static inline void ccArrayFastRemoveObjectAtIndex(ccArray *arr, unsigned in void ccArrayFastRemoveObjectAtIndex(ccArray *arr, unsigned int index);
t index)
{ void ccArrayFastRemoveObject(ccArray *arr, CCObject* object);
arr->arr[index]->release();
unsigned int last = --arr->num;
arr->arr[index] = arr->arr[last];
}
static inline void ccArrayFastRemoveObject(ccArray *arr, CCObject* object)
{
unsigned int index = ccArrayGetIndexOfObject(arr, object);
if (index != UINT_MAX)
ccArrayFastRemoveObjectAtIndex(arr, index);
}
/** Searches for the first occurance of object and removes it. If object is not /** Searches for the first occurance of object and removes it. If object is not
found the function has no effect. */ found the function has no effect. */
static inline void ccArrayRemoveObject(ccArray *arr, CCObject* object) void ccArrayRemoveObject(ccArray *arr, CCObject* object, bool bReleaseObj =
{ true);
unsigned int index = ccArrayGetIndexOfObject(arr, object);
if (index != UINT_MAX)
{
ccArrayRemoveObjectAtIndex(arr, index);
}
}
/** Removes from arr all objects in minusArr. For each object in minusArr, the /** Removes from arr all objects in minusArr. For each object in minusArr, the
first matching instance in arr will be removed. */ first matching instance in arr will be removed. */
static inline void ccArrayRemoveArray(ccArray *arr, ccArray *minusArr) void ccArrayRemoveArray(ccArray *arr, ccArray *minusArr);
{
for( unsigned int i = 0; i < minusArr->num; i++)
{
ccArrayRemoveObject(arr, minusArr->arr[i]);
}
}
/** Removes from arr all objects in minusArr. For each object in minusArr, all /** Removes from arr all objects in minusArr. For each object in minusArr, all
matching instances in arr will be removed. */ matching instances in arr will be removed. */
static inline void ccArrayFullRemoveArray(ccArray *arr, ccArray *minusArr) void ccArrayFullRemoveArray(ccArray *arr, ccArray *minusArr);
{
unsigned int back = 0;
for( unsigned int i = 0; i < arr->num; i++)
{
if( ccArrayContainsObject(minusArr, arr->arr[i]) )
{
delete arr->arr[i];
back++;
}
else
{
arr->arr[i - back] = arr->arr[i];
}
}
arr->num -= back; // #pragma mark -
} // #pragma mark ccCArray for Values (c structures)
typedef struct _ccCArray typedef struct _ccCArray {
{ unsigned int num, max;
unsigned int num, max; void** arr;
void** arr; //equals CCObject** arr;
} ccCArray; } ccCArray;
static inline void ccCArrayRemoveAllValues(ccCArray *arr);
/** Allocates and initializes a new C array with specified capacity */ /** Allocates and initializes a new C array with specified capacity */
static inline ccCArray* ccCArrayNew(unsigned int capacity) ccCArray* ccCArrayNew(unsigned int capacity);
{
if (capacity == 0)
{
capacity = 1;
}
ccCArray *arr = (ccCArray*)malloc( sizeof(ccCArray) );
arr->num = 0;
arr->arr = (void**) malloc( capacity * sizeof(void*) );
arr->max = capacity;
return arr;
}
/** Frees C array after removing all remaining values. Silently ignores nil arr. */ /** Frees C array after removing all remaining values. Silently ignores nil arr. */
static inline void ccCArrayFree(ccCArray *arr) void ccCArrayFree(ccCArray *arr);
{
if( arr == NULL )
{
return;
}
ccCArrayRemoveAllValues(arr);
free(arr->arr);
free(arr);
}
/** Doubles C array capacity */ /** Doubles C array capacity */
static inline void ccCArrayDoubleCapacity(ccCArray *arr) void ccCArrayDoubleCapacity(ccCArray *arr);
{
ccArrayDoubleCapacity((ccArray*)arr);
}
/** Increases array capacity such that max >= num + extra. */ /** Increases array capacity such that max >= num + extra. */
static inline void ccCArrayEnsureExtraCapacity(ccCArray *arr, unsigned int void ccCArrayEnsureExtraCapacity(ccCArray *arr, unsigned int extra);
extra)
{
ccArrayEnsureExtraCapacity((ccArray*)arr,extra);
}
/** Returns index of first occurence of value, NSNotFound if value not foun d. */ /** Returns index of first occurence of value, NSNotFound if value not foun d. */
static inline int ccCArrayGetIndexOfValue(ccCArray *arr, void* value) unsigned int ccCArrayGetIndexOfValue(ccCArray *arr, void* value);
{
for (unsigned int i = 0; i < arr->num; i++)
{
if (arr->arr[i] == value)
{
return i;
}
}
return -1;
}
/** Returns a Boolean value that indicates whether value is present in the C array. */ /** Returns a Boolean value that indicates whether value is present in the C array. */
static inline bool ccCArrayContainsValue(ccCArray *arr, void* value) bool ccCArrayContainsValue(ccCArray *arr, void* value);
{
return ccCArrayGetIndexOfValue(arr, value) != -1; /** Inserts a value at a certain position. Behaviour undefined if aray does
} n't have enough capacity */
void ccCArrayInsertValueAtIndex( ccCArray *arr, void* value, unsigned int i
/** Inserts a value at a certain position. The valid index is [0, num] */ ndex);
static inline void ccCArrayInsertValueAtIndex( ccCArray *arr, void* value,
unsigned int index) /** Appends an value. Bahaviour undefined if array doesn't have enough capa
{ city. */
CCAssert( index < arr->max, "ccCArrayInsertValueAtIndex: invalid index" void ccCArrayAppendValue(ccCArray *arr, void* value);
);
unsigned int remaining = arr->num - index;
// make sure it has enough capacity
if (arr->num + 1 == arr->max)
{
ccCArrayDoubleCapacity(arr);
}
// last Value doesn't need to be moved
if( remaining > 0)
{
// tex coordinates
memmove( &arr->arr[index+1],&arr->arr[index], sizeof(void*)
* remaining );
}
arr->num++;
arr->arr[index] = value;
}
/** Appends an value */
static inline void ccCArrayAppendValue(ccCArray *arr, void* value)
{
arr->arr[arr->num] = value;
arr->num++;
// double the capacity for the next append action
// if the num >= max
if (arr->num >= arr->max)
{
ccCArrayDoubleCapacity(arr);
}
}
/** Appends an value. Capacity of arr is increased if needed. */ /** Appends an value. Capacity of arr is increased if needed. */
static inline void ccCArrayAppendValueWithResize(ccCArray *arr, void* value void ccCArrayAppendValueWithResize(ccCArray *arr, void* value);
)
{
ccCArrayEnsureExtraCapacity(arr, 1);
ccCArrayAppendValue(arr, value);
}
/** Appends values from plusArr to arr. Behaviour undefined if arr doesn't have /** Appends values from plusArr to arr. Behaviour undefined if arr doesn't have
enough capacity. */ enough capacity. */
static inline void ccCArrayAppendArray(ccCArray *arr, ccCArray *plusArr) void ccCArrayAppendArray(ccCArray *arr, ccCArray *plusArr);
{
for (unsigned int i = 0; i < plusArr->num; i++)
{
ccCArrayAppendValue(arr, plusArr->arr[i]);
}
}
/** Appends values from plusArr to arr. Capacity of arr is increased if nee ded. */ /** Appends values from plusArr to arr. Capacity of arr is increased if nee ded. */
static inline void ccCArrayAppendArrayWithResize(ccCArray *arr, ccCArray *p void ccCArrayAppendArrayWithResize(ccCArray *arr, ccCArray *plusArr);
lusArr)
{
ccCArrayEnsureExtraCapacity(arr, plusArr->num);
ccCArrayAppendArray(arr, plusArr);
}
/** Removes all values from arr */ /** Removes all values from arr */
static inline void ccCArrayRemoveAllValues(ccCArray *arr) void ccCArrayRemoveAllValues(ccCArray *arr);
{
arr->num = 0;
}
/** Removes value at specified index and pushes back all subsequent values. /** Removes value at specified index and pushes back all subsequent values.
Behaviour undefined if index outside [0, num-1]. */ Behaviour undefined if index outside [0, num-1].
static inline void ccCArrayRemoveValueAtIndex(ccCArray *arr, unsigned int i @since v0.99.4
ndex) */
{ void ccCArrayRemoveValueAtIndex(ccCArray *arr, unsigned int index);
for (unsigned int last = --arr->num; index < last; index++)
{
arr->arr[index] = arr->arr[index + 1];
}
}
/** Removes value at specified index and fills the gap with the last value, /** Removes value at specified index and fills the gap with the last value,
thereby avoiding the need to push back subsequent values. thereby avoiding the need to push back subsequent values.
Behaviour undefined if index outside [0, num-1]. */ Behaviour undefined if index outside [0, num-1].
static inline void ccCArrayFastRemoveValueAtIndex(ccCArray *arr, unsigned i @since v0.99.4
nt index) */
{ void ccCArrayFastRemoveValueAtIndex(ccCArray *arr, unsigned int index);
unsigned int last = --arr->num;
arr->arr[index] = arr->arr[last];
}
/** Searches for the first occurance of value and removes it. If value is n
ot
found the function has no effect. */
static inline void ccCArrayRemoveValue(ccCArray *arr, void* value)
{
unsigned int index = ccCArrayGetIndexOfValue(arr, value);
if (index != UINT_MAX)
{
ccCArrayRemoveValueAtIndex(arr, index);
}
}
/** Removes from arr all values in minusArr. For each Value in minusArr, th /** Searches for the first occurance of value and removes it. If value is n
e ot found the function has no effect.
first matching instance in arr will be removed. */ @since v0.99.4
static inline void ccCArrayRemoveArray(ccCArray *arr, ccCArray *minusArr) */
{ void ccCArrayRemoveValue(ccCArray *arr, void* value);
for( unsigned int i = 0; i < minusArr->num; i++)
{
ccCArrayRemoveValue(arr, minusArr->arr[i]);
}
}
/** Removes from arr all values in minusArr. For each value in minusArr, al /** Removes from arr all values in minusArr. For each Value in minusArr, th
l e first matching instance in arr will be removed.
matching instances in arr will be removed. */ @since v0.99.4
static inline void ccCArrayFullRemoveArray(ccCArray *arr, ccCArray *minusAr */
r) void ccCArrayRemoveArray(ccCArray *arr, ccCArray *minusArr);
{
unsigned int back = 0;
for (unsigned int i = 0; i < arr->num; i++)
{
if( ccCArrayContainsValue(minusArr, arr->arr[i]) )
{
back++;
} else
{
arr->arr[i - back] = arr->arr[i];
}
}
arr->num -= back; /** Removes from arr all values in minusArr. For each value in minusArr, al
} l matching instances in arr will be removed.
@since v0.99.4
*/
void ccCArrayFullRemoveArray(ccCArray *arr, ccCArray *minusArr);
} NS_CC_END
#endif // CC_ARRAY_H #endif // CC_ARRAY_H
 End of changes. 49 change blocks. 
409 lines changed or deleted 99 lines changed or added


 ccConfig.h   ccConfig.h 
skipping to change at line 30 skipping to change at line 30
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CCCONFIG_H__ #ifndef __CCCONFIG_H__
#define __CCCONFIG_H__ #define __CCCONFIG_H__
#include "CCPlatformConfig.h" #include "platform/CCPlatformConfig.h"
/**
@file
cocos2d (cc) configuration file
*/
/** @def CC_ENABLE_GL_STATE_CACHE
If enabled, cocos2d will maintain an OpenGL state cache internally to avoi
d unnecessary switches.
In order to use them, you have to use the following functions, insead of t
he the GL ones:
- ccGLUseProgram() instead of glUseProgram()
- ccGLDeleteProgram() instead of glDeleteProgram()
- ccGLBlendFunc() instead of glBlendFunc()
If this functionality is disabled, then ccGLUseProgram(), ccGLDeleteProgra
m(), ccGLBlendFunc() will call the GL ones, without using the cache.
It is recommened to enable whenever possible to improve speed.
If you are migrating your code from GL ES 1.1, then keep it disabled. Once
all your code works as expected, turn it on.
@since v2.0.0
*/
#ifndef CC_ENABLE_GL_STATE_CACHE
#define CC_ENABLE_GL_STATE_CACHE 1
#endif
/** @def CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL /** @def CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL
If enabled, the texture coordinates will be calculated by using this formul a: If enabled, the texture coordinates will be calculated by using this formul a:
- texCoord.left = (rect.origin.x*2+1) / (texture.wide*2); - texCoord.left = (rect.origin.x*2+1) / (texture.wide*2);
- texCoord.right = texCoord.left + (rect.size.width*2-2)/(texture.wide*2); - texCoord.right = texCoord.left + (rect.size.width*2-2)/(texture.wide*2);
The same for bottom and top. The same for bottom and top.
This formula prevents artifacts by using 99% of the texture. This formula prevents artifacts by using 99% of the texture.
The "correct" way to prevent artifacts is by using the spritesheet-artifact -fixer.py or a similar tool. The "correct" way to prevent artifacts is by using the spritesheet-artifact -fixer.py or a similar tool.
skipping to change at line 56 skipping to change at line 79
- CCTileMap - CCTileMap
To enabled set it to 1. Disabled by default. To enabled set it to 1. Disabled by default.
@since v0.99.5 @since v0.99.5
*/ */
#ifndef CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL #ifndef CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL
#define CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL 0 #define CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL 0
#endif #endif
/** @def CC_FONT_LABEL_SUPPORT
If enabled, FontLabel will be used to render .ttf files.
If the .ttf file is not found, then it will use the standard UIFont class
If disabled, the standard UIFont class will be used.
To disable set it to 0. Enabled by default.
Only valid for cocos2d-ios. Not supported on cocos2d-mac
*/
#ifndef CC_FONT_LABEL_SUPPORT
#define CC_FONT_LABEL_SUPPORT 1
#endif
/** @def CC_DIRECTOR_FAST_FPS
If enabled, then the FPS will be drawn using CCLabelAtlas (fast rendering)
.
You will need to add the fps_images.png to your project.
If disabled, the FPS will be rendered using CCLabel (slow rendering)
To enable set it to a value different than 0. Enabled by default.
*/
#ifndef CC_DIRECTOR_FAST_FPS
#define CC_DIRECTOR_FAST_FPS 1
#endif
/** @def CC_DIRECTOR_FPS_INTERVAL /** @def CC_DIRECTOR_FPS_INTERVAL
Senconds between FPS updates. Senconds between FPS updates.
0.5 seconds, means that the FPS number will be updated every 0.5 seconds. 0.5 seconds, means that the FPS number will be updated every 0.5 seconds.
Having a bigger number means a more reliable FPS Having a bigger number means a more reliable FPS
Default value: 0.1f Default value: 0.1f
*/ */
#ifndef CC_DIRECTOR_FPS_INTERVAL #ifndef CC_DIRECTOR_STATS_INTERVAL
#define CC_DIRECTOR_FPS_INTERVAL (0.5f) #define CC_DIRECTOR_STATS_INTERVAL (0.1f)
#endif
/** @def CC_DIRECTOR_FPS_POSITION
Position of the FPS
Default: 0,0 (bottom-left corner)
*/
#ifndef CC_DIRECTOR_FPS_POSITION
#define CC_DIRECTOR_FPS_POSITION ccp(0,0)
#endif #endif
/** @def CC_DIRECTOR_DISPATCH_FAST_EVENTS /** @def CC_DIRECTOR_DISPATCH_FAST_EVENTS
If enabled, and only when it is used with CCFastDirector, the main loop wi ll wait 0.04 seconds to If enabled, and only when it is used with CCFastDirector, the main loop wi ll wait 0.04 seconds to
dispatch all the events, even if there are not events to dispatch. dispatch all the events, even if there are not events to dispatch.
If your game uses lot's of events (eg: touches) it might be a good idea to enable this feature. If your game uses lot's of events (eg: touches) it might be a good idea to enable this feature.
Otherwise, it is safe to leave it disabled. Otherwise, it is safe to leave it disabled.
To enable set it to 1. Disabled by default. To enable set it to 1. Disabled by default.
skipping to change at line 120 skipping to change at line 128
To enable set it to a 1, to disable it set to 0. Enabled by default. To enable set it to a 1, to disable it set to 0. Enabled by default.
Only valid for cocos2d-mac. Not supported on cocos2d-ios. Only valid for cocos2d-mac. Not supported on cocos2d-ios.
*/ */
#ifndef CC_DIRECTOR_MAC_USE_DISPLAY_LINK_THREAD #ifndef CC_DIRECTOR_MAC_USE_DISPLAY_LINK_THREAD
#define CC_DIRECTOR_MAC_USE_DISPLAY_LINK_THREAD 1 #define CC_DIRECTOR_MAC_USE_DISPLAY_LINK_THREAD 1
#endif #endif
/** @def CC_COCOSNODE_RENDER_SUBPIXEL /** @def CC_NODE_RENDER_SUBPIXEL
If enabled, the CCNode objects (CCSprite, CCLabel,etc) will be able to ren der in subpixels. If enabled, the CCNode objects (CCSprite, CCLabel,etc) will be able to ren der in subpixels.
If disabled, integer pixels will be used. If disabled, integer pixels will be used.
To enable set it to 1. Enabled by default. To enable set it to 1. Enabled by default.
*/ */
#ifndef CC_COCOSNODE_RENDER_SUBPIXEL #ifndef CC_NODE_RENDER_SUBPIXEL
#define CC_COCOSNODE_RENDER_SUBPIXEL 1 #define CC_NODE_RENDER_SUBPIXEL 1
#endif #endif
/** @def CC_SPRITEBATCHNODE_RENDER_SUBPIXEL /** @def CC_SPRITEBATCHNODE_RENDER_SUBPIXEL
If enabled, the CCSprite objects rendered with CCSpriteBatchNode will be a ble to render in subpixels. If enabled, the CCSprite objects rendered with CCSpriteBatchNode will be a ble to render in subpixels.
If disabled, integer pixels will be used. If disabled, integer pixels will be used.
To enable set it to 1. Enabled by default. To enable set it to 1. Enabled by default.
*/ */
#ifndef CC_SPRITEBATCHNODE_RENDER_SUBPIXEL #ifndef CC_SPRITEBATCHNODE_RENDER_SUBPIXEL
#define CC_SPRITEBATCHNODE_RENDER_SUBPIXEL 1 #define CC_SPRITEBATCHNODE_RENDER_SUBPIXEL 1
#endif
/** @def CC_USES_VBO
If enabled, batch nodes (texture atlas and particle system) will use VBO in
stead of vertex list (VBO is recommended by Apple)
To enable set it to 1.
Enabled by default on iPhone with ARMv7 processors, iPhone Simulator and Ma
c
Disabled by default on iPhone with ARMv6 processors.
@since v0.99.5
*/
#ifndef CC_USES_VBO
#if (CC_TARGET_PLATFORM == CC_PLATFORM_MARMALADE)
#define CC_USES_VBO 0
#else
#define CC_USES_VBO 1
#endif
#endif
/** @def CC_NODE_TRANSFORM_USING_AFFINE_MATRIX
If enabled, CCNode will transform the nodes using a cached Affine matrix.
If disabled, the node will be transformed using glTranslate,glRotate,glSca
le.
Using the affine matrix only requires 2 GL calls.
Using the translate/rotate/scale requires 5 GL calls.
But computing the Affine matrix is relative expensive.
But according to performance tests, Affine matrix performs better.
This parameter doesn't affect CCSpriteBatchNode nodes.
To enable set it to a value different than 0. Enabled by default.
*/
#ifndef CC_NODE_TRANSFORM_USING_AFFINE_MATRIX
#define CC_NODE_TRANSFORM_USING_AFFINE_MATRIX 1
#endif
/** @def CC_OPTIMIZE_BLEND_FUNC_FOR_PREMULTIPLIED_ALPHA
If most of your imamges have pre-multiplied alpha, set it to 1 (if you are
going to use .PNG/.JPG file images).
Only set to 0 if ALL your images by-pass Apple UIImage loading system (eg:
if you use libpng or PVR images)
To enable set it to a value different than 0. Enabled by default.
@since v0.99.5
*/
#ifndef CC_OPTIMIZE_BLEND_FUNC_FOR_PREMULTIPLIED_ALPHA
#define CC_OPTIMIZE_BLEND_FUNC_FOR_PREMULTIPLIED_ALPHA 1
#endif #endif
/** @def CC_TEXTURE_ATLAS_USE_TRIANGLE_STRIP /** @def CC_TEXTURE_ATLAS_USE_TRIANGLE_STRIP
Use GL_TRIANGLE_STRIP instead of GL_TRIANGLES when rendering the texture a tlas. Use GL_TRIANGLE_STRIP instead of GL_TRIANGLES when rendering the texture a tlas.
It seems it is the recommend way, but it is much slower, so, enable it at your own risk It seems it is the recommend way, but it is much slower, so, enable it at your own risk
To enable set it to a value different than 0. Disabled by default. To enable set it to a value different than 0. Disabled by default.
*/ */
#ifndef CC_TEXTURE_ATLAS_USE_TRIANGLE_STRIP #ifndef CC_TEXTURE_ATLAS_USE_TRIANGLE_STRIP
#define CC_TEXTURE_ATLAS_USE_TRIANGLE_STRIP 0 #define CC_TEXTURE_ATLAS_USE_TRIANGLE_STRIP 0
#endif #endif
/** @def CC_TEXTURE_NPOT_SUPPORT /** @def CC_TEXTURE_ATLAS_USE_VAO
If enabled, NPOT textures will be used where available. Only 3rd gen (and By default, CCTextureAtlas (used by many cocos2d classes) will use VAO (Ve
newer) devices support NPOT textures. rtex Array Objects).
NPOT textures have the following limitations: Apple recommends its usage but they might consume a lot of memory, special
- They can't have mipmaps ly if you use many of them.
- They only accept GL_CLAMP_TO_EDGE in GL_TEXTURE_WRAP_{S,T} So for certain cases, where you might need hundreds of VAO objects, it mig
ht be a good idea to disable it.
To enable set it to a value different than 0. Disabled by default.
This value governs only the PNG, GIF, BMP, images.
This value DOES NOT govern the PVR (PVR.GZ, PVR.CCZ) files. If NPOT PVR is
loaded, then it will create an NPOT texture ignoring this value.
@deprecated This value will be removed in 1.1 and NPOT textures will be lo aded by default if the device supports it. To disable it set it to 0. Enabled by default.
@since v0.99.2
*/ */
#ifndef CC_TEXTURE_NPOT_SUPPORT #ifndef CC_TEXTURE_ATLAS_USE_VAO
#define CC_TEXTURE_NPOT_SUPPORT 0 #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == C
C_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC)
#define CC_TEXTURE_ATLAS_USE_VAO 1
#else
/* Some android devices cannot support VAO very well, so we disable
it by default for android platform. */
/* Blackberry also doesn't support this feature. */
#define CC_TEXTURE_ATLAS_USE_VAO 0
#endif
#endif #endif
/** @def CC_RETINA_DISPLAY_SUPPORT /** @def CC_USE_LA88_LABELS
If enabled, cocos2d supports retina display. If enabled, it will use LA88 (Luminance Alpha 16-bit textures) for CCLabel
For performance reasons, it's recommended disable it in games without retin TTF objects.
a display support, like iPad only games. If it is disabled, it will use A8 (Alpha 8-bit textures).
LA88 textures are 6% faster than A8 textures, but they will consume 2x mem
To enable set it to 1. Use 0 to disable it. Enabled by default. ory.
This value governs only the PNG, GIF, BMP, images.
This value DOES NOT govern the PVR (PVR.GZ, PVR.CCZ) files. If NPOT PVR is
loaded, then it will create an NPOT texture ignoring this value.
@deprecated This value will be removed in 1.1 and NPOT textures will be loa This feature is enabled by default.
ded by default if the device supports it.
@since v0.99.5
*/
#ifndef CC_RETINA_DISPLAY_SUPPORT
#define CC_RETINA_DISPLAY_SUPPORT 1
#endif
/** @def CC_RETINA_DISPLAY_FILENAME_SUFFIX @since v0.99.5
It's the suffix that will be appended to the files in order to load "retina */
display" images. #ifndef CC_USE_LA88_LABELS
#define CC_USE_LA88_LABELS 1
On an iPhone4 with Retina Display support enabled, the file @"sprite-hd.png
" will be loaded instead of @"sprite.png".
If the file doesn't exist it will use the non-retina display image.
Platforms: Only used on Retina Display devices like iPhone 4.
@since v0.99.5
*/
#ifndef CC_RETINA_DISPLAY_FILENAME_SUFFIX
#define CC_RETINA_DISPLAY_FILENAME_SUFFIX "-hd"
#endif
/** @def CC_USE_LA88_LABELS_ON_NEON_ARCH
If enabled, it will use LA88 (16-bit textures) on Neon devices for CCLabelT
TF objects.
If it is disabled, or if it is used on another architecture it will use A8
(8-bit textures).
On Neon devices, LA88 textures are 6% faster than A8 textures, but then wil
l consume 2x memory.
This feature is disabled by default.
Platforms: Only used on ARM Neon architectures like iPhone 3GS or newer and
iPad.
@since v0.99.5
*/
#ifndef CC_USE_LA88_LABELS_ON_NEON_ARCH
#define CC_USE_LA88_LABELS_ON_NEON_ARCH 0
#endif #endif
/** @def CC_SPRITE_DEBUG_DRAW /** @def CC_SPRITE_DEBUG_DRAW
If enabled, all subclasses of CCSprite will draw a bounding box If enabled, all subclasses of CCSprite will draw a bounding box
Useful for debugging purposes only. It is recommened to leave it disabled. Useful for debugging purposes only. It is recommened to leave it disabled.
To enable set it to a value different than 0. Disabled by default: To enable set it to a value different than 0. Disabled by default:
0 -- disabled 0 -- disabled
1 -- draw bounding box 1 -- draw bounding box
2 -- draw texture box 2 -- draw texture box
skipping to change at line 318 skipping to change at line 247
If enabled, will activate various profilers withing cocos2d. This statisti cal data will be output to the console If enabled, will activate various profilers withing cocos2d. This statisti cal data will be output to the console
once per second showing average time (in milliseconds) required to execute the specific routine(s). once per second showing average time (in milliseconds) required to execute the specific routine(s).
Useful for debugging purposes only. It is recommened to leave it disabled. Useful for debugging purposes only. It is recommened to leave it disabled.
To enable set it to a value different than 0. Disabled by default. To enable set it to a value different than 0. Disabled by default.
*/ */
#ifndef CC_ENABLE_PROFILERS #ifndef CC_ENABLE_PROFILERS
#define CC_ENABLE_PROFILERS 0 #define CC_ENABLE_PROFILERS 0
#endif #endif
#if CC_RETINA_DISPLAY_SUPPORT
#define CC_IS_RETINA_DISPLAY_SUPPORTED 1
#else
#define CC_IS_RETINA_DISPLAY_SUPPORTED 0
#endif
/** Enable Lua engine debug log */ /** Enable Lua engine debug log */
#ifndef CC_LUA_ENGINE_DEBUG #ifndef CC_LUA_ENGINE_DEBUG
#define CC_LUA_ENGINE_DEBUG 0 #define CC_LUA_ENGINE_DEBUG 0
#endif #endif
#endif // __CCCONFIG_H__ #endif // __CCCONFIG_H__
 End of changes. 14 change blocks. 
155 lines changed or deleted 72 lines changed or added


 ccMacros.h   ccMacros.h 
skipping to change at line 34 skipping to change at line 34
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CCMACROS_H__ #ifndef __CCMACROS_H__
#define __CCMACROS_H__ #define __CCMACROS_H__
#ifndef _USE_MATH_DEFINES #ifndef _USE_MATH_DEFINES
#define _USE_MATH_DEFINES #define _USE_MATH_DEFINES
#endif #endif
#include "CCCommon.h" #include "platform/CCCommon.h"
#include "CCStdC.h" #include "CCStdC.h"
#ifndef CCAssert #ifndef CCAssert
#define CCAssert(cond, msg) CC_ASSERT(cond) #define CCAssert(cond, msg) CC_ASSERT(cond)
#endif // CCAssert #endif // CCAssert
#include "ccConfig.h" #include "ccConfig.h"
/** @def CC_SWAP /** @def CC_SWAP
simple macro that swaps 2 variables simple macro that swaps 2 variables
*/ */
#define CC_SWAP(x, y, type) \ #define CC_SWAP(x, y, type) \
{ type temp = (x); \ { type temp = (x); \
x = y; y = temp; \ x = y; y = temp; \
} }
/** @def CCRANDOM_MINUS1_1 /** @def CCRANDOM_MINUS1_1
returns a random float between -1 and 1 returns a random float between -1 and 1
*/ */
#define CCRANDOM_MINUS1_1() ((2.0f*((float)rand()/RAND_MAX))-1.0f) #define CCRANDOM_MINUS1_1() ((2.0f*((float)rand()/RAND_MAX))-1.0f)
/** @def CCRANDOM_0_1 /** @def CCRANDOM_0_1
returns a random float between 0 and 1 returns a random float between 0 and 1
*/ */
skipping to change at line 71 skipping to change at line 71
/** @def CC_DEGREES_TO_RADIANS /** @def CC_DEGREES_TO_RADIANS
converts degrees to radians converts degrees to radians
*/ */
#define CC_DEGREES_TO_RADIANS(__ANGLE__) ((__ANGLE__) * 0.01745329252f) // PI / 180 #define CC_DEGREES_TO_RADIANS(__ANGLE__) ((__ANGLE__) * 0.01745329252f) // PI / 180
/** @def CC_RADIANS_TO_DEGREES /** @def CC_RADIANS_TO_DEGREES
converts radians to degrees converts radians to degrees
*/ */
#define CC_RADIANS_TO_DEGREES(__ANGLE__) ((__ANGLE__) * 57.29577951f) // PI * 180 #define CC_RADIANS_TO_DEGREES(__ANGLE__) ((__ANGLE__) * 57.29577951f) // PI * 180
#define kCCRepeatForever UINT_MAX -1
/** @def CC_BLEND_SRC /** @def CC_BLEND_SRC
default gl blend src function. Compatible with premultiplied alpha images. default gl blend src function. Compatible with premultiplied alpha images.
*/ */
#if CC_OPTIMIZE_BLEND_FUNC_FOR_PREMULTIPLIED_ALPHA #define CC_BLEND_SRC GL_ONE
#define CC_BLEND_SRC GL_ONE
#define CC_BLEND_DST GL_ONE_MINUS_SRC_ALPHA
#else
#define CC_BLEND_SRC GL_SRC_ALPHA
#define CC_BLEND_DST GL_ONE_MINUS_SRC_ALPHA
#endif // ! CC_OPTIMIZE_BLEND_FUNC_FOR_PREMULTIPLIED_ALPHA
/** @def CC_BLEND_DST
default gl blend dst function. Compatible with premultiplied alpha images.
*/
#define CC_BLEND_DST GL_ONE_MINUS_SRC_ALPHA #define CC_BLEND_DST GL_ONE_MINUS_SRC_ALPHA
/** @def CC_ENABLE_DEFAULT_GL_STATES /** @def CC_NODE_DRAW_SETUP
GL states that are enabled: Helpful macro that setups the GL server state, the correct GL program and
- GL_TEXTURE_2D sets the Model View Projection matrix
- GL_VERTEX_ARRAY @since v2.0
- GL_TEXTURE_COORD_ARRAY */
- GL_COLOR_ARRAY #define CC_NODE_DRAW_SETUP() \
*/ do { \
#define CC_ENABLE_DEFAULT_GL_STATES() { \ ccGLEnable( m_glServerState ); \
glEnableClientState(GL_VERTEX_ARRAY); \ CCAssert(getShaderProgram(), "No shader program set for this node"); \
glEnableClientState(GL_COLOR_ARRAY); \ { \
glEnableClientState(GL_TEXTURE_COORD_ARRAY); \ getShaderProgram()->use(); \
glEnable(GL_TEXTURE_2D); getShaderProgram()->setUniformForModelViewProjectionMatrix(); \
\ } \
} } while(0)
/** @def CC_DISABLE_DEFAULT_GL_STATES /** @def CC_DIRECTOR_END
Disable default GL states: Stops and removes the director from memory.
- GL_TEXTURE_2D Removes the CCGLView from its parent
- GL_VERTEX_ARRAY
- GL_TEXTURE_COORD_ARRAY @since v0.99.4
- GL_COLOR_ARRAY */
*/ #define CC_DIRECTOR_END() \
#define CC_DISABLE_DEFAULT_GL_STATES() { \ do { \
glDisable(GL_TEXTURE_2D); CCDirector *__director = CCDirector::sharedDirector(); \
\ __director->end(); \
glDisableClientState(GL_COLOR_ARRAY); \ } while(0)
glDisableClientState(GL_TEXTURE_COORD_ARRAY); \
glDisableClientState(GL_VERTEX_ARRAY); \
}
#ifndef FLT_EPSILON
#define FLT_EPSILON 1.192092896e-07F
#endif // FLT_EPSILON
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
TypeName(const TypeName&);\
void operator=(const TypeName&)
/**
@since v0.99.5
@todo upto-0.99.5 check the code for retina
*/
#if CC_IS_RETINA_DISPLAY_SUPPORTED
/****************************/
/** RETINA DISPLAY ENABLED **/
/****************************/
/** @def CC_CONTENT_SCALE_FACTOR /** @def CC_CONTENT_SCALE_FACTOR
On Mac it returns 1; On Mac it returns 1;
On iPhone it returns 2 if RetinaDisplay is On. Otherwise it returns 1 On iPhone it returns 2 if RetinaDisplay is On. Otherwise it returns 1
*/ */
#define CC_CONTENT_SCALE_FACTOR() CCDirector::sharedDirector()->getContentS caleFactor() #define CC_CONTENT_SCALE_FACTOR() CCDirector::sharedDirector()->getContentS caleFactor()
/****************************/
/** RETINA DISPLAY ENABLED **/
/****************************/
/** @def CC_RECT_PIXELS_TO_POINTS /** @def CC_RECT_PIXELS_TO_POINTS
Converts a rect in pixels to points Converts a rect in pixels to points
*/ */
#define CC_RECT_PIXELS_TO_POINTS(__pixels__) #define CC_RECT_PIXELS_TO_POINTS(__rect_in_pixels__)
\
\ CCRectMake( (__rect_in_pixels__).origin.x / CC_CONTENT_SCALE_FACTOR(),
CCRectMake( (__pixels__).origin.x / CC_CONTENT_SCALE_FACTOR(), (__pixel (__rect_in_pixels__).origin.y / CC_CONTENT_SCALE_FACTOR(), \
s__).origin.y / CC_CONTENT_SCALE_FACTOR(), \ (__rect_in_pixels__).size.width / CC_CONTENT_SCALE_FACTOR(), (_
(__pixels__).size.width / CC_CONTENT_SCALE_FACTOR(), (__pixels__).size. _rect_in_pixels__).size.height / CC_CONTENT_SCALE_FACTOR() )
height / CC_CONTENT_SCALE_FACTOR() )
/** @def CC_RECT_POINTS_TO_PIXELS /** @def CC_RECT_POINTS_TO_PIXELS
Converts a rect in points to pixels Converts a rect in points to pixels
*/ */
#define CC_RECT_POINTS_TO_PIXELS(__points__) #define CC_RECT_POINTS_TO_PIXELS(__rect_in_points_points__)
\
\ CCRectMake( (__rect_in_points_points__).origin.x * CC_CONTENT_SCALE_FAC
CCRectMake( (__points__).origin.x * CC_CONTENT_SCALE_FACTOR(), (__point TOR(), (__rect_in_points_points__).origin.y * CC_CONTENT_SCALE_FACTOR(),
s__).origin.y * CC_CONTENT_SCALE_FACTOR(), \ \
(__points__).size.width * CC_CONTENT_SCALE_FACTOR(), (__points__).size. (__rect_in_points_points__).size.width * CC_CONTENT_SCALE_FACTO
height * CC_CONTENT_SCALE_FACTOR() ) R(), (__rect_in_points_points__).size.height * CC_CONTENT_SCALE_FACTOR() )
#else // retina disabled
/*****************************/
/** RETINA DISPLAY DISABLED **/
/*****************************/
#define CC_CONTENT_SCALE_FACTOR() 1
#define CC_RECT_PIXELS_TO_POINTS(__pixels__) __pixels__
#define CC_RECT_POINTS_TO_PIXELS(__points__) __points__
#endif /** @def CC_POINT_PIXELS_TO_POINTS
Converts a rect in pixels to points
*/
#define CC_POINT_PIXELS_TO_POINTS(__pixels__)
\
CCPointMake( (__pixels__).x / CC_CONTENT_SCALE_FACTOR(), (__pixels__).y / C
C_CONTENT_SCALE_FACTOR())
/** @def CC_POINT_POINTS_TO_PIXELS
Converts a rect in points to pixels
*/
#define CC_POINT_POINTS_TO_PIXELS(__points__)
\
CCPointMake( (__points__).x * CC_CONTENT_SCALE_FACTOR(), (__points__).y * C
C_CONTENT_SCALE_FACTOR())
/** @def CC_POINT_PIXELS_TO_POINTS
Converts a rect in pixels to points
*/
#define CC_SIZE_PIXELS_TO_POINTS(__size_in_pixels__)
\
CCSizeMake( (__size_in_pixels__).width / CC_CONTENT_SCALE_FACTOR(), (__size
_in_pixels__).height / CC_CONTENT_SCALE_FACTOR())
/** @def CC_POINT_POINTS_TO_PIXELS
Converts a rect in points to pixels
*/
#define CC_SIZE_POINTS_TO_PIXELS(__size_in_points__)
\
CCSizeMake( (__size_in_points__).width * CC_CONTENT_SCALE_FACTOR(), (__size
_in_points__).height * CC_CONTENT_SCALE_FACTOR())
#ifndef FLT_EPSILON
#define FLT_EPSILON 1.192092896e-07F
#endif // FLT_EPSILON
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
TypeName(const TypeName&);\
void operator=(const TypeName&)
/** /**
Helper marcos which converts 4-byte little/big endian Helper marcos which converts 4-byte little/big endian
integral number to the machine native number representation integral number to the machine native number representation
It should work same as apples CFSwapInt32LittleToHost(..) It should work same as apples CFSwapInt32LittleToHost(..)
*/ */
/// when define returns true it means that our architecture uses big endian /// when define returns true it means that our architecture uses big endian
#define CC_HOST_IS_BIG_ENDIAN (bool)(*(unsigned short *)"\0\xff" < 0x100) #define CC_HOST_IS_BIG_ENDIAN (bool)(*(unsigned short *)"\0\xff" < 0x100)
#define CC_SWAP32(i) ((i & 0x000000ff) << 24 | (i & 0x0000ff00) << 8 | (i & 0x00ff0000) >> 8 | (i & 0xff000000) >> 24) #define CC_SWAP32(i) ((i & 0x000000ff) << 24 | (i & 0x0000ff00) << 8 | (i & 0x00ff0000) >> 8 | (i & 0xff000000) >> 24)
#define CC_SWAP16(i) ((i & 0x00ff) << 8 | (i &0xff00) >> 8) #define CC_SWAP16(i) ((i & 0x00ff) << 8 | (i &0xff00) >> 8)
#define CC_SWAP_INT32_LITTLE_TO_HOST(i) ((CC_HOST_IS_BIG_ENDIAN == true)? C C_SWAP32(i) : (i) ) #define CC_SWAP_INT32_LITTLE_TO_HOST(i) ((CC_HOST_IS_BIG_ENDIAN == true)? C C_SWAP32(i) : (i) )
#define CC_SWAP_INT16_LITTLE_TO_HOST(i) ((CC_HOST_IS_BIG_ENDIAN == true)? C C_SWAP16(i) : (i) ) #define CC_SWAP_INT16_LITTLE_TO_HOST(i) ((CC_HOST_IS_BIG_ENDIAN == true)? C C_SWAP16(i) : (i) )
#define CC_SWAP_INT32_BIG_TO_HOST(i) ((CC_HOST_IS_BIG_ENDIAN == true)? ( i) : CC_SWAP32(i) ) #define CC_SWAP_INT32_BIG_TO_HOST(i) ((CC_HOST_IS_BIG_ENDIAN == true)? ( i) : CC_SWAP32(i) )
#define CC_SWAP_INT16_BIG_TO_HOST(i) ((CC_HOST_IS_BIG_ENDIAN == true)? ( i): CC_SWAP16(i) ) #define CC_SWAP_INT16_BIG_TO_HOST(i) ((CC_HOST_IS_BIG_ENDIAN == true)? ( i): CC_SWAP16(i) )
/**********************/
/** Profiling Macros **/
/**********************/
#if CC_ENABLE_PROFILERS
#define CC_PROFILER_DISPLAY_TIMERS() CCProfiler::sharedProfiler()->displayT
imers()
#define CC_PROFILER_PURGE_ALL() CCProfiler::sharedProfiler()->releaseAllTim
ers()
#define CC_PROFILER_START(__name__) CCProfilingBeginTimingBlock(__name__)
#define CC_PROFILER_STOP(__name__) CCProfilingEndTimingBlock(__name__)
#define CC_PROFILER_RESET(__name__) CCProfilingResetTimingBlock(__name__)
#define CC_PROFILER_START_CATEGORY(__cat__, __name__) do{ if(__cat__) CCPro
filingBeginTimingBlock(__name__); } while(0)
#define CC_PROFILER_STOP_CATEGORY(__cat__, __name__) do{ if(__cat__) CCProf
ilingEndTimingBlock(__name__); } while(0)
#define CC_PROFILER_RESET_CATEGORY(__cat__, __name__) do{ if(__cat__) CCPro
filingResetTimingBlock(__name__); } while(0)
#define CC_PROFILER_START_INSTANCE(__id__, __name__) do{ CCProfilingBeginTi
mingBlock( [NSString stringWithFormat:@"%08X - %@", __id__, __name__] ); }
while(0)
#define CC_PROFILER_STOP_INSTANCE(__id__, __name__) do{ CCProfilingEndTimin
gBlock( [NSString stringWithFormat:@"%08X - %@", __id__, __name__] ); }
while(0)
#define CC_PROFILER_RESET_INSTANCE(__id__, __name__) do{ CCProfilingResetTi
mingBlock( [NSString stringWithFormat:@"%08X - %@", __id__, __name__] ); }
while(0)
#else
#define CC_PROFILER_DISPLAY_TIMERS() do {} while (0)
#define CC_PROFILER_PURGE_ALL() do {} while (0)
#define CC_PROFILER_START(__name__) do {} while (0)
#define CC_PROFILER_STOP(__name__) do {} while (0)
#define CC_PROFILER_RESET(__name__) do {} while (0)
#define CC_PROFILER_START_CATEGORY(__cat__, __name__) do {} while(0)
#define CC_PROFILER_STOP_CATEGORY(__cat__, __name__) do {} while(0)
#define CC_PROFILER_RESET_CATEGORY(__cat__, __name__) do {} while(0)
#define CC_PROFILER_START_INSTANCE(__id__, __name__) do {} while(0)
#define CC_PROFILER_STOP_INSTANCE(__id__, __name__) do {} while(0)
#define CC_PROFILER_RESET_INSTANCE(__id__, __name__) do {} while(0)
#endif
#if !defined(COCOS2D_DEBUG) || COCOS2D_DEBUG == 0
#define CHECK_GL_ERROR_DEBUG()
#else
#define CHECK_GL_ERROR_DEBUG() \
do { \
GLenum __error = glGetError(); \
if(__error) { \
CCLog("OpenGL error 0x%04X in %s %s %d\n", __error, __FILE__, _
_FUNCTION__, __LINE__); \
} \
} while (false)
#endif
/** @def CC_INCREMENT_GL_DRAWS_BY_ONE
Increments the GL Draws counts by one.
The number of calls per frame are displayed on the screen when the CCDirec
tor's stats are enabled.
*/
extern unsigned int CC_DLL g_uNumberOfDraws;
#define CC_INCREMENT_GL_DRAWS(__n__) g_uNumberOfDraws += __n__
/*******************/
/** Notifications **/
/*******************/
/** @def CCAnimationFrameDisplayedNotification
Notification name when a CCSpriteFrame is displayed
*/
#define CCAnimationFrameDisplayedNotification "CCAnimationFrameDisplayedNot
ification"
#endif // __CCMACROS_H__ #endif // __CCMACROS_H__
 End of changes. 10 change blocks. 
91 lines changed or deleted 173 lines changed or added


 ccTypes.h   ccTypes.h 
skipping to change at line 30 skipping to change at line 30
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __CCTYPES_H__ #ifndef __CCTYPES_H__
#define __CCTYPES_H__ #define __CCTYPES_H__
#include "CCGeometry.h" #include "cocoa/CCGeometry.h"
#include "CCGL.h" #include "CCGL.h"
namespace cocos2d { NS_CC_BEGIN
/** RGB color composed of bytes 3 bytes /** RGB color composed of bytes 3 bytes
@since v0.8 @since v0.8
*/ */
typedef struct _ccColor3B typedef struct _ccColor3B
{ {
GLubyte r; GLubyte r;
GLubyte g; GLubyte g;
GLubyte b; GLubyte b;
} ccColor3B; } ccColor3B;
//! helper macro that creates an ccColor3B type //! helper macro that creates an ccColor3B type
static inline ccColor3B static inline ccColor3B
ccc3(const GLubyte r, const GLubyte g, const GLubyte b) ccc3(const GLubyte r, const GLubyte g, const GLubyte b)
{ {
ccColor3B c = {r, g, b}; ccColor3B c = {r, g, b};
return c; return c;
} }
//ccColor3B predefined colors //ccColor3B predefined colors
//! White color (255,255,255) //! White color (255,255,255)
static const ccColor3B ccWHITE={255,255,255}; static const ccColor3B ccWHITE={255,255,255};
//! Yellow color (255,255,0) //! Yellow color (255,255,0)
static const ccColor3B ccYELLOW={255,255,0}; static const ccColor3B ccYELLOW={255,255,0};
//! Blue color (0,0,255) //! Blue color (0,0,255)
static const ccColor3B ccBLUE={0,0,255}; static const ccColor3B ccBLUE={0,0,255};
//! Green Color (0,255,0) //! Green Color (0,255,0)
static const ccColor3B ccGREEN={0,255,0}; static const ccColor3B ccGREEN={0,255,0};
skipping to change at line 78 skipping to change at line 77
//! Orange Color (255,127,0) //! Orange Color (255,127,0)
static const ccColor3B ccORANGE={255,127,0}; static const ccColor3B ccORANGE={255,127,0};
//! Gray Color (166,166,166) //! Gray Color (166,166,166)
static const ccColor3B ccGRAY={166,166,166}; static const ccColor3B ccGRAY={166,166,166};
/** RGBA color composed of 4 bytes /** RGBA color composed of 4 bytes
@since v0.8 @since v0.8
*/ */
typedef struct _ccColor4B typedef struct _ccColor4B
{ {
GLubyte r; GLubyte r;
GLubyte g; GLubyte g;
GLubyte b; GLubyte b;
GLubyte a; GLubyte a;
} ccColor4B; } ccColor4B;
//! helper macro that creates an ccColor4B type //! helper macro that creates an ccColor4B type
static inline ccColor4B static inline ccColor4B
ccc4(const GLubyte r, const GLubyte g, const GLubyte b, const GLubyte o) ccc4(const GLubyte r, const GLubyte g, const GLubyte b, const GLubyte o)
{ {
ccColor4B c = {r, g, b, o}; ccColor4B c = {r, g, b, o};
return c; return c;
} }
/** RGBA color composed of 4 floats /** RGBA color composed of 4 floats
@since v0.8 @since v0.8
*/ */
typedef struct _ccColor4F { typedef struct _ccColor4F {
GLfloat r; GLfloat r;
GLfloat g; GLfloat g;
GLfloat b; GLfloat b;
GLfloat a; GLfloat a;
} ccColor4F; } ccColor4F;
/** Returns a ccColor4F from a ccColor3B. Alpha will be 1. /** Returns a ccColor4F from a ccColor3B. Alpha will be 1.
@since v0.99.1 @since v0.99.1
*/ */
static inline ccColor4F ccc4FFromccc3B(ccColor3B c) static inline ccColor4F ccc4FFromccc3B(ccColor3B c)
{ {
ccColor4F c4 = {c.r/255.f, c.g/255.f, c.b/255.f, 1.f}; ccColor4F c4 = {c.r/255.f, c.g/255.f, c.b/255.f, 1.f};
return c4; return c4;
}
//! helper that creates a ccColor4f type
static inline ccColor4F
ccc4f(const GLfloat r, const GLfloat g, const GLfloat b, const GLfloat a)
{
ccColor4F c4 = {r, g, b, a};
return c4;
} }
/** Returns a ccColor4F from a ccColor4B. /** Returns a ccColor4F from a ccColor4B.
@since v0.99.1 @since v0.99.1
*/ */
static inline ccColor4F ccc4FFromccc4B(ccColor4B c) static inline ccColor4F ccc4FFromccc4B(ccColor4B c)
{ {
ccColor4F c4 = {c.r/255.f, c.g/255.f, c.b/255.f, c.a/255.f}; ccColor4F c4 = {c.r/255.f, c.g/255.f, c.b/255.f, c.a/255.f};
return c4; return c4;
} }
/** returns YES if both ccColor4F are equal. Otherwise it returns NO. /** returns YES if both ccColor4F are equal. Otherwise it returns NO.
@since v0.99.1 @since v0.99.1
*/ */
static inline bool ccc4FEqual(ccColor4F a, ccColor4F b) static inline bool ccc4FEqual(ccColor4F a, ccColor4F b)
{ {
return a.r == b.r && a.g == b.g && a.b == b.b && a.a == b.a; return a.r == b.r && a.g == b.g && a.b == b.b && a.a == b.a;
} }
/** A vertex composed of 2 floats: x, y /** A vertex composed of 2 floats: x, y
@since v0.8 @since v0.8
*/ */
typedef struct _ccVertex2F typedef struct _ccVertex2F
{ {
GLfloat x; GLfloat x;
GLfloat y; GLfloat y;
} ccVertex2F; } ccVertex2F;
static inline ccVertex2F vertex2(const float x, const float y) static inline ccVertex2F vertex2(const float x, const float y)
{ {
ccVertex2F c = {x, y}; ccVertex2F c = {x, y};
return c; return c;
} }
/** A vertex composed of 2 floats: x, y /** A vertex composed of 2 floats: x, y
@since v0.8 @since v0.8
*/ */
typedef struct _ccVertex3F typedef struct _ccVertex3F
{ {
GLfloat x; GLfloat x;
GLfloat y; GLfloat y;
GLfloat z; GLfloat z;
} ccVertex3F; } ccVertex3F;
static inline ccVertex3F vertex3(const float x, const float y, const float z) static inline ccVertex3F vertex3(const float x, const float y, const float z)
{ {
ccVertex3F c = {x, y, z}; ccVertex3F c = {x, y, z};
return c; return c;
} }
/** A texcoord composed of 2 floats: u, y /** A texcoord composed of 2 floats: u, y
@since v0.8 @since v0.8
*/ */
typedef struct _ccTex2F { typedef struct _ccTex2F {
GLfloat u; GLfloat u;
GLfloat v; GLfloat v;
} ccTex2F; } ccTex2F;
static inline ccTex2F tex2(const float u, const float v) static inline ccTex2F tex2(const float u, const float v)
{ {
ccTex2F t = {u , v}; ccTex2F t = {u , v};
return t; return t;
} }
//! Point Sprite component //! Point Sprite component
typedef struct _ccPointSprite typedef struct _ccPointSprite
{ {
ccVertex2F pos; // 8 bytes ccVertex2F pos; // 8 bytes
ccColor4B color; // 4 bytes ccColor4B color; // 4 bytes
GLfloat size; // 4 bytes GLfloat size; // 4 bytes
} ccPointSprite; } ccPointSprite;
//! A 2D Quad. 4 * 2 floats //! A 2D Quad. 4 * 2 floats
typedef struct _ccQuad2 { typedef struct _ccQuad2 {
ccVertex2F tl; ccVertex2F tl;
ccVertex2F tr; ccVertex2F tr;
ccVertex2F bl; ccVertex2F bl;
ccVertex2F br; ccVertex2F br;
} ccQuad2; } ccQuad2;
//! A 3D Quad. 4 * 3 floats //! A 3D Quad. 4 * 3 floats
typedef struct _ccQuad3 { typedef struct _ccQuad3 {
ccVertex3F bl; ccVertex3F bl;
ccVertex3F br; ccVertex3F br;
ccVertex3F tl; ccVertex3F tl;
ccVertex3F tr; ccVertex3F tr;
} ccQuad3; } ccQuad3;
//! A 2D grid size //! A 2D grid size
typedef struct _ccGridSize typedef struct _ccGridSize
{ {
int x; int x;
int y; int y;
} ccGridSize; } ccGridSize;
//! helper function to create a ccGridSize //! helper function to create a ccGridSize
static inline ccGridSize static inline ccGridSize
ccg(const int x, const int y) ccg(const int x, const int y)
{ {
ccGridSize v = {x, y}; ccGridSize v = {x, y};
return v; return v;
} }
//! a Point with a vertex point, a tex coord point and a color 4B //! a Point with a vertex point, a tex coord point and a color 4B
typedef struct _ccV2F_C4B_T2F typedef struct _ccV2F_C4B_T2F
{ {
//! vertices (2F) //! vertices (2F)
ccVertex2F vertices; ccVertex2F vertices;
//! colors (4B) //! colors (4B)
ccColor4B colors; ccColor4B colors;
//! tex coords (2F) //! tex coords (2F)
ccTex2F texCoords; ccTex2F texCoords;
} ccV2F_C4B_T2F; } ccV2F_C4B_T2F;
//! a Point with a vertex point, a tex coord point and a color 4F //! a Point with a vertex point, a tex coord point and a color 4F
typedef struct _ccV2F_C4F_T2F typedef struct _ccV2F_C4F_T2F
{ {
//! vertices (2F) //! vertices (2F)
ccVertex2F vertices; ccVertex2F vertices;
//! colors (4F) //! colors (4F)
ccColor4F colors; ccColor4F colors;
//! tex coords (2F) //! tex coords (2F)
ccTex2F texCoords; ccTex2F texCoords;
} ccV2F_C4F_T2F; } ccV2F_C4F_T2F;
//! a Point with a vertex point, a tex coord point and a color 4B //! a Point with a vertex point, a tex coord point and a color 4B
typedef struct _ccV3F_C4B_T2F typedef struct _ccV3F_C4B_T2F
{ {
//! vertices (3F) //! vertices (3F)
ccVertex3F vertices; // 12 bytes ccVertex3F vertices; // 12 bytes
// char __padding__[4]; // char __padding__[4];
//! colors (4B) //! colors (4B)
ccColor4B colors; // 4 bytes ccColor4B colors; // 4 bytes
// char __padding2__[4]; // char __padding2__[4];
// tex coords (2F) // tex coords (2F)
ccTex2F texCoords; // 8 byts ccTex2F texCoords; // 8 byts
} ccV3F_C4B_T2F; } ccV3F_C4B_T2F;
//! 4 ccVertex2FTex2FColor4B Quad //! 4 ccVertex2FTex2FColor4B Quad
typedef struct _ccV2F_C4B_T2F_Quad typedef struct _ccV2F_C4B_T2F_Quad
{ {
//! bottom left //! bottom left
ccV2F_C4B_T2F bl; ccV2F_C4B_T2F bl;
//! bottom right //! bottom right
ccV2F_C4B_T2F br; ccV2F_C4B_T2F br;
//! top left //! top left
ccV2F_C4B_T2F tl; ccV2F_C4B_T2F tl;
//! top right //! top right
ccV2F_C4B_T2F tr; ccV2F_C4B_T2F tr;
} ccV2F_C4B_T2F_Quad; } ccV2F_C4B_T2F_Quad;
//! 4 ccVertex3FTex2FColor4B //! 4 ccVertex3FTex2FColor4B
typedef struct _ccV3F_C4B_T2F_Quad typedef struct _ccV3F_C4B_T2F_Quad
{ {
//! top left //! top left
ccV3F_C4B_T2F tl; ccV3F_C4B_T2F tl;
//! bottom left //! bottom left
ccV3F_C4B_T2F bl; ccV3F_C4B_T2F bl;
//! top right //! top right
ccV3F_C4B_T2F tr; ccV3F_C4B_T2F tr;
//! bottom right //! bottom right
ccV3F_C4B_T2F br; ccV3F_C4B_T2F br;
} ccV3F_C4B_T2F_Quad; } ccV3F_C4B_T2F_Quad;
//! 4 ccVertex2FTex2FColor4F Quad //! 4 ccVertex2FTex2FColor4F Quad
typedef struct _ccV2F_C4F_T2F_Quad typedef struct _ccV2F_C4F_T2F_Quad
{ {
//! bottom left //! bottom left
ccV2F_C4F_T2F bl; ccV2F_C4F_T2F bl;
//! bottom right //! bottom right
ccV2F_C4F_T2F br; ccV2F_C4F_T2F br;
//! top left //! top left
ccV2F_C4F_T2F tl; ccV2F_C4F_T2F tl;
//! top right //! top right
ccV2F_C4F_T2F tr; ccV2F_C4F_T2F tr;
} ccV2F_C4F_T2F_Quad; } ccV2F_C4F_T2F_Quad;
//! Blend Function used for textures //! Blend Function used for textures
typedef struct _ccBlendFunc typedef struct _ccBlendFunc
{ {
//! source blend function //! source blend function
GLenum src; GLenum src;
//! destination blend function //! destination blend function
GLenum dst; GLenum dst;
} ccBlendFunc; } ccBlendFunc;
//! delta time type // XXX: If any of these enums are edited and/or reordered, udpate CCTexture
//! if you want more resolution redefine it as a double 2D.m
typedef float ccTime; //! Vertical text alignment type
//typedef double ccTime; typedef enum
{
kCCVerticalTextAlignmentTop,
kCCVerticalTextAlignmentCenter,
kCCVerticalTextAlignmentBottom,
} CCVerticalTextAlignment;
// XXX: If any of these enums are edited and/or reordered, udpate CCTexture
2D.m
//! Horizontal text alignment type
typedef enum typedef enum
{ {
CCTextAlignmentLeft, kCCTextAlignmentLeft,
CCTextAlignmentCenter, kCCTextAlignmentCenter,
CCTextAlignmentRight, kCCTextAlignmentRight,
} CCTextAlignment; } CCTextAlignment;
}//namespace cocos2d // types for animation in particle systems
// texture coordinates for a quad
typedef struct _ccT2F_Quad
{
//! bottom left
ccTex2F bl;
//! bottom right
ccTex2F br;
//! top left
ccTex2F tl;
//! top right
ccTex2F tr;
} ccT2F_Quad;
// struct that holds the size in pixels, texture coordinates and delays for
animated CCParticleSystemQuad
typedef struct
{
ccT2F_Quad texCoords;
float delay;
CCSize size;
} ccAnimationFrameData;
NS_CC_END
#endif //__CCTYPES_H__ #endif //__CCTYPES_H__
 End of changes. 35 change blocks. 
110 lines changed or deleted 149 lines changed or added


 ccUtils.h   ccUtils.h 
skipping to change at line 31 skipping to change at line 31
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __SUPPORT_CC_UTILS_H__ #ifndef __SUPPORT_CC_UTILS_H__
#define __SUPPORT_CC_UTILS_H__ #define __SUPPORT_CC_UTILS_H__
/** @file ccUtils.h /** @file ccUtils.h
Misc free functions Misc free functions
*/ */
namespace cocos2d namespace cocos2d {
{ /*
/* ccNextPOT function is licensed under the same license that is used in CCTex
ccNextPOT function is licensed under the same license that is used i ture2D.m.
n CCTexture2D.m. */
*/
/** returns the Next Power of Two value.
/** returns the Next Power of Two value.
Examples:
Examples: - If "value" is 15, it will return 16.
- If "value" is 15, it will return 16. - If "value" is 16, it will return 16.
- If "value" is 16, it will return 16. - If "value" is 17, it will return 32.
- If "value" is 17, it will return 32.
@since v0.99.5
*/
@since v0.99.5 unsigned long ccNextPOT( unsigned long value );
*/
unsigned long ccNextPOT( unsigned long value );
} }
#endif // __SUPPORT_CC_UTILS_H__ #endif // __SUPPORT_CC_UTILS_H__
 End of changes. 3 change blocks. 
16 lines changed or deleted 16 lines changed or added


 chipmunk.h   chipmunk.h 
skipping to change at line 25 skipping to change at line 25
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * 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 I N THE * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS I N THE
* SOFTWARE. * SOFTWARE.
*/ */
#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 1 #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 *message, const char *condition, const char *file , int line, int isError); void cpMessage(const char *condition, const char *file, int line, int isErr or, int isHardError, const char *message, ...);
#ifdef NDEBUG #ifdef NDEBUG
#define cpAssertWarn(condition, message) #define cpAssertWarn(condition, ...)
#else #else
#define cpAssertWarn(condition, message) if(!(condition)) cpMessage( message, #condition, __FILE__, __LINE__, 0) #define cpAssertWarn(condition, ...) if(!(condition)) cpMessage(#con dition, __FILE__, __LINE__, 0, 0, __VA_ARGS__)
#endif #endif
#ifdef NDEBUG #ifdef NDEBUG
#define cpAssert(condition, message) #define cpAssertSoft(condition, ...)
#else #else
#define cpAssert(condition, message) if(!(condition)) cpMessage(mess age, #condition, __FILE__, __LINE__, 1) #define cpAssertSoft(condition, ...) if(!(condition)) cpMessage(#con dition, __FILE__, __LINE__, 1, 0, __VA_ARGS__)
#endif #endif
// Hard assertions are important and cheap to execute. They are not disable
d by compiling as debug.
#define cpAssertHard(condition, ...) if(!(condition)) cpMessage(#condition,
__FILE__, __LINE__, 1, 1, __VA_ARGS__)
#include "chipmunk_types.h" #include "chipmunk_types.h"
// Maximum allocated size for various Chipmunk buffers /// @defgroup misc Misc
#define CP_BUFFER_BYTES (32*1024) /// @{
/// Allocated size for various Chipmunk buffers
#ifndef CP_BUFFER_BYTES
#define CP_BUFFER_BYTES (32*1024)
#endif
#ifndef cpcalloc
/// Chipmunk calloc() alias.
#define cpcalloc calloc
#endif
#ifndef cprealloc
/// Chipmunk realloc() alias.
#define cprealloc realloc
#endif
#ifndef cpfree
/// Chipmunk free() alias.
#define cpfree free
#endif
typedef struct cpArray cpArray;
typedef struct cpHashSet cpHashSet;
typedef struct cpBody cpBody;
typedef struct cpShape cpShape;
typedef struct cpConstraint cpConstraint;
#define cpmalloc malloc typedef struct cpCollisionHandler cpCollisionHandler;
#define cpcalloc calloc typedef struct cpArbiter cpArbiter;
#define cprealloc realloc
#define cpfree free typedef struct cpSpace cpSpace;
#include "cpVect.h" #include "cpVect.h"
#include "cpBB.h" #include "cpBB.h"
#include "cpArray.h" #include "cpSpatialIndex.h"
#include "cpHashSet.h"
#include "cpSpaceHash.h"
#include "cpBody.h" #include "cpBody.h"
#include "cpShape.h" #include "cpShape.h"
#include "cpPolyShape.h" #include "cpPolyShape.h"
#include "cpArbiter.h" #include "cpArbiter.h"
#include "cpCollision.h"
#include "constraints/cpConstraint.h" #include "constraints/cpConstraint.h"
#include "cpSpace.h" #include "cpSpace.h"
#define CP_HASH_COEF (3344921057ul) // Chipmunk 6.1.1
#define CP_HASH_PAIR(A, B) ((cpHashValue)(A)*CP_HASH_COEF ^ (cpHashValue)(B #define CP_VERSION_MAJOR 6
)*CP_HASH_COEF) #define CP_VERSION_MINOR 1
#define CP_VERSION_RELEASE 1
/// Version string.
extern const char *cpVersionString; extern const char *cpVersionString;
/// @deprecated
void cpInitChipmunk(void); void cpInitChipmunk(void);
/** /// Calculate the moment of inertia for a circle.
Calculate the moment of inertia for a circle. /// @c r1 and @c r2 are the inner and outer diameters. A solid circle has a
r1 and r2 are the inner and outer diameters. A solid circle has an i n inner diameter of 0.
nner diameter of 0.
*/
cpFloat cpMomentForCircle(cpFloat m, cpFloat r1, cpFloat r2, cpVect offset) ; cpFloat cpMomentForCircle(cpFloat m, cpFloat r1, cpFloat r2, cpVect offset) ;
/** /// Calculate area of a hollow circle.
Calculate area of a hollow circle. /// @c r1 and @c r2 are the inner and outer diameters. A solid circle has a
*/ n inner diameter of 0.
cpFloat cpAreaForCircle(cpFloat r1, cpFloat r2); cpFloat cpAreaForCircle(cpFloat r1, cpFloat r2);
/** /// Calculate the moment of inertia for a line segment.
Calculate the moment of inertia for a line segment. /// Beveling radius is not supported.
Beveling radius is not supported.
*/
cpFloat cpMomentForSegment(cpFloat m, cpVect a, cpVect b); cpFloat cpMomentForSegment(cpFloat m, cpVect a, cpVect b);
/** /// Calculate the area of a fattened (capsule shaped) line segment.
Calculate the area of a fattened (capsule shaped) line segment.
*/
cpFloat cpAreaForSegment(cpVect a, cpVect b, cpFloat r); cpFloat cpAreaForSegment(cpVect a, cpVect b, cpFloat r);
/** /// Calculate the moment of inertia for a solid polygon shape assuming it's
Calculate the moment of inertia for a solid polygon shape assuming i center of gravity is at it's centroid. The offset is added to each vertex.
t's center of gravity is at it's centroid. The offset is added to each vert
ex.
*/
cpFloat cpMomentForPoly(cpFloat m, int numVerts, const cpVect *verts, cpVec t offset); cpFloat cpMomentForPoly(cpFloat m, int numVerts, const cpVect *verts, cpVec t offset);
/** /// Calculate the signed area of a polygon. A Clockwise winding gives posit
Calculate the signed area of a polygon. ive area.
*/ /// This is probably backwards from what you expect, but matches Chipmunk's
the winding for poly shapes.
cpFloat cpAreaForPoly(const int numVerts, const cpVect *verts); cpFloat cpAreaForPoly(const int numVerts, const cpVect *verts);
/** /// Calculate the natural centroid of a polygon.
Calculate the natural centroid of a polygon.
*/
cpVect cpCentroidForPoly(const int numVerts, const cpVect *verts); cpVect cpCentroidForPoly(const int numVerts, const cpVect *verts);
/** /// Center the polygon on the origin. (Subtracts the centroid of the polygo
Center the polygon on the origin. (Subtracts the centroid of the pol n from each vertex)
ygon from each vertex)
*/
void cpRecenterPoly(const int numVerts, cpVect *verts); void cpRecenterPoly(const int numVerts, cpVect *verts);
/** /// Calculate the moment of inertia for a solid box.
Calculate the moment of inertia for a solid box.
*/
cpFloat cpMomentForBox(cpFloat m, cpFloat width, cpFloat height); cpFloat cpMomentForBox(cpFloat m, cpFloat width, cpFloat height);
/// Calculate the moment of inertia for a solid box.
cpFloat cpMomentForBox2(cpFloat m, cpBB box);
/// Calculate the convex hull of a given set of points. Returns the count o
f 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, cpFl
oat 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 heav
y functions.
// Collision handlers are post-step callbacks are not included to avoid mem
ory management issues.
// If you want to use blocks for those and are aware of how to correctly ma
nage 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 *co
nstraint));
void cpBodyEachShape_b(cpBody *body, void (^block)(cpShape *shape));
void cpBodyEachConstraint_b(cpBody *body, void (^block)(cpConstraint *const
raint));
void cpBodyEachArbiter_b(cpBody *body, void (^block)(cpArbiter *arbiter));
typedef void (^cpSpaceNearestPointQueryBlock)(cpShape *shape, cpFloat dista
nce, cpVect point);
void cpSpaceNearestPointQuery_b(cpSpace *space, cpVect point, cpFloat maxDi
stance, cpLayers layers, cpGroup group, cpSpaceNearestPointQueryBlock block
);
typedef void (^cpSpaceSegmentQueryBlock)(cpShape *shape, cpFloat t, cpVect
n);
void cpSpaceSegmentQuery_b(cpSpace *space, cpVect start, cpVect end, cpLaye
rs layers, cpGroup group, cpSpaceSegmentQueryBlock block);
typedef void (^cpSpaceBBQueryBlock)(cpShape *shape);
void cpSpaceBBQuery_b(cpSpace *space, cpBB bb, cpLayers layers, cpGroup gro
up, cpSpaceBBQueryBlock block);
typedef void (^cpSpaceShapeQueryBlock)(cpShape *shape, cpContactPointSet *p
oints);
cpBool cpSpaceShapeQuery_b(cpSpace *space, cpShape *shape, cpSpaceShapeQuer
yBlock block);
#endif
#endif
//@}
#ifdef __cplusplus #ifdef __cplusplus
} }
static inline cpVect operator *(const cpVect v, const cpFloat s){return cpv mult(v, s);} static inline cpVect operator *(const cpVect v, const cpFloat s){return cpv mult(v, s);}
static inline cpVect operator +(const cpVect v1, const cpVect v2){return cp vadd(v1, v2);} static inline cpVect operator +(const cpVect v1, const cpVect v2){return cp vadd(v1, v2);}
static inline cpVect operator -(const cpVect v1, const cpVect v2){return cp vsub(v1, v2);} static inline cpVect operator -(const cpVect v1, const cpVect v2){return cp vsub(v1, v2);}
static inline cpBool operator ==(const cpVect v1, const cpVect v2){return c pveql(v1, v2);} static inline cpBool operator ==(const cpVect v1, const cpVect v2){return c pveql(v1, v2);}
static inline cpVect operator -(const cpVect v){return cpvneg(v);} static inline cpVect operator -(const cpVect v){return cpvneg(v);}
#endif #endif
#endif #endif
 End of changes. 26 change blocks. 
54 lines changed or deleted 148 lines changed or added


 chipmunk_ffi.h   chipmunk_ffi.h 
#ifdef CHIPMUNK_FFI
// Create non static inlined copies of Chipmunk functions, useful for worki ng with dynamic FFIs // Create non static inlined copies of Chipmunk functions, useful for worki ng with dynamic FFIs
// This file should only be included in chipmunk.c // This file should only be included in chipmunk.c
#ifndef _CHIPMUNK_FFI_H_
#define _CHIPMUNK_FFI_H_
#ifdef _MSC_VER #ifdef _MSC_VER
#if _MSC_VER >= 1600 #if _MSC_VER >= 1600
#define MAKE_REF(name) decltype(name) *_##name = name #define MAKE_REF(name) decltype(name) *_##name = name
#else #else
#define MAKE_REF(name) #define MAKE_REF(name)
#endif #endif
#else #else
#define MAKE_REF(name) __typeof__(name) *_##name = name #define MAKE_REF(name) __typeof__(name) *_##name = name
#endif #endif
#define MAKE_PROPERTIES_REF(struct, property) \
MAKE_REF(struct##Get##property); MAKE_REF(struct##Set##property);
MAKE_REF(cpv); // makes a variable named _cpv that contains the function po inter for cpv() MAKE_REF(cpv); // makes a variable named _cpv that contains the function po inter for cpv()
MAKE_REF(cpveql); MAKE_REF(cpveql);
MAKE_REF(cpvadd); MAKE_REF(cpvadd);
MAKE_REF(cpvneg); MAKE_REF(cpvneg);
MAKE_REF(cpvsub); MAKE_REF(cpvsub);
MAKE_REF(cpvmult); MAKE_REF(cpvmult);
MAKE_REF(cpvdot); MAKE_REF(cpvdot);
MAKE_REF(cpvcross); MAKE_REF(cpvcross);
MAKE_REF(cpvperp); MAKE_REF(cpvperp);
MAKE_REF(cpvrperp); MAKE_REF(cpvrperp);
skipping to change at line 40 skipping to change at line 42
MAKE_REF(cpvlengthsq); MAKE_REF(cpvlengthsq);
MAKE_REF(cpvlerp); MAKE_REF(cpvlerp);
MAKE_REF(cpvnormalize); MAKE_REF(cpvnormalize);
MAKE_REF(cpvnormalize_safe); MAKE_REF(cpvnormalize_safe);
MAKE_REF(cpvclamp); MAKE_REF(cpvclamp);
MAKE_REF(cpvlerpconst); MAKE_REF(cpvlerpconst);
MAKE_REF(cpvdist); MAKE_REF(cpvdist);
MAKE_REF(cpvdistsq); MAKE_REF(cpvdistsq);
MAKE_REF(cpvnear); MAKE_REF(cpvnear);
MAKE_REF(cpBBNew); MAKE_REF(cpfmax);
MAKE_REF(cpBBintersects); MAKE_REF(cpfmin);
MAKE_REF(cpBBcontainsBB); MAKE_REF(cpfabs);
MAKE_REF(cpBBcontainsVect); MAKE_REF(cpfclamp);
MAKE_REF(cpBBmerge); MAKE_REF(cpflerp);
MAKE_REF(cpBBexpand); MAKE_REF(cpflerpconst);
MAKE_REF(cpBodyWorld2Local); MAKE_REF(cpBBNew);
MAKE_REF(cpBodyLocal2World); MAKE_REF(cpBBNewForCircle);
MAKE_REF(cpBodyApplyImpulse); MAKE_REF(cpBBIntersects);
MAKE_REF(cpBBContainsBB);
MAKE_REF(cpBBContainsVect);
MAKE_REF(cpBBMerge);
MAKE_REF(cpBBExpand);
MAKE_REF(cpBBArea);
MAKE_REF(cpBBMergedArea);
MAKE_REF(cpBBSegmentQuery);
MAKE_REF(cpBBIntersectsSegment);
MAKE_REF(cpBodyGetMass);
MAKE_REF(cpBodyGetMoment);
MAKE_REF(cpBodyGetPos);
MAKE_REF(cpBodyGetAngle);
MAKE_REF(cpBodyGetRot);
MAKE_PROPERTIES_REF(cpBody, Vel);
MAKE_PROPERTIES_REF(cpBody, Force);
MAKE_PROPERTIES_REF(cpBody, AngVel);
MAKE_PROPERTIES_REF(cpBody, Torque);
MAKE_PROPERTIES_REF(cpBody, VelLimit);
MAKE_PROPERTIES_REF(cpBody, AngVelLimit);
MAKE_PROPERTIES_REF(cpBody, UserData);
MAKE_REF(cpBodyIsSleeping); MAKE_REF(cpBodyIsSleeping);
MAKE_REF(cpBodyIsStatic);
MAKE_REF(cpBodyIsRogue); MAKE_REF(cpBodyIsRogue);
MAKE_REF(cpBodyLocal2World);
MAKE_REF(cpBodyWorld2Local);
MAKE_REF(cpBodyKineticEnergy); MAKE_REF(cpBodyKineticEnergy);
MAKE_REF(cpArbiterIsFirstContact); MAKE_REF(cpShapeGetBB);
MAKE_PROPERTIES_REF(cpShape, Body);
MAKE_PROPERTIES_REF(cpShape, Sensor);
MAKE_PROPERTIES_REF(cpShape, Elasticity);
MAKE_PROPERTIES_REF(cpShape, Friction);
MAKE_PROPERTIES_REF(cpShape, SurfaceVelocity);
MAKE_PROPERTIES_REF(cpShape, UserData);
MAKE_PROPERTIES_REF(cpShape, CollisionType);
MAKE_PROPERTIES_REF(cpShape, Group);
MAKE_PROPERTIES_REF(cpShape, Layers);
MAKE_REF(cpArbiterGetShapes); MAKE_REF(cpArbiterGetShapes);
MAKE_REF(cpArbiterGetNormal); MAKE_REF(cpArbiterGetBodies);
MAKE_REF(cpArbiterGetPoint); MAKE_REF(cpArbiterIsFirstContact);
MAKE_REF(cpArbiterGetCount);
MAKE_REF(cpConstraintGetA);
MAKE_REF(cpConstraintGetB);
MAKE_PROPERTIES_REF(cpConstraint, MaxForce);
MAKE_PROPERTIES_REF(cpConstraint, ErrorBias);
MAKE_PROPERTIES_REF(cpConstraint, MaxBias);
MAKE_PROPERTIES_REF(cpConstraint, UserData);
MAKE_REF(cpConstraintGetImpulse); MAKE_REF(cpConstraintGetImpulse);
MAKE_PROPERTIES_REF(cpDampedRotarySpring, RestAngle);
MAKE_PROPERTIES_REF(cpDampedRotarySpring, Stiffness);
MAKE_PROPERTIES_REF(cpDampedRotarySpring, Damping);
//MAKE_PROPERTIES_REF(cpDampedRotarySpring, SpringTorqueFunc);
MAKE_PROPERTIES_REF(cpDampedSpring, Anchr1);
MAKE_PROPERTIES_REF(cpDampedSpring, Anchr2);
MAKE_PROPERTIES_REF(cpDampedSpring, RestLength);
MAKE_PROPERTIES_REF(cpDampedSpring, Stiffness);
MAKE_PROPERTIES_REF(cpDampedSpring, Damping);
//MAKE_PROPERTIES_REF(cpDampedSpring, SpringForceFunc);
MAKE_PROPERTIES_REF(cpGearJoint, Phase);
MAKE_REF(cpGearJointGetRatio);
MAKE_PROPERTIES_REF(cpGrooveJoint, Anchr2);
MAKE_REF(cpGrooveJointGetGrooveA);
MAKE_REF(cpGrooveJointGetGrooveB);
MAKE_PROPERTIES_REF(cpPinJoint, Anchr1);
MAKE_PROPERTIES_REF(cpPinJoint, Anchr2);
MAKE_PROPERTIES_REF(cpPinJoint, Dist);
MAKE_PROPERTIES_REF(cpPivotJoint, Anchr1);
MAKE_PROPERTIES_REF(cpPivotJoint, Anchr2);
MAKE_PROPERTIES_REF(cpRatchetJoint, Angle);
MAKE_PROPERTIES_REF(cpRatchetJoint, Phase);
MAKE_PROPERTIES_REF(cpRatchetJoint, Ratchet);
MAKE_PROPERTIES_REF(cpRotaryLimitJoint, Min);
MAKE_PROPERTIES_REF(cpRotaryLimitJoint, Max);
MAKE_PROPERTIES_REF(cpSimpleMotor, Rate);
MAKE_PROPERTIES_REF(cpSlideJoint, Anchr1);
MAKE_PROPERTIES_REF(cpSlideJoint, Anchr2);
MAKE_PROPERTIES_REF(cpSlideJoint, Min);
MAKE_PROPERTIES_REF(cpSlideJoint, Max);
MAKE_REF(cpSegmentQueryHitPoint); MAKE_REF(cpSegmentQueryHitPoint);
MAKE_REF(cpSegmentQueryHitDist); MAKE_REF(cpSegmentQueryHitDist);
#endif // _CHIPMUNK_FFI_H_ MAKE_REF(cpSpatialIndexDestroy);
MAKE_REF(cpSpatialIndexCount);
MAKE_REF(cpSpatialIndexEach);
MAKE_REF(cpSpatialIndexContains);
MAKE_REF(cpSpatialIndexInsert);
MAKE_REF(cpSpatialIndexRemove);
MAKE_REF(cpSpatialIndexReindex);
MAKE_REF(cpSpatialIndexReindexObject);
MAKE_REF(cpSpatialIndexSegmentQuery);
MAKE_REF(cpSpatialIndexQuery);
MAKE_REF(cpSpatialIndexReindexQuery);
MAKE_PROPERTIES_REF(cpSpace, Iterations);
MAKE_PROPERTIES_REF(cpSpace, Gravity);
MAKE_PROPERTIES_REF(cpSpace, Damping);
MAKE_PROPERTIES_REF(cpSpace, IdleSpeedThreshold);
MAKE_PROPERTIES_REF(cpSpace, SleepTimeThreshold);
MAKE_PROPERTIES_REF(cpSpace, CollisionSlop);
MAKE_PROPERTIES_REF(cpSpace, CollisionBias);
MAKE_PROPERTIES_REF(cpSpace, CollisionPersistence);
MAKE_PROPERTIES_REF(cpSpace, EnableContactGraph);
MAKE_PROPERTIES_REF(cpSpace, UserData);
MAKE_REF(cpSpaceGetStaticBody);
MAKE_REF(cpSpaceGetCurrentTimeStep);
MAKE_REF(cpSpaceIsLocked);
#endif
 End of changes. 12 change blocks. 
15 lines changed or deleted 98 lines changed or added


 chipmunk_private.h   chipmunk_private.h 
skipping to change at line 22 skipping to change at line 22
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * 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 I N THE * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS I N THE
* SOFTWARE. * SOFTWARE.
*/ */
#ifndef _CHIPMUNK_PRIVATE_H_
#define _CHIPMUNK_PRIVATE_H_
#define CP_ALLOW_PRIVATE_ACCESS 1 #define CP_ALLOW_PRIVATE_ACCESS 1
#include "chipmunk.h" #include "chipmunk.h"
void *cpSpaceGetPostStepData(cpSpace *space, void *obj); #define CP_HASH_COEF (3344921057ul)
#define CP_HASH_PAIR(A, B) ((cpHashValue)(A)*CP_HASH_COEF ^ (cpHashValue)(B
)*CP_HASH_COEF)
//MARK: cpArray
struct cpArray {
int num, max;
void **arr;
};
cpArray *cpArrayNew(int size);
void cpArrayFree(cpArray *arr);
void cpArrayPush(cpArray *arr, void *object);
void *cpArrayPop(cpArray *arr);
void cpArrayDeleteObj(cpArray *arr, void *obj);
cpBool cpArrayContains(cpArray *arr, void *ptr);
void cpArrayFreeEach(cpArray *arr, void (freeFunc)(void*));
//MARK: Foreach loops
static inline cpConstraint *
cpConstraintNext(cpConstraint *node, cpBody *body)
{
return (node->a == body ? node->next_a : node->next_b);
}
#define CP_BODY_FOREACH_CONSTRAINT(bdy, var)\
for(cpConstraint *var = bdy->constraintList; var; var = cpConstraint
Next(var, bdy))
static inline cpArbiter *
cpArbiterNext(cpArbiter *node, cpBody *body)
{
return (node->body_a == body ? node->thread_a.next : node->thread_b.
next);
}
#define CP_BODY_FOREACH_ARBITER(bdy, var)\
for(cpArbiter *var = bdy->arbiterList; var; var = cpArbiterNext(var,
bdy))
#define CP_BODY_FOREACH_SHAPE(body, var)\
for(cpShape *var = body->shapeList; var; var = var->next)
#define CP_BODY_FOREACH_COMPONENT(root, var)\
for(cpBody *var = root; var; var = var->node.next)
//MARK: cpHashSet
typedef cpBool (*cpHashSetEqlFunc)(void *ptr, void *elt);
typedef void *(*cpHashSetTransFunc)(void *ptr, void *data);
cpHashSet *cpHashSetNew(int size, cpHashSetEqlFunc eqlFunc);
void cpHashSetSetDefaultValue(cpHashSet *set, void *default_value);
void cpHashSetFree(cpHashSet *set);
int cpHashSetCount(cpHashSet *set);
void *cpHashSetInsert(cpHashSet *set, cpHashValue hash, void *ptr, void *da
ta, cpHashSetTransFunc trans);
void *cpHashSetRemove(cpHashSet *set, cpHashValue hash, void *ptr);
void *cpHashSetFind(cpHashSet *set, cpHashValue hash, void *ptr);
typedef void (*cpHashSetIteratorFunc)(void *elt, void *data);
void cpHashSetEach(cpHashSet *set, cpHashSetIteratorFunc func, void *data);
typedef cpBool (*cpHashSetFilterFunc)(void *elt, void *data);
void cpHashSetFilter(cpHashSet *set, cpHashSetFilterFunc func, void *data);
//MARK: Body Functions
void cpBodyAddShape(cpBody *body, cpShape *shape);
void cpBodyRemoveShape(cpBody *body, cpShape *shape);
void cpBodyRemoveConstraint(cpBody *body, cpConstraint *constraint);
//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 *bod
y);
static inline cpBool
cpShapeActive(cpShape *shape)
{
return shape->prev || (shape->body && shape->body->shapeList == shap
e);
}
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 th
is 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
cpPolyShapeValueOnAxis(const cpPolyShape *poly, const cpVect n, const cpFlo
at d)
{
cpVect *verts = poly->tVerts;
cpFloat min = cpvdot(n, verts[0]);
for(int i=1; i<poly->numVerts; i++){
min = cpfmin(min, cpvdot(n, verts[i]));
}
return min - d;
}
static inline cpBool
cpPolyShapeContainsVert(const cpPolyShape *poly, const cpVect v)
{
cpSplittingPlane *planes = poly->tPlanes;
for(int i=0; i<poly->numVerts; i++){
cpFloat dist = cpSplittingPlaneCompare(planes[i], v);
if(dist > 0.0f) return cpFalse;
}
return cpTrue;
}
static inline cpBool
cpPolyShapeContainsVertPartial(const cpPolyShape *poly, const cpVect v, con
st cpVect n)
{
cpSplittingPlane *planes = poly->tPlanes;
for(int i=0; i<poly->numVerts; i++){
if(cpvdot(planes[i].n, n) < 0.0f) continue;
cpFloat dist = cpSplittingPlaneCompare(planes[i], v);
if(dist > 0.0f) return cpFalse;
}
return cpTrue;
}
//MARK: Spatial Index Functions
cpSpatialIndex *cpSpatialIndexInit(cpSpatialIndex *index, cpSpatialIndexCla
ss *klass, cpSpatialIndexBBFunc bbfunc, cpSpatialIndex *staticIndex);
//MARK: Space Functions
extern cpCollisionHandler cpDefaultCollisionHandler;
void cpSpaceProcessComponents(cpSpace *space, cpFloat dt);
void cpSpacePushFreshContactBuffer(cpSpace *space);
cpContact *cpContactBufferGetArray(cpSpace *space);
void cpSpacePushContacts(cpSpace *space, int count);
void *cpSpaceGetPostStepData(cpSpace *space, void *key);
cpBool cpSpaceArbiterSetFilter(cpArbiter *arb, cpSpace *space);
void cpSpaceFilterArbiters(cpSpace *space, cpBody *body, cpShape *filter);
void cpSpaceActivateBody(cpSpace *space, cpBody *body); void cpSpaceActivateBody(cpSpace *space, cpBody *body);
void cpSpaceLock(cpSpace *space);
void cpSpaceUnlock(cpSpace *space, cpBool runPostStep);
static inline void static inline cpCollisionHandler *
cpSpaceLock(cpSpace *space) cpSpaceLookupHandler(cpSpace *space, cpCollisionType a, cpCollisionType b)
{ {
space->locked++; cpCollisionType types[] = {a, b};
return (cpCollisionHandler *)cpHashSetFind(space->collisionHandlers,
CP_HASH_PAIR(a, b), types);
} }
static inline void static inline void
cpSpaceUnlock(cpSpace *space) cpSpaceUncacheArbiter(cpSpace *space, cpArbiter *arb)
{ {
space->locked--; cpShape *a = arb->a, *b = arb->b;
cpAssert(space->locked >= 0, "Internal error:Space lock underflow.") cpShape *shape_pair[] = {a, b};
; cpHashValue arbHashID = CP_HASH_PAIR((cpHashValue)a, (cpHashValue)b)
;
cpHashSetRemove(space->cachedArbiters, arbHashID, shape_pair);
cpArrayDeleteObj(space->arbiters, arb);
}
if(!space->locked){ void cpShapeUpdateFunc(cpShape *shape, void *unused);
cpArray *waking = space->rousedBodies; void cpSpaceCollideShapes(cpShape *a, cpShape *b, cpSpace *space);
for(int i=0, count=waking->num; i<count; i++){
cpSpaceActivateBody(space, (cpBody *)waking->arr[i])
;
}
waking->num = 0; //MARK: Arbiters
}
struct cpContact {
cpVect p, n;
cpFloat dist;
cpVect r1, r2;
cpFloat nMass, tMass, bounce;
cpFloat jnAcc, jtAcc, jBias;
cpFloat bias;
cpHashValue hash;
};
cpContact* cpContactInit(cpContact *con, cpVect p, cpVect n, cpFloat dist,
cpHashValue hash);
cpArbiter* cpArbiterInit(cpArbiter *arb, cpShape *a, cpShape *b);
static inline void
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.
cpCollisionHandler *handler = cpSpaceLookupHandler(space, arb->a->co
llision_type, arb->b->collision_type);
handler->separate(arb, space, handler->data);
} }
#endif static inline struct cpArbiterThread *
cpArbiterThreadForBody(cpArbiter *arb, cpBody *body)
{
return (arb->body_a == body ? &arb->thread_a : &arb->thread_b);
}
void cpArbiterUnthread(cpArbiter *arb);
void cpArbiterUpdate(cpArbiter *arb, cpContact *contacts, int numContacts,
struct cpCollisionHandler *handler, cpShape *a, cpShape *b);
void cpArbiterPreStep(cpArbiter *arb, cpFloat dt, cpFloat bias, cpFloat slo
p);
void cpArbiterApplyCachedImpulse(cpArbiter *arb, cpFloat dt_coef);
void cpArbiterApplyImpulse(cpArbiter *arb);
 End of changes. 10 change blocks. 
19 lines changed or deleted 225 lines changed or added


 chipmunk_types.h   chipmunk_types.h 
#ifndef _CHIPMUNK_TYPES_H_ #include <math.h>
#define _CHIPMUNK_TYPES_H_
#ifndef WIN32
#include <stdint.h>
#endif
#ifdef __APPLE__ #ifdef __APPLE__
#ifndef AIRPLAYUSECHIPMUNK
#import "TargetConditionals.h" #import "TargetConditionals.h"
#endif #endif
#endif
// cocos2d-x: dont' use CGPoints to make your code multi-platform #if (TARGET_OS_IPHONE == 1) || (TARGET_OS_MAC == 1) && (!defined CP_USE_CGP
// #if (defined TARGET_OS_IPHONE) && (!defined CP_USE_CGPOINTS) OINTS)
// #define CP_USE_CGPOINTS #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
// cocos2d-x: GL_DOUBLE isn't support on all platforms #define CP_USE_DOUBLES 1
// #define CP_USE_DOUBLES 1
#endif #endif
/// @defgroup basicTypes Basic Types
/// Most of these types can be configured at compile time.
/// @{
#if CP_USE_DOUBLES #if CP_USE_DOUBLES
/// Chipmunk's floating point type.
/// 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
skipping to change at line 89 skipping to change at line 94
#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
static inline cpFloat /// Return the max of two cpFloats.
cpfmax(cpFloat a, cpFloat b) static inline cpFloat cpfmax(cpFloat a, cpFloat b)
{ {
return (a > b) ? a : b; return (a > b) ? a : b;
} }
static inline cpFloat /// Return the min of two cpFloats.
cpfmin(cpFloat a, cpFloat b) static inline cpFloat cpfmin(cpFloat a, cpFloat b)
{ {
return (a < b) ? a : b; return (a < b) ? a : b;
} }
static inline cpFloat /// Return the absolute value of a cpFloat.
cpfabs(cpFloat n) static inline cpFloat cpfabs(cpFloat f)
{ {
return (n < 0) ? -n : n; return (f < 0) ? -f : f;
} }
static inline cpFloat /// Clamp @c f to be between @c min and @c max.
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);
} }
static inline cpFloat /// Clamp @c f to be between 0 and 1.
cpflerp(cpFloat f1, cpFloat f2, cpFloat t) static inline cpFloat cpfclamp01(cpFloat f)
{
return cpfmax(0.0f, cpfmin(f, 1.0f));
}
/// Linearly interpolate (or extrapolate) between @c f1 and @c f2 by @c t p
ercent.
static inline cpFloat cpflerp(cpFloat f1, cpFloat f2, cpFloat t)
{ {
return f1*(1.0f - t) + f2*t; return f1*(1.0f - t) + f2*t;
} }
static inline cpFloat /// Linearly interpolate from @c f1 to @c f2 by no more than @c d.
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);
} }
// CGPoints are structurally the same, and allow /// Hash value type.
// easy interoperability with other Cocoa libraries typedef uintptr_t cpHashValue;
#ifdef CP_USE_CGPOINTS
typedef CGPoint cpVect;
#else
typedef struct cpVect{cpFloat x,y;} cpVect;
#endif
typedef unsigned int cpHashValue;
// Oh C, how we love to define our own boolean types to get compiler compat ibility // Oh C, how we love to define our own boolean types to get compiler compat ibility
/// 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.
#define cpTrue 1 #define cpTrue 1
#endif #endif
#ifndef cpFalse #ifndef cpFalse
/// 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.
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
typedef unsigned int cpCollisionType; /// Type used for cpSpace.collision_type.
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
typedef unsigned int cpGroup; /// Type used for cpShape.group.
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.
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.
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.
#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.
#define CP_ALL_LAYERS (~(cpLayers)0) #define CP_ALL_LAYERS (~(cpLayers)0)
#endif #endif
/// @}
#endif // _CHIPMUNK_TYPES_H_ // CGPoints are structurally the same, and allow
// easy interoperability with other Cocoa libraries
#if CP_USE_CGPOINTS
typedef CGPoint cpVect;
#else
/// Chipmunk's 2D vector type.
/// @addtogroup cpVect
typedef struct cpVect{cpFloat x,y;} cpVect;
#endif
 End of changes. 28 change blocks. 
35 lines changed or deleted 52 lines changed or added


 chipmunk_unsafe.h   chipmunk_unsafe.h 
skipping to change at line 33 skipping to change at line 33
* In this case "unsafe" is referring to operations which may reduce the * In this case "unsafe" is referring to operations which may reduce the
* physical accuracy or numerical stability of the simulation, but will not * physical accuracy or numerical stability of the simulation, but will not
* cause crashes. * cause crashes.
* *
* The prime example is mutating collision shapes. Chipmunk does not suppor t * The prime example is mutating collision shapes. Chipmunk does not suppor t
* this directly. Mutating shapes using this API will caused objects in con tact * this directly. Mutating shapes using this API will caused objects in con tact
* to be pushed apart using Chipmunk's overlap solver, but not using real * to be pushed apart using Chipmunk's overlap solver, but not using real
* persistent velocities. Probably not what you meant, but perhaps close en ough. * persistent velocities. Probably not what you meant, but perhaps close en ough.
*/ */
/// @defgroup unsafe Chipmunk Unsafe Shape Operations
/// These functions are used for mutating collision shapes.
/// Chipmunk does not have any way to get velocity information on changing
shapes,
/// so the results will be unrealistic. You must explicity include the chip
munk_unsafe.h header to use them.
/// @{
#ifndef CHIPMUNK_UNSAFE_HEADER #ifndef CHIPMUNK_UNSAFE_HEADER
#define CHIPMUNK_UNSAFE_HEADER #define CHIPMUNK_UNSAFE_HEADER
#ifdef __cplusplus #ifdef __cplusplus
extern "C" { extern "C" {
#endif #endif
/// Set the radius of a circle shape.
void cpCircleShapeSetRadius(cpShape *shape, cpFloat radius); void cpCircleShapeSetRadius(cpShape *shape, cpFloat radius);
/// Set the offset of a circle shape.
void cpCircleShapeSetOffset(cpShape *shape, cpVect offset); void cpCircleShapeSetOffset(cpShape *shape, cpVect offset);
/// Set the endpoints of a segment shape.
void cpSegmentShapeSetEndpoints(cpShape *shape, cpVect a, cpVect b); void cpSegmentShapeSetEndpoints(cpShape *shape, cpVect a, cpVect b);
/// Set the radius of a segment shape.
void cpSegmentShapeSetRadius(cpShape *shape, cpFloat radius); void cpSegmentShapeSetRadius(cpShape *shape, cpFloat radius);
/// Set the vertexes of a poly shape.
void cpPolyShapeSetVerts(cpShape *shape, int numVerts, cpVect *verts, cpVec t offset); void cpPolyShapeSetVerts(cpShape *shape, int numVerts, cpVect *verts, cpVec t offset);
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif
#endif #endif
/// @}
 End of changes. 8 change blocks. 
1 lines changed or deleted 13 lines changed or added


 chvalid.h   chvalid.h 
skipping to change at line 31 skipping to change at line 31
extern "C" { extern "C" {
#endif #endif
/* /*
* Define our typedefs and structures * Define our typedefs and structures
* *
*/ */
typedef struct _xmlChSRange xmlChSRange; typedef struct _xmlChSRange xmlChSRange;
typedef xmlChSRange *xmlChSRangePtr; typedef xmlChSRange *xmlChSRangePtr;
struct _xmlChSRange { struct _xmlChSRange {
unsigned short low; unsigned short low;
unsigned short high; unsigned short high;
}; };
typedef struct _xmlChLRange xmlChLRange; typedef struct _xmlChLRange xmlChLRange;
typedef xmlChLRange *xmlChLRangePtr; typedef xmlChLRange *xmlChLRangePtr;
struct _xmlChLRange { struct _xmlChLRange {
unsigned int low; unsigned int low;
unsigned int high; unsigned int high;
}; };
typedef struct _xmlChRangeGroup xmlChRangeGroup; typedef struct _xmlChRangeGroup xmlChRangeGroup;
typedef xmlChRangeGroup *xmlChRangeGroupPtr; typedef xmlChRangeGroup *xmlChRangeGroupPtr;
struct _xmlChRangeGroup { struct _xmlChRangeGroup {
int nbShortRange; int nbShortRange;
int nbLongRange; int nbLongRange;
const xmlChSRange *shortRange; /* points to an array of ranges */ const xmlChSRange *shortRange; /* points to an array of ranges */
const xmlChLRange *longRange; const xmlChLRange *longRange;
}; };
/** /**
* Range checking routine * Range checking routine
*/ */
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlCharInRange(unsigned int val, const xmlChRangeGroup *grou p); xmlCharInRange(unsigned int val, const xmlChRangeGroup *group);
/** /**
* xmlIsBaseChar_ch: * xmlIsBaseChar_ch:
* @c: char to validate * @c: char to validate
* *
* Automatically generated by genChRanges.py * Automatically generated by genChRanges.py
*/ */
#define xmlIsBaseChar_ch(c) (((0x41 <= (c)) && ((c) <= 0x5a)) || \ #define xmlIsBaseChar_ch(c) (((0x41 <= (c)) && ((c) <= 0x5a)) || \
((0x61 <= (c)) && ((c) <= 0x7a)) || \ ((0x61 <= (c)) && ((c) <= 0x7a)) || \
((0xc0 <= (c)) && ((c) <= 0xd6)) || \ ((0xc0 <= (c)) && ((c) <= 0xd6)) || \
((0xd8 <= (c)) && ((c) <= 0xf6)) || \ ((0xd8 <= (c)) && ((c) <= 0xf6)) || \
(0xf8 <= (c))) (0xf8 <= (c)))
/** /**
* xmlIsBaseCharQ: * xmlIsBaseCharQ:
* @c: char to validate * @c: char to validate
* *
* Automatically generated by genChRanges.py * Automatically generated by genChRanges.py
*/ */
#define xmlIsBaseCharQ(c) (((c) < 0x100) ? \ #define xmlIsBaseCharQ(c) (((c) < 0x100) ? \
xmlIsBaseChar_ch((c)) : \ xmlIsBaseChar_ch((c)) : \
xmlCharInRange((c), &xmlIsBaseCharGroup)) xmlCharInRange((c), &xmlIsBaseCharGroup))
XMLPUBVAR const xmlChRangeGroup xmlIsBaseCharGroup; XMLPUBVAR const xmlChRangeGroup xmlIsBaseCharGroup;
/** /**
* xmlIsBlank_ch: * xmlIsBlank_ch:
* @c: char to validate * @c: char to validate
* *
* Automatically generated by genChRanges.py * Automatically generated by genChRanges.py
*/ */
#define xmlIsBlank_ch(c) (((c) == 0x20) || \ #define xmlIsBlank_ch(c) (((c) == 0x20) || \
((0x9 <= (c)) && ((c) <= 0xa)) || \ ((0x9 <= (c)) && ((c) <= 0xa)) || \
((c) == 0xd)) ((c) == 0xd))
/** /**
* xmlIsBlankQ: * xmlIsBlankQ:
* @c: char to validate * @c: char to validate
* *
* Automatically generated by genChRanges.py * Automatically generated by genChRanges.py
*/ */
#define xmlIsBlankQ(c) (((c) < 0x100) ? \ #define xmlIsBlankQ(c) (((c) < 0x100) ? \
xmlIsBlank_ch((c)) : 0) xmlIsBlank_ch((c)) : 0)
/** /**
* xmlIsChar_ch: * xmlIsChar_ch:
* @c: char to validate * @c: char to validate
* *
* Automatically generated by genChRanges.py * Automatically generated by genChRanges.py
*/ */
#define xmlIsChar_ch(c) (((0x9 <= (c)) && ((c) <= 0xa)) || \ #define xmlIsChar_ch(c) (((0x9 <= (c)) && ((c) <= 0xa)) || \
((c) == 0xd) || \ ((c) == 0xd) || \
(0x20 <= (c))) (0x20 <= (c)))
/** /**
* xmlIsCharQ: * xmlIsCharQ:
* @c: char to validate * @c: char to validate
* *
* Automatically generated by genChRanges.py * Automatically generated by genChRanges.py
*/ */
#define xmlIsCharQ(c) (((c) < 0x100) ? \ #define xmlIsCharQ(c) (((c) < 0x100) ? \
xmlIsChar_ch((c)) :\ xmlIsChar_ch((c)) :\
(((0x100 <= (c)) && ((c) <= 0xd7ff)) || \ (((0x100 <= (c)) && ((c) <= 0xd7ff)) || \
((0xe000 <= (c)) && ((c) <= 0xfffd)) || \ ((0xe000 <= (c)) && ((c) <= 0xfffd)) || \
((0x10000 <= (c)) && ((c) <= 0x10ffff)))) ((0x10000 <= (c)) && ((c) <= 0x10ffff))))
XMLPUBVAR const xmlChRangeGroup xmlIsCharGroup; XMLPUBVAR const xmlChRangeGroup xmlIsCharGroup;
/** /**
* xmlIsCombiningQ: * xmlIsCombiningQ:
* @c: char to validate * @c: char to validate
* *
* Automatically generated by genChRanges.py * Automatically generated by genChRanges.py
*/ */
#define xmlIsCombiningQ(c) (((c) < 0x100) ? \ #define xmlIsCombiningQ(c) (((c) < 0x100) ? \
0 : \ 0 : \
xmlCharInRange((c), &xmlIsCombiningGroup)) xmlCharInRange((c), &xmlIsCombiningGroup))
XMLPUBVAR const xmlChRangeGroup xmlIsCombiningGroup; XMLPUBVAR const xmlChRangeGroup xmlIsCombiningGroup;
/** /**
* xmlIsDigit_ch: * xmlIsDigit_ch:
* @c: char to validate * @c: char to validate
* *
* Automatically generated by genChRanges.py * Automatically generated by genChRanges.py
*/ */
#define xmlIsDigit_ch(c) (((0x30 <= (c)) && ((c) <= 0x39))) #define xmlIsDigit_ch(c) (((0x30 <= (c)) && ((c) <= 0x39)))
/** /**
* xmlIsDigitQ: * xmlIsDigitQ:
* @c: char to validate * @c: char to validate
* *
* Automatically generated by genChRanges.py * Automatically generated by genChRanges.py
*/ */
#define xmlIsDigitQ(c) (((c) < 0x100) ? \ #define xmlIsDigitQ(c) (((c) < 0x100) ? \
xmlIsDigit_ch((c)) : \ xmlIsDigit_ch((c)) : \
xmlCharInRange((c), &xmlIsDigitGroup)) xmlCharInRange((c), &xmlIsDigitGroup))
XMLPUBVAR const xmlChRangeGroup xmlIsDigitGroup; XMLPUBVAR const xmlChRangeGroup xmlIsDigitGroup;
/** /**
* xmlIsExtender_ch: * xmlIsExtender_ch:
* @c: char to validate * @c: char to validate
* *
* Automatically generated by genChRanges.py * Automatically generated by genChRanges.py
*/ */
#define xmlIsExtender_ch(c) (((c) == 0xb7)) #define xmlIsExtender_ch(c) (((c) == 0xb7))
/** /**
* xmlIsExtenderQ: * xmlIsExtenderQ:
* @c: char to validate * @c: char to validate
* *
* Automatically generated by genChRanges.py * Automatically generated by genChRanges.py
*/ */
#define xmlIsExtenderQ(c) (((c) < 0x100) ? \ #define xmlIsExtenderQ(c) (((c) < 0x100) ? \
xmlIsExtender_ch((c)) : \ xmlIsExtender_ch((c)) : \
xmlCharInRange((c), &xmlIsExtenderGroup)) xmlCharInRange((c), &xmlIsExtenderGroup))
XMLPUBVAR const xmlChRangeGroup xmlIsExtenderGroup; XMLPUBVAR const xmlChRangeGroup xmlIsExtenderGroup;
/** /**
* xmlIsIdeographicQ: * xmlIsIdeographicQ:
* @c: char to validate * @c: char to validate
* *
* Automatically generated by genChRanges.py * Automatically generated by genChRanges.py
*/ */
#define xmlIsIdeographicQ(c) (((c) < 0x100) ? \ #define xmlIsIdeographicQ(c) (((c) < 0x100) ? \
0 :\ 0 :\
(((0x4e00 <= (c)) && ((c) <= 0x9fa5)) || \ (((0x4e00 <= (c)) && ((c) <= 0x9fa5)) || \
((c) == 0x3007) || \ ((c) == 0x3007) || \
((0x3021 <= (c)) && ((c) <= 0x3029)))) ((0x3021 <= (c)) && ((c) <= 0x3029))))
XMLPUBVAR const xmlChRangeGroup xmlIsIdeographicGroup; XMLPUBVAR const xmlChRangeGroup xmlIsIdeographicGroup;
XMLPUBVAR const unsigned char xmlIsPubidChar_tab[256]; XMLPUBVAR const unsigned char xmlIsPubidChar_tab[256];
/** /**
* xmlIsPubidChar_ch: * xmlIsPubidChar_ch:
* @c: char to validate * @c: char to validate
* *
* Automatically generated by genChRanges.py * Automatically generated by genChRanges.py
*/ */
#define xmlIsPubidChar_ch(c) (xmlIsPubidChar_tab[(c)]) #define xmlIsPubidChar_ch(c) (xmlIsPubidChar_tab[(c)])
/** /**
* xmlIsPubidCharQ: * xmlIsPubidCharQ:
* @c: char to validate * @c: char to validate
* *
* Automatically generated by genChRanges.py * Automatically generated by genChRanges.py
*/ */
#define xmlIsPubidCharQ(c) (((c) < 0x100) ? \ #define xmlIsPubidCharQ(c) (((c) < 0x100) ? \
xmlIsPubidChar_ch((c)) : 0) xmlIsPubidChar_ch((c)) : 0)
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlIsBaseChar(unsigned int ch); xmlIsBaseChar(unsigned int ch);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlIsBlank(unsigned int ch); xmlIsBlank(unsigned int ch);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlIsChar(unsigned int ch); xmlIsChar(unsigned int ch);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlIsCombining(unsigned int ch); xmlIsCombining(unsigned int ch);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlIsDigit(unsigned int ch); xmlIsDigit(unsigned int ch);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlIsExtender(unsigned int ch); xmlIsExtender(unsigned int ch);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlIsIdeographic(unsigned int ch); xmlIsIdeographic(unsigned int ch);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlIsPubidChar(unsigned int ch); xmlIsPubidChar(unsigned int ch);
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif
#endif /* __XML_CHVALID_H__ */ #endif /* __XML_CHVALID_H__ */
 End of changes. 26 change blocks. 
57 lines changed or deleted 57 lines changed or added


 cocos2d.h   cocos2d.h 
skipping to change at line 31 skipping to change at line 31
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FRO M,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __COCOS2D_H__ #ifndef __COCOS2D_H__
#define __COCOS2D_H__ #define __COCOS2D_H__
// 0x00 HI ME LO // 0x00 HI ME LO
// 00 01 00 01 // 00 02 00 00
#define COCOS2D_VERSION 0x00010001 #define COCOS2D_VERSION 0x00020000
// //
// all cocos2d include files // all cocos2d include files
// //
#include "ccConfig.h" // should be included first #include "ccConfig.h"
#include "CCAction.h"
#include "CCAnimation.h"
#include "CCAnimationCache.h"
#include "CCActionManager.h"
#include "CCCamera.h"
#include "CCActionCamera.h"
#include "CCProtocols.h"
#include "CCNode.h"
#include "CCDirector.h"
#include "CCUserDefault.h"
#include "CCActionInstant.h"
#include "CCActionInterval.h"
#include "CCActionEase.h"
#include "CCLabelTTF.h"
#include "CCLayer.h"
#include "CCMenu.h"
#include "CCMenuItem.h"
#include "CCParticleSystem.h"
#include "CCParticleSystemPoint.h"
#include "CCParticleSystemQuad.h"
#include "CCParticleExamples.h"
#include "CCScene.h"
#include "CCSprite.h"
#include "CCSpriteFrameCache.h"
#include "CCTextureCache.h"
#include "CCTransition.h"
#include "CCTextureAtlas.h"
#include "CCLabelAtlas.h"
#include "CCAtlasNode.h"
#include "CCActionTiledGrid.h"
#include "CCActionGrid3D.h"
#include "CCActionGrid.h"
#include "CCLabelBMFont.h"
#include "CCParallaxNode.h"
#include "CCTileMapAtlas.h"
#include "CCTMXTiledMap.h"
#include "CCTMXLayer.h"
#include "CCTMXObjectGroup.h"
#include "CCTMXXMLParser.h"
#include "CCRenderTexture.h"
#include "CCMotionStreak.h"
#include "CCActionPageTurn3D.h"
#include "CCTransitionPageTurn.h"
#include "CCTexture2D.h"
#include "CCTexturePVR.h"
#include "CCTransitionRadial.h"
#include "CCActionProgressTimer.h"
#include "CCTouchHandler.h"
#include "CCTouchDispatcher.h"
#include "CCDrawingPrimitives.h"
#include "CCScheduler.h"
// havn't implement on wophone // actions
#if (CC_TARGET_PLATFORM != CC_PLATFORM_WOPHONE) #include "actions/CCAction.h"
#include "CCTextFieldTTF.h" #include "actions/CCActionInterval.h"
#endif #include "actions/CCActionCamera.h"
#include "actions/CCActionManager.h"
#include "actions/CCActionEase.h"
#include "actions/CCActionPageTurn3D.h"
#include "actions/CCActionGrid.h"
#include "actions/CCActionProgressTimer.h"
#include "actions/CCActionGrid3D.h"
#include "actions/CCActionTiledGrid.h"
#include "actions/CCActionInstant.h"
#include "actions/CCActionTween.h"
#include "actions/CCActionCatmullRom.h"
// base_nodes
#include "base_nodes/CCNode.h"
#include "base_nodes/CCAtlasNode.h"
// cocoa
#include "cocoa/CCAffineTransform.h"
#include "cocoa/CCDictionary.h"
#include "cocoa/CCObject.h"
#include "cocoa/CCArray.h"
#include "cocoa/CCGeometry.h"
#include "cocoa/CCSet.h"
#include "cocoa/CCAutoreleasePool.h"
#include "cocoa/CCInteger.h"
#include "cocoa/CCString.h"
#include "cocoa/CCNS.h"
#include "cocoa/CCZone.h"
// effects
#include "effects/CCGrabber.h"
#include "effects/CCGrid.h"
// // include
// cocoa includes #include "CCEventType.h"
// #include "CCProtocols.h"
#include "CCSet.h" #include "ccConfig.h"
#include "CCMutableArray.h" #include "ccMacros.h"
#include "CCMutableDictionary.h" #include "ccTypes.h"
#include "CCObject.h"
#include "CCZone.h"
#include "CCGeometry.h"
#include "CCAffineTransform.h"
#include "CCTouch.h"
#include "CCPointExtension.h"
//
// platform specific
//
#include "CCApplication.h"
#include "CCEGLView.h"
#include "CCImage.h"
#include "CCFileUtils.h"
#include "CCAccelerometer.h"
// extensions // kazmath
#include "extensions/CCNotificationCenter.h" #include "kazmath/include/kazmath/kazmath.h"
#include "kazmath/include/kazmath/GL/matrix.h"
// keypad_dispatcher
#include "keypad_dispatcher/CCKeypadDelegate.h"
#include "keypad_dispatcher/CCKeypadDispatcher.h"
// label_nodes
#include "label_nodes/CCLabelAtlas.h"
#include "label_nodes/CCLabelTTF.h"
#include "label_nodes/CCLabelBMFont.h"
// layers_scenes_transitions_nodes
#include "layers_scenes_transitions_nodes/CCLayer.h"
#include "layers_scenes_transitions_nodes/CCScene.h"
#include "layers_scenes_transitions_nodes/CCTransition.h"
#include "layers_scenes_transitions_nodes/CCTransitionPageTurn.h"
#include "layers_scenes_transitions_nodes/CCTransitionProgress.h"
// menu_nodes
#include "menu_nodes/CCMenu.h"
#include "menu_nodes/CCMenuItem.h"
// misc_nodes
#include "misc_nodes/CCMotionStreak.h"
#include "misc_nodes/CCProgressTimer.h"
#include "misc_nodes/CCRenderTexture.h"
// particle_nodes
#include "particle_nodes/CCParticleBatchNode.h"
#include "particle_nodes/CCParticleSystem.h"
#include "particle_nodes/CCParticleExamples.h"
#include "particle_nodes/CCParticleSystemQuad.h"
// platform
#include "platform/CCCommon.h"
#include "platform/CCFileUtils.h"
#include "platform/CCImage.h"
#include "platform/CCSAXParser.h"
#include "platform/CCThread.h"
#include "platform/platform.h"
#include "platform/CCPlatformConfig.h"
#include "platform/CCPlatformMacros.h"
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
#include "platform/ios/CCAccelerometer.h"
#include "platform/ios/CCApplication.h"
#include "platform/ios/CCEGLView.h"
#include "platform/ios/CCGL.h"
#include "platform/ios/CCStdC.h"
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_IOS
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#include "platform/android/CCAccelerometer.h"
#include "platform/android/CCApplication.h"
#include "platform/android/CCEGLView.h"
#include "platform/android/CCGL.h"
#include "platform/android/CCStdC.h"
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
#if (CC_TARGET_PLATFORM == CC_PLATFORM_BLACKBERRY)
#include "platform/blackberry/CCAccelerometer.h"
#include "platform/blackberry/CCApplication.h"
#include "platform/blackberry/CCEGLView.h"
#include "platform/blackberry/CCGL.h"
#include "platform/blackberry/CCStdC.h"
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_BLACKBERRY
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
#include "platform/win32/CCAccelerometer.h"
#include "platform/win32/CCApplication.h"
#include "platform/win32/CCEGLView.h"
#include "platform/win32/CCGL.h"
#include "platform/win32/CCStdC.h"
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_WIN32
#if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC)
#include "platform/mac/CCAccelerometer.h"
#include "platform/mac/CCApplication.h"
#include "platform/mac/CCEGLView.h"
#include "platform/mac/CCGL.h"
#include "platform/mac/CCStdC.h"
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_MAC
#if (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX)
#include "platform/linux/CCAccelerometer.h"
#include "platform/linux/CCApplication.h"
#include "platform/linux/CCEGLView.h"
#include "platform/linux/CCGL.h"
#include "platform/linux/CCStdC.h"
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_LINUX
// script_support
#include "script_support/CCScriptSupport.h"
// shaders
#include "shaders/CCGLProgram.h"
#include "shaders/ccGLStateCache.h"
#include "shaders/CCShaderCache.h"
#include "shaders/ccShaders.h"
// sprite_nodes
#include "sprite_nodes/CCAnimation.h"
#include "sprite_nodes/CCAnimationCache.h"
#include "sprite_nodes/CCSprite.h"
#include "sprite_nodes/CCSpriteBatchNode.h"
#include "sprite_nodes/CCSpriteFrame.h"
#include "sprite_nodes/CCSpriteFrameCache.h"
// support
#include "support/CCNotificationCenter.h"
#include "support/CCPointExtension.h"
#include "support/CCProfiling.h"
#include "support/CCUserDefault.h"
#include "support/CCVertex.h"
// text_input_node
#include "text_input_node/CCIMEDelegate.h"
#include "text_input_node/CCIMEDispatcher.h"
#include "text_input_node/CCTextFieldTTF.h"
// textures
#include "textures/CCTexture2D.h"
#include "textures/CCTextureAtlas.h"
#include "textures/CCTextureCache.h"
#include "textures/CCTexturePVR.h"
// tilemap_parallax_nodes
#include "tilemap_parallax_nodes/CCParallaxNode.h"
#include "tilemap_parallax_nodes/CCTMXLayer.h"
#include "tilemap_parallax_nodes/CCTMXObjectGroup.h"
#include "tilemap_parallax_nodes/CCTMXTiledMap.h"
#include "tilemap_parallax_nodes/CCTMXXMLParser.h"
#include "tilemap_parallax_nodes/CCTileMapAtlas.h"
// touch_dispatcher
#include "touch_dispatcher/CCTouch.h"
#include "touch_dispatcher/CCTouchDelegateProtocol.h"
#include "touch_dispatcher/CCTouchDispatcher.h"
#include "touch_dispatcher/CCTouchHandler.h"
// // root
// cocos2d macros #include "CCCamera.h"
// #include "CCConfiguration.h"
#include "ccTypes.h" #include "CCDirector.h"
#include "ccMacros.h" #include "CCDrawingPrimitives.h"
#include "CCScheduler.h"
namespace cocos2d { NS_CC_BEGIN
const char* cocos2dVersion(); const char* cocos2dVersion();
}//namespace cocos2d NS_CC_END
#endif // __COCOS2D_H__ #endif // __COCOS2D_H__
 End of changes. 8 change blocks. 
88 lines changed or deleted 194 lines changed or added


 controller.h   controller.h 
#ifndef _CONTROLLER_H_ #ifndef _CONTROLLER_H_
#define _CONTROLLER_H_ #define _CONTROLLER_H_
#include "cocos2d.h" #include "cocos2d.h"
using namespace cocos2d; USING_NS_CC;
class TestController : public CCLayer class TestController : public CCLayer
{ {
public: public:
TestController(); TestController();
~TestController(); ~TestController();
void menuCallback(CCObject * pSender); void menuCallback(CCObject * pSender);
void closeCallback(CCObject * pSender); void closeCallback(CCObject * pSender);
 End of changes. 1 change blocks. 
1 lines changed or deleted 1 lines changed or added


 cpArbiter.h   cpArbiter.h 
skipping to change at line 22 skipping to change at line 22
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * 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 I N THE * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS I N THE
* SOFTWARE. * SOFTWARE.
*/ */
struct cpArbiter; /// @defgroup cpArbiter cpArbiter
struct cpSpace; /// The cpArbiter struct controls pairs of colliding shapes.
struct cpCollisionHandler; /// They are also used in conjuction with collision handler callbacks
/// allowing you to retrieve information on the collision and control it.
// Determines how fast penetrations resolve themselves. /// @{
extern cpFloat cp_bias_coef;
// Amount of allowed penetration. Used to reduce vibrating contacts. /// Collision begin event function callback type.
extern cpFloat cp_collision_slop; /// Returning false from a begin callback causes the collision to be ignore
d until
// Data structure for contact points. /// the the separate callback is called when the objects stop colliding.
typedef struct cpContact { typedef cpBool (*cpCollisionBeginFunc)(cpArbiter *arb, cpSpace *space, void
// Contact point and normal. *data);
cpVect CP_PRIVATE(p), CP_PRIVATE(n); /// Collision pre-solve event function callback type.
// Penetration distance. /// Returning false from a pre-step callback causes the collision to be ign
CP_PRIVATE(cpFloat dist); ored until the next step.
typedef cpBool (*cpCollisionPreSolveFunc)(cpArbiter *arb, cpSpace *space, v
// Calculated by cpArbiterPreStep(). oid *data);
cpVect CP_PRIVATE(r1), CP_PRIVATE(r2); /// Collision post-solve event function callback type.
cpFloat CP_PRIVATE(nMass), CP_PRIVATE(tMass), CP_PRIVATE(bounce); typedef void (*cpCollisionPostSolveFunc)(cpArbiter *arb, cpSpace *space, vo
id *data);
// Persistant contact information. /// Collision separate event function callback type.
cpFloat CP_PRIVATE(jnAcc), CP_PRIVATE(jtAcc), CP_PRIVATE(jBias); typedef void (*cpCollisionSeparateFunc)(cpArbiter *arb, cpSpace *space, voi
CP_PRIVATE(cpFloat bias); d *data);
// Hash value used to (mostly) uniquely identify a contact. /// @private
CP_PRIVATE(cpHashValue hash); struct cpCollisionHandler {
} cpContact; cpCollisionType a;
cpCollisionType b;
// Contacts are always allocated in groups. cpCollisionBeginFunc begin;
cpContact* cpContactInit(cpContact *con, cpVect p, cpVect n, cpFloat dist, cpCollisionPreSolveFunc preSolve;
cpHashValue hash); cpCollisionPostSolveFunc postSolve;
cpCollisionSeparateFunc separate;
// Sum the contact impulses. (Can be used after cpSpaceStep() returns) void *data;
cpVect CP_PRIVATE(cpContactsSumImpulses)(cpContact *contacts, int numContac };
ts);
cpVect CP_PRIVATE(cpContactsSumImpulsesWithFriction)(cpContact *contacts, i
nt numContacts);
#define CP_MAX_CONTACTS_PER_ARBITER 6 typedef struct cpContact cpContact;
#define CP_MAX_CONTACTS_PER_ARBITER 4
/// @private
typedef enum cpArbiterState { typedef enum cpArbiterState {
cpArbiterStateNormal, // Arbiter is active and its the first collision.
cpArbiterStateFirstColl, cpArbiterStateFirstColl,
// Arbiter is active and its not the first collision.
cpArbiterStateNormal,
// Collision has been explicitly ignored.
// Either by returning false from a begin collision handler or calli
ng cpArbiterIgnore().
cpArbiterStateIgnore, cpArbiterStateIgnore,
cpArbiterStateSleep, // Collison is no longer active. A space will cache an arbiter for u p to cpSpace.collisionPersistence more steps.
cpArbiterStateCached, cpArbiterStateCached,
} cpArbiterState; } cpArbiterState;
// Data structure for tracking collisions between shapes. /// @private
typedef struct cpArbiter { struct cpArbiterThread {
// Information on the contact points between the objects. // Links to next and previous arbiters in the contact graph.
struct cpArbiter *next, *prev;
};
/// A colliding pair of shapes.
struct cpArbiter {
/// Calculated value to use for the elasticity coefficient.
/// Override in a pre-solve collision handler for custom behavior.
cpFloat e;
/// Calculated value to use for the friction coefficient.
/// Override in a pre-solve collision handler for custom behavior.
cpFloat u;
/// Calculated value to use for applying surface velocities.
/// Override in a pre-solve collision handler for custom behavior.
cpVect surface_vr;
CP_PRIVATE(cpShape *a);
CP_PRIVATE(cpShape *b);
CP_PRIVATE(cpBody *body_a);
CP_PRIVATE(cpBody *body_b);
CP_PRIVATE(struct cpArbiterThread thread_a);
CP_PRIVATE(struct cpArbiterThread thread_b);
CP_PRIVATE(int numContacts); CP_PRIVATE(int numContacts);
CP_PRIVATE(cpContact *contacts); CP_PRIVATE(cpContact *contacts);
// The two shapes and bodies involved in the collision.
// These variables are NOT in the order defined by the collision han
dler.
// Using CP_ARBITER_GET_SHAPES and CP_ARBITER_GET_BODIES will save y
ou from
// many headaches
cpShape CP_PRIVATE(*a), CP_PRIVATE(*b);
// Calculated before calling the pre-solve collision handler
// Override them with custom values if you want specialized behavior
CP_PRIVATE(cpFloat e);
CP_PRIVATE(cpFloat u);
// Used for surface_v calculations, implementation may change
CP_PRIVATE(cpVect surface_vr);
// Time stamp of the arbiter. (from cpSpace)
CP_PRIVATE(cpTimestamp stamp); CP_PRIVATE(cpTimestamp stamp);
CP_PRIVATE(cpCollisionHandler *handler);
CP_PRIVATE(struct cpCollisionHandler *handler);
// Are the shapes swapped in relation to the collision handler?
CP_PRIVATE(cpBool swappedColl); CP_PRIVATE(cpBool swappedColl);
CP_PRIVATE(cpArbiterState state); CP_PRIVATE(cpArbiterState state);
} cpArbiter; };
#define CP_DefineArbiterStructGetter(type, member, name) \
static inline type cpArbiterGet##name(const cpArbiter *arb){return arb->mem
ber;}
// Arbiters are allocated in large buffers by the space and don't require a #define CP_DefineArbiterStructSetter(type, member, name) \
destroy function static inline void cpArbiterSet##name(cpArbiter *arb, type value){arb->memb
cpArbiter* CP_PRIVATE(cpArbiterInit)(cpArbiter *arb, cpShape *a, cpShape *b er = value;}
);
// These functions are all intended to be used internally. #define CP_DefineArbiterStructProperty(type, member, name) \
// Inject new contact points into the arbiter while preserving contact hist CP_DefineArbiterStructGetter(type, member, name) \
ory. CP_DefineArbiterStructSetter(type, member, name)
void CP_PRIVATE(cpArbiterUpdate)(cpArbiter *arb, cpContact *contacts, int n
umContacts, struct cpCollisionHandler *handler, cpShape *a, cpShape *b); CP_DefineArbiterStructProperty(cpFloat, e, Elasticity);
// Precalculate values used by the solver. CP_DefineArbiterStructProperty(cpFloat, u, Friction);
void CP_PRIVATE(cpArbiterPreStep)(cpArbiter *arb, cpFloat dt_inv); CP_DefineArbiterStructProperty(cpVect, surface_vr, SurfaceVelocity);
void CP_PRIVATE(cpArbiterApplyCachedImpulse)(cpArbiter *arb);
// Run an iteration of the solver on the arbiter. /// Calculate the total impulse that was applied by this arbiter.
void CP_PRIVATE(cpArbiterApplyImpulse)(cpArbiter *arb, cpFloat eCoef); /// This function should only be called from a post-solve, post-step or cpB
odyEachArbiter callback.
// Arbiter Helper Functions cpVect cpArbiterTotalImpulse(const cpArbiter *arb);
cpVect cpArbiterTotalImpulse(cpArbiter *arb); /// Calculate the total impulse including the friction that was applied by
cpVect cpArbiterTotalImpulseWithFriction(cpArbiter *arb); this arbiter.
/// This function should only be called from a post-solve, post-step or cpB
odyEachArbiter callback.
cpVect cpArbiterTotalImpulseWithFriction(const cpArbiter *arb);
/// Calculate the amount of energy lost in a collision including static, bu
t not dynamic friction.
/// This function should only be called from a post-solve, post-step or cpB
odyEachArbiter callback.
cpFloat cpArbiterTotalKE(const cpArbiter *arb);
/// Causes a collision pair to be ignored as if you returned false from a b
egin callback.
/// If called from a pre-step callback, you will still need to return false
/// if you want it to be ignored in the current step.
void cpArbiterIgnore(cpArbiter *arb); void cpArbiterIgnore(cpArbiter *arb);
static inline void /// Return the colliding shapes involved for this arbiter.
cpArbiterGetShapes(const cpArbiter *arb, cpShape **a, cpShape **b) /// The order of their cpSpace.collision_type values will match
/// the order set when the collision handler was registered.
static inline void cpArbiterGetShapes(const cpArbiter *arb, cpShape **a, cp
Shape **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 .
#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);
static inline void /// Return the colliding bodies involved for this arbiter.
cpArbiterGetBodies(const cpArbiter *arb, cpBody **a, cpBody **b) /// The order of the cpSpace.collision_type the bodies are associated with
values will match
/// the order set when the collision handler was registered.
static inline void cpArbiterGetBodies(const cpArbiter *arb, cpBody **a, cpB
ody **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 .
#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);
static inline cpBool /// A struct that wraps up the important collision data for an arbiter.
cpArbiterIsFirstContact(const cpArbiter *arb)
{
return arb->CP_PRIVATE(state) == cpArbiterStateFirstColl;
}
static inline int
cpArbiterGetCount(const cpArbiter *arb)
{
return arb->CP_PRIVATE(numContacts);
}
static inline cpVect
cpArbiterGetNormal(const cpArbiter *arb, int i)
{
cpVect n = arb->CP_PRIVATE(contacts)[i].CP_PRIVATE(n);
return arb->CP_PRIVATE(swappedColl) ? cpvneg(n) : n;
}
static inline cpVect
cpArbiterGetPoint(const cpArbiter *arb, int i)
{
return arb->CP_PRIVATE(contacts)[i].CP_PRIVATE(p);
}
static inline cpFloat
cpArbiterGetDepth(const cpArbiter *arb, int i)
{
return arb->CP_PRIVATE(contacts)[i].CP_PRIVATE(dist);
}
typedef struct cpContactPointSet { typedef struct cpContactPointSet {
/// The number of contact points in the set.
int count; int count;
/// The array of contact points.
struct { struct {
cpVect point, normal; /// The position of the contact point.
cpVect point;
/// The normal of the contact point.
cpVect normal;
/// 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.
cpContactPointSet cpArbiterGetContactPointSet(const cpArbiter *arb);
static inline cpContactPointSet /// Returns true if this is the first step a pair of objects started collid
cpArbiterGetContactPointSet(const cpArbiter *arb) ing.
{ cpBool cpArbiterIsFirstContact(const cpArbiter *arb);
cpContactPointSet set; /// Get the number of contact points for this arbiter.
set.count = cpArbiterGetCount(arb); int cpArbiterGetCount(const cpArbiter *arb);
/// Get the normal of the @c ith contact point.
cpVect cpArbiterGetNormal(const cpArbiter *arb, int i);
/// Get the position of the @c ith contact point.
cpVect cpArbiterGetPoint(const cpArbiter *arb, int i);
/// Get the depth of the @c ith contact point.
cpFloat cpArbiterGetDepth(const cpArbiter *arb, int i);
int i; /// @}
for(i=0; i<set.count; i++){
set.points[i].point = arb->CP_PRIVATE(contacts)[i].CP_PRIVAT
E(p);
set.points[i].normal = arb->CP_PRIVATE(contacts)[i].CP_PRIVA
TE(n);
set.points[i].dist = arb->CP_PRIVATE(contacts)[i].CP_PRIVATE
(dist);
}
return set;
}
 End of changes. 23 change blocks. 
123 lines changed or deleted 141 lines changed or added


 cpBB.h   cpBB.h 
skipping to change at line 22 skipping to change at line 22
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * 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 I N THE * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS I N THE
* SOFTWARE. * SOFTWARE.
*/ */
/// @defgroup cpBBB cpBB
/// Chipmunk's axis-aligned 2D bounding box type along with a few handy rou
tines.
/// @{
/// 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;
static inline cpBB /// Convenience constructor for cpBB structs.
cpBBNew(const cpFloat l, const cpFloat b, static inline cpBB cpBBNew(const cpFloat l, const cpFloat b, const cpFloat
const cpFloat r, const cpFloat t) r, const cpFloat t)
{ {
cpBB bb = {l, b, r, t}; cpBB bb = {l, b, r, t};
return bb; return bb;
} }
static inline cpBool /// Constructs a cpBB for a circle with the given position and radius.
cpBBintersects(const cpBB a, const cpBB b) static inline cpBB cpBBNewForCircle(const cpVect p, const cpFloat r)
{ {
return (a.l<=b.r && b.l<=a.r && a.b<=b.t && b.b<=a.t); return cpBBNew(p.x - r, p.y - r, p.x + r, p.y + r);
} }
static inline cpBool /// Returns true if @c a and @c b intersect.
cpBBcontainsBB(const cpBB bb, const cpBB other) static inline cpBool cpBBIntersects(const cpBB a, const cpBB b)
{ {
return (bb.l < other.l && bb.r > other.r && bb.b < other.b && bb.t > other.t); return (a.l <= b.r && b.l <= a.r && a.b <= b.t && b.b <= a.t);
} }
static inline cpBool /// Returns true if @c other lies completely within @c bb.
cpBBcontainsVect(const cpBB bb, const cpVect v) static inline cpBool cpBBContainsBB(const cpBB bb, const cpBB other)
{ {
return (bb.l < v.x && bb.r > v.x && bb.b < v.y && bb.t > v.y); return (bb.l <= other.l && bb.r >= other.r && bb.b <= other.b && bb. t >= other.t);
} }
static inline cpBB /// Returns true if @c bb contains @c v.
cpBBmerge(const cpBB a, const cpBB b){ 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);
}
/// Returns a bounding box that holds both bounding boxes.
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)
); );
} }
static inline cpBB /// Returns a bounding box that holds both @c bb and @c v.
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.
static inline cpFloat cpBBArea(cpBB bb)
{
return (bb.r - bb.l)*(bb.t - bb.b);
}
/// Merges @c a and @c b and returns the area of the merged bounding box.
static inline cpFloat cpBBMergedArea(cpBB a, cpBB b)
{
return (cpfmax(a.r, b.r) - cpfmin(a.l, b.l))*(cpfmax(a.t, b.t) - cpf
min(a.b, b.b));
}
/// Returns the fraction along the segment query the cpBB is hit. Returns I
NFINITY if it doesn't hit.
static inline cpFloat cpBBSegmentQuery(cpBB bb, cpVect a, cpVect b)
{
cpFloat idx = 1.0f/(b.x - a.x);
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 txmin = cpfmin(tx1, tx2);
cpFloat txmax = cpfmax(tx1, tx2);
cpFloat idy = 1.0f/(b.y - a.y);
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 tymin = cpfmin(ty1, ty2);
cpFloat tymax = cpfmax(ty1, ty2);
if(tymin <= txmax && txmin <= tymax){
cpFloat min = cpfmax(txmin, tymin);
cpFloat max = cpfmin(txmax, tymax);
if(0.0 <= max && min <= 1.0) return cpfmax(min, 0.0);
}
return INFINITY;
}
/// 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)
{
return (cpBBSegmentQuery(bb, a, b) != INFINITY);
}
/// Clamp a vector to a bounding box.
cpVect cpBBClampVect(const cpBB bb, const cpVect v); // clamps the vector t o lie within the bbox cpVect cpBBClampVect(const cpBB bb, const cpVect v); // clamps the vector t o lie within the bbox
// TODO edge case issue // TODO edge case issue
/// Wrap a vector to a bounding box.
cpVect cpBBWrapVect(const cpBB bb, const cpVect v); // wrap a vector to a b box cpVect cpBBWrapVect(const cpBB bb, const cpVect v); // wrap a vector to a b box
///@}
 End of changes. 14 change blocks. 
16 lines changed or deleted 78 lines changed or added


 cpBody.h   cpBody.h 
skipping to change at line 22 skipping to change at line 22
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * 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 I N THE * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS I N THE
* SOFTWARE. * SOFTWARE.
*/ */
struct cpBody; /// @defgroup cpBody cpBody
struct cpShape; /// Chipmunk's rigid body type. Rigid bodies hold the physical properties o
struct cpSpace; f an object like
/// it's mass, and position and velocity of it's center of gravity. They do
typedef void (*cpBodyVelocityFunc)(struct cpBody *body, cpVect gravity, cpF n't have an shape on their own.
loat damping, cpFloat dt); /// They are given a shape by creating collision shapes (cpShape) that poin
typedef void (*cpBodyPositionFunc)(struct cpBody *body, cpFloat dt); t to the body.
/// @{
extern cpBodyVelocityFunc cpBodyUpdateVelocityDefault;
extern cpBodyPositionFunc cpBodyUpdatePositionDefault; /// Rigid body velocity update function type.
typedef void (*cpBodyVelocityFunc)(cpBody *body, cpVect gravity, cpFloat da
// Structure to hold information about the contact graph components mping, cpFloat dt);
// when putting groups of objects to sleep. /// Rigid body position update function type.
// No interesting user accessible fields. typedef void (*cpBodyPositionFunc)(cpBody *body, cpFloat dt);
/// Used internally to track information on the collision graph.
/// @private
typedef struct cpComponentNode { typedef struct cpComponentNode {
struct cpBody *parent; cpBody *root;
struct cpBody *next; cpBody *next;
int rank;
cpFloat idleTime; cpFloat idleTime;
} cpComponentNode; } cpComponentNode;
typedef struct cpBody{ /// Chipmunk's rigid body struct.
// *** Integration Functions. struct cpBody {
/// Function that is called to integrate the body's velocity. (Defau
// Function that is called to integrate the body's velocity. (Defaul lts to cpBodyUpdateVelocity)
ts to cpBodyUpdateVelocity)
cpBodyVelocityFunc velocity_func; cpBodyVelocityFunc velocity_func;
// Function that is called to integrate the body's position. (Defaul ts to cpBodyUpdatePosition) /// Function that is called to integrate the body's position. (Defau lts to cpBodyUpdatePosition)
cpBodyPositionFunc position_func; cpBodyPositionFunc position_func;
// *** Mass Properties /// Mass of the body.
/// Must agree with cpBody.m_inv! Use cpBodySetMass() when changing
// Mass and it's inverse. the mass for this reason.
// Always use cpBodySetMass() whenever changing the mass as these va cpFloat m;
lues must agree. /// Mass inverse.
cpFloat m, m_inv; cpFloat m_inv;
// Moment of inertia and it's inverse. /// Moment of inertia of the body.
// Always use cpBodySetMoment() whenever changing the moment as thes /// Must agree with cpBody.i_inv! Use cpBodySetMoment() when changin
e values must agree. g the moment for this reason.
cpFloat i, i_inv; cpFloat i;
/// Moment of inertia inverse.
cpFloat i_inv;
/// Position of the rigid body's center of gravity.
cpVect p;
/// Velocity of the rigid body's center of gravity.
cpVect v;
/// Force acting on the rigid body's center of gravity.
cpVect f;
/// Rotation of the body around it's center of gravity in radians.
/// Must agree with cpBody.rot! Use cpBodySetAngle() when changing t
he angle for this reason.
cpFloat a;
/// Angular velocity of the body around it's center of gravity in ra
dians/second.
cpFloat w;
/// Torque applied to the body around it's center of gravity.
cpFloat t;
// *** Positional Properties /// Cached unit length vector representing the angle of the body.
/// Used for fast rotations using cpvrotate().
// Linear components of motion (position, velocity, and force)
cpVect p, v, f;
// Angular components of motion (angle, angular velocity, and torque
)
// Always use cpBodySetAngle() to set the angle of the body as a and
rot must agree.
cpFloat a, w, t;
// Cached unit length vector representing the angle of the body.
// Used for fast vector rotation using cpvrotate().
cpVect rot; cpVect rot;
// *** User Definable Fields /// User definable data pointer.
/// Generally this points to your the game object class so you can a
// User defined data pointer. ccess it
/// when given a cpBody reference in a callback.
cpDataPointer data; cpDataPointer data;
// *** Other Fields /// Maximum velocity allowed when updating the velocity.
cpFloat v_limit;
/// Maximum rotational rate (in radians/second) allowed when updatin
g the angular velocity.
cpFloat w_limit;
// Maximum velocities this body can move at after integrating veloci
ty
cpFloat v_limit, w_limit;
// *** Internally Used Fields
// Velocity bias values used when solving penetrations and correctin
g constraints.
CP_PRIVATE(cpVect v_bias); CP_PRIVATE(cpVect v_bias);
CP_PRIVATE(cpFloat w_bias); CP_PRIVATE(cpFloat w_bias);
// Space this body has been added to CP_PRIVATE(cpSpace *space);
CP_PRIVATE(struct cpSpace *space);
// Pointer to the shape list. CP_PRIVATE(cpShape *shapeList);
// Shapes form a linked list using cpShape.next when added to a spac CP_PRIVATE(cpArbiter *arbiterList);
e. CP_PRIVATE(cpConstraint *constraintList);
CP_PRIVATE(struct cpShape *shapesList);
// Used by cpSpaceStep() to store contact graph information.
CP_PRIVATE(cpComponentNode node); CP_PRIVATE(cpComponentNode node);
} cpBody; };
// Basic allocation/destruction functions /// Allocate a cpBody.
cpBody *cpBodyAlloc(void); cpBody* cpBodyAlloc(void);
cpBody *cpBodyInit(cpBody *body, cpFloat m, cpFloat i); /// Initialize a cpBody.
cpBody *cpBodyNew(cpFloat m, cpFloat i); cpBody* cpBodyInit(cpBody *body, cpFloat m, cpFloat i);
/// Allocate and initialize a cpBody.
cpBody *cpBodyInitStatic(cpBody *body); cpBody* cpBodyNew(cpFloat m, cpFloat i);
cpBody *cpBodyNewStatic();
/// Initialize a static cpBody.
cpBody* cpBodyInitStatic(cpBody *body);
/// Allocate and initialize a static cpBody.
cpBody* cpBodyNewStatic(void);
/// Destroy a cpBody.
void cpBodyDestroy(cpBody *body); void cpBodyDestroy(cpBody *body);
/// Destroy and free a cpBody.
void cpBodyFree(cpBody *body); void cpBodyFree(cpBody *body);
// Wake up a sleeping or idle body. (defined in cpSpace.c) /// Check that the properties of a body is sane. (Only in debug mode)
#ifdef NDEBUG
#define cpBodyAssertSane(body)
#else
void cpBodySanityCheck(cpBody *body);
#define cpBodyAssertSane(body) cpBodySanityCheck(body)
#endif
// Defined in cpSpace.c
/// Wake up a sleeping or idle body.
void cpBodyActivate(cpBody *body); void cpBodyActivate(cpBody *body);
/// Wake up any sleeping or idle bodies touching a static body.
void cpBodyActivateStatic(cpBody *body, cpShape *filter);
// Force a body to sleep; /// Force a body to fall asleep immediately.
// defined in cpSpaceComponent.c
void cpBodySleep(cpBody *body); void cpBodySleep(cpBody *body);
/// Force a body to fall asleep immediately along with other bodies in a gr oup.
void cpBodySleepWithGroup(cpBody *body, cpBody *group); void cpBodySleepWithGroup(cpBody *body, cpBody *group);
static inline cpBool /// Returns true if the body is sleeping.
cpBodyIsSleeping(const cpBody *body) static inline cpBool cpBodyIsSleeping(const cpBody *body)
{ {
return (CP_PRIVATE(body->node).next != ((cpBody*)0)); return (CP_PRIVATE(body->node).root != ((cpBody*)0));
} }
static inline cpBool /// Returns true if the body is static.
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;
} }
static inline cpBool /// Returns true if the body has not been added to a space.
cpBodyIsRogue(const cpBody *body) static inline cpBool cpBodyIsRogue(const cpBody *body)
{ {
return (body->CP_PRIVATE(space) == ((struct cpSpace*)0)); return (body->CP_PRIVATE(space) == ((cpSpace*)0));
} }
#define CP_DefineBodyGetter(type, member, name) \ #define CP_DefineBodyStructGetter(type, member, name) \
static inline type cpBodyGet##name(const cpBody *body){return body->member; } static inline type cpBodyGet##name(const cpBody *body){return body->member; }
#define CP_DefineBodySetter(type, member, name) \ #define CP_DefineBodyStructSetter(type, member, name) \
static inline void \ static inline void cpBodySet##name(cpBody *body, const type value){ \
cpBodySet##name(cpBody *body, const type value){ \
cpBodyActivate(body); \ cpBodyActivate(body); \
cpBodyAssertSane(body); \
body->member = value; \ body->member = value; \
} \ }
#define CP_DefineBodyStructProperty(type, member, name) \
CP_DefineBodyStructGetter(type, member, name) \
CP_DefineBodyStructSetter(type, member, name)
#define CP_DefineBodyProperty(type, member, name) \ // TODO add to docs
CP_DefineBodyGetter(type, member, name) \ CP_DefineBodyStructGetter(cpSpace*, CP_PRIVATE(space), Space);
CP_DefineBodySetter(type, member, name)
// Accessors for cpBody struct members CP_DefineBodyStructGetter(cpFloat, m, Mass);
CP_DefineBodyGetter(cpFloat, m, Mass); /// Set the mass of a body.
void cpBodySetMass(cpBody *body, cpFloat m); void cpBodySetMass(cpBody *body, cpFloat m);
CP_DefineBodyGetter(cpFloat, i, Moment); CP_DefineBodyStructGetter(cpFloat, i, Moment);
/// Set the moment of a body.
void cpBodySetMoment(cpBody *body, cpFloat i); void cpBodySetMoment(cpBody *body, cpFloat i);
CP_DefineBodyProperty(cpVect, p, Pos); CP_DefineBodyStructGetter(cpVect, p, Pos);
CP_DefineBodyProperty(cpVect, v, Vel); /// Set the position of a body.
CP_DefineBodyProperty(cpVect, f, Force); void cpBodySetPos(cpBody *body, cpVect pos);
CP_DefineBodyGetter(cpFloat, a, Angle); CP_DefineBodyStructProperty(cpVect, v, Vel);
CP_DefineBodyStructProperty(cpVect, f, Force);
CP_DefineBodyStructGetter(cpFloat, a, Angle);
/// Set the angle of a body.
void cpBodySetAngle(cpBody *body, cpFloat a); void cpBodySetAngle(cpBody *body, cpFloat a);
CP_DefineBodyProperty(cpFloat, w, AngVel); CP_DefineBodyStructProperty(cpFloat, w, AngVel);
CP_DefineBodyProperty(cpFloat, t, Torque); CP_DefineBodyStructProperty(cpFloat, t, Torque);
CP_DefineBodyGetter(cpVect, rot, Rot); CP_DefineBodyStructGetter(cpVect, rot, Rot);
CP_DefineBodyProperty(cpFloat, v_limit, VelLimit); CP_DefineBodyStructProperty(cpFloat, v_limit, VelLimit);
CP_DefineBodyProperty(cpFloat, w_limit, AngVelLimit); CP_DefineBodyStructProperty(cpFloat, w_limit, AngVelLimit);
CP_DefineBodyStructProperty(cpDataPointer, data, UserData);
// Modify the velocity of the body so that it will move to the specified a
bsolute coordinates in the next timestep.
// Intended for objects that are moved manually with a custom velocity inte
gration function.
void cpBodySlew(cpBody *body, cpVect pos, cpFloat dt);
// Default Integration functions. /// Default Integration functions.
void cpBodyUpdateVelocity(cpBody *body, cpVect gravity, cpFloat damping, cp Float dt); void cpBodyUpdateVelocity(cpBody *body, cpVect gravity, cpFloat damping, cp Float dt);
void cpBodyUpdatePosition(cpBody *body, cpFloat dt); void cpBodyUpdatePosition(cpBody *body, cpFloat dt);
// Convert body local to world coordinates /// Convert body relative/local coordinates to absolute/world coordinates.
static inline cpVect static inline cpVect cpBodyLocal2World(const cpBody *body, const cpVect v)
cpBodyLocal2World(const cpBody *body, const cpVect v)
{ {
return cpvadd(body->p, cpvrotate(v, body->rot)); return cpvadd(body->p, cpvrotate(v, body->rot));
} }
// Convert world to body local coordinates /// Convert body absolute/world coordinates to relative/local coordinates.
static inline cpVect static inline cpVect cpBodyWorld2Local(const cpBody *body, const cpVect v)
cpBodyWorld2Local(const cpBody *body, const cpVect v)
{ {
return cpvunrotate(cpvsub(v, body->p), body->rot); return cpvunrotate(cpvsub(v, body->p), body->rot);
} }
// Zero the forces on a body. /// Set the forces and torque or a body to zero.
void cpBodyResetForces(cpBody *body); void cpBodyResetForces(cpBody *body);
// Apply a force (in world coordinates) to a body at a point relative to th e center of gravity (also in world coordinates). /// Apply an force (in world coordinates) to the body at a point relative t o the center of gravity (also in world coordinates).
void cpBodyApplyForce(cpBody *body, const cpVect f, const cpVect r); void cpBodyApplyForce(cpBody *body, const cpVect f, const cpVect r);
// Apply an impulse (in world coordinates) to the body at a point relative to the center of gravity (also in world coordinates). /// Apply an impulse (in world coordinates) to the body at a point relative to the center of gravity (also in world coordinates).
void cpBodyApplyImpulse(cpBody *body, const cpVect j, const cpVect r); void cpBodyApplyImpulse(cpBody *body, const cpVect j, const cpVect r);
static inline cpFloat /// Get the velocity on a body (in world units) at a point on the body in w
cpBodyKineticEnergy(const cpBody *body) orld coordinates.
cpVect cpBodyGetVelAtWorldPoint(cpBody *body, cpVect point);
/// Get the velocity on a body (in world units) at a point on the body in l
ocal coordinates.
cpVect cpBodyGetVelAtLocalPoint(cpBody *body, cpVect point);
/// Get the kinetic energy of a 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);
} }
// Apply a damped spring force between two bodies. /// Body/shape iterator callback function type.
// Warning: Large damping values can be unstable. Use a cpDampedSpring cons typedef void (*cpBodyShapeIteratorFunc)(cpBody *body, cpShape *shape, void
traint for this instead. *data);
void cpApplyDampedSpring(cpBody *a, cpBody *b, cpVect anchr1, cpVect anchr2 /// Call @c func once for each shape attached to @c body and added to the s
, cpFloat rlen, cpFloat k, cpFloat dmp, cpFloat dt); pace.
void cpBodyEachShape(cpBody *body, cpBodyShapeIteratorFunc func, void *data
);
/// Body/constraint iterator callback function type.
typedef void (*cpBodyConstraintIteratorFunc)(cpBody *body, cpConstraint *co
nstraint, void *data);
/// Call @c func once for each constraint attached to @c body and added to
the space.
void cpBodyEachConstraint(cpBody *body, cpBodyConstraintIteratorFunc func,
void *data);
/// Body/arbiter iterator callback function type.
typedef void (*cpBodyArbiterIteratorFunc)(cpBody *body, cpArbiter *arbiter,
void *data);
/// Call @c func once for each arbiter that is currently active on the body
.
void cpBodyEachArbiter(cpBody *body, cpBodyArbiterIteratorFunc func, void *
data);
///@}
 End of changes. 42 change blocks. 
123 lines changed or deleted 150 lines changed or added


 cpConstraint.h   cpConstraint.h 
skipping to change at line 22 skipping to change at line 22
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * 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 I N THE * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS I N THE
* SOFTWARE. * SOFTWARE.
*/ */
// TODO: Comment me! /// @defgroup cpConstraint cpConstraint
/// @{
extern cpFloat cp_constraint_bias_coef; typedef struct cpConstraintClass cpConstraintClass;
struct cpConstraintClass; typedef void (*cpConstraintPreStepImpl)(cpConstraint *constraint, cpFloat d
struct cpConstraint; t);
typedef void (*cpConstraintApplyCachedImpulseImpl)(cpConstraint *constraint
, cpFloat dt_coef);
typedef void (*cpConstraintApplyImpulseImpl)(cpConstraint *constraint);
typedef cpFloat (*cpConstraintGetImpulseImpl)(cpConstraint *constraint);
/// @private
struct cpConstraintClass {
cpConstraintPreStepImpl preStep;
cpConstraintApplyCachedImpulseImpl applyCachedImpulse;
cpConstraintApplyImpulseImpl applyImpulse;
cpConstraintGetImpulseImpl getImpulse;
};
/// Callback function type that gets called before solving a joint.
typedef void (*cpConstraintPreSolveFunc)(cpConstraint *constraint, cpSpace
*space);
/// Callback function type that gets called after solving a joint.
typedef void (*cpConstraintPostSolveFunc)(cpConstraint *constraint, cpSpace
*space);
typedef void (*cpConstraintPreStepFunction)(struct cpConstraint *constraint /// Opaque cpConstraint struct.
, cpFloat dt, cpFloat dt_inv); struct cpConstraint {
typedef void (*cpConstraintApplyImpulseFunction)(struct cpConstraint *const CP_PRIVATE(const cpConstraintClass *klass);
raint);
typedef cpFloat (*cpConstraintGetImpulseFunction)(struct cpConstraint *cons
traint);
typedef struct cpConstraintClass { /// The first body connected to this constraint.
cpConstraintPreStepFunction preStep; cpBody *a;
cpConstraintApplyImpulseFunction applyImpulse; /// The second body connected to this constraint.
cpConstraintGetImpulseFunction getImpulse; cpBody *b;
} cpConstraintClass;
typedef struct cpConstraint { CP_PRIVATE(cpSpace *space);
CP_PRIVATE(const cpConstraintClass *klass);
CP_PRIVATE(cpConstraint *next_a);
CP_PRIVATE(cpConstraint *next_b);
cpBody *a, *b; /// The maximum force that this constraint is allowed to use.
/// Defaults to infinity.
cpFloat maxForce; cpFloat maxForce;
cpFloat biasCoef; /// The rate at which joint error is corrected.
/// Defaults to pow(1.0 - 0.1, 60.0) meaning that it will
/// correct 10% of the error every 1/60th of a second.
cpFloat errorBias;
/// The maximum rate at which joint error is corrected.
/// Defaults to infinity.
cpFloat maxBias; cpFloat maxBias;
/// Function called before the solver runs.
/// Animate your joint anchors, update your motor torque, etc.
cpConstraintPreSolveFunc preSolve;
/// Function called after the solver runs.
/// Use the applied impulse to perform effects like breakable joints
.
cpConstraintPostSolveFunc postSolve;
/// User definable data pointer.
/// Generally this points to your the game object class so you can a
ccess it
/// when given a cpConstraint reference in a callback.
cpDataPointer data; cpDataPointer data;
} cpConstraint; };
#ifdef CP_USE_DEPRECATED_API_4
typedef cpConstraint cpJoint;
#endif
/// Destroy a constraint.
void cpConstraintDestroy(cpConstraint *constraint); void cpConstraintDestroy(cpConstraint *constraint);
/// Destroy and free a constraint.
void cpConstraintFree(cpConstraint *constraint); void cpConstraintFree(cpConstraint *constraint);
static inline void /// @private
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);
} }
static inline cpFloat /// @private
cpConstraintGetImpulse(cpConstraint *constraint) #define CP_DefineConstraintStructGetter(type, member, name) \
static inline type cpConstraint##Get##name(const cpConstraint *constraint){
return constraint->member;}
/// @private
#define CP_DefineConstraintStructSetter(type, member, name) \
static inline void cpConstraint##Set##name(cpConstraint *constraint, type v
alue){ \
cpConstraintActivateBodies(constraint); \
constraint->member = value; \
}
/// @private
#define CP_DefineConstraintStructProperty(type, member, name) \
CP_DefineConstraintStructGetter(type, member, name) \
CP_DefineConstraintStructSetter(type, member, name)
CP_DefineConstraintStructGetter(cpSpace*, CP_PRIVATE(space), Space);
CP_DefineConstraintStructGetter(cpBody*, a, A);
CP_DefineConstraintStructGetter(cpBody*, b, B);
CP_DefineConstraintStructProperty(cpFloat, maxForce, MaxForce);
CP_DefineConstraintStructProperty(cpFloat, errorBias, ErrorBias);
CP_DefineConstraintStructProperty(cpFloat, maxBias, MaxBias);
CP_DefineConstraintStructProperty(cpConstraintPreSolveFunc, preSolve, PreSo
lveFunc);
CP_DefineConstraintStructProperty(cpConstraintPostSolveFunc, postSolve, Pos
tSolveFunc);
CP_DefineConstraintStructProperty(cpDataPointer, data, UserData);
// Get the last impulse applied by this 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) \
cpAssert(constraint->CP_PRIVATE(klass) == struct##GetClass(), "Const raint is not a "#struct); cpAssertHard(constraint->CP_PRIVATE(klass) == struct##GetClass(), "C onstraint is not a "#struct)
#define CP_DefineConstraintGetter(struct, type, member, name) \ #define CP_DefineConstraintGetter(struct, type, member, name) \
static inline type \ static inline type struct##Get##name(const cpConstraint *constraint){ \
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 \ static inline void struct##Set##name(cpConstraint *constraint, type value){
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) \
CP_DefineConstraintGetter(struct, type, member, name) \ CP_DefineConstraintGetter(struct, type, member, name) \
CP_DefineConstraintSetter(struct, type, member, name) CP_DefineConstraintSetter(struct, type, member, name)
// Built in Joint types
#include "cpPinJoint.h" #include "cpPinJoint.h"
#include "cpSlideJoint.h" #include "cpSlideJoint.h"
#include "cpPivotJoint.h" #include "cpPivotJoint.h"
#include "cpGrooveJoint.h" #include "cpGrooveJoint.h"
#include "cpDampedSpring.h" #include "cpDampedSpring.h"
#include "cpDampedRotarySpring.h" #include "cpDampedRotarySpring.h"
#include "cpRotaryLimitJoint.h" #include "cpRotaryLimitJoint.h"
#include "cpRatchetJoint.h" #include "cpRatchetJoint.h"
#include "cpGearJoint.h" #include "cpGearJoint.h"
#include "cpSimpleMotor.h" #include "cpSimpleMotor.h"
 End of changes. 21 change blocks. 
36 lines changed or deleted 102 lines changed or added


 cpDampedRotarySpring.h   cpDampedRotarySpring.h 
skipping to change at line 22 skipping to change at line 22
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * 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 I N THE * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS I N THE
* SOFTWARE. * SOFTWARE.
*/ */
/// @defgroup cpDampedRotarySpring cpDampedRotarySpring
/// @{
typedef cpFloat (*cpDampedRotarySpringTorqueFunc)(struct cpConstraint *spri ng, cpFloat relativeAngle); typedef cpFloat (*cpDampedRotarySpringTorqueFunc)(struct cpConstraint *spri ng, cpFloat relativeAngle);
const cpConstraintClass *cpDampedRotarySpringGetClass(); const cpConstraintClass *cpDampedRotarySpringGetClass(void);
/// @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;
cpDampedRotarySpring *cpDampedRotarySpringAlloc(void); /// Allocate a damped rotary spring.
cpDampedRotarySpring *cpDampedRotarySpringInit(cpDampedRotarySpring *joint, cpDampedRotarySpring* cpDampedRotarySpringAlloc(void);
cpBody *a, cpBody *b, cpFloat restAngle, cpFloat stiffness, cpFloat dampin /// Initialize a damped rotary spring.
g); cpDampedRotarySpring* cpDampedRotarySpringInit(cpDampedRotarySpring *joint,
cpConstraint *cpDampedRotarySpringNew(cpBody *a, cpBody *b, cpFloat restAng cpBody *a, cpBody *b, cpFloat restAngle, cpFloat stiffness, cpFloat dampin
le, cpFloat stiffness, cpFloat damping); g);
/// Allocate and initialize a damped rotary spring.
cpConstraint* cpDampedRotarySpringNew(cpBody *a, cpBody *b, cpFloat restAng
le, cpFloat stiffness, cpFloat damping);
CP_DefineConstraintProperty(cpDampedRotarySpring, cpFloat, restAngle, RestA ngle); CP_DefineConstraintProperty(cpDampedRotarySpring, cpFloat, restAngle, RestA ngle);
CP_DefineConstraintProperty(cpDampedRotarySpring, cpFloat, stiffness, Stiff ness); CP_DefineConstraintProperty(cpDampedRotarySpring, cpFloat, stiffness, Stiff ness);
CP_DefineConstraintProperty(cpDampedRotarySpring, cpFloat, damping, Damping ); CP_DefineConstraintProperty(cpDampedRotarySpring, cpFloat, damping, Damping );
CP_DefineConstraintProperty(cpDampedRotarySpring, cpDampedRotarySpringTorqu eFunc, springTorqueFunc, SpringTorqueFunc); CP_DefineConstraintProperty(cpDampedRotarySpring, cpDampedRotarySpringTorqu eFunc, springTorqueFunc, SpringTorqueFunc);
/// @}
 End of changes. 5 change blocks. 
7 lines changed or deleted 14 lines changed or added


 cpDampedSpring.h   cpDampedSpring.h 
skipping to change at line 22 skipping to change at line 22
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * 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 I N THE * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS I N THE
* SOFTWARE. * SOFTWARE.
*/ */
struct cpDampedSpring; /// @defgroup cpDampedSpring cpDampedSpring
/// @{
typedef cpFloat (*cpDampedSpringForceFunc)(struct cpConstraint *spring, cpF loat dist); typedef struct cpDampedSpring cpDampedSpring;
const cpConstraintClass *cpDampedSpringGetClass(); typedef cpFloat (*cpDampedSpringForceFunc)(cpConstraint *spring, cpFloat di st);
typedef struct cpDampedSpring { const cpConstraintClass *cpDampedSpringGetClass(void);
/// @private
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;
} cpDampedSpring; };
cpDampedSpring *cpDampedSpringAlloc(void); /// Allocate a damped spring.
cpDampedSpring *cpDampedSpringInit(cpDampedSpring *joint, cpBody *a, cpBody cpDampedSpring* cpDampedSpringAlloc(void);
*b, cpVect anchr1, cpVect anchr2, cpFloat restLength, cpFloat stiffness, c /// Initialize a damped spring.
pFloat damping); cpDampedSpring* cpDampedSpringInit(cpDampedSpring *joint, cpBody *a, cpBody
cpConstraint *cpDampedSpringNew(cpBody *a, cpBody *b, cpVect anchr1, cpVect *b, cpVect anchr1, cpVect anchr2, cpFloat restLength, cpFloat stiffness, c
anchr2, cpFloat restLength, cpFloat stiffness, cpFloat damping); pFloat damping);
/// Allocate and initialize a damped spring.
cpConstraint* cpDampedSpringNew(cpBody *a, cpBody *b, cpVect anchr1, cpVect
anchr2, cpFloat restLength, cpFloat stiffness, cpFloat damping);
CP_DefineConstraintProperty(cpDampedSpring, cpVect, anchr1, Anchr1); CP_DefineConstraintProperty(cpDampedSpring, cpVect, anchr1, Anchr1);
CP_DefineConstraintProperty(cpDampedSpring, cpVect, anchr2, Anchr2); CP_DefineConstraintProperty(cpDampedSpring, cpVect, anchr2, Anchr2);
CP_DefineConstraintProperty(cpDampedSpring, cpFloat, restLength, RestLength ); CP_DefineConstraintProperty(cpDampedSpring, cpFloat, restLength, RestLength );
CP_DefineConstraintProperty(cpDampedSpring, cpFloat, stiffness, Stiffness); CP_DefineConstraintProperty(cpDampedSpring, cpFloat, stiffness, Stiffness);
CP_DefineConstraintProperty(cpDampedSpring, cpFloat, damping, Damping); CP_DefineConstraintProperty(cpDampedSpring, cpFloat, damping, Damping);
CP_DefineConstraintProperty(cpDampedSpring, cpDampedSpringForceFunc, spring ForceFunc, SpringForceFunc); CP_DefineConstraintProperty(cpDampedSpring, cpDampedSpringForceFunc, spring ForceFunc, SpringForceFunc);
/// @}
 End of changes. 7 change blocks. 
11 lines changed or deleted 18 lines changed or added


 cpGearJoint.h   cpGearJoint.h 
skipping to change at line 22 skipping to change at line 22
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * 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 I N THE * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS I N THE
* SOFTWARE. * SOFTWARE.
*/ */
const cpConstraintClass *cpGearJointGetClass(); /// @defgroup cpGearJoint cpGearJoint
/// @{
const cpConstraintClass *cpGearJointGetClass(void);
/// @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;
cpGearJoint *cpGearJointAlloc(void); /// Allocate a gear joint.
cpGearJoint *cpGearJointInit(cpGearJoint *joint, cpBody *a, cpBody *b, cpFl cpGearJoint* cpGearJointAlloc(void);
oat phase, cpFloat ratio); /// Initialize a gear joint.
cpConstraint *cpGearJointNew(cpBody *a, cpBody *b, cpFloat phase, cpFloat r cpGearJoint* cpGearJointInit(cpGearJoint *joint, cpBody *a, cpBody *b, cpFl
atio); oat phase, cpFloat ratio);
/// Allocate and initialize a gear joint.
cpConstraint* cpGearJointNew(cpBody *a, cpBody *b, cpFloat phase, cpFloat r
atio);
CP_DefineConstraintProperty(cpGearJoint, cpFloat, phase, Phase); CP_DefineConstraintProperty(cpGearJoint, cpFloat, phase, Phase);
CP_DefineConstraintGetter(cpGearJoint, cpFloat, ratio, Ratio); CP_DefineConstraintGetter(cpGearJoint, cpFloat, ratio, Ratio);
/// Set the ratio of a gear joint.
void cpGearJointSetRatio(cpConstraint *constraint, cpFloat value); void cpGearJointSetRatio(cpConstraint *constraint, cpFloat value);
/// @}
 End of changes. 5 change blocks. 
6 lines changed or deleted 14 lines changed or added


 cpGrooveJoint.h   cpGrooveJoint.h 
skipping to change at line 22 skipping to change at line 22
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * 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 I N THE * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS I N THE
* SOFTWARE. * SOFTWARE.
*/ */
const cpConstraintClass *cpGrooveJointGetClass(); /// @defgroup cpGrooveJoint cpGrooveJoint
/// @{
const cpConstraintClass *cpGrooveJointGetClass(void);
/// @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;
cpGrooveJoint *cpGrooveJointAlloc(void); /// Allocate a groove joint.
cpGrooveJoint *cpGrooveJointInit(cpGrooveJoint *joint, cpBody *a, cpBody *b cpGrooveJoint* cpGrooveJointAlloc(void);
, cpVect groove_a, cpVect groove_b, cpVect anchr2); /// Initialize a groove joint.
cpConstraint *cpGrooveJointNew(cpBody *a, cpBody *b, cpVect groove_a, cpVec cpGrooveJoint* cpGrooveJointInit(cpGrooveJoint *joint, cpBody *a, cpBody *b
t groove_b, cpVect anchr2); , cpVect groove_a, cpVect groove_b, cpVect anchr2);
/// Allocate and initialize a groove joint.
cpConstraint* cpGrooveJointNew(cpBody *a, cpBody *b, cpVect groove_a, cpVec
t groove_b, cpVect anchr2);
CP_DefineConstraintGetter(cpGrooveJoint, cpVect, grv_a, GrooveA); CP_DefineConstraintGetter(cpGrooveJoint, cpVect, grv_a, GrooveA);
/// Set endpoint a of a groove joint's groove
void cpGrooveJointSetGrooveA(cpConstraint *constraint, cpVect value); void cpGrooveJointSetGrooveA(cpConstraint *constraint, cpVect value);
CP_DefineConstraintGetter(cpGrooveJoint, cpVect, grv_b, GrooveB); CP_DefineConstraintGetter(cpGrooveJoint, cpVect, grv_b, GrooveB);
/// Set endpoint b of a groove joint's groove
void cpGrooveJointSetGrooveB(cpConstraint *constraint, cpVect value); void cpGrooveJointSetGrooveB(cpConstraint *constraint, cpVect value);
CP_DefineConstraintProperty(cpGrooveJoint, cpVect, anchr2, Anchr2); CP_DefineConstraintProperty(cpGrooveJoint, cpVect, anchr2, Anchr2);
/// @}
 End of changes. 6 change blocks. 
6 lines changed or deleted 15 lines changed or added


 cpPinJoint.h   cpPinJoint.h 
skipping to change at line 22 skipping to change at line 22
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * 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 I N THE * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS I N THE
* SOFTWARE. * SOFTWARE.
*/ */
const cpConstraintClass *cpPinJointGetClass(); /// @defgroup cpPinJoint cpPinJoint
/// @{
const cpConstraintClass *cpPinJointGetClass(void);
/// @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;
cpPinJoint *cpPinJointAlloc(void); /// Allocate a pin joint.
cpPinJoint *cpPinJointInit(cpPinJoint *joint, cpBody *a, cpBody *b, cpVect cpPinJoint* cpPinJointAlloc(void);
anchr1, cpVect anchr2); /// Initialize a pin joint.
cpConstraint *cpPinJointNew(cpBody *a, cpBody *b, cpVect anchr1, cpVect anc cpPinJoint* cpPinJointInit(cpPinJoint *joint, cpBody *a, cpBody *b, cpVect
hr2); anchr1, cpVect anchr2);
/// Allocate and initialize a pin joint.
cpConstraint* cpPinJointNew(cpBody *a, cpBody *b, cpVect anchr1, cpVect anc
hr2);
CP_DefineConstraintProperty(cpPinJoint, cpVect, anchr1, Anchr1); CP_DefineConstraintProperty(cpPinJoint, cpVect, anchr1, Anchr1);
CP_DefineConstraintProperty(cpPinJoint, cpVect, anchr2, Anchr2); CP_DefineConstraintProperty(cpPinJoint, cpVect, anchr2, Anchr2);
CP_DefineConstraintProperty(cpPinJoint, cpFloat, dist, Dist); CP_DefineConstraintProperty(cpPinJoint, cpFloat, dist, Dist);
///@}
 End of changes. 4 change blocks. 
6 lines changed or deleted 13 lines changed or added


 cpPivotJoint.h   cpPivotJoint.h 
skipping to change at line 22 skipping to change at line 22
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * 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 I N THE * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS I N THE
* SOFTWARE. * SOFTWARE.
*/ */
const cpConstraintClass *cpPivotJointGetClass(); /// @defgroup cpPivotJoint cpPivotJoint
/// @{
const cpConstraintClass *cpPivotJointGetClass(void);
/// @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;
cpPivotJoint *cpPivotJointAlloc(void); /// Allocate a pivot joint
cpPivotJoint *cpPivotJointInit(cpPivotJoint *joint, cpBody *a, cpBody *b, c cpPivotJoint* cpPivotJointAlloc(void);
pVect anchr1, cpVect anchr2); /// Initialize a pivot joint.
cpConstraint *cpPivotJointNew(cpBody *a, cpBody *b, cpVect pivot); cpPivotJoint* cpPivotJointInit(cpPivotJoint *joint, cpBody *a, cpBody *b, c
cpConstraint *cpPivotJointNew2(cpBody *a, cpBody *b, cpVect anchr1, cpVect pVect anchr1, cpVect anchr2);
anchr2); /// Allocate and initialize a pivot joint.
cpConstraint* cpPivotJointNew(cpBody *a, cpBody *b, cpVect pivot);
/// Allocate and initialize a pivot joint with specific anchors.
cpConstraint* cpPivotJointNew2(cpBody *a, cpBody *b, cpVect anchr1, cpVect
anchr2);
CP_DefineConstraintProperty(cpPivotJoint, cpVect, anchr1, Anchr1); CP_DefineConstraintProperty(cpPivotJoint, cpVect, anchr1, Anchr1);
CP_DefineConstraintProperty(cpPivotJoint, cpVect, anchr2, Anchr2); CP_DefineConstraintProperty(cpPivotJoint, cpVect, anchr2, Anchr2);
/// @}
 End of changes. 4 change blocks. 
7 lines changed or deleted 15 lines changed or added


 cpPolyShape.h   cpPolyShape.h 
skipping to change at line 22 skipping to change at line 22
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * 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 I N THE * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS I N THE
* SOFTWARE. * SOFTWARE.
*/ */
// Axis structure used by cpPolyShape. /// @defgroup cpPolyShape cpPolyShape
typedef struct cpPolyShapeAxis{ /// @{
// normal
/// @private
typedef struct cpSplittingPlane {
cpVect n; cpVect n;
// distance from origin
cpFloat d; cpFloat d;
} cpPolyShapeAxis; } cpSplittingPlane;
// Convex polygon shape structure. /// @private
typedef struct cpPolyShape{ typedef struct cpPolyShape {
cpShape shape; cpShape shape;
// Vertex and axis lists. int numVerts;
CP_PRIVATE(int numVerts); cpVect *verts, *tVerts;
CP_PRIVATE(cpVect *verts); cpSplittingPlane *planes, *tPlanes;
CP_PRIVATE(cpPolyShapeAxis *axes);
// Transformed vertex and axis lists.
CP_PRIVATE(cpVect *tVerts);
CP_PRIVATE(cpPolyShapeAxis *tAxes);
} cpPolyShape; } cpPolyShape;
// Basic allocation functions. /// Allocate a polygon shape.
cpPolyShape *cpPolyShapeAlloc(void); cpPolyShape* cpPolyShapeAlloc(void);
cpPolyShape *cpPolyShapeInit(cpPolyShape *poly, cpBody *body, int numVerts, /// Initialize a polygon shape.
cpVect *verts, cpVect offset); /// A convex hull will be created from the vertexes.
cpShape *cpPolyShapeNew(cpBody *body, int numVerts, cpVect *verts, cpVect o cpPolyShape* cpPolyShapeInit(cpPolyShape *poly, cpBody *body, int numVerts,
ffset); cpVect *verts, cpVect offset);
/// Allocate and initialize a polygon shape.
cpPolyShape *cpBoxShapeInit(cpPolyShape *poly, cpBody *body, cpFloat width, /// A convex hull will be created from the vertexes.
cpFloat height); cpShape* cpPolyShapeNew(cpBody *body, int numVerts, cpVect *verts, cpVect o
cpShape *cpBoxShapeNew(cpBody *body, cpFloat width, cpFloat height); ffset);
/// Initialize a box shaped polygon shape.
cpPolyShape* cpBoxShapeInit(cpPolyShape *poly, cpBody *body, cpFloat width,
cpFloat height);
/// Initialize an offset box shaped polygon shape.
cpPolyShape* cpBoxShapeInit2(cpPolyShape *poly, cpBody *body, cpBB box);
/// Allocate and initialize a box shaped polygon shape.
cpShape* cpBoxShapeNew(cpBody *body, cpFloat width, cpFloat height);
/// Allocate and initialize an offset box shaped polygon shape.
cpShape* cpBoxShapeNew2(cpBody *body, cpBB box);
// Check that a set of vertexes has a correct winding and that they are con /// Check that a set of vertexes is convex and has a clockwise winding.
vex /// NOTE: Due to floating point precision issues, hulls created with cpQuic
kHull() 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.
int cpPolyShapeGetNumVerts(cpShape *shape); int cpPolyShapeGetNumVerts(cpShape *shape);
/// Get the @c ith vertex of a polygon shape.
cpVect cpPolyShapeGetVert(cpShape *shape, int idx); cpVect cpPolyShapeGetVert(cpShape *shape, int idx);
// *** inlined utility functions /// @}
// Returns the minimum distance of the polygon to the axis.
static inline cpFloat
cpPolyShapeValueOnAxis(const cpPolyShape *poly, const cpVect n, const cpFlo
at d)
{
cpVect *verts = poly->CP_PRIVATE(tVerts);
cpFloat min = cpvdot(n, verts[0]);
int i;
for(i=1; i<poly->CP_PRIVATE(numVerts); i++)
min = cpfmin(min, cpvdot(n, verts[i]));
return min - d;
}
// Returns true if the polygon contains the vertex.
static inline cpBool
cpPolyShapeContainsVert(const cpPolyShape *poly, const cpVect v)
{
cpPolyShapeAxis *axes = poly->CP_PRIVATE(tAxes);
int i;
for(i=0; i<poly->CP_PRIVATE(numVerts); i++){
cpFloat dist = cpvdot(axes[i].n, v) - axes[i].d;
if(dist > 0.0f) return cpFalse;
}
return cpTrue;
}
// Same as cpPolyShapeContainsVert() but ignores faces pointing away from t
he normal.
static inline cpBool
cpPolyShapeContainsVertPartial(const cpPolyShape *poly, const cpVect v, con
st cpVect n)
{
cpPolyShapeAxis *axes = poly->CP_PRIVATE(tAxes);
int i;
for(i=0; i<poly->CP_PRIVATE(numVerts); i++){
if(cpvdot(axes[i].n, n) < 0.0f) continue;
cpFloat dist = cpvdot(axes[i].n, v) - axes[i].d;
if(dist > 0.0f) return cpFalse;
}
return cpTrue;
}
 End of changes. 10 change blocks. 
27 lines changed or deleted 36 lines changed or added


 cpRatchetJoint.h   cpRatchetJoint.h 
skipping to change at line 22 skipping to change at line 22
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * 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 I N THE * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS I N THE
* SOFTWARE. * SOFTWARE.
*/ */
const cpConstraintClass *cpRatchetJointGetClass(); /// @defgroup cpRatchetJoint cpRatchetJoint
/// @{
const cpConstraintClass *cpRatchetJointGetClass(void);
/// @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;
cpRatchetJoint *cpRatchetJointAlloc(void); /// Allocate a ratchet joint.
cpRatchetJoint *cpRatchetJointInit(cpRatchetJoint *joint, cpBody *a, cpBody cpRatchetJoint* cpRatchetJointAlloc(void);
*b, cpFloat phase, cpFloat ratchet); /// Initialize a ratched joint.
cpConstraint *cpRatchetJointNew(cpBody *a, cpBody *b, cpFloat phase, cpFloa cpRatchetJoint* cpRatchetJointInit(cpRatchetJoint *joint, cpBody *a, cpBody
t ratchet); *b, cpFloat phase, cpFloat ratchet);
/// Allocate and initialize a ratchet joint.
cpConstraint* cpRatchetJointNew(cpBody *a, cpBody *b, cpFloat phase, cpFloa
t ratchet);
CP_DefineConstraintProperty(cpRatchetJoint, cpFloat, angle, Angle); CP_DefineConstraintProperty(cpRatchetJoint, cpFloat, angle, Angle);
CP_DefineConstraintProperty(cpRatchetJoint, cpFloat, phase, Phase); CP_DefineConstraintProperty(cpRatchetJoint, cpFloat, phase, Phase);
CP_DefineConstraintProperty(cpRatchetJoint, cpFloat, ratchet, Ratchet); CP_DefineConstraintProperty(cpRatchetJoint, cpFloat, ratchet, Ratchet);
/// @}
 End of changes. 4 change blocks. 
6 lines changed or deleted 13 lines changed or added


 cpRotaryLimitJoint.h   cpRotaryLimitJoint.h 
skipping to change at line 22 skipping to change at line 22
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * 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 I N THE * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS I N THE
* SOFTWARE. * SOFTWARE.
*/ */
const cpConstraintClass *cpRotaryLimitJointGetClass(); /// @defgroup cpRotaryLimitJoint cpRotaryLimitJoint
/// @{
const cpConstraintClass *cpRotaryLimitJointGetClass(void);
/// @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;
cpRotaryLimitJoint *cpRotaryLimitJointAlloc(void); /// Allocate a damped rotary limit joint.
cpRotaryLimitJoint *cpRotaryLimitJointInit(cpRotaryLimitJoint *joint, cpBod cpRotaryLimitJoint* cpRotaryLimitJointAlloc(void);
y *a, cpBody *b, cpFloat min, cpFloat max); /// Initialize a damped rotary limit joint.
cpConstraint *cpRotaryLimitJointNew(cpBody *a, cpBody *b, cpFloat min, cpFl cpRotaryLimitJoint* cpRotaryLimitJointInit(cpRotaryLimitJoint *joint, cpBod
oat max); y *a, cpBody *b, cpFloat min, cpFloat max);
/// Allocate and initialize a damped rotary limit joint.
cpConstraint* cpRotaryLimitJointNew(cpBody *a, cpBody *b, cpFloat min, cpFl
oat max);
CP_DefineConstraintProperty(cpRotaryLimitJoint, cpFloat, min, Min); CP_DefineConstraintProperty(cpRotaryLimitJoint, cpFloat, min, Min);
CP_DefineConstraintProperty(cpRotaryLimitJoint, cpFloat, max, Max); CP_DefineConstraintProperty(cpRotaryLimitJoint, cpFloat, max, Max);
/// @}
 End of changes. 4 change blocks. 
6 lines changed or deleted 13 lines changed or added


 cpShape.h   cpShape.h 
skipping to change at line 22 skipping to change at line 22
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * 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 I N THE * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS I N THE
* SOFTWARE. * SOFTWARE.
*/ */
// Forward declarations required for defining other structs. /// @defgroup cpShape cpShape
struct cpShape; /// The cpShape struct defines the shape of a rigid body.
struct 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 coordi
nates)
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.
typedef struct cpSegmentQueryInfo { typedef struct cpSegmentQueryInfo {
struct cpShape *shape; // shape that was hit, NULL if no collision /// The shape that was hit, NULL if no collision occured.
cpFloat t; // Distance along query segment, will always be in the ra cpShape *shape;
nge [0, 1]. /// The normalized distance along the query segment in the range [0,
cpVect n; // normal of hit surface 1].
cpFloat t;
/// The normal of the surface hit.
cpVect n;
} cpSegmentQueryInfo; } cpSegmentQueryInfo;
// Enumeration of shape types. /// @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;
// Shape class. Holds function pointers and type data. typedef cpBB (*cpShapeCacheDataImpl)(cpShape *shape, cpVect p, cpVect rot);
typedef struct cpShapeClass { typedef void (*cpShapeDestroyImpl)(cpShape *shape);
typedef void (*cpShapeNearestPointQueryImpl)(cpShape *shape, cpVect p, cpNe
arestPointQueryInfo *info);
typedef void (*cpShapeSegmentQueryImpl)(cpShape *shape, cpVect a, cpVect b,
cpSegmentQueryInfo *info);
/// @private
struct cpShapeClass {
cpShapeType type; cpShapeType type;
// Called by cpShapeCacheBB(). cpShapeCacheDataImpl cacheData;
cpBB (*cacheData)(struct cpShape *shape, cpVect p, cpVect rot); cpShapeDestroyImpl destroy;
// Called to by cpShapeDestroy(). cpShapeNearestPointQueryImpl nearestPointQuery;
void (*destroy)(struct cpShape *shape); cpShapeSegmentQueryImpl segmentQuery;
};
// called by cpShapePointQuery().
cpBool (*pointQuery)(struct cpShape *shape, cpVect p); /// Opaque collision shape struct.
struct cpShape {
// called by cpShapeSegmentQuery()
void (*segmentQuery)(struct cpShape *shape, cpVect a, cpVect b, cpS
egmentQueryInfo *info);
} cpShapeClass;
// Basic shape struct that the others inherit from.
typedef struct cpShape{
// The "class" of a shape as defined above
CP_PRIVATE(const cpShapeClass *klass); CP_PRIVATE(const cpShapeClass *klass);
// cpBody that the shape is attached to. /// The rigid body this collision shape is attached to.
cpBody *body; cpBody *body;
// Cached BBox for the shape. /// The current bounding box of the shape.
cpBB bb; cpBB bb;
// Sensors invoke callbacks, but do not generate collisions /// Sensor flag.
/// Sensor shapes call collision callbacks but don't produce collisi
ons.
cpBool sensor; cpBool sensor;
// *** Surface properties. /// 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 Fields /// User definable data pointer.
/// Generally this points to your the game object class so you can a
// User defined data pointer for the shape. ccess it
/// when given a cpShape reference in a callback.
cpDataPointer data; cpDataPointer data;
// User defined collision type for the shape. /// Collision type of this shape used when picking collision handler s.
cpCollisionType collision_type; cpCollisionType collision_type;
// User defined collision group for the shape. /// Group of this shape. Shapes in the same group don't collide.
cpGroup group; cpGroup group;
// User defined layer bitmask for the shape. // Layer bitmask for this shape. Shapes only collide if the bitwise and of their layers is non-zero.
cpLayers layers; cpLayers layers;
// *** Internally Used Fields CP_PRIVATE(cpSpace *space);
// Shapes form a linked list when added to space on a non-NULL body CP_PRIVATE(cpShape *next);
CP_PRIVATE(struct cpShape *next); CP_PRIVATE(cpShape *prev);
// Unique id used as the hash value.
CP_PRIVATE(cpHashValue hashid); CP_PRIVATE(cpHashValue hashid);
} cpShape; };
// Low level shape initialization func.
cpShape* cpShapeInit(cpShape *shape, const struct cpShapeClass *klass, cpBo
dy *body);
// Basic destructor functions. (allocation functions are not shared) /// Destroy a shape.
void cpShapeDestroy(cpShape *shape); void cpShapeDestroy(cpShape *shape);
/// Destroy and Free a shape.
void cpShapeFree(cpShape *shape); void cpShapeFree(cpShape *shape);
// Cache the BBox of the shape. /// Update, cache and return the bounding box of a shape based on the body it's attached to.
cpBB cpShapeCacheBB(cpShape *shape); cpBB cpShapeCacheBB(cpShape *shape);
/// Update, cache and return the bounding box of a shape with an explicit t
ransformation.
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);
#define CP_DeclareShapeGetter(struct, type, name) type struct##Get##name(cp /// Perform a nearest point query. It finds the closest point on the surfac
Shape *shape) e of shape to a specific point.
/// The value returned is the distance between the points. A negative dista
nce means the point is inside the shape.
cpFloat cpShapeNearestPointQuery(cpShape *shape, cpVect p, cpNearestPointQu
eryInfo *out);
// Circle shape structure. /// Perform a segment query against a shape. @c info must be a pointer to a
typedef struct cpCircleShape{ valid cpSegmentQueryInfo structure.
cpShape shape; cpBool cpShapeSegmentQuery(cpShape *shape, cpVect a, cpVect b, cpSegmentQue
ryInfo *info);
// Center in body space coordinates /// Get the hit point for a segment query.
CP_PRIVATE(cpVect c); static inline cpVect cpSegmentQueryHitPoint(const cpVect start, const cpVec
// Radius. t end, const cpSegmentQueryInfo info)
CP_PRIVATE(cpFloat r); {
return cpvlerp(start, end, info.t);
}
/// Get the hit distance for a segment query.
static inline cpFloat cpSegmentQueryHitDist(const cpVect start, const cpVec
t end, const cpSegmentQueryInfo info)
{
return cpvdist(start, end)*info.t;
}
#define CP_DefineShapeStructGetter(type, member, name) \
static inline type cpShapeGet##name(const cpShape *shape){return shape->mem
ber;}
#define CP_DefineShapeStructSetter(type, member, name, activates) \
static inline void cpShapeSet##name(cpShape *shape, type value){ \
if(activates && shape->body) cpBodyActivate(shape->body); \
shape->member = value; \
}
#define CP_DefineShapeStructProperty(type, member, name, activates) \
CP_DefineShapeStructGetter(type, member, name) \
CP_DefineShapeStructSetter(type, member, name, activates)
CP_DefineShapeStructGetter(cpSpace*, CP_PRIVATE(space), Space);
CP_DefineShapeStructGetter(cpBody*, body, Body);
void cpShapeSetBody(cpShape *shape, cpBody *body);
CP_DefineShapeStructGetter(cpBB, bb, BB);
CP_DefineShapeStructProperty(cpBool, sensor, Sensor, cpTrue);
CP_DefineShapeStructProperty(cpFloat, e, Elasticity, cpFalse);
CP_DefineShapeStructProperty(cpFloat, u, Friction, cpTrue);
CP_DefineShapeStructProperty(cpVect, surface_v, SurfaceVelocity, cpTrue);
CP_DefineShapeStructProperty(cpDataPointer, data, UserData, cpFalse);
CP_DefineShapeStructProperty(cpCollisionType, collision_type, CollisionType
, cpTrue);
CP_DefineShapeStructProperty(cpGroup, group, Group, cpTrue);
CP_DefineShapeStructProperty(cpLayers, layers, Layers, cpTrue);
/// When initializing a shape, it's hash value comes from a counter.
/// Because the hash value may affect iteration order, you can reset the sh
ape ID counter
/// when recreating a space. This will make the simulation be deterministic
.
void cpResetShapeIdCounter(void);
// Transformed center. (world space coordinates) #define CP_DeclareShapeGetter(struct, type, name) type struct##Get##name(co
CP_PRIVATE(cpVect tc); nst cpShape *shape)
/// @}
/// @defgroup cpCircleShape cpCircleShape
/// @private
typedef struct cpCircleShape {
cpShape shape;
cpVect c, tc;
cpFloat r;
} cpCircleShape; } cpCircleShape;
// Basic allocation functions for cpCircleShape. /// Allocate a circle shape.
cpCircleShape *cpCircleShapeAlloc(void); cpCircleShape* cpCircleShapeAlloc(void);
cpCircleShape *cpCircleShapeInit(cpCircleShape *circle, cpBody *body, cpFlo /// Initialize a circle shape.
at radius, cpVect offset); cpCircleShape* cpCircleShapeInit(cpCircleShape *circle, cpBody *body, cpFlo
cpShape *cpCircleShapeNew(cpBody *body, cpFloat radius, cpVect offset); at radius, cpVect offset);
/// Allocate and initialize a circle shape.
cpShape* cpCircleShapeNew(cpBody *body, cpFloat radius, cpVect offset);
CP_DeclareShapeGetter(cpCircleShape, cpVect, Offset); CP_DeclareShapeGetter(cpCircleShape, cpVect, Offset);
CP_DeclareShapeGetter(cpCircleShape, cpFloat, Radius); CP_DeclareShapeGetter(cpCircleShape, cpFloat, Radius);
// Segment shape structure. /// @}
typedef struct cpSegmentShape{ /// @defgroup cpSegmentShape cpSegmentShape
/// @private
typedef struct cpSegmentShape {
cpShape shape; cpShape shape;
// Endpoints and normal of the segment. (body space coordinates) cpVect a, b, n;
cpVect CP_PRIVATE(a), CP_PRIVATE(b), CP_PRIVATE(n); cpVect ta, tb, tn;
// Radius of the segment. (Thickness) cpFloat r;
cpFloat CP_PRIVATE(r);
// Transformed endpoints and normal. (world space coordinates) cpVect a_tangent, b_tangent;
cpVect CP_PRIVATE(ta), CP_PRIVATE(tb), CP_PRIVATE(tn);
} cpSegmentShape; } cpSegmentShape;
// Basic allocation functions for cpSegmentShape. /// Allocate a segment shape.
cpSegmentShape* cpSegmentShapeAlloc(void); cpSegmentShape* cpSegmentShapeAlloc(void);
/// Initialize a segment shape.
cpSegmentShape* cpSegmentShapeInit(cpSegmentShape *seg, cpBody *body, cpVec t a, cpVect b, cpFloat radius); cpSegmentShape* cpSegmentShapeInit(cpSegmentShape *seg, cpBody *body, cpVec t a, cpVect b, cpFloat radius);
/// Allocate and initialize a segment shape.
cpShape* cpSegmentShapeNew(cpBody *body, cpVect a, cpVect b, cpFloat radius ); cpShape* cpSegmentShapeNew(cpBody *body, cpVect a, cpVect b, cpFloat radius );
void cpSegmentShapeSetNeighbors(cpShape *shape, cpVect prev, cpVect next);
CP_DeclareShapeGetter(cpSegmentShape, cpVect, A); CP_DeclareShapeGetter(cpSegmentShape, cpVect, A);
CP_DeclareShapeGetter(cpSegmentShape, cpVect, B); CP_DeclareShapeGetter(cpSegmentShape, cpVect, B);
CP_DeclareShapeGetter(cpSegmentShape, cpVect, Normal); CP_DeclareShapeGetter(cpSegmentShape, cpVect, Normal);
CP_DeclareShapeGetter(cpSegmentShape, cpFloat, Radius); CP_DeclareShapeGetter(cpSegmentShape, cpFloat, Radius);
// For determinism, you can reset the shape id counter. /// @}
void cpResetShapeIdCounter(void);
// Directed segment queries against individual shapes.
void cpSegmentQueryInfoPrint(cpSegmentQueryInfo *info);
cpBool cpShapeSegmentQuery(cpShape *shape, cpVect a, cpVect b, cpSegmentQue
ryInfo *info);
static inline cpVect
cpSegmentQueryHitPoint(const cpVect start, const cpVect end, const cpSegmen
tQueryInfo info)
{
return cpvlerp(start, end, info.t);
}
static inline cpFloat
cpSegmentQueryHitDist(const cpVect start, const cpVect end, const cpSegment
QueryInfo info)
{
return cpvdist(start, end)*info.t;
}
 End of changes. 38 change blocks. 
77 lines changed or deleted 162 lines changed or added


 cpSimpleMotor.h   cpSimpleMotor.h 
skipping to change at line 22 skipping to change at line 22
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * 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 I N THE * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS I N THE
* SOFTWARE. * SOFTWARE.
*/ */
const cpConstraintClass *cpSimpleMotorGetClass(); /// @defgroup cpSimpleMotor cpSimpleMotor
/// @{
const cpConstraintClass *cpSimpleMotorGetClass(void);
/// @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;
cpSimpleMotor *cpSimpleMotorAlloc(void); /// Allocate a simple motor.
cpSimpleMotor *cpSimpleMotorInit(cpSimpleMotor *joint, cpBody *a, cpBody *b cpSimpleMotor* cpSimpleMotorAlloc(void);
, cpFloat rate); /// initialize a simple motor.
cpConstraint *cpSimpleMotorNew(cpBody *a, cpBody *b, cpFloat rate); cpSimpleMotor* cpSimpleMotorInit(cpSimpleMotor *joint, cpBody *a, cpBody *b
, cpFloat rate);
/// Allocate and initialize a simple motor.
cpConstraint* cpSimpleMotorNew(cpBody *a, cpBody *b, cpFloat rate);
CP_DefineConstraintProperty(cpSimpleMotor, cpFloat, rate, Rate); CP_DefineConstraintProperty(cpSimpleMotor, cpFloat, rate, Rate);
/// @}
 End of changes. 4 change blocks. 
5 lines changed or deleted 12 lines changed or added


 cpSlideJoint.h   cpSlideJoint.h 
skipping to change at line 22 skipping to change at line 22
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * 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 I N THE * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS I N THE
* SOFTWARE. * SOFTWARE.
*/ */
const cpConstraintClass *cpSlideJointGetClass(); /// @defgroup cpSlideJoint cpSlideJoint
/// @{
const cpConstraintClass *cpSlideJointGetClass(void);
/// @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;
cpSlideJoint *cpSlideJointAlloc(void); /// Allocate a slide joint.
cpSlideJoint *cpSlideJointInit(cpSlideJoint *joint, cpBody *a, cpBody *b, c cpSlideJoint* cpSlideJointAlloc(void);
pVect anchr1, cpVect anchr2, cpFloat min, cpFloat max); /// Initialize a slide joint.
cpConstraint *cpSlideJointNew(cpBody *a, cpBody *b, cpVect anchr1, cpVect a cpSlideJoint* cpSlideJointInit(cpSlideJoint *joint, cpBody *a, cpBody *b, c
nchr2, cpFloat min, cpFloat max); pVect anchr1, cpVect anchr2, cpFloat min, cpFloat max);
/// Allocate and initialize a slide joint.
cpConstraint* cpSlideJointNew(cpBody *a, cpBody *b, cpVect anchr1, cpVect a
nchr2, cpFloat min, cpFloat max);
CP_DefineConstraintProperty(cpSlideJoint, cpVect, anchr1, Anchr1); CP_DefineConstraintProperty(cpSlideJoint, cpVect, anchr1, Anchr1);
CP_DefineConstraintProperty(cpSlideJoint, cpVect, anchr2, Anchr2); CP_DefineConstraintProperty(cpSlideJoint, cpVect, anchr2, Anchr2);
CP_DefineConstraintProperty(cpSlideJoint, cpFloat, min, Min); CP_DefineConstraintProperty(cpSlideJoint, cpFloat, min, Min);
CP_DefineConstraintProperty(cpSlideJoint, cpFloat, max, Max); CP_DefineConstraintProperty(cpSlideJoint, cpFloat, max, Max);
/// @}
 End of changes. 4 change blocks. 
6 lines changed or deleted 13 lines changed or added


 cpSpace.h   cpSpace.h 
skipping to change at line 22 skipping to change at line 22
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * 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 I N THE * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS I N THE
* SOFTWARE. * SOFTWARE.
*/ */
struct cpSpace; /// @defgroup cpSpace cpSpace
/// @{
// Number of frames that contact information should persist. typedef struct cpContactBufferHeader cpContactBufferHeader;
extern cpTimestamp cp_contact_persistence; typedef void (*cpSpaceArbiterApplyImpulseFunc)(cpArbiter *arb);
// User collision handler function types. /// Basic Unit of Simulation in Chipmunk
typedef cpBool (*cpCollisionBeginFunc)(cpArbiter *arb, struct cpSpace *spac struct cpSpace {
e, void *data); /// Number of iterations to use in the impulse solver to solve conta
typedef cpBool (*cpCollisionPreSolveFunc)(cpArbiter *arb, struct cpSpace *s cts.
pace, void *data);
typedef void (*cpCollisionPostSolveFunc)(cpArbiter *arb, struct cpSpace *sp
ace, void *data);
typedef void (*cpCollisionSeparateFunc)(cpArbiter *arb, struct cpSpace *spa
ce, void *data);
// Structure for holding collision pair function information.
// Used internally.
typedef struct cpCollisionHandler {
cpCollisionType a;
cpCollisionType b;
cpCollisionBeginFunc begin;
cpCollisionPreSolveFunc preSolve;
cpCollisionPostSolveFunc postSolve;
cpCollisionSeparateFunc separate;
void *data;
} cpCollisionHandler;
extern cpCollisionHandler cpSpaceDefaultHandler;
typedef struct cpContactBufferHeader {
cpTimestamp stamp;
struct cpContactBufferHeader *next;
unsigned int numContacts;
} cpContactBufferHeader;
typedef struct cpSpace{
// *** User definable fields
// Number of iterations to use in the impulse solver to solve contac
ts.
int iterations; int iterations;
// Number of iterations to use in the impulse solver to solve elasti /// Gravity to pass to rigid bodies when integrating velocity.
c collisions.
int elasticIterations;
// Default gravity to supply when integrating rigid body motions.
cpVect gravity; cpVect gravity;
// Default damping to supply when integrating rigid body motions. /// 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.
/// The default value is 1.0, meaning no damping is applied.
/// @note This damping value is different than those of cpDampedSpri
ng 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 thresh /// The default value of 0 means to let the space guess a good thres
old based on gravity. hold 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.
// The default value of INFINITY disables the sleeping algorithm. /// Enabling sleeping also implicitly enables the the contact graph.
/// The default value of INFINITY disables the sleeping algorithm.
cpFloat sleepTimeThreshold; cpFloat sleepTimeThreshold;
// *** Internally Used Fields /// Amount of encouraged penetration between colliding shapes.
/// Used to reduce oscillating contacts and keep the collision cache
warm.
/// Defaults to 0.1. If you have poor simulation quality,
/// increase this number as much as possible without allowing visibl
e amounts of overlap.
cpFloat collisionSlop;
/// Determines how fast overlapping shapes are pushed apart.
/// 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.
cpFloat collisionBias;
/// Number of frames that contact information should persist.
/// Defaults to 3. There is probably never a reason to change this v
alue.
cpTimestamp collisionPersistence;
/// Rebuild the contact graph during each step. Must be enabled to u
se the cpBodyEachArbiter() function.
/// Disabled by default for a small performance boost. Enabled impli
citly when the sleeping feature is enabled.
cpBool enableContactGraph;
/// User definable data pointer.
/// Generally this points to your game's controller or game state
/// class so you can access it when given a cpSpace reference in a c
allback.
cpDataPointer data;
/// The designated static body for this space.
/// You can modify this body, or replace it with your own static bod
y.
/// By default it points to a statically allocated cpBody in the cpS
pace struct.
cpBody *staticBody;
// When the space lock count is non zero you cannot add or remove ob
jects
CP_PRIVATE(int locked);
// Time stamp. Is incremented on every call to cpSpaceStep().
CP_PRIVATE(cpTimestamp stamp); CP_PRIVATE(cpTimestamp stamp);
CP_PRIVATE(cpFloat curr_dt);
// The static and active shape spatial hashes.
CP_PRIVATE(cpSpaceHash *staticShapes);
CP_PRIVATE(cpSpaceHash *activeShapes);
// List of bodies in the system.
CP_PRIVATE(cpArray *bodies); CP_PRIVATE(cpArray *bodies);
CP_PRIVATE(cpArray *rousedBodies);
// List of groups of sleeping bodies.
CP_PRIVATE(cpArray *sleepingComponents); CP_PRIVATE(cpArray *sleepingComponents);
// List of bodies that have been flagged to be awoken. CP_PRIVATE(cpSpatialIndex *staticShapes);
CP_PRIVATE(cpArray *rousedBodies); CP_PRIVATE(cpSpatialIndex *activeShapes);
// List of active arbiters for the impulse solver.
CP_PRIVATE(cpArray *arbiters); CP_PRIVATE(cpArray *arbiters);
CP_PRIVATE(cpArray *pooledArbiters);
// Linked list ring of contact buffers.
// Head is the newest buffer, and each buffer points to a newer buff
er.
// Head wraps around and points to the oldest (tail) buffer.
CP_PRIVATE(cpContactBufferHeader *contactBuffersHead); CP_PRIVATE(cpContactBufferHeader *contactBuffersHead);
CP_PRIVATE(cpContactBufferHeader *_contactBuffersTail_Deprecated); CP_PRIVATE(cpHashSet *cachedArbiters);
CP_PRIVATE(cpArray *pooledArbiters);
CP_PRIVATE(cpArray *constraints);
// List of buffers to be free()ed when destroying the space.
CP_PRIVATE(cpArray *allocatedBuffers); CP_PRIVATE(cpArray *allocatedBuffers);
CP_PRIVATE(int locked);
// Persistant contact set. CP_PRIVATE(cpHashSet *collisionHandlers);
CP_PRIVATE(cpHashSet *contactSet);
// List of constraints in the system.
CP_PRIVATE(cpArray *constraints);
// Set of collisionpair functions.
CP_PRIVATE(cpHashSet *collFuncSet);
// Default collision handler.
CP_PRIVATE(cpCollisionHandler defaultHandler); CP_PRIVATE(cpCollisionHandler defaultHandler);
CP_PRIVATE(cpHashSet *postStepCallbacks); CP_PRIVATE(cpBool skipPostStep);
CP_PRIVATE(cpArray *postStepCallbacks);
cpBody staticBody; CP_PRIVATE(cpBody _staticBody);
} cpSpace; };
// Basic allocation/destruction functions. /// Allocate a cpSpace.
cpSpace* cpSpaceAlloc(void); cpSpace* cpSpaceAlloc(void);
/// Initialize a cpSpace.
cpSpace* cpSpaceInit(cpSpace *space); cpSpace* cpSpaceInit(cpSpace *space);
/// Allocate and initialize a cpSpace.
cpSpace* cpSpaceNew(void); cpSpace* cpSpaceNew(void);
/// Destroy a cpSpace.
void cpSpaceDestroy(cpSpace *space); void cpSpaceDestroy(cpSpace *space);
/// Destroy and free a cpSpace.
void cpSpaceFree(cpSpace *space); void cpSpaceFree(cpSpace *space);
// Convenience function. Frees all referenced entities. (bodies, shapes and #define CP_DefineSpaceStructGetter(type, member, name) \
constraints) static inline type cpSpaceGet##name(const cpSpace *space){return space->mem
void cpSpaceFreeChildren(cpSpace *space); ber;}
#define CP_DefineSpaceStructSetter(type, member, name) \
static inline void cpSpaceSet##name(cpSpace *space, type value){space->memb
er = value;}
// Collision handler management functions. #define CP_DefineSpaceStructProperty(type, member, name) \
CP_DefineSpaceStructGetter(type, member, name) \
CP_DefineSpaceStructSetter(type, member, name)
CP_DefineSpaceStructProperty(int, iterations, Iterations);
CP_DefineSpaceStructProperty(cpVect, gravity, Gravity);
CP_DefineSpaceStructProperty(cpFloat, damping, Damping);
CP_DefineSpaceStructProperty(cpFloat, idleSpeedThreshold, IdleSpeedThreshol
d);
CP_DefineSpaceStructProperty(cpFloat, sleepTimeThreshold, SleepTimeThreshol
d);
CP_DefineSpaceStructProperty(cpFloat, collisionSlop, CollisionSlop);
CP_DefineSpaceStructProperty(cpFloat, collisionBias, CollisionBias);
CP_DefineSpaceStructProperty(cpTimestamp, collisionPersistence, CollisionPe
rsistence);
CP_DefineSpaceStructProperty(cpBool, enableContactGraph, EnableContactGraph
);
CP_DefineSpaceStructProperty(cpDataPointer, data, UserData);
CP_DefineSpaceStructGetter(cpBody*, staticBody, StaticBody);
CP_DefineSpaceStructGetter(cpFloat, CP_PRIVATE(curr_dt), CurrentTimeStep);
/// returns true from inside a callback and objects cannot be added/removed
.
static inline cpBool
cpSpaceIsLocked(cpSpace *space)
{
return space->CP_PRIVATE(locked);
}
/// Set a default collision handler for this space.
/// The default collision handler is invoked for each colliding pair of sha
pes
/// that isn't explicitly handled by a specific collision handler.
/// 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 giv
en collision types collide.
/// 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.
void cpSpaceRemoveCollisionHandler(cpSpace *space, cpCollisionType a, cpCol lisionType b); void cpSpaceRemoveCollisionHandler(cpSpace *space, cpCollisionType a, cpCol lisionType b);
// Add and remove entities from the system. /// Add a collision shape to the simulation.
cpShape *cpSpaceAddShape(cpSpace *space, cpShape *shape); /// If the shape is attached to a static body, it will be added as a static
cpShape *cpSpaceAddStaticShape(cpSpace *space, cpShape *shape); shape.
cpBody *cpSpaceAddBody(cpSpace *space, cpBody *body); cpShape* cpSpaceAddShape(cpSpace *space, cpShape *shape);
cpConstraint *cpSpaceAddConstraint(cpSpace *space, cpConstraint *constraint /// Explicity add a shape as a static shape to the simulation.
); cpShape* cpSpaceAddStaticShape(cpSpace *space, cpShape *shape);
/// Add a rigid body to the simulation.
cpBody* cpSpaceAddBody(cpSpace *space, cpBody *body);
/// Add a constraint to the simulation.
cpConstraint* cpSpaceAddConstraint(cpSpace *space, cpConstraint *constraint
);
/// Remove a collision shape from the simulation.
void cpSpaceRemoveShape(cpSpace *space, cpShape *shape); void cpSpaceRemoveShape(cpSpace *space, cpShape *shape);
/// Remove a collision shape added using cpSpaceAddStaticShape() from the s imulation.
void cpSpaceRemoveStaticShape(cpSpace *space, cpShape *shape); void cpSpaceRemoveStaticShape(cpSpace *space, cpShape *shape);
/// Remove a rigid body from the simulation.
void cpSpaceRemoveBody(cpSpace *space, cpBody *body); void cpSpaceRemoveBody(cpSpace *space, cpBody *body);
/// Remove a constraint from the simulation.
void cpSpaceRemoveConstraint(cpSpace *space, cpConstraint *constraint); void cpSpaceRemoveConstraint(cpSpace *space, cpConstraint *constraint);
// Post Step function definition /// Test if a collision shape has been added to the space.
cpBool cpSpaceContainsShape(cpSpace *space, cpShape *shape);
/// Test if a rigid body has been added to the space.
cpBool cpSpaceContainsBody(cpSpace *space, cpBody *body);
/// Test if a constraint has been added to the space.
cpBool cpSpaceContainsConstraint(cpSpace *space, cpConstraint *constraint);
/// Post Step callback function type.
typedef void (*cpPostStepFunc)(cpSpace *space, void *obj, void *data); typedef void (*cpPostStepFunc)(cpSpace *space, void *obj, void *data);
// Register a post step function to be called after cpSpaceStep() has finis /// Schedule a post-step callback to be called when cpSpaceStep() finishes.
hed. /// You can only register one callback per unique value for @c key.
// obj is used a key, you can only register one callback per unique value f void cpSpaceAddPostStepCallback(cpSpace *space, cpPostStepFunc func, void *
or obj key, void *data);
void cpSpaceAddPostStepCallback(cpSpace *space, cpPostStepFunc func, void *
obj, void *data);
// Point query callback function /// Point query callback function type.
typedef void (*cpSpacePointQueryFunc)(cpShape *shape, void *data); typedef void (*cpSpacePointQueryFunc)(cpShape *shape, void *data);
/// Query the space at a point and call @c func for each shape found.
void cpSpacePointQuery(cpSpace *space, cpVect point, cpLayers layers, cpGro up group, cpSpacePointQueryFunc func, void *data); void cpSpacePointQuery(cpSpace *space, cpVect point, cpLayers layers, cpGro up group, cpSpacePointQueryFunc func, void *data);
/// Query the space at a point and return the first shape found. Returns NU LL if no shapes were found.
cpShape *cpSpacePointQueryFirst(cpSpace *space, cpVect point, cpLayers laye rs, cpGroup group); cpShape *cpSpacePointQueryFirst(cpSpace *space, cpVect point, cpLayers laye rs, cpGroup group);
// Segment query callback function /// Nearest point query callback function type.
typedef void (*cpSpaceNearestPointQueryFunc)(cpShape *shape, cpFloat distan
ce, 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 maxDist
ance, cpLayers layers, cpGroup group, cpSpaceNearestPointQueryFunc func, vo
id *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, cpFl
oat maxDistance, cpLayers layers, cpGroup group, cpNearestPointQueryInfo *o
ut);
/// 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 spac e calling @c func for each shape intersected.
void cpSpaceSegmentQuery(cpSpace *space, cpVect start, cpVect end, cpLayers layers, cpGroup group, cpSpaceSegmentQueryFunc func, void *data); void cpSpaceSegmentQuery(cpSpace *space, cpVect start, cpVect end, cpLayers layers, cpGroup group, cpSpaceSegmentQueryFunc func, void *data);
/// Perform a directed line segment query (like a raycast) against the spac e and return the first shape hit. Returns NULL if no shapes were hit.
cpShape *cpSpaceSegmentQueryFirst(cpSpace *space, cpVect start, cpVect end, cpLayers layers, cpGroup group, cpSegmentQueryInfo *out); cpShape *cpSpaceSegmentQueryFirst(cpSpace *space, cpVect start, cpVect end, cpLayers layers, cpGroup group, cpSegmentQueryInfo *out);
// BB query callback function /// Rectangle Query callback function type.
typedef void (*cpSpaceBBQueryFunc)(cpShape *shape, void *data); typedef void (*cpSpaceBBQueryFunc)(cpShape *shape, void *data);
/// Perform a fast rectangle query on the space calling @c func for each sh
ape found.
/// Only the shape's bounding boxes are checked for overlap, not their full
shape.
void cpSpaceBBQuery(cpSpace *space, cpBB bb, cpLayers layers, cpGroup group , cpSpaceBBQueryFunc func, void *data); void cpSpaceBBQuery(cpSpace *space, cpBB bb, cpLayers layers, cpGroup group , cpSpaceBBQueryFunc func, void *data);
// Shape query callback function /// Shape query callback function type.
typedef void (*cpSpaceShapeQueryFunc)(cpShape *shape, cpContactPointSet *po ints, void *data); typedef void (*cpSpaceShapeQueryFunc)(cpShape *shape, cpContactPointSet *po ints, void *data);
/// Query a space for any shapes overlapping the given shape and call @c fu nc for each shape found.
cpBool cpSpaceShapeQuery(cpSpace *space, cpShape *shape, cpSpaceShapeQueryF unc func, void *data); cpBool cpSpaceShapeQuery(cpSpace *space, cpShape *shape, cpSpaceShapeQueryF unc func, void *data);
/// Call cpBodyActivate() for any shape that is overlaps the given shape.
void cpSpaceActivateShapesTouchingShape(cpSpace *space, cpShape *shape); void cpSpaceActivateShapesTouchingShape(cpSpace *space, cpShape *shape);
// Iterator function for iterating the bodies in a space. /// Space/body iterator callback function type.
typedef void (*cpSpaceBodyIterator)(cpBody *body, void *data); typedef void (*cpSpaceBodyIteratorFunc)(cpBody *body, void *data);
void cpSpaceEachBody(cpSpace *space, cpSpaceBodyIterator func, void *data); /// Call @c func for each body in the space.
void cpSpaceEachBody(cpSpace *space, cpSpaceBodyIteratorFunc func, void *da
// Spatial hash management functions. ta);
void cpSpaceResizeStaticHash(cpSpace *space, cpFloat dim, int count);
void cpSpaceResizeActiveHash(cpSpace *space, cpFloat dim, int count); /// Space/body iterator callback function type.
void cpSpaceRehashStatic(cpSpace *space); typedef void (*cpSpaceShapeIteratorFunc)(cpShape *shape, void *data);
/// Call @c func for each shape in the space.
void cpSpaceEachShape(cpSpace *space, cpSpaceShapeIteratorFunc func, void *
data);
/// Space/constraint iterator callback function type.
typedef void (*cpSpaceConstraintIteratorFunc)(cpConstraint *constraint, voi
d *data);
/// Call @c func for each shape in the space.
void cpSpaceEachConstraint(cpSpace *space, cpSpaceConstraintIteratorFunc fu
nc, void *data);
/// Update the collision detection info for the static shapes in the space.
void cpSpaceReindexStatic(cpSpace *space);
/// Update the collision detection data for a specific shape in the space.
void cpSpaceReindexShape(cpSpace *space, cpShape *shape);
/// Update the collision detection data for all shapes attached to a body.
void cpSpaceReindexShapesForBody(cpSpace *space, cpBody *body);
void cpSpaceRehashShape(cpSpace *space, cpShape *shape); /// Switch the space to use a spatial has as it's spatial index.
void cpSpaceUseSpatialHash(cpSpace *space, cpFloat dim, int count);
// Update the space. /// Step the space forward in time by @c dt.
void cpSpaceStep(cpSpace *space, cpFloat dt); void cpSpaceStep(cpSpace *space, cpFloat dt);
/// @}
 End of changes. 52 change blocks. 
117 lines changed or deleted 207 lines changed or added


 cpVect.h   cpVect.h 
skipping to change at line 22 skipping to change at line 22
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * 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 I N THE * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS I N THE
* SOFTWARE. * SOFTWARE.
*/ */
/// @defgroup cpVect cpVect
/// Chipmunk's 2D vector type along with a handy 2D vector math lib.
/// @{
/// Constant for the zero vector. /// Constant for the zero vector.
static const cpVect cpvzero = {0.0f,0.0f}; static const cpVect cpvzero = {0.0f,0.0f};
/// Convenience constructor for cpVect structs. /// Convenience constructor for cpVect structs.
static inline cpVect static inline cpVect cpv(const cpFloat x, const cpFloat y)
cpv(const cpFloat x, const cpFloat y)
{ {
cpVect v = {x, y}; cpVect v = {x, y};
return v; return v;
} }
// non-inlined functions
/// Returns the length of v. /// Returns the length of v.
cpFloat cpvlength(const cpVect v); cpFloat cpvlength(const cpVect v);
/// Spherical linearly interpolate between v1 and v2. /// Spherical linearly interpolate between v1 and v2.
cpVect cpvslerp(const cpVect v1, const cpVect v2, const cpFloat t); cpVect cpvslerp(const cpVect v1, const cpVect v2, const cpFloat t);
/// Spherical linearly interpolate between v1 towards v2 by no more than an gle a radians /// Spherical linearly interpolate between v1 towards v2 by no more than an gle a radians
cpVect cpvslerpconst(const cpVect v1, const cpVect v2, const cpFloat a); cpVect cpvslerpconst(const cpVect v1, const cpVect v2, const cpFloat a);
/// Returns the unit length vector for the given angle (in radians). /// Returns the unit length vector for the given angle (in radians).
cpVect cpvforangle(const cpFloat a); 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
Returns a string representation of v. Intended mostly for debugging purposes and not production use.
purposes and not production use. /// @attention The string points to a static local and is reset every ti
me the function is called.
@attention The string points to a static local and is reset every ti /// If you want to print more than one vector you will have to split up
me the function is called. your printing onto separate lines.
If you want to print more than one vector you will have to split up char* cpvstr(const cpVect v);
your printing onto separate lines.
*/
char *cpvstr(const cpVect v);
/// Check if two vectors are equal. (Be careful when comparing floating poi nt numbers!) /// Check if two vectors are equal. (Be careful when comparing floating poi nt numbers!)
static inline cpBool static inline cpBool cpveql(const cpVect v1, const cpVect v2)
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 static inline cpVect cpvadd(const cpVect v1, const cpVect v2)
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);
} }
/// Negate a vector. /// Subtract two vectors.
static inline cpVect static inline cpVect cpvsub(const cpVect v1, const cpVect v2)
cpvneg(const cpVect v)
{ {
return cpv(-v.x, -v.y); return cpv(v1.x - v2.x, v1.y - v2.y);
} }
/// Subtract two vectors. /// Negate a vector.
static inline cpVect static inline cpVect cpvneg(const cpVect v)
cpvsub(const cpVect v1, const cpVect v2)
{ {
return cpv(v1.x - v2.x, v1.y - v2.y); return cpv(-v.x, -v.y);
} }
/// Scalar multiplication. /// Scalar multiplication.
static inline cpVect static inline cpVect cpvmult(const cpVect v, const cpFloat s)
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 static inline cpFloat cpvdot(const cpVect v1, const cpVect v2)
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. /// The cross product of 2D vectors results in a 3D vector with only a z co
The cross product of 2D vectors results in a 3D vector with only a z mponent.
component. /// 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 static inline cpVect cpvperp(const cpVect v)
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 static inline cpVect cpvrperp(const cpVect v)
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 static inline cpVect cpvproject(const cpVect v1, const cpVect v2)
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 occ ur if v1 is not a unit vector. /// Uses complex number multiplication to rotate v1 by v2. Scaling will occ ur if v1 is not a unit vector.
static inline cpVect static inline cpVect cpvrotate(const cpVect v1, const cpVect v2)
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 static inline cpVect cpvunrotate(const cpVect v1, const cpVect v2)
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 static inline cpFloat cpvlengthsq(const cpVect v)
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 static inline cpVect cpvlerp(const cpVect v1, const cpVect v2, const cpFloa
cpvlerp(const cpVect v1, const cpVect v2, const cpFloat t) t 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 static inline cpVect cpvnormalize(const cpVect v)
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. Pro tects against divide by zero errors. /// Returns a normalized copy of v or cpvzero if v was already cpvzero. Pro tects against divide by zero errors.
static inline cpVect static inline cpVect cpvnormalize_safe(const cpVect v)
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 static inline cpVect cpvclamp(const cpVect v, const cpFloat len)
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 static inline cpVect cpvlerpconst(cpVect v1, cpVect v2, cpFloat d)
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 static inline cpFloat cpvdist(const cpVect v1, const cpVect v2)
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() w hen you only need to compare distances. /// Returns the squared distance between v1 and v2. Faster than cpvdist() w hen you only need to compare distances.
static inline cpFloat static inline cpFloat cpvdistsq(const cpVect v1, const cpVect v2)
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 static inline cpBool cpvnear(const cpVect v1, const cpVect v2, const cpFloa
cpvnear(const cpVect v1, const cpVect v2, const cpFloat dist) t dist)
{ {
return cpvdistsq(v1, v2) < dist*dist; return cpvdistsq(v1, v2) < dist*dist;
} }
/// @}
 End of changes. 28 change blocks. 
66 lines changed or deleted 43 lines changed or added


 crypt.h   crypt.h 
/* crypt.h -- base code for crypt/uncrypt ZIPfile #pragma GCC system_header
#pragma GCC visibility push(default)
Version 1.01e, February 12th, 2005 #include_next <crypt.h>
#pragma GCC visibility pop
Copyright (C) 1998-2005 Gilles Vollant
This code is a modified version of crypting code in Infozip distribution
The encryption/decryption parts of this source code (as opposed to the
non-echoing password parts) were originally written in Europe. The
whole source package can be freely distributed, including from the USA.
(Prior to January 2000, re-export from the US was a violation of US law.
)
This encryption code is a direct transcription of the algorithm from
Roger Schlafly, described by Phil Katz in the file appnote.txt. This
file (appnote.txt) is distributed with the PKZIP program (even in the
version without encryption capabilities).
If you don't need crypting in your application, just define symbols
NOCRYPT and NOUNCRYPT.
This code support the "Traditional PKWARE Encryption".
The new AES encryption added on Zip format by Winzip (see the page
http://www.winzip.com/aes_info.htm ) and PKWare PKZip 5.x Strong
Encryption is not supported.
*/
#define CRC32(c, b) ((*(pcrc_32_tab+(((int)(c) ^ (b)) & 0xff))) ^ ((c) >> 8
))
/***********************************************************************
* Return the next byte in the pseudo-random sequence
*/
static int decrypt_byte(unsigned long* pkeys, const unsigned long* pcrc_32_
tab)
{
unsigned temp; /* POTENTIAL BUG: temp*(temp^1) may overflow in an
* unpredictable manner on 16-bit systems; not a proble
m
* with any known compiler so far, though */
temp = ((unsigned)(*(pkeys+2)) & 0xffff) | 2;
return (int)(((temp * (temp ^ 1)) >> 8) & 0xff);
}
/***********************************************************************
* Update the encryption keys with the next byte of plain text
*/
static int update_keys(unsigned long* pkeys,const unsigned long* pcrc_32_ta
b,int c)
{
(*(pkeys+0)) = CRC32((*(pkeys+0)), c);
(*(pkeys+1)) += (*(pkeys+0)) & 0xff;
(*(pkeys+1)) = (*(pkeys+1)) * 134775813L + 1;
{
register int keyshift = (int)((*(pkeys+1)) >> 24);
(*(pkeys+2)) = CRC32((*(pkeys+2)), keyshift);
}
return c;
}
/***********************************************************************
* Initialize the encryption keys and the random header according to
* the given password.
*/
static void init_keys(const char* passwd,unsigned long* pkeys,const unsigne
d long* pcrc_32_tab)
{
*(pkeys+0) = 305419896L;
*(pkeys+1) = 591751049L;
*(pkeys+2) = 878082192L;
while (*passwd != '\0') {
update_keys(pkeys,pcrc_32_tab,(int)*passwd);
passwd++;
}
}
#define zdecode(pkeys,pcrc_32_tab,c) \
(update_keys(pkeys,pcrc_32_tab,c ^= decrypt_byte(pkeys,pcrc_32_tab)))
#define zencode(pkeys,pcrc_32_tab,c,t) \
(t=decrypt_byte(pkeys,pcrc_32_tab), update_keys(pkeys,pcrc_32_tab,c), t
^(c))
#ifdef INCLUDECRYPTINGCODE_IFCRYPTALLOWED
#define RAND_HEAD_LEN 12
/* "last resort" source for second part of crypt seed pattern */
# ifndef ZCR_SEED2
# define ZCR_SEED2 3141592654UL /* use PI as default pattern */
# endif
static int crypthead(passwd, buf, bufSize, pkeys, pcrc_32_tab, crcForCrypti
ng)
const char *passwd; /* password string */
unsigned char *buf; /* where to write header */
int bufSize;
unsigned long* pkeys;
const unsigned long* pcrc_32_tab;
unsigned long crcForCrypting;
{
int n; /* index in random header */
int t; /* temporary */
int c; /* random byte */
unsigned char header[RAND_HEAD_LEN-2]; /* random header */
static unsigned calls = 0; /* ensure different random header each tim
e */
if (bufSize<RAND_HEAD_LEN)
return 0;
/* First generate RAND_HEAD_LEN-2 random bytes. We encrypt the
* output of rand() to get less predictability, since rand() is
* often poorly implemented.
*/
if (++calls == 1)
{
srand((unsigned)(time(NULL) ^ ZCR_SEED2));
}
init_keys(passwd, pkeys, pcrc_32_tab);
for (n = 0; n < RAND_HEAD_LEN-2; n++)
{
c = (rand() >> 7) & 0xff;
header[n] = (unsigned char)zencode(pkeys, pcrc_32_tab, c, t);
}
/* Encrypt random header (last two bytes is high word of crc) */
init_keys(passwd, pkeys, pcrc_32_tab);
for (n = 0; n < RAND_HEAD_LEN-2; n++)
{
buf[n] = (unsigned char)zencode(pkeys, pcrc_32_tab, header[n], t);
}
buf[n++] = zencode(pkeys, pcrc_32_tab, (int)(crcForCrypting >> 16) & 0x
ff, t);
buf[n++] = zencode(pkeys, pcrc_32_tab, (int)(crcForCrypting >> 24) & 0x
ff, t);
return n;
}
#endif
 End of changes. 1 change blocks. 
lines changed or deleted lines changed or added


 debugXML.h   debugXML.h 
skipping to change at line 29 skipping to change at line 29
#include <libxml/xpath.h> #include <libxml/xpath.h>
#ifdef __cplusplus #ifdef __cplusplus
extern "C" { extern "C" {
#endif #endif
/* /*
* The standard Dump routines. * The standard Dump routines.
*/ */
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlDebugDumpString (FILE *output, xmlDebugDumpString (FILE *output,
const xmlChar *str); const xmlChar *str);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlDebugDumpAttr (FILE *output, xmlDebugDumpAttr (FILE *output,
xmlAttrPtr attr, xmlAttrPtr attr,
int depth); int depth);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlDebugDumpAttrList (FILE *output, xmlDebugDumpAttrList (FILE *output,
xmlAttrPtr attr, xmlAttrPtr attr,
int depth); int depth);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlDebugDumpOneNode (FILE *output, xmlDebugDumpOneNode (FILE *output,
xmlNodePtr node, xmlNodePtr node,
int depth); int depth);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlDebugDumpNode (FILE *output, xmlDebugDumpNode (FILE *output,
xmlNodePtr node, xmlNodePtr node,
int depth); int depth);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlDebugDumpNodeList (FILE *output, xmlDebugDumpNodeList (FILE *output,
xmlNodePtr node, xmlNodePtr node,
int depth); int depth);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlDebugDumpDocumentHead(FILE *output, xmlDebugDumpDocumentHead(FILE *output,
xmlDocPtr doc); xmlDocPtr doc);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlDebugDumpDocument (FILE *output, xmlDebugDumpDocument (FILE *output,
xmlDocPtr doc); xmlDocPtr doc);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlDebugDumpDTD (FILE *output, xmlDebugDumpDTD (FILE *output,
xmlDtdPtr dtd); xmlDtdPtr dtd);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlDebugDumpEntities (FILE *output, xmlDebugDumpEntities (FILE *output,
xmlDocPtr doc); xmlDocPtr doc);
/**************************************************************** /****************************************************************
* * * *
* Checking routines * * Checking routines *
* * * *
****************************************************************/ ****************************************************************/
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlDebugCheckDocument (FILE * output, xmlDebugCheckDocument (FILE * output,
xmlDocPtr doc); xmlDocPtr doc);
/**************************************************************** /****************************************************************
* * * *
* XML shell helpers * * XML shell helpers *
* * * *
****************************************************************/ ****************************************************************/
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlLsOneNode (FILE *output, xmlNodePtr node); xmlLsOneNode (FILE *output, xmlNodePtr node);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlLsCountNode (xmlNodePtr node); xmlLsCountNode (xmlNodePtr node);
XMLPUBFUN const char * XMLCALL XMLPUBFUN const char * XMLCALL
xmlBoolToText (int boolval); xmlBoolToText (int boolval);
/**************************************************************** /****************************************************************
* * * *
* The XML shell related structures and functions * * The XML shell related structures and functions *
* * * *
****************************************************************/ ****************************************************************/
#ifdef LIBXML_XPATH_ENABLED #ifdef LIBXML_XPATH_ENABLED
/** /**
* xmlShellReadlineFunc: * xmlShellReadlineFunc:
* @prompt: a string prompt * @prompt: a string prompt
* *
* This is a generic signature for the XML shell input function. * This is a generic signature for the XML shell input function.
* *
* Returns a string which will be freed by the Shell. * Returns a string which will be freed by the Shell.
skipping to change at line 136 skipping to change at line 136
* @arg: a string argument * @arg: a string argument
* @node: a first node * @node: a first node
* @node2: a second node * @node2: a second node
* *
* This is a generic signature for the XML shell functions. * This is a generic signature for the XML shell functions.
* *
* Returns an int, negative returns indicating errors. * Returns an int, negative returns indicating errors.
*/ */
typedef int (* xmlShellCmd) (xmlShellCtxtPtr ctxt, typedef int (* xmlShellCmd) (xmlShellCtxtPtr ctxt,
char *arg, char *arg,
xmlNodePtr node, xmlNodePtr node,
xmlNodePtr node2); xmlNodePtr node2);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlShellPrintXPathError (int errorType, xmlShellPrintXPathError (int errorType,
const char *arg); const char *arg);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlShellPrintXPathResult(xmlXPathObjectPtr list); xmlShellPrintXPathResult(xmlXPathObjectPtr list);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlShellList (xmlShellCtxtPtr ctxt, xmlShellList (xmlShellCtxtPtr ctxt,
char *arg, char *arg,
xmlNodePtr node, xmlNodePtr node,
xmlNodePtr node2); xmlNodePtr node2);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlShellBase (xmlShellCtxtPtr ctxt, xmlShellBase (xmlShellCtxtPtr ctxt,
char *arg, char *arg,
xmlNodePtr node, xmlNodePtr node,
xmlNodePtr node2); xmlNodePtr node2);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlShellDir (xmlShellCtxtPtr ctxt, xmlShellDir (xmlShellCtxtPtr ctxt,
char *arg, char *arg,
xmlNodePtr node, xmlNodePtr node,
xmlNodePtr node2); xmlNodePtr node2);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlShellLoad (xmlShellCtxtPtr ctxt, xmlShellLoad (xmlShellCtxtPtr ctxt,
char *filename, char *filename,
xmlNodePtr node, xmlNodePtr node,
xmlNodePtr node2); xmlNodePtr node2);
#ifdef LIBXML_OUTPUT_ENABLED #ifdef LIBXML_OUTPUT_ENABLED
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlShellPrintNode (xmlNodePtr node); xmlShellPrintNode (xmlNodePtr node);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlShellCat (xmlShellCtxtPtr ctxt, xmlShellCat (xmlShellCtxtPtr ctxt,
char *arg, char *arg,
xmlNodePtr node, xmlNodePtr node,
xmlNodePtr node2); xmlNodePtr node2);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlShellWrite (xmlShellCtxtPtr ctxt, xmlShellWrite (xmlShellCtxtPtr ctxt,
char *filename, char *filename,
xmlNodePtr node, xmlNodePtr node,
xmlNodePtr node2); xmlNodePtr node2);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlShellSave (xmlShellCtxtPtr ctxt, xmlShellSave (xmlShellCtxtPtr ctxt,
char *filename, char *filename,
xmlNodePtr node, xmlNodePtr node,
xmlNodePtr node2); xmlNodePtr node2);
#endif /* LIBXML_OUTPUT_ENABLED */ #endif /* LIBXML_OUTPUT_ENABLED */
#ifdef LIBXML_VALID_ENABLED #ifdef LIBXML_VALID_ENABLED
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlShellValidate (xmlShellCtxtPtr ctxt, xmlShellValidate (xmlShellCtxtPtr ctxt,
char *dtd, char *dtd,
xmlNodePtr node, xmlNodePtr node,
xmlNodePtr node2); xmlNodePtr node2);
#endif /* LIBXML_VALID_ENABLED */ #endif /* LIBXML_VALID_ENABLED */
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlShellDu (xmlShellCtxtPtr ctxt, xmlShellDu (xmlShellCtxtPtr ctxt,
char *arg, char *arg,
xmlNodePtr tree, xmlNodePtr tree,
xmlNodePtr node2); xmlNodePtr node2);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlShellPwd (xmlShellCtxtPtr ctxt, xmlShellPwd (xmlShellCtxtPtr ctxt,
char *buffer, char *buffer,
xmlNodePtr node, xmlNodePtr node,
xmlNodePtr node2); xmlNodePtr node2);
/* /*
* The Shell interface. * The Shell interface.
*/ */
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlShell (xmlDocPtr doc, xmlShell (xmlDocPtr doc,
char *filename, char *filename,
xmlShellReadlineFunc input, xmlShellReadlineFunc input,
FILE *output); FILE *output);
#endif /* LIBXML_XPATH_ENABLED */ #endif /* LIBXML_XPATH_ENABLED */
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif
#endif /* LIBXML_DEBUG_ENABLED */ #endif /* LIBXML_DEBUG_ENABLED */
#endif /* __DEBUG_XML__ */ #endif /* __DEBUG_XML__ */
 End of changes. 26 change blocks. 
95 lines changed or deleted 95 lines changed or added


 dict.h   dict.h 
skipping to change at line 31 skipping to change at line 31
/* /*
* The dictionnary. * The dictionnary.
*/ */
typedef struct _xmlDict xmlDict; typedef struct _xmlDict xmlDict;
typedef xmlDict *xmlDictPtr; typedef xmlDict *xmlDictPtr;
/* /*
* Constructor and destructor. * Constructor and destructor.
*/ */
XMLPUBFUN xmlDictPtr XMLCALL XMLPUBFUN xmlDictPtr XMLCALL
xmlDictCreate (void); xmlDictCreate (void);
XMLPUBFUN xmlDictPtr XMLCALL XMLPUBFUN xmlDictPtr XMLCALL
xmlDictCreateSub(xmlDictPtr sub); xmlDictCreateSub(xmlDictPtr sub);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlDictReference(xmlDictPtr dict); xmlDictReference(xmlDictPtr dict);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlDictFree (xmlDictPtr dict); xmlDictFree (xmlDictPtr dict);
/* /*
* Lookup of entry in the dictionnary. * Lookup of entry in the dictionnary.
*/ */
XMLPUBFUN const xmlChar * XMLCALL XMLPUBFUN const xmlChar * XMLCALL
xmlDictLookup (xmlDictPtr dict, xmlDictLookup (xmlDictPtr dict,
const xmlChar *name, const xmlChar *name,
int len); int len);
XMLPUBFUN const xmlChar * XMLCALL XMLPUBFUN const xmlChar * XMLCALL
xmlDictExists (xmlDictPtr dict, xmlDictExists (xmlDictPtr dict,
const xmlChar *name, const xmlChar *name,
int len); int len);
XMLPUBFUN const xmlChar * XMLCALL XMLPUBFUN const xmlChar * XMLCALL
xmlDictQLookup (xmlDictPtr dict, xmlDictQLookup (xmlDictPtr dict,
const xmlChar *prefix, const xmlChar *prefix,
const xmlChar *name); const xmlChar *name);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlDictOwns (xmlDictPtr dict, xmlDictOwns (xmlDictPtr dict,
const xmlChar *str); const xmlChar *str);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlDictSize (xmlDictPtr dict); xmlDictSize (xmlDictPtr dict);
/* /*
* Cleanup function * Cleanup function
*/ */
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlDictCleanup (void); xmlDictCleanup (void);
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif
 End of changes. 9 change blocks. 
16 lines changed or deleted 16 lines changed or added


 globals.h   globals.h 
skipping to change at line 67 skipping to change at line 67
XMLPUBFUN xmlParserInputBufferCreateFilenameFunc XMLPUBFUN xmlParserInputBufferCreateFilenameFunc
XMLCALL xmlParserInputBufferCreateFilenameDefault (xmlParserInputBufferCrea teFilenameFunc func); XMLCALL xmlParserInputBufferCreateFilenameDefault (xmlParserInputBufferCrea teFilenameFunc func);
XMLPUBFUN xmlOutputBufferCreateFilenameFunc XMLPUBFUN xmlOutputBufferCreateFilenameFunc
XMLCALL xmlOutputBufferCreateFilenameDefault (xmlOutputBufferCreateFilename Func func); XMLCALL xmlOutputBufferCreateFilenameDefault (xmlOutputBufferCreateFilename Func func);
/* /*
* Externally global symbols which need to be protected for backwards * Externally global symbols which need to be protected for backwards
* compatibility support. * compatibility support.
*/ */
#undef docbDefaultSAXHandler #undef docbDefaultSAXHandler
#undef htmlDefaultSAXHandler #undef htmlDefaultSAXHandler
#undef oldXMLWDcompatibility #undef oldXMLWDcompatibility
#undef xmlBufferAllocScheme #undef xmlBufferAllocScheme
#undef xmlDefaultBufferSize #undef xmlDefaultBufferSize
#undef xmlDefaultSAXHandler #undef xmlDefaultSAXHandler
#undef xmlDefaultSAXLocator #undef xmlDefaultSAXLocator
#undef xmlDoValidityCheckingDefaultValue #undef xmlDoValidityCheckingDefaultValue
#undef xmlFree #undef xmlFree
#undef xmlGenericError #undef xmlGenericError
#undef xmlStructuredError #undef xmlStructuredError
#undef xmlGenericErrorContext #undef xmlGenericErrorContext
#undef xmlStructuredErrorContext #undef xmlStructuredErrorContext
#undef xmlGetWarningsDefaultValue #undef xmlGetWarningsDefaultValue
#undef xmlIndentTreeOutput #undef xmlIndentTreeOutput
#undef xmlTreeIndentString #undef xmlTreeIndentString
#undef xmlKeepBlanksDefaultValue #undef xmlKeepBlanksDefaultValue
#undef xmlLineNumbersDefaultValue #undef xmlLineNumbersDefaultValue
#undef xmlLoadExtDtdDefaultValue #undef xmlLoadExtDtdDefaultValue
#undef xmlMalloc #undef xmlMalloc
#undef xmlMallocAtomic #undef xmlMallocAtomic
#undef xmlMemStrdup #undef xmlMemStrdup
#undef xmlParserDebugEntities #undef xmlParserDebugEntities
#undef xmlParserVersion #undef xmlParserVersion
#undef xmlPedanticParserDefaultValue #undef xmlPedanticParserDefaultValue
#undef xmlRealloc #undef xmlRealloc
#undef xmlSaveNoEmptyTags #undef xmlSaveNoEmptyTags
#undef xmlSubstituteEntitiesDefaultValue #undef xmlSubstituteEntitiesDefaultValue
#undef xmlRegisterNodeDefaultValue #undef xmlRegisterNodeDefaultValue
#undef xmlDeregisterNodeDefaultValue #undef xmlDeregisterNodeDefaultValue
#undef xmlLastError #undef xmlLastError
#undef xmlParserInputBufferCreateFilenameValue #undef xmlParserInputBufferCreateFilenameValue
#undef xmlOutputBufferCreateFilenameValue #undef xmlOutputBufferCreateFilenameValue
/** /**
* xmlRegisterNodeFunc: * xmlRegisterNodeFunc:
* @node: the current node * @node: the current node
* *
skipping to change at line 120 skipping to change at line 120
* @node: the current node * @node: the current node
* *
* Signature for the deregistration callback of a discarded node * Signature for the deregistration callback of a discarded node
*/ */
typedef void (*xmlDeregisterNodeFunc) (xmlNodePtr node); typedef void (*xmlDeregisterNodeFunc) (xmlNodePtr node);
typedef struct _xmlGlobalState xmlGlobalState; typedef struct _xmlGlobalState xmlGlobalState;
typedef xmlGlobalState *xmlGlobalStatePtr; typedef xmlGlobalState *xmlGlobalStatePtr;
struct _xmlGlobalState struct _xmlGlobalState
{ {
const char *xmlParserVersion; const char *xmlParserVersion;
xmlSAXLocator xmlDefaultSAXLocator; xmlSAXLocator xmlDefaultSAXLocator;
xmlSAXHandlerV1 xmlDefaultSAXHandler; xmlSAXHandlerV1 xmlDefaultSAXHandler;
xmlSAXHandlerV1 docbDefaultSAXHandler; xmlSAXHandlerV1 docbDefaultSAXHandler;
xmlSAXHandlerV1 htmlDefaultSAXHandler; xmlSAXHandlerV1 htmlDefaultSAXHandler;
xmlFreeFunc xmlFree; xmlFreeFunc xmlFree;
xmlMallocFunc xmlMalloc; xmlMallocFunc xmlMalloc;
xmlStrdupFunc xmlMemStrdup; xmlStrdupFunc xmlMemStrdup;
xmlReallocFunc xmlRealloc; xmlReallocFunc xmlRealloc;
xmlGenericErrorFunc xmlGenericError; xmlGenericErrorFunc xmlGenericError;
xmlStructuredErrorFunc xmlStructuredError; xmlStructuredErrorFunc xmlStructuredError;
void *xmlGenericErrorContext; void *xmlGenericErrorContext;
int oldXMLWDcompatibility; int oldXMLWDcompatibility;
xmlBufferAllocationScheme xmlBufferAllocScheme; xmlBufferAllocationScheme xmlBufferAllocScheme;
int xmlDefaultBufferSize; int xmlDefaultBufferSize;
int xmlSubstituteEntitiesDefaultValue; int xmlSubstituteEntitiesDefaultValue;
int xmlDoValidityCheckingDefaultValue; int xmlDoValidityCheckingDefaultValue;
int xmlGetWarningsDefaultValue; int xmlGetWarningsDefaultValue;
int xmlKeepBlanksDefaultValue; int xmlKeepBlanksDefaultValue;
int xmlLineNumbersDefaultValue; int xmlLineNumbersDefaultValue;
int xmlLoadExtDtdDefaultValue; int xmlLoadExtDtdDefaultValue;
int xmlParserDebugEntities; int xmlParserDebugEntities;
int xmlPedanticParserDefaultValue; int xmlPedanticParserDefaultValue;
int xmlSaveNoEmptyTags; int xmlSaveNoEmptyTags;
int xmlIndentTreeOutput; int xmlIndentTreeOutput;
const char *xmlTreeIndentString; const char *xmlTreeIndentString;
xmlRegisterNodeFunc xmlRegisterNodeDefaultValue; xmlRegisterNodeFunc xmlRegisterNodeDefaultValue;
xmlDeregisterNodeFunc xmlDeregisterNodeDefaultValue; xmlDeregisterNodeFunc xmlDeregisterNodeDefaultValue;
xmlMallocFunc xmlMallocAtomic; xmlMallocFunc xmlMallocAtomic;
xmlError xmlLastError; xmlError xmlLastError;
xmlParserInputBufferCreateFilenameFunc xmlParserInputBufferCreateFil xmlParserInputBufferCreateFilenameFunc xmlParserInputBufferCreateFilena
enameValue; meValue;
xmlOutputBufferCreateFilenameFunc xmlOutputBufferCreateFilenameValue xmlOutputBufferCreateFilenameFunc xmlOutputBufferCreateFilenameValue;
;
void *xmlStructuredErrorContext; void *xmlStructuredErrorContext;
}; };
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif
#include <libxml/threads.h> #include <libxml/threads.h>
#ifdef __cplusplus #ifdef __cplusplus
extern "C" { extern "C" {
#endif #endif
XMLPUBFUN void XMLCALL xmlInitializeGlobalState(xmlGlobalStatePtr gs); XMLPUBFUN void XMLCALL xmlInitializeGlobalState(xmlGlobalStatePtr gs);
XMLPUBFUN void XMLCALL xmlThrDefSetGenericErrorFunc(void *ctx, xmlGenericEr rorFunc handler); XMLPUBFUN void XMLCALL xmlThrDefSetGenericErrorFunc(void *ctx, xmlGenericEr rorFunc handler);
XMLPUBFUN void XMLCALL xmlThrDefSetStructuredErrorFunc(void *ctx, xmlStruct uredErrorFunc handler); XMLPUBFUN void XMLCALL xmlThrDefSetStructuredErrorFunc(void *ctx, xmlStruct uredErrorFunc handler);
XMLPUBFUN xmlRegisterNodeFunc XMLCALL xmlRegisterNodeDefault(xmlRegisterNod eFunc func); XMLPUBFUN xmlRegisterNodeFunc XMLCALL xmlRegisterNodeDefault(xmlRegisterNod eFunc func);
XMLPUBFUN xmlRegisterNodeFunc XMLCALL xmlThrDefRegisterNodeDefault(xmlRegis terNodeFunc func); XMLPUBFUN xmlRegisterNodeFunc XMLCALL xmlThrDefRegisterNodeDefault(xmlRegis terNodeFunc func);
XMLPUBFUN xmlDeregisterNodeFunc XMLCALL xmlDeregisterNodeDefault(xmlDeregis terNodeFunc func); XMLPUBFUN xmlDeregisterNodeFunc XMLCALL xmlDeregisterNodeDefault(xmlDeregis terNodeFunc func);
XMLPUBFUN xmlDeregisterNodeFunc XMLCALL xmlThrDefDeregisterNodeDefault(xmlD eregisterNodeFunc func); XMLPUBFUN xmlDeregisterNodeFunc XMLCALL xmlThrDefDeregisterNodeDefault(xmlD eregisterNodeFunc func);
XMLPUBFUN xmlOutputBufferCreateFilenameFunc XMLCALL XMLPUBFUN xmlOutputBufferCreateFilenameFunc XMLCALL
xmlThrDefOutputBufferCreateFilenameDefault(xmlOutputBufferCreateFile nameFunc func); xmlThrDefOutputBufferCreateFilenameDefault(xmlOutputBufferCreateFilenam eFunc func);
XMLPUBFUN xmlParserInputBufferCreateFilenameFunc XMLCALL XMLPUBFUN xmlParserInputBufferCreateFilenameFunc XMLCALL
xmlThrDefParserInputBufferCreateFilenameDefault(xmlParserInputBuffer CreateFilenameFunc func); xmlThrDefParserInputBufferCreateFilenameDefault(xmlParserInputBufferCre ateFilenameFunc func);
/** DOC_DISABLE */ /** DOC_DISABLE */
/* /*
* In general the memory allocation entry points are not kept * In general the memory allocation entry points are not kept
* thread specific but this can be overridden by LIBXML_THREAD_ALLOC_ENABLE D * thread specific but this can be overridden by LIBXML_THREAD_ALLOC_ENABLE D
* - xmlMalloc * - xmlMalloc
* - xmlMallocAtomic * - xmlMallocAtomic
* - xmlRealloc * - xmlRealloc
* - xmlMemStrdup * - xmlMemStrdup
* - xmlFree * - xmlFree
 End of changes. 10 change blocks. 
72 lines changed or deleted 71 lines changed or added


 iconv.h   iconv.h 
skipping to change at line 59 skipping to change at line 59
/* Get size_t declaration. */ /* Get size_t declaration. */
#include <stddef.h> #include <stddef.h>
/* Get errno declaration and values. */ /* Get errno declaration and values. */
#include <errno.h> #include <errno.h>
/* Some systems, like SunOS 4, don't have EILSEQ. Some systems, like BSD/OS , /* Some systems, like SunOS 4, don't have EILSEQ. Some systems, like BSD/OS ,
have EILSEQ in a different header. On these systems, define EILSEQ have EILSEQ in a different header. On these systems, define EILSEQ
ourselves. */ ourselves. */
#ifndef EILSEQ #ifndef EILSEQ
/* Igor: called upon EILSEQ from glibc, since autogeneration of this header /* Igor: called upon EILSEQ from glibc, since autogeneration of this header
on Windows didn't do the job. */ on Windows didn't do the job. */
/* #define EILSEQ @EILSEQ@ */ /* #define EILSEQ @EILSEQ@ */
#define EILSEQ 84 #define EILSEQ 84
#endif #endif
#ifdef __cplusplus #ifdef __cplusplus
extern "C" { extern "C" {
#endif #endif
/* Allocates descriptor for code conversion from encoding `fromcode' to /* Allocates descriptor for code conversion from encoding `fromcode' to
encoding `tocode'. */ encoding `tocode'. */
skipping to change at line 121 skipping to change at line 121
void* data); void* data);
/* Support for relocatable packages. */ /* Support for relocatable packages. */
/* Sets the original and the current installation prefix of the package. /* Sets the original and the current installation prefix of the package.
Relocation simply replaces a pathname starting with the original prefix Relocation simply replaces a pathname starting with the original prefix
by the corresponding pathname with the current prefix instead. Both by the corresponding pathname with the current prefix instead. Both
prefixes should be directory names without trailing slash (i.e. use "" prefixes should be directory names without trailing slash (i.e. use ""
instead of "/"). */ instead of "/"). */
extern void libiconv_set_relocation_prefix (const char *orig_prefix, extern void libiconv_set_relocation_prefix (const char *orig_prefix,
const char *curr_prefix); const char *curr_prefix);
#endif #endif
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif
#endif /* _LIBICONV_H */ #endif /* _LIBICONV_H */
 End of changes. 2 change blocks. 
2 lines changed or deleted 2 lines changed or added


 ioapi.h   ioapi.h 
skipping to change at line 24 skipping to change at line 24
Oct-2009 - Change to fseeko64, ftello64 and fopen64 so large files woul d work on linux. Oct-2009 - Change to fseeko64, ftello64 and fopen64 so large files woul d work on linux.
More if/def section may be needed to support other platforms More if/def section may be needed to support other platforms
Oct-2009 - Defined fxxxx64 calls to normal fopen/ftell/fseek so they wo uld compile on windows. Oct-2009 - Defined fxxxx64 calls to normal fopen/ftell/fseek so they wo uld compile on windows.
(but you should use iowin32.c for windows instead ) (but you should use iowin32.c for windows instead )
*/ */
#ifndef _ZLIBIOAPI64_H #ifndef _ZLIBIOAPI64_H
#define _ZLIBIOAPI64_H #define _ZLIBIOAPI64_H
#include "CCPlatformConfig.h" #include "platform/CCPlatformConfig.h"
#if (!defined(_WIN32)) && (!defined(WIN32)) #if (!defined(_WIN32)) && (!defined(WIN32))
// Linux needs this to support file operation on files larger then 4+GB // Linux needs this to support file operation on files larger then 4+GB
// But might need better if/def to select just the platforms that needs t hem. // But might need better if/def to select just the platforms that needs t hem.
#ifndef __USE_FILE_OFFSET64 #ifndef __USE_FILE_OFFSET64
#define __USE_FILE_OFFSET64 #define __USE_FILE_OFFSET64
#endif #endif
#ifndef __USE_LARGEFILE64 #ifndef __USE_LARGEFILE64
 End of changes. 1 change blocks. 
1 lines changed or deleted 1 lines changed or added


 jconfig.h   jconfig.h 
/* jconfig.dj --- jconfig.h for DJGPP (Delorie's GNU C port) on MS-DOS. */ /* jconfig.vc --- jconfig.h for Microsoft Visual C++ on Windows 95 or NT. *
/* see jconfig.doc for explanations */ /
/* see jconfig.txt for explanations */
#define HAVE_PROTOTYPES #define HAVE_PROTOTYPES
#define HAVE_UNSIGNED_CHAR #define HAVE_UNSIGNED_CHAR
#define HAVE_UNSIGNED_SHORT #define HAVE_UNSIGNED_SHORT
/* #define void char */ /* #define void char */
/* #define const */ /* #define const */
#undef CHAR_IS_UNSIGNED #undef CHAR_IS_UNSIGNED
#define HAVE_STDDEF_H #define HAVE_STDDEF_H
#define HAVE_STDLIB_H #define HAVE_STDLIB_H
#undef NEED_BSD_STRINGS #undef NEED_BSD_STRINGS
#undef NEED_SYS_TYPES_H #undef NEED_SYS_TYPES_H
#undef NEED_FAR_POINTERS /* DJGPP uses flat 32-bit addressing */ #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
#undef NEED_SHORT_EXTERNAL_NAMES #undef NEED_SHORT_EXTERNAL_NAMES
#undef INCOMPLETE_TYPES_BROKEN #undef INCOMPLETE_TYPES_BROKEN
/* Define "boolean" as unsigned char, not int, per Windows custom */
#ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
typedef unsigned char boolean;
#endif
#define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
#ifdef JPEG_INTERNALS #ifdef JPEG_INTERNALS
#undef RIGHT_SHIFT_IS_UNSIGNED #undef RIGHT_SHIFT_IS_UNSIGNED
#endif /* JPEG_INTERNALS */ #endif /* JPEG_INTERNALS */
#ifdef JPEG_CJPEG_DJPEG #ifdef JPEG_CJPEG_DJPEG
#define BMP_SUPPORTED /* BMP image file format */ #define BMP_SUPPORTED /* BMP image file format */
#define GIF_SUPPORTED /* GIF image file format */ #define GIF_SUPPORTED /* GIF image file format */
#define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */ #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
#undef RLE_SUPPORTED /* Utah RLE image file format */ #undef RLE_SUPPORTED /* Utah RLE image file format */
#define TARGA_SUPPORTED /* Targa image file format */ #define TARGA_SUPPORTED /* Targa image file format */
#undef TWO_FILE_COMMANDLINE /* optional */ #define TWO_FILE_COMMANDLINE /* optional */
#define USE_SETMODE /* Needed to make one-file style work in DJG #define USE_SETMODE /* Microsoft has setmode() */
PP */ #undef NEED_SIGNAL_CATCHER
#undef NEED_SIGNAL_CATCHER /* Define this if you use jmemname.c */
#undef DONT_USE_B_MODE #undef DONT_USE_B_MODE
#undef PROGRESS_REPORT /* optional */ #undef PROGRESS_REPORT /* optional */
#endif /* JPEG_CJPEG_DJPEG */ #endif /* JPEG_CJPEG_DJPEG */
 End of changes. 5 change blocks. 
14 lines changed or deleted 20 lines changed or added


 jconfig_linux.h   jconfig_linux.h 
skipping to change at line 25 skipping to change at line 25
#define HAVE_LOCALE_H 1 #define HAVE_LOCALE_H 1
/* #undef NEED_BSD_STRINGS */ /* #undef NEED_BSD_STRINGS */
/* #undef NEED_SYS_TYPES_H */ /* #undef NEED_SYS_TYPES_H */
/* #undef NEED_FAR_POINTERS */ /* #undef NEED_FAR_POINTERS */
/* #undef NEED_SHORT_EXTERNAL_NAMES */ /* #undef NEED_SHORT_EXTERNAL_NAMES */
/* Define this if you get warnings about undefined structures. */ /* Define this if you get warnings about undefined structures. */
/* #undef INCOMPLETE_TYPES_BROKEN */ /* #undef INCOMPLETE_TYPES_BROKEN */
/* Define "boolean" as unsigned char, not int, on Windows systems. */ /* Define "boolean" as unsigned char, not int, on Windows systems. */
#ifdef _WIN32 #ifdef _WIN32
#ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read * / #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
typedef unsigned char boolean; typedef unsigned char boolean;
#endif #endif
#define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */ #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
#endif #endif
#ifdef JPEG_INTERNALS #ifdef JPEG_INTERNALS
/* #undef RIGHT_SHIFT_IS_UNSIGNED */ /* #undef RIGHT_SHIFT_IS_UNSIGNED */
#define INLINE __inline__ #define INLINE __inline__
/* These are for configuring the JPEG memory manager. */ /* These are for configuring the JPEG memory manager. */
/* #undef DEFAULT_MAX_MEM */ /* #undef DEFAULT_MAX_MEM */
/* #undef NO_MKTEMP */ /* #undef NO_MKTEMP */
#endif /* JPEG_INTERNALS */ #endif /* JPEG_INTERNALS */
#ifdef JPEG_CJPEG_DJPEG #ifdef JPEG_CJPEG_DJPEG
#define BMP_SUPPORTED /* BMP image file format */ #define BMP_SUPPORTED /* BMP image file format */
#define GIF_SUPPORTED /* GIF image file format */ #define GIF_SUPPORTED /* GIF image file format */
#define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */ #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
/* #undef RLE_SUPPORTED */ /* #undef RLE_SUPPORTED */
#define TARGA_SUPPORTED /* Targa image file format */ #define TARGA_SUPPORTED /* Targa image file format */
/* #undef TWO_FILE_COMMANDLINE */ /* #undef TWO_FILE_COMMANDLINE */
/* #undef NEED_SIGNAL_CATCHER */ /* #undef NEED_SIGNAL_CATCHER */
/* #undef DONT_USE_B_MODE */ /* #undef DONT_USE_B_MODE */
/* Define this if you want percent-done progress reports from cjpeg/djpeg. */ /* Define this if you want percent-done progress reports from cjpeg/djpeg. */
/* #undef PROGRESS_REPORT */ /* #undef PROGRESS_REPORT */
#endif /* JPEG_CJPEG_DJPEG */ #endif /* JPEG_CJPEG_DJPEG */
 End of changes. 4 change blocks. 
6 lines changed or deleted 6 lines changed or added


 jconfig_win.h   jconfig_win.h 
skipping to change at line 16 skipping to change at line 16
#define HAVE_PROTOTYPES #define HAVE_PROTOTYPES
#define HAVE_UNSIGNED_CHAR #define HAVE_UNSIGNED_CHAR
#define HAVE_UNSIGNED_SHORT #define HAVE_UNSIGNED_SHORT
/* #define void char */ /* #define void char */
/* #define const */ /* #define const */
#undef CHAR_IS_UNSIGNED #undef CHAR_IS_UNSIGNED
#define HAVE_STDDEF_H #define HAVE_STDDEF_H
#define HAVE_STDLIB_H #define HAVE_STDLIB_H
#undef NEED_BSD_STRINGS #undef NEED_BSD_STRINGS
#undef NEED_SYS_TYPES_H #undef NEED_SYS_TYPES_H
#undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */ #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
#undef NEED_SHORT_EXTERNAL_NAMES #undef NEED_SHORT_EXTERNAL_NAMES
#undef INCOMPLETE_TYPES_BROKEN #undef INCOMPLETE_TYPES_BROKEN
/* Define "boolean" as unsigned char, not int, per Windows custom */ /* Define "boolean" as unsigned char, not int, per Windows custom */
#ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read * / #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
typedef unsigned char boolean; typedef unsigned char boolean;
#endif #endif
#define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */ #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
#ifdef JPEG_INTERNALS #ifdef JPEG_INTERNALS
#undef RIGHT_SHIFT_IS_UNSIGNED #undef RIGHT_SHIFT_IS_UNSIGNED
#endif /* JPEG_INTERNALS */ #endif /* JPEG_INTERNALS */
#ifdef JPEG_CJPEG_DJPEG #ifdef JPEG_CJPEG_DJPEG
#define BMP_SUPPORTED /* BMP image file format */ #define BMP_SUPPORTED /* BMP image file format */
#define GIF_SUPPORTED /* GIF image file format */ #define GIF_SUPPORTED /* GIF image file format */
#define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */ #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
#undef RLE_SUPPORTED /* Utah RLE image file format */ #undef RLE_SUPPORTED /* Utah RLE image file format */
#define TARGA_SUPPORTED /* Targa image file format */ #define TARGA_SUPPORTED /* Targa image file format */
#define TWO_FILE_COMMANDLINE /* optional */ #define TWO_FILE_COMMANDLINE /* optional */
#define USE_SETMODE /* Microsoft has setmode() */ #define USE_SETMODE /* Microsoft has setmode() */
#undef NEED_SIGNAL_CATCHER #undef NEED_SIGNAL_CATCHER
#undef DONT_USE_B_MODE #undef DONT_USE_B_MODE
#undef PROGRESS_REPORT /* optional */ #undef PROGRESS_REPORT /* optional */
#endif /* JPEG_CJPEG_DJPEG */ #endif /* JPEG_CJPEG_DJPEG */
#endif // __JCONFIG_WIN_H__ #endif // __JCONFIG_WIN_H__
 End of changes. 6 change blocks. 
11 lines changed or deleted 11 lines changed or added


 jerror.h   jerror.h 
skipping to change at line 36 skipping to change at line 36
#else #else
/* Repeated inclusions of this file are no-ops unless JMESSAGE is defined * / /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined * /
#define JMESSAGE(code,string) #define JMESSAGE(code,string)
#endif /* JERROR_H */ #endif /* JERROR_H */
#endif /* JMESSAGE */ #endif /* JMESSAGE */
#ifdef JMAKE_ENUM_LIST #ifdef JMAKE_ENUM_LIST
typedef enum { typedef enum {
#define JMESSAGE(code,string) code , #define JMESSAGE(code,string) code ,
#endif /* JMAKE_ENUM_LIST */ #endif /* JMAKE_ENUM_LIST */
JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! * / JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! * /
/* For maintenance convenience, list is alphabetical by message code name * / /* For maintenance convenience, list is alphabetical by message code name * /
JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix") JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix") JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode") JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS") JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
JMESSAGE(JERR_BAD_CROP_SPEC, "Invalid crop request") JMESSAGE(JERR_BAD_CROP_SPEC, "Invalid crop request")
JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range") JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
JMESSAGE(JERR_BAD_DCTSIZE, "DCT scaled block size %dx%d not supported") JMESSAGE(JERR_BAD_DCTSIZE, "DCT scaled block size %dx%d not supported")
JMESSAGE(JERR_BAD_DROP_SAMPLING, JMESSAGE(JERR_BAD_DROP_SAMPLING,
"Component index %d: mismatching sampling ratio %d:%d, %d:%d, %c") "Component index %d: mismatching sampling ratio %d:%d, %d:%d, %c")
JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition") JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace") JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace") JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length") JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
JMESSAGE(JERR_BAD_LIB_VERSION, JMESSAGE(JERR_BAD_LIB_VERSION,
"Wrong JPEG library version: library is %d, caller expects %d") "Wrong JPEG library version: library is %d, caller expects %d")
JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved sca n") JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved sca n")
JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d") JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d") JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
JMESSAGE(JERR_BAD_PROGRESSION, JMESSAGE(JERR_BAD_PROGRESSION,
"Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d") "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
JMESSAGE(JERR_BAD_PROG_SCRIPT, JMESSAGE(JERR_BAD_PROG_SCRIPT,
"Invalid progressive parameters at scan script entry %d") "Invalid progressive parameters at scan script entry %d")
JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors") JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d") JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d") JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
JMESSAGE(JERR_BAD_STRUCT_SIZE, JMESSAGE(JERR_BAD_STRUCT_SIZE,
"JPEG parameter struct mismatch: library thinks size is %u, caller expects %u") "JPEG parameter struct mismatch: library thinks size is %u, caller exp ects %u")
JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access") JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small") JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here") JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet") JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d") JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request") JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d") JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x") JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d") JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d") JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
skipping to change at line 93 skipping to change at line 93
JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan") JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
JMESSAGE(JERR_FILE_READ, "Input file read error") JMESSAGE(JERR_FILE_READ, "Input file read error")
JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?") JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented ye t") JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented ye t")
JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow") JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry") JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixel s") JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixel s")
JMESSAGE(JERR_INPUT_EMPTY, "Empty input file") JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
JMESSAGE(JERR_INPUT_EOF, "Premature end of input file") JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
JMESSAGE(JERR_MISMATCHED_QUANT_TABLE, JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
"Cannot transcode due to multiple use of quantization table %d") "Cannot transcode due to multiple use of quantization table %d")
JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data") JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change") JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
JMESSAGE(JERR_NOTIMPL, "Not implemented yet") JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time" ) JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time" )
JMESSAGE(JERR_NO_ARITH_TABLE, "Arithmetic table 0x%02x was not defined") JMESSAGE(JERR_NO_ARITH_TABLE, "Arithmetic table 0x%02x was not defined")
JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported") JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined") JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image") JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined") JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x") JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)") JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
JMESSAGE(JERR_QUANT_COMPONENTS, JMESSAGE(JERR_QUANT_COMPONENTS,
"Cannot quantize more than %d color components") "Cannot quantize more than %d color components")
JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors") JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors") JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers" ) JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers" )
JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker" ) JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker" )
JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x") JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers" ) JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers" )
JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF") JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s") JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file") JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file") JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
JMESSAGE(JERR_TFILE_WRITE, JMESSAGE(JERR_TFILE_WRITE,
"Write failed on temporary file --- out of disk space?") "Write failed on temporary file --- out of disk space?")
JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines") JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x") JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up") JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation") JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
JMESSAGE(JERR_XMS_READ, "Read from XMS failed") JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed") JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT) JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
JMESSAGE(JMSG_VERSION, JVERSION) JMESSAGE(JMSG_VERSION, JVERSION)
JMESSAGE(JTRC_16BIT_TABLES, JMESSAGE(JTRC_16BIT_TABLES,
"Caution: quantization tables are too coarse for baseline JPEG") "Caution: quantization tables are too coarse for baseline JPEG")
JMESSAGE(JTRC_ADOBE, JMESSAGE(JTRC_ADOBE,
"Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d" ) "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u") JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u") JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x") JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x") JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d") JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
JMESSAGE(JTRC_DRI, "Define Restart Interval %u") JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u") JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u") JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
JMESSAGE(JTRC_EOI, "End Of Image") JMESSAGE(JTRC_EOI, "End Of Image")
JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d") JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d") JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE, JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
"Warning: thumbnail image size does not match data length %u") "Warning: thumbnail image size does not match data length %u")
JMESSAGE(JTRC_JFIF_EXTENSION, JMESSAGE(JTRC_JFIF_EXTENSION,
"JFIF extension marker: type 0x%02x, length %u") "JFIF extension marker: type 0x%02x, length %u")
JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image") JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u") JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x") JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u") JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors") JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors") JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization") JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d") JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
JMESSAGE(JTRC_RST, "RST%d") JMESSAGE(JTRC_RST, "RST%d")
JMESSAGE(JTRC_SMOOTH_NOTIMPL, JMESSAGE(JTRC_SMOOTH_NOTIMPL,
"Smoothing not supported with nonstandard sampling ratios") "Smoothing not supported with nonstandard sampling ratios")
JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components= %d") JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components= %d")
JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d") JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
JMESSAGE(JTRC_SOI, "Start of Image") JMESSAGE(JTRC_SOI, "Start of Image")
JMESSAGE(JTRC_SOS, "Start Of Scan: %d components") JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d") JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d") JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s") JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s") JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
JMESSAGE(JTRC_THUMB_JPEG, JMESSAGE(JTRC_THUMB_JPEG,
"JFIF extension marker: JPEG-compressed thumbnail image, length %u" ) "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
JMESSAGE(JTRC_THUMB_PALETTE, JMESSAGE(JTRC_THUMB_PALETTE,
"JFIF extension marker: palette thumbnail image, length %u") "JFIF extension marker: palette thumbnail image, length %u")
JMESSAGE(JTRC_THUMB_RGB, JMESSAGE(JTRC_THUMB_RGB,
"JFIF extension marker: RGB thumbnail image, length %u") "JFIF extension marker: RGB thumbnail image, length %u")
JMESSAGE(JTRC_UNKNOWN_IDS, JMESSAGE(JTRC_UNKNOWN_IDS,
"Unrecognized component IDs %d %d %d, assuming YCbCr") "Unrecognized component IDs %d %d %d, assuming YCbCr")
JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u") JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u") JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d") JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
JMESSAGE(JWRN_ARITH_BAD_CODE, "Corrupt JPEG data: bad arithmetic code") JMESSAGE(JWRN_ARITH_BAD_CODE, "Corrupt JPEG data: bad arithmetic code")
JMESSAGE(JWRN_BOGUS_PROGRESSION, JMESSAGE(JWRN_BOGUS_PROGRESSION,
"Inconsistent progression sequence for component %d coefficient %d" ) "Inconsistent progression sequence for component %d coefficient %d")
JMESSAGE(JWRN_EXTRANEOUS_DATA, JMESSAGE(JWRN_EXTRANEOUS_DATA,
"Corrupt JPEG data: %u extraneous bytes before marker 0x%02x") "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment ") JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment ")
JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code") JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d") JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file") JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
JMESSAGE(JWRN_MUST_RESYNC, JMESSAGE(JWRN_MUST_RESYNC,
"Corrupt JPEG data: found marker 0x%02x instead of RST%d") "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG") JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines") JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
#ifdef JMAKE_ENUM_LIST #ifdef JMAKE_ENUM_LIST
JMSG_LASTMSGCODE JMSG_LASTMSGCODE
} J_MESSAGE_CODE; } J_MESSAGE_CODE;
#undef JMAKE_ENUM_LIST #undef JMAKE_ENUM_LIST
#endif /* JMAKE_ENUM_LIST */ #endif /* JMAKE_ENUM_LIST */
skipping to change at line 247 skipping to change at line 247
(cinfo)->err->msg_parm.i[2] = (p3), \ (cinfo)->err->msg_parm.i[2] = (p3), \
(cinfo)->err->msg_parm.i[3] = (p4), \ (cinfo)->err->msg_parm.i[3] = (p4), \
(cinfo)->err->msg_parm.i[4] = (p5), \ (cinfo)->err->msg_parm.i[4] = (p5), \
(cinfo)->err->msg_parm.i[5] = (p6), \ (cinfo)->err->msg_parm.i[5] = (p6), \
(*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo))) (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
#define ERREXITS(cinfo,code,str) \ #define ERREXITS(cinfo,code,str) \
((cinfo)->err->msg_code = (code), \ ((cinfo)->err->msg_code = (code), \
strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \ strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
(*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo))) (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
#define MAKESTMT(stuff) do { stuff } while (0) #define MAKESTMT(stuff) do { stuff } while (0)
/* Nonfatal errors (we can keep going, but the data is probably corrupt) */ /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
#define WARNMS(cinfo,code) \ #define WARNMS(cinfo,code) \
((cinfo)->err->msg_code = (code), \ ((cinfo)->err->msg_code = (code), \
(*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1)) (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
#define WARNMS1(cinfo,code,p1) \ #define WARNMS1(cinfo,code,p1) \
((cinfo)->err->msg_code = (code), \ ((cinfo)->err->msg_code = (code), \
(cinfo)->err->msg_parm.i[0] = (p1), \ (cinfo)->err->msg_parm.i[0] = (p1), \
(*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1)) (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
#define WARNMS2(cinfo,code,p1,p2) \ #define WARNMS2(cinfo,code,p1,p2) \
skipping to change at line 278 skipping to change at line 278
((cinfo)->err->msg_code = (code), \ ((cinfo)->err->msg_code = (code), \
(cinfo)->err->msg_parm.i[0] = (p1), \ (cinfo)->err->msg_parm.i[0] = (p1), \
(*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl))) (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
#define TRACEMS2(cinfo,lvl,code,p1,p2) \ #define TRACEMS2(cinfo,lvl,code,p1,p2) \
((cinfo)->err->msg_code = (code), \ ((cinfo)->err->msg_code = (code), \
(cinfo)->err->msg_parm.i[0] = (p1), \ (cinfo)->err->msg_parm.i[0] = (p1), \
(cinfo)->err->msg_parm.i[1] = (p2), \ (cinfo)->err->msg_parm.i[1] = (p2), \
(*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl))) (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
#define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \ #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \ MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
_mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \ _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
(cinfo)->err->msg_code = (code); \ (cinfo)->err->msg_code = (code); \
(*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); ) (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
#define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \ #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \ MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
_mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \ _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
(cinfo)->err->msg_code = (code); \ (cinfo)->err->msg_code = (code); \
(*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); ) (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
#define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \ #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \ MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
_mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \ _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
_mp[4] = (p5); \ _mp[4] = (p5); \
(cinfo)->err->msg_code = (code); \ (cinfo)->err->msg_code = (code); \
(*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); ) (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
#define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \ #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \ MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
_mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \ _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
_mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \ _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
(cinfo)->err->msg_code = (code); \ (cinfo)->err->msg_code = (code); \
(*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); ) (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
#define TRACEMSS(cinfo,lvl,code,str) \ #define TRACEMSS(cinfo,lvl,code,str) \
((cinfo)->err->msg_code = (code), \ ((cinfo)->err->msg_code = (code), \
strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \ strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
(*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl))) (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
#endif /* JERROR_H */ #endif /* JERROR_H */
 End of changes. 26 change blocks. 
36 lines changed or deleted 36 lines changed or added


 jmorecfg.h   jmorecfg.h 
skipping to change at line 23 skipping to change at line 23
/* /*
* Define BITS_IN_JSAMPLE as either * Define BITS_IN_JSAMPLE as either
* 8 for 8-bit sample values (the usual setting) * 8 for 8-bit sample values (the usual setting)
* 12 for 12-bit sample values * 12 for 12-bit sample values
* Only 8 and 12 are legal data precisions for lossy JPEG according to the * Only 8 and 12 are legal data precisions for lossy JPEG according to the
* JPEG standard, and the IJG code does not support anything else! * JPEG standard, and the IJG code does not support anything else!
* We do not support run-time selection of data precision, sorry. * We do not support run-time selection of data precision, sorry.
*/ */
#define BITS_IN_JSAMPLE 8 /* use 8 or 12 */ #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
/* /*
* Maximum number of components (color channels) allowed in JPEG image. * Maximum number of components (color channels) allowed in JPEG image.
* To meet the letter of the JPEG spec, set this to 255. However, darn * To meet the letter of the JPEG spec, set this to 255. However, darn
* few applications need more than 4 channels (maybe 5 for CMYK + alpha * few applications need more than 4 channels (maybe 5 for CMYK + alpha
* mask). We recommend 10 as a reasonable compromise; use 4 if you are * mask). We recommend 10 as a reasonable compromise; use 4 if you are
* really short on memory. (Each allowed component costs a hundred or so * really short on memory. (Each allowed component costs a hundred or so
* bytes of storage, whether actually used in an image or not.) * bytes of storage, whether actually used in an image or not.)
*/ */
#define MAX_COMPONENTS 10 /* maximum number of image components */ #define MAX_COMPONENTS 10 /* maximum number of image components */
/* /*
* Basic data types. * Basic data types.
* You may need to change these if you have a machine with unusual data * You may need to change these if you have a machine with unusual data
* type sizes; for example, "char" not 8 bits, "short" not 16 bits, * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
* or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits, * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
* but it had better be at least 16. * but it had better be at least 16.
*/ */
/* Representation of a single sample (pixel element value). /* Representation of a single sample (pixel element value).
skipping to change at line 71 skipping to change at line 71
typedef char JSAMPLE; typedef char JSAMPLE;
#ifdef CHAR_IS_UNSIGNED #ifdef CHAR_IS_UNSIGNED
#define GETJSAMPLE(value) ((int) (value)) #define GETJSAMPLE(value) ((int) (value))
#else #else
#define GETJSAMPLE(value) ((int) (value) & 0xFF) #define GETJSAMPLE(value) ((int) (value) & 0xFF)
#endif /* CHAR_IS_UNSIGNED */ #endif /* CHAR_IS_UNSIGNED */
#endif /* HAVE_UNSIGNED_CHAR */ #endif /* HAVE_UNSIGNED_CHAR */
#define MAXJSAMPLE 255 #define MAXJSAMPLE 255
#define CENTERJSAMPLE 128 #define CENTERJSAMPLE 128
#endif /* BITS_IN_JSAMPLE == 8 */ #endif /* BITS_IN_JSAMPLE == 8 */
#if BITS_IN_JSAMPLE == 12 #if BITS_IN_JSAMPLE == 12
/* JSAMPLE should be the smallest type that will hold the values 0..4095. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
* On nearly all machines "short" will do nicely. * On nearly all machines "short" will do nicely.
*/ */
typedef short JSAMPLE; typedef short JSAMPLE;
#define GETJSAMPLE(value) ((int) (value)) #define GETJSAMPLE(value) ((int) (value))
#define MAXJSAMPLE 4095 #define MAXJSAMPLE 4095
#define CENTERJSAMPLE 2048 #define CENTERJSAMPLE 2048
#endif /* BITS_IN_JSAMPLE == 12 */ #endif /* BITS_IN_JSAMPLE == 12 */
/* Representation of a DCT frequency coefficient. /* Representation of a DCT frequency coefficient.
* This should be a signed value of at least 16 bits; "short" is usually OK . * This should be a signed value of at least 16 bits; "short" is usually OK .
* Again, we allocate large arrays of these, but you can change to int * Again, we allocate large arrays of these, but you can change to int
* if you have memory to burn and "short" is really slow. * if you have memory to burn and "short" is really slow.
*/ */
typedef short JCOEF; typedef short JCOEF;
skipping to change at line 148 skipping to change at line 148
/* UINT16 must hold at least the values 0..65535. */ /* UINT16 must hold at least the values 0..65535. */
#ifdef HAVE_UNSIGNED_SHORT #ifdef HAVE_UNSIGNED_SHORT
typedef unsigned short UINT16; typedef unsigned short UINT16;
#else /* not HAVE_UNSIGNED_SHORT */ #else /* not HAVE_UNSIGNED_SHORT */
typedef unsigned int UINT16; typedef unsigned int UINT16;
#endif /* HAVE_UNSIGNED_SHORT */ #endif /* HAVE_UNSIGNED_SHORT */
/* INT16 must hold at least the values -32768..32767. */ /* INT16 must hold at least the values -32768..32767. */
#ifndef XMD_H /* X11/xmd.h correctly defines INT16 */ #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
typedef short INT16; typedef short INT16;
#endif #endif
/* INT32 must hold at least signed 32-bit values. */ /* INT32 must hold at least signed 32-bit values. */
#ifndef XMD_H /* X11/xmd.h correctly defines INT32 */ #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
#ifndef _BASETSD_H_ /* Microsoft defines it in basetsd.h */ #ifndef _BASETSD_H_ /* Microsoft defines it in basetsd.h */
#ifndef _BASETSD_H /* MinGW is slightly different */ #ifndef _BASETSD_H /* MinGW is slightly different */
#ifndef QGLOBAL_H /* Qt defines it in qglobal.h */ #ifndef QGLOBAL_H /* Qt defines it in qglobal.h */
typedef long INT32; typedef long INT32;
#endif #endif
#endif #endif
#endif #endif
#endif #endif
/* Datatype used for image dimensions. The JPEG standard only supports /* Datatype used for image dimensions. The JPEG standard only supports
* images up to 64K*64K due to 16-bit fields in SOF markers. Therefore * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
* "unsigned int" is sufficient on all machines. However, if you need to * "unsigned int" is sufficient on all machines. However, if you need to
* handle larger images and you don't mind deviating from the spec, you * handle larger images and you don't mind deviating from the spec, you
skipping to change at line 183 skipping to change at line 183
#define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */ #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
/* These macros are used in all function definitions and extern declaration s. /* These macros are used in all function definitions and extern declaration s.
* You could modify them if you need to change function linkage conventions ; * You could modify them if you need to change function linkage conventions ;
* in particular, you'll need to do that to make the library a Windows DLL. * in particular, you'll need to do that to make the library a Windows DLL.
* Another application is to make all functions global for use with debugge rs * Another application is to make all functions global for use with debugge rs
* or code profilers that require it. * or code profilers that require it.
*/ */
/* a function called through method pointers: */ /* a function called through method pointers: */
#define METHODDEF(type) static type #define METHODDEF(type) static type
/* a function used only in its module: */ /* a function used only in its module: */
#define LOCAL(type) static type #define LOCAL(type) static type
/* a function referenced thru EXTERNs: */ /* a function referenced thru EXTERNs: */
#define GLOBAL(type) type #define GLOBAL(type) type
/* a reference to a GLOBAL function: */ /* a reference to a GLOBAL function: */
#define EXTERN(type) extern type #define EXTERN(type) extern type
/* This macro is used to declare a "method", that is, a function pointer. /* This macro is used to declare a "method", that is, a function pointer.
* We want to supply prototype parameters if the compiler can cope. * We want to supply prototype parameters if the compiler can cope.
* Note that the arglist parameter must be parenthesized! * Note that the arglist parameter must be parenthesized!
* Again, you can customize this if you need special linkage keywords. * Again, you can customize this if you need special linkage keywords.
*/ */
#ifdef HAVE_PROTOTYPES #ifdef HAVE_PROTOTYPES
#define JMETHOD(type,methodname,arglist) type (*methodname) arglist #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
#else #else
skipping to change at line 227 skipping to change at line 227
/* /*
* On a few systems, type boolean and/or its values FALSE, TRUE may appear * On a few systems, type boolean and/or its values FALSE, TRUE may appear
* in standard header files. Or you may have conflicts with application- * in standard header files. Or you may have conflicts with application-
* specific header files that you want to include together with these files . * specific header files that you want to include together with these files .
* Defining HAVE_BOOLEAN before including jpeglib.h should make it work. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
*/ */
#ifndef HAVE_BOOLEAN #ifndef HAVE_BOOLEAN
typedef int boolean; typedef int boolean;
#endif #endif
#ifndef FALSE /* in case these macros already exist */ #ifndef FALSE /* in case these macros already exist */
#define FALSE 0 /* values of boolean */ #define FALSE 0 /* values of boolean */
#endif #endif
#ifndef TRUE #ifndef TRUE
#define TRUE 1 #define TRUE 1
#endif #endif
/* /*
* The remaining options affect code selection within the JPEG library, * The remaining options affect code selection within the JPEG library,
* but they don't need to be visible to most applications using the library . * but they don't need to be visible to most applications using the library .
* To minimize application namespace pollution, the symbols won't be * To minimize application namespace pollution, the symbols won't be
* defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
*/ */
#ifdef JPEG_INTERNALS #ifdef JPEG_INTERNALS
skipping to change at line 257 skipping to change at line 257
/* /*
* These defines indicate whether to include various optional functions. * These defines indicate whether to include various optional functions.
* Undefining some of these symbols will produce a smaller but less capable * Undefining some of these symbols will produce a smaller but less capable
* library. Note that you can leave certain source files out of the * library. Note that you can leave certain source files out of the
* compilation/linking process if you've #undef'd the corresponding symbols . * compilation/linking process if you've #undef'd the corresponding symbols .
* (You may HAVE to do that if your compiler doesn't like null source files .) * (You may HAVE to do that if your compiler doesn't like null source files .)
*/ */
/* Capability options common to encoder and decoder: */ /* Capability options common to encoder and decoder: */
#define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */ #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
#define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */ #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
#define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW
*/ */
/* Encoder capability options: */ /* Encoder capability options: */
#define C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */ #define C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
#define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */ #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
#define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires M #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTI
ULTISCAN)*/ SCAN)*/
#define DCT_SCALING_SUPPORTED /* Input rescaling via DCT? (Requires DC #define DCT_SCALING_SUPPORTED /* Input rescaling via DCT? (Requires
T_ISLOW)*/ DCT_ISLOW)*/
#define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parm
*/ s? */
/* Note: if you selected 12-bit data precision, it is dangerous to turn off /* Note: if you selected 12-bit data precision, it is dangerous to turn off
* ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8- bit * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8- bit
* precision, so jchuff.c normally uses entropy optimization to compute * precision, so jchuff.c normally uses entropy optimization to compute
* usable tables for higher precision. If you don't want to do optimizatio n, * usable tables for higher precision. If you don't want to do optimizatio n,
* you'll have to supply different default Huffman tables. * you'll have to supply different default Huffman tables.
* The exact same statements apply for progressive JPEG: the default tables * The exact same statements apply for progressive JPEG: the default tables
* don't work for progressive mode. (This may get fixed, however.) * don't work for progressive mode. (This may get fixed, however.)
*/ */
#define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */ #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
/* Decoder capability options: */ /* Decoder capability options: */
#define D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */ #define D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
#define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */ #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
#define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires M #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTI
ULTISCAN)*/ SCAN)*/
#define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */ #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
#define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */ #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
#define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */ #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
#undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */ #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
#define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */ #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
#define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */ #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
#define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */ #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
/* more capability options later, no doubt */ /* more capability options later, no doubt */
/* /*
* Ordering of RGB data in scanlines passed to or from the application. * Ordering of RGB data in scanlines passed to or from the application.
* If your application wants to deal with data in the order B,G,R, just * If your application wants to deal with data in the order B,G,R, just
* change these macros. You can also deal with formats such as R,G,B,X * change these macros. You can also deal with formats such as R,G,B,X
* (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changin g * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changin g
* the offsets will also change the order in which colormap data is organiz ed. * the offsets will also change the order in which colormap data is organiz ed.
* RESTRICTIONS: * RESTRICTIONS:
* 1. The sample applications cjpeg,djpeg do NOT support modified RGB forma ts. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB forma ts.
* 2. These macros only affect RGB<=>YCbCr color conversion, so they are no t * 2. These macros only affect RGB<=>YCbCr color conversion, so they are no t
* useful if you are using JPEG color spaces other than YCbCr or graysca le. * useful if you are using JPEG color spaces other than YCbCr or graysca le.
* 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZ E * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZ E
* is not 3 (they don't understand about dummy color components!). So y ou * is not 3 (they don't understand about dummy color components!). So y ou
* can't use color quantization if you change that value. * can't use color quantization if you change that value.
*/ */
#define RGB_RED 0 /* Offset of Red in an RGB scanline #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
element */ #define RGB_GREEN 1 /* Offset of Green */
#define RGB_GREEN 1 /* Offset of Green */ #define RGB_BLUE 2 /* Offset of Blue */
#define RGB_BLUE 2 /* Offset of Blue */ #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
#define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
/* Definitions for speed-related optimizations. */ /* Definitions for speed-related optimizations. */
/* If your compiler supports inline functions, define INLINE /* If your compiler supports inline functions, define INLINE
* as the inline keyword; otherwise define it as empty. * as the inline keyword; otherwise define it as empty.
*/ */
#ifndef INLINE #ifndef INLINE
#ifdef __GNUC__ /* for instance, GNU C knows about i nline */ #ifdef __GNUC__ /* for instance, GNU C knows about inline */
#define INLINE __inline__ #define INLINE __inline__
#endif #endif
#ifndef INLINE #ifndef INLINE
#define INLINE /* default is to define it as empty */ #define INLINE /* default is to define it as empty */
#endif #endif
#endif #endif
/* On some machines (notably 68000 series) "int" is 32 bits, but multiplyin g /* On some machines (notably 68000 series) "int" is 32 bits, but multiplyin g
* two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIE R * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIE R
* as short on such a machine. MULTIPLIER must be at least 16 bits wide. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
*/ */
#ifndef MULTIPLIER #ifndef MULTIPLIER
#define MULTIPLIER int /* type for fastest integer multiply */ #define MULTIPLIER int /* type for fastest integer multiply */
#endif #endif
/* FAST_FLOAT should be either float or double, whichever is done faster /* FAST_FLOAT should be either float or double, whichever is done faster
* by your compiler. (Note that this type is only used in the floating poi nt * by your compiler. (Note that this type is only used in the floating poi nt
* DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.) * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
* Typically, float is faster in ANSI C compilers, while double is faster i n * Typically, float is faster in ANSI C compilers, while double is faster i n
* pre-ANSI compilers (because they insist on converting to double anyway). * pre-ANSI compilers (because they insist on converting to double anyway).
* The code below therefore chooses float if we have ANSI-style prototypes. * The code below therefore chooses float if we have ANSI-style prototypes.
*/ */
 End of changes. 20 change blocks. 
42 lines changed or deleted 41 lines changed or added


 lauxlib.h   lauxlib.h 
skipping to change at line 24 skipping to change at line 24
#if defined(LUA_COMPAT_GETN) #if defined(LUA_COMPAT_GETN)
LUALIB_API int (luaL_getn) (lua_State *L, int t); LUALIB_API int (luaL_getn) (lua_State *L, int t);
LUALIB_API void (luaL_setn) (lua_State *L, int t, int n); LUALIB_API void (luaL_setn) (lua_State *L, int t, int n);
#else #else
#define luaL_getn(L,i) ((int)lua_objlen(L, i)) #define luaL_getn(L,i) ((int)lua_objlen(L, i))
#define luaL_setn(L,i,j) ((void)0) /* no op! */ #define luaL_setn(L,i,j) ((void)0) /* no op! */
#endif #endif
#if defined(LUA_COMPAT_OPENLIB) #if defined(LUA_COMPAT_OPENLIB)
#define luaI_openlib luaL_openlib #define luaI_openlib luaL_openlib
#endif #endif
/* extra error code for `luaL_load' */ /* extra error code for `luaL_load' */
#define LUA_ERRFILE (LUA_ERRERR+1) #define LUA_ERRFILE (LUA_ERRERR+1)
typedef struct luaL_Reg { typedef struct luaL_Reg {
const char *name; const char *name;
lua_CFunction func; lua_CFunction func;
} luaL_Reg; } luaL_Reg;
skipping to change at line 89 skipping to change at line 89
LUALIB_API const char *(luaL_findtable) (lua_State *L, int idx, LUALIB_API const char *(luaL_findtable) (lua_State *L, int idx,
const char *fname, int szhint); const char *fname, int szhint);
/* /*
** =============================================================== ** ===============================================================
** some useful macros ** some useful macros
** =============================================================== ** ===============================================================
*/ */
#define luaL_argcheck(L, cond,numarg,extramsg) \ #define luaL_argcheck(L, cond,numarg,extramsg) \
((void)((cond) || luaL_argerror(L, (numarg), (extramsg)))) ((void)((cond) || luaL_argerror(L, (numarg), (extramsg))))
#define luaL_checkstring(L,n) (luaL_checklstring(L, (n), NULL)) #define luaL_checkstring(L,n) (luaL_checklstring(L, (n), NULL))
#define luaL_optstring(L,n,d) (luaL_optlstring(L, (n), (d), NULL)) #define luaL_optstring(L,n,d) (luaL_optlstring(L, (n), (d), NULL))
#define luaL_checkint(L,n) ((int)luaL_checkinteger(L, (n))) #define luaL_checkint(L,n) ((int)luaL_checkinteger(L, (n)))
#define luaL_optint(L,n,d) ((int)luaL_optinteger(L, (n), (d))) #define luaL_optint(L,n,d) ((int)luaL_optinteger(L, (n), (d)))
#define luaL_checklong(L,n) ((long)luaL_checkinteger(L, (n))) #define luaL_checklong(L,n) ((long)luaL_checkinteger(L, (n)))
#define luaL_optlong(L,n,d) ((long)luaL_optinteger(L, (n), (d))) #define luaL_optlong(L,n,d) ((long)luaL_optinteger(L, (n), (d)))
#define luaL_typename(L,i) lua_typename(L, lua_type(L,(i))) #define luaL_typename(L,i) lua_typename(L, lua_type(L,(i)))
#define luaL_dofile(L, fn) \ #define luaL_dofile(L, fn) \
(luaL_loadfile(L, fn) || lua_pcall(L, 0, LUA_MULTRET, 0)) (luaL_loadfile(L, fn) || lua_pcall(L, 0, LUA_MULTRET, 0))
#define luaL_dostring(L, s) \ #define luaL_dostring(L, s) \
(luaL_loadstring(L, s) || lua_pcall(L, 0, LUA_MULTRET, 0)) (luaL_loadstring(L, s) || lua_pcall(L, 0, LUA_MULTRET, 0))
#define luaL_getmetatable(L,n) (lua_getfield(L, LUA_REGISTRYINDEX, (n))) #define luaL_getmetatable(L,n) (lua_getfield(L, LUA_REGISTRYINDEX, (n)))
#define luaL_opt(L,f,n,d) (lua_isnoneornil(L,(n)) ? (d) : f(L,(n))) #define luaL_opt(L,f,n,d) (lua_isnoneornil(L,(n)) ? (d) : f(L,(n)))
/* /*
** {====================================================== ** {======================================================
** Generic Buffer manipulation ** Generic Buffer manipulation
** ======================================================= ** =======================================================
*/ */
typedef struct luaL_Buffer { typedef struct luaL_Buffer {
char *p; /* current position in buffer */ char *p; /* current position in buffer */
int lvl; /* number of strings in the stack (level) */ int lvl; /* number of strings in the stack (level) */
lua_State *L; lua_State *L;
char buffer[LUAL_BUFFERSIZE]; char buffer[LUAL_BUFFERSIZE];
} luaL_Buffer; } luaL_Buffer;
#define luaL_addchar(B,c) \ #define luaL_addchar(B,c) \
((void)((B)->p < ((B)->buffer+LUAL_BUFFERSIZE) || luaL_prepbuffer(B)), \ ((void)((B)->p < ((B)->buffer+LUAL_BUFFERSIZE) || luaL_prepbuffer(B)), \
(*(B)->p++ = (char)(c))) (*(B)->p++ = (char)(c)))
/* compatibility only */ /* compatibility only */
#define luaL_putchar(B,c) luaL_addchar(B,c) #define luaL_putchar(B,c) luaL_addchar(B,c)
#define luaL_addsize(B,n) ((B)->p += (n)) #define luaL_addsize(B,n) ((B)->p += (n))
LUALIB_API void (luaL_buffinit) (lua_State *L, luaL_Buffer *B); LUALIB_API void (luaL_buffinit) (lua_State *L, luaL_Buffer *B);
LUALIB_API char *(luaL_prepbuffer) (luaL_Buffer *B); LUALIB_API char *(luaL_prepbuffer) (luaL_Buffer *B);
LUALIB_API void (luaL_addlstring) (luaL_Buffer *B, const char *s, size_t l) ; LUALIB_API void (luaL_addlstring) (luaL_Buffer *B, const char *s, size_t l) ;
LUALIB_API void (luaL_addstring) (luaL_Buffer *B, const char *s); LUALIB_API void (luaL_addstring) (luaL_Buffer *B, const char *s);
LUALIB_API void (luaL_addvalue) (luaL_Buffer *B); LUALIB_API void (luaL_addvalue) (luaL_Buffer *B);
LUALIB_API void (luaL_pushresult) (luaL_Buffer *B); LUALIB_API void (luaL_pushresult) (luaL_Buffer *B);
/* }====================================================== */ /* }====================================================== */
skipping to change at line 154 skipping to change at line 154
#define LUA_NOREF (-2) #define LUA_NOREF (-2)
#define LUA_REFNIL (-1) #define LUA_REFNIL (-1)
#define lua_ref(L,lock) ((lock) ? luaL_ref(L, LUA_REGISTRYINDEX) : \ #define lua_ref(L,lock) ((lock) ? luaL_ref(L, LUA_REGISTRYINDEX) : \
(lua_pushstring(L, "unlocked references are obsolete"), lua_error(L), 0)) (lua_pushstring(L, "unlocked references are obsolete"), lua_error(L), 0))
#define lua_unref(L,ref) luaL_unref(L, LUA_REGISTRYINDEX, (ref)) #define lua_unref(L,ref) luaL_unref(L, LUA_REGISTRYINDEX, (ref))
#define lua_getref(L,ref) lua_rawgeti(L, LUA_REGISTRYINDEX, (ref)) #define lua_getref(L,ref) lua_rawgeti(L, LUA_REGISTRYINDEX, (ref))
#define luaL_reg luaL_Reg #define luaL_reg luaL_Reg
#endif #endif
 End of changes. 11 change blocks. 
18 lines changed or deleted 18 lines changed or added


 lcode.h   lcode.h 
skipping to change at line 35 skipping to change at line 35
OPR_ADD, OPR_SUB, OPR_MUL, OPR_DIV, OPR_MOD, OPR_POW, OPR_ADD, OPR_SUB, OPR_MUL, OPR_DIV, OPR_MOD, OPR_POW,
OPR_CONCAT, OPR_CONCAT,
OPR_NE, OPR_EQ, OPR_NE, OPR_EQ,
OPR_LT, OPR_LE, OPR_GT, OPR_GE, OPR_LT, OPR_LE, OPR_GT, OPR_GE,
OPR_AND, OPR_OR, OPR_AND, OPR_OR,
OPR_NOBINOPR OPR_NOBINOPR
} BinOpr; } BinOpr;
typedef enum UnOpr { OPR_MINUS, OPR_NOT, OPR_LEN, OPR_NOUNOPR } UnOpr; typedef enum UnOpr { OPR_MINUS, OPR_NOT, OPR_LEN, OPR_NOUNOPR } UnOpr;
#define getcode(fs,e) ((fs)->f->code[(e)->u.s.info]) #define getcode(fs,e) ((fs)->f->code[(e)->u.s.info])
#define luaK_codeAsBx(fs,o,A,sBx) luaK_codeABx(fs,o,A,(sBx)+MAXARG_sBx ) #define luaK_codeAsBx(fs,o,A,sBx) luaK_codeABx(fs,o,A,(sBx)+MAXARG_sBx)
#define luaK_setmultret(fs,e) luaK_setreturns(fs, e, LUA_MULTRET) #define luaK_setmultret(fs,e) luaK_setreturns(fs, e, LUA_MULTRET)
LUAI_FUNC int luaK_codeABx (FuncState *fs, OpCode o, int A, unsigned int Bx ); LUAI_FUNC int luaK_codeABx (FuncState *fs, OpCode o, int A, unsigned int Bx );
LUAI_FUNC int luaK_codeABC (FuncState *fs, OpCode o, int A, int B, int C); LUAI_FUNC int luaK_codeABC (FuncState *fs, OpCode o, int A, int B, int C);
LUAI_FUNC void luaK_fixline (FuncState *fs, int line); LUAI_FUNC void luaK_fixline (FuncState *fs, int line);
LUAI_FUNC void luaK_nil (FuncState *fs, int from, int n); LUAI_FUNC void luaK_nil (FuncState *fs, int from, int n);
LUAI_FUNC void luaK_reserveregs (FuncState *fs, int n); LUAI_FUNC void luaK_reserveregs (FuncState *fs, int n);
LUAI_FUNC void luaK_checkstack (FuncState *fs, int n); LUAI_FUNC void luaK_checkstack (FuncState *fs, int n);
LUAI_FUNC int luaK_stringK (FuncState *fs, TString *s); LUAI_FUNC int luaK_stringK (FuncState *fs, TString *s);
LUAI_FUNC int luaK_numberK (FuncState *fs, lua_Number r); LUAI_FUNC int luaK_numberK (FuncState *fs, lua_Number r);
LUAI_FUNC void luaK_dischargevars (FuncState *fs, expdesc *e); LUAI_FUNC void luaK_dischargevars (FuncState *fs, expdesc *e);
 End of changes. 3 change blocks. 
3 lines changed or deleted 3 lines changed or added


 ldebug.h   ldebug.h 
skipping to change at line 12 skipping to change at line 12
** $Id: ldebug.h,v 2.3.1.1 2007/12/27 13:02:25 roberto Exp $ ** $Id: ldebug.h,v 2.3.1.1 2007/12/27 13:02:25 roberto Exp $
** Auxiliary functions from Debug Interface module ** Auxiliary functions from Debug Interface module
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
#ifndef ldebug_h #ifndef ldebug_h
#define ldebug_h #define ldebug_h
#include "lstate.h" #include "lstate.h"
#define pcRel(pc, p) (cast(int, (pc) - (p)->code) - 1) #define pcRel(pc, p) (cast(int, (pc) - (p)->code) - 1)
#define getline(f,pc) (((f)->lineinfo) ? (f)->lineinfo[pc] : 0) #define getline(f,pc) (((f)->lineinfo) ? (f)->lineinfo[pc] : 0)
#define resethookcount(L) (L->hookcount = L->basehookcount) #define resethookcount(L) (L->hookcount = L->basehookcount)
LUAI_FUNC void luaG_typeerror (lua_State *L, const TValue *o, LUAI_FUNC void luaG_typeerror (lua_State *L, const TValue *o,
const char *opname); const char *opname);
LUAI_FUNC void luaG_concaterror (lua_State *L, StkId p1, StkId p2); LUAI_FUNC void luaG_concaterror (lua_State *L, StkId p1, StkId p2);
LUAI_FUNC void luaG_aritherror (lua_State *L, const TValue *p1, LUAI_FUNC void luaG_aritherror (lua_State *L, const TValue *p1,
const TValue *p2); const TValue *p2);
LUAI_FUNC int luaG_ordererror (lua_State *L, const TValue *p1, LUAI_FUNC int luaG_ordererror (lua_State *L, const TValue *p1,
const TValue *p2); const TValue *p2);
LUAI_FUNC void luaG_runerror (lua_State *L, const char *fmt, ...); LUAI_FUNC void luaG_runerror (lua_State *L, const char *fmt, ...);
LUAI_FUNC void luaG_errormsg (lua_State *L); LUAI_FUNC void luaG_errormsg (lua_State *L);
 End of changes. 3 change blocks. 
3 lines changed or deleted 3 lines changed or added


 ldo.h   ldo.h 
skipping to change at line 14 skipping to change at line 14
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
#ifndef ldo_h #ifndef ldo_h
#define ldo_h #define ldo_h
#include "lobject.h" #include "lobject.h"
#include "lstate.h" #include "lstate.h"
#include "lzio.h" #include "lzio.h"
#define luaD_checkstack(L,n) \ #define luaD_checkstack(L,n) \
if ((char *)L->stack_last - (char *)L->top <= (n)*(int)sizeof(TValue)) \ if ((char *)L->stack_last - (char *)L->top <= (n)*(int)sizeof(TValue)) \
luaD_growstack(L, n); \ luaD_growstack(L, n); \
else condhardstacktests(luaD_reallocstack(L, L->stacksize - EXTRA_STACK - 1)); else condhardstacktests(luaD_reallocstack(L, L->stacksize - EXTRA_STACK - 1));
#define incr_top(L) {luaD_checkstack(L,1); L->top++;} #define incr_top(L) {luaD_checkstack(L,1); L->top++;}
#define savestack(L,p) ((char *)(p) - (char *)L->stack) #define savestack(L,p) ((char *)(p) - (char *)L->stack)
#define restorestack(L,n) ((TValue *)((char *)L->stack + (n))) #define restorestack(L,n) ((TValue *)((char *)L->stack + (n)))
#define saveci(L,p) ((char *)(p) - (char *)L->base_ci) #define saveci(L,p) ((char *)(p) - (char *)L->base_ci)
#define restoreci(L,n) ((CallInfo *)((char *)L->base_ci + (n))) #define restoreci(L,n) ((CallInfo *)((char *)L->base_ci + (n)))
/* results from luaD_precall */ /* results from luaD_precall */
#define PCRLUA 0 /* initiated a call to a Lua function */ #define PCRLUA 0 /* initiated a call to a Lua function */
#define PCRC 1 /* did a call to a C function */ #define PCRC 1 /* did a call to a C function */
#define PCRYIELD 2 /* C funtion yielded */ #define PCRYIELD 2 /* C funtion yielded */
/* type of protected functions, to be ran by `runprotected' */ /* type of protected functions, to be ran by `runprotected' */
typedef void (*Pfunc) (lua_State *L, void *ud); typedef void (*Pfunc) (lua_State *L, void *ud);
LUAI_FUNC int luaD_protectedparser (lua_State *L, ZIO *z, const char *name) ; LUAI_FUNC int luaD_protectedparser (lua_State *L, ZIO *z, const char *name) ;
LUAI_FUNC void luaD_callhook (lua_State *L, int event, int line); LUAI_FUNC void luaD_callhook (lua_State *L, int event, int line);
LUAI_FUNC int luaD_precall (lua_State *L, StkId func, int nresults); LUAI_FUNC int luaD_precall (lua_State *L, StkId func, int nresults);
LUAI_FUNC void luaD_call (lua_State *L, StkId func, int nResults); LUAI_FUNC void luaD_call (lua_State *L, StkId func, int nResults);
LUAI_FUNC int luaD_pcall (lua_State *L, Pfunc func, void *u, LUAI_FUNC int luaD_pcall (lua_State *L, Pfunc func, void *u,
ptrdiff_t oldtop, ptrdiff_t ef); ptrdiff_t oldtop, ptrdiff_t ef);
 End of changes. 4 change blocks. 
8 lines changed or deleted 8 lines changed or added


 lfunc.h   lfunc.h 
skipping to change at line 12 skipping to change at line 12
** $Id: lfunc.h,v 2.4.1.1 2007/12/27 13:02:25 roberto Exp $ ** $Id: lfunc.h,v 2.4.1.1 2007/12/27 13:02:25 roberto Exp $
** Auxiliary functions to manipulate prototypes and closures ** Auxiliary functions to manipulate prototypes and closures
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
#ifndef lfunc_h #ifndef lfunc_h
#define lfunc_h #define lfunc_h
#include "lobject.h" #include "lobject.h"
#define sizeCclosure(n) (cast(int, sizeof(CClosure)) + \ #define sizeCclosure(n) (cast(int, sizeof(CClosure)) + \
cast(int, sizeof(TValue)*((n)-1))) cast(int, sizeof(TValue)*((n)-1)))
#define sizeLclosure(n) (cast(int, sizeof(LClosure)) + \ #define sizeLclosure(n) (cast(int, sizeof(LClosure)) + \
cast(int, sizeof(TValue *)*((n)-1))) cast(int, sizeof(TValue *)*((n)-1)))
LUAI_FUNC Proto *luaF_newproto (lua_State *L); LUAI_FUNC Proto *luaF_newproto (lua_State *L);
LUAI_FUNC Closure *luaF_newCclosure (lua_State *L, int nelems, Table *e); LUAI_FUNC Closure *luaF_newCclosure (lua_State *L, int nelems, Table *e);
LUAI_FUNC Closure *luaF_newLclosure (lua_State *L, int nelems, Table *e); LUAI_FUNC Closure *luaF_newLclosure (lua_State *L, int nelems, Table *e);
LUAI_FUNC UpVal *luaF_newupval (lua_State *L); LUAI_FUNC UpVal *luaF_newupval (lua_State *L);
LUAI_FUNC UpVal *luaF_findupval (lua_State *L, StkId level); LUAI_FUNC UpVal *luaF_findupval (lua_State *L, StkId level);
LUAI_FUNC void luaF_close (lua_State *L, StkId level); LUAI_FUNC void luaF_close (lua_State *L, StkId level);
LUAI_FUNC void luaF_freeproto (lua_State *L, Proto *f); LUAI_FUNC void luaF_freeproto (lua_State *L, Proto *f);
LUAI_FUNC void luaF_freeclosure (lua_State *L, Closure *c); LUAI_FUNC void luaF_freeclosure (lua_State *L, Closure *c);
 End of changes. 2 change blocks. 
2 lines changed or deleted 2 lines changed or added


 lgc.h   lgc.h 
skipping to change at line 15 skipping to change at line 15
*/ */
#ifndef lgc_h #ifndef lgc_h
#define lgc_h #define lgc_h
#include "lobject.h" #include "lobject.h"
/* /*
** Possible states of the Garbage Collector ** Possible states of the Garbage Collector
*/ */
#define GCSpause 0 #define GCSpause 0
#define GCSpropagate 1 #define GCSpropagate 1
#define GCSsweepstring 2 #define GCSsweepstring 2
#define GCSsweep 3 #define GCSsweep 3
#define GCSfinalize 4 #define GCSfinalize 4
/* /*
** some userful bit tricks ** some userful bit tricks
*/ */
#define resetbits(x,m) ((x) &= cast(lu_byte, ~(m))) #define resetbits(x,m) ((x) &= cast(lu_byte, ~(m)))
#define setbits(x,m) ((x) |= (m)) #define setbits(x,m) ((x) |= (m))
#define testbits(x,m) ((x) & (m)) #define testbits(x,m) ((x) & (m))
#define bitmask(b) (1<<(b)) #define bitmask(b) (1<<(b))
#define bit2mask(b1,b2) (bitmask(b1) | bitmask(b2)) #define bit2mask(b1,b2) (bitmask(b1) | bitmask(b2))
#define l_setbit(x,b) setbits(x, bitmask(b)) #define l_setbit(x,b) setbits(x, bitmask(b))
#define resetbit(x,b) resetbits(x, bitmask(b)) #define resetbit(x,b) resetbits(x, bitmask(b))
#define testbit(x,b) testbits(x, bitmask(b)) #define testbit(x,b) testbits(x, bitmask(b))
#define set2bits(x,b1,b2) setbits(x, (bit2mask(b1, b2))) #define set2bits(x,b1,b2) setbits(x, (bit2mask(b1, b2)))
#define reset2bits(x,b1,b2) resetbits(x, (bit2mask(b1, b2))) #define reset2bits(x,b1,b2) resetbits(x, (bit2mask(b1, b2)))
#define test2bits(x,b1,b2) testbits(x, (bit2mask(b1, b2))) #define test2bits(x,b1,b2) testbits(x, (bit2mask(b1, b2)))
/* /*
** Layout for bit use in `marked' field: ** Layout for bit use in `marked' field:
** bit 0 - object is white (type 0) ** bit 0 - object is white (type 0)
** bit 1 - object is white (type 1) ** bit 1 - object is white (type 1)
** bit 2 - object is black ** bit 2 - object is black
** bit 3 - for userdata: has been finalized ** bit 3 - for userdata: has been finalized
** bit 3 - for tables: has weak keys ** bit 3 - for tables: has weak keys
** bit 4 - for tables: has weak values ** bit 4 - for tables: has weak values
** bit 5 - object is fixed (should not be collected) ** bit 5 - object is fixed (should not be collected)
** bit 6 - object is "super" fixed (only the main thread) ** bit 6 - object is "super" fixed (only the main thread)
*/ */
#define WHITE0BIT 0 #define WHITE0BIT 0
#define WHITE1BIT 1 #define WHITE1BIT 1
#define BLACKBIT 2 #define BLACKBIT 2
#define FINALIZEDBIT 3 #define FINALIZEDBIT 3
#define KEYWEAKBIT 3 #define KEYWEAKBIT 3
#define VALUEWEAKBIT 4 #define VALUEWEAKBIT 4
#define FIXEDBIT 5 #define FIXEDBIT 5
#define SFIXEDBIT 6 #define SFIXEDBIT 6
#define WHITEBITS bit2mask(WHITE0BIT, WHITE1BIT) #define WHITEBITS bit2mask(WHITE0BIT, WHITE1BIT)
#define iswhite(x) test2bits((x)->gch.marked, WHITE0BIT, WHITE1BIT) #define iswhite(x) test2bits((x)->gch.marked, WHITE0BIT, WHITE1BIT)
#define isblack(x) testbit((x)->gch.marked, BLACKBIT) #define isblack(x) testbit((x)->gch.marked, BLACKBIT)
#define isgray(x) (!isblack(x) && !iswhite(x)) #define isgray(x) (!isblack(x) && !iswhite(x))
#define otherwhite(g) (g->currentwhite ^ WHITEBITS) #define otherwhite(g) (g->currentwhite ^ WHITEBITS)
#define isdead(g,v) ((v)->gch.marked & otherwhite(g) & WHITEBITS) #define isdead(g,v) ((v)->gch.marked & otherwhite(g) & WHITEBITS)
#define changewhite(x) ((x)->gch.marked ^= WHITEBITS) #define changewhite(x) ((x)->gch.marked ^= WHITEBITS)
#define gray2black(x) l_setbit((x)->gch.marked, BLACKBIT) #define gray2black(x) l_setbit((x)->gch.marked, BLACKBIT)
#define valiswhite(x) (iscollectable(x) && iswhite(gcvalue(x))) #define valiswhite(x) (iscollectable(x) && iswhite(gcvalue(x)))
#define luaC_white(g) cast(lu_byte, (g)->currentwhite & WHITEBITS) #define luaC_white(g) cast(lu_byte, (g)->currentwhite & WHITEBITS)
#define luaC_checkGC(L) { \ #define luaC_checkGC(L) { \
condhardstacktests(luaD_reallocstack(L, L->stacksize - EXTRA_STACK - 1)); \ condhardstacktests(luaD_reallocstack(L, L->stacksize - EXTRA_STACK - 1)); \
if (G(L)->totalbytes >= G(L)->GCthreshold) \ if (G(L)->totalbytes >= G(L)->GCthreshold) \
luaC_step(L); } luaC_step(L); }
#define luaC_barrier(L,p,v) { if (valiswhite(v) && isblack(obj2gco(p))) \ #define luaC_barrier(L,p,v) { if (valiswhite(v) && isblack(obj2gco(p))) \
luaC_barrierf(L,obj2gco(p),gcvalue(v)); } luaC_barrierf(L,obj2gco(p),gcvalue(v)); }
#define luaC_barriert(L,t,v) { if (valiswhite(v) && isblack(obj2gco(t))) \ #define luaC_barriert(L,t,v) { if (valiswhite(v) && isblack(obj2gco(t))) \
luaC_barrierback(L,t); } luaC_barrierback(L,t); }
#define luaC_objbarrier(L,p,o) \ #define luaC_objbarrier(L,p,o) \
{ if (iswhite(obj2gco(o)) && isblack(obj2gco(p))) \ { if (iswhite(obj2gco(o)) && isblack(obj2gco(p))) \
luaC_barrierf(L,obj2gco(p),obj2gco(o)); } luaC_barrierf(L,obj2gco(p),obj2gco(o)); }
#define luaC_objbarriert(L,t,o) \ #define luaC_objbarriert(L,t,o) \
{ if (iswhite(obj2gco(o)) && isblack(obj2gco(t))) luaC_barrierback(L,t); } { if (iswhite(obj2gco(o)) && isblack(obj2gco(t))) luaC_barrierback(L,t); }
LUAI_FUNC size_t luaC_separateudata (lua_State *L, int all); LUAI_FUNC size_t luaC_separateudata (lua_State *L, int all);
LUAI_FUNC void luaC_callGCTM (lua_State *L); LUAI_FUNC void luaC_callGCTM (lua_State *L);
LUAI_FUNC void luaC_freeall (lua_State *L); LUAI_FUNC void luaC_freeall (lua_State *L);
LUAI_FUNC void luaC_step (lua_State *L); LUAI_FUNC void luaC_step (lua_State *L);
LUAI_FUNC void luaC_fullgc (lua_State *L); LUAI_FUNC void luaC_fullgc (lua_State *L);
LUAI_FUNC void luaC_link (lua_State *L, GCObject *o, lu_byte tt); LUAI_FUNC void luaC_link (lua_State *L, GCObject *o, lu_byte tt);
 End of changes. 12 change blocks. 
37 lines changed or deleted 37 lines changed or added


 list.h   list.h 
skipping to change at line 56 skipping to change at line 56
* @user: extra user provided data to the walker * @user: extra user provided data to the walker
* *
* Callback function used when walking a list with xmlListWalk(). * Callback function used when walking a list with xmlListWalk().
* *
* Returns 0 to stop walking the list, 1 otherwise. * Returns 0 to stop walking the list, 1 otherwise.
*/ */
typedef int (*xmlListWalker) (const void *data, const void *user); typedef int (*xmlListWalker) (const void *data, const void *user);
/* Creation/Deletion */ /* Creation/Deletion */
XMLPUBFUN xmlListPtr XMLCALL XMLPUBFUN xmlListPtr XMLCALL
xmlListCreate (xmlListDeallocator deallocator, xmlListCreate (xmlListDeallocator deallocator,
xmlListDataCompare compare); xmlListDataCompare compare);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlListDelete (xmlListPtr l); xmlListDelete (xmlListPtr l);
/* Basic Operators */ /* Basic Operators */
XMLPUBFUN void * XMLCALL XMLPUBFUN void * XMLCALL
xmlListSearch (xmlListPtr l, xmlListSearch (xmlListPtr l,
void *data); void *data);
XMLPUBFUN void * XMLCALL XMLPUBFUN void * XMLCALL
xmlListReverseSearch (xmlListPtr l, xmlListReverseSearch (xmlListPtr l,
void *data); void *data);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlListInsert (xmlListPtr l, xmlListInsert (xmlListPtr l,
void *data) ; void *data) ;
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlListAppend (xmlListPtr l, xmlListAppend (xmlListPtr l,
void *data) ; void *data) ;
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlListRemoveFirst (xmlListPtr l, xmlListRemoveFirst (xmlListPtr l,
void *data); void *data);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlListRemoveLast (xmlListPtr l, xmlListRemoveLast (xmlListPtr l,
void *data); void *data);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlListRemoveAll (xmlListPtr l, xmlListRemoveAll (xmlListPtr l,
void *data); void *data);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlListClear (xmlListPtr l); xmlListClear (xmlListPtr l);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlListEmpty (xmlListPtr l); xmlListEmpty (xmlListPtr l);
XMLPUBFUN xmlLinkPtr XMLCALL XMLPUBFUN xmlLinkPtr XMLCALL
xmlListFront (xmlListPtr l); xmlListFront (xmlListPtr l);
XMLPUBFUN xmlLinkPtr XMLCALL XMLPUBFUN xmlLinkPtr XMLCALL
xmlListEnd (xmlListPtr l); xmlListEnd (xmlListPtr l);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlListSize (xmlListPtr l); xmlListSize (xmlListPtr l);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlListPopFront (xmlListPtr l); xmlListPopFront (xmlListPtr l);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlListPopBack (xmlListPtr l); xmlListPopBack (xmlListPtr l);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlListPushFront (xmlListPtr l, xmlListPushFront (xmlListPtr l,
void *data); void *data);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlListPushBack (xmlListPtr l, xmlListPushBack (xmlListPtr l,
void *data); void *data);
/* Advanced Operators */ /* Advanced Operators */
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlListReverse (xmlListPtr l); xmlListReverse (xmlListPtr l);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlListSort (xmlListPtr l); xmlListSort (xmlListPtr l);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlListWalk (xmlListPtr l, xmlListWalk (xmlListPtr l,
xmlListWalker walker, xmlListWalker walker,
const void *user); const void *user);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlListReverseWalk (xmlListPtr l, xmlListReverseWalk (xmlListPtr l,
xmlListWalker walker, xmlListWalker walker,
const void *user); const void *user);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlListMerge (xmlListPtr l1, xmlListMerge (xmlListPtr l1,
xmlListPtr l2); xmlListPtr l2);
XMLPUBFUN xmlListPtr XMLCALL XMLPUBFUN xmlListPtr XMLCALL
xmlListDup (const xmlListPtr old); xmlListDup (const xmlListPtr old);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlListCopy (xmlListPtr cur, xmlListCopy (xmlListPtr cur,
const xmlListPtr old); const xmlListPtr old);
/* Link operators */ /* Link operators */
XMLPUBFUN void * XMLCALL XMLPUBFUN void * XMLCALL
xmlLinkGetData (xmlLinkPtr lk); xmlLinkGetData (xmlLinkPtr lk);
/* xmlListUnique() */ /* xmlListUnique() */
/* xmlListSwap */ /* xmlListSwap */
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif
#endif /* __XML_LINK_INCLUDE__ */ #endif /* __XML_LINK_INCLUDE__ */
 End of changes. 26 change blocks. 
42 lines changed or deleted 42 lines changed or added


 llex.h   llex.h 
skipping to change at line 13 skipping to change at line 13
** Lexical Analyzer ** Lexical Analyzer
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
#ifndef llex_h #ifndef llex_h
#define llex_h #define llex_h
#include "lobject.h" #include "lobject.h"
#include "lzio.h" #include "lzio.h"
#define FIRST_RESERVED 257 #define FIRST_RESERVED 257
/* maximum length of a reserved word */ /* maximum length of a reserved word */
#define TOKEN_LEN (sizeof("function")/sizeof(char)) #define TOKEN_LEN (sizeof("function")/sizeof(char))
/* /*
* WARNING: if you change the order of this enumeration, * WARNING: if you change the order of this enumeration,
* grep "ORDER RESERVED" * grep "ORDER RESERVED"
*/ */
enum RESERVED { enum RESERVED {
/* terminal symbols denoted by reserved words */ /* terminal symbols denoted by reserved words */
TK_AND = FIRST_RESERVED, TK_BREAK, TK_AND = FIRST_RESERVED, TK_BREAK,
TK_DO, TK_ELSE, TK_ELSEIF, TK_END, TK_FALSE, TK_FOR, TK_FUNCTION, TK_DO, TK_ELSE, TK_ELSEIF, TK_END, TK_FALSE, TK_FOR, TK_FUNCTION,
TK_IF, TK_IN, TK_LOCAL, TK_NIL, TK_NOT, TK_OR, TK_REPEAT, TK_IF, TK_IN, TK_LOCAL, TK_NIL, TK_NOT, TK_OR, TK_REPEAT,
TK_RETURN, TK_THEN, TK_TRUE, TK_UNTIL, TK_WHILE, TK_RETURN, TK_THEN, TK_TRUE, TK_UNTIL, TK_WHILE,
/* other terminal symbols */ /* other terminal symbols */
TK_CONCAT, TK_DOTS, TK_EQ, TK_GE, TK_LE, TK_NE, TK_NUMBER, TK_CONCAT, TK_DOTS, TK_EQ, TK_GE, TK_LE, TK_NE, TK_NUMBER,
TK_NAME, TK_STRING, TK_EOS TK_NAME, TK_STRING, TK_EOS
}; };
/* number of reserved words */ /* number of reserved words */
#define NUM_RESERVED (cast(int, TK_WHILE-FIRST_RESERVED+1)) #define NUM_RESERVED (cast(int, TK_WHILE-FIRST_RESERVED+1))
/* array with token `names' */ /* array with token `names' */
LUAI_DATA const char *const luaX_tokens []; LUAI_DATA const char *const luaX_tokens [];
typedef union { typedef union {
lua_Number r; lua_Number r;
TString *ts; TString *ts;
} SemInfo; /* semantics information */ } SemInfo; /* semantics information */
typedef struct Token { typedef struct Token {
 End of changes. 3 change blocks. 
3 lines changed or deleted 3 lines changed or added


 llimits.h   llimits.h 
skipping to change at line 24 skipping to change at line 24
typedef LUAI_UINT32 lu_int32; typedef LUAI_UINT32 lu_int32;
typedef LUAI_UMEM lu_mem; typedef LUAI_UMEM lu_mem;
typedef LUAI_MEM l_mem; typedef LUAI_MEM l_mem;
/* chars used as small naturals (so that `char' is reserved for characters) */ /* chars used as small naturals (so that `char' is reserved for characters) */
typedef unsigned char lu_byte; typedef unsigned char lu_byte;
#define MAX_SIZET ((size_t)(~(size_t)0)-2) #define MAX_SIZET ((size_t)(~(size_t)0)-2)
#define MAX_LUMEM ((lu_mem)(~(lu_mem)0)-2) #define MAX_LUMEM ((lu_mem)(~(lu_mem)0)-2)
#define MAX_INT (INT_MAX-2) /* maximum value of an int (-2 for safety) */ #define MAX_INT (INT_MAX-2) /* maximum value of an int (-2 for safety) */
/* /*
** conversion of pointer to integer ** conversion of pointer to integer
** this is for hashing only; there is no problem if the integer ** this is for hashing only; there is no problem if the integer
** cannot hold the whole pointer value ** cannot hold the whole pointer value
*/ */
#define IntPoint(p) ((unsigned int)(lu_mem)(p)) #define IntPoint(p) ((unsigned int)(lu_mem)(p))
/* type to ensure maximum alignment */ /* type to ensure maximum alignment */
typedef LUAI_USER_ALIGNMENT_T L_Umaxalign; typedef LUAI_USER_ALIGNMENT_T L_Umaxalign;
/* result of a `usual argument conversion' over lua_Number */ /* result of a `usual argument conversion' over lua_Number */
typedef LUAI_UACNUMBER l_uacNumber; typedef LUAI_UACNUMBER l_uacNumber;
/* internal assertions for in-house debugging */ /* internal assertions for in-house debugging */
#ifdef lua_assert #ifdef lua_assert
#define check_exp(c,e) (lua_assert(c), (e)) #define check_exp(c,e) (lua_assert(c), (e))
#define api_check(l,e) lua_assert(e) #define api_check(l,e) lua_assert(e)
#else #else
#define lua_assert(c) ((void)0) #define lua_assert(c) ((void)0)
#define check_exp(c,e) (e) #define check_exp(c,e) (e)
#define api_check luai_apicheck #define api_check luai_apicheck
#endif #endif
#ifndef UNUSED #ifndef UNUSED
#define UNUSED(x) ((void)(x)) /* to avoid warnings */ #define UNUSED(x) ((void)(x)) /* to avoid warnings */
#endif #endif
#ifndef cast #ifndef cast
#define cast(t, exp) ((t)(exp)) #define cast(t, exp) ((t)(exp))
#endif #endif
#define cast_byte(i) cast(lu_byte, (i)) #define cast_byte(i) cast(lu_byte, (i))
#define cast_num(i) cast(lua_Number, (i)) #define cast_num(i) cast(lua_Number, (i))
#define cast_int(i) cast(int, (i)) #define cast_int(i) cast(int, (i))
/* /*
** type for virtual-machine instructions ** type for virtual-machine instructions
** must be an unsigned with (at least) 4 bytes (see details in lopcodes.h) ** must be an unsigned with (at least) 4 bytes (see details in lopcodes.h)
*/ */
typedef lu_int32 Instruction; typedef lu_int32 Instruction;
/* maximum stack for a Lua function */ /* maximum stack for a Lua function */
#define MAXSTACK 250 #define MAXSTACK 250
/* minimum size for the string table (must be power of 2) */ /* minimum size for the string table (must be power of 2) */
#ifndef MINSTRTABSIZE #ifndef MINSTRTABSIZE
#define MINSTRTABSIZE 32 #define MINSTRTABSIZE 32
#endif #endif
/* minimum size for string buffer */ /* minimum size for string buffer */
#ifndef LUA_MINBUFFER #ifndef LUA_MINBUFFER
#define LUA_MINBUFFER 32 #define LUA_MINBUFFER 32
#endif #endif
#ifndef lua_lock #ifndef lua_lock
#define lua_lock(L) ((void) 0) #define lua_lock(L) ((void) 0)
#define lua_unlock(L) ((void) 0) #define lua_unlock(L) ((void) 0)
#endif #endif
#ifndef luai_threadyield #ifndef luai_threadyield
#define luai_threadyield(L) {lua_unlock(L); lua_lock(L);} #define luai_threadyield(L) {lua_unlock(L); lua_lock(L);}
#endif #endif
/* /*
** macro to control inclusion of some hard tests on stack reallocation ** macro to control inclusion of some hard tests on stack reallocation
*/ */
#ifndef HARDSTACKTESTS #ifndef HARDSTACKTESTS
#define condhardstacktests(x) ((void)0) #define condhardstacktests(x) ((void)0)
#else #else
#define condhardstacktests(x) x #define condhardstacktests(x) x
#endif #endif
#endif #endif
 End of changes. 12 change blocks. 
17 lines changed or deleted 17 lines changed or added


 lmem.h   lmem.h 
skipping to change at line 15 skipping to change at line 15
*/ */
#ifndef lmem_h #ifndef lmem_h
#define lmem_h #define lmem_h
#include <stddef.h> #include <stddef.h>
#include "llimits.h" #include "llimits.h"
#include "lua.h" #include "lua.h"
#define MEMERRMSG "not enough memory" #define MEMERRMSG "not enough memory"
#define luaM_reallocv(L,b,on,n,e) \ #define luaM_reallocv(L,b,on,n,e) \
((cast(size_t, (n)+1) <= MAX_SIZET/(e)) ? /* +1 to avoid warnings * ((cast(size_t, (n)+1) <= MAX_SIZET/(e)) ? /* +1 to avoid warnings */ \
/ \ luaM_realloc_(L, (b), (on)*(e), (n)*(e)) : \
luaM_realloc_(L, (b), (on)*(e), (n)*(e)) : \ luaM_toobig(L))
luaM_toobig(L))
#define luaM_freemem(L, b, s) luaM_realloc_(L, (b), (s), 0) #define luaM_freemem(L, b, s) luaM_realloc_(L, (b), (s), 0)
#define luaM_free(L, b) luaM_realloc_(L, (b), sizeof(*(b)), #define luaM_free(L, b) luaM_realloc_(L, (b), sizeof(*(b)), 0)
0)
#define luaM_freearray(L, b, n, t) luaM_reallocv(L, (b), n, 0, sizeof(t)) #define luaM_freearray(L, b, n, t) luaM_reallocv(L, (b), n, 0, sizeof(t))
#define luaM_malloc(L,t) luaM_realloc_(L, NULL, 0, (t)) #define luaM_malloc(L,t) luaM_realloc_(L, NULL, 0, (t))
#define luaM_new(L,t) cast(t *, luaM_malloc(L, sizeof(t))) #define luaM_new(L,t) cast(t *, luaM_malloc(L, sizeof(t)))
#define luaM_newvector(L,n,t) \ #define luaM_newvector(L,n,t) \
cast(t *, luaM_reallocv(L, NULL, 0, n, sizeof(t))) cast(t *, luaM_reallocv(L, NULL, 0, n, sizeof(t)))
#define luaM_growvector(L,v,nelems,size,t,limit,e) \ #define luaM_growvector(L,v,nelems,size,t,limit,e) \
if ((nelems)+1 > (size)) \ if ((nelems)+1 > (size)) \
((v)=cast(t *, luaM_growaux_(L,v,&(size),sizeof(t),limit,e))) ((v)=cast(t *, luaM_growaux_(L,v,&(size),sizeof(t),limit,e)))
#define luaM_reallocvector(L, v,oldn,n,t) \ #define luaM_reallocvector(L, v,oldn,n,t) \
((v)=cast(t *, luaM_reallocv(L, v, oldn, n, sizeof(t)))) ((v)=cast(t *, luaM_reallocv(L, v, oldn, n, sizeof(t))))
LUAI_FUNC void *luaM_realloc_ (lua_State *L, void *block, size_t oldsize, LUAI_FUNC void *luaM_realloc_ (lua_State *L, void *block, size_t oldsize,
size_t size); size_t size);
 End of changes. 5 change blocks. 
11 lines changed or deleted 9 lines changed or added


 lobject.h   lobject.h 
skipping to change at line 16 skipping to change at line 16
#ifndef lobject_h #ifndef lobject_h
#define lobject_h #define lobject_h
#include <stdarg.h> #include <stdarg.h>
#include "llimits.h" #include "llimits.h"
#include "lua.h" #include "lua.h"
/* tags for values visible from Lua */ /* tags for values visible from Lua */
#define LAST_TAG LUA_TTHREAD #define LAST_TAG LUA_TTHREAD
#define NUM_TAGS (LAST_TAG+1) #define NUM_TAGS (LAST_TAG+1)
/* /*
** Extra tags for non-values ** Extra tags for non-values
*/ */
#define LUA_TPROTO (LAST_TAG+1) #define LUA_TPROTO (LAST_TAG+1)
#define LUA_TUPVAL (LAST_TAG+2) #define LUA_TUPVAL (LAST_TAG+2)
#define LUA_TDEADKEY (LAST_TAG+3) #define LUA_TDEADKEY (LAST_TAG+3)
/* /*
** Union of all collectable objects ** Union of all collectable objects
*/ */
typedef union GCObject GCObject; typedef union GCObject GCObject;
/* /*
** Common Header for all collectable objects (in macro form, to be ** Common Header for all collectable objects (in macro form, to be
** included in other objects) ** included in other objects)
*/ */
#define CommonHeader GCObject *next; lu_byte tt; lu_byte marked #define CommonHeader GCObject *next; lu_byte tt; lu_byte marked
/* /*
** Common header in struct form ** Common header in struct form
*/ */
typedef struct GCheader { typedef struct GCheader {
CommonHeader; CommonHeader;
} GCheader; } GCheader;
/* /*
** Union of all Lua values ** Union of all Lua values
skipping to change at line 59 skipping to change at line 59
GCObject *gc; GCObject *gc;
void *p; void *p;
lua_Number n; lua_Number n;
int b; int b;
} Value; } Value;
/* /*
** Tagged Values ** Tagged Values
*/ */
#define TValuefields Value value; int tt #define TValuefields Value value; int tt
typedef struct lua_TValue { typedef struct lua_TValue {
TValuefields; TValuefields;
} TValue; } TValue;
/* Macros to test type */ /* Macros to test type */
#define ttisnil(o) (ttype(o) == LUA_TNIL) #define ttisnil(o) (ttype(o) == LUA_TNIL)
#define ttisnumber(o) (ttype(o) == LUA_TNUMBER) #define ttisnumber(o) (ttype(o) == LUA_TNUMBER)
#define ttisstring(o) (ttype(o) == LUA_TSTRING) #define ttisstring(o) (ttype(o) == LUA_TSTRING)
#define ttistable(o) (ttype(o) == LUA_TTABLE) #define ttistable(o) (ttype(o) == LUA_TTABLE)
#define ttisfunction(o) (ttype(o) == LUA_TFUNCTION) #define ttisfunction(o) (ttype(o) == LUA_TFUNCTION)
#define ttisboolean(o) (ttype(o) == LUA_TBOOLEAN) #define ttisboolean(o) (ttype(o) == LUA_TBOOLEAN)
#define ttisuserdata(o) (ttype(o) == LUA_TUSERDATA) #define ttisuserdata(o) (ttype(o) == LUA_TUSERDATA)
#define ttisthread(o) (ttype(o) == LUA_TTHREAD) #define ttisthread(o) (ttype(o) == LUA_TTHREAD)
#define ttislightuserdata(o) (ttype(o) == LUA_TLIGHTUSERDATA) #define ttislightuserdata(o) (ttype(o) == LUA_TLIGHTUSERDATA)
/* Macros to access values */ /* Macros to access values */
#define ttype(o) ((o)->tt) #define ttype(o) ((o)->tt)
#define gcvalue(o) check_exp(iscollectable(o), (o)->value.gc) #define gcvalue(o) check_exp(iscollectable(o), (o)->value.gc)
#define pvalue(o) check_exp(ttislightuserdata(o), (o)->value.p) #define pvalue(o) check_exp(ttislightuserdata(o), (o)->value.p)
#define nvalue(o) check_exp(ttisnumber(o), (o)->value.n) #define nvalue(o) check_exp(ttisnumber(o), (o)->value.n)
#define rawtsvalue(o) check_exp(ttisstring(o), &(o)->value.gc->ts) #define rawtsvalue(o) check_exp(ttisstring(o), &(o)->value.gc->ts)
#define tsvalue(o) (&rawtsvalue(o)->tsv) #define tsvalue(o) (&rawtsvalue(o)->tsv)
#define rawuvalue(o) check_exp(ttisuserdata(o), &(o)->value.gc->u) #define rawuvalue(o) check_exp(ttisuserdata(o), &(o)->value.gc->u)
#define uvalue(o) (&rawuvalue(o)->uv) #define uvalue(o) (&rawuvalue(o)->uv)
#define clvalue(o) check_exp(ttisfunction(o), &(o)->value.gc->cl) #define clvalue(o) check_exp(ttisfunction(o), &(o)->value.gc->cl)
#define hvalue(o) check_exp(ttistable(o), &(o)->value.gc->h) #define hvalue(o) check_exp(ttistable(o), &(o)->value.gc->h)
#define bvalue(o) check_exp(ttisboolean(o), (o)->value.b) #define bvalue(o) check_exp(ttisboolean(o), (o)->value.b)
#define thvalue(o) check_exp(ttisthread(o), &(o)->value.gc->th) #define thvalue(o) check_exp(ttisthread(o), &(o)->value.gc->th)
#define l_isfalse(o) (ttisnil(o) || (ttisboolean(o) && bvalue(o) == 0)) #define l_isfalse(o) (ttisnil(o) || (ttisboolean(o) && bvalue(o) == 0))
/* /*
** for internal debug only ** for internal debug only
*/ */
#define checkconsistency(obj) \ #define checkconsistency(obj) \
lua_assert(!iscollectable(obj) || (ttype(obj) == (obj)->value.gc->gch.tt) ) lua_assert(!iscollectable(obj) || (ttype(obj) == (obj)->value.gc->gch.tt) )
#define checkliveness(g,obj) \ #define checkliveness(g,obj) \
lua_assert(!iscollectable(obj) || \ lua_assert(!iscollectable(obj) || \
((ttype(obj) == (obj)->value.gc->gch.tt) && !isdead(g, (obj)->value.gc))) ((ttype(obj) == (obj)->value.gc->gch.tt) && !isdead(g, (obj)->value.gc)))
skipping to change at line 154 skipping to change at line 154
#define setobj(L,obj1,obj2) \ #define setobj(L,obj1,obj2) \
{ const TValue *o2=(obj2); TValue *o1=(obj1); \ { const TValue *o2=(obj2); TValue *o1=(obj1); \
o1->value = o2->value; o1->tt=o2->tt; \ o1->value = o2->value; o1->tt=o2->tt; \
checkliveness(G(L),o1); } checkliveness(G(L),o1); }
/* /*
** different types of sets, according to destination ** different types of sets, according to destination
*/ */
/* from stack to (same) stack */ /* from stack to (same) stack */
#define setobjs2s setobj #define setobjs2s setobj
/* to stack (not from same stack) */ /* to stack (not from same stack) */
#define setobj2s setobj #define setobj2s setobj
#define setsvalue2s setsvalue #define setsvalue2s setsvalue
#define sethvalue2s sethvalue #define sethvalue2s sethvalue
#define setptvalue2s setptvalue #define setptvalue2s setptvalue
/* from table to same table */ /* from table to same table */
#define setobjt2t setobj #define setobjt2t setobj
/* to table */ /* to table */
#define setobj2t setobj #define setobj2t setobj
/* to new object */ /* to new object */
#define setobj2n setobj #define setobj2n setobj
#define setsvalue2n setsvalue #define setsvalue2n setsvalue
#define setttype(obj, tt) (ttype(obj) = (tt)) #define setttype(obj, tt) (ttype(obj) = (tt))
#define iscollectable(o) (ttype(o) >= LUA_TSTRING) #define iscollectable(o) (ttype(o) >= LUA_TSTRING)
typedef TValue *StkId; /* index to stack elements */ typedef TValue *StkId; /* index to stack elements */
/* /*
** String headers for string table ** String headers for string table
*/ */
typedef union TString { typedef union TString {
L_Umaxalign dummy; /* ensures maximum alignment for strings */ L_Umaxalign dummy; /* ensures maximum alignment for strings */
struct { struct {
CommonHeader; CommonHeader;
lu_byte reserved; lu_byte reserved;
unsigned int hash; unsigned int hash;
size_t len; size_t len;
} tsv; } tsv;
} TString; } TString;
#define getstr(ts) cast(const char *, (ts) + 1) #define getstr(ts) cast(const char *, (ts) + 1)
#define svalue(o) getstr(rawtsvalue(o)) #define svalue(o) getstr(rawtsvalue(o))
typedef union Udata { typedef union Udata {
L_Umaxalign dummy; /* ensures maximum alignment for `local' udata */ L_Umaxalign dummy; /* ensures maximum alignment for `local' udata */
struct { struct {
CommonHeader; CommonHeader;
struct Table *metatable; struct Table *metatable;
struct Table *env; struct Table *env;
size_t len; size_t len;
} uv; } uv;
skipping to change at line 228 skipping to change at line 228
int linedefined; int linedefined;
int lastlinedefined; int lastlinedefined;
GCObject *gclist; GCObject *gclist;
lu_byte nups; /* number of upvalues */ lu_byte nups; /* number of upvalues */
lu_byte numparams; lu_byte numparams;
lu_byte is_vararg; lu_byte is_vararg;
lu_byte maxstacksize; lu_byte maxstacksize;
} Proto; } Proto;
/* masks for new-style vararg */ /* masks for new-style vararg */
#define VARARG_HASARG 1 #define VARARG_HASARG 1
#define VARARG_ISVARARG 2 #define VARARG_ISVARARG 2
#define VARARG_NEEDSARG 4 #define VARARG_NEEDSARG 4
typedef struct LocVar { typedef struct LocVar {
TString *varname; TString *varname;
int startpc; /* first point where variable is active */ int startpc; /* first point where variable is active */
int endpc; /* first point where variable is dead */ int endpc; /* first point where variable is dead */
} LocVar; } LocVar;
/* /*
** Upvalues ** Upvalues
*/ */
skipping to change at line 259 skipping to change at line 259
struct UpVal *next; struct UpVal *next;
} l; } l;
} u; } u;
} UpVal; } UpVal;
/* /*
** Closures ** Closures
*/ */
#define ClosureHeader \ #define ClosureHeader \
CommonHeader; lu_byte isC; lu_byte nupvalues; GCObject *gclist; \ CommonHeader; lu_byte isC; lu_byte nupvalues; GCObject *gclist; \
struct Table *env struct Table *env
typedef struct CClosure { typedef struct CClosure {
ClosureHeader; ClosureHeader;
lua_CFunction f; lua_CFunction f;
TValue upvalue[1]; TValue upvalue[1];
} CClosure; } CClosure;
typedef struct LClosure { typedef struct LClosure {
ClosureHeader; ClosureHeader;
struct Proto *p; struct Proto *p;
UpVal *upvals[1]; UpVal *upvals[1];
} LClosure; } LClosure;
typedef union Closure { typedef union Closure {
CClosure c; CClosure c;
LClosure l; LClosure l;
} Closure; } Closure;
#define iscfunction(o) (ttype(o) == LUA_TFUNCTION && clvalue(o)->c.isC) #define iscfunction(o) (ttype(o) == LUA_TFUNCTION && clvalue(o)->c.isC)
#define isLfunction(o) (ttype(o) == LUA_TFUNCTION && !clvalue(o)->c.isC) #define isLfunction(o) (ttype(o) == LUA_TFUNCTION && !clvalue(o)->c.isC)
/* /*
** Tables ** Tables
*/ */
typedef union TKey { typedef union TKey {
struct { struct {
TValuefields; TValuefields;
struct Node *next; /* for chaining */ struct Node *next; /* for chaining */
} nk; } nk;
skipping to change at line 315 skipping to change at line 315
Node *node; Node *node;
Node *lastfree; /* any free position is before this position */ Node *lastfree; /* any free position is before this position */
GCObject *gclist; GCObject *gclist;
int sizearray; /* size of `array' array */ int sizearray; /* size of `array' array */
} Table; } Table;
/* /*
** `module' operation for hashing (size is always a power of 2) ** `module' operation for hashing (size is always a power of 2)
*/ */
#define lmod(s,size) \ #define lmod(s,size) \
(check_exp((size&(size-1))==0, (cast(int, (s) & ((size)-1))))) (check_exp((size&(size-1))==0, (cast(int, (s) & ((size)-1)))))
#define twoto(x) (1<<(x)) #define twoto(x) (1<<(x))
#define sizenode(t) (twoto((t)->lsizenode)) #define sizenode(t) (twoto((t)->lsizenode))
#define luaO_nilobject (&luaO_nilobject_) #define luaO_nilobject (&luaO_nilobject_)
LUAI_DATA const TValue luaO_nilobject_; LUAI_DATA const TValue luaO_nilobject_;
#define ceillog2(x) (luaO_log2((x)-1) + 1) #define ceillog2(x) (luaO_log2((x)-1) + 1)
LUAI_FUNC int luaO_log2 (unsigned int x); LUAI_FUNC int luaO_log2 (unsigned int x);
LUAI_FUNC int luaO_int2fb (unsigned int x); LUAI_FUNC int luaO_int2fb (unsigned int x);
LUAI_FUNC int luaO_fb2int (int x); LUAI_FUNC int luaO_fb2int (int x);
LUAI_FUNC int luaO_rawequalObj (const TValue *t1, const TValue *t2); LUAI_FUNC int luaO_rawequalObj (const TValue *t1, const TValue *t2);
LUAI_FUNC int luaO_str2d (const char *s, lua_Number *result); LUAI_FUNC int luaO_str2d (const char *s, lua_Number *result);
LUAI_FUNC const char *luaO_pushvfstring (lua_State *L, const char *fmt, LUAI_FUNC const char *luaO_pushvfstring (lua_State *L, const char *fmt,
va_list argp); va_list argp);
LUAI_FUNC const char *luaO_pushfstring (lua_State *L, const char *fmt, ...) ; LUAI_FUNC const char *luaO_pushfstring (lua_State *L, const char *fmt, ...) ;
LUAI_FUNC void luaO_chunkid (char *out, const char *source, size_t len); LUAI_FUNC void luaO_chunkid (char *out, const char *source, size_t len);
 End of changes. 22 change blocks. 
52 lines changed or deleted 52 lines changed or added


 lopcodes.h   lopcodes.h 
skipping to change at line 16 skipping to change at line 16
#ifndef lopcodes_h #ifndef lopcodes_h
#define lopcodes_h #define lopcodes_h
#include "llimits.h" #include "llimits.h"
/*========================================================================= == /*========================================================================= ==
We assume that instructions are unsigned numbers. We assume that instructions are unsigned numbers.
All instructions have an opcode in the first 6 bits. All instructions have an opcode in the first 6 bits.
Instructions can have the following fields: Instructions can have the following fields:
`A' : 8 bits `A' : 8 bits
`B' : 9 bits `B' : 9 bits
`C' : 9 bits `C' : 9 bits
`Bx' : 18 bits (`B' and `C' together) `Bx' : 18 bits (`B' and `C' together)
`sBx' : signed Bx `sBx' : signed Bx
A signed argument is represented in excess K; that is, the number A signed argument is represented in excess K; that is, the number
value is the unsigned value minus K. K is exactly the maximum value value is the unsigned value minus K. K is exactly the maximum value
for that argument (so that -max is represented by 0, and +max is for that argument (so that -max is represented by 0, and +max is
represented by 2*max), which is half the maximum for the corresponding represented by 2*max), which is half the maximum for the corresponding
unsigned argument. unsigned argument.
=========================================================================== */ =========================================================================== */
enum OpMode {iABC, iABx, iAsBx}; /* basic instruction format */ enum OpMode {iABC, iABx, iAsBx}; /* basic instruction format */
/* /*
** size and position of opcode arguments. ** size and position of opcode arguments.
*/ */
#define SIZE_C 9 #define SIZE_C 9
#define SIZE_B 9 #define SIZE_B 9
#define SIZE_Bx (SIZE_C + SIZE_B) #define SIZE_Bx (SIZE_C + SIZE_B)
#define SIZE_A 8 #define SIZE_A 8
#define SIZE_OP 6 #define SIZE_OP 6
#define POS_OP 0 #define POS_OP 0
#define POS_A (POS_OP + SIZE_OP) #define POS_A (POS_OP + SIZE_OP)
#define POS_C (POS_A + SIZE_A) #define POS_C (POS_A + SIZE_A)
#define POS_B (POS_C + SIZE_C) #define POS_B (POS_C + SIZE_C)
#define POS_Bx POS_C #define POS_Bx POS_C
/* /*
** limits for opcode arguments. ** limits for opcode arguments.
** we use (signed) int to manipulate most arguments, ** we use (signed) int to manipulate most arguments,
** so they must fit in LUAI_BITSINT-1 bits (-1 for sign) ** so they must fit in LUAI_BITSINT-1 bits (-1 for sign)
*/ */
#if SIZE_Bx < LUAI_BITSINT-1 #if SIZE_Bx < LUAI_BITSINT-1
#define MAXARG_Bx ((1<<SIZE_Bx)-1) #define MAXARG_Bx ((1<<SIZE_Bx)-1)
#define MAXARG_sBx (MAXARG_Bx>>1) /* `sBx' is signed */ #define MAXARG_sBx (MAXARG_Bx>>1) /* `sBx' is signed */
#else #else
#define MAXARG_Bx MAX_INT #define MAXARG_Bx MAX_INT
#define MAXARG_sBx MAX_INT #define MAXARG_sBx MAX_INT
#endif #endif
#define MAXARG_A ((1<<SIZE_A)-1) #define MAXARG_A ((1<<SIZE_A)-1)
#define MAXARG_B ((1<<SIZE_B)-1) #define MAXARG_B ((1<<SIZE_B)-1)
#define MAXARG_C ((1<<SIZE_C)-1) #define MAXARG_C ((1<<SIZE_C)-1)
/* creates a mask with `n' 1 bits at position `p' */ /* creates a mask with `n' 1 bits at position `p' */
#define MASK1(n,p) ((~((~(Instruction)0)<<n))<<p) #define MASK1(n,p) ((~((~(Instruction)0)<<n))<<p)
/* creates a mask with `n' 0 bits at position `p' */ /* creates a mask with `n' 0 bits at position `p' */
#define MASK0(n,p) (~MASK1(n,p)) #define MASK0(n,p) (~MASK1(n,p))
/* /*
** the following macros help to manipulate instructions ** the following macros help to manipulate instructions
*/ */
#define GET_OPCODE(i) (cast(OpCode, ((i)>>POS_OP) & MASK1(SIZE_OP,0))) #define GET_OPCODE(i) (cast(OpCode, ((i)>>POS_OP) & MASK1(SIZE_OP,0)))
#define SET_OPCODE(i,o) ((i) = (((i)&MASK0(SIZE_OP,POS_OP)) | \ #define SET_OPCODE(i,o) ((i) = (((i)&MASK0(SIZE_OP,POS_OP)) | \
((cast(Instruction, o)<<POS_OP)&MASK1(SIZE_OP,POS_OP)))) ((cast(Instruction, o)<<POS_OP)&MASK1(SIZE_OP,POS_OP))))
#define GETARG_A(i) (cast(int, ((i)>>POS_A) & MASK1(SIZE_A,0))) #define GETARG_A(i) (cast(int, ((i)>>POS_A) & MASK1(SIZE_A,0)))
#define SETARG_A(i,u) ((i) = (((i)&MASK0(SIZE_A,POS_A)) | \ #define SETARG_A(i,u) ((i) = (((i)&MASK0(SIZE_A,POS_A)) | \
((cast(Instruction, u)<<POS_A)&MASK1(SIZE_A,POS_A)))) ((cast(Instruction, u)<<POS_A)&MASK1(SIZE_A,POS_A))))
#define GETARG_B(i) (cast(int, ((i)>>POS_B) & MASK1(SIZE_B,0))) #define GETARG_B(i) (cast(int, ((i)>>POS_B) & MASK1(SIZE_B,0)))
#define SETARG_B(i,b) ((i) = (((i)&MASK0(SIZE_B,POS_B)) | \ #define SETARG_B(i,b) ((i) = (((i)&MASK0(SIZE_B,POS_B)) | \
((cast(Instruction, b)<<POS_B)&MASK1(SIZE_B,POS_B)))) ((cast(Instruction, b)<<POS_B)&MASK1(SIZE_B,POS_B))))
#define GETARG_C(i) (cast(int, ((i)>>POS_C) & MASK1(SIZE_C,0))) #define GETARG_C(i) (cast(int, ((i)>>POS_C) & MASK1(SIZE_C,0)))
#define SETARG_C(i,b) ((i) = (((i)&MASK0(SIZE_C,POS_C)) | \ #define SETARG_C(i,b) ((i) = (((i)&MASK0(SIZE_C,POS_C)) | \
((cast(Instruction, b)<<POS_C)&MASK1(SIZE_C,POS_C)))) ((cast(Instruction, b)<<POS_C)&MASK1(SIZE_C,POS_C))))
#define GETARG_Bx(i) (cast(int, ((i)>>POS_Bx) & MASK1(SIZE_Bx,0))) #define GETARG_Bx(i) (cast(int, ((i)>>POS_Bx) & MASK1(SIZE_Bx,0)))
#define SETARG_Bx(i,b) ((i) = (((i)&MASK0(SIZE_Bx,POS_Bx)) | \ #define SETARG_Bx(i,b) ((i) = (((i)&MASK0(SIZE_Bx,POS_Bx)) | \
((cast(Instruction, b)<<POS_Bx)&MASK1(SIZE_Bx,POS_Bx)))) ((cast(Instruction, b)<<POS_Bx)&MASK1(SIZE_Bx,POS_Bx))))
#define GETARG_sBx(i) (GETARG_Bx(i)-MAXARG_sBx) #define GETARG_sBx(i) (GETARG_Bx(i)-MAXARG_sBx)
#define SETARG_sBx(i,b) SETARG_Bx((i),cast(unsigned int, (b)+MAXARG_ #define SETARG_sBx(i,b) SETARG_Bx((i),cast(unsigned int, (b)+MAXARG_sBx)
sBx)) )
#define CREATE_ABC(o,a,b,c) ((cast(Instruction, o)<<POS_OP) \ #define CREATE_ABC(o,a,b,c) ((cast(Instruction, o)<<POS_OP) \
| (cast(Instruction, a)<<POS_A) \ | (cast(Instruction, a)<<POS_A) \
| (cast(Instruction, b)<<POS_B) \ | (cast(Instruction, b)<<POS_B) \
| (cast(Instruction, c)<<POS_C)) | (cast(Instruction, c)<<POS_C))
#define CREATE_ABx(o,a,bc) ((cast(Instruction, o)<<POS_OP) \ #define CREATE_ABx(o,a,bc) ((cast(Instruction, o)<<POS_OP) \
| (cast(Instruction, a)<<POS_A) \ | (cast(Instruction, a)<<POS_A) \
| (cast(Instruction, bc)<<POS_Bx)) | (cast(Instruction, bc)<<POS_Bx))
/* /*
** Macros to operate RK indices ** Macros to operate RK indices
*/ */
/* this bit 1 means constant (0 means register) */ /* this bit 1 means constant (0 means register) */
#define BITRK (1 << (SIZE_B - 1)) #define BITRK (1 << (SIZE_B - 1))
/* test whether value is a constant */ /* test whether value is a constant */
#define ISK(x) ((x) & BITRK) #define ISK(x) ((x) & BITRK)
/* gets the index of the constant */ /* gets the index of the constant */
#define INDEXK(r) ((int)(r) & ~BITRK) #define INDEXK(r) ((int)(r) & ~BITRK)
#define MAXINDEXRK (BITRK - 1) #define MAXINDEXRK (BITRK - 1)
/* code a constant index as a RK value */ /* code a constant index as a RK value */
#define RKASK(x) ((x) | BITRK) #define RKASK(x) ((x) | BITRK)
/* /*
** invalid register that fits in 8 bits ** invalid register that fits in 8 bits
*/ */
#define NO_REG MAXARG_A #define NO_REG MAXARG_A
/* /*
** R(x) - register ** R(x) - register
** Kst(x) - constant (in constant table) ** Kst(x) - constant (in constant table)
** RK(x) == if ISK(x) then Kst(INDEXK(x)) else R(x) ** RK(x) == if ISK(x) then Kst(INDEXK(x)) else R(x)
*/ */
/* /*
** grep "ORDER OP" if you change these enums ** grep "ORDER OP" if you change these enums
*/ */
typedef enum { typedef enum {
/*---------------------------------------------------------------------- /*----------------------------------------------------------------------
name args description name args description
------------------------------------------------------------------------*/ ------------------------------------------------------------------------*/
OP_MOVE,/* A B R(A) := R(B) */ OP_MOVE,/* A B R(A) := R(B) */
OP_LOADK,/* A Bx R(A) := Kst(Bx) */ OP_LOADK,/* A Bx R(A) := Kst(Bx) */
OP_LOADBOOL,/* A B C R(A) := (Bool)B; if (C) pc++ */ OP_LOADBOOL,/* A B C R(A) := (Bool)B; if (C) pc++ */
OP_LOADNIL,/* A B R(A) := ... := R(B) := nil */ OP_LOADNIL,/* A B R(A) := ... := R(B) := nil */
OP_GETUPVAL,/* A B R(A) := UpValue[B] */ OP_GETUPVAL,/* A B R(A) := UpValue[B] */
OP_GETGLOBAL,/* A Bx R(A) := Gbl[Kst(Bx)] OP_GETGLOBAL,/* A Bx R(A) := Gbl[Kst(Bx)] */
*/ OP_GETTABLE,/* A B C R(A) := R(B)[RK(C)] */
OP_GETTABLE,/* A B C R(A) := R(B)[RK(C)] */
OP_SETGLOBAL,/* A Bx Gbl[Kst(Bx)] := R(A) OP_SETGLOBAL,/* A Bx Gbl[Kst(Bx)] := R(A) */
*/ OP_SETUPVAL,/* A B UpValue[B] := R(A) */
OP_SETUPVAL,/* A B UpValue[B] := R(A) */ OP_SETTABLE,/* A B C R(A)[RK(B)] := RK(C) */
OP_SETTABLE,/* A B C R(A)[RK(B)] := RK(C) */
OP_NEWTABLE,/* A B C R(A) := {} (size = B,C) */ OP_NEWTABLE,/* A B C R(A) := {} (size = B,C) */
OP_SELF,/* A B C R(A+1) := R(B); R(A) := R(B)[RK(C)] */ OP_SELF,/* A B C R(A+1) := R(B); R(A) := R(B)[RK(C)] */
OP_ADD,/* A B C R(A) := RK(B) + RK(C) */ OP_ADD,/* A B C R(A) := RK(B) + RK(C) */
OP_SUB,/* A B C R(A) := RK(B) - RK(C) */ OP_SUB,/* A B C R(A) := RK(B) - RK(C) */
OP_MUL,/* A B C R(A) := RK(B) * RK(C) */ OP_MUL,/* A B C R(A) := RK(B) * RK(C) */
OP_DIV,/* A B C R(A) := RK(B) / RK(C) */ OP_DIV,/* A B C R(A) := RK(B) / RK(C) */
OP_MOD,/* A B C R(A) := RK(B) % RK(C) */ OP_MOD,/* A B C R(A) := RK(B) % RK(C) */
OP_POW,/* A B C R(A) := RK(B) ^ RK(C) */ OP_POW,/* A B C R(A) := RK(B) ^ RK(C) */
OP_UNM,/* A B R(A) := -R(B) */ OP_UNM,/* A B R(A) := -R(B) */
OP_NOT,/* A B R(A) := not R(B) */ OP_NOT,/* A B R(A) := not R(B) */
OP_LEN,/* A B R(A) := length of R(B) */ OP_LEN,/* A B R(A) := length of R(B) */
OP_CONCAT,/* A B C R(A) := R(B).. ... ..R(C) */ OP_CONCAT,/* A B C R(A) := R(B).. ... ..R(C) */
OP_JMP,/* sBx pc+=sBx */ OP_JMP,/* sBx pc+=sBx */
OP_EQ,/* A B C if ((RK(B) == RK(C)) ~= A) then pc++ */ OP_EQ,/* A B C if ((RK(B) == RK(C)) ~= A) then pc++ */
OP_LT,/* A B C if ((RK(B) < RK(C)) ~= A) then pc++ */ OP_LT,/* A B C if ((RK(B) < RK(C)) ~= A) then pc++ */
OP_LE,/* A B C if ((RK(B) <= RK(C)) ~= A) then pc++ */ OP_LE,/* A B C if ((RK(B) <= RK(C)) ~= A) then pc++ */
OP_TEST,/* A C if not (R(A) <=> C) then pc++ */ OP_TEST,/* A C if not (R(A) <=> C) then pc++ */
OP_TESTSET,/* A B C if (R(B) <=> C) then R(A) := R(B) else pc++ */ OP_TESTSET,/* A B C if (R(B) <=> C) then R(A) := R(B) else pc++ */
OP_CALL,/* A B C R(A), ... ,R(A+C-2) := R(A)(R(A+1), ... ,R(A+B-1)) * OP_CALL,/* A B C R(A), ... ,R(A+C-2) := R(A)(R(A+1), ... ,R(A+B-1)) *
/ /
OP_TAILCALL,/* A B C return R(A)(R(A+1), ... ,R(A+B-1)) */ OP_TAILCALL,/* A B C return R(A)(R(A+1), ... ,R(A+B-1)) */
OP_RETURN,/* A B return R(A), ... ,R(A+B-2) (see note) */ OP_RETURN,/* A B return R(A), ... ,R(A+B-2) (see note) */
OP_FORLOOP,/* A sBx R(A)+=R(A+2); OP_FORLOOP,/* A sBx R(A)+=R(A+2);
if R(A) <?= R(A+1) then { pc+=sBx; R(A+3)=R(A) }*/ if R(A) <?= R(A+1) then { pc+=sBx; R(A+3)=R(A) }*/
OP_FORPREP,/* A sBx R(A)-=R(A+2); pc+=sBx */ OP_FORPREP,/* A sBx R(A)-=R(A+2); pc+=sBx */
OP_TFORLOOP,/* A C R(A+3), ... ,R(A+2+C) := R(A)(R(A+1), R(A+2)); OP_TFORLOOP,/* A C R(A+3), ... ,R(A+2+C) := R(A)(R(A+1), R(A+2));
if R(A+3) ~= nil then R(A+2)=R(A+3) else pc++ */ if R(A+3) ~= nil then R(A+2)=R(A+3) else pc++ */
OP_SETLIST,/* A B C R(A)[(C-1)*FPF+i] := R(A+i), 1 <= i <= B */ OP_SETLIST,/* A B C R(A)[(C-1)*FPF+i] := R(A+i), 1 <= i <= B */
OP_CLOSE,/* A close all variables in the stack up to (>=) R(A)*/ OP_CLOSE,/* A close all variables in the stack up to (>=) R(A)*/
OP_CLOSURE,/* A Bx R(A) := closure(KPROTO[Bx], R(A), ... ,R(A+n)) */ OP_CLOSURE,/* A Bx R(A) := closure(KPROTO[Bx], R(A), ... ,R(A+n))
*/
OP_VARARG/* A B R(A), R(A+1), ..., R(A+B-1) = vararg */ OP_VARARG/* A B R(A), R(A+1), ..., R(A+B-1) = vararg */
} OpCode; } OpCode;
#define NUM_OPCODES (cast(int, OP_VARARG) + 1) #define NUM_OPCODES (cast(int, OP_VARARG) + 1)
/*========================================================================= == /*========================================================================= ==
Notes: Notes:
(*) In OP_CALL, if (B == 0) then B = top. C is the number of returns - 1, (*) In OP_CALL, if (B == 0) then B = top. C is the number of returns - 1,
and can be 0: OP_CALL then sets `top' to last_result+1, so and can be 0: OP_CALL then sets `top' to last_result+1, so
next open instruction (OP_CALL, OP_RETURN, OP_SETLIST) may use `top'. next open instruction (OP_CALL, OP_RETURN, OP_SETLIST) may use `top'.
(*) In OP_VARARG, if (B == 0) then use actual number of varargs and (*) In OP_VARARG, if (B == 0) then use actual number of varargs and
set top (like in OP_CALL with C == 0). set top (like in OP_CALL with C == 0).
skipping to change at line 239 skipping to change at line 239
enum OpArgMask { enum OpArgMask {
OpArgN, /* argument is not used */ OpArgN, /* argument is not used */
OpArgU, /* argument is used */ OpArgU, /* argument is used */
OpArgR, /* argument is a register or a jump offset */ OpArgR, /* argument is a register or a jump offset */
OpArgK /* argument is a constant or register/constant */ OpArgK /* argument is a constant or register/constant */
}; };
LUAI_DATA const lu_byte luaP_opmodes[NUM_OPCODES]; LUAI_DATA const lu_byte luaP_opmodes[NUM_OPCODES];
#define getOpMode(m) (cast(enum OpMode, luaP_opmodes[m] & 3)) #define getOpMode(m) (cast(enum OpMode, luaP_opmodes[m] & 3))
#define getBMode(m) (cast(enum OpArgMask, (luaP_opmodes[m] >> 4) & 3)) #define getBMode(m) (cast(enum OpArgMask, (luaP_opmodes[m] >> 4) & 3))
#define getCMode(m) (cast(enum OpArgMask, (luaP_opmodes[m] >> 2) & 3)) #define getCMode(m) (cast(enum OpArgMask, (luaP_opmodes[m] >> 2) & 3))
#define testAMode(m) (luaP_opmodes[m] & (1 << 6)) #define testAMode(m) (luaP_opmodes[m] & (1 << 6))
#define testTMode(m) (luaP_opmodes[m] & (1 << 7)) #define testTMode(m) (luaP_opmodes[m] & (1 << 7))
LUAI_DATA const char *const luaP_opnames[NUM_OPCODES+1]; /* opcode names * / LUAI_DATA const char *const luaP_opnames[NUM_OPCODES+1]; /* opcode names * /
/* number of list items to accumulate before a SETLIST instruction */ /* number of list items to accumulate before a SETLIST instruction */
#define LFIELDS_PER_FLUSH 50 #define LFIELDS_PER_FLUSH 50
#endif #endif
 End of changes. 30 change blocks. 
108 lines changed or deleted 107 lines changed or added


 lparser.h   lparser.h 
skipping to change at line 19 skipping to change at line 19
#include "llimits.h" #include "llimits.h"
#include "lobject.h" #include "lobject.h"
#include "lzio.h" #include "lzio.h"
/* /*
** Expression descriptor ** Expression descriptor
*/ */
typedef enum { typedef enum {
VVOID, /* no value */ VVOID, /* no value */
VNIL, VNIL,
VTRUE, VTRUE,
VFALSE, VFALSE,
VK, /* info = index of constant in `k' */ VK, /* info = index of constant in `k' */
VKNUM, /* nval = numerical value */ VKNUM, /* nval = numerical value */
VLOCAL, /* info = local register */ VLOCAL, /* info = local register */
VUPVAL, /* info = index of upvalue in `upvalues' */ VUPVAL, /* info = index of upvalue in `upvalues' */
VGLOBAL, /* info = index of table; aux = index of global name in `k' VGLOBAL, /* info = index of table; aux = index of global name in `k' *
*/ /
VINDEXED, /* info = table register; aux = index register (or `k') */ VINDEXED, /* info = table register; aux = index register (or `k') */
VJMP, /* info = instruction pc */ VJMP, /* info = instruction pc */
VRELOCABLE, /* info = instruction pc */ VRELOCABLE, /* info = instruction pc */
VNONRELOC, /* info = result register */ VNONRELOC, /* info = result register */
VCALL, /* info = instruction pc */ VCALL, /* info = instruction pc */
VVARARG /* info = instruction pc */ VVARARG /* info = instruction pc */
} expkind; } expkind;
typedef struct expdesc { typedef struct expdesc {
expkind k; expkind k;
union { union {
struct { int info, aux; } s; struct { int info, aux; } s;
lua_Number nval; lua_Number nval;
} u; } u;
int t; /* patch list of `exit when true' */ int t; /* patch list of `exit when true' */
int f; /* patch list of `exit when false' */ int f; /* patch list of `exit when false' */
 End of changes. 3 change blocks. 
12 lines changed or deleted 12 lines changed or added


 lstate.h   lstate.h 
skipping to change at line 19 skipping to change at line 19
#include "lua.h" #include "lua.h"
#include "lobject.h" #include "lobject.h"
#include "ltm.h" #include "ltm.h"
#include "lzio.h" #include "lzio.h"
struct lua_longjmp; /* defined in ldo.c */ struct lua_longjmp; /* defined in ldo.c */
/* table of globals */ /* table of globals */
#define gt(L) (&L->l_gt) #define gt(L) (&L->l_gt)
/* registry */ /* registry */
#define registry(L) (&G(L)->l_registry) #define registry(L) (&G(L)->l_registry)
/* extra stack space to handle TM calls and some other extras */ /* extra stack space to handle TM calls and some other extras */
#define EXTRA_STACK 5 #define EXTRA_STACK 5
#define BASIC_CI_SIZE 8 #define BASIC_CI_SIZE 8
#define BASIC_STACK_SIZE (2*LUA_MINSTACK) #define BASIC_STACK_SIZE (2*LUA_MINSTACK)
typedef struct stringtable { typedef struct stringtable {
GCObject **hash; GCObject **hash;
lu_int32 nuse; /* number of elements */ lu_int32 nuse; /* number of elements */
int size; int size;
} stringtable; } stringtable;
/* /*
** informations about a call ** informations about a call
*/ */
typedef struct CallInfo { typedef struct CallInfo {
StkId base; /* base for this function */ StkId base; /* base for this function */
StkId func; /* function index in the stack */ StkId func; /* function index in the stack */
StkId top; /* top for this function */ StkId top; /* top for this function */
const Instruction *savedpc; const Instruction *savedpc;
int nresults; /* expected number of results from this function */ int nresults; /* expected number of results from this function */
int tailcalls; /* number of tail calls lost under this entry */ int tailcalls; /* number of tail calls lost under this entry */
} CallInfo; } CallInfo;
#define curr_func(L) (clvalue(L->ci->func)) #define curr_func(L) (clvalue(L->ci->func))
#define ci_func(ci) (clvalue((ci)->func)) #define ci_func(ci) (clvalue((ci)->func))
#define f_isLua(ci) (!ci_func(ci)->c.isC) #define f_isLua(ci) (!ci_func(ci)->c.isC)
#define isLua(ci) (ttisfunction((ci)->func) && f_isLua(ci)) #define isLua(ci) (ttisfunction((ci)->func) && f_isLua(ci))
/* /*
** `global state', shared by all threads of this state ** `global state', shared by all threads of this state
*/ */
typedef struct global_State { typedef struct global_State {
stringtable strt; /* hash table for strings */ stringtable strt; /* hash table for strings */
lua_Alloc frealloc; /* function to reallocate memory */ lua_Alloc frealloc; /* function to reallocate memory */
void *ud; /* auxiliary data to `frealloc' */ void *ud; /* auxiliary data to `frealloc' */
lu_byte currentwhite; lu_byte currentwhite;
lu_byte gcstate; /* state of garbage collector */ lu_byte gcstate; /* state of garbage collector */
skipping to change at line 117 skipping to change at line 117
int hookcount; int hookcount;
lua_Hook hook; lua_Hook hook;
TValue l_gt; /* table of globals */ TValue l_gt; /* table of globals */
TValue env; /* temporary place for environments */ TValue env; /* temporary place for environments */
GCObject *openupval; /* list of open upvalues in this stack */ GCObject *openupval; /* list of open upvalues in this stack */
GCObject *gclist; GCObject *gclist;
struct lua_longjmp *errorJmp; /* current error recover point */ struct lua_longjmp *errorJmp; /* current error recover point */
ptrdiff_t errfunc; /* current error handling function (stack index) */ ptrdiff_t errfunc; /* current error handling function (stack index) */
}; };
#define G(L) (L->l_G) #define G(L) (L->l_G)
/* /*
** Union of all collectable objects ** Union of all collectable objects
*/ */
union GCObject { union GCObject {
GCheader gch; GCheader gch;
union TString ts; union TString ts;
union Udata u; union Udata u;
union Closure cl; union Closure cl;
struct Table h; struct Table h;
struct Proto p; struct Proto p;
struct UpVal uv; struct UpVal uv;
struct lua_State th; /* thread */ struct lua_State th; /* thread */
}; };
/* macros to convert a GCObject into a specific value */ /* macros to convert a GCObject into a specific value */
#define rawgco2ts(o) check_exp((o)->gch.tt == LUA_TSTRING, &((o)->ts)) #define rawgco2ts(o) check_exp((o)->gch.tt == LUA_TSTRING, &((o)->ts))
#define gco2ts(o) (&rawgco2ts(o)->tsv) #define gco2ts(o) (&rawgco2ts(o)->tsv)
#define rawgco2u(o) check_exp((o)->gch.tt == LUA_TUSERDATA, &((o)->u)) #define rawgco2u(o) check_exp((o)->gch.tt == LUA_TUSERDATA, &((o)->u))
#define gco2u(o) (&rawgco2u(o)->uv) #define gco2u(o) (&rawgco2u(o)->uv)
#define gco2cl(o) check_exp((o)->gch.tt == LUA_TFUNCTION, &((o)->cl)) #define gco2cl(o) check_exp((o)->gch.tt == LUA_TFUNCTION, &((o)->cl))
#define gco2h(o) check_exp((o)->gch.tt == LUA_TTABLE, &((o)->h)) #define gco2h(o) check_exp((o)->gch.tt == LUA_TTABLE, &((o)->h))
#define gco2p(o) check_exp((o)->gch.tt == LUA_TPROTO, &((o)->p)) #define gco2p(o) check_exp((o)->gch.tt == LUA_TPROTO, &((o)->p))
#define gco2uv(o) check_exp((o)->gch.tt == LUA_TUPVAL, &((o)->uv)) #define gco2uv(o) check_exp((o)->gch.tt == LUA_TUPVAL, &((o)->uv))
#define ngcotouv(o) \ #define ngcotouv(o) \
check_exp((o) == NULL || (o)->gch.tt == LUA_TUPVAL, &((o)->uv)) check_exp((o) == NULL || (o)->gch.tt == LUA_TUPVAL, &((o)->uv))
#define gco2th(o) check_exp((o)->gch.tt == LUA_TTHREAD, &((o)->th)) #define gco2th(o) check_exp((o)->gch.tt == LUA_TTHREAD, &((o)->th))
/* macro to convert any Lua object into a GCObject */ /* macro to convert any Lua object into a GCObject */
#define obj2gco(v) (cast(GCObject *, (v))) #define obj2gco(v) (cast(GCObject *, (v)))
LUAI_FUNC lua_State *luaE_newthread (lua_State *L); LUAI_FUNC lua_State *luaE_newthread (lua_State *L);
LUAI_FUNC void luaE_freethread (lua_State *L, lua_State *L1); LUAI_FUNC void luaE_freethread (lua_State *L, lua_State *L1);
#endif #endif
 End of changes. 8 change blocks. 
19 lines changed or deleted 19 lines changed or added


 lstring.h   lstring.h 
skipping to change at line 14 skipping to change at line 14
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
#ifndef lstring_h #ifndef lstring_h
#define lstring_h #define lstring_h
#include "lgc.h" #include "lgc.h"
#include "lobject.h" #include "lobject.h"
#include "lstate.h" #include "lstate.h"
#define sizestring(s) (sizeof(union TString)+((s)->len+1)*sizeof(char)) #define sizestring(s) (sizeof(union TString)+((s)->len+1)*sizeof(char))
#define sizeudata(u) (sizeof(union Udata)+(u)->len) #define sizeudata(u) (sizeof(union Udata)+(u)->len)
#define luaS_new(L, s) (luaS_newlstr(L, s, strlen(s))) #define luaS_new(L, s) (luaS_newlstr(L, s, strlen(s)))
#define luaS_newliteral(L, s) (luaS_newlstr(L, "" s, \ #define luaS_newliteral(L, s) (luaS_newlstr(L, "" s, \
(sizeof(s)/sizeof(char))-1)) (sizeof(s)/sizeof(char))-1))
#define luaS_fix(s) l_setbit((s)->tsv.marked, FIXEDBIT) #define luaS_fix(s) l_setbit((s)->tsv.marked, FIXEDBIT)
LUAI_FUNC void luaS_resize (lua_State *L, int newsize); LUAI_FUNC void luaS_resize (lua_State *L, int newsize);
LUAI_FUNC Udata *luaS_newudata (lua_State *L, size_t s, Table *e); LUAI_FUNC Udata *luaS_newudata (lua_State *L, size_t s, Table *e);
LUAI_FUNC TString *luaS_newlstr (lua_State *L, const char *str, size_t l); LUAI_FUNC TString *luaS_newlstr (lua_State *L, const char *str, size_t l);
#endif #endif
 End of changes. 4 change blocks. 
5 lines changed or deleted 5 lines changed or added


 ltable.h   ltable.h 
skipping to change at line 12 skipping to change at line 12
** $Id: ltable.h,v 2.10.1.1 2007/12/27 13:02:25 roberto Exp $ ** $Id: ltable.h,v 2.10.1.1 2007/12/27 13:02:25 roberto Exp $
** Lua tables (hash) ** Lua tables (hash)
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
#ifndef ltable_h #ifndef ltable_h
#define ltable_h #define ltable_h
#include "lobject.h" #include "lobject.h"
#define gnode(t,i) (&(t)->node[i]) #define gnode(t,i) (&(t)->node[i])
#define gkey(n) (&(n)->i_key.nk) #define gkey(n) (&(n)->i_key.nk)
#define gval(n) (&(n)->i_val) #define gval(n) (&(n)->i_val)
#define gnext(n) ((n)->i_key.nk.next) #define gnext(n) ((n)->i_key.nk.next)
#define key2tval(n) (&(n)->i_key.tvk) #define key2tval(n) (&(n)->i_key.tvk)
LUAI_FUNC const TValue *luaH_getnum (Table *t, int key); LUAI_FUNC const TValue *luaH_getnum (Table *t, int key);
LUAI_FUNC TValue *luaH_setnum (lua_State *L, Table *t, int key); LUAI_FUNC TValue *luaH_setnum (lua_State *L, Table *t, int key);
LUAI_FUNC const TValue *luaH_getstr (Table *t, TString *key); LUAI_FUNC const TValue *luaH_getstr (Table *t, TString *key);
LUAI_FUNC TValue *luaH_setstr (lua_State *L, Table *t, TString *key); LUAI_FUNC TValue *luaH_setstr (lua_State *L, Table *t, TString *key);
LUAI_FUNC const TValue *luaH_get (Table *t, const TValue *key); LUAI_FUNC const TValue *luaH_get (Table *t, const TValue *key);
LUAI_FUNC TValue *luaH_set (lua_State *L, Table *t, const TValue *key); LUAI_FUNC TValue *luaH_set (lua_State *L, Table *t, const TValue *key);
LUAI_FUNC Table *luaH_new (lua_State *L, int narray, int lnhash); LUAI_FUNC Table *luaH_new (lua_State *L, int narray, int lnhash);
LUAI_FUNC void luaH_resizearray (lua_State *L, Table *t, int nasize); LUAI_FUNC void luaH_resizearray (lua_State *L, Table *t, int nasize);
LUAI_FUNC void luaH_free (lua_State *L, Table *t); LUAI_FUNC void luaH_free (lua_State *L, Table *t);
 End of changes. 2 change blocks. 
5 lines changed or deleted 5 lines changed or added


 ltm.h   ltm.h 
skipping to change at line 34 skipping to change at line 34
TM_MUL, TM_MUL,
TM_DIV, TM_DIV,
TM_MOD, TM_MOD,
TM_POW, TM_POW,
TM_UNM, TM_UNM,
TM_LEN, TM_LEN,
TM_LT, TM_LT,
TM_LE, TM_LE,
TM_CONCAT, TM_CONCAT,
TM_CALL, TM_CALL,
TM_N /* number of elements in the enum */ TM_N /* number of elements in the enum */
} TMS; } TMS;
#define gfasttm(g,et,e) ((et) == NULL ? NULL : \ #define gfasttm(g,et,e) ((et) == NULL ? NULL : \
((et)->flags & (1u<<(e))) ? NULL : luaT_gettm(et, e, (g)->tmname[e])) ((et)->flags & (1u<<(e))) ? NULL : luaT_gettm(et, e, (g)->tmname[e]))
#define fasttm(l,et,e) gfasttm(G(l), et, e) #define fasttm(l,et,e) gfasttm(G(l), et, e)
LUAI_DATA const char *const luaT_typenames[]; LUAI_DATA const char *const luaT_typenames[];
LUAI_FUNC const TValue *luaT_gettm (Table *events, TMS event, TString *enam e); LUAI_FUNC const TValue *luaT_gettm (Table *events, TMS event, TString *enam e);
LUAI_FUNC const TValue *luaT_gettmbyobj (lua_State *L, const TValue *o, LUAI_FUNC const TValue *luaT_gettmbyobj (lua_State *L, const TValue *o,
TMS event); TMS event);
LUAI_FUNC void luaT_init (lua_State *L); LUAI_FUNC void luaT_init (lua_State *L);
#endif #endif
 End of changes. 2 change blocks. 
2 lines changed or deleted 2 lines changed or added


 lua.h   lua.h 
skipping to change at line 16 skipping to change at line 16
*/ */
#ifndef lua_h #ifndef lua_h
#define lua_h #define lua_h
#include <stdarg.h> #include <stdarg.h>
#include <stddef.h> #include <stddef.h>
#include "luaconf.h" #include "luaconf.h"
#define LUA_VERSION "Lua 5.1" #define LUA_VERSION "Lua 5.1"
#define LUA_RELEASE "Lua 5.1.4" #define LUA_RELEASE "Lua 5.1.4"
#define LUA_VERSION_NUM 501 #define LUA_VERSION_NUM 501
#define LUA_COPYRIGHT "Copyright (C) 1994-2008 Lua.org, PUC-Rio" #define LUA_COPYRIGHT "Copyright (C) 1994-2008 Lua.org, PUC-Rio"
#define LUA_AUTHORS "R. Ierusalimschy, L. H. de Figueiredo & W. Celes" #define LUA_AUTHORS "R. Ierusalimschy, L. H. de Figueiredo & W. Celes"
/* mark for precompiled code (`<esc>Lua') */ /* mark for precompiled code (`<esc>Lua') */
#define LUA_SIGNATURE "\033Lua" #define LUA_SIGNATURE "\033Lua"
/* option for multiple returns in `lua_pcall' and `lua_call' */ /* option for multiple returns in `lua_pcall' and `lua_call' */
#define LUA_MULTRET (-1) #define LUA_MULTRET (-1)
/* /*
** pseudo-indices ** pseudo-indices
*/ */
#define LUA_REGISTRYINDEX (-10000) #define LUA_REGISTRYINDEX (-10000)
#define LUA_ENVIRONINDEX (-10001) #define LUA_ENVIRONINDEX (-10001)
#define LUA_GLOBALSINDEX (-10002) #define LUA_GLOBALSINDEX (-10002)
#define lua_upvalueindex(i) (LUA_GLOBALSINDEX-(i)) #define lua_upvalueindex(i) (LUA_GLOBALSINDEX-(i))
/* thread status; 0 is OK */ /* thread status; 0 is OK */
#define LUA_YIELD 1 #define LUA_YIELD 1
#define LUA_ERRRUN 2 #define LUA_ERRRUN 2
#define LUA_ERRSYNTAX 3 #define LUA_ERRSYNTAX 3
#define LUA_ERRMEM 4 #define LUA_ERRMEM 4
#define LUA_ERRERR 5 #define LUA_ERRERR 5
typedef struct lua_State lua_State; typedef struct lua_State lua_State;
typedef int (*lua_CFunction) (lua_State *L); typedef int (*lua_CFunction) (lua_State *L);
/* /*
** functions that read/write blocks when loading/dumping Lua chunks ** functions that read/write blocks when loading/dumping Lua chunks
*/ */
typedef const char * (*lua_Reader) (lua_State *L, void *ud, size_t *sz); typedef const char * (*lua_Reader) (lua_State *L, void *ud, size_t *sz);
typedef int (*lua_Writer) (lua_State *L, const void* p, size_t sz, void* ud ); typedef int (*lua_Writer) (lua_State *L, const void* p, size_t sz, void* ud );
/* /*
** prototype for memory-allocation functions ** prototype for memory-allocation functions
*/ */
typedef void * (*lua_Alloc) (void *ud, void *ptr, size_t osize, size_t nsiz e); typedef void * (*lua_Alloc) (void *ud, void *ptr, size_t osize, size_t nsiz e);
/* /*
** basic types ** basic types
*/ */
#define LUA_TNONE (-1) #define LUA_TNONE (-1)
#define LUA_TNIL 0 #define LUA_TNIL 0
#define LUA_TBOOLEAN 1 #define LUA_TBOOLEAN 1
#define LUA_TLIGHTUSERDATA 2 #define LUA_TLIGHTUSERDATA 2
#define LUA_TNUMBER 3 #define LUA_TNUMBER 3
#define LUA_TSTRING 4 #define LUA_TSTRING 4
#define LUA_TTABLE 5 #define LUA_TTABLE 5
#define LUA_TFUNCTION 6 #define LUA_TFUNCTION 6
#define LUA_TUSERDATA 7 #define LUA_TUSERDATA 7
#define LUA_TTHREAD 8 #define LUA_TTHREAD 8
/* minimum Lua stack available to a C function */ /* minimum Lua stack available to a C function */
#define LUA_MINSTACK 20 #define LUA_MINSTACK 20
/* /*
** generic extra include file ** generic extra include file
*/ */
#if defined(LUA_USER_H) #if defined(LUA_USER_H)
#include LUA_USER_H #include LUA_USER_H
#endif #endif
/* type of numbers in Lua */ /* type of numbers in Lua */
typedef LUA_NUMBER lua_Number; typedef LUA_NUMBER lua_Number;
skipping to change at line 133 skipping to change at line 133
LUA_API int (lua_equal) (lua_State *L, int idx1, int idx2); LUA_API int (lua_equal) (lua_State *L, int idx1, int idx2);
LUA_API int (lua_rawequal) (lua_State *L, int idx1, int idx2); LUA_API int (lua_rawequal) (lua_State *L, int idx1, int idx2);
LUA_API int (lua_lessthan) (lua_State *L, int idx1, int idx2); LUA_API int (lua_lessthan) (lua_State *L, int idx1, int idx2);
LUA_API lua_Number (lua_tonumber) (lua_State *L, int idx); LUA_API lua_Number (lua_tonumber) (lua_State *L, int idx);
LUA_API lua_Integer (lua_tointeger) (lua_State *L, int idx); LUA_API lua_Integer (lua_tointeger) (lua_State *L, int idx);
LUA_API int (lua_toboolean) (lua_State *L, int idx); LUA_API int (lua_toboolean) (lua_State *L, int idx);
LUA_API const char *(lua_tolstring) (lua_State *L, int idx, size_t *len ); LUA_API const char *(lua_tolstring) (lua_State *L, int idx, size_t *len );
LUA_API size_t (lua_objlen) (lua_State *L, int idx); LUA_API size_t (lua_objlen) (lua_State *L, int idx);
LUA_API lua_CFunction (lua_tocfunction) (lua_State *L, int idx); LUA_API lua_CFunction (lua_tocfunction) (lua_State *L, int idx);
LUA_API void *(lua_touserdata) (lua_State *L, int idx); LUA_API void *(lua_touserdata) (lua_State *L, int idx);
LUA_API lua_State *(lua_tothread) (lua_State *L, int idx); LUA_API lua_State *(lua_tothread) (lua_State *L, int idx);
LUA_API const void *(lua_topointer) (lua_State *L, int idx); LUA_API const void *(lua_topointer) (lua_State *L, int idx);
/* /*
** push functions (C -> stack) ** push functions (C -> stack)
*/ */
LUA_API void (lua_pushnil) (lua_State *L); LUA_API void (lua_pushnil) (lua_State *L);
LUA_API void (lua_pushnumber) (lua_State *L, lua_Number n); LUA_API void (lua_pushnumber) (lua_State *L, lua_Number n);
LUA_API void (lua_pushinteger) (lua_State *L, lua_Integer n); LUA_API void (lua_pushinteger) (lua_State *L, lua_Integer n);
LUA_API void (lua_pushlstring) (lua_State *L, const char *s, size_t l); LUA_API void (lua_pushlstring) (lua_State *L, const char *s, size_t l);
skipping to change at line 197 skipping to change at line 197
** coroutine functions ** coroutine functions
*/ */
LUA_API int (lua_yield) (lua_State *L, int nresults); LUA_API int (lua_yield) (lua_State *L, int nresults);
LUA_API int (lua_resume) (lua_State *L, int narg); LUA_API int (lua_resume) (lua_State *L, int narg);
LUA_API int (lua_status) (lua_State *L); LUA_API int (lua_status) (lua_State *L);
/* /*
** garbage-collection function and options ** garbage-collection function and options
*/ */
#define LUA_GCSTOP 0 #define LUA_GCSTOP 0
#define LUA_GCRESTART 1 #define LUA_GCRESTART 1
#define LUA_GCCOLLECT 2 #define LUA_GCCOLLECT 2
#define LUA_GCCOUNT 3 #define LUA_GCCOUNT 3
#define LUA_GCCOUNTB 4 #define LUA_GCCOUNTB 4
#define LUA_GCSTEP 5 #define LUA_GCSTEP 5
#define LUA_GCSETPAUSE 6 #define LUA_GCSETPAUSE 6
#define LUA_GCSETSTEPMUL 7 #define LUA_GCSETSTEPMUL 7
LUA_API int (lua_gc) (lua_State *L, int what, int data); LUA_API int (lua_gc) (lua_State *L, int what, int data);
/* /*
** miscellaneous functions ** miscellaneous functions
*/ */
LUA_API int (lua_error) (lua_State *L); LUA_API int (lua_error) (lua_State *L);
LUA_API int (lua_next) (lua_State *L, int idx); LUA_API int (lua_next) (lua_State *L, int idx);
skipping to change at line 227 skipping to change at line 227
LUA_API lua_Alloc (lua_getallocf) (lua_State *L, void **ud); LUA_API lua_Alloc (lua_getallocf) (lua_State *L, void **ud);
LUA_API void lua_setallocf (lua_State *L, lua_Alloc f, void *ud); LUA_API void lua_setallocf (lua_State *L, lua_Alloc f, void *ud);
/* /*
** =============================================================== ** ===============================================================
** some useful macros ** some useful macros
** =============================================================== ** ===============================================================
*/ */
#define lua_pop(L,n) lua_settop(L, -(n)-1) #define lua_pop(L,n) lua_settop(L, -(n)-1)
#define lua_newtable(L) lua_createtable(L, 0, 0) #define lua_newtable(L) lua_createtable(L, 0, 0)
#define lua_register(L,n,f) (lua_pushcfunction(L, (f)), lua_setglobal(L, (n ))) #define lua_register(L,n,f) (lua_pushcfunction(L, (f)), lua_setglobal(L, (n )))
#define lua_pushcfunction(L,f) lua_pushcclosure(L, (f), 0) #define lua_pushcfunction(L,f) lua_pushcclosure(L, (f), 0)
#define lua_strlen(L,i) lua_objlen(L, (i)) #define lua_strlen(L,i) lua_objlen(L, (i))
#define lua_isfunction(L,n) (lua_type(L, (n)) == LUA_TFUNCTION) #define lua_isfunction(L,n) (lua_type(L, (n)) == LUA_TFUNCTION)
#define lua_istable(L,n) (lua_type(L, (n)) == LUA_TTABLE) #define lua_istable(L,n) (lua_type(L, (n)) == LUA_TTABLE)
#define lua_islightuserdata(L,n) (lua_type(L, (n)) == LUA_TLIGHTUSERD #define lua_islightuserdata(L,n) (lua_type(L, (n)) == LUA_TLIGHTUSERDATA
ATA) )
#define lua_isnil(L,n) (lua_type(L, (n)) == LUA_TNIL) #define lua_isnil(L,n) (lua_type(L, (n)) == LUA_TNIL)
#define lua_isboolean(L,n) (lua_type(L, (n)) == LUA_TBOOLEAN) #define lua_isboolean(L,n) (lua_type(L, (n)) == LUA_TBOOLEAN)
#define lua_isthread(L,n) (lua_type(L, (n)) == LUA_TTHREAD) #define lua_isthread(L,n) (lua_type(L, (n)) == LUA_TTHREAD)
#define lua_isnone(L,n) (lua_type(L, (n)) == LUA_TNONE) #define lua_isnone(L,n) (lua_type(L, (n)) == LUA_TNONE)
#define lua_isnoneornil(L, n) (lua_type(L, (n)) <= 0) #define lua_isnoneornil(L, n) (lua_type(L, (n)) <= 0)
#define lua_pushliteral(L, s) \ #define lua_pushliteral(L, s) \
lua_pushlstring(L, "" s, (sizeof(s)/sizeof(char))-1) lua_pushlstring(L, "" s, (sizeof(s)/sizeof(char))-1)
#define lua_setglobal(L,s) lua_setfield(L, LUA_GLOBALSINDEX, (s)) #define lua_setglobal(L,s) lua_setfield(L, LUA_GLOBALSINDEX, (s))
#define lua_getglobal(L,s) lua_getfield(L, LUA_GLOBALSINDEX, (s)) #define lua_getglobal(L,s) lua_getfield(L, LUA_GLOBALSINDEX, (s))
#define lua_tostring(L,i) lua_tolstring(L, (i), NULL) #define lua_tostring(L,i) lua_tolstring(L, (i), NULL)
/* /*
** compatibility macros and functions ** compatibility macros and functions
*/ */
#define lua_open() luaL_newstate() #define lua_open() luaL_newstate()
#define lua_getregistry(L) lua_pushvalue(L, LUA_REGISTRYINDEX) #define lua_getregistry(L) lua_pushvalue(L, LUA_REGISTRYINDEX)
#define lua_getgccount(L) lua_gc(L, LUA_GCCOUNT, 0) #define lua_getgccount(L) lua_gc(L, LUA_GCCOUNT, 0)
#define lua_Chunkreader lua_Reader #define lua_Chunkreader lua_Reader
#define lua_Chunkwriter lua_Writer #define lua_Chunkwriter lua_Writer
/* hack */ /* hack */
LUA_API void lua_setlevel (lua_State *from, lua_State *to); LUA_API void lua_setlevel (lua_State *from, lua_State *to);
/* /*
** {====================================================================== ** {======================================================================
** Debug API ** Debug API
** ======================================================================= ** =======================================================================
*/ */
/* /*
** Event codes ** Event codes
*/ */
#define LUA_HOOKCALL 0 #define LUA_HOOKCALL 0
#define LUA_HOOKRET 1 #define LUA_HOOKRET 1
#define LUA_HOOKLINE 2 #define LUA_HOOKLINE 2
#define LUA_HOOKCOUNT 3 #define LUA_HOOKCOUNT 3
#define LUA_HOOKTAILRET 4 #define LUA_HOOKTAILRET 4
/* /*
** Event masks ** Event masks
*/ */
#define LUA_MASKCALL (1 << LUA_HOOKCALL) #define LUA_MASKCALL (1 << LUA_HOOKCALL)
#define LUA_MASKRET (1 << LUA_HOOKRET) #define LUA_MASKRET (1 << LUA_HOOKRET)
#define LUA_MASKLINE (1 << LUA_HOOKLINE) #define LUA_MASKLINE (1 << LUA_HOOKLINE)
#define LUA_MASKCOUNT (1 << LUA_HOOKCOUNT) #define LUA_MASKCOUNT (1 << LUA_HOOKCOUNT)
typedef struct lua_Debug lua_Debug; /* activation record */ typedef struct lua_Debug lua_Debug; /* activation record */
/* Functions to be called by the debuger in specific events */ /* Functions to be called by the debuger in specific events */
typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar); typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);
LUA_API int lua_getstack (lua_State *L, int level, lua_Debug *ar); LUA_API int lua_getstack (lua_State *L, int level, lua_Debug *ar);
LUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar); LUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);
LUA_API const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n) ; LUA_API const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n) ;
LUA_API const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n) ; LUA_API const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n) ;
LUA_API const char *lua_getupvalue (lua_State *L, int funcindex, int n); LUA_API const char *lua_getupvalue (lua_State *L, int funcindex, int n);
LUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n); LUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n);
LUA_API int lua_sethook (lua_State *L, lua_Hook func, int mask, int count); LUA_API int lua_sethook (lua_State *L, lua_Hook func, int mask, int count);
LUA_API lua_Hook lua_gethook (lua_State *L); LUA_API lua_Hook lua_gethook (lua_State *L);
LUA_API int lua_gethookmask (lua_State *L); LUA_API int lua_gethookmask (lua_State *L);
LUA_API int lua_gethookcount (lua_State *L); LUA_API int lua_gethookcount (lua_State *L);
struct lua_Debug { struct lua_Debug {
int event; int event;
const char *name; /* (n) */ const char *name; /* (n) */
const char *namewhat; /* (n) `global', `local', `field', `method' const char *namewhat; /* (n) `global', `local', `field', `method' */
*/ const char *what; /* (S) `Lua', `C', `main', `tail' */
const char *what; /* (S) `Lua', `C', `main', `tail' */ const char *source; /* (S) */
const char *source; /* (S) */ int currentline; /* (l) */
int currentline; /* (l) */ int nups; /* (u) number of upvalues */
int nups; /* (u) number of upvalues */ int linedefined; /* (S) */
int linedefined; /* (S) */ int lastlinedefined; /* (S) */
int lastlinedefined; /* (S) */
char short_src[LUA_IDSIZE]; /* (S) */ char short_src[LUA_IDSIZE]; /* (S) */
/* private part */ /* private part */
int i_ci; /* active function */ int i_ci; /* active function */
}; };
/* }====================================================================== */ /* }====================================================================== */
/************************************************************************** **** /************************************************************************** ****
* Copyright (C) 1994-2008 Lua.org, PUC-Rio. All rights reserved. * Copyright (C) 1994-2008 Lua.org, PUC-Rio. All rights reserved.
* *
 End of changes. 26 change blocks. 
77 lines changed or deleted 76 lines changed or added


 luaconf.h   luaconf.h 
skipping to change at line 34 skipping to change at line 34
#if defined(__STRICT_ANSI__) #if defined(__STRICT_ANSI__)
#define LUA_ANSI #define LUA_ANSI
#endif #endif
#if !defined(LUA_ANSI) && defined(_WIN32) #if !defined(LUA_ANSI) && defined(_WIN32)
#define LUA_WIN #define LUA_WIN
#endif #endif
#if defined(LUA_USE_LINUX) #if defined(LUA_USE_LINUX)
#define LUA_USE_POSIX #define LUA_USE_POSIX
#define LUA_USE_DLOPEN /* needs an extra library: -ldl */ #define LUA_USE_DLOPEN /* needs an extra library: -ldl */
#define LUA_USE_READLINE /* needs some extra libraries */ #define LUA_USE_READLINE /* needs some extra libraries */
#endif #endif
#if defined(LUA_USE_MACOSX) #if defined(LUA_USE_MACOSX)
#define LUA_USE_POSIX #define LUA_USE_POSIX
#define LUA_DL_DYLD /* does not need extra library */ #define LUA_DL_DYLD /* does not need extra library */
#endif #endif
/* /*
@@ LUA_USE_POSIX includes all functionallity listed as X/Open System @@ LUA_USE_POSIX includes all functionallity listed as X/Open System
@* Interfaces Extension (XSI). @* Interfaces Extension (XSI).
** CHANGE it (define it) if your system is XSI compatible. ** CHANGE it (define it) if your system is XSI compatible.
*/ */
#if defined(LUA_USE_POSIX) #if defined(LUA_USE_POSIX)
#define LUA_USE_MKSTEMP #define LUA_USE_MKSTEMP
#define LUA_USE_ISATTY #define LUA_USE_ISATTY
skipping to change at line 64 skipping to change at line 64
/* /*
@@ LUA_PATH and LUA_CPATH are the names of the environment variables that @@ LUA_PATH and LUA_CPATH are the names of the environment variables that
@* Lua check to set its paths. @* Lua check to set its paths.
@@ LUA_INIT is the name of the environment variable that Lua @@ LUA_INIT is the name of the environment variable that Lua
@* checks for initialization code. @* checks for initialization code.
** CHANGE them if you want different names. ** CHANGE them if you want different names.
*/ */
#define LUA_PATH "LUA_PATH" #define LUA_PATH "LUA_PATH"
#define LUA_CPATH "LUA_CPATH" #define LUA_CPATH "LUA_CPATH"
#define LUA_INIT "LUA_INIT" #define LUA_INIT "LUA_INIT"
/* /*
@@ LUA_PATH_DEFAULT is the default path that Lua uses to look for @@ LUA_PATH_DEFAULT is the default path that Lua uses to look for
@* Lua libraries. @* Lua libraries.
@@ LUA_CPATH_DEFAULT is the default path that Lua uses to look for @@ LUA_CPATH_DEFAULT is the default path that Lua uses to look for
@* C libraries. @* C libraries.
** CHANGE them if your machine has a non-conventional directory ** CHANGE them if your machine has a non-conventional directory
** hierarchy or if you want to install your libraries in ** hierarchy or if you want to install your libraries in
** non-conventional directories. ** non-conventional directories.
*/ */
#if defined(_WIN32) #if defined(_WIN32)
/* /*
** In Windows, any exclamation mark ('!') in the path is replaced by the ** In Windows, any exclamation mark ('!') in the path is replaced by the
** path of the directory of the executable file of the current process. ** path of the directory of the executable file of the current process.
*/ */
#define LUA_LDIR "!\\lua\\" #define LUA_LDIR "!\\lua\\"
#define LUA_CDIR "!\\" #define LUA_CDIR "!\\"
#define LUA_PATH_DEFAULT \ #define LUA_PATH_DEFAULT \
".\\?.lua;" LUA_LDIR"?.lua;" LUA_LDIR"?\\init.lua;" \ ".\\?.lua;" LUA_LDIR"?.lua;" LUA_LDIR"?\\init.lua;" \
LUA_CDIR"?.lua;" LUA_CDIR"?\\init.lua" LUA_CDIR"?.lua;" LUA_CDIR"?\\init.lua"
#define LUA_CPATH_DEFAULT \ #define LUA_CPATH_DEFAULT \
".\\?.dll;" LUA_CDIR"?.dll;" LUA_CDIR"loadall.dll" ".\\?.dll;" LUA_CDIR"?.dll;" LUA_CDIR"loadall.dll"
#else #else
#define LUA_ROOT "/usr/local/" #define LUA_ROOT "/usr/local/"
#define LUA_LDIR LUA_ROOT "share/lua/5.1/" #define LUA_LDIR LUA_ROOT "share/lua/5.1/"
#define LUA_CDIR LUA_ROOT "lib/lua/5.1/" #define LUA_CDIR LUA_ROOT "lib/lua/5.1/"
#define LUA_PATH_DEFAULT \ #define LUA_PATH_DEFAULT \
"./?.lua;" LUA_LDIR"?.lua;" LUA_LDIR"?/init.lua;" \ "./?.lua;" LUA_LDIR"?.lua;" LUA_LDIR"?/init.lua;" \
LUA_CDIR"?.lua;" LUA_CDIR"?/init.lua" LUA_CDIR"?.lua;" LUA_CDIR"?/init.lua"
#define LUA_CPATH_DEFAULT \ #define LUA_CPATH_DEFAULT \
"./?.so;" LUA_CDIR"?.so;" LUA_CDIR"loadall.so" "./?.so;" LUA_CDIR"?.so;" LUA_CDIR"loadall.so"
#endif #endif
/* /*
@@ LUA_DIRSEP is the directory separator (for submodules). @@ LUA_DIRSEP is the directory separator (for submodules).
** CHANGE it if your machine does not use "/" as the directory separator ** CHANGE it if your machine does not use "/" as the directory separator
** and is not Windows. (On Windows Lua automatically uses "\".) ** and is not Windows. (On Windows Lua automatically uses "\".)
*/ */
#if defined(_WIN32) #if defined(_WIN32)
#define LUA_DIRSEP "\\" #define LUA_DIRSEP "\\"
#else #else
#define LUA_DIRSEP "/" #define LUA_DIRSEP "/"
#endif #endif
/* /*
@@ LUA_PATHSEP is the character that separates templates in a path. @@ LUA_PATHSEP is the character that separates templates in a path.
@@ LUA_PATH_MARK is the string that marks the substitution points in a @@ LUA_PATH_MARK is the string that marks the substitution points in a
@* template. @* template.
@@ LUA_EXECDIR in a Windows path is replaced by the executable's @@ LUA_EXECDIR in a Windows path is replaced by the executable's
@* directory. @* directory.
@@ LUA_IGMARK is a mark to ignore all before it when bulding the @@ LUA_IGMARK is a mark to ignore all before it when bulding the
@* luaopen_ function name. @* luaopen_ function name.
** CHANGE them if for some reason your system cannot use those ** CHANGE them if for some reason your system cannot use those
** characters. (E.g., if one of those characters is a common character ** characters. (E.g., if one of those characters is a common character
** in file/directory names.) Probably you do not need to change them. ** in file/directory names.) Probably you do not need to change them.
*/ */
#define LUA_PATHSEP ";" #define LUA_PATHSEP ";"
#define LUA_PATH_MARK "?" #define LUA_PATH_MARK "?"
#define LUA_EXECDIR "!" #define LUA_EXECDIR "!"
#define LUA_IGMARK "-" #define LUA_IGMARK "-"
/* /*
@@ LUA_INTEGER is the integral type used by lua_pushinteger/lua_tointeger. @@ LUA_INTEGER is the integral type used by lua_pushinteger/lua_tointeger.
** CHANGE that if ptrdiff_t is not adequate on your machine. (On most ** CHANGE that if ptrdiff_t is not adequate on your machine. (On most
** machines, ptrdiff_t gives a good choice between int or long.) ** machines, ptrdiff_t gives a good choice between int or long.)
*/ */
#define LUA_INTEGER ptrdiff_t #define LUA_INTEGER ptrdiff_t
/* /*
@@ LUA_API is a mark for all core API functions. @@ LUA_API is a mark for all core API functions.
@@ LUALIB_API is a mark for all standard library functions. @@ LUALIB_API is a mark for all standard library functions.
** CHANGE them if you need to define those functions in some special way. ** CHANGE them if you need to define those functions in some special way.
** For instance, if you want to create one Windows DLL with the core and ** For instance, if you want to create one Windows DLL with the core and
** the libraries, you may want to use the following definition (define ** the libraries, you may want to use the following definition (define
** LUA_BUILD_AS_DLL to get it). ** LUA_BUILD_AS_DLL to get it).
*/ */
#if defined(LUA_BUILD_AS_DLL) #if defined(LUA_BUILD_AS_DLL)
#if defined(LUA_CORE) || defined(LUA_LIB) #if defined(LUA_CORE) || defined(LUA_LIB)
#define LUA_API __declspec(dllexport) #define LUA_API __declspec(dllexport)
#else #else
#define LUA_API __declspec(dllimport) #define LUA_API __declspec(dllimport)
#endif #endif
#else #else
#define LUA_API extern #define LUA_API extern
#endif #endif
/* more often than not the libs go together with the core */ /* more often than not the libs go together with the core */
#define LUALIB_API LUA_API #define LUALIB_API LUA_API
/* /*
@@ LUAI_FUNC is a mark for all extern functions that are not to be @@ LUAI_FUNC is a mark for all extern functions that are not to be
@* exported to outside modules. @* exported to outside modules.
@@ LUAI_DATA is a mark for all extern (const) variables that are not to @@ LUAI_DATA is a mark for all extern (const) variables that are not to
@* be exported to outside modules. @* be exported to outside modules.
** CHANGE them if you need to mark them in some special way. Elf/gcc ** CHANGE them if you need to mark them in some special way. Elf/gcc
** (versions 3.2 and later) mark them as "hidden" to optimize access ** (versions 3.2 and later) mark them as "hidden" to optimize access
** when Lua is compiled as a shared library. ** when Lua is compiled as a shared library.
*/ */
#if defined(luaall_c) #if defined(luaall_c)
#define LUAI_FUNC static #define LUAI_FUNC static
#define LUAI_DATA /* empty */ #define LUAI_DATA /* empty */
#elif defined(__GNUC__) && ((__GNUC__*100 + __GNUC_MINOR__) >= 302) && \ #elif defined(__GNUC__) && ((__GNUC__*100 + __GNUC_MINOR__) >= 302) && \
defined(__ELF__) defined(__ELF__)
#define LUAI_FUNC __attribute__((visibility("hidden"))) extern #define LUAI_FUNC __attribute__((visibility("hidden"))) extern
#define LUAI_DATA LUAI_FUNC #define LUAI_DATA LUAI_FUNC
#else #else
#define LUAI_FUNC extern #define LUAI_FUNC extern
#define LUAI_DATA extern #define LUAI_DATA extern
#endif #endif
/* /*
@@ LUA_QL describes how error messages quote program elements. @@ LUA_QL describes how error messages quote program elements.
** CHANGE it if you want a different appearance. ** CHANGE it if you want a different appearance.
*/ */
#define LUA_QL(x) "'" x "'" #define LUA_QL(x) "'" x "'"
#define LUA_QS LUA_QL("%s") #define LUA_QS LUA_QL("%s")
/* /*
@@ LUA_IDSIZE gives the maximum size for the description of the source @@ LUA_IDSIZE gives the maximum size for the description of the source
@* of a function in debug information. @* of a function in debug information.
** CHANGE it if you want a different size. ** CHANGE it if you want a different size.
*/ */
#define LUA_IDSIZE 60 #define LUA_IDSIZE 60
/* /*
** {================================================================== ** {==================================================================
** Stand-alone configuration ** Stand-alone configuration
** =================================================================== ** ===================================================================
*/ */
#if defined(lua_c) || defined(luaall_c) #if defined(lua_c) || defined(luaall_c)
/* /*
@@ lua_stdin_is_tty detects whether the standard input is a 'tty' (that @@ lua_stdin_is_tty detects whether the standard input is a 'tty' (that
@* is, whether we're running lua interactively). @* is, whether we're running lua interactively).
** CHANGE it if you have a better definition for non-POSIX/non-Windows ** CHANGE it if you have a better definition for non-POSIX/non-Windows
** systems. ** systems.
*/ */
#if defined(LUA_USE_ISATTY) #if defined(LUA_USE_ISATTY)
#include <unistd.h> #include <unistd.h>
#define lua_stdin_is_tty() isatty(0) #define lua_stdin_is_tty() isatty(0)
#elif defined(LUA_WIN) #elif defined(LUA_WIN)
#include <io.h> #include <io.h>
#include <stdio.h> #include <stdio.h>
#define lua_stdin_is_tty() _isatty(_fileno(stdin)) #define lua_stdin_is_tty() _isatty(_fileno(stdin))
#else #else
#define lua_stdin_is_tty() 1 /* assume stdin is a tty */ #define lua_stdin_is_tty() 1 /* assume stdin is a tty */
#endif #endif
/* /*
@@ LUA_PROMPT is the default prompt used by stand-alone Lua. @@ LUA_PROMPT is the default prompt used by stand-alone Lua.
@@ LUA_PROMPT2 is the default continuation prompt used by stand-alone Lua. @@ LUA_PROMPT2 is the default continuation prompt used by stand-alone Lua.
** CHANGE them if you want different prompts. (You can also change the ** CHANGE them if you want different prompts. (You can also change the
** prompts dynamically, assigning to globals _PROMPT/_PROMPT2.) ** prompts dynamically, assigning to globals _PROMPT/_PROMPT2.)
*/ */
#define LUA_PROMPT "> " #define LUA_PROMPT "> "
#define LUA_PROMPT2 ">> " #define LUA_PROMPT2 ">> "
/* /*
@@ LUA_PROGNAME is the default name for the stand-alone Lua program. @@ LUA_PROGNAME is the default name for the stand-alone Lua program.
** CHANGE it if your stand-alone interpreter has a different name and ** CHANGE it if your stand-alone interpreter has a different name and
** your system is not able to detect that name automatically. ** your system is not able to detect that name automatically.
*/ */
#define LUA_PROGNAME "lua" #define LUA_PROGNAME "lua"
/* /*
@@ LUA_MAXINPUT is the maximum length for an input line in the @@ LUA_MAXINPUT is the maximum length for an input line in the
@* stand-alone interpreter. @* stand-alone interpreter.
** CHANGE it if you need longer lines. ** CHANGE it if you need longer lines.
*/ */
#define LUA_MAXINPUT 512 #define LUA_MAXINPUT 512
/* /*
@@ lua_readline defines how to show a prompt and then read a line from @@ lua_readline defines how to show a prompt and then read a line from
@* the standard input. @* the standard input.
@@ lua_saveline defines how to "save" a read line in a "history". @@ lua_saveline defines how to "save" a read line in a "history".
@@ lua_freeline defines how to free a line read by lua_readline. @@ lua_freeline defines how to free a line read by lua_readline.
** CHANGE them if you want to improve this functionality (e.g., by using ** CHANGE them if you want to improve this functionality (e.g., by using
** GNU readline and history facilities). ** GNU readline and history facilities).
*/ */
#if defined(LUA_USE_READLINE) #if defined(LUA_USE_READLINE)
#include <stdio.h> #include <stdio.h>
#include <readline/readline.h> #include <readline/readline.h>
#include <readline/history.h> #include <readline/history.h>
#define lua_readline(L,b,p) ((void)L, ((b)=readline(p)) != NULL) #define lua_readline(L,b,p) ((void)L, ((b)=readline(p)) != NULL)
#define lua_saveline(L,idx) \ #define lua_saveline(L,idx) \
if (lua_strlen(L,idx) > 0) /* non-empty line? */ \ if (lua_strlen(L,idx) > 0) /* non-empty line? */ \
add_history(lua_tostring(L, idx)); /* add it to history */ add_history(lua_tostring(L, idx)); /* add it to history */
#define lua_freeline(L,b) ((void)L, free(b)) #define lua_freeline(L,b) ((void)L, free(b))
#else #else
#define lua_readline(L,b,p) \ #define lua_readline(L,b,p) \
((void)L, fputs(p, stdout), fflush(stdout), /* show prompt */ \ ((void)L, fputs(p, stdout), fflush(stdout), /* show prompt */ \
fgets(b, LUA_MAXINPUT, stdin) != NULL) /* get line */ fgets(b, LUA_MAXINPUT, stdin) != NULL) /* get line */
#define lua_saveline(L,idx) { (void)L; (void)idx; } #define lua_saveline(L,idx) { (void)L; (void)idx; }
#define lua_freeline(L,b) { (void)L; (void)b; } #define lua_freeline(L,b) { (void)L; (void)b; }
#endif #endif
#endif #endif
/* }================================================================== */ /* }================================================================== */
/* /*
@@ LUAI_GCPAUSE defines the default pause between garbage-collector cycles @@ LUAI_GCPAUSE defines the default pause between garbage-collector cycles
@* as a percentage. @* as a percentage.
** CHANGE it if you want the GC to run faster or slower (higher values ** CHANGE it if you want the GC to run faster or slower (higher values
** mean larger pauses which mean slower collection.) You can also change ** mean larger pauses which mean slower collection.) You can also change
** this value dynamically. ** this value dynamically.
*/ */
#define LUAI_GCPAUSE 200 /* 200% (wait memory to double before next GC) */ #define LUAI_GCPAUSE 200 /* 200% (wait memory to double before next GC) */
/* /*
@@ LUAI_GCMUL defines the default speed of garbage collection relative to @@ LUAI_GCMUL defines the default speed of garbage collection relative to
@* memory allocation as a percentage. @* memory allocation as a percentage.
** CHANGE it if you want to change the granularity of the garbage ** CHANGE it if you want to change the granularity of the garbage
** collection. (Higher values mean coarser collections. 0 represents ** collection. (Higher values mean coarser collections. 0 represents
** infinity, where each step performs a full collection.) You can also ** infinity, where each step performs a full collection.) You can also
** change this value dynamically. ** change this value dynamically.
*/ */
#define LUAI_GCMUL 200 /* GC runs 'twice the speed' of memory allocatio n */ #define LUAI_GCMUL 200 /* GC runs 'twice the speed' of memory allocation */
/* /*
@@ LUA_COMPAT_GETN controls compatibility with old getn behavior. @@ LUA_COMPAT_GETN controls compatibility with old getn behavior.
** CHANGE it (define it) if you want exact compatibility with the ** CHANGE it (define it) if you want exact compatibility with the
** behavior of setn/getn in Lua 5.0. ** behavior of setn/getn in Lua 5.0.
*/ */
#undef LUA_COMPAT_GETN #undef LUA_COMPAT_GETN
/* /*
@@ LUA_COMPAT_LOADLIB controls compatibility about global loadlib. @@ LUA_COMPAT_LOADLIB controls compatibility about global loadlib.
skipping to change at line 326 skipping to change at line 326
** the new '%' operator instead of 'math.mod'. ** the new '%' operator instead of 'math.mod'.
*/ */
#define LUA_COMPAT_MOD #define LUA_COMPAT_MOD
/* /*
@@ LUA_COMPAT_LSTR controls compatibility with old long string nesting @@ LUA_COMPAT_LSTR controls compatibility with old long string nesting
@* facility. @* facility.
** CHANGE it to 2 if you want the old behaviour, or undefine it to turn ** CHANGE it to 2 if you want the old behaviour, or undefine it to turn
** off the advisory error when nesting [[...]]. ** off the advisory error when nesting [[...]].
*/ */
#define LUA_COMPAT_LSTR 1 #define LUA_COMPAT_LSTR 1
/* /*
@@ LUA_COMPAT_GFIND controls compatibility with old 'string.gfind' name. @@ LUA_COMPAT_GFIND controls compatibility with old 'string.gfind' name.
** CHANGE it to undefined as soon as you rename 'string.gfind' to ** CHANGE it to undefined as soon as you rename 'string.gfind' to
** 'string.gmatch'. ** 'string.gmatch'.
*/ */
#define LUA_COMPAT_GFIND #define LUA_COMPAT_GFIND
/* /*
@@ LUA_COMPAT_OPENLIB controls compatibility with old 'luaL_openlib' @@ LUA_COMPAT_OPENLIB controls compatibility with old 'luaL_openlib'
skipping to change at line 352 skipping to change at line 352
/* /*
@@ luai_apicheck is the assert macro used by the Lua-C API. @@ luai_apicheck is the assert macro used by the Lua-C API.
** CHANGE luai_apicheck if you want Lua to perform some checks in the ** CHANGE luai_apicheck if you want Lua to perform some checks in the
** parameters it gets from API calls. This may slow down the interpreter ** parameters it gets from API calls. This may slow down the interpreter
** a bit, but may be quite useful when debugging C code that interfaces ** a bit, but may be quite useful when debugging C code that interfaces
** with Lua. A useful redefinition is to use assert.h. ** with Lua. A useful redefinition is to use assert.h.
*/ */
#if defined(LUA_USE_APICHECK) #if defined(LUA_USE_APICHECK)
#include <assert.h> #include <assert.h>
#define luai_apicheck(L,o) { (void)L; assert(o); } #define luai_apicheck(L,o) { (void)L; assert(o); }
#else #else
#define luai_apicheck(L,o) { (void)L; } #define luai_apicheck(L,o) { (void)L; }
#endif #endif
/* /*
@@ LUAI_BITSINT defines the number of bits in an int. @@ LUAI_BITSINT defines the number of bits in an int.
** CHANGE here if Lua cannot automatically detect the number of bits of ** CHANGE here if Lua cannot automatically detect the number of bits of
** your machine. Probably you do not need to change this. ** your machine. Probably you do not need to change this.
*/ */
/* avoid overflows in comparison */ /* avoid overflows in comparison */
#if INT_MAX-20 < 32760 #if INT_MAX-20 < 32760
#define LUAI_BITSINT 16 #define LUAI_BITSINT 16
#elif INT_MAX > 2147483640L #elif INT_MAX > 2147483640L
/* int has at least 32 bits */ /* int has at least 32 bits */
#define LUAI_BITSINT 32 #define LUAI_BITSINT 32
#else #else
#error "you must define LUA_BITSINT with number of bits in an integer" #error "you must define LUA_BITSINT with number of bits in an integer"
#endif #endif
/* /*
@@ LUAI_UINT32 is an unsigned integer with at least 32 bits. @@ LUAI_UINT32 is an unsigned integer with at least 32 bits.
@@ LUAI_INT32 is an signed integer with at least 32 bits. @@ LUAI_INT32 is an signed integer with at least 32 bits.
@@ LUAI_UMEM is an unsigned integer big enough to count the total @@ LUAI_UMEM is an unsigned integer big enough to count the total
@* memory used by Lua. @* memory used by Lua.
@@ LUAI_MEM is a signed integer big enough to count the total memory @@ LUAI_MEM is a signed integer big enough to count the total memory
@* used by Lua. @* used by Lua.
** CHANGE here if for some weird reason the default definitions are not ** CHANGE here if for some weird reason the default definitions are not
** good enough for your machine. (The definitions in the 'else' ** good enough for your machine. (The definitions in the 'else'
** part always works, but may waste space on machines with 64-bit ** part always works, but may waste space on machines with 64-bit
** longs.) Probably you do not need to change this. ** longs.) Probably you do not need to change this.
*/ */
#if LUAI_BITSINT >= 32 #if LUAI_BITSINT >= 32
#define LUAI_UINT32 unsigned int #define LUAI_UINT32 unsigned int
#define LUAI_INT32 int #define LUAI_INT32 int
#define LUAI_MAXINT32 INT_MAX #define LUAI_MAXINT32 INT_MAX
#define LUAI_UMEM size_t #define LUAI_UMEM size_t
#define LUAI_MEM ptrdiff_t #define LUAI_MEM ptrdiff_t
#else #else
/* 16-bit ints */ /* 16-bit ints */
#define LUAI_UINT32 unsigned long #define LUAI_UINT32 unsigned long
#define LUAI_INT32 long #define LUAI_INT32 long
#define LUAI_MAXINT32 LONG_MAX #define LUAI_MAXINT32 LONG_MAX
#define LUAI_UMEM unsigned long #define LUAI_UMEM unsigned long
#define LUAI_MEM long #define LUAI_MEM long
#endif #endif
/* /*
@@ LUAI_MAXCALLS limits the number of nested calls. @@ LUAI_MAXCALLS limits the number of nested calls.
** CHANGE it if you need really deep recursive calls. This limit is ** CHANGE it if you need really deep recursive calls. This limit is
** arbitrary; its only purpose is to stop infinite recursion before ** arbitrary; its only purpose is to stop infinite recursion before
** exhausting memory. ** exhausting memory.
*/ */
#define LUAI_MAXCALLS 20000 #define LUAI_MAXCALLS 20000
/* /*
@@ LUAI_MAXCSTACK limits the number of Lua stack slots that a C function @@ LUAI_MAXCSTACK limits the number of Lua stack slots that a C function
@* can use. @* can use.
** CHANGE it if you need lots of (Lua) stack space for your C ** CHANGE it if you need lots of (Lua) stack space for your C
** functions. This limit is arbitrary; its only purpose is to stop C ** functions. This limit is arbitrary; its only purpose is to stop C
** functions to consume unlimited stack space. (must be smaller than ** functions to consume unlimited stack space. (must be smaller than
** -LUA_REGISTRYINDEX) ** -LUA_REGISTRYINDEX)
*/ */
#define LUAI_MAXCSTACK 8000 #define LUAI_MAXCSTACK 8000
/* /*
** {================================================================== ** {==================================================================
** CHANGE (to smaller values) the following definitions if your system ** CHANGE (to smaller values) the following definitions if your system
** has a small C stack. (Or you may want to change them to larger ** has a small C stack. (Or you may want to change them to larger
** values if your system has a large C stack and these limits are ** values if your system has a large C stack and these limits are
** too rigid for you.) Some of these constants control the size of ** too rigid for you.) Some of these constants control the size of
** stack-allocated arrays used by the compiler or the interpreter, while ** stack-allocated arrays used by the compiler or the interpreter, while
** others limit the maximum number of recursive calls that the compiler ** others limit the maximum number of recursive calls that the compiler
** or the interpreter can perform. Values too large may cause a C stack ** or the interpreter can perform. Values too large may cause a C stack
** overflow for some forms of deep constructs. ** overflow for some forms of deep constructs.
** =================================================================== ** ===================================================================
*/ */
/* /*
@@ LUAI_MAXCCALLS is the maximum depth for nested C calls (short) and @@ LUAI_MAXCCALLS is the maximum depth for nested C calls (short) and
@* syntactical nested non-terminals in a program. @* syntactical nested non-terminals in a program.
*/ */
#define LUAI_MAXCCALLS 200 #define LUAI_MAXCCALLS 200
/* /*
@@ LUAI_MAXVARS is the maximum number of local variables per function @@ LUAI_MAXVARS is the maximum number of local variables per function
@* (must be smaller than 250). @* (must be smaller than 250).
*/ */
#define LUAI_MAXVARS 200 #define LUAI_MAXVARS 200
/* /*
@@ LUAI_MAXUPVALUES is the maximum number of upvalues per function @@ LUAI_MAXUPVALUES is the maximum number of upvalues per function
@* (must be smaller than 250). @* (must be smaller than 250).
*/ */
#define LUAI_MAXUPVALUES 60 #define LUAI_MAXUPVALUES 60
/* /*
@@ LUAL_BUFFERSIZE is the buffer size used by the lauxlib buffer system. @@ LUAL_BUFFERSIZE is the buffer size used by the lauxlib buffer system.
*/ */
#define LUAL_BUFFERSIZE BUFSIZ #define LUAL_BUFFERSIZE BUFSIZ
/* }================================================================== */ /* }================================================================== */
/* /*
** {================================================================== ** {==================================================================
@@ LUA_NUMBER is the type of numbers in Lua. @@ LUA_NUMBER is the type of numbers in Lua.
** CHANGE the following definitions only if you want to build Lua ** CHANGE the following definitions only if you want to build Lua
** with a number type different from double. You may also need to ** with a number type different from double. You may also need to
** change lua_number2int & lua_number2integer. ** change lua_number2int & lua_number2integer.
** =================================================================== ** ===================================================================
*/ */
#define LUA_NUMBER_DOUBLE #define LUA_NUMBER_DOUBLE
#define LUA_NUMBER double #define LUA_NUMBER double
/* /*
@@ LUAI_UACNUMBER is the result of an 'usual argument conversion' @@ LUAI_UACNUMBER is the result of an 'usual argument conversion'
@* over a number. @* over a number.
*/ */
#define LUAI_UACNUMBER double #define LUAI_UACNUMBER double
/* /*
@@ LUA_NUMBER_SCAN is the format for reading numbers. @@ LUA_NUMBER_SCAN is the format for reading numbers.
@@ LUA_NUMBER_FMT is the format for writing numbers. @@ LUA_NUMBER_FMT is the format for writing numbers.
@@ lua_number2str converts a number to a string. @@ lua_number2str converts a number to a string.
@@ LUAI_MAXNUMBER2STR is maximum size of previous conversion. @@ LUAI_MAXNUMBER2STR is maximum size of previous conversion.
@@ lua_str2number converts a string to a number. @@ lua_str2number converts a string to a number.
*/ */
#define LUA_NUMBER_SCAN "%lf" #define LUA_NUMBER_SCAN "%lf"
#define LUA_NUMBER_FMT "%.14g" #define LUA_NUMBER_FMT "%.14g"
#define lua_number2str(s,n) sprintf((s), LUA_NUMBER_FMT, (n)) #define lua_number2str(s,n) sprintf((s), LUA_NUMBER_FMT, (n))
#define LUAI_MAXNUMBER2STR 32 /* 16 digits, sign, point, and \0 */ #define LUAI_MAXNUMBER2STR 32 /* 16 digits, sign, point, and \0 */
#define lua_str2number(s,p) strtod((s), (p)) #define lua_str2number(s,p) strtod((s), (p))
/* /*
@@ The luai_num* macros define the primitive operations over numbers. @@ The luai_num* macros define the primitive operations over numbers.
*/ */
#if defined(LUA_CORE) #if defined(LUA_CORE)
#include <math.h> #include <math.h>
#define luai_numadd(a,b) ((a)+(b)) #define luai_numadd(a,b) ((a)+(b))
#define luai_numsub(a,b) ((a)-(b)) #define luai_numsub(a,b) ((a)-(b))
#define luai_nummul(a,b) ((a)*(b)) #define luai_nummul(a,b) ((a)*(b))
#define luai_numdiv(a,b) ((a)/(b)) #define luai_numdiv(a,b) ((a)/(b))
#define luai_nummod(a,b) ((a) - floor((a)/(b))*(b)) #define luai_nummod(a,b) ((a) - floor((a)/(b))*(b))
#define luai_numpow(a,b) (pow(a,b)) #define luai_numpow(a,b) (pow(a,b))
#define luai_numunm(a) (-(a)) #define luai_numunm(a) (-(a))
#define luai_numeq(a,b) ((a)==(b)) #define luai_numeq(a,b) ((a)==(b))
#define luai_numlt(a,b) ((a)<(b)) #define luai_numlt(a,b) ((a)<(b))
#define luai_numle(a,b) ((a)<=(b)) #define luai_numle(a,b) ((a)<=(b))
#define luai_numisnan(a) (!luai_numeq((a), (a))) #define luai_numisnan(a) (!luai_numeq((a), (a)))
#endif #endif
/* /*
@@ lua_number2int is a macro to convert lua_Number to int. @@ lua_number2int is a macro to convert lua_Number to int.
@@ lua_number2integer is a macro to convert lua_Number to lua_Integer. @@ lua_number2integer is a macro to convert lua_Number to lua_Integer.
** CHANGE them if you know a faster way to convert a lua_Number to ** CHANGE them if you know a faster way to convert a lua_Number to
** int (with any rounding method and without throwing errors) in your ** int (with any rounding method and without throwing errors) in your
** system. In Pentium machines, a naive typecast from double to int ** system. In Pentium machines, a naive typecast from double to int
** in C is extremely slow, so any alternative is worth trying. ** in C is extremely slow, so any alternative is worth trying.
*/ */
/* On a Pentium, resort to a trick */ /* On a Pentium, resort to a trick */
#if defined(LUA_NUMBER_DOUBLE) && !defined(LUA_ANSI) && !defined(__SSE2__) && \ #if defined(LUA_NUMBER_DOUBLE) && !defined(LUA_ANSI) && !defined(__SSE2__) && \
(defined(__i386) || defined (_M_IX86) || defined(__i386__)) (defined(__i386) || defined (_M_IX86) || defined(__i386__))
/* On a Microsoft compiler, use assembler */ /* On a Microsoft compiler, use assembler */
#if defined(_MSC_VER) #if defined(_MSC_VER)
#define lua_number2int(i,d) __asm fld d __asm fistp i #define lua_number2int(i,d) __asm fld d __asm fistp i
#define lua_number2integer(i,n) lua_number2int(i, n) #define lua_number2integer(i,n) lua_number2int(i, n)
/* the next trick should work on any Pentium, but sometimes clashes /* the next trick should work on any Pentium, but sometimes clashes
with a DirectX idiosyncrasy */ with a DirectX idiosyncrasy */
#else #else
union luai_Cast { double l_d; long l_l; }; union luai_Cast { double l_d; long l_l; };
#define lua_number2int(i,d) \ #define lua_number2int(i,d) \
{ volatile union luai_Cast u; u.l_d = (d) + 6755399441055744.0; (i) = u.l _l; } { volatile union luai_Cast u; u.l_d = (d) + 6755399441055744.0; (i) = u.l _l; }
#define lua_number2integer(i,n) lua_number2int(i, n) #define lua_number2integer(i,n) lua_number2int(i, n)
#endif #endif
/* this option always works, but may be slow */ /* this option always works, but may be slow */
#else #else
#define lua_number2int(i,d) ((i)=(int)(d)) #define lua_number2int(i,d) ((i)=(int)(d))
#define lua_number2integer(i,d) ((i)=(lua_Integer)(d)) #define lua_number2integer(i,d) ((i)=(lua_Integer)(d))
#endif #endif
/* }================================================================== */ /* }================================================================== */
/* /*
@@ LUAI_USER_ALIGNMENT_T is a type that requires maximum alignment. @@ LUAI_USER_ALIGNMENT_T is a type that requires maximum alignment.
** CHANGE it if your system requires alignments larger than double. (For ** CHANGE it if your system requires alignments larger than double. (For
** instance, if your system supports long doubles and they must be ** instance, if your system supports long doubles and they must be
** aligned in 16-byte boundaries, then you should add long double in the ** aligned in 16-byte boundaries, then you should add long double in the
** union.) Probably you do not need to change this. ** union.) Probably you do not need to change this.
*/ */
#define LUAI_USER_ALIGNMENT_T union { double u; void *s; long l; } #define LUAI_USER_ALIGNMENT_T union { double u; void *s; long l; }
/* /*
@@ LUAI_THROW/LUAI_TRY define how Lua does exception handling. @@ LUAI_THROW/LUAI_TRY define how Lua does exception handling.
** CHANGE them if you prefer to use longjmp/setjmp even with C++ ** CHANGE them if you prefer to use longjmp/setjmp even with C++
** or if want/don't to use _longjmp/_setjmp instead of regular ** or if want/don't to use _longjmp/_setjmp instead of regular
** longjmp/setjmp. By default, Lua handles errors with exceptions when ** longjmp/setjmp. By default, Lua handles errors with exceptions when
** compiling as C++ code, with _longjmp/_setjmp when asked to use them, ** compiling as C++ code, with _longjmp/_setjmp when asked to use them,
** and with longjmp/setjmp otherwise. ** and with longjmp/setjmp otherwise.
*/ */
#if defined(__cplusplus) #if defined(__cplusplus)
/* C++ exceptions */ /* C++ exceptions */
#define LUAI_THROW(L,c) throw(c) #define LUAI_THROW(L,c) throw(c)
#define LUAI_TRY(L,c,a) try { a } catch(...) \ #define LUAI_TRY(L,c,a) try { a } catch(...) \
{ if ((c)->status == 0) (c)->status = -1; } { if ((c)->status == 0) (c)->status = -1; }
#define luai_jmpbuf int /* dummy variable */ #define luai_jmpbuf int /* dummy variable */
#elif defined(LUA_USE_ULONGJMP) #elif defined(LUA_USE_ULONGJMP)
/* in Unix, try _longjmp/_setjmp (more efficient) */ /* in Unix, try _longjmp/_setjmp (more efficient) */
#define LUAI_THROW(L,c) _longjmp((c)->b, 1) #define LUAI_THROW(L,c) _longjmp((c)->b, 1)
#define LUAI_TRY(L,c,a) if (_setjmp((c)->b) == 0) { a } #define LUAI_TRY(L,c,a) if (_setjmp((c)->b) == 0) { a }
#define luai_jmpbuf jmp_buf #define luai_jmpbuf jmp_buf
#else #else
/* default handling with long jumps */ /* default handling with long jumps */
#define LUAI_THROW(L,c) longjmp((c)->b, 1) #define LUAI_THROW(L,c) longjmp((c)->b, 1)
#define LUAI_TRY(L,c,a) if (setjmp((c)->b) == 0) { a } #define LUAI_TRY(L,c,a) if (setjmp((c)->b) == 0) { a }
#define luai_jmpbuf jmp_buf #define luai_jmpbuf jmp_buf
#endif #endif
/* /*
@@ LUA_MAXCAPTURES is the maximum number of captures that a pattern @@ LUA_MAXCAPTURES is the maximum number of captures that a pattern
@* can do during pattern-matching. @* can do during pattern-matching.
** CHANGE it if you need more captures. This limit is arbitrary. ** CHANGE it if you need more captures. This limit is arbitrary.
*/ */
#define LUA_MAXCAPTURES 32 #define LUA_MAXCAPTURES 32
/* /*
@@ lua_tmpnam is the function that the OS library uses to create a @@ lua_tmpnam is the function that the OS library uses to create a
@* temporary name. @* temporary name.
@@ LUA_TMPNAMBUFSIZE is the maximum size of a name created by lua_tmpnam. @@ LUA_TMPNAMBUFSIZE is the maximum size of a name created by lua_tmpnam.
** CHANGE them if you have an alternative to tmpnam (which is considered ** CHANGE them if you have an alternative to tmpnam (which is considered
** insecure) or if you want the original tmpnam anyway. By default, Lua ** insecure) or if you want the original tmpnam anyway. By default, Lua
** uses tmpnam except when POSIX is available, where it uses mkstemp. ** uses tmpnam except when POSIX is available, where it uses mkstemp.
*/ */
#if defined(loslib_c) || defined(luaall_c) #if defined(loslib_c) || defined(luaall_c)
#if defined(LUA_USE_MKSTEMP) #if defined(LUA_USE_MKSTEMP)
#include <unistd.h> #include <unistd.h>
#define LUA_TMPNAMBUFSIZE 32 #define LUA_TMPNAMBUFSIZE 32
#define lua_tmpnam(b,e) { \ #define lua_tmpnam(b,e) { \
strcpy(b, "/tmp/lua_XXXXXX"); \ strcpy(b, "/tmp/lua_XXXXXX"); \
e = mkstemp(b); \ e = mkstemp(b); \
if (e != -1) close(e); \ if (e != -1) close(e); \
e = (e == -1); } e = (e == -1); }
#else #else
#define LUA_TMPNAMBUFSIZE L_tmpnam #define LUA_TMPNAMBUFSIZE L_tmpnam
#define lua_tmpnam(b,e) { e = (tmpnam(b) == NULL); } #define lua_tmpnam(b,e) { e = (tmpnam(b) == NULL); }
#endif #endif
#endif #endif
/* /*
@@ lua_popen spawns a new process connected to the current one through @@ lua_popen spawns a new process connected to the current one through
@* the file streams. @* the file streams.
** CHANGE it if you have a way to implement it in your system. ** CHANGE it if you have a way to implement it in your system.
*/ */
#if defined(LUA_USE_POPEN) #if defined(LUA_USE_POPEN)
#define lua_popen(L,c,m) ((void)L, fflush(NULL), popen(c,m)) #define lua_popen(L,c,m) ((void)L, fflush(NULL), popen(c,m))
#define lua_pclose(L,file) ((void)L, (pclose(file) != -1)) #define lua_pclose(L,file) ((void)L, (pclose(file) != -1))
#elif defined(LUA_WIN) #elif defined(LUA_WIN)
#define lua_popen(L,c,m) ((void)L, _popen(c,m)) #define lua_popen(L,c,m) ((void)L, _popen(c,m))
#define lua_pclose(L,file) ((void)L, (_pclose(file) != -1)) #define lua_pclose(L,file) ((void)L, (_pclose(file) != -1))
#else #else
#define lua_popen(L,c,m) ((void)((void)c, m), \ #define lua_popen(L,c,m) ((void)((void)c, m), \
luaL_error(L, LUA_QL("popen") " not supported"), (FILE*)0) luaL_error(L, LUA_QL("popen") " not supported"), (FILE*)0)
#define lua_pclose(L,file) ((void)((void)L, file), 0) #define lua_pclose(L,file) ((void)((void)L, file), 0)
#endif #endif
/* /*
@@ LUA_DL_* define which dynamic-library system Lua should use. @@ LUA_DL_* define which dynamic-library system Lua should use.
** CHANGE here if Lua has problems choosing the appropriate ** CHANGE here if Lua has problems choosing the appropriate
** dynamic-library system for your platform (either Windows' DLL, Mac's ** dynamic-library system for your platform (either Windows' DLL, Mac's
** dyld, or Unix's dlopen). If your system is some kind of Unix, there ** dyld, or Unix's dlopen). If your system is some kind of Unix, there
** is a good chance that it has dlopen, so LUA_DL_DLOPEN will work for ** is a good chance that it has dlopen, so LUA_DL_DLOPEN will work for
** it. To use dlopen you also need to adapt the src/Makefile (probably ** it. To use dlopen you also need to adapt the src/Makefile (probably
skipping to change at line 665 skipping to change at line 665
#if defined(LUA_WIN) #if defined(LUA_WIN)
#define LUA_DL_DLL #define LUA_DL_DLL
#endif #endif
/* /*
@@ LUAI_EXTRASPACE allows you to add user-specific data in a lua_State @@ LUAI_EXTRASPACE allows you to add user-specific data in a lua_State
@* (the data goes just *before* the lua_State pointer). @* (the data goes just *before* the lua_State pointer).
** CHANGE (define) this if you really need that. This value must be ** CHANGE (define) this if you really need that. This value must be
** a multiple of the maximum alignment required for your machine. ** a multiple of the maximum alignment required for your machine.
*/ */
#define LUAI_EXTRASPACE 0 #define LUAI_EXTRASPACE 0
/* /*
@@ luai_userstate* allow user-specific actions on threads. @@ luai_userstate* allow user-specific actions on threads.
** CHANGE them if you defined LUAI_EXTRASPACE and need to do something ** CHANGE them if you defined LUAI_EXTRASPACE and need to do something
** extra when a thread is created/deleted/resumed/yielded. ** extra when a thread is created/deleted/resumed/yielded.
*/ */
#define luai_userstateopen(L) ((void)L) #define luai_userstateopen(L) ((void)L)
#define luai_userstateclose(L) ((void)L) #define luai_userstateclose(L) ((void)L)
#define luai_userstatethread(L,L1) ((void)L) #define luai_userstatethread(L,L1) ((void)L)
#define luai_userstatefree(L) ((void)L) #define luai_userstatefree(L) ((void)L)
#define luai_userstateresume(L,n) ((void)L) #define luai_userstateresume(L,n) ((void)L)
#define luai_userstateyield(L,n) ((void)L) #define luai_userstateyield(L,n) ((void)L)
/* /*
@@ LUA_INTFRMLEN is the length modifier for integer conversions @@ LUA_INTFRMLEN is the length modifier for integer conversions
@* in 'string.format'. @* in 'string.format'.
@@ LUA_INTFRM_T is the integer type correspoding to the previous length @@ LUA_INTFRM_T is the integer type correspoding to the previous length
@* modifier. @* modifier.
** CHANGE them if your system supports long long or does not support long. ** CHANGE them if your system supports long long or does not support long.
*/ */
#if defined(LUA_USELONGLONG) #if defined(LUA_USELONGLONG)
#define LUA_INTFRMLEN "ll" #define LUA_INTFRMLEN "ll"
#define LUA_INTFRM_T long long #define LUA_INTFRM_T long long
#else #else
#define LUA_INTFRMLEN "l" #define LUA_INTFRMLEN "l"
#define LUA_INTFRM_T long #define LUA_INTFRM_T long
#endif #endif
/* =================================================================== */ /* =================================================================== */
/* /*
** Local configuration. You can use this space to add your redefinitions ** Local configuration. You can use this space to add your redefinitions
** without modifying the main part of the file. ** without modifying the main part of the file.
*/ */
 End of changes. 64 change blocks. 
133 lines changed or deleted 133 lines changed or added


 lualib.h   lualib.h 
skipping to change at line 13 skipping to change at line 13
** Lua standard libraries ** Lua standard libraries
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
#ifndef lualib_h #ifndef lualib_h
#define lualib_h #define lualib_h
#include "lua.h" #include "lua.h"
/* Key to file-handle type */ /* Key to file-handle type */
#define LUA_FILEHANDLE "FILE*" #define LUA_FILEHANDLE "FILE*"
#define LUA_COLIBNAME "coroutine" #define LUA_COLIBNAME "coroutine"
LUALIB_API int (luaopen_base) (lua_State *L); LUALIB_API int (luaopen_base) (lua_State *L);
#define LUA_TABLIBNAME "table" #define LUA_TABLIBNAME "table"
LUALIB_API int (luaopen_table) (lua_State *L); LUALIB_API int (luaopen_table) (lua_State *L);
#define LUA_IOLIBNAME "io" #define LUA_IOLIBNAME "io"
LUALIB_API int (luaopen_io) (lua_State *L); LUALIB_API int (luaopen_io) (lua_State *L);
#define LUA_OSLIBNAME "os" #define LUA_OSLIBNAME "os"
LUALIB_API int (luaopen_os) (lua_State *L); LUALIB_API int (luaopen_os) (lua_State *L);
#define LUA_STRLIBNAME "string" #define LUA_STRLIBNAME "string"
LUALIB_API int (luaopen_string) (lua_State *L); LUALIB_API int (luaopen_string) (lua_State *L);
#define LUA_MATHLIBNAME "math" #define LUA_MATHLIBNAME "math"
LUALIB_API int (luaopen_math) (lua_State *L); LUALIB_API int (luaopen_math) (lua_State *L);
#define LUA_DBLIBNAME "debug" #define LUA_DBLIBNAME "debug"
LUALIB_API int (luaopen_debug) (lua_State *L); LUALIB_API int (luaopen_debug) (lua_State *L);
#define LUA_LOADLIBNAME "package" #define LUA_LOADLIBNAME "package"
LUALIB_API int (luaopen_package) (lua_State *L); LUALIB_API int (luaopen_package) (lua_State *L);
/* open all previous libraries */ /* open all previous libraries */
LUALIB_API void (luaL_openlibs) (lua_State *L); LUALIB_API void (luaL_openlibs) (lua_State *L);
#ifndef lua_assert #ifndef lua_assert
#define lua_assert(x) ((void)0) #define lua_assert(x) ((void)0)
#endif #endif
#endif #endif
 End of changes. 10 change blocks. 
10 lines changed or deleted 10 lines changed or added


 lundump.h   lundump.h 
skipping to change at line 28 skipping to change at line 28
/* dump one chunk; from ldump.c */ /* dump one chunk; from ldump.c */
LUAI_FUNC int luaU_dump (lua_State* L, const Proto* f, lua_Writer w, void* data, int strip); LUAI_FUNC int luaU_dump (lua_State* L, const Proto* f, lua_Writer w, void* data, int strip);
#ifdef luac_c #ifdef luac_c
/* print one chunk; from print.c */ /* print one chunk; from print.c */
LUAI_FUNC void luaU_print (const Proto* f, int full); LUAI_FUNC void luaU_print (const Proto* f, int full);
#endif #endif
/* for header of binary files -- this is Lua 5.1 */ /* for header of binary files -- this is Lua 5.1 */
#define LUAC_VERSION 0x51 #define LUAC_VERSION 0x51
/* for header of binary files -- this is the official format */ /* for header of binary files -- this is the official format */
#define LUAC_FORMAT 0 #define LUAC_FORMAT 0
/* size of header of binary files */ /* size of header of binary files */
#define LUAC_HEADERSIZE 12 #define LUAC_HEADERSIZE 12
#endif #endif
 End of changes. 3 change blocks. 
3 lines changed or deleted 3 lines changed or added


 lvm.h   lvm.h 
skipping to change at line 16 skipping to change at line 16
#ifndef lvm_h #ifndef lvm_h
#define lvm_h #define lvm_h
#include "ldo.h" #include "ldo.h"
#include "lobject.h" #include "lobject.h"
#include "ltm.h" #include "ltm.h"
#define tostring(L,o) ((ttype(o) == LUA_TSTRING) || (luaV_tostring(L, o))) #define tostring(L,o) ((ttype(o) == LUA_TSTRING) || (luaV_tostring(L, o)))
#define tonumber(o,n) (ttype(o) == LUA_TNUMBER || \ #define tonumber(o,n) (ttype(o) == LUA_TNUMBER || \
(((o) = luaV_tonumber(o,n)) != NULL)) (((o) = luaV_tonumber(o,n)) != NULL))
#define equalobj(L,o1,o2) \ #define equalobj(L,o1,o2) \
(ttype(o1) == ttype(o2) && luaV_equalval(L, o1, o2)) (ttype(o1) == ttype(o2) && luaV_equalval(L, o1, o2))
LUAI_FUNC int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r ); LUAI_FUNC int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r );
LUAI_FUNC int luaV_equalval (lua_State *L, const TValue *t1, const TValue * t2); LUAI_FUNC int luaV_equalval (lua_State *L, const TValue *t1, const TValue * t2);
LUAI_FUNC const TValue *luaV_tonumber (const TValue *obj, TValue *n); LUAI_FUNC const TValue *luaV_tonumber (const TValue *obj, TValue *n);
LUAI_FUNC int luaV_tostring (lua_State *L, StkId obj); LUAI_FUNC int luaV_tostring (lua_State *L, StkId obj);
LUAI_FUNC void luaV_gettable (lua_State *L, const TValue *t, TValue *key, LUAI_FUNC void luaV_gettable (lua_State *L, const TValue *t, TValue *key,
StkId val); StkId val);
LUAI_FUNC void luaV_settable (lua_State *L, const TValue *t, TValue *key, LUAI_FUNC void luaV_settable (lua_State *L, const TValue *t, TValue *key,
StkId val); StkId val);
LUAI_FUNC void luaV_execute (lua_State *L, int nexeccalls); LUAI_FUNC void luaV_execute (lua_State *L, int nexeccalls);
 End of changes. 2 change blocks. 
2 lines changed or deleted 2 lines changed or added


 lzio.h   lzio.h 
skipping to change at line 14 skipping to change at line 14
** See Copyright Notice in lua.h ** See Copyright Notice in lua.h
*/ */
#ifndef lzio_h #ifndef lzio_h
#define lzio_h #define lzio_h
#include "lua.h" #include "lua.h"
#include "lmem.h" #include "lmem.h"
#define EOZ (-1) /* end of stream */ #define EOZ (-1) /* end of stream */
typedef struct Zio ZIO; typedef struct Zio ZIO;
#define char2int(c) cast(int, cast(unsigned char, (c))) #define char2int(c) cast(int, cast(unsigned char, (c)))
#define zgetc(z) (((z)->n--)>0 ? char2int(*(z)->p++) : luaZ_fill(z)) #define zgetc(z) (((z)->n--)>0 ? char2int(*(z)->p++) : luaZ_fill(z))
typedef struct Mbuffer { typedef struct Mbuffer {
char *buffer; char *buffer;
size_t n; size_t n;
size_t buffsize; size_t buffsize;
} Mbuffer; } Mbuffer;
#define luaZ_initbuffer(L, buff) ((buff)->buffer = NULL, (buff)->buffsize = 0) #define luaZ_initbuffer(L, buff) ((buff)->buffer = NULL, (buff)->buffsize = 0)
#define luaZ_buffer(buff) ((buff)->buffer) #define luaZ_buffer(buff) ((buff)->buffer)
#define luaZ_sizebuffer(buff) ((buff)->buffsize) #define luaZ_sizebuffer(buff) ((buff)->buffsize)
#define luaZ_bufflen(buff) ((buff)->n) #define luaZ_bufflen(buff) ((buff)->n)
#define luaZ_resetbuffer(buff) ((buff)->n = 0) #define luaZ_resetbuffer(buff) ((buff)->n = 0)
#define luaZ_resizebuffer(L, buff, size) \ #define luaZ_resizebuffer(L, buff, size) \
(luaM_reallocvector(L, (buff)->buffer, (buff)->buffsize, size, char) (luaM_reallocvector(L, (buff)->buffer, (buff)->buffsize, size, char), \
, \ (buff)->buffsize = size)
(buff)->buffsize = size)
#define luaZ_freebuffer(L, buff) luaZ_resizebuffer(L, buff, 0) #define luaZ_freebuffer(L, buff) luaZ_resizebuffer(L, buff, 0)
LUAI_FUNC char *luaZ_openspace (lua_State *L, Mbuffer *buff, size_t n); LUAI_FUNC char *luaZ_openspace (lua_State *L, Mbuffer *buff, size_t n);
LUAI_FUNC void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, LUAI_FUNC void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader,
void *data); void *data);
LUAI_FUNC size_t luaZ_read (ZIO* z, void* b, size_t n); /* read next n bytes */ LUAI_FUNC size_t luaZ_read (ZIO* z, void* b, size_t n); /* read next n b ytes */
LUAI_FUNC int luaZ_lookahead (ZIO *z); LUAI_FUNC int luaZ_lookahead (ZIO *z);
/* --------- Private Part ------------------ */ /* --------- Private Part ------------------ */
struct Zio { struct Zio {
size_t n; /* bytes still unread */ size_t n; /* bytes still unread */
const char *p; /* current position in buffer */ const char *p; /* current position in buffer */
lua_Reader reader; lua_Reader reader;
void* data; /* additional data */ void* data; /* additional data */
lua_State *L; /* Lua state (for reader) */ lua_State *L; /* Lua state (for reader) */
}; };
LUAI_FUNC int luaZ_fill (ZIO *z); LUAI_FUNC int luaZ_fill (ZIO *z);
#endif #endif
 End of changes. 8 change blocks. 
14 lines changed or deleted 13 lines changed or added


 main.h   main.h 
#ifndef __MAIN_H__ #ifndef __MAIN_H__
#define __MAIN_H__ #define __MAIN_H__
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from W indows headers #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from W indows headers
// Windows Header Files: // Windows Header Files:
#include <windows.h> //#include <windows.h>
#include <tchar.h> //#include <tchar.h>
// C RunTime Header Files // C RunTime Header Files
#include "CCStdC.h" #include "CCStdC.h"
#endif // __MAIN_H__ #endif // __MAIN_H__
 End of changes. 1 change blocks. 
2 lines changed or deleted 2 lines changed or added


 nanoftp.h   nanoftp.h 
skipping to change at line 41 skipping to change at line 41
* @year: the year * @year: the year
* @month: the month * @month: the month
* @day: the day * @day: the day
* @hour: the hour * @hour: the hour
* @minute: the minute * @minute: the minute
* *
* A callback for the xmlNanoFTPList command. * A callback for the xmlNanoFTPList command.
* Note that only one of year and day:minute are specified. * Note that only one of year and day:minute are specified.
*/ */
typedef void (*ftpListCallback) (void *userData, typedef void (*ftpListCallback) (void *userData,
const char *filename, const char *attrib, const char *filename, const char *attrib,
const char *owner, const char *group, const char *owner, const char *group,
unsigned long size, int links, int year, unsigned long size, int links, int year,
const char *month, int day, int hour, const char *month, int day, int hour,
int minute); int minute);
/** /**
* ftpDataCallback: * ftpDataCallback:
* @userData: the user provided context * @userData: the user provided context
* @data: the data received * @data: the data received
* @len: its size in bytes * @len: its size in bytes
* *
* A callback for the xmlNanoFTPGet command. * A callback for the xmlNanoFTPGet command.
*/ */
typedef void (*ftpDataCallback) (void *userData, typedef void (*ftpDataCallback) (void *userData,
const char *data, const char *data,
int len); int len);
/* /*
* Init * Init
*/ */
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlNanoFTPInit (void); xmlNanoFTPInit (void);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlNanoFTPCleanup (void); xmlNanoFTPCleanup (void);
/* /*
* Creating/freeing contexts. * Creating/freeing contexts.
*/ */
XMLPUBFUN void * XMLCALL XMLPUBFUN void * XMLCALL
xmlNanoFTPNewCtxt (const char *URL); xmlNanoFTPNewCtxt (const char *URL);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlNanoFTPFreeCtxt (void * ctx); xmlNanoFTPFreeCtxt (void * ctx);
XMLPUBFUN void * XMLCALL XMLPUBFUN void * XMLCALL
xmlNanoFTPConnectTo (const char *server, xmlNanoFTPConnectTo (const char *server,
int port); int port);
/* /*
* Opening/closing session connections. * Opening/closing session connections.
*/ */
XMLPUBFUN void * XMLCALL XMLPUBFUN void * XMLCALL
xmlNanoFTPOpen (const char *URL); xmlNanoFTPOpen (const char *URL);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlNanoFTPConnect (void *ctx); xmlNanoFTPConnect (void *ctx);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlNanoFTPClose (void *ctx); xmlNanoFTPClose (void *ctx);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlNanoFTPQuit (void *ctx); xmlNanoFTPQuit (void *ctx);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlNanoFTPScanProxy (const char *URL); xmlNanoFTPScanProxy (const char *URL);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlNanoFTPProxy (const char *host, xmlNanoFTPProxy (const char *host,
int port, int port,
const char *user, const char *user,
const char *passwd, const char *passwd,
int type); int type);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlNanoFTPUpdateURL (void *ctx, xmlNanoFTPUpdateURL (void *ctx,
const char *URL); const char *URL);
/* /*
* Rather internal commands. * Rather internal commands.
*/ */
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlNanoFTPGetResponse (void *ctx); xmlNanoFTPGetResponse (void *ctx);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlNanoFTPCheckResponse (void *ctx); xmlNanoFTPCheckResponse (void *ctx);
/* /*
* CD/DIR/GET handlers. * CD/DIR/GET handlers.
*/ */
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlNanoFTPCwd (void *ctx, xmlNanoFTPCwd (void *ctx,
const char *directory); const char *directory);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlNanoFTPDele (void *ctx, xmlNanoFTPDele (void *ctx,
const char *file); const char *file);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlNanoFTPGetConnection (void *ctx); xmlNanoFTPGetConnection (void *ctx);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlNanoFTPCloseConnection(void *ctx); xmlNanoFTPCloseConnection(void *ctx);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlNanoFTPList (void *ctx, xmlNanoFTPList (void *ctx,
ftpListCallback callback, ftpListCallback callback,
void *userData, void *userData,
const char *filename); const char *filename);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlNanoFTPGetSocket (void *ctx, xmlNanoFTPGetSocket (void *ctx,
const char *filename); const char *filename);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlNanoFTPGet (void *ctx, xmlNanoFTPGet (void *ctx,
ftpDataCallback callback, ftpDataCallback callback,
void *userData, void *userData,
const char *filename); const char *filename);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlNanoFTPRead (void *ctx, xmlNanoFTPRead (void *ctx,
void *dest, void *dest,
int len); int len);
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif
#endif /* LIBXML_FTP_ENABLED */ #endif /* LIBXML_FTP_ENABLED */
#endif /* __NANO_FTP_H__ */ #endif /* __NANO_FTP_H__ */
 End of changes. 24 change blocks. 
46 lines changed or deleted 46 lines changed or added


 nanohttp.h   nanohttp.h 
skipping to change at line 22 skipping to change at line 22
#define __NANO_HTTP_H__ #define __NANO_HTTP_H__
#include <libxml/xmlversion.h> #include <libxml/xmlversion.h>
#ifdef LIBXML_HTTP_ENABLED #ifdef LIBXML_HTTP_ENABLED
#ifdef __cplusplus #ifdef __cplusplus
extern "C" { extern "C" {
#endif #endif
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlNanoHTTPInit (void); xmlNanoHTTPInit (void);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlNanoHTTPCleanup (void); xmlNanoHTTPCleanup (void);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlNanoHTTPScanProxy (const char *URL); xmlNanoHTTPScanProxy (const char *URL);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlNanoHTTPFetch (const char *URL, xmlNanoHTTPFetch (const char *URL,
const char *filename, const char *filename,
char **contentType); char **contentType);
XMLPUBFUN void * XMLCALL XMLPUBFUN void * XMLCALL
xmlNanoHTTPMethod (const char *URL, xmlNanoHTTPMethod (const char *URL,
const char *method, const char *method,
const char *input, const char *input,
char **contentType, char **contentType,
const char *headers, const char *headers,
int ilen); int ilen);
XMLPUBFUN void * XMLCALL XMLPUBFUN void * XMLCALL
xmlNanoHTTPMethodRedir (const char *URL, xmlNanoHTTPMethodRedir (const char *URL,
const char *method, const char *method,
const char *input, const char *input,
char **contentType, char **contentType,
char **redir, char **redir,
const char *headers, const char *headers,
int ilen); int ilen);
XMLPUBFUN void * XMLCALL XMLPUBFUN void * XMLCALL
xmlNanoHTTPOpen (const char *URL, xmlNanoHTTPOpen (const char *URL,
char **contentType); char **contentType);
XMLPUBFUN void * XMLCALL XMLPUBFUN void * XMLCALL
xmlNanoHTTPOpenRedir (const char *URL, xmlNanoHTTPOpenRedir (const char *URL,
char **contentType, char **contentType,
char **redir); char **redir);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlNanoHTTPReturnCode (void *ctx); xmlNanoHTTPReturnCode (void *ctx);
XMLPUBFUN const char * XMLCALL XMLPUBFUN const char * XMLCALL
xmlNanoHTTPAuthHeader (void *ctx); xmlNanoHTTPAuthHeader (void *ctx);
XMLPUBFUN const char * XMLCALL XMLPUBFUN const char * XMLCALL
xmlNanoHTTPRedir (void *ctx); xmlNanoHTTPRedir (void *ctx);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlNanoHTTPContentLength( void * ctx ); xmlNanoHTTPContentLength( void * ctx );
XMLPUBFUN const char * XMLCALL XMLPUBFUN const char * XMLCALL
xmlNanoHTTPEncoding (void *ctx); xmlNanoHTTPEncoding (void *ctx);
XMLPUBFUN const char * XMLCALL XMLPUBFUN const char * XMLCALL
xmlNanoHTTPMimeType (void *ctx); xmlNanoHTTPMimeType (void *ctx);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlNanoHTTPRead (void *ctx, xmlNanoHTTPRead (void *ctx,
void *dest, void *dest,
int len); int len);
#ifdef LIBXML_OUTPUT_ENABLED #ifdef LIBXML_OUTPUT_ENABLED
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlNanoHTTPSave (void *ctxt, xmlNanoHTTPSave (void *ctxt,
const char *filename); const char *filename);
#endif /* LIBXML_OUTPUT_ENABLED */ #endif /* LIBXML_OUTPUT_ENABLED */
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlNanoHTTPClose (void *ctx); xmlNanoHTTPClose (void *ctx);
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif
#endif /* LIBXML_HTTP_ENABLED */ #endif /* LIBXML_HTTP_ENABLED */
#endif /* __NANO_HTTP_H__ */ #endif /* __NANO_HTTP_H__ */
 End of changes. 17 change blocks. 
36 lines changed or deleted 36 lines changed or added


 os_types.h   os_types.h 
skipping to change at line 27 skipping to change at line 27
#ifndef _OS_TYPES_H #ifndef _OS_TYPES_H
#define _OS_TYPES_H #define _OS_TYPES_H
/* make it easy on the folks that want to compile the libs with a /* make it easy on the folks that want to compile the libs with a
different malloc than stdlib */ different malloc than stdlib */
#define _ogg_malloc malloc #define _ogg_malloc malloc
#define _ogg_calloc calloc #define _ogg_calloc calloc
#define _ogg_realloc realloc #define _ogg_realloc realloc
#define _ogg_free free #define _ogg_free free
#if defined(_WIN32) && !defined(SHP) #if defined(_WIN32)
# if defined(__CYGWIN__) # if defined(__CYGWIN__)
# include <stdint.h> # include <stdint.h>
typedef int16_t ogg_int16_t; typedef int16_t ogg_int16_t;
typedef uint16_t ogg_uint16_t; typedef uint16_t ogg_uint16_t;
typedef int32_t ogg_int32_t; typedef int32_t ogg_int32_t;
typedef uint32_t ogg_uint32_t; typedef uint32_t ogg_uint32_t;
typedef int64_t ogg_int64_t; typedef int64_t ogg_int64_t;
typedef uint64_t ogg_uint64_t; typedef uint64_t ogg_uint64_t;
# elif defined(__MINGW32__) # elif defined(__MINGW32__)
skipping to change at line 98 skipping to change at line 98
#elif defined(__BEOS__) #elif defined(__BEOS__)
/* Be */ /* Be */
# include <inttypes.h> # include <inttypes.h>
typedef int16_t ogg_int16_t; typedef int16_t ogg_int16_t;
typedef uint16_t ogg_uint16_t; typedef uint16_t ogg_uint16_t;
typedef int32_t ogg_int32_t; typedef int32_t ogg_int32_t;
typedef uint32_t ogg_uint32_t; typedef uint32_t ogg_uint32_t;
typedef int64_t ogg_int64_t; typedef int64_t ogg_int64_t;
#elif defined(__QNX__)
/* QNX */
# include <inttypes.h>
typedef int16_t ogg_int16_t;
typedef uint16_t ogg_uint16_t;
typedef int32_t ogg_int32_t;
typedef uint32_t ogg_uint32_t;
typedef int64_t ogg_int64_t;
#elif defined (__EMX__) #elif defined (__EMX__)
/* OS/2 GCC */ /* OS/2 GCC */
typedef short ogg_int16_t; typedef short ogg_int16_t;
typedef unsigned short ogg_uint16_t; typedef unsigned short ogg_uint16_t;
typedef int ogg_int32_t; typedef int ogg_int32_t;
typedef unsigned int ogg_uint32_t; typedef unsigned int ogg_uint32_t;
typedef long long ogg_int64_t; typedef long long ogg_int64_t;
#elif defined (DJGPP) #elif defined (DJGPP)
skipping to change at line 141 skipping to change at line 151
#elif defined(__TMS320C6X__) #elif defined(__TMS320C6X__)
/* TI C64x compiler */ /* TI C64x compiler */
typedef signed short ogg_int16_t; typedef signed short ogg_int16_t;
typedef unsigned short ogg_uint16_t; typedef unsigned short ogg_uint16_t;
typedef signed int ogg_int32_t; typedef signed int ogg_int32_t;
typedef unsigned int ogg_uint32_t; typedef unsigned int ogg_uint32_t;
typedef long long int ogg_int64_t; typedef long long int ogg_int64_t;
#elif defined(SHP)
typedef short ogg_int16_t;
typedef unsigned short ogg_uint16_t;
typedef int ogg_int32_t;
typedef unsigned int ogg_uint32_t;
typedef long long ogg_int64_t;
typedef unsigned long long ogg_uint64_t;
#else #else
# include <ogg/config_types.h> # include <ogg/config_types.h>
#endif #endif
#endif /* _OS_TYPES_H */ #endif /* _OS_TYPES_H */
 End of changes. 3 change blocks. 
8 lines changed or deleted 11 lines changed or added


 parser.h   parser.h 
skipping to change at line 33 skipping to change at line 33
#ifdef __cplusplus #ifdef __cplusplus
extern "C" { extern "C" {
#endif #endif
/** /**
* XML_DEFAULT_VERSION: * XML_DEFAULT_VERSION:
* *
* The default version of XML used: 1.0 * The default version of XML used: 1.0
*/ */
#define XML_DEFAULT_VERSION "1.0" #define XML_DEFAULT_VERSION "1.0"
/** /**
* xmlParserInput: * xmlParserInput:
* *
* An xmlParserInput is an input flow for the XML processor. * An xmlParserInput is an input flow for the XML processor.
* Each entity parsed is associated an xmlParserInput (except the * Each entity parsed is associated an xmlParserInput (except the
* few predefined ones). This is the case both for internal entities * few predefined ones). This is the case both for internal entities
* - in which case the flow is already completely in memory - or * - in which case the flow is already completely in memory - or
* external entities - in which case we use the buf structure for * external entities - in which case we use the buf structure for
* progressive reading and I18N conversions to the internal UTF-8 format. * progressive reading and I18N conversions to the internal UTF-8 format.
skipping to change at line 113 skipping to change at line 113
xmlParserNodeInfo* buffer; xmlParserNodeInfo* buffer;
}; };
/** /**
* xmlParserInputState: * xmlParserInputState:
* *
* The parser is now working also as a state based parser. * The parser is now working also as a state based parser.
* The recursive one use the state info for entities processing. * The recursive one use the state info for entities processing.
*/ */
typedef enum { typedef enum {
XML_PARSER_EOF = -1, /* nothing is to be parsed */ XML_PARSER_EOF = -1, /* nothing is to be parsed */
XML_PARSER_START = 0, /* nothing has been parsed */ XML_PARSER_START = 0, /* nothing has been parsed */
XML_PARSER_MISC, /* Misc* before int subset */ XML_PARSER_MISC, /* Misc* before int subset */
XML_PARSER_PI, /* Within a processing instruction */ XML_PARSER_PI, /* Within a processing instruction */
XML_PARSER_DTD, /* within some DTD content */ XML_PARSER_DTD, /* within some DTD content */
XML_PARSER_PROLOG, /* Misc* after internal subset */ XML_PARSER_PROLOG, /* Misc* after internal subset */
XML_PARSER_COMMENT, /* within a comment */ XML_PARSER_COMMENT, /* within a comment */
XML_PARSER_START_TAG, /* within a start tag */ XML_PARSER_START_TAG, /* within a start tag */
XML_PARSER_CONTENT, /* within the content */ XML_PARSER_CONTENT, /* within the content */
XML_PARSER_CDATA_SECTION, /* within a CDATA section */ XML_PARSER_CDATA_SECTION, /* within a CDATA section */
XML_PARSER_END_TAG, /* within a closing tag */ XML_PARSER_END_TAG, /* within a closing tag */
XML_PARSER_ENTITY_DECL, /* within an entity declaration */ XML_PARSER_ENTITY_DECL, /* within an entity declaration */
XML_PARSER_ENTITY_VALUE, /* within an entity value in a decl */ XML_PARSER_ENTITY_VALUE, /* within an entity value in a decl */
XML_PARSER_ATTRIBUTE_VALUE, /* within an attribute value */ XML_PARSER_ATTRIBUTE_VALUE, /* within an attribute value */
XML_PARSER_SYSTEM_LITERAL, /* within a SYSTEM value */ XML_PARSER_SYSTEM_LITERAL, /* within a SYSTEM value */
XML_PARSER_EPILOG, /* the Misc* after the last end tag XML_PARSER_EPILOG, /* the Misc* after the last end tag */
*/ XML_PARSER_IGNORE, /* within an IGNORED section */
XML_PARSER_IGNORE, /* within an IGNORED section */ XML_PARSER_PUBLIC_LITERAL /* within a PUBLIC value */
XML_PARSER_PUBLIC_LITERAL /* within a PUBLIC value */
} xmlParserInputState; } xmlParserInputState;
/** /**
* XML_DETECT_IDS: * XML_DETECT_IDS:
* *
* Bit in the loadsubset context field to tell to do ID/REFs lookups. * Bit in the loadsubset context field to tell to do ID/REFs lookups.
* Use it to initialize xmlLoadExtDtdDefaultValue. * Use it to initialize xmlLoadExtDtdDefaultValue.
*/ */
#define XML_DETECT_IDS 2 #define XML_DETECT_IDS 2
/** /**
* XML_COMPLETE_ATTRS: * XML_COMPLETE_ATTRS:
* *
* Bit in the loadsubset context field to tell to do complete the * Bit in the loadsubset context field to tell to do complete the
* elements attributes lists with the ones defaulted from the DTDs. * elements attributes lists with the ones defaulted from the DTDs.
* Use it to initialize xmlLoadExtDtdDefaultValue. * Use it to initialize xmlLoadExtDtdDefaultValue.
*/ */
#define XML_COMPLETE_ATTRS 4 #define XML_COMPLETE_ATTRS 4
/** /**
* XML_SKIP_IDS: * XML_SKIP_IDS:
* *
* Bit in the loadsubset context field to tell to not do ID/REFs registrati on. * Bit in the loadsubset context field to tell to not do ID/REFs registrati on.
* Used to initialize xmlLoadExtDtdDefaultValue in some special cases. * Used to initialize xmlLoadExtDtdDefaultValue in some special cases.
*/ */
#define XML_SKIP_IDS 8 #define XML_SKIP_IDS 8
/** /**
* xmlParserMode: * xmlParserMode:
* *
* A parser can operate in various modes * A parser can operate in various modes
*/ */
typedef enum { typedef enum {
XML_PARSE_UNKNOWN = 0, XML_PARSE_UNKNOWN = 0,
XML_PARSE_DOM = 1, XML_PARSE_DOM = 1,
XML_PARSE_SAX = 2, XML_PARSE_SAX = 2,
skipping to change at line 252 skipping to change at line 252
/* xml:space values */ /* xml:space values */
int * space; /* Should the parser preserve spaces */ int * space; /* Should the parser preserve spaces */
int spaceNr; /* Depth of the parsing stack */ int spaceNr; /* Depth of the parsing stack */
int spaceMax; /* Max depth of the parsing stack */ int spaceMax; /* Max depth of the parsing stack */
int * spaceTab; /* array of space infos */ int * spaceTab; /* array of space infos */
int depth; /* to prevent entity substitution loo ps */ int depth; /* to prevent entity substitution loo ps */
xmlParserInputPtr entity; /* used to check entities boundaries */ xmlParserInputPtr entity; /* used to check entities boundaries */
int charset; /* encoding of the in-memory content int charset; /* encoding of the in-memory content
actually an xmlCharEncoding */ actually an xmlCharEncoding */
int nodelen; /* Those two fields are there to */ int nodelen; /* Those two fields are there to */
int nodemem; /* Speed up large node parsing */ int nodemem; /* Speed up large node parsing */
int pedantic; /* signal pedantic warnings */ int pedantic; /* signal pedantic warnings */
void *_private; /* For user data, libxml won't touch it */ void *_private; /* For user data, libxml won't touch it */
int loadsubset; /* should the external subset be load ed */ int loadsubset; /* should the external subset be load ed */
int linenumbers; /* set line number in element content */ int linenumbers; /* set line number in element content */
void *catalogs; /* document's own catalog */ void *catalogs; /* document's own catalog */
int recovery; /* run in recovery mode */ int recovery; /* run in recovery mode */
int progressive; /* is this a progressive parsing */ int progressive; /* is this a progressive parsing */
skipping to change at line 348 skipping to change at line 348
* Callback: * Callback:
* The entity loader, to control the loading of external entities, * The entity loader, to control the loading of external entities,
* the application can either: * the application can either:
* - override this resolveEntity() callback in the SAX block * - override this resolveEntity() callback in the SAX block
* - or better use the xmlSetExternalEntityLoader() function to * - or better use the xmlSetExternalEntityLoader() function to
* set up it's own entity resolution routine * set up it's own entity resolution routine
* *
* Returns the xmlParserInputPtr if inlined or NULL for DOM behaviour. * Returns the xmlParserInputPtr if inlined or NULL for DOM behaviour.
*/ */
typedef xmlParserInputPtr (*resolveEntitySAXFunc) (void *ctx, typedef xmlParserInputPtr (*resolveEntitySAXFunc) (void *ctx,
const xmlChar *publicId, const xmlChar *publicId,
const xmlChar *systemId); const xmlChar *systemId);
/** /**
* internalSubsetSAXFunc: * internalSubsetSAXFunc:
* @ctx: the user data (XML parser context) * @ctx: the user data (XML parser context)
* @name: the root element name * @name: the root element name
* @ExternalID: the external ID * @ExternalID: the external ID
* @SystemID: the SYSTEM ID (e.g. filename or URL) * @SystemID: the SYSTEM ID (e.g. filename or URL)
* *
* Callback on internal subset declaration. * Callback on internal subset declaration.
*/ */
typedef void (*internalSubsetSAXFunc) (void *ctx, typedef void (*internalSubsetSAXFunc) (void *ctx,
const xmlChar *name, const xmlChar *name,
const xmlChar *ExternalID, const xmlChar *ExternalID,
const xmlChar *SystemID); const xmlChar *SystemID);
/** /**
* externalSubsetSAXFunc: * externalSubsetSAXFunc:
* @ctx: the user data (XML parser context) * @ctx: the user data (XML parser context)
* @name: the root element name * @name: the root element name
* @ExternalID: the external ID * @ExternalID: the external ID
* @SystemID: the SYSTEM ID (e.g. filename or URL) * @SystemID: the SYSTEM ID (e.g. filename or URL)
* *
* Callback on external subset declaration. * Callback on external subset declaration.
*/ */
typedef void (*externalSubsetSAXFunc) (void *ctx, typedef void (*externalSubsetSAXFunc) (void *ctx,
const xmlChar *name, const xmlChar *name,
const xmlChar *ExternalID, const xmlChar *ExternalID,
const xmlChar *SystemID); const xmlChar *SystemID);
/** /**
* getEntitySAXFunc: * getEntitySAXFunc:
* @ctx: the user data (XML parser context) * @ctx: the user data (XML parser context)
* @name: The entity name * @name: The entity name
* *
* Get an entity by name. * Get an entity by name.
* *
* Returns the xmlEntityPtr if found. * Returns the xmlEntityPtr if found.
*/ */
typedef xmlEntityPtr (*getEntitySAXFunc) (void *ctx, typedef xmlEntityPtr (*getEntitySAXFunc) (void *ctx,
const xmlChar *name); const xmlChar *name);
/** /**
* getParameterEntitySAXFunc: * getParameterEntitySAXFunc:
* @ctx: the user data (XML parser context) * @ctx: the user data (XML parser context)
* @name: The entity name * @name: The entity name
* *
* Get a parameter entity by name. * Get a parameter entity by name.
* *
* Returns the xmlEntityPtr if found. * Returns the xmlEntityPtr if found.
*/ */
typedef xmlEntityPtr (*getParameterEntitySAXFunc) (void *ctx, typedef xmlEntityPtr (*getParameterEntitySAXFunc) (void *ctx,
const xmlChar *name); const xmlChar *name);
/** /**
* entityDeclSAXFunc: * entityDeclSAXFunc:
* @ctx: the user data (XML parser context) * @ctx: the user data (XML parser context)
* @name: the entity name * @name: the entity name
* @type: the entity type * @type: the entity type
* @publicId: The public ID of the entity * @publicId: The public ID of the entity
* @systemId: The system ID of the entity * @systemId: The system ID of the entity
* @content: the entity value (without processing). * @content: the entity value (without processing).
* *
* An entity definition has been parsed. * An entity definition has been parsed.
*/ */
typedef void (*entityDeclSAXFunc) (void *ctx, typedef void (*entityDeclSAXFunc) (void *ctx,
const xmlChar *name, const xmlChar *name,
int type, int type,
const xmlChar *publicId, const xmlChar *publicId,
const xmlChar *systemId, const xmlChar *systemId,
xmlChar *content); xmlChar *content);
/** /**
* notationDeclSAXFunc: * notationDeclSAXFunc:
* @ctx: the user data (XML parser context) * @ctx: the user data (XML parser context)
* @name: The name of the notation * @name: The name of the notation
* @publicId: The public ID of the entity * @publicId: The public ID of the entity
* @systemId: The system ID of the entity * @systemId: The system ID of the entity
* *
* What to do when a notation declaration has been parsed. * What to do when a notation declaration has been parsed.
*/ */
typedef void (*notationDeclSAXFunc)(void *ctx, typedef void (*notationDeclSAXFunc)(void *ctx,
const xmlChar *name, const xmlChar *name,
const xmlChar *publicId, const xmlChar *publicId,
const xmlChar *systemId); const xmlChar *systemId);
/** /**
* attributeDeclSAXFunc: * attributeDeclSAXFunc:
* @ctx: the user data (XML parser context) * @ctx: the user data (XML parser context)
* @elem: the name of the element * @elem: the name of the element
* @fullname: the attribute name * @fullname: the attribute name
* @type: the attribute type * @type: the attribute type
* @def: the type of default value * @def: the type of default value
* @defaultValue: the attribute default value * @defaultValue: the attribute default value
* @tree: the tree of enumerated value set * @tree: the tree of enumerated value set
* *
* An attribute definition has been parsed. * An attribute definition has been parsed.
*/ */
typedef void (*attributeDeclSAXFunc)(void *ctx, typedef void (*attributeDeclSAXFunc)(void *ctx,
const xmlChar *elem, const xmlChar *elem,
const xmlChar *fullname, const xmlChar *fullname,
int type, int type,
int def, int def,
const xmlChar *defaultValue, const xmlChar *defaultValue,
xmlEnumerationPtr tree); xmlEnumerationPtr tree);
/** /**
* elementDeclSAXFunc: * elementDeclSAXFunc:
* @ctx: the user data (XML parser context) * @ctx: the user data (XML parser context)
* @name: the element name * @name: the element name
* @type: the element type * @type: the element type
* @content: the element value tree * @content: the element value tree
* *
* An element definition has been parsed. * An element definition has been parsed.
*/ */
typedef void (*elementDeclSAXFunc)(void *ctx, typedef void (*elementDeclSAXFunc)(void *ctx,
const xmlChar *name, const xmlChar *name,
int type, int type,
xmlElementContentPtr content); xmlElementContentPtr content);
/** /**
* unparsedEntityDeclSAXFunc: * unparsedEntityDeclSAXFunc:
* @ctx: the user data (XML parser context) * @ctx: the user data (XML parser context)
* @name: The name of the entity * @name: The name of the entity
* @publicId: The public ID of the entity * @publicId: The public ID of the entity
* @systemId: The system ID of the entity * @systemId: The system ID of the entity
* @notationName: the name of the notation * @notationName: the name of the notation
* *
* What to do when an unparsed entity declaration is parsed. * What to do when an unparsed entity declaration is parsed.
*/ */
typedef void (*unparsedEntityDeclSAXFunc)(void *ctx, typedef void (*unparsedEntityDeclSAXFunc)(void *ctx,
const xmlChar *name, const xmlChar *name,
const xmlChar *publicId, const xmlChar *publicId,
const xmlChar *systemId, const xmlChar *systemId,
const xmlChar *notationName); const xmlChar *notationName);
/** /**
* setDocumentLocatorSAXFunc: * setDocumentLocatorSAXFunc:
* @ctx: the user data (XML parser context) * @ctx: the user data (XML parser context)
* @loc: A SAX Locator * @loc: A SAX Locator
* *
* Receive the document locator at startup, actually xmlDefaultSAXLocator. * Receive the document locator at startup, actually xmlDefaultSAXLocator.
* Everything is available on the context, so this is useless in our case. * Everything is available on the context, so this is useless in our case.
*/ */
typedef void (*setDocumentLocatorSAXFunc) (void *ctx, typedef void (*setDocumentLocatorSAXFunc) (void *ctx,
xmlSAXLocatorPtr loc); xmlSAXLocatorPtr loc);
/** /**
* startDocumentSAXFunc: * startDocumentSAXFunc:
* @ctx: the user data (XML parser context) * @ctx: the user data (XML parser context)
* *
* Called when the document start being processed. * Called when the document start being processed.
*/ */
typedef void (*startDocumentSAXFunc) (void *ctx); typedef void (*startDocumentSAXFunc) (void *ctx);
/** /**
* endDocumentSAXFunc: * endDocumentSAXFunc:
* @ctx: the user data (XML parser context) * @ctx: the user data (XML parser context)
skipping to change at line 508 skipping to change at line 508
typedef void (*endDocumentSAXFunc) (void *ctx); typedef void (*endDocumentSAXFunc) (void *ctx);
/** /**
* startElementSAXFunc: * startElementSAXFunc:
* @ctx: the user data (XML parser context) * @ctx: the user data (XML parser context)
* @name: The element name, including namespace prefix * @name: The element name, including namespace prefix
* @atts: An array of name/value attributes pairs, NULL terminated * @atts: An array of name/value attributes pairs, NULL terminated
* *
* Called when an opening tag has been processed. * Called when an opening tag has been processed.
*/ */
typedef void (*startElementSAXFunc) (void *ctx, typedef void (*startElementSAXFunc) (void *ctx,
const xmlChar *name, const xmlChar *name,
const xmlChar **atts); const xmlChar **atts);
/** /**
* endElementSAXFunc: * endElementSAXFunc:
* @ctx: the user data (XML parser context) * @ctx: the user data (XML parser context)
* @name: The element name * @name: The element name
* *
* Called when the end of an element has been detected. * Called when the end of an element has been detected.
*/ */
typedef void (*endElementSAXFunc) (void *ctx, typedef void (*endElementSAXFunc) (void *ctx,
const xmlChar *name); const xmlChar *name);
/** /**
* attributeSAXFunc: * attributeSAXFunc:
* @ctx: the user data (XML parser context) * @ctx: the user data (XML parser context)
* @name: The attribute name, including namespace prefix * @name: The attribute name, including namespace prefix
* @value: The attribute value * @value: The attribute value
* *
* Handle an attribute that has been read by the parser. * Handle an attribute that has been read by the parser.
* The default handling is to convert the attribute into an * The default handling is to convert the attribute into an
* DOM subtree and past it in a new xmlAttr element added to * DOM subtree and past it in a new xmlAttr element added to
* the element. * the element.
*/ */
typedef void (*attributeSAXFunc) (void *ctx, typedef void (*attributeSAXFunc) (void *ctx,
const xmlChar *name, const xmlChar *name,
const xmlChar *value); const xmlChar *value);
/** /**
* referenceSAXFunc: * referenceSAXFunc:
* @ctx: the user data (XML parser context) * @ctx: the user data (XML parser context)
* @name: The entity name * @name: The entity name
* *
* Called when an entity reference is detected. * Called when an entity reference is detected.
*/ */
typedef void (*referenceSAXFunc) (void *ctx, typedef void (*referenceSAXFunc) (void *ctx,
const xmlChar *name); const xmlChar *name);
/** /**
* charactersSAXFunc: * charactersSAXFunc:
* @ctx: the user data (XML parser context) * @ctx: the user data (XML parser context)
* @ch: a xmlChar string * @ch: a xmlChar string
* @len: the number of xmlChar * @len: the number of xmlChar
* *
* Receiving some chars from the parser. * Receiving some chars from the parser.
*/ */
typedef void (*charactersSAXFunc) (void *ctx, typedef void (*charactersSAXFunc) (void *ctx,
const xmlChar *ch, const xmlChar *ch,
int len); int len);
/** /**
* ignorableWhitespaceSAXFunc: * ignorableWhitespaceSAXFunc:
* @ctx: the user data (XML parser context) * @ctx: the user data (XML parser context)
* @ch: a xmlChar string * @ch: a xmlChar string
* @len: the number of xmlChar * @len: the number of xmlChar
* *
* Receiving some ignorable whitespaces from the parser. * Receiving some ignorable whitespaces from the parser.
* UNUSED: by default the DOM building will use characters. * UNUSED: by default the DOM building will use characters.
*/ */
typedef void (*ignorableWhitespaceSAXFunc) (void *ctx, typedef void (*ignorableWhitespaceSAXFunc) (void *ctx,
const xmlChar *ch, const xmlChar *ch,
int len); int len);
/** /**
* processingInstructionSAXFunc: * processingInstructionSAXFunc:
* @ctx: the user data (XML parser context) * @ctx: the user data (XML parser context)
* @target: the target name * @target: the target name
* @data: the PI data's * @data: the PI data's
* *
* A processing instruction has been parsed. * A processing instruction has been parsed.
*/ */
typedef void (*processingInstructionSAXFunc) (void *ctx, typedef void (*processingInstructionSAXFunc) (void *ctx,
const xmlChar *target, const xmlChar *target,
const xmlChar *data); const xmlChar *data);
/** /**
* commentSAXFunc: * commentSAXFunc:
* @ctx: the user data (XML parser context) * @ctx: the user data (XML parser context)
* @value: the comment content * @value: the comment content
* *
* A comment has been parsed. * A comment has been parsed.
*/ */
typedef void (*commentSAXFunc) (void *ctx, typedef void (*commentSAXFunc) (void *ctx,
const xmlChar *value); const xmlChar *value);
/** /**
* cdataBlockSAXFunc: * cdataBlockSAXFunc:
* @ctx: the user data (XML parser context) * @ctx: the user data (XML parser context)
* @value: The pcdata content * @value: The pcdata content
* @len: the block length * @len: the block length
* *
* Called when a pcdata block has been parsed. * Called when a pcdata block has been parsed.
*/ */
typedef void (*cdataBlockSAXFunc) ( typedef void (*cdataBlockSAXFunc) (
void *ctx, void *ctx,
const xmlChar *value, const xmlChar *value,
int len); int len);
/** /**
* warningSAXFunc: * warningSAXFunc:
* @ctx: an XML parser context * @ctx: an XML parser context
* @msg: the message to display/transmit * @msg: the message to display/transmit
* @...: extra parameters for the message display * @...: extra parameters for the message display
* *
* Display and format a warning messages, callback. * Display and format a warning messages, callback.
*/ */
typedef void (XMLCDECL *warningSAXFunc) (void *ctx, typedef void (XMLCDECL *warningSAXFunc) (void *ctx,
const char *msg, ...) LIBXML_ATTR_FORMAT(2,3 ); const char *msg, ...) LIBXML_ATTR_FORMAT(2,3);
/** /**
* errorSAXFunc: * errorSAXFunc:
* @ctx: an XML parser context * @ctx: an XML parser context
* @msg: the message to display/transmit * @msg: the message to display/transmit
* @...: extra parameters for the message display * @...: extra parameters for the message display
* *
* Display and format an error messages, callback. * Display and format an error messages, callback.
*/ */
typedef void (XMLCDECL *errorSAXFunc) (void *ctx, typedef void (XMLCDECL *errorSAXFunc) (void *ctx,
const char *msg, ...) LIBXML_ATTR_FORMAT(2,3 ); const char *msg, ...) LIBXML_ATTR_FORMAT(2,3);
/** /**
* fatalErrorSAXFunc: * fatalErrorSAXFunc:
* @ctx: an XML parser context * @ctx: an XML parser context
* @msg: the message to display/transmit * @msg: the message to display/transmit
* @...: extra parameters for the message display * @...: extra parameters for the message display
* *
* Display and format fatal error messages, callback. * Display and format fatal error messages, callback.
* Note: so far fatalError() SAX callbacks are not used, error() * Note: so far fatalError() SAX callbacks are not used, error()
* get all the callbacks for errors. * get all the callbacks for errors.
*/ */
typedef void (XMLCDECL *fatalErrorSAXFunc) (void *ctx, typedef void (XMLCDECL *fatalErrorSAXFunc) (void *ctx,
const char *msg, ...) LIBXML_ATTR_FORMAT(2,3 ); const char *msg, ...) LIBXML_ATTR_FORMAT(2,3);
/** /**
* isStandaloneSAXFunc: * isStandaloneSAXFunc:
* @ctx: the user data (XML parser context) * @ctx: the user data (XML parser context)
* *
* Is this document tagged standalone? * Is this document tagged standalone?
* *
* Returns 1 if true * Returns 1 if true
*/ */
typedef int (*isStandaloneSAXFunc) (void *ctx); typedef int (*isStandaloneSAXFunc) (void *ctx);
/** /**
skipping to change at line 659 skipping to change at line 659
* hasExternalSubsetSAXFunc: * hasExternalSubsetSAXFunc:
* @ctx: the user data (XML parser context) * @ctx: the user data (XML parser context)
* *
* Does this document has an external subset? * Does this document has an external subset?
* *
* Returns 1 if true * Returns 1 if true
*/ */
typedef int (*hasExternalSubsetSAXFunc) (void *ctx); typedef int (*hasExternalSubsetSAXFunc) (void *ctx);
/************************************************************************ /************************************************************************
* * * *
* The SAX version 2 API extensions * * The SAX version 2 API extensions *
* * * *
************************************************************************/ ************************************************************************/
/** /**
* XML_SAX2_MAGIC: * XML_SAX2_MAGIC:
* *
* Special constant found in SAX2 blocks initialized fields * Special constant found in SAX2 blocks initialized fields
*/ */
#define XML_SAX2_MAGIC 0xDEEDBEAF #define XML_SAX2_MAGIC 0xDEEDBEAF
/** /**
* startElementNsSAX2Func: * startElementNsSAX2Func:
skipping to change at line 690 skipping to change at line 690
* ones are at the end of the array * ones are at the end of the array
* @attributes: pointer to the array of (localname/prefix/URI/value/end) * @attributes: pointer to the array of (localname/prefix/URI/value/end)
* attribute values. * attribute values.
* *
* SAX2 callback when an element start has been detected by the parser. * SAX2 callback when an element start has been detected by the parser.
* It provides the namespace informations for the element, as well as * It provides the namespace informations for the element, as well as
* the new namespace declarations on the element. * the new namespace declarations on the element.
*/ */
typedef void (*startElementNsSAX2Func) (void *ctx, typedef void (*startElementNsSAX2Func) (void *ctx,
const xmlChar *localname, const xmlChar *localname,
const xmlChar *prefix, const xmlChar *prefix,
const xmlChar *URI, const xmlChar *URI,
int nb_namespaces, int nb_namespaces,
const xmlChar **namespaces, const xmlChar **namespaces,
int nb_attributes, int nb_attributes,
int nb_defaulted, int nb_defaulted,
const xmlChar **attributes); const xmlChar **attributes);
/** /**
* endElementNsSAX2Func: * endElementNsSAX2Func:
* @ctx: the user data (XML parser context) * @ctx: the user data (XML parser context)
* @localname: the local name of the element * @localname: the local name of the element
* @prefix: the element namespace prefix if available * @prefix: the element namespace prefix if available
* @URI: the element namespace name if available * @URI: the element namespace name if available
* *
* SAX2 callback when an element end has been detected by the parser. * SAX2 callback when an element end has been detected by the parser.
* It provides the namespace informations for the element. * It provides the namespace informations for the element.
*/ */
typedef void (*endElementNsSAX2Func) (void *ctx, typedef void (*endElementNsSAX2Func) (void *ctx,
const xmlChar *localname, const xmlChar *localname,
const xmlChar *prefix, const xmlChar *prefix,
const xmlChar *URI); const xmlChar *URI);
struct _xmlSAXHandler { struct _xmlSAXHandler {
internalSubsetSAXFunc internalSubset; internalSubsetSAXFunc internalSubset;
isStandaloneSAXFunc isStandalone; isStandaloneSAXFunc isStandalone;
hasInternalSubsetSAXFunc hasInternalSubset; hasInternalSubsetSAXFunc hasInternalSubset;
hasExternalSubsetSAXFunc hasExternalSubset; hasExternalSubsetSAXFunc hasExternalSubset;
resolveEntitySAXFunc resolveEntity; resolveEntitySAXFunc resolveEntity;
getEntitySAXFunc getEntity; getEntitySAXFunc getEntity;
entityDeclSAXFunc entityDecl; entityDeclSAXFunc entityDecl;
notationDeclSAXFunc notationDecl; notationDeclSAXFunc notationDecl;
skipping to change at line 798 skipping to change at line 798
* xmlExternalEntityLoader: * xmlExternalEntityLoader:
* @URL: The System ID of the resource requested * @URL: The System ID of the resource requested
* @ID: The Public ID of the resource requested * @ID: The Public ID of the resource requested
* @context: the XML parser context * @context: the XML parser context
* *
* External entity loaders types. * External entity loaders types.
* *
* Returns the entity input parser. * Returns the entity input parser.
*/ */
typedef xmlParserInputPtr (*xmlExternalEntityLoader) (const char *URL, typedef xmlParserInputPtr (*xmlExternalEntityLoader) (const char *URL,
const char *ID, const char *ID,
xmlParserCtxtPtr context); xmlParserCtxtPtr context);
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif
#include <libxml/encoding.h> #include <libxml/encoding.h>
#include <libxml/xmlIO.h> #include <libxml/xmlIO.h>
#include <libxml/globals.h> #include <libxml/globals.h>
#ifdef __cplusplus #ifdef __cplusplus
extern "C" { extern "C" {
#endif #endif
/* /*
* Init/Cleanup * Init/Cleanup
*/ */
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlInitParser (void); xmlInitParser (void);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlCleanupParser (void); xmlCleanupParser (void);
/* /*
* Input functions * Input functions
*/ */
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlParserInputRead (xmlParserInputPtr in, xmlParserInputRead (xmlParserInputPtr in,
int len); int len);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlParserInputGrow (xmlParserInputPtr in, xmlParserInputGrow (xmlParserInputPtr in,
int len); int len);
/* /*
* Basic parsing Interfaces * Basic parsing Interfaces
*/ */
#ifdef LIBXML_SAX1_ENABLED #ifdef LIBXML_SAX1_ENABLED
XMLPUBFUN xmlDocPtr XMLCALL XMLPUBFUN xmlDocPtr XMLCALL
xmlParseDoc (const xmlChar *cur); xmlParseDoc (const xmlChar *cur);
XMLPUBFUN xmlDocPtr XMLCALL XMLPUBFUN xmlDocPtr XMLCALL
xmlParseFile (const char *filename); xmlParseFile (const char *filename);
XMLPUBFUN xmlDocPtr XMLCALL XMLPUBFUN xmlDocPtr XMLCALL
xmlParseMemory (const char *buffer, xmlParseMemory (const char *buffer,
int size); int size);
#endif /* LIBXML_SAX1_ENABLED */ #endif /* LIBXML_SAX1_ENABLED */
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlSubstituteEntitiesDefault(int val); xmlSubstituteEntitiesDefault(int val);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlKeepBlanksDefault (int val); xmlKeepBlanksDefault (int val);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlStopParser (xmlParserCtxtPtr ctxt); xmlStopParser (xmlParserCtxtPtr ctxt);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlPedanticParserDefault(int val); xmlPedanticParserDefault(int val);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlLineNumbersDefault (int val); xmlLineNumbersDefault (int val);
#ifdef LIBXML_SAX1_ENABLED #ifdef LIBXML_SAX1_ENABLED
/* /*
* Recovery mode * Recovery mode
*/ */
XMLPUBFUN xmlDocPtr XMLCALL XMLPUBFUN xmlDocPtr XMLCALL
xmlRecoverDoc (const xmlChar *cur); xmlRecoverDoc (const xmlChar *cur);
XMLPUBFUN xmlDocPtr XMLCALL XMLPUBFUN xmlDocPtr XMLCALL
xmlRecoverMemory (const char *buffer, xmlRecoverMemory (const char *buffer,
int size); int size);
XMLPUBFUN xmlDocPtr XMLCALL XMLPUBFUN xmlDocPtr XMLCALL
xmlRecoverFile (const char *filename); xmlRecoverFile (const char *filename);
#endif /* LIBXML_SAX1_ENABLED */ #endif /* LIBXML_SAX1_ENABLED */
/* /*
* Less common routines and SAX interfaces * Less common routines and SAX interfaces
*/ */
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlParseDocument (xmlParserCtxtPtr ctxt); xmlParseDocument (xmlParserCtxtPtr ctxt);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlParseExtParsedEnt (xmlParserCtxtPtr ctxt); xmlParseExtParsedEnt (xmlParserCtxtPtr ctxt);
#ifdef LIBXML_SAX1_ENABLED #ifdef LIBXML_SAX1_ENABLED
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlSAXUserParseFile (xmlSAXHandlerPtr sax, xmlSAXUserParseFile (xmlSAXHandlerPtr sax,
void *user_data, void *user_data,
const char *filename); const char *filename);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlSAXUserParseMemory (xmlSAXHandlerPtr sax, xmlSAXUserParseMemory (xmlSAXHandlerPtr sax,
void *user_data, void *user_data,
const char *buffer, const char *buffer,
int size); int size);
XMLPUBFUN xmlDocPtr XMLCALL XMLPUBFUN xmlDocPtr XMLCALL
xmlSAXParseDoc (xmlSAXHandlerPtr sax, xmlSAXParseDoc (xmlSAXHandlerPtr sax,
const xmlChar *cur, const xmlChar *cur,
int recovery); int recovery);
XMLPUBFUN xmlDocPtr XMLCALL XMLPUBFUN xmlDocPtr XMLCALL
xmlSAXParseMemory (xmlSAXHandlerPtr sax, xmlSAXParseMemory (xmlSAXHandlerPtr sax,
const char *buffer, const char *buffer,
int size, int size,
int recovery); int recovery);
XMLPUBFUN xmlDocPtr XMLCALL XMLPUBFUN xmlDocPtr XMLCALL
xmlSAXParseMemoryWithData (xmlSAXHandlerPtr sax, xmlSAXParseMemoryWithData (xmlSAXHandlerPtr sax,
const char *buffer, const char *buffer,
int size, int size,
int recovery, int recovery,
void *data); void *data);
XMLPUBFUN xmlDocPtr XMLCALL XMLPUBFUN xmlDocPtr XMLCALL
xmlSAXParseFile (xmlSAXHandlerPtr sax, xmlSAXParseFile (xmlSAXHandlerPtr sax,
const char *filename, const char *filename,
int recovery); int recovery);
XMLPUBFUN xmlDocPtr XMLCALL XMLPUBFUN xmlDocPtr XMLCALL
xmlSAXParseFileWithData (xmlSAXHandlerPtr sax, xmlSAXParseFileWithData (xmlSAXHandlerPtr sax,
const char *filename, const char *filename,
int recovery, int recovery,
void *data); void *data);
XMLPUBFUN xmlDocPtr XMLCALL XMLPUBFUN xmlDocPtr XMLCALL
xmlSAXParseEntity (xmlSAXHandlerPtr sax, xmlSAXParseEntity (xmlSAXHandlerPtr sax,
const char *filename); const char *filename);
XMLPUBFUN xmlDocPtr XMLCALL XMLPUBFUN xmlDocPtr XMLCALL
xmlParseEntity (const char *filename); xmlParseEntity (const char *filename);
#endif /* LIBXML_SAX1_ENABLED */ #endif /* LIBXML_SAX1_ENABLED */
#ifdef LIBXML_VALID_ENABLED #ifdef LIBXML_VALID_ENABLED
XMLPUBFUN xmlDtdPtr XMLCALL XMLPUBFUN xmlDtdPtr XMLCALL
xmlSAXParseDTD (xmlSAXHandlerPtr sax, xmlSAXParseDTD (xmlSAXHandlerPtr sax,
const xmlChar *ExternalID, const xmlChar *ExternalID,
const xmlChar *SystemID); const xmlChar *SystemID);
XMLPUBFUN xmlDtdPtr XMLCALL XMLPUBFUN xmlDtdPtr XMLCALL
xmlParseDTD (const xmlChar *ExternalID, xmlParseDTD (const xmlChar *ExternalID,
const xmlChar *SystemID); const xmlChar *SystemID);
XMLPUBFUN xmlDtdPtr XMLCALL XMLPUBFUN xmlDtdPtr XMLCALL
xmlIOParseDTD (xmlSAXHandlerPtr sax, xmlIOParseDTD (xmlSAXHandlerPtr sax,
xmlParserInputBufferPtr input, xmlParserInputBufferPtr input,
xmlCharEncoding enc); xmlCharEncoding enc);
#endif /* LIBXML_VALID_ENABLE */ #endif /* LIBXML_VALID_ENABLE */
#ifdef LIBXML_SAX1_ENABLED #ifdef LIBXML_SAX1_ENABLED
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlParseBalancedChunkMemory(xmlDocPtr doc, xmlParseBalancedChunkMemory(xmlDocPtr doc,
xmlSAXHandlerPtr sax, xmlSAXHandlerPtr sax,
void *user_data, void *user_data,
int depth, int depth,
const xmlChar *string, const xmlChar *string,
xmlNodePtr *lst); xmlNodePtr *lst);
#endif /* LIBXML_SAX1_ENABLED */ #endif /* LIBXML_SAX1_ENABLED */
XMLPUBFUN xmlParserErrors XMLCALL XMLPUBFUN xmlParserErrors XMLCALL
xmlParseInNodeContext (xmlNodePtr node, xmlParseInNodeContext (xmlNodePtr node,
const char *data, const char *data,
int datalen, int datalen,
int options, int options,
xmlNodePtr *lst); xmlNodePtr *lst);
#ifdef LIBXML_SAX1_ENABLED #ifdef LIBXML_SAX1_ENABLED
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlParseBalancedChunkMemoryRecover(xmlDocPtr doc, xmlParseBalancedChunkMemoryRecover(xmlDocPtr doc,
xmlSAXHandlerPtr sax, xmlSAXHandlerPtr sax,
void *user_data, void *user_data,
int depth, int depth,
const xmlChar *string, const xmlChar *string,
xmlNodePtr *lst, xmlNodePtr *lst,
int recover); int recover);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlParseExternalEntity (xmlDocPtr doc, xmlParseExternalEntity (xmlDocPtr doc,
xmlSAXHandlerPtr sax, xmlSAXHandlerPtr sax,
void *user_data, void *user_data,
int depth, int depth,
const xmlChar *URL, const xmlChar *URL,
const xmlChar *ID, const xmlChar *ID,
xmlNodePtr *lst); xmlNodePtr *lst);
#endif /* LIBXML_SAX1_ENABLED */ #endif /* LIBXML_SAX1_ENABLED */
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlParseCtxtExternalEntity(xmlParserCtxtPtr ctx, xmlParseCtxtExternalEntity(xmlParserCtxtPtr ctx,
const xmlChar *URL, const xmlChar *URL,
const xmlChar *ID, const xmlChar *ID,
xmlNodePtr *lst); xmlNodePtr *lst);
/* /*
* Parser contexts handling. * Parser contexts handling.
*/ */
XMLPUBFUN xmlParserCtxtPtr XMLCALL XMLPUBFUN xmlParserCtxtPtr XMLCALL
xmlNewParserCtxt (void); xmlNewParserCtxt (void);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlInitParserCtxt (xmlParserCtxtPtr ctxt); xmlInitParserCtxt (xmlParserCtxtPtr ctxt);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlClearParserCtxt (xmlParserCtxtPtr ctxt); xmlClearParserCtxt (xmlParserCtxtPtr ctxt);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlFreeParserCtxt (xmlParserCtxtPtr ctxt); xmlFreeParserCtxt (xmlParserCtxtPtr ctxt);
#ifdef LIBXML_SAX1_ENABLED #ifdef LIBXML_SAX1_ENABLED
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlSetupParserForBuffer (xmlParserCtxtPtr ctxt, xmlSetupParserForBuffer (xmlParserCtxtPtr ctxt,
const xmlChar* buffer, const xmlChar* buffer,
const char *filename); const char *filename);
#endif /* LIBXML_SAX1_ENABLED */ #endif /* LIBXML_SAX1_ENABLED */
XMLPUBFUN xmlParserCtxtPtr XMLCALL XMLPUBFUN xmlParserCtxtPtr XMLCALL
xmlCreateDocParserCtxt (const xmlChar *cur); xmlCreateDocParserCtxt (const xmlChar *cur);
#ifdef LIBXML_LEGACY_ENABLED #ifdef LIBXML_LEGACY_ENABLED
/* /*
* Reading/setting optional parsing features. * Reading/setting optional parsing features.
*/ */
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlGetFeaturesList (int *len, xmlGetFeaturesList (int *len,
const char **result); const char **result);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlGetFeature (xmlParserCtxtPtr ctxt, xmlGetFeature (xmlParserCtxtPtr ctxt,
const char *name, const char *name,
void *result); void *result);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlSetFeature (xmlParserCtxtPtr ctxt, xmlSetFeature (xmlParserCtxtPtr ctxt,
const char *name, const char *name,
void *value); void *value);
#endif /* LIBXML_LEGACY_ENABLED */ #endif /* LIBXML_LEGACY_ENABLED */
#ifdef LIBXML_PUSH_ENABLED #ifdef LIBXML_PUSH_ENABLED
/* /*
* Interfaces for the Push mode. * Interfaces for the Push mode.
*/ */
XMLPUBFUN xmlParserCtxtPtr XMLCALL XMLPUBFUN xmlParserCtxtPtr XMLCALL
xmlCreatePushParserCtxt(xmlSAXHandlerPtr sax, xmlCreatePushParserCtxt(xmlSAXHandlerPtr sax,
void *user_data, void *user_data,
const char *chunk, const char *chunk,
int size, int size,
const char *filename); const char *filename);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlParseChunk (xmlParserCtxtPtr ctxt, xmlParseChunk (xmlParserCtxtPtr ctxt,
const char *chunk, const char *chunk,
int size, int size,
int terminate); int terminate);
#endif /* LIBXML_PUSH_ENABLED */ #endif /* LIBXML_PUSH_ENABLED */
/* /*
* Special I/O mode. * Special I/O mode.
*/ */
XMLPUBFUN xmlParserCtxtPtr XMLCALL XMLPUBFUN xmlParserCtxtPtr XMLCALL
xmlCreateIOParserCtxt (xmlSAXHandlerPtr sax, xmlCreateIOParserCtxt (xmlSAXHandlerPtr sax,
void *user_data, void *user_data,
xmlInputReadCallback ioread, xmlInputReadCallback ioread,
xmlInputCloseCallback ioclose, xmlInputCloseCallback ioclose,
void *ioctx, void *ioctx,
xmlCharEncoding enc); xmlCharEncoding enc);
XMLPUBFUN xmlParserInputPtr XMLCALL XMLPUBFUN xmlParserInputPtr XMLCALL
xmlNewIOInputStream (xmlParserCtxtPtr ctxt, xmlNewIOInputStream (xmlParserCtxtPtr ctxt,
xmlParserInputBufferPtr input, xmlParserInputBufferPtr input,
xmlCharEncoding enc); xmlCharEncoding enc);
/* /*
* Node infos. * Node infos.
*/ */
XMLPUBFUN const xmlParserNodeInfo* XMLCALL XMLPUBFUN const xmlParserNodeInfo* XMLCALL
xmlParserFindNodeInfo (const xmlParserCtxtPtr ctxt, xmlParserFindNodeInfo (const xmlParserCtxtPtr ctxt,
const xmlNodePtr node); const xmlNodePtr node);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlInitNodeInfoSeq (xmlParserNodeInfoSeqPtr seq); xmlInitNodeInfoSeq (xmlParserNodeInfoSeqPtr seq);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlClearNodeInfoSeq (xmlParserNodeInfoSeqPtr seq); xmlClearNodeInfoSeq (xmlParserNodeInfoSeqPtr seq);
XMLPUBFUN unsigned long XMLCALL XMLPUBFUN unsigned long XMLCALL
xmlParserFindNodeInfoIndex(const xmlParserNodeInfoSeqPtr seq , xmlParserFindNodeInfoIndex(const xmlParserNodeInfoSeqPtr seq,
const xmlNodePtr node); const xmlNodePtr node);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlParserAddNodeInfo (xmlParserCtxtPtr ctxt, xmlParserAddNodeInfo (xmlParserCtxtPtr ctxt,
const xmlParserNodeInfoPtr info); const xmlParserNodeInfoPtr info);
/* /*
* External entities handling actually implemented in xmlIO. * External entities handling actually implemented in xmlIO.
*/ */
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlSetExternalEntityLoader(xmlExternalEntityLoader f); xmlSetExternalEntityLoader(xmlExternalEntityLoader f);
XMLPUBFUN xmlExternalEntityLoader XMLCALL XMLPUBFUN xmlExternalEntityLoader XMLCALL
xmlGetExternalEntityLoader(void); xmlGetExternalEntityLoader(void);
XMLPUBFUN xmlParserInputPtr XMLCALL XMLPUBFUN xmlParserInputPtr XMLCALL
xmlLoadExternalEntity (const char *URL, xmlLoadExternalEntity (const char *URL,
const char *ID, const char *ID,
xmlParserCtxtPtr ctxt); xmlParserCtxtPtr ctxt);
/* /*
* Index lookup, actually implemented in the encoding module * Index lookup, actually implemented in the encoding module
*/ */
XMLPUBFUN long XMLCALL XMLPUBFUN long XMLCALL
xmlByteConsumed (xmlParserCtxtPtr ctxt); xmlByteConsumed (xmlParserCtxtPtr ctxt);
/* /*
* New set of simpler/more flexible APIs * New set of simpler/more flexible APIs
*/ */
/** /**
* xmlParserOption: * xmlParserOption:
* *
* This is the set of XML parser options that can be passed down * This is the set of XML parser options that can be passed down
* to the xmlReadDoc() and similar calls. * to the xmlReadDoc() and similar calls.
*/ */
typedef enum { typedef enum {
XML_PARSE_RECOVER = 1<<0, /* recover on errors */ XML_PARSE_RECOVER = 1<<0, /* recover on errors */
XML_PARSE_NOENT = 1<<1, /* substitute entities */ XML_PARSE_NOENT = 1<<1, /* substitute entities */
XML_PARSE_DTDLOAD = 1<<2, /* load the external subset */ XML_PARSE_DTDLOAD = 1<<2, /* load the external subset */
XML_PARSE_DTDATTR = 1<<3, /* default DTD attributes */ XML_PARSE_DTDATTR = 1<<3, /* default DTD attributes */
XML_PARSE_DTDVALID = 1<<4, /* validate with the DTD */ XML_PARSE_DTDVALID = 1<<4, /* validate with the DTD */
XML_PARSE_NOERROR = 1<<5, /* suppress error reports */ XML_PARSE_NOERROR = 1<<5, /* suppress error reports */
XML_PARSE_NOWARNING = 1<<6, /* suppress warning reports */ XML_PARSE_NOWARNING = 1<<6, /* suppress warning reports */
XML_PARSE_PEDANTIC = 1<<7, /* pedantic error reporting */ XML_PARSE_PEDANTIC = 1<<7, /* pedantic error reporting */
XML_PARSE_NOBLANKS = 1<<8, /* remove blank nodes */ XML_PARSE_NOBLANKS = 1<<8, /* remove blank nodes */
XML_PARSE_SAX1 = 1<<9, /* use the SAX1 interface internally */ XML_PARSE_SAX1 = 1<<9, /* use the SAX1 interface internally */
XML_PARSE_XINCLUDE = 1<<10,/* Implement XInclude substitition */ XML_PARSE_XINCLUDE = 1<<10,/* Implement XInclude substitition */
XML_PARSE_NONET = 1<<11,/* Forbid network access */ XML_PARSE_NONET = 1<<11,/* Forbid network access */
XML_PARSE_NODICT = 1<<12,/* Do not reuse the context dictionnary */ XML_PARSE_NODICT = 1<<12,/* Do not reuse the context dictionnary */
XML_PARSE_NSCLEAN = 1<<13,/* remove redundant namespaces declarations XML_PARSE_NSCLEAN = 1<<13,/* remove redundant namespaces declaration
*/ s */
XML_PARSE_NOCDATA = 1<<14,/* merge CDATA as text nodes */ XML_PARSE_NOCDATA = 1<<14,/* merge CDATA as text nodes */
XML_PARSE_NOXINCNODE= 1<<15,/* do not generate XINCLUDE START/END nodes */ XML_PARSE_NOXINCNODE= 1<<15,/* do not generate XINCLUDE START/END nodes */
XML_PARSE_COMPACT = 1<<16,/* compact small text nodes; no modificatio n of XML_PARSE_COMPACT = 1<<16,/* compact small text nodes; no modificatio n of
the tree allowed afterwards (will possib ly the tree allowed afterwards (will possib ly
crash if you try to modify the tree) */ crash if you try to modify the tree) */
XML_PARSE_OLD10 = 1<<17,/* parse using XML-1.0 before update 5 */ XML_PARSE_OLD10 = 1<<17,/* parse using XML-1.0 before update 5 */
XML_PARSE_NOBASEFIX = 1<<18,/* do not fixup XINCLUDE xml:base uris */ XML_PARSE_NOBASEFIX = 1<<18,/* do not fixup XINCLUDE xml:base uris */
XML_PARSE_HUGE = 1<<19, /* relax any hardcoded limit from the pars er */ XML_PARSE_HUGE = 1<<19, /* relax any hardcoded limit from the pars er */
XML_PARSE_OLDSAX = 1<<20 /* parse using SAX2 interface from before 2 .7.0 */ XML_PARSE_OLDSAX = 1<<20 /* parse using SAX2 interface from before 2 .7.0 */
} xmlParserOption; } xmlParserOption;
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlCtxtReset (xmlParserCtxtPtr ctxt); xmlCtxtReset (xmlParserCtxtPtr ctxt);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlCtxtResetPush (xmlParserCtxtPtr ctxt, xmlCtxtResetPush (xmlParserCtxtPtr ctxt,
const char *chunk, const char *chunk,
int size, int size,
const char *filename, const char *filename,
const char *encoding); const char *encoding);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlCtxtUseOptions (xmlParserCtxtPtr ctxt, xmlCtxtUseOptions (xmlParserCtxtPtr ctxt,
int options); int options);
XMLPUBFUN xmlDocPtr XMLCALL XMLPUBFUN xmlDocPtr XMLCALL
xmlReadDoc (const xmlChar *cur, xmlReadDoc (const xmlChar *cur,
const char *URL, const char *URL,
const char *encoding, const char *encoding,
int options); int options);
XMLPUBFUN xmlDocPtr XMLCALL XMLPUBFUN xmlDocPtr XMLCALL
xmlReadFile (const char *URL, xmlReadFile (const char *URL,
const char *encoding, const char *encoding,
int options); int options);
XMLPUBFUN xmlDocPtr XMLCALL XMLPUBFUN xmlDocPtr XMLCALL
xmlReadMemory (const char *buffer, xmlReadMemory (const char *buffer,
int size, int size,
const char *URL, const char *URL,
const char *encoding, const char *encoding,
int options); int options);
XMLPUBFUN xmlDocPtr XMLCALL XMLPUBFUN xmlDocPtr XMLCALL
xmlReadFd (int fd, xmlReadFd (int fd,
const char *URL, const char *URL,
const char *encoding, const char *encoding,
int options); int options);
XMLPUBFUN xmlDocPtr XMLCALL XMLPUBFUN xmlDocPtr XMLCALL
xmlReadIO (xmlInputReadCallback ioread, xmlReadIO (xmlInputReadCallback ioread,
xmlInputCloseCallback ioclose, xmlInputCloseCallback ioclose,
void *ioctx, void *ioctx,
const char *URL, const char *URL,
const char *encoding, const char *encoding,
int options); int options);
XMLPUBFUN xmlDocPtr XMLCALL XMLPUBFUN xmlDocPtr XMLCALL
xmlCtxtReadDoc (xmlParserCtxtPtr ctxt, xmlCtxtReadDoc (xmlParserCtxtPtr ctxt,
const xmlChar *cur, const xmlChar *cur,
const char *URL, const char *URL,
const char *encoding, const char *encoding,
int options); int options);
XMLPUBFUN xmlDocPtr XMLCALL XMLPUBFUN xmlDocPtr XMLCALL
xmlCtxtReadFile (xmlParserCtxtPtr ctxt, xmlCtxtReadFile (xmlParserCtxtPtr ctxt,
const char *filename, const char *filename,
const char *encoding, const char *encoding,
int options); int options);
XMLPUBFUN xmlDocPtr XMLCALL XMLPUBFUN xmlDocPtr XMLCALL
xmlCtxtReadMemory (xmlParserCtxtPtr ctxt, xmlCtxtReadMemory (xmlParserCtxtPtr ctxt,
const char *buffer, const char *buffer,
int size, int size,
const char *URL, const char *URL,
const char *encoding, const char *encoding,
int options); int options);
XMLPUBFUN xmlDocPtr XMLCALL XMLPUBFUN xmlDocPtr XMLCALL
xmlCtxtReadFd (xmlParserCtxtPtr ctxt, xmlCtxtReadFd (xmlParserCtxtPtr ctxt,
int fd, int fd,
const char *URL, const char *URL,
const char *encoding, const char *encoding,
int options); int options);
XMLPUBFUN xmlDocPtr XMLCALL XMLPUBFUN xmlDocPtr XMLCALL
xmlCtxtReadIO (xmlParserCtxtPtr ctxt, xmlCtxtReadIO (xmlParserCtxtPtr ctxt,
xmlInputReadCallback ioread, xmlInputReadCallback ioread,
xmlInputCloseCallback ioclose, xmlInputCloseCallback ioclose,
void *ioctx, void *ioctx,
const char *URL, const char *URL,
const char *encoding, const char *encoding,
int options); int options);
/* /*
* Library wide options * Library wide options
*/ */
/** /**
* xmlFeature: * xmlFeature:
* *
* Used to examine the existance of features that can be enabled * Used to examine the existance of features that can be enabled
* or disabled at compile-time. * or disabled at compile-time.
* They used to be called XML_FEATURE_xxx but this clashed with Expat * They used to be called XML_FEATURE_xxx but this clashed with Expat
skipping to change at line 1222 skipping to change at line 1222
XML_WITH_REGEXP = 22, XML_WITH_REGEXP = 22,
XML_WITH_AUTOMATA = 23, XML_WITH_AUTOMATA = 23,
XML_WITH_EXPR = 24, XML_WITH_EXPR = 24,
XML_WITH_SCHEMAS = 25, XML_WITH_SCHEMAS = 25,
XML_WITH_SCHEMATRON = 26, XML_WITH_SCHEMATRON = 26,
XML_WITH_MODULES = 27, XML_WITH_MODULES = 27,
XML_WITH_DEBUG = 28, XML_WITH_DEBUG = 28,
XML_WITH_DEBUG_MEM = 29, XML_WITH_DEBUG_MEM = 29,
XML_WITH_DEBUG_RUN = 30, XML_WITH_DEBUG_RUN = 30,
XML_WITH_ZLIB = 31, XML_WITH_ZLIB = 31,
XML_WITH_ICU = 32,
XML_WITH_NONE = 99999 /* just to be sure of allocation size */ XML_WITH_NONE = 99999 /* just to be sure of allocation size */
} xmlFeature; } xmlFeature;
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlHasFeature (xmlFeature feature); xmlHasFeature (xmlFeature feature);
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif
#endif /* __XML_PARSER_H__ */ #endif /* __XML_PARSER_H__ */
 End of changes. 87 change blocks. 
315 lines changed or deleted 313 lines changed or added


 pattern.h   pattern.h 
skipping to change at line 40 skipping to change at line 40
typedef xmlPattern *xmlPatternPtr; typedef xmlPattern *xmlPatternPtr;
/** /**
* xmlPatternFlags: * xmlPatternFlags:
* *
* This is the set of options affecting the behaviour of pattern * This is the set of options affecting the behaviour of pattern
* matching with this module * matching with this module
* *
*/ */
typedef enum { typedef enum {
XML_PATTERN_DEFAULT = 0, /* simple pattern match */ XML_PATTERN_DEFAULT = 0, /* simple pattern match */
XML_PATTERN_XPATH = 1<<0, /* standard XPath pattern */ XML_PATTERN_XPATH = 1<<0, /* standard XPath pattern */
XML_PATTERN_XSSEL = 1<<1, /* XPath subset for schema selector XML_PATTERN_XSSEL = 1<<1, /* XPath subset for schema selector
*/ */
XML_PATTERN_XSFIELD = 1<<2 /* XPath subset for schema f XML_PATTERN_XSFIELD = 1<<2 /* XPath subset for schema field *
ield */ /
} xmlPatternFlags; } xmlPatternFlags;
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlFreePattern (xmlPatternPtr comp); xmlFreePattern (xmlPatternPtr comp);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlFreePatternList (xmlPatternPtr comp); xmlFreePatternList (xmlPatternPtr comp);
XMLPUBFUN xmlPatternPtr XMLCALL XMLPUBFUN xmlPatternPtr XMLCALL
xmlPatterncompile (const xmlChar *pattern, xmlPatterncompile (const xmlChar *pattern,
xmlDict *dict, xmlDict *dict,
int flags, int flags,
const xmlChar **namespaces) const xmlChar **namespaces);
;
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlPatternMatch (xmlPatternPtr comp, xmlPatternMatch (xmlPatternPtr comp,
xmlNodePtr node); xmlNodePtr node);
/* streaming interfaces */ /* streaming interfaces */
typedef struct _xmlStreamCtxt xmlStreamCtxt; typedef struct _xmlStreamCtxt xmlStreamCtxt;
typedef xmlStreamCtxt *xmlStreamCtxtPtr; typedef xmlStreamCtxt *xmlStreamCtxtPtr;
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlPatternStreamable (xmlPatternPtr comp); xmlPatternStreamable (xmlPatternPtr comp);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlPatternMaxDepth (xmlPatternPtr comp); xmlPatternMaxDepth (xmlPatternPtr comp);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlPatternMinDepth (xmlPatternPtr comp); xmlPatternMinDepth (xmlPatternPtr comp);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlPatternFromRoot (xmlPatternPtr comp); xmlPatternFromRoot (xmlPatternPtr comp);
XMLPUBFUN xmlStreamCtxtPtr XMLCALL XMLPUBFUN xmlStreamCtxtPtr XMLCALL
xmlPatternGetStreamCtxt (xmlPatternPtr comp); xmlPatternGetStreamCtxt (xmlPatternPtr comp);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlFreeStreamCtxt (xmlStreamCtxtPtr stream); xmlFreeStreamCtxt (xmlStreamCtxtPtr stream);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlStreamPushNode (xmlStreamCtxtPtr stream, xmlStreamPushNode (xmlStreamCtxtPtr stream,
const xmlChar *name, const xmlChar *name,
const xmlChar *ns, const xmlChar *ns,
int nodeType); int nodeType);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlStreamPush (xmlStreamCtxtPtr stream, xmlStreamPush (xmlStreamCtxtPtr stream,
const xmlChar *name, const xmlChar *name,
const xmlChar *ns); const xmlChar *ns);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlStreamPushAttr (xmlStreamCtxtPtr stream, xmlStreamPushAttr (xmlStreamCtxtPtr stream,
const xmlChar *name, const xmlChar *name,
const xmlChar *ns); const xmlChar *ns);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlStreamPop (xmlStreamCtxtPtr stream); xmlStreamPop (xmlStreamCtxtPtr stream);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlStreamWantsAnyNode (xmlStreamCtxtPtr stream); xmlStreamWantsAnyNode (xmlStreamCtxtPtr stream);
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif
#endif /* LIBXML_PATTERN_ENABLED */ #endif /* LIBXML_PATTERN_ENABLED */
#endif /* __XML_PATTERN_H__ */ #endif /* __XML_PATTERN_H__ */
 End of changes. 16 change blocks. 
33 lines changed or deleted 32 lines changed or added


 platform.h   platform.h 
skipping to change at line 31 skipping to change at line 31
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
*************************************************************************** */ *************************************************************************** */
#ifndef __PLATFORM_H__ #ifndef __PLATFORM_H__
#define __PLATFORM_H__ #define __PLATFORM_H__
#include "CCThread.h" #include "CCThread.h"
#include "CCPlatformMacros.h" #include "CCPlatformMacros.h"
NS_CC_BEGIN; NS_CC_BEGIN
/**
* @addtogroup platform
* @{
*/
struct CC_DLL cc_timeval struct CC_DLL cc_timeval
{ {
long tv_sec; // seconds long tv_sec; // seconds
long tv_usec; // microSeconds long tv_usec; // microSeconds
}; };
class CC_DLL CCTime class CC_DLL CCTime
{ {
public: public:
static int gettimeofdayCocos2d(struct cc_timeval *tp, void *tzp); static int gettimeofdayCocos2d(struct cc_timeval *tp, void *tzp);
static void timersubCocos2d(struct cc_timeval *out, struct cc_timeval * start, struct cc_timeval *end); static double timersubCocos2d(struct cc_timeval *start, struct cc_timev al *end);
}; };
NS_CC_END; // end of platform group
/// @}
NS_CC_END
#endif // __PLATFORM_H__ #endif // __PLATFORM_H__
 End of changes. 4 change blocks. 
5 lines changed or deleted 13 lines changed or added


 png.h   png.h 
/* png.h - header file for PNG reference library /* png.h - header file for PNG reference library
* *
* libpng version 1.4.5 - December 9, 2010 * libpng version 1.4.8 - July 7, 2011
* Copyright (c) 1998-2010 Glenn Randers-Pehrson * Copyright (c) 1998-2011 Glenn Randers-Pehrson
* (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger) * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
* (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc. ) * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc. )
* *
* This code is released under the libpng license (See LICENSE, below) * This code is released under the libpng license (See LICENSE, below)
* *
* Authors and maintainers: * Authors and maintainers:
* libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalna t * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalna t
* libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilge r * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilge r
* libpng versions 0.97, January 1998, through 1.4.5 - December 9, 2010: G lenn * libpng versions 0.97, January 1998, through 1.4.8 - July 7, 2011: Glenn
* See also "Contributing Authors", below. * See also "Contributing Authors", below.
* *
* Note about libpng version numbers: * Note about libpng version numbers:
* *
* Due to various miscommunications, unforeseen code incompatibilities * Due to various miscommunications, unforeseen code incompatibilities
* and occasional factors outside the authors' control, version numberin g * and occasional factors outside the authors' control, version numberin g
* on the library has not always been consistent and straightforward. * on the library has not always been consistent and straightforward.
* The following table summarizes matters since version 0.89c, which was * The following table summarizes matters since version 0.89c, which was
* the first widely used release: * the first widely used release:
* *
skipping to change at line 156 skipping to change at line 156
* 1.4.3rc01-03 14 10403 14.so.14.3[.0] * 1.4.3rc01-03 14 10403 14.so.14.3[.0]
* 1.4.3 14 10403 14.so.14.3[.0] * 1.4.3 14 10403 14.so.14.3[.0]
* 1.4.4beta01-08 14 10404 14.so.14.4[.0] * 1.4.4beta01-08 14 10404 14.so.14.4[.0]
* 1.4.4rc01-05 14 10404 14.so.14.4[.0] * 1.4.4rc01-05 14 10404 14.so.14.4[.0]
* 1.4.4 14 10404 14.so.14.4[.0] * 1.4.4 14 10404 14.so.14.4[.0]
* 1.4.5beta01-04 14 10405 14.so.14.5[.0] * 1.4.5beta01-04 14 10405 14.so.14.5[.0]
* 1.4.5rc01 14 10405 14.so.14.5[.0] * 1.4.5rc01 14 10405 14.so.14.5[.0]
* 1.4.5beta05-07 14 10405 14.so.14.5[.0] * 1.4.5beta05-07 14 10405 14.so.14.5[.0]
* 1.4.5rc02-03 14 10405 14.so.14.5[.0] * 1.4.5rc02-03 14 10405 14.so.14.5[.0]
* 1.4.5 14 10405 14.so.14.5[.0] * 1.4.5 14 10405 14.so.14.5[.0]
* 1.4.6beta01-07 14 10406 14.so.14.6[.0]
* 1.4.6rc01 14 10406 14.so.14.6[.0]
* 1.4.6 14 10406 14.so.14.6[.0]
* 1.4.7rc01 14 10407 14.so.14.7[.0]
* 1.4.7 14 10407 14.so.14.7[.0]
* 1.4.8beta01-05 14 10408 14.so.14.8[.0]
* 1.4.8rc01 14 10408 14.so.14.8[.0]
* 1.4.8 14 10408 14.so.14.8[.0]
* *
* Henceforth the source version will match the shared-library major * Henceforth the source version will match the shared-library major
* and minor numbers; the shared-library major version number will be * and minor numbers; the shared-library major version number will be
* used for changes in backward compatibility, as it is intended. The * used for changes in backward compatibility, as it is intended. The
* PNG_LIBPNG_VER macro, which is not used within libpng but is availabl e * PNG_LIBPNG_VER macro, which is not used within libpng but is availabl e
* for applications, is an unsigned integer of the form xyyzz correspond ing * for applications, is an unsigned integer of the form xyyzz correspond ing
* to the source version x.y.z (leading zeros in y and z). Beta version s * to the source version x.y.z (leading zeros in y and z). Beta version s
* were given the previous public release number plus a letter, until * were given the previous public release number plus a letter, until
* version 1.0.6j; from then on they were given the upcoming public * version 1.0.6j; from then on they were given the upcoming public
* release number plus "betaNN" or "rcN". * release number plus "betaNN" or "rcN".
skipping to change at line 187 skipping to change at line 195
*/ */
/* /*
* COPYRIGHT NOTICE, DISCLAIMER, and LICENSE: * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
* *
* If you modify libpng you may insert additional notices immediately follo wing * If you modify libpng you may insert additional notices immediately follo wing
* this sentence. * this sentence.
* *
* This code is released under the libpng license. * This code is released under the libpng license.
* *
* libpng versions 1.2.6, August 15, 2004, through 1.4.5, December 9, 2010, are * libpng versions 1.2.6, August 15, 2004, through 1.4.8, July 7, 2011, are
* Copyright (c) 2004, 2006-2010 Glenn Randers-Pehrson, and are * Copyright (c) 2004, 2006-2010 Glenn Randers-Pehrson, and are
* distributed according to the same disclaimer and license as libpng-1.2.5 * distributed according to the same disclaimer and license as libpng-1.2.5
* with the following individual added to the list of Contributing Authors: * with the following individual added to the list of Contributing Authors:
* *
* Cosmin Truta * Cosmin Truta
* *
* libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
* Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
* distributed according to the same disclaimer and license as libpng-1.0.6 * distributed according to the same disclaimer and license as libpng-1.0.6
* with the following individuals added to the list of Contributing Authors : * with the following individuals added to the list of Contributing Authors :
skipping to change at line 299 skipping to change at line 307
* with testing, bug fixes, and patience. This wouldn't have been * with testing, bug fixes, and patience. This wouldn't have been
* possible without all of you. * possible without all of you.
* *
* Thanks to Frank J. T. Wojcik for helping with the documentation. * Thanks to Frank J. T. Wojcik for helping with the documentation.
*/ */
/* /*
* Y2K compliance in libpng: * Y2K compliance in libpng:
* ========================= * =========================
* *
* December 9, 2010 * July 7, 2011
* *
* Since the PNG Development group is an ad-hoc body, we can't make * Since the PNG Development group is an ad-hoc body, we can't make
* an official declaration. * an official declaration.
* *
* This is your unofficial assurance that libpng from version 0.71 and * This is your unofficial assurance that libpng from version 0.71 and
* upward through 1.4.5 are Y2K compliant. It is my belief that earlier * upward through 1.4.8 are Y2K compliant. It is my belief that earlier
* versions were also Y2K compliant. * versions were also Y2K compliant.
* *
* Libpng only has three year fields. One is a 2-byte unsigned integer * Libpng only has three year fields. One is a 2-byte unsigned integer
* that will hold years up to 65535. The other two hold the date in tex t * that will hold years up to 65535. The other two hold the date in tex t
* format, and will hold years up to 9999. * format, and will hold years up to 9999.
* *
* The integer is * The integer is
* "png_uint_16 year" in png_time_struct. * "png_uint_16 year" in png_time_struct.
* *
* The strings are * The strings are
skipping to change at line 361 skipping to change at line 369
#ifndef PNG_H #ifndef PNG_H
#define PNG_H #define PNG_H
/* This is not the place to learn how to use libpng. The file libpng.txt /* This is not the place to learn how to use libpng. The file libpng.txt
* describes how to use libpng, and the file example.c summarizes it * describes how to use libpng, and the file example.c summarizes it
* with some code on which to build. This file is useful for looking * with some code on which to build. This file is useful for looking
* at the actual function definitions and structure components. * at the actual function definitions and structure components.
*/ */
/* Version information for png.h - this should match the version in png.c * / /* Version information for png.h - this should match the version in png.c * /
#define PNG_LIBPNG_VER_STRING "1.4.5" #define PNG_LIBPNG_VER_STRING "1.4.8"
#define PNG_HEADER_VERSION_STRING \ #define PNG_HEADER_VERSION_STRING \
" libpng version 1.4.5 - December 9, 2010\n" " libpng version 1.4.8 - July 7, 2011\n"
#define PNG_LIBPNG_VER_SONUM 14 #define PNG_LIBPNG_VER_SONUM 14
#define PNG_LIBPNG_VER_DLLNUM 14 #define PNG_LIBPNG_VER_DLLNUM 14
/* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */ /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
#define PNG_LIBPNG_VER_MAJOR 1 #define PNG_LIBPNG_VER_MAJOR 1
#define PNG_LIBPNG_VER_MINOR 4 #define PNG_LIBPNG_VER_MINOR 4
#define PNG_LIBPNG_VER_RELEASE 5 #define PNG_LIBPNG_VER_RELEASE 8
/* This should match the numeric part of the final component of /* This should match the numeric part of the final component of
* PNG_LIBPNG_VER_STRING, omitting any leading zero: * PNG_LIBPNG_VER_STRING, omitting any leading zero:
*/ */
#define PNG_LIBPNG_VER_BUILD 0 #define PNG_LIBPNG_VER_BUILD 0
/* Release Status */ /* Release Status */
#define PNG_LIBPNG_BUILD_ALPHA 1 #define PNG_LIBPNG_BUILD_ALPHA 1
#define PNG_LIBPNG_BUILD_BETA 2 #define PNG_LIBPNG_BUILD_BETA 2
#define PNG_LIBPNG_BUILD_RC 3 #define PNG_LIBPNG_BUILD_RC 3
skipping to change at line 401 skipping to change at line 409
PNG_LIBPNG_BUILD_PRIVATE */ PNG_LIBPNG_BUILD_PRIVATE */
#define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_BETA #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_BETA
/* Careful here. At one time, Guy wanted to use 082, but that would be oct al. /* Careful here. At one time, Guy wanted to use 082, but that would be oct al.
* We must not include leading zeros. * We must not include leading zeros.
* Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
* version 1.0.0 was mis-numbered 100 instead of 10000). From * version 1.0.0 was mis-numbered 100 instead of 10000). From
* version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release
*/ */
#define PNG_LIBPNG_VER 10405 /* 1.4.5 */ #define PNG_LIBPNG_VER 10408 /* 1.4.8 */
#ifndef PNG_VERSION_INFO_ONLY #ifndef PNG_VERSION_INFO_ONLY
/* Include the compression library's header */ /* Include the compression library's header */
#include "zlib.h" #include "zlib.h"
#endif #endif
/* Include all user configurable info, including optional assembler routine s */ /* Include all user configurable info, including optional assembler routine s */
#include "pngconf.h" #include "pngconf.h"
/* /*
skipping to change at line 908 skipping to change at line 916
png_fixed_point int_y_red PNG_DEPSTRUCT; png_fixed_point int_y_red PNG_DEPSTRUCT;
png_fixed_point int_x_green PNG_DEPSTRUCT; png_fixed_point int_x_green PNG_DEPSTRUCT;
png_fixed_point int_y_green PNG_DEPSTRUCT; png_fixed_point int_y_green PNG_DEPSTRUCT;
png_fixed_point int_x_blue PNG_DEPSTRUCT; png_fixed_point int_x_blue PNG_DEPSTRUCT;
png_fixed_point int_y_blue PNG_DEPSTRUCT; png_fixed_point int_y_blue PNG_DEPSTRUCT;
#endif #endif
} png_info; } png_info;
typedef png_info FAR * png_infop; typedef png_info FAR * png_infop;
typedef PNG_CONST png_info FAR * png_const_infop;
typedef png_info FAR * FAR * png_infopp; typedef png_info FAR * FAR * png_infopp;
/* Maximum positive integer used in PNG is (2^31)-1 */ /* Maximum positive integer used in PNG is (2^31)-1 */
#define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL) #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
#define PNG_UINT_32_MAX ((png_uint_32)(-1)) #define PNG_UINT_32_MAX ((png_uint_32)(-1))
#define PNG_SIZE_MAX ((png_size_t)(-1)) #define PNG_SIZE_MAX ((png_size_t)(-1))
/* These describe the color_type field in png_info. */ /* These describe the color_type field in png_info. */
/* color type masks */ /* color type masks */
#define PNG_COLOR_MASK_PALETTE 1 #define PNG_COLOR_MASK_PALETTE 1
skipping to change at line 1028 skipping to change at line 1037
typedef png_row_info FAR * FAR * png_row_infopp; typedef png_row_info FAR * FAR * png_row_infopp;
/* These are the function types for the I/O functions and for the functions /* These are the function types for the I/O functions and for the functions
* that allow the user to override the default I/O functions with his or he r * that allow the user to override the default I/O functions with his or he r
* own. The png_error_ptr type should match that of user-supplied warning * own. The png_error_ptr type should match that of user-supplied warning
* and error functions, while the png_rw_ptr type should match that of the * and error functions, while the png_rw_ptr type should match that of the
* user read/write data functions. * user read/write data functions.
*/ */
typedef struct png_struct_def png_struct; typedef struct png_struct_def png_struct;
typedef png_struct FAR * png_structp; typedef png_struct FAR * png_structp;
typedef PNG_CONST png_struct FAR * png_const_structp;
typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp)) ; typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp)) ;
typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_ t)); typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_ t));
typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp)); typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32 , typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32 ,
int)); int));
typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_3 2, typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_3 2,
int)); int));
#ifdef PNG_PROGRESSIVE_READ_SUPPORTED #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
skipping to change at line 1484 skipping to change at line 1494
#ifdef PNG_IO_STATE_SUPPORTED #ifdef PNG_IO_STATE_SUPPORTED
/* New member added in libpng-1.4.0 */ /* New member added in libpng-1.4.0 */
png_uint_32 io_state PNG_DEPSTRUCT; png_uint_32 io_state PNG_DEPSTRUCT;
#endif #endif
}; };
/* This triggers a compiler error in png.c, if png.c and png.h /* This triggers a compiler error in png.c, if png.c and png.h
* do not agree upon the version number. * do not agree upon the version number.
*/ */
typedef png_structp version_1_4_5; typedef png_structp version_1_4_8;
typedef png_struct FAR * FAR * png_structpp; typedef png_struct FAR * FAR * png_structpp;
/* Here are the function definitions most commonly used. This is not /* Here are the function definitions most commonly used. This is not
* the place to find out how to use libpng. See libpng.txt for the * the place to find out how to use libpng. See libpng.txt for the
* full explanation, see example.c for the summary. This just provides * full explanation, see example.c for the summary. This just provides
* a simple one line description of the use of each function. * a simple one line description of the use of each function.
*/ */
/* Returns the version number of the library */ /* Returns the version number of the library */
skipping to change at line 1527 skipping to change at line 1537
PNG_EXPORT(png_structp,png_create_read_struct) PNG_EXPORT(png_structp,png_create_read_struct)
PNGARG((png_const_charp user_png_ver, png_voidp error_ptr, PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
png_error_ptr error_fn, png_error_ptr warn_fn)) PNG_ALLOCATED; png_error_ptr error_fn, png_error_ptr warn_fn)) PNG_ALLOCATED;
/* Allocate and initialize png_ptr struct for writing, and any other memory */ /* Allocate and initialize png_ptr struct for writing, and any other memory */
PNG_EXPORT(png_structp,png_create_write_struct) PNG_EXPORT(png_structp,png_create_write_struct)
PNGARG((png_const_charp user_png_ver, png_voidp error_ptr, PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
png_error_ptr error_fn, png_error_ptr warn_fn)) PNG_ALLOCATED; png_error_ptr error_fn, png_error_ptr warn_fn)) PNG_ALLOCATED;
PNG_EXPORT(png_size_t,png_get_compression_buffer_size) PNG_EXPORT(png_size_t,png_get_compression_buffer_size)
PNGARG((png_structp png_ptr)); PNGARG((png_const_structp png_ptr));
PNG_EXPORT(void,png_set_compression_buffer_size) PNG_EXPORT(void,png_set_compression_buffer_size)
PNGARG((png_structp png_ptr, png_size_t size)); PNGARG((png_structp png_ptr, png_size_t size));
/* Moved from pngconf.h in 1.4.0 and modified to ensure setjmp/longjmp /* Moved from pngconf.h in 1.4.0 and modified to ensure setjmp/longjmp
* match up. * match up.
*/ */
#ifdef PNG_SETJMP_SUPPORTED #ifdef PNG_SETJMP_SUPPORTED
/* This function returns the jmp_buf built in to *png_ptr. It must be /* This function returns the jmp_buf built in to *png_ptr. It must be
* supplied with an appropriate 'longjmp' function to use on that jmp_buf * supplied with an appropriate 'longjmp' function to use on that jmp_buf
skipping to change at line 1649 skipping to change at line 1659
#endif #endif
#ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
/* Reduce RGB to grayscale. */ /* Reduce RGB to grayscale. */
#ifdef PNG_FLOATING_POINT_SUPPORTED #ifdef PNG_FLOATING_POINT_SUPPORTED
PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr, PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
int error_action, double red, double green )); int error_action, double red, double green ));
#endif #endif
PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr, PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
int error_action, png_fixed_point red, png_fixed_point green )); int error_action, png_fixed_point red, png_fixed_point green ));
PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_const_structp
png_ptr)); png_ptr));
#endif #endif
PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth, PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
png_colorp palette)); png_colorp palette));
#ifdef PNG_READ_STRIP_ALPHA_SUPPORTED #ifdef PNG_READ_STRIP_ALPHA_SUPPORTED
PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr)); PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
#endif #endif
skipping to change at line 1970 skipping to change at line 1980
* write and use replacement functions. The replacement error_fn should * write and use replacement functions. The replacement error_fn should
* still do a longjmp to the last setjmp location if you are using this * still do a longjmp to the last setjmp location if you are using this
* method of error handling. If error_fn or warning_fn is NULL, the * method of error handling. If error_fn or warning_fn is NULL, the
* default function will be used. * default function will be used.
*/ */
PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr, PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn)); png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
/* Return the user pointer associated with the error functions */ /* Return the user pointer associated with the error functions */
PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr)); PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_const_structp png_ptr)) ;
/* Replace the default data output functions with a user supplied one(s). /* Replace the default data output functions with a user supplied one(s).
* If buffered output is not used, then output_flush_fn can be set to NULL. * If buffered output is not used, then output_flush_fn can be set to NULL.
* If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
* output_flush_fn will be ignored (and thus can be NULL). * output_flush_fn will be ignored (and thus can be NULL).
* It is probably a mistake to use NULL for output_flush_fn if * It is probably a mistake to use NULL for output_flush_fn if
* write_data_fn is not also NULL unless you have built libpng with * write_data_fn is not also NULL unless you have built libpng with
* PNG_WRITE_FLUSH_SUPPORTED undefined, because in this case libpng's * PNG_WRITE_FLUSH_SUPPORTED undefined, because in this case libpng's
* default flush function, which uses the standard *FILE structure, will * default flush function, which uses the standard *FILE structure, will
* be used. * be used.
skipping to change at line 2003 skipping to change at line 2013
png_read_status_ptr read_row_fn)); png_read_status_ptr read_row_fn));
PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr, PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
png_write_status_ptr write_row_fn)); png_write_status_ptr write_row_fn));
#ifdef PNG_USER_MEM_SUPPORTED #ifdef PNG_USER_MEM_SUPPORTED
/* Replace the default memory allocation functions with user supplied one(s ). */ /* Replace the default memory allocation functions with user supplied one(s ). */
PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr, PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn)); png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
/* Return the user pointer associated with the memory functions */ /* Return the user pointer associated with the memory functions */
PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr)); PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_const_structp png_ptr));
#endif #endif
#ifdef PNG_READ_USER_TRANSFORM_SUPPORTED #ifdef PNG_READ_USER_TRANSFORM_SUPPORTED
PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
png_ptr, png_user_transform_ptr read_user_transform_fn)); png_ptr, png_user_transform_ptr read_user_transform_fn));
#endif #endif
#ifdef PNG_WRITE_USER_TRANSFORM_SUPPORTED #ifdef PNG_WRITE_USER_TRANSFORM_SUPPORTED
PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
png_ptr, png_user_transform_ptr write_user_transform_fn)); png_ptr, png_user_transform_ptr write_user_transform_fn));
#endif #endif
#if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \ #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
png_ptr, png_voidp user_transform_ptr, int user_transform_depth, png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
int user_transform_channels)); int user_transform_channels));
/* Return the user pointer associated with the user transform functions */ /* Return the user pointer associated with the user transform functions */
PNG_EXPORT(png_voidp,png_get_user_transform_ptr) PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
PNGARG((png_structp png_ptr)); PNGARG((png_const_structp png_ptr));
#endif #endif
#ifdef PNG_USER_CHUNKS_SUPPORTED #ifdef PNG_USER_CHUNKS_SUPPORTED
PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr, PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn)); png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_const_structp
png_ptr)); png_ptr));
#endif #endif
#ifdef PNG_PROGRESSIVE_READ_SUPPORTED #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
/* Sets the function callbacks for the push reader, and a pointer to a /* Sets the function callbacks for the push reader, and a pointer to a
* user-defined structure available to the callback functions. * user-defined structure available to the callback functions.
*/ */
PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr, PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
png_voidp progressive_ptr, png_voidp progressive_ptr,
png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn, png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
png_progressive_end_ptr end_fn)); png_progressive_end_ptr end_fn));
/* Returns the user pointer associated with the push read functions */ /* Returns the user pointer associated with the push read functions */
PNG_EXPORT(png_voidp,png_get_progressive_ptr) PNG_EXPORT(png_voidp,png_get_progressive_ptr)
PNGARG((png_structp png_ptr)); PNGARG((png_const_structp png_ptr));
/* Function to be called when data becomes available */ /* Function to be called when data becomes available */
PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr, PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
png_infop info_ptr, png_bytep buffer, png_size_t buffer_size)); png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
/* Function that combines rows. Not very much different than the /* Function that combines rows. Not very much different than the
* png_combine_row() call. Is this even used????? * png_combine_row() call. Is this even used?????
*/ */
PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr, PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
png_bytep old_row, png_bytep new_row)); png_bytep old_row, png_bytep new_row));
skipping to change at line 2152 skipping to change at line 2162
* setting pointers into the png_info_struct where the data is stored. The * setting pointers into the png_info_struct where the data is stored. The
* png_get_<chunk> functions return a non-zero value if the data was availa ble * png_get_<chunk> functions return a non-zero value if the data was availa ble
* in info_ptr, or return zero and do not change any of the parameters if t he * in info_ptr, or return zero and do not change any of the parameters if t he
* data was not available. * data was not available.
* *
* These functions should be used instead of directly accessing png_info * These functions should be used instead of directly accessing png_info
* to avoid problems with future changes in the size and internal layout of * to avoid problems with future changes in the size and internal layout of
* png_info_struct. * png_info_struct.
*/ */
/* Returns "flag" if chunk data is valid in info_ptr. */ /* Returns "flag" if chunk data is valid in info_ptr. */
PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr, PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_const_structp png_ptr,
png_infop info_ptr, png_uint_32 flag)); png_const_infop info_ptr, png_uint_32 flag));
/* Returns number of bytes needed to hold a transformed row. */ /* Returns number of bytes needed to hold a transformed row. */
PNG_EXPORT(png_size_t,png_get_rowbytes) PNGARG((png_structp png_ptr, PNG_EXPORT(png_size_t,png_get_rowbytes) PNGARG((png_const_structp png_ptr,
png_infop info_ptr)); png_const_infop info_ptr));
#ifdef PNG_INFO_IMAGE_SUPPORTED #ifdef PNG_INFO_IMAGE_SUPPORTED
/* Returns row_pointers, which is an array of pointers to scanlines that wa s /* Returns row_pointers, which is an array of pointers to scanlines that wa s
* returned from png_read_png(). * returned from png_read_png().
*/ */
PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr, PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_const_structp png_ptr,
png_infop info_ptr)); png_const_infop info_ptr));
/* Set row_pointers, which is an array of pointers to scanlines for use /* Set row_pointers, which is an array of pointers to scanlines for use
* by png_write_png(). * by png_write_png().
*/ */
PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr, PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
png_infop info_ptr, png_bytepp row_pointers)); png_infop info_ptr, png_bytepp row_pointers));
#endif #endif
/* Returns number of color channels in image. */ /* Returns number of color channels in image. */
PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr, PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_const_structp png_ptr,
png_infop info_ptr)); png_const_infop info_ptr));
#ifdef PNG_EASY_ACCESS_SUPPORTED #ifdef PNG_EASY_ACCESS_SUPPORTED
/* Returns image width in pixels. */ /* Returns image width in pixels. */
PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_const_structp
png_ptr, png_infop info_ptr)); png_ptr, png_const_infop info_ptr));
/* Returns image height in pixels. */ /* Returns image height in pixels. */
PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_const_structp
png_ptr, png_infop info_ptr)); png_ptr, png_const_infop info_ptr));
/* Returns image bit_depth. */ /* Returns image bit_depth. */
PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_const_structp
png_ptr, png_infop info_ptr)); png_ptr, png_const_infop info_ptr));
/* Returns image color_type. */ /* Returns image color_type. */
PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_const_structp
png_ptr, png_infop info_ptr)); png_ptr, png_const_infop info_ptr));
/* Returns image filter_type. */ /* Returns image filter_type. */
PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_const_structp
png_ptr, png_infop info_ptr)); png_ptr, png_const_infop info_ptr));
/* Returns image interlace_type. */ /* Returns image interlace_type. */
PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_const_structp
png_ptr, png_infop info_ptr)); png_ptr, png_const_infop info_ptr));
/* Returns image compression_type. */ /* Returns image compression_type. */
PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_const_structp
png_ptr, png_infop info_ptr)); png_ptr, png_const_infop info_ptr));
/* Returns image resolution in pixels per meter, from pHYs chunk data. */ /* Returns image resolution in pixels per meter, from pHYs chunk data. */
PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_const_structp
png_ptr, png_infop info_ptr)); png_ptr, png_const_infop info_ptr));
PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_const_struc
png_ptr, png_infop info_ptr)); tp
PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp png_ptr, png_const_infop info_ptr));
png_ptr, png_infop info_ptr)); PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_const_struc
tp
png_ptr, png_const_infop info_ptr));
/* Returns pixel aspect ratio, computed from pHYs chunk data. */ /* Returns pixel aspect ratio, computed from pHYs chunk data. */
#ifdef PNG_FLOATING_POINT_SUPPORTED #ifdef PNG_FLOATING_POINT_SUPPORTED
PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_const_structp
png_ptr, png_infop info_ptr)); png_ptr, png_const_infop info_ptr));
#endif #endif
/* Returns image x, y offset in pixels or microns, from oFFs chunk data. */ /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_const_structp
png_ptr, png_infop info_ptr)); png_ptr, png_const_infop info_ptr));
PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_const_structp
png_ptr, png_infop info_ptr)); png_ptr, png_const_infop info_ptr));
PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_const_structp
png_ptr, png_infop info_ptr)); png_ptr, png_const_infop info_ptr));
PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_const_structp
png_ptr, png_infop info_ptr)); png_ptr, png_const_infop info_ptr));
#endif /* PNG_EASY_ACCESS_SUPPORTED */ #endif /* PNG_EASY_ACCESS_SUPPORTED */
/* Returns pointer to signature string read from PNG header */ /* Returns pointer to signature string read from PNG header */
PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr, PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_const_structp png_ptr,
png_infop info_ptr)); png_infop info_ptr));
#ifdef PNG_bKGD_SUPPORTED #ifdef PNG_bKGD_SUPPORTED
PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr, PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_const_structp png_ptr,
png_infop info_ptr, png_color_16p *background)); png_infop info_ptr, png_color_16p *background));
#endif #endif
#ifdef PNG_bKGD_SUPPORTED #ifdef PNG_bKGD_SUPPORTED
PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr, PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
png_infop info_ptr, png_color_16p background)); png_infop info_ptr, png_color_16p background));
#endif #endif
#ifdef PNG_cHRM_SUPPORTED #ifdef PNG_cHRM_SUPPORTED
#ifdef PNG_FLOATING_POINT_SUPPORTED #ifdef PNG_FLOATING_POINT_SUPPORTED
PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr, PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_const_structp png_ptr,
png_infop info_ptr, double *white_x, double *white_y, double *red_x, png_const_infop info_ptr, double *white_x, double *white_y, double *red_
x,
double *red_y, double *green_x, double *green_y, double *blue_x, double *red_y, double *green_x, double *green_y, double *blue_x,
double *blue_y)); double *blue_y));
#endif #endif
#ifdef PNG_FIXED_POINT_SUPPORTED #ifdef PNG_FIXED_POINT_SUPPORTED
PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr, PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_const_structp png_pt
png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point r,
png_const_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
*int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y, *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_po int png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_po int
*int_blue_x, png_fixed_point *int_blue_y)); *int_blue_x, png_fixed_point *int_blue_y));
#endif #endif
#endif #endif
#ifdef PNG_cHRM_SUPPORTED #ifdef PNG_cHRM_SUPPORTED
#ifdef PNG_FLOATING_POINT_SUPPORTED #ifdef PNG_FLOATING_POINT_SUPPORTED
PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr, PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
png_infop info_ptr, double white_x, double white_y, double red_x, png_infop info_ptr, double white_x, double white_y, double red_x,
skipping to change at line 2278 skipping to change at line 2288
PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr, PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_whi te_y, png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_whi te_y,
png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x, int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
png_fixed_point int_blue_y)); png_fixed_point int_blue_y));
#endif #endif
#endif #endif
#ifdef PNG_gAMA_SUPPORTED #ifdef PNG_gAMA_SUPPORTED
#ifdef PNG_FLOATING_POINT_SUPPORTED #ifdef PNG_FLOATING_POINT_SUPPORTED
PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr, PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_const_structp png_ptr,
png_infop info_ptr, double *file_gamma)); png_const_infop info_ptr, double *file_gamma));
#endif #endif
PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr, PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_const_structp png_pt
png_infop info_ptr, png_fixed_point *int_file_gamma)); r,
png_const_infop info_ptr, png_fixed_point *int_file_gamma));
#endif #endif
#ifdef PNG_gAMA_SUPPORTED #ifdef PNG_gAMA_SUPPORTED
#ifdef PNG_FLOATING_POINT_SUPPORTED #ifdef PNG_FLOATING_POINT_SUPPORTED
PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr, PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
png_infop info_ptr, double file_gamma)); png_infop info_ptr, double file_gamma));
#endif #endif
PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr, PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
png_infop info_ptr, png_fixed_point int_file_gamma)); png_infop info_ptr, png_fixed_point int_file_gamma));
#endif #endif
#ifdef PNG_hIST_SUPPORTED #ifdef PNG_hIST_SUPPORTED
PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr, PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_const_structp png_ptr,
png_infop info_ptr, png_uint_16p *hist)); png_const_infop info_ptr, png_uint_16p *hist));
#endif #endif
#ifdef PNG_hIST_SUPPORTED #ifdef PNG_hIST_SUPPORTED
PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr, PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
png_infop info_ptr, png_uint_16p hist)); png_infop info_ptr, png_uint_16p hist));
#endif #endif
PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr, PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
png_infop info_ptr, png_uint_32 *width, png_uint_32 *height, png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
int *bit_depth, int *color_type, int *interlace_method, int *bit_depth, int *color_type, int *interlace_method,
int *compression_method, int *filter_method)); int *compression_method, int *filter_method));
PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr, PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth , png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth ,
int color_type, int interlace_method, int compression_method, int color_type, int interlace_method, int compression_method,
int filter_method)); int filter_method));
#ifdef PNG_oFFs_SUPPORTED #ifdef PNG_oFFs_SUPPORTED
PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr, PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_const_structp png_ptr,
png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y, png_const_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
int *unit_type)); int *unit_type));
#endif #endif
#ifdef PNG_oFFs_SUPPORTED #ifdef PNG_oFFs_SUPPORTED
PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr, PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y, png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
int unit_type)); int unit_type));
#endif #endif
#ifdef PNG_pCAL_SUPPORTED #ifdef PNG_pCAL_SUPPORTED
PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr, PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_const_structp png_ptr,
png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1, png_const_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32
*X1,
int *type, int *nparams, png_charp *units, png_charpp *params)); int *type, int *nparams, png_charp *units, png_charpp *params));
#endif #endif
#ifdef PNG_pCAL_SUPPORTED #ifdef PNG_pCAL_SUPPORTED
PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr, PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1, png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
int type, int nparams, png_charp units, png_charpp params)); int type, int nparams, png_charp units, png_charpp params));
#endif #endif
#ifdef PNG_pHYs_SUPPORTED #ifdef PNG_pHYs_SUPPORTED
PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr, PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_const_structp png_ptr,
png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_ty png_const_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *u
pe)); nit_type));
#endif #endif
#ifdef PNG_pHYs_SUPPORTED #ifdef PNG_pHYs_SUPPORTED
PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr, PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type) ); png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type) );
#endif #endif
PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr, PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_const_structp png_ptr,
png_infop info_ptr, png_colorp *palette, int *num_palette)); png_const_infop info_ptr, png_colorp *palette, int *num_palette));
PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr, PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
png_infop info_ptr, png_colorp palette, int num_palette)); png_infop info_ptr, png_colorp palette, int num_palette));
#ifdef PNG_sBIT_SUPPORTED #ifdef PNG_sBIT_SUPPORTED
PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr, PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_const_structp png_ptr,
png_infop info_ptr, png_color_8p *sig_bit)); png_infop info_ptr, png_color_8p *sig_bit));
#endif #endif
#ifdef PNG_sBIT_SUPPORTED #ifdef PNG_sBIT_SUPPORTED
PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr, PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
png_infop info_ptr, png_color_8p sig_bit)); png_infop info_ptr, png_color_8p sig_bit));
#endif #endif
#ifdef PNG_sRGB_SUPPORTED #ifdef PNG_sRGB_SUPPORTED
PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr, PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_const_structp png_ptr,
png_infop info_ptr, int *intent)); png_const_infop info_ptr, int *intent));
#endif #endif
#ifdef PNG_sRGB_SUPPORTED #ifdef PNG_sRGB_SUPPORTED
PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr, PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
png_infop info_ptr, int intent)); png_infop info_ptr, int intent));
PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr, PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
png_infop info_ptr, int intent)); png_infop info_ptr, int intent));
#endif #endif
#ifdef PNG_iCCP_SUPPORTED #ifdef PNG_iCCP_SUPPORTED
PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr, PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_const_structp png_ptr,
png_infop info_ptr, png_charpp name, int *compression_type, png_const_infop info_ptr, png_charpp name, int *compression_type,
png_charpp profile, png_uint_32 *proflen)); png_charpp profile, png_uint_32 *proflen));
/* Note to maintainer: profile should be png_bytepp */ /* Note to maintainer: profile should be png_bytepp */
#endif #endif
#ifdef PNG_iCCP_SUPPORTED #ifdef PNG_iCCP_SUPPORTED
PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr, PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
png_infop info_ptr, png_charp name, int compression_type, png_infop info_ptr, png_charp name, int compression_type,
png_charp profile, png_uint_32 proflen)); png_charp profile, png_uint_32 proflen));
/* Note to maintainer: profile should be png_bytep */ /* Note to maintainer: profile should be png_bytep */
#endif #endif
#ifdef PNG_sPLT_SUPPORTED #ifdef PNG_sPLT_SUPPORTED
PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr, PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_const_structp png_ptr,
png_infop info_ptr, png_sPLT_tpp entries)); png_const_infop info_ptr, png_sPLT_tpp entries));
#endif #endif
#ifdef PNG_sPLT_SUPPORTED #ifdef PNG_sPLT_SUPPORTED
PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr, PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
png_infop info_ptr, png_sPLT_tp entries, int nentries)); png_infop info_ptr, png_sPLT_tp entries, int nentries));
#endif #endif
#ifdef PNG_TEXT_SUPPORTED #ifdef PNG_TEXT_SUPPORTED
/* png_get_text also returns the number of text chunks in *num_text */ /* png_get_text also returns the number of text chunks in *num_text */
PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr, PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_const_structp png_ptr,
png_infop info_ptr, png_textp *text_ptr, int *num_text)); png_const_infop info_ptr, png_textp *text_ptr, int *num_text));
#endif #endif
/* Note while png_set_text() will accept a structure whose text, /* Note while png_set_text() will accept a structure whose text,
* language, and translated keywords are NULL pointers, the structure * language, and translated keywords are NULL pointers, the structure
* returned by png_get_text will always contain regular * returned by png_get_text will always contain regular
* zero-terminated C strings. They might be empty strings but * zero-terminated C strings. They might be empty strings but
* they will never be NULL pointers. * they will never be NULL pointers.
*/ */
#ifdef PNG_TEXT_SUPPORTED #ifdef PNG_TEXT_SUPPORTED
PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr, PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
png_infop info_ptr, png_textp text_ptr, int num_text)); png_infop info_ptr, png_textp text_ptr, int num_text));
#endif #endif
#ifdef PNG_tIME_SUPPORTED #ifdef PNG_tIME_SUPPORTED
PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr, PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_const_structp png_ptr,
png_infop info_ptr, png_timep *mod_time)); png_infop info_ptr, png_timep *mod_time));
#endif #endif
#ifdef PNG_tIME_SUPPORTED #ifdef PNG_tIME_SUPPORTED
PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr, PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
png_infop info_ptr, png_timep mod_time)); png_infop info_ptr, png_timep mod_time));
#endif #endif
#ifdef PNG_tRNS_SUPPORTED #ifdef PNG_tRNS_SUPPORTED
PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr, PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_const_structp png_ptr,
png_infop info_ptr, png_bytep *trans_alpha, int *num_trans, png_infop info_ptr, png_bytep *trans_alpha, int *num_trans,
png_color_16p *trans_color)); png_color_16p *trans_color));
#endif #endif
#ifdef PNG_tRNS_SUPPORTED #ifdef PNG_tRNS_SUPPORTED
PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr, PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
png_infop info_ptr, png_bytep trans_alpha, int num_trans, png_infop info_ptr, png_bytep trans_alpha, int num_trans,
png_color_16p trans_color)); png_color_16p trans_color));
#endif #endif
#ifdef PNG_tRNS_SUPPORTED #ifdef PNG_tRNS_SUPPORTED
#endif #endif
#ifdef PNG_sCAL_SUPPORTED #ifdef PNG_sCAL_SUPPORTED
#ifdef PNG_FLOATING_POINT_SUPPORTED #ifdef PNG_FLOATING_POINT_SUPPORTED
PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr, PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_const_structp png_ptr,
png_infop info_ptr, int *unit, double *width, double *height)); png_const_infop info_ptr, int *unit, double *width, double *height));
#else #else
#ifdef PNG_FIXED_POINT_SUPPORTED #ifdef PNG_FIXED_POINT_SUPPORTED
PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr, PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_const_structp png_ptr,
png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight)); png_const_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheig
ht));
#endif #endif
#endif #endif
#endif /* PNG_sCAL_SUPPORTED */ #endif /* PNG_sCAL_SUPPORTED */
#ifdef PNG_sCAL_SUPPORTED #ifdef PNG_sCAL_SUPPORTED
#ifdef PNG_FLOATING_POINT_SUPPORTED #ifdef PNG_FLOATING_POINT_SUPPORTED
PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr, PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
png_infop info_ptr, int unit, double width, double height)); png_infop info_ptr, int unit, double width, double height));
#else #else
#ifdef PNG_FIXED_POINT_SUPPORTED #ifdef PNG_FIXED_POINT_SUPPORTED
skipping to change at line 2487 skipping to change at line 2497
PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
png_ptr, int keep, png_bytep chunk_list, int num_chunks)); png_ptr, int keep, png_bytep chunk_list, int num_chunks));
PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_byte p PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_byte p
chunk_name)); chunk_name));
#endif #endif
#ifdef PNG_UNKNOWN_CHUNKS_SUPPORTED #ifdef PNG_UNKNOWN_CHUNKS_SUPPORTED
PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr, PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)); png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
PNG_EXPORT(void, png_set_unknown_chunk_location) PNG_EXPORT(void, png_set_unknown_chunk_location)
PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location )); PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location ));
PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_const_structp
png_ptr, png_infop info_ptr, png_unknown_chunkpp entries)); png_ptr, png_const_infop info_ptr, png_unknown_chunkpp entries));
#endif #endif
/* Png_free_data() will turn off the "valid" flag for anything it frees. /* Png_free_data() will turn off the "valid" flag for anything it frees.
* If you need to turn it off for a chunk that your application has freed, * If you need to turn it off for a chunk that your application has freed,
* you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); * you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK);
*/ */
PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr, PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
png_infop info_ptr, int mask)); png_infop info_ptr, int mask));
#ifdef PNG_INFO_IMAGE_SUPPORTED #ifdef PNG_INFO_IMAGE_SUPPORTED
skipping to change at line 2510 skipping to change at line 2520
PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr, PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
png_infop info_ptr, png_infop info_ptr,
int transforms, int transforms,
png_voidp params)); png_voidp params));
PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr, PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
png_infop info_ptr, png_infop info_ptr,
int transforms, int transforms,
png_voidp params)); png_voidp params));
#endif #endif
PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr)); PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_const_structp png_ptr))
PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr)); ;
PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_const_structp png_ptr)
);
PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_const_structp
png_ptr)); png_ptr));
PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr)); PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_const_structp png_ptr) );
#ifdef PNG_MNG_FEATURES_SUPPORTED #ifdef PNG_MNG_FEATURES_SUPPORTED
PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
png_ptr, png_uint_32 mng_features_permitted)); png_ptr, png_uint_32 mng_features_permitted));
#endif #endif
/* For use in png_set_keep_unknown, added to version 1.2.6 */ /* For use in png_set_keep_unknown, added to version 1.2.6 */
#define PNG_HANDLE_CHUNK_AS_DEFAULT 0 #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
#define PNG_HANDLE_CHUNK_NEVER 1 #define PNG_HANDLE_CHUNK_NEVER 1
#define PNG_HANDLE_CHUNK_IF_SAFE 2 #define PNG_HANDLE_CHUNK_IF_SAFE 2
skipping to change at line 2539 skipping to change at line 2549
*/ */
#ifdef PNG_ERROR_NUMBERS_SUPPORTED #ifdef PNG_ERROR_NUMBERS_SUPPORTED
PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
png_ptr, png_uint_32 strip_mode)); png_ptr, png_uint_32 strip_mode));
#endif #endif
/* Added in libpng-1.2.6 */ /* Added in libpng-1.2.6 */
#ifdef PNG_SET_USER_LIMITS_SUPPORTED #ifdef PNG_SET_USER_LIMITS_SUPPORTED
PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max)); png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_const_structp
png_ptr)); png_ptr));
PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_const_structp
png_ptr)); png_ptr));
/* Added in libpng-1.4.0 */ /* Added in libpng-1.4.0 */
PNG_EXPORT(void,png_set_chunk_cache_max) PNGARG((png_structp PNG_EXPORT(void,png_set_chunk_cache_max) PNGARG((png_structp
png_ptr, png_uint_32 user_chunk_cache_max)); png_ptr, png_uint_32 user_chunk_cache_max));
PNG_EXPORT(png_uint_32,png_get_chunk_cache_max) PNG_EXPORT(png_uint_32,png_get_chunk_cache_max)
PNGARG((png_structp png_ptr)); PNGARG((png_const_structp png_ptr));
/* Added in libpng-1.4.1 */ /* Added in libpng-1.4.1 */
PNG_EXPORT(void,png_set_chunk_malloc_max) PNGARG((png_structp PNG_EXPORT(void,png_set_chunk_malloc_max) PNGARG((png_structp
png_ptr, png_alloc_size_t user_chunk_cache_max)); png_ptr, png_alloc_size_t user_chunk_cache_max));
PNG_EXPORT(png_alloc_size_t,png_get_chunk_malloc_max) PNG_EXPORT(png_alloc_size_t,png_get_chunk_malloc_max)
PNGARG((png_structp png_ptr)); PNGARG((png_const_structp png_ptr));
#endif #endif
#if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED) #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
PNG_EXPORT(png_uint_32,png_get_pixels_per_inch) PNGARG((png_structp png_ptr PNG_EXPORT(png_uint_32,png_get_pixels_per_inch)
, PNGARG((png_const_structp png_ptr, png_const_infop info_ptr));
png_infop info_ptr));
PNG_EXPORT(png_uint_32,png_get_x_pixels_per_inch) PNGARG((png_structp png_p PNG_EXPORT(png_uint_32,png_get_x_pixels_per_inch)
tr, PNGARG((png_const_structp png_ptr, png_const_infop info_ptr));
png_infop info_ptr));
PNG_EXPORT(png_uint_32,png_get_y_pixels_per_inch) PNGARG((png_structp png_p PNG_EXPORT(png_uint_32,png_get_y_pixels_per_inch)
tr, PNGARG((png_const_structp png_ptr, png_const_infop info_ptr));
png_infop info_ptr));
PNG_EXPORT(float,png_get_x_offset_inches) PNGARG((png_structp png_ptr, PNG_EXPORT(float,png_get_x_offset_inches) PNGARG((png_const_structp png_ptr
png_infop info_ptr)); ,
png_const_infop info_ptr));
PNG_EXPORT(float,png_get_y_offset_inches) PNGARG((png_structp png_ptr, PNG_EXPORT(float,png_get_y_offset_inches) PNGARG((png_const_structp png_ptr
png_infop info_ptr)); ,
png_const_infop info_ptr));
#ifdef PNG_pHYs_SUPPORTED #ifdef PNG_pHYs_SUPPORTED
PNG_EXPORT(png_uint_32,png_get_pHYs_dpi) PNGARG((png_structp png_ptr, PNG_EXPORT(png_uint_32,png_get_pHYs_dpi) PNGARG((png_const_structp png_ptr,
png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type) png_const_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y,
); int *unit_type));
#endif /* PNG_pHYs_SUPPORTED */ #endif /* PNG_pHYs_SUPPORTED */
#endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */ #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
/* Added in libpng-1.4.0 */ /* Added in libpng-1.4.0 */
#ifdef PNG_IO_STATE_SUPPORTED #ifdef PNG_IO_STATE_SUPPORTED
PNG_EXPORT(png_uint_32,png_get_io_state) PNGARG((png_structp png_ptr)); PNG_EXPORT(png_uint_32,png_get_io_state) PNGARG((png_const_structp png_ptr) );
PNG_EXPORT(png_bytep,png_get_io_chunk_name) PNG_EXPORT(png_bytep,png_get_io_chunk_name)
PNGARG((png_structp png_ptr)); PNGARG((png_structp png_ptr));
/* The flags returned by png_get_io_state() are the following: */ /* The flags returned by png_get_io_state() are the following: */
#define PNG_IO_NONE 0x0000 /* no I/O at this moment */ #define PNG_IO_NONE 0x0000 /* no I/O at this moment */
#define PNG_IO_READING 0x0001 /* currently reading */ #define PNG_IO_READING 0x0001 /* currently reading */
#define PNG_IO_WRITING 0x0002 /* currently writing */ #define PNG_IO_WRITING 0x0002 /* currently writing */
#define PNG_IO_SIGNATURE 0x0010 /* currently at the file signature */ #define PNG_IO_SIGNATURE 0x0010 /* currently at the file signature */
#define PNG_IO_CHUNK_HDR 0x0020 /* currently at the chunk header */ #define PNG_IO_CHUNK_HDR 0x0020 /* currently at the chunk header */
 End of changes. 68 change blocks. 
120 lines changed or deleted 138 lines changed or added


 pngconf.h   pngconf.h 
/* pngconf.h - machine configurable file for libpng /* pngconf.h - machine configurable file for libpng
* *
* libpng version 1.4.5 - December 9, 2010 * libpng version 1.4.8 - July 7, 2011
* For conditions of distribution and use, see copyright notice in png.h * For conditions of distribution and use, see copyright notice in png.h
* Copyright (c) 1998-2010 Glenn Randers-Pehrson * Copyright (c) 1998-2011 Glenn Randers-Pehrson
* (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger) * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
* (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc. ) * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc. )
* *
* This code is released under the libpng license. * This code is released under the libpng license.
* For conditions of distribution and use, see the disclaimer * For conditions of distribution and use, see the disclaimer
* and license in png.h * and license in png.h
* *
*/ */
/* Any machine specific code is near the front of this file, so if you /* Any machine specific code is near the front of this file, so if you
skipping to change at line 87 skipping to change at line 87
# ifdef PRIVATEBUILD # ifdef PRIVATEBUILD
# pragma message("PRIVATEBUILD is deprecated.\ # pragma message("PRIVATEBUILD is deprecated.\
Use PNG_USER_PRIVATEBUILD instead.") Use PNG_USER_PRIVATEBUILD instead.")
# define PNG_USER_PRIVATEBUILD PRIVATEBUILD # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
# endif # endif
#endif /* __STDC__ */ #endif /* __STDC__ */
/* End of material added to libpng-1.2.8 */ /* End of material added to libpng-1.2.8 */
/* Added at libpng-1.4.6 */
#ifndef PNG_UNUSED
/* Unused formal parameter warnings are silenced using the following macro
* which is expected to have no bad effects on performance (optimizing
* compilers will probably remove it entirely). Note that if you replace
* it with something other than whitespace, you must include the terminatin
g
* semicolon.
*/
# define PNG_UNUSED(param) (void)param;
#endif
/* End of material added to libpng-1.4.6 */
#ifndef PNG_VERSION_INFO_ONLY #ifndef PNG_VERSION_INFO_ONLY
/* This is the size of the compression buffer, and thus the size of /* This is the size of the compression buffer, and thus the size of
* an IDAT chunk. Make this whatever size you feel is best for your * an IDAT chunk. Make this whatever size you feel is best for your
* machine. One of these will be allocated per png_struct. When this * machine. One of these will be allocated per png_struct. When this
* is full, it writes the data to the disk, and does some other * is full, it writes the data to the disk, and does some other
* calculations. Making this an extremely small size will slow * calculations. Making this an extremely small size will slow
* the library down, but you may want to experiment to determine * the library down, but you may want to experiment to determine
* where it becomes significant, if you are concerned with memory * where it becomes significant, if you are concerned with memory
* usage. Note that zlib allocates at least 32Kb also. For readers, * usage. Note that zlib allocates at least 32Kb also. For readers,
skipping to change at line 303 skipping to change at line 315
# define PNG_NO_CONSOLE_IO # define PNG_NO_CONSOLE_IO
# endif # endif
# ifdef PNG_DEBUG # ifdef PNG_DEBUG
# if (PNG_DEBUG > 0) # if (PNG_DEBUG > 0)
# include <stdio.h> # include <stdio.h>
# endif # endif
# endif # endif
# else # else
# include <stdio.h> # include <stdio.h>
# endif # endif
#define PNG_NO_CONSOLE_IO
#if !(defined PNG_NO_CONSOLE_IO) && !defined(PNG_CONSOLE_IO_SUPPORTED) #if !(defined PNG_NO_CONSOLE_IO) && !defined(PNG_CONSOLE_IO_SUPPORTED)
# define PNG_CONSOLE_IO_SUPPORTED # define PNG_CONSOLE_IO_SUPPORTED
#endif #endif
/* This macro protects us against machines that don't have function /* This macro protects us against machines that don't have function
* prototypes (ie K&R style headers). If your compiler does not handle * prototypes (ie K&R style headers). If your compiler does not handle
* function prototypes, define this macro and use the included ansi2knr. * function prototypes, define this macro and use the included ansi2knr.
* I've always been able to use _NO_PROTO as the indicator, but you may * I've always been able to use _NO_PROTO as the indicator, but you may
* need to drag the empty declaration out in front of here, or change the * need to drag the empty declaration out in front of here, or change the
* ifdef to suit your own needs. * ifdef to suit your own needs.
skipping to change at line 346 skipping to change at line 358
# if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \ # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC) defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
# define MACOS # define MACOS
# endif # endif
#endif #endif
/* Enough people need this for various reasons to include it here */ /* Enough people need this for various reasons to include it here */
#if !defined(MACOS) && !defined(RISCOS) #if !defined(MACOS) && !defined(RISCOS)
# include <sys/types.h> # include <sys/types.h>
#endif #endif
#define PNG_NO_SETJMP
/* PNG_SETJMP_NOT_SUPPORTED and PNG_NO_SETJMP_SUPPORTED are deprecated. */ /* PNG_SETJMP_NOT_SUPPORTED and PNG_NO_SETJMP_SUPPORTED are deprecated. */
#if !defined(PNG_NO_SETJMP) && \ #if !defined(PNG_NO_SETJMP) && \
!defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED) !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
# define PNG_SETJMP_SUPPORTED # define PNG_SETJMP_SUPPORTED
#endif #endif
#ifdef PNG_SETJMP_SUPPORTED #ifdef PNG_SETJMP_SUPPORTED
/* This is an attempt to force a single setjmp behaviour on Linux. If /* This is an attempt to force a single setjmp behaviour on Linux. If
* the X config stuff didn't define _BSD_SOURCE we wouldn't need this. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
* *
skipping to change at line 1381 skipping to change at line 1393
# ifdef __GNUC__ # ifdef __GNUC__
# ifndef PNG_USE_RESULT # ifndef PNG_USE_RESULT
# define PNG_USE_RESULT __attribute__((__warn_unused_result__)) # define PNG_USE_RESULT __attribute__((__warn_unused_result__))
# endif # endif
# ifndef PNG_NORETURN # ifndef PNG_NORETURN
# define PNG_NORETURN __attribute__((__noreturn__)) # define PNG_NORETURN __attribute__((__noreturn__))
# endif # endif
# ifndef PNG_ALLOCATED # ifndef PNG_ALLOCATED
# define PNG_ALLOCATED __attribute__((__malloc__)) # define PNG_ALLOCATED __attribute__((__malloc__))
# endif # endif
# ifndef PNG_DEPRECATED
# define PNG_DEPRECATED __attribute__((__deprecated__))
# endif
/* This specifically protects structure members that should only be /* This specifically protects structure members that should only be
* accessed from within the library, therefore should be empty during * accessed from within the library, therefore should be empty during
* a library build. * a library build.
*/ */
# ifndef PNG_DEPRECATED
# define PNG_DEPRECATED __attribute__((__deprecated__))
# endif
# ifndef PNG_DEPSTRUCT # ifndef PNG_DEPSTRUCT
# define PNG_DEPSTRUCT __attribute__((__deprecated__)) # define PNG_DEPSTRUCT __attribute__((__deprecated__))
# endif # endif
# ifndef PNG_PRIVATE # ifndef PNG_PRIVATE
# if 0 /* Doesn't work so we use deprecated instead*/ # if 0 /* Doesn't work so we use deprecated instead*/
# define PNG_PRIVATE \ # define PNG_PRIVATE \
__attribute__((warning("This function is not exported by libpng." ))) __attribute__((warning("This function is not exported by libpng." )))
# else # else
# define PNG_PRIVATE \ # define PNG_PRIVATE \
__attribute__((__deprecated__)) __attribute__((__deprecated__))
 End of changes. 7 change blocks. 
7 lines changed or deleted 20 lines changed or added


 pngpriv.h   pngpriv.h 
/* pngpriv.h - private declarations for use inside libpng /* pngpriv.h - private declarations for use inside libpng
* *
* libpng version 1.4.5 - December 9, 2010 * libpng version 1.4.8 - July 7, 2011
* For conditions of distribution and use, see copyright notice in png.h * For conditions of distribution and use, see copyright notice in png.h
* Copyright (c) 1998-2010 Glenn Randers-Pehrson * Copyright (c) 1998-2011 Glenn Randers-Pehrson
* (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger) * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
* (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc. ) * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc. )
* *
* This code is released under the libpng license. * This code is released under the libpng license.
* For conditions of distribution and use, see the disclaimer * For conditions of distribution and use, see the disclaimer
* and license in png.h * and license in png.h
*/ */
/* The symbols declared in this file (including the functions declared /* The symbols declared in this file (including the functions declared
* as PNG_EXTERN) are PRIVATE. They are not part of the libpng public * as PNG_EXTERN) are PRIVATE. They are not part of the libpng public
skipping to change at line 29 skipping to change at line 29
* change in an incompatible way, or even disappear. * change in an incompatible way, or even disappear.
* Although the libpng users are not forbidden to include this header, * Although the libpng users are not forbidden to include this header,
* they should be well aware of the issues that may arise from doing so. * they should be well aware of the issues that may arise from doing so.
*/ */
#ifndef PNGPRIV_H #ifndef PNGPRIV_H
#define PNGPRIV_H #define PNGPRIV_H
#ifndef PNG_VERSION_INFO_ONLY #ifndef PNG_VERSION_INFO_ONLY
#if defined(_AIX) && defined(_ALL_SOURCE)
/* On AIX if _ALL_SOURCE is defined standard header files (including
* stdlib.h) define identifiers that are not permitted by the ANSI and
* POSIX standards. In particular 'jmpbuf' is #defined and this will
* prevent compilation of libpng. The following prevents this:
*/
# undef _ALL_SOURCE
#endif
#include <stdlib.h> #include <stdlib.h>
#ifndef PNG_EXTERN #ifndef PNG_EXTERN
/* The functions exported by PNG_EXTERN are internal functions, which /* The functions exported by PNG_EXTERN are internal functions, which
* aren't usually used outside the library (as far as I know), so it is * aren't usually used outside the library (as far as I know), so it is
* debatable if they should be exported at all. In the future, when it * debatable if they should be exported at all. In the future, when it
* is possible to have run-time registry of chunk-handling functions, * is possible to have run-time registry of chunk-handling functions,
* some of these will be made available again. * some of these will be made available again.
# define PNG_EXTERN extern # define PNG_EXTERN extern
*/ */
skipping to change at line 77 skipping to change at line 86
#if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__) #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
# define PNG_ALWAYS_EXTERN # define PNG_ALWAYS_EXTERN
#endif #endif
/* This provides the non-ANSI (far) memory allocation routines. */ /* This provides the non-ANSI (far) memory allocation routines. */
#if defined(__TURBOC__) && defined(__MSDOS__) #if defined(__TURBOC__) && defined(__MSDOS__)
# include <mem.h> # include <mem.h>
# include <alloc.h> # include <alloc.h>
#endif #endif
#ifndef SHP
#if defined(WIN32) || defined(_Windows) || defined(_WINDOWS) || \ #if defined(WIN32) || defined(_Windows) || defined(_WINDOWS) || \
defined(_WIN32) || defined(__WIN32__) defined(_WIN32) || defined(__WIN32__)
# include <windows.h> /* defines _WINDOWS_ macro */ # include <windows.h> /* defines _WINDOWS_ macro */
#endif #endif
#endif
/* Various modes of operation. Note that after an init, mode is set to /* Various modes of operation. Note that after an init, mode is set to
* zero automatically when the structure is created. * zero automatically when the structure is created.
*/ */
#define PNG_HAVE_IHDR 0x01 #define PNG_HAVE_IHDR 0x01
#define PNG_HAVE_PLTE 0x02 #define PNG_HAVE_PLTE 0x02
#define PNG_HAVE_IDAT 0x04 #define PNG_HAVE_IDAT 0x04
#define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream * / #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream * /
#define PNG_HAVE_IEND 0x10 #define PNG_HAVE_IEND 0x10
#define PNG_HAVE_gAMA 0x20 #define PNG_HAVE_gAMA 0x20
#define PNG_HAVE_cHRM 0x40 #define PNG_HAVE_cHRM 0x40
 End of changes. 5 change blocks. 
4 lines changed or deleted 12 lines changed or added


 prime.h   prime.h 
skipping to change at line 64 skipping to change at line 64
1610612741, 1610612741,
0, 0,
}; };
static inline int static inline int
next_prime(int n) next_prime(int n)
{ {
int i = 0; int i = 0;
while(n > primes[i]){ while(n > primes[i]){
i++; i++;
cpAssert(primes[i], "Tried to resize a hash table to a size greater than 1610612741 O_o"); // realistically this should never happen cpAssertHard(primes[i], "Tried to resize a hash table to a s ize greater than 1610612741 O_o"); // realistically this should never happe n
} }
return primes[i]; return primes[i];
} }
 End of changes. 1 change blocks. 
1 lines changed or deleted 1 lines changed or added


 pthread.h   pthread.h 
/* This is an implementation of the threads API of POSIX 1003.1-2001.
*
* ------------------------------------------------------------------------
--
*
* Pthreads-win32 - POSIX Threads Library for Win32
* Copyright(C) 1998 John E. Bossom
* Copyright(C) 1999,2005 Pthreads-win32 contributors
*
* Contact Email: rpj@callisto.canberra.edu.au
*
* The current list of contributors is contained
* in the file CONTRIBUTORS included with the source
* code distribution. The list can also be seen at the
* following World Wide Web location:
* http://sources.redhat.com/pthreads-win32/contributors.html
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING.LIB;
* if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
#if !defined( PTHREAD_H )
#define PTHREAD_H
/*
* See the README file for an explanation of the pthreads-win32 version
* numbering scheme and how the DLL is named etc.
*/
#define PTW32_VERSION 2,8,0,0
#define PTW32_VERSION_STRING "2, 8, 0, 0\0"
/* There are three implementations of cancel cleanup.
* Note that pthread.h is included in both application
* compilation units and also internally for the library.
* The code here and within the library aims to work
* for all reasonable combinations of environments.
*
* The three implementations are:
*
* WIN32 SEH
* C
* C++
*
* Please note that exiting a push/pop block via
* "return", "exit", "break", or "continue" will
* lead to different behaviour amongst applications
* depending upon whether the library was built
* using SEH, C++, or C. For example, a library built
* with SEH will call the cleanup routine, while both
* C++ and C built versions will not.
*/
/*
* Define defaults for cleanup code.
* Note: Unless the build explicitly defines one of the following, then
* we default to standard C style cleanup. This style uses setjmp/longjmp
* in the cancelation and thread exit implementations and therefore won't
* do stack unwinding if linked to applications that have it (e.g.
* C++ apps). This is currently consistent with most/all commercial Unix
* POSIX threads implementations.
*/
#if !defined( __CLEANUP_SEH ) && !defined( __CLEANUP_CXX ) && !defined( __C
LEANUP_C )
# define __CLEANUP_C
#endif
#if defined( __CLEANUP_SEH ) && ( !defined( _MSC_VER ) && !defined(PTW32_RC
_MSC))
#error ERROR [__FILE__, line __LINE__]: SEH is not supported for this compi
ler.
#endif
/*
* Stop here if we are being included by the resource compiler.
*/
#ifndef RC_INVOKED
#undef PTW32_LEVEL
#if defined(_POSIX_SOURCE)
#define PTW32_LEVEL 0
/* Early POSIX */
#endif
#if defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 199309
#undef PTW32_LEVEL
#define PTW32_LEVEL 1
/* Include 1b, 1c and 1d */
#endif
#if defined(INCLUDE_NP)
#undef PTW32_LEVEL
#define PTW32_LEVEL 2
/* Include Non-Portable extensions */
#endif
#define PTW32_LEVEL_MAX 3
#if !defined(PTW32_LEVEL)
#define PTW32_LEVEL PTW32_LEVEL_MAX
/* Include everything */
#endif
#ifdef _UWIN
# define HAVE_STRUCT_TIMESPEC 1
# define HAVE_SIGNAL_H 1
# undef HAVE_CONFIG_H
# pragma comment(lib, "pthread")
#endif
/*
* -------------------------------------------------------------
*
*
* Module: pthread.h
*
* Purpose:
* Provides an implementation of PThreads based upon the
* standard:
*
* POSIX 1003.1-2001
* and
* The Single Unix Specification version 3
*
* (these two are equivalent)
*
* in order to enhance code portability between Windows,
* various commercial Unix implementations, and Linux.
*
* See the ANNOUNCE file for a full list of conforming
* routines and defined constants, and a list of missing
* routines and constants not defined in this implementation.
*
* Authors:
* There have been many contributors to this library.
* The initial implementation was contributed by
* John Bossom, and several others have provided major
* sections or revisions of parts of the implementation.
* Often significant effort has been contributed to
* find and fix important bugs and other problems to
* improve the reliability of the library, which sometimes
* is not reflected in the amount of code which changed as
* result.
* As much as possible, the contributors are acknowledged
* in the ChangeLog file in the source code distribution
* where their changes are noted in detail.
*
* Contributors are listed in the CONTRIBUTORS file.
*
* As usual, all bouquets go to the contributors, and all
* brickbats go to the project maintainer.
*
* Maintainer:
* The code base for this project is coordinated and
* eventually pre-tested, packaged, and made available by
*
* Ross Johnson <rpj@callisto.canberra.edu.au>
*
* QA Testers:
* Ultimately, the library is tested in the real world by
* a host of competent and demanding scientists and
* engineers who report bugs and/or provide solutions
* which are then fixed or incorporated into subsequent
* versions of the library. Each time a bug is fixed, a
* test case is written to prove the fix and ensure
* that later changes to the code don't reintroduce the
* same error. The number of test cases is slowly growing
* and therefore so is the code reliability.
*
* Compliance:
* See the file ANNOUNCE for the list of implemented
* and not-implemented routines and defined options.
* Of course, these are all defined is this file as well.
*
* Web site:
* The source code and other information about this library
* are available from
*
* http://sources.redhat.com/pthreads-win32/
*
* -------------------------------------------------------------
*/
/* Try to avoid including windows.h */
#if defined(__MINGW32__) && defined(__cplusplus)
#define PTW32_INCLUDE_WINDOWS_H
#endif
#ifdef PTW32_INCLUDE_WINDOWS_H
#include <windows.h>
#endif
#if defined(_MSC_VER) && _MSC_VER < 1300 || defined(__DMC__)
/*
* VC++6.0 or early compiler's header has no DWORD_PTR type.
*/
typedef unsigned long DWORD_PTR;
#endif
/* /*
Bada pthread * -----------------
Copyright (c) 2010 Markovtsev Vadim * autoconf switches
* -----------------
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif /* HAVE_CONFIG_H */
#ifndef NEED_FTIME
#include <time.h>
#else /* NEED_FTIME */
/* use native WIN32 time API */
#endif /* NEED_FTIME */
#if HAVE_SIGNAL_H
#include <signal.h>
#endif /* HAVE_SIGNAL_H */
#include <setjmp.h>
#include <limits.h>
/*
* Boolean values to make us independent of system includes.
*/
enum {
PTW32_FALSE = 0,
PTW32_TRUE = (! PTW32_FALSE)
};
Permission is hereby granted, free of charge, to any person obtaining a co /*
py * This is a duplicate of what is in the autoconf config.h,
of this software and associated documentation files (the "Software"), to d * which is only used when building the pthread-win32 libraries.
eal */
in the Software without restriction, including without limitation the righ
ts #ifndef PTW32_CONFIG_H
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # if defined(WINCE)
copies of the Software, and to permit persons to whom the Software is # define NEED_ERRNO
furnished to do so, subject to the following conditions: # define NEED_SEM
# endif
The above copyright notice and this permission notice shall be included in # if defined(_UWIN) || defined(__MINGW32__)
all copies or substantial portions of the Software. # define HAVE_MODE_T
# endif
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #endif
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL TH
E
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FR
OM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef __BADA_PTHREAD_H__ /*
#define __BADA_PTHREAD_H__ *
*/
#ifdef CC_BADA_2_0 #if PTW32_LEVEL >= PTW32_LEVEL_MAX
#include <libxml/../pthread.h> #ifdef NEED_ERRNO
#include "need_errno.h"
#else #else
#include <errno.h>
#endif
#endif /* PTW32_LEVEL >= PTW32_LEVEL_MAX */
/*
* Several systems don't define some error numbers.
*/
#ifndef ENOTSUP
# define ENOTSUP 48 /* This is the value in Solaris. */
#endif
#ifndef ETIMEDOUT
# define ETIMEDOUT 10060 /* This is the value in winsock.h. */
#endif
#ifndef ENOSYS
# define ENOSYS 140 /* Semi-arbitrary value */
#endif
#ifndef EDEADLK
# ifdef EDEADLOCK
# define EDEADLK EDEADLOCK
# else
# define EDEADLK 36 /* This is the value in MSVC. */
# endif
#endif
#include <sched.h>
/*
* To avoid including windows.h we define only those things that we
* actually need from it.
*/
#ifndef PTW32_INCLUDE_WINDOWS_H
#ifndef HANDLE
# define PTW32__HANDLE_DEF
# define HANDLE void *
#endif
#ifndef DWORD
# define PTW32__DWORD_DEF
# define DWORD unsigned long
#endif
#endif
#ifndef HAVE_STRUCT_TIMESPEC
#define HAVE_STRUCT_TIMESPEC 1
struct timespec {
long tv_sec;
long tv_nsec;
};
#endif /* HAVE_STRUCT_TIMESPEC */
#ifndef SIG_BLOCK
#define SIG_BLOCK 0
#endif /* SIG_BLOCK */
#ifndef SIG_UNBLOCK
#define SIG_UNBLOCK 1
#endif /* SIG_UNBLOCK */
#ifndef SIG_SETMASK
#define SIG_SETMASK 2
#endif /* SIG_SETMASK */
#ifdef __cplusplus #ifdef __cplusplus
extern "C" { extern "C"
{
#endif /* __cplusplus */
/*
* -------------------------------------------------------------
*
* POSIX 1003.1-2001 Options
* =========================
*
* Options are normally set in <unistd.h>, which is not provided
* with pthreads-win32.
*
* For conformance with the Single Unix Specification (version 3), all of t
he
* options below are defined, and have a value of either -1 (not supported)
* or 200112L (supported).
*
* These options can neither be left undefined nor have a value of 0, becau
se
* either indicates that sysconf(), which is not implemented, may be used a
t
* runtime to check the status of the option.
*
* _POSIX_THREADS (== 200112L)
* If == 200112L, you can use threads
*
* _POSIX_THREAD_ATTR_STACKSIZE (== 200112L)
* If == 200112L, you can control the size of a thread
's
* stack
* pthread_attr_getstacksize
* pthread_attr_setstacksize
*
* _POSIX_THREAD_ATTR_STACKADDR (== -1)
* If == 200112L, you can allocate and control a threa
d's
* stack. If not supported, the following functions
* will return ENOSYS, indicating they are not
* supported:
* pthread_attr_getstackaddr
* pthread_attr_setstackaddr
*
* _POSIX_THREAD_PRIORITY_SCHEDULING (== -1)
* If == 200112L, you can use realtime scheduling.
* This option indicates that the behaviour of some
* implemented functions conforms to the additional TP
S
* requirements in the standard. E.g. rwlocks favour
* writers over readers when threads have equal priori
ty.
*
* _POSIX_THREAD_PRIO_INHERIT (== -1)
* If == 200112L, you can create priority inheritance
* mutexes.
* pthread_mutexattr_getprotocol +
* pthread_mutexattr_setprotocol +
*
* _POSIX_THREAD_PRIO_PROTECT (== -1)
* If == 200112L, you can create priority ceiling mute
xes
* Indicates the availability of:
* pthread_mutex_getprioceiling
* pthread_mutex_setprioceiling
* pthread_mutexattr_getprioceiling
* pthread_mutexattr_getprotocol +
* pthread_mutexattr_setprioceiling
* pthread_mutexattr_setprotocol +
*
* _POSIX_THREAD_PROCESS_SHARED (== -1)
* If set, you can create mutexes and condition
* variables that can be shared with another
* process.If set, indicates the availability
* of:
* pthread_mutexattr_getpshared
* pthread_mutexattr_setpshared
* pthread_condattr_getpshared
* pthread_condattr_setpshared
*
* _POSIX_THREAD_SAFE_FUNCTIONS (== 200112L)
* If == 200112L you can use the special *_r library
* functions that provide thread-safe behaviour
*
* _POSIX_READER_WRITER_LOCKS (== 200112L)
* If == 200112L, you can use read/write locks
*
* _POSIX_SPIN_LOCKS (== 200112L)
* If == 200112L, you can use spin locks
*
* _POSIX_BARRIERS (== 200112L)
* If == 200112L, you can use barriers
*
* + These functions provide both 'inherit' and/or
* 'protect' protocol, based upon these macro
* settings.
*
* -------------------------------------------------------------
*/
/*
* POSIX Options
*/
#undef _POSIX_THREADS
#define _POSIX_THREADS 200112L
#undef _POSIX_READER_WRITER_LOCKS
#define _POSIX_READER_WRITER_LOCKS 200112L
#undef _POSIX_SPIN_LOCKS
#define _POSIX_SPIN_LOCKS 200112L
#undef _POSIX_BARRIERS
#define _POSIX_BARRIERS 200112L
#undef _POSIX_THREAD_SAFE_FUNCTIONS
#define _POSIX_THREAD_SAFE_FUNCTIONS 200112L
#undef _POSIX_THREAD_ATTR_STACKSIZE
#define _POSIX_THREAD_ATTR_STACKSIZE 200112L
/*
* The following options are not supported
*/
#undef _POSIX_THREAD_ATTR_STACKADDR
#define _POSIX_THREAD_ATTR_STACKADDR -1
#undef _POSIX_THREAD_PRIO_INHERIT
#define _POSIX_THREAD_PRIO_INHERIT -1
#undef _POSIX_THREAD_PRIO_PROTECT
#define _POSIX_THREAD_PRIO_PROTECT -1
/* TPS is not fully supported. */
#undef _POSIX_THREAD_PRIORITY_SCHEDULING
#define _POSIX_THREAD_PRIORITY_SCHEDULING -1
#undef _POSIX_THREAD_PROCESS_SHARED
#define _POSIX_THREAD_PROCESS_SHARED -1
/*
* POSIX 1003.1-2001 Limits
* ===========================
*
* These limits are normally set in <limits.h>, which is not provided with
* pthreads-win32.
*
* PTHREAD_DESTRUCTOR_ITERATIONS
* Maximum number of attempts to destroy
* a thread's thread-specific data on
* termination (must be at least 4)
*
* PTHREAD_KEYS_MAX
* Maximum number of thread-specific data keys
* available per process (must be at least 128)
*
* PTHREAD_STACK_MIN
* Minimum supported stack size for a thread
*
* PTHREAD_THREADS_MAX
* Maximum number of threads supported per
* process (must be at least 64).
*
* SEM_NSEMS_MAX
* The maximum number of semaphores a process can have
.
* (must be at least 256)
*
* SEM_VALUE_MAX
* The maximum value a semaphore can have.
* (must be at least 32767)
*
*/
#undef _POSIX_THREAD_DESTRUCTOR_ITERATIONS
#define _POSIX_THREAD_DESTRUCTOR_ITERATIONS 4
#undef PTHREAD_DESTRUCTOR_ITERATIONS
#define PTHREAD_DESTRUCTOR_ITERATIONS _POSIX_THREAD_DESTRUCTOR_IT
ERATIONS
#undef _POSIX_THREAD_KEYS_MAX
#define _POSIX_THREAD_KEYS_MAX 128
#undef PTHREAD_KEYS_MAX
#define PTHREAD_KEYS_MAX _POSIX_THREAD_KEYS_MAX
#undef PTHREAD_STACK_MIN
#define PTHREAD_STACK_MIN 0
#undef _POSIX_THREAD_THREADS_MAX
#define _POSIX_THREAD_THREADS_MAX 64
/* Arbitrary value */
#undef PTHREAD_THREADS_MAX
#define PTHREAD_THREADS_MAX 2019
#undef _POSIX_SEM_NSEMS_MAX
#define _POSIX_SEM_NSEMS_MAX 256
/* Arbitrary value */
#undef SEM_NSEMS_MAX
#define SEM_NSEMS_MAX 1024
#undef _POSIX_SEM_VALUE_MAX
#define _POSIX_SEM_VALUE_MAX 32767
#undef SEM_VALUE_MAX
#define SEM_VALUE_MAX INT_MAX
#if __GNUC__ && ! defined (__declspec)
# error Please upgrade your GNU compiler to one that supports __declspec.
#endif #endif
#define PTHREAD_STACK_SIZE (64*1024) /*
#define PTHREAD_STACK_MINSIZE 16384 * When building the DLL code, you should define PTW32_BUILD so that
#define PTHREAD_THREADS_MAX 1024 * the variables/functions are exported correctly. When using the DLL,
* do NOT define PTW32_BUILD, and then the variables/functions will
#define MAX_SPIN_COUNT 50 * be imported correctly.
#define SPIN_SLEEP_DURATION 2000001 */
#define PTHREAD_DESTRUCTOR_ITERATIONS 1 #ifndef PTW32_STATIC_LIB
# ifdef PTW32_BUILD
#define PTHREAD_KEYS_MAX 32 # define PTW32_DLLPORT __declspec (dllexport)
# else
typedef void* pthread_t; # define PTW32_DLLPORT __declspec (dllimport)
struct pthread_mutex; # endif
typedef struct pthread_mutex* pthread_mutex_t; #else
struct pthread_attr; # define PTW32_DLLPORT
typedef struct pthread_attr* pthread_attr_t; #endif
struct pthread_mutexattr;
typedef struct pthread_mutexattr* pthread_mutexattr_t; /*
struct pthread_cond; * The Open Watcom C/C++ compiler uses a non-standard calling convention
typedef struct pthread_cond* pthread_cond_t; * that passes function args in registers unless __cdecl is explicitly spec
ified
* in exposed function prototypes.
*
* We force all calls to cdecl even though this could slow Watcom code down
* slightly. If you know that the Watcom compiler will be used to build bot
h
* the DLL and application, then you can probably define this as a null str
ing.
* Remember that pthread.h (this file) is used for both the DLL and applica
tion builds.
*/
#define PTW32_CDECL __cdecl
#if defined(_UWIN) && PTW32_LEVEL >= PTW32_LEVEL_MAX
# include <sys/types.h>
#else
/*
* Generic handle type - intended to extend uniqueness beyond
* that available with a simple pointer. It should scale for either
* IA-32 or IA-64.
*/
typedef struct {
void * p; /* Pointer to actual object */
unsigned int x; /* Extra information - reuse count etc */
} ptw32_handle_t;
typedef ptw32_handle_t pthread_t;
typedef struct pthread_attr_t_ * pthread_attr_t;
typedef struct pthread_once_t_ pthread_once_t;
typedef struct pthread_key_t_ * pthread_key_t;
typedef struct pthread_mutex_t_ * pthread_mutex_t;
typedef struct pthread_mutexattr_t_ * pthread_mutexattr_t;
typedef struct pthread_cond_t_ * pthread_cond_t;
typedef struct pthread_condattr_t_ * pthread_condattr_t;
#endif
typedef struct pthread_rwlock_t_ * pthread_rwlock_t;
typedef struct pthread_rwlockattr_t_ * pthread_rwlockattr_t;
typedef struct pthread_spinlock_t_ * pthread_spinlock_t;
typedef struct pthread_barrier_t_ * pthread_barrier_t;
typedef struct pthread_barrierattr_t_ * pthread_barrierattr_t;
#define PTHREAD_SPIN_LOCKED 1 /*
#define PTHREAD_SPIN_UNLOCKED 0 * ====================
* ====================
* POSIX Threads
* ====================
* ====================
*/
enum { enum {
/*
* pthread_attr_{get,set}detachstate
*/
PTHREAD_CREATE_JOINABLE = 0, /* Default */
PTHREAD_CREATE_DETACHED = 1,
/*
* pthread_attr_{get,set}inheritsched
*/
PTHREAD_INHERIT_SCHED = 0,
PTHREAD_EXPLICIT_SCHED = 1, /* Default */
/*
* pthread_{get,set}scope
*/
PTHREAD_SCOPE_PROCESS = 0,
PTHREAD_SCOPE_SYSTEM = 1, /* Default */
/*
* pthread_setcancelstate paramters
*/
PTHREAD_CANCEL_ENABLE = 0, /* Default */
PTHREAD_CANCEL_DISABLE = 1,
/*
* pthread_setcanceltype parameters
*/
PTHREAD_CANCEL_ASYNCHRONOUS = 0,
PTHREAD_CANCEL_DEFERRED = 1, /* Default */
/*
* pthread_mutexattr_{get,set}pshared
* pthread_condattr_{get,set}pshared
*/
PTHREAD_PROCESS_PRIVATE = 0,
PTHREAD_PROCESS_SHARED = 1,
/*
* pthread_barrier_wait
*/
PTHREAD_BARRIER_SERIAL_THREAD = -1
};
/*
* ====================
* ====================
* Cancelation
* ====================
* ====================
*/
#define PTHREAD_CANCELED ((void *) -1)
/*
* ====================
* ====================
* Once Key
* ====================
* ====================
*/
#define PTHREAD_ONCE_INIT { PTW32_FALSE, 0, 0, 0}
struct pthread_once_t_
{
int done; /* indicates if user function has been executed
*/
void * lock;
int reserved1;
int reserved2;
};
/*
* ====================
* ====================
* Object initialisers
* ====================
* ====================
*/
#define PTHREAD_MUTEX_INITIALIZER ((pthread_mutex_t) -1)
#define PTHREAD_RECURSIVE_MUTEX_INITIALIZER ((pthread_mutex_t) -2)
#define PTHREAD_ERRORCHECK_MUTEX_INITIALIZER ((pthread_mutex_t) -3)
/*
* Compatibility with LinuxThreads
*/
#define PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP PTHREAD_RECURSIVE_MUTEX_INIT
IALIZER
#define PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP PTHREAD_ERRORCHECK_MUTEX_IN
ITIALIZER
#define PTHREAD_COND_INITIALIZER ((pthread_cond_t) -1)
#define PTHREAD_RWLOCK_INITIALIZER ((pthread_rwlock_t) -1)
#define PTHREAD_SPINLOCK_INITIALIZER ((pthread_spinlock_t) -1)
/*
* Mutex types.
*/
enum
{
/* Compatibility with LinuxThreads */
PTHREAD_MUTEX_FAST_NP, PTHREAD_MUTEX_FAST_NP,
#define PTHREAD_MUTEX_FAST_NP PTHREAD_MUTEX_FAST_NP
PTHREAD_MUTEX_RECURSIVE_NP, PTHREAD_MUTEX_RECURSIVE_NP,
#define PTHREAD_MUTEX_RECURSIVE_NP PTHREAD_MUTEX_RECURSIVE_NP
PTHREAD_MUTEX_ERRORCHECK_NP, PTHREAD_MUTEX_ERRORCHECK_NP,
#define PTHREAD_MUTEX_ERRORCHECK_NP PTHREAD_MUTEX_ERRORCHECK_NP PTHREAD_MUTEX_TIMED_NP = PTHREAD_MUTEX_FAST_NP,
PTHREAD_MUTEX_ADAPTIVE_NP = PTHREAD_MUTEX_FAST_NP,
/* For compatibility with POSIX */
PTHREAD_MUTEX_NORMAL = PTHREAD_MUTEX_FAST_NP,
PTHREAD_MUTEX_RECURSIVE = PTHREAD_MUTEX_RECURSIVE_NP,
PTHREAD_MUTEX_ERRORCHECK = PTHREAD_MUTEX_ERRORCHECK_NP,
PTHREAD_MUTEX_DEFAULT = PTHREAD_MUTEX_NORMAL
}; };
enum { typedef struct ptw32_cleanup_t ptw32_cleanup_t;
PTHREAD_PROCESS_PRIVATE,
#define PTHREAD_PROCESS_PRIVATE PTHREAD_PROCESS_PRIVATE #if defined(_MSC_VER)
PTHREAD_PROCESS_SHARED /* Disable MSVC 'anachronism used' warning */
#define PTHREAD_PROCESS_SHARED PTHREAD_PROCESS_SHARED #pragma warning( disable : 4229 )
#endif
typedef void (* PTW32_CDECL ptw32_cleanup_callback_t)(void *);
#if defined(_MSC_VER)
#pragma warning( default : 4229 )
#endif
struct ptw32_cleanup_t
{
ptw32_cleanup_callback_t routine;
void *arg;
struct ptw32_cleanup_t *prev;
}; };
#define PTHREAD_MUTEX_INITIALIZER \ #ifdef __CLEANUP_SEH
{{PTHREAD_SPIN_UNLOCKED},0,PTHREAD_MUTEX_FAST_NP,0} /*
* WIN32 SEH version of cancel cleanup.
*/
#define pthread_cleanup_push( _rout, _arg ) \
{ \
ptw32_cleanup_t _cleanup; \
\
_cleanup.routine = (ptw32_cleanup_callback_t)(_rout); \
_cleanup.arg = (_arg); \
__try \
{ \
#define pthread_cleanup_pop( _execute ) \
} \
__finally \
{ \
if( _execute || AbnormalTermination()) \
{ \
(*(_cleanup.routine))( _cleanup.arg ); \
} \
} \
}
#else /* __CLEANUP_SEH */
#ifdef __CLEANUP_C
/*
* C implementation of PThreads cancel cleanup
*/
#define pthread_cleanup_push( _rout, _arg ) \
{ \
ptw32_cleanup_t _cleanup; \
\
ptw32_push_cleanup( &_cleanup, (ptw32_cleanup_callback_t) (_rou
t), (_arg) ); \
#define pthread_cleanup_pop( _execute ) \
(void) ptw32_pop_cleanup( _execute ); \
}
#else /* __CLEANUP_C */
#ifdef __CLEANUP_CXX
/*
* C++ version of cancel cleanup.
* - John E. Bossom.
*/
class PThreadCleanup {
/*
* PThreadCleanup
*
* Purpose
* This class is a C++ helper class that is
* used to implement pthread_cleanup_push/
* pthread_cleanup_pop.
* The destructor of this class automatically
* pops the pushed cleanup routine regardless
* of how the code exits the scope
* (i.e. such as by an exception)
*/
ptw32_cleanup_callback_t cleanUpRout;
void * obj;
int executeIt;
public:
PThreadCleanup() :
cleanUpRout( 0 ),
obj( 0 ),
executeIt( 0 )
/*
* No cleanup performed
*/
{
}
PThreadCleanup(
ptw32_cleanup_callback_t routine,
void * arg ) :
cleanUpRout( routine ),
obj( arg ),
executeIt( 1 )
/*
* Registers a cleanup routine for 'arg'
*/
{
}
~PThreadCleanup()
{
if ( executeIt && ((void *) cleanUpRout != (void *) 0) )
{
(void) (*cleanUpRout)( obj );
}
}
void execute( int exec )
{
executeIt = exec;
}
};
/*
* C++ implementation of PThreads cancel cleanup;
* This implementation takes advantage of a helper
* class who's destructor automatically calls the
* cleanup routine if we exit our scope weirdly
*/
#define pthread_cleanup_push( _rout, _arg ) \
{ \
PThreadCleanup cleanup((ptw32_cleanup_callback_t)(_rout), \
(void *) (_arg) );
#define pthread_cleanup_pop( _execute ) \
cleanup.execute( _execute ); \
}
#define PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP \ #else
{{PTHREAD_SPIN_UNLOCKED},0,PTHREAD_MUTEX_RECURSIVE_NP,0}
#define PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP \ #error ERROR [__FILE__, line __LINE__]: Cleanup type undefined.
{{PTHREAD_SPIN_UNLOCKED},0,PTHREAD_MUTEX_ERRORCHECK_NP,0}
int pthread_mutexattr_init(pthread_mutexattr_t*attr); #endif /* __CLEANUP_CXX */
int pthread_mutexattr_destroy(pthread_mutexattr_t*attr);
//int pthread_mutexattr_getkind_np(const pthread_mutexattr_t*attr,int*kind)
;
//int pthread_mutexattr_setkind_np(pthread_mutexattr_t*attr,int kind);
int pthread_mutex_init(pthread_mutex_t*mutex,
const pthread_mutexattr_t*mutexattr);
int pthread_mutex_lock(pthread_mutex_t*mutex);
int pthread_mutex_unlock(pthread_mutex_t*mutex);
int pthread_mutex_trylock(pthread_mutex_t*mutex);
int pthread_mutex_destroy(pthread_mutex_t*mutex);
/* Conditions */
typedef void* pthread_condattr_t;
#define PTHREAD_COND_INITIALIZER \
{{PTHREAD_SPIN_UNLOCKED},0}
int pthread_cond_init(pthread_cond_t*cond,pthread_condattr_t*cond_attr);
int pthread_cond_destroy(pthread_cond_t*cond);
int pthread_cond_signal(pthread_cond_t*cond);
int pthread_cond_broadcast(pthread_cond_t*cond);
int pthread_cond_timedwait(pthread_cond_t*cond,pthread_mutex_t*mutex,
const struct timespec*abstime);
int pthread_cond_wait(pthread_cond_t*cond,pthread_mutex_t*mutex);
// These two functions are not described in the standard. Use them as follo
ws:
// [thread #1]
// pthread_cond_enter(cond);
// pthread_cond_wait(cond, null);
// pthread_cond_exit(cond);
//
// [thread #2]
// pthread_cond_enter(cond);
// pthread_cond_broadcast(cond);
// pthread_cond_exit(cond);
//
// The mutex style locking will result in a dead lock.
int pthread_cond_enter(pthread_cond_t*cond);
int pthread_cond_exit(pthread_cond_t*cond);
/* only for completeness (always return NULL) */
int pthread_condattr_init(pthread_condattr_t*attr);
int pthread_condattr_destroy(pthread_condattr_t*attr);
int pthread_condattr_getpshared(const pthread_condattr_t*attr,int*pshared);
int pthread_condattr_setpshared(pthread_condattr_t*attr,int pshared);
/* thread specific variables */
typedef unsigned int pthread_key_t;
/*
int pthread_key_create(pthread_key_t*key,void(*destructor)(const void*));
int pthread_key_delete(pthread_key_t key);
int pthread_setspecific(pthread_key_t key,const void*value);
const void*pthread_getspecific(pthread_key_t key);
*/
enum { #endif /* __CLEANUP_C */
PTHREAD_CREATE_JOINABLE,
#define PTHREAD_CREATE_JOINABLE PTHREAD_CREATE_JOINABLE
PTHREAD_CREATE_DETACHED
#define PTHREAD_CREATE_DETACHED PTHREAD_CREATE_DETACHED
};
enum { #endif /* __CLEANUP_SEH */
PTHREAD_EXPLICIT_SCHED,
#define PTHREAD_EXPLICIT_SCHED PTHREAD_EXPLICIT_SCHED
PTHREAD_INHERIT_SCHED
#define PTHREAD_INHERIT_SCHED PTHREAD_INHERIT_SCHED
};
enum { /* for completeness */ /*
PTHREAD_SCOPE_SYSTEM, * ===============
#define PTHREAD_SCOPE_SYSTEM PTHREAD_SCOPE_SYSTEM * ===============
PTHREAD_SCOPE_PROCESS * Methods
#define PTHREAD_SCOPE_PROCESS PTHREAD_SCOPE_PROCESS * ===============
}; * ===============
*/
/*
* PThread Attribute Functions
*/
PTW32_DLLPORT int PTW32_CDECL pthread_attr_init (pthread_attr_t * attr);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_destroy (pthread_attr_t * attr);
int pthread_attr_init(pthread_attr_t*attr); PTW32_DLLPORT int PTW32_CDECL pthread_attr_getdetachstate (const pthread_at
int pthread_attr_destroy(pthread_attr_t*attr); tr_t * attr,
int *detachstate);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_getstackaddr (const pthread_attr
_t * attr,
void **stackaddr);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_getstacksize (const pthread_attr
_t * attr,
size_t * stacksize);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_setdetachstate (pthread_attr_t *
attr,
int detachstate);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_setstackaddr (pthread_attr_t * a
ttr,
void *stackaddr);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_setstacksize (pthread_attr_t * a
ttr,
size_t stacksize);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_getschedparam (const pthread_att
r_t *attr,
struct sched_param *param);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_setschedparam (pthread_attr_t *a
ttr,
const struct sched_param *param);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_setschedpolicy (pthread_attr_t *
,
int);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_getschedpolicy (pthread_attr_t *
,
int *);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_setinheritsched(pthread_attr_t *
attr,
int inheritsched);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_getinheritsched(pthread_attr_t *
attr,
int * inheritsched);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_setscope (pthread_attr_t *,
int);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_getscope (const pthread_attr_t *
,
int *);
int pthread_attr_setdetachstate(pthread_attr_t*attr,const int detachstate);
int pthread_attr_getdetachstate(const pthread_attr_t*attr,int*detachstate);
/* /*
int pthread_attr_setschedpolicy(pthread_attr_t*attr,const int policy); * PThread Functions
int pthread_attr_getschedpolicy(const pthread_attr_t*attr,int*policy); */
PTW32_DLLPORT int PTW32_CDECL pthread_create (pthread_t * tid,
const pthread_attr_t * attr,
void *(*start) (void *),
void *arg);
int pthread_attr_setschedparam(pthread_attr_t*attr, PTW32_DLLPORT int PTW32_CDECL pthread_detach (pthread_t tid);
const struct sched_param*param);
int pthread_attr_getschedparam(const pthread_attr_t*attr,
struct sched_param*param);
int pthread_attr_setinheritsched(pthread_attr_t*attr,const int inherit); PTW32_DLLPORT int PTW32_CDECL pthread_equal (pthread_t t1,
int pthread_attr_getinheritsched(const pthread_attr_t*attr,int*inherit); pthread_t t2);
int pthread_attr_setscope(pthread_attr_t*attr,const int scope); PTW32_DLLPORT void PTW32_CDECL pthread_exit (void *value_ptr);
int pthread_attr_getscope(const pthread_attr_t*attr,int*scope);
int pthread_attr_setstackaddr(pthread_attr_t*attr,void*stack); PTW32_DLLPORT int PTW32_CDECL pthread_join (pthread_t thread,
int pthread_attr_getstackaddr(const pthread_attr_t*attr,void**stack); void **value_ptr);
int pthread_attr_setstacksize(pthread_attr_t*attr,const size_t stacksize); PTW32_DLLPORT pthread_t PTW32_CDECL pthread_self (void);
int pthread_attr_getstacksize(const pthread_attr_t*attr,size_t*stacksize);
int pthread_setschedparam(const pthread_t target_thread,const int policy, PTW32_DLLPORT int PTW32_CDECL pthread_cancel (pthread_t thread);
const struct sched_param*param);
int pthread_getschedparam(const pthread_t target_thread,int*policy,
struct sched_param*param);
*/
/* ONCE */
typedef int pthread_once_t;
#define PTHREAD_ONCE_INIT PTHREAD_SPIN_UNLOCKED
//int pthread_once(pthread_once_t*once_control,void(*init_routine)(void)); PTW32_DLLPORT int PTW32_CDECL pthread_setcancelstate (int state,
int *oldstate);
/* CANCEL */ PTW32_DLLPORT int PTW32_CDECL pthread_setcanceltype (int type,
int *oldtype);
enum { PTW32_DLLPORT void PTW32_CDECL pthread_testcancel (void);
PTHREAD_CANCEL_ENABLE,
#define PTHREAD_CANCEL_ENABLE PTHREAD_CANCEL_ENABLE
PTHREAD_CANCEL_DISABLE,
#define PTHREAD_CANCEL_DISABLE PTHREAD_CANCEL_DISABLE
};
enum { PTW32_DLLPORT int PTW32_CDECL pthread_once (pthread_once_t * once_control,
PTHREAD_CANCEL_DEFERRED, void (*init_routine) (void));
#define PTHREAD_CANCEL_DEFERRED PTHREAD_CANCEL_DEFERRED
PTHREAD_CANCEL_ASYNCHRONOUS, #if PTW32_LEVEL >= PTW32_LEVEL_MAX
#define PTHREAD_CANCEL_ASYNCHRONOUS PTHREAD_CANCEL_ASYNCHRONOUS PTW32_DLLPORT ptw32_cleanup_t * PTW32_CDECL ptw32_pop_cleanup (int execute)
;
PTW32_DLLPORT void PTW32_CDECL ptw32_push_cleanup (ptw32_cleanup_t * cleanu
p,
void (*routine) (void *),
void *arg);
#endif /* PTW32_LEVEL >= PTW32_LEVEL_MAX */
/*
* Thread Specific Data Functions
*/
PTW32_DLLPORT int PTW32_CDECL pthread_key_create (pthread_key_t * key,
void (*destructor) (void *));
PTW32_DLLPORT int PTW32_CDECL pthread_key_delete (pthread_key_t key);
PTW32_DLLPORT int PTW32_CDECL pthread_setspecific (pthread_key_t key,
const void *value);
PTW32_DLLPORT void * PTW32_CDECL pthread_getspecific (pthread_key_t key);
/*
* Mutex Attribute Functions
*/
PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_init (pthread_mutexattr_t *
attr);
PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_destroy (pthread_mutexattr_
t * attr);
PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_getpshared (const pthread_m
utexattr_t
* attr,
int *pshared);
PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_setpshared (pthread_mutexat
tr_t * attr,
int pshared);
PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_settype (pthread_mutexattr_
t * attr, int kind);
PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_gettype (pthread_mutexattr_
t * attr, int *kind);
/*
* Barrier Attribute Functions
*/
PTW32_DLLPORT int PTW32_CDECL pthread_barrierattr_init (pthread_barrierattr
_t * attr);
PTW32_DLLPORT int PTW32_CDECL pthread_barrierattr_destroy (pthread_barriera
ttr_t * attr);
PTW32_DLLPORT int PTW32_CDECL pthread_barrierattr_getpshared (const pthread
_barrierattr_t
* attr,
int *pshared);
PTW32_DLLPORT int PTW32_CDECL pthread_barrierattr_setpshared (pthread_barri
erattr_t * attr,
int pshared);
/*
* Mutex Functions
*/
PTW32_DLLPORT int PTW32_CDECL pthread_mutex_init (pthread_mutex_t * mutex,
const pthread_mutexattr_t * attr);
PTW32_DLLPORT int PTW32_CDECL pthread_mutex_destroy (pthread_mutex_t * mute
x);
PTW32_DLLPORT int PTW32_CDECL pthread_mutex_lock (pthread_mutex_t * mutex);
PTW32_DLLPORT int PTW32_CDECL pthread_mutex_timedlock(pthread_mutex_t *mute
x,
const struct timespec *abstime);
PTW32_DLLPORT int PTW32_CDECL pthread_mutex_trylock (pthread_mutex_t * mute
x);
PTW32_DLLPORT int PTW32_CDECL pthread_mutex_unlock (pthread_mutex_t * mutex
);
/*
* Spinlock Functions
*/
PTW32_DLLPORT int PTW32_CDECL pthread_spin_init (pthread_spinlock_t * lock,
int pshared);
PTW32_DLLPORT int PTW32_CDECL pthread_spin_destroy (pthread_spinlock_t * lo
ck);
PTW32_DLLPORT int PTW32_CDECL pthread_spin_lock (pthread_spinlock_t * lock)
;
PTW32_DLLPORT int PTW32_CDECL pthread_spin_trylock (pthread_spinlock_t * lo
ck);
PTW32_DLLPORT int PTW32_CDECL pthread_spin_unlock (pthread_spinlock_t * loc
k);
/*
* Barrier Functions
*/
PTW32_DLLPORT int PTW32_CDECL pthread_barrier_init (pthread_barrier_t * bar
rier,
const pthread_barrierattr_t * attr,
unsigned int count);
PTW32_DLLPORT int PTW32_CDECL pthread_barrier_destroy (pthread_barrier_t *
barrier);
PTW32_DLLPORT int PTW32_CDECL pthread_barrier_wait (pthread_barrier_t * bar
rier);
/*
* Condition Variable Attribute Functions
*/
PTW32_DLLPORT int PTW32_CDECL pthread_condattr_init (pthread_condattr_t * a
ttr);
PTW32_DLLPORT int PTW32_CDECL pthread_condattr_destroy (pthread_condattr_t
* attr);
PTW32_DLLPORT int PTW32_CDECL pthread_condattr_getpshared (const pthread_co
ndattr_t * attr,
int *pshared);
PTW32_DLLPORT int PTW32_CDECL pthread_condattr_setpshared (pthread_condattr
_t * attr,
int pshared);
/*
* Condition Variable Functions
*/
PTW32_DLLPORT int PTW32_CDECL pthread_cond_init (pthread_cond_t * cond,
const pthread_condattr_t * attr);
PTW32_DLLPORT int PTW32_CDECL pthread_cond_destroy (pthread_cond_t * cond);
PTW32_DLLPORT int PTW32_CDECL pthread_cond_wait (pthread_cond_t * cond,
pthread_mutex_t * mutex);
PTW32_DLLPORT int PTW32_CDECL pthread_cond_timedwait (pthread_cond_t * cond
,
pthread_mutex_t * mutex,
const struct timespec *abstime);
PTW32_DLLPORT int PTW32_CDECL pthread_cond_signal (pthread_cond_t * cond);
PTW32_DLLPORT int PTW32_CDECL pthread_cond_broadcast (pthread_cond_t * cond
);
/*
* Scheduling
*/
PTW32_DLLPORT int PTW32_CDECL pthread_setschedparam (pthread_t thread,
int policy,
const struct sched_param *param);
PTW32_DLLPORT int PTW32_CDECL pthread_getschedparam (pthread_t thread,
int *policy,
struct sched_param *param);
PTW32_DLLPORT int PTW32_CDECL pthread_setconcurrency (int);
PTW32_DLLPORT int PTW32_CDECL pthread_getconcurrency (void);
/*
* Read-Write Lock Functions
*/
PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_init(pthread_rwlock_t *lock,
const pthread_rwlockattr_t *attr);
PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_destroy(pthread_rwlock_t *lock
);
PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_tryrdlock(pthread_rwlock_t *);
PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_trywrlock(pthread_rwlock_t *);
PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_rdlock(pthread_rwlock_t *lock)
;
PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_timedrdlock(pthread_rwlock_t *
lock,
const struct timespec *abstime);
PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_wrlock(pthread_rwlock_t *lock)
;
PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_timedwrlock(pthread_rwlock_t *
lock,
const struct timespec *abstime);
PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_unlock(pthread_rwlock_t *lock)
;
PTW32_DLLPORT int PTW32_CDECL pthread_rwlockattr_init (pthread_rwlockattr_t
* attr);
PTW32_DLLPORT int PTW32_CDECL pthread_rwlockattr_destroy (pthread_rwlockatt
r_t * attr);
PTW32_DLLPORT int PTW32_CDECL pthread_rwlockattr_getpshared (const pthread_
rwlockattr_t * attr,
int *pshared);
PTW32_DLLPORT int PTW32_CDECL pthread_rwlockattr_setpshared (pthread_rwlock
attr_t * attr,
int pshared);
#if PTW32_LEVEL >= PTW32_LEVEL_MAX - 1
/*
* Signal Functions. Should be defined in <signal.h> but MSVC and MinGW32
* already have signal.h that don't define these.
*/
PTW32_DLLPORT int PTW32_CDECL pthread_kill(pthread_t thread, int sig);
/*
* Non-portable functions
*/
/*
* Compatibility with Linux.
*/
PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_setkind_np(pthread_mutexatt
r_t * attr,
int kind);
PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_getkind_np(pthread_mutexatt
r_t * attr,
int *kind);
/*
* Possibly supported by other POSIX threads implementations
*/
PTW32_DLLPORT int PTW32_CDECL pthread_delay_np (struct timespec * interval)
;
PTW32_DLLPORT int PTW32_CDECL pthread_num_processors_np(void);
/*
* Useful if an application wants to statically link
* the lib rather than load the DLL at run-time.
*/
PTW32_DLLPORT int PTW32_CDECL pthread_win32_process_attach_np(void);
PTW32_DLLPORT int PTW32_CDECL pthread_win32_process_detach_np(void);
PTW32_DLLPORT int PTW32_CDECL pthread_win32_thread_attach_np(void);
PTW32_DLLPORT int PTW32_CDECL pthread_win32_thread_detach_np(void);
/*
* Features that are auto-detected at load/run time.
*/
PTW32_DLLPORT int PTW32_CDECL pthread_win32_test_features_np(int);
enum ptw32_features {
PTW32_SYSTEM_INTERLOCKED_COMPARE_EXCHANGE = 0x0001, /* System provides it
. */
PTW32_ALERTABLE_ASYNC_CANCEL = 0x0002 /* Can cancel blocked
threads. */
}; };
#define PTHREAD_CANCELED ((void *) -1) /*
* Register a system time change with the library.
* Causes the library to perform various functions
* in response to the change. Should be called whenever
* the application's top level window receives a
* WM_TIMECHANGE message. It can be passed directly to
* pthread_create() as a new thread if desired.
*/
PTW32_DLLPORT void * PTW32_CDECL pthread_timechange_handler_np(void *);
int pthread_kill(pthread_t thread,int sig); #endif /*PTW32_LEVEL >= PTW32_LEVEL_MAX - 1 */
int pthread_cancel(pthread_t thread);
/*int pthread_setcancelstate(int state,int*oldstate);
int pthread_setcanceltype(int type,int*oldtype); #if PTW32_LEVEL >= PTW32_LEVEL_MAX
void pthread_testcancel(void);
*/
/* CLEANUP */
/* /*
void pthread_cleanup_push(void(*routine)(void*),void*arg); * Returns the Win32 HANDLE for the POSIX thread.
void pthread_cleanup_pop(int execute); */
PTW32_DLLPORT HANDLE PTW32_CDECL pthread_getw32threadhandle_np(pthread_t th
read);
void pthread_cleanup_push_defer_np(void(*routine)(void*),void*arg);
void pthread_cleanup_pop_restore_np(int execute);
*/
/* FORK */
/* /*
pid_t pthread_atfork(void(*prepare)(void),void(*parent)(void), * Protected Methods
void(*child)(void)); *
*/ * This function blocks until the given WIN32 handle
/* THREADS */ * is signaled or pthread_cancel had been called.
pthread_t pthread_self(void); * This function allows the caller to hook into the
* PThreads cancel mechanism. It is implemented using
*
* WaitForMultipleObjects
*
* on 'waitHandle' and a manually reset WIN32 Event
* used to implement pthread_cancel. The 'timeout'
* argument to TimedWait is simply passed to
* WaitForMultipleObjects.
*/
PTW32_DLLPORT int PTW32_CDECL pthreadCancelableWait (HANDLE waitHandle);
PTW32_DLLPORT int PTW32_CDECL pthreadCancelableTimedWait (HANDLE waitHandle
,
DWORD timeout);
int pthread_create(pthread_t*__threadarg, #endif /* PTW32_LEVEL >= PTW32_LEVEL_MAX */
const pthread_attr_t*__attr,
void*(*__start_routine)(void *),
void*__arg);
void pthread_exit(void*__retval); /*
* Thread-Safe C Runtime Library Mappings.
*/
#ifndef _UWIN
# if defined(NEED_ERRNO)
PTW32_DLLPORT int * PTW32_CDECL _errno( void );
# else
# ifndef errno
# if (defined(_MT) || defined(_DLL))
__declspec(dllimport) extern int * __cdecl _errno(void);
# define errno (*_errno())
# endif
# endif
# endif
#endif
int pthread_join(pthread_t __th,void**__thread_return); /*
* WIN32 C runtime library had been made thread-safe
* without affecting the user interface. Provide
* mappings from the UNIX thread-safe versions to
* the standard C runtime library calls.
* Only provide function mappings for functions that
* actually exist on WIN32.
*/
#if !defined(__MINGW32__)
#define strtok_r( _s, _sep, _lasts ) \
( *(_lasts) = strtok( (_s), (_sep) ) )
#endif /* !__MINGW32__ */
#define asctime_r( _tm, _buf ) \
( strcpy( (_buf), asctime( (_tm) ) ), \
(_buf) )
#define ctime_r( _clock, _buf ) \
( strcpy( (_buf), ctime( (_clock) ) ), \
(_buf) )
#define gmtime_r( _clock, _result ) \
( *(_result) = *gmtime( (_clock) ), \
(_result) )
#define localtime_r( _clock, _result ) \
( *(_result) = *localtime( (_clock) ), \
(_result) )
int pthread_detach(pthread_t __th); #define rand_r( _seed ) \
int pthread_equal(pthread_t __thread1,pthread_t __thread2); ( _seed == _seed? rand() : rand() )
//int pthread_sigmask(int how,const sigset_t*newset,sigset_t*oldset); /*
* Some compiler environments don't define some things.
*/
#if defined(__BORLANDC__)
# define _ftime ftime
# define _timeb timeb
#endif
#ifdef __cplusplus #ifdef __cplusplus
}
/*
* Internal exceptions
*/
class ptw32_exception {};
class ptw32_exception_cancel : public ptw32_exception {};
class ptw32_exception_exit : public ptw32_exception {};
#endif #endif
#endif /* CC_BADA_2_0 */ #if PTW32_LEVEL >= PTW32_LEVEL_MAX
/* FIXME: This is only required if the library was built using SEH */
/*
* Get internal SEH tag
*/
PTW32_DLLPORT DWORD PTW32_CDECL ptw32_get_exception_services_code(void);
#endif /* PTW32_LEVEL >= PTW32_LEVEL_MAX */
#ifndef PTW32_BUILD
#ifdef __CLEANUP_SEH
/*
* Redefine the SEH __except keyword to ensure that applications
* propagate our internal exceptions up to the library's internal handlers.
*/
#define __except( E ) \
__except( ( GetExceptionCode() == ptw32_get_exception_services_code
() ) \
? EXCEPTION_CONTINUE_SEARCH : ( E ) )
#endif /* __CLEANUP_SEH */
#ifdef __CLEANUP_CXX
/*
* Redefine the C++ catch keyword to ensure that applications
* propagate our internal exceptions up to the library's internal handlers.
*/
#ifdef _MSC_VER
/*
* WARNING: Replace any 'catch( ... )' with 'PtW32CatchAll'
* if you want Pthread-Win32 cancelation and pthread_exit to work.
*/
#ifndef PtW32NoCatchWarn
#pragma message("Specify \"/DPtW32NoCatchWarn\" compiler flag to skip this
message.")
#pragma message("----------------------------------------------------------
--------")
#pragma message("When compiling applications with MSVC++ and C++ exception
handling:")
#pragma message(" Replace any 'catch( ... )' in routines called from POSIX
threads")
#pragma message(" with 'PtW32CatchAll' or 'CATCHALL' if you want POSIX thr
ead")
#pragma message(" cancelation and pthread_exit to work. For example:")
#pragma message("")
#pragma message(" #ifdef PtW32CatchAll")
#pragma message(" PtW32CatchAll")
#pragma message(" #else")
#pragma message(" catch(...)")
#pragma message(" #endif")
#pragma message(" {")
#pragma message(" /* Catchall block processing */")
#pragma message(" }")
#pragma message("----------------------------------------------------------
--------")
#endif
#define PtW32CatchAll \
catch( ptw32_exception & ) { throw; } \
catch( ... )
#else /* _MSC_VER */
#define catch( E ) \
catch( ptw32_exception & ) { throw; } \
catch( E )
#endif /* _MSC_VER */
#endif /* __CLEANUP_CXX */
#endif /* ! PTW32_BUILD */
#ifdef __cplusplus
} /* End of extern "C" */
#endif /* __cplusplus */
#ifdef PTW32__HANDLE_DEF
# undef HANDLE
#endif
#ifdef PTW32__DWORD_DEF
# undef DWORD
#endif
#undef PTW32_LEVEL
#undef PTW32_LEVEL_MAX
#endif /* ! RC_INVOKED */
#endif /* __BADA_PTHREAD_H__ */ #endif /* PTHREAD_H */
 End of changes. 49 change blocks. 
210 lines changed or deleted 1391 lines changed or added


 resource.h   resource.h 
//{{NO_DEPENDENCIES}} //{{NO_DEPENDENCIES}}
// Microsoft Developer Studio generated include file. // Microsoft Visual C++ generated include file.
// Used by VisualPng.rc // Used by TestLua.RC
// //
#define IDM_FILE_OPEN 40001
#define IDM_FILE_SAVE 40002 #define IDS_PROJNAME 100
#define IDM_FILE_NEXT 40003 #define IDR_TESTLUA 100
#define IDM_FILE_PREVIOUS 40004
#define IDM_FILE_EXIT 40005 #define ID_FILE_NEW_WINDOW 32771
#define IDM_OPTIONS_BACKGROUND 40006
#define IDM_OPTIONS_STRETCH 40007
#define IDM_HELP_ABOUT 40008
// Next default values for new objects // Next default values for new objects
// //
#ifdef APSTUDIO_INVOKED #ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS #ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 113 #define _APS_NEXT_RESOURCE_VALUE 201
#define _APS_NEXT_COMMAND_VALUE 40009 #define _APS_NEXT_CONTROL_VALUE 1000
#define _APS_NEXT_CONTROL_VALUE 1001 #define _APS_NEXT_SYMED_VALUE 101
#define _APS_NEXT_SYMED_VALUE 101 #define _APS_NEXT_COMMAND_VALUE 32775
#endif #endif
#endif #endif
 End of changes. 3 change blocks. 
14 lines changed or deleted 11 lines changed or added


 semaphore.h   semaphore.h 
/* /*
Bada pthread * Module: semaphore.h
Copyright (c) 2010 Markovtsev Vadim *
* Purpose:
* Semaphores aren't actually part of the PThreads standard.
* They are defined by the POSIX Standard:
*
* POSIX 1003.1b-1993 (POSIX.1b)
*
* ------------------------------------------------------------------------
--
*
* Pthreads-win32 - POSIX Threads Library for Win32
* Copyright(C) 1998 John E. Bossom
* Copyright(C) 1999,2005 Pthreads-win32 contributors
*
* Contact Email: rpj@callisto.canberra.edu.au
*
* The current list of contributors is contained
* in the file CONTRIBUTORS included with the source
* code distribution. The list can also be seen at the
* following World Wide Web location:
* http://sources.redhat.com/pthreads-win32/contributors.html
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING.LIB;
* if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
#if !defined( SEMAPHORE_H )
#define SEMAPHORE_H
#undef PTW32_LEVEL
#if defined(_POSIX_SOURCE)
#define PTW32_LEVEL 0
/* Early POSIX */
#endif
#if defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 199309
#undef PTW32_LEVEL
#define PTW32_LEVEL 1
/* Include 1b, 1c and 1d */
#endif
#if defined(INCLUDE_NP)
#undef PTW32_LEVEL
#define PTW32_LEVEL 2
/* Include Non-Portable extensions */
#endif
#define PTW32_LEVEL_MAX 3
#if !defined(PTW32_LEVEL)
#define PTW32_LEVEL PTW32_LEVEL_MAX
/* Include everything */
#endif
#if __GNUC__ && ! defined (__declspec)
# error Please upgrade your GNU compiler to one that supports __declspec.
#endif
Permission is hereby granted, free of charge, to any person obtaining a co /*
py * When building the DLL code, you should define PTW32_BUILD so that
of this software and associated documentation files (the "Software"), to d * the variables/functions are exported correctly. When using the DLL,
eal * do NOT define PTW32_BUILD, and then the variables/functions will
in the Software without restriction, including without limitation the righ * be imported correctly.
ts */
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #ifndef PTW32_STATIC_LIB
copies of the Software, and to permit persons to whom the Software is # ifdef PTW32_BUILD
furnished to do so, subject to the following conditions: # define PTW32_DLLPORT __declspec (dllexport)
# else
The above copyright notice and this permission notice shall be included in # define PTW32_DLLPORT __declspec (dllimport)
all copies or substantial portions of the Software. # endif
#else
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # define PTW32_DLLPORT
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #endif
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL TH
E /*
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * This is a duplicate of what is in the autoconf config.h,
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FR * which is only used when building the pthread-win32 libraries.
OM, */
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. #ifndef PTW32_CONFIG_H
*/ # if defined(WINCE)
# define NEED_ERRNO
#ifndef SEMAPHORE_H_ # define NEED_SEM
#define SEMAPHORE_H_ # endif
# if defined(_UWIN) || defined(__MINGW32__)
#include <FBaseRtThread.h> # define HAVE_MODE_T
#include <time.h> # endif
#endif
typedef struct sem{
Osp::Base::Runtime::Semaphore *id; /*
int value; *
Osp::Base::Runtime::Mutex *mutex; */
}sem_t;
#if PTW32_LEVEL >= PTW32_LEVEL_MAX
#define SEM_FAILED ((sem_t*)0) #ifdef NEED_ERRNO
#define SEM_VALUE_MAX ((int)((~0u)>>1)) #include "need_errno.h"
#define SEM_MAGIC 0x35d108f2 #else
#include <errno.h>
int sem_destroy(sem_t*sem); #endif
int sem_getvalue(sem_t*sem,int*sval); #endif /* PTW32_LEVEL >= PTW32_LEVEL_MAX */
int sem_init(sem_t*sem,int pshared,unsigned int value);
int sem_post(sem_t*sem); #define _POSIX_SEMAPHORES
int sem_trywait(sem_t*sem);
int sem_wait(sem_t*sem); #ifdef __cplusplus
extern "C"
sem_t*sem_open(const char*name,int oflag,...); {
int sem_close(sem_t*sem); #endif /* __cplusplus */
int sem_unlink(const char*name);
#ifndef HAVE_MODE_T
typedef unsigned int mode_t;
#endif
typedef struct sem_t_ * sem_t;
PTW32_DLLPORT int __cdecl sem_init (sem_t * sem,
int pshared,
unsigned int value);
PTW32_DLLPORT int __cdecl sem_destroy (sem_t * sem);
PTW32_DLLPORT int __cdecl sem_trywait (sem_t * sem);
PTW32_DLLPORT int __cdecl sem_wait (sem_t * sem);
PTW32_DLLPORT int __cdecl sem_timedwait (sem_t * sem,
const struct timespec * abstime);
PTW32_DLLPORT int __cdecl sem_post (sem_t * sem);
PTW32_DLLPORT int __cdecl sem_post_multiple (sem_t * sem,
int count);
PTW32_DLLPORT int __cdecl sem_open (const char * name,
int oflag,
mode_t mode,
unsigned int value);
PTW32_DLLPORT int __cdecl sem_close (sem_t * sem);
PTW32_DLLPORT int __cdecl sem_unlink (const char * name);
PTW32_DLLPORT int __cdecl sem_getvalue (sem_t * sem,
int * sval);
#ifdef __cplusplus
} /* End of extern "C" */
#endif /* __cplusplus */
int sem_timedwait(sem_t*sem,const struct timespec*abstime); #undef PTW32_LEVEL
#undef PTW32_LEVEL_MAX
#endif /* SEMAPHORE_H_ */ #endif /* !SEMAPHORE_H */
 End of changes. 4 change blocks. 
53 lines changed or deleted 161 lines changed or added


 testBasic.h   testBasic.h 
#ifndef _TEST_BASIC_H_ #ifndef _TEST_BASIC_H_
#define _TEST_BASIC_H_ #define _TEST_BASIC_H_
#include "cocos2d.h" #include "cocos2d.h"
using namespace cocos2d; USING_NS_CC;
using namespace std;
class TestScene : public CCScene class TestScene : public CCScene
{ {
public: public:
TestScene(bool bPortrait = false); TestScene(bool bPortrait = false);
virtual void onEnter(); virtual void onEnter();
virtual void runThisTest() = 0; virtual void runThisTest() = 0;
// The CallBack for back to the main menu scene // The CallBack for back to the main menu scene
virtual void MainMenuCallback(CCObject* pSender); virtual void MainMenuCallback(CCObject* pSender);
protected:
bool m_bPortrait; // indicate if this test case requires portrait mode
}; };
#endif #endif
 End of changes. 2 change blocks. 
4 lines changed or deleted 2 lines changed or added


 tests.h   tests.h 
#ifndef _TESTS_H_ #ifndef _TESTS_H_
#define _TESTS_H_ #define _TESTS_H_
#include "ActionsTest/ActionsTest.h" #include "ActionsTest/ActionsTest.h"
#include "TransitionsTest/TransitionsTest.h" #include "TransitionsTest/TransitionsTest.h"
#include "ProgressActionsTest/ProgressActionsTest.h" #include "ActionsProgressTest/ActionsProgressTest.h"
#include "EffectsTest/EffectsTest.h" #include "EffectsTest/EffectsTest.h"
#include "ClickAndMoveTest/ClickAndMoveTest.h" #include "ClickAndMoveTest/ClickAndMoveTest.h"
#include "RotateWorldTest/RotateWorldTest.h" #include "RotateWorldTest/RotateWorldTest.h"
#include "ParticleTest/ParticleTest.h" #include "ParticleTest/ParticleTest.h"
#include "EaseActionsTest/EaseActionsTest.h" #include "ActionsEaseTest/ActionsEaseTest.h"
#include "MotionStreakTest/MotionStreakTest.h" #include "MotionStreakTest/MotionStreakTest.h"
#include "DrawPrimitivesTest/DrawPrimitivesTest.h" #include "DrawPrimitivesTest/DrawPrimitivesTest.h"
#include "CocosNodeTest/CocosNodeTest.h"
#include "TouchesTest/TouchesTest.h" #include "TouchesTest/TouchesTest.h"
#include "MenuTest/MenuTest.h" #include "MenuTest/MenuTest.h"
#include "ActionManagerTest/ActionManagerTest.h" #include "ActionManagerTest/ActionManagerTest.h"
#include "LayerTest/LayerTest.h" #include "LayerTest/LayerTest.h"
#include "SceneTest/SceneTest.h" #include "SceneTest/SceneTest.h"
#include "ParallaxTest/ParallaxTest.h" #include "ParallaxTest/ParallaxTest.h"
#include "TileMapTest/TileMapTest.h" #include "TileMapTest/TileMapTest.h"
#include "IntervalTest/IntervalTest.h" #include "IntervalTest/IntervalTest.h"
#include "LabelTest/LabelTest.h" #include "LabelTest/LabelTest.h"
// havn't implement on marmalade
//#if (CC_TARGET_PLATFORM != CC_PLATFORM_MARMALADE)
#include "TextInputTest/TextInputTest.h" #include "TextInputTest/TextInputTest.h"
//#endif
#include "SpriteTest/SpriteTest.h" #include "SpriteTest/SpriteTest.h"
#include "SchedulerTest/SchedulerTest.h" #include "SchedulerTest/SchedulerTest.h"
#include "RenderTextureTest/RenderTextureTest.h" #include "RenderTextureTest/RenderTextureTest.h"
#include "Box2DTest/Box2dTest.h" #include "Box2DTest/Box2dTest.h"
#include "Box2DTestBed/Box2dView.h" #include "Box2DTestBed/Box2dView.h"
#include "EffectsAdvancedTest/EffectsAdvancedTest.h" #include "EffectsAdvancedTest/EffectsAdvancedTest.h"
#include "HiResTest/HiResTest.h"
#include "AccelerometerTest/AccelerometerTest.h" #include "AccelerometerTest/AccelerometerTest.h"
#include "KeypadTest/KeypadTest.h" #include "KeypadTest/KeypadTest.h"
#include "PerformanceTest/PerformanceTest.h" #include "PerformanceTest/PerformanceTest.h"
#include "ZwoptexTest/ZwoptexTest.h" #include "ZwoptexTest/ZwoptexTest.h"
#include "CocosDenshionTest/CocosDenshionTest.h" #include "CocosDenshionTest/CocosDenshionTest.h"
#include "CurlTest/CurlTest.h" #include "CurlTest/CurlTest.h"
#include "UserDefaultTest/UserDefaultTest.h" #include "UserDefaultTest/UserDefaultTest.h"
#include "DirectorTest/DirectorTest.h"
#include "BugsTest/BugsTest.h" #include "BugsTest/BugsTest.h"
#include "Texture2dTest/Texture2dTest.h" #include "Texture2dTest/Texture2dTest.h"
#include "FontTest/FontTest.h" #include "FontTest/FontTest.h"
#include "CurrentLanguageTest/CurrentLanguageTest.h" #include "CurrentLanguageTest/CurrentLanguageTest.h"
#include "TextureCacheTest/TextureCacheTest.h" #include "TextureCacheTest/TextureCacheTest.h"
#include "NodeTest/NodeTest.h"
#include "ShaderTest/ShaderTest.h"
#if (CC_TARGET_PLATFORM != CC_PLATFORM_MARMALADE) #if (CC_TARGET_PLATFORM != CC_PLATFORM_MARMALADE)
#include "ChipmunkTest/cocos2dChipmunkDemo.h" #include "ChipmunkAccelTouchTest/ChipmunkAccelTouchTest.h"
#else #else
#ifdef MARMALADEUSECHIPMUNK #ifdef MARMALADEUSECHIPMUNK
#if (MARMALADEUSECHIPMUNK == 1) #if (MARMALADEUSECHIPMUNK == 1)
#include "ChipmunkTest/cocos2dChipmunkDemo.h" #include "ChipmunkAccelTouchTest/ChipmunkAccelTouchTest.h"
#endif #endif
#endif #endif
#endif // (CC_TARGET_PLATFORM != CC_PLATFORM_MARMALADE) #endif // (CC_TARGET_PLATFORM != CC_PLATFORM_MARMALADE)
#include "ExtensionsTest/ExtensionsTest.h" #include "ExtensionsTest/ExtensionsTest.h"
#include "MutiTouchTest/MutiTouchTest.h"
enum enum
{ {
TEST_ACTIONS = 0, TEST_ACTIONS = 0,
TEST_TRANSITIONS, TEST_TRANSITIONS,
TEST_PROGRESS_ACTIONS, TEST_PROGRESS_ACTIONS,
TEST_EFFECTS, TEST_EFFECTS,
TEST_CLICK_AND_MOVE, TEST_CLICK_AND_MOVE,
TEST_ROTATE_WORLD, TEST_ROTATE_WORLD,
TEST_PARTICLE, TEST_PARTICLE,
skipping to change at line 82 skipping to change at line 79
TEST_DRAW_PRIMITIVES, TEST_DRAW_PRIMITIVES,
TEST_COCOSNODE, TEST_COCOSNODE,
TEST_TOUCHES, TEST_TOUCHES,
TEST_MENU, TEST_MENU,
TEST_ACTION_MANAGER, TEST_ACTION_MANAGER,
TEST_LAYER, TEST_LAYER,
TEST_SCENE, TEST_SCENE,
TEST_PARALLAX, TEST_PARALLAX,
TEST_TILE_MAP, TEST_TILE_MAP,
TEST_INTERVAL, TEST_INTERVAL,
TEST_CHIPMUNK, TEST_CHIPMUNKACCELTOUCH,
TEST_LABEL, TEST_LABEL,
TEST_TEXT_INPUT, TEST_TEXT_INPUT,
TEST_SPRITE, TEST_SPRITE,
TEST_SCHEDULER, TEST_SCHEDULER,
TEST_RENDERTEXTURE, TEST_RENDERTEXTURE,
TEST_TEXTURE2D, TEST_TEXTURE2D,
TEST_BOX2D, TEST_BOX2D,
TEST_BOX2DBED, TEST_BOX2DBED,
TEST_EFFECT_ADVANCE, TEST_EFFECT_ADVANCE,
TEST_HIRES,
TEST_ACCELEROMRTER, TEST_ACCELEROMRTER,
TEST_KEYPAD, TEST_KEYPAD,
TEST_COCOSDENSHION, TEST_COCOSDENSHION,
TEST_PERFORMANCE, TEST_PERFORMANCE,
TEST_ZWOPTEX, TEST_ZWOPTEX,
TEST_CURL, TEST_CURL,
TEST_USERDEFAULT, TEST_USERDEFAULT,
TEST_DIRECTOR,
TEST_BUGS, TEST_BUGS,
TEST_FONTS, TEST_FONTS,
TEST_CURRENT_LANGUAGE, TEST_CURRENT_LANGUAGE,
TEST_TEXTURECACHE, TEST_TEXTURECACHE,
TEST_EXTENSIONS, TEST_EXTENSIONS,
TEST_SHADER,
TEST_MUTITOUCH,
TESTS_COUNT, TESTS_COUNT,
}; };
const std::string g_aTestNames[TESTS_COUNT] = { const std::string g_aTestNames[TESTS_COUNT] = {
"ActionsTest", "ActionsTest",
"TransitionsTest", "TransitionsTest",
"ProgressActionsTest", "ActionsProgressTest",
"EffectsTest", "EffectsTest",
"ClickAndMoveTest", "ClickAndMoveTest",
"RotateWorldTest", "RotateWorldTest",
"ParticleTest", "ParticleTest",
"EaseActionsTest", "ActionsEaseTest",
"MotionStreakTest", "MotionStreakTest",
"DrawPrimitivesTest", "DrawPrimitivesTest",
"CocosNodeTest", "NodeTest",
"TouchesTest", "TouchesTest",
"MenuTest", "MenuTest",
"ActionManagerTest", "ActionManagerTest",
"LayerTest", "LayerTest",
"SceneTest", "SceneTest",
"ParallaxTest", "ParallaxTest",
"TileMapTest", "TileMapTest",
"IntervalTest", "IntervalTest",
"ChipmunkTest", "ChipmunkAccelTouchTest",
"LabelTest", "LabelTest",
"TextInputTest", "TextInputTest",
"SpriteTest", "SpriteTest",
"SchdulerTest", "SchdulerTest",
"RenderTextureTest", "RenderTextureTest",
"Texture2DTest", "Texture2DTest",
"Box2dTest", "Box2dTest",
"Box2dTestBed", "Box2dTestBed",
"EffectAdvancedTest", "EffectAdvancedTest",
"HiResTest",
"Accelerometer", "Accelerometer",
"KeypadTest", "KeypadTest",
"CocosDenshionTest", "CocosDenshionTest",
"PerformanceTest", "PerformanceTest",
"ZwoptexTest", "ZwoptexTest",
"CurlTest", "CurlTest",
"UserDefaultTest", "UserDefaultTest",
"DirectorTest",
"BugsTest", "BugsTest",
"FontTest", "FontTest",
"CurrentLanguageTest", "CurrentLanguageTest",
"TextureCacheTest", "TextureCacheTest",
"ExtensionsTest" "ExtensionsTest",
"ShaderTest",
"MutiTouchTest"
}; };
#endif #endif
 End of changes. 25 change blocks. 
33 lines changed or deleted 30 lines changed or added


 testsAppDelegate.h   testsAppDelegate.h 
skipping to change at line 15 skipping to change at line 15
// Created by Walzer on 10-11-16. // Created by Walzer on 10-11-16.
// Copyright 2010 __MyCompanyName__. All rights reserved. // Copyright 2010 __MyCompanyName__. All rights reserved.
// //
#import <UIKit/UIKit.h> #import <UIKit/UIKit.h>
@class RootViewController; @class RootViewController;
@interface AppController : NSObject <UIApplicationDelegate> { @interface AppController : NSObject <UIApplicationDelegate> {
UIWindow *window; UIWindow *window;
RootViewController *viewController; RootViewController *viewController;
} }
@end @end
 End of changes. 1 change blocks. 
1 lines changed or deleted 1 lines changed or added


 tolua++.h   tolua++.h 
skipping to change at line 56 skipping to change at line 56
#include "lauxlib.h" #include "lauxlib.h"
struct tolua_Error struct tolua_Error
{ {
int index; int index;
int array; int array;
const char* type; const char* type;
}; };
typedef struct tolua_Error tolua_Error; typedef struct tolua_Error tolua_Error;
#define TOLUA_NOPEER LUA_REGISTRYINDEX /* for lua 5.1 */ #define TOLUA_NOPEER LUA_REGISTRYINDEX /* for lua 5.1 */
TOLUA_API const char* tolua_typename (lua_State* L, int lo); TOLUA_API const char* tolua_typename (lua_State* L, int lo);
TOLUA_API void tolua_error (lua_State* L, const char* msg, tolua_Error* err ); TOLUA_API void tolua_error (lua_State* L, const char* msg, tolua_Error* err );
TOLUA_API int tolua_isnoobj (lua_State* L, int lo, tolua_Error* err); TOLUA_API int tolua_isnoobj (lua_State* L, int lo, tolua_Error* err);
TOLUA_API int tolua_isvalue (lua_State* L, int lo, int def, tolua_Error* er r); TOLUA_API int tolua_isvalue (lua_State* L, int lo, int def, tolua_Error* er r);
TOLUA_API int tolua_isvaluenil (lua_State* L, int lo, tolua_Error* err); TOLUA_API int tolua_isvaluenil (lua_State* L, int lo, tolua_Error* err);
TOLUA_API int tolua_isboolean (lua_State* L, int lo, int def, tolua_Error* err); TOLUA_API int tolua_isboolean (lua_State* L, int lo, int def, tolua_Error* err);
TOLUA_API int tolua_isnumber (lua_State* L, int lo, int def, tolua_Error* e rr); TOLUA_API int tolua_isnumber (lua_State* L, int lo, int def, tolua_Error* e rr);
TOLUA_API int tolua_isstring (lua_State* L, int lo, int def, tolua_Error* e rr); TOLUA_API int tolua_isstring (lua_State* L, int lo, int def, tolua_Error* e rr);
TOLUA_API int tolua_istable (lua_State* L, int lo, int def, tolua_Error* er r); TOLUA_API int tolua_istable (lua_State* L, int lo, int def, tolua_Error* er r);
 End of changes. 1 change blocks. 
1 lines changed or deleted 1 lines changed or added


 tolua_fix.h   tolua_fix.h 
skipping to change at line 14 skipping to change at line 14
#include "tolua++.h" #include "tolua++.h"
#ifdef __cplusplus #ifdef __cplusplus
extern "C" extern "C"
{ {
#endif #endif
#define TOLUA_REFID_PTR_MAPPING "tolua_refid_ptr_mapping" #define TOLUA_REFID_PTR_MAPPING "tolua_refid_ptr_mapping"
#define TOLUA_REFID_TYPE_MAPPING "tolua_refid_type_mapping" #define TOLUA_REFID_TYPE_MAPPING "tolua_refid_type_mapping"
#define TOLUA_REFID_FUNC_MAPPING "tolua_refid_func_mapping"
TOLUA_API void tolua_prepare_ccobject_table(lua_State* L); TOLUA_API void tolua_prepare_ccobject_table(lua_State* L);
TOLUA_API int tolua_pushusertype_ccobject(lua_State* L, TOLUA_API int tolua_pushusertype_ccobject(lua_State* L,
int uid, int uid,
int* p_refid, int* p_refid,
void* ptr, void* ptr,
const char* type); const char* type);
TOLUA_API int tolua_remove_ccobject_by_refid(lua_State* L, int refid); TOLUA_API int tolua_remove_ccobject_by_refid(lua_State* L, int refid);
TOLUA_API int tolua_ref_function(lua_State* L, int lo, int def); TOLUA_API int tolua_ref_function(lua_State* L, int lo, int def);
TOLUA_API void tolua_remove_function_by_refid(lua_State* L, int refid); TOLUA_API void tolua_remove_function_by_refid(lua_State* L, int refid);
 End of changes. 1 change blocks. 
1 lines changed or deleted 0 lines changed or added


 tree.h   tree.h 
skipping to change at line 74 skipping to change at line 74
/* #define LIBXML_NAMESPACE_DICT */ /* #define LIBXML_NAMESPACE_DICT */
/** /**
* xmlBufferAllocationScheme: * xmlBufferAllocationScheme:
* *
* A buffer allocation scheme can be defined to either match exactly the * A buffer allocation scheme can be defined to either match exactly the
* need or double it's allocated size each time it is found too small. * need or double it's allocated size each time it is found too small.
*/ */
typedef enum { typedef enum {
XML_BUFFER_ALLOC_DOUBLEIT, /* double each time one need to grow */ XML_BUFFER_ALLOC_DOUBLEIT, /* double each time one need to grow */
XML_BUFFER_ALLOC_EXACT, /* grow only to the minimal size */ XML_BUFFER_ALLOC_EXACT, /* grow only to the minimal size */
XML_BUFFER_ALLOC_IMMUTABLE, /* immutable buffer */ XML_BUFFER_ALLOC_IMMUTABLE, /* immutable buffer */
XML_BUFFER_ALLOC_IO /* special allocation scheme used fo r I/O */ XML_BUFFER_ALLOC_IO /* special allocation scheme used for I/O */
} xmlBufferAllocationScheme; } xmlBufferAllocationScheme;
/** /**
* xmlBuffer: * xmlBuffer:
* *
* A buffer structure. * A buffer structure.
*/ */
typedef struct _xmlBuffer xmlBuffer; typedef struct _xmlBuffer xmlBuffer;
typedef xmlBuffer *xmlBufferPtr; typedef xmlBuffer *xmlBufferPtr;
struct _xmlBuffer { struct _xmlBuffer {
xmlChar *content; /* The buffer content UTF8 */ xmlChar *content; /* The buffer content UTF8 */
unsigned int use; /* The buffer size used */ unsigned int use; /* The buffer size used */
unsigned int size; /* The buffer size */ unsigned int size; /* The buffer size */
xmlBufferAllocationScheme alloc; /* The realloc method */ xmlBufferAllocationScheme alloc; /* The realloc method */
xmlChar *contentIO; /* in IO mode we may have a differen t base */ xmlChar *contentIO; /* in IO mode we may have a different base * /
}; };
/** /**
* XML_XML_NAMESPACE: * XML_XML_NAMESPACE:
* *
* This is the namespace for the special xml: prefix predefined in the * This is the namespace for the special xml: prefix predefined in the
* XML Namespace specification. * XML Namespace specification.
*/ */
#define XML_XML_NAMESPACE \ #define XML_XML_NAMESPACE \
(const xmlChar *) "http://www.w3.org/XML/1998/namespace" (const xmlChar *) "http://www.w3.org/XML/1998/namespace"
skipping to change at line 121 skipping to change at line 121
/* /*
* The different element types carried by an XML tree. * The different element types carried by an XML tree.
* *
* NOTE: This is synchronized with DOM Level1 values * NOTE: This is synchronized with DOM Level1 values
* See http://www.w3.org/TR/REC-DOM-Level-1/ * See http://www.w3.org/TR/REC-DOM-Level-1/
* *
* Actually this had diverged a bit, and now XML_DOCUMENT_TYPE_NODE should * Actually this had diverged a bit, and now XML_DOCUMENT_TYPE_NODE should
* be deprecated to use an XML_DTD_NODE. * be deprecated to use an XML_DTD_NODE.
*/ */
typedef enum { typedef enum {
XML_ELEMENT_NODE= 1, XML_ELEMENT_NODE= 1,
XML_ATTRIBUTE_NODE= 2, XML_ATTRIBUTE_NODE= 2,
XML_TEXT_NODE= 3, XML_TEXT_NODE= 3,
XML_CDATA_SECTION_NODE= 4, XML_CDATA_SECTION_NODE= 4,
XML_ENTITY_REF_NODE= 5, XML_ENTITY_REF_NODE= 5,
XML_ENTITY_NODE= 6, XML_ENTITY_NODE= 6,
XML_PI_NODE= 7, XML_PI_NODE= 7,
XML_COMMENT_NODE= 8, XML_COMMENT_NODE= 8,
XML_DOCUMENT_NODE= 9, XML_DOCUMENT_NODE= 9,
XML_DOCUMENT_TYPE_NODE= 10, XML_DOCUMENT_TYPE_NODE= 10,
XML_DOCUMENT_FRAG_NODE= 11, XML_DOCUMENT_FRAG_NODE= 11,
XML_NOTATION_NODE= 12, XML_NOTATION_NODE= 12,
XML_HTML_DOCUMENT_NODE= 13, XML_HTML_DOCUMENT_NODE= 13,
XML_DTD_NODE= 14, XML_DTD_NODE= 14,
XML_ELEMENT_DECL= 15, XML_ELEMENT_DECL= 15,
XML_ATTRIBUTE_DECL= 16, XML_ATTRIBUTE_DECL= 16,
XML_ENTITY_DECL= 17, XML_ENTITY_DECL= 17,
XML_NAMESPACE_DECL= 18, XML_NAMESPACE_DECL= 18,
XML_XINCLUDE_START= 19, XML_XINCLUDE_START= 19,
XML_XINCLUDE_END= 20 XML_XINCLUDE_END= 20
#ifdef LIBXML_DOCB_ENABLED #ifdef LIBXML_DOCB_ENABLED
,XML_DOCB_DOCUMENT_NODE= 21 ,XML_DOCB_DOCUMENT_NODE= 21
#endif #endif
} xmlElementType; } xmlElementType;
/** /**
* xmlNotation: * xmlNotation:
* *
* A DTD Notation definition. * A DTD Notation definition.
*/ */
typedef struct _xmlNotation xmlNotation; typedef struct _xmlNotation xmlNotation;
typedef xmlNotation *xmlNotationPtr; typedef xmlNotation *xmlNotationPtr;
struct _xmlNotation { struct _xmlNotation {
const xmlChar *name; /* Notation name */ const xmlChar *name; /* Notation name */
const xmlChar *PublicID; /* Public identifier, if any const xmlChar *PublicID; /* Public identifier, if any
*/ */
const xmlChar *SystemID; /* System identifier, if any const xmlChar *SystemID; /* System identifier, if any
*/ */
}; };
/** /**
* xmlAttributeType: * xmlAttributeType:
* *
* A DTD Attribute type definition. * A DTD Attribute type definition.
*/ */
typedef enum { typedef enum {
XML_ATTRIBUTE_CDATA = 1, XML_ATTRIBUTE_CDATA = 1,
XML_ATTRIBUTE_ID, XML_ATTRIBUTE_ID,
XML_ATTRIBUTE_IDREF , XML_ATTRIBUTE_IDREF ,
XML_ATTRIBUTE_IDREFS, XML_ATTRIBUTE_IDREFS,
XML_ATTRIBUTE_ENTITY, XML_ATTRIBUTE_ENTITY,
XML_ATTRIBUTE_ENTITIES, XML_ATTRIBUTE_ENTITIES,
XML_ATTRIBUTE_NMTOKEN, XML_ATTRIBUTE_NMTOKEN,
XML_ATTRIBUTE_NMTOKENS, XML_ATTRIBUTE_NMTOKENS,
XML_ATTRIBUTE_ENUMERATION, XML_ATTRIBUTE_ENUMERATION,
XML_ATTRIBUTE_NOTATION XML_ATTRIBUTE_NOTATION
} xmlAttributeType; } xmlAttributeType;
/** /**
skipping to change at line 201 skipping to change at line 201
/** /**
* xmlEnumeration: * xmlEnumeration:
* *
* List structure used when there is an enumeration in DTDs. * List structure used when there is an enumeration in DTDs.
*/ */
typedef struct _xmlEnumeration xmlEnumeration; typedef struct _xmlEnumeration xmlEnumeration;
typedef xmlEnumeration *xmlEnumerationPtr; typedef xmlEnumeration *xmlEnumerationPtr;
struct _xmlEnumeration { struct _xmlEnumeration {
struct _xmlEnumeration *next; /* next one */ struct _xmlEnumeration *next; /* next one */
const xmlChar *name; /* Enumeration name */ const xmlChar *name; /* Enumeration name */
}; };
/** /**
* xmlAttribute: * xmlAttribute:
* *
* An Attribute declaration in a DTD. * An Attribute declaration in a DTD.
*/ */
typedef struct _xmlAttribute xmlAttribute; typedef struct _xmlAttribute xmlAttribute;
typedef xmlAttribute *xmlAttributePtr; typedef xmlAttribute *xmlAttributePtr;
struct _xmlAttribute { struct _xmlAttribute {
void *_private; /* application data */ void *_private; /* application data */
xmlElementType type; /* XML_ATTRIBUTE_DECL, must be seco nd ! */ xmlElementType type; /* XML_ATTRIBUTE_DECL, must be seco nd ! */
const xmlChar *name; /* Attribute name */ const xmlChar *name; /* Attribute name */
struct _xmlNode *children; /* NULL */ struct _xmlNode *children; /* NULL */
struct _xmlNode *last; /* NULL */ struct _xmlNode *last; /* NULL */
struct _xmlDtd *parent; /* -> DTD */ struct _xmlDtd *parent; /* -> DTD */
struct _xmlNode *next; /* next sibling link */ struct _xmlNode *next; /* next sibling link */
struct _xmlNode *prev; /* previous sibling link */ struct _xmlNode *prev; /* previous sibling link */
struct _xmlDoc *doc; /* the containing document */ struct _xmlDoc *doc; /* the containing document */
struct _xmlAttribute *nexth; /* next in hash table */ struct _xmlAttribute *nexth; /* next in hash table */
xmlAttributeType atype; /* The attribute type */ xmlAttributeType atype; /* The attribute type */
xmlAttributeDefault def; /* the default */ xmlAttributeDefault def; /* the default */
const xmlChar *defaultValue; /* or the default value */ const xmlChar *defaultValue; /* or the default value */
xmlEnumerationPtr tree; /* or the enumeration tree if any * / xmlEnumerationPtr tree; /* or the enumeration tree if any * /
const xmlChar *prefix; /* the namespace prefix if any */ const xmlChar *prefix; /* the namespace prefix if any */
const xmlChar *elem; /* Element holding the attribute */ const xmlChar *elem; /* Element holding the attribute */
}; };
/** /**
* xmlElementContentType: * xmlElementContentType:
* *
* Possible definitions of element content types. * Possible definitions of element content types.
*/ */
typedef enum { typedef enum {
XML_ELEMENT_CONTENT_PCDATA = 1, XML_ELEMENT_CONTENT_PCDATA = 1,
XML_ELEMENT_CONTENT_ELEMENT, XML_ELEMENT_CONTENT_ELEMENT,
skipping to change at line 267 skipping to change at line 267
/** /**
* xmlElementContent: * xmlElementContent:
* *
* An XML Element content as stored after parsing an element definition * An XML Element content as stored after parsing an element definition
* in a DTD. * in a DTD.
*/ */
typedef struct _xmlElementContent xmlElementContent; typedef struct _xmlElementContent xmlElementContent;
typedef xmlElementContent *xmlElementContentPtr; typedef xmlElementContent *xmlElementContentPtr;
struct _xmlElementContent { struct _xmlElementContent {
xmlElementContentType type; /* PCDATA, ELEMENT, SEQ or OR */ xmlElementContentType type; /* PCDATA, ELEMENT, SEQ or OR */
xmlElementContentOccur ocur; /* ONCE, OPT, MULT or PLUS */ xmlElementContentOccur ocur; /* ONCE, OPT, MULT or PLUS */
const xmlChar *name; /* Element name */ const xmlChar *name; /* Element name */
struct _xmlElementContent *c1; /* first child */ struct _xmlElementContent *c1; /* first child */
struct _xmlElementContent *c2; /* second child */ struct _xmlElementContent *c2; /* second child */
struct _xmlElementContent *parent; /* parent */ struct _xmlElementContent *parent; /* parent */
const xmlChar *prefix; /* Namespace prefix */ const xmlChar *prefix; /* Namespace prefix */
}; };
/** /**
* xmlElementTypeVal: * xmlElementTypeVal:
* *
* The different possibilities for an element content type. * The different possibilities for an element content type.
*/ */
typedef enum { typedef enum {
XML_ELEMENT_TYPE_UNDEFINED = 0, XML_ELEMENT_TYPE_UNDEFINED = 0,
skipping to change at line 307 skipping to change at line 307
/** /**
* xmlElement: * xmlElement:
* *
* An XML Element declaration from a DTD. * An XML Element declaration from a DTD.
*/ */
typedef struct _xmlElement xmlElement; typedef struct _xmlElement xmlElement;
typedef xmlElement *xmlElementPtr; typedef xmlElement *xmlElementPtr;
struct _xmlElement { struct _xmlElement {
void *_private; /* application data */ void *_private; /* application data */
xmlElementType type; /* XML_ELEMENT_DECL, must be second ! */ xmlElementType type; /* XML_ELEMENT_DECL, must be second ! */
const xmlChar *name; /* Element name */ const xmlChar *name; /* Element name */
struct _xmlNode *children; /* NULL */ struct _xmlNode *children; /* NULL */
struct _xmlNode *last; /* NULL */ struct _xmlNode *last; /* NULL */
struct _xmlDtd *parent; /* -> DTD */ struct _xmlDtd *parent; /* -> DTD */
struct _xmlNode *next; /* next sibling link */ struct _xmlNode *next; /* next sibling link */
struct _xmlNode *prev; /* previous sibling link */ struct _xmlNode *prev; /* previous sibling link */
struct _xmlDoc *doc; /* the containing document */ struct _xmlDoc *doc; /* the containing document */
xmlElementTypeVal etype; /* The type */ xmlElementTypeVal etype; /* The type */
xmlElementContentPtr content; /* the allowed element content */ xmlElementContentPtr content; /* the allowed element content */
xmlAttributePtr attributes; /* List of the declared attributes * xmlAttributePtr attributes; /* List of the declared attributes */
/ const xmlChar *prefix; /* the namespace prefix if any */
const xmlChar *prefix; /* the namespace prefix if any */
#ifdef LIBXML_REGEXP_ENABLED #ifdef LIBXML_REGEXP_ENABLED
xmlRegexpPtr contModel; /* the validating regexp */ xmlRegexpPtr contModel; /* the validating regexp */
#else #else
void *contModel; void *contModel;
#endif #endif
}; };
/** /**
* XML_LOCAL_NAMESPACE: * XML_LOCAL_NAMESPACE:
* *
* A namespace declaration node. * A namespace declaration node.
*/ */
#define XML_LOCAL_NAMESPACE XML_NAMESPACE_DECL #define XML_LOCAL_NAMESPACE XML_NAMESPACE_DECL
typedef xmlElementType xmlNsType; typedef xmlElementType xmlNsType;
skipping to change at line 349 skipping to change at line 349
* An XML namespace. * An XML namespace.
* Note that prefix == NULL is valid, it defines the default namespace * Note that prefix == NULL is valid, it defines the default namespace
* within the subtree (until overridden). * within the subtree (until overridden).
* *
* xmlNsType is unified with xmlElementType. * xmlNsType is unified with xmlElementType.
*/ */
typedef struct _xmlNs xmlNs; typedef struct _xmlNs xmlNs;
typedef xmlNs *xmlNsPtr; typedef xmlNs *xmlNsPtr;
struct _xmlNs { struct _xmlNs {
struct _xmlNs *next; /* next Ns link for this node */ struct _xmlNs *next; /* next Ns link for this node */
xmlNsType type; /* global or local */ xmlNsType type; /* global or local */
const xmlChar *href; /* URL for the namespace */ const xmlChar *href; /* URL for the namespace */
const xmlChar *prefix; /* prefix for the namespace */ const xmlChar *prefix; /* prefix for the namespace */
void *_private; /* application data */ void *_private; /* application data */
struct _xmlDoc *context; /* normally an xmlDoc */ struct _xmlDoc *context; /* normally an xmlDoc */
}; };
/** /**
* xmlDtd: * xmlDtd:
* *
* An XML DTD, as defined by <!DOCTYPE ... There is actually one for * An XML DTD, as defined by <!DOCTYPE ... There is actually one for
* the internal subset and for the external subset. * the internal subset and for the external subset.
*/ */
typedef struct _xmlDtd xmlDtd; typedef struct _xmlDtd xmlDtd;
typedef xmlDtd *xmlDtdPtr; typedef xmlDtd *xmlDtdPtr;
struct _xmlDtd { struct _xmlDtd {
void *_private; /* application data */ void *_private; /* application data */
xmlElementType type; /* XML_DTD_NODE, must be second ! */ xmlElementType type; /* XML_DTD_NODE, must be second ! */
const xmlChar *name; /* Name of the DTD */ const xmlChar *name; /* Name of the DTD */
struct _xmlNode *children; /* the value of the property link */ struct _xmlNode *children; /* the value of the property link */
struct _xmlNode *last; /* last child link */ struct _xmlNode *last; /* last child link */
struct _xmlDoc *parent; /* child->parent link */ struct _xmlDoc *parent; /* child->parent link */
struct _xmlNode *next; /* next sibling link */ struct _xmlNode *next; /* next sibling link */
struct _xmlNode *prev; /* previous sibling link */ struct _xmlNode *prev; /* previous sibling link */
struct _xmlDoc *doc; /* the containing document */ struct _xmlDoc *doc; /* the containing document */
/* End of common part */ /* End of common part */
void *notations; /* Hash table for notations if any */ void *notations; /* Hash table for notations if any */
void *elements; /* Hash table for elements if any */ void *elements; /* Hash table for elements if any */
void *attributes; /* Hash table for attributes if any */ void *attributes; /* Hash table for attributes if any */
void *entities; /* Hash table for entities if any */ void *entities; /* Hash table for entities if any */
const xmlChar *ExternalID; /* External identifier for PUBLIC DTD */ const xmlChar *ExternalID; /* External identifier for PUBLIC DTD */
const xmlChar *SystemID; /* URI for a SYSTEM or PUBLIC DTD */ const xmlChar *SystemID; /* URI for a SYSTEM or PUBLIC DTD */
void *pentities; /* Hash table for param entities if any */ void *pentities; /* Hash table for param entities if any */
}; };
/** /**
* xmlAttr: * xmlAttr:
* *
* An attribute on an XML node. * An attribute on an XML node.
*/ */
typedef struct _xmlAttr xmlAttr; typedef struct _xmlAttr xmlAttr;
typedef xmlAttr *xmlAttrPtr; typedef xmlAttr *xmlAttrPtr;
struct _xmlAttr { struct _xmlAttr {
void *_private; /* application data */ void *_private; /* application data */
xmlElementType type; /* XML_ATTRIBUTE_NODE, must be second ! */ xmlElementType type; /* XML_ATTRIBUTE_NODE, must be second ! */
const xmlChar *name; /* the name of the property */ const xmlChar *name; /* the name of the property */
struct _xmlNode *children; /* the value of the property */ struct _xmlNode *children; /* the value of the property */
struct _xmlNode *last; /* NULL */ struct _xmlNode *last; /* NULL */
struct _xmlNode *parent; /* child->parent link */ struct _xmlNode *parent; /* child->parent link */
struct _xmlAttr *next; /* next sibling link */ struct _xmlAttr *next; /* next sibling link */
struct _xmlAttr *prev; /* previous sibling link */ struct _xmlAttr *prev; /* previous sibling link */
struct _xmlDoc *doc; /* the containing document */ struct _xmlDoc *doc; /* the containing document */
xmlNs *ns; /* pointer to the associated namespace */ xmlNs *ns; /* pointer to the associated namespace */
xmlAttributeType atype; /* the attribute type if validating */ xmlAttributeType atype; /* the attribute type if validating */
void *psvi; /* for type/PSVI informations */ void *psvi; /* for type/PSVI informations */
}; };
/** /**
* xmlID: * xmlID:
* *
* An XML ID instance. * An XML ID instance.
*/ */
typedef struct _xmlID xmlID; typedef struct _xmlID xmlID;
typedef xmlID *xmlIDPtr; typedef xmlID *xmlIDPtr;
struct _xmlID { struct _xmlID {
struct _xmlID *next; /* next ID */ struct _xmlID *next; /* next ID */
const xmlChar *value; /* The ID name */ const xmlChar *value; /* The ID name */
xmlAttrPtr attr; /* The attribute holding it */ xmlAttrPtr attr; /* The attribute holding it */
const xmlChar *name; /* The attribute if attr is not available */ const xmlChar *name; /* The attribute if attr is not available */
int lineno; /* The line number if attr is not available int lineno; /* The line number if attr is not availabl
*/ e */
struct _xmlDoc *doc; /* The document holding the ID */ struct _xmlDoc *doc; /* The document holding the ID */
}; };
/** /**
* xmlRef: * xmlRef:
* *
* An XML IDREF instance. * An XML IDREF instance.
*/ */
typedef struct _xmlRef xmlRef; typedef struct _xmlRef xmlRef;
typedef xmlRef *xmlRefPtr; typedef xmlRef *xmlRefPtr;
struct _xmlRef { struct _xmlRef {
struct _xmlRef *next; /* next Ref */ struct _xmlRef *next; /* next Ref */
const xmlChar *value; /* The Ref name */ const xmlChar *value; /* The Ref name */
xmlAttrPtr attr; /* The attribute holding it */ xmlAttrPtr attr; /* The attribute holding it */
const xmlChar *name; /* The attribute if attr is not available */ const xmlChar *name; /* The attribute if attr is not available */
int lineno; /* The line number if attr is not available int lineno; /* The line number if attr is not availabl
*/ e */
}; };
/** /**
* xmlNode: * xmlNode:
* *
* A node in an XML tree. * A node in an XML tree.
*/ */
typedef struct _xmlNode xmlNode; typedef struct _xmlNode xmlNode;
typedef xmlNode *xmlNodePtr; typedef xmlNode *xmlNodePtr;
struct _xmlNode { struct _xmlNode {
void *_private; /* application data */ void *_private; /* application data */
xmlElementType type; /* type number, must be second ! */ xmlElementType type; /* type number, must be second ! */
const xmlChar *name; /* the name of the node, or the entity */ const xmlChar *name; /* the name of the node, or the entity */
struct _xmlNode *children; /* parent->childs link */ struct _xmlNode *children; /* parent->childs link */
struct _xmlNode *last; /* last child link */ struct _xmlNode *last; /* last child link */
struct _xmlNode *parent; /* child->parent link */ struct _xmlNode *parent; /* child->parent link */
struct _xmlNode *next; /* next sibling link */ struct _xmlNode *next; /* next sibling link */
struct _xmlNode *prev; /* previous sibling link */ struct _xmlNode *prev; /* previous sibling link */
struct _xmlDoc *doc; /* the containing document */ struct _xmlDoc *doc; /* the containing document */
/* End of common part */ /* End of common part */
xmlNs *ns; /* pointer to the associated namespace */ xmlNs *ns; /* pointer to the associated namespace */
xmlChar *content; /* the content */ xmlChar *content; /* the content */
struct _xmlAttr *properties;/* properties list */ struct _xmlAttr *properties;/* properties list */
xmlNs *nsDef; /* namespace definitions on this node */ xmlNs *nsDef; /* namespace definitions on this node */
void *psvi; /* for type/PSVI informations */ void *psvi; /* for type/PSVI informations */
unsigned short line; /* line number */ unsigned short line; /* line number */
unsigned short extra; /* extra data for XPath/XSLT */ unsigned short extra; /* extra data for XPath/XSLT */
}; };
/** /**
* XML_GET_CONTENT: * XML_GET_CONTENT:
* *
* Macro to extract the content pointer of a node. * Macro to extract the content pointer of a node.
*/ */
#define XML_GET_CONTENT(n) \ #define XML_GET_CONTENT(n) \
((n)->type == XML_ELEMENT_NODE ? NULL : (n)->content) ((n)->type == XML_ELEMENT_NODE ? NULL : (n)->content)
/** /**
* XML_GET_LINE: * XML_GET_LINE:
* *
* Macro to extract the line number of an element node. * Macro to extract the line number of an element node.
*/ */
#define XML_GET_LINE(n) \ #define XML_GET_LINE(n) \
(xmlGetLineNo(n)) (xmlGetLineNo(n))
/** /**
* xmlDocProperty * xmlDocProperty
* *
* Set of properties of the document as found by the parser * Set of properties of the document as found by the parser
* Some of them are linked to similary named xmlParserOption * Some of them are linked to similary named xmlParserOption
*/ */
typedef enum { typedef enum {
XML_DOC_WELLFORMED = 1<<0, /* document is XML well formed */ XML_DOC_WELLFORMED = 1<<0, /* document is XML well formed */
XML_DOC_NSVALID = 1<<1, /* document is Namespace valid */ XML_DOC_NSVALID = 1<<1, /* document is Namespace valid */
XML_DOC_OLD10 = 1<<2, /* parsed with old XML-1.0 parser */ XML_DOC_OLD10 = 1<<2, /* parsed with old XML-1.0 parser */
XML_DOC_DTDVALID = 1<<3, /* DTD validation was successful */ XML_DOC_DTDVALID = 1<<3, /* DTD validation was successful */
XML_DOC_XINCLUDE = 1<<4, /* XInclude substitution was done */ XML_DOC_XINCLUDE = 1<<4, /* XInclude substitution was done */
XML_DOC_USERBUILT = 1<<5, /* Document was built using the API XML_DOC_USERBUILT = 1<<5, /* Document was built using the API
and not by parsing an instance * / and not by parsing an instance * /
XML_DOC_INTERNAL = 1<<6, /* built for internal processing */ XML_DOC_INTERNAL = 1<<6, /* built for internal processing */
XML_DOC_HTML = 1<<7 /* parsed or built HTML document */ XML_DOC_HTML = 1<<7 /* parsed or built HTML document */
} xmlDocProperties; } xmlDocProperties;
/** /**
* xmlDoc: * xmlDoc:
* *
* An XML document. * An XML document.
*/ */
typedef struct _xmlDoc xmlDoc; typedef struct _xmlDoc xmlDoc;
typedef xmlDoc *xmlDocPtr; typedef xmlDoc *xmlDocPtr;
struct _xmlDoc { struct _xmlDoc {
void *_private; /* application data */ void *_private; /* application data */
xmlElementType type; /* XML_DOCUMENT_NODE, must be second ! */ xmlElementType type; /* XML_DOCUMENT_NODE, must be second ! */
char *name; /* name/filename/URI of the document */ char *name; /* name/filename/URI of the document */
struct _xmlNode *children; /* the document tree */ struct _xmlNode *children; /* the document tree */
struct _xmlNode *last; /* last child link */ struct _xmlNode *last; /* last child link */
struct _xmlNode *parent; /* child->parent link */ struct _xmlNode *parent; /* child->parent link */
struct _xmlNode *next; /* next sibling link */ struct _xmlNode *next; /* next sibling link */
struct _xmlNode *prev; /* previous sibling link */ struct _xmlNode *prev; /* previous sibling link */
struct _xmlDoc *doc; /* autoreference to itself */ struct _xmlDoc *doc; /* autoreference to itself */
/* End of common part */ /* End of common part */
int compression;/* level of zlib compression */ int compression;/* level of zlib compression */
int standalone; /* standalone document (no external refs) int standalone; /* standalone document (no external refs)
1 if standalone="yes" 1 if standalone="yes"
0 if standalone="no" 0 if standalone="no"
-1 if there is no XML declaration -1 if there is no XML declaration
-2 if there is an XML declaration, but n -2 if there is an XML declaration, but no
o standalone attribute was specified */
standalone attribute was specified * struct _xmlDtd *intSubset; /* the document internal subset */
/ struct _xmlDtd *extSubset; /* the document external subset */
struct _xmlDtd *intSubset; /* the document internal subset */ struct _xmlNs *oldNs; /* Global namespace, the old way */
struct _xmlDtd *extSubset; /* the document external subset */ const xmlChar *version; /* the XML version string */
struct _xmlNs *oldNs; /* Global namespace, the old way */
const xmlChar *version; /* the XML version string */
const xmlChar *encoding; /* external initial encoding, if any */ const xmlChar *encoding; /* external initial encoding, if any */
void *ids; /* Hash table for ID attributes if any */ void *ids; /* Hash table for ID attributes if any */
void *refs; /* Hash table for IDREFs attributes if any */ void *refs; /* Hash table for IDREFs attributes if any */
const xmlChar *URL; /* The URI for that document */ const xmlChar *URL; /* The URI for that document */
int charset; /* encoding of the in-memory content int charset; /* encoding of the in-memory content
actually an xmlCharEncoding */ actually an xmlCharEncoding */
struct _xmlDict *dict; /* dict used to allocate names or NULL */ struct _xmlDict *dict; /* dict used to allocate names or NULL */
void *psvi; /* for type/PSVI informations */ void *psvi; /* for type/PSVI informations */
int parseFlags; /* set of xmlParserOption used to pa int parseFlags; /* set of xmlParserOption used to parse
rse the the
document */ document */
int properties; /* set of xmlDocProperties for this int properties; /* set of xmlDocProperties for this docu
document ment
set at the end of parsing */ set at the end of parsing */
}; };
typedef struct _xmlDOMWrapCtxt xmlDOMWrapCtxt; typedef struct _xmlDOMWrapCtxt xmlDOMWrapCtxt;
typedef xmlDOMWrapCtxt *xmlDOMWrapCtxtPtr; typedef xmlDOMWrapCtxt *xmlDOMWrapCtxtPtr;
/** /**
* xmlDOMWrapAcquireNsFunction: * xmlDOMWrapAcquireNsFunction:
* @ctxt: a DOM wrapper context * @ctxt: a DOM wrapper context
* @node: the context node (element or attribute) * @node: the context node (element or attribute)
* @nsName: the requested namespace name * @nsName: the requested namespace name
* @nsPrefix: the requested namespace prefix * @nsPrefix: the requested namespace prefix
* *
* A function called to acquire namespaces (xmlNs) from the wrapper. * A function called to acquire namespaces (xmlNs) from the wrapper.
* *
* Returns an xmlNsPtr or NULL in case of an error. * Returns an xmlNsPtr or NULL in case of an error.
*/ */
typedef xmlNsPtr (*xmlDOMWrapAcquireNsFunction) (xmlDOMWrapCtxtPtr ctxt, typedef xmlNsPtr (*xmlDOMWrapAcquireNsFunction) (xmlDOMWrapCtxtPtr ctxt,
xmlNodePtr node, xmlNodePtr node,
const xmlChar *nsName, const xmlChar *nsName,
const xmlChar *nsPrefix); const xmlChar *nsPrefix);
/** /**
* xmlDOMWrapCtxt: * xmlDOMWrapCtxt:
* *
* Context for DOM wrapper-operations. * Context for DOM wrapper-operations.
*/ */
struct _xmlDOMWrapCtxt { struct _xmlDOMWrapCtxt {
void * _private; void * _private;
/* /*
* The type of this context, just in case we need specialized * The type of this context, just in case we need specialized
skipping to change at line 618 skipping to change at line 618
/* /*
* Variables. * Variables.
*/ */
/* /*
* Some helper functions * Some helper functions
*/ */
#if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_XPATH_ENABLED) || define d(LIBXML_SCHEMAS_ENABLED) || defined(LIBXML_DEBUG_ENABLED) || defined (LIBX ML_HTML_ENABLED) || defined(LIBXML_SAX1_ENABLED) || defined(LIBXML_HTML_ENA BLED) || defined(LIBXML_WRITER_ENABLED) || defined(LIBXML_DOCB_ENABLED) #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_XPATH_ENABLED) || define d(LIBXML_SCHEMAS_ENABLED) || defined(LIBXML_DEBUG_ENABLED) || defined (LIBX ML_HTML_ENABLED) || defined(LIBXML_SAX1_ENABLED) || defined(LIBXML_HTML_ENA BLED) || defined(LIBXML_WRITER_ENABLED) || defined(LIBXML_DOCB_ENABLED)
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlValidateNCName (const xmlChar *value, xmlValidateNCName (const xmlChar *value,
int space); int space);
#endif #endif
#if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED) #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED)
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlValidateQName (const xmlChar *value, xmlValidateQName (const xmlChar *value,
int space); int space);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlValidateName (const xmlChar *value, xmlValidateName (const xmlChar *value,
int space); int space);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlValidateNMToken (const xmlChar *value, xmlValidateNMToken (const xmlChar *value,
int space); int space);
#endif #endif
XMLPUBFUN xmlChar * XMLCALL XMLPUBFUN xmlChar * XMLCALL
xmlBuildQName (const xmlChar *ncname, xmlBuildQName (const xmlChar *ncname,
const xmlChar *prefix, const xmlChar *prefix,
xmlChar *memory, xmlChar *memory,
int len); int len);
XMLPUBFUN xmlChar * XMLCALL XMLPUBFUN xmlChar * XMLCALL
xmlSplitQName2 (const xmlChar *name, xmlSplitQName2 (const xmlChar *name,
xmlChar **prefix); xmlChar **prefix);
XMLPUBFUN const xmlChar * XMLCALL XMLPUBFUN const xmlChar * XMLCALL
xmlSplitQName3 (const xmlChar *name, xmlSplitQName3 (const xmlChar *name,
int *len); int *len);
/* /*
* Handling Buffers. * Handling Buffers.
*/ */
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlSetBufferAllocationScheme(xmlBufferAllocationScheme schem e); xmlSetBufferAllocationScheme(xmlBufferAllocationScheme scheme);
XMLPUBFUN xmlBufferAllocationScheme XMLCALL XMLPUBFUN xmlBufferAllocationScheme XMLCALL
xmlGetBufferAllocationScheme(void); xmlGetBufferAllocationScheme(void);
XMLPUBFUN xmlBufferPtr XMLCALL XMLPUBFUN xmlBufferPtr XMLCALL
xmlBufferCreate (void); xmlBufferCreate (void);
XMLPUBFUN xmlBufferPtr XMLCALL XMLPUBFUN xmlBufferPtr XMLCALL
xmlBufferCreateSize (size_t size); xmlBufferCreateSize (size_t size);
XMLPUBFUN xmlBufferPtr XMLCALL XMLPUBFUN xmlBufferPtr XMLCALL
xmlBufferCreateStatic (void *mem, xmlBufferCreateStatic (void *mem,
size_t size); size_t size);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlBufferResize (xmlBufferPtr buf, xmlBufferResize (xmlBufferPtr buf,
unsigned int size); unsigned int size);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlBufferFree (xmlBufferPtr buf); xmlBufferFree (xmlBufferPtr buf);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlBufferDump (FILE *file, xmlBufferDump (FILE *file,
xmlBufferPtr buf); xmlBufferPtr buf);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlBufferAdd (xmlBufferPtr buf, xmlBufferAdd (xmlBufferPtr buf,
const xmlChar *str, const xmlChar *str,
int len); int len);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlBufferAddHead (xmlBufferPtr buf, xmlBufferAddHead (xmlBufferPtr buf,
const xmlChar *str, const xmlChar *str,
int len); int len);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlBufferCat (xmlBufferPtr buf, xmlBufferCat (xmlBufferPtr buf,
const xmlChar *str); const xmlChar *str);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlBufferCCat (xmlBufferPtr buf, xmlBufferCCat (xmlBufferPtr buf,
const char *str); const char *str);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlBufferShrink (xmlBufferPtr buf, xmlBufferShrink (xmlBufferPtr buf,
unsigned int len); unsigned int len);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlBufferGrow (xmlBufferPtr buf, xmlBufferGrow (xmlBufferPtr buf,
unsigned int len); unsigned int len);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlBufferEmpty (xmlBufferPtr buf); xmlBufferEmpty (xmlBufferPtr buf);
XMLPUBFUN const xmlChar* XMLCALL XMLPUBFUN const xmlChar* XMLCALL
xmlBufferContent (const xmlBufferPtr buf); xmlBufferContent (const xmlBufferPtr buf);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlBufferSetAllocationScheme(xmlBufferPtr buf, xmlBufferSetAllocationScheme(xmlBufferPtr buf,
xmlBufferAllocationScheme scheme); xmlBufferAllocationScheme scheme);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlBufferLength (const xmlBufferPtr buf); xmlBufferLength (const xmlBufferPtr buf);
/* /*
* Creating/freeing new structures. * Creating/freeing new structures.
*/ */
XMLPUBFUN xmlDtdPtr XMLCALL XMLPUBFUN xmlDtdPtr XMLCALL
xmlCreateIntSubset (xmlDocPtr doc, xmlCreateIntSubset (xmlDocPtr doc,
const xmlChar *name, const xmlChar *name,
const xmlChar *ExternalID, const xmlChar *ExternalID,
const xmlChar *SystemID); const xmlChar *SystemID);
XMLPUBFUN xmlDtdPtr XMLCALL XMLPUBFUN xmlDtdPtr XMLCALL
xmlNewDtd (xmlDocPtr doc, xmlNewDtd (xmlDocPtr doc,
const xmlChar *name, const xmlChar *name,
const xmlChar *ExternalID, const xmlChar *ExternalID,
const xmlChar *SystemID); const xmlChar *SystemID);
XMLPUBFUN xmlDtdPtr XMLCALL XMLPUBFUN xmlDtdPtr XMLCALL
xmlGetIntSubset (xmlDocPtr doc); xmlGetIntSubset (xmlDocPtr doc);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlFreeDtd (xmlDtdPtr cur); xmlFreeDtd (xmlDtdPtr cur);
#ifdef LIBXML_LEGACY_ENABLED #ifdef LIBXML_LEGACY_ENABLED
XMLPUBFUN xmlNsPtr XMLCALL XMLPUBFUN xmlNsPtr XMLCALL
xmlNewGlobalNs (xmlDocPtr doc, xmlNewGlobalNs (xmlDocPtr doc,
const xmlChar *href, const xmlChar *href,
const xmlChar *prefix); const xmlChar *prefix);
#endif /* LIBXML_LEGACY_ENABLED */ #endif /* LIBXML_LEGACY_ENABLED */
XMLPUBFUN xmlNsPtr XMLCALL XMLPUBFUN xmlNsPtr XMLCALL
xmlNewNs (xmlNodePtr node, xmlNewNs (xmlNodePtr node,
const xmlChar *href, const xmlChar *href,
const xmlChar *prefix); const xmlChar *prefix);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlFreeNs (xmlNsPtr cur); xmlFreeNs (xmlNsPtr cur);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlFreeNsList (xmlNsPtr cur); xmlFreeNsList (xmlNsPtr cur);
XMLPUBFUN xmlDocPtr XMLCALL XMLPUBFUN xmlDocPtr XMLCALL
xmlNewDoc (const xmlChar *version); xmlNewDoc (const xmlChar *version);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlFreeDoc (xmlDocPtr cur); xmlFreeDoc (xmlDocPtr cur);
XMLPUBFUN xmlAttrPtr XMLCALL XMLPUBFUN xmlAttrPtr XMLCALL
xmlNewDocProp (xmlDocPtr doc, xmlNewDocProp (xmlDocPtr doc,
const xmlChar *name, const xmlChar *name,
const xmlChar *value); const xmlChar *value);
#if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_HTML_ENABLED) || \ #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_HTML_ENABLED) || \
defined(LIBXML_SCHEMAS_ENABLED) defined(LIBXML_SCHEMAS_ENABLED)
XMLPUBFUN xmlAttrPtr XMLCALL XMLPUBFUN xmlAttrPtr XMLCALL
xmlNewProp (xmlNodePtr node, xmlNewProp (xmlNodePtr node,
const xmlChar *name, const xmlChar *name,
const xmlChar *value); const xmlChar *value);
#endif #endif
XMLPUBFUN xmlAttrPtr XMLCALL XMLPUBFUN xmlAttrPtr XMLCALL
xmlNewNsProp (xmlNodePtr node, xmlNewNsProp (xmlNodePtr node,
xmlNsPtr ns, xmlNsPtr ns,
const xmlChar *name, const xmlChar *name,
const xmlChar *value); const xmlChar *value);
XMLPUBFUN xmlAttrPtr XMLCALL XMLPUBFUN xmlAttrPtr XMLCALL
xmlNewNsPropEatName (xmlNodePtr node, xmlNewNsPropEatName (xmlNodePtr node,
xmlNsPtr ns, xmlNsPtr ns,
xmlChar *name, xmlChar *name,
const xmlChar *value); const xmlChar *value);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlFreePropList (xmlAttrPtr cur); xmlFreePropList (xmlAttrPtr cur);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlFreeProp (xmlAttrPtr cur); xmlFreeProp (xmlAttrPtr cur);
XMLPUBFUN xmlAttrPtr XMLCALL XMLPUBFUN xmlAttrPtr XMLCALL
xmlCopyProp (xmlNodePtr target, xmlCopyProp (xmlNodePtr target,
xmlAttrPtr cur); xmlAttrPtr cur);
XMLPUBFUN xmlAttrPtr XMLCALL XMLPUBFUN xmlAttrPtr XMLCALL
xmlCopyPropList (xmlNodePtr target, xmlCopyPropList (xmlNodePtr target,
xmlAttrPtr cur); xmlAttrPtr cur);
#ifdef LIBXML_TREE_ENABLED #ifdef LIBXML_TREE_ENABLED
XMLPUBFUN xmlDtdPtr XMLCALL XMLPUBFUN xmlDtdPtr XMLCALL
xmlCopyDtd (xmlDtdPtr dtd); xmlCopyDtd (xmlDtdPtr dtd);
#endif /* LIBXML_TREE_ENABLED */ #endif /* LIBXML_TREE_ENABLED */
#if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED) #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED)
XMLPUBFUN xmlDocPtr XMLCALL XMLPUBFUN xmlDocPtr XMLCALL
xmlCopyDoc (xmlDocPtr doc, xmlCopyDoc (xmlDocPtr doc,
int recursive); int recursive);
#endif /* defined(LIBXML_TREE_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED) * / #endif /* defined(LIBXML_TREE_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED) * /
/* /*
* Creating new nodes. * Creating new nodes.
*/ */
XMLPUBFUN xmlNodePtr XMLCALL XMLPUBFUN xmlNodePtr XMLCALL
xmlNewDocNode (xmlDocPtr doc, xmlNewDocNode (xmlDocPtr doc,
xmlNsPtr ns, xmlNsPtr ns,
const xmlChar *name, const xmlChar *name,
const xmlChar *content); const xmlChar *content);
XMLPUBFUN xmlNodePtr XMLCALL XMLPUBFUN xmlNodePtr XMLCALL
xmlNewDocNodeEatName (xmlDocPtr doc, xmlNewDocNodeEatName (xmlDocPtr doc,
xmlNsPtr ns, xmlNsPtr ns,
xmlChar *name, xmlChar *name,
const xmlChar *content); const xmlChar *content);
XMLPUBFUN xmlNodePtr XMLCALL XMLPUBFUN xmlNodePtr XMLCALL
xmlNewNode (xmlNsPtr ns, xmlNewNode (xmlNsPtr ns,
const xmlChar *name); const xmlChar *name);
XMLPUBFUN xmlNodePtr XMLCALL XMLPUBFUN xmlNodePtr XMLCALL
xmlNewNodeEatName (xmlNsPtr ns, xmlNewNodeEatName (xmlNsPtr ns,
xmlChar *name); xmlChar *name);
#if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED) #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED)
XMLPUBFUN xmlNodePtr XMLCALL XMLPUBFUN xmlNodePtr XMLCALL
xmlNewChild (xmlNodePtr parent, xmlNewChild (xmlNodePtr parent,
xmlNsPtr ns, xmlNsPtr ns,
const xmlChar *name, const xmlChar *name,
const xmlChar *content); const xmlChar *content);
#endif #endif
XMLPUBFUN xmlNodePtr XMLCALL XMLPUBFUN xmlNodePtr XMLCALL
xmlNewDocText (xmlDocPtr doc, xmlNewDocText (xmlDocPtr doc,
const xmlChar *content); const xmlChar *content);
XMLPUBFUN xmlNodePtr XMLCALL XMLPUBFUN xmlNodePtr XMLCALL
xmlNewText (const xmlChar *content); xmlNewText (const xmlChar *content);
XMLPUBFUN xmlNodePtr XMLCALL XMLPUBFUN xmlNodePtr XMLCALL
xmlNewDocPI (xmlDocPtr doc, xmlNewDocPI (xmlDocPtr doc,
const xmlChar *name, const xmlChar *name,
const xmlChar *content); const xmlChar *content);
XMLPUBFUN xmlNodePtr XMLCALL XMLPUBFUN xmlNodePtr XMLCALL
xmlNewPI (const xmlChar *name, xmlNewPI (const xmlChar *name,
const xmlChar *content); const xmlChar *content);
XMLPUBFUN xmlNodePtr XMLCALL XMLPUBFUN xmlNodePtr XMLCALL
xmlNewDocTextLen (xmlDocPtr doc, xmlNewDocTextLen (xmlDocPtr doc,
const xmlChar *content, const xmlChar *content,
int len); int len);
XMLPUBFUN xmlNodePtr XMLCALL XMLPUBFUN xmlNodePtr XMLCALL
xmlNewTextLen (const xmlChar *content, xmlNewTextLen (const xmlChar *content,
int len); int len);
XMLPUBFUN xmlNodePtr XMLCALL XMLPUBFUN xmlNodePtr XMLCALL
xmlNewDocComment (xmlDocPtr doc, xmlNewDocComment (xmlDocPtr doc,
const xmlChar *content); const xmlChar *content);
XMLPUBFUN xmlNodePtr XMLCALL XMLPUBFUN xmlNodePtr XMLCALL
xmlNewComment (const xmlChar *content); xmlNewComment (const xmlChar *content);
XMLPUBFUN xmlNodePtr XMLCALL XMLPUBFUN xmlNodePtr XMLCALL
xmlNewCDataBlock (xmlDocPtr doc, xmlNewCDataBlock (xmlDocPtr doc,
const xmlChar *content, const xmlChar *content,
int len); int len);
XMLPUBFUN xmlNodePtr XMLCALL XMLPUBFUN xmlNodePtr XMLCALL
xmlNewCharRef (xmlDocPtr doc, xmlNewCharRef (xmlDocPtr doc,
const xmlChar *name); const xmlChar *name);
XMLPUBFUN xmlNodePtr XMLCALL XMLPUBFUN xmlNodePtr XMLCALL
xmlNewReference (xmlDocPtr doc, xmlNewReference (xmlDocPtr doc,
const xmlChar *name); const xmlChar *name);
XMLPUBFUN xmlNodePtr XMLCALL XMLPUBFUN xmlNodePtr XMLCALL
xmlCopyNode (const xmlNodePtr node, xmlCopyNode (const xmlNodePtr node,
int recursive); int recursive);
XMLPUBFUN xmlNodePtr XMLCALL XMLPUBFUN xmlNodePtr XMLCALL
xmlDocCopyNode (const xmlNodePtr node, xmlDocCopyNode (const xmlNodePtr node,
xmlDocPtr doc, xmlDocPtr doc,
int recursive); int recursive);
XMLPUBFUN xmlNodePtr XMLCALL XMLPUBFUN xmlNodePtr XMLCALL
xmlDocCopyNodeList (xmlDocPtr doc, xmlDocCopyNodeList (xmlDocPtr doc,
const xmlNodePtr node); const xmlNodePtr node);
XMLPUBFUN xmlNodePtr XMLCALL XMLPUBFUN xmlNodePtr XMLCALL
xmlCopyNodeList (const xmlNodePtr node); xmlCopyNodeList (const xmlNodePtr node);
#ifdef LIBXML_TREE_ENABLED #ifdef LIBXML_TREE_ENABLED
XMLPUBFUN xmlNodePtr XMLCALL XMLPUBFUN xmlNodePtr XMLCALL
xmlNewTextChild (xmlNodePtr parent, xmlNewTextChild (xmlNodePtr parent,
xmlNsPtr ns, xmlNsPtr ns,
const xmlChar *name, const xmlChar *name,
const xmlChar *content); const xmlChar *content);
XMLPUBFUN xmlNodePtr XMLCALL XMLPUBFUN xmlNodePtr XMLCALL
xmlNewDocRawNode (xmlDocPtr doc, xmlNewDocRawNode (xmlDocPtr doc,
xmlNsPtr ns, xmlNsPtr ns,
const xmlChar *name, const xmlChar *name,
const xmlChar *content); const xmlChar *content);
XMLPUBFUN xmlNodePtr XMLCALL XMLPUBFUN xmlNodePtr XMLCALL
xmlNewDocFragment (xmlDocPtr doc); xmlNewDocFragment (xmlDocPtr doc);
#endif /* LIBXML_TREE_ENABLED */ #endif /* LIBXML_TREE_ENABLED */
/* /*
* Navigating. * Navigating.
*/ */
XMLPUBFUN long XMLCALL XMLPUBFUN long XMLCALL
xmlGetLineNo (xmlNodePtr node); xmlGetLineNo (xmlNodePtr node);
#if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_DEBUG_ENABLED) #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_DEBUG_ENABLED)
XMLPUBFUN xmlChar * XMLCALL XMLPUBFUN xmlChar * XMLCALL
xmlGetNodePath (xmlNodePtr node); xmlGetNodePath (xmlNodePtr node);
#endif /* defined(LIBXML_TREE_ENABLED) || defined(LIBXML_DEBUG_ENABLED) */ #endif /* defined(LIBXML_TREE_ENABLED) || defined(LIBXML_DEBUG_ENABLED) */
XMLPUBFUN xmlNodePtr XMLCALL XMLPUBFUN xmlNodePtr XMLCALL
xmlDocGetRootElement (xmlDocPtr doc); xmlDocGetRootElement (xmlDocPtr doc);
XMLPUBFUN xmlNodePtr XMLCALL XMLPUBFUN xmlNodePtr XMLCALL
xmlGetLastChild (xmlNodePtr parent); xmlGetLastChild (xmlNodePtr parent);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlNodeIsText (xmlNodePtr node); xmlNodeIsText (xmlNodePtr node);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlIsBlankNode (xmlNodePtr node); xmlIsBlankNode (xmlNodePtr node);
/* /*
* Changing the structure. * Changing the structure.
*/ */
#if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_WRITER_ENABLED) #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_WRITER_ENABLED)
XMLPUBFUN xmlNodePtr XMLCALL XMLPUBFUN xmlNodePtr XMLCALL
xmlDocSetRootElement (xmlDocPtr doc, xmlDocSetRootElement (xmlDocPtr doc,
xmlNodePtr root); xmlNodePtr root);
#endif /* defined(LIBXML_TREE_ENABLED) || defined(LIBXML_WRITER_ENABLED) */ #endif /* defined(LIBXML_TREE_ENABLED) || defined(LIBXML_WRITER_ENABLED) */
#ifdef LIBXML_TREE_ENABLED #ifdef LIBXML_TREE_ENABLED
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlNodeSetName (xmlNodePtr cur, xmlNodeSetName (xmlNodePtr cur,
const xmlChar *name); const xmlChar *name);
#endif /* LIBXML_TREE_ENABLED */ #endif /* LIBXML_TREE_ENABLED */
XMLPUBFUN xmlNodePtr XMLCALL XMLPUBFUN xmlNodePtr XMLCALL
xmlAddChild (xmlNodePtr parent, xmlAddChild (xmlNodePtr parent,
xmlNodePtr cur); xmlNodePtr cur);
XMLPUBFUN xmlNodePtr XMLCALL XMLPUBFUN xmlNodePtr XMLCALL
xmlAddChildList (xmlNodePtr parent, xmlAddChildList (xmlNodePtr parent,
xmlNodePtr cur); xmlNodePtr cur);
#if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_WRITER_ENABLED) #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_WRITER_ENABLED)
XMLPUBFUN xmlNodePtr XMLCALL XMLPUBFUN xmlNodePtr XMLCALL
xmlReplaceNode (xmlNodePtr old, xmlReplaceNode (xmlNodePtr old,
xmlNodePtr cur); xmlNodePtr cur);
#endif /* defined(LIBXML_TREE_ENABLED) || defined(LIBXML_WRITER_ENABLED) */ #endif /* defined(LIBXML_TREE_ENABLED) || defined(LIBXML_WRITER_ENABLED) */
#if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_HTML_ENABLED) || \ #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_HTML_ENABLED) || \
defined(LIBXML_SCHEMAS_ENABLED) defined(LIBXML_SCHEMAS_ENABLED)
XMLPUBFUN xmlNodePtr XMLCALL XMLPUBFUN xmlNodePtr XMLCALL
xmlAddPrevSibling (xmlNodePtr cur, xmlAddPrevSibling (xmlNodePtr cur,
xmlNodePtr elem); xmlNodePtr elem);
#endif /* LIBXML_TREE_ENABLED || LIBXML_HTML_ENABLED || LIBXML_SCHEMAS_ENAB LED */ #endif /* LIBXML_TREE_ENABLED || LIBXML_HTML_ENABLED || LIBXML_SCHEMAS_ENAB LED */
XMLPUBFUN xmlNodePtr XMLCALL XMLPUBFUN xmlNodePtr XMLCALL
xmlAddSibling (xmlNodePtr cur, xmlAddSibling (xmlNodePtr cur,
xmlNodePtr elem); xmlNodePtr elem);
XMLPUBFUN xmlNodePtr XMLCALL XMLPUBFUN xmlNodePtr XMLCALL
xmlAddNextSibling (xmlNodePtr cur, xmlAddNextSibling (xmlNodePtr cur,
xmlNodePtr elem); xmlNodePtr elem);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlUnlinkNode (xmlNodePtr cur); xmlUnlinkNode (xmlNodePtr cur);
XMLPUBFUN xmlNodePtr XMLCALL XMLPUBFUN xmlNodePtr XMLCALL
xmlTextMerge (xmlNodePtr first, xmlTextMerge (xmlNodePtr first,
xmlNodePtr second); xmlNodePtr second);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlTextConcat (xmlNodePtr node, xmlTextConcat (xmlNodePtr node,
const xmlChar *content, const xmlChar *content,
int len); int len);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlFreeNodeList (xmlNodePtr cur); xmlFreeNodeList (xmlNodePtr cur);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlFreeNode (xmlNodePtr cur); xmlFreeNode (xmlNodePtr cur);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlSetTreeDoc (xmlNodePtr tree, xmlSetTreeDoc (xmlNodePtr tree,
xmlDocPtr doc); xmlDocPtr doc);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlSetListDoc (xmlNodePtr list, xmlSetListDoc (xmlNodePtr list,
xmlDocPtr doc); xmlDocPtr doc);
/* /*
* Namespaces. * Namespaces.
*/ */
XMLPUBFUN xmlNsPtr XMLCALL XMLPUBFUN xmlNsPtr XMLCALL
xmlSearchNs (xmlDocPtr doc, xmlSearchNs (xmlDocPtr doc,
xmlNodePtr node, xmlNodePtr node,
const xmlChar *nameSpace); const xmlChar *nameSpace);
XMLPUBFUN xmlNsPtr XMLCALL XMLPUBFUN xmlNsPtr XMLCALL
xmlSearchNsByHref (xmlDocPtr doc, xmlSearchNsByHref (xmlDocPtr doc,
xmlNodePtr node, xmlNodePtr node,
const xmlChar *href); const xmlChar *href);
#if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_XPATH_ENABLED) || define d(LIBXML_SCHEMAS_ENABLED) #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_XPATH_ENABLED) || define d(LIBXML_SCHEMAS_ENABLED)
XMLPUBFUN xmlNsPtr * XMLCALL XMLPUBFUN xmlNsPtr * XMLCALL
xmlGetNsList (xmlDocPtr doc, xmlGetNsList (xmlDocPtr doc,
xmlNodePtr node); xmlNodePtr node);
#endif /* defined(LIBXML_TREE_ENABLED) || defined(LIBXML_XPATH_ENABLED) */ #endif /* defined(LIBXML_TREE_ENABLED) || defined(LIBXML_XPATH_ENABLED) */
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlSetNs (xmlNodePtr node, xmlSetNs (xmlNodePtr node,
xmlNsPtr ns); xmlNsPtr ns);
XMLPUBFUN xmlNsPtr XMLCALL XMLPUBFUN xmlNsPtr XMLCALL
xmlCopyNamespace (xmlNsPtr cur); xmlCopyNamespace (xmlNsPtr cur);
XMLPUBFUN xmlNsPtr XMLCALL XMLPUBFUN xmlNsPtr XMLCALL
xmlCopyNamespaceList (xmlNsPtr cur); xmlCopyNamespaceList (xmlNsPtr cur);
/* /*
* Changing the content. * Changing the content.
*/ */
#if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_XINCLUDE_ENABLED) || def ined(LIBXML_SCHEMAS_ENABLED) || defined(LIBXML_HTML_ENABLED) #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_XINCLUDE_ENABLED) || def ined(LIBXML_SCHEMAS_ENABLED) || defined(LIBXML_HTML_ENABLED)
XMLPUBFUN xmlAttrPtr XMLCALL XMLPUBFUN xmlAttrPtr XMLCALL
xmlSetProp (xmlNodePtr node, xmlSetProp (xmlNodePtr node,
const xmlChar *name, const xmlChar *name,
const xmlChar *value); const xmlChar *value);
XMLPUBFUN xmlAttrPtr XMLCALL XMLPUBFUN xmlAttrPtr XMLCALL
xmlSetNsProp (xmlNodePtr node, xmlSetNsProp (xmlNodePtr node,
xmlNsPtr ns, xmlNsPtr ns,
const xmlChar *name, const xmlChar *name,
const xmlChar *value); const xmlChar *value);
#endif /* defined(LIBXML_TREE_ENABLED) || defined(LIBXML_XINCLUDE_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED) || defined(LIBXML_HTML_ENABLED) */ #endif /* defined(LIBXML_TREE_ENABLED) || defined(LIBXML_XINCLUDE_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED) || defined(LIBXML_HTML_ENABLED) */
XMLPUBFUN xmlChar * XMLCALL XMLPUBFUN xmlChar * XMLCALL
xmlGetNoNsProp (xmlNodePtr node, xmlGetNoNsProp (xmlNodePtr node,
const xmlChar *name); const xmlChar *name);
XMLPUBFUN xmlChar * XMLCALL XMLPUBFUN xmlChar * XMLCALL
xmlGetProp (xmlNodePtr node, xmlGetProp (xmlNodePtr node,
const xmlChar *name); const xmlChar *name);
XMLPUBFUN xmlAttrPtr XMLCALL XMLPUBFUN xmlAttrPtr XMLCALL
xmlHasProp (xmlNodePtr node, xmlHasProp (xmlNodePtr node,
const xmlChar *name); const xmlChar *name);
XMLPUBFUN xmlAttrPtr XMLCALL XMLPUBFUN xmlAttrPtr XMLCALL
xmlHasNsProp (xmlNodePtr node, xmlHasNsProp (xmlNodePtr node,
const xmlChar *name, const xmlChar *name,
const xmlChar *nameSpace); const xmlChar *nameSpace);
XMLPUBFUN xmlChar * XMLCALL XMLPUBFUN xmlChar * XMLCALL
xmlGetNsProp (xmlNodePtr node, xmlGetNsProp (xmlNodePtr node,
const xmlChar *name, const xmlChar *name,
const xmlChar *nameSpace); const xmlChar *nameSpace);
XMLPUBFUN xmlNodePtr XMLCALL XMLPUBFUN xmlNodePtr XMLCALL
xmlStringGetNodeList (xmlDocPtr doc, xmlStringGetNodeList (xmlDocPtr doc,
const xmlChar *value); const xmlChar *value);
XMLPUBFUN xmlNodePtr XMLCALL XMLPUBFUN xmlNodePtr XMLCALL
xmlStringLenGetNodeList (xmlDocPtr doc, xmlStringLenGetNodeList (xmlDocPtr doc,
const xmlChar *value, const xmlChar *value,
int len); int len);
XMLPUBFUN xmlChar * XMLCALL XMLPUBFUN xmlChar * XMLCALL
xmlNodeListGetString (xmlDocPtr doc, xmlNodeListGetString (xmlDocPtr doc,
xmlNodePtr list, xmlNodePtr list,
int inLine); int inLine);
#ifdef LIBXML_TREE_ENABLED #ifdef LIBXML_TREE_ENABLED
XMLPUBFUN xmlChar * XMLCALL XMLPUBFUN xmlChar * XMLCALL
xmlNodeListGetRawString (xmlDocPtr doc, xmlNodeListGetRawString (xmlDocPtr doc,
xmlNodePtr list, xmlNodePtr list,
int inLine); int inLine);
#endif /* LIBXML_TREE_ENABLED */ #endif /* LIBXML_TREE_ENABLED */
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlNodeSetContent (xmlNodePtr cur, xmlNodeSetContent (xmlNodePtr cur,
const xmlChar *content); const xmlChar *content);
#ifdef LIBXML_TREE_ENABLED #ifdef LIBXML_TREE_ENABLED
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlNodeSetContentLen (xmlNodePtr cur, xmlNodeSetContentLen (xmlNodePtr cur,
const xmlChar *content, const xmlChar *content,
int len); int len);
#endif /* LIBXML_TREE_ENABLED */ #endif /* LIBXML_TREE_ENABLED */
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlNodeAddContent (xmlNodePtr cur, xmlNodeAddContent (xmlNodePtr cur,
const xmlChar *content); const xmlChar *content);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlNodeAddContentLen (xmlNodePtr cur, xmlNodeAddContentLen (xmlNodePtr cur,
const xmlChar *content, const xmlChar *content,
int len); int len);
XMLPUBFUN xmlChar * XMLCALL XMLPUBFUN xmlChar * XMLCALL
xmlNodeGetContent (xmlNodePtr cur); xmlNodeGetContent (xmlNodePtr cur);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlNodeBufGetContent (xmlBufferPtr buffer, xmlNodeBufGetContent (xmlBufferPtr buffer,
xmlNodePtr cur); xmlNodePtr cur);
XMLPUBFUN xmlChar * XMLCALL XMLPUBFUN xmlChar * XMLCALL
xmlNodeGetLang (xmlNodePtr cur); xmlNodeGetLang (xmlNodePtr cur);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlNodeGetSpacePreserve (xmlNodePtr cur); xmlNodeGetSpacePreserve (xmlNodePtr cur);
#ifdef LIBXML_TREE_ENABLED #ifdef LIBXML_TREE_ENABLED
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlNodeSetLang (xmlNodePtr cur, xmlNodeSetLang (xmlNodePtr cur,
const xmlChar *lang); const xmlChar *lang);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlNodeSetSpacePreserve (xmlNodePtr cur, xmlNodeSetSpacePreserve (xmlNodePtr cur,
int val); int val);
#endif /* LIBXML_TREE_ENABLED */ #endif /* LIBXML_TREE_ENABLED */
XMLPUBFUN xmlChar * XMLCALL XMLPUBFUN xmlChar * XMLCALL
xmlNodeGetBase (xmlDocPtr doc, xmlNodeGetBase (xmlDocPtr doc,
xmlNodePtr cur); xmlNodePtr cur);
#if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_XINCLUDE_ENABLED) #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_XINCLUDE_ENABLED)
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlNodeSetBase (xmlNodePtr cur, xmlNodeSetBase (xmlNodePtr cur,
const xmlChar *uri); const xmlChar *uri);
#endif #endif
/* /*
* Removing content. * Removing content.
*/ */
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlRemoveProp (xmlAttrPtr cur); xmlRemoveProp (xmlAttrPtr cur);
#if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED) #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED)
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlUnsetNsProp (xmlNodePtr node, xmlUnsetNsProp (xmlNodePtr node,
xmlNsPtr ns, xmlNsPtr ns,
const xmlChar *name); const xmlChar *name);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlUnsetProp (xmlNodePtr node, xmlUnsetProp (xmlNodePtr node,
const xmlChar *name); const xmlChar *name);
#endif /* defined(LIBXML_TREE_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED) * / #endif /* defined(LIBXML_TREE_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED) * /
/* /*
* Internal, don't use. * Internal, don't use.
*/ */
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlBufferWriteCHAR (xmlBufferPtr buf, xmlBufferWriteCHAR (xmlBufferPtr buf,
const xmlChar *string); const xmlChar *string);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlBufferWriteChar (xmlBufferPtr buf, xmlBufferWriteChar (xmlBufferPtr buf,
const char *string); const char *string);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlBufferWriteQuotedString(xmlBufferPtr buf, xmlBufferWriteQuotedString(xmlBufferPtr buf,
const xmlChar *string); const xmlChar *string);
#ifdef LIBXML_OUTPUT_ENABLED #ifdef LIBXML_OUTPUT_ENABLED
XMLPUBFUN void xmlAttrSerializeTxtContent(xmlBufferPtr buf, XMLPUBFUN void xmlAttrSerializeTxtContent(xmlBufferPtr buf,
xmlDocPtr doc, xmlDocPtr doc,
xmlAttrPtr attr, xmlAttrPtr attr,
const xmlChar *string); const xmlChar *string);
#endif /* LIBXML_OUTPUT_ENABLED */ #endif /* LIBXML_OUTPUT_ENABLED */
#ifdef LIBXML_TREE_ENABLED #ifdef LIBXML_TREE_ENABLED
/* /*
* Namespace handling. * Namespace handling.
*/ */
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlReconciliateNs (xmlDocPtr doc, xmlReconciliateNs (xmlDocPtr doc,
xmlNodePtr tree); xmlNodePtr tree);
#endif #endif
#ifdef LIBXML_OUTPUT_ENABLED #ifdef LIBXML_OUTPUT_ENABLED
/* /*
* Saving. * Saving.
*/ */
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlDocDumpFormatMemory (xmlDocPtr cur, xmlDocDumpFormatMemory (xmlDocPtr cur,
xmlChar **mem, xmlChar **mem,
int *size, int *size,
int format); int format);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlDocDumpMemory (xmlDocPtr cur, xmlDocDumpMemory (xmlDocPtr cur,
xmlChar **mem, xmlChar **mem,
int *size); int *size);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlDocDumpMemoryEnc (xmlDocPtr out_doc, xmlDocDumpMemoryEnc (xmlDocPtr out_doc,
xmlChar **doc_txt_ptr, xmlChar **doc_txt_ptr,
int * doc_txt_len, int * doc_txt_len,
const char *txt_encoding); const char *txt_encoding);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlDocDumpFormatMemoryEnc(xmlDocPtr out_doc, xmlDocDumpFormatMemoryEnc(xmlDocPtr out_doc,
xmlChar **doc_txt_ptr, xmlChar **doc_txt_ptr,
int * doc_txt_len, int * doc_txt_len,
const char *txt_encoding, const char *txt_encoding,
int format); int format);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlDocFormatDump (FILE *f, xmlDocFormatDump (FILE *f,
xmlDocPtr cur, xmlDocPtr cur,
int format); int format);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlDocDump (FILE *f, xmlDocDump (FILE *f,
xmlDocPtr cur); xmlDocPtr cur);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlElemDump (FILE *f, xmlElemDump (FILE *f,
xmlDocPtr doc, xmlDocPtr doc,
xmlNodePtr cur); xmlNodePtr cur);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlSaveFile (const char *filename, xmlSaveFile (const char *filename,
xmlDocPtr cur); xmlDocPtr cur);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlSaveFormatFile (const char *filename, xmlSaveFormatFile (const char *filename,
xmlDocPtr cur, xmlDocPtr cur,
int format); int format);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlNodeDump (xmlBufferPtr buf, xmlNodeDump (xmlBufferPtr buf,
xmlDocPtr doc, xmlDocPtr doc,
xmlNodePtr cur, xmlNodePtr cur,
int level, int level,
int format); int format);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlSaveFileTo (xmlOutputBufferPtr buf, xmlSaveFileTo (xmlOutputBufferPtr buf,
xmlDocPtr cur, xmlDocPtr cur,
const char *encoding); const char *encoding);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlSaveFormatFileTo (xmlOutputBufferPtr buf, xmlSaveFormatFileTo (xmlOutputBufferPtr buf,
xmlDocPtr cur, xmlDocPtr cur,
const char *encoding, const char *encoding,
int format); int format);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlNodeDumpOutput (xmlOutputBufferPtr buf, xmlNodeDumpOutput (xmlOutputBufferPtr buf,
xmlDocPtr doc, xmlDocPtr doc,
xmlNodePtr cur, xmlNodePtr cur,
int level, int level,
int format, int format,
const char *encoding); const char *encoding);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlSaveFormatFileEnc (const char *filename, xmlSaveFormatFileEnc (const char *filename,
xmlDocPtr cur, xmlDocPtr cur,
const char *encoding, const char *encoding,
int format); int format);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlSaveFileEnc (const char *filename, xmlSaveFileEnc (const char *filename,
xmlDocPtr cur, xmlDocPtr cur,
const char *encoding); const char *encoding);
#endif /* LIBXML_OUTPUT_ENABLED */ #endif /* LIBXML_OUTPUT_ENABLED */
/* /*
* XHTML * XHTML
*/ */
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlIsXHTML (const xmlChar *systemID, xmlIsXHTML (const xmlChar *systemID,
const xmlChar *publicID); const xmlChar *publicID);
/* /*
* Compression. * Compression.
*/ */
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlGetDocCompressMode (xmlDocPtr doc); xmlGetDocCompressMode (xmlDocPtr doc);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlSetDocCompressMode (xmlDocPtr doc, xmlSetDocCompressMode (xmlDocPtr doc,
int mode); int mode);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlGetCompressMode (void); xmlGetCompressMode (void);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlSetCompressMode (int mode); xmlSetCompressMode (int mode);
/* /*
* DOM-wrapper helper functions. * DOM-wrapper helper functions.
*/ */
XMLPUBFUN xmlDOMWrapCtxtPtr XMLCALL XMLPUBFUN xmlDOMWrapCtxtPtr XMLCALL
xmlDOMWrapNewCtxt (void); xmlDOMWrapNewCtxt (void);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlDOMWrapFreeCtxt (xmlDOMWrapCtxtPtr ctxt); xmlDOMWrapFreeCtxt (xmlDOMWrapCtxtPtr ctxt);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlDOMWrapReconcileNamespaces(xmlDOMWrapCtxtPtr ctxt, xmlDOMWrapReconcileNamespaces(xmlDOMWrapCtxtPtr ctxt,
xmlNodePtr elem, xmlNodePtr elem,
int options); int options);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlDOMWrapAdoptNode (xmlDOMWrapCtxtPtr ctxt, xmlDOMWrapAdoptNode (xmlDOMWrapCtxtPtr ctxt,
xmlDocPtr sourceDoc, xmlDocPtr sourceDoc,
xmlNodePtr node, xmlNodePtr node,
xmlDocPtr destDoc, xmlDocPtr destDoc,
xmlNodePtr destParent, xmlNodePtr destParent,
int options); int options);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlDOMWrapRemoveNode (xmlDOMWrapCtxtPtr ctxt, xmlDOMWrapRemoveNode (xmlDOMWrapCtxtPtr ctxt,
xmlDocPtr doc, xmlDocPtr doc,
xmlNodePtr node, xmlNodePtr node,
int options); int options);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlDOMWrapCloneNode (xmlDOMWrapCtxtPtr ctxt, xmlDOMWrapCloneNode (xmlDOMWrapCtxtPtr ctxt,
xmlDocPtr sourceDoc, xmlDocPtr sourceDoc,
xmlNodePtr node, xmlNodePtr node,
xmlNodePtr *clonedNode, xmlNodePtr *clonedNode,
xmlDocPtr destDoc, xmlDocPtr destDoc,
xmlNodePtr destParent, xmlNodePtr destParent,
int deep, int deep,
int options); int options);
#ifdef LIBXML_TREE_ENABLED #ifdef LIBXML_TREE_ENABLED
/* /*
* 5 interfaces from DOM ElementTraversal, but different in entities * 5 interfaces from DOM ElementTraversal, but different in entities
* traversal. * traversal.
*/ */
XMLPUBFUN unsigned long XMLCALL XMLPUBFUN unsigned long XMLCALL
xmlChildElementCount (xmlNodePtr parent); xmlChildElementCount (xmlNodePtr parent);
XMLPUBFUN xmlNodePtr XMLCALL XMLPUBFUN xmlNodePtr XMLCALL
xmlNextElementSibling (xmlNodePtr node); xmlNextElementSibling (xmlNodePtr node);
 End of changes. 174 change blocks. 
527 lines changed or deleted 524 lines changed or added


 uri.h   uri.h 
skipping to change at line 34 skipping to change at line 34
* A parsed URI reference. This is a struct containing the various fields * A parsed URI reference. This is a struct containing the various fields
* as described in RFC 2396 but separated for further processing. * as described in RFC 2396 but separated for further processing.
* *
* Note: query is a deprecated field which is incorrectly unescaped. * Note: query is a deprecated field which is incorrectly unescaped.
* query_raw takes precedence over query if the former is set. * query_raw takes precedence over query if the former is set.
* See: http://mail.gnome.org/archives/xml/2007-April/thread.html#00127 * See: http://mail.gnome.org/archives/xml/2007-April/thread.html#00127
*/ */
typedef struct _xmlURI xmlURI; typedef struct _xmlURI xmlURI;
typedef xmlURI *xmlURIPtr; typedef xmlURI *xmlURIPtr;
struct _xmlURI { struct _xmlURI {
char *scheme; /* the URI scheme */ char *scheme; /* the URI scheme */
char *opaque; /* opaque part */ char *opaque; /* opaque part */
char *authority; /* the authority part */ char *authority; /* the authority part */
char *server; /* the server part */ char *server; /* the server part */
char *user; /* the user part */ char *user; /* the user part */
int port; /* the port number */ int port; /* the port number */
char *path; /* the path string */ char *path; /* the path string */
char *query; /* the query string (deprecated - use with caution) char *query; /* the query string (deprecated - use with caution) */
*/ char *fragment; /* the fragment identifier */
char *fragment; /* the fragment identifier */ int cleanup; /* parsing potentially unclean URI */
int cleanup; /* parsing potentially unclean URI */ char *query_raw; /* the query string (as it appears in the URI) */
char *query_raw; /* the query string (as it appears in the URI) */
}; };
/* /*
* This function is in tree.h: * This function is in tree.h:
* xmlChar * xmlNodeGetBase (xmlDocPtr doc, * xmlChar * xmlNodeGetBase (xmlDocPtr doc,
* xmlNodePtr cur); * xmlNodePtr cur);
*/ */
XMLPUBFUN xmlURIPtr XMLCALL XMLPUBFUN xmlURIPtr XMLCALL
xmlCreateURI (void); xmlCreateURI (void);
XMLPUBFUN xmlChar * XMLCALL XMLPUBFUN xmlChar * XMLCALL
xmlBuildURI (const xmlChar *URI, xmlBuildURI (const xmlChar *URI,
const xmlChar *base); const xmlChar *base);
XMLPUBFUN xmlChar * XMLCALL XMLPUBFUN xmlChar * XMLCALL
xmlBuildRelativeURI (const xmlChar *URI, xmlBuildRelativeURI (const xmlChar *URI,
const xmlChar *base); const xmlChar *base);
XMLPUBFUN xmlURIPtr XMLCALL XMLPUBFUN xmlURIPtr XMLCALL
xmlParseURI (const char *str); xmlParseURI (const char *str);
XMLPUBFUN xmlURIPtr XMLCALL XMLPUBFUN xmlURIPtr XMLCALL
xmlParseURIRaw (const char *str, xmlParseURIRaw (const char *str,
int raw); int raw);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlParseURIReference (xmlURIPtr uri, xmlParseURIReference (xmlURIPtr uri,
const char *str); const char *str);
XMLPUBFUN xmlChar * XMLCALL XMLPUBFUN xmlChar * XMLCALL
xmlSaveUri (xmlURIPtr uri); xmlSaveUri (xmlURIPtr uri);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlPrintURI (FILE *stream, xmlPrintURI (FILE *stream,
xmlURIPtr uri); xmlURIPtr uri);
XMLPUBFUN xmlChar * XMLCALL XMLPUBFUN xmlChar * XMLCALL
xmlURIEscapeStr (const xmlChar *str, xmlURIEscapeStr (const xmlChar *str,
const xmlChar *list); const xmlChar *list);
XMLPUBFUN char * XMLCALL XMLPUBFUN char * XMLCALL
xmlURIUnescapeString (const char *str, xmlURIUnescapeString (const char *str,
int len, int len,
char *target); char *target);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlNormalizeURIPath (char *path); xmlNormalizeURIPath (char *path);
XMLPUBFUN xmlChar * XMLCALL XMLPUBFUN xmlChar * XMLCALL
xmlURIEscape (const xmlChar *str); xmlURIEscape (const xmlChar *str);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlFreeURI (xmlURIPtr uri); xmlFreeURI (xmlURIPtr uri);
XMLPUBFUN xmlChar* XMLCALL XMLPUBFUN xmlChar* XMLCALL
xmlCanonicPath (const xmlChar *path); xmlCanonicPath (const xmlChar *path);
XMLPUBFUN xmlChar* XMLCALL XMLPUBFUN xmlChar* XMLCALL
xmlPathToURI (const xmlChar *path); xmlPathToURI (const xmlChar *path);
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif
#endif /* __XML_URI_H__ */ #endif /* __XML_URI_H__ */
 End of changes. 17 change blocks. 
36 lines changed or deleted 35 lines changed or added


 uthash.h   uthash.h 
#ifndef __AUDIOENGINE_UTHASH_H__ /*
#define __AUDIOENGINE_UTHASH_H__ Copyright (c) 2003-2010, Troy D. Hanson http://uthash.sourceforge.net
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __SUPPORT_DATA_SUPPORT_UTHASH_H__
#define __SUPPORT_DATA_SUPPORT_UTHASH_H__
#include <string.h> /* memcmp,strlen */ #include <string.h> /* memcmp,strlen */
#include <stddef.h> /* ptrdiff_t */ #include <stddef.h> /* ptrdiff_t */
#include <stdlib.h> /* exit() */
namespace CocosDenshion { namespace cocos2d {
/* These macros use decltype or the earlier __typeof GNU extension. /* These macros use decltype or the earlier __typeof GNU extension.
As decltype is only available in newer compilers (VS2010 or gcc 4.3+ As decltype is only available in newer compilers (VS2010 or gcc 4.3+
when compiling c++ source) this code uses whatever method is needed when compiling c++ source) this code uses whatever method is needed
or, for VS2008 where neither is available, uses casting workarounds. */ or, for VS2008 where neither is available, uses casting workarounds. */
#ifdef _MSC_VER /* MS compiler */ #ifdef _MSC_VER /* MS compiler */
#if _MSC_VER >= 1600 && __cplusplus /* VS2010 or newer in C++ mode */ #if _MSC_VER >= 1600 && defined(__cplusplus) /* VS2010 or newer in C++ mod e */
#define DECLTYPE(x) (decltype(x)) #define DECLTYPE(x) (decltype(x))
#else /* VS2008 or older (or VS2010 in C mode) */ #else /* VS2008 or older (or VS2010 in C mode) */
#define NO_DECLTYPE #define NO_DECLTYPE
#define DECLTYPE(x) #define DECLTYPE(x)
#endif #endif
#else /* GNU, Sun and other compilers */ #else /* GNU, Sun and other compilers */
#define DECLTYPE(x) (__typeof(x)) #define DECLTYPE(x) (__typeof(x))
#endif #endif
#ifdef ANDROID
#define NO_DECLTYPE
#undef DECLTYPE
#define DECLTYPE(x)
#endif
#ifdef NO_DECLTYPE #ifdef NO_DECLTYPE
#define DECLTYPE_ASSIGN(dst,src) \ #define DECLTYPE_ASSIGN(dst,src) \
do { \ do { \
char **_da_dst = (char**)(&(dst)); \ char **_da_dst = (char**)(&(dst)); \
*_da_dst = (char*)(src); \ *_da_dst = (char*)(src); \
} while(0) } while(0)
#else #else
#define DECLTYPE_ASSIGN(dst,src) \ #define DECLTYPE_ASSIGN(dst,src) \
do { \ do { \
(dst) = DECLTYPE(dst)(src); \ (dst) = DECLTYPE(dst)(src); \
} while(0) } while(0)
#endif #endif
/* uint32_t next definded will conflict with other libraries and an "error
C2872: 'uint32_t' : ambiguous symbol" will appear.
so we replace all uint32_t with 'unsigned int'.
*/
/* a number of the hash function use uint32_t which isn't defined on win32 */ /* a number of the hash function use uint32_t which isn't defined on win32 */
#ifdef _MSC_VER
typedef unsigned int uint32_t;
#else
#include <inttypes.h> /* uint32_t */
#endif
#define UTHASH_VERSION 1.9 // #ifdef _MSC_VER
// typedef unsigned int uint32_t;
// #else
// #ifndef __QNX__
// #include <inttypes.h> /* uint32_t */
// #endif /* __QNX__ */
// #endif /* _MSC_VER */
#define UTHASH_VERSION 1.9.3
#define uthash_fatal(msg) exit(-1) /* fatal error (out of memory,etc ) */ #define uthash_fatal(msg) exit(-1) /* fatal error (out of memory,etc ) */
#define uthash_malloc(sz) malloc(sz) /* malloc fcn */ #define uthash_malloc(sz) malloc(sz) /* malloc fcn */
#define uthash_free(ptr) free(ptr) /* free fcn */ #define uthash_free(ptr,sz) free(ptr) /* free fcn */
#define uthash_noexpand_fyi(tbl) /* can be defined to log noexpand */ #define uthash_noexpand_fyi(tbl) /* can be defined to log noexpand */
#define uthash_expand_fyi(tbl) /* can be defined to log expands */ #define uthash_expand_fyi(tbl) /* can be defined to log expands */
/* initial number of buckets */ /* initial number of buckets */
#define HASH_INITIAL_NUM_BUCKETS 32 /* initial number of buckets */ #define HASH_INITIAL_NUM_BUCKETS 32 /* initial number of buckets */
#define HASH_INITIAL_NUM_BUCKETS_LOG2 5 /* lg2 of initial number of bucket s */ #define HASH_INITIAL_NUM_BUCKETS_LOG2 5 /* lg2 of initial number of bucket s */
#define HASH_BKT_CAPACITY_THRESH 10 /* expand when bucket count reache s */ #define HASH_BKT_CAPACITY_THRESH 10 /* expand when bucket count reache s */
/* calculate the element whose hash handle address is hhe */ /* calculate the element whose hash handle address is hhe */
skipping to change at line 88 skipping to change at line 124
do { \ do { \
(tbl)->bloom_nbits = HASH_BLOOM; \ (tbl)->bloom_nbits = HASH_BLOOM; \
(tbl)->bloom_bv = (uint8_t*)uthash_malloc(HASH_BLOOM_BYTELEN); \ (tbl)->bloom_bv = (uint8_t*)uthash_malloc(HASH_BLOOM_BYTELEN); \
if (!((tbl)->bloom_bv)) { uthash_fatal( "out of memory"); } \ if (!((tbl)->bloom_bv)) { uthash_fatal( "out of memory"); } \
memset((tbl)->bloom_bv, 0, HASH_BLOOM_BYTELEN); \ memset((tbl)->bloom_bv, 0, HASH_BLOOM_BYTELEN); \
(tbl)->bloom_sig = HASH_BLOOM_SIGNATURE; \ (tbl)->bloom_sig = HASH_BLOOM_SIGNATURE; \
} while (0); } while (0);
#define HASH_BLOOM_FREE(tbl) \ #define HASH_BLOOM_FREE(tbl) \
do { \ do { \
uthash_free((tbl)->bloom_bv); \ uthash_free((tbl)->bloom_bv, HASH_BLOOM_BYTELEN); \
} while (0); } while (0);
#define HASH_BLOOM_BITSET(bv,idx) (bv[(idx)/8] |= (1U << ((idx)%8))) #define HASH_BLOOM_BITSET(bv,idx) (bv[(idx)/8] |= (1U << ((idx)%8)))
#define HASH_BLOOM_BITTEST(bv,idx) (bv[(idx)/8] & (1U << ((idx)%8))) #define HASH_BLOOM_BITTEST(bv,idx) (bv[(idx)/8] & (1U << ((idx)%8)))
#define HASH_BLOOM_ADD(tbl,hashv) \ #define HASH_BLOOM_ADD(tbl,hashv) \
HASH_BLOOM_BITSET((tbl)->bloom_bv, (hashv & (uint32_t)((1ULL << (tbl)->bl oom_nbits) - 1))) HASH_BLOOM_BITSET((tbl)->bloom_bv, (hashv & (unsigned int)((1ULL << (tbl) ->bloom_nbits) - 1)))
#define HASH_BLOOM_TEST(tbl,hashv) \ #define HASH_BLOOM_TEST(tbl,hashv) \
HASH_BLOOM_BITTEST((tbl)->bloom_bv, (hashv & (uint32_t)((1ULL << (tbl)->b loom_nbits) - 1))) HASH_BLOOM_BITTEST((tbl)->bloom_bv, (hashv & (unsigned int)((1ULL << (tbl )->bloom_nbits) - 1)))
#else #else
#define HASH_BLOOM_MAKE(tbl) #define HASH_BLOOM_MAKE(tbl)
#define HASH_BLOOM_FREE(tbl) #define HASH_BLOOM_FREE(tbl)
#define HASH_BLOOM_ADD(tbl,hashv) #define HASH_BLOOM_ADD(tbl,hashv)
#define HASH_BLOOM_TEST(tbl,hashv) (1) #define HASH_BLOOM_TEST(tbl,hashv) (1)
#endif #endif
#define HASH_MAKE_TABLE(hh,head) \ #define HASH_MAKE_TABLE(hh,head) \
do { \ do { \
skipping to change at line 176 skipping to change at line 212
* we were forfeiting our ability to further refer to the deletee (users) * we were forfeiting our ability to further refer to the deletee (users)
* in the patch-up process. Solution: use scratch space to * in the patch-up process. Solution: use scratch space to
* copy the deletee pointer, then the latter references are via that * copy the deletee pointer, then the latter references are via that
* scratch pointer rather than through the repointed (users) symbol. * scratch pointer rather than through the repointed (users) symbol.
*/ */
#define HASH_DELETE(hh,head,delptr) \ #define HASH_DELETE(hh,head,delptr) \
do { \ do { \
unsigned _hd_bkt; \ unsigned _hd_bkt; \
struct UT_hash_handle *_hd_hh_del; \ struct UT_hash_handle *_hd_hh_del; \
if ( ((delptr)->hh.prev == NULL) && ((delptr)->hh.next == NULL) ) { \ if ( ((delptr)->hh.prev == NULL) && ((delptr)->hh.next == NULL) ) { \
uthash_free((head)->hh.tbl->buckets ); uthash_free((head)->hh.tbl->buckets,
\ \
(head)->hh.tbl->num_buckets*sizeof(struct UT_hash_bucke
t) ); \
HASH_BLOOM_FREE((head)->hh.tbl); \ HASH_BLOOM_FREE((head)->hh.tbl); \
uthash_free((head)->hh.tbl); \ uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \
head = NULL; \ head = NULL; \
} else { \ } else { \
_hd_hh_del = &((delptr)->hh); \ _hd_hh_del = &((delptr)->hh); \
if ((delptr) == ELMT_FROM_HH((head)->hh.tbl,(head)->hh.tbl->tail)) { \ if ((delptr) == ELMT_FROM_HH((head)->hh.tbl,(head)->hh.tbl->tail)) { \
(head)->hh.tbl->tail = \ (head)->hh.tbl->tail = \
(UT_hash_handle*)((char*)((delptr)->hh.prev) + \ (UT_hash_handle*)((char*)((delptr)->hh.prev) + \
(head)->hh.tbl->hho); \ (head)->hh.tbl->hho); \
} \ } \
if ((delptr)->hh.prev) { \ if ((delptr)->hh.prev) { \
((UT_hash_handle*)((char*)((delptr)->hh.prev) + \ ((UT_hash_handle*)((char*)((delptr)->hh.prev) + \
skipping to change at line 214 skipping to change at line 251
/* convenience forms of HASH_FIND/HASH_ADD/HASH_DEL */ /* convenience forms of HASH_FIND/HASH_ADD/HASH_DEL */
#define HASH_FIND_STR(head,findstr,out) \ #define HASH_FIND_STR(head,findstr,out) \
HASH_FIND(hh,head,findstr,strlen(findstr),out) HASH_FIND(hh,head,findstr,strlen(findstr),out)
#define HASH_ADD_STR(head,strfield,add) \ #define HASH_ADD_STR(head,strfield,add) \
HASH_ADD(hh,head,strfield,strlen(add->strfield),add) HASH_ADD(hh,head,strfield,strlen(add->strfield),add)
#define HASH_FIND_INT(head,findint,out) \ #define HASH_FIND_INT(head,findint,out) \
HASH_FIND(hh,head,findint,sizeof(int),out) HASH_FIND(hh,head,findint,sizeof(int),out)
#define HASH_ADD_INT(head,intfield,add) \ #define HASH_ADD_INT(head,intfield,add) \
HASH_ADD(hh,head,intfield,sizeof(int),add) HASH_ADD(hh,head,intfield,sizeof(int),add)
#define HASH_FIND_PTR(head,findptr,out)
\
HASH_FIND(hh,head,findptr,sizeof(void *),out)
#define HASH_ADD_PTR(head,ptrfield,add)
\
HASH_ADD(hh,head,ptrfield,sizeof(void *),add)
#define HASH_DEL(head,delptr) \ #define HASH_DEL(head,delptr) \
HASH_DELETE(hh,head,delptr) HASH_DELETE(hh,head,delptr)
/* HASH_FSCK checks hash integrity on every add/delete when HASH_DEBUG is d efined. /* HASH_FSCK checks hash integrity on every add/delete when HASH_DEBUG is d efined.
* This is for uthash developer only; it compiles away if HASH_DEBUG isn't defined. * This is for uthash developer only; it compiles away if HASH_DEBUG isn't defined.
*/ */
#ifdef HASH_DEBUG #ifdef HASH_DEBUG
#define HASH_OOPS(...) do { fprintf(stderr,__VA_ARGS__); exit(-1); } while (0) #define HASH_OOPS(...) do { fprintf(stderr,__VA_ARGS__); exit(-1); } while (0)
#define HASH_FSCK(hh,head) \ #define HASH_FSCK(hh,head) \
do { \ do { \
skipping to change at line 302 skipping to change at line 343
#ifdef HASH_FUNCTION #ifdef HASH_FUNCTION
#define HASH_FCN HASH_FUNCTION #define HASH_FCN HASH_FUNCTION
#else #else
#define HASH_FCN HASH_JEN #define HASH_FCN HASH_JEN
#endif #endif
/* The Bernstein hash function, used in Perl prior to v5.6 */ /* The Bernstein hash function, used in Perl prior to v5.6 */
#define HASH_BER(key,keylen,num_bkts,hashv,bkt) \ #define HASH_BER(key,keylen,num_bkts,hashv,bkt) \
do { \ do { \
unsigned _hb_keylen=keylen; \ unsigned _hb_keylen=keylen; \
char *_hb_key=(char*)key; \ char *_hb_key=(char*)(key); \
(hashv) = 0; \ (hashv) = 0; \
while (_hb_keylen--) { (hashv) = ((hashv) * 33) + *_hb_key++; } \ while (_hb_keylen--) { (hashv) = ((hashv) * 33) + *_hb_key++; } \
bkt = (hashv) & (num_bkts-1); \ bkt = (hashv) & (num_bkts-1); \
} while (0) } while (0)
/* SAX/FNV/OAT/JEN hash functions are macro variants of those listed at /* SAX/FNV/OAT/JEN hash functions are macro variants of those listed at
* http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx */ * http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx */
#define HASH_SAX(key,keylen,num_bkts,hashv,bkt) \ #define HASH_SAX(key,keylen,num_bkts,hashv,bkt) \
do { \ do { \
unsigned _sx_i; \ unsigned _sx_i; \
char *_hs_key=(char*)key; \ char *_hs_key=(char*)(key); \
hashv = 0; \ hashv = 0; \
for(_sx_i=0; _sx_i < keylen; _sx_i++) \ for(_sx_i=0; _sx_i < keylen; _sx_i++) \
hashv ^= (hashv << 5) + (hashv >> 2) + _hs_key[_sx_i]; \ hashv ^= (hashv << 5) + (hashv >> 2) + _hs_key[_sx_i]; \
bkt = hashv & (num_bkts-1); \ bkt = hashv & (num_bkts-1); \
} while (0) } while (0)
#define HASH_FNV(key,keylen,num_bkts,hashv,bkt) \ #define HASH_FNV(key,keylen,num_bkts,hashv,bkt) \
do { \ do { \
unsigned _fn_i; \ unsigned _fn_i; \
char *_hf_key=(char*)key; \ char *_hf_key=(char*)(key); \
hashv = 2166136261UL; \ hashv = 2166136261UL; \
for(_fn_i=0; _fn_i < keylen; _fn_i++) \ for(_fn_i=0; _fn_i < keylen; _fn_i++) \
hashv = (hashv * 16777619) ^ _hf_key[_fn_i]; \ hashv = (hashv * 16777619) ^ _hf_key[_fn_i]; \
bkt = hashv & (num_bkts-1); \ bkt = hashv & (num_bkts-1); \
} while(0); } while(0);
#define HASH_OAT(key,keylen,num_bkts,hashv,bkt) \ #define HASH_OAT(key,keylen,num_bkts,hashv,bkt) \
do { \ do { \
unsigned _ho_i; \ unsigned _ho_i; \
char *_ho_key=(char*)key; \ char *_ho_key=(char*)(key); \
hashv = 0; \ hashv = 0; \
for(_ho_i=0; _ho_i < keylen; _ho_i++) { \ for(_ho_i=0; _ho_i < keylen; _ho_i++) { \
hashv += _ho_key[_ho_i]; \ hashv += _ho_key[_ho_i]; \
hashv += (hashv << 10); \ hashv += (hashv << 10); \
hashv ^= (hashv >> 6); \ hashv ^= (hashv >> 6); \
} \ } \
hashv += (hashv << 3); \ hashv += (hashv << 3); \
hashv ^= (hashv >> 11); \ hashv ^= (hashv >> 11); \
hashv += (hashv << 15); \ hashv += (hashv << 15); \
bkt = hashv & (num_bkts-1); \ bkt = hashv & (num_bkts-1); \
skipping to change at line 362 skipping to change at line 403
b -= c; b -= a; b ^= ( a << 16 ); \ b -= c; b -= a; b ^= ( a << 16 ); \
c -= a; c -= b; c ^= ( b >> 5 ); \ c -= a; c -= b; c ^= ( b >> 5 ); \
a -= b; a -= c; a ^= ( c >> 3 ); \ a -= b; a -= c; a ^= ( c >> 3 ); \
b -= c; b -= a; b ^= ( a << 10 ); \ b -= c; b -= a; b ^= ( a << 10 ); \
c -= a; c -= b; c ^= ( b >> 15 ); \ c -= a; c -= b; c ^= ( b >> 15 ); \
} while (0) } while (0)
#define HASH_JEN(key,keylen,num_bkts,hashv,bkt) \ #define HASH_JEN(key,keylen,num_bkts,hashv,bkt) \
do { \ do { \
unsigned _hj_i,_hj_j,_hj_k; \ unsigned _hj_i,_hj_j,_hj_k; \
char *_hj_key=(char*)key; \ char *_hj_key=(char*)(key); \
hashv = 0xfeedbeef; \ hashv = 0xfeedbeef; \
_hj_i = _hj_j = 0x9e3779b9; \ _hj_i = _hj_j = 0x9e3779b9; \
_hj_k = keylen; \ _hj_k = keylen; \
while (_hj_k >= 12) { \ while (_hj_k >= 12) { \
_hj_i += (_hj_key[0] + ( (unsigned)_hj_key[1] << 8 ) \ _hj_i += (_hj_key[0] + ( (unsigned)_hj_key[1] << 8 ) \
+ ( (unsigned)_hj_key[2] << 16 ) \ + ( (unsigned)_hj_key[2] << 16 ) \
+ ( (unsigned)_hj_key[3] << 24 ) ); \ + ( (unsigned)_hj_key[3] << 24 ) ); \
_hj_j += (_hj_key[4] + ( (unsigned)_hj_key[5] << 8 ) \ _hj_j += (_hj_key[4] + ( (unsigned)_hj_key[5] << 8 ) \
+ ( (unsigned)_hj_key[6] << 16 ) \ + ( (unsigned)_hj_key[6] << 16 ) \
+ ( (unsigned)_hj_key[7] << 24 ) ); \ + ( (unsigned)_hj_key[7] << 24 ) ); \
skipping to change at line 408 skipping to change at line 449
} while(0) } while(0)
/* The Paul Hsieh hash function */ /* The Paul Hsieh hash function */
#undef get16bits #undef get16bits
#if (defined(__GNUC__) && defined(__i386__)) || defined(__WATCOMC__) \ #if (defined(__GNUC__) && defined(__i386__)) || defined(__WATCOMC__) \
|| defined(_MSC_VER) || defined (__BORLANDC__) || defined (__TURBOC__) || defined(_MSC_VER) || defined (__BORLANDC__) || defined (__TURBOC__)
#define get16bits(d) (*((const uint16_t *) (d))) #define get16bits(d) (*((const uint16_t *) (d)))
#endif #endif
#if !defined (get16bits) #if !defined (get16bits)
#define get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8) #define get16bits(d) ((((unsigned int)(((const uint8_t *)(d))[1])) << 8)
\ \
+(uint32_t)(((const uint8_t *)(d))[0]) ) +(unsigned int)(((const uint8_t *)(d))[0]) )
#endif #endif
#define HASH_SFH(key,keylen,num_bkts,hashv,bkt) \ #define HASH_SFH(key,keylen,num_bkts,hashv,bkt) \
do { \ do { \
char *_sfh_key=(char*)key; char *_sfh_key=(char*)(key);
\ \
uint32_t _sfh_tmp, _sfh_len = keylen; unsigned int _sfh_tmp, _sfh_len = keylen;
\ \
\ \
int _sfh_rem = _sfh_len & 3; \ int _sfh_rem = _sfh_len & 3; \
_sfh_len >>= 2; \ _sfh_len >>= 2; \
hashv = 0xcafebabe; \ hashv = 0xcafebabe; \
\ \
/* Main loop */ \ /* Main loop */ \
for (;_sfh_len > 0; _sfh_len--) { \ for (;_sfh_len > 0; _sfh_len--) { \
hashv += get16bits (_sfh_key); \ hashv += get16bits (_sfh_key); \
_sfh_tmp = (get16bits (_sfh_key+2) << 11) ^ hashv; \ _sfh_tmp = (get16bits (_sfh_key+2) << 11) ^ hashv; \
hashv = (hashv << 16) ^ _sfh_tmp; \ hashv = (hashv << 16) ^ _sfh_tmp; \
skipping to change at line 478 skipping to change at line 519
#else #else
#define HASH_MUR HASH_MUR_ALIGNED #define HASH_MUR HASH_MUR_ALIGNED
#endif #endif
/* Appleby's MurmurHash fast version for unaligned-tolerant archs like i386 */ /* Appleby's MurmurHash fast version for unaligned-tolerant archs like i386 */
#define HASH_MUR_UNALIGNED(key,keylen,num_bkts,hashv,bkt) \ #define HASH_MUR_UNALIGNED(key,keylen,num_bkts,hashv,bkt) \
do { \ do { \
const unsigned int _mur_m = 0x5bd1e995; \ const unsigned int _mur_m = 0x5bd1e995; \
const int _mur_r = 24; \ const int _mur_r = 24; \
hashv = 0xcafebabe ^ keylen; \ hashv = 0xcafebabe ^ keylen; \
char *_mur_key = (char *)key; char *_mur_key = (char *)(key);
\ \
uint32_t _mur_tmp, _mur_len = keylen; unsigned int _mur_tmp, _mur_len = keylen;
\ \
\ \
for (;_mur_len >= 4; _mur_len-=4) { \ for (;_mur_len >= 4; _mur_len-=4) { \
_mur_tmp = *(uint32_t *)_mur_key; \ _mur_tmp = *(unsigned int *)_mur_key; \
_mur_tmp *= _mur_m; \ _mur_tmp *= _mur_m; \
_mur_tmp ^= _mur_tmp >> _mur_r; \ _mur_tmp ^= _mur_tmp >> _mur_r; \
_mur_tmp *= _mur_m; \ _mur_tmp *= _mur_m; \
hashv *= _mur_m; \ hashv *= _mur_m; \
hashv ^= _mur_tmp; \ hashv ^= _mur_tmp; \
_mur_key += 4; \ _mur_key += 4; \
} \ } \
\ \
switch(_mur_len) \ switch(_mur_len) \
{ \ { \
skipping to change at line 511 skipping to change at line 552
hashv ^= hashv >> 15; \ hashv ^= hashv >> 15; \
\ \
bkt = hashv & (num_bkts-1); \ bkt = hashv & (num_bkts-1); \
} while(0) } while(0)
/* Appleby's MurmurHash version for alignment-sensitive archs like Sparc */ /* Appleby's MurmurHash version for alignment-sensitive archs like Sparc */
#define HASH_MUR_ALIGNED(key,keylen,num_bkts,hashv,bkt) \ #define HASH_MUR_ALIGNED(key,keylen,num_bkts,hashv,bkt) \
do { \ do { \
const unsigned int _mur_m = 0x5bd1e995; \ const unsigned int _mur_m = 0x5bd1e995; \
const int _mur_r = 24; \ const int _mur_r = 24; \
hashv = 0xcafebabe ^ keylen; hashv = 0xcafebabe ^ (keylen);
\ \
char *_mur_key = (char *)key; char *_mur_key = (char *)(key);
\ \
uint32_t _mur_len = keylen; unsigned int _mur_len = keylen;
\ \
int _mur_align = (int)_mur_key & 3; \ int _mur_align = (int)_mur_key & 3; \
\ \
if (_mur_align && (_mur_len >= 4)) { \ if (_mur_align && (_mur_len >= 4)) { \
unsigned _mur_t = 0, _mur_d = 0; \ unsigned _mur_t = 0, _mur_d = 0; \
switch(_mur_align) { \ switch(_mur_align) { \
case 1: _mur_t |= _mur_key[2] << 16; \ case 1: _mur_t |= _mur_key[2] << 16; \
case 2: _mur_t |= _mur_key[1] << 8; \ case 2: _mur_t |= _mur_key[1] << 8; \
case 3: _mur_t |= _mur_key[0]; \ case 3: _mur_t |= _mur_key[0]; \
} \ } \
_mur_t <<= (8 * _mur_align); \ _mur_t <<= (8 * _mur_align); \
skipping to change at line 712 skipping to change at line 753
tbl->ideal_chain_maxlen; \ tbl->ideal_chain_maxlen; \
} \ } \
_he_thh->hh_prev = NULL; \ _he_thh->hh_prev = NULL; \
_he_thh->hh_next = _he_newbkt->hh_head; \ _he_thh->hh_next = _he_newbkt->hh_head; \
if (_he_newbkt->hh_head) _he_newbkt->hh_head->hh_prev = \ if (_he_newbkt->hh_head) _he_newbkt->hh_head->hh_prev = \
_he_thh; \ _he_thh; \
_he_newbkt->hh_head = _he_thh; \ _he_newbkt->hh_head = _he_thh; \
_he_thh = _he_hh_nxt; \ _he_thh = _he_hh_nxt; \
} \ } \
} \ } \
uthash_free( tbl->buckets, tbl->num_buckets*sizeof(struct UT_hash_bucke t) ); \
tbl->num_buckets *= 2; \ tbl->num_buckets *= 2; \
tbl->log2_num_buckets++; \ tbl->log2_num_buckets++; \
uthash_free( tbl->buckets ); \
tbl->buckets = _he_new_buckets; \ tbl->buckets = _he_new_buckets; \
tbl->ineff_expands = (tbl->nonideal_items > (tbl->num_items >> 1)) ? \ tbl->ineff_expands = (tbl->nonideal_items > (tbl->num_items >> 1)) ? \
(tbl->ineff_expands+1) : 0; \ (tbl->ineff_expands+1) : 0; \
if (tbl->ineff_expands > 1) { \ if (tbl->ineff_expands > 1) { \
tbl->noexpand=1; \ tbl->noexpand=1; \
uthash_noexpand_fyi(tbl); \ uthash_noexpand_fyi(tbl); \
} \ } \
uthash_expand_fyi(tbl); \ uthash_expand_fyi(tbl); \
} while(0) } while(0)
skipping to change at line 854 skipping to change at line 895
} \ } \
} \ } \
} \ } \
} \ } \
HASH_FSCK(hh_dst,dst); \ HASH_FSCK(hh_dst,dst); \
} while (0) } while (0)
#define HASH_CLEAR(hh,head) \ #define HASH_CLEAR(hh,head) \
do { \ do { \
if (head) { \ if (head) { \
uthash_free((head)->hh.tbl->buckets ); uthash_free((head)->hh.tbl->buckets,
\ \
uthash_free((head)->hh.tbl); (head)->hh.tbl->num_buckets*sizeof(struct UT_hash_bucket));
\ \
uthash_free((head)->hh.tbl, sizeof(UT_hash_table));
\
(head)=NULL; \ (head)=NULL; \
} \ } \
} while(0) } while(0)
#ifdef NO_DECLTYPE
#define HASH_ITER(hh,head,el,tmp)
\
for((el)=(head), (*(char**)(&(tmp)))=(char*)((head)?(head)->hh.next:NULL);
\
el; (el)=(tmp),(*(char**)(&(tmp)))=(char*)((tmp)?(tmp)->hh.next:NULL))
#else
#define HASH_ITER(hh,head,el,tmp)
\
for((el)=(head),(tmp)=DECLTYPE(el)((head)?(head)->hh.next:NULL);
\
el; (el)=(tmp),(tmp)=DECLTYPE(el)((tmp)?(tmp)->hh.next:NULL))
#endif
/* obtain a count of items in the hash */ /* obtain a count of items in the hash */
#define HASH_COUNT(head) HASH_CNT(hh,head) #define HASH_COUNT(head) HASH_CNT(hh,head)
#define HASH_CNT(hh,head) (head?(head->hh.tbl->num_items):0) #define HASH_CNT(hh,head) ((head)?((head)->hh.tbl->num_items):0)
typedef struct UT_hash_bucket { typedef struct UT_hash_bucket {
struct UT_hash_handle *hh_head; struct UT_hash_handle *hh_head;
unsigned count; unsigned count;
/* expand_mult is normally set to 0. In this situation, the max chain le ngth /* expand_mult is normally set to 0. In this situation, the max chain le ngth
* threshold is enforced at its default value, HASH_BKT_CAPACITY_THRESH. (If * threshold is enforced at its default value, HASH_BKT_CAPACITY_THRESH. (If
* the bucket's chain exceeds this length, bucket expansion is triggered ). * the bucket's chain exceeds this length, bucket expansion is triggered ).
* However, setting expand_mult to a non-zero value delays bucket expans ion * However, setting expand_mult to a non-zero value delays bucket expans ion
* (that would be triggered by additions to this particular bucket) * (that would be triggered by additions to this particular bucket)
skipping to change at line 912 skipping to change at line 964
unsigned nonideal_items; unsigned nonideal_items;
/* ineffective expands occur when a bucket doubling was performed, but /* ineffective expands occur when a bucket doubling was performed, but
* afterward, more than half the items in the hash had nonideal chain * afterward, more than half the items in the hash had nonideal chain
* positions. If this happens on two consecutive expansions we inhibit a ny * positions. If this happens on two consecutive expansions we inhibit a ny
* further expansion, as it's not helping; this happens when the hash * further expansion, as it's not helping; this happens when the hash
* function isn't a good fit for the key domain. When expansion is inhib ited * function isn't a good fit for the key domain. When expansion is inhib ited
* the hash will still work, albeit no longer in constant time. */ * the hash will still work, albeit no longer in constant time. */
unsigned ineff_expands, noexpand; unsigned ineff_expands, noexpand;
uint32_t signature; /* used only to find hash tables in external analysi s */ unsigned int signature; /* used only to find hash tables in external ana lysis */
#ifdef HASH_BLOOM #ifdef HASH_BLOOM
uint32_t bloom_sig; /* used only to test bloom exists in external analys is */ unsigned int bloom_sig; /* used only to test bloom exists in external an alysis */
uint8_t *bloom_bv; uint8_t *bloom_bv;
char bloom_nbits; char bloom_nbits;
#endif #endif
} UT_hash_table; } UT_hash_table;
typedef struct UT_hash_handle { typedef struct UT_hash_handle {
struct UT_hash_table *tbl; struct UT_hash_table *tbl;
void *prev; /* prev element in app order */ void *prev; /* prev element in app order */
void *next; /* next element in app order */ void *next; /* next element in app order */
struct UT_hash_handle *hh_prev; /* previous hh in bucket order */ struct UT_hash_handle *hh_prev; /* previous hh in bucket order */
struct UT_hash_handle *hh_next; /* next hh in bucket order */ struct UT_hash_handle *hh_next; /* next hh in bucket order */
void *key; /* ptr to enclosing struct's key */ void *key; /* ptr to enclosing struct's key */
unsigned keylen; /* enclosing struct's key len */ unsigned keylen; /* enclosing struct's key len */
unsigned hashv; /* result of hash-fcn(key) */ unsigned hashv; /* result of hash-fcn(key) */
} UT_hash_handle; } UT_hash_handle;
}//namespace cocos2d
} // end of namespace CocosDenshion
#endif /* __SUPPORT_DATA_SUPPORT_UTHASH_H__*/ #endif /* __SUPPORT_DATA_SUPPORT_UTHASH_H__*/
 End of changes. 33 change blocks. 
50 lines changed or deleted 110 lines changed or added


 util.h   util.h 
skipping to change at line 22 skipping to change at line 22
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * 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 I N THE * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS I N THE
* SOFTWARE. * SOFTWARE.
*/ */
#define CP_DefineClassGetter(t) // These are utility routines to use when creating custom constraints.
\ // I'm not sure if this should be part of the private API or not.
const cpConstraintClass * t##GetClass(void); // I should probably clean up the naming conventions if it is...
\
const cpConstraintClass * t##GetClass(){return (cpConstraintClass *)&klass; #define CP_DefineClassGetter(t) const cpConstraintClass * t##GetClass(void)
} {return (cpConstraintClass *)&klass;}
void cpConstraintInit(cpConstraint *constraint, const cpConstraintClass *kl ass, cpBody *a, cpBody *b); void cpConstraintInit(cpConstraint *constraint, const cpConstraintClass *kl ass, cpBody *a, cpBody *b);
#define J_MAX(constraint, dt) (((cpConstraint *)constraint)->maxForce*(dt)) #define J_MAX(constraint, dt) (((cpConstraint *)constraint)->maxForce*(dt))
// Get valid body pointers and exit early if the bodies are idle
#define CONSTRAINT_BEGIN(constraint, a_var, b_var) \
cpBody *a_var, *b_var; { \
a_var = ((cpConstraint *)constraint)->a; \
b_var = ((cpConstraint *)constraint)->b; \
if( \
(cpBodyIsSleeping(a_var) || cpBodyIsStatic(a_var)) && \
(cpBodyIsSleeping(b_var) || cpBodyIsStatic(b_var)) \
) return; \
}
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){
skipping to change at line 70 skipping to change at line 61
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->v_bias = cpvadd(body->v_bias, cpvmult(j, body->m_inv)); body->CP_PRIVATE(v_bias) = cpvadd(body->CP_PRIVATE(v_bias), cpvmult(
body->w_bias += body->i_inv*cpvcross(r, j); j, body->m_inv));
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 cpVect static inline cpFloat
clamp_vect(cpVect v, cpFloat len) k_scalar_body(cpBody *body, cpVect r, cpVect n)
{ {
return cpvclamp(v, len); cpFloat rcn = cpvcross(r, n);
// return (cpvdot(v,v) > len*len) ? cpvmult(cpvnormalize(v), len) : v; 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 mass_sum = a->m_inv + b->m_inv; cpFloat value = k_scalar_body(a, r1, n) + k_scalar_body(b, r2, n);
cpFloat r1cn = cpvcross(r1, n); cpAssertSoft(value != 0.0, "Unsolvable collision or constraint.");
cpFloat r2cn = cpvcross(r2, n);
cpFloat value = mass_sum + a->i_inv*r1cn*r1cn + b->i_inv*r2cn*r2cn;
cpAssert(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 b e so gross... // If I wasn't lazy and wrote a proper matrix class, this wouldn't b e so gross...
cpFloat k11, k12, k21, k22; cpFloat k11, k12, k21, k22;
skipping to change at line 131 skipping to change at line 118
// 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;
cpAssert(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
bias_coef(cpFloat errorBias, cpFloat dt)
{
return 1.0f - cpfpow(errorBias, dt);
}
 End of changes. 8 change blocks. 
30 lines changed or deleted 16 lines changed or added


 vorbisfile.h   vorbisfile.h 
skipping to change at line 56 skipping to change at line 56
#ifndef OV_EXCLUDE_STATIC_CALLBACKS #ifndef OV_EXCLUDE_STATIC_CALLBACKS
/* a few sets of convenient callbacks, especially for use under /* a few sets of convenient callbacks, especially for use under
* Windows where ov_open_callbacks() should always be used instead of * Windows where ov_open_callbacks() should always be used instead of
* ov_open() to avoid problems with incompatible crt.o version linking * ov_open() to avoid problems with incompatible crt.o version linking
* issues. */ * issues. */
static int _ov_header_fseek_wrap(FILE *f,ogg_int64_t off,int whence){ static int _ov_header_fseek_wrap(FILE *f,ogg_int64_t off,int whence){
if(f==NULL)return(-1); if(f==NULL)return(-1);
//#ifdef __MINGW32__ #ifdef __MINGW32__
// return fseeko64(f,off,whence); return fseeko64(f,off,whence);
//#elif defined (_WIN32) #elif defined (_WIN32)
// return _fseeki64(f,off,whence); return _fseeki64(f,off,whence);
//#else #else
return fseek(f,off,whence); return fseek(f,off,whence);
//#endif #endif
} }
/* These structs below (OV_CALLBACKS_DEFAULT etc) are defined here as /* These structs below (OV_CALLBACKS_DEFAULT etc) are defined here as
* static data. That means that every file which includes this header * static data. That means that every file which includes this header
* will get its own copy of these structs whether it uses them or * will get its own copy of these structs whether it uses them or
* not unless it #defines OV_EXCLUDE_STATIC_CALLBACKS. * not unless it #defines OV_EXCLUDE_STATIC_CALLBACKS.
* These static symbols are essential on platforms such as Windows on * These static symbols are essential on platforms such as Windows on
* which several different versions of stdio support may be linked to * which several different versions of stdio support may be linked to
* by different DLLs, and we need to be certain we know which one * by different DLLs, and we need to be certain we know which one
* we're using (the same one as the main application). * we're using (the same one as the main application).
 End of changes. 2 change blocks. 
6 lines changed or deleted 6 lines changed or added


 xmlIO.h   xmlIO.h 
skipping to change at line 134 skipping to change at line 134
#endif #endif
struct _xmlParserInputBuffer { struct _xmlParserInputBuffer {
void* context; void* context;
xmlInputReadCallback readcallback; xmlInputReadCallback readcallback;
xmlInputCloseCallback closecallback; xmlInputCloseCallback closecallback;
xmlCharEncodingHandlerPtr encoder; /* I18N conversions to UTF-8 */ xmlCharEncodingHandlerPtr encoder; /* I18N conversions to UTF-8 */
xmlBufferPtr buffer; /* Local buffer encoded in UTF-8 */ xmlBufferPtr buffer; /* Local buffer encoded in UTF-8 */
xmlBufferPtr raw; /* if encoder != NULL buffer for raw input */ xmlBufferPtr raw; /* if encoder != NULL buffer for raw input */
int compressed; /* -1=unknown, 0=not compressed, 1=compr essed */ int compressed; /* -1=unknown, 0=not compressed, 1=compressed */
int error; int error;
unsigned long rawconsumed;/* amount consumed from raw */ unsigned long rawconsumed;/* amount consumed from raw */
}; };
#ifdef LIBXML_OUTPUT_ENABLED #ifdef LIBXML_OUTPUT_ENABLED
struct _xmlOutputBuffer { struct _xmlOutputBuffer {
void* context; void* context;
xmlOutputWriteCallback writecallback; xmlOutputWriteCallback writecallback;
xmlOutputCloseCallback closecallback; xmlOutputCloseCallback closecallback;
skipping to change at line 158 skipping to change at line 158
xmlBufferPtr conv; /* if encoder != NULL buffer for output */ xmlBufferPtr conv; /* if encoder != NULL buffer for output */
int written; /* total number of byte written */ int written; /* total number of byte written */
int error; int error;
}; };
#endif /* LIBXML_OUTPUT_ENABLED */ #endif /* LIBXML_OUTPUT_ENABLED */
/* /*
* Interfaces for input * Interfaces for input
*/ */
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlCleanupInputCallbacks (void); xmlCleanupInputCallbacks (void);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlPopInputCallbacks (void); xmlPopInputCallbacks (void);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlRegisterDefaultInputCallbacks (void); xmlRegisterDefaultInputCallbacks (void);
XMLPUBFUN xmlParserInputBufferPtr XMLCALL XMLPUBFUN xmlParserInputBufferPtr XMLCALL
xmlAllocParserInputBuffer (xmlCharEncoding enc); xmlAllocParserInputBuffer (xmlCharEncoding enc);
XMLPUBFUN xmlParserInputBufferPtr XMLCALL XMLPUBFUN xmlParserInputBufferPtr XMLCALL
xmlParserInputBufferCreateFilename (const char *URI, xmlParserInputBufferCreateFilename (const char *URI,
xmlCharEncoding enc); xmlCharEncoding enc);
XMLPUBFUN xmlParserInputBufferPtr XMLCALL XMLPUBFUN xmlParserInputBufferPtr XMLCALL
xmlParserInputBufferCreateFile (FILE *file, xmlParserInputBufferCreateFile (FILE *file,
xmlCharEncoding enc); xmlCharEncoding enc);
XMLPUBFUN xmlParserInputBufferPtr XMLCALL XMLPUBFUN xmlParserInputBufferPtr XMLCALL
xmlParserInputBufferCreateFd (int fd, xmlParserInputBufferCreateFd (int fd,
xmlCharEncoding enc); xmlCharEncoding enc);
XMLPUBFUN xmlParserInputBufferPtr XMLCALL XMLPUBFUN xmlParserInputBufferPtr XMLCALL
xmlParserInputBufferCreateMem (const char *mem, int size, xmlParserInputBufferCreateMem (const char *mem, int size,
xmlCharEncoding enc); xmlCharEncoding enc);
XMLPUBFUN xmlParserInputBufferPtr XMLCALL XMLPUBFUN xmlParserInputBufferPtr XMLCALL
xmlParserInputBufferCreateStatic (const char *mem, int size, xmlParserInputBufferCreateStatic (const char *mem, int size,
xmlCharEncoding enc); xmlCharEncoding enc);
XMLPUBFUN xmlParserInputBufferPtr XMLCALL XMLPUBFUN xmlParserInputBufferPtr XMLCALL
xmlParserInputBufferCreateIO (xmlInputReadCallback iore xmlParserInputBufferCreateIO (xmlInputReadCallback ioread,
ad, xmlInputCloseCallback ioclose,
xmlInputCloseCallback iocl void *ioctx,
ose, xmlCharEncoding enc);
void *ioctx,
xmlCharEncoding enc);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlParserInputBufferRead (xmlParserInputBufferPtr in, xmlParserInputBufferRead (xmlParserInputBufferPtr in,
int len); int len);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlParserInputBufferGrow (xmlParserInputBufferPtr in, xmlParserInputBufferGrow (xmlParserInputBufferPtr in,
int len); int len);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlParserInputBufferPush (xmlParserInputBufferPtr in, xmlParserInputBufferPush (xmlParserInputBufferPtr in,
int len, int len,
const char *buf); const char *buf);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlFreeParserInputBuffer (xmlParserInputBufferPtr in) ; xmlFreeParserInputBuffer (xmlParserInputBufferPtr in);
XMLPUBFUN char * XMLCALL XMLPUBFUN char * XMLCALL
xmlParserGetDirectory (const char *filename); xmlParserGetDirectory (const char *filename);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlRegisterInputCallbacks (xmlInputMatchCallback match xmlRegisterInputCallbacks (xmlInputMatchCallback matchFunc,
Func, xmlInputOpenCallback openFunc,
xmlInputOpenCallback openFu xmlInputReadCallback readFunc,
nc, xmlInputCloseCallback closeFunc);
xmlInputReadCallback readFu
nc,
xmlInputCloseCallback close
Func);
xmlParserInputBufferPtr xmlParserInputBufferPtr
__xmlParserInputBufferCreateFilename(const char *URI, __xmlParserInputBufferCreateFilename(const char *URI,
xmlCharEncoding enc);
xmlCharEncoding enc);
#ifdef LIBXML_OUTPUT_ENABLED #ifdef LIBXML_OUTPUT_ENABLED
/* /*
* Interfaces for output * Interfaces for output
*/ */
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlCleanupOutputCallbacks (void); xmlCleanupOutputCallbacks (void);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlRegisterDefaultOutputCallbacks(void); xmlRegisterDefaultOutputCallbacks(void);
XMLPUBFUN xmlOutputBufferPtr XMLCALL XMLPUBFUN xmlOutputBufferPtr XMLCALL
xmlAllocOutputBuffer (xmlCharEncodingHandlerPtr encoder); xmlAllocOutputBuffer (xmlCharEncodingHandlerPtr encoder);
XMLPUBFUN xmlOutputBufferPtr XMLCALL XMLPUBFUN xmlOutputBufferPtr XMLCALL
xmlOutputBufferCreateFilename (const char *URI, xmlOutputBufferCreateFilename (const char *URI,
xmlCharEncodingHandlerPtr encoder, xmlCharEncodingHandlerPtr encoder,
int compression); int compression);
XMLPUBFUN xmlOutputBufferPtr XMLCALL XMLPUBFUN xmlOutputBufferPtr XMLCALL
xmlOutputBufferCreateFile (FILE *file, xmlOutputBufferCreateFile (FILE *file,
xmlCharEncodingHandlerPtr encoder); xmlCharEncodingHandlerPtr encoder);
XMLPUBFUN xmlOutputBufferPtr XMLCALL XMLPUBFUN xmlOutputBufferPtr XMLCALL
xmlOutputBufferCreateBuffer (xmlBufferPtr buffer, xmlOutputBufferCreateBuffer (xmlBufferPtr buffer,
xmlCharEncodingHandlerPtr encoder); xmlCharEncodingHandlerPtr encoder);
XMLPUBFUN xmlOutputBufferPtr XMLCALL XMLPUBFUN xmlOutputBufferPtr XMLCALL
xmlOutputBufferCreateFd (int fd, xmlOutputBufferCreateFd (int fd,
xmlCharEncodingHandlerPtr encoder); xmlCharEncodingHandlerPtr encoder);
XMLPUBFUN xmlOutputBufferPtr XMLCALL XMLPUBFUN xmlOutputBufferPtr XMLCALL
xmlOutputBufferCreateIO (xmlOutputWriteCallback iowrite, xmlOutputBufferCreateIO (xmlOutputWriteCallback iowrite,
xmlOutputCloseCallback ioclose, xmlOutputCloseCallback ioclose,
void *ioctx, void *ioctx,
xmlCharEncodingHandlerPtr encoder); xmlCharEncodingHandlerPtr encoder);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlOutputBufferWrite (xmlOutputBufferPtr out, xmlOutputBufferWrite (xmlOutputBufferPtr out,
int len, int len,
const char *buf); const char *buf);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlOutputBufferWriteString (xmlOutputBufferPtr out, xmlOutputBufferWriteString (xmlOutputBufferPtr out,
const char *str); const char *str);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlOutputBufferWriteEscape (xmlOutputBufferPtr out, xmlOutputBufferWriteEscape (xmlOutputBufferPtr out,
const xmlChar *str, const xmlChar *str,
xmlCharEncodingOutputFunc escaping) xmlCharEncodingOutputFunc escaping);
;
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlOutputBufferFlush (xmlOutputBufferPtr out); xmlOutputBufferFlush (xmlOutputBufferPtr out);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlOutputBufferClose (xmlOutputBufferPtr out); xmlOutputBufferClose (xmlOutputBufferPtr out);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlRegisterOutputCallbacks (xmlOutputMatchCallback matchFunc, xmlRegisterOutputCallbacks (xmlOutputMatchCallback matchFunc,
xmlOutputOpenCallback openFunc, xmlOutputOpenCallback openFunc,
xmlOutputWriteCallback writeFunc, xmlOutputWriteCallback writeFunc,
xmlOutputCloseCallback closeFunc); xmlOutputCloseCallback closeFunc);
xmlOutputBufferPtr xmlOutputBufferPtr
__xmlOutputBufferCreateFilename(const char *URI, __xmlOutputBufferCreateFilename(const char *URI,
xmlCharEncodingHandlerPtr encoder, xmlCharEncodingHandlerPtr encoder,
int compression); int compression);
#ifdef LIBXML_HTTP_ENABLED #ifdef LIBXML_HTTP_ENABLED
/* This function only exists if HTTP support built into the library */ /* This function only exists if HTTP support built into the library */
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlRegisterHTTPPostCallbacks (void ); xmlRegisterHTTPPostCallbacks (void );
#endif /* LIBXML_HTTP_ENABLED */ #endif /* LIBXML_HTTP_ENABLED */
#endif /* LIBXML_OUTPUT_ENABLED */ #endif /* LIBXML_OUTPUT_ENABLED */
XMLPUBFUN xmlParserInputPtr XMLCALL XMLPUBFUN xmlParserInputPtr XMLCALL
xmlCheckHTTPInput (xmlParserCtxtPtr ctxt, xmlCheckHTTPInput (xmlParserCtxtPtr ctxt,
xmlParserInputPtr ret); xmlParserInputPtr ret);
/* /*
* A predefined entity loader disabling network accesses * A predefined entity loader disabling network accesses
*/ */
XMLPUBFUN xmlParserInputPtr XMLCALL XMLPUBFUN xmlParserInputPtr XMLCALL
xmlNoNetExternalEntityLoader (const char *URL, xmlNoNetExternalEntityLoader (const char *URL,
const char *ID, const char *ID,
xmlParserCtxtPtr ctxt); xmlParserCtxtPtr ctxt);
/* /*
* xmlNormalizeWindowsPath is obsolete, don't use it. * xmlNormalizeWindowsPath is obsolete, don't use it.
* Check xmlCanonicPath in uri.h for a better alternative. * Check xmlCanonicPath in uri.h for a better alternative.
*/ */
XMLPUBFUN xmlChar * XMLCALL XMLPUBFUN xmlChar * XMLCALL
xmlNormalizeWindowsPath (const xmlChar *path); xmlNormalizeWindowsPath (const xmlChar *path);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlCheckFilename (const char *path); xmlCheckFilename (const char *path);
/** /**
* Default 'file://' protocol callbacks * Default 'file://' protocol callbacks
*/ */
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlFileMatch (const char *filename); xmlFileMatch (const char *filename);
XMLPUBFUN void * XMLCALL XMLPUBFUN void * XMLCALL
xmlFileOpen (const char *filename); xmlFileOpen (const char *filename);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlFileRead (void * context, xmlFileRead (void * context,
char * buffer, char * buffer,
int len); int len);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlFileClose (void * context); xmlFileClose (void * context);
/** /**
* Default 'http://' protocol callbacks * Default 'http://' protocol callbacks
*/ */
#ifdef LIBXML_HTTP_ENABLED #ifdef LIBXML_HTTP_ENABLED
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlIOHTTPMatch (const char *filename); xmlIOHTTPMatch (const char *filename);
XMLPUBFUN void * XMLCALL XMLPUBFUN void * XMLCALL
xmlIOHTTPOpen (const char *filename); xmlIOHTTPOpen (const char *filename);
#ifdef LIBXML_OUTPUT_ENABLED #ifdef LIBXML_OUTPUT_ENABLED
XMLPUBFUN void * XMLCALL XMLPUBFUN void * XMLCALL
xmlIOHTTPOpenW (const char * post_uri, xmlIOHTTPOpenW (const char * post_uri,
int compression ); int compression );
#endif /* LIBXML_OUTPUT_ENABLED */ #endif /* LIBXML_OUTPUT_ENABLED */
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlIOHTTPRead (void * context, xmlIOHTTPRead (void * context,
char * buffer, char * buffer,
int len); int len);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlIOHTTPClose (void * context); xmlIOHTTPClose (void * context);
#endif /* LIBXML_HTTP_ENABLED */ #endif /* LIBXML_HTTP_ENABLED */
/** /**
* Default 'ftp://' protocol callbacks * Default 'ftp://' protocol callbacks
*/ */
#ifdef LIBXML_FTP_ENABLED #ifdef LIBXML_FTP_ENABLED
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlIOFTPMatch (const char *filename); xmlIOFTPMatch (const char *filename);
XMLPUBFUN void * XMLCALL XMLPUBFUN void * XMLCALL
xmlIOFTPOpen (const char *filename); xmlIOFTPOpen (const char *filename);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlIOFTPRead (void * context, xmlIOFTPRead (void * context,
char * buffer, char * buffer,
int len); int len);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlIOFTPClose (void * context); xmlIOFTPClose (void * context);
#endif /* LIBXML_FTP_ENABLED */ #endif /* LIBXML_FTP_ENABLED */
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif
#endif /* __XML_IO_H__ */ #endif /* __XML_IO_H__ */
 End of changes. 51 change blocks. 
99 lines changed or deleted 91 lines changed or added


 xmlautomata.h   xmlautomata.h 
skipping to change at line 44 skipping to change at line 44
* *
* A state int the automata description, * A state int the automata description,
*/ */
typedef struct _xmlAutomataState xmlAutomataState; typedef struct _xmlAutomataState xmlAutomataState;
typedef xmlAutomataState *xmlAutomataStatePtr; typedef xmlAutomataState *xmlAutomataStatePtr;
/* /*
* Building API * Building API
*/ */
XMLPUBFUN xmlAutomataPtr XMLCALL XMLPUBFUN xmlAutomataPtr XMLCALL
xmlNewAutomata (void); xmlNewAutomata (void);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlFreeAutomata (xmlAutomataPtr am); xmlFreeAutomata (xmlAutomataPtr am);
XMLPUBFUN xmlAutomataStatePtr XMLCALL XMLPUBFUN xmlAutomataStatePtr XMLCALL
xmlAutomataGetInitState (xmlAutomataPtr am); xmlAutomataGetInitState (xmlAutomataPtr am);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlAutomataSetFinalState (xmlAutomataPtr am, xmlAutomataSetFinalState (xmlAutomataPtr am,
xmlAutomataStatePtr state); xmlAutomataStatePtr state);
XMLPUBFUN xmlAutomataStatePtr XMLCALL XMLPUBFUN xmlAutomataStatePtr XMLCALL
xmlAutomataNewState (xmlAutomataPtr am); xmlAutomataNewState (xmlAutomataPtr am);
XMLPUBFUN xmlAutomataStatePtr XMLCALL XMLPUBFUN xmlAutomataStatePtr XMLCALL
xmlAutomataNewTransition (xmlAutomataPtr am, xmlAutomataNewTransition (xmlAutomataPtr am,
xmlAutomataStatePtr from, xmlAutomataStatePtr from,
xmlAutomataStatePtr to, xmlAutomataStatePtr to,
const xmlChar *token, const xmlChar *token,
void *data); void *data);
XMLPUBFUN xmlAutomataStatePtr XMLCALL XMLPUBFUN xmlAutomataStatePtr XMLCALL
xmlAutomataNewTransition2 (xmlAutomataPtr am, xmlAutomataNewTransition2 (xmlAutomataPtr am,
xmlAutomataStatePtr from, xmlAutomataStatePtr from,
xmlAutomataStatePtr to, xmlAutomataStatePtr to,
const xmlChar *token, const xmlChar *token,
const xmlChar *token2, const xmlChar *token2,
void *data); void *data);
XMLPUBFUN xmlAutomataStatePtr XMLCALL XMLPUBFUN xmlAutomataStatePtr XMLCALL
xmlAutomataNewNegTrans (xmlAutomataPtr am, xmlAutomataNewNegTrans (xmlAutomataPtr am,
xmlAutomataStatePtr from, xmlAutomataStatePtr from,
xmlAutomataStatePtr to, xmlAutomataStatePtr to,
const xmlChar *token, const xmlChar *token,
const xmlChar *token2, const xmlChar *token2,
void *data); void *data);
XMLPUBFUN xmlAutomataStatePtr XMLCALL XMLPUBFUN xmlAutomataStatePtr XMLCALL
xmlAutomataNewCountTrans (xmlAutomataPtr am, xmlAutomataNewCountTrans (xmlAutomataPtr am,
xmlAutomataStatePtr from, xmlAutomataStatePtr from,
xmlAutomataStatePtr to, xmlAutomataStatePtr to,
const xmlChar *token, const xmlChar *token,
int min, int min,
int max, int max,
void *data); void *data);
XMLPUBFUN xmlAutomataStatePtr XMLCALL XMLPUBFUN xmlAutomataStatePtr XMLCALL
xmlAutomataNewCountTrans2 (xmlAutomataPtr am, xmlAutomataNewCountTrans2 (xmlAutomataPtr am,
xmlAutomataStatePtr from, xmlAutomataStatePtr from,
xmlAutomataStatePtr to, xmlAutomataStatePtr to,
const xmlChar *token, const xmlChar *token,
const xmlChar *token2, const xmlChar *token2,
int min, int min,
int max, int max,
void *data); void *data);
XMLPUBFUN xmlAutomataStatePtr XMLCALL XMLPUBFUN xmlAutomataStatePtr XMLCALL
xmlAutomataNewOnceTrans (xmlAutomataPtr am, xmlAutomataNewOnceTrans (xmlAutomataPtr am,
xmlAutomataStatePtr from, xmlAutomataStatePtr from,
xmlAutomataStatePtr to, xmlAutomataStatePtr to,
const xmlChar *token, const xmlChar *token,
int min, int min,
int max, int max,
void *data); void *data);
XMLPUBFUN xmlAutomataStatePtr XMLCALL XMLPUBFUN xmlAutomataStatePtr XMLCALL
xmlAutomataNewOnceTrans2 (xmlAutomataPtr am, xmlAutomataNewOnceTrans2 (xmlAutomataPtr am,
xmlAutomataStatePtr from, xmlAutomataStatePtr from,
xmlAutomataStatePtr to, xmlAutomataStatePtr to,
const xmlChar *token, const xmlChar *token,
const xmlChar *token2, const xmlChar *token2,
int min, int min,
int max, int max,
void *data); void *data);
XMLPUBFUN xmlAutomataStatePtr XMLCALL XMLPUBFUN xmlAutomataStatePtr XMLCALL
xmlAutomataNewAllTrans (xmlAutomataPtr am, xmlAutomataNewAllTrans (xmlAutomataPtr am,
xmlAutomataStatePtr from, xmlAutomataStatePtr from,
xmlAutomataStatePtr to, xmlAutomataStatePtr to,
int lax); int lax);
XMLPUBFUN xmlAutomataStatePtr XMLCALL XMLPUBFUN xmlAutomataStatePtr XMLCALL
xmlAutomataNewEpsilon (xmlAutomataPtr am, xmlAutomataNewEpsilon (xmlAutomataPtr am,
xmlAutomataStatePtr from, xmlAutomataStatePtr from,
xmlAutomataStatePtr to); xmlAutomataStatePtr to);
XMLPUBFUN xmlAutomataStatePtr XMLCALL XMLPUBFUN xmlAutomataStatePtr XMLCALL
xmlAutomataNewCountedTrans (xmlAutomataPtr am, xmlAutomataNewCountedTrans (xmlAutomataPtr am,
xmlAutomataStatePtr from, xmlAutomataStatePtr from,
xmlAutomataStatePtr to, xmlAutomataStatePtr to,
int counter); int counter);
XMLPUBFUN xmlAutomataStatePtr XMLCALL XMLPUBFUN xmlAutomataStatePtr XMLCALL
xmlAutomataNewCounterTrans (xmlAutomataPtr am, xmlAutomataNewCounterTrans (xmlAutomataPtr am,
xmlAutomataStatePtr from, xmlAutomataStatePtr from,
xmlAutomataStatePtr to, xmlAutomataStatePtr to,
int counter); int counter);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlAutomataNewCounter (xmlAutomataPtr am, xmlAutomataNewCounter (xmlAutomataPtr am,
int min, int min,
int max); int max);
XMLPUBFUN xmlRegexpPtr XMLCALL XMLPUBFUN xmlRegexpPtr XMLCALL
xmlAutomataCompile (xmlAutomataPtr am); xmlAutomataCompile (xmlAutomataPtr am);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlAutomataIsDeterminist (xmlAutomataPtr am); xmlAutomataIsDeterminist (xmlAutomataPtr am);
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif
#endif /* LIBXML_AUTOMATA_ENABLED */ #endif /* LIBXML_AUTOMATA_ENABLED */
#endif /* LIBXML_REGEXP_ENABLED */ #endif /* LIBXML_REGEXP_ENABLED */
#endif /* __XML_AUTOMATA_H__ */ #endif /* __XML_AUTOMATA_H__ */
 End of changes. 9 change blocks. 
84 lines changed or deleted 84 lines changed or added


 xmlerror.h   xmlerror.h 
skipping to change at line 26 skipping to change at line 26
extern "C" { extern "C" {
#endif #endif
/** /**
* xmlErrorLevel: * xmlErrorLevel:
* *
* Indicates the level of an error * Indicates the level of an error
*/ */
typedef enum { typedef enum {
XML_ERR_NONE = 0, XML_ERR_NONE = 0,
XML_ERR_WARNING = 1, /* A simple warning */ XML_ERR_WARNING = 1, /* A simple warning */
XML_ERR_ERROR = 2, /* A recoverable error */ XML_ERR_ERROR = 2, /* A recoverable error */
XML_ERR_FATAL = 3 /* A fatal error */ XML_ERR_FATAL = 3 /* A fatal error */
} xmlErrorLevel; } xmlErrorLevel;
/** /**
* xmlErrorDomain: * xmlErrorDomain:
* *
* Indicates where an error may have come from * Indicates where an error may have come from
*/ */
typedef enum { typedef enum {
XML_FROM_NONE = 0, XML_FROM_NONE = 0,
XML_FROM_PARSER, /* The XML parser */ XML_FROM_PARSER, /* The XML parser */
XML_FROM_TREE, /* The tree module */ XML_FROM_TREE, /* The tree module */
XML_FROM_NAMESPACE, /* The XML Namespace module */ XML_FROM_NAMESPACE, /* The XML Namespace module */
XML_FROM_DTD, /* The XML DTD validation with parser context*/ XML_FROM_DTD, /* The XML DTD validation with parser context*/
XML_FROM_HTML, /* The HTML parser */ XML_FROM_HTML, /* The HTML parser */
XML_FROM_MEMORY, /* The memory allocator */ XML_FROM_MEMORY, /* The memory allocator */
XML_FROM_OUTPUT, /* The serialization code */ XML_FROM_OUTPUT, /* The serialization code */
XML_FROM_IO, /* The Input/Output stack */ XML_FROM_IO, /* The Input/Output stack */
XML_FROM_FTP, /* The FTP module */ XML_FROM_FTP, /* The FTP module */
XML_FROM_HTTP, /* The HTTP module */ XML_FROM_HTTP, /* The HTTP module */
XML_FROM_XINCLUDE, /* The XInclude processing */ XML_FROM_XINCLUDE, /* The XInclude processing */
XML_FROM_XPATH, /* The XPath module */ XML_FROM_XPATH, /* The XPath module */
XML_FROM_XPOINTER, /* The XPointer module */ XML_FROM_XPOINTER, /* The XPointer module */
XML_FROM_REGEXP, /* The regular expressions module */ XML_FROM_REGEXP, /* The regular expressions module */
XML_FROM_DATATYPE, /* The W3C XML Schemas Datatype module */ XML_FROM_DATATYPE, /* The W3C XML Schemas Datatype module */
XML_FROM_SCHEMASP, /* The W3C XML Schemas parser module */ XML_FROM_SCHEMASP, /* The W3C XML Schemas parser module */
XML_FROM_SCHEMASV, /* The W3C XML Schemas validation module */ XML_FROM_SCHEMASV, /* The W3C XML Schemas validation module */
XML_FROM_RELAXNGP, /* The Relax-NG parser module */ XML_FROM_RELAXNGP, /* The Relax-NG parser module */
XML_FROM_RELAXNGV, /* The Relax-NG validator module */ XML_FROM_RELAXNGV, /* The Relax-NG validator module */
XML_FROM_CATALOG, /* The Catalog module */ XML_FROM_CATALOG, /* The Catalog module */
XML_FROM_C14N, /* The Canonicalization module */ XML_FROM_C14N, /* The Canonicalization module */
XML_FROM_XSLT, /* The XSLT engine from libxslt */ XML_FROM_XSLT, /* The XSLT engine from libxslt */
XML_FROM_VALID, /* The XML DTD validation with valid context */ XML_FROM_VALID, /* The XML DTD validation with valid context */
XML_FROM_CHECK, /* The error checking module */ XML_FROM_CHECK, /* The error checking module */
XML_FROM_WRITER, /* The xmlwriter module */ XML_FROM_WRITER, /* The xmlwriter module */
XML_FROM_MODULE, /* The dynamically loaded module module*/ XML_FROM_MODULE, /* The dynamically loaded module module*/
XML_FROM_I18N, /* The module handling character conversion */ XML_FROM_I18N, /* The module handling character conversion */
XML_FROM_SCHEMATRONV /* The Schematron validator module */ XML_FROM_SCHEMATRONV /* The Schematron validator module */
} xmlErrorDomain; } xmlErrorDomain;
/** /**
* xmlError: * xmlError:
* *
* An XML Error instance. * An XML Error instance.
*/ */
typedef struct _xmlError xmlError; typedef struct _xmlError xmlError;
typedef xmlError *xmlErrorPtr; typedef xmlError *xmlErrorPtr;
struct _xmlError { struct _xmlError {
int domain; /* What part of the library raised this erro int domain; /* What part of the library raised this error */
r */ int code; /* The error code, e.g. an xmlParserError */
int code; /* The error code, e.g. an xmlParserError */
char *message;/* human-readable informative error message */ char *message;/* human-readable informative error message */
xmlErrorLevel level;/* how consequent is the error */ xmlErrorLevel level;/* how consequent is the error */
char *file; /* the filename */ char *file; /* the filename */
int line; /* the line number if available */ int line; /* the line number if available */
char *str1; /* extra string information */ char *str1; /* extra string information */
char *str2; /* extra string information */ char *str2; /* extra string information */
char *str3; /* extra string information */ char *str3; /* extra string information */
int int1; /* extra number information */ int int1; /* extra number information */
int int2; /* column number of the error or 0 if N/A (t int int2; /* column number of the error or 0 if N/A (todo: re
odo: rename this field when we would break ABI) */ name this field when we would break ABI) */
void *ctxt; /* the parser context if available */ void *ctxt; /* the parser context if available */
void *node; /* the node in the tree */ void *node; /* the node in the tree */
}; };
/** /**
* xmlParserError: * xmlParserError:
* *
* This is an error that the XML (or HTML) parser can generate * This is an error that the XML (or HTML) parser can generate
*/ */
typedef enum { typedef enum {
skipping to change at line 845 skipping to change at line 845
/** /**
* xmlGenericErrorFunc: * xmlGenericErrorFunc:
* @ctx: a parsing context * @ctx: a parsing context
* @msg: the message * @msg: the message
* @...: the extra arguments of the varags to format the message * @...: the extra arguments of the varags to format the message
* *
* Signature of the function to use when there is an error and * Signature of the function to use when there is an error and
* no parsing or validity context available . * no parsing or validity context available .
*/ */
typedef void (XMLCDECL *xmlGenericErrorFunc) (void *ctx, typedef void (XMLCDECL *xmlGenericErrorFunc) (void *ctx,
const char *msg, const char *msg,
...) LIBXML_ATTR_FORMAT(2,3); ...) LIBXML_ATTR_FORMAT(2,3);
/** /**
* xmlStructuredErrorFunc: * xmlStructuredErrorFunc:
* @userData: user provided data for the error callback * @userData: user provided data for the error callback
* @error: the error being raised. * @error: the error being raised.
* *
* Signature of the function to use when there is an error and * Signature of the function to use when there is an error and
* the module handles the new error reporting mechanism. * the module handles the new error reporting mechanism.
*/ */
typedef void (XMLCALL *xmlStructuredErrorFunc) (void *userData, xmlErrorPtr error); typedef void (XMLCALL *xmlStructuredErrorFunc) (void *userData, xmlErrorPtr error);
/* /*
* Use the following function to reset the two global variables * Use the following function to reset the two global variables
* xmlGenericError and xmlGenericErrorContext. * xmlGenericError and xmlGenericErrorContext.
*/ */
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlSetGenericErrorFunc (void *ctx, xmlSetGenericErrorFunc (void *ctx,
xmlGenericErrorFunc handler); xmlGenericErrorFunc handler);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
initGenericErrorDefaultFunc (xmlGenericErrorFunc *handler); initGenericErrorDefaultFunc (xmlGenericErrorFunc *handler);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlSetStructuredErrorFunc (void *ctx, xmlSetStructuredErrorFunc (void *ctx,
xmlStructuredErrorFunc handler); xmlStructuredErrorFunc handler);
/* /*
* Default message routines used by SAX and Valid context for error * Default message routines used by SAX and Valid context for error
* and warning reporting. * and warning reporting.
*/ */
XMLPUBFUN void XMLCDECL XMLPUBFUN void XMLCDECL
xmlParserError (void *ctx, xmlParserError (void *ctx,
const char *msg, const char *msg,
...) LIBXML_ATTR_FORMAT(2,3); ...) LIBXML_ATTR_FORMAT(2,3);
XMLPUBFUN void XMLCDECL XMLPUBFUN void XMLCDECL
xmlParserWarning (void *ctx, xmlParserWarning (void *ctx,
const char *msg, const char *msg,
...) LIBXML_ATTR_FORMAT(2,3); ...) LIBXML_ATTR_FORMAT(2,3);
XMLPUBFUN void XMLCDECL XMLPUBFUN void XMLCDECL
xmlParserValidityError (void *ctx, xmlParserValidityError (void *ctx,
const char *msg, const char *msg,
...) LIBXML_ATTR_FORMAT(2,3); ...) LIBXML_ATTR_FORMAT(2,3);
XMLPUBFUN void XMLCDECL XMLPUBFUN void XMLCDECL
xmlParserValidityWarning (void *ctx, xmlParserValidityWarning (void *ctx,
const char *msg, const char *msg,
...) LIBXML_ATTR_FORMAT(2,3); ...) LIBXML_ATTR_FORMAT(2,3);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlParserPrintFileInfo (xmlParserInputPtr input); xmlParserPrintFileInfo (xmlParserInputPtr input);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlParserPrintFileContext (xmlParserInputPtr input); xmlParserPrintFileContext (xmlParserInputPtr input);
/* /*
* Extended error information routines * Extended error information routines
*/ */
XMLPUBFUN xmlErrorPtr XMLCALL XMLPUBFUN xmlErrorPtr XMLCALL
xmlGetLastError (void); xmlGetLastError (void);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlResetLastError (void); xmlResetLastError (void);
XMLPUBFUN xmlErrorPtr XMLCALL XMLPUBFUN xmlErrorPtr XMLCALL
xmlCtxtGetLastError (void *ctx); xmlCtxtGetLastError (void *ctx);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlCtxtResetLastError (void *ctx); xmlCtxtResetLastError (void *ctx);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlResetError (xmlErrorPtr err); xmlResetError (xmlErrorPtr err);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlCopyError (xmlErrorPtr from, xmlCopyError (xmlErrorPtr from,
xmlErrorPtr to); xmlErrorPtr to);
#ifdef IN_LIBXML #ifdef IN_LIBXML
/* /*
* Internal callback reporting routine * Internal callback reporting routine
*/ */
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
__xmlRaiseError (xmlStructuredErrorFunc schannel, __xmlRaiseError (xmlStructuredErrorFunc schannel,
xmlGenericErrorFunc channel, xmlGenericErrorFunc channel,
void *data, void *data,
void *ctx, void *ctx,
void *node, void *node,
int domain, int domain,
int code, int code,
xmlErrorLevel level, xmlErrorLevel level,
const char *file, const char *file,
int line, int line,
const char *str1, const char *str1,
const char *str2, const char *str2,
const char *str3, const char *str3,
int int1, int int1,
int col, int col,
const char *msg, const char *msg,
...) LIBXML_ATTR_FORMAT(16,17); ...) LIBXML_ATTR_FORMAT(16,17);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
__xmlSimpleError (int domain, __xmlSimpleError (int domain,
int code, int code,
xmlNodePtr node, xmlNodePtr node,
const char *msg, const char *msg,
const char *extra); const char *extra);
#endif #endif
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif
#endif /* __XML_ERROR_H__ */ #endif /* __XML_ERROR_H__ */
 End of changes. 23 change blocks. 
91 lines changed or deleted 90 lines changed or added


 xmlmemory.h   xmlmemory.h 
skipping to change at line 103 skipping to change at line 103
LIBXML_DLL_IMPORT xmlReallocFunc xmlRealloc; LIBXML_DLL_IMPORT xmlReallocFunc xmlRealloc;
LIBXML_DLL_IMPORT xmlStrdupFunc xmlMemStrdup; LIBXML_DLL_IMPORT xmlStrdupFunc xmlMemStrdup;
*/ */
/* /*
* The way to overload the existing functions. * The way to overload the existing functions.
* The xmlGc function have an extra entry for atomic block * The xmlGc function have an extra entry for atomic block
* allocations useful for garbage collected memory allocators * allocations useful for garbage collected memory allocators
*/ */
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlMemSetup (xmlFreeFunc freeFunc, xmlMemSetup (xmlFreeFunc freeFunc,
xmlMallocFunc mallocFunc, xmlMallocFunc mallocFunc,
xmlReallocFunc reallocFunc, xmlReallocFunc reallocFunc,
xmlStrdupFunc strdupFunc); xmlStrdupFunc strdupFunc);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlMemGet (xmlFreeFunc *freeFunc, xmlMemGet (xmlFreeFunc *freeFunc,
xmlMallocFunc *mallocFunc, xmlMallocFunc *mallocFunc,
xmlReallocFunc *reallocFunc, xmlReallocFunc *reallocFunc,
xmlStrdupFunc *strdupFunc); xmlStrdupFunc *strdupFunc);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlGcMemSetup (xmlFreeFunc freeFunc, xmlGcMemSetup (xmlFreeFunc freeFunc,
xmlMallocFunc mallocFunc, xmlMallocFunc mallocFunc,
xmlMallocFunc mallocAtomicFunc, xmlMallocFunc mallocAtomicFunc,
xmlReallocFunc reallocFunc, xmlReallocFunc reallocFunc,
xmlStrdupFunc strdupFunc); xmlStrdupFunc strdupFunc);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlGcMemGet (xmlFreeFunc *freeFunc, xmlGcMemGet (xmlFreeFunc *freeFunc,
xmlMallocFunc *mallocFunc, xmlMallocFunc *mallocFunc,
xmlMallocFunc *mallocAtomicFunc, xmlMallocFunc *mallocAtomicFunc,
xmlReallocFunc *reallocFunc, xmlReallocFunc *reallocFunc,
xmlStrdupFunc *strdupFunc); xmlStrdupFunc *strdupFunc);
/* /*
* Initialization of the memory layer. * Initialization of the memory layer.
*/ */
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlInitMemory (void); xmlInitMemory (void);
/* /*
* Cleanup of the memory layer. * Cleanup of the memory layer.
*/ */
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlCleanupMemory (void); xmlCleanupMemory (void);
/* /*
* These are specific to the XML debug memory wrapper. * These are specific to the XML debug memory wrapper.
*/ */
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlMemUsed (void); xmlMemUsed (void);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlMemBlocks (void); xmlMemBlocks (void);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlMemDisplay (FILE *fp); xmlMemDisplay (FILE *fp);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlMemDisplayLast(FILE *fp, long nbBytes); xmlMemDisplayLast(FILE *fp, long nbBytes);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlMemShow (FILE *fp, int nr); xmlMemShow (FILE *fp, int nr);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlMemoryDump (void); xmlMemoryDump (void);
XMLPUBFUN void * XMLCALL XMLPUBFUN void * XMLCALL
xmlMemMalloc (size_t size) LIBXML_ATTR_ALLOC_SIZE(1); xmlMemMalloc (size_t size) LIBXML_ATTR_ALLOC_SIZE(1);
XMLPUBFUN void * XMLCALL XMLPUBFUN void * XMLCALL
xmlMemRealloc (void *ptr,size_t size); xmlMemRealloc (void *ptr,size_t size);
XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL
xmlMemFree (void *ptr); xmlMemFree (void *ptr);
XMLPUBFUN char * XMLCALL XMLPUBFUN char * XMLCALL
xmlMemoryStrdup (const char *str); xmlMemoryStrdup (const char *str);
XMLPUBFUN void * XMLCALL XMLPUBFUN void * XMLCALL
xmlMallocLoc (size_t size, const char *file, int line) LIBXML_ATT R_ALLOC_SIZE(1); xmlMallocLoc (size_t size, const char *file, int line) LIBXML_ATTR_A LLOC_SIZE(1);
XMLPUBFUN void * XMLCALL XMLPUBFUN void * XMLCALL
xmlReallocLoc (void *ptr, size_t size, const char *file, int line) ; xmlReallocLoc (void *ptr, size_t size, const char *file, int line);
XMLPUBFUN void * XMLCALL XMLPUBFUN void * XMLCALL
xmlMallocAtomicLoc (size_t size, const char *file, int line) LIBXML_ ATTR_ALLOC_SIZE(1); xmlMallocAtomicLoc (size_t size, const char *file, int line) LIBXML_ATT R_ALLOC_SIZE(1);
XMLPUBFUN char * XMLCALL XMLPUBFUN char * XMLCALL
xmlMemStrdupLoc (const char *str, const char *file, int line); xmlMemStrdupLoc (const char *str, const char *file, int line);
#ifdef DEBUG_MEMORY_LOCATION #ifdef DEBUG_MEMORY_LOCATION
/** /**
* xmlMalloc: * xmlMalloc:
* @size: number of bytes to allocate * @size: number of bytes to allocate
* *
* Wrapper for the malloc() function used in the XML library. * Wrapper for the malloc() function used in the XML library.
* *
* Returns the pointer to the allocated area or NULL in case of error. * Returns the pointer to the allocated area or NULL in case of error.
*/ */
 End of changes. 16 change blocks. 
36 lines changed or deleted 36 lines changed or added


 xmlsave.h   xmlsave.h 
skipping to change at line 30 skipping to change at line 30
extern "C" { extern "C" {
#endif #endif
/** /**
* xmlSaveOption: * xmlSaveOption:
* *
* This is the set of XML save options that can be passed down * This is the set of XML save options that can be passed down
* to the xmlSaveToFd() and similar calls. * to the xmlSaveToFd() and similar calls.
*/ */
typedef enum { typedef enum {
XML_SAVE_FORMAT = 1<<0, /* format save output */ XML_SAVE_FORMAT = 1<<0, /* format save output */
XML_SAVE_NO_DECL = 1<<1, /* drop the xml declaration */ XML_SAVE_NO_DECL = 1<<1, /* drop the xml declaration */
XML_SAVE_NO_EMPTY = 1<<2, /* no empty tags */ XML_SAVE_NO_EMPTY = 1<<2, /* no empty tags */
XML_SAVE_NO_XHTML = 1<<3, /* disable XHTML1 specific rules */ XML_SAVE_NO_XHTML = 1<<3, /* disable XHTML1 specific rules */
XML_SAVE_XHTML = 1<<4, /* force XHTML1 specific rules */ XML_SAVE_XHTML = 1<<4, /* force XHTML1 specific rules */
XML_SAVE_AS_XML = 1<<5, /* force XML serialization on HTML doc */ XML_SAVE_AS_XML = 1<<5, /* force XML serialization on HTML doc */
XML_SAVE_AS_HTML = 1<<6, /* force HTML serialization on XML doc */ XML_SAVE_AS_HTML = 1<<6 /* force HTML serialization on XML doc */
XML_SAVE_WSNONSIG = 1<<7 /* format with non-significant whitespace *
/
} xmlSaveOption; } xmlSaveOption;
typedef struct _xmlSaveCtxt xmlSaveCtxt; typedef struct _xmlSaveCtxt xmlSaveCtxt;
typedef xmlSaveCtxt *xmlSaveCtxtPtr; typedef xmlSaveCtxt *xmlSaveCtxtPtr;
XMLPUBFUN xmlSaveCtxtPtr XMLCALL XMLPUBFUN xmlSaveCtxtPtr XMLCALL
xmlSaveToFd (int fd, xmlSaveToFd (int fd,
const char *encoding, const char *encoding,
int options); int options);
XMLPUBFUN xmlSaveCtxtPtr XMLCALL XMLPUBFUN xmlSaveCtxtPtr XMLCALL
xmlSaveToFilename (const char *filename, xmlSaveToFilename (const char *filename,
const char *encoding, const char *encoding,
int options); int options);
XMLPUBFUN xmlSaveCtxtPtr XMLCALL XMLPUBFUN xmlSaveCtxtPtr XMLCALL
xmlSaveToBuffer (xmlBufferPtr buffer, xmlSaveToBuffer (xmlBufferPtr buffer,
const char *encoding, const char *encoding,
int options); int options);
XMLPUBFUN xmlSaveCtxtPtr XMLCALL XMLPUBFUN xmlSaveCtxtPtr XMLCALL
xmlSaveToIO (xmlOutputWriteCallback iowrite, xmlSaveToIO (xmlOutputWriteCallback iowrite,
xmlOutputCloseCallback ioclose, xmlOutputCloseCallback ioclose,
void *ioctx, void *ioctx,
const char *encoding, const char *encoding,
int options); int options);
XMLPUBFUN long XMLCALL XMLPUBFUN long XMLCALL
xmlSaveDoc (xmlSaveCtxtPtr ctxt, xmlSaveDoc (xmlSaveCtxtPtr ctxt,
xmlDocPtr doc); xmlDocPtr doc);
XMLPUBFUN long XMLCALL XMLPUBFUN long XMLCALL
xmlSaveTree (xmlSaveCtxtPtr ctxt, xmlSaveTree (xmlSaveCtxtPtr ctxt,
xmlNodePtr node); xmlNodePtr node);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlSaveFlush (xmlSaveCtxtPtr ctxt); xmlSaveFlush (xmlSaveCtxtPtr ctxt);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlSaveClose (xmlSaveCtxtPtr ctxt); xmlSaveClose (xmlSaveCtxtPtr ctxt);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlSaveSetEscape (xmlSaveCtxtPtr ctxt, xmlSaveSetEscape (xmlSaveCtxtPtr ctxt,
xmlCharEncodingOutputFunc escape); xmlCharEncodingOutputFunc escape);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlSaveSetAttrEscape (xmlSaveCtxtPtr ctxt, xmlSaveSetAttrEscape (xmlSaveCtxtPtr ctxt,
xmlCharEncodingOutputFunc escape); xmlCharEncodingOutputFunc escape);
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif
#endif /* LIBXML_OUTPUT_ENABLED */ #endif /* LIBXML_OUTPUT_ENABLED */
#endif /* __XML_XMLSAVE_H__ */ #endif /* __XML_XMLSAVE_H__ */
 End of changes. 12 change blocks. 
32 lines changed or deleted 30 lines changed or added


 xmlunicode.h   xmlunicode.h 
skipping to change at line 26 skipping to change at line 26
#define __XML_UNICODE_H__ #define __XML_UNICODE_H__
#include <libxml/xmlversion.h> #include <libxml/xmlversion.h>
#ifdef LIBXML_UNICODE_ENABLED #ifdef LIBXML_UNICODE_ENABLED
#ifdef __cplusplus #ifdef __cplusplus
extern "C" { extern "C" {
#endif #endif
XMLPUBFUN int XMLCALL xmlUCSIsAegeanNumbers (int code); XMLPUBFUN int XMLCALL xmlUCSIsAegeanNumbers (int code);
XMLPUBFUN int XMLCALL xmlUCSIsAlphabeticPresentationForms (int code); XMLPUBFUN int XMLCALL xmlUCSIsAlphabeticPresentationForms (int code);
XMLPUBFUN int XMLCALL xmlUCSIsArabic (int code); XMLPUBFUN int XMLCALL xmlUCSIsArabic (int code);
XMLPUBFUN int XMLCALL xmlUCSIsArabicPresentationFormsA (int code); XMLPUBFUN int XMLCALL xmlUCSIsArabicPresentationFormsA (int code);
XMLPUBFUN int XMLCALL xmlUCSIsArabicPresentationFormsB (int code); XMLPUBFUN int XMLCALL xmlUCSIsArabicPresentationFormsB (int code);
XMLPUBFUN int XMLCALL xmlUCSIsArmenian (int code); XMLPUBFUN int XMLCALL xmlUCSIsArmenian (int code);
XMLPUBFUN int XMLCALL xmlUCSIsArrows (int code); XMLPUBFUN int XMLCALL xmlUCSIsArrows (int code);
XMLPUBFUN int XMLCALL xmlUCSIsBasicLatin (int code); XMLPUBFUN int XMLCALL xmlUCSIsBasicLatin (int code);
XMLPUBFUN int XMLCALL xmlUCSIsBengali (int code); XMLPUBFUN int XMLCALL xmlUCSIsBengali (int code);
XMLPUBFUN int XMLCALL xmlUCSIsBlockElements (int code); XMLPUBFUN int XMLCALL xmlUCSIsBlockElements (int code);
XMLPUBFUN int XMLCALL xmlUCSIsBopomofo (int code); XMLPUBFUN int XMLCALL xmlUCSIsBopomofo (int code);
XMLPUBFUN int XMLCALL xmlUCSIsBopomofoExtended (int code); XMLPUBFUN int XMLCALL xmlUCSIsBopomofoExtended (int code);
XMLPUBFUN int XMLCALL xmlUCSIsBoxDrawing (int code); XMLPUBFUN int XMLCALL xmlUCSIsBoxDrawing (int code);
XMLPUBFUN int XMLCALL xmlUCSIsBraillePatterns (int code); XMLPUBFUN int XMLCALL xmlUCSIsBraillePatterns (int code);
XMLPUBFUN int XMLCALL xmlUCSIsBuhid (int code); XMLPUBFUN int XMLCALL xmlUCSIsBuhid (int code);
XMLPUBFUN int XMLCALL xmlUCSIsByzantineMusicalSymbols (int code); XMLPUBFUN int XMLCALL xmlUCSIsByzantineMusicalSymbols (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCJKCompatibility (int code); XMLPUBFUN int XMLCALL xmlUCSIsCJKCompatibility (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCJKCompatibilityForms (int code); XMLPUBFUN int XMLCALL xmlUCSIsCJKCompatibilityForms (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCJKCompatibilityIdeographs (int code); XMLPUBFUN int XMLCALL xmlUCSIsCJKCompatibilityIdeographs (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCJKCompatibilityIdeographsSupplement (int XMLPUBFUN int XMLCALL xmlUCSIsCJKCompatibilityIdeographsSupplement (int
code); code);
XMLPUBFUN int XMLCALL xmlUCSIsCJKRadicalsSupplement (int code); XMLPUBFUN int XMLCALL xmlUCSIsCJKRadicalsSupplement (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCJKSymbolsandPunctuation (int code); XMLPUBFUN int XMLCALL xmlUCSIsCJKSymbolsandPunctuation (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCJKUnifiedIdeographs (int code); XMLPUBFUN int XMLCALL xmlUCSIsCJKUnifiedIdeographs (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCJKUnifiedIdeographsExtensionA (int code); XMLPUBFUN int XMLCALL xmlUCSIsCJKUnifiedIdeographsExtensionA (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCJKUnifiedIdeographsExtensionB (int code); XMLPUBFUN int XMLCALL xmlUCSIsCJKUnifiedIdeographsExtensionB (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCherokee (int code); XMLPUBFUN int XMLCALL xmlUCSIsCherokee (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCombiningDiacriticalMarks (int code); XMLPUBFUN int XMLCALL xmlUCSIsCombiningDiacriticalMarks (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCombiningDiacriticalMarksforSymbols (int XMLPUBFUN int XMLCALL xmlUCSIsCombiningDiacriticalMarksforSymbols (int c
code); ode);
XMLPUBFUN int XMLCALL xmlUCSIsCombiningHalfMarks (int code); XMLPUBFUN int XMLCALL xmlUCSIsCombiningHalfMarks (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCombiningMarksforSymbols (int code); XMLPUBFUN int XMLCALL xmlUCSIsCombiningMarksforSymbols (int code);
XMLPUBFUN int XMLCALL xmlUCSIsControlPictures (int code); XMLPUBFUN int XMLCALL xmlUCSIsControlPictures (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCurrencySymbols (int code); XMLPUBFUN int XMLCALL xmlUCSIsCurrencySymbols (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCypriotSyllabary (int code); XMLPUBFUN int XMLCALL xmlUCSIsCypriotSyllabary (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCyrillic (int code); XMLPUBFUN int XMLCALL xmlUCSIsCyrillic (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCyrillicSupplement (int code); XMLPUBFUN int XMLCALL xmlUCSIsCyrillicSupplement (int code);
XMLPUBFUN int XMLCALL xmlUCSIsDeseret (int code); XMLPUBFUN int XMLCALL xmlUCSIsDeseret (int code);
XMLPUBFUN int XMLCALL xmlUCSIsDevanagari (int code); XMLPUBFUN int XMLCALL xmlUCSIsDevanagari (int code);
XMLPUBFUN int XMLCALL xmlUCSIsDingbats (int code); XMLPUBFUN int XMLCALL xmlUCSIsDingbats (int code);
XMLPUBFUN int XMLCALL xmlUCSIsEnclosedAlphanumerics (int code); XMLPUBFUN int XMLCALL xmlUCSIsEnclosedAlphanumerics (int code);
XMLPUBFUN int XMLCALL xmlUCSIsEnclosedCJKLettersandMonths (int code); XMLPUBFUN int XMLCALL xmlUCSIsEnclosedCJKLettersandMonths (int code);
XMLPUBFUN int XMLCALL xmlUCSIsEthiopic (int code); XMLPUBFUN int XMLCALL xmlUCSIsEthiopic (int code);
XMLPUBFUN int XMLCALL xmlUCSIsGeneralPunctuation (int code); XMLPUBFUN int XMLCALL xmlUCSIsGeneralPunctuation (int code);
XMLPUBFUN int XMLCALL xmlUCSIsGeometricShapes (int code); XMLPUBFUN int XMLCALL xmlUCSIsGeometricShapes (int code);
XMLPUBFUN int XMLCALL xmlUCSIsGeorgian (int code); XMLPUBFUN int XMLCALL xmlUCSIsGeorgian (int code);
XMLPUBFUN int XMLCALL xmlUCSIsGothic (int code); XMLPUBFUN int XMLCALL xmlUCSIsGothic (int code);
XMLPUBFUN int XMLCALL xmlUCSIsGreek (int code); XMLPUBFUN int XMLCALL xmlUCSIsGreek (int code);
XMLPUBFUN int XMLCALL xmlUCSIsGreekExtended (int code); XMLPUBFUN int XMLCALL xmlUCSIsGreekExtended (int code);
XMLPUBFUN int XMLCALL xmlUCSIsGreekandCoptic (int code); XMLPUBFUN int XMLCALL xmlUCSIsGreekandCoptic (int code);
XMLPUBFUN int XMLCALL xmlUCSIsGujarati (int code); XMLPUBFUN int XMLCALL xmlUCSIsGujarati (int code);
XMLPUBFUN int XMLCALL xmlUCSIsGurmukhi (int code); XMLPUBFUN int XMLCALL xmlUCSIsGurmukhi (int code);
XMLPUBFUN int XMLCALL xmlUCSIsHalfwidthandFullwidthForms (int code); XMLPUBFUN int XMLCALL xmlUCSIsHalfwidthandFullwidthForms (int code);
XMLPUBFUN int XMLCALL xmlUCSIsHangulCompatibilityJamo (int code); XMLPUBFUN int XMLCALL xmlUCSIsHangulCompatibilityJamo (int code);
XMLPUBFUN int XMLCALL xmlUCSIsHangulJamo (int code); XMLPUBFUN int XMLCALL xmlUCSIsHangulJamo (int code);
XMLPUBFUN int XMLCALL xmlUCSIsHangulSyllables (int code); XMLPUBFUN int XMLCALL xmlUCSIsHangulSyllables (int code);
XMLPUBFUN int XMLCALL xmlUCSIsHanunoo (int code); XMLPUBFUN int XMLCALL xmlUCSIsHanunoo (int code);
XMLPUBFUN int XMLCALL xmlUCSIsHebrew (int code); XMLPUBFUN int XMLCALL xmlUCSIsHebrew (int code);
XMLPUBFUN int XMLCALL xmlUCSIsHighPrivateUseSurrogates (int code); XMLPUBFUN int XMLCALL xmlUCSIsHighPrivateUseSurrogates (int code);
XMLPUBFUN int XMLCALL xmlUCSIsHighSurrogates (int code); XMLPUBFUN int XMLCALL xmlUCSIsHighSurrogates (int code);
XMLPUBFUN int XMLCALL xmlUCSIsHiragana (int code); XMLPUBFUN int XMLCALL xmlUCSIsHiragana (int code);
XMLPUBFUN int XMLCALL xmlUCSIsIPAExtensions (int code); XMLPUBFUN int XMLCALL xmlUCSIsIPAExtensions (int code);
XMLPUBFUN int XMLCALL xmlUCSIsIdeographicDescriptionCharacters (int code); XMLPUBFUN int XMLCALL xmlUCSIsIdeographicDescriptionCharacters (int code
XMLPUBFUN int XMLCALL xmlUCSIsKanbun (int code); );
XMLPUBFUN int XMLCALL xmlUCSIsKangxiRadicals (int code); XMLPUBFUN int XMLCALL xmlUCSIsKanbun (int code);
XMLPUBFUN int XMLCALL xmlUCSIsKannada (int code); XMLPUBFUN int XMLCALL xmlUCSIsKangxiRadicals (int code);
XMLPUBFUN int XMLCALL xmlUCSIsKatakana (int code); XMLPUBFUN int XMLCALL xmlUCSIsKannada (int code);
XMLPUBFUN int XMLCALL xmlUCSIsKatakanaPhoneticExtensions (int code); XMLPUBFUN int XMLCALL xmlUCSIsKatakana (int code);
XMLPUBFUN int XMLCALL xmlUCSIsKhmer (int code); XMLPUBFUN int XMLCALL xmlUCSIsKatakanaPhoneticExtensions (int code);
XMLPUBFUN int XMLCALL xmlUCSIsKhmerSymbols (int code); XMLPUBFUN int XMLCALL xmlUCSIsKhmer (int code);
XMLPUBFUN int XMLCALL xmlUCSIsLao (int code); XMLPUBFUN int XMLCALL xmlUCSIsKhmerSymbols (int code);
XMLPUBFUN int XMLCALL xmlUCSIsLatin1Supplement (int code); XMLPUBFUN int XMLCALL xmlUCSIsLao (int code);
XMLPUBFUN int XMLCALL xmlUCSIsLatinExtendedA (int code); XMLPUBFUN int XMLCALL xmlUCSIsLatin1Supplement (int code);
XMLPUBFUN int XMLCALL xmlUCSIsLatinExtendedB (int code); XMLPUBFUN int XMLCALL xmlUCSIsLatinExtendedA (int code);
XMLPUBFUN int XMLCALL xmlUCSIsLatinExtendedAdditional (int code); XMLPUBFUN int XMLCALL xmlUCSIsLatinExtendedB (int code);
XMLPUBFUN int XMLCALL xmlUCSIsLetterlikeSymbols (int code); XMLPUBFUN int XMLCALL xmlUCSIsLatinExtendedAdditional (int code);
XMLPUBFUN int XMLCALL xmlUCSIsLimbu (int code); XMLPUBFUN int XMLCALL xmlUCSIsLetterlikeSymbols (int code);
XMLPUBFUN int XMLCALL xmlUCSIsLinearBIdeograms (int code); XMLPUBFUN int XMLCALL xmlUCSIsLimbu (int code);
XMLPUBFUN int XMLCALL xmlUCSIsLinearBSyllabary (int code); XMLPUBFUN int XMLCALL xmlUCSIsLinearBIdeograms (int code);
XMLPUBFUN int XMLCALL xmlUCSIsLowSurrogates (int code); XMLPUBFUN int XMLCALL xmlUCSIsLinearBSyllabary (int code);
XMLPUBFUN int XMLCALL xmlUCSIsMalayalam (int code); XMLPUBFUN int XMLCALL xmlUCSIsLowSurrogates (int code);
XMLPUBFUN int XMLCALL xmlUCSIsMathematicalAlphanumericSymbols (int code); XMLPUBFUN int XMLCALL xmlUCSIsMalayalam (int code);
XMLPUBFUN int XMLCALL xmlUCSIsMathematicalOperators (int code); XMLPUBFUN int XMLCALL xmlUCSIsMathematicalAlphanumericSymbols (int code)
XMLPUBFUN int XMLCALL xmlUCSIsMiscellaneousMathematicalSymbolsA (int ;
code); XMLPUBFUN int XMLCALL xmlUCSIsMathematicalOperators (int code);
XMLPUBFUN int XMLCALL xmlUCSIsMiscellaneousMathematicalSymbolsB (int XMLPUBFUN int XMLCALL xmlUCSIsMiscellaneousMathematicalSymbolsA (int cod
code); e);
XMLPUBFUN int XMLCALL xmlUCSIsMiscellaneousSymbols (int code); XMLPUBFUN int XMLCALL xmlUCSIsMiscellaneousMathematicalSymbolsB (int cod
XMLPUBFUN int XMLCALL xmlUCSIsMiscellaneousSymbolsandArrows (int code); e);
XMLPUBFUN int XMLCALL xmlUCSIsMiscellaneousTechnical (int code); XMLPUBFUN int XMLCALL xmlUCSIsMiscellaneousSymbols (int code);
XMLPUBFUN int XMLCALL xmlUCSIsMongolian (int code); XMLPUBFUN int XMLCALL xmlUCSIsMiscellaneousSymbolsandArrows (int code);
XMLPUBFUN int XMLCALL xmlUCSIsMusicalSymbols (int code); XMLPUBFUN int XMLCALL xmlUCSIsMiscellaneousTechnical (int code);
XMLPUBFUN int XMLCALL xmlUCSIsMyanmar (int code); XMLPUBFUN int XMLCALL xmlUCSIsMongolian (int code);
XMLPUBFUN int XMLCALL xmlUCSIsNumberForms (int code); XMLPUBFUN int XMLCALL xmlUCSIsMusicalSymbols (int code);
XMLPUBFUN int XMLCALL xmlUCSIsOgham (int code); XMLPUBFUN int XMLCALL xmlUCSIsMyanmar (int code);
XMLPUBFUN int XMLCALL xmlUCSIsOldItalic (int code); XMLPUBFUN int XMLCALL xmlUCSIsNumberForms (int code);
XMLPUBFUN int XMLCALL xmlUCSIsOpticalCharacterRecognition (int code); XMLPUBFUN int XMLCALL xmlUCSIsOgham (int code);
XMLPUBFUN int XMLCALL xmlUCSIsOriya (int code); XMLPUBFUN int XMLCALL xmlUCSIsOldItalic (int code);
XMLPUBFUN int XMLCALL xmlUCSIsOsmanya (int code); XMLPUBFUN int XMLCALL xmlUCSIsOpticalCharacterRecognition (int code);
XMLPUBFUN int XMLCALL xmlUCSIsPhoneticExtensions (int code); XMLPUBFUN int XMLCALL xmlUCSIsOriya (int code);
XMLPUBFUN int XMLCALL xmlUCSIsPrivateUse (int code); XMLPUBFUN int XMLCALL xmlUCSIsOsmanya (int code);
XMLPUBFUN int XMLCALL xmlUCSIsPrivateUseArea (int code); XMLPUBFUN int XMLCALL xmlUCSIsPhoneticExtensions (int code);
XMLPUBFUN int XMLCALL xmlUCSIsRunic (int code); XMLPUBFUN int XMLCALL xmlUCSIsPrivateUse (int code);
XMLPUBFUN int XMLCALL xmlUCSIsShavian (int code); XMLPUBFUN int XMLCALL xmlUCSIsPrivateUseArea (int code);
XMLPUBFUN int XMLCALL xmlUCSIsSinhala (int code); XMLPUBFUN int XMLCALL xmlUCSIsRunic (int code);
XMLPUBFUN int XMLCALL xmlUCSIsSmallFormVariants (int code); XMLPUBFUN int XMLCALL xmlUCSIsShavian (int code);
XMLPUBFUN int XMLCALL xmlUCSIsSpacingModifierLetters (int code); XMLPUBFUN int XMLCALL xmlUCSIsSinhala (int code);
XMLPUBFUN int XMLCALL xmlUCSIsSpecials (int code); XMLPUBFUN int XMLCALL xmlUCSIsSmallFormVariants (int code);
XMLPUBFUN int XMLCALL xmlUCSIsSuperscriptsandSubscripts (int code); XMLPUBFUN int XMLCALL xmlUCSIsSpacingModifierLetters (int code);
XMLPUBFUN int XMLCALL xmlUCSIsSupplementalArrowsA (int code); XMLPUBFUN int XMLCALL xmlUCSIsSpecials (int code);
XMLPUBFUN int XMLCALL xmlUCSIsSupplementalArrowsB (int code); XMLPUBFUN int XMLCALL xmlUCSIsSuperscriptsandSubscripts (int code);
XMLPUBFUN int XMLCALL xmlUCSIsSupplementalMathematicalOperators (int XMLPUBFUN int XMLCALL xmlUCSIsSupplementalArrowsA (int code);
code); XMLPUBFUN int XMLCALL xmlUCSIsSupplementalArrowsB (int code);
XMLPUBFUN int XMLCALL xmlUCSIsSupplementaryPrivateUseAreaA (int code); XMLPUBFUN int XMLCALL xmlUCSIsSupplementalMathematicalOperators (int cod
XMLPUBFUN int XMLCALL xmlUCSIsSupplementaryPrivateUseAreaB (int code); e);
XMLPUBFUN int XMLCALL xmlUCSIsSyriac (int code); XMLPUBFUN int XMLCALL xmlUCSIsSupplementaryPrivateUseAreaA (int code);
XMLPUBFUN int XMLCALL xmlUCSIsTagalog (int code); XMLPUBFUN int XMLCALL xmlUCSIsSupplementaryPrivateUseAreaB (int code);
XMLPUBFUN int XMLCALL xmlUCSIsTagbanwa (int code); XMLPUBFUN int XMLCALL xmlUCSIsSyriac (int code);
XMLPUBFUN int XMLCALL xmlUCSIsTags (int code); XMLPUBFUN int XMLCALL xmlUCSIsTagalog (int code);
XMLPUBFUN int XMLCALL xmlUCSIsTaiLe (int code); XMLPUBFUN int XMLCALL xmlUCSIsTagbanwa (int code);
XMLPUBFUN int XMLCALL xmlUCSIsTaiXuanJingSymbols (int code); XMLPUBFUN int XMLCALL xmlUCSIsTags (int code);
XMLPUBFUN int XMLCALL xmlUCSIsTamil (int code); XMLPUBFUN int XMLCALL xmlUCSIsTaiLe (int code);
XMLPUBFUN int XMLCALL xmlUCSIsTelugu (int code); XMLPUBFUN int XMLCALL xmlUCSIsTaiXuanJingSymbols (int code);
XMLPUBFUN int XMLCALL xmlUCSIsThaana (int code); XMLPUBFUN int XMLCALL xmlUCSIsTamil (int code);
XMLPUBFUN int XMLCALL xmlUCSIsThai (int code); XMLPUBFUN int XMLCALL xmlUCSIsTelugu (int code);
XMLPUBFUN int XMLCALL xmlUCSIsTibetan (int code); XMLPUBFUN int XMLCALL xmlUCSIsThaana (int code);
XMLPUBFUN int XMLCALL xmlUCSIsUgaritic (int code); XMLPUBFUN int XMLCALL xmlUCSIsThai (int code);
XMLPUBFUN int XMLCALL xmlUCSIsUnifiedCanadianAboriginalSyllabics (int XMLPUBFUN int XMLCALL xmlUCSIsTibetan (int code);
code); XMLPUBFUN int XMLCALL xmlUCSIsUgaritic (int code);
XMLPUBFUN int XMLCALL xmlUCSIsVariationSelectors (int code); XMLPUBFUN int XMLCALL xmlUCSIsUnifiedCanadianAboriginalSyllabics (int co
XMLPUBFUN int XMLCALL xmlUCSIsVariationSelectorsSupplement (int code); de);
XMLPUBFUN int XMLCALL xmlUCSIsYiRadicals (int code); XMLPUBFUN int XMLCALL xmlUCSIsVariationSelectors (int code);
XMLPUBFUN int XMLCALL xmlUCSIsYiSyllables (int code); XMLPUBFUN int XMLCALL xmlUCSIsVariationSelectorsSupplement (int code);
XMLPUBFUN int XMLCALL xmlUCSIsYijingHexagramSymbols (int code); XMLPUBFUN int XMLCALL xmlUCSIsYiRadicals (int code);
XMLPUBFUN int XMLCALL xmlUCSIsYiSyllables (int code);
XMLPUBFUN int XMLCALL xmlUCSIsBlock (int code, const char *block); XMLPUBFUN int XMLCALL xmlUCSIsYijingHexagramSymbols (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCatC (int code); XMLPUBFUN int XMLCALL xmlUCSIsBlock (int code, const char *block);
XMLPUBFUN int XMLCALL xmlUCSIsCatCc (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCatCf (int code); XMLPUBFUN int XMLCALL xmlUCSIsCatC (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCatCo (int code); XMLPUBFUN int XMLCALL xmlUCSIsCatCc (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCatCs (int code); XMLPUBFUN int XMLCALL xmlUCSIsCatCf (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCatL (int code); XMLPUBFUN int XMLCALL xmlUCSIsCatCo (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCatLl (int code); XMLPUBFUN int XMLCALL xmlUCSIsCatCs (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCatLm (int code); XMLPUBFUN int XMLCALL xmlUCSIsCatL (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCatLo (int code); XMLPUBFUN int XMLCALL xmlUCSIsCatLl (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCatLt (int code); XMLPUBFUN int XMLCALL xmlUCSIsCatLm (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCatLu (int code); XMLPUBFUN int XMLCALL xmlUCSIsCatLo (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCatM (int code); XMLPUBFUN int XMLCALL xmlUCSIsCatLt (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCatMc (int code); XMLPUBFUN int XMLCALL xmlUCSIsCatLu (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCatMe (int code); XMLPUBFUN int XMLCALL xmlUCSIsCatM (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCatMn (int code); XMLPUBFUN int XMLCALL xmlUCSIsCatMc (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCatN (int code); XMLPUBFUN int XMLCALL xmlUCSIsCatMe (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCatNd (int code); XMLPUBFUN int XMLCALL xmlUCSIsCatMn (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCatNl (int code); XMLPUBFUN int XMLCALL xmlUCSIsCatN (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCatNo (int code); XMLPUBFUN int XMLCALL xmlUCSIsCatNd (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCatP (int code); XMLPUBFUN int XMLCALL xmlUCSIsCatNl (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCatPc (int code); XMLPUBFUN int XMLCALL xmlUCSIsCatNo (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCatPd (int code); XMLPUBFUN int XMLCALL xmlUCSIsCatP (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCatPe (int code); XMLPUBFUN int XMLCALL xmlUCSIsCatPc (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCatPf (int code); XMLPUBFUN int XMLCALL xmlUCSIsCatPd (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCatPi (int code); XMLPUBFUN int XMLCALL xmlUCSIsCatPe (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCatPo (int code); XMLPUBFUN int XMLCALL xmlUCSIsCatPf (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCatPs (int code); XMLPUBFUN int XMLCALL xmlUCSIsCatPi (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCatS (int code); XMLPUBFUN int XMLCALL xmlUCSIsCatPo (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCatSc (int code); XMLPUBFUN int XMLCALL xmlUCSIsCatPs (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCatSk (int code); XMLPUBFUN int XMLCALL xmlUCSIsCatS (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCatSm (int code); XMLPUBFUN int XMLCALL xmlUCSIsCatSc (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCatSo (int code); XMLPUBFUN int XMLCALL xmlUCSIsCatSk (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCatZ (int code); XMLPUBFUN int XMLCALL xmlUCSIsCatSm (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCatZl (int code); XMLPUBFUN int XMLCALL xmlUCSIsCatSo (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCatZp (int code); XMLPUBFUN int XMLCALL xmlUCSIsCatZ (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCatZs (int code); XMLPUBFUN int XMLCALL xmlUCSIsCatZl (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCatZp (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCatZs (int code);
XMLPUBFUN int XMLCALL xmlUCSIsCat (int code, const char *cat); XMLPUBFUN int XMLCALL xmlUCSIsCat (int code, const char *cat);
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif
#endif /* LIBXML_UNICODE_ENABLED */ #endif /* LIBXML_UNICODE_ENABLED */
#endif /* __XML_UNICODE_H__ */ #endif /* __XML_UNICODE_H__ */
 End of changes. 2 change blocks. 
174 lines changed or deleted 176 lines changed or added


 xmlwriter.h   xmlwriter.h 
skipping to change at line 72 skipping to change at line 72
/* /*
* Comments * Comments
*/ */
XMLPUBFUN int XMLCALL xmlTextWriterStartComment(xmlTextWriterPtr XMLPUBFUN int XMLCALL xmlTextWriterStartComment(xmlTextWriterPtr
writer); writer);
XMLPUBFUN int XMLCALL xmlTextWriterEndComment(xmlTextWriterPtr writer); XMLPUBFUN int XMLCALL xmlTextWriterEndComment(xmlTextWriterPtr writer);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlTextWriterWriteFormatComment(xmlTextWriterPtr writer, xmlTextWriterWriteFormatComment(xmlTextWriterPtr writer,
const char *format, ...) const char *format, ...)
LIBXML_ATTR_FORMAT(2,3); LIBXML_ATTR_FORMAT(2,3);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlTextWriterWriteVFormatComment(xmlTextWriterPtr writer, xmlTextWriterWriteVFormatComment(xmlTextWriterPtr writer,
const char *format, const char *format,
va_list argptr) va_list argptr)
LIBXML_ATTR_FORMAT(2,0); LIBXML_ATTR_FORMAT(2,0);
XMLPUBFUN int XMLCALL xmlTextWriterWriteComment(xmlTextWriterPtr XMLPUBFUN int XMLCALL xmlTextWriterWriteComment(xmlTextWriterPtr
writer, writer,
const xmlChar * const xmlChar *
content); content);
/* /*
* Elements * Elements
*/ */
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlTextWriterStartElement(xmlTextWriterPtr writer, xmlTextWriterStartElement(xmlTextWriterPtr writer,
skipping to change at line 107 skipping to change at line 107
XMLPUBFUN int XMLCALL xmlTextWriterFullEndElement(xmlTextWriterPtr XMLPUBFUN int XMLCALL xmlTextWriterFullEndElement(xmlTextWriterPtr
writer); writer);
/* /*
* Elements conveniency functions * Elements conveniency functions
*/ */
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlTextWriterWriteFormatElement(xmlTextWriterPtr writer, xmlTextWriterWriteFormatElement(xmlTextWriterPtr writer,
const xmlChar * name, const xmlChar * name,
const char *format, ...) const char *format, ...)
LIBXML_ATTR_FORMAT(3,4); LIBXML_ATTR_FORMAT(3,4);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlTextWriterWriteVFormatElement(xmlTextWriterPtr writer, xmlTextWriterWriteVFormatElement(xmlTextWriterPtr writer,
const xmlChar * name, const xmlChar * name,
const char *format, const char *format,
va_list argptr) va_list argptr)
LIBXML_ATTR_FORMAT(3,0); LIBXML_ATTR_FORMAT(3,0);
XMLPUBFUN int XMLCALL xmlTextWriterWriteElement(xmlTextWriterPtr XMLPUBFUN int XMLCALL xmlTextWriterWriteElement(xmlTextWriterPtr
writer, writer,
const xmlChar * name, const xmlChar * name,
const xmlChar * const xmlChar *
content); content);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlTextWriterWriteFormatElementNS(xmlTextWriterPtr writer, xmlTextWriterWriteFormatElementNS(xmlTextWriterPtr writer,
const xmlChar * prefix, const xmlChar * prefix,
const xmlChar * name, const xmlChar * name,
const xmlChar * namespaceURI, const xmlChar * namespaceURI,
const char *format, ...) const char *format, ...)
LIBXML_ATTR_FORMAT(5,6); LIBXML_ATTR_FORMAT(5,6);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlTextWriterWriteVFormatElementNS(xmlTextWriterPtr writer, xmlTextWriterWriteVFormatElementNS(xmlTextWriterPtr writer,
const xmlChar * prefix, const xmlChar * prefix,
const xmlChar * name, const xmlChar * name,
const xmlChar * namespaceURI, const xmlChar * namespaceURI,
const char *format, const char *format,
va_list argptr) va_list argptr)
LIBXML_ATTR_FORMAT(5,0); LIBXML_ATTR_FORMAT(5,0);
XMLPUBFUN int XMLCALL xmlTextWriterWriteElementNS(xmlTextWriterPtr XMLPUBFUN int XMLCALL xmlTextWriterWriteElementNS(xmlTextWriterPtr
writer, writer,
const xmlChar * const xmlChar *
prefix, prefix,
const xmlChar * name, const xmlChar * name,
const xmlChar * const xmlChar *
namespaceURI, namespaceURI,
const xmlChar * const xmlChar *
content); content);
/* /*
* Text * Text
*/ */
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlTextWriterWriteFormatRaw(xmlTextWriterPtr writer, xmlTextWriterWriteFormatRaw(xmlTextWriterPtr writer,
const char *format, ...) const char *format, ...)
LIBXML_ATTR_FORMAT(2,3); LIBXML_ATTR_FORMAT(2,3);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlTextWriterWriteVFormatRaw(xmlTextWriterPtr writer, xmlTextWriterWriteVFormatRaw(xmlTextWriterPtr writer,
const char *format, va_list argptr) const char *format, va_list argptr)
LIBXML_ATTR_FORMAT(2,0); LIBXML_ATTR_FORMAT(2,0);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlTextWriterWriteRawLen(xmlTextWriterPtr writer, xmlTextWriterWriteRawLen(xmlTextWriterPtr writer,
const xmlChar * content, int len); const xmlChar * content, int len);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlTextWriterWriteRaw(xmlTextWriterPtr writer, xmlTextWriterWriteRaw(xmlTextWriterPtr writer,
const xmlChar * content); const xmlChar * content);
XMLPUBFUN int XMLCALL xmlTextWriterWriteFormatString(xmlTextWriterPtr XMLPUBFUN int XMLCALL xmlTextWriterWriteFormatString(xmlTextWriterPtr
writer, writer,
const char const char
*format, ...) *format, ...)
LIBXML_ATTR_FORMAT( 2,3); LIBXML_ATTR_FORMAT(2,3);
XMLPUBFUN int XMLCALL xmlTextWriterWriteVFormatString(xmlTextWriterPtr XMLPUBFUN int XMLCALL xmlTextWriterWriteVFormatString(xmlTextWriterPtr
writer, writer,
const char const char
*format, *format,
va_list argptr) va_list argptr)
LIBXML_ATTR_FORMAT (2,0); LIBXML_ATTR_FORMAT(2,0);
XMLPUBFUN int XMLCALL xmlTextWriterWriteString(xmlTextWriterPtr writer, XMLPUBFUN int XMLCALL xmlTextWriterWriteString(xmlTextWriterPtr writer,
const xmlChar * const xmlChar *
content); content);
XMLPUBFUN int XMLCALL xmlTextWriterWriteBase64(xmlTextWriterPtr writer, XMLPUBFUN int XMLCALL xmlTextWriterWriteBase64(xmlTextWriterPtr writer,
const char *data, const char *data,
int start, int len); int start, int len);
XMLPUBFUN int XMLCALL xmlTextWriterWriteBinHex(xmlTextWriterPtr writer, XMLPUBFUN int XMLCALL xmlTextWriterWriteBinHex(xmlTextWriterPtr writer,
const char *data, const char *data,
int start, int len); int start, int len);
skipping to change at line 206 skipping to change at line 206
XMLPUBFUN int XMLCALL xmlTextWriterEndAttribute(xmlTextWriterPtr XMLPUBFUN int XMLCALL xmlTextWriterEndAttribute(xmlTextWriterPtr
writer); writer);
/* /*
* Attributes conveniency functions * Attributes conveniency functions
*/ */
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlTextWriterWriteFormatAttribute(xmlTextWriterPtr writer, xmlTextWriterWriteFormatAttribute(xmlTextWriterPtr writer,
const xmlChar * name, const xmlChar * name,
const char *format, ...) const char *format, ...)
LIBXML_ATTR_FORMAT(3,4); LIBXML_ATTR_FORMAT(3,4);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlTextWriterWriteVFormatAttribute(xmlTextWriterPtr writer, xmlTextWriterWriteVFormatAttribute(xmlTextWriterPtr writer,
const xmlChar * name, const xmlChar * name,
const char *format, const char *format,
va_list argptr) va_list argptr)
LIBXML_ATTR_FORMAT(3,0); LIBXML_ATTR_FORMAT(3,0);
XMLPUBFUN int XMLCALL xmlTextWriterWriteAttribute(xmlTextWriterPtr XMLPUBFUN int XMLCALL xmlTextWriterWriteAttribute(xmlTextWriterPtr
writer, writer,
const xmlChar * name, const xmlChar * name,
const xmlChar * const xmlChar *
content); content);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlTextWriterWriteFormatAttributeNS(xmlTextWriterPtr writer, xmlTextWriterWriteFormatAttributeNS(xmlTextWriterPtr writer,
const xmlChar * prefix, const xmlChar * prefix,
const xmlChar * name, const xmlChar * name,
const xmlChar * namespaceURI, const xmlChar * namespaceURI,
const char *format, ...) const char *format, ...)
LIBXML_ATTR_FORMAT(5,6); LIBXML_ATTR_FORMAT(5,6);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlTextWriterWriteVFormatAttributeNS(xmlTextWriterPtr writer, xmlTextWriterWriteVFormatAttributeNS(xmlTextWriterPtr writer,
const xmlChar * prefix, const xmlChar * prefix,
const xmlChar * name, const xmlChar * name,
const xmlChar * namespaceURI, const xmlChar * namespaceURI,
const char *format, const char *format,
va_list argptr) va_list argptr)
LIBXML_ATTR_FORMAT(5,0); LIBXML_ATTR_FORMAT(5,0);
XMLPUBFUN int XMLCALL xmlTextWriterWriteAttributeNS(xmlTextWriterPtr XMLPUBFUN int XMLCALL xmlTextWriterWriteAttributeNS(xmlTextWriterPtr
writer, writer,
const xmlChar * const xmlChar *
prefix, prefix,
const xmlChar * const xmlChar *
name, name,
const xmlChar * const xmlChar *
namespaceURI, namespaceURI,
const xmlChar * const xmlChar *
content); content);
skipping to change at line 259 skipping to change at line 259
const xmlChar * target); const xmlChar * target);
XMLPUBFUN int XMLCALL xmlTextWriterEndPI(xmlTextWriterPtr writer); XMLPUBFUN int XMLCALL xmlTextWriterEndPI(xmlTextWriterPtr writer);
/* /*
* PI conveniency functions * PI conveniency functions
*/ */
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlTextWriterWriteFormatPI(xmlTextWriterPtr writer, xmlTextWriterWriteFormatPI(xmlTextWriterPtr writer,
const xmlChar * target, const xmlChar * target,
const char *format, ...) const char *format, ...)
LIBXML_ATTR_FORMAT(3,4); LIBXML_ATTR_FORMAT(3,4);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlTextWriterWriteVFormatPI(xmlTextWriterPtr writer, xmlTextWriterWriteVFormatPI(xmlTextWriterPtr writer,
const xmlChar * target, const xmlChar * target,
const char *format, va_list argptr) const char *format, va_list argptr)
LIBXML_ATTR_FORMAT(3,0); LIBXML_ATTR_FORMAT(3,0);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlTextWriterWritePI(xmlTextWriterPtr writer, xmlTextWriterWritePI(xmlTextWriterPtr writer,
const xmlChar * target, const xmlChar * target,
const xmlChar * content); const xmlChar * content);
/** /**
* xmlTextWriterWriteProcessingInstruction: * xmlTextWriterWriteProcessingInstruction:
* *
* This macro maps to xmlTextWriterWritePI * This macro maps to xmlTextWriterWritePI
*/ */
skipping to change at line 289 skipping to change at line 289
*/ */
XMLPUBFUN int XMLCALL xmlTextWriterStartCDATA(xmlTextWriterPtr writer); XMLPUBFUN int XMLCALL xmlTextWriterStartCDATA(xmlTextWriterPtr writer);
XMLPUBFUN int XMLCALL xmlTextWriterEndCDATA(xmlTextWriterPtr writer); XMLPUBFUN int XMLCALL xmlTextWriterEndCDATA(xmlTextWriterPtr writer);
/* /*
* CDATA conveniency functions * CDATA conveniency functions
*/ */
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlTextWriterWriteFormatCDATA(xmlTextWriterPtr writer, xmlTextWriterWriteFormatCDATA(xmlTextWriterPtr writer,
const char *format, ...) const char *format, ...)
LIBXML_ATTR_FORMAT(2,3); LIBXML_ATTR_FORMAT(2,3);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlTextWriterWriteVFormatCDATA(xmlTextWriterPtr writer, xmlTextWriterWriteVFormatCDATA(xmlTextWriterPtr writer,
const char *format, va_list argptr) const char *format, va_list argptr)
LIBXML_ATTR_FORMAT(2,0); LIBXML_ATTR_FORMAT(2,0);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlTextWriterWriteCDATA(xmlTextWriterPtr writer, xmlTextWriterWriteCDATA(xmlTextWriterPtr writer,
const xmlChar * content); const xmlChar * content);
/* /*
* DTD * DTD
*/ */
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlTextWriterStartDTD(xmlTextWriterPtr writer, xmlTextWriterStartDTD(xmlTextWriterPtr writer,
const xmlChar * name, const xmlChar * name,
skipping to change at line 317 skipping to change at line 317
/* /*
* DTD conveniency functions * DTD conveniency functions
*/ */
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlTextWriterWriteFormatDTD(xmlTextWriterPtr writer, xmlTextWriterWriteFormatDTD(xmlTextWriterPtr writer,
const xmlChar * name, const xmlChar * name,
const xmlChar * pubid, const xmlChar * pubid,
const xmlChar * sysid, const xmlChar * sysid,
const char *format, ...) const char *format, ...)
LIBXML_ATTR_FORMAT(5,6); LIBXML_ATTR_FORMAT(5,6);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlTextWriterWriteVFormatDTD(xmlTextWriterPtr writer, xmlTextWriterWriteVFormatDTD(xmlTextWriterPtr writer,
const xmlChar * name, const xmlChar * name,
const xmlChar * pubid, const xmlChar * pubid,
const xmlChar * sysid, const xmlChar * sysid,
const char *format, va_list argptr) const char *format, va_list argptr)
LIBXML_ATTR_FORMAT(5,0); LIBXML_ATTR_FORMAT(5,0);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlTextWriterWriteDTD(xmlTextWriterPtr writer, xmlTextWriterWriteDTD(xmlTextWriterPtr writer,
const xmlChar * name, const xmlChar * name,
const xmlChar * pubid, const xmlChar * pubid,
const xmlChar * sysid, const xmlChar * sysid,
const xmlChar * subset); const xmlChar * subset);
/** /**
* xmlTextWriterWriteDocType: * xmlTextWriterWriteDocType:
* *
skipping to change at line 355 skipping to change at line 355
XMLPUBFUN int XMLCALL xmlTextWriterEndDTDElement(xmlTextWriterPtr XMLPUBFUN int XMLCALL xmlTextWriterEndDTDElement(xmlTextWriterPtr
writer); writer);
/* /*
* DTD element definition conveniency functions * DTD element definition conveniency functions
*/ */
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlTextWriterWriteFormatDTDElement(xmlTextWriterPtr writer, xmlTextWriterWriteFormatDTDElement(xmlTextWriterPtr writer,
const xmlChar * name, const xmlChar * name,
const char *format, ...) const char *format, ...)
LIBXML_ATTR_FORMAT(3,4); LIBXML_ATTR_FORMAT(3,4);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlTextWriterWriteVFormatDTDElement(xmlTextWriterPtr writer, xmlTextWriterWriteVFormatDTDElement(xmlTextWriterPtr writer,
const xmlChar * name, const xmlChar * name,
const char *format, const char *format,
va_list argptr) va_list argptr)
LIBXML_ATTR_FORMAT(3,0); LIBXML_ATTR_FORMAT(3,0);
XMLPUBFUN int XMLCALL xmlTextWriterWriteDTDElement(xmlTextWriterPtr XMLPUBFUN int XMLCALL xmlTextWriterWriteDTDElement(xmlTextWriterPtr
writer, writer,
const xmlChar * const xmlChar *
name, name,
const xmlChar * const xmlChar *
content); content);
/* /*
* DTD attribute list definition * DTD attribute list definition
*/ */
skipping to change at line 385 skipping to change at line 385
XMLPUBFUN int XMLCALL xmlTextWriterEndDTDAttlist(xmlTextWriterPtr XMLPUBFUN int XMLCALL xmlTextWriterEndDTDAttlist(xmlTextWriterPtr
writer); writer);
/* /*
* DTD attribute list definition conveniency functions * DTD attribute list definition conveniency functions
*/ */
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlTextWriterWriteFormatDTDAttlist(xmlTextWriterPtr writer, xmlTextWriterWriteFormatDTDAttlist(xmlTextWriterPtr writer,
const xmlChar * name, const xmlChar * name,
const char *format, ...) const char *format, ...)
LIBXML_ATTR_FORMAT(3,4); LIBXML_ATTR_FORMAT(3,4);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlTextWriterWriteVFormatDTDAttlist(xmlTextWriterPtr writer, xmlTextWriterWriteVFormatDTDAttlist(xmlTextWriterPtr writer,
const xmlChar * name, const xmlChar * name,
const char *format, const char *format,
va_list argptr) va_list argptr)
LIBXML_ATTR_FORMAT(3,0); LIBXML_ATTR_FORMAT(3,0);
XMLPUBFUN int XMLCALL xmlTextWriterWriteDTDAttlist(xmlTextWriterPtr XMLPUBFUN int XMLCALL xmlTextWriterWriteDTDAttlist(xmlTextWriterPtr
writer, writer,
const xmlChar * const xmlChar *
name, name,
const xmlChar * const xmlChar *
content); content);
/* /*
* DTD entity definition * DTD entity definition
*/ */
skipping to change at line 416 skipping to change at line 416
writer); writer);
/* /*
* DTD entity definition conveniency functions * DTD entity definition conveniency functions
*/ */
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlTextWriterWriteFormatDTDInternalEntity(xmlTextWriterPtr writer, xmlTextWriterWriteFormatDTDInternalEntity(xmlTextWriterPtr writer,
int pe, int pe,
const xmlChar * name, const xmlChar * name,
const char *format, ...) const char *format, ...)
LIBXML_ATTR_FORMAT(4,5); LIBXML_ATTR_FORMAT(4,5);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlTextWriterWriteVFormatDTDInternalEntity(xmlTextWriterPtr writer, xmlTextWriterWriteVFormatDTDInternalEntity(xmlTextWriterPtr writer,
int pe, int pe,
const xmlChar * name, const xmlChar * name,
const char *format, const char *format,
va_list argptr) va_list argptr)
LIBXML_ATTR_FORMAT(4,0); LIBXML_ATTR_FORMAT(4,0);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlTextWriterWriteDTDInternalEntity(xmlTextWriterPtr writer, xmlTextWriterWriteDTDInternalEntity(xmlTextWriterPtr writer,
int pe, int pe,
const xmlChar * name, const xmlChar * name,
const xmlChar * content); const xmlChar * content);
XMLPUBFUN int XMLCALL XMLPUBFUN int XMLCALL
xmlTextWriterWriteDTDExternalEntity(xmlTextWriterPtr writer, xmlTextWriterWriteDTDExternalEntity(xmlTextWriterPtr writer,
int pe, int pe,
const xmlChar * name, const xmlChar * name,
const xmlChar * pubid, const xmlChar * pubid,
 End of changes. 26 change blocks. 
26 lines changed or deleted 26 lines changed or added

This html diff was produced by rfcdiff 1.41. The latest version is available from http://tools.ietf.org/tools/rfcdiff/