See the file LICENSE for the license governing this code.
The Kit namespace provides generic / fundamental functions. There are functions to get the current time, scale a value for a given display ratio and determine if a display is retina.
Kit sections all devices / computers / consoles into three categories based on maximum and minimum screen dimensions. A display of 1024 x 768 has a max dimension of 1024 and min dimension of 768, for example. Thinking of displays in terms of maximum and minimum dimensions simplifies things by removing orientation from the equation.
A further distinction is made between a large screens and small screens. Small screens have a minimum screen dimension less than 768 pixels.
Kit.h / Kit.cpp are meant to be able to be included in any type of game project.
#pragma once
#include "Libraries.h"Directory names for your game’s SD, HD and HDR Asset subdirectories. If your game does not have separate tiers of art assets, these can safely be ignored.
const char* const kSDPath = "SD";
const char* const kHDPath = "HD";
const char* const kHDRPath = "HDR";namespace Kit
{Initialize given the screen size in pixels.
void init(const Size& screenPixelSize);Return design specifications for the initialized screen.
void getSpecs(Size& designResolution, float& scaleFactor, string& assetSubdir);Returns true if the current screen is HD (has a max screen dimension >= 960).
bool isHD();Returns true if the current screen is small (has a min screen dimension < 768).
bool isSmallScreen();Returns true if retina display is available and enabled.
bool isRetina();Returns true if the device has a 16 x 9 display.
bool is16x9();The Kit::scale method scales an SD-centric value up to the appropriate scale for the current screen regardless of retina.
Kit::scale(1) will return 1 for all SD non-retina screens and 2 otherwise.
Meant to be used with point as opposed to pixel math.
float scale(float f);Return a position offset from the middle of the screen and scaled for the current screen.
Vec2 centralize(const Vec2& p);Return the inverse of cocos2d::Director‘s content scale.
float getInverseContentScale();Get / set whether the device is fullscreen.
bool isFullscreen();
void setIsFullscreen(bool);Returns the current absolute time in seconds (seconds since 1970).
double time();Returns the amount of time in seconds that the game has been running.
double upTime();Calls the appropriate method to run the given scene (either Director::runWithScene or Director::replaceScene).
void runScene(Scene* scene);Returns true if the resource filename exists in the game’s bundle.
bool resourceExists(const string& filename);Returns true if the sprite frame exists and is cached in memory.
bool spriteFrameExists(const string& filename);Returns the maximum texture size in pixels.
int maxTextureSize();Returns the current memory usage in bytes.
long getMemoryUsage();Format a string.
It printfs to a static char buffer and returns a pointer.
Do not nest calls to this method (because it uses a static buffer).
const char* const stringWithFormat(const char* format, ...);
const char* const stringWithFormat(const char* format, va_list args);Parse a string into an integer vector given the delimiter.
void parseVector(const string& str, int& val1, int& val2, char delim);Parse a map value into an integer vector given the delimiter.
void parseVector(ValueMap& properties, const string& key, int& val1, int& val2, char delim);Parse value map string value into range of integers. Example: “32-48” will become 32 and 48.
Single value equivalent to specifying min and max. Example “32” becomes 32 and 32.
void parseRange(ValueMap& properties, const string& key, int& min, int& max);
void parseRangeArray(ValueMap& properties, const string& key, vector<int>& mins, vector<int>& maxs);Parse a string into a color.
Color3B parseColor(const string& color, const Color3B& defaultColor);Return a value map safely from inside another value map.
const ValueMap& safeValueMapKey(ValueMap& map, const string& key);Return a value vector safely from inside a value map.
const ValueVector& safeValueVectorKey(ValueMap& map, const string& key);Return the sprite frame from the animation for the given frame number.
SpriteFrame* getSpriteFrame(Animation* anim, int frameNumber);Return true if the point is inside the polygon.
bool isInsidePolygon(const Vec2& p, const vector<Vec2>& poly);Base64 encode / decode.
void decodeBase64(const char* input, string& output);
void encodeBase64(const void* input, size_t size, string& output);
};
#ifdef NDEBUG
// comment this to enable logging in release mode
#define NOLOG
#endif
#ifdef NOLOG
#define Log(...) do {} while (0)
#else
#define Log(...) cocos2d::log(__VA_ARGS__)
#endif
#ifdef NDEBUG // if release mode
#define Assert(...) do {} while (0)
#define Assert1(...) do {} while (0)
#define Assert2(...) do {} while (0)
#define Assert3(...) do {} while (0)
#define Assert4(...) do {} while (0)
#define Assert5(...) do {} while (0)
#else
void Assert(bool condition, const char* const message);
#define Assert1(condition, format, param1) if(!(condition)) Assert(condition, Kit::stringWithFormat(format, param1))
#define Assert2(condition, format, param1, param2) if(!(condition)) Assert(condition, Kit::stringWithFormat(format, param1, param2) )
#define Assert3(condition, format, param1, param2, param3) if(!(condition)) Assert(condition, Kit::stringWithFormat(format, param1, param2, param3) )
#define Assert4(condition, format, param1, param2, param3, param4) if(!(condition)) Assert(condition, Kit::stringWithFormat(format, param1, param2, param3, param4) )
#define Assert5(condition, format, param1, param2, param3, param4, param5) if(!(condition)) Assert(condition, Kit::stringWithFormat(format, param1, param2, param3, param4, param5) )
#endifFunctions and macros too fundamental to be prefixed with Kit::.
A simple void / void function callback type.
typedef function<void ()> callbackType;Return true if an object inherits from or belongs to a class.
#define isClass(object, class) (dynamic_cast<class*>(object) != nullptr)Get a pointer to the subclass of an object (essentially just a shortened version of dynamic_cast<SomeClass*>(someObject)).
#define getSubclass(object, class) dynamic_cast<class*>(object);Implement a public getter method and protected member variable using pass by value.
#define GETTER(varType, varName, functionName) \
protected: varType varName; \
public: virtual varType get##functionName(void) const {return varName;}Implement a public getter method and protected member variable using pass by reference.
#define GETTER_BYREF(varType, varName, functionName) \
protected: varType varName; \
public: virtual const varType& get##functionName(void) const {return varName;}Implement a public getter method, public setter method and protected member variable using pass by value.
#define GETTER_SETTER(varType, varName, functionName) \
protected: varType varName; \
public: virtual varType get##functionName(void) const {return varName;} \
public: virtual void set##functionName(varType var) {varName = var;}Implement a public getter method, public setter method and protected member variable using pass by reference.
#define GETTER_SETTER_BYREF(varType, varName, functionName) \
protected: varType varName; \
public: virtual const varType& get##functionName(void) const {return varName;} \
public: virtual void set##functionName(const varType& var) {varName = var;}Return a value clamped inclusively between a minimum and maximum.
template<class T> T clamp(const T& val, const T& min, const T& max)
{
return (val > max ? max : (val < min ? min : val));
}Return a random float between 0 and 1 using rand.
inline float randf01()
{
return (float)(rand() % RAND_MAX) / (float)RAND_MAX;
}Return a random float between -1 and 1 using rand.
inline float randf()
{
return (randf01() - 0.5f) * 2.0f;
}Return the sign of the value. Values > 0 return 1. Values <= 0 return -1.
template<class T> inline T sign(const T& val)
{
return (val > 0 ? 1 : -1);
}Create a new sprite given the filename which can be either the name of a sprite frame or the name of an image file.
Sprite is meant to be released by calling releaseSprite.
template<class SpriteClass> inline SpriteClass* newSprite(const string& filename)
{
auto frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(filename);
auto sprite = new SpriteClass;
if (frame)
sprite->initWithSpriteFrame(frame);
else
sprite->initWithFile(filename);
return sprite;
}Release the given sprite.
template<class SpriteClass> inline void releaseSprite(SpriteClass* sprite)
{
if (sprite)
sprite->release();
}Parse a string value into a long integer.
inline int parseInt(const string& str)
{
return (int)strtol(str.c_str(), nullptr, 10);
}Parse a string value into a floating point value.
inline float parseFloat(const string& str)
{
return strtof(str.c_str(), nullptr);
}These functions check if a container has a key.
template<class T>
inline bool hasValue(const vector<T>& vec, const T& value)
{
return find(vec.begin(), vec.end(), value) != vec.end();
}
template<class T, class U>
inline bool hasKey(const string& key, map<T, U>& map)
{
return map.find(key) != map.end();
}
template<class T, class U>
inline bool hasKey(const string& key, unordered_map<T, U>& map)
{
return map.find(key) != map.end();
}
inline bool hasStringVal(const string& key, ValueMap& map)
{
return map.find(key) != map.end() && map[key].getType() == Value::Type::STRING;
}Return the lowercase version of a string.
inline string lowercase(const string& str)
{
string lower = str;
transform(lower.begin(), lower.end(), lower.begin(), ::tolower);
return lower;
}Split the given string by the given delimiter and store result in the given container.
inline void split(const string& s, char delim, vector<string>& elems)
{
stringstream ss(s);
string item;
elems.clear();
while(std::getline(ss, item, delim))
elems.push_back(item);
}
inline void split(const string& s, char delim, map<string, bool>& elems)
{
stringstream ss(s);
string item;
elems.clear();
while(std::getline(ss, item, delim))
elems[item] = true;
}Apply a tone to a color. Tones > 1 make the color brighter. Tones < 1 make the color darker.
inline Color3B applyTone(const Color3B& color, float tone)
{
return Color3B(
clamp((int)(color.r * tone), 0, 255),
clamp((int)(color.g * tone), 0, 255),
clamp((int)(color.b * tone), 0, 255)
);
}An enumeration of the four basic directions. Provides methods to convert directions to vectors and vice versa.
enum
{
kUp,
kRight,
kDown,
kLeft,
kNumDirs
};Return the opposite direction.
inline int oppositeDirection(int dir)
{
return (dir + (kNumDirs >> 1)) % kNumDirs;
}Convert a direction to a vector.
inline Vec2 vectorFromDirection(int dir)
{
switch (dir)
{
case kUp: return Vec2(0.0f, 1.0f);
case kRight: return Vec2(1.0f, 0.0f);
case kDown: return Vec2(0.0f, -1.0f);
case kLeft: return Vec2(-1.0f, 0.0f);
}
return Vec2::ZERO;
}Convert a vector to a direction.
inline int directionFromVector(const Vec2& v)
{
if (v.x == 0.0f && v.y == -1.0f)
return kDown;
else if (v.x == 0.0f && v.y == 1.0f)
return kUp;
else if (v.x == -1.0f && v.y == 0.0f)
return kLeft;
else if (v.x == 1.0f && v.y == 0.0f)
return kRight;
return -1;
}Convert a string to a direction. Example: “up” == kUp.
inline int directionFromString(const string& str)
{
if (str == "up") return kUp;
else if (str == "right") return kRight;
else if (str == "down") return kDown;
else if (str == "left") return kLeft;
return -1;
}Represents a color in hue, saturation, value format.
struct ColorHSV
{
unsigned char h;
unsigned char s;
unsigned char v;
ColorHSV();
ColorHSV(const Color3B& rgb);
~ColorHSV();
ColorHSV& operator=(const ColorHSV& rhs);
ColorHSV& operator=(const Color3B& rhs);Convert the HSV color to RGB.
Color3B toRGB() const;
static Color3B toRGB(int h, int s, int v);
};Core
Object types