mirror of
https://github.com/cocos/cocos4.git
synced 2026-12-04 18:42:40 +08:00
+5
-2
@@ -6,9 +6,12 @@ script:
|
||||
sudo: required
|
||||
before_install:
|
||||
- tools/travis-scripts/before-install.sh
|
||||
|
||||
# blocklist
|
||||
branches:
|
||||
only:
|
||||
- develop
|
||||
except:
|
||||
- master
|
||||
|
||||
env:
|
||||
global:
|
||||
- secure: bUrk522Qw5Mc3SfDXHZtJ/aF9QbLXYDnUVSOJXt1wUB1d8xAQphTcZ1ARNYu7I5m3ZXqRfzTS4POOT58qeS3sYPpJ8urWW18hgX3I/dmsL1WJXmwnOV+0J3xLt6AT3ttqj7/emaf0xxuBvZ0szyRz0rU4wprtWftWMFiUrsF8G1an2Qa/g/f5LhilnDiKAqFdHMkn0ogaggL0PbgliHeHo7SEOfSF2gQaSIBta7jzE/BEZZ3R4AuReB3oNDwxr+1E4BpPaGO1lMLzdr8MAjWBGVLBRlpVDihgFTTmdka8UYasjEWDs6GbSjJRsTZQkluOo+1UylSiLn5o1tnWMqINo5DDaayBSKWRV/x+Sx+KMG221BwHLGFHrhEm8Jwc3g5IBiFrc9Xn/PAoCL3Zi/m0m8Y/TVIlA2nWuU0jeMZYXOb0ALCplAQMrG/Yt7euzgSjZ9iPvO7HO8BkaRkUxafcp6svWyMedNeDczG6liLSquJak+XIbOpWCOW+KVxc2S2Unz37MSOQR/aB9dJ8fKI/4e3LCdYrSKW9MSKAz9BSYA2IK2F8Fgr6zY3IPTANQCi6o8i/N54wsmpY17uvzqNDGuag5m/FkNpFWVQUy/TdONanXV6m1jvREaxtDHucSnP3olmvx6pi1awRspDfRmcILK08yvul+yLol0nQwenlx0=
|
||||
|
||||
+13
-8
@@ -42,26 +42,31 @@ Git user attention
|
||||
|
||||
1. Clone the repo from GitHub.
|
||||
|
||||
$ git clone https://github.com/cocos-creator/cocos2d-x-lite.git
|
||||
$ git clone https://github.com/cocos-creator/cocos2d-x-lite.git
|
||||
|
||||
2. After cloning the repo, please execute `download-deps.py` to download and install dependencies.
|
||||
|
||||
$ cd cocos2d-x-lite
|
||||
$ python download-deps.py
|
||||
$ cd cocos2d-x-lite
|
||||
$ python download-deps.py
|
||||
|
||||
3. After running `download-deps.py`.
|
||||
|
||||
$ git submodule update --init
|
||||
$ git submodule update --init
|
||||
|
||||
4. Build simulator
|
||||
|
||||
$ npm install
|
||||
$ gulp gen-simulator
|
||||
$ gulp update-simulator-config
|
||||
$ npm install
|
||||
$ gulp sign-simulator
|
||||
$ gulp gen-simulator
|
||||
$ gulp update-simulator-config
|
||||
|
||||
`gulp sign-simulator` only need to run on Mac. It can help you to sign the simulator project in "tools/simulator/frameworks/runtime-src/proj.ios_mac/simulator.xcodeproj", so you can debug the simulator on Mac. This command will open the XCode project in the background. Then you should set the signing manually, and close XCode to make it finished. If you don't want to sign it, just close XCode directly. You need to rerun this command once the project is changed.
|
||||

|
||||
|
||||
|
||||
5. Build prebuilt library
|
||||
|
||||
$ gulp gen-libs
|
||||
$ gulp gen-libs
|
||||
|
||||
Contributing to the Project
|
||||
--------------------------------
|
||||
|
||||
@@ -1672,13 +1672,18 @@ void Label::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags)
|
||||
{
|
||||
return;
|
||||
}
|
||||
// Don't do calculate the culling if the transform was not updated
|
||||
bool transformUpdated = flags & FLAGS_TRANSFORM_DIRTY;
|
||||
#if CC_USE_CULLING
|
||||
_insideBounds = transformUpdated ? renderer->checkVisibility(transform, _contentSize) : _insideBounds;
|
||||
|
||||
if (_director->isCullingEnabled()) {
|
||||
// Don't calculate the culling if the transform was not updated
|
||||
if (flags & FLAGS_TRANSFORM_DIRTY || flags & FLAGS_CULLING_DIRTY) {
|
||||
_insideBounds = renderer->checkVisibility(transform, _contentSize);
|
||||
}
|
||||
}
|
||||
else {
|
||||
_insideBounds = true;
|
||||
}
|
||||
|
||||
if (_insideBounds)
|
||||
#endif
|
||||
{
|
||||
if (!_shadowEnabled && (_currentLabelType == LabelType::BMFONT || _currentLabelType == LabelType::CHARMAP))
|
||||
{
|
||||
@@ -1696,7 +1701,7 @@ void Label::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags)
|
||||
else
|
||||
{
|
||||
_customCommand.init(_globalZOrder, transform, flags);
|
||||
_customCommand.func = CC_CALLBACK_0(Label::onDraw, this, transform, transformUpdated);
|
||||
_customCommand.func = CC_CALLBACK_0(Label::onDraw, this, transform, flags & FLAGS_TRANSFORM_DIRTY);
|
||||
|
||||
renderer->addCommand(&_customCommand);
|
||||
}
|
||||
@@ -1735,8 +1740,7 @@ void Label::visit(Renderer *renderer, const Mat4 &parentTransform, uint32_t pare
|
||||
// IMPORTANT:
|
||||
// To ease the migration to v3.0, we still support the Mat4 stack,
|
||||
// but it is deprecated and your code should not rely on it
|
||||
_director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
|
||||
_director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _modelViewTransform);
|
||||
_director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _modelViewTransform);
|
||||
|
||||
if (!_children.empty())
|
||||
{
|
||||
|
||||
@@ -406,7 +406,11 @@ void MenuItemSprite::setNormalImage(Node* image)
|
||||
}
|
||||
|
||||
_normalImage = image;
|
||||
this->setContentSize(_normalImage->getContentSize());
|
||||
if (_normalImage)
|
||||
{
|
||||
this->setContentSize(_normalImage->getContentSize());
|
||||
}
|
||||
|
||||
this->updateImagesVisibility();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,6 +82,7 @@ Node::Node()
|
||||
, _additionalTransform(nullptr)
|
||||
, _additionalTransformDirty(false)
|
||||
, _transformUpdated(true)
|
||||
, _cullingDirty(true)
|
||||
// children (lazy allocs)
|
||||
// lazy alloc
|
||||
, _localZOrderAndArrival(0)
|
||||
@@ -1216,6 +1217,7 @@ uint32_t Node::processParentFlags(const Mat4& parentTransform, uint32_t parentFl
|
||||
uint32_t flags = parentFlags;
|
||||
flags |= (_transformUpdated ? FLAGS_TRANSFORM_DIRTY : 0);
|
||||
flags |= (_contentSizeDirty ? FLAGS_CONTENT_SIZE_DIRTY : 0);
|
||||
flags |= (_cullingDirty ? FLAGS_CULLING_DIRTY : 0);
|
||||
|
||||
|
||||
if(flags & FLAGS_DIRTY_MASK)
|
||||
@@ -1223,6 +1225,7 @@ uint32_t Node::processParentFlags(const Mat4& parentTransform, uint32_t parentFl
|
||||
|
||||
_transformUpdated = false;
|
||||
_contentSizeDirty = false;
|
||||
_cullingDirty = false;
|
||||
|
||||
return flags;
|
||||
}
|
||||
@@ -1249,8 +1252,7 @@ void Node::visit(Renderer* renderer, const Mat4 &parentTransform, uint32_t paren
|
||||
// IMPORTANT:
|
||||
// To ease the migration to v3.0, we still support the Mat4 stack,
|
||||
// but it is deprecated and your code should not rely on it
|
||||
_director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
|
||||
_director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _modelViewTransform);
|
||||
_director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _modelViewTransform);
|
||||
|
||||
auto camera = creator::CameraNode::getInstance();
|
||||
if (camera) {
|
||||
@@ -2147,9 +2149,9 @@ void Node::setCameraMask(unsigned short mask, bool applyChildren)
|
||||
}
|
||||
}
|
||||
|
||||
void Node::markTransformUpdated()
|
||||
void Node::markCullingDirty()
|
||||
{
|
||||
_transformUpdated = true;
|
||||
_cullingDirty = true;
|
||||
}
|
||||
|
||||
NS_CC_END
|
||||
|
||||
@@ -109,6 +109,7 @@ public:
|
||||
FLAGS_TRANSFORM_DIRTY = (1 << 0),
|
||||
FLAGS_CONTENT_SIZE_DIRTY = (1 << 1),
|
||||
FLAGS_RENDER_AS_3D = (1 << 3),
|
||||
FLAGS_CULLING_DIRTY = (1 << 4),
|
||||
|
||||
FLAGS_DIRTY_MASK = (FLAGS_TRANSFORM_DIRTY | FLAGS_CONTENT_SIZE_DIRTY),
|
||||
};
|
||||
@@ -1775,9 +1776,9 @@ public:
|
||||
virtual void setCameraMask(unsigned short mask, bool applyChildren = true);
|
||||
|
||||
/**
|
||||
* Mark transformUpdated as true, this will make flags contains FLAGS_TRANSFORM_DIRTY flag.
|
||||
* Mark cullingDirty as true, this will make flags contains FLAGS_CULLING_DIRTY flag.
|
||||
*/
|
||||
void markTransformUpdated();
|
||||
void markCullingDirty();
|
||||
|
||||
CC_CONSTRUCTOR_ACCESS:
|
||||
// Nodes should be created using create();
|
||||
@@ -1929,7 +1930,8 @@ protected:
|
||||
mutable bool _additionalTransformDirty; ///< transform dirty ?
|
||||
|
||||
bool _transformUpdated; ///< Whether or not the Transform object was updated since the last frame
|
||||
char padding[7];
|
||||
bool _cullingDirty; ///< Whether culling is dirty
|
||||
|
||||
private:
|
||||
CC_DISALLOW_COPY_AND_ASSIGN(Node);
|
||||
};
|
||||
|
||||
@@ -744,6 +744,12 @@ void RenderTexture::draw(Renderer *renderer, const Mat4 &transform, uint32_t fla
|
||||
}
|
||||
}
|
||||
|
||||
void RenderTexture::cleanup()
|
||||
{
|
||||
Node::cleanup();
|
||||
_saveFileCallback = nullptr;
|
||||
}
|
||||
|
||||
void RenderTexture::begin()
|
||||
{
|
||||
Director* director = Director::getInstance();
|
||||
|
||||
@@ -262,6 +262,7 @@ public:
|
||||
// Overrides
|
||||
virtual void visit(Renderer *renderer, const Mat4 &parentTransform, uint32_t parentFlags) override;
|
||||
virtual void draw(Renderer *renderer, const Mat4 &transform, uint32_t flags) override;
|
||||
virtual void cleanup() override;
|
||||
|
||||
/** Flag: Use stack matrix computed from scene hierarchy or generate new modelView and projection matrix.
|
||||
*
|
||||
|
||||
@@ -645,11 +645,16 @@ void Sprite::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags)
|
||||
return;
|
||||
}
|
||||
|
||||
#if CC_USE_CULLING
|
||||
// Don't calculate the culling if the transform was not updated
|
||||
_insideBounds = (flags & FLAGS_TRANSFORM_DIRTY) ? renderer->checkVisibility(transform, _contentSize) : _insideBounds;
|
||||
if (_director->isCullingEnabled()) {
|
||||
if (flags & FLAGS_TRANSFORM_DIRTY || flags & FLAGS_CULLING_DIRTY) {
|
||||
_insideBounds = renderer->checkVisibility(transform, _contentSize);
|
||||
}
|
||||
}
|
||||
else {
|
||||
_insideBounds = true;
|
||||
}
|
||||
|
||||
if(_insideBounds)
|
||||
#endif
|
||||
{
|
||||
_trianglesCommand.init(_globalZOrder,
|
||||
_texture,
|
||||
|
||||
@@ -2,7 +2,9 @@ LOCAL_PATH := $(call my-dir)
|
||||
|
||||
include $(CLEAR_VARS)
|
||||
|
||||
LOCAL_MODULE := cocos2dx_internal_static
|
||||
# cis is short name for cocos2dx_internal_static
|
||||
# Shorter name could avoid compilation errors on Windows system which has a limitation of 260 bytes for build path.
|
||||
LOCAL_MODULE := cis
|
||||
LOCAL_MODULE_FILENAME := libcocos2dxinternal
|
||||
|
||||
LOCAL_ARM_MODE := arm
|
||||
@@ -283,7 +285,7 @@ LOCAL_STATIC_LIBRARIES += cocos_ui_static
|
||||
LOCAL_STATIC_LIBRARIES += spine_static
|
||||
LOCAL_STATIC_LIBRARIES += dragonbones_static
|
||||
LOCAL_STATIC_LIBRARIES += creator_static
|
||||
LOCAL_STATIC_LIBRARIES += cocos2dx_internal_static
|
||||
LOCAL_STATIC_LIBRARIES += cis
|
||||
|
||||
include $(BUILD_STATIC_LIBRARY)
|
||||
|
||||
|
||||
@@ -91,6 +91,44 @@ const char *Director::EVENT_BEFORE_UPDATE = "director_before_update";
|
||||
const char *Director::EVENT_AFTER_UPDATE = "director_after_update";
|
||||
const char *Director::EVENT_RESET = "director_reset";
|
||||
|
||||
|
||||
Director::MatrixStack::MatrixStack()
|
||||
{
|
||||
}
|
||||
|
||||
void Director::MatrixStack::init() {
|
||||
_stack.clear();
|
||||
_stack.reserve(16);
|
||||
|
||||
_stack.push_back(Mat4::IDENTITY);
|
||||
_stackTop = 0;
|
||||
}
|
||||
|
||||
void Director::MatrixStack::push(const Mat4& m) {
|
||||
if (_stackTop >= _stack.size() - 1) {
|
||||
_stack.push_back(m);
|
||||
}
|
||||
else {
|
||||
_stack[_stackTop + 1] = m;
|
||||
}
|
||||
++_stackTop;
|
||||
}
|
||||
|
||||
void Director::MatrixStack::pop() {
|
||||
if (_stackTop > 0) {
|
||||
--_stackTop;
|
||||
}
|
||||
}
|
||||
|
||||
Mat4& Director::MatrixStack::top() {
|
||||
return _stack[_stackTop];
|
||||
}
|
||||
|
||||
const Mat4& Director::MatrixStack::top() const {
|
||||
return _stack[_stackTop];
|
||||
}
|
||||
|
||||
|
||||
Director* Director::getInstance()
|
||||
{
|
||||
if (!s_SharedDirector)
|
||||
@@ -105,7 +143,8 @@ Director* Director::getInstance()
|
||||
|
||||
Director::Director()
|
||||
: _isStatusLabelUpdated(true),
|
||||
_invalid(true)
|
||||
_invalid(true),
|
||||
_isCullingEnabled(true)
|
||||
{
|
||||
}
|
||||
|
||||
@@ -430,24 +469,9 @@ void Director::setNextDeltaTimeZero(bool nextDeltaTimeZero)
|
||||
//
|
||||
void Director::initMatrixStack()
|
||||
{
|
||||
while (!_modelViewMatrixStack.empty())
|
||||
{
|
||||
_modelViewMatrixStack.pop();
|
||||
}
|
||||
|
||||
while (!_projectionMatrixStack.empty())
|
||||
{
|
||||
_projectionMatrixStack.pop();
|
||||
}
|
||||
|
||||
while (!_textureMatrixStack.empty())
|
||||
{
|
||||
_textureMatrixStack.pop();
|
||||
}
|
||||
|
||||
_modelViewMatrixStack.push(Mat4::IDENTITY);
|
||||
_projectionMatrixStack.push(Mat4::IDENTITY);
|
||||
_textureMatrixStack.push(Mat4::IDENTITY);
|
||||
_modelViewMatrixStack.init();
|
||||
_projectionMatrixStack.init();
|
||||
_textureMatrixStack.init();
|
||||
}
|
||||
|
||||
void Director::resetMatrixStack()
|
||||
@@ -539,15 +563,35 @@ void Director::pushMatrix(MATRIX_STACK_TYPE type)
|
||||
{
|
||||
if(type == MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW)
|
||||
{
|
||||
_modelViewMatrixStack.push(_modelViewMatrixStack.top());
|
||||
pushMatrix(type, _modelViewMatrixStack.top());
|
||||
}
|
||||
else if(type == MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION)
|
||||
{
|
||||
_projectionMatrixStack.push(_projectionMatrixStack.top());
|
||||
pushMatrix(type, _projectionMatrixStack.top());
|
||||
}
|
||||
else if(type == MATRIX_STACK_TYPE::MATRIX_STACK_TEXTURE)
|
||||
{
|
||||
_textureMatrixStack.push(_textureMatrixStack.top());
|
||||
pushMatrix(type, _textureMatrixStack.top());
|
||||
}
|
||||
else
|
||||
{
|
||||
CCASSERT(false, "unknown matrix stack type");
|
||||
}
|
||||
}
|
||||
|
||||
void Director::pushMatrix(MATRIX_STACK_TYPE type, const Mat4& mat)
|
||||
{
|
||||
if(type == MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW)
|
||||
{
|
||||
_modelViewMatrixStack.push(mat);
|
||||
}
|
||||
else if(type == MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION)
|
||||
{
|
||||
_projectionMatrixStack.push(mat);
|
||||
}
|
||||
else if(type == MATRIX_STACK_TYPE::MATRIX_STACK_TEXTURE)
|
||||
{
|
||||
_textureMatrixStack.push(mat);
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
@@ -81,6 +81,7 @@ enum class MATRIX_STACK_TYPE
|
||||
MATRIX_STACK_TEXTURE
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
@brief Class that creates and handles the main Window and manages how
|
||||
and when to execute the Scenes.
|
||||
@@ -452,6 +453,11 @@ public:
|
||||
* @js NA
|
||||
*/
|
||||
void pushMatrix(MATRIX_STACK_TYPE type);
|
||||
/**
|
||||
* Put a specified type matrix to the top of specified type of matrix stack.
|
||||
* @js NA
|
||||
*/
|
||||
void pushMatrix(MATRIX_STACK_TYPE type, const Mat4& mat);
|
||||
/** Pops the top matrix of the specified type of matrix stack.
|
||||
* @js NA
|
||||
*/
|
||||
@@ -499,6 +505,9 @@ public:
|
||||
bool isPurgeDirectorInNextLoop() const { return _purgeDirectorInNextLoop; }
|
||||
|
||||
bool isValid() const { return !_invalid; }
|
||||
|
||||
void setCullingEnabled (bool enable) { _isCullingEnabled = enable; }
|
||||
bool isCullingEnabled () const { return _isCullingEnabled; }
|
||||
|
||||
protected:
|
||||
void reset();
|
||||
@@ -524,10 +533,7 @@ protected:
|
||||
void destroyTextureCache();
|
||||
|
||||
void initMatrixStack();
|
||||
|
||||
std::stack<Mat4> _modelViewMatrixStack;
|
||||
std::stack<Mat4> _projectionMatrixStack;
|
||||
std::stack<Mat4> _textureMatrixStack;
|
||||
|
||||
|
||||
/** Scheduler associated with this director
|
||||
@since v2.0
|
||||
@@ -623,6 +629,31 @@ protected:
|
||||
|
||||
// GLView will recreate stats labels to fit visible rect
|
||||
friend class GLView;
|
||||
|
||||
bool _isCullingEnabled;
|
||||
|
||||
private:
|
||||
/**
|
||||
Use std::vector to implement a quick matrix stack.
|
||||
*/
|
||||
class MatrixStack
|
||||
{
|
||||
public:
|
||||
MatrixStack();
|
||||
void init();
|
||||
void pop();
|
||||
void push(const Mat4& m);
|
||||
Mat4& top();
|
||||
const Mat4& top() const;
|
||||
protected:
|
||||
std::vector<Mat4> _stack;
|
||||
int _stackTop;
|
||||
};
|
||||
|
||||
|
||||
MatrixStack _modelViewMatrixStack;
|
||||
MatrixStack _projectionMatrixStack;
|
||||
MatrixStack _textureMatrixStack;
|
||||
};
|
||||
|
||||
// end of base group
|
||||
|
||||
@@ -690,7 +690,10 @@ void EventDispatcher::removeEventListener(EventListener* listener)
|
||||
|
||||
if (isFound)
|
||||
{
|
||||
releaseListener(listener);
|
||||
if (_inDispatch > 0)
|
||||
CC_SAFE_RELEASE(listener);
|
||||
else
|
||||
releaseListener(listener);
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
@@ -405,6 +405,8 @@ Data UserDefault::getDataForKey(const char* pKey, const Data& defaultValue)
|
||||
// delete xmle node
|
||||
deleteNode(doc, node);
|
||||
}
|
||||
} else {
|
||||
delete doc;
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
@@ -278,11 +278,6 @@ THE SOFTWARE.
|
||||
#define CC_LUA_ENGINE_DEBUG 0
|
||||
#endif
|
||||
|
||||
/** Use culling or not. */
|
||||
#ifndef CC_USE_CULLING
|
||||
#define CC_USE_CULLING 1
|
||||
#endif
|
||||
|
||||
/** Support PNG or not. If your application don't use png format picture, you can undefine this macro to save package size.
|
||||
*/
|
||||
#ifndef CC_USE_PNG
|
||||
|
||||
@@ -26,6 +26,4 @@ LOCAL_C_INCLUDES := $(LOCAL_PATH)/.. \
|
||||
$(LOCAL_PATH)/../.. \
|
||||
$(LOCAL_PATH)/../../../external/sources
|
||||
|
||||
# LOCAL_STATIC_LIBRARIES := cocos2dx_internal_static
|
||||
|
||||
include $(BUILD_STATIC_LIBRARY)
|
||||
|
||||
@@ -19,7 +19,6 @@ namespace creator {
|
||||
CameraNode::CameraNode()
|
||||
{
|
||||
_mat.setIdentity();
|
||||
_cameraInstance = this;
|
||||
visitingIndex = 0;
|
||||
}
|
||||
|
||||
@@ -34,7 +33,16 @@ namespace creator {
|
||||
}
|
||||
_commands.clear();
|
||||
}
|
||||
_cameraInstance = nullptr;
|
||||
}
|
||||
|
||||
void CameraNode::setEnable(bool enable)
|
||||
{
|
||||
if (enable) {
|
||||
_cameraInstance = this;
|
||||
}
|
||||
else {
|
||||
_cameraInstance = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
CameraNode* CameraNode::getInstance() {
|
||||
|
||||
@@ -47,6 +47,8 @@ namespace creator {
|
||||
|
||||
static CameraNode* getInstance();
|
||||
|
||||
void setEnable(bool enable);
|
||||
|
||||
void setTransform(float a, float b, float c, float d, float tx, float ty);
|
||||
|
||||
bool containsNode(cocos2d::Node* node);
|
||||
|
||||
@@ -1102,11 +1102,18 @@ void Scale9SpriteV2::draw(cocos2d::Renderer *renderer, const cocos2d::Mat4 &tran
|
||||
if (!this->_spriteFrame || !this->_spriteFrame->getTexture()) {
|
||||
return;
|
||||
}
|
||||
#if CC_USE_CULLING
|
||||
// Don't calculate the culling if the transform was not updated
|
||||
_insideBounds = (flags & FLAGS_TRANSFORM_DIRTY) ? renderer->checkVisibility(transform, _contentSize) : _insideBounds;
|
||||
|
||||
if (_director->isCullingEnabled()) {
|
||||
// Don't calculate the culling if the transform was not updated
|
||||
if (flags & FLAGS_TRANSFORM_DIRTY || flags & FLAGS_CULLING_DIRTY) {
|
||||
_insideBounds = renderer->checkVisibility(transform, _contentSize);
|
||||
}
|
||||
}
|
||||
else {
|
||||
_insideBounds = true;
|
||||
}
|
||||
|
||||
if (_insideBounds)
|
||||
#endif
|
||||
{
|
||||
if (this->_quadsDirty) {
|
||||
//rebuild quads
|
||||
|
||||
@@ -168,16 +168,18 @@ bool DBCCSprite::_checkVisibility(const cocos2d::Mat4& transform, const cocos2d:
|
||||
|
||||
void DBCCSprite::draw(cocos2d::Renderer* renderer, const cocos2d::Mat4& transform, uint32_t flags)
|
||||
{
|
||||
#if CC_USE_CULLING
|
||||
const auto& rect = this->_polyInfo.rect;
|
||||
|
||||
if ((flags & FLAGS_TRANSFORM_DIRTY))
|
||||
{
|
||||
_insideBounds = _checkVisibility(transform, _contentSize, rect);
|
||||
if (_director->isCullingEnabled()) {
|
||||
// Don't calculate the culling if the transform was not updated
|
||||
if (flags & FLAGS_TRANSFORM_DIRTY || flags & FLAGS_CULLING_DIRTY)
|
||||
{
|
||||
_insideBounds = _checkVisibility(transform, _contentSize, this->_polyInfo.rect);
|
||||
}
|
||||
}
|
||||
else {
|
||||
_insideBounds = true;
|
||||
}
|
||||
|
||||
if (_insideBounds)
|
||||
#endif
|
||||
{
|
||||
_trianglesCommand.init(_globalZOrder, _texture->getName(), getGLProgramState(), _blendFunc, _polyInfo.triangles, transform, flags);
|
||||
renderer->addCommand(&_trianglesCommand);
|
||||
|
||||
@@ -39,8 +39,6 @@ LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/../.. \
|
||||
$(LOCAL_PATH)/../../.. \
|
||||
$(LOCAL_PATH)/../../../../external/sources
|
||||
|
||||
# LOCAL_STATIC_LIBRARIES := cocos2dx_internal_static
|
||||
|
||||
LOCAL_CFLAGS += -Wno-psabi
|
||||
LOCAL_EXPORT_CFLAGS += -Wno-psabi
|
||||
|
||||
|
||||
@@ -22,7 +22,6 @@ LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../external/websockets/include/android \
|
||||
$(LOCAL_PATH)/.. \
|
||||
$(LOCAL_PATH)/../../external/sources
|
||||
|
||||
# LOCAL_STATIC_LIBRARIES := cocos2dx_internal_static
|
||||
LOCAL_STATIC_LIBRARIES += libwebsockets_static
|
||||
LOCAL_STATIC_LIBRARIES += cocos_ssl_static
|
||||
LOCAL_STATIC_LIBRARIES += cocos_crypto_static
|
||||
|
||||
@@ -338,6 +338,7 @@ namespace cocos2d { namespace network {
|
||||
{
|
||||
DLLOG("Destruct DownloaderAppleImpl %p", self);
|
||||
self.downloadSession = nil;
|
||||
self.taskDict = nil;
|
||||
[super dealloc];
|
||||
}
|
||||
#pragma mark - NSURLSessionTaskDelegate methods
|
||||
|
||||
@@ -813,7 +813,9 @@ void SIOClientImpl::onMessage(WebSocket* /*ws*/, const WebSocket::Data& data)
|
||||
case 0:
|
||||
CCLOGINFO("Received Disconnect Signal for Endpoint: %s\n", endpoint.c_str());
|
||||
disconnectFromEndpoint(endpoint);
|
||||
c->fireEvent("disconnect", payload);
|
||||
if (c) {
|
||||
c->fireEvent("disconnect", payload);
|
||||
}
|
||||
break;
|
||||
case 1:
|
||||
CCLOGINFO("Connected to endpoint: %s \n", endpoint.c_str());
|
||||
|
||||
Binary file not shown.
@@ -0,0 +1,65 @@
|
||||
/****************************************************************************
|
||||
* Copyright (c) 2017 Chukong Technologies Inc.
|
||||
*
|
||||
* http://www.cocos2d-x.org
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
package org.cocos2dx.lib;
|
||||
|
||||
import android.content.pm.ApplicationInfo;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.util.Log;
|
||||
|
||||
import com.cocos.analytics.CAAgent;
|
||||
|
||||
public class CAAgentWrapper {
|
||||
|
||||
private static final String TAG = "CAAgentWrapper";
|
||||
|
||||
public static void init(String channelID, String appID, String appSecret) {
|
||||
CAAgent.init(Cocos2dxActivity.getContext(), channelID, appID, appSecret);
|
||||
}
|
||||
|
||||
public static String getChannelID() {
|
||||
try {
|
||||
ApplicationInfo applicationInfo = Cocos2dxActivity.getContext().getPackageManager()
|
||||
.getApplicationInfo(Cocos2dxActivity.getContext().getPackageName(),
|
||||
PackageManager.GET_META_DATA);
|
||||
if (applicationInfo != null) {
|
||||
if (applicationInfo.metaData != null) {
|
||||
if (applicationInfo.metaData.containsKey("ASC_ChannelID"))
|
||||
{
|
||||
String channelID = applicationInfo.metaData.get("ASC_ChannelID") + "";
|
||||
if (channelID.startsWith("A")) {
|
||||
channelID = channelID.substring(1);
|
||||
}
|
||||
return channelID;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
Log.e(TAG,"Could not get channel ID", e);
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
}
|
||||
@@ -45,6 +45,8 @@ import android.view.Window;
|
||||
import android.view.WindowManager;
|
||||
import android.widget.FrameLayout;
|
||||
|
||||
import com.cocos.analytics.CAAgent;
|
||||
|
||||
import org.cocos2dx.lib.Cocos2dxHelper.Cocos2dxHelperListener;
|
||||
|
||||
import javax.microedition.khronos.egl.EGL10;
|
||||
@@ -272,6 +274,8 @@ public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelpe
|
||||
|
||||
this.hideVirtualButton();
|
||||
|
||||
CAAgent.enableDebug(false);
|
||||
|
||||
onLoadNativeLibraries();
|
||||
|
||||
sContext = this;
|
||||
@@ -348,6 +352,7 @@ public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelpe
|
||||
@Override
|
||||
protected void onDestroy() {
|
||||
Cocos2dxAudioFocusManager.unregisterAudioFocusListener(this);
|
||||
CAAgent.onDestroy();
|
||||
super.onDestroy();
|
||||
}
|
||||
|
||||
|
||||
@@ -35,6 +35,7 @@ import android.view.KeyEvent;
|
||||
import android.view.MotionEvent;
|
||||
import android.view.View;
|
||||
import android.view.inputmethod.InputMethodManager;
|
||||
import com.cocos.analytics.CAAgent;
|
||||
|
||||
public class Cocos2dxGLSurfaceView extends GLSurfaceView {
|
||||
// ===========================================================
|
||||
@@ -178,6 +179,7 @@ public class Cocos2dxGLSurfaceView extends GLSurfaceView {
|
||||
@Override
|
||||
public void run() {
|
||||
Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleOnResume();
|
||||
CAAgent.onResume(Cocos2dxGLSurfaceView.this.getContext());
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -188,6 +190,7 @@ public class Cocos2dxGLSurfaceView extends GLSurfaceView {
|
||||
@Override
|
||||
public void run() {
|
||||
Cocos2dxGLSurfaceView.this.mCocos2dxRenderer.handleOnPause();
|
||||
CAAgent.onPause(Cocos2dxGLSurfaceView.this.getContext());
|
||||
}
|
||||
});
|
||||
this.setRenderMode(RENDERMODE_WHEN_DIRTY);
|
||||
|
||||
@@ -2,7 +2,7 @@ apply plugin: 'com.android.library'
|
||||
|
||||
android {
|
||||
compileSdkVersion 22
|
||||
buildToolsVersion '25.0.0'
|
||||
buildToolsVersion '26.0.2'
|
||||
|
||||
defaultConfig {
|
||||
minSdkVersion 10
|
||||
|
||||
@@ -792,9 +792,32 @@ bool Renderer::checkVisibility(const Mat4& transform, const Size& size)
|
||||
visibleRect = camera->getVisibleRect();
|
||||
}
|
||||
|
||||
Rect rect(0,0, size.width, size.height);
|
||||
rect = RectApplyTransform(rect, transform);
|
||||
return rect.intersectsRect(visibleRect);
|
||||
// half size of the screen
|
||||
Size screen_half = visibleRect.size;
|
||||
screen_half.width /= 2;
|
||||
screen_half.height /= 2;
|
||||
|
||||
float hSizeX = size.width / 2;
|
||||
float hSizeY = size.height / 2;
|
||||
|
||||
Vec4 v4world, v4local;
|
||||
v4local.set(hSizeX, hSizeY, 0, 1);
|
||||
transform.transformVector(v4local, &v4world);
|
||||
|
||||
// center of screen is (0,0)
|
||||
v4world.x = v4world.x - screen_half.width - visibleRect.origin.x;
|
||||
v4world.y = v4world.y - screen_half.height - visibleRect.origin.y;
|
||||
|
||||
// convert content size to world coordinates
|
||||
float wshw = std::max(fabsf(hSizeX * transform.m[0] + hSizeY * transform.m[4]), fabsf(hSizeX * transform.m[0] - hSizeY * transform.m[4]));
|
||||
float wshh = std::max(fabsf(hSizeX * transform.m[1] + hSizeY * transform.m[5]), fabsf(hSizeX * transform.m[1] - hSizeY * transform.m[5]));
|
||||
|
||||
// compare if it in the positive quadrant of the screen
|
||||
float tmpx = (fabsf(v4world.x) - wshw);
|
||||
float tmpy = (fabsf(v4world.y) - wshh);
|
||||
bool ret = (tmpx < screen_half.width && tmpy < screen_half.height);
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
void Renderer::setClearColor(const Color4F &clearColor)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
Copyright (c) 2008-2010 Ricardo Quesada
|
||||
Copyright (c) 2010-2012 cocos2d-x.org
|
||||
Copyright (c) 2011 Zynga Inc.
|
||||
Copyright (c) 2013-2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2013-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
@@ -158,8 +158,8 @@ void TextureCache::addImageAsync(const std::string &path, const std::function<vo
|
||||
if (_loadingThread == nullptr)
|
||||
{
|
||||
// create a new thread to load images
|
||||
_loadingThread = new (std::nothrow) std::thread(&TextureCache::loadImage, this);
|
||||
_needQuit = false;
|
||||
_loadingThread = new (std::nothrow) std::thread(&TextureCache::loadImage, this);
|
||||
}
|
||||
|
||||
if (0 == _asyncRefCount)
|
||||
@@ -174,10 +174,8 @@ void TextureCache::addImageAsync(const std::string &path, const std::function<vo
|
||||
|
||||
// add async struct into queue
|
||||
_asyncStructQueue.push_back(data);
|
||||
_requestMutex.lock();
|
||||
std::unique_lock<std::mutex> ul(_requestMutex);
|
||||
_requestQueue.push_back(data);
|
||||
_requestMutex.unlock();
|
||||
|
||||
_sleepCondition.notify_one();
|
||||
}
|
||||
|
||||
@@ -213,13 +211,11 @@ void TextureCache::unbindAllImageAsync()
|
||||
void TextureCache::loadImage()
|
||||
{
|
||||
AsyncStruct *asyncStruct = nullptr;
|
||||
std::mutex signalMutex;
|
||||
std::unique_lock<std::mutex> signal(signalMutex);
|
||||
while (!_needQuit)
|
||||
{
|
||||
std::unique_lock<std::mutex> ul(_requestMutex);
|
||||
// pop an AsyncStruct from request queue
|
||||
_requestMutex.lock();
|
||||
if(_requestQueue.empty())
|
||||
if (_requestQueue.empty())
|
||||
{
|
||||
asyncStruct = nullptr;
|
||||
}
|
||||
@@ -228,12 +224,15 @@ void TextureCache::loadImage()
|
||||
asyncStruct = _requestQueue.front();
|
||||
_requestQueue.pop_front();
|
||||
}
|
||||
_requestMutex.unlock();
|
||||
|
||||
if (nullptr == asyncStruct) {
|
||||
_sleepCondition.wait(signal);
|
||||
if (_needQuit) {
|
||||
break;
|
||||
}
|
||||
_sleepCondition.wait(ul);
|
||||
continue;
|
||||
}
|
||||
ul.unlock();
|
||||
|
||||
// load image
|
||||
asyncStruct->loadSuccess = asyncStruct->image->initWithImageFile(asyncStruct->filename);
|
||||
@@ -582,8 +581,10 @@ std::string TextureCache::getTextureFilePath( cocos2d::Texture2D *texture )const
|
||||
void TextureCache::waitForQuit()
|
||||
{
|
||||
// notify sub thread to quick
|
||||
std::unique_lock<std::mutex> ul(_requestMutex);
|
||||
_needQuit = true;
|
||||
_sleepCondition.notify_one();
|
||||
ul.unlock();
|
||||
if (_loadingThread) _loadingThread->join();
|
||||
|
||||
// Clear async tasks which are still in the queue.
|
||||
|
||||
@@ -118,6 +118,16 @@ getAlphaTextureName : function (
|
||||
return 0;
|
||||
},
|
||||
|
||||
/**
|
||||
* @method getName
|
||||
* @return {unsigned int}
|
||||
*/
|
||||
getName : function (
|
||||
)
|
||||
{
|
||||
return 0;
|
||||
},
|
||||
|
||||
/**
|
||||
* @method initWithString
|
||||
* @param {String|String} str
|
||||
@@ -811,14 +821,6 @@ getChildren : function(
|
||||
return new Array();
|
||||
},
|
||||
|
||||
/**
|
||||
* @method markTransformUpdated
|
||||
*/
|
||||
markTransformUpdated : function (
|
||||
)
|
||||
{
|
||||
},
|
||||
|
||||
/**
|
||||
* @method pause
|
||||
*/
|
||||
@@ -2014,6 +2016,14 @@ isCascadeColorEnabled : function (
|
||||
return false;
|
||||
},
|
||||
|
||||
/**
|
||||
* @method markCullingDirty
|
||||
*/
|
||||
markCullingDirty : function (
|
||||
)
|
||||
{
|
||||
},
|
||||
|
||||
/**
|
||||
* @method stopAction
|
||||
* @param {cc.Action} arg0
|
||||
@@ -2529,6 +2539,16 @@ getDeltaTime : function (
|
||||
return 0;
|
||||
},
|
||||
|
||||
/**
|
||||
* @method isCullingEnabled
|
||||
* @return {bool}
|
||||
*/
|
||||
isCullingEnabled : function (
|
||||
)
|
||||
{
|
||||
return false;
|
||||
},
|
||||
|
||||
/**
|
||||
* @method setGLDefaultValues
|
||||
*/
|
||||
@@ -2577,6 +2597,16 @@ mat4
|
||||
{
|
||||
},
|
||||
|
||||
/**
|
||||
* @method setCullingEnabled
|
||||
* @param {bool} arg0
|
||||
*/
|
||||
setCullingEnabled : function (
|
||||
bool
|
||||
)
|
||||
{
|
||||
},
|
||||
|
||||
/**
|
||||
* @method getNotificationNode
|
||||
* @return {cc.Node}
|
||||
@@ -2695,10 +2725,12 @@ vec2
|
||||
|
||||
/**
|
||||
* @method pushMatrix
|
||||
* @param {cc.MATRIX_STACK_TYPE} arg0
|
||||
*/
|
||||
pushMatrix : function (
|
||||
matrix_stack_type
|
||||
* @param {cc.MATRIX_STACK_TYPE|cc.MATRIX_STACK_TYPE} matrix_stack_type
|
||||
* @param {mat4_object} mat4
|
||||
*/
|
||||
pushMatrix : function(
|
||||
matrix_stack_type,
|
||||
mat4
|
||||
)
|
||||
{
|
||||
},
|
||||
@@ -13731,6 +13763,24 @@ begin : function (
|
||||
{
|
||||
},
|
||||
|
||||
/**
|
||||
* @method saveToFile
|
||||
* @param {String|String} str
|
||||
* @param {cc.Image::Format|bool} format
|
||||
* @param {bool|function} bool
|
||||
* @param {function} func
|
||||
* @return {bool|bool}
|
||||
*/
|
||||
saveToFile : function(
|
||||
str,
|
||||
format,
|
||||
bool,
|
||||
func
|
||||
)
|
||||
{
|
||||
return false;
|
||||
},
|
||||
|
||||
/**
|
||||
* @method setAutoDraw
|
||||
* @param {bool} arg0
|
||||
@@ -13970,12 +14020,28 @@ str
|
||||
},
|
||||
|
||||
/**
|
||||
* @method setUniformLocationWith1f
|
||||
* @param {int} arg0
|
||||
* @param {float} arg1
|
||||
* @method getProgram
|
||||
* @return {unsigned int}
|
||||
*/
|
||||
setUniformLocationWith1f : function (
|
||||
int,
|
||||
getProgram : function (
|
||||
)
|
||||
{
|
||||
return 0;
|
||||
},
|
||||
|
||||
/**
|
||||
* @method setUniformLocationWith2f
|
||||
* @param {int|int|int|int} int
|
||||
* @param {float|float|float|float} float
|
||||
* @param {float|float|float} float
|
||||
* @param {float|float} float
|
||||
* @param {float} float
|
||||
*/
|
||||
setUniformLocationWith2f : function(
|
||||
int,
|
||||
float,
|
||||
float,
|
||||
float,
|
||||
float
|
||||
)
|
||||
{
|
||||
@@ -13997,22 +14063,6 @@ str
|
||||
return false;
|
||||
},
|
||||
|
||||
/**
|
||||
* @method setUniformLocationWith3f
|
||||
* @param {int} arg0
|
||||
* @param {float} arg1
|
||||
* @param {float} arg2
|
||||
* @param {float} arg3
|
||||
*/
|
||||
setUniformLocationWith3f : function (
|
||||
int,
|
||||
float,
|
||||
float,
|
||||
float
|
||||
)
|
||||
{
|
||||
},
|
||||
|
||||
/**
|
||||
* @method setUniformsForBuiltins
|
||||
* @param {mat4_object} mat4
|
||||
@@ -14023,40 +14073,6 @@ mat4
|
||||
{
|
||||
},
|
||||
|
||||
/**
|
||||
* @method setUniformLocationWith3i
|
||||
* @param {int} arg0
|
||||
* @param {int} arg1
|
||||
* @param {int} arg2
|
||||
* @param {int} arg3
|
||||
*/
|
||||
setUniformLocationWith3i : function (
|
||||
int,
|
||||
int,
|
||||
int,
|
||||
int
|
||||
)
|
||||
{
|
||||
},
|
||||
|
||||
/**
|
||||
* @method setUniformLocationWith4f
|
||||
* @param {int} arg0
|
||||
* @param {float} arg1
|
||||
* @param {float} arg2
|
||||
* @param {float} arg3
|
||||
* @param {float} arg4
|
||||
*/
|
||||
setUniformLocationWith4f : function (
|
||||
int,
|
||||
float,
|
||||
float,
|
||||
float,
|
||||
float
|
||||
)
|
||||
{
|
||||
},
|
||||
|
||||
/**
|
||||
* @method updateUniforms
|
||||
*/
|
||||
@@ -14065,18 +14081,6 @@ updateUniforms : function (
|
||||
{
|
||||
},
|
||||
|
||||
/**
|
||||
* @method getUniformLocation
|
||||
* @param {String} arg0
|
||||
* @return {int}
|
||||
*/
|
||||
getUniformLocation : function (
|
||||
str
|
||||
)
|
||||
{
|
||||
return 0;
|
||||
},
|
||||
|
||||
/**
|
||||
* @method link
|
||||
* @return {bool}
|
||||
@@ -14095,6 +14099,16 @@ reset : function (
|
||||
{
|
||||
},
|
||||
|
||||
/**
|
||||
* @method getProgramLog
|
||||
* @return {String}
|
||||
*/
|
||||
getProgramLog : function (
|
||||
)
|
||||
{
|
||||
return ;
|
||||
},
|
||||
|
||||
/**
|
||||
* @method getAttribLocation
|
||||
* @param {String} arg0
|
||||
@@ -14108,58 +14122,30 @@ str
|
||||
},
|
||||
|
||||
/**
|
||||
* @method setUniformLocationWith2f
|
||||
* @param {int} arg0
|
||||
* @param {float} arg1
|
||||
* @param {float} arg2
|
||||
* @method getUniformLocation
|
||||
* @param {String} arg0
|
||||
* @return {int}
|
||||
*/
|
||||
setUniformLocationWith2f : function (
|
||||
int,
|
||||
float,
|
||||
float
|
||||
)
|
||||
{
|
||||
},
|
||||
|
||||
/**
|
||||
* @method setUniformLocationWith4i
|
||||
* @param {int} arg0
|
||||
* @param {int} arg1
|
||||
* @param {int} arg2
|
||||
* @param {int} arg3
|
||||
* @param {int} arg4
|
||||
*/
|
||||
setUniformLocationWith4i : function (
|
||||
int,
|
||||
int,
|
||||
int,
|
||||
int,
|
||||
int
|
||||
)
|
||||
{
|
||||
},
|
||||
|
||||
/**
|
||||
* @method setUniformLocationWith1i
|
||||
* @param {int} arg0
|
||||
* @param {int} arg1
|
||||
*/
|
||||
setUniformLocationWith1i : function (
|
||||
int,
|
||||
int
|
||||
getUniformLocation : function (
|
||||
str
|
||||
)
|
||||
{
|
||||
return 0;
|
||||
},
|
||||
|
||||
/**
|
||||
* @method setUniformLocationWith2i
|
||||
* @param {int} arg0
|
||||
* @param {int} arg1
|
||||
* @param {int} arg2
|
||||
*/
|
||||
setUniformLocationWith2i : function (
|
||||
int,
|
||||
int,
|
||||
* @param {int|int|int|int} int
|
||||
* @param {int|int|int|int} int
|
||||
* @param {int|int|int} int
|
||||
* @param {int|int} int
|
||||
* @param {int} int
|
||||
*/
|
||||
setUniformLocationWith2i : function(
|
||||
int,
|
||||
int,
|
||||
int,
|
||||
int,
|
||||
int
|
||||
)
|
||||
{
|
||||
|
||||
@@ -48,6 +48,16 @@ getVisibleRect : function (
|
||||
return cc.Rect;
|
||||
},
|
||||
|
||||
/**
|
||||
* @method setEnable
|
||||
* @param {bool} arg0
|
||||
*/
|
||||
setEnable : function (
|
||||
bool
|
||||
)
|
||||
{
|
||||
},
|
||||
|
||||
/**
|
||||
* @method containsNode
|
||||
* @param {cc.Node} arg0
|
||||
|
||||
@@ -351,6 +351,24 @@ static bool js_cocos2dx_Texture2D_getAlphaTextureName(se::State& s)
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_Texture2D_getAlphaTextureName)
|
||||
|
||||
static bool js_cocos2dx_Texture2D_getName(se::State& s)
|
||||
{
|
||||
cocos2d::Texture2D* cobj = (cocos2d::Texture2D*)s.nativeThisObject();
|
||||
SE_PRECONDITION2(cobj, false, "js_cocos2dx_Texture2D_getName : Invalid Native Object");
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 0) {
|
||||
unsigned int result = cobj->getName();
|
||||
ok &= uint32_to_seval(result, &s.rval());
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_Texture2D_getName : Error processing arguments");
|
||||
return true;
|
||||
}
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_Texture2D_getName)
|
||||
|
||||
static bool js_cocos2dx_Texture2D_initWithString(se::State& s)
|
||||
{
|
||||
CC_UNUSED bool ok = true;
|
||||
@@ -862,6 +880,7 @@ bool js_register_cocos2dx_Texture2D(se::Object* obj)
|
||||
cls->defineFunction("hasPremultipliedAlpha", _SE(js_cocos2dx_Texture2D_hasPremultipliedAlpha));
|
||||
cls->defineFunction("getPixelsHigh", _SE(js_cocos2dx_Texture2D_getPixelsHigh));
|
||||
cls->defineFunction("getAlphaTextureName", _SE(js_cocos2dx_Texture2D_getAlphaTextureName));
|
||||
cls->defineFunction("getName", _SE(js_cocos2dx_Texture2D_getName));
|
||||
cls->defineFunction("initWithString", _SE(js_cocos2dx_Texture2D_initWithString));
|
||||
cls->defineFunction("setMaxT", _SE(js_cocos2dx_Texture2D_setMaxT));
|
||||
cls->defineFunction("getPath", _SE(js_cocos2dx_Texture2D_getPath));
|
||||
@@ -1993,21 +2012,6 @@ static bool js_cocos2dx_Node_getChildren(se::State& s)
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_Node_getChildren)
|
||||
|
||||
static bool js_cocos2dx_Node_markTransformUpdated(se::State& s)
|
||||
{
|
||||
cocos2d::Node* cobj = (cocos2d::Node*)s.nativeThisObject();
|
||||
SE_PRECONDITION2(cobj, false, "js_cocos2dx_Node_markTransformUpdated : Invalid Native Object");
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
if (argc == 0) {
|
||||
cobj->markTransformUpdated();
|
||||
return true;
|
||||
}
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_Node_markTransformUpdated)
|
||||
|
||||
static bool js_cocos2dx_Node_pause(se::State& s)
|
||||
{
|
||||
cocos2d::Node* cobj = (cocos2d::Node*)s.nativeThisObject();
|
||||
@@ -4417,6 +4421,21 @@ static bool js_cocos2dx_Node_isCascadeColorEnabled(se::State& s)
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_Node_isCascadeColorEnabled)
|
||||
|
||||
static bool js_cocos2dx_Node_markCullingDirty(se::State& s)
|
||||
{
|
||||
cocos2d::Node* cobj = (cocos2d::Node*)s.nativeThisObject();
|
||||
SE_PRECONDITION2(cobj, false, "js_cocos2dx_Node_markCullingDirty : Invalid Native Object");
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
if (argc == 0) {
|
||||
cobj->markCullingDirty();
|
||||
return true;
|
||||
}
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_Node_markCullingDirty)
|
||||
|
||||
static bool js_cocos2dx_Node_stopAction(se::State& s)
|
||||
{
|
||||
cocos2d::Node* cobj = (cocos2d::Node*)s.nativeThisObject();
|
||||
@@ -4529,7 +4548,6 @@ bool js_register_cocos2dx_Node(se::Object* obj)
|
||||
cls->defineFunction("setOpacityModifyRGB", _SE(js_cocos2dx_Node_setOpacityModifyRGB));
|
||||
cls->defineFunction("setCascadeOpacityEnabled", _SE(js_cocos2dx_Node_setCascadeOpacityEnabled));
|
||||
cls->defineFunction("getChildren", _SE(js_cocos2dx_Node_getChildren));
|
||||
cls->defineFunction("markTransformUpdated", _SE(js_cocos2dx_Node_markTransformUpdated));
|
||||
cls->defineFunction("pause", _SE(js_cocos2dx_Node_pause));
|
||||
cls->defineFunction("convertToWorldSpaceAR", _SE(js_cocos2dx_Node_convertToWorldSpaceAR));
|
||||
cls->defineFunction("isIgnoreAnchorPointForPosition", _SE(js_cocos2dx_Node_isIgnoreAnchorPointForPosition));
|
||||
@@ -4645,6 +4663,7 @@ bool js_register_cocos2dx_Node(se::Object* obj)
|
||||
cls->defineFunction("convertToNodeSpace", _SE(js_cocos2dx_Node_convertToNodeSpace));
|
||||
cls->defineFunction("setTag", _SE(js_cocos2dx_Node_setTag));
|
||||
cls->defineFunction("isCascadeColorEnabled", _SE(js_cocos2dx_Node_isCascadeColorEnabled));
|
||||
cls->defineFunction("markCullingDirty", _SE(js_cocos2dx_Node_markCullingDirty));
|
||||
cls->defineFunction("stopAction", _SE(js_cocos2dx_Node_stopAction));
|
||||
cls->defineFunction("getActionManager", _SE(js_cocos2dx_Node_getActionManager));
|
||||
cls->defineFunction("ctor", _SE(js_cocos2dx_Node_ctor));
|
||||
@@ -5579,6 +5598,24 @@ static bool js_cocos2dx_Director_getDeltaTime(se::State& s)
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_Director_getDeltaTime)
|
||||
|
||||
static bool js_cocos2dx_Director_isCullingEnabled(se::State& s)
|
||||
{
|
||||
cocos2d::Director* cobj = (cocos2d::Director*)s.nativeThisObject();
|
||||
SE_PRECONDITION2(cobj, false, "js_cocos2dx_Director_isCullingEnabled : Invalid Native Object");
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 0) {
|
||||
bool result = cobj->isCullingEnabled();
|
||||
ok &= boolean_to_seval(result, &s.rval());
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_Director_isCullingEnabled : Error processing arguments");
|
||||
return true;
|
||||
}
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_Director_isCullingEnabled)
|
||||
|
||||
static bool js_cocos2dx_Director_setGLDefaultValues(se::State& s)
|
||||
{
|
||||
cocos2d::Director* cobj = (cocos2d::Director*)s.nativeThisObject();
|
||||
@@ -5668,6 +5705,25 @@ static bool js_cocos2dx_Director_loadMatrix(se::State& s)
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_Director_loadMatrix)
|
||||
|
||||
static bool js_cocos2dx_Director_setCullingEnabled(se::State& s)
|
||||
{
|
||||
cocos2d::Director* cobj = (cocos2d::Director*)s.nativeThisObject();
|
||||
SE_PRECONDITION2(cobj, false, "js_cocos2dx_Director_setCullingEnabled : Invalid Native Object");
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 1) {
|
||||
bool arg0;
|
||||
ok &= seval_to_boolean(args[0], &arg0);
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_Director_setCullingEnabled : Error processing arguments");
|
||||
cobj->setCullingEnabled(arg0);
|
||||
return true;
|
||||
}
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_Director_setCullingEnabled)
|
||||
|
||||
static bool js_cocos2dx_Director_getNotificationNode(se::State& s)
|
||||
{
|
||||
cocos2d::Director* cobj = (cocos2d::Director*)s.nativeThisObject();
|
||||
@@ -5881,19 +5937,35 @@ SE_BIND_FUNC(js_cocos2dx_Director_convertToUI)
|
||||
|
||||
static bool js_cocos2dx_Director_pushMatrix(se::State& s)
|
||||
{
|
||||
CC_UNUSED bool ok = true;
|
||||
cocos2d::Director* cobj = (cocos2d::Director*)s.nativeThisObject();
|
||||
SE_PRECONDITION2(cobj, false, "js_cocos2dx_Director_pushMatrix : Invalid Native Object");
|
||||
SE_PRECONDITION2( cobj, false, "js_cocos2dx_Director_pushMatrix : Invalid Native Object");
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 1) {
|
||||
cocos2d::MATRIX_STACK_TYPE arg0;
|
||||
ok &= seval_to_int32(args[0], (int32_t*)&arg0);
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_Director_pushMatrix : Error processing arguments");
|
||||
cobj->pushMatrix(arg0);
|
||||
return true;
|
||||
}
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1);
|
||||
do {
|
||||
if (argc == 2) {
|
||||
cocos2d::MATRIX_STACK_TYPE arg0;
|
||||
ok &= seval_to_int32(args[0], (int32_t*)&arg0);
|
||||
if (!ok) { ok = true; break; }
|
||||
cocos2d::Mat4 arg1;
|
||||
ok &= seval_to_Mat4(args[1], &arg1);
|
||||
if (!ok) { ok = true; break; }
|
||||
cobj->pushMatrix(arg0, arg1);
|
||||
return true;
|
||||
}
|
||||
} while(false);
|
||||
|
||||
do {
|
||||
if (argc == 1) {
|
||||
cocos2d::MATRIX_STACK_TYPE arg0;
|
||||
ok &= seval_to_int32(args[0], (int32_t*)&arg0);
|
||||
if (!ok) { ok = true; break; }
|
||||
cobj->pushMatrix(arg0);
|
||||
return true;
|
||||
}
|
||||
} while(false);
|
||||
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d", (int)argc);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_Director_pushMatrix)
|
||||
@@ -6646,11 +6718,13 @@ bool js_register_cocos2dx_Director(se::Object* obj)
|
||||
cls->defineFunction("getContentScaleFactor", _SE(js_cocos2dx_Director_getContentScaleFactor));
|
||||
cls->defineFunction("getWinSizeInPixels", _SE(js_cocos2dx_Director_getWinSizeInPixels));
|
||||
cls->defineFunction("getDeltaTime", _SE(js_cocos2dx_Director_getDeltaTime));
|
||||
cls->defineFunction("isCullingEnabled", _SE(js_cocos2dx_Director_isCullingEnabled));
|
||||
cls->defineFunction("setGLDefaultValues", _SE(js_cocos2dx_Director_setGLDefaultValues));
|
||||
cls->defineFunction("setActionManager", _SE(js_cocos2dx_Director_setActionManager));
|
||||
cls->defineFunction("setAlphaBlending", _SE(js_cocos2dx_Director_setAlphaBlending));
|
||||
cls->defineFunction("popToRootScene", _SE(js_cocos2dx_Director_popToRootScene));
|
||||
cls->defineFunction("loadMatrix", _SE(js_cocos2dx_Director_loadMatrix));
|
||||
cls->defineFunction("setCullingEnabled", _SE(js_cocos2dx_Director_setCullingEnabled));
|
||||
cls->defineFunction("getNotificationNode", _SE(js_cocos2dx_Director_getNotificationNode));
|
||||
cls->defineFunction("getWinSize", _SE(js_cocos2dx_Director_getWinSize));
|
||||
cls->defineFunction("end", _SE(js_cocos2dx_Director_end));
|
||||
@@ -31205,6 +31279,173 @@ static bool js_cocos2dx_RenderTexture_begin(se::State& s)
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_RenderTexture_begin)
|
||||
|
||||
static bool js_cocos2dx_RenderTexture_saveToFile(se::State& s)
|
||||
{
|
||||
CC_UNUSED bool ok = true;
|
||||
cocos2d::RenderTexture* cobj = (cocos2d::RenderTexture*)s.nativeThisObject();
|
||||
SE_PRECONDITION2( cobj, false, "js_cocos2dx_RenderTexture_saveToFile : Invalid Native Object");
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
do {
|
||||
if (argc == 2) {
|
||||
std::string arg0;
|
||||
ok &= seval_to_std_string(args[0], &arg0);
|
||||
if (!ok) { ok = true; break; }
|
||||
cocos2d::Image::Format arg1;
|
||||
ok &= seval_to_int32(args[1], (int32_t*)&arg1);
|
||||
if (!ok) { ok = true; break; }
|
||||
bool result = cobj->saveToFile(arg0, arg1);
|
||||
ok &= boolean_to_seval(result, &s.rval());
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_RenderTexture_saveToFile : Error processing arguments");
|
||||
return true;
|
||||
}
|
||||
} while(false);
|
||||
|
||||
do {
|
||||
if (argc == 3) {
|
||||
std::string arg0;
|
||||
ok &= seval_to_std_string(args[0], &arg0);
|
||||
if (!ok) { ok = true; break; }
|
||||
cocos2d::Image::Format arg1;
|
||||
ok &= seval_to_int32(args[1], (int32_t*)&arg1);
|
||||
if (!ok) { ok = true; break; }
|
||||
bool arg2;
|
||||
ok &= seval_to_boolean(args[2], &arg2);
|
||||
bool result = cobj->saveToFile(arg0, arg1, arg2);
|
||||
ok &= boolean_to_seval(result, &s.rval());
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_RenderTexture_saveToFile : Error processing arguments");
|
||||
return true;
|
||||
}
|
||||
} while(false);
|
||||
|
||||
do {
|
||||
if (argc == 4) {
|
||||
std::string arg0;
|
||||
ok &= seval_to_std_string(args[0], &arg0);
|
||||
if (!ok) { ok = true; break; }
|
||||
cocos2d::Image::Format arg1;
|
||||
ok &= seval_to_int32(args[1], (int32_t*)&arg1);
|
||||
if (!ok) { ok = true; break; }
|
||||
bool arg2;
|
||||
ok &= seval_to_boolean(args[2], &arg2);
|
||||
std::function<void (cocos2d::RenderTexture *, const std::basic_string<char> &)> arg3;
|
||||
do {
|
||||
if (args[3].isObject() && args[3].toObject()->isFunction())
|
||||
{
|
||||
se::Value jsThis(s.thisObject());
|
||||
se::Value jsFunc(args[3]);
|
||||
jsThis.toObject()->attachObject(jsFunc.toObject());
|
||||
auto lambda = [=](cocos2d::RenderTexture* larg0, const std::basic_string<char> & larg1) -> void {
|
||||
se::ScriptEngine::getInstance()->clearException();
|
||||
se::AutoHandleScope hs;
|
||||
|
||||
CC_UNUSED bool ok = true;
|
||||
se::ValueArray args;
|
||||
args.resize(2);
|
||||
ok &= native_ptr_to_seval<cocos2d::RenderTexture>((cocos2d::RenderTexture*)larg0, &args[0]);
|
||||
ok &= std_string_to_seval(larg1, &args[1]);
|
||||
se::Value rval;
|
||||
se::Object* thisObj = jsThis.isObject() ? jsThis.toObject() : nullptr;
|
||||
se::Object* funcObj = jsFunc.toObject();
|
||||
bool succeed = funcObj->call(args, thisObj, &rval);
|
||||
if (!succeed) {
|
||||
se::ScriptEngine::getInstance()->clearException();
|
||||
}
|
||||
};
|
||||
arg3 = lambda;
|
||||
}
|
||||
else
|
||||
{
|
||||
arg3 = nullptr;
|
||||
}
|
||||
} while(false)
|
||||
;
|
||||
if (!ok) { ok = true; break; }
|
||||
bool result = cobj->saveToFile(arg0, arg1, arg2, arg3);
|
||||
ok &= boolean_to_seval(result, &s.rval());
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_RenderTexture_saveToFile : Error processing arguments");
|
||||
return true;
|
||||
}
|
||||
} while(false);
|
||||
|
||||
do {
|
||||
if (argc == 1) {
|
||||
std::string arg0;
|
||||
ok &= seval_to_std_string(args[0], &arg0);
|
||||
if (!ok) { ok = true; break; }
|
||||
bool result = cobj->saveToFile(arg0);
|
||||
ok &= boolean_to_seval(result, &s.rval());
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_RenderTexture_saveToFile : Error processing arguments");
|
||||
return true;
|
||||
}
|
||||
} while(false);
|
||||
|
||||
do {
|
||||
if (argc == 2) {
|
||||
std::string arg0;
|
||||
ok &= seval_to_std_string(args[0], &arg0);
|
||||
if (!ok) { ok = true; break; }
|
||||
bool arg1;
|
||||
ok &= seval_to_boolean(args[1], &arg1);
|
||||
bool result = cobj->saveToFile(arg0, arg1);
|
||||
ok &= boolean_to_seval(result, &s.rval());
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_RenderTexture_saveToFile : Error processing arguments");
|
||||
return true;
|
||||
}
|
||||
} while(false);
|
||||
|
||||
do {
|
||||
if (argc == 3) {
|
||||
std::string arg0;
|
||||
ok &= seval_to_std_string(args[0], &arg0);
|
||||
if (!ok) { ok = true; break; }
|
||||
bool arg1;
|
||||
ok &= seval_to_boolean(args[1], &arg1);
|
||||
std::function<void (cocos2d::RenderTexture *, const std::basic_string<char> &)> arg2;
|
||||
do {
|
||||
if (args[2].isObject() && args[2].toObject()->isFunction())
|
||||
{
|
||||
se::Value jsThis(s.thisObject());
|
||||
se::Value jsFunc(args[2]);
|
||||
jsThis.toObject()->attachObject(jsFunc.toObject());
|
||||
auto lambda = [=](cocos2d::RenderTexture* larg0, const std::basic_string<char> & larg1) -> void {
|
||||
se::ScriptEngine::getInstance()->clearException();
|
||||
se::AutoHandleScope hs;
|
||||
|
||||
CC_UNUSED bool ok = true;
|
||||
se::ValueArray args;
|
||||
args.resize(2);
|
||||
ok &= native_ptr_to_seval<cocos2d::RenderTexture>((cocos2d::RenderTexture*)larg0, &args[0]);
|
||||
ok &= std_string_to_seval(larg1, &args[1]);
|
||||
se::Value rval;
|
||||
se::Object* thisObj = jsThis.isObject() ? jsThis.toObject() : nullptr;
|
||||
se::Object* funcObj = jsFunc.toObject();
|
||||
bool succeed = funcObj->call(args, thisObj, &rval);
|
||||
if (!succeed) {
|
||||
se::ScriptEngine::getInstance()->clearException();
|
||||
}
|
||||
};
|
||||
arg2 = lambda;
|
||||
}
|
||||
else
|
||||
{
|
||||
arg2 = nullptr;
|
||||
}
|
||||
} while(false)
|
||||
;
|
||||
if (!ok) { ok = true; break; }
|
||||
bool result = cobj->saveToFile(arg0, arg1, arg2);
|
||||
ok &= boolean_to_seval(result, &s.rval());
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_RenderTexture_saveToFile : Error processing arguments");
|
||||
return true;
|
||||
}
|
||||
} while(false);
|
||||
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d", (int)argc);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_RenderTexture_saveToFile)
|
||||
|
||||
static bool js_cocos2dx_RenderTexture_setAutoDraw(se::State& s)
|
||||
{
|
||||
cocos2d::RenderTexture* cobj = (cocos2d::RenderTexture*)s.nativeThisObject();
|
||||
@@ -31610,6 +31851,7 @@ bool js_register_cocos2dx_RenderTexture(se::Object* obj)
|
||||
cls->defineFunction("setKeepMatrix", _SE(js_cocos2dx_RenderTexture_setKeepMatrix));
|
||||
cls->defineFunction("setClearFlags", _SE(js_cocos2dx_RenderTexture_setClearFlags));
|
||||
cls->defineFunction("begin", _SE(js_cocos2dx_RenderTexture_begin));
|
||||
cls->defineFunction("saveToFile", _SE(js_cocos2dx_RenderTexture_saveToFile));
|
||||
cls->defineFunction("setAutoDraw", _SE(js_cocos2dx_RenderTexture_setAutoDraw));
|
||||
cls->defineFunction("setClearColor", _SE(js_cocos2dx_RenderTexture_setClearColor));
|
||||
cls->defineFunction("beginWithClear", _SE(js_cocos2dx_RenderTexture_beginWithClear));
|
||||
@@ -31796,26 +32038,105 @@ static bool js_cocos2dx_GLProgram_initWithByteArrays(se::State& s)
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_GLProgram_initWithByteArrays)
|
||||
|
||||
static bool js_cocos2dx_GLProgram_setUniformLocationWith1f(se::State& s)
|
||||
static bool js_cocos2dx_GLProgram_getProgram(se::State& s)
|
||||
{
|
||||
cocos2d::GLProgram* cobj = (cocos2d::GLProgram*)s.nativeThisObject();
|
||||
SE_PRECONDITION2(cobj, false, "js_cocos2dx_GLProgram_setUniformLocationWith1f : Invalid Native Object");
|
||||
SE_PRECONDITION2(cobj, false, "js_cocos2dx_GLProgram_getProgram : Invalid Native Object");
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 2) {
|
||||
int arg0 = 0;
|
||||
float arg1 = 0;
|
||||
ok &= seval_to_int32(args[0], (int32_t*)&arg0);
|
||||
ok &= seval_to_float(args[1], &arg1);
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_GLProgram_setUniformLocationWith1f : Error processing arguments");
|
||||
cobj->setUniformLocationWith1f(arg0, arg1);
|
||||
if (argc == 0) {
|
||||
unsigned int result = cobj->getProgram();
|
||||
ok &= uint32_to_seval(result, &s.rval());
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_GLProgram_getProgram : Error processing arguments");
|
||||
return true;
|
||||
}
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 2);
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_GLProgram_setUniformLocationWith1f)
|
||||
SE_BIND_FUNC(js_cocos2dx_GLProgram_getProgram)
|
||||
|
||||
static bool js_cocos2dx_GLProgram_setUniformLocationWith2f(se::State& s)
|
||||
{
|
||||
CC_UNUSED bool ok = true;
|
||||
cocos2d::GLProgram* cobj = (cocos2d::GLProgram*)s.nativeThisObject();
|
||||
SE_PRECONDITION2( cobj, false, "js_cocos2dx_GLProgram_setUniformLocationWith2f : Invalid Native Object");
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
do {
|
||||
if (argc == 3) {
|
||||
int arg0 = 0;
|
||||
ok &= seval_to_int32(args[0], (int32_t*)&arg0);
|
||||
if (!ok) { ok = true; break; }
|
||||
float arg1 = 0;
|
||||
ok &= seval_to_float(args[1], &arg1);
|
||||
if (!ok) { ok = true; break; }
|
||||
float arg2 = 0;
|
||||
ok &= seval_to_float(args[2], &arg2);
|
||||
if (!ok) { ok = true; break; }
|
||||
cobj->setUniformLocationWith2f(arg0, arg1, arg2);
|
||||
return true;
|
||||
}
|
||||
} while(false);
|
||||
|
||||
do {
|
||||
if (argc == 2) {
|
||||
int arg0 = 0;
|
||||
ok &= seval_to_int32(args[0], (int32_t*)&arg0);
|
||||
if (!ok) { ok = true; break; }
|
||||
float arg1 = 0;
|
||||
ok &= seval_to_float(args[1], &arg1);
|
||||
if (!ok) { ok = true; break; }
|
||||
cobj->setUniformLocationWith1f(arg0, arg1);
|
||||
return true;
|
||||
}
|
||||
} while(false);
|
||||
|
||||
do {
|
||||
if (argc == 4) {
|
||||
int arg0 = 0;
|
||||
ok &= seval_to_int32(args[0], (int32_t*)&arg0);
|
||||
if (!ok) { ok = true; break; }
|
||||
float arg1 = 0;
|
||||
ok &= seval_to_float(args[1], &arg1);
|
||||
if (!ok) { ok = true; break; }
|
||||
float arg2 = 0;
|
||||
ok &= seval_to_float(args[2], &arg2);
|
||||
if (!ok) { ok = true; break; }
|
||||
float arg3 = 0;
|
||||
ok &= seval_to_float(args[3], &arg3);
|
||||
if (!ok) { ok = true; break; }
|
||||
cobj->setUniformLocationWith3f(arg0, arg1, arg2, arg3);
|
||||
return true;
|
||||
}
|
||||
} while(false);
|
||||
|
||||
do {
|
||||
if (argc == 5) {
|
||||
int arg0 = 0;
|
||||
ok &= seval_to_int32(args[0], (int32_t*)&arg0);
|
||||
if (!ok) { ok = true; break; }
|
||||
float arg1 = 0;
|
||||
ok &= seval_to_float(args[1], &arg1);
|
||||
if (!ok) { ok = true; break; }
|
||||
float arg2 = 0;
|
||||
ok &= seval_to_float(args[2], &arg2);
|
||||
if (!ok) { ok = true; break; }
|
||||
float arg3 = 0;
|
||||
ok &= seval_to_float(args[3], &arg3);
|
||||
if (!ok) { ok = true; break; }
|
||||
float arg4 = 0;
|
||||
ok &= seval_to_float(args[4], &arg4);
|
||||
if (!ok) { ok = true; break; }
|
||||
cobj->setUniformLocationWith4f(arg0, arg1, arg2, arg3, arg4);
|
||||
return true;
|
||||
}
|
||||
} while(false);
|
||||
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d", (int)argc);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_GLProgram_setUniformLocationWith2f)
|
||||
|
||||
static bool js_cocos2dx_GLProgram_initWithFilenames(se::State& s)
|
||||
{
|
||||
@@ -31862,31 +32183,6 @@ static bool js_cocos2dx_GLProgram_initWithFilenames(se::State& s)
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_GLProgram_initWithFilenames)
|
||||
|
||||
static bool js_cocos2dx_GLProgram_setUniformLocationWith3f(se::State& s)
|
||||
{
|
||||
cocos2d::GLProgram* cobj = (cocos2d::GLProgram*)s.nativeThisObject();
|
||||
SE_PRECONDITION2(cobj, false, "js_cocos2dx_GLProgram_setUniformLocationWith3f : Invalid Native Object");
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 4) {
|
||||
int arg0 = 0;
|
||||
float arg1 = 0;
|
||||
float arg2 = 0;
|
||||
float arg3 = 0;
|
||||
ok &= seval_to_int32(args[0], (int32_t*)&arg0);
|
||||
ok &= seval_to_float(args[1], &arg1);
|
||||
ok &= seval_to_float(args[2], &arg2);
|
||||
ok &= seval_to_float(args[3], &arg3);
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_GLProgram_setUniformLocationWith3f : Error processing arguments");
|
||||
cobj->setUniformLocationWith3f(arg0, arg1, arg2, arg3);
|
||||
return true;
|
||||
}
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 4);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_GLProgram_setUniformLocationWith3f)
|
||||
|
||||
static bool js_cocos2dx_GLProgram_setUniformsForBuiltins(se::State& s)
|
||||
{
|
||||
CC_UNUSED bool ok = true;
|
||||
@@ -31916,58 +32212,6 @@ static bool js_cocos2dx_GLProgram_setUniformsForBuiltins(se::State& s)
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_GLProgram_setUniformsForBuiltins)
|
||||
|
||||
static bool js_cocos2dx_GLProgram_setUniformLocationWith3i(se::State& s)
|
||||
{
|
||||
cocos2d::GLProgram* cobj = (cocos2d::GLProgram*)s.nativeThisObject();
|
||||
SE_PRECONDITION2(cobj, false, "js_cocos2dx_GLProgram_setUniformLocationWith3i : Invalid Native Object");
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 4) {
|
||||
int arg0 = 0;
|
||||
int arg1 = 0;
|
||||
int arg2 = 0;
|
||||
int arg3 = 0;
|
||||
ok &= seval_to_int32(args[0], (int32_t*)&arg0);
|
||||
ok &= seval_to_int32(args[1], (int32_t*)&arg1);
|
||||
ok &= seval_to_int32(args[2], (int32_t*)&arg2);
|
||||
ok &= seval_to_int32(args[3], (int32_t*)&arg3);
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_GLProgram_setUniformLocationWith3i : Error processing arguments");
|
||||
cobj->setUniformLocationWith3i(arg0, arg1, arg2, arg3);
|
||||
return true;
|
||||
}
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 4);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_GLProgram_setUniformLocationWith3i)
|
||||
|
||||
static bool js_cocos2dx_GLProgram_setUniformLocationWith4f(se::State& s)
|
||||
{
|
||||
cocos2d::GLProgram* cobj = (cocos2d::GLProgram*)s.nativeThisObject();
|
||||
SE_PRECONDITION2(cobj, false, "js_cocos2dx_GLProgram_setUniformLocationWith4f : Invalid Native Object");
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 5) {
|
||||
int arg0 = 0;
|
||||
float arg1 = 0;
|
||||
float arg2 = 0;
|
||||
float arg3 = 0;
|
||||
float arg4 = 0;
|
||||
ok &= seval_to_int32(args[0], (int32_t*)&arg0);
|
||||
ok &= seval_to_float(args[1], &arg1);
|
||||
ok &= seval_to_float(args[2], &arg2);
|
||||
ok &= seval_to_float(args[3], &arg3);
|
||||
ok &= seval_to_float(args[4], &arg4);
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_GLProgram_setUniformLocationWith4f : Error processing arguments");
|
||||
cobj->setUniformLocationWith4f(arg0, arg1, arg2, arg3, arg4);
|
||||
return true;
|
||||
}
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 5);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_GLProgram_setUniformLocationWith4f)
|
||||
|
||||
static bool js_cocos2dx_GLProgram_updateUniforms(se::State& s)
|
||||
{
|
||||
cocos2d::GLProgram* cobj = (cocos2d::GLProgram*)s.nativeThisObject();
|
||||
@@ -31983,27 +32227,6 @@ static bool js_cocos2dx_GLProgram_updateUniforms(se::State& s)
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_GLProgram_updateUniforms)
|
||||
|
||||
static bool js_cocos2dx_GLProgram_getUniformLocation(se::State& s)
|
||||
{
|
||||
cocos2d::GLProgram* cobj = (cocos2d::GLProgram*)s.nativeThisObject();
|
||||
SE_PRECONDITION2(cobj, false, "js_cocos2dx_GLProgram_getUniformLocation : Invalid Native Object");
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 1) {
|
||||
std::string arg0;
|
||||
ok &= seval_to_std_string(args[0], &arg0);
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_GLProgram_getUniformLocation : Error processing arguments");
|
||||
int result = cobj->getUniformLocation(arg0);
|
||||
ok &= int32_to_seval(result, &s.rval());
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_GLProgram_getUniformLocation : Error processing arguments");
|
||||
return true;
|
||||
}
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_GLProgram_getUniformLocation)
|
||||
|
||||
static bool js_cocos2dx_GLProgram_link(se::State& s)
|
||||
{
|
||||
cocos2d::GLProgram* cobj = (cocos2d::GLProgram*)s.nativeThisObject();
|
||||
@@ -32037,6 +32260,24 @@ static bool js_cocos2dx_GLProgram_reset(se::State& s)
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_GLProgram_reset)
|
||||
|
||||
static bool js_cocos2dx_GLProgram_getProgramLog(se::State& s)
|
||||
{
|
||||
cocos2d::GLProgram* cobj = (cocos2d::GLProgram*)s.nativeThisObject();
|
||||
SE_PRECONDITION2(cobj, false, "js_cocos2dx_GLProgram_getProgramLog : Invalid Native Object");
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 0) {
|
||||
std::string result = cobj->getProgramLog();
|
||||
ok &= std_string_to_seval(result, &s.rval());
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_GLProgram_getProgramLog : Error processing arguments");
|
||||
return true;
|
||||
}
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_GLProgram_getProgramLog)
|
||||
|
||||
static bool js_cocos2dx_GLProgram_getAttribLocation(se::State& s)
|
||||
{
|
||||
cocos2d::GLProgram* cobj = (cocos2d::GLProgram*)s.nativeThisObject();
|
||||
@@ -32058,96 +32299,105 @@ static bool js_cocos2dx_GLProgram_getAttribLocation(se::State& s)
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_GLProgram_getAttribLocation)
|
||||
|
||||
static bool js_cocos2dx_GLProgram_setUniformLocationWith2f(se::State& s)
|
||||
static bool js_cocos2dx_GLProgram_getUniformLocation(se::State& s)
|
||||
{
|
||||
cocos2d::GLProgram* cobj = (cocos2d::GLProgram*)s.nativeThisObject();
|
||||
SE_PRECONDITION2(cobj, false, "js_cocos2dx_GLProgram_setUniformLocationWith2f : Invalid Native Object");
|
||||
SE_PRECONDITION2(cobj, false, "js_cocos2dx_GLProgram_getUniformLocation : Invalid Native Object");
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 3) {
|
||||
int arg0 = 0;
|
||||
float arg1 = 0;
|
||||
float arg2 = 0;
|
||||
ok &= seval_to_int32(args[0], (int32_t*)&arg0);
|
||||
ok &= seval_to_float(args[1], &arg1);
|
||||
ok &= seval_to_float(args[2], &arg2);
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_GLProgram_setUniformLocationWith2f : Error processing arguments");
|
||||
cobj->setUniformLocationWith2f(arg0, arg1, arg2);
|
||||
if (argc == 1) {
|
||||
std::string arg0;
|
||||
ok &= seval_to_std_string(args[0], &arg0);
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_GLProgram_getUniformLocation : Error processing arguments");
|
||||
int result = cobj->getUniformLocation(arg0);
|
||||
ok &= int32_to_seval(result, &s.rval());
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_GLProgram_getUniformLocation : Error processing arguments");
|
||||
return true;
|
||||
}
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 3);
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_GLProgram_setUniformLocationWith2f)
|
||||
|
||||
static bool js_cocos2dx_GLProgram_setUniformLocationWith4i(se::State& s)
|
||||
{
|
||||
cocos2d::GLProgram* cobj = (cocos2d::GLProgram*)s.nativeThisObject();
|
||||
SE_PRECONDITION2(cobj, false, "js_cocos2dx_GLProgram_setUniformLocationWith4i : Invalid Native Object");
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 5) {
|
||||
int arg0 = 0;
|
||||
int arg1 = 0;
|
||||
int arg2 = 0;
|
||||
int arg3 = 0;
|
||||
int arg4 = 0;
|
||||
ok &= seval_to_int32(args[0], (int32_t*)&arg0);
|
||||
ok &= seval_to_int32(args[1], (int32_t*)&arg1);
|
||||
ok &= seval_to_int32(args[2], (int32_t*)&arg2);
|
||||
ok &= seval_to_int32(args[3], (int32_t*)&arg3);
|
||||
ok &= seval_to_int32(args[4], (int32_t*)&arg4);
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_GLProgram_setUniformLocationWith4i : Error processing arguments");
|
||||
cobj->setUniformLocationWith4i(arg0, arg1, arg2, arg3, arg4);
|
||||
return true;
|
||||
}
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 5);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_GLProgram_setUniformLocationWith4i)
|
||||
|
||||
static bool js_cocos2dx_GLProgram_setUniformLocationWith1i(se::State& s)
|
||||
{
|
||||
cocos2d::GLProgram* cobj = (cocos2d::GLProgram*)s.nativeThisObject();
|
||||
SE_PRECONDITION2(cobj, false, "js_cocos2dx_GLProgram_setUniformLocationWith1i : Invalid Native Object");
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 2) {
|
||||
int arg0 = 0;
|
||||
int arg1 = 0;
|
||||
ok &= seval_to_int32(args[0], (int32_t*)&arg0);
|
||||
ok &= seval_to_int32(args[1], (int32_t*)&arg1);
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_GLProgram_setUniformLocationWith1i : Error processing arguments");
|
||||
cobj->setUniformLocationWith1i(arg0, arg1);
|
||||
return true;
|
||||
}
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 2);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_GLProgram_setUniformLocationWith1i)
|
||||
SE_BIND_FUNC(js_cocos2dx_GLProgram_getUniformLocation)
|
||||
|
||||
static bool js_cocos2dx_GLProgram_setUniformLocationWith2i(se::State& s)
|
||||
{
|
||||
CC_UNUSED bool ok = true;
|
||||
cocos2d::GLProgram* cobj = (cocos2d::GLProgram*)s.nativeThisObject();
|
||||
SE_PRECONDITION2(cobj, false, "js_cocos2dx_GLProgram_setUniformLocationWith2i : Invalid Native Object");
|
||||
SE_PRECONDITION2( cobj, false, "js_cocos2dx_GLProgram_setUniformLocationWith2i : Invalid Native Object");
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 3) {
|
||||
int arg0 = 0;
|
||||
int arg1 = 0;
|
||||
int arg2 = 0;
|
||||
ok &= seval_to_int32(args[0], (int32_t*)&arg0);
|
||||
ok &= seval_to_int32(args[1], (int32_t*)&arg1);
|
||||
ok &= seval_to_int32(args[2], (int32_t*)&arg2);
|
||||
SE_PRECONDITION2(ok, false, "js_cocos2dx_GLProgram_setUniformLocationWith2i : Error processing arguments");
|
||||
cobj->setUniformLocationWith2i(arg0, arg1, arg2);
|
||||
return true;
|
||||
}
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 3);
|
||||
do {
|
||||
if (argc == 3) {
|
||||
int arg0 = 0;
|
||||
ok &= seval_to_int32(args[0], (int32_t*)&arg0);
|
||||
if (!ok) { ok = true; break; }
|
||||
int arg1 = 0;
|
||||
ok &= seval_to_int32(args[1], (int32_t*)&arg1);
|
||||
if (!ok) { ok = true; break; }
|
||||
int arg2 = 0;
|
||||
ok &= seval_to_int32(args[2], (int32_t*)&arg2);
|
||||
if (!ok) { ok = true; break; }
|
||||
cobj->setUniformLocationWith2i(arg0, arg1, arg2);
|
||||
return true;
|
||||
}
|
||||
} while(false);
|
||||
|
||||
do {
|
||||
if (argc == 2) {
|
||||
int arg0 = 0;
|
||||
ok &= seval_to_int32(args[0], (int32_t*)&arg0);
|
||||
if (!ok) { ok = true; break; }
|
||||
int arg1 = 0;
|
||||
ok &= seval_to_int32(args[1], (int32_t*)&arg1);
|
||||
if (!ok) { ok = true; break; }
|
||||
cobj->setUniformLocationWith1i(arg0, arg1);
|
||||
return true;
|
||||
}
|
||||
} while(false);
|
||||
|
||||
do {
|
||||
if (argc == 4) {
|
||||
int arg0 = 0;
|
||||
ok &= seval_to_int32(args[0], (int32_t*)&arg0);
|
||||
if (!ok) { ok = true; break; }
|
||||
int arg1 = 0;
|
||||
ok &= seval_to_int32(args[1], (int32_t*)&arg1);
|
||||
if (!ok) { ok = true; break; }
|
||||
int arg2 = 0;
|
||||
ok &= seval_to_int32(args[2], (int32_t*)&arg2);
|
||||
if (!ok) { ok = true; break; }
|
||||
int arg3 = 0;
|
||||
ok &= seval_to_int32(args[3], (int32_t*)&arg3);
|
||||
if (!ok) { ok = true; break; }
|
||||
cobj->setUniformLocationWith3i(arg0, arg1, arg2, arg3);
|
||||
return true;
|
||||
}
|
||||
} while(false);
|
||||
|
||||
do {
|
||||
if (argc == 5) {
|
||||
int arg0 = 0;
|
||||
ok &= seval_to_int32(args[0], (int32_t*)&arg0);
|
||||
if (!ok) { ok = true; break; }
|
||||
int arg1 = 0;
|
||||
ok &= seval_to_int32(args[1], (int32_t*)&arg1);
|
||||
if (!ok) { ok = true; break; }
|
||||
int arg2 = 0;
|
||||
ok &= seval_to_int32(args[2], (int32_t*)&arg2);
|
||||
if (!ok) { ok = true; break; }
|
||||
int arg3 = 0;
|
||||
ok &= seval_to_int32(args[3], (int32_t*)&arg3);
|
||||
if (!ok) { ok = true; break; }
|
||||
int arg4 = 0;
|
||||
ok &= seval_to_int32(args[4], (int32_t*)&arg4);
|
||||
if (!ok) { ok = true; break; }
|
||||
cobj->setUniformLocationWith4i(arg0, arg1, arg2, arg3, arg4);
|
||||
return true;
|
||||
}
|
||||
} while(false);
|
||||
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d", (int)argc);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(js_cocos2dx_GLProgram_setUniformLocationWith2i)
|
||||
@@ -32279,21 +32529,17 @@ bool js_register_cocos2dx_GLProgram(se::Object* obj)
|
||||
cls->defineFunction("getVertexShaderLog", _SE(js_cocos2dx_GLProgram_getVertexShaderLog));
|
||||
cls->defineFunction("getUniform", _SE(js_cocos2dx_GLProgram_getUniform));
|
||||
cls->defineFunction("initWithString", _SE(js_cocos2dx_GLProgram_initWithByteArrays));
|
||||
cls->defineFunction("setUniformLocationWith1f", _SE(js_cocos2dx_GLProgram_setUniformLocationWith1f));
|
||||
cls->defineFunction("getProgram", _SE(js_cocos2dx_GLProgram_getProgram));
|
||||
cls->defineFunction("setUniformLocationF32", _SE(js_cocos2dx_GLProgram_setUniformLocationWith2f));
|
||||
cls->defineFunction("init", _SE(js_cocos2dx_GLProgram_initWithFilenames));
|
||||
cls->defineFunction("setUniformLocationWith3f", _SE(js_cocos2dx_GLProgram_setUniformLocationWith3f));
|
||||
cls->defineFunction("setUniformsForBuiltins", _SE(js_cocos2dx_GLProgram_setUniformsForBuiltins));
|
||||
cls->defineFunction("setUniformLocationWith3i", _SE(js_cocos2dx_GLProgram_setUniformLocationWith3i));
|
||||
cls->defineFunction("setUniformLocationWith4f", _SE(js_cocos2dx_GLProgram_setUniformLocationWith4f));
|
||||
cls->defineFunction("updateUniforms", _SE(js_cocos2dx_GLProgram_updateUniforms));
|
||||
cls->defineFunction("getUniformLocation", _SE(js_cocos2dx_GLProgram_getUniformLocation));
|
||||
cls->defineFunction("link", _SE(js_cocos2dx_GLProgram_link));
|
||||
cls->defineFunction("reset", _SE(js_cocos2dx_GLProgram_reset));
|
||||
cls->defineFunction("getProgramLog", _SE(js_cocos2dx_GLProgram_getProgramLog));
|
||||
cls->defineFunction("getAttribLocation", _SE(js_cocos2dx_GLProgram_getAttribLocation));
|
||||
cls->defineFunction("setUniformLocationWith2f", _SE(js_cocos2dx_GLProgram_setUniformLocationWith2f));
|
||||
cls->defineFunction("setUniformLocationWith4i", _SE(js_cocos2dx_GLProgram_setUniformLocationWith4i));
|
||||
cls->defineFunction("setUniformLocationI32", _SE(js_cocos2dx_GLProgram_setUniformLocationWith1i));
|
||||
cls->defineFunction("setUniformLocationWith2i", _SE(js_cocos2dx_GLProgram_setUniformLocationWith2i));
|
||||
cls->defineFunction("getUniformLocation", _SE(js_cocos2dx_GLProgram_getUniformLocation));
|
||||
cls->defineFunction("setUniformLocationI32", _SE(js_cocos2dx_GLProgram_setUniformLocationWith2i));
|
||||
cls->defineFunction("ctor", _SE(js_cocos2dx_GLProgram_ctor));
|
||||
cls->defineStaticFunction("createWithByteArrays", _SE(js_cocos2dx_GLProgram_createWithByteArrays));
|
||||
cls->defineStaticFunction("createWithFilenames", _SE(js_cocos2dx_GLProgram_createWithFilenames));
|
||||
|
||||
@@ -24,6 +24,7 @@ SE_DECLARE_FUNC(js_cocos2dx_Texture2D_getMaxS);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_Texture2D_hasPremultipliedAlpha);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_Texture2D_getPixelsHigh);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_Texture2D_getAlphaTextureName);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_Texture2D_getName);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_Texture2D_initWithString);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_Texture2D_setMaxT);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_Texture2D_getPath);
|
||||
@@ -123,7 +124,6 @@ SE_DECLARE_FUNC(js_cocos2dx_Node_getDescription);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_Node_setOpacityModifyRGB);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_Node_setCascadeOpacityEnabled);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_Node_getChildren);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_Node_markTransformUpdated);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_Node_pause);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_Node_convertToWorldSpaceAR);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_Node_isIgnoreAnchorPointForPosition);
|
||||
@@ -239,6 +239,7 @@ SE_DECLARE_FUNC(js_cocos2dx_Node_getParentToNodeTransform);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_Node_convertToNodeSpace);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_Node_setTag);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_Node_isCascadeColorEnabled);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_Node_markCullingDirty);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_Node_stopAction);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_Node_getActionManager);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_Node_create);
|
||||
@@ -304,11 +305,13 @@ SE_DECLARE_FUNC(js_cocos2dx_Director_setContentScaleFactor);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_Director_getContentScaleFactor);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_Director_getWinSizeInPixels);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_Director_getDeltaTime);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_Director_isCullingEnabled);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_Director_setGLDefaultValues);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_Director_setActionManager);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_Director_setAlphaBlending);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_Director_popToRootScene);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_Director_loadMatrix);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_Director_setCullingEnabled);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_Director_getNotificationNode);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_Director_getWinSize);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_Director_end);
|
||||
@@ -2076,6 +2079,7 @@ SE_DECLARE_FUNC(js_cocos2dx_RenderTexture_isAutoDraw);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_RenderTexture_setKeepMatrix);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_RenderTexture_setClearFlags);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_RenderTexture_begin);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_RenderTexture_saveToFile);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_RenderTexture_setAutoDraw);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_RenderTexture_setClearColor);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_RenderTexture_beginWithClear);
|
||||
@@ -2101,20 +2105,16 @@ SE_DECLARE_FUNC(js_cocos2dx_GLProgram_use);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_GLProgram_getVertexShaderLog);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_GLProgram_getUniform);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_GLProgram_initWithByteArrays);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_GLProgram_setUniformLocationWith1f);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_GLProgram_getProgram);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_GLProgram_setUniformLocationWith2f);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_GLProgram_initWithFilenames);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_GLProgram_setUniformLocationWith3f);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_GLProgram_setUniformsForBuiltins);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_GLProgram_setUniformLocationWith3i);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_GLProgram_setUniformLocationWith4f);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_GLProgram_updateUniforms);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_GLProgram_getUniformLocation);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_GLProgram_link);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_GLProgram_reset);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_GLProgram_getProgramLog);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_GLProgram_getAttribLocation);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_GLProgram_setUniformLocationWith2f);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_GLProgram_setUniformLocationWith4i);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_GLProgram_setUniformLocationWith1i);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_GLProgram_getUniformLocation);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_GLProgram_setUniformLocationWith2i);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_GLProgram_createWithByteArrays);
|
||||
SE_DECLARE_FUNC(js_cocos2dx_GLProgram_createWithFilenames);
|
||||
|
||||
@@ -72,6 +72,25 @@ static bool js_creator_camera_CameraNode_getVisibleRect(se::State& s)
|
||||
}
|
||||
SE_BIND_FUNC(js_creator_camera_CameraNode_getVisibleRect)
|
||||
|
||||
static bool js_creator_camera_CameraNode_setEnable(se::State& s)
|
||||
{
|
||||
creator::CameraNode* cobj = (creator::CameraNode*)s.nativeThisObject();
|
||||
SE_PRECONDITION2(cobj, false, "js_creator_camera_CameraNode_setEnable : Invalid Native Object");
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
CC_UNUSED bool ok = true;
|
||||
if (argc == 1) {
|
||||
bool arg0;
|
||||
ok &= seval_to_boolean(args[0], &arg0);
|
||||
SE_PRECONDITION2(ok, false, "js_creator_camera_CameraNode_setEnable : Error processing arguments");
|
||||
cobj->setEnable(arg0);
|
||||
return true;
|
||||
}
|
||||
SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1);
|
||||
return false;
|
||||
}
|
||||
SE_BIND_FUNC(js_creator_camera_CameraNode_setEnable)
|
||||
|
||||
static bool js_creator_camera_CameraNode_containsNode(se::State& s)
|
||||
{
|
||||
creator::CameraNode* cobj = (creator::CameraNode*)s.nativeThisObject();
|
||||
@@ -163,6 +182,7 @@ bool js_register_creator_camera_CameraNode(se::Object* obj)
|
||||
cls->defineFunction("removeTarget", _SE(js_creator_camera_CameraNode_removeTarget));
|
||||
cls->defineFunction("setTransform", _SE(js_creator_camera_CameraNode_setTransform));
|
||||
cls->defineFunction("getVisibleRect", _SE(js_creator_camera_CameraNode_getVisibleRect));
|
||||
cls->defineFunction("setEnable", _SE(js_creator_camera_CameraNode_setEnable));
|
||||
cls->defineFunction("containsNode", _SE(js_creator_camera_CameraNode_containsNode));
|
||||
cls->defineFunction("addTarget", _SE(js_creator_camera_CameraNode_addTarget));
|
||||
cls->defineStaticFunction("getInstance", _SE(js_creator_camera_CameraNode_getInstance));
|
||||
|
||||
@@ -11,6 +11,7 @@ bool register_all_creator_camera(se::Object* obj);
|
||||
SE_DECLARE_FUNC(js_creator_camera_CameraNode_removeTarget);
|
||||
SE_DECLARE_FUNC(js_creator_camera_CameraNode_setTransform);
|
||||
SE_DECLARE_FUNC(js_creator_camera_CameraNode_getVisibleRect);
|
||||
SE_DECLARE_FUNC(js_creator_camera_CameraNode_setEnable);
|
||||
SE_DECLARE_FUNC(js_creator_camera_CameraNode_containsNode);
|
||||
SE_DECLARE_FUNC(js_creator_camera_CameraNode_addTarget);
|
||||
SE_DECLARE_FUNC(js_creator_camera_CameraNode_getInstance);
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,4 +1,4 @@
|
||||
# JSB2.0 绑定教程
|
||||
# JSB 2.0 绑定教程
|
||||
|
||||
## 抽象层
|
||||
|
||||
@@ -6,18 +6,18 @@
|
||||
|
||||

|
||||
|
||||
### 宏(macro)
|
||||
### 宏(Macro)
|
||||
|
||||
抽象层必然会比直接使用JS引擎API的方式多占用一些CPU执行时间,如何把抽象层本身的开销降到最低成为设计的第一目标。
|
||||
抽象层必然会比直接使用 JS 引擎 API 的方式多占用一些 CPU 执行时间,如何把抽象层本身的开销降到最低成为设计的第一目标。
|
||||
|
||||
JS绑定的大部分工作其实就是设定JS相关操作的CPP回调,在回调函数中关联CPP对象。其实主要包含如下两种类型:
|
||||
JS 绑定的大部分工作其实就是设定 JS 相关操作的 CPP 回调,在回调函数中关联 CPP 对象。其实主要包含如下两种类型:
|
||||
|
||||
* 注册JS函数(包含全局函数,类构造函数、类析构函数、类成员函数,类静态成员函数),绑定一个CPP回调
|
||||
* 注册JS对象的属性读写访问器,分别绑定读与写的CPP回调
|
||||
* 注册 JS 函数(包含全局函数,类构造函数、类析构函数、类成员函数,类静态成员函数),绑定一个 CPP 回调
|
||||
* 注册 JS 对象的属性读写访问器,分别绑定读与写的 CPP 回调
|
||||
|
||||
如何做到抽象层开销最小而且暴露统一的API供上层使用?
|
||||
如何做到抽象层开销最小而且暴露统一的 API 供上层使用?
|
||||
|
||||
以注册JS函数的回调定义为例,JavaScriptCore, SpiderMonkey, V8, ChakraCore的定义各不相同,具体如下:
|
||||
以注册 JS 函数的回调定义为例,JavaScriptCore,SpiderMonkey,V8,ChakraCore 的定义各不相同,具体如下:
|
||||
|
||||
**JavaScriptCore:**
|
||||
|
||||
@@ -62,7 +62,7 @@ JsValueRef JSB_foo_func(
|
||||
);
|
||||
```
|
||||
|
||||
我们评估了几种方案,最终确定使用`宏`来抹平不同JS引擎回调函数定义与参数类型的不同,不管底层是使用什么引擎,开发者统一使用一种回调函数的定义。我们借鉴了lua的回调函数定义方式,抽象层所有的JS到CPP的回调函数的定义为:
|
||||
我们评估了几种方案,最终确定使用`宏`来抹平不同 JS 引擎回调函数定义与参数类型的不同,不管底层是使用什么引擎,开发者统一使用一种回调函数的定义。我们借鉴了 lua 的回调函数定义方式,抽象层所有的 JS 到 CPP 的回调函数的定义为:
|
||||
|
||||
```c++
|
||||
bool foo(se::State& s)
|
||||
@@ -73,34 +73,34 @@ bool foo(se::State& s)
|
||||
SE_BIND_FUNC(foo) // 此处以回调函数的定义为例
|
||||
```
|
||||
|
||||
开发者编写完回调函数后,记住使用`SE_BIND_XXX`系列的宏对回调函数进行包装。目前提供了如下几个宏:
|
||||
开发者编写完回调函数后,记住使用 `SE_BIND_XXX` 系列的宏对回调函数进行包装。目前提供了如下几个宏:
|
||||
|
||||
* SE\_BIND\_PROP_GET: 包装一个JS对象属性读取的回调函数
|
||||
* SE\_BIND\_PROP_SET: 包装一个JS对象属性写入的回调函数
|
||||
* SE\_BIND_FUNC: 包装一个JS函数,可用于全局函数、类成员函数、类静态函数
|
||||
* SE\_DECLARE_FUNC: 声明一个JS函数,一般在.h头文件中使用
|
||||
* SE\_BIND_CTOR: 包装一个JS构造函数
|
||||
* SE\_BIND\_SUB\_CLS\_CTOR: 包装一个JS子类的构造函数,此子类使用cc.Class.extend继承Native绑定类
|
||||
* SE\_FINALIZE_FUNC: 包装一个JS对象被GC回收后的回调函数
|
||||
* SE\_DECLARE\_FINALIZE_FUNC: 声明一个JS对象被GC回收后的回调函数
|
||||
* _SE: 包装回调函数的名称,转义为每个JS引擎能够识别的回调函数的定义,注意,第一个字符为下划线,类似Windows下用的`_T("xxx")`来包装Unicode或者MultiBytes字符串
|
||||
* SE\_BIND\_PROP_GET:包装一个 JS 对象属性读取的回调函数
|
||||
* SE\_BIND\_PROP_SET:包装一个 JS 对象属性写入的回调函数
|
||||
* SE\_BIND_FUNC:包装一个 JS 函数,可用于全局函数、类成员函数、类静态函数
|
||||
* SE\_DECLARE_FUNC:声明一个 JS 函数,一般在 .h 头文件中使用
|
||||
* SE\_BIND_CTOR:包装一个 JS 构造函数
|
||||
* SE\_BIND\_SUB\_CLS\_CTOR:包装一个 JS 子类的构造函数,此子类使用 cc.Class.extend 继承 Native 绑定类
|
||||
* SE\_FINALIZE_FUNC:包装一个 JS 对象被 GC 回收后的回调函数
|
||||
* SE\_DECLARE\_FINALIZE_FUNC:声明一个 JS 对象被 GC 回收后的回调函数
|
||||
* _SE:包装回调函数的名称,转义为每个 JS 引擎能够识别的回调函数的定义,注意,第一个字符为下划线,类似 Windows 下用的`_T("xxx")`来包装 Unicode 或者 MultiBytes 字符串
|
||||
|
||||
## API
|
||||
|
||||
### CPP命名空间(namespace)
|
||||
### CPP 命名空间(namespace)
|
||||
|
||||
CPP抽象层所有的类型都在`se`命名空间下,其为ScriptEngine的缩写。
|
||||
CPP 抽象层所有的类型都在 `se` 命名空间下,其为 ScriptEngine 的缩写。
|
||||
|
||||
### 类型
|
||||
|
||||
#### se::ScriptEngine
|
||||
|
||||
se::ScriptEngine为JS引擎的管理员,掌管JS引擎初始化、销毁、重启、Native模块注册、加载脚本、强制垃圾回收、JS异常清理、是否启用调试器。
|
||||
它是一个单例,可通过se::ScriptEngine::getInstance()得到对应的实例。
|
||||
se::ScriptEngine 为 JS 引擎的管理员,掌管 JS 引擎初始化、销毁、重启、Native 模块注册、加载脚本、强制垃圾回收、JS 异常清理、是否启用调试器。
|
||||
它是一个单例,可通过 se::ScriptEngine::getInstance() 得到对应的实例。
|
||||
|
||||
#### se::Value
|
||||
|
||||
se::Value可以被理解为JS变量在CPP层的引用。JS变量有`object`, `number`, `string`, `boolean`, `null`, `undefined`六种类型,因此se::Value使用`union`包含`object`, `number`, `string`, `boolean`4种`有值类型`,`无值类型`: `null`, `undefined`可由`_type`直接表示。
|
||||
se::Value 可以被理解为 JS 变量在 CPP 层的引用。JS 变量有 `object`, `number`, `string`, `boolean`, `null`, `undefined` 六种类型,因此 se::Value 使用 `union` 包含 `object`, `number`, `string`, `boolean`4 种`有值类型`,`无值类型`: `null`, `undefined` 可由 `_type` 直接表示。
|
||||
|
||||
```c++
|
||||
namespace se {
|
||||
@@ -131,17 +131,17 @@ namespace se {
|
||||
}
|
||||
```
|
||||
|
||||
如果se::Value中保存基础数据类型,比如`number`,`string`,`boolean`,其内部是直接存储一份值副本。
|
||||
`object`的存储比较特殊,是通过`se::Object*`对JS对象的弱引用(weak reference)。
|
||||
如果 se::Value 中保存基础数据类型,比如 `number`,`string`,`boolean`,其内部是直接存储一份值副本。
|
||||
`object` 的存储比较特殊,是通过 `se::Object*` 对 JS 对象的弱引用(weak reference)。
|
||||
|
||||
#### se::Object
|
||||
|
||||
se::Object继承于se::RefCounter引用计数管理类。目前抽象层中只有se::Object继承于se::RefCounter。
|
||||
上一小节我们说到,se::Object是保存了对JS对象的弱引用,这里笔者有必要解释一下为什么是弱引用。
|
||||
se::Object 继承于 se::RefCounter 引用计数管理类。目前抽象层中只有 se::Object 继承于 se::RefCounter。
|
||||
上一小节我们说到,se::Object 是保存了对 JS 对象的弱引用,这里笔者有必要解释一下为什么是弱引用。
|
||||
|
||||
* 原因一:JS对象控制CPP对象的生命周期的需要
|
||||
* 原因一:JS 对象控制 CPP 对象的生命周期的需要
|
||||
|
||||
当在脚本层中通过`var sp = new cc.Sprite("a.png");`创建了一个Sprite后,在构造回调函数绑定中我们会创建一个se::Object并保留在一个全局的map(NativePtrToObjectMap)中,此map用于查询`cocos2d::Sprite*`指针获取对应的JS对象`se::Object*`。
|
||||
当在脚本层中通过 `var sp = new cc.Sprite("a.png");` 创建了一个 Sprite 后,在构造回调函数绑定中我们会创建一个 se::Object 并保留在一个全局的 map (NativePtrToObjectMap) 中,此 map 用于查询 `cocos2d::Sprite*` 指针获取对应的 JS 对象 `se::Object*` 。
|
||||
|
||||
```c++
|
||||
static bool js_cocos2d_Sprite_finalize(se::State& s)
|
||||
@@ -158,26 +158,26 @@ SE_BIND_FINALIZE_FUNC(js_cocos2d_Sprite_finalize)
|
||||
|
||||
static bool js_cocos2dx_Sprite_constructor(se::State& s)
|
||||
{
|
||||
cocos2d::Sprite* cobj = new (std::nothrow) cocos2d::Sprite(); // cobj将在finalize函数中被释放
|
||||
s.thisObject()->setPrivateData(cobj); // setPrivateData内部会去保存cobj到NativePtrToObjectMap中
|
||||
cocos2d::Sprite* cobj = new (std::nothrow) cocos2d::Sprite(); // cobj 将在 finalize 函数中被释放
|
||||
s.thisObject()->setPrivateData(cobj); // setPrivateData 内部会去保存 cobj 到 NativePtrToObjectMap 中
|
||||
return true;
|
||||
}
|
||||
SE_BIND_CTOR(js_cocos2dx_Sprite_constructor, __jsb_cocos2d_Sprite_class, js_cocos2d_Sprite_finalize)
|
||||
```
|
||||
|
||||
设想如果强制要求se::Object为JS对象的强引用(strong reference),即让JS对象不受GC控制,由于se::Object一直存在于map中,finalize回调将永远无法被触发,从而导致内存泄露。
|
||||
设想如果强制要求 se::Object 为 JS 对象的强引用(strong reference),即让 JS 对象不受 GC 控制,由于 se::Object 一直存在于 map 中,finalize 回调将永远无法被触发,从而导致内存泄露。
|
||||
|
||||
正是由于se::Object保存的是JS对象的弱引用,JS对象控制CPP对象的生命周期才能够实现。以上代码中,当JS对象被释放后,会触发finalize回调,开发者只需要在`js_cocos2d_Sprite_finalize`中释放对应的c++对象即可,se::Object的释放已经被包含在`SE_BIND_FINALIZE_FUNC`宏中自动处理,开发者无需管理在`JS对象控制CPP对象`模式中se::Object的释放,但是在`CPP对象控制JS对象`模式中,开发者需要管理对se::Object的释放,具体下一节中会举例说明。
|
||||
正是由于 se::Object 保存的是 JS 对象的弱引用,JS 对象控制 CPP 对象的生命周期才能够实现。以上代码中,当 JS 对象被释放后,会触发 finalize 回调,开发者只需要在 `js_cocos2d_Sprite_finalize` 中释放对应的 c++ 对象即可,se::Object 的释放已经被包含在 `SE_BIND_FINALIZE_FUNC` 宏中自动处理,开发者无需管理在`JS 对象控制 CPP 对象`模式中 se::Object 的释放,但是在 `CPP 对象控制 JS 对象` 模式中,开发者需要管理对 se::Object 的释放,具体下一节中会举例说明。
|
||||
|
||||
* 原因二:更加灵活,手动调用root方法以支持强引用
|
||||
* 原因二:更加灵活,手动调用 root 方法以支持强引用
|
||||
|
||||
se::Object中提供了root/unroot方法供开发者调用,root会把JS对象放入到不受GC扫描到的区域,调用root后,se::Object就强引用了JS对象,只有当unroot被调用,或者se::Object被释放后,JS对象才会放回到受GC扫描到的区域。
|
||||
se::Object 中提供了 root/unroot 方法供开发者调用,root 会把 JS 对象放入到不受 GC 扫描到的区域,调用 root 后,se::Object 就强引用了 JS 对象,只有当 unroot 被调用,或者 se::Object 被释放后,JS 对象才会放回到受 GC 扫描到的区域。
|
||||
|
||||
一般情况下,如果对象是非`cocos2d::Ref`的子类,会采用CPP对象控制JS对象的生命周期的方式去绑定。引擎内spine, dragonbones, box2d,anysdk等第三方库的绑定就是采用此方式。当CPP对象被释放的时候,需要在NativePtrToObjectMap中查找对应的se::Object,然后手动unroot和decRef。以spine中spTrackEntry的绑定为例:
|
||||
一般情况下,如果对象是非 `cocos2d::Ref` 的子类,会采用 CPP 对象控制 JS 对象的生命周期的方式去绑定。引擎内 spine, dragonbones, box2d,anysdk 等第三方库的绑定就是采用此方式。当 CPP 对象被释放的时候,需要在 NativePtrToObjectMap 中查找对应的 se::Object,然后手动 unroot 和 decRef。以 spine 中 spTrackEntry 的绑定为例:
|
||||
|
||||
```c++
|
||||
spTrackEntry_setDisposeCallback([](spTrackEntry* entry){
|
||||
// spTrackEntry的销毁回调
|
||||
// spTrackEntry 的销毁回调
|
||||
auto cleanup = [entry](){
|
||||
|
||||
if (!se::ScriptEngine::getInstance()->isValid())
|
||||
@@ -191,13 +191,13 @@ spTrackEntry_setDisposeCallback([](spTrackEntry* entry){
|
||||
{
|
||||
CCLOG("spTrackEntry %p was recycled!", entry);
|
||||
se::Object* seObj = iter->second;
|
||||
seObj->clearPrivateData(); // 解除mapping关系
|
||||
seObj->unroot(); // unroot,使JS对象受GC管理
|
||||
seObj->decRef(); // 释放se::Object
|
||||
seObj->clearPrivateData(); // 解除 mapping 关系
|
||||
seObj->unroot(); // unroot,使 JS 对象受 GC 管理
|
||||
seObj->decRef(); // 释放 se::Object
|
||||
}
|
||||
};
|
||||
|
||||
// 确保不再垃圾回收中去操作JS引擎的API
|
||||
// 确保不再垃圾回收中去操作 JS 引擎的 API
|
||||
if (!se::ScriptEngine::getInstance()->isGarbageCollecting())
|
||||
{
|
||||
cleanup();
|
||||
@@ -212,18 +212,18 @@ spTrackEntry_setDisposeCallback([](spTrackEntry* entry){
|
||||
|
||||
__对象类型__
|
||||
|
||||
绑定对象的创建已经被隐藏在对应的`SE_BIND_CTOR`和`SE_BIND_SUB_CLS_CTOR`函数中,开发者在绑定回调中如果需要用到当前对象对应的se::Object,只需要通过s.thisObject()即可获取。其中s为se::State类型,具体会在后续章节中说明。
|
||||
绑定对象的创建已经被隐藏在对应的 `SE_BIND_CTOR` 和 `SE_BIND_SUB_CLS_CTOR` 函数中,开发者在绑定回调中如果需要用到当前对象对应的 se::Object,只需要通过 s.thisObject() 即可获取。其中 s 为 se::State 类型,具体会在后续章节中说明。
|
||||
|
||||
此外,se::Object目前支持以下几种对象的手动创建:
|
||||
此外,se::Object 目前支持以下几种对象的手动创建:
|
||||
|
||||
* Plain Object : 通过se::Object::createPlainObject创建, 类似JS中的`var a = {};`
|
||||
* Array Object : 通过se::Object::createArrayObject创建,类似JS中的`var a = [];`
|
||||
* Uint8 Typed Array Object : 通过se::Object::createUint8TypedArray创建,类似JS中的`var a = new Uint8Array(buffer);`
|
||||
* Array Buffer Object : 通过se::Object::createArrayBufferObject,类似JS中的`var a = new ArrayBuffer(len);`
|
||||
* Plain Object : 通过 se::Object::createPlainObject 创建,类似 JS 中的 `var a = {};`
|
||||
* Array Object : 通过 se::Object::createArrayObject 创建,类似 JS 中的 `var a = [];`
|
||||
* Uint8 Typed Array Object : 通过 se::Object::createUint8TypedArray 创建,类似 JS 中的 `var a = new Uint8Array(buffer);`
|
||||
* Array Buffer Object : 通过 se::Object::createArrayBufferObject,类似 JS 中的 `var a = new ArrayBuffer(len);`
|
||||
|
||||
__手动创建对象的释放__
|
||||
|
||||
se::Object::createXXX方法与cocos2d-x中的create方法不同,抽象层是完全独立的一个模块,并不依赖与cocos2d-x的autorelease机制。虽然se::Object也是继承引用计数类,但开发者需要处理**手动创建出来的对象**的释放。
|
||||
se::Object::createXXX 方法与 cocos2d-x 中的 create 方法不同,抽象层是完全独立的一个模块,并不依赖与 cocos2d-x 的 autorelease 机制。虽然 se::Object 也是继承引用计数类,但开发者需要处理**手动创建出来的对象**的释放。
|
||||
|
||||
```c++
|
||||
se::Object* obj = se::Object::createPlainObject();
|
||||
@@ -232,19 +232,19 @@ se::Object* obj = se::Object::createPlainObject();
|
||||
obj->decRef(); // 释放引用,避免内存泄露
|
||||
```
|
||||
|
||||
#### se::HandleObject (推荐的管理手动创建对象的辅助类)
|
||||
#### se::HandleObject (推荐的管理手动创建对象的辅助类)
|
||||
|
||||
* 在比较复杂的逻辑中使用手动创建对象,开发者往往会忘记在不同的逻辑中处理decRef
|
||||
* 在比较复杂的逻辑中使用手动创建对象,开发者往往会忘记在不同的逻辑中处理 decRef
|
||||
|
||||
```c++
|
||||
bool foo()
|
||||
{
|
||||
se::Object* obj = se::Object::createPlainObject();
|
||||
if (var1)
|
||||
return false; // 这里直接返回了,忘记做decRef释放操作
|
||||
return false; // 这里直接返回了,忘记做 decRef 释放操作
|
||||
|
||||
if (var2)
|
||||
return false; // 这里直接返回了,忘记做decRef释放操作
|
||||
return false; // 这里直接返回了,忘记做 decRef 释放操作
|
||||
...
|
||||
...
|
||||
obj->decRef();
|
||||
@@ -252,14 +252,14 @@ bool foo()
|
||||
}
|
||||
```
|
||||
|
||||
就算在不同的返回条件分支中加上了decRef也会导致逻辑复杂,难以维护,如果后期加入另外一个返回分支,很容易忘记decRef。
|
||||
就算在不同的返回条件分支中加上了 decRef 也会导致逻辑复杂,难以维护,如果后期加入另外一个返回分支,很容易忘记 decRef。
|
||||
|
||||
* JS引擎在se::Object::createXXX后,如果由于某种原因JS引擎做了GC操作,导致后续使用的se::Object内部引用了一个非法指针,引发程序崩溃
|
||||
* JS 引擎在 se::Object::createXXX 后,如果由于某种原因 JS 引擎做了 GC 操作,导致后续使用的 se::Object 内部引用了一个非法指针,引发程序崩溃
|
||||
|
||||
为了解决上述两个问题,抽象层定义了一个辅助管理**手动创建对象**的类型,即`se::HandleObject`。
|
||||
为了解决上述两个问题,抽象层定义了一个辅助管理**手动创建对象**的类型,即 `se::HandleObject` 。
|
||||
|
||||
`se::HandleObject`是一个辅助类,用于更加简单地管理手动创建的se::Object对象的释放、root和unroot操作。
|
||||
以下两种代码写法是等价的,使用se::HandleObject的代码量明显少很多,而且更加安全。
|
||||
`se::HandleObject` 是一个辅助类,用于更加简单地管理手动创建的 se::Object 对象的释放、root 和 unroot 操作。
|
||||
以下两种代码写法是等价的,使用 se::HandleObject 的代码量明显少很多,而且更加安全。
|
||||
|
||||
```c++
|
||||
{
|
||||
@@ -272,52 +272,52 @@ bool foo()
|
||||
|
||||
{
|
||||
se::Object* obj = se::Object::createPlainObject();
|
||||
obj->root(); // 在手动创建完对象后立马root,防止对象被GC
|
||||
obj->root(); // 在手动创建完对象后立马 root,防止对象被 GC
|
||||
|
||||
obj->setProperty(...);
|
||||
otherObject->setProperty("foo", se::Value(obj));
|
||||
|
||||
obj->unroot(); // 当对象被使用完后,调用unroot
|
||||
obj->unroot(); // 当对象被使用完后,调用 unroot
|
||||
obj->decRef(); // 引用计数减一,避免内存泄露
|
||||
}
|
||||
```
|
||||
|
||||
注意:
|
||||
|
||||
* 不要尝试使用se::HandleObject创建一个native与JS的绑定对象,在JS控制CPP的模式中,绑定对象的释放会被抽象层自动处理,在CPP控制JS的模式中,前一章节中已经有描述了。
|
||||
* se::HandleObject对象只能够在栈上被分配,而且栈上构造的时候必须传入一个se::Object指针。
|
||||
* 不要尝试使用 se::HandleObject 创建一个 native 与 JS 的绑定对象,在 JS 控制 CPP 的模式中,绑定对象的释放会被抽象层自动处理,在 CPP 控制 JS 的模式中,前一章节中已经有描述了。
|
||||
* se::HandleObject 对象只能够在栈上被分配,而且栈上构造的时候必须传入一个 se::Object 指针。
|
||||
|
||||
|
||||
#### se::Class
|
||||
|
||||
se::Class用于暴露CPP类到JS中,它会在JS中创建一个对应名称的constructor function。
|
||||
se::Class 用于暴露 CPP 类到 JS 中,它会在 JS 中创建一个对应名称的 constructor function。
|
||||
|
||||
它有如下方法:
|
||||
|
||||
* `static se::Class* create(className, obj, parentProto, ctor)`: 创建一个Class,注册成功后,在JS层中可以通过`var xxx = new SomeClass();`的方式创建一个对象
|
||||
* `bool defineFunction(name, func)`: 定义Class中的成员函数
|
||||
* `bool defineProperty(name, getter, setter)`: 定义Class属性读写器
|
||||
* `bool defineStaticFunction(name, func)`: 定义Class的静态成员函数,可通过SomeClass.foo()这种非new的方式访问,与类实例对象无关
|
||||
* `bool defineStaticProperty(name, getter, setter)`: 定义Class的静态属性读写器,可通过SomeClass.propertyA直接读写,与类实例对象无关
|
||||
* `bool defineFinalizeFunction(func)`: 定义JS对象被GC后的CPP回调
|
||||
* `bool install()`: 注册此类到JS虚拟机中
|
||||
* `Object* getProto()`: 获取注册到JS中的类(其实是JS的constructor)的prototype对象,类似function Foo(){}的Foo.prototype
|
||||
* `const char* getName() const`: 获取当前Class的名称
|
||||
* `static se::Class* create(className, obj, parentProto, ctor)`: 创建一个 Class,注册成功后,在 JS 层中可以通过`var xxx = new SomeClass();`的方式创建一个对象
|
||||
* `bool defineFunction(name, func)`: 定义 Class 中的成员函数
|
||||
* `bool defineProperty(name, getter, setter)`: 定义 Class 属性读写器
|
||||
* `bool defineStaticFunction(name, func)`: 定义 Class 的静态成员函数,可通过 SomeClass.foo() 这种非 new 的方式访问,与类实例对象无关
|
||||
* `bool defineStaticProperty(name, getter, setter)`: 定义 Class 的静态属性读写器,可通过 SomeClass.propertyA 直接读写,与类实例对象无关
|
||||
* `bool defineFinalizeFunction(func)`: 定义 JS 对象被 GC 后的 CPP 回调
|
||||
* `bool install()`: 注册此类到 JS 虚拟机中
|
||||
* `Object* getProto()`: 获取注册到 JS 中的类(其实是 JS 的 constructor)的 prototype 对象,类似 function Foo(){}的 Foo.prototype
|
||||
* `const char* getName() const`: 获取当前 Class 的名称
|
||||
|
||||
**注意:**
|
||||
|
||||
Class类型创建后,不需要手动释放内存,它会被封装层自动处理。
|
||||
Class 类型创建后,不需要手动释放内存,它会被封装层自动处理。
|
||||
|
||||
更具体API说明可以翻看API文档或者代码注释
|
||||
更具体 API 说明可以翻看 API 文档或者代码注释
|
||||
|
||||
#### se::AutoHandleScope
|
||||
|
||||
se::AutoHandleScope对象类型完全是为了解决V8的兼容问题而引入的概念。
|
||||
V8中,当有CPP函数中需要触发JS相关操作,比如调用JS函数,访问JS属性等任何调用v8::Local<>的操作,V8强制要求在调用这些操作前必须存在一个v8::HandleScope作用域,否则会引发程序崩溃。
|
||||
se::AutoHandleScope 对象类型完全是为了解决 V8 的兼容问题而引入的概念。
|
||||
V8 中,当有 CPP 函数中需要触发 JS 相关操作,比如调用 JS 函数,访问 JS 属性等任何调用 v8::Local<> 的操作,V8 强制要求在调用这些操作前必须存在一个 v8::HandleScope 作用域,否则会引发程序崩溃。
|
||||
|
||||
因此抽象层中引入了se::AutoHandleScope的概念,其只在V8上有实现,其他JS引擎目前都只是空实现。
|
||||
因此抽象层中引入了 se::AutoHandleScope 的概念,其只在 V8 上有实现,其他 JS 引擎目前都只是空实现。
|
||||
|
||||
开发者需要记住,在任何代码执行中,需要调用JS的逻辑前,声明一个se::AutoHandleScope即可,比如:
|
||||
开发者需要记住,在任何代码执行中,需要调用 JS 的逻辑前,声明一个 se::AutoHandleScope 即可,比如:
|
||||
|
||||
```c++
|
||||
class SomeClass {
|
||||
@@ -336,14 +336,14 @@ class SomeClass {
|
||||
|
||||
#### se::State
|
||||
|
||||
之前章节我们有提及State类型,它是绑定回调中的一个环境,我们通过se::State可以取得当前的CPP指针、se::Object对象指针、参数列表、返回值引用。
|
||||
之前章节我们有提及 State 类型,它是绑定回调中的一个环境,我们通过 se::State 可以取得当前的 CPP 指针、se::Object 对象指针、参数列表、返回值引用。
|
||||
|
||||
```c++
|
||||
bool foo(se::State& s)
|
||||
{
|
||||
// 获取native对象指针
|
||||
// 获取 native 对象指针
|
||||
SomeClass* cobj = (SomeClass*)s.nativeThisObject();
|
||||
// 获取se::Object对象指针
|
||||
// 获取 se::Object 对象指针
|
||||
se::Object* thisObject = s.thisObject();
|
||||
// 获取参数列表
|
||||
const se::ValueArray& args = s.args();
|
||||
@@ -354,11 +354,11 @@ bool foo(se::State& s)
|
||||
SE_BIND_FUNC(foo)
|
||||
```
|
||||
|
||||
## 抽象层依赖Cocos引擎么?
|
||||
## 抽象层依赖 Cocos 引擎么?
|
||||
|
||||
不依赖。
|
||||
|
||||
ScriptEngine这层设计之初就将其定义为一个独立模块,完全不依赖Cocos引擎。开发者完整可以通过copy、paste把cocos/scripting/js-bindings/jswrapper下的所有抽象层源码拷贝到其他项目中直接使用。
|
||||
ScriptEngine 这层设计之初就将其定义为一个独立模块,完全不依赖 Cocos 引擎。开发者完整可以通过 copy、paste 把 cocos/scripting/js-bindings/jswrapper 下的所有抽象层源码拷贝到其他项目中直接使用。
|
||||
|
||||
## 手动绑定
|
||||
|
||||
@@ -370,7 +370,7 @@ static bool Foo_balabala(se::State& s)
|
||||
const auto& args = s.args();
|
||||
int argc = (int)args.size();
|
||||
|
||||
if (argc >= 2) // 这里约定参数个数必须大于等于2,否则抛出错误到JS层且返回false
|
||||
if (argc >= 2) // 这里约定参数个数必须大于等于 2,否则抛出错误到 JS 层且返回 false
|
||||
{
|
||||
...
|
||||
...
|
||||
@@ -381,27 +381,27 @@ static bool Foo_balabala(se::State& s)
|
||||
return false;
|
||||
}
|
||||
|
||||
// 如果是绑定函数,则用SE_BIND_FUNC,构造函数、析构函数、子类构造函数等类似
|
||||
// 如果是绑定函数,则用 SE_BIND_FUNC,构造函数、析构函数、子类构造函数等类似
|
||||
SE_BIND_FUNC(Foo_balabala)
|
||||
```
|
||||
|
||||
### 为JS对象设置一个属性值
|
||||
### 为 JS 对象设置一个属性值
|
||||
|
||||
```c++
|
||||
se::Object* globalObj = se::ScriptEngine::getInstance()->getGlobalObject(); // 这里为了演示方便,获取全局对象
|
||||
globalObj->setProperty("foo", se::Value(100)); // 给全局对象设置一个foo属性,值为100
|
||||
globalObj->setProperty("foo", se::Value(100)); // 给全局对象设置一个 foo 属性,值为 100
|
||||
```
|
||||
|
||||
在JS中就可以直接使用foo这个全局变量了
|
||||
在 JS 中就可以直接使用 foo 这个全局变量了
|
||||
|
||||
```js
|
||||
cc.log("foo value: " + foo); // 打印出 foo value: 100
|
||||
```
|
||||
|
||||
### 为JS对象定义一个属性读写回调
|
||||
### 为 JS 对象定义一个属性读写回调
|
||||
|
||||
```c++
|
||||
// 全局对象的foo属性的读回调
|
||||
// 全局对象的 foo 属性的读回调
|
||||
static bool Global_get_foo(se::State& s)
|
||||
{
|
||||
NativeObj* cobj = (NativeObj*)s.nativeThisObject();
|
||||
@@ -411,7 +411,7 @@ static bool Global_get_foo(se::State& s)
|
||||
}
|
||||
SE_BIND_PROP_GET(Global_get_foo)
|
||||
|
||||
// 全局对象的foo属性的写回调
|
||||
// 全局对象的 foo 属性的写回调
|
||||
static bool Global_set_foo(se::State& s)
|
||||
{
|
||||
const auto& args = s.args();
|
||||
@@ -421,7 +421,7 @@ static bool Global_set_foo(se::State& s)
|
||||
NativeObj* cobj = (NativeObj*)s.nativeThisObject();
|
||||
int32_t arg1 = args[0].toInt32();
|
||||
cobj->setValue(arg1);
|
||||
// void类型的函数,无需设置s.rval,未设置默认返回undefined给JS层
|
||||
// void 类型的函数,无需设置 s.rval,未设置默认返回 undefined 给 JS 层
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -433,11 +433,11 @@ SE_BIND_PROP_SET(Global_set_foo)
|
||||
void some_func()
|
||||
{
|
||||
se::Object* globalObj = se::ScriptEngine::getInstance()->getGlobalObject(); // 这里为了演示方便,获取全局对象
|
||||
globalObj->defineProperty("foo", _SE(Global_get_foo), _SE(Global_set_foo)); // 使用_SE宏包装一下具体的函数名称
|
||||
globalObj->defineProperty("foo", _SE(Global_get_foo), _SE(Global_set_foo)); // 使用_SE 宏包装一下具体的函数名称
|
||||
}
|
||||
```
|
||||
|
||||
### 为JS对象设置一个函数
|
||||
### 为 JS 对象设置一个函数
|
||||
|
||||
```c++
|
||||
static bool Foo_function(se::State& s)
|
||||
@@ -450,12 +450,12 @@ SE_BIND_FUNC(Foo_function)
|
||||
void some_func()
|
||||
{
|
||||
se::Object* globalObj = se::ScriptEngine::getInstance()->getGlobalObject(); // 这里为了演示方便,获取全局对象
|
||||
globalObj->defineFunction("foo", _SE(Foo_function)); // 使用_SE宏包装一下具体的函数名称
|
||||
globalObj->defineFunction("foo", _SE(Foo_function)); // 使用_SE 宏包装一下具体的函数名称
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
### 注册一个CPP类到JS虚拟机中
|
||||
### 注册一个 CPP 类到 JS 虚拟机中
|
||||
|
||||
```c++
|
||||
static se::Object* __jsb_ns_SomeClass_proto = nullptr;
|
||||
@@ -557,39 +557,39 @@ SE_BIND_FUNC(js_SomeClass_static_func)
|
||||
|
||||
bool js_register_ns_SomeClass(se::Object* global)
|
||||
{
|
||||
// 保证namespace对象存在
|
||||
// 保证 namespace 对象存在
|
||||
se::Value nsVal;
|
||||
if (!global->getProperty("ns", &nsVal))
|
||||
{
|
||||
// 不存在则创建一个JS对象,相当于 var ns = {};
|
||||
// 不存在则创建一个 JS 对象,相当于 var ns = {};
|
||||
se::HandleObject jsobj(se::Object::createPlainObject());
|
||||
nsVal.setObject(jsobj);
|
||||
|
||||
// 将ns对象挂载到global对象中,名称为ns
|
||||
// 将 ns 对象挂载到 global 对象中,名称为 ns
|
||||
global->setProperty("ns", nsVal);
|
||||
}
|
||||
se::Object* ns = nsVal.toObject();
|
||||
|
||||
// 创建一个Class对象,开发者无需考虑Class对象的释放,其交由ScriptEngine内部自动处理
|
||||
auto cls = se::Class::create("SomeClass", ns, nullptr, _SE(js_SomeClass_constructor)); // 如果无构造函数,最后一个参数可传入nullptr,则这个类在JS中无法被new SomeClass()出来
|
||||
// 创建一个 Class 对象,开发者无需考虑 Class 对象的释放,其交由 ScriptEngine 内部自动处理
|
||||
auto cls = se::Class::create("SomeClass", ns, nullptr, _SE(js_SomeClass_constructor)); // 如果无构造函数,最后一个参数可传入 nullptr,则这个类在 JS 中无法被 new SomeClass()出来
|
||||
|
||||
// 为这个Class对象定义成员函数、属性、静态函数、析构函数
|
||||
// 为这个 Class 对象定义成员函数、属性、静态函数、析构函数
|
||||
cls->defineFunction("foo", _SE(js_SomeClass_foo));
|
||||
cls->defineProperty("xxx", _SE(js_SomeClass_get_xxx), _SE(js_SomeClass_set_xxx));
|
||||
|
||||
cls->defineFinalizeFunction(_SE(js_SomeClass_finalize));
|
||||
|
||||
// 注册类型到JS VirtualMachine的操作
|
||||
// 注册类型到 JS VirtualMachine 的操作
|
||||
cls->install();
|
||||
|
||||
// JSBClassType为Cocos引擎绑定层封装的类型注册的辅助函数,此函数不属于ScriptEngine这层
|
||||
// JSBClassType 为 Cocos 引擎绑定层封装的类型注册的辅助函数,此函数不属于 ScriptEngine 这层
|
||||
JSBClassType::registerClass<ns::SomeClass>(cls);
|
||||
|
||||
// 保存注册的结果,便于其他地方使用,比如类继承
|
||||
__jsb_ns_SomeClass_proto = cls->getProto();
|
||||
__jsb_ns_SomeClass_class = cls;
|
||||
|
||||
// 为每个此Class实例化出来的对象附加一个属性
|
||||
// 为每个此 Class 实例化出来的对象附加一个属性
|
||||
__jsb_ns_SomeClass_proto->setProperty("yyy", se::Value("helloyyy"));
|
||||
|
||||
// 注册静态成员变量和静态成员函数
|
||||
@@ -606,7 +606,7 @@ bool js_register_ns_SomeClass(se::Object* global)
|
||||
}
|
||||
```
|
||||
|
||||
### 如何绑定CPP接口中的回调函数?
|
||||
### 如何绑定 CPP 接口中的回调函数?
|
||||
|
||||
```c++
|
||||
static bool js_SomeClass_setCallback(se::State& s)
|
||||
@@ -628,21 +628,21 @@ static bool js_SomeClass_setCallback(se::State& s)
|
||||
{
|
||||
assert(jsFunc.isObject() && jsFunc.toObject()->isFunction());
|
||||
|
||||
// 如果当前SomeClass是可以被new出来的类,我们 使用se::Object::attachObject把jsFunc和jsTarget关联到当前对象中
|
||||
// 如果当前 SomeClass 是可以被 new 出来的类,我们 使用 se::Object::attachObject 把 jsFunc 和 jsTarget 关联到当前对象中
|
||||
s.thisObject()->attachObject(jsFunc.toObject());
|
||||
s.thisObject()->attachObject(jsTarget.toObject());
|
||||
|
||||
// 如果当前SomeClass类是一个单例类,或者永远只有一个实例的类,我们不能用se::Object::attachObject去关联
|
||||
// 必须使用se::Object::root,开发者无需关系unroot,unroot的操作会随着lambda的销毁触发jsFunc的析构,在se::Object的析构函数中进行unroot操作。
|
||||
// js_cocos2dx_EventDispatcher_addCustomEventListener的绑定代码就是使用此方式,因为EventDispatcher始终只有一个实例,
|
||||
// 如果使用s.thisObject->attachObject(jsFunc.toObject);会导致对应的func和target永远无法被释放,引发内存泄露。
|
||||
// 如果当前 SomeClass 类是一个单例类,或者永远只有一个实例的类,我们不能用 se::Object::attachObject 去关联
|
||||
// 必须使用 se::Object::root,开发者无需关系 unroot,unroot 的操作会随着 lambda 的销毁触发 jsFunc 的析构,在 se::Object 的析构函数中进行 unroot 操作。
|
||||
// js_cocos2dx_EventDispatcher_addCustomEventListener 的绑定代码就是使用此方式,因为 EventDispatcher 始终只有一个实例,
|
||||
// 如果使用 s.thisObject->attachObject(jsFunc.toObject);会导致对应的 func 和 target 永远无法被释放,引发内存泄露。
|
||||
|
||||
// jsFunc.toObject()->root();
|
||||
// jsTarget.toObject()->root();
|
||||
|
||||
cobj->setCallback([jsFunc, jsTarget](int counter){
|
||||
|
||||
// CPP回调函数中要传递数据给JS或者调用JS函数,在回调函数开始需要添加如下两行代码。
|
||||
// CPP 回调函数中要传递数据给 JS 或者调用 JS 函数,在回调函数开始需要添加如下两行代码。
|
||||
se::ScriptEngine::getInstance()->clearException();
|
||||
se::AutoHandleScope hs;
|
||||
|
||||
@@ -663,7 +663,7 @@ static bool js_SomeClass_setCallback(se::State& s)
|
||||
SE_BIND_FUNC(js_SomeClass_setCallback)
|
||||
```
|
||||
|
||||
SomeClass类注册后,就可以在JS中这样使用了:
|
||||
SomeClass 类注册后,就可以在 JS 中这样使用了:
|
||||
|
||||
```js
|
||||
var myObj = new ns.SomeClass();
|
||||
@@ -692,10 +692,10 @@ SomeClass类注册后,就可以在JS中这样使用了:
|
||||
|
||||
setTimeout(function(){
|
||||
myObj.setCallback(null);
|
||||
}, 6000); // 6秒后清空callback
|
||||
}, 6000); // 6 秒后清空 callback
|
||||
```
|
||||
|
||||
Console中会输出:
|
||||
Console 中会输出:
|
||||
|
||||
```
|
||||
SomeClass::foo
|
||||
@@ -714,11 +714,11 @@ Delegate obj, onCallback: 6, this.myVar: 105
|
||||
setCallback(nullptr)
|
||||
```
|
||||
|
||||
### 如何使用cocos2d-x bindings这层的类型转换辅助函数?
|
||||
### 如何使用 cocos2d-x bindings 这层的类型转换辅助函数?
|
||||
|
||||
类型转换辅助函数位于`cocos/scripting/js-bindings/manual/jsb_conversions.hpp/.cpp`中,其包含:
|
||||
|
||||
#### se::Value转换为C++类型
|
||||
#### se::Value 转换为 C++ 类型
|
||||
```
|
||||
bool seval_to_int32(const se::Value& v, int32_t* ret);
|
||||
bool seval_to_uint32(const se::Value& v, uint32_t* ret);
|
||||
@@ -779,7 +779,7 @@ bool seval_to_Map_string_key(const se::Value& v, cocos2d::Map<std::string, T>* r
|
||||
|
||||
```
|
||||
|
||||
#### C++类型转换为se::Value
|
||||
#### C++ 类型转换为 se::Value
|
||||
|
||||
```c++
|
||||
bool int8_to_seval(int8_t v, se::Value* ret);
|
||||
@@ -871,8 +871,8 @@ bool b2AABB_to_seval(const b2AABB& v, se::Value* ret);
|
||||
|
||||
```
|
||||
|
||||
辅助转换函数不属于`Script Engine Wrapper`抽象层,属于cocos2d-x绑定层,封装这些函数是为了在绑定代码中更加方便的转换。
|
||||
每个转换函数都返回`bool`类型,表示转换是否成功,开发者如果调用这些接口,需要去判断这个返回值。
|
||||
辅助转换函数不属于`Script Engine Wrapper`抽象层,属于 cocos2d-x 绑定层,封装这些函数是为了在绑定代码中更加方便的转换。
|
||||
每个转换函数都返回 `bool` 类型,表示转换是否成功,开发者如果调用这些接口,需要去判断这个返回值。
|
||||
|
||||
以上接口,直接根据接口名称即可知道具体的用法,接口中第一个参数为输入,第二个参数为输出参数。用法如下:
|
||||
|
||||
@@ -886,27 +886,27 @@ int32_t v;
|
||||
bool ok = seval_to_int32(args[0], &v); // 第二个参数为输出参数,传入输出参数的地址
|
||||
```
|
||||
|
||||
#### (IMPORTANT)理解native\_ptr\_to\_seval与native\_ptr\_to\_rooted\_seval的区别
|
||||
#### (IMPORTANT)理解 native\_ptr\_to\_seval 与 native\_ptr\_to\_rooted\_seval 的区别
|
||||
|
||||
**开发者一定要理解清楚这二者的区别,才不会因为误用导致JS层内存泄露这种比较难查的bug。**
|
||||
**开发者一定要理解清楚这二者的区别,才不会因为误用导致 JS 层内存泄露这种比较难查的 bug。**
|
||||
|
||||
* `native_ptr_to_seval`用于`JS控制CPP对象生命周期`的模式。当在绑定层需要根据一个CPP对象指针获取一个se::Value的时候,可调用此方法。引擎内大部分继承于`cocos2d::Ref`的子类都采取这种方式去获取se::Value。记住一点,当你管理的绑定对象是由JS控制生命周期,需要转换为seval的时候,请用此方法,否则考虑用`native_ptr_to_rooted_seval`。
|
||||
* `native_ptr_to_rooted_seval`用于`CPP控制JS对象生命周期`的模式。一般而言,第三方库中的对象绑定都会用到此方法。此方法会根据传入的CPP对象指针查找cache住的se::Object,如果不存在,则创建一个rooted的se::Object,即这个创建出来的JS对象将不受GC控制,并永远在内存中。开发者需要监听CPP对象的释放,并在释放的时候去做se::Object的unroot操作,具体可参照前面章节中描述的spTrackEntry_setDisposeCallback中的内容。
|
||||
* `native_ptr_to_seval` 用于 `JS 控制 CPP 对象生命周期` 的模式。当在绑定层需要根据一个 CPP 对象指针获取一个 se::Value 的时候,可调用此方法。引擎内大部分继承于 `cocos2d::Ref` 的子类都采取这种方式去获取 se::Value。记住一点,当你管理的绑定对象是由 JS 控制生命周期,需要转换为 seval 的时候,请用此方法,否则考虑用 `native_ptr_to_rooted_seval` 。
|
||||
* `native_ptr_to_rooted_seval`用于`CPP 控制 JS 对象生命周期`的模式。一般而言,第三方库中的对象绑定都会用到此方法。此方法会根据传入的 CPP 对象指针查找 cache 住的 se::Object,如果不存在,则创建一个 rooted 的 se::Object,即这个创建出来的 JS 对象将不受 GC 控制,并永远在内存中。开发者需要监听 CPP 对象的释放,并在释放的时候去做 se::Object 的 unroot 操作,具体可参照前面章节中描述的 spTrackEntry_setDisposeCallback 中的内容。
|
||||
|
||||
|
||||
## 自动绑定
|
||||
|
||||
### 配置模块ini文件
|
||||
### 配置模块 ini 文件
|
||||
|
||||
配置方法与1.6中的方法相同,主要注意的是:1.7中废弃了`script_control_cpp`,因为`script_control_cpp`字段会影响到整个模块,如果模块中需要绑定cocos2d::Ref子类和非cocos::Ref子类,原来的绑定配置则无法满足需求。1.7中取而代之的新字段为`classes_owned_by_cpp`,表示哪些类是需要由CPP来控制JS对象的生命周期。
|
||||
配置方法与 1.6 中的方法相同,主要注意的是:1.7 中废弃了 `script_control_cpp` ,因为 `script_control_cpp` 字段会影响到整个模块,如果模块中需要绑定 cocos2d::Ref 子类和非 cocos::Ref 子类,原来的绑定配置则无法满足需求。1.7 中取而代之的新字段为 `classes_owned_by_cpp` ,表示哪些类是需要由 CPP 来控制 JS 对象的生命周期。
|
||||
|
||||
1.7中另外加入的一个配置字段为`persistent_classes`, 用于表示哪些类是在游戏运行中一直存在的,比如:TextureCache SpriteFrameCache FileUtils EventDispatcher ActionManager Scheduler
|
||||
1.7 中另外加入的一个配置字段为 `persistent_classes` , 用于表示哪些类是在游戏运行中一直存在的,比如:TextureCache SpriteFrameCache FileUtils EventDispatcher ActionManager Scheduler
|
||||
|
||||
其他字段与1.6一致。
|
||||
其他字段与 1.6 一致。
|
||||
|
||||
具体可以参考引擎目录下的tools/tojs/cocos2dx.ini等ini配置。
|
||||
具体可以参考引擎目录下的 tools/tojs/cocos2dx.ini 等 ini 配置。
|
||||
|
||||
### 理解ini文件中每个字段的意义
|
||||
### 理解 ini 文件中每个字段的意义
|
||||
|
||||
```
|
||||
# 模块名称
|
||||
@@ -915,19 +915,19 @@ bool ok = seval_to_int32(args[0], &v); // 第二个参数为输出参数,传
|
||||
# 绑定回调函数的前缀,也是生成的自动绑定文件的前缀
|
||||
prefix = cocos2dx
|
||||
|
||||
# 绑定的类挂载在JS中的哪个对象中,类似命名空间
|
||||
# 绑定的类挂载在 JS 中的哪个对象中,类似命名空间
|
||||
target_namespace = cc
|
||||
|
||||
# 自动绑定工具基于Android编译环境,此处配置Android头文件搜索路径
|
||||
# 自动绑定工具基于 Android 编译环境,此处配置 Android 头文件搜索路径
|
||||
android_headers = -I%(androidndkdir)s/platforms/android-14/arch-arm/usr/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.8/libs/armeabi-v7a/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.8/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.9/libs/armeabi-v7a/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.9/include
|
||||
|
||||
# 配置Android编译参数
|
||||
# 配置 Android 编译参数
|
||||
android_flags = -D_SIZE_T_DEFINED_
|
||||
|
||||
# 配置clang头文件搜索路径
|
||||
# 配置 clang 头文件搜索路径
|
||||
clang_headers = -I%(clangllvmdir)s/%(clang_include)s
|
||||
|
||||
# 配置clang编译参数
|
||||
# 配置 clang 编译参数
|
||||
clang_flags = -nostdinc -x c++ -std=c++11 -U __SSE__
|
||||
|
||||
# 配置引擎的头文件搜索路径
|
||||
@@ -948,7 +948,7 @@ replace_headers=CCProtectedNode.h::2d/CCProtectedNode.h,CCAsyncTaskPool.h::base/
|
||||
# 需要绑定哪些类,可以使用正则表达式,以空格为间隔
|
||||
classes =
|
||||
|
||||
# 哪些类需要在JS层通过cc.Class.extend,以空格为间隔
|
||||
# 哪些类需要在 JS 层通过 cc.Class.extend,以空格为间隔
|
||||
classes_need_extend =
|
||||
|
||||
# 需要为哪些类绑定属性,以逗号为间隔
|
||||
@@ -973,19 +973,19 @@ classes_have_no_parents = Node Director SimpleAudioEngine FileUtils TMXMapInfo A
|
||||
# 配置哪些父类需要被忽略
|
||||
base_classes_to_skip = Ref Clonable
|
||||
|
||||
# 配置哪些类是抽象类,抽象类没有构造函数,即在js层无法通过var a = new SomeClass();的方式构造JS对象
|
||||
# 配置哪些类是抽象类,抽象类没有构造函数,即在 js 层无法通过 var a = new SomeClass();的方式构造 JS 对象
|
||||
abstract_classes = Director SpriteFrameCache Set SimpleAudioEngine
|
||||
|
||||
# 配置哪些类是始终以一个实例的方式存在的,游戏运行过程中不会被销毁
|
||||
persistent_classes = TextureCache SpriteFrameCache FileUtils EventDispatcher ActionManager Scheduler
|
||||
|
||||
# 配置哪些类是需要由CPP对象来控制JS对象生命周期的,未配置的类,默认采用JS控制CPP对象生命周期
|
||||
# 配置哪些类是需要由 CPP 对象来控制 JS 对象生命周期的,未配置的类,默认采用 JS 控制 CPP 对象生命周期
|
||||
classes_owned_by_cpp =
|
||||
```
|
||||
|
||||
## 远程调试与Profile
|
||||
## 远程调试与 Profile
|
||||
|
||||
默认远程调试和Profile是在debug模式中生效的,如果需要在release模式下也启用,需要手动修改cocos/scripting/js-bindings/jswrapper/config.hpp中的宏开关。
|
||||
默认远程调试和 Profile 是在 debug 模式中生效的,如果需要在 release 模式下也启用,需要手动修改 cocos/scripting/js-bindings/jswrapper/config.hpp 中的宏开关。
|
||||
|
||||
```c++
|
||||
#if defined(COCOS2D_DEBUG) && COCOS2D_DEBUG > 0
|
||||
@@ -1000,7 +1000,7 @@ classes_owned_by_cpp =
|
||||
改为:
|
||||
|
||||
```c++
|
||||
#if 1 // 这里改为1,强制启用调试
|
||||
#if 1 // 这里改为 1,强制启用调试
|
||||
#define SE_ENABLE_INSPECTOR 1
|
||||
#define SE_DEBUG 2
|
||||
#else
|
||||
@@ -1009,17 +1009,17 @@ classes_owned_by_cpp =
|
||||
#endif
|
||||
```
|
||||
|
||||
### Chrome远程调试V8
|
||||
### Chrome 远程调试 V8
|
||||
|
||||
#### Windows
|
||||
|
||||
* 编译、运行游戏(或在Creator中直接使用模拟器运行)
|
||||
* 用Chrome浏览器打开[chrome-devtools://devtools/bundled/inspector.html?v8only=true&ws=127.0.0.1:5086/00010002-0003-4004-8005-000600070008](chrome-devtools://devtools/bundled/inspector.html?v8only=true&ws=127.0.0.1:5086/00010002-0003-4004-8005-000600070008)
|
||||
* 编译、运行游戏(或在 Creator 中直接使用模拟器运行)
|
||||
* 用 Chrome 浏览器打开[chrome-devtools://devtools/bundled/inspector.html?v8only=true&ws=127.0.0.1:5086/00010002-0003-4004-8005-000600070008](chrome-devtools://devtools/bundled/inspector.html?v8only=true&ws=127.0.0.1:5086/00010002-0003-4004-8005-000600070008)
|
||||
|
||||
断点调试:
|
||||

|
||||
|
||||
抓取JS Heap
|
||||
抓取 JS Heap
|
||||

|
||||
|
||||
Profile
|
||||
@@ -1027,46 +1027,48 @@ Profile
|
||||
|
||||
#### Android
|
||||
|
||||
* 保证Android设备与PC或者Mac在同一个局域网中
|
||||
* 保证 Android 设备与 PC 或者 Mac 在同一个局域网中
|
||||
* 编译,运行游戏
|
||||
* 用Chrome浏览器打开[chrome-devtools://devtools/bundled/inspector.html?v8only=true&ws=xxx.xxx.xxx.xxx:5086/00010002-0003-4004-8005-000600070008](chrome-devtools://devtools/bundled/inspector.html?v8only=true&ws=xxx.xxx.xxx.xxx:5086/00010002-0003-4004-8005-000600070008), 其中`xxx.xxx.xxx.xxx`为局域网中Android设备的IP地址
|
||||
* 调试界面与Windows相同
|
||||
* 用 Chrome 浏览器打开[chrome-devtools://devtools/bundled/inspector.html?v8only=true&ws=xxx.xxx.xxx.xxx:5086/00010002-0003-4004-8005-000600070008](chrome-devtools://devtools/bundled/inspector.html?v8only=true&ws=xxx.xxx.xxx.xxx:5086/00010002-0003-4004-8005-000600070008), 其中 `xxx.xxx.xxx.xxx` 为局域网中 Android 设备的 IP 地址
|
||||
* 调试界面与 Windows 相同
|
||||
|
||||
|
||||
### Safari远程调试JavaScriptCore
|
||||
### Safari 远程调试 JavaScriptCore
|
||||
|
||||
#### macOS
|
||||
|
||||
1. 打开Mac上的Safari,偏好设置 -> 高级 -> 显示开发者选项
|
||||
2. 为Xcode工程添加entitlements文件,如果entitlements存在则跳过此步骤。如果不存在,则到工程的Capabilities设置中打开App Sandbox,然后再关闭,这时.entitlements文件会自动被添加进工程。,还需要确保Build Setting里面Code Signing Entitlemenets选项中包含entitlements文件。 
|
||||
3. 打开entitlements文件,添加com.apple.security.get-task-allow,值类型为Boolean,值为YES. 
|
||||
4. 编译、运行游戏
|
||||
5. 如果是直接在Creator的模拟器中运行,则可以跳过第2,3,4步骤
|
||||
6. Safari菜单中选择Develop -> 你的Mac设备名称 -> Cocos2d-x JSB 会自动打开Web Inspector页面,然后即可进行设置断点、Timeline profile、console等操作。  
|
||||
1. 打开 Mac 上的 Safari,偏好设置 -> 高级 -> 显示开发者选项
|
||||
2. 为 Xcode 工程添加 entitlements 文件,如果 entitlements 存在则跳过此步骤。如果不存在,则到工程的 Capabilities 设置中打开 App Sandbox,然后再关闭,这时 .entitlements 文件会自动被添加进工程。,还需要确保 Build Setting 里面 Code Signing Entitlemenets 选项中包含 entitlements 文件。 
|
||||
3. 打开 entitlements 文件,添加 com.apple.security.get-task-allow,值类型为 Boolean,值为 YES. 
|
||||
4. 签名 : General -> 选择你的 Mac 工程 -> Signing -> 选择你的开发者证书
|
||||
5. 编译、运行游戏
|
||||
6. 如果是直接在 Creator 的模拟器中运行,则可以跳过第 2,3,4,5 步骤
|
||||
7. Safari 菜单中选择 Develop -> 你的 Mac 设备名称 -> Cocos2d-x JSB 会自动打开 Web Inspector 页面,然后即可进行设置断点、Timeline profile、console 等操作。  
|
||||
|
||||
**注意**
|
||||
|
||||
如果开发者有修改引擎源码或者自己合并了一些Patch,需要重新编译模拟器,记得重新设置一下模拟器工程的证书。
|
||||
如果开发者有修改引擎源码或者自己合并了一些 Patch,需要重新编译模拟器,记得重新设置一下模拟器工程的证书。
|
||||
|
||||

|
||||
|
||||
然后再调用`gulp gen-simulator`生成模拟器。
|
||||
然后再调用 `gulp gen-simulator` 生成模拟器。
|
||||
|
||||
#### iOS
|
||||
|
||||
1. 先打开iPhone的设置 -> Safari -> 高级 -> Web检查器
|
||||
2. 为Xcode工程添加entitlements文件,如果entitlements存在则跳过此步骤。如果不存在,则到工程的Capabilities设置中打开App Sandbox,然后再关闭,这时.entitlements文件会自动被添加进工程。 (图示与macOS的第2步类似)
|
||||
3. 打开entitlements文件,添加com.apple.security.get-task-allow,值类型为Boolean,值为YES。(图示与macOS的第3步类似)
|
||||
4. 编译、运行游戏
|
||||
5. Safari菜单中选择Develop -> 你的iPhone设备名称 -> Cocos2d-x JSB 会自动打开Web Inspector页面,然后即可进行设置断点、Timeline profile、console等操作。(图示与macOS的第6步类似)
|
||||
1. 先打开 iPhone 的设置 -> Safari -> 高级 -> Web 检查器
|
||||
2. 为 Xcode 工程添加 entitlements 文件,如果 entitlements 存在则跳过此步骤。如果不存在,则到工程的 Capabilities 设置中打开 App Sandbox,然后再关闭,这时 .entitlements 文件会自动被添加进工程。 (图示与 macOS 的第 2 步类似)
|
||||
3. 打开 entitlements 文件,添加 com.apple.security.get-task-allow,值类型为 Boolean,值为 YES。(图示与 macOS 的第 3 步类似)
|
||||
4. 签名 : General -> 选择你的 iOS 工程 -> Signing -> 选择你的开发者证书
|
||||
5. 编译、运行游戏
|
||||
6. Safari 菜单中选择 Develop -> 你的 iPhone 设备名称 -> Cocos2d-x JSB 会自动打开 Web Inspector 页面,然后即可进行设置断点、Timeline profile、console 等操作。(图示与 macOS 的第 6 步类似)
|
||||
|
||||
## Q & A
|
||||
|
||||
### se::ScriptEngine与ScriptingCore的区别,为什么还要保留ScriptingCore?
|
||||
### se::ScriptEngine 与 ScriptingCore 的区别,为什么还要保留 ScriptingCore?
|
||||
|
||||
在1.7中,抽象层被设计为一个与引擎没有关系的独立模块,对JS引擎的管理从ScriptingCore被移动到了se::ScriptEngine类中,ScriptingCore被保留下来是希望通过它把引擎的一些事件传递给封装层,充当适配器的角色。
|
||||
在 1.7 中,抽象层被设计为一个与引擎没有关系的独立模块,对 JS 引擎的管理从 ScriptingCore 被移动到了 se::ScriptEngine 类中,ScriptingCore 被保留下来是希望通过它把引擎的一些事件传递给封装层,充当适配器的角色。
|
||||
|
||||
ScriptingCore只需要在AppDelegate中被使用一次即可, 之后的所有操作都只需要用到se::ScriptEngine。
|
||||
ScriptingCore 只需要在 AppDelegate 中被使用一次即可,之后的所有操作都只需要用到 se::ScriptEngine。
|
||||
|
||||
```c++
|
||||
bool AppDelegate::applicationDidFinishLaunching()
|
||||
@@ -1075,8 +1077,8 @@ bool AppDelegate::applicationDidFinishLaunching()
|
||||
...
|
||||
director->setAnimationInterval(1.0 / 60);
|
||||
|
||||
// 这两行把ScriptingCore这个适配器设置给引擎,用于传递引擎的一些事件,
|
||||
// 比如Node的onEnter, onExit, Action的update,JS对象的持有与解除持有
|
||||
// 这两行把 ScriptingCore 这个适配器设置给引擎,用于传递引擎的一些事件,
|
||||
// 比如 Node 的 onEnter, onExit, Action 的 update,JS 对象的持有与解除持有
|
||||
ScriptingCore* sc = ScriptingCore::getInstance();
|
||||
ScriptEngineManager::getInstance()->setScriptEngine(sc);
|
||||
|
||||
@@ -1085,34 +1087,34 @@ bool AppDelegate::applicationDidFinishLaunching()
|
||||
...
|
||||
}
|
||||
```
|
||||
### se::Object::root/unroot 与 se::Object::incRef/decRef的区别?
|
||||
### se::Object::root/unroot 与 se::Object::incRef/decRef 的区别?
|
||||
|
||||
root/unroot用于控制JS对象是否受GC控制,root表示不受GC控制,unroot则相反,表示交由GC控制,对一个se::Object来说,root和unroot可以被调用多次,se::Object内部有_rootCount变量用于表示root的次数。当unroot被调用,且_rootCount为0时,se::Object关联的JS对象将交由GC管理。还有一种情况,即如果se::Object的析构被触发了,如果_rootCount > 0,则强制把JS对象交由GC控制。
|
||||
root/unroot 用于控制 JS 对象是否受 GC 控制,root 表示不受 GC 控制,unroot 则相反,表示交由 GC 控制,对一个 se::Object 来说,root 和 unroot 可以被调用多次,se::Object 内部有_rootCount 变量用于表示 root 的次数。当 unroot 被调用,且_rootCount 为 0 时,se::Object 关联的 JS 对象将交由 GC 管理。还有一种情况,即如果 se::Object 的析构被触发了,如果_rootCount > 0,则强制把 JS 对象交由 GC 控制。
|
||||
|
||||
incRef/decRef用于控制se::Object这个`cpp`对象的生命周期,前面章节已经提及,建议用户使用se::HandleObject来控制`手动创建非绑定对象`的方式控制se::Object的生命周期。因此,一般情况下,开发者不需要接触到incRef/decRef。
|
||||
incRef/decRef 用于控制 se::Object 这个 `cpp` 对象的生命周期,前面章节已经提及,建议用户使用 se::HandleObject 来控制`手动创建非绑定对象`的方式控制 se::Object 的生命周期。因此,一般情况下,开发者不需要接触到 incRef/decRef。
|
||||
|
||||
|
||||
### 对象生命周期的关联与解除关联
|
||||
|
||||
se::Object::attachObject/dettachObject
|
||||
|
||||
`objA->attachObject(objB);`类似于JS中执行`objA.__nativeRefs[index] = objB`,只有当objA被GC后,objB才有可能被GC
|
||||
`objA->dettachObject(objB);`类似于JS中执行`delete objA.__nativeRefs[index];`,这样objB的生命周期就不受objA控制了
|
||||
`objA->attachObject(objB);`类似于 JS 中执行`objA.__nativeRefs[index] = objB`,只有当 objA 被 GC 后,objB 才有可能被 GC
|
||||
`objA->dettachObject(objB);`类似于 JS 中执行`delete objA.__nativeRefs[index];`,这样 objB 的生命周期就不受 objA 控制了
|
||||
|
||||
### cocos2d::Ref子类与非cocos2d::Ref子类JS/CPP对象生命周期管理有何不同?
|
||||
### cocos2d::Ref 子类与非 cocos2d::Ref 子类 JS/CPP 对象生命周期管理有何不同?
|
||||
|
||||
目前引擎中cocos2d::Ref子类的绑定采用JS对象控制CPP对象生命周期的方式,这样做的好处是,解决了一直以来被诟病的需要在JS层retain,release对象的烦恼。
|
||||
目前引擎中 cocos2d::Ref 子类的绑定采用 JS 对象控制 CPP 对象生命周期的方式,这样做的好处是,解决了一直以来被诟病的需要在 JS 层 retain,release 对象的烦恼。
|
||||
|
||||
非cocos2d::Ref子类采用CPP对象控制JS对象生命周期的方式。此方式要求,CPP对象销毁后需要通知绑定层去调用对应se::Object的clearPrivateData, unroot, decRef的方法。JS代码中一定要慎重操作对象,当有可能出现非法对象的逻辑中,使用cc.sys.isObjectValid来判断CPP对象是否被释放了。
|
||||
非 cocos2d::Ref 子类采用 CPP 对象控制 JS 对象生命周期的方式。此方式要求,CPP 对象销毁后需要通知绑定层去调用对应 se::Object 的 clearPrivateData, unroot, decRef 的方法。JS 代码中一定要慎重操作对象,当有可能出现非法对象的逻辑中,使用 cc.sys.isObjectValid 来判断 CPP 对象是否被释放了。
|
||||
|
||||
### 绑定cocos2d::Ref子类的析构函数需要注意的事项
|
||||
### 绑定 cocos2d::Ref 子类的析构函数需要注意的事项
|
||||
|
||||
如果在JS对象的finalize回调中调用任何JS引擎的API,可能导致崩溃。因为当前引擎正在进行垃圾回收的流程,无法被打断处理其他操作。
|
||||
finalize回调中是告诉CPP层是否对应的CPP对象的内存,不能在CPP对象的析构中又去操作JS引擎API。
|
||||
如果在 JS 对象的 finalize 回调中调用任何 JS 引擎的 API,可能导致崩溃。因为当前引擎正在进行垃圾回收的流程,无法被打断处理其他操作。
|
||||
finalize 回调中是告诉 CPP 层是否对应的 CPP 对象的内存,不能在 CPP 对象的析构中又去操作 JS 引擎 API。
|
||||
|
||||
那如果必须调用,应该如何处理?
|
||||
|
||||
cocos2d-x的绑定中,如果引用计数为1了,我们不使用release,而是使用autorelease延时CPP类的析构到帧结束去执行。
|
||||
cocos2d-x 的绑定中,如果引用计数为 1 了,我们不使用 release,而是使用 autorelease 延时 CPP 类的析构到帧结束去执行。
|
||||
|
||||
```c++
|
||||
static bool js_cocos2d_Sprite_finalize(se::State& s)
|
||||
@@ -1128,9 +1130,9 @@ static bool js_cocos2d_Sprite_finalize(se::State& s)
|
||||
SE_BIND_FINALIZE_FUNC(js_cocos2d_Sprite_finalize)
|
||||
```
|
||||
|
||||
### 请不要在栈(Stack)上分配cocos2d::Ref的子类对象
|
||||
### 请不要在栈(Stack)上分配 cocos2d::Ref 的子类对象
|
||||
|
||||
Ref的子类必须在堆(Heap)上分配,即通过`new`,然后通过`release`来释放。当JS对象的finalize回调函数中统一使用`autorelease`或`release`来释放。如果是在栈上的对象,reference count很有可能为0,而这时调用`release`,其内部会调用`delete`,从而导致程序崩溃。所以为了防止这个行为的出现,开发者可以在继承于cocos2d::Ref的绑定类中,标识析构函数为`protected`或者`private`,保证在编译阶段就能发现这个问题。
|
||||
Ref 的子类必须在堆(Heap)上分配,即通过 `new` ,然后通过 `release` 来释放。当 JS 对象的 finalize 回调函数中统一使用 `autorelease` 或 `release` 来释放。如果是在栈上的对象,reference count 很有可能为 0,而这时调用 `release` ,其内部会调用 `delete` ,从而导致程序崩溃。所以为了防止这个行为的出现,开发者可以在继承于 cocos2d::Ref 的绑定类中,标识析构函数为 `protected` 或者 `private` ,保证在编译阶段就能发现这个问题。
|
||||
|
||||
例如:
|
||||
|
||||
@@ -1160,7 +1162,7 @@ event->release();
|
||||
|
||||
### 如何监听脚本错误
|
||||
|
||||
在AppDelegate.cpp中通过se::ScriptEngine::getInstance()->setExceptionCallback(...)设置JS层异常回调。
|
||||
在 AppDelegate.cpp 中通过 se::ScriptEngine::getInstance()->setExceptionCallback(...)设置 JS 层异常回调。
|
||||
|
||||
```c++
|
||||
bool AppDelegate::applicationDidFinishLaunching()
|
||||
|
||||
@@ -1,11 +1,26 @@
|
||||
//
|
||||
// HandleObject.cpp
|
||||
// cocos2d_js_bindings
|
||||
//
|
||||
// Created by James Chen on 7/31/17.
|
||||
//
|
||||
//
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#include "HandleObject.hpp"
|
||||
#include "Object.hpp"
|
||||
|
||||
@@ -16,6 +31,8 @@ HandleObject::HandleObject(Object* obj)
|
||||
{
|
||||
if (_obj != nullptr)
|
||||
{
|
||||
// se::HandleObject could not be used for native binding object.
|
||||
assert(!_obj->_getClass());
|
||||
_obj->root();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#pragma once
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
@@ -1,11 +1,26 @@
|
||||
//
|
||||
// MappingUtils.cpp
|
||||
// cocos2d_js_bindings
|
||||
//
|
||||
// Created by James Chen on 8/17/17.
|
||||
//
|
||||
//
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#include "MappingUtils.hpp"
|
||||
|
||||
namespace se {
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#pragma once
|
||||
|
||||
#include <unordered_map>
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#pragma once
|
||||
|
||||
#include "config.hpp"
|
||||
|
||||
@@ -1,11 +1,26 @@
|
||||
//
|
||||
// Ref.cpp
|
||||
// cocos2d_js_bindings
|
||||
//
|
||||
// Created by James Chen on 4/27/17.
|
||||
//
|
||||
//
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#include "RefCounter.hpp"
|
||||
|
||||
namespace se {
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#pragma once
|
||||
|
||||
namespace se {
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#pragma once
|
||||
|
||||
#include "config.hpp"
|
||||
|
||||
@@ -1,11 +1,26 @@
|
||||
//
|
||||
// State.cpp
|
||||
// cocos2d_js_bindings
|
||||
//
|
||||
// Created by guanghui on 5/27/17.
|
||||
//
|
||||
//
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#include "State.hpp"
|
||||
#include "Object.hpp"
|
||||
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#pragma once
|
||||
|
||||
#include "Value.hpp"
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#include "Value.hpp"
|
||||
#include "Object.hpp"
|
||||
|
||||
@@ -496,14 +519,7 @@ namespace se {
|
||||
}
|
||||
else if (_type == Type::Object)
|
||||
{
|
||||
if (toObject()->isFunction())
|
||||
{
|
||||
ret = "[Object function]";
|
||||
}
|
||||
else
|
||||
{
|
||||
ret = "[Object object]";
|
||||
}
|
||||
ret = toObject()->toString();
|
||||
}
|
||||
else if (_type == Type::Null)
|
||||
{
|
||||
@@ -513,6 +529,10 @@ namespace se {
|
||||
{
|
||||
ret = "undefined";
|
||||
}
|
||||
else
|
||||
{
|
||||
assert(false);
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#pragma once
|
||||
|
||||
#include <vector>
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#pragma once
|
||||
|
||||
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#include "Class.hpp"
|
||||
|
||||
#if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_CHAKRACORE
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#pragma once
|
||||
|
||||
#include "../config.hpp"
|
||||
@@ -10,27 +33,88 @@ namespace se {
|
||||
|
||||
class Object;
|
||||
|
||||
/**
|
||||
* se::Class represents a definition of how to create a native binding object.
|
||||
*/
|
||||
class Class final
|
||||
{
|
||||
private:
|
||||
Class();
|
||||
~Class();
|
||||
public:
|
||||
|
||||
/**
|
||||
* @brief Creates a class used for creating relevant native binding objects.
|
||||
* @param[in] className A null-terminated UTF8 string containing the class's name.
|
||||
* @param[in] obj The object that current class proto object attaches to. Should not be nullptr.
|
||||
* @param[in] parentProto The parent proto object that current class inherits from. Passing nullptr means a new class has no parent.
|
||||
* @param[in] ctor A callback to invoke when your constructor is used in a 'new' expression. Pass nullptr to use the default object constructor.
|
||||
* @return A class instance used for creating relevant native binding objects.
|
||||
* @note Don't need to delete the pointer return by this method, it's managed internally.
|
||||
*/
|
||||
static Class* create(const std::string& className, Object* obj, Object* parentProto, JsNativeFunction ctor);
|
||||
|
||||
bool install();
|
||||
Object* getProto();
|
||||
|
||||
/**
|
||||
* @brief Defines a member function with a callback. Each objects created by class will have this function property.
|
||||
* @param[in] name A null-terminated UTF8 string containing the function name.
|
||||
* @param[in] func A callback to invoke when the property is called as a function.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool defineFunction(const char *name, JsNativeFunction func);
|
||||
|
||||
/**
|
||||
* @brief Defines a property with accessor callbacks. Each objects created by class will have this property.
|
||||
* @param[in] name A null-terminated UTF8 string containing the property name.
|
||||
* @param[in] getter A callback to invoke when the property is read.
|
||||
* @param[in] setter A callback to invoke when the property is set.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool defineProperty(const char *name, JsNativeFunction getter, JsNativeFunction setter);
|
||||
|
||||
/**
|
||||
* @brief Defines a static function with a callback. Only JavaScript constructor object will have this function.
|
||||
* @param[in] name A null-terminated UTF8 string containing the function name.
|
||||
* @param[in] func A callback to invoke when the constructor's property is called as a function.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool defineStaticFunction(const char *name, JsNativeFunction func);
|
||||
|
||||
/**
|
||||
* @brief Defines a static property with accessor callbacks. Only JavaScript constructor object will have this property.
|
||||
* @param[in] name A null-terminated UTF8 string containing the property name.
|
||||
* @param[in] getter A callback to invoke when the constructor's property is read.
|
||||
* @param[in] setter A callback to invoke when the constructor's property is set.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool defineStaticProperty(const char *name, JsNativeFunction getter, JsNativeFunction setter);
|
||||
|
||||
/**
|
||||
* @brief Defines the finalize function with a callback.
|
||||
* @param[in] func The callback to invoke when a JavaScript object is garbage collected.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool defineFinalizeFunction(JsFinalizeCallback func);
|
||||
|
||||
/**
|
||||
* @brief Installs class to JavaScript VM.
|
||||
* @return true if succeed, otherwise false.
|
||||
* @note After this method, an object could be created by `var foo = new Foo();`.
|
||||
*/
|
||||
bool install();
|
||||
|
||||
/**
|
||||
* @brief Gets the proto object of this class.
|
||||
* @return The proto object of this class.
|
||||
* @note Don't need to be released in user code.
|
||||
*/
|
||||
Object* getProto();
|
||||
|
||||
/**
|
||||
* @brief Gets the class name.
|
||||
* @return The class name.
|
||||
*/
|
||||
const char* getName() const { return _name.c_str(); }
|
||||
|
||||
private:
|
||||
Class();
|
||||
~Class();
|
||||
|
||||
bool init(const std::string& clsName, Object* obj, Object* parentProto, JsNativeFunction ctor);
|
||||
void destroy();
|
||||
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#pragma once
|
||||
|
||||
#include "../config.hpp"
|
||||
@@ -31,6 +54,9 @@
|
||||
void* nativeThisObject = se::internal::getPrivate(_argv[0]); \
|
||||
se::State state(nativeThisObject, args); \
|
||||
ret = funcName(state); \
|
||||
if (!ret) { \
|
||||
SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \
|
||||
} \
|
||||
se::internal::seToJsValue(state.rval(), &_jsRet); \
|
||||
return _jsRet; \
|
||||
}
|
||||
@@ -47,6 +73,9 @@
|
||||
se::Object* _thisObject = state.thisObject(); \
|
||||
if (_thisObject) _thisObject->_cleanup(nativeThisObject); \
|
||||
ret = funcName(state); \
|
||||
if (!ret) { \
|
||||
SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \
|
||||
} \
|
||||
SAFE_DEC_REF(_thisObject); \
|
||||
se->_setGarbageCollecting(false); \
|
||||
} \
|
||||
@@ -75,6 +104,10 @@
|
||||
_found = thisObject->getProperty("_ctor", &_property); \
|
||||
if (_found) _property.toObject()->call(args, thisObject); \
|
||||
} \
|
||||
else \
|
||||
{ \
|
||||
SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \
|
||||
} \
|
||||
return _jsRet; \
|
||||
}
|
||||
|
||||
@@ -98,6 +131,10 @@
|
||||
_found = thisObject->getProperty("_ctor", &_property); \
|
||||
if (_found) _property.toObject()->call(args, thisObject); \
|
||||
} \
|
||||
else \
|
||||
{ \
|
||||
SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \
|
||||
} \
|
||||
return _jsRet; \
|
||||
}
|
||||
|
||||
@@ -107,10 +144,13 @@
|
||||
{ \
|
||||
assert(_argc == 1); \
|
||||
JsValueRef _jsRet = JS_INVALID_REFERENCE; \
|
||||
SE_UNUSED bool ret = true; \
|
||||
bool ret = true; \
|
||||
void* nativeThisObject = se::internal::getPrivate(_argv[0]); \
|
||||
se::State state(nativeThisObject); \
|
||||
ret = funcName(state); \
|
||||
if (!ret) { \
|
||||
SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \
|
||||
} \
|
||||
se::internal::seToJsValue(state.rval(), &_jsRet); \
|
||||
return _jsRet; \
|
||||
}
|
||||
@@ -120,7 +160,7 @@
|
||||
JsValueRef funcName##Registry(JsValueRef _callee, bool _isConstructCall, JsValueRef* _argv, unsigned short _argc, void* _callbackState) \
|
||||
{ \
|
||||
assert(_argc == 2); \
|
||||
SE_UNUSED bool ret = true; \
|
||||
bool ret = true; \
|
||||
void* nativeThisObject = se::internal::getPrivate(_argv[0]); \
|
||||
se::Value data; \
|
||||
se::internal::jsToSeValue(_argv[1], &data); \
|
||||
@@ -128,6 +168,9 @@
|
||||
args.push_back(std::move(data)); \
|
||||
se::State state(nativeThisObject, args); \
|
||||
ret = funcName(state); \
|
||||
if (!ret) { \
|
||||
SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \
|
||||
} \
|
||||
return JS_INVALID_REFERENCE; \
|
||||
}
|
||||
|
||||
@@ -138,7 +181,7 @@
|
||||
#define SE_QUOTEME(x) SE_QUOTEME_(x)
|
||||
|
||||
//FIXME: implement this macro
|
||||
#define SE_REPORT_ERROR(fmt, ...) LOGD("ERROR (" __FILE__ ", " SE_QUOTEME(__LINE__) "): " fmt "\n", ##__VA_ARGS__)
|
||||
#define SE_REPORT_ERROR(fmt, ...) SE_LOGE("[ERROR] (" __FILE__ ", " SE_QUOTEME(__LINE__) "): " fmt "\n", ##__VA_ARGS__)
|
||||
|
||||
#if COCOS2D_DEBUG > 0
|
||||
|
||||
@@ -147,7 +190,7 @@
|
||||
{ \
|
||||
if (!(cond)) \
|
||||
{ \
|
||||
LOGD("ASSERT (" __FILE__ ", " SE_QUOTEME(__LINE__) "): " fmt "\n", ##__VA_ARGS__); \
|
||||
SE_LOGE("ASSERT (" __FILE__ ", " SE_QUOTEME(__LINE__) "): " fmt "\n", ##__VA_ARGS__); \
|
||||
assert(false); \
|
||||
} \
|
||||
} while(false)
|
||||
@@ -164,7 +207,7 @@
|
||||
JsErrorCode _errCode = cmd; \
|
||||
if (_errCode != JsNoError) \
|
||||
{ \
|
||||
LOGD("Error 0x%x at '%s, %s, %d'\n", \
|
||||
SE_LOGE("Error 0x%x at '%s, %s, %d'\n", \
|
||||
_errCode, #cmd, __FILE__, __LINE__); \
|
||||
assert(false); \
|
||||
} \
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#include "Object.hpp"
|
||||
|
||||
#if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_CHAKRACORE
|
||||
@@ -57,11 +80,64 @@ namespace se {
|
||||
return obj;
|
||||
}
|
||||
|
||||
Object* Object::createUint8TypedArray(uint8_t* data, size_t byteLength)
|
||||
Object* Object::createTypedArray(TypedArrayType type, void* data, size_t byteLength)
|
||||
{
|
||||
if (type == TypedArrayType::NONE)
|
||||
{
|
||||
SE_LOGE("Don't pass se::Object::TypedArrayType::NONE to createTypedArray API!");
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
if (type == TypedArrayType::UINT8_CLAMPED)
|
||||
{
|
||||
SE_LOGE("Doesn't support to create Uint8ClampedArray with Object::createTypedArray API!");
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
JsTypedArrayType typedArrayType;
|
||||
size_t elementLength = 0;
|
||||
|
||||
switch (type) {
|
||||
case TypedArrayType::INT8:
|
||||
typedArrayType = JsArrayTypeInt8;
|
||||
elementLength = byteLength;
|
||||
break;
|
||||
case TypedArrayType::INT16:
|
||||
typedArrayType = JsArrayTypeInt16;
|
||||
elementLength = byteLength / 2;
|
||||
break;
|
||||
case TypedArrayType::INT32:
|
||||
typedArrayType = JsArrayTypeInt32;
|
||||
elementLength = byteLength / 4;
|
||||
break;
|
||||
case TypedArrayType::UINT8:
|
||||
typedArrayType = JsArrayTypeUint8;
|
||||
elementLength = byteLength;
|
||||
break;
|
||||
case TypedArrayType::UINT16:
|
||||
typedArrayType = JsArrayTypeUint16;
|
||||
elementLength = byteLength / 2;
|
||||
break;
|
||||
case TypedArrayType::UINT32:
|
||||
typedArrayType = JsArrayTypeUint32;
|
||||
elementLength = byteLength / 4;
|
||||
break;
|
||||
case TypedArrayType::FLOAT32:
|
||||
typedArrayType = JsArrayTypeFloat32;
|
||||
elementLength = byteLength / 4;
|
||||
break;
|
||||
case TypedArrayType::FLOAT64:
|
||||
typedArrayType = JsArrayTypeFloat64;
|
||||
elementLength = byteLength / 8;
|
||||
break;
|
||||
default:
|
||||
assert(false); // Should never go here.
|
||||
break;
|
||||
}
|
||||
|
||||
Object* obj = nullptr;
|
||||
JsValueRef jsobj;
|
||||
_CHECK(JsCreateTypedArray(JsArrayTypeUint8, JS_INVALID_REFERENCE, 0, (unsigned int)byteLength, &jsobj));
|
||||
_CHECK(JsCreateTypedArray(typedArrayType, JS_INVALID_REFERENCE, 0, (unsigned int)elementLength, &jsobj));
|
||||
ChakraBytePtr buffer = nullptr;
|
||||
unsigned int bufferLength = 0;
|
||||
JsTypedArrayType arrType;
|
||||
@@ -75,6 +151,11 @@ namespace se {
|
||||
return obj;
|
||||
}
|
||||
|
||||
Object* Object::createUint8TypedArray(uint8_t* data, size_t dataCount)
|
||||
{
|
||||
return createTypedArray(TypedArrayType::UINT8, data, dataCount);
|
||||
}
|
||||
|
||||
Object* Object::createJSONObject(const std::string& jsonStr)
|
||||
{
|
||||
bool ok = false;
|
||||
@@ -179,7 +260,7 @@ namespace se {
|
||||
}
|
||||
else
|
||||
{
|
||||
LOGD("Object::_cleanup, ScriptEngine was initialized again, ignore cleanup work, oldVMId: %u, newVMId: %u\n", _currentVMId, se->getVMId());
|
||||
SE_LOGD("Object::_cleanup, ScriptEngine was initialized again, ignore cleanup work, oldVMId: %u, newVMId: %u\n", _currentVMId, se->getVMId());
|
||||
}
|
||||
|
||||
_isCleanup = true;
|
||||
@@ -455,8 +536,7 @@ namespace se {
|
||||
{
|
||||
if (isFunction())
|
||||
{
|
||||
std::string info;
|
||||
internal::forceConvertJsValueToStdString(_obj, &info);
|
||||
std::string info = toString();
|
||||
if (info.find("[native code]") != std::string::npos)
|
||||
{
|
||||
return true;
|
||||
@@ -475,6 +555,42 @@ namespace se {
|
||||
return false;
|
||||
}
|
||||
|
||||
Object::TypedArrayType Object::getTypedArrayType() const
|
||||
{
|
||||
TypedArrayType ret = TypedArrayType::NONE;
|
||||
if (!isTypedArray())
|
||||
return ret;
|
||||
|
||||
JsTypedArrayType type;
|
||||
JsValueRef arrayBuffer = JS_INVALID_REFERENCE;
|
||||
unsigned int byteOffset = 0;
|
||||
unsigned int byteLength = 0;
|
||||
|
||||
if (JsNoError == JsGetTypedArrayInfo(_obj, &type, &arrayBuffer, &byteOffset, &byteLength))
|
||||
{
|
||||
if (type == JsArrayTypeInt8)
|
||||
ret = TypedArrayType::INT8;
|
||||
else if (type == JsArrayTypeInt16)
|
||||
ret = TypedArrayType::INT16;
|
||||
else if (type == JsArrayTypeInt32)
|
||||
ret = TypedArrayType::INT32;
|
||||
else if (type == JsArrayTypeUint8)
|
||||
ret = TypedArrayType::UINT8;
|
||||
else if (type == JsArrayTypeUint8Clamped)
|
||||
ret = TypedArrayType::UINT8_CLAMPED;
|
||||
else if (type == JsArrayTypeUint16)
|
||||
ret = TypedArrayType::UINT16;
|
||||
else if (type == JsArrayTypeUint32)
|
||||
ret = TypedArrayType::UINT32;
|
||||
else if (type == JsArrayTypeFloat32)
|
||||
ret = TypedArrayType::FLOAT32;
|
||||
else if (type == JsArrayTypeFloat64)
|
||||
ret = TypedArrayType::FLOAT64;
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
bool Object::getTypedArrayData(uint8_t** ptr, size_t* length) const
|
||||
{
|
||||
assert(isTypedArray());
|
||||
@@ -595,7 +711,7 @@ namespace se {
|
||||
}
|
||||
else
|
||||
{
|
||||
LOGD("Object::unroot, ScriptEngine was initialized again, ignore cleanup work, oldVMId: %u, newVMId: %u\n", _currentVMId, se->getVMId());
|
||||
SE_LOGD("Object::unroot, ScriptEngine was initialized again, ignore cleanup work, oldVMId: %u, newVMId: %u\n", _currentVMId, se->getVMId());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -656,6 +772,24 @@ namespace se {
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string Object::toString() const
|
||||
{
|
||||
std::string ret;
|
||||
if (isFunction() || isArray() || isTypedArray())
|
||||
{
|
||||
internal::forceConvertJsValueToStdString(_obj, &ret);
|
||||
}
|
||||
else if (isArrayBuffer())
|
||||
{
|
||||
ret = "[object ArrayBuffer]";
|
||||
}
|
||||
else
|
||||
{
|
||||
ret = "[object Object]";
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
} // namespace se {
|
||||
|
||||
#endif // #if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_CHAKRACORE
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#pragma once
|
||||
|
||||
#include "../config.hpp"
|
||||
@@ -12,51 +35,323 @@ namespace se {
|
||||
|
||||
class Class;
|
||||
|
||||
/**
|
||||
* se::Object represents JavaScript Object.
|
||||
*/
|
||||
class Object final : public RefCounter
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief Creates a JavaScript Object like `{} or new Object()`.
|
||||
* @return A JavaScript Object, or nullptr if there is an error.
|
||||
* @note The return value (non-null) has to be released manually.
|
||||
*/
|
||||
static Object* createPlainObject();
|
||||
|
||||
/**
|
||||
* @brief Creates a JavaScript Array Object like `[] or new Array()`.
|
||||
* @param[in] length The initical length of array.
|
||||
* @return A JavaScript Array Object, or nullptr if there is an error.
|
||||
* @note The return value (non-null) has to be released manually.
|
||||
*/
|
||||
static Object* createArrayObject(size_t length);
|
||||
static Object* createUint8TypedArray(uint8_t* data, size_t byteLength);
|
||||
static Object* createArrayBufferObject(void* data, size_t byteLength);
|
||||
|
||||
/**
|
||||
* @brief Creates a JavaScript Typed Array Object with uint8 format from an existing pointer.
|
||||
* @param[in] bytes A pointer to the byte buffer to be used as the backing store of the Typed Array object.
|
||||
* @param[in] byteLength The number of bytes pointed to by the parameter bytes.
|
||||
* @return A JavaScript Typed Array Object whose backing store is the same as the one pointed data, or nullptr if there is an error.
|
||||
* @note The return value (non-null) has to be released manually.
|
||||
*/
|
||||
SE_DEPRECATED_ATTRIBUTE static Object* createUint8TypedArray(uint8_t* bytes, size_t byteLength);
|
||||
|
||||
enum class TypedArrayType
|
||||
{
|
||||
NONE,
|
||||
INT8,
|
||||
INT16,
|
||||
INT32,
|
||||
UINT8,
|
||||
UINT8_CLAMPED,
|
||||
UINT16,
|
||||
UINT32,
|
||||
FLOAT32,
|
||||
FLOAT64
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Creates a JavaScript Typed Array Object with specified format from an existing pointer.
|
||||
* @param[in] type The format of typed array.
|
||||
* @param[in] data A pointer to the byte buffer to be used as the backing store of the Typed Array object.
|
||||
* @param[in] byteLength The number of bytes pointed to by the parameter bytes.
|
||||
* @return A JavaScript Typed Array Object whose backing store is the same as the one pointed data, or nullptr if there is an error.
|
||||
* @note The return value (non-null) has to be released manually.
|
||||
*/
|
||||
static Object* createTypedArray(TypedArrayType type, void* data, size_t byteLength);
|
||||
|
||||
/**
|
||||
* @brief Creates a JavaScript Array Buffer object from an existing pointer.
|
||||
* @param[in] bytes A pointer to the byte buffer to be used as the backing store of the Typed Array object.
|
||||
* @param[in] byteLength The number of bytes pointed to by the parameter bytes.
|
||||
* @return A Array Buffer Object whose backing store is the same as the one pointed to data, or nullptr if there is an error.
|
||||
* @note The return value (non-null) has to be released manually.
|
||||
*/
|
||||
static Object* createArrayBufferObject(void* bytes, size_t byteLength);
|
||||
|
||||
/**
|
||||
* @brief Creates a JavaScript Object from a JSON formatted string.
|
||||
* @param[in] jsonStr The utf-8 string containing the JSON string to be parsed.
|
||||
* @return A JavaScript Object containing the parsed value, or nullptr if the input is invalid.
|
||||
* @note The return value (non-null) has to be released manually.
|
||||
*/
|
||||
static Object* createJSONObject(const std::string& jsonStr);
|
||||
static Object* getObjectWithPtr(void* ptr);
|
||||
|
||||
/**
|
||||
* @brief Creates a JavaScript Native Binding Object from an existing se::Class instance.
|
||||
* @param[in] cls The se::Class instance which stores native callback informations.
|
||||
* @return A JavaScript Native Binding Object, or nullptr if there is an error.
|
||||
* @note The return value (non-null) has to be released manually.
|
||||
*/
|
||||
static Object* createObjectWithClass(Class* cls);
|
||||
|
||||
bool getProperty(const char* name, Value* data);
|
||||
bool setProperty(const char* name, const Value& v);
|
||||
/**
|
||||
* @brief Gets a se::Object from an existing native object pointer.
|
||||
* @param[in] ptr The native object pointer associated with the se::Object
|
||||
* @return A JavaScript Native Binding Object, or nullptr if there is an error.
|
||||
* @note The return value (non-null) has to be released manually.
|
||||
*/
|
||||
static Object* getObjectWithPtr(void* ptr);
|
||||
|
||||
/**
|
||||
* @brief Gets a property from an object.
|
||||
* @param[in] name A utf-8 string containing the property's name.
|
||||
* @param[out] value The property's value if object has the property, otherwise the undefined value.
|
||||
* @return true if object has the property, otherwise false.
|
||||
*/
|
||||
bool getProperty(const char* name, Value* value);
|
||||
|
||||
/**
|
||||
* @brief Sets a property to an object.
|
||||
* @param[in] name A utf-8 string containing the property's name.
|
||||
* @param[in] value A value to be used as the property's value.
|
||||
* @return true if the property is set successfully, otherwise false.
|
||||
*/
|
||||
bool setProperty(const char* name, const Value& value);
|
||||
|
||||
/**
|
||||
* @brief Defines a property with native accessor callbacks for an object.
|
||||
* @param[in] name A utf-8 string containing the property's name.
|
||||
* @param[in] getter The native callback for getter.
|
||||
* @param[in] setter The native callback for setter.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool defineProperty(const char *name, JsNativeFunction getter, JsNativeFunction setter);
|
||||
|
||||
bool isFunction() const;
|
||||
bool call(const ValueArray& args, Object* thisObject, Value* rval = nullptr);
|
||||
|
||||
/**
|
||||
* @brief Defines a function with a native callback for an object.
|
||||
* @param[in] funcName A utf-8 string containing the function name.
|
||||
* @param[in] func The native callback triggered by JavaScript code.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool defineFunction(const char *funcName, JsNativeFunction func);
|
||||
|
||||
bool isTypedArray() const;
|
||||
bool getTypedArrayData(uint8_t** ptr, size_t* length) const;
|
||||
/**
|
||||
* @brief Tests whether an object can be called as a function.
|
||||
* @return true if object can be called as a function, otherwise false.
|
||||
*/
|
||||
bool isFunction() const;
|
||||
|
||||
/**
|
||||
* @brief Calls an object as a function.
|
||||
* @param[in] args A se::Value array of arguments to pass to the function. Pass se::EmptyValueArray if argumentCount is 0.
|
||||
* @param[in] thisObject The object to use as "this," or NULL to use the global object as "this."
|
||||
* @param[out] rval The se::Value that results from calling object as a function, passing nullptr if return value is ignored.
|
||||
* @return true if object is a function and there isn't any errors, otherwise false.
|
||||
*/
|
||||
bool call(const ValueArray& args, Object* thisObject, Value* rval = nullptr);
|
||||
|
||||
/**
|
||||
* @brief Tests whether an object is an array.
|
||||
* @return true if object is an array, otherwise false.
|
||||
*/
|
||||
bool isArray() const;
|
||||
|
||||
/**
|
||||
* @brief Gets array length of an array object.
|
||||
* @param[out] length The array length to be stored. It's set to 0 if there is an error.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool getArrayLength(uint32_t* length) const;
|
||||
|
||||
/**
|
||||
* @brief Gets an element from an array object by numeric index.
|
||||
* @param[in] index An integer value for index.
|
||||
* @param[out] data The se::Value to be stored for the element in certain index.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool getArrayElement(uint32_t index, Value* data) const;
|
||||
|
||||
/**
|
||||
* @brief Sets an element to an array object by numeric index.
|
||||
* @param[in] index An integer value for index.
|
||||
* @param[in] data The se::Value to be set to array with certain index.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool setArrayElement(uint32_t index, const Value& data);
|
||||
|
||||
/** @brief Tests whether an object is a typed array.
|
||||
* @return true if object is a typed array, otherwise false.
|
||||
*/
|
||||
bool isTypedArray() const;
|
||||
|
||||
/**
|
||||
* @brief Gets the type of a typed array object.
|
||||
* @return The type of a typed array object.
|
||||
*/
|
||||
TypedArrayType getTypedArrayType() const;
|
||||
|
||||
/**
|
||||
* @brief Gets backing store of a typed array object.
|
||||
* @param[out] ptr A temporary pointer to the backing store of a JavaScript Typed Array object.
|
||||
* @param[out] length The byte length of a JavaScript Typed Array object.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool getTypedArrayData(uint8_t** ptr, size_t* length) const;
|
||||
|
||||
/**
|
||||
* @brief Tests whether an object is an array buffer object.
|
||||
* @return true if object is an array buffer object, otherwise false.
|
||||
*/
|
||||
bool isArrayBuffer() const;
|
||||
|
||||
/**
|
||||
* @brief Gets buffer data of an array buffer object.
|
||||
* @param[out] ptr A pointer to the data buffer that serves as the backing store for a JavaScript Typed Array object.
|
||||
* @param[out] length The number of bytes in a JavaScript data object.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool getArrayBufferData(uint8_t** ptr, size_t* length) const;
|
||||
|
||||
/**
|
||||
* @brief Gets all property names of an object.
|
||||
* @param[out] allKeys A string vector to store all property names.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool getAllKeys(std::vector<std::string>* allKeys) const;
|
||||
|
||||
/**
|
||||
* @brief Sets a pointer to private data on an object.
|
||||
* @param[in] data A void* to set as the object's private data.
|
||||
* @note This method will associate private data with se::Object by std::unordered_map::emplace.
|
||||
* It's used for search a se::Object via a void* private data.
|
||||
*/
|
||||
void setPrivateData(void* data);
|
||||
|
||||
/**
|
||||
* @brief Gets an object's private data.
|
||||
* @return A void* that is the object's private data, if the object has private data, otherwise nullptr.
|
||||
*/
|
||||
void* getPrivateData() const;
|
||||
|
||||
/**
|
||||
* @brief Roots an object from garbage collection.
|
||||
* @note Use this method when you want to store an object in a global or on the heap, where the garbage collector will not be able to discover your reference to it.
|
||||
* An object may be rooted multiple times and must be unrooted an equal number of times before becoming eligible for garbage collection.
|
||||
*/
|
||||
void clearPrivateData();
|
||||
|
||||
/**
|
||||
* @brief Roots an object from garbage collection.
|
||||
* @note Use this method when you want to store an object in a global or on the heap, where the garbage collector will not be able to discover your reference to it.
|
||||
* An object may be rooted multiple times and must be unrooted an equal number of times before becoming eligible for garbage collection.
|
||||
*/
|
||||
void root();
|
||||
|
||||
/**
|
||||
* @brief Unroots an object from garbage collection.
|
||||
* @note An object may be rooted multiple times and must be unrooted an equal number of times before becoming eligible for garbage collection.
|
||||
*/
|
||||
void unroot();
|
||||
|
||||
/**
|
||||
* @brief Tests whether an object is rooted.
|
||||
* @return true if it has been already rooted, otherwise false.
|
||||
*/
|
||||
bool isRooted() const;
|
||||
|
||||
/**
|
||||
* @brief Tests whether two objects are strict equal, as compared by the JS === operator.
|
||||
* @param[in] o The object to be tested with this object.
|
||||
* @return true if the two values are strict equal, otherwise false.
|
||||
*/
|
||||
bool strictEquals(Object* obj) const;
|
||||
|
||||
/**
|
||||
* @brief Attaches an object to current object.
|
||||
* @param[in] obj The object to be attached.
|
||||
* @return true if succeed, otherwise false.
|
||||
* @note This method will set `obj` as a property of current object, therefore the lifecycle of child object will depend on current object,
|
||||
* which means `obj` may be garbage collected only after current object is garbage collected.
|
||||
* It's normally used in binding a native callback method. For example:
|
||||
|
||||
```javascript
|
||||
var self = this;
|
||||
someObject.setCallback(function(){}, self);
|
||||
```
|
||||
|
||||
```c++
|
||||
static bool SomeObject_setCallback(se::State& s)
|
||||
{
|
||||
SomeObject* cobj = (SomeObject*)s.nativeThisObject();
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
if (argc == 2) {
|
||||
std::function<void()> arg0;
|
||||
do {
|
||||
if (args[0].isObject() && args[0].toObject()->isFunction())
|
||||
{
|
||||
se::Value jsThis(args[1]);
|
||||
se::Value jsFunc(args[0]);
|
||||
|
||||
jsThis.toObject()->attachObject(jsFunc.toObject());
|
||||
|
||||
auto lambda = [=]() -> void {
|
||||
...
|
||||
// Call jsFunc stuff...
|
||||
...
|
||||
};
|
||||
arg0 = lambda;
|
||||
}
|
||||
else
|
||||
{
|
||||
arg0 = nullptr;
|
||||
}
|
||||
} while(false);
|
||||
SE_PRECONDITION2(ok, false, "Error processing arguments");
|
||||
cobj->setCallback(arg0);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
```
|
||||
*/
|
||||
bool attachObject(Object* obj);
|
||||
|
||||
/**
|
||||
* @brief Detaches an object from current object.
|
||||
* @param[in] obj The object to be detached.
|
||||
* @return true if succeed, otherwise false.
|
||||
* @note The attached object will not be released if current object is not garbage collected.
|
||||
*/
|
||||
bool detachObject(Object* obj);
|
||||
|
||||
/**
|
||||
* @brief Returns the string for describing current object.
|
||||
* @return The string for describing current object.
|
||||
*/
|
||||
std::string toString() const;
|
||||
|
||||
// Private API used in wrapper
|
||||
static Object* _createJSObject(Class* cls, JsValueRef obj);
|
||||
JsValueRef _getJSObject() const;
|
||||
@@ -65,7 +360,6 @@ namespace se {
|
||||
void _setFinalizeCallback(JsFinalizeCallback finalizeCb);
|
||||
bool _isNativeFunction() const;
|
||||
//
|
||||
|
||||
private:
|
||||
static void cleanup();
|
||||
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#include "ScriptEngine.hpp"
|
||||
|
||||
#if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_CHAKRACORE
|
||||
@@ -27,14 +50,14 @@ namespace se {
|
||||
{
|
||||
std::string str;
|
||||
internal::forceConvertJsValueToStdString(arguments[1], &str);
|
||||
LOGD("JS: %s\n", str.c_str());
|
||||
SE_LOGD("JS: %s\n", str.c_str());
|
||||
}
|
||||
return JS_INVALID_REFERENCE;
|
||||
}
|
||||
|
||||
void myJsBeforeCollectCallback(void *callbackState)
|
||||
{
|
||||
LOGD("GC start ...\n");
|
||||
SE_LOGD("GC start ...\n");
|
||||
}
|
||||
|
||||
JsValueRef privateDataContructor(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState)
|
||||
@@ -61,7 +84,7 @@ namespace se {
|
||||
if ((argc - msgIndex) == 1)
|
||||
{
|
||||
std::string msg = args[msgIndex].toStringForce();
|
||||
LOGD("JS: %s%s\n", prefix, msg.c_str());
|
||||
SE_LOGD("JS: %s%s\n", prefix, msg.c_str());
|
||||
}
|
||||
else if (argc > 1)
|
||||
{
|
||||
@@ -80,7 +103,7 @@ namespace se {
|
||||
}
|
||||
}
|
||||
|
||||
LOGD("JS: %s%s\n", prefix, msg.c_str());
|
||||
SE_LOGD("JS: %s%s\n", prefix, msg.c_str());
|
||||
}
|
||||
|
||||
return true;
|
||||
@@ -170,7 +193,7 @@ namespace se {
|
||||
bool ScriptEngine::init()
|
||||
{
|
||||
cleanup();
|
||||
LOGD("Initializing ChakraCore, version: %d.%d.%d\n", CHAKRA_CORE_MAJOR_VERSION, CHAKRA_CORE_MINOR_VERSION, CHAKRA_CORE_PATCH_VERSION);
|
||||
SE_LOGD("Initializing ChakraCore, version: %d.%d.%d\n", CHAKRA_CORE_MAJOR_VERSION, CHAKRA_CORE_MINOR_VERSION, CHAKRA_CORE_PATCH_VERSION);
|
||||
|
||||
++_vmId;
|
||||
for (const auto& hook : _beforeInitHookArray)
|
||||
@@ -289,7 +312,7 @@ namespace se {
|
||||
Value tmp;
|
||||
if (exceptionObj->getProperty(key.c_str(), &tmp))
|
||||
{
|
||||
// LOGD("[%s]=%s\n", key.c_str(), tmp.toStringForce().c_str());
|
||||
// SE_LOGD("[%s]=%s\n", key.c_str(), tmp.toStringForce().c_str());
|
||||
if (key == "message")
|
||||
{
|
||||
ret.message = tmp.toString();
|
||||
@@ -372,9 +395,9 @@ namespace se {
|
||||
|
||||
void ScriptEngine::garbageCollect()
|
||||
{
|
||||
LOGD("GC begin ..., (Native -> JS map) count: %d\n", (int)NativePtrToObjectMap::size());
|
||||
SE_LOGD("GC begin ..., (Native -> JS map) count: %d\n", (int)NativePtrToObjectMap::size());
|
||||
_CHECK(JsCollectGarbage(_rt));
|
||||
LOGD("GC end ..., (Native -> JS map) count: %d\n", (int)NativePtrToObjectMap::size());
|
||||
SE_LOGD("GC end ..., (Native -> JS map) count: %d\n", (int)NativePtrToObjectMap::size());
|
||||
}
|
||||
|
||||
void ScriptEngine::clearException()
|
||||
@@ -388,7 +411,7 @@ namespace se {
|
||||
_CHECK(JsGetAndClearException(&exception));
|
||||
|
||||
ExceptionInfo exceptionInfo = formatException(exception);
|
||||
LOGD("ERROR: %s, %s, \nSTACK:\n%s\n", exceptionInfo.message.c_str(), exceptionInfo.location.c_str(), exceptionInfo.stack.c_str());
|
||||
SE_LOGD("ERROR: %s, location: %s, \nSTACK:\n%s\n", exceptionInfo.message.c_str(), exceptionInfo.location.c_str(), exceptionInfo.stack.c_str());
|
||||
|
||||
if (_exceptionCallback != nullptr)
|
||||
{
|
||||
@@ -414,7 +437,7 @@ namespace se {
|
||||
}
|
||||
else
|
||||
{
|
||||
LOGE("ERROR: __errorHandler has exception\n");
|
||||
SE_LOGE("ERROR: __errorHandler has exception\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -483,46 +506,10 @@ namespace se {
|
||||
return evalString(scriptBuffer.c_str(), scriptBuffer.length(), ret, path.c_str());
|
||||
}
|
||||
|
||||
LOGE("ScriptEngine::runScript script buffer is empty!\n");
|
||||
SE_LOGE("ScriptEngine::runScript script buffer is empty!\n");
|
||||
return false;
|
||||
}
|
||||
|
||||
void ScriptEngine::_retainScriptObject(void* owner, void* target)
|
||||
{
|
||||
auto iterOwner = NativePtrToObjectMap::find(owner);
|
||||
if (iterOwner == NativePtrToObjectMap::end())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
auto iterTarget = NativePtrToObjectMap::find(target);
|
||||
if (iterTarget == NativePtrToObjectMap::end())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
clearException();
|
||||
iterOwner->second->attachObject(iterTarget->second);
|
||||
}
|
||||
|
||||
void ScriptEngine::_releaseScriptObject(void* owner, void* target)
|
||||
{
|
||||
auto iterOwner = NativePtrToObjectMap::find(owner);
|
||||
if (iterOwner == NativePtrToObjectMap::end())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
auto iterTarget = NativePtrToObjectMap::find(target);
|
||||
if (iterTarget == NativePtrToObjectMap::end())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
clearException();
|
||||
iterOwner->second->detachObject(iterTarget->second);
|
||||
}
|
||||
|
||||
void ScriptEngine::enableDebugger(const std::string& serverAddr, uint32_t port)
|
||||
{
|
||||
//FIXME:
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#pragma once
|
||||
|
||||
#include "../config.hpp"
|
||||
@@ -14,6 +37,12 @@ namespace se {
|
||||
|
||||
extern Class* __jsb_CCPrivateData_class;
|
||||
|
||||
/**
|
||||
* A stack-allocated class that governs a number of local handles.
|
||||
* It's only implemented for v8 wrapper now.
|
||||
* Other script engine wrappers have empty implementation for this class.
|
||||
* It's used at the beginning of executing any wrapper API.
|
||||
*/
|
||||
class AutoHandleScope
|
||||
{
|
||||
public:
|
||||
@@ -21,24 +50,51 @@ namespace se {
|
||||
~AutoHandleScope() {}
|
||||
};
|
||||
|
||||
/**
|
||||
* ScriptEngine is a sington which represents a context of JavaScript VM.
|
||||
*/
|
||||
class ScriptEngine final
|
||||
{
|
||||
private:
|
||||
ScriptEngine();
|
||||
~ScriptEngine();
|
||||
|
||||
public:
|
||||
/**
|
||||
* @brief Gets or creates the instance of script engine.
|
||||
* @return The script engine instance.
|
||||
*/
|
||||
static ScriptEngine* getInstance();
|
||||
|
||||
/**
|
||||
* @brief Destroys the instance of script engine.
|
||||
*/
|
||||
static void destroyInstance();
|
||||
|
||||
/**
|
||||
* @brief Gets the global object of JavaScript VM.
|
||||
* @return The se::Object stores the global JavaScript object.
|
||||
*/
|
||||
Object* getGlobalObject();
|
||||
|
||||
typedef bool (*RegisterCallback)(Object*);
|
||||
|
||||
/**
|
||||
* @brief Adds a callback for registering a native binding module.
|
||||
* @param[in] cb A callback for registering a native binding module.
|
||||
* @note This method just add a callback to a vector, callbacks is invoked in `start` method.
|
||||
*/
|
||||
void addRegisterCallback(RegisterCallback cb);
|
||||
|
||||
/**
|
||||
* @brief Starts the script engine.
|
||||
* @return true if succeed, otherwise false.
|
||||
* @note This method will invoke all callbacks of native binding modules by the order of registration.
|
||||
*/
|
||||
bool start();
|
||||
|
||||
/**
|
||||
* @brief Initializes script engine.
|
||||
* @return true if succeed, otherwise false.
|
||||
* @note This method will create JavaScript context and global object.
|
||||
*/
|
||||
bool init();
|
||||
void cleanup();
|
||||
|
||||
/**
|
||||
* @brief Adds a hook function before initializing script engine.
|
||||
@@ -54,10 +110,35 @@ namespace se {
|
||||
*/
|
||||
void addAfterInitHook(const std::function<void()>& hook);
|
||||
|
||||
/**
|
||||
* @brief Cleanups script engine.
|
||||
* @note This method will removes all objects in JavaScript VM even whose are rooted, then shutdown JavaScript VMf.
|
||||
*/
|
||||
void cleanup();
|
||||
|
||||
/**
|
||||
* @brief Adds a hook function before cleanuping script engine.
|
||||
* @param[in] hook A hook function to be invoked before cleanuping script engine.
|
||||
* @note Multiple hook functions could be added, they will be invoked by the order of adding.
|
||||
*/
|
||||
void addBeforeCleanupHook(const std::function<void()>& hook);
|
||||
|
||||
/**
|
||||
* @brief Adds a hook function after cleanuping script engine.
|
||||
* @param[in] hook A hook function to be invoked after cleanuping script engine.
|
||||
* @note Multiple hook functions could be added, they will be invoked by the order of adding.
|
||||
*/
|
||||
void addAfterCleanupHook(const std::function<void()>& hook);
|
||||
|
||||
bool evalString(const char* script, ssize_t length = -1, Value* ret = nullptr, const char* fileName = nullptr);
|
||||
/**
|
||||
* @brief Executes a utf-8 string buffer which contains JavaScript code.
|
||||
* @param[in] scriptStr A utf-8 string buffer, if it isn't null-terminated, parameter `length` should be assigned and > 0.
|
||||
* @param[in] length The length of parameter `scriptStr`, it will be set to string length internally if passing < 0 and parameter `scriptStr` is null-terminated.
|
||||
* @param[in] rval The se::Value that results from evaluating script. Passing nullptr if you don't care about the result.
|
||||
* @param[in] fileName A string containing a URL for the script's source file. This is used by debuggers and when reporting exceptions. Pass NULL if you do not care to include source file information.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool evalString(const char* scriptStr, ssize_t length = -1, Value* rval = nullptr, const char* fileName = nullptr);
|
||||
|
||||
/**
|
||||
* Delegate class for file operation
|
||||
@@ -103,32 +184,82 @@ namespace se {
|
||||
* @param[in] rval The se::Value that results from evaluating script. Passing nullptr if you don't care about the result.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool runScript(const std::string& path, Value* ret = nullptr);
|
||||
bool runScript(const std::string& path, Value* rval = nullptr);
|
||||
|
||||
/**
|
||||
* @brief Tests whether script engine is doing garbage collection.
|
||||
* @return true if it's in garbage collection, otherwise false.
|
||||
*/
|
||||
bool isGarbageCollecting();
|
||||
void _setGarbageCollecting(bool isGarbageCollecting);
|
||||
|
||||
/**
|
||||
* @brief Performs a JavaScript garbage collection.
|
||||
*/
|
||||
void garbageCollect();
|
||||
|
||||
bool isValid() { return _isValid; }
|
||||
/**
|
||||
* @brief Tests whether script engine is being cleaned up.
|
||||
* @return true if it's in cleaning up, otherwise false.
|
||||
*/
|
||||
bool isInCleanup() { return _isInCleanup; }
|
||||
|
||||
/**
|
||||
* @brief Tests whether script engine is valid.
|
||||
* @return true if it's valid, otherwise false.
|
||||
*/
|
||||
bool isValid() { return _isValid; }
|
||||
|
||||
/**
|
||||
* @brief Clears all exceptions.
|
||||
*/
|
||||
void clearException();
|
||||
|
||||
using ExceptionCallback = std::function<void(const char*, const char*, const char*)>; // location, message, stack
|
||||
|
||||
/**
|
||||
* @brief Sets the callback function while an exception is fired.
|
||||
* @param[in] cb The callback function to notify that an exception is fired.
|
||||
*/
|
||||
void setExceptionCallback(const ExceptionCallback& cb);
|
||||
|
||||
/**
|
||||
* @brief Gets the start time of script engine.
|
||||
* @return The start time of script engine.
|
||||
*/
|
||||
const std::chrono::steady_clock::time_point& getStartTime() const { return _startTime; }
|
||||
|
||||
/**
|
||||
* @brief Enables JavaScript debugger
|
||||
* @param[in] serverAddr The address of debugger server.
|
||||
* @param[in] port The port of debugger server will use.
|
||||
*/
|
||||
void enableDebugger(const std::string& serverAddr, uint32_t port);
|
||||
|
||||
/**
|
||||
* @brief Tests whether JavaScript debugger is enabled
|
||||
* @return true if JavaScript debugger is enabled, otherwise false.
|
||||
*/
|
||||
bool isDebuggerEnabled() const;
|
||||
|
||||
/**
|
||||
* @brief Main loop update trigger, it's need to invoked in main thread every frame.
|
||||
*/
|
||||
void mainLoopUpdate();
|
||||
|
||||
/**
|
||||
* @brief Gets script virtual machine instance ID. Default value is 1, increase by 1 if `init` is invoked.
|
||||
*/
|
||||
uint32_t getVMId() const { return _vmId; }
|
||||
|
||||
// Private API used in wrapper
|
||||
void _setGarbageCollecting(bool isGarbageCollecting);
|
||||
void _retainScriptObject(void* owner, void* target);
|
||||
void _releaseScriptObject(void* owner, void* target);
|
||||
|
||||
//
|
||||
private:
|
||||
ScriptEngine();
|
||||
~ScriptEngine();
|
||||
|
||||
struct ExceptionInfo
|
||||
{
|
||||
std::string location;
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#pragma once
|
||||
|
||||
#include "ScriptEngine.hpp"
|
||||
|
||||
@@ -1,11 +1,26 @@
|
||||
//
|
||||
// Utils.cpp
|
||||
// cocos2d_js_bindings
|
||||
//
|
||||
// Created by James Chen on 4/26/17.
|
||||
//
|
||||
//
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#include "Utils.hpp"
|
||||
|
||||
#if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_CHAKRACORE
|
||||
@@ -224,16 +239,21 @@ namespace se {
|
||||
}
|
||||
|
||||
assert(finalizeCb);
|
||||
HandleObject privateObj(Object::createObjectWithClass(__jsb_CCPrivateData_class));
|
||||
Object* privateObj = Object::createObjectWithClass(__jsb_CCPrivateData_class);
|
||||
privateObj->root();
|
||||
|
||||
internal::PrivateData* privateData = (internal::PrivateData*)malloc(sizeof(internal::PrivateData));
|
||||
privateData->data = data;
|
||||
privateData->finalizeCb = finalizeCb;
|
||||
_CHECK(JsSetExternalData(privateObj->_getJSObject(), privateData));
|
||||
// LOGD("setPrivate: %p\n", data);
|
||||
// SE_LOGD("setPrivate: %p\n", data);
|
||||
|
||||
JsPropertyIdRef propertyId = JS_INVALID_REFERENCE;
|
||||
JsCreatePropertyId(KEY_PRIVATE_DATA, strlen(KEY_PRIVATE_DATA), &propertyId);
|
||||
_CHECK(JsSetProperty(obj, propertyId, privateObj->_getJSObject(), true));
|
||||
|
||||
privateObj->unroot();
|
||||
privateObj->decRef();
|
||||
}
|
||||
|
||||
void* getPrivate(JsValueRef obj)
|
||||
@@ -270,7 +290,7 @@ namespace se {
|
||||
assert(privateData);
|
||||
data = privateData->data;
|
||||
}
|
||||
// LOGD("getPrivate: %p\n", data);
|
||||
// SE_LOGD("getPrivate: %p\n", data);
|
||||
return data;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#pragma once
|
||||
|
||||
#include "../config.hpp"
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#pragma once
|
||||
|
||||
#define SCRIPT_ENGINE_NONE 0
|
||||
@@ -27,8 +50,8 @@
|
||||
#include <android/log.h>
|
||||
|
||||
#define LOG_TAG "jswrapper"
|
||||
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
|
||||
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
|
||||
#define SE_LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
|
||||
#define SE_LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
|
||||
|
||||
#elif defined(_WIN32) && defined(_WINDOWS)
|
||||
|
||||
@@ -43,13 +66,13 @@
|
||||
void seLog(const char * format, ...);
|
||||
|
||||
#define LOG_TAG "jswrapper"
|
||||
#define LOGD(fmt, ...) seLog("D/" LOG_TAG " (" QUOTEME(__LINE__) "): " fmt "", ##__VA_ARGS__)
|
||||
#define LOGE(fmt, ...) seLog("E/" LOG_TAG " (" QUOTEME(__LINE__) "): " fmt "", ##__VA_ARGS__)
|
||||
#define SE_LOGD(fmt, ...) seLog("D/" LOG_TAG " (" QUOTEME(__LINE__) "): " fmt "", ##__VA_ARGS__)
|
||||
#define SE_LOGE(fmt, ...) seLog("E/" LOG_TAG " (" QUOTEME(__LINE__) "): " fmt "", ##__VA_ARGS__)
|
||||
|
||||
#else
|
||||
|
||||
#define LOGD(...) do { printf(__VA_ARGS__); fflush(stdout); } while (false)
|
||||
#define LOGE(...) do { printf(__VA_ARGS__); fflush(stdout); } while (false)
|
||||
#define SE_LOGD(...) do { printf(__VA_ARGS__); fflush(stdout); } while (false)
|
||||
#define SE_LOGE(...) do { printf(__VA_ARGS__); fflush(stdout); } while (false)
|
||||
|
||||
#endif
|
||||
|
||||
@@ -68,5 +91,16 @@ typedef SSIZE_T ssize_t;
|
||||
#define _SSIZE_T_DEFINED // libuv also defines ssize_t, use the one defined here.
|
||||
#endif // __SSIZE_T
|
||||
|
||||
#endif
|
||||
#endif // #if defined(_WIN32) && defined(_WINDOWS)
|
||||
|
||||
/** @def SE_DEPRECATED_ATTRIBUTE
|
||||
* Only certain compilers support __attribute__((deprecated)).
|
||||
*/
|
||||
#if defined(__GNUC__) && ((__GNUC__ >= 4) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1)))
|
||||
#define SE_DEPRECATED_ATTRIBUTE __attribute__((deprecated))
|
||||
#elif _MSC_VER >= 1400 //vs 2005 or higher
|
||||
#define SE_DEPRECATED_ATTRIBUTE __declspec(deprecated)
|
||||
#else
|
||||
#define SE_DEPRECATED_ATTRIBUTE
|
||||
#endif // SE_DEPRECATED_ATTRIBUTE
|
||||
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#pragma once
|
||||
|
||||
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#include "Class.hpp"
|
||||
|
||||
#if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_JSC
|
||||
@@ -103,7 +126,7 @@ namespace se {
|
||||
_jsCls = JSClassCreate(&_jsClsDef);
|
||||
|
||||
JSObjectRef jsCtor = JSObjectMakeConstructor(__cx, _jsCls, _ctor);
|
||||
HandleObject ctorObj(Object::_createJSObject(this, jsCtor));
|
||||
HandleObject ctorObj(Object::_createJSObject(nullptr, jsCtor));
|
||||
|
||||
Value functionCtor;
|
||||
ScriptEngine::getInstance()->getGlobalObject()->getProperty("Function", &functionCtor);
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#pragma once
|
||||
|
||||
#include "../config.hpp"
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#pragma once
|
||||
|
||||
#include "../config.hpp"
|
||||
@@ -32,6 +55,9 @@
|
||||
se::internal::jsToSeArgs(_cx, argc, _argv, &args); \
|
||||
se::State state(nativeThisObject, args); \
|
||||
ret = funcName(state); \
|
||||
if (!ret) { \
|
||||
SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \
|
||||
} \
|
||||
se::internal::seToJsValue(_cx, state.rval(), &_jsRet); \
|
||||
} \
|
||||
return _jsRet; \
|
||||
@@ -50,6 +76,9 @@
|
||||
se::Object* _thisObject = state.thisObject(); \
|
||||
if (_thisObject) _thisObject->_cleanup(nativeThisObject); \
|
||||
ret = funcName(state); \
|
||||
if (!ret) { \
|
||||
SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \
|
||||
} \
|
||||
JSObjectSetPrivate(_obj, nullptr); \
|
||||
SAFE_DEC_REF(_thisObject); \
|
||||
} \
|
||||
@@ -78,6 +107,10 @@
|
||||
_found = thisObject->getProperty("_ctor", &_property); \
|
||||
if (_found) _property.toObject()->call(args, thisObject); \
|
||||
} \
|
||||
else \
|
||||
{ \
|
||||
SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \
|
||||
} \
|
||||
return JSValueToObject(_cx, _jsRet, nullptr); \
|
||||
}
|
||||
|
||||
@@ -85,7 +118,7 @@
|
||||
#define SE_BIND_SUB_CLS_CTOR(funcName, cls, finalizeCb) \
|
||||
JSValueRef funcName##Registry(JSContextRef _cx, JSObjectRef _function, JSObjectRef _thisObject, size_t argc, const JSValueRef _argv[], JSValueRef* _exception) \
|
||||
{ \
|
||||
SE_UNUSED bool ret = true; \
|
||||
bool ret = true; \
|
||||
JSValueRef _jsRet = JSValueMakeUndefined(_cx); \
|
||||
se::ValueArray args; \
|
||||
se::internal::jsToSeArgs(_cx, argc, _argv, &args); \
|
||||
@@ -100,6 +133,10 @@
|
||||
_found = thisObject->getProperty("_ctor", &_property); \
|
||||
if (_found) _property.toObject()->call(args, thisObject); \
|
||||
} \
|
||||
else \
|
||||
{ \
|
||||
SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \
|
||||
} \
|
||||
return _jsRet; \
|
||||
}
|
||||
|
||||
@@ -117,6 +154,10 @@
|
||||
{ \
|
||||
se::internal::seToJsValue(_cx, state.rval(), &_jsRet); \
|
||||
} \
|
||||
else \
|
||||
{ \
|
||||
SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \
|
||||
} \
|
||||
} \
|
||||
return _jsRet; \
|
||||
}
|
||||
@@ -137,6 +178,9 @@
|
||||
args.push_back(std::move(data)); \
|
||||
se::State state(nativeThisObject, args); \
|
||||
ret = funcName(state); \
|
||||
if (!ret) { \
|
||||
SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \
|
||||
} \
|
||||
} \
|
||||
return _jsRet; \
|
||||
}
|
||||
@@ -149,7 +193,7 @@
|
||||
#define SE_QUOTEME(x) SE_QUOTEME_(x)
|
||||
|
||||
//FIXME: implement this macro
|
||||
#define SE_REPORT_ERROR(fmt, ...) LOGD("ERROR (" __FILE__ ", " SE_QUOTEME(__LINE__) "): " fmt "\n", ##__VA_ARGS__)
|
||||
#define SE_REPORT_ERROR(fmt, ...) SE_LOGE("[ERROR] (" __FILE__ ", " SE_QUOTEME(__LINE__) "): " fmt "\n", ##__VA_ARGS__)
|
||||
|
||||
#if COCOS2D_DEBUG > 0
|
||||
|
||||
@@ -158,7 +202,7 @@
|
||||
{ \
|
||||
if (!(cond)) \
|
||||
{ \
|
||||
LOGD("ASSERT (" __FILE__ ", " SE_QUOTEME(__LINE__) "): " fmt "\n", ##__VA_ARGS__); \
|
||||
SE_LOGE("ASSERT (" __FILE__ ", " SE_QUOTEME(__LINE__) "): " fmt "\n", ##__VA_ARGS__); \
|
||||
assert(false); \
|
||||
} \
|
||||
} while(false)
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#include "Object.hpp"
|
||||
|
||||
#if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_JSC
|
||||
@@ -15,6 +38,20 @@ namespace se {
|
||||
#if SE_DEBUG > 0
|
||||
uint32_t __id = 0;
|
||||
#endif
|
||||
|
||||
bool isInstanceOfConstructor(JSContextRef ctx, JSValueRef value, const char* ctorName)
|
||||
{
|
||||
if (ctorName == nullptr)
|
||||
return false;
|
||||
Object* global = ScriptEngine::getInstance()->getGlobalObject();
|
||||
Value ctorVal;
|
||||
bool ret = false;
|
||||
if (global->getProperty(ctorName, &ctorVal), ctorVal.isObject())
|
||||
{
|
||||
ret = JSValueIsInstanceOfConstructor(ctx, value, ctorVal.toObject()->_getJSObject(), nullptr);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
|
||||
Object::Object()
|
||||
@@ -125,15 +162,71 @@ namespace se {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
Object* Object::createUint8TypedArray(uint8_t* data, size_t byteLength)
|
||||
template<typename T>
|
||||
static bool _setArrayElement(Object* arr, void* data, size_t byteLength)
|
||||
{
|
||||
T* p = (T*)data;
|
||||
size_t count = byteLength / sizeof(T);
|
||||
for (size_t i = 0; i < count; ++i)
|
||||
{
|
||||
if (!arr->setArrayElement((uint32_t)i, se::Value(p[i])))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
Object* Object::createTypedArray(TypedArrayType type, void* data, size_t byteLength)
|
||||
{
|
||||
if (type == TypedArrayType::NONE)
|
||||
{
|
||||
SE_LOGE("Don't pass se::Object::TypedArrayType::NONE to createTypedArray API!");
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
if (type == TypedArrayType::UINT8_CLAMPED)
|
||||
{
|
||||
SE_LOGE("Doesn't support to create Uint8ClampedArray with Object::createTypedArray API!");
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
#if (__MAC_OS_X_VERSION_MAX_ALLOWED >= 101200 || __IPHONE_OS_VERSION_MAX_ALLOWED >= 100000)
|
||||
if (isSupportTypedArrayAPI())
|
||||
{
|
||||
void* copiedData = malloc(byteLength);
|
||||
memcpy(copiedData, data, byteLength);
|
||||
JSValueRef exception = nullptr;
|
||||
JSObjectRef jsobj = JSObjectMakeTypedArrayWithBytesNoCopy(__cx, kJSTypedArrayTypeUint8Array, copiedData, byteLength, myJSTypedArrayBytesDeallocator, nullptr, &exception);
|
||||
JSTypedArrayType jscTypedArrayType = kJSTypedArrayTypeNone;
|
||||
switch (type) {
|
||||
case TypedArrayType::INT8:
|
||||
jscTypedArrayType = kJSTypedArrayTypeInt8Array;
|
||||
break;
|
||||
case TypedArrayType::INT16:
|
||||
jscTypedArrayType = kJSTypedArrayTypeInt16Array;
|
||||
break;
|
||||
case TypedArrayType::INT32:
|
||||
jscTypedArrayType = kJSTypedArrayTypeInt32Array;
|
||||
break;
|
||||
case TypedArrayType::UINT8:
|
||||
jscTypedArrayType = kJSTypedArrayTypeUint8Array;
|
||||
break;
|
||||
case TypedArrayType::UINT16:
|
||||
jscTypedArrayType = kJSTypedArrayTypeUint16Array;
|
||||
break;
|
||||
case TypedArrayType::UINT32:
|
||||
jscTypedArrayType = kJSTypedArrayTypeUint32Array;
|
||||
break;
|
||||
case TypedArrayType::FLOAT32:
|
||||
jscTypedArrayType = kJSTypedArrayTypeFloat32Array;
|
||||
break;
|
||||
case TypedArrayType::FLOAT64:
|
||||
jscTypedArrayType = kJSTypedArrayTypeFloat64Array;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
JSObjectRef jsobj = JSObjectMakeTypedArrayWithBytesNoCopy(__cx, jscTypedArrayType, copiedData, byteLength, myJSTypedArrayBytesDeallocator, nullptr, &exception);
|
||||
if (exception != nullptr)
|
||||
{
|
||||
ScriptEngine::getInstance()->_clearException(exception);
|
||||
@@ -146,30 +239,75 @@ namespace se {
|
||||
#endif
|
||||
{
|
||||
HandleObject arr(Object::createArrayObject(byteLength));
|
||||
Type objectType = Type::UNKNOWN;
|
||||
|
||||
if (!arr.isEmpty())
|
||||
{
|
||||
uint8_t* p = (uint8_t*)data;
|
||||
for (size_t i = 0; i < byteLength; ++i)
|
||||
{
|
||||
arr->setArrayElement((uint32_t)i, se::Value(p[i]));
|
||||
const char* typedArrayCtor = nullptr;
|
||||
switch (type) {
|
||||
case TypedArrayType::INT8:
|
||||
typedArrayCtor = "Int8Array";
|
||||
objectType = Type::TYPED_ARRAY_INT8;
|
||||
_setArrayElement<int8_t>(arr.get(), data, byteLength);
|
||||
break;
|
||||
case TypedArrayType::INT16:
|
||||
typedArrayCtor = "Int16Array";
|
||||
objectType = Type::TYPED_ARRAY_INT16;
|
||||
_setArrayElement<int16_t>(arr.get(), data, byteLength);
|
||||
break;
|
||||
case TypedArrayType::INT32:
|
||||
typedArrayCtor = "Int32Array";
|
||||
objectType = Type::TYPED_ARRAY_INT32;
|
||||
_setArrayElement<int32_t>(arr.get(), data, byteLength);
|
||||
break;
|
||||
case TypedArrayType::UINT8:
|
||||
typedArrayCtor = "Uint8Array";
|
||||
objectType = Type::TYPED_ARRAY_UINT8;
|
||||
_setArrayElement<uint8_t>(arr.get(), data, byteLength);
|
||||
break;
|
||||
case TypedArrayType::UINT16:
|
||||
typedArrayCtor = "Uint16Array";
|
||||
objectType = Type::TYPED_ARRAY_UINT16;
|
||||
_setArrayElement<uint16_t>(arr.get(), data, byteLength);
|
||||
break;
|
||||
case TypedArrayType::UINT32:
|
||||
typedArrayCtor = "Uint32Array";
|
||||
objectType = Type::TYPED_ARRAY_UINT32;
|
||||
_setArrayElement<uint32_t>(arr.get(), data, byteLength);
|
||||
break;
|
||||
case TypedArrayType::FLOAT32:
|
||||
typedArrayCtor = "Float32Array";
|
||||
objectType = Type::TYPED_ARRAY_FLOAT32;
|
||||
_setArrayElement<float>(arr.get(), data, byteLength);
|
||||
break;
|
||||
case TypedArrayType::FLOAT64:
|
||||
typedArrayCtor = "Float64Array";
|
||||
objectType = Type::TYPED_ARRAY_FLOAT64;
|
||||
_setArrayElement<double>(arr.get(), data, byteLength);
|
||||
break;
|
||||
default:
|
||||
assert(false); // Should never go here.
|
||||
break;
|
||||
}
|
||||
|
||||
ValueArray args;
|
||||
args.push_back(Value(arr));
|
||||
Value func;
|
||||
bool ok = ScriptEngine::getInstance()->getGlobalObject()->getProperty("__jsc_createUint8TypedArray", &func);
|
||||
bool ok = ScriptEngine::getInstance()->getGlobalObject()->getProperty(typedArrayCtor, &func);
|
||||
if (ok && func.isObject() && func.toObject()->isFunction())
|
||||
{
|
||||
Value ret;
|
||||
ok = func.toObject()->call(args, nullptr, &ret);
|
||||
if (ok && ret.isObject())
|
||||
JSValueRef exception = nullptr;
|
||||
JSObjectRef ret = JSObjectCallAsConstructor(__cx, func.toObject()->_obj, 1, &arr->_obj, &exception);
|
||||
if (exception == nullptr)
|
||||
{
|
||||
Object* obj = Object::_createJSObject(nullptr, ret.toObject()->_obj);
|
||||
Object* obj = Object::_createJSObject(nullptr, ret);
|
||||
if (obj != nullptr)
|
||||
obj->_type = Type::TYPED_ARRAY;
|
||||
obj->_type = objectType;
|
||||
|
||||
return obj;
|
||||
}
|
||||
else
|
||||
{
|
||||
ScriptEngine::getInstance()->_clearException(exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -177,6 +315,11 @@ namespace se {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
Object* Object::createUint8TypedArray(uint8_t* data, size_t dataCount)
|
||||
{
|
||||
return createTypedArray(TypedArrayType::UINT8, data, dataCount);
|
||||
}
|
||||
|
||||
Object* Object::createJSONObject(const std::string& jsonStr)
|
||||
{
|
||||
Object* obj = nullptr;
|
||||
@@ -268,7 +411,7 @@ namespace se {
|
||||
|
||||
if (_rootCount > 0)
|
||||
{
|
||||
// LOGD("Object::_cleanup, (%p) rootCount: %u\n", this, _rootCount);
|
||||
// SE_LOGD("Object::_cleanup, (%p) rootCount: %u\n", this, _rootCount);
|
||||
// Don't unprotect if it's in cleanup, otherwise, it will trigger crash.
|
||||
if (!se->isInCleanup() && !se->isGarbageCollecting())
|
||||
JSValueUnprotect(__cx, _obj);
|
||||
@@ -278,7 +421,7 @@ namespace se {
|
||||
}
|
||||
else
|
||||
{
|
||||
LOGD("Object::_cleanup, ScriptEngine was initialized again, ignore cleanup work, oldVMId: %u, newVMId: %u\n", _currentVMId, se->getVMId());
|
||||
SE_LOGD("Object::_cleanup, ScriptEngine was initialized again, ignore cleanup work, oldVMId: %u, newVMId: %u\n", _currentVMId, se->getVMId());
|
||||
}
|
||||
|
||||
_isCleanup = true;
|
||||
@@ -446,7 +589,7 @@ namespace se {
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Object::getArrayElement(uint32_t index, Value* data) const
|
||||
bool Object::getArrayElement(uint32_t index, Value* data) const
|
||||
{
|
||||
assert(isArray());
|
||||
assert(data != nullptr);
|
||||
@@ -505,8 +648,19 @@ namespace se {
|
||||
|
||||
bool Object::isTypedArray() const
|
||||
{
|
||||
if (_type == Type::TYPED_ARRAY)
|
||||
if (_type == Type::TYPED_ARRAY_INT8
|
||||
|| _type == Type::TYPED_ARRAY_INT16
|
||||
|| _type == Type::TYPED_ARRAY_INT32
|
||||
|| _type == Type::TYPED_ARRAY_UINT8
|
||||
|| _type == Type::TYPED_ARRAY_UINT8_CLAMPED
|
||||
|| _type == Type::TYPED_ARRAY_UINT16
|
||||
|| _type == Type::TYPED_ARRAY_UINT32
|
||||
|| _type == Type::TYPED_ARRAY_FLOAT32
|
||||
|| _type == Type::TYPED_ARRAY_FLOAT64
|
||||
)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
#if (__MAC_OS_X_VERSION_MAX_ALLOWED >= 101200 || __IPHONE_OS_VERSION_MAX_ALLOWED >= 100000)
|
||||
if (isSupportTypedArrayAPI())
|
||||
@@ -514,29 +668,166 @@ namespace se {
|
||||
JSTypedArrayType type = JSValueGetTypedArrayType(__cx, _obj, nullptr);
|
||||
bool ret = (type != kJSTypedArrayTypeNone && type != kJSTypedArrayTypeArrayBuffer);
|
||||
if (ret)
|
||||
_type = Type::TYPED_ARRAY;
|
||||
{
|
||||
switch (type) {
|
||||
case kJSTypedArrayTypeInt8Array:
|
||||
_type = Type::TYPED_ARRAY_INT8;
|
||||
break;
|
||||
case kJSTypedArrayTypeInt16Array:
|
||||
_type = Type::TYPED_ARRAY_INT16;
|
||||
break;
|
||||
case kJSTypedArrayTypeInt32Array:
|
||||
_type = Type::TYPED_ARRAY_INT32;
|
||||
break;
|
||||
case kJSTypedArrayTypeUint8Array:
|
||||
_type = Type::TYPED_ARRAY_UINT8;
|
||||
break;
|
||||
case kJSTypedArrayTypeUint8ClampedArray:
|
||||
_type = Type::TYPED_ARRAY_UINT8_CLAMPED;
|
||||
break;
|
||||
case kJSTypedArrayTypeUint16Array:
|
||||
_type = Type::TYPED_ARRAY_UINT16;
|
||||
break;
|
||||
case kJSTypedArrayTypeUint32Array:
|
||||
_type = Type::TYPED_ARRAY_UINT32;
|
||||
break;
|
||||
case kJSTypedArrayTypeFloat32Array:
|
||||
_type = Type::TYPED_ARRAY_FLOAT32;
|
||||
break;
|
||||
case kJSTypedArrayTypeFloat64Array:
|
||||
_type = Type::TYPED_ARRAY_FLOAT64;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
#endif
|
||||
Value func;
|
||||
bool ok = ScriptEngine::getInstance()->getGlobalObject()->getProperty("__jsc_isTypedArray", &func);
|
||||
if (ok && func.isObject() && func.toObject()->isFunction())
|
||||
{
|
||||
ValueArray args;
|
||||
args.push_back(Value((Object*)this));
|
||||
return isInstanceOfConstructor(__cx, _obj, "__jscTypedArrayConstructor");
|
||||
}
|
||||
|
||||
Value rval;
|
||||
ok = func.toObject()->call(args, nullptr, &rval);
|
||||
if (ok && rval.isBoolean())
|
||||
Object::TypedArrayType Object::getTypedArrayType() const
|
||||
{
|
||||
if (_type == Type::TYPED_ARRAY_INT8)
|
||||
return TypedArrayType::INT8;
|
||||
else if (_type == Type::TYPED_ARRAY_INT16)
|
||||
return TypedArrayType::INT16;
|
||||
else if (_type == Type::TYPED_ARRAY_INT32)
|
||||
return TypedArrayType::INT32;
|
||||
else if (_type == Type::TYPED_ARRAY_UINT8)
|
||||
return TypedArrayType::UINT8;
|
||||
else if (_type == Type::TYPED_ARRAY_UINT8_CLAMPED)
|
||||
return TypedArrayType::UINT8_CLAMPED;
|
||||
else if (_type == Type::TYPED_ARRAY_UINT16)
|
||||
return TypedArrayType::UINT16;
|
||||
else if (_type == Type::TYPED_ARRAY_UINT32)
|
||||
return TypedArrayType::UINT32;
|
||||
else if (_type == Type::TYPED_ARRAY_FLOAT32)
|
||||
return TypedArrayType::FLOAT32;
|
||||
else if (_type == Type::TYPED_ARRAY_FLOAT64)
|
||||
return TypedArrayType::FLOAT64;
|
||||
|
||||
TypedArrayType typedArrayType = TypedArrayType::NONE;
|
||||
|
||||
#if (__MAC_OS_X_VERSION_MAX_ALLOWED >= 101200 || __IPHONE_OS_VERSION_MAX_ALLOWED >= 100000)
|
||||
if (isSupportTypedArrayAPI())
|
||||
{
|
||||
JSTypedArrayType type = JSValueGetTypedArrayType(__cx, _obj, nullptr);
|
||||
bool ret = (type != kJSTypedArrayTypeNone && type != kJSTypedArrayTypeArrayBuffer);
|
||||
if (ret)
|
||||
{
|
||||
bool ret = rval.toBoolean();
|
||||
if (ret)
|
||||
_type = Type::TYPED_ARRAY;
|
||||
return ret;
|
||||
switch (type) {
|
||||
case kJSTypedArrayTypeInt8Array:
|
||||
_type = Type::TYPED_ARRAY_INT8;
|
||||
typedArrayType = TypedArrayType::INT8;
|
||||
break;
|
||||
case kJSTypedArrayTypeInt16Array:
|
||||
_type = Type::TYPED_ARRAY_INT16;
|
||||
typedArrayType = TypedArrayType::INT16;
|
||||
break;
|
||||
case kJSTypedArrayTypeInt32Array:
|
||||
_type = Type::TYPED_ARRAY_INT32;
|
||||
typedArrayType = TypedArrayType::INT32;
|
||||
break;
|
||||
case kJSTypedArrayTypeUint8Array:
|
||||
_type = Type::TYPED_ARRAY_UINT8;
|
||||
typedArrayType = TypedArrayType::UINT8;
|
||||
break;
|
||||
case kJSTypedArrayTypeUint8ClampedArray:
|
||||
_type = Type::TYPED_ARRAY_UINT8_CLAMPED;
|
||||
typedArrayType = TypedArrayType::UINT8_CLAMPED;
|
||||
break;
|
||||
case kJSTypedArrayTypeUint16Array:
|
||||
_type = Type::TYPED_ARRAY_UINT16;
|
||||
typedArrayType = TypedArrayType::UINT16;
|
||||
break;
|
||||
case kJSTypedArrayTypeUint32Array:
|
||||
_type = Type::TYPED_ARRAY_UINT32;
|
||||
typedArrayType = TypedArrayType::UINT32;
|
||||
break;
|
||||
case kJSTypedArrayTypeFloat32Array:
|
||||
_type = Type::TYPED_ARRAY_FLOAT32;
|
||||
typedArrayType = TypedArrayType::FLOAT32;
|
||||
break;
|
||||
case kJSTypedArrayTypeFloat64Array:
|
||||
_type = Type::TYPED_ARRAY_FLOAT64;
|
||||
typedArrayType = TypedArrayType::FLOAT64;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
return typedArrayType;
|
||||
}
|
||||
#endif
|
||||
if (isInstanceOfConstructor(__cx, _obj, "Int8Array"))
|
||||
{
|
||||
_type = Type::TYPED_ARRAY_INT8;
|
||||
typedArrayType = TypedArrayType::INT8;
|
||||
}
|
||||
else if (isInstanceOfConstructor(__cx, _obj, "Int16Array"))
|
||||
{
|
||||
_type = Type::TYPED_ARRAY_INT16;
|
||||
typedArrayType = TypedArrayType::INT16;
|
||||
}
|
||||
else if (isInstanceOfConstructor(__cx, _obj, "Int32Array"))
|
||||
{
|
||||
_type = Type::TYPED_ARRAY_INT32;
|
||||
typedArrayType = TypedArrayType::INT32;
|
||||
}
|
||||
else if (isInstanceOfConstructor(__cx, _obj, "Uint8Array"))
|
||||
{
|
||||
_type = Type::TYPED_ARRAY_UINT8;
|
||||
typedArrayType = TypedArrayType::UINT8;
|
||||
}
|
||||
else if (isInstanceOfConstructor(__cx, _obj, "Uint8ClampedArray"))
|
||||
{
|
||||
_type = Type::TYPED_ARRAY_UINT8_CLAMPED;
|
||||
typedArrayType = TypedArrayType::UINT8_CLAMPED;
|
||||
}
|
||||
else if (isInstanceOfConstructor(__cx, _obj, "Uint16Array"))
|
||||
{
|
||||
_type = Type::TYPED_ARRAY_UINT16;
|
||||
typedArrayType = TypedArrayType::UINT16;
|
||||
}
|
||||
else if (isInstanceOfConstructor(__cx, _obj, "Uint32Array"))
|
||||
{
|
||||
_type = Type::TYPED_ARRAY_UINT32;
|
||||
typedArrayType = TypedArrayType::UINT32;
|
||||
}
|
||||
else if (isInstanceOfConstructor(__cx, _obj, "Float32Array"))
|
||||
{
|
||||
_type = Type::TYPED_ARRAY_FLOAT32;
|
||||
typedArrayType = TypedArrayType::FLOAT32;
|
||||
}
|
||||
else if (isInstanceOfConstructor(__cx, _obj, "Float64Array"))
|
||||
{
|
||||
_type = Type::TYPED_ARRAY_FLOAT64;
|
||||
typedArrayType = TypedArrayType::FLOAT64;
|
||||
}
|
||||
|
||||
return false;
|
||||
return typedArrayType;
|
||||
}
|
||||
|
||||
bool Object::getTypedArrayData(uint8_t** ptr, size_t* length) const
|
||||
@@ -545,28 +836,44 @@ namespace se {
|
||||
#if (__MAC_OS_X_VERSION_MAX_ALLOWED >= 101200 || __IPHONE_OS_VERSION_MAX_ALLOWED >= 100000)
|
||||
if (isSupportTypedArrayAPI())
|
||||
{
|
||||
bool succeed = false;
|
||||
JSValueRef exception = nullptr;
|
||||
*length = JSObjectGetTypedArrayByteLength(__cx, _obj, &exception);
|
||||
if (exception != nullptr)
|
||||
do
|
||||
{
|
||||
*length = JSObjectGetTypedArrayByteLength(__cx, _obj, &exception);
|
||||
if (exception != nullptr)
|
||||
break;
|
||||
|
||||
size_t offset = JSObjectGetTypedArrayByteOffset(__cx, _obj, &exception);
|
||||
if (exception != nullptr)
|
||||
break;
|
||||
|
||||
uint8_t* buf = (uint8_t*)JSObjectGetTypedArrayBytesPtr(__cx, _obj, &exception);
|
||||
if (exception != nullptr)
|
||||
break;
|
||||
|
||||
if (buf == nullptr)
|
||||
break;
|
||||
|
||||
*ptr = buf + offset;
|
||||
succeed = true;
|
||||
} while (false);
|
||||
|
||||
if (!succeed)
|
||||
{
|
||||
*ptr = nullptr;
|
||||
*length = 0;
|
||||
ScriptEngine::getInstance()->_clearException(exception);
|
||||
return false;
|
||||
}
|
||||
|
||||
*ptr = (uint8_t*)JSObjectGetTypedArrayBytesPtr(__cx, _obj, &exception);
|
||||
if (exception != nullptr)
|
||||
{
|
||||
ScriptEngine::getInstance()->_clearException(exception);
|
||||
return false;
|
||||
}
|
||||
|
||||
return (*ptr != nullptr);
|
||||
return true;
|
||||
}
|
||||
else
|
||||
#endif
|
||||
{
|
||||
Value func;
|
||||
bool ok = ScriptEngine::getInstance()->getGlobalObject()->getProperty("__jsc_getUint8ArrayData", &func);
|
||||
bool ok = ScriptEngine::getInstance()->getGlobalObject()->getProperty("__jsc_getTypedArrayData", &func);
|
||||
if (ok && func.isObject() && func.toObject()->isFunction())
|
||||
{
|
||||
ValueArray args;
|
||||
@@ -615,8 +922,7 @@ namespace se {
|
||||
{
|
||||
if (isFunction())
|
||||
{
|
||||
std::string info;
|
||||
internal::forceConvertJsValueToStdString(__cx, _obj, &info);
|
||||
std::string info = toString();
|
||||
if (info.find("[native code]") != std::string::npos)
|
||||
{
|
||||
return true;
|
||||
@@ -627,7 +933,19 @@ namespace se {
|
||||
|
||||
bool Object::isArray() const
|
||||
{
|
||||
return JSValueIsArray(__cx, _obj);
|
||||
if (_type == Type::ARRAY)
|
||||
return true;
|
||||
|
||||
#if (__MAC_OS_X_VERSION_MAX_ALLOWED >= 101100 || __IPHONE_OS_VERSION_MAX_ALLOWED >= 90000)
|
||||
if (isSupportArrayTestAPI())
|
||||
{
|
||||
return JSValueIsArray(__cx, _obj);
|
||||
}
|
||||
#endif
|
||||
bool ret = isInstanceOfConstructor(__cx, _obj, "Array");
|
||||
if (ret)
|
||||
_type = Type::ARRAY;
|
||||
return ret;
|
||||
}
|
||||
|
||||
bool Object::isArrayBuffer() const
|
||||
@@ -653,25 +971,10 @@ namespace se {
|
||||
}
|
||||
#endif
|
||||
|
||||
Value func;
|
||||
bool ok = ScriptEngine::getInstance()->getGlobalObject()->getProperty("__jsc_isArrayBuffer", &func);
|
||||
if (ok && func.isObject() && func.toObject()->isFunction())
|
||||
{
|
||||
ValueArray args;
|
||||
args.push_back(Value((Object*)this));
|
||||
|
||||
Value rval;
|
||||
ok = func.toObject()->call(args, nullptr, &rval);
|
||||
if (ok && rval.isBoolean())
|
||||
{
|
||||
bool ret = rval.toBoolean();
|
||||
if (ret)
|
||||
_type = Type::ARRAY_BUFFER;
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
bool ret = isInstanceOfConstructor(__cx, _obj, "ArrayBuffer");
|
||||
if (ret)
|
||||
_type = Type::ARRAY_BUFFER;
|
||||
return ret;
|
||||
}
|
||||
|
||||
bool Object::getArrayBufferData(uint8_t** ptr, size_t* length) const
|
||||
@@ -834,12 +1137,12 @@ namespace se {
|
||||
}
|
||||
else
|
||||
{
|
||||
LOGD("Object::unroot, ScriptEngine was initialized again, ignore cleanup work, oldVMId: %u, newVMId: %u\n", _currentVMId, se->getVMId());
|
||||
SE_LOGD("Object::unroot, ScriptEngine was initialized again, ignore cleanup work, oldVMId: %u, newVMId: %u\n", _currentVMId, se->getVMId());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
bool Object::isRooted() const
|
||||
{
|
||||
return _rootCount > 0;
|
||||
@@ -893,6 +1196,25 @@ namespace se {
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string Object::toString() const
|
||||
{
|
||||
std::string ret;
|
||||
if (isFunction() || isArray() || isTypedArray())
|
||||
{
|
||||
internal::forceConvertJsValueToStdString(__cx, _obj, &ret);
|
||||
}
|
||||
else if (isArrayBuffer())
|
||||
{
|
||||
ret = "[object ArrayBuffer]";
|
||||
}
|
||||
else
|
||||
{
|
||||
ret = "[object Object]";
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
} // namespace se {
|
||||
|
||||
#endif // #if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_JSC
|
||||
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#pragma once
|
||||
|
||||
#include "../config.hpp"
|
||||
@@ -39,8 +62,33 @@ namespace se {
|
||||
* @param[in] byteLength The number of bytes pointed to by the parameter bytes.
|
||||
* @return A JavaScript Typed Array Object whose backing store is the same as the one pointed data, or nullptr if there is an error.
|
||||
* @note The return value (non-null) has to be released manually.
|
||||
* @deprecated This method is deprecated, please use `se::Object::createTypedArray` instead.
|
||||
*/
|
||||
static Object* createUint8TypedArray(uint8_t* bytes, size_t byteLength);
|
||||
SE_DEPRECATED_ATTRIBUTE static Object* createUint8TypedArray(uint8_t* bytes, size_t byteLength);
|
||||
|
||||
enum class TypedArrayType
|
||||
{
|
||||
NONE,
|
||||
INT8,
|
||||
INT16,
|
||||
INT32,
|
||||
UINT8,
|
||||
UINT8_CLAMPED,
|
||||
UINT16,
|
||||
UINT32,
|
||||
FLOAT32,
|
||||
FLOAT64
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Creates a JavaScript Typed Array Object with specified format from an existing pointer.
|
||||
* @param[in] type The format of typed array.
|
||||
* @param[in] data A pointer to the byte buffer to be used as the backing store of the Typed Array object.
|
||||
* @param[in] byteLength The number of bytes pointed to by the parameter bytes.
|
||||
* @return A JavaScript Typed Array Object whose backing store is the same as the one pointed data, or nullptr if there is an error.
|
||||
* @note The return value (non-null) has to be released manually.
|
||||
*/
|
||||
static Object* createTypedArray(TypedArrayType type, void* data, size_t byteLength);
|
||||
|
||||
/**
|
||||
* @brief Creates a JavaScript Array Buffer object from an existing pointer.
|
||||
@@ -107,6 +155,7 @@ namespace se {
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool defineFunction(const char *funcName, JSObjectCallAsFunctionCallback func);
|
||||
|
||||
/**
|
||||
* @brief Tests whether an object can be called as a function.
|
||||
* @return true if object can be called as a function, otherwise false.
|
||||
@@ -156,6 +205,12 @@ namespace se {
|
||||
*/
|
||||
bool isTypedArray() const;
|
||||
|
||||
/**
|
||||
* @brief Gets the type of a typed array object.
|
||||
* @return The type of a typed array object.
|
||||
*/
|
||||
TypedArrayType getTypedArrayType() const;
|
||||
|
||||
/**
|
||||
* @brief Gets backing store of a typed array object.
|
||||
* @param[out] ptr A temporary pointer to the backing store of a JavaScript Typed Array object.
|
||||
@@ -290,6 +345,12 @@ namespace se {
|
||||
*/
|
||||
bool detachObject(Object* obj);
|
||||
|
||||
/**
|
||||
* @brief Returns the string for describing current object.
|
||||
* @return The string for describing current object.
|
||||
*/
|
||||
std::string toString() const;
|
||||
|
||||
// Private API used in wrapper
|
||||
static Object* _createJSObject(Class* cls, JSObjectRef obj);
|
||||
JSObjectRef _getJSObject() const;
|
||||
@@ -315,7 +376,15 @@ namespace se {
|
||||
PLAIN,
|
||||
ARRAY,
|
||||
ARRAY_BUFFER,
|
||||
TYPED_ARRAY,
|
||||
TYPED_ARRAY_INT8,
|
||||
TYPED_ARRAY_INT16,
|
||||
TYPED_ARRAY_INT32,
|
||||
TYPED_ARRAY_UINT8,
|
||||
TYPED_ARRAY_UINT8_CLAMPED,
|
||||
TYPED_ARRAY_UINT16,
|
||||
TYPED_ARRAY_UINT32,
|
||||
TYPED_ARRAY_FLOAT32,
|
||||
TYPED_ARRAY_FLOAT64,
|
||||
FUNCTION
|
||||
};
|
||||
|
||||
|
||||
@@ -1,7 +1,31 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#pragma once
|
||||
|
||||
namespace se {
|
||||
|
||||
bool isSupportTypedArrayAPI();
|
||||
bool isSupportArrayTestAPI();
|
||||
|
||||
} // namespace se
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#include "PlatformUtils.h"
|
||||
#include "../config.hpp"
|
||||
|
||||
@@ -15,18 +38,42 @@ namespace se {
|
||||
|
||||
bool isSupportTypedArrayAPI()
|
||||
{
|
||||
static bool isSupported = false;
|
||||
static bool isInited = false;
|
||||
if (!isInited)
|
||||
{
|
||||
#if TARGET_OS_IPHONE
|
||||
float version = [[UIDevice currentDevice].systemVersion floatValue];
|
||||
if (version >= 10.0)
|
||||
return true;
|
||||
float version = [[UIDevice currentDevice].systemVersion floatValue];
|
||||
isSupported = (version >= 10.0f);
|
||||
#elif TARGET_OS_MAC
|
||||
NSOperatingSystemVersion minimumSupportedOSVersion = { .majorVersion = 10, .minorVersion = 12, .patchVersion = 0 };
|
||||
return [NSProcessInfo.processInfo isOperatingSystemAtLeastVersion:minimumSupportedOSVersion] ? true : false;
|
||||
NSOperatingSystemVersion minimumSupportedOSVersion = { .majorVersion = 10, .minorVersion = 12, .patchVersion = 0 };
|
||||
isSupported = [NSProcessInfo.processInfo isOperatingSystemAtLeastVersion:minimumSupportedOSVersion] ? true : false;
|
||||
#else
|
||||
LOGE("isSupportTypedArrayAPI: Unknown system!");
|
||||
SE_LOGE("isSupportTypedArrayAPI: Unknown system!");
|
||||
#endif
|
||||
isInited = true;
|
||||
}
|
||||
return isSupported;
|
||||
}
|
||||
|
||||
return false;
|
||||
bool isSupportArrayTestAPI()
|
||||
{
|
||||
static bool isSupported = false;
|
||||
static bool isInited = false;
|
||||
if (!isInited)
|
||||
{
|
||||
#if TARGET_OS_IPHONE
|
||||
float version = [[UIDevice currentDevice].systemVersion floatValue];
|
||||
isSupported = (version >= 9.0f);
|
||||
#elif TARGET_OS_MAC
|
||||
NSOperatingSystemVersion minimumSupportedOSVersion = { .majorVersion = 10, .minorVersion = 11, .patchVersion = 0 };
|
||||
isSupported = [NSProcessInfo.processInfo isOperatingSystemAtLeastVersion:minimumSupportedOSVersion] ? true : false;
|
||||
#else
|
||||
SE_LOGE("isSupportArrayTestAPI: Unknown system!");
|
||||
#endif
|
||||
isInited = true;
|
||||
}
|
||||
return isSupported;
|
||||
}
|
||||
|
||||
} // namespace se
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#include "ScriptEngine.hpp"
|
||||
|
||||
#if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_JSC
|
||||
@@ -8,7 +31,9 @@
|
||||
#include "../State.hpp"
|
||||
#include "../MappingUtils.hpp"
|
||||
|
||||
#if SE_DEBUG > 0
|
||||
extern "C" JS_EXPORT void JSSynchronousGarbageCollectForDebugging(JSContextRef);
|
||||
#endif
|
||||
|
||||
namespace se {
|
||||
|
||||
@@ -31,10 +56,10 @@ namespace se {
|
||||
JSValueRef __forceGC(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject,
|
||||
size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
|
||||
{
|
||||
LOGD("GC begin ..., (Native -> JS map) count: %d\n", (int)NativePtrToObjectMap::size());
|
||||
// JSGarbageCollect(ctx);
|
||||
JSSynchronousGarbageCollectForDebugging(ctx);
|
||||
LOGD("GC end ..., (Native -> JS map) count: %d\n", (int)NativePtrToObjectMap::size());
|
||||
if (__instance != nullptr)
|
||||
{
|
||||
__instance->garbageCollect();
|
||||
}
|
||||
return JSValueMakeUndefined(ctx);
|
||||
}
|
||||
|
||||
@@ -45,7 +70,7 @@ namespace se {
|
||||
{
|
||||
std::string ret;
|
||||
internal::forceConvertJsValueToStdString(ctx, arguments[0], &ret);
|
||||
LOGD("JS: %s\n", ret.c_str());
|
||||
SE_LOGD("JS: %s\n", ret.c_str());
|
||||
}
|
||||
return JSValueMakeUndefined(ctx);
|
||||
}
|
||||
@@ -64,6 +89,7 @@ namespace se {
|
||||
free(p);
|
||||
}
|
||||
|
||||
Value __consoleVal;
|
||||
Value __oldConsoleLog;
|
||||
Value __oldConsoleDebug;
|
||||
Value __oldConsoleInfo;
|
||||
@@ -81,7 +107,7 @@ namespace se {
|
||||
if ((argc - msgIndex) == 1)
|
||||
{
|
||||
std::string msg = args[msgIndex].toStringForce();
|
||||
LOGD("JS: %s%s\n", prefix, msg.c_str());
|
||||
SE_LOGD("JS: %s%s\n", prefix, msg.c_str());
|
||||
}
|
||||
else if (argc > 1)
|
||||
{
|
||||
@@ -100,7 +126,7 @@ namespace se {
|
||||
}
|
||||
}
|
||||
|
||||
LOGD("JS: %s%s\n", prefix, msg.c_str());
|
||||
SE_LOGD("JS: %s%s\n", prefix, msg.c_str());
|
||||
}
|
||||
|
||||
return true;
|
||||
@@ -109,7 +135,7 @@ namespace se {
|
||||
bool JSB_console_log(State& s)
|
||||
{
|
||||
JSB_console_format_log(s, "");
|
||||
__oldConsoleLog.toObject()->call(s.args(), s.thisObject());
|
||||
__oldConsoleLog.toObject()->call(s.args(), __consoleVal.toObject());
|
||||
return true;
|
||||
}
|
||||
SE_BIND_FUNC(JSB_console_log)
|
||||
@@ -117,7 +143,7 @@ namespace se {
|
||||
bool JSB_console_debug(State& s)
|
||||
{
|
||||
JSB_console_format_log(s, "[DEBUG]: ");
|
||||
__oldConsoleDebug.toObject()->call(s.args(), s.thisObject());
|
||||
__oldConsoleDebug.toObject()->call(s.args(), __consoleVal.toObject());
|
||||
return true;
|
||||
}
|
||||
SE_BIND_FUNC(JSB_console_debug)
|
||||
@@ -125,7 +151,7 @@ namespace se {
|
||||
bool JSB_console_info(State& s)
|
||||
{
|
||||
JSB_console_format_log(s, "[INFO]: ");
|
||||
__oldConsoleInfo.toObject()->call(s.args(), s.thisObject());
|
||||
__oldConsoleInfo.toObject()->call(s.args(), __consoleVal.toObject());
|
||||
return true;
|
||||
}
|
||||
SE_BIND_FUNC(JSB_console_info)
|
||||
@@ -133,7 +159,7 @@ namespace se {
|
||||
bool JSB_console_warn(State& s)
|
||||
{
|
||||
JSB_console_format_log(s, "[WARN]: ");
|
||||
__oldConsoleWarn.toObject()->call(s.args(), s.thisObject());
|
||||
__oldConsoleWarn.toObject()->call(s.args(), __consoleVal.toObject());
|
||||
return true;
|
||||
}
|
||||
SE_BIND_FUNC(JSB_console_warn)
|
||||
@@ -141,7 +167,7 @@ namespace se {
|
||||
bool JSB_console_error(State& s)
|
||||
{
|
||||
JSB_console_format_log(s, "[ERROR]: ");
|
||||
__oldConsoleError.toObject()->call(s.args(), s.thisObject());
|
||||
__oldConsoleError.toObject()->call(s.args(), __consoleVal.toObject());
|
||||
return true;
|
||||
}
|
||||
SE_BIND_FUNC(JSB_console_error)
|
||||
@@ -154,7 +180,7 @@ namespace se {
|
||||
if (args[0].isBoolean() && !args[0].toBoolean())
|
||||
{
|
||||
JSB_console_format_log(s, "[ASSERT]: ", 1);
|
||||
__oldConsoleAssert.toObject()->call(s.args(), s.thisObject());
|
||||
__oldConsoleAssert.toObject()->call(s.args(), __consoleVal.toObject());
|
||||
}
|
||||
}
|
||||
return true;
|
||||
@@ -194,7 +220,7 @@ namespace se {
|
||||
bool ScriptEngine::init()
|
||||
{
|
||||
cleanup();
|
||||
LOGD("Initializing JavaScriptCore \n");
|
||||
SE_LOGD("Initializing JavaScriptCore \n");
|
||||
++_vmId;
|
||||
|
||||
for (const auto& hook : _beforeInitHookArray)
|
||||
@@ -228,26 +254,25 @@ namespace se {
|
||||
_globalObj->root();
|
||||
_globalObj->setProperty("window", Value(_globalObj));
|
||||
|
||||
Value consoleVal;
|
||||
if (_globalObj->getProperty("console", &consoleVal) && consoleVal.isObject())
|
||||
if (_globalObj->getProperty("console", &__consoleVal) && __consoleVal.isObject())
|
||||
{
|
||||
consoleVal.toObject()->getProperty("log", &__oldConsoleLog);
|
||||
consoleVal.toObject()->defineFunction("log", _SE(JSB_console_log));
|
||||
__consoleVal.toObject()->getProperty("log", &__oldConsoleLog);
|
||||
__consoleVal.toObject()->defineFunction("log", _SE(JSB_console_log));
|
||||
|
||||
consoleVal.toObject()->getProperty("debug", &__oldConsoleDebug);
|
||||
consoleVal.toObject()->defineFunction("debug", _SE(JSB_console_debug));
|
||||
__consoleVal.toObject()->getProperty("debug", &__oldConsoleDebug);
|
||||
__consoleVal.toObject()->defineFunction("debug", _SE(JSB_console_debug));
|
||||
|
||||
consoleVal.toObject()->getProperty("info", &__oldConsoleInfo);
|
||||
consoleVal.toObject()->defineFunction("info", _SE(JSB_console_info));
|
||||
__consoleVal.toObject()->getProperty("info", &__oldConsoleInfo);
|
||||
__consoleVal.toObject()->defineFunction("info", _SE(JSB_console_info));
|
||||
|
||||
consoleVal.toObject()->getProperty("warn", &__oldConsoleWarn);
|
||||
consoleVal.toObject()->defineFunction("warn", _SE(JSB_console_warn));
|
||||
__consoleVal.toObject()->getProperty("warn", &__oldConsoleWarn);
|
||||
__consoleVal.toObject()->defineFunction("warn", _SE(JSB_console_warn));
|
||||
|
||||
consoleVal.toObject()->getProperty("error", &__oldConsoleError);
|
||||
consoleVal.toObject()->defineFunction("error", _SE(JSB_console_error));
|
||||
__consoleVal.toObject()->getProperty("error", &__oldConsoleError);
|
||||
__consoleVal.toObject()->defineFunction("error", _SE(JSB_console_error));
|
||||
|
||||
consoleVal.toObject()->getProperty("assert", &__oldConsoleAssert);
|
||||
consoleVal.toObject()->defineFunction("assert", _SE(JSB_console_assert));
|
||||
__consoleVal.toObject()->getProperty("assert", &__oldConsoleAssert);
|
||||
__consoleVal.toObject()->defineFunction("assert", _SE(JSB_console_assert));
|
||||
}
|
||||
|
||||
_globalObj->setProperty("scriptEngineType", Value("JavaScriptCore"));
|
||||
@@ -285,7 +310,7 @@ namespace se {
|
||||
if (!_isValid)
|
||||
return;
|
||||
|
||||
LOGD("ScriptEngine::cleanup begin ...\n");
|
||||
SE_LOGD("ScriptEngine::cleanup begin ...\n");
|
||||
_isInCleanup = true;
|
||||
for (const auto& hook : _beforeCleanupHookArray)
|
||||
{
|
||||
@@ -298,6 +323,7 @@ namespace se {
|
||||
Class::cleanup();
|
||||
garbageCollect();
|
||||
|
||||
__consoleVal.setUndefined();
|
||||
__oldConsoleLog.setUndefined();
|
||||
__oldConsoleDebug.setUndefined();
|
||||
__oldConsoleInfo.setUndefined();
|
||||
@@ -322,7 +348,7 @@ namespace se {
|
||||
|
||||
NativePtrToObjectMap::destroy();
|
||||
NonRefNativePtrCreatedByCtorMap::destroy();
|
||||
LOGD("ScriptEngine::cleanup end ...\n");
|
||||
SE_LOGD("ScriptEngine::cleanup end ...\n");
|
||||
}
|
||||
|
||||
ScriptEngine::ExceptionInfo ScriptEngine::_formatException(JSValueRef exception)
|
||||
@@ -403,7 +429,7 @@ namespace se {
|
||||
{
|
||||
exceptionStr += "\nSTACK:\n" + exceptionInfo.stack;
|
||||
}
|
||||
LOGD("ERROR: %s\n", exceptionStr.c_str());
|
||||
SE_LOGD("ERROR: %s\n", exceptionStr.c_str());
|
||||
|
||||
if (_exceptionCallback != nullptr)
|
||||
{
|
||||
@@ -429,7 +455,7 @@ namespace se {
|
||||
}
|
||||
else
|
||||
{
|
||||
LOGE("ERROR: __errorHandler has exception\n");
|
||||
SE_LOGE("ERROR: __errorHandler has exception\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -504,10 +530,18 @@ namespace se {
|
||||
|
||||
void ScriptEngine::garbageCollect()
|
||||
{
|
||||
LOGD("GC begin ..., (Native -> JS map) count: %d\n", (int)NativePtrToObjectMap::size());
|
||||
// JSGarbageCollect(_cx);
|
||||
// JSSynchronousGarbageCollectForDebugging is private API in JavaScriptCore framework.
|
||||
// AppStore will reject the apps reference non-public symbols.
|
||||
// Therefore, we use JSSynchronousGarbageCollectForDebugging for easily debugging memory
|
||||
// problems in debug mode, and use public API JSGarbageCollect in release mode to pass
|
||||
// the AppStore's verify check.
|
||||
#if SE_DEBUG > 0
|
||||
SE_LOGD("GC begin ..., (Native -> JS map) count: %d\n", (int)NativePtrToObjectMap::size());
|
||||
JSSynchronousGarbageCollectForDebugging(_cx);
|
||||
LOGD("GC end ..., (Native -> JS map) count: %d\n", (int)NativePtrToObjectMap::size());
|
||||
SE_LOGD("GC end ..., (Native -> JS map) count: %d\n", (int)NativePtrToObjectMap::size());
|
||||
#else
|
||||
JSGarbageCollect(_cx);
|
||||
#endif
|
||||
}
|
||||
|
||||
bool ScriptEngine::evalString(const char* script, ssize_t length/* = -1 */, Value* ret/* = nullptr */, const char* fileName/* = nullptr */)
|
||||
@@ -550,7 +584,7 @@ namespace se {
|
||||
{
|
||||
if (exception == nullptr)
|
||||
{
|
||||
LOGD("Unknown syntax error parsing file %s\n", fileName);
|
||||
SE_LOGD("Unknown syntax error parsing file %s\n", fileName);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -585,46 +619,10 @@ namespace se {
|
||||
return evalString(scriptBuffer.c_str(), scriptBuffer.length(), ret, path.c_str());
|
||||
}
|
||||
|
||||
LOGE("ScriptEngine::runScript script %s, buffer is empty!\n", path.c_str());
|
||||
SE_LOGE("ScriptEngine::runScript script %s, buffer is empty!\n", path.c_str());
|
||||
return false;
|
||||
}
|
||||
|
||||
void ScriptEngine::_retainScriptObject(void* owner, void* target)
|
||||
{
|
||||
auto iterOwner = NativePtrToObjectMap::find(owner);
|
||||
if (iterOwner == NativePtrToObjectMap::end())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
auto iterTarget = NativePtrToObjectMap::find(target);
|
||||
if (iterTarget == NativePtrToObjectMap::end())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
clearException();
|
||||
iterOwner->second->attachObject(iterTarget->second);
|
||||
}
|
||||
|
||||
void ScriptEngine::_releaseScriptObject(void* owner, void* target)
|
||||
{
|
||||
auto iterOwner = NativePtrToObjectMap::find(owner);
|
||||
if (iterOwner == NativePtrToObjectMap::end())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
auto iterTarget = NativePtrToObjectMap::find(target);
|
||||
if (iterTarget == NativePtrToObjectMap::end())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
clearException();
|
||||
iterOwner->second->detachObject(iterTarget->second);
|
||||
}
|
||||
|
||||
void ScriptEngine::clearException()
|
||||
{
|
||||
//FIXME:
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#pragma once
|
||||
|
||||
#include "../config.hpp"
|
||||
@@ -41,7 +64,6 @@ namespace se {
|
||||
|
||||
/**
|
||||
* @brief Destroys the instance of script engine.
|
||||
* @return
|
||||
*/
|
||||
static void destroyInstance();
|
||||
|
||||
@@ -162,7 +184,7 @@ namespace se {
|
||||
* @param[in] rval The se::Value that results from evaluating script. Passing nullptr if you don't care about the result.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool runScript(const std::string& path, Value* ret = nullptr);
|
||||
bool runScript(const std::string& path, Value* rval = nullptr);
|
||||
|
||||
/**
|
||||
* @brief Tests whether script engine is doing garbage collection.
|
||||
@@ -208,6 +230,7 @@ namespace se {
|
||||
|
||||
/**
|
||||
* @brief Enables JavaScript debugger
|
||||
* @param[in] serverAddr The address of debugger server.
|
||||
* @param[in] port The port of debugger server will use.
|
||||
*/
|
||||
void enableDebugger(const std::string& serverAddr, uint32_t port);
|
||||
@@ -229,12 +252,8 @@ namespace se {
|
||||
uint32_t getVMId() const { return _vmId; }
|
||||
|
||||
// Private API used in wrapper
|
||||
void _retainScriptObject(void* owner, void* target);
|
||||
void _releaseScriptObject(void* owner, void* target);
|
||||
|
||||
void _clearException(JSValueRef exception);
|
||||
JSContextRef _getContext() const { return _cx; }
|
||||
|
||||
void _setGarbageCollecting(bool isGarbageCollecting);
|
||||
//
|
||||
private:
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#pragma once
|
||||
|
||||
#include "ScriptEngine.hpp"
|
||||
|
||||
@@ -1,11 +1,26 @@
|
||||
//
|
||||
// Utils.cpp
|
||||
// cocos2d_js_bindings
|
||||
//
|
||||
// Created by James Chen on 4/26/17.
|
||||
//
|
||||
//
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#include "Utils.hpp"
|
||||
|
||||
#if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_JSC
|
||||
@@ -35,7 +50,7 @@ namespace se {
|
||||
ok = globalObject->getProperty("Object", &v);
|
||||
if (!ok || !v.isObject())
|
||||
{
|
||||
LOGD("ERROR: couldn't find Object\n");
|
||||
SE_LOGD("ERROR: couldn't find Object\n");
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -43,7 +58,7 @@ namespace se {
|
||||
ok = v.toObject()->getProperty("defineProperty", &definePropertyFunc);
|
||||
if (!ok || !v.isObject())
|
||||
{
|
||||
LOGD("ERROR: couldn't find Object.defineProperty\n");
|
||||
SE_LOGD("ERROR: couldn't find Object.defineProperty\n");
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -253,7 +268,9 @@ namespace se {
|
||||
}
|
||||
|
||||
assert(finalizeCb);
|
||||
HandleObject privateObj(Object::createObjectWithClass(__jsb_CCPrivateData_class));
|
||||
Object* privateObj = Object::createObjectWithClass(__jsb_CCPrivateData_class);
|
||||
privateObj->root();
|
||||
|
||||
internal::PrivateData* privateData = (internal::PrivateData*)malloc(sizeof(internal::PrivateData));
|
||||
privateData->data = data;
|
||||
privateData->finalizeCb = finalizeCb;
|
||||
@@ -268,6 +285,9 @@ namespace se {
|
||||
ScriptEngine::getInstance()->_clearException(exception);
|
||||
}
|
||||
JSStringRelease(key);
|
||||
|
||||
privateObj->unroot();
|
||||
privateObj->decRef();
|
||||
}
|
||||
|
||||
void* getPrivate(JSObjectRef obj)
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#pragma once
|
||||
|
||||
#include "../config.hpp"
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#pragma once
|
||||
|
||||
#ifndef UINT64_C
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#include "Class.hpp"
|
||||
#include "Object.hpp"
|
||||
#include "Utils.hpp"
|
||||
@@ -69,7 +92,7 @@ namespace se {
|
||||
_ctor = empty_constructor;
|
||||
}
|
||||
|
||||
// LOGD("Class init ( %s ) ...\n", clsName);
|
||||
// SE_LOGD("Class init ( %s ) ...\n", clsName);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -112,7 +135,7 @@ namespace se {
|
||||
if (jsobj != nullptr)
|
||||
{
|
||||
_proto = Object::_createJSObject(nullptr, jsobj);
|
||||
// LOGD("_proto: %p, name: %s\n", _proto, _name);
|
||||
// SE_LOGD("_proto: %p, name: %s\n", _proto, _name);
|
||||
_proto->root();
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#pragma once
|
||||
|
||||
#include "../config.hpp"
|
||||
@@ -10,28 +33,91 @@ namespace se {
|
||||
|
||||
class Object;
|
||||
|
||||
/**
|
||||
* se::Class represents a definition of how to create a native binding object.
|
||||
*/
|
||||
class Class final
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief Creates a class used for creating relevant native binding objects.
|
||||
* @param[in] className A null-terminated UTF8 string containing the class's name.
|
||||
* @param[in] obj The object that current class proto object attaches to. Should not be nullptr.
|
||||
* @param[in] parentProto The parent proto object that current class inherits from. Passing nullptr means a new class has no parent.
|
||||
* @param[in] ctor A callback to invoke when your constructor is used in a 'new' expression. Pass nullptr to use the default object constructor.
|
||||
* @return A class instance used for creating relevant native binding objects.
|
||||
* @note Don't need to delete the pointer return by this method, it's managed internally.
|
||||
*/
|
||||
static Class* create(const char* className, Object* obj, Object* parentProto, JSNative ctor);
|
||||
|
||||
/**
|
||||
* @brief Defines a member function with a callback. Each objects created by class will have this function property.
|
||||
* @param[in] name A null-terminated UTF8 string containing the function name.
|
||||
* @param[in] func A callback to invoke when the property is called as a function.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool defineFunction(const char *name, JSNative func);
|
||||
|
||||
/**
|
||||
* @brief Defines a property with accessor callbacks. Each objects created by class will have this property.
|
||||
* @param[in] name A null-terminated UTF8 string containing the property name.
|
||||
* @param[in] getter A callback to invoke when the property is read.
|
||||
* @param[in] setter A callback to invoke when the property is set.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool defineProperty(const char *name, JSNative getter, JSNative setter);
|
||||
|
||||
/**
|
||||
* @brief Defines a static function with a callback. Only JavaScript constructor object will have this function.
|
||||
* @param[in] name A null-terminated UTF8 string containing the function name.
|
||||
* @param[in] func A callback to invoke when the constructor's property is called as a function.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool defineStaticFunction(const char *name, JSNative func);
|
||||
|
||||
/**
|
||||
* @brief Defines a static property with accessor callbacks. Only JavaScript constructor object will have this property.
|
||||
* @param[in] name A null-terminated UTF8 string containing the property name.
|
||||
* @param[in] getter A callback to invoke when the constructor's property is read.
|
||||
* @param[in] setter A callback to invoke when the constructor's property is set.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool defineStaticProperty(const char *name, JSNative getter, JSNative setter);
|
||||
|
||||
/**
|
||||
* @brief Defines the finalize function with a callback.
|
||||
* @param[in] func The callback to invoke when a JavaScript object is garbage collected.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool defineFinalizeFunction(JSFinalizeOp func);
|
||||
|
||||
/**
|
||||
* @brief Installs class to JavaScript VM.
|
||||
* @return true if succeed, otherwise false.
|
||||
* @note After this method, an object could be created by `var foo = new Foo();`.
|
||||
*/
|
||||
bool install();
|
||||
|
||||
/**
|
||||
* @brief Gets the proto object of this class.
|
||||
* @return The proto object of this class.
|
||||
* @note Don't need to be released in user code.
|
||||
*/
|
||||
Object* getProto();
|
||||
|
||||
/**
|
||||
* @brief Gets the class name.
|
||||
* @return The class name.
|
||||
*/
|
||||
const char* getName() const { return _name; }
|
||||
|
||||
// Private API used in wrapper
|
||||
JSFinalizeOp _getFinalizeCb() const;
|
||||
//
|
||||
private:
|
||||
Class();
|
||||
~Class();
|
||||
public:
|
||||
|
||||
static Class* create(const char* className, Object* obj, Object* parentProto, JSNative ctor);
|
||||
|
||||
bool install();
|
||||
Object* getProto();
|
||||
JSFinalizeOp _getFinalizeCb() const;
|
||||
|
||||
bool defineFunction(const char *name, JSNative func);
|
||||
bool defineProperty(const char *name, JSNative getter, JSNative setter);
|
||||
bool defineStaticFunction(const char *name, JSNative func);
|
||||
bool defineStaticProperty(const char *name, JSNative getter, JSNative setter);
|
||||
bool defineFinalizeFunction(JSFinalizeOp func);
|
||||
|
||||
const char* getName() const { return _name; }
|
||||
|
||||
private:
|
||||
bool init(const char* clsName, Object* obj, Object* parentProto, JSNative ctor);
|
||||
void destroy();
|
||||
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#pragma once
|
||||
|
||||
#include "../config.hpp"
|
||||
@@ -25,6 +48,9 @@
|
||||
void* nativeThisObject = se::internal::getPrivate(_cx, _thizObj); \
|
||||
se::State state(nativeThisObject, args); \
|
||||
ret = funcName(state); \
|
||||
if (!ret) { \
|
||||
SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \
|
||||
} \
|
||||
se::internal::setReturnValue(_cx, state.rval(), _argv); \
|
||||
return ret; \
|
||||
}
|
||||
@@ -36,11 +62,14 @@
|
||||
void funcName##Registry(JSFreeOp* _fop, JSObject* _obj) \
|
||||
{ \
|
||||
void* nativeThisObject = JS_GetPrivate(_obj); \
|
||||
bool ok = false; \
|
||||
bool ret = false; \
|
||||
if (nativeThisObject == nullptr) \
|
||||
return;\
|
||||
se::State state(nativeThisObject); \
|
||||
ok = funcName(state); \
|
||||
ret = funcName(state); \
|
||||
if (!ret) { \
|
||||
SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \
|
||||
} \
|
||||
}
|
||||
|
||||
|
||||
@@ -62,6 +91,10 @@
|
||||
_found = thisObject->getProperty("_ctor", &_property); \
|
||||
if (_found) _property.toObject()->call(args, thisObject); \
|
||||
} \
|
||||
else \
|
||||
{ \
|
||||
SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \
|
||||
} \
|
||||
return ret; \
|
||||
}
|
||||
|
||||
@@ -85,6 +118,10 @@
|
||||
_found = thisObject->getProperty("_ctor", &_property); \
|
||||
if (_found) _property.toObject()->call(args, thisObject); \
|
||||
} \
|
||||
else \
|
||||
{ \
|
||||
SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \
|
||||
} \
|
||||
return ret; \
|
||||
}
|
||||
|
||||
@@ -99,6 +136,9 @@
|
||||
void* nativeThisObject = se::internal::getPrivate(_cx, _thizObj); \
|
||||
se::State state(nativeThisObject); \
|
||||
ret = funcName(state); \
|
||||
if (!ret) { \
|
||||
SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \
|
||||
} \
|
||||
se::internal::setReturnValue(_cx, state.rval(), _argv); \
|
||||
return ret; \
|
||||
}
|
||||
@@ -118,6 +158,9 @@
|
||||
args.push_back(std::move(data)); \
|
||||
se::State state(nativeThisObject, args); \
|
||||
ret = funcName(state); \
|
||||
if (!ret) { \
|
||||
SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \
|
||||
} \
|
||||
return ret; \
|
||||
}
|
||||
|
||||
@@ -128,7 +171,7 @@
|
||||
#define SE_QUOTEME(x) SE_QUOTEME_(x)
|
||||
|
||||
#define SE_REPORT_ERROR(fmt, ...) \
|
||||
LOGD("ERROR (" __FILE__ ", " SE_QUOTEME(__LINE__) "): " fmt "\n", ##__VA_ARGS__); \
|
||||
SE_LOGD("ERROR (" __FILE__ ", " SE_QUOTEME(__LINE__) "): " fmt "\n", ##__VA_ARGS__); \
|
||||
JS_ReportErrorUTF8(se::ScriptEngine::getInstance()->_getContext(), fmt, ##__VA_ARGS__)
|
||||
|
||||
#if COCOS2D_DEBUG > 0
|
||||
@@ -138,7 +181,7 @@
|
||||
{ \
|
||||
if (!(cond)) \
|
||||
{ \
|
||||
LOGD("ASSERT (" __FILE__ ", " SE_QUOTEME(__LINE__) "): " fmt "\n", ##__VA_ARGS__); \
|
||||
SE_LOGE("ASSERT (" __FILE__ ", " SE_QUOTEME(__LINE__) "): " fmt "\n", ##__VA_ARGS__); \
|
||||
assert(false); \
|
||||
} \
|
||||
} while(false)
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#include "Object.hpp"
|
||||
|
||||
#if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_SM
|
||||
@@ -118,17 +141,74 @@ namespace se {
|
||||
return obj;
|
||||
}
|
||||
|
||||
Object* Object::createUint8TypedArray(uint8_t* data, size_t byteLength)
|
||||
Object* Object::createTypedArray(TypedArrayType type, void* data, size_t byteLength)
|
||||
{
|
||||
JS::RootedObject jsobj(__cx, JS_NewUint8Array(__cx, (uint32_t)byteLength));
|
||||
if (type == TypedArrayType::NONE)
|
||||
{
|
||||
SE_LOGE("Don't pass se::Object::TypedArrayType::NONE to createTypedArray API!");
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
if (type == TypedArrayType::UINT8_CLAMPED)
|
||||
{
|
||||
SE_LOGE("Doesn't support to create Uint8ClampedArray with Object::createTypedArray API!");
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
JSObject* arr = nullptr;
|
||||
void* tmpData = nullptr;
|
||||
bool isShared = false;
|
||||
JS::AutoCheckCannotGC nogc;
|
||||
uint8_t* tmpData = JS_GetUint8ArrayData(jsobj, &isShared, nogc);
|
||||
memcpy((void*)tmpData, (const void*)data, byteLength);
|
||||
Object* obj = Object::_createJSObject(nullptr, jsobj);
|
||||
|
||||
switch (type) {
|
||||
case TypedArrayType::INT8:
|
||||
arr = JS_NewInt8Array(__cx, (uint32_t)byteLength);
|
||||
tmpData = JS_GetInt8ArrayData(arr, &isShared, nogc);
|
||||
break;
|
||||
case TypedArrayType::INT16:
|
||||
arr = JS_NewInt16Array(__cx, (uint32_t)byteLength/2);
|
||||
tmpData = JS_GetInt16ArrayData(arr, &isShared, nogc);
|
||||
break;
|
||||
case TypedArrayType::INT32:
|
||||
arr = JS_NewInt32Array(__cx, (uint32_t)byteLength/4);
|
||||
tmpData = JS_GetInt32ArrayData(arr, &isShared, nogc);
|
||||
break;
|
||||
case TypedArrayType::UINT8:
|
||||
arr = JS_NewUint8Array(__cx, (uint32_t)byteLength);
|
||||
tmpData = JS_GetUint8ArrayData(arr, &isShared, nogc);
|
||||
break;
|
||||
case TypedArrayType::UINT16:
|
||||
arr = JS_NewUint16Array(__cx, (uint32_t)byteLength/2);
|
||||
tmpData = JS_GetUint16ArrayData(arr, &isShared, nogc);
|
||||
break;
|
||||
case TypedArrayType::UINT32:
|
||||
arr = JS_NewUint32Array(__cx, (uint32_t)byteLength/4);
|
||||
tmpData = JS_GetUint32ArrayData(arr, &isShared, nogc);
|
||||
break;
|
||||
case TypedArrayType::FLOAT32:
|
||||
arr = JS_NewFloat32Array(__cx, (uint32_t)byteLength/4);
|
||||
tmpData = JS_GetFloat32ArrayData(arr, &isShared, nogc);
|
||||
break;
|
||||
case TypedArrayType::FLOAT64:
|
||||
arr = JS_NewFloat64Array(__cx, (uint32_t)byteLength/8);
|
||||
tmpData = JS_GetFloat64ArrayData(arr, &isShared, nogc);
|
||||
break;
|
||||
default:
|
||||
assert(false); // Should never go here.
|
||||
break;
|
||||
}
|
||||
|
||||
memcpy(tmpData, (const void*)data, byteLength);
|
||||
|
||||
Object* obj = Object::_createJSObject(nullptr, arr);
|
||||
return obj;
|
||||
}
|
||||
|
||||
Object* Object::createUint8TypedArray(uint8_t* data, size_t dataCount)
|
||||
{
|
||||
return createTypedArray(TypedArrayType::UINT8, data, dataCount);
|
||||
}
|
||||
|
||||
Object* Object::createJSONObject(const std::string& jsonStr)
|
||||
{
|
||||
Value strVal(jsonStr);
|
||||
@@ -224,10 +304,10 @@ namespace se {
|
||||
return ok;
|
||||
}
|
||||
|
||||
bool Object::defineFunction(const char *funcName, JSNative func, int minArgs)
|
||||
bool Object::defineFunction(const char *funcName, JSNative func)
|
||||
{
|
||||
JS::RootedObject object(__cx, _getJSObject());
|
||||
bool ok = JS_DefineFunction(__cx, object, funcName, func, minArgs, 0);
|
||||
bool ok = JS_DefineFunction(__cx, object, funcName, func, 0, 0);
|
||||
return ok;
|
||||
}
|
||||
|
||||
@@ -287,7 +367,33 @@ namespace se {
|
||||
|
||||
bool Object::isTypedArray() const
|
||||
{
|
||||
return JS_IsTypedArrayObject( _getJSObject());
|
||||
return JS_IsTypedArrayObject(_getJSObject());
|
||||
}
|
||||
|
||||
Object::TypedArrayType Object::getTypedArrayType() const
|
||||
{
|
||||
TypedArrayType ret = TypedArrayType::NONE;
|
||||
JSObject* obj = _getJSObject();
|
||||
if (JS_IsInt8Array(obj))
|
||||
ret = TypedArrayType::INT8;
|
||||
else if (JS_IsInt16Array(obj))
|
||||
ret = TypedArrayType::INT16;
|
||||
else if (JS_IsInt32Array(obj))
|
||||
ret = TypedArrayType::INT32;
|
||||
else if (JS_IsUint8Array(obj))
|
||||
ret = TypedArrayType::UINT8;
|
||||
else if (JS_IsUint8ClampedArray(obj))
|
||||
ret = TypedArrayType::UINT8_CLAMPED;
|
||||
else if (JS_IsUint16Array(obj))
|
||||
ret = TypedArrayType::UINT16;
|
||||
else if (JS_IsUint32Array(obj))
|
||||
ret = TypedArrayType::UINT32;
|
||||
else if (JS_IsFloat32Array(obj))
|
||||
ret = TypedArrayType::FLOAT32;
|
||||
else if (JS_IsFloat64Array(obj))
|
||||
ret = TypedArrayType::FLOAT64;
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
bool Object::getTypedArrayData(uint8_t** ptr, size_t* length) const
|
||||
@@ -536,54 +642,63 @@ namespace se {
|
||||
bool Object::attachObject(Object* obj)
|
||||
{
|
||||
assert(obj);
|
||||
JSObject* ownerObj = _getJSObject();
|
||||
JSObject* targetObj = obj->_getJSObject();
|
||||
if (ownerObj == nullptr || targetObj == nullptr)
|
||||
|
||||
Object* global = ScriptEngine::getInstance()->getGlobalObject();
|
||||
Value jsbVal;
|
||||
if (!global->getProperty("jsb", &jsbVal))
|
||||
return false;
|
||||
Object* jsbObj = jsbVal.toObject();
|
||||
|
||||
Value func;
|
||||
|
||||
if (!jsbObj->getProperty("registerNativeRef", &func))
|
||||
return false;
|
||||
|
||||
JS::RootedValue valOwner(__cx, JS::ObjectValue(*ownerObj));
|
||||
JS::RootedValue valTarget(__cx, JS::ObjectValue(*targetObj));
|
||||
|
||||
JS::RootedObject jsbObj(__cx);
|
||||
JS::RootedObject globalObj(__cx, ScriptEngine::getInstance()->getGlobalObject()->_getJSObject());
|
||||
get_or_create_js_obj(__cx, globalObj, "jsb", &jsbObj);
|
||||
|
||||
JS::AutoValueVector args(__cx);
|
||||
args.resize(2);
|
||||
args[0].set(valOwner);
|
||||
args[1].set(valTarget);
|
||||
|
||||
JS::RootedValue rval(__cx);
|
||||
|
||||
return JS_CallFunctionName(__cx, jsbObj, "registerNativeRef", args, &rval);
|
||||
ValueArray args;
|
||||
args.push_back(Value(this));
|
||||
args.push_back(Value(obj));
|
||||
func.toObject()->call(args, global);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Object::detachObject(Object* obj)
|
||||
{
|
||||
assert(obj);
|
||||
JSObject* ownerObj = _getJSObject();
|
||||
JSObject* targetObj = obj->_getJSObject();
|
||||
if (ownerObj == nullptr || targetObj == nullptr)
|
||||
{
|
||||
LOGD("%s: try to detach on invalid object, owner: %p, target: %p\n", __FUNCTION__, ownerObj, targetObj);
|
||||
Object* global = ScriptEngine::getInstance()->getGlobalObject();
|
||||
Value jsbVal;
|
||||
if (!global->getProperty("jsb", &jsbVal))
|
||||
return false;
|
||||
Object* jsbObj = jsbVal.toObject();
|
||||
|
||||
Value func;
|
||||
|
||||
if (!jsbObj->getProperty("unregisterNativeRef", &func))
|
||||
return false;
|
||||
|
||||
ValueArray args;
|
||||
args.push_back(Value(this));
|
||||
args.push_back(Value(obj));
|
||||
func.toObject()->call(args, global);
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string Object::toString() const
|
||||
{
|
||||
std::string ret;
|
||||
if (isFunction() || isArray() || isTypedArray())
|
||||
{
|
||||
JS::RootedValue val(__cx, JS::ObjectOrNullValue(_getJSObject()));
|
||||
internal::forceConvertJsValueToStdString(__cx, val, &ret);
|
||||
}
|
||||
|
||||
JS::RootedValue valOwner(__cx, JS::ObjectValue(*ownerObj));
|
||||
JS::RootedValue valTarget(__cx, JS::ObjectValue(*targetObj));
|
||||
|
||||
JS::RootedObject jsbObj(__cx);
|
||||
JS::RootedObject globalObj(__cx, ScriptEngine::getInstance()->getGlobalObject()->_getJSObject());
|
||||
get_or_create_js_obj(__cx, globalObj, "jsb", &jsbObj);
|
||||
|
||||
JS::AutoValueVector args(__cx);
|
||||
args.resize(2);
|
||||
args[0].set(valOwner);
|
||||
args[1].set(valTarget);
|
||||
|
||||
JS::RootedValue rval(__cx);
|
||||
|
||||
return JS_CallFunctionName(__cx, jsbObj, "unregisterNativeRef", args, &rval);
|
||||
else if (isArrayBuffer())
|
||||
{
|
||||
ret = "[object ArrayBuffer]";
|
||||
}
|
||||
else
|
||||
{
|
||||
ret = "[object Object]";
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
} // namespace se {
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#pragma once
|
||||
|
||||
#include "../config.hpp"
|
||||
@@ -12,51 +35,322 @@ namespace se {
|
||||
|
||||
class Class;
|
||||
|
||||
/**
|
||||
* se::Object represents JavaScript Object.
|
||||
*/
|
||||
class Object final : public RefCounter
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief Creates a JavaScript Object like `{} or new Object()`.
|
||||
* @return A JavaScript Object, or nullptr if there is an error.
|
||||
* @note The return value (non-null) has to be released manually.
|
||||
*/
|
||||
static Object* createPlainObject();
|
||||
static Object* createObjectWithClass(Class* cls);
|
||||
|
||||
/**
|
||||
* @brief Creates a JavaScript Array Object like `[] or new Array()`.
|
||||
* @param[in] length The initical length of array.
|
||||
* @return A JavaScript Array Object, or nullptr if there is an error.
|
||||
* @note The return value (non-null) has to be released manually.
|
||||
*/
|
||||
static Object* createArrayObject(size_t length);
|
||||
static Object* createUint8TypedArray(uint8_t* data, size_t byteLength);
|
||||
|
||||
/**
|
||||
* @brief Creates a JavaScript Typed Array Object with uint8 format from an existing pointer.
|
||||
* @param[in] bytes A pointer to the byte buffer to be used as the backing store of the Typed Array object.
|
||||
* @param[in] byteLength The number of bytes pointed to by the parameter bytes.
|
||||
* @return A JavaScript Typed Array Object whose backing store is the same as the one pointed data, or nullptr if there is an error.
|
||||
* @note The return value (non-null) has to be released manually.
|
||||
* @deprecated This method is deprecated, please use `se::Object::createTypedArray` instead.
|
||||
*/
|
||||
SE_DEPRECATED_ATTRIBUTE static Object* createUint8TypedArray(uint8_t* data, size_t byteLength);
|
||||
|
||||
enum class TypedArrayType
|
||||
{
|
||||
NONE,
|
||||
INT8,
|
||||
INT16,
|
||||
INT32,
|
||||
UINT8,
|
||||
UINT8_CLAMPED,
|
||||
UINT16,
|
||||
UINT32,
|
||||
FLOAT32,
|
||||
FLOAT64
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Creates a JavaScript Typed Array Object with specified format from an existing pointer.
|
||||
* @param[in] type The format of typed array.
|
||||
* @param[in] data A pointer to the byte buffer to be used as the backing store of the Typed Array object.
|
||||
* @param[in] byteLength The number of bytes pointed to by the parameter bytes.
|
||||
* @return A JavaScript Typed Array Object whose backing store is the same as the one pointed data, or nullptr if there is an error.
|
||||
* @note The return value (non-null) has to be released manually.
|
||||
*/
|
||||
static Object* createTypedArray(TypedArrayType type, void* data, size_t byteLength);
|
||||
|
||||
/**
|
||||
* @brief Creates a JavaScript Array Buffer object from an existing pointer.
|
||||
* @param[in] bytes A pointer to the byte buffer to be used as the backing store of the Typed Array object.
|
||||
* @param[in] byteLength The number of bytes pointed to by the parameter bytes.
|
||||
* @return A Array Buffer Object whose backing store is the same as the one pointed to data, or nullptr if there is an error.
|
||||
* @note The return value (non-null) has to be released manually.
|
||||
*/
|
||||
static Object* createArrayBufferObject(void* data, size_t byteLength);
|
||||
|
||||
/**
|
||||
* @brief Creates a JavaScript Object from a JSON formatted string.
|
||||
* @param[in] jsonStr The utf-8 string containing the JSON string to be parsed.
|
||||
* @return A JavaScript Object containing the parsed value, or nullptr if the input is invalid.
|
||||
* @note The return value (non-null) has to be released manually.
|
||||
*/
|
||||
static Object* createJSONObject(const std::string& jsonStr);
|
||||
|
||||
/**
|
||||
* @brief Creates a JavaScript Native Binding Object from an existing se::Class instance.
|
||||
* @param[in] cls The se::Class instance which stores native callback informations.
|
||||
* @return A JavaScript Native Binding Object, or nullptr if there is an error.
|
||||
* @note The return value (non-null) has to be released manually.
|
||||
*/
|
||||
static Object* createObjectWithClass(Class* cls);
|
||||
|
||||
/**
|
||||
* @brief Gets a se::Object from an existing native object pointer.
|
||||
* @param[in] ptr The native object pointer associated with the se::Object
|
||||
* @return A JavaScript Native Binding Object, or nullptr if there is an error.
|
||||
* @note The return value (non-null) has to be released manually.
|
||||
*/
|
||||
static Object* getObjectWithPtr(void* ptr);
|
||||
|
||||
bool getProperty(const char* name, Value* data);
|
||||
bool setProperty(const char* name, const Value& v);
|
||||
/**
|
||||
* @brief Gets a property from an object.
|
||||
* @param[in] name A utf-8 string containing the property's name.
|
||||
* @param[out] value The property's value if object has the property, otherwise the undefined value.
|
||||
* @return true if object has the property, otherwise false.
|
||||
*/
|
||||
bool getProperty(const char* name, Value* value);
|
||||
|
||||
/**
|
||||
* @brief Sets a property to an object.
|
||||
* @param[in] name A utf-8 string containing the property's name.
|
||||
* @param[in] value A value to be used as the property's value.
|
||||
* @return true if the property is set successfully, otherwise false.
|
||||
*/
|
||||
bool setProperty(const char* name, const Value& value);
|
||||
|
||||
/**
|
||||
* @brief Defines a property with native accessor callbacks for an object.
|
||||
* @param[in] name A utf-8 string containing the property's name.
|
||||
* @param[in] getter The native callback for getter.
|
||||
* @param[in] setter The native callback for setter.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool defineProperty(const char *name, JSNative getter, JSNative setter);
|
||||
|
||||
/**
|
||||
* @brief Defines a function with a native callback for an object.
|
||||
* @param[in] funcName A utf-8 string containing the function name.
|
||||
* @param[in] func The native callback triggered by JavaScript code.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool defineFunction(const char *funcName, JSNative func);
|
||||
|
||||
/**
|
||||
* @brief Tests whether an object can be called as a function.
|
||||
* @return true if object can be called as a function, otherwise false.
|
||||
*/
|
||||
bool isFunction() const;
|
||||
|
||||
/**
|
||||
* @brief Calls an object as a function.
|
||||
* @param[in] args A se::Value array of arguments to pass to the function. Pass se::EmptyValueArray if argumentCount is 0.
|
||||
* @param[in] thisObject The object to use as "this," or NULL to use the global object as "this."
|
||||
* @param[out] rval The se::Value that results from calling object as a function, passing nullptr if return value is ignored.
|
||||
* @return true if object is a function and there isn't any errors, otherwise false.
|
||||
*/
|
||||
bool call(const ValueArray& args, Object* thisObject, Value* rval = nullptr);
|
||||
|
||||
bool defineFunction(const char *funcName, JSNative func, int minArgs = 0);
|
||||
|
||||
bool isTypedArray() const;
|
||||
bool getTypedArrayData(uint8_t** ptr, size_t* length) const;
|
||||
|
||||
/**
|
||||
* @brief Tests whether an object is an array.
|
||||
* @return true if object is an array, otherwise false.
|
||||
*/
|
||||
bool isArray() const;
|
||||
|
||||
/**
|
||||
* @brief Gets array length of an array object.
|
||||
* @param[out] length The array length to be stored. It's set to 0 if there is an error.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool getArrayLength(uint32_t* length) const;
|
||||
|
||||
/**
|
||||
* @brief Gets an element from an array object by numeric index.
|
||||
* @param[in] index An integer value for index.
|
||||
* @param[out] data The se::Value to be stored for the element in certain index.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool getArrayElement(uint32_t index, Value* data) const;
|
||||
|
||||
/**
|
||||
* @brief Sets an element to an array object by numeric index.
|
||||
* @param[in] index An integer value for index.
|
||||
* @param[in] data The se::Value to be set to array with certain index.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool setArrayElement(uint32_t index, const Value& data);
|
||||
|
||||
/** @brief Tests whether an object is a typed array.
|
||||
* @return true if object is a typed array, otherwise false.
|
||||
*/
|
||||
bool isTypedArray() const;
|
||||
|
||||
/**
|
||||
* @brief Gets the type of a typed array object.
|
||||
* @return The type of a typed array object.
|
||||
*/
|
||||
TypedArrayType getTypedArrayType() const;
|
||||
|
||||
/**
|
||||
* @brief Gets backing store of a typed array object.
|
||||
* @param[out] ptr A temporary pointer to the backing store of a JavaScript Typed Array object.
|
||||
* @param[out] length The byte length of a JavaScript Typed Array object.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool getTypedArrayData(uint8_t** ptr, size_t* length) const;
|
||||
|
||||
/**
|
||||
* @brief Tests whether an object is an array buffer object.
|
||||
* @return true if object is an array buffer object, otherwise false.
|
||||
*/
|
||||
bool isArrayBuffer() const;
|
||||
|
||||
/**
|
||||
* @brief Gets buffer data of an array buffer object.
|
||||
* @param[out] ptr A pointer to the data buffer that serves as the backing store for a JavaScript Typed Array object.
|
||||
* @param[out] length The number of bytes in a JavaScript data object.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool getArrayBufferData(uint8_t** ptr, size_t* length) const;
|
||||
|
||||
/**
|
||||
* @brief Gets all property names of an object.
|
||||
* @param[out] allKeys A string vector to store all property names.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool getAllKeys(std::vector<std::string>* allKeys) const;
|
||||
|
||||
/**
|
||||
* @brief Sets a pointer to private data on an object.
|
||||
* @param[in] data A void* to set as the object's private data.
|
||||
* @note This method will associate private data with se::Object by std::unordered_map::emplace.
|
||||
* It's used for search a se::Object via a void* private data.
|
||||
*/
|
||||
void setPrivateData(void* data);
|
||||
|
||||
/**
|
||||
* @brief Gets an object's private data.
|
||||
* @return A void* that is the object's private data, if the object has private data, otherwise nullptr.
|
||||
*/
|
||||
void* getPrivateData() const;
|
||||
|
||||
/**
|
||||
* @brief Clears private data of an object.
|
||||
*/
|
||||
void clearPrivateData();
|
||||
|
||||
/**
|
||||
* @brief Roots an object from garbage collection.
|
||||
* @note Use this method when you want to store an object in a global or on the heap, where the garbage collector will not be able to discover your reference to it.
|
||||
* An object may be rooted multiple times and must be unrooted an equal number of times before becoming eligible for garbage collection.
|
||||
*/
|
||||
void root();
|
||||
|
||||
/**
|
||||
* @brief Unroots an object from garbage collection.
|
||||
* @note An object may be rooted multiple times and must be unrooted an equal number of times before becoming eligible for garbage collection.
|
||||
*/
|
||||
void unroot();
|
||||
|
||||
/**
|
||||
* @brief Tests whether an object is rooted.
|
||||
* @return true if it has been already rooted, otherwise false.
|
||||
*/
|
||||
bool isRooted() const;
|
||||
|
||||
/**
|
||||
* @brief Tests whether two objects are strict equal, as compared by the JS === operator.
|
||||
* @param[in] o The object to be tested with this object.
|
||||
* @return true if the two values are strict equal, otherwise false.
|
||||
*/
|
||||
bool strictEquals(Object* o) const;
|
||||
|
||||
/**
|
||||
* @brief Attaches an object to current object.
|
||||
* @param[in] obj The object to be attached.
|
||||
* @return true if succeed, otherwise false.
|
||||
* @note This method will set `obj` as a property of current object, therefore the lifecycle of child object will depend on current object,
|
||||
* which means `obj` may be garbage collected only after current object is garbage collected.
|
||||
* It's normally used in binding a native callback method. For example:
|
||||
|
||||
```javascript
|
||||
var self = this;
|
||||
someObject.setCallback(function(){}, self);
|
||||
```
|
||||
|
||||
```c++
|
||||
static bool SomeObject_setCallback(se::State& s)
|
||||
{
|
||||
SomeObject* cobj = (SomeObject*)s.nativeThisObject();
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
if (argc == 2) {
|
||||
std::function<void()> arg0;
|
||||
do {
|
||||
if (args[0].isObject() && args[0].toObject()->isFunction())
|
||||
{
|
||||
se::Value jsThis(args[1]);
|
||||
se::Value jsFunc(args[0]);
|
||||
|
||||
jsThis.toObject()->attachObject(jsFunc.toObject());
|
||||
|
||||
auto lambda = [=]() -> void {
|
||||
...
|
||||
// Call jsFunc stuff...
|
||||
...
|
||||
};
|
||||
arg0 = lambda;
|
||||
}
|
||||
else
|
||||
{
|
||||
arg0 = nullptr;
|
||||
}
|
||||
} while(false);
|
||||
SE_PRECONDITION2(ok, false, "Error processing arguments");
|
||||
cobj->setCallback(arg0);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
```
|
||||
*/
|
||||
bool attachObject(Object* obj);
|
||||
|
||||
/**
|
||||
* @brief Detaches an object from current object.
|
||||
* @param[in] obj The object to be detached.
|
||||
* @return true if succeed, otherwise false.
|
||||
* @note The attached object will not be released if current object is not garbage collected.
|
||||
*/
|
||||
bool detachObject(Object* obj);
|
||||
|
||||
/**
|
||||
* @brief Returns the string for describing current object.
|
||||
* @return The string for describing current object.
|
||||
*/
|
||||
std::string toString() const;
|
||||
|
||||
// Private API used in wrapper
|
||||
static Object* _createJSObject(Class* cls, JSObject* obj);
|
||||
void _setFinalizeCallback(JSFinalizeOp finalizeCb);
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#include "ScriptEngine.hpp"
|
||||
|
||||
#if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_SM
|
||||
@@ -23,7 +46,7 @@
|
||||
#include <sstream>
|
||||
|
||||
#if SE_DEBUG
|
||||
#define TRACE_DEBUGGER_SERVER(...) LOGD(__VA_ARGS__)
|
||||
#define TRACE_DEBUGGER_SERVER(...) SE_LOGD(__VA_ARGS__)
|
||||
#else
|
||||
#define TRACE_DEBUGGER_SERVER(...)
|
||||
#endif // #if COCOS2D_DEBUG
|
||||
@@ -57,7 +80,7 @@ namespace se {
|
||||
MOZ_RELEASE_ASSERT(report);
|
||||
MOZ_RELEASE_ASSERT(JSREPORT_IS_WARNING(report->flags));
|
||||
|
||||
LOGE("%s:%u:%s\n", report->filename ? report->filename : "<no filename>",
|
||||
SE_LOGE("%s:%u:%s\n", report->filename ? report->filename : "<no filename>",
|
||||
(unsigned int) report->lineno,
|
||||
report->message().c_str());
|
||||
}
|
||||
@@ -85,7 +108,7 @@ namespace se {
|
||||
JS::RootedString jsstr(cx, string);
|
||||
char* buffer = JS_EncodeStringToUTF8(cx, jsstr);
|
||||
|
||||
LOGD("JS: %s\n", buffer);
|
||||
SE_LOGD("JS: %s\n", buffer);
|
||||
|
||||
JS_free(cx, buffer);
|
||||
}
|
||||
@@ -123,11 +146,11 @@ namespace se {
|
||||
if (status == JSGC_BEGIN)
|
||||
{
|
||||
ScriptEngine::getInstance()->_setGarbageCollecting(true);
|
||||
LOGD("on_garbage_collect: begin, Native -> JS map count: %d, all objects: %d\n", (int)NativePtrToObjectMap::size(), (int)__objectMap.size());
|
||||
SE_LOGD("on_garbage_collect: begin, Native -> JS map count: %d, all objects: %d\n", (int)NativePtrToObjectMap::size(), (int)__objectMap.size());
|
||||
}
|
||||
else if (status == JSGC_END)
|
||||
{
|
||||
LOGD("on_garbage_collect: end, Native -> JS map count: %d, all objects: %d\n", (int)NativePtrToObjectMap::size(), (int)__objectMap.size());
|
||||
SE_LOGD("on_garbage_collect: end, Native -> JS map count: %d, all objects: %d\n", (int)NativePtrToObjectMap::size(), (int)__objectMap.size());
|
||||
ScriptEngine::getInstance()->_setGarbageCollecting(false);
|
||||
}
|
||||
}
|
||||
@@ -227,7 +250,7 @@ namespace se {
|
||||
if ((argc - msgIndex) == 1)
|
||||
{
|
||||
std::string msg = args[msgIndex].toStringForce();
|
||||
LOGD("JS: %s%s\n", prefix, msg.c_str());
|
||||
SE_LOGD("JS: %s%s\n", prefix, msg.c_str());
|
||||
}
|
||||
else if (argc > 1)
|
||||
{
|
||||
@@ -246,7 +269,7 @@ namespace se {
|
||||
}
|
||||
}
|
||||
|
||||
LOGD("JS: %s%s\n", prefix, msg.c_str());
|
||||
SE_LOGD("JS: %s%s\n", prefix, msg.c_str());
|
||||
}
|
||||
|
||||
return true;
|
||||
@@ -387,7 +410,7 @@ namespace se {
|
||||
bool ScriptEngine::init()
|
||||
{
|
||||
cleanup();
|
||||
LOGD("Initializing SpiderMonkey, version: %s\n", JS_GetImplementationVersion());
|
||||
SE_LOGD("Initializing SpiderMonkey, version: %s\n", JS_GetImplementationVersion());
|
||||
++_vmId;
|
||||
|
||||
for (const auto& hook : _beforeInitHookArray)
|
||||
@@ -766,7 +789,7 @@ namespace se {
|
||||
#endif
|
||||
|
||||
if ((err = getaddrinfo(NULL, portstr.str().c_str(), &hints, &result)) != 0) {
|
||||
LOGD("getaddrinfo error : %s\n", gai_strerror(err));
|
||||
SE_LOGD("getaddrinfo error : %s\n", gai_strerror(err));
|
||||
}
|
||||
|
||||
for (rp = result; rp != NULL; rp = rp->ai_next) {
|
||||
@@ -940,21 +963,30 @@ namespace se {
|
||||
|
||||
bool ScriptEngine::getScript(const std::string& path, JS::MutableHandleScript script)
|
||||
{
|
||||
// a) check jsc file first
|
||||
std::string byteCodePath = removeFileExt(path) + BYTE_CODE_FILE_EXT;
|
||||
if (_filenameScriptMap.find(byteCodePath) != _filenameScriptMap.end())
|
||||
std::string fullPath = _fileOperationDelegate.onGetFullPath(path);
|
||||
auto iter = _filenameScriptMap.find(fullPath);
|
||||
if (iter != _filenameScriptMap.end())
|
||||
{
|
||||
script.set(_filenameScriptMap[byteCodePath]->get());
|
||||
JS::PersistentRootedScript* rootedScript = iter->second;
|
||||
script.set(rootedScript->get());
|
||||
return true;
|
||||
}
|
||||
|
||||
// b) no jsc file, check js file
|
||||
if (_filenameScriptMap.find(path) != _filenameScriptMap.end())
|
||||
{
|
||||
script.set(_filenameScriptMap[path]->get());
|
||||
return true;
|
||||
}
|
||||
|
||||
// // a) check jsc file first
|
||||
// std::string byteCodePath = removeFileExt(path) + BYTE_CODE_FILE_EXT;
|
||||
// if (_filenameScriptMap.find(byteCodePath) != _filenameScriptMap.end())
|
||||
// {
|
||||
// script.set(_filenameScriptMap[byteCodePath]->get());
|
||||
// return true;
|
||||
// }
|
||||
//
|
||||
// // b) no jsc file, check js file
|
||||
// if (_filenameScriptMap.find(path) != _filenameScriptMap.end())
|
||||
// {
|
||||
// script.set(_filenameScriptMap[path]->get());
|
||||
// return true;
|
||||
// }
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -971,28 +1003,31 @@ namespace se {
|
||||
|
||||
bool compileSucceed = false;
|
||||
|
||||
// a) check jsc file first
|
||||
std::string byteCodePath = removeFileExt(path) + BYTE_CODE_FILE_EXT;
|
||||
|
||||
// Check whether '.jsc' files exist to avoid outputting log which says 'couldn't find .jsc file'.
|
||||
if (_fileOperationDelegate.onCheckFileExist(byteCodePath))
|
||||
{
|
||||
_fileOperationDelegate.onGetDataFromFile(byteCodePath, [&](const uint8_t* data, size_t dataLen) {
|
||||
if (data != nullptr && dataLen > 0)
|
||||
{
|
||||
JS::TranscodeBuffer buffer;
|
||||
bool appended = buffer.append(data, dataLen);
|
||||
JS::TranscodeResult result = JS::DecodeScript(_cx, buffer, script);
|
||||
if (appended && result == JS::TranscodeResult::TranscodeResult_Ok)
|
||||
{
|
||||
compileSucceed = true;
|
||||
_filenameScriptMap[byteCodePath] = new (std::nothrow) JS::PersistentRootedScript(_cx, script.get());
|
||||
}
|
||||
assert(compileSucceed);
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
// Creator v1.7 supports v8, spidermonkey, javascriptcore and chakracore as its script engine,
|
||||
// jsc file isn't bytecode format anymore, it's a xxtea encrpted binary format instead.
|
||||
// Therefore, for unifying the flow, ScriptEngine class will not support spidermonkey bytecode.
|
||||
// // a) check jsc file first
|
||||
// std::string byteCodePath = removeFileExt(path) + BYTE_CODE_FILE_EXT;
|
||||
//
|
||||
// // Check whether '.jsc' files exist to avoid outputting log which says 'couldn't find .jsc file'.
|
||||
// if (_fileOperationDelegate.onCheckFileExist(byteCodePath))
|
||||
// {
|
||||
// _fileOperationDelegate.onGetDataFromFile(byteCodePath, [&](const uint8_t* data, size_t dataLen) {
|
||||
// if (data != nullptr && dataLen > 0)
|
||||
// {
|
||||
// JS::TranscodeBuffer buffer;
|
||||
// bool appended = buffer.append(data, dataLen);
|
||||
// JS::TranscodeResult result = JS::DecodeScript(_cx, buffer, script);
|
||||
// if (appended && result == JS::TranscodeResult::TranscodeResult_Ok)
|
||||
// {
|
||||
// compileSucceed = true;
|
||||
// _filenameScriptMap[byteCodePath] = new (std::nothrow) JS::PersistentRootedScript(_cx, script.get());
|
||||
// }
|
||||
// assert(compileSucceed);
|
||||
// }
|
||||
// });
|
||||
//
|
||||
// }
|
||||
|
||||
// b) no jsc file, check js file
|
||||
if (!compileSucceed)
|
||||
@@ -1006,12 +1041,12 @@ namespace se {
|
||||
{
|
||||
JS::CompileOptions op(_cx);
|
||||
op.setUTF8(true);
|
||||
std::string fullPath = _fileOperationDelegate.onGetFullPath(path);
|
||||
op.setFileAndLine(fullPath.c_str(), 1);
|
||||
op.setFileAndLine(path.c_str(), 1);
|
||||
ok = JS::Compile(_cx, op, jsFileContent.c_str(), jsFileContent.size(), script);
|
||||
if (ok)
|
||||
{
|
||||
compileSucceed = true;
|
||||
std::string fullPath = _fileOperationDelegate.onGetFullPath(path);
|
||||
_filenameScriptMap[fullPath] = new (std::nothrow) JS::PersistentRootedScript(_cx, script.get());
|
||||
}
|
||||
assert(compileSucceed);
|
||||
@@ -1022,7 +1057,7 @@ namespace se {
|
||||
|
||||
if (!compileSucceed)
|
||||
{
|
||||
LOGD("ScriptEngine::compileScript fail:%s\n", path.c_str());
|
||||
SE_LOGD("ScriptEngine::compileScript fail:%s\n", path.c_str());
|
||||
}
|
||||
|
||||
return compileSucceed;
|
||||
@@ -1075,12 +1110,10 @@ namespace se {
|
||||
ok = JS_ExecuteScript(_cx, script, &rval);
|
||||
if (!ok)
|
||||
{
|
||||
LOGE("Evaluating %s failed (evaluatedOK == JS_FALSE)\n", path.c_str());
|
||||
SE_LOGE("Evaluating %s failed (evaluatedOK == JS_FALSE)\n", path.c_str());
|
||||
clearException();
|
||||
}
|
||||
|
||||
assert(ok);
|
||||
|
||||
if (ok && ret != nullptr && !rval.isNullOrUndefined())
|
||||
{
|
||||
internal::jsToSeValue(_cx, rval, ret);
|
||||
@@ -1090,42 +1123,6 @@ namespace se {
|
||||
return ok;
|
||||
}
|
||||
|
||||
void ScriptEngine::_retainScriptObject(void* owner, void* target)
|
||||
{
|
||||
auto iterOwner = NativePtrToObjectMap::find(owner);
|
||||
if (iterOwner == NativePtrToObjectMap::end())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
auto iterTarget = NativePtrToObjectMap::find(target);
|
||||
if (iterTarget == NativePtrToObjectMap::end())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
clearException();
|
||||
iterOwner->second->attachObject(iterTarget->second);
|
||||
}
|
||||
|
||||
void ScriptEngine::_releaseScriptObject(void* owner, void* target)
|
||||
{
|
||||
auto iterOwner = NativePtrToObjectMap::find(owner);
|
||||
if (iterOwner == NativePtrToObjectMap::end())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
auto iterTarget = NativePtrToObjectMap::find(target);
|
||||
if (iterTarget == NativePtrToObjectMap::end())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
clearException();
|
||||
iterOwner->second->detachObject(iterTarget->second);
|
||||
}
|
||||
|
||||
void ScriptEngine::clearException()
|
||||
{
|
||||
if (_cx == nullptr)
|
||||
@@ -1165,7 +1162,7 @@ namespace se {
|
||||
exceptionStr += stack;
|
||||
}
|
||||
|
||||
LOGE("ERROR: %s\n", exceptionStr.c_str());
|
||||
SE_LOGE("ERROR: %s\n", exceptionStr.c_str());
|
||||
if (_exceptionCallback != nullptr)
|
||||
{
|
||||
_exceptionCallback(location.c_str(), message, stack);
|
||||
@@ -1190,7 +1187,7 @@ namespace se {
|
||||
}
|
||||
else
|
||||
{
|
||||
LOGE("ERROR: __errorHandler has exception\n");
|
||||
SE_LOGE("ERROR: __errorHandler has exception\n");
|
||||
}
|
||||
|
||||
if (stack != nullptr)
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#pragma once
|
||||
|
||||
#include "../config.hpp"
|
||||
@@ -13,7 +36,13 @@ namespace se {
|
||||
class Value;
|
||||
|
||||
extern Class* __jsb_CCPrivateData_class;
|
||||
|
||||
|
||||
/**
|
||||
* A stack-allocated class that governs a number of local handles.
|
||||
* It's only implemented for v8 wrapper now.
|
||||
* Other script engine wrappers have empty implementation for this class.
|
||||
* It's used at the beginning of executing any wrapper API.
|
||||
*/
|
||||
class AutoHandleScope
|
||||
{
|
||||
public:
|
||||
@@ -21,24 +50,52 @@ namespace se {
|
||||
~AutoHandleScope();
|
||||
};
|
||||
|
||||
/**
|
||||
* ScriptEngine is a sington which represents a context of JavaScript VM.
|
||||
*/
|
||||
class ScriptEngine final
|
||||
{
|
||||
private:
|
||||
ScriptEngine();
|
||||
~ScriptEngine();
|
||||
|
||||
public:
|
||||
/**
|
||||
* @brief Gets or creates the instance of script engine.
|
||||
* @return The script engine instance.
|
||||
*/
|
||||
static ScriptEngine* getInstance();
|
||||
|
||||
/**
|
||||
* @brief Destroys the instance of script engine.
|
||||
*/
|
||||
static void destroyInstance();
|
||||
|
||||
/**
|
||||
* @brief Gets the global object of JavaScript VM.
|
||||
* @return The se::Object stores the global JavaScript object.
|
||||
*/
|
||||
Object* getGlobalObject();
|
||||
|
||||
typedef bool (*RegisterCallback)(Object*);
|
||||
|
||||
/**
|
||||
* @brief Adds a callback for registering a native binding module.
|
||||
* @param[in] cb A callback for registering a native binding module.
|
||||
* @note This method just add a callback to a vector, callbacks is invoked in `start` method.
|
||||
*/
|
||||
void addRegisterCallback(RegisterCallback cb);
|
||||
|
||||
/**
|
||||
* @brief Starts the script engine.
|
||||
* @return true if succeed, otherwise false.
|
||||
* @note This method will invoke all callbacks of native binding modules by the order of registration.
|
||||
*/
|
||||
bool start();
|
||||
|
||||
/**
|
||||
* @brief Initializes script engine.
|
||||
* @return true if succeed, otherwise false.
|
||||
* @note This method will create JavaScript context and global object.
|
||||
*/
|
||||
bool init();
|
||||
void cleanup();
|
||||
|
||||
/**
|
||||
* @brief Adds a hook function before initializing script engine.
|
||||
* @param[in] hook A hook function to be invoked before initializing script engine.
|
||||
@@ -53,11 +110,39 @@ namespace se {
|
||||
*/
|
||||
void addAfterInitHook(const std::function<void()>& hook);
|
||||
|
||||
/**
|
||||
* @brief Cleanups script engine.
|
||||
* @note This method will removes all objects in JavaScript VM even whose are rooted, then shutdown JavaScript VMf.
|
||||
*/
|
||||
void cleanup();
|
||||
|
||||
/**
|
||||
* @brief Adds a hook function before cleanuping script engine.
|
||||
* @param[in] hook A hook function to be invoked before cleanuping script engine.
|
||||
* @note Multiple hook functions could be added, they will be invoked by the order of adding.
|
||||
*/
|
||||
void addBeforeCleanupHook(const std::function<void()>& hook);
|
||||
|
||||
/**
|
||||
* @brief Adds a hook function after cleanuping script engine.
|
||||
* @param[in] hook A hook function to be invoked after cleanuping script engine.
|
||||
* @note Multiple hook functions could be added, they will be invoked by the order of adding.
|
||||
*/
|
||||
void addAfterCleanupHook(const std::function<void()>& hook);
|
||||
|
||||
bool evalString(const char* string, ssize_t length = -1, Value* ret = nullptr, const char* fileName = nullptr);
|
||||
/**
|
||||
* @brief Executes a utf-8 string buffer which contains JavaScript code.
|
||||
* @param[in] scriptStr A utf-8 string buffer, if it isn't null-terminated, parameter `length` should be assigned and > 0.
|
||||
* @param[in] length The length of parameter `scriptStr`, it will be set to string length internally if passing < 0 and parameter `scriptStr` is null-terminated.
|
||||
* @param[in] rval The se::Value that results from evaluating script. Passing nullptr if you don't care about the result.
|
||||
* @param[in] fileName A string containing a URL for the script's source file. This is used by debuggers and when reporting exceptions. Pass NULL if you do not care to include source file information.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool evalString(const char* scriptStr, ssize_t length = -1, Value* rval = nullptr, const char* fileName = nullptr);
|
||||
|
||||
/**
|
||||
* Delegate class for file operation
|
||||
*/
|
||||
class FileOperationDelegate
|
||||
{
|
||||
public:
|
||||
@@ -84,38 +169,94 @@ namespace se {
|
||||
std::function<std::string(const std::string&)> onGetFullPath;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Sets the delegate for file operation.
|
||||
* @param delegate[in] The delegate instance for file operation.
|
||||
*/
|
||||
void setFileOperationDelegate(const FileOperationDelegate& delegate);
|
||||
|
||||
bool runScript(const std::string& fullPath, Value* ret = nullptr);
|
||||
|
||||
JSContext* _getContext() { return _cx; }
|
||||
/**
|
||||
* @brief Executes a file which contains JavaScript code.
|
||||
* @param[in] path Script file path.
|
||||
* @param[in] rval The se::Value that results from evaluating script. Passing nullptr if you don't care about the result.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool runScript(const std::string& path, Value* rval = nullptr);
|
||||
|
||||
/**
|
||||
* @brief Tests whether script engine is doing garbage collection.
|
||||
* @return true if it's in garbage collection, otherwise false.
|
||||
*/
|
||||
bool isGarbageCollecting();
|
||||
void _setGarbageCollecting(bool isGarbageCollecting);
|
||||
|
||||
/**
|
||||
* @brief Performs a JavaScript garbage collection.
|
||||
*/
|
||||
void garbageCollect() { JS_GC( _cx ); }
|
||||
|
||||
bool isValid() { return _isValid; }
|
||||
/**
|
||||
* @brief Tests whether script engine is being cleaned up.
|
||||
* @return true if it's in cleaning up, otherwise false.
|
||||
*/
|
||||
bool isInCleanup() { return _isInCleanup; }
|
||||
|
||||
/**
|
||||
* @brief Tests whether script engine is valid.
|
||||
* @return true if it's valid, otherwise false.
|
||||
*/
|
||||
bool isValid() { return _isValid; }
|
||||
|
||||
/**
|
||||
* @brief Clears all exceptions.
|
||||
*/
|
||||
void clearException();
|
||||
|
||||
using ExceptionCallback = std::function<void(const char*, const char*, const char*)>; // location, message, stack
|
||||
|
||||
/**
|
||||
* @brief Sets the callback function while an exception is fired.
|
||||
* @param[in] cb The callback function to notify that an exception is fired.
|
||||
*/
|
||||
void setExceptionCallback(const ExceptionCallback& cb);
|
||||
|
||||
/**
|
||||
* @brief Gets the start time of script engine.
|
||||
* @return The start time of script engine.
|
||||
*/
|
||||
const std::chrono::steady_clock::time_point& getStartTime() const { return _startTime; }
|
||||
|
||||
/**
|
||||
* @brief Enables JavaScript debugger
|
||||
* @param[in] serverAddr The address of debugger server.
|
||||
* @param[in] port The port of debugger server will use.
|
||||
*/
|
||||
void enableDebugger(const std::string& serverAddr, uint32_t port);
|
||||
|
||||
/**
|
||||
* @brief Tests whether JavaScript debugger is enabled
|
||||
* @return true if JavaScript debugger is enabled, otherwise false.
|
||||
*/
|
||||
bool isDebuggerEnabled() const;
|
||||
|
||||
/**
|
||||
* @brief Main loop update trigger, it's need to invoked in main thread every frame.
|
||||
*/
|
||||
void mainLoopUpdate();
|
||||
|
||||
/**
|
||||
* @brief Gets script virtual machine instance ID. Default value is 1, increase by 1 if `init` is invoked.
|
||||
*/
|
||||
uint32_t getVMId() const { return _vmId; }
|
||||
|
||||
void _retainScriptObject(void* owner, void* target);
|
||||
void _releaseScriptObject(void* owner, void* target);
|
||||
|
||||
// Private API used in wrapper
|
||||
JSContext* _getContext() { return _cx; }
|
||||
void _setGarbageCollecting(bool isGarbageCollecting);
|
||||
void _debugProcessInput(const std::string& str);
|
||||
|
||||
//
|
||||
private:
|
||||
ScriptEngine();
|
||||
~ScriptEngine();
|
||||
|
||||
static void onWeakPointerCompartmentCallback(JSContext* cx, JSCompartment* comp, void* data);
|
||||
static void onWeakPointerZoneGroupCallback(JSContext* cx, void* data);
|
||||
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#pragma once
|
||||
|
||||
#include "ScriptEngine.hpp"
|
||||
|
||||
@@ -1,11 +1,26 @@
|
||||
//
|
||||
// Utils.cpp
|
||||
// cocos2d_js_bindings
|
||||
//
|
||||
// Created by James Chen on 4/26/17.
|
||||
//
|
||||
//
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#include "Utils.hpp"
|
||||
|
||||
#if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_SM
|
||||
@@ -18,6 +33,13 @@ namespace se {
|
||||
|
||||
namespace internal {
|
||||
|
||||
void forceConvertJsValueToStdString(JSContext* cx, JS::HandleValue jsval, std::string* ret)
|
||||
{
|
||||
assert(ret != nullptr);
|
||||
JS::RootedString jsStr(cx, JS::ToString(cx, jsval));
|
||||
*ret = jsToStdString(cx, jsStr);
|
||||
}
|
||||
|
||||
std::string jsToStdString(JSContext* cx, JS::HandleString jsStr)
|
||||
{
|
||||
char* str = JS_EncodeStringToUTF8(cx, jsStr);
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#pragma once
|
||||
|
||||
#include "../config.hpp"
|
||||
@@ -20,6 +43,7 @@ namespace se {
|
||||
JSFinalizeOp finalizeCb;
|
||||
};
|
||||
|
||||
void forceConvertJsValueToStdString(JSContext* cx, JS::HandleValue jsval, std::string* ret);
|
||||
std::string jsToStdString(JSContext* cx, JS::HandleString jsStr);
|
||||
|
||||
void jsToSeArgs(JSContext* cx, int argc, const JS::CallArgs& argv, ValueArray* outArr);
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#pragma once
|
||||
|
||||
#include "libplatform/libplatform.h"
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#include "Class.hpp"
|
||||
|
||||
#if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_V8
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#pragma once
|
||||
|
||||
#include "../config.hpp"
|
||||
@@ -10,34 +33,95 @@ namespace se {
|
||||
|
||||
class Object;
|
||||
|
||||
/**
|
||||
* se::Class represents a definition of how to create a native binding object.
|
||||
*/
|
||||
class Class final
|
||||
{
|
||||
private:
|
||||
Class();
|
||||
~Class();
|
||||
public:
|
||||
/**
|
||||
* @brief Creates a class used for creating relevant native binding objects.
|
||||
* @param[in] className A null-terminated UTF8 string containing the class's name.
|
||||
* @param[in] obj The object that current class proto object attaches to. Should not be nullptr.
|
||||
* @param[in] parentProto The parent proto object that current class inherits from. Passing nullptr means a new class has no parent.
|
||||
* @param[in] ctor A callback to invoke when your constructor is used in a 'new' expression. Pass nullptr to use the default object constructor.
|
||||
* @return A class instance used for creating relevant native binding objects.
|
||||
* @note Don't need to delete the pointer return by this method, it's managed internally.
|
||||
*/
|
||||
static Class* create(const std::string& className, Object* obj, Object* parentProto, v8::FunctionCallback ctor);
|
||||
|
||||
static Class* create(const std::string& clsName, Object* parent, Object* parentProto, v8::FunctionCallback ctor);
|
||||
|
||||
bool install();
|
||||
void destroy();
|
||||
|
||||
/**
|
||||
* @brief Defines a member function with a callback. Each objects created by class will have this function property.
|
||||
* @param[in] name A null-terminated UTF8 string containing the function name.
|
||||
* @param[in] func A callback to invoke when the property is called as a function.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool defineFunction(const char *name, v8::FunctionCallback func);
|
||||
bool defineProperty(const char *name, v8::AccessorNameGetterCallback getter, v8::AccessorNameSetterCallback setter);
|
||||
bool defineStaticFunction(const char *name, v8::FunctionCallback func);
|
||||
bool defineStaticProperty(const char *name, v8::AccessorNameGetterCallback getter, v8::AccessorNameSetterCallback setter);
|
||||
bool defineFinalizeFunction(V8FinalizeFunc finalizeFunc);
|
||||
|
||||
/**
|
||||
* @brief Defines a property with accessor callbacks. Each objects created by class will have this property.
|
||||
* @param[in] name A null-terminated UTF8 string containing the property name.
|
||||
* @param[in] getter A callback to invoke when the property is read.
|
||||
* @param[in] setter A callback to invoke when the property is set.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool defineProperty(const char *name, v8::AccessorNameGetterCallback getter, v8::AccessorNameSetterCallback setter);
|
||||
|
||||
/**
|
||||
* @brief Defines a static function with a callback. Only JavaScript constructor object will have this function.
|
||||
* @param[in] name A null-terminated UTF8 string containing the function name.
|
||||
* @param[in] func A callback to invoke when the constructor's property is called as a function.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool defineStaticFunction(const char *name, v8::FunctionCallback func);
|
||||
|
||||
/**
|
||||
* @brief Defines a static property with accessor callbacks. Only JavaScript constructor object will have this property.
|
||||
* @param[in] name A null-terminated UTF8 string containing the property name.
|
||||
* @param[in] getter A callback to invoke when the constructor's property is read.
|
||||
* @param[in] setter A callback to invoke when the constructor's property is set.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool defineStaticProperty(const char *name, v8::AccessorNameGetterCallback getter, v8::AccessorNameSetterCallback setter);
|
||||
|
||||
/**
|
||||
* @brief Defines the finalize function with a callback.
|
||||
* @param[in] func The callback to invoke when a JavaScript object is garbage collected.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool defineFinalizeFunction(V8FinalizeFunc func);
|
||||
|
||||
/**
|
||||
* @brief Installs class to JavaScript VM.
|
||||
* @return true if succeed, otherwise false.
|
||||
* @note After this method, an object could be created by `var foo = new Foo();`.
|
||||
*/
|
||||
bool install();
|
||||
|
||||
/**
|
||||
* @brief Gets the proto object of this class.
|
||||
* @return The proto object of this class.
|
||||
* @note Don't need to be released in user code.
|
||||
*/
|
||||
Object* getProto() const;
|
||||
|
||||
V8FinalizeFunc _getFinalizeFunction() const;
|
||||
|
||||
/**
|
||||
* @brief Gets the class name.
|
||||
* @return The class name.
|
||||
*/
|
||||
const char* getName() const { return _name.c_str(); }
|
||||
|
||||
// Private API used in wrapper
|
||||
V8FinalizeFunc _getFinalizeFunction() const;
|
||||
private:
|
||||
Class();
|
||||
~Class();
|
||||
|
||||
void setCreateProto(bool createProto);
|
||||
|
||||
bool init(const std::string& clsName, Object* parent, Object* parentProto, v8::FunctionCallback ctor);
|
||||
void destroy();
|
||||
|
||||
static void cleanup();
|
||||
// static v8::Local<v8::Object> _createJSObject(const std::string &clsName, Class** outCls);
|
||||
static v8::Local<v8::Object> _createJSObjectWithClass(Class* cls);
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#pragma once
|
||||
|
||||
#include "../config.hpp"
|
||||
@@ -31,6 +54,9 @@
|
||||
void* nativeThisObject = se::internal::getPrivate(_isolate, _v8args.This()); \
|
||||
se::State state(nativeThisObject, args); \
|
||||
ret = funcName(state); \
|
||||
if (!ret) { \
|
||||
SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \
|
||||
} \
|
||||
se::internal::setReturnValue(state.rval(), _v8args); \
|
||||
}
|
||||
|
||||
@@ -42,7 +68,10 @@
|
||||
auto se = se::ScriptEngine::getInstance(); \
|
||||
se->_setGarbageCollecting(true); \
|
||||
se::State state(nativeThisObject); \
|
||||
SE_UNUSED bool ok = funcName(state); \
|
||||
bool ret = funcName(state); \
|
||||
if (!ret) { \
|
||||
SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \
|
||||
} \
|
||||
se->_setGarbageCollecting(false); \
|
||||
}
|
||||
|
||||
@@ -55,13 +84,16 @@
|
||||
{ \
|
||||
v8::Isolate* _isolate = _v8args.GetIsolate(); \
|
||||
v8::HandleScope _hs(_isolate); \
|
||||
SE_UNUSED bool ret = true; \
|
||||
bool ret = true; \
|
||||
se::ValueArray args; \
|
||||
se::internal::jsToSeArgs(_v8args, &args); \
|
||||
se::Object* thisObject = se::Object::_createJSObject(cls, _v8args.This()); \
|
||||
thisObject->_setFinalizeCallback(_SE(finalizeCb)); \
|
||||
se::State state(thisObject, args); \
|
||||
ret = funcName(state); \
|
||||
if (!ret) { \
|
||||
SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \
|
||||
} \
|
||||
se::Value _property; \
|
||||
bool _found = false; \
|
||||
_found = thisObject->getProperty("_ctor", &_property); \
|
||||
@@ -80,6 +112,9 @@
|
||||
void* nativeThisObject = se::internal::getPrivate(_isolate, _v8args.This()); \
|
||||
se::State state(nativeThisObject); \
|
||||
ret = funcName(state); \
|
||||
if (!ret) { \
|
||||
SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \
|
||||
} \
|
||||
se::internal::setReturnValue(state.rval(), _v8args); \
|
||||
}
|
||||
|
||||
@@ -97,6 +132,9 @@
|
||||
args.push_back(std::move(data)); \
|
||||
se::State state(nativeThisObject, args); \
|
||||
ret = funcName(state); \
|
||||
if (!ret) { \
|
||||
SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", #funcName, __FILE__, __LINE__); \
|
||||
} \
|
||||
}
|
||||
|
||||
|
||||
@@ -107,7 +145,7 @@
|
||||
#define SE_QUOTEME(x) SE_QUOTEME_(x)
|
||||
|
||||
//FIXME: implement this macro
|
||||
#define SE_REPORT_ERROR(fmt, ...) LOGD("ERROR (" __FILE__ ", " SE_QUOTEME(__LINE__) "): " fmt "\n", ##__VA_ARGS__)
|
||||
#define SE_REPORT_ERROR(fmt, ...) SE_LOGE("[ERROR] (" __FILE__ ", " SE_QUOTEME(__LINE__) "): " fmt "\n", ##__VA_ARGS__)
|
||||
|
||||
#if COCOS2D_DEBUG > 0
|
||||
|
||||
@@ -116,7 +154,7 @@
|
||||
{ \
|
||||
if (!(cond)) \
|
||||
{ \
|
||||
LOGD("ASSERT (" __FILE__ ", " SE_QUOTEME(__LINE__) "): " fmt "\n", ##__VA_ARGS__); \
|
||||
SE_LOGE("ASSERT (" __FILE__ ", " SE_QUOTEME(__LINE__) "): " fmt "\n", ##__VA_ARGS__); \
|
||||
assert(false); \
|
||||
} \
|
||||
} while(false)
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#include "Object.hpp"
|
||||
|
||||
#if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_V8
|
||||
@@ -186,15 +209,62 @@ namespace se {
|
||||
return obj;
|
||||
}
|
||||
|
||||
Object* Object::createUint8TypedArray(uint8_t* data, size_t byteLength)
|
||||
Object* Object::createTypedArray(TypedArrayType type, void* data, size_t byteLength)
|
||||
{
|
||||
if (type == TypedArrayType::NONE)
|
||||
{
|
||||
SE_LOGE("Don't pass se::Object::TypedArrayType::NONE to createTypedArray API!");
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
if (type == TypedArrayType::UINT8_CLAMPED)
|
||||
{
|
||||
SE_LOGE("Doesn't support to create Uint8ClampedArray with Object::createTypedArray API!");
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
v8::Local<v8::ArrayBuffer> jsobj = v8::ArrayBuffer::New(__isolate, byteLength);
|
||||
memcpy(jsobj->GetContents().Data(), data, byteLength);
|
||||
v8::Local<v8::Uint8Array> arr = v8::Uint8Array::New(jsobj, 0, byteLength);
|
||||
v8::Local<v8::Object> arr;
|
||||
switch (type) {
|
||||
case TypedArrayType::INT8:
|
||||
arr = v8::Int8Array::New(jsobj, 0, byteLength);
|
||||
break;
|
||||
case TypedArrayType::INT16:
|
||||
arr = v8::Int16Array::New(jsobj, 0, byteLength / 2);
|
||||
break;
|
||||
case TypedArrayType::INT32:
|
||||
arr = v8::Int32Array::New(jsobj, 0, byteLength / 4);
|
||||
break;
|
||||
case TypedArrayType::UINT8:
|
||||
arr = v8::Uint8Array::New(jsobj, 0, byteLength);
|
||||
break;
|
||||
case TypedArrayType::UINT16:
|
||||
arr = v8::Uint16Array::New(jsobj, 0, byteLength / 2);
|
||||
break;
|
||||
case TypedArrayType::UINT32:
|
||||
arr = v8::Uint32Array::New(jsobj, 0, byteLength / 4);
|
||||
break;
|
||||
case TypedArrayType::FLOAT32:
|
||||
arr = v8::Float32Array::New(jsobj, 0, byteLength / 4);
|
||||
break;
|
||||
case TypedArrayType::FLOAT64:
|
||||
arr = v8::Float64Array::New(jsobj, 0, byteLength / 8);
|
||||
break;
|
||||
default:
|
||||
assert(false); // Should never go here.
|
||||
break;
|
||||
}
|
||||
|
||||
Object* obj = Object::_createJSObject(nullptr, arr);
|
||||
return obj;
|
||||
}
|
||||
|
||||
Object* Object::createUint8TypedArray(uint8_t* data, size_t dataCount)
|
||||
{
|
||||
return createTypedArray(TypedArrayType::UINT8, data, dataCount);
|
||||
}
|
||||
|
||||
Object* Object::createJSONObject(const std::string& jsonStr)
|
||||
{
|
||||
v8::Local<v8::Context> context = __isolate->GetCurrentContext();
|
||||
@@ -267,7 +337,7 @@ namespace se {
|
||||
v8::Maybe<bool> ret = _obj.handle(__isolate)->Set(__isolate->GetCurrentContext(), nameValue.ToLocalChecked(), value);
|
||||
if (ret.IsNothing())
|
||||
{
|
||||
LOGD("ERROR: %s, Set return nothing ...\n", __FUNCTION__);
|
||||
SE_LOGD("ERROR: %s, Set return nothing ...\n", __FUNCTION__);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
@@ -294,8 +364,7 @@ namespace se {
|
||||
{
|
||||
if (isFunction())
|
||||
{
|
||||
v8::String::Utf8Value utf8(const_cast<Object*>(this)->_obj.handle(__isolate));
|
||||
std::string info = *utf8;
|
||||
std::string info = toString();
|
||||
if (info.find("[native code]") != std::string::npos)
|
||||
{
|
||||
return true;
|
||||
@@ -309,14 +378,40 @@ namespace se {
|
||||
return const_cast<Object*>(this)->_obj.handle(__isolate)->IsTypedArray();
|
||||
}
|
||||
|
||||
Object::TypedArrayType Object::getTypedArrayType() const
|
||||
{
|
||||
v8::Local<v8::Value> value = const_cast<Object*>(this)->_obj.handle(__isolate);
|
||||
TypedArrayType ret = TypedArrayType::NONE;
|
||||
if (value->IsInt8Array())
|
||||
ret = TypedArrayType::INT8;
|
||||
else if (value->IsInt16Array())
|
||||
ret = TypedArrayType::INT16;
|
||||
else if (value->IsInt32Array())
|
||||
ret = TypedArrayType::INT32;
|
||||
else if (value->IsUint8Array())
|
||||
ret = TypedArrayType::UINT8;
|
||||
else if (value->IsUint8ClampedArray())
|
||||
ret = TypedArrayType::UINT8_CLAMPED;
|
||||
else if (value->IsUint16Array())
|
||||
ret = TypedArrayType::UINT16;
|
||||
else if (value->IsUint32Array())
|
||||
ret = TypedArrayType::UINT32;
|
||||
else if (value->IsFloat32Array())
|
||||
ret = TypedArrayType::FLOAT32;
|
||||
else if (value->IsFloat64Array())
|
||||
ret = TypedArrayType::FLOAT64;
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
bool Object::getTypedArrayData(uint8_t** ptr, size_t* length) const
|
||||
{
|
||||
assert(isTypedArray());
|
||||
v8::Local<v8::Object> obj = const_cast<Object*>(this)->_obj.handle(__isolate);
|
||||
v8::Local<v8::Uint8Array> arr = v8::Local<v8::Uint8Array>::Cast(obj);
|
||||
v8::Local<v8::TypedArray> arr = v8::Local<v8::TypedArray>::Cast(obj);
|
||||
v8::ArrayBuffer::Contents content = arr->Buffer()->GetContents();
|
||||
*ptr = (uint8_t*)content.Data();
|
||||
*length = content.ByteLength();
|
||||
*ptr = (uint8_t*)content.Data() + arr->ByteOffset();
|
||||
*length = arr->ByteLength();
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -380,7 +475,7 @@ namespace se {
|
||||
{
|
||||
if (_obj.persistent().IsEmpty())
|
||||
{
|
||||
LOGD("Function object is released!\n");
|
||||
SE_LOGD("Function object is released!\n");
|
||||
return false;
|
||||
}
|
||||
size_t argc = 0;
|
||||
@@ -393,7 +488,7 @@ namespace se {
|
||||
{
|
||||
if (thisObject->_obj.persistent().IsEmpty())
|
||||
{
|
||||
LOGD("This object is released!\n");
|
||||
SE_LOGD("This object is released!\n");
|
||||
return false;
|
||||
}
|
||||
thiz = thisObject->_obj.handle(__isolate);
|
||||
@@ -403,7 +498,7 @@ namespace se {
|
||||
{
|
||||
if (argv[i].IsEmpty())
|
||||
{
|
||||
LOGD("%s argv[%d] is released!\n", __FUNCTION__, (int)i);
|
||||
SE_LOGD("%s argv[%d] is released!\n", __FUNCTION__, (int)i);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -694,6 +789,24 @@ namespace se {
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string Object::toString() const
|
||||
{
|
||||
std::string ret;
|
||||
if (isFunction() || isArray() || isTypedArray())
|
||||
{
|
||||
v8::String::Utf8Value utf8(const_cast<Object*>(this)->_obj.handle(__isolate));
|
||||
ret = *utf8;
|
||||
}
|
||||
else if (isArrayBuffer())
|
||||
{
|
||||
ret = "[object ArrayBuffer]";
|
||||
}
|
||||
else
|
||||
{
|
||||
ret = "[object Object]";
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
} // namespace se {
|
||||
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#pragma once
|
||||
|
||||
#include "../config.hpp"
|
||||
@@ -17,53 +40,322 @@ namespace se {
|
||||
struct PrivateData;
|
||||
}
|
||||
|
||||
/**
|
||||
* se::Object represents JavaScript Object.
|
||||
*/
|
||||
class Object final : public RefCounter
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief Creates a JavaScript Object like `{} or new Object()`.
|
||||
* @return A JavaScript Object, or nullptr if there is an error.
|
||||
* @note The return value (non-null) has to be released manually.
|
||||
*/
|
||||
static Object* createPlainObject();
|
||||
|
||||
/**
|
||||
* @brief Creates a JavaScript Array Object like `[] or new Array()`.
|
||||
* @param[in] length The initical length of array.
|
||||
* @return A JavaScript Array Object, or nullptr if there is an error.
|
||||
* @note The return value (non-null) has to be released manually.
|
||||
*/
|
||||
static Object* createArrayObject(size_t length);
|
||||
static Object* createUint8TypedArray(uint8_t* data, size_t byteLength);
|
||||
static Object* createArrayBufferObject(void* data, size_t byteLength);
|
||||
|
||||
/**
|
||||
* @brief Creates a JavaScript Typed Array Object with uint8 format from an existing pointer.
|
||||
* @param[in] bytes A pointer to the byte buffer to be used as the backing store of the Typed Array object.
|
||||
* @param[in] byteLength The number of bytes pointed to by the parameter bytes.
|
||||
* @return A JavaScript Typed Array Object whose backing store is the same as the one pointed data, or nullptr if there is an error.
|
||||
* @note The return value (non-null) has to be released manually.
|
||||
* @deprecated This method is deprecated, please use `se::Object::createTypedArray` instead.
|
||||
*/
|
||||
SE_DEPRECATED_ATTRIBUTE static Object* createUint8TypedArray(uint8_t* bytes, size_t byteLength);
|
||||
|
||||
enum class TypedArrayType
|
||||
{
|
||||
NONE,
|
||||
INT8,
|
||||
INT16,
|
||||
INT32,
|
||||
UINT8,
|
||||
UINT8_CLAMPED,
|
||||
UINT16,
|
||||
UINT32,
|
||||
FLOAT32,
|
||||
FLOAT64
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Creates a JavaScript Typed Array Object with specified format from an existing pointer.
|
||||
* @param[in] type The format of typed array.
|
||||
* @param[in] data A pointer to the byte buffer to be used as the backing store of the Typed Array object.
|
||||
* @param[in] byteLength The number of bytes pointed to by the parameter bytes.
|
||||
* @return A JavaScript Typed Array Object whose backing store is the same as the one pointed data, or nullptr if there is an error.
|
||||
* @note The return value (non-null) has to be released manually.
|
||||
*/
|
||||
static Object* createTypedArray(TypedArrayType type, void* data, size_t byteLength);
|
||||
|
||||
/**
|
||||
* @brief Creates a JavaScript Array Buffer object from an existing pointer.
|
||||
* @param[in] bytes A pointer to the byte buffer to be used as the backing store of the Typed Array object.
|
||||
* @param[in] byteLength The number of bytes pointed to by the parameter bytes.
|
||||
* @return A Array Buffer Object whose backing store is the same as the one pointed to data, or nullptr if there is an error.
|
||||
* @note The return value (non-null) has to be released manually.
|
||||
*/
|
||||
static Object* createArrayBufferObject(void* bytes, size_t byteLength);
|
||||
|
||||
/**
|
||||
* @brief Creates a JavaScript Object from a JSON formatted string.
|
||||
* @param[in] jsonStr The utf-8 string containing the JSON string to be parsed.
|
||||
* @return A JavaScript Object containing the parsed value, or nullptr if the input is invalid.
|
||||
* @note The return value (non-null) has to be released manually.
|
||||
*/
|
||||
static Object* createJSONObject(const std::string& jsonStr);
|
||||
static Object* getObjectWithPtr(void* ptr);
|
||||
|
||||
/**
|
||||
* @brief Creates a JavaScript Native Binding Object from an existing se::Class instance.
|
||||
* @param[in] cls The se::Class instance which stores native callback informations.
|
||||
* @return A JavaScript Native Binding Object, or nullptr if there is an error.
|
||||
* @note The return value (non-null) has to be released manually.
|
||||
*/
|
||||
static Object* createObjectWithClass(Class* cls);
|
||||
|
||||
/**
|
||||
* @brief Gets a se::Object from an existing native object pointer.
|
||||
* @param[in] ptr The native object pointer associated with the se::Object
|
||||
* @return A JavaScript Native Binding Object, or nullptr if there is an error.
|
||||
* @note The return value (non-null) has to be released manually.
|
||||
*/
|
||||
static Object* getObjectWithPtr(void* ptr);
|
||||
|
||||
bool getProperty(const char *name, Value* data);
|
||||
bool setProperty(const char *name, const Value& data);
|
||||
/**
|
||||
* @brief Gets a property from an object.
|
||||
* @param[in] name A utf-8 string containing the property's name.
|
||||
* @param[out] value The property's value if object has the property, otherwise the undefined value.
|
||||
* @return true if object has the property, otherwise false.
|
||||
*/
|
||||
bool getProperty(const char *name, Value* value);
|
||||
|
||||
/**
|
||||
* @brief Sets a property to an object.
|
||||
* @param[in] name A utf-8 string containing the property's name.
|
||||
* @param[in] value A value to be used as the property's value.
|
||||
* @return true if the property is set successfully, otherwise false.
|
||||
*/
|
||||
bool setProperty(const char *name, const Value& value);
|
||||
|
||||
/**
|
||||
* @brief Defines a property with native accessor callbacks for an object.
|
||||
* @param[in] name A utf-8 string containing the property's name.
|
||||
* @param[in] getter The native callback for getter.
|
||||
* @param[in] setter The native callback for setter.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool defineProperty(const char *name, v8::AccessorNameGetterCallback getter, v8::AccessorNameSetterCallback setter);
|
||||
|
||||
bool isFunction() const;
|
||||
|
||||
bool call(const ValueArray& args, Object* thisObject, Value* rval = nullptr);
|
||||
|
||||
/**
|
||||
* @brief Defines a function with a native callback for an object.
|
||||
* @param[in] funcName A utf-8 string containing the function name.
|
||||
* @param[in] func The native callback triggered by JavaScript code.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool defineFunction(const char *funcName, v8::FunctionCallback func);
|
||||
|
||||
bool isTypedArray() const;
|
||||
bool getTypedArrayData(uint8_t** ptr, size_t* length) const;
|
||||
/**
|
||||
* @brief Tests whether an object can be called as a function.
|
||||
* @return true if object can be called as a function, otherwise false.
|
||||
*/
|
||||
bool isFunction() const;
|
||||
|
||||
/**
|
||||
* @brief Calls an object as a function.
|
||||
* @param[in] args A se::Value array of arguments to pass to the function. Pass se::EmptyValueArray if argumentCount is 0.
|
||||
* @param[in] thisObject The object to use as "this," or NULL to use the global object as "this."
|
||||
* @param[out] rval The se::Value that results from calling object as a function, passing nullptr if return value is ignored.
|
||||
* @return true if object is a function and there isn't any errors, otherwise false.
|
||||
*/
|
||||
bool call(const ValueArray& args, Object* thisObject, Value* rval = nullptr);
|
||||
|
||||
/**
|
||||
* @brief Tests whether an object is an array.
|
||||
* @return true if object is an array, otherwise false.
|
||||
*/
|
||||
bool isArray() const;
|
||||
|
||||
/**
|
||||
* @brief Gets array length of an array object.
|
||||
* @param[out] length The array length to be stored. It's set to 0 if there is an error.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool getArrayLength(uint32_t* length) const;
|
||||
|
||||
/**
|
||||
* @brief Gets an element from an array object by numeric index.
|
||||
* @param[in] index An integer value for index.
|
||||
* @param[out] data The se::Value to be stored for the element in certain index.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool getArrayElement(uint32_t index, Value* data) const;
|
||||
|
||||
/**
|
||||
* @brief Sets an element to an array object by numeric index.
|
||||
* @param[in] index An integer value for index.
|
||||
* @param[in] data The se::Value to be set to array with certain index.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool setArrayElement(uint32_t index, const Value& data);
|
||||
|
||||
/** @brief Tests whether an object is a typed array.
|
||||
* @return true if object is a typed array, otherwise false.
|
||||
*/
|
||||
bool isTypedArray() const;
|
||||
|
||||
/**
|
||||
* @brief Gets the type of a typed array object.
|
||||
* @return The type of a typed array object.
|
||||
*/
|
||||
TypedArrayType getTypedArrayType() const;
|
||||
|
||||
/**
|
||||
* @brief Gets backing store of a typed array object.
|
||||
* @param[out] ptr A temporary pointer to the backing store of a JavaScript Typed Array object.
|
||||
* @param[out] length The byte length of a JavaScript Typed Array object.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool getTypedArrayData(uint8_t** ptr, size_t* length) const;
|
||||
|
||||
/**
|
||||
* @brief Tests whether an object is an array buffer object.
|
||||
* @return true if object is an array buffer object, otherwise false.
|
||||
*/
|
||||
bool isArrayBuffer() const;
|
||||
|
||||
/**
|
||||
* @brief Gets buffer data of an array buffer object.
|
||||
* @param[out] ptr A pointer to the data buffer that serves as the backing store for a JavaScript Typed Array object.
|
||||
* @param[out] length The number of bytes in a JavaScript data object.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool getArrayBufferData(uint8_t** ptr, size_t* length) const;
|
||||
|
||||
/**
|
||||
* @brief Gets all property names of an object.
|
||||
* @param[out] allKeys A string vector to store all property names.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool getAllKeys(std::vector<std::string>* allKeys) const;
|
||||
|
||||
/**
|
||||
* @brief Sets a pointer to private data on an object.
|
||||
* @param[in] data A void* to set as the object's private data.
|
||||
* @note This method will associate private data with se::Object by std::unordered_map::emplace.
|
||||
* It's used for search a se::Object via a void* private data.
|
||||
*/
|
||||
void setPrivateData(void* data);
|
||||
|
||||
/**
|
||||
* @brief Gets an object's private data.
|
||||
* @return A void* that is the object's private data, if the object has private data, otherwise nullptr.
|
||||
*/
|
||||
void* getPrivateData() const;
|
||||
|
||||
/**
|
||||
* @brief Clears private data of an object.
|
||||
*/
|
||||
void clearPrivateData();
|
||||
|
||||
/**
|
||||
* @brief Roots an object from garbage collection.
|
||||
* @note Use this method when you want to store an object in a global or on the heap, where the garbage collector will not be able to discover your reference to it.
|
||||
* An object may be rooted multiple times and must be unrooted an equal number of times before becoming eligible for garbage collection.
|
||||
*/
|
||||
void root();
|
||||
|
||||
/**
|
||||
* @brief Unroots an object from garbage collection.
|
||||
* @note An object may be rooted multiple times and must be unrooted an equal number of times before becoming eligible for garbage collection.
|
||||
*/
|
||||
void unroot();
|
||||
|
||||
/**
|
||||
* @brief Tests whether an object is rooted.
|
||||
* @return true if it has been already rooted, otherwise false.
|
||||
*/
|
||||
bool isRooted() const;
|
||||
|
||||
/**
|
||||
* @brief Tests whether two objects are strict equal, as compared by the JS === operator.
|
||||
* @param[in] o The object to be tested with this object.
|
||||
* @return true if the two values are strict equal, otherwise false.
|
||||
*/
|
||||
bool strictEquals(Object* o) const;
|
||||
|
||||
/**
|
||||
* @brief Attaches an object to current object.
|
||||
* @param[in] obj The object to be attached.
|
||||
* @return true if succeed, otherwise false.
|
||||
* @note This method will set `obj` as a property of current object, therefore the lifecycle of child object will depend on current object,
|
||||
* which means `obj` may be garbage collected only after current object is garbage collected.
|
||||
* It's normally used in binding a native callback method. For example:
|
||||
|
||||
```javascript
|
||||
var self = this;
|
||||
someObject.setCallback(function(){}, self);
|
||||
```
|
||||
|
||||
```c++
|
||||
static bool SomeObject_setCallback(se::State& s)
|
||||
{
|
||||
SomeObject* cobj = (SomeObject*)s.nativeThisObject();
|
||||
const auto& args = s.args();
|
||||
size_t argc = args.size();
|
||||
if (argc == 2) {
|
||||
std::function<void()> arg0;
|
||||
do {
|
||||
if (args[0].isObject() && args[0].toObject()->isFunction())
|
||||
{
|
||||
se::Value jsThis(args[1]);
|
||||
se::Value jsFunc(args[0]);
|
||||
|
||||
jsThis.toObject()->attachObject(jsFunc.toObject());
|
||||
|
||||
auto lambda = [=]() -> void {
|
||||
...
|
||||
// Call jsFunc stuff...
|
||||
...
|
||||
};
|
||||
arg0 = lambda;
|
||||
}
|
||||
else
|
||||
{
|
||||
arg0 = nullptr;
|
||||
}
|
||||
} while(false);
|
||||
SE_PRECONDITION2(ok, false, "Error processing arguments");
|
||||
cobj->setCallback(arg0);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
```
|
||||
*/
|
||||
bool attachObject(Object* obj);
|
||||
|
||||
/**
|
||||
* @brief Detaches an object from current object.
|
||||
* @param[in] obj The object to be detached.
|
||||
* @return true if succeed, otherwise false.
|
||||
* @note The attached object will not be released if current object is not garbage collected.
|
||||
*/
|
||||
bool detachObject(Object* obj);
|
||||
|
||||
/**
|
||||
* @brief Returns the string for describing current object.
|
||||
* @return The string for describing current object.
|
||||
*/
|
||||
std::string toString() const;
|
||||
|
||||
// Private API used in wrapper
|
||||
static Object* _createJSObject(Class* cls, v8::Local<v8::Object> obj);
|
||||
v8::Local<v8::Object> _getJSObject() const;
|
||||
|
||||
@@ -1,3 +1,23 @@
|
||||
// Copyright Joyent, Inc. and other Node contributors.
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a
|
||||
// copy of this software and associated documentation files (the
|
||||
// "Software"), to deal in the Software without restriction, including
|
||||
// without limitation the rights to use, copy, modify, merge, publish,
|
||||
// distribute, sublicense, and/or sell copies of the Software, and to permit
|
||||
// persons to whom the Software is furnished to do so, subject to the
|
||||
// following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included
|
||||
// in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
|
||||
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
|
||||
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
|
||||
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
|
||||
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
|
||||
// USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
#include "ObjectWrap.h"
|
||||
|
||||
#if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_V8
|
||||
@@ -81,7 +101,7 @@ namespace se {
|
||||
/*static*/
|
||||
void ObjectWrap::weakCallback(const v8::WeakCallbackInfo<ObjectWrap> &data) {
|
||||
ObjectWrap *wrap = data.GetParameter();
|
||||
// LOGD("weakCallback: %p, nativeObj = %p, finalize: %p\n", wrap, wrap->_nativeObj, wrap->_finalizeCb);
|
||||
// SE_LOGD("weakCallback: %p, nativeObj = %p, finalize: %p\n", wrap, wrap->_nativeObj, wrap->_finalizeCb);
|
||||
assert(wrap->refs_ == 0);
|
||||
wrap->handle_.Reset();
|
||||
if (wrap->_finalizeCb != nullptr)
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#include "ScriptEngine.hpp"
|
||||
|
||||
#if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_V8
|
||||
@@ -29,7 +52,7 @@ namespace se {
|
||||
if (info[0]->IsString())
|
||||
{
|
||||
v8::String::Utf8Value utf8(info[0]);
|
||||
LOGD("JS: %s\n", *utf8);
|
||||
SE_LOGD("JS: %s\n", *utf8);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,6 +64,9 @@ namespace se {
|
||||
std::string stackTraceToString(v8::Local<v8::StackTrace> stack)
|
||||
{
|
||||
std::string stackStr;
|
||||
if (stack.IsEmpty())
|
||||
return stackStr;
|
||||
|
||||
char tmp[100] = {0};
|
||||
for (int i = 0, e = stack->GetFrameCount(); i < e; ++i)
|
||||
{
|
||||
@@ -96,7 +122,7 @@ namespace se {
|
||||
if ((argc - msgIndex) == 1)
|
||||
{
|
||||
std::string msg = args[msgIndex].toStringForce();
|
||||
LOGD("JS: %s%s\n", prefix, msg.c_str());
|
||||
SE_LOGD("JS: %s%s\n", prefix, msg.c_str());
|
||||
}
|
||||
else if (argc > 1)
|
||||
{
|
||||
@@ -115,7 +141,7 @@ namespace se {
|
||||
}
|
||||
}
|
||||
|
||||
LOGD("JS: %s%s\n", prefix, msg.c_str());
|
||||
SE_LOGD("JS: %s%s\n", prefix, msg.c_str());
|
||||
}
|
||||
|
||||
return true;
|
||||
@@ -185,7 +211,7 @@ namespace se {
|
||||
errorStr += ", message: ";
|
||||
errorStr += message;
|
||||
|
||||
LOGE("%s\n", errorStr.c_str());
|
||||
SE_LOGE("%s\n", errorStr.c_str());
|
||||
if (getInstance()->_exceptionCallback != nullptr)
|
||||
{
|
||||
getInstance()->_exceptionCallback(location, message, "(no stack information)");
|
||||
@@ -204,7 +230,7 @@ namespace se {
|
||||
message += "false";
|
||||
|
||||
errorStr += ", " + message;
|
||||
LOGE("%s\n", errorStr.c_str());
|
||||
SE_LOGE("%s\n", errorStr.c_str());
|
||||
if (getInstance()->_exceptionCallback != nullptr)
|
||||
{
|
||||
getInstance()->_exceptionCallback(location, message.c_str(), "(no stack information)");
|
||||
@@ -226,9 +252,9 @@ namespace se {
|
||||
Value column;
|
||||
internal::jsToSeValue(v8::Isolate::GetCurrent(), origin.ResourceColumnOffset(), &column);
|
||||
|
||||
std::string location = resouceNameVal.toString() + ":" + line.toStringForce() + ":" + column.toStringForce();
|
||||
std::string location = resouceNameVal.toStringForce() + ":" + line.toStringForce() + ":" + column.toStringForce();
|
||||
|
||||
std::string errorStr = msgVal.toString() + ", " + location;
|
||||
std::string errorStr = msgVal.toString() + ", location: " + location;
|
||||
std::string stackStr = stackTraceToString(message->GetStackTrace());
|
||||
if (!stackStr.empty())
|
||||
{
|
||||
@@ -238,7 +264,7 @@ namespace se {
|
||||
}
|
||||
errorStr += "\nSTACK:\n" + stackStr;
|
||||
}
|
||||
LOGE("ERROR: %s\n", errorStr.c_str());
|
||||
SE_LOGE("ERROR: %s\n", errorStr.c_str());
|
||||
|
||||
if (thiz->_exceptionCallback != nullptr)
|
||||
{
|
||||
@@ -264,7 +290,7 @@ namespace se {
|
||||
}
|
||||
else
|
||||
{
|
||||
LOGE("ERROR: __errorHandler has exception\n");
|
||||
SE_LOGE("ERROR: __errorHandler has exception\n");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -306,6 +332,7 @@ namespace se {
|
||||
, _exceptionCallback(nullptr)
|
||||
#if SE_ENABLE_INSPECTOR
|
||||
, _env(nullptr)
|
||||
, _isolateData(nullptr)
|
||||
#endif
|
||||
, _debuggerServerPort(0)
|
||||
, _vmId(0)
|
||||
@@ -334,7 +361,7 @@ namespace se {
|
||||
bool ScriptEngine::init()
|
||||
{
|
||||
cleanup();
|
||||
LOGD("Initializing V8, version: %s\n", v8::V8::GetVersion());
|
||||
SE_LOGD("Initializing V8, version: %s\n", v8::V8::GetVersion());
|
||||
++_vmId;
|
||||
|
||||
for (const auto& hook : _beforeInitHookArray)
|
||||
@@ -417,7 +444,7 @@ namespace se {
|
||||
if (!_isValid)
|
||||
return;
|
||||
|
||||
LOGD("ScriptEngine::cleanup begin ...\n");
|
||||
SE_LOGD("ScriptEngine::cleanup begin ...\n");
|
||||
_isInCleanup = true;
|
||||
|
||||
{
|
||||
@@ -441,11 +468,19 @@ namespace se {
|
||||
__oldConsoleAssert.setUndefined();
|
||||
|
||||
#if SE_ENABLE_INSPECTOR
|
||||
_env->inspector_agent()->Stop();
|
||||
if (_isolateData != nullptr)
|
||||
{
|
||||
node::FreeIsolateData(_isolateData);
|
||||
_isolateData = nullptr;
|
||||
}
|
||||
|
||||
node::FreeIsolateData(_isolateData);
|
||||
_env->CleanupHandles();
|
||||
node::FreeEnvironment(_env);
|
||||
if (_env != nullptr)
|
||||
{
|
||||
_env->inspector_agent()->Stop();
|
||||
_env->CleanupHandles();
|
||||
node::FreeEnvironment(_env);
|
||||
_env = nullptr;
|
||||
}
|
||||
#endif
|
||||
|
||||
_context.Get(_isolate)->Exit();
|
||||
@@ -472,7 +507,7 @@ namespace se {
|
||||
NativePtrToObjectMap::destroy();
|
||||
NonRefNativePtrCreatedByCtorMap::destroy();
|
||||
|
||||
LOGD("ScriptEngine::cleanup end ...\n");
|
||||
SE_LOGD("ScriptEngine::cleanup end ...\n");
|
||||
}
|
||||
|
||||
Object* ScriptEngine::getGlobalObject() const
|
||||
@@ -526,7 +561,8 @@ namespace se {
|
||||
options.set_inspector_enabled(true);
|
||||
options.set_port((int)_debuggerServerPort);
|
||||
options.set_host_name(_debuggerServerAddr.c_str());
|
||||
_env->inspector_agent()->Start(_platform, "", options);
|
||||
bool ok = _env->inspector_agent()->Start(_platform, "", options);
|
||||
assert(ok);
|
||||
#endif
|
||||
}
|
||||
//
|
||||
@@ -549,7 +585,7 @@ namespace se {
|
||||
|
||||
void ScriptEngine::garbageCollect()
|
||||
{
|
||||
LOGD("GC begin ..., (js->native map) size: %d, all objects: %d\n", (int)NativePtrToObjectMap::size(), (int)__objectMap.size());
|
||||
SE_LOGD("GC begin ..., (js->native map) size: %d, all objects: %d\n", (int)NativePtrToObjectMap::size(), (int)__objectMap.size());
|
||||
const double kLongIdlePauseInSeconds = 1.0;
|
||||
_isolate->ContextDisposedNotification();
|
||||
_isolate->IdleNotificationDeadline(_platform->MonotonicallyIncreasingTime() + kLongIdlePauseInSeconds);
|
||||
@@ -557,7 +593,7 @@ namespace se {
|
||||
// garbage and will therefore also invoke all weak callbacks of actually
|
||||
// unreachable persistent handles.
|
||||
_isolate->LowMemoryNotification();
|
||||
LOGD("GC end ..., (js->native map) size: %d, all objects: %d\n", (int)NativePtrToObjectMap::size(), (int)__objectMap.size());
|
||||
SE_LOGD("GC end ..., (js->native map) size: %d, all objects: %d\n", (int)NativePtrToObjectMap::size(), (int)__objectMap.size());
|
||||
}
|
||||
|
||||
bool ScriptEngine::isGarbageCollecting()
|
||||
@@ -647,48 +683,10 @@ namespace se {
|
||||
return evalString(scriptBuffer.c_str(), scriptBuffer.length(), ret, path.c_str());
|
||||
}
|
||||
|
||||
LOGE("ScriptEngine::runScript script %s, buffer is empty!\n", path.c_str());
|
||||
SE_LOGE("ScriptEngine::runScript script %s, buffer is empty!\n", path.c_str());
|
||||
return false;
|
||||
}
|
||||
|
||||
void ScriptEngine::_retainScriptObject(void* owner, void* target)
|
||||
{
|
||||
auto iterOwner = NativePtrToObjectMap::find(owner);
|
||||
if (iterOwner == NativePtrToObjectMap::end())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
auto iterTarget = NativePtrToObjectMap::find(target);
|
||||
if (iterTarget == NativePtrToObjectMap::end())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
clearException();
|
||||
AutoHandleScope hs;
|
||||
iterOwner->second->attachObject(iterTarget->second);
|
||||
}
|
||||
|
||||
void ScriptEngine::_releaseScriptObject(void* owner, void* target)
|
||||
{
|
||||
auto iterOwner = NativePtrToObjectMap::find(owner);
|
||||
if (iterOwner == NativePtrToObjectMap::end())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
auto iterTarget = NativePtrToObjectMap::find(target);
|
||||
if (iterTarget == NativePtrToObjectMap::end())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
clearException();
|
||||
AutoHandleScope hs;
|
||||
iterOwner->second->detachObject(iterTarget->second);
|
||||
}
|
||||
|
||||
void ScriptEngine::clearException()
|
||||
{
|
||||
//FIXME:
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#pragma once
|
||||
|
||||
#include "../config.hpp"
|
||||
@@ -26,6 +49,12 @@ namespace se {
|
||||
|
||||
extern Class* __jsb_CCPrivateData_class;
|
||||
|
||||
/**
|
||||
* A stack-allocated class that governs a number of local handles.
|
||||
* It's only implemented for v8 wrapper now.
|
||||
* Other script engine wrappers have empty implementation for this class.
|
||||
* It's used at the beginning of executing any wrapper API.
|
||||
*/
|
||||
class AutoHandleScope
|
||||
{
|
||||
public:
|
||||
@@ -40,24 +69,51 @@ namespace se {
|
||||
v8::HandleScope _handleScope;
|
||||
};
|
||||
|
||||
/**
|
||||
* ScriptEngine is a sington which represents a context of JavaScript VM.
|
||||
*/
|
||||
class ScriptEngine final
|
||||
{
|
||||
private:
|
||||
ScriptEngine();
|
||||
~ScriptEngine();
|
||||
public:
|
||||
|
||||
/**
|
||||
* @brief Gets or creates the instance of script engine.
|
||||
* @return The script engine instance.
|
||||
*/
|
||||
static ScriptEngine* getInstance();
|
||||
|
||||
/**
|
||||
* @brief Destroys the instance of script engine.
|
||||
*/
|
||||
static void destroyInstance();
|
||||
|
||||
/**
|
||||
* @brief Gets the global object of JavaScript VM.
|
||||
* @return The se::Object stores the global JavaScript object.
|
||||
*/
|
||||
Object* getGlobalObject() const;
|
||||
|
||||
typedef bool (*RegisterCallback)(Object*);
|
||||
|
||||
/**
|
||||
* @brief Adds a callback for registering a native binding module.
|
||||
* @param[in] cb A callback for registering a native binding module.
|
||||
* @note This method just add a callback to a vector, callbacks is invoked in `start` method.
|
||||
*/
|
||||
void addRegisterCallback(RegisterCallback cb);
|
||||
|
||||
/**
|
||||
* @brief Starts the script engine.
|
||||
* @return true if succeed, otherwise false.
|
||||
* @note This method will invoke all callbacks of native binding modules by the order of registration.
|
||||
*/
|
||||
bool start();
|
||||
|
||||
/**
|
||||
* @brief Initializes script engine.
|
||||
* @return true if succeed, otherwise false.
|
||||
* @note This method will create JavaScript context and global object.
|
||||
*/
|
||||
bool init();
|
||||
void cleanup();
|
||||
|
||||
/**
|
||||
* @brief Adds a hook function before initializing script engine.
|
||||
@@ -73,10 +129,35 @@ namespace se {
|
||||
*/
|
||||
void addAfterInitHook(const std::function<void()>& hook);
|
||||
|
||||
/**
|
||||
* @brief Cleanups script engine.
|
||||
* @note This method will removes all objects in JavaScript VM even whose are rooted, then shutdown JavaScript VMf.
|
||||
*/
|
||||
void cleanup();
|
||||
|
||||
/**
|
||||
* @brief Adds a hook function before cleanuping script engine.
|
||||
* @param[in] hook A hook function to be invoked before cleanuping script engine.
|
||||
* @note Multiple hook functions could be added, they will be invoked by the order of adding.
|
||||
*/
|
||||
void addBeforeCleanupHook(const std::function<void()>& hook);
|
||||
|
||||
/**
|
||||
* @brief Adds a hook function after cleanuping script engine.
|
||||
* @param[in] hook A hook function to be invoked after cleanuping script engine.
|
||||
* @note Multiple hook functions could be added, they will be invoked by the order of adding.
|
||||
*/
|
||||
void addAfterCleanupHook(const std::function<void()>& hook);
|
||||
|
||||
bool evalString(const char* script, ssize_t length = -1, Value* ret = nullptr, const char* fileName = nullptr);
|
||||
/**
|
||||
* @brief Executes a utf-8 string buffer which contains JavaScript code.
|
||||
* @param[in] scriptStr A utf-8 string buffer, if it isn't null-terminated, parameter `length` should be assigned and > 0.
|
||||
* @param[in] length The length of parameter `scriptStr`, it will be set to string length internally if passing < 0 and parameter `scriptStr` is null-terminated.
|
||||
* @param[in] rval The se::Value that results from evaluating script. Passing nullptr if you don't care about the result.
|
||||
* @param[in] fileName A string containing a URL for the script's source file. This is used by debuggers and when reporting exceptions. Pass NULL if you do not care to include source file information.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool evalString(const char* scriptStr, ssize_t length = -1, Value* rval = nullptr, const char* fileName = nullptr);
|
||||
|
||||
/**
|
||||
* Delegate class for file operation
|
||||
@@ -122,33 +203,83 @@ namespace se {
|
||||
* @param[in] rval The se::Value that results from evaluating script. Passing nullptr if you don't care about the result.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
bool runScript(const std::string& path, Value* ret = nullptr);
|
||||
bool runScript(const std::string& path, Value* rval = nullptr);
|
||||
|
||||
/**
|
||||
* @brief Tests whether script engine is doing garbage collection.
|
||||
* @return true if it's in garbage collection, otherwise false.
|
||||
*/
|
||||
bool isGarbageCollecting();
|
||||
void _setGarbageCollecting(bool isGarbageCollecting);
|
||||
|
||||
/**
|
||||
* @brief Performs a JavaScript garbage collection.
|
||||
*/
|
||||
void garbageCollect();
|
||||
|
||||
bool isValid() const;
|
||||
/**
|
||||
* @brief Tests whether script engine is being cleaned up.
|
||||
* @return true if it's in cleaning up, otherwise false.
|
||||
*/
|
||||
bool isInCleanup() { return _isInCleanup; }
|
||||
|
||||
/**
|
||||
* @brief Tests whether script engine is valid.
|
||||
* @return true if it's valid, otherwise false.
|
||||
*/
|
||||
bool isValid() const;
|
||||
|
||||
/**
|
||||
* @brief Clears all exceptions.
|
||||
*/
|
||||
void clearException();
|
||||
|
||||
using ExceptionCallback = std::function<void(const char*, const char*, const char*)>; // location, message, stack
|
||||
|
||||
/**
|
||||
* @brief Sets the callback function while an exception is fired.
|
||||
* @param[in] cb The callback function to notify that an exception is fired.
|
||||
*/
|
||||
void setExceptionCallback(const ExceptionCallback& cb);
|
||||
|
||||
/**
|
||||
* @brief Gets the start time of script engine.
|
||||
* @return The start time of script engine.
|
||||
*/
|
||||
const std::chrono::steady_clock::time_point& getStartTime() const { return _startTime; }
|
||||
|
||||
/**
|
||||
* @brief Enables JavaScript debugger
|
||||
* @param[in] serverAddr The address of debugger server.
|
||||
* @param[in] port The port of debugger server will use.
|
||||
*/
|
||||
void enableDebugger(const std::string& serverAddr, uint32_t port);
|
||||
|
||||
/**
|
||||
* @brief Tests whether JavaScript debugger is enabled
|
||||
* @return true if JavaScript debugger is enabled, otherwise false.
|
||||
*/
|
||||
bool isDebuggerEnabled() const;
|
||||
|
||||
/**
|
||||
* @brief Main loop update trigger, it's need to invoked in main thread every frame.
|
||||
*/
|
||||
void mainLoopUpdate();
|
||||
|
||||
/**
|
||||
* @brief Gets script virtual machine instance ID. Default value is 1, increase by 1 if `init` is invoked.
|
||||
*/
|
||||
uint32_t getVMId() const { return _vmId; }
|
||||
|
||||
// Private API used in wrapper
|
||||
void _retainScriptObject(void* owner, void* target);
|
||||
void _releaseScriptObject(void* owner, void* target);
|
||||
|
||||
v8::Local<v8::Context> _getContext() const;
|
||||
void _setGarbageCollecting(bool isGarbageCollecting);
|
||||
//
|
||||
private:
|
||||
ScriptEngine();
|
||||
~ScriptEngine();
|
||||
|
||||
static void privateDataFinalize(void* nativeObj);
|
||||
|
||||
static void onFatalErrorCallback(const char* location, const char* message);
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#pragma once
|
||||
|
||||
#include "ScriptEngine.hpp"
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#include "Utils.hpp"
|
||||
|
||||
#if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_V8
|
||||
@@ -173,7 +196,7 @@ namespace se {
|
||||
if (c > 0)
|
||||
{
|
||||
wrap.wrap(data);
|
||||
// LOGD("setPrivate1: %p\n", data);
|
||||
// SE_LOGD("setPrivate1: %p\n", data);
|
||||
if (outInternalData != nullptr)
|
||||
*outInternalData = nullptr;
|
||||
}
|
||||
@@ -191,7 +214,7 @@ namespace se {
|
||||
assert(!key.IsEmpty());
|
||||
v8::Maybe<bool> ret = obj->Set(isolate->GetCurrentContext(), key.ToLocalChecked(), privateObj->_getJSObject());
|
||||
assert(!ret.IsNothing());
|
||||
// LOGD("setPrivate: native data: %p\n", privateData);
|
||||
// SE_LOGD("setPrivate: native data: %p\n", privateData);
|
||||
// privateObj->decRef(); // NOTE: it's released in ScriptEngine::privateDataFinalize
|
||||
|
||||
if (outInternalData != nullptr)
|
||||
@@ -211,7 +234,7 @@ namespace se {
|
||||
if (c > 0)
|
||||
{
|
||||
void* nativeObj = ObjectWrap::unwrap(objChecked);
|
||||
// LOGD("getPrivate1: %p\n", nativeObj);
|
||||
// SE_LOGD("getPrivate1: %p\n", nativeObj);
|
||||
return nativeObj;
|
||||
}
|
||||
|
||||
@@ -233,7 +256,7 @@ namespace se {
|
||||
if (privateObj.IsEmpty())
|
||||
return nullptr;
|
||||
PrivateData* privateData = (PrivateData*)ObjectWrap::unwrap(privateObj.ToLocalChecked());
|
||||
// LOGD("getPrivate: native data: %p\n", privateData);
|
||||
// SE_LOGD("getPrivate: native data: %p\n", privateData);
|
||||
return privateData->data;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#pragma once
|
||||
|
||||
#include "../config.hpp"
|
||||
|
||||
@@ -115,7 +115,7 @@ static int StartDebugSignalHandler() {
|
||||
CHECK_EQ(0, pthread_sigmask(SIG_SETMASK, &sigmask, nullptr));
|
||||
CHECK_EQ(0, pthread_attr_destroy(&attr));
|
||||
if (err != 0) {
|
||||
LOGE("node[%d]: pthread_create: %s\n", getpid(), strerror(err));
|
||||
SE_LOGE("node[%d]: pthread_create: %s\n", getpid(), strerror(err));
|
||||
|
||||
// Leave SIGUSR1 blocked. We don't install a signal handler,
|
||||
// receiving the signal would terminate the process.
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user