Bindings fix and assets manger ex fix (#17115)

* Fix custom event being discard during event emission

* Fix tilemap black line issue

* Fix auto bindings config

* Adapt websocket to new memory model

* Improve cocos2d_specifics code stability

* Fix issue with get_or_create_js_object function

* Improve memory usage in function wrapper invocation

* Use JS Function bind to avoid memory tracking issues

* Support size parameter to collect total byte size before update process

* Fix download resuming issue on Android

* Remove temporary assets when temporary manifest is invalid or out of date

* Use version compare handle to compare manifests versions

* Support max concurrent tasks setting & download verify callback

* Add Manifest::Asset conversion

* Avoid crash caused by wrappers

* Sync implementation of tested and published AssetsManagerEx from Cocos Creator

* Fix linux compilation issues
This commit is contained in:
pandamicro 2017-03-15 16:09:02 +08:00 коммит произвёл minggo
Родитель 010a724149
Коммит 0eec73ba43
39 изменённых файлов: 1423 добавлений и 273 удалений

Просмотреть файл

@ -5712,6 +5712,9 @@
B6DD2FF61B04825B00E47F5F /* fastlz.c in Sources */ = {isa = PBXBuildFile; fileRef = B6DD2FA51B04825B00E47F5F /* fastlz.c */; };
B6DD2FF71B04825B00E47F5F /* fastlz.h in Headers */ = {isa = PBXBuildFile; fileRef = B6DD2FA61B04825B00E47F5F /* fastlz.h */; };
B6DD2FF81B04825B00E47F5F /* fastlz.h in Headers */ = {isa = PBXBuildFile; fileRef = B6DD2FA61B04825B00E47F5F /* fastlz.h */; };
BA6249A81E77D2850096291C /* tinydir.h in Headers */ = {isa = PBXBuildFile; fileRef = BA6249A71E77D2850096291C /* tinydir.h */; };
BA6249A91E77D2850096291C /* tinydir.h in Headers */ = {isa = PBXBuildFile; fileRef = BA6249A71E77D2850096291C /* tinydir.h */; };
BA6249AA1E77D2850096291C /* tinydir.h in Headers */ = {isa = PBXBuildFile; fileRef = BA6249A71E77D2850096291C /* tinydir.h */; };
C50306691B60B583001E6D43 /* CCBoneNode.cpp in Sources */ = {isa = PBXBuildFile; fileRef = C50306631B60B583001E6D43 /* CCBoneNode.cpp */; };
C503066A1B60B583001E6D43 /* CCBoneNode.h in Headers */ = {isa = PBXBuildFile; fileRef = C50306641B60B583001E6D43 /* CCBoneNode.h */; };
C503066B1B60B583001E6D43 /* CCSkeletonNode.cpp in Sources */ = {isa = PBXBuildFile; fileRef = C50306651B60B583001E6D43 /* CCSkeletonNode.cpp */; };
@ -7791,6 +7794,9 @@
B6DD2FA31B04825B00E47F5F /* DetourTileCacheBuilder.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DetourTileCacheBuilder.h; sourceTree = "<group>"; };
B6DD2FA51B04825B00E47F5F /* fastlz.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = fastlz.c; sourceTree = "<group>"; };
B6DD2FA61B04825B00E47F5F /* fastlz.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = fastlz.h; sourceTree = "<group>"; };
BA6249A51E77D2850096291C /* COPYING */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = COPYING; sourceTree = "<group>"; };
BA6249A61E77D2850096291C /* package.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; path = package.json; sourceTree = "<group>"; };
BA6249A71E77D2850096291C /* tinydir.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = tinydir.h; sourceTree = "<group>"; };
C50306631B60B583001E6D43 /* CCBoneNode.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CCBoneNode.cpp; sourceTree = "<group>"; };
C50306641B60B583001E6D43 /* CCBoneNode.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCBoneNode.h; sourceTree = "<group>"; };
C50306651B60B583001E6D43 /* CCSkeletonNode.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CCSkeletonNode.cpp; sourceTree = "<group>"; };
@ -8462,6 +8468,7 @@
1AD71EF8180E28C400808F54 /* json */,
1A57035C180BD0D90088DEC7 /* png */,
1A57038A180BD1EF0088DEC7 /* tiff */,
BA6249A41E77D2850096291C /* tinydir */,
1A570348180BD09B0088DEC7 /* tinyxml2 */,
1A57034F180BD0B00088DEC7 /* unzip */,
1A5703A5180BD2410088DEC7 /* webp */,
@ -11365,6 +11372,17 @@
path = ../external/recast/fastlz;
sourceTree = "<group>";
};
BA6249A41E77D2850096291C /* tinydir */ = {
isa = PBXGroup;
children = (
BA6249A51E77D2850096291C /* COPYING */,
BA6249A61E77D2850096291C /* package.json */,
BA6249A71E77D2850096291C /* tinydir.h */,
);
name = tinydir;
path = ../external/tinydir;
sourceTree = "<group>";
};
C50306621B60B56C001E6D43 /* Skeleton */ = {
isa = PBXGroup;
children = (
@ -11789,6 +11807,7 @@
A045F6DE1BA816A1005076C7 /* CCCameraBackgroundBrush.h in Headers */,
50ABBED91925AB6F00A911A9 /* ZipUtils.h in Headers */,
50643BDB19BFAF4400EF68ED /* CCStdC.h in Headers */,
BA6249A81E77D2850096291C /* tinydir.h in Headers */,
1A5701C3180BCB5A0088DEC7 /* CCLabelBMFont.h in Headers */,
1A2B22B01E6E54D6001D5EC9 /* Uri.h in Headers */,
B6CAB33F1AF9AA1A00B9B856 /* gim_basic_geometry_operations.h in Headers */,
@ -12851,6 +12870,7 @@
507B3E641C31BDD30067B53E /* DetourAssert.h in Headers */,
507B3E651C31BDD30067B53E /* CCParticleSystemQuadLoader.h in Headers */,
507B3E661C31BDD30067B53E /* CCPUOnEventFlagObserverTranslator.h in Headers */,
BA6249AA1E77D2850096291C /* tinydir.h in Headers */,
50864CAE1C7BC1B000B3BAB1 /* cpDampedSpring.h in Headers */,
507B3E671C31BDD30067B53E /* btDefaultMotionState.h in Headers */,
507B3E681C31BDD30067B53E /* btScalar.h in Headers */,
@ -13979,6 +13999,7 @@
5020A16C1D49912500E80C72 /* AtlasAttachmentLoader.h in Headers */,
B6CAB2E01AF9AA1A00B9B856 /* btScaledBvhTriangleMeshShape.h in Headers */,
50ABBE9E1925AB6F00A911A9 /* CCRefPtr.h in Headers */,
BA6249A91E77D2850096291C /* tinydir.h in Headers */,
15AE18DA19AAD33D00C27E9E /* CCSpriteLoader.h in Headers */,
B6CAB4401AF9AA1A00B9B856 /* btGpuUtilsSharedCode.h in Headers */,
15AE196219AAD35100C27E9E /* CCSSceneReader.h in Headers */,

Просмотреть файл

@ -87,6 +87,18 @@ namespace cocos2d { namespace network {
int errorCodeInternal,
const std::string& errorStr)> onTaskError;
void setOnFileTaskSuccess(const std::function<void(const DownloadTask& task)>& callback) {onFileTaskSuccess = callback;};
void setOnTaskProgress(const std::function<void(const DownloadTask& task,
int64_t bytesReceived,
int64_t totalBytesReceived,
int64_t totalBytesExpected)>& callback) {onTaskProgress = callback;};
void setOnTaskError(const std::function<void(const DownloadTask& task,
int errorCode,
int errorCodeInternal,
const std::string& errorStr)>& callback) {onTaskError = callback;};
std::shared_ptr<const DownloadTask> createDownloadDataTask(const std::string& srcUrl, const std::string& identifier = "");
std::shared_ptr<const DownloadTask> createDownloadFileTask(const std::string& srcUrl, const std::string& storagePath, const std::string& identifier = "");

Просмотреть файл

@ -33,7 +33,8 @@ THE SOFTWARE.
#include "platform/CCSAXParser.h"
//#include "base/ccUtils.h"
#include "tinyxml2.h"
#include "tinyxml2/tinyxml2.h"
#include "tinydir/tinydir.h"
#ifdef MINIZIP_FROM_SYSTEM
#include <minizip/unzip.h>
#else // from our embedded sources
@ -1166,6 +1167,130 @@ void FileUtils::getFileSize(const std::string &filepath, std::function<void(long
}, std::move(callback));
}
std::vector<std::string> FileUtils::listFiles(const std::string& dirPath) const
{
std::string fullpath = fullPathForFilename(dirPath);
std::vector<std::string> files;
if (isDirectoryExist(fullpath))
{
tinydir_dir dir;
#ifdef UNICODE
unsigned int length = MultiByteToWideChar(CP_UTF8, 0, &fullpath[0], (int)fullpath.size(), NULL, 0);
if (length != fullpath.size())
{
return files;
}
std::wstring fullpathstr(length, 0);
MultiByteToWideChar(CP_UTF8, 0, &fullpath[0], (int)fullpath.size(), &fullpathstr[0], length);
#else
std::string fullpathstr = fullpath;
#endif
if (tinydir_open(&dir, &fullpathstr[0]) != -1)
{
while (dir.has_next)
{
tinydir_file file;
if (tinydir_readfile(&dir, &file) == -1)
{
// Error getting file
break;
}
#ifdef UNICODE
std::wstring path = file.path;
length = WideCharToMultiByte(CP_UTF8, 0, &path[0], (int)path.size(), NULL, 0, NULL, NULL);
std::string filepath;
if (length > 0)
{
filepath.resize(length);
WideCharToMultiByte(CP_UTF8, 0, &path[0], (int)path.size(), &filepath[0], length, NULL, NULL);
}
#else
std::string filepath = file.path;
#endif
if (file.is_dir)
{
filepath.append("/");
}
files.push_back(filepath);
if (tinydir_next(&dir) == -1)
{
// Error getting next file
break;
}
}
}
tinydir_close(&dir);
}
return files;
}
void FileUtils::listFilesRecursively(const std::string& dirPath, std::vector<std::string> *files) const
{
std::string fullpath = fullPathForFilename(dirPath);
if (isDirectoryExist(fullpath))
{
tinydir_dir dir;
#ifdef UNICODE
unsigned int length = MultiByteToWideChar(CP_UTF8, 0, &fullpath[0], (int)fullpath.size(), NULL, 0);
if (length != fullpath.size())
{
return;
}
std::wstring fullpathstr(length, 0);
MultiByteToWideChar(CP_UTF8, 0, &fullpath[0], (int)fullpath.size(), &fullpathstr[0], length);
#else
std::string fullpathstr = fullpath;
#endif
if (tinydir_open(&dir, &fullpathstr[0]) != -1)
{
while (dir.has_next)
{
tinydir_file file;
if (tinydir_readfile(&dir, &file) == -1)
{
// Error getting file
break;
}
#ifdef UNICODE
std::wstring path = file.path;
length = WideCharToMultiByte(CP_UTF8, 0, &path[0], (int)path.size(), NULL, 0, NULL, NULL);
std::string filepath;
if (length > 0)
{
filepath.resize(length);
WideCharToMultiByte(CP_UTF8, 0, &path[0], (int)path.size(), &filepath[0], length, NULL, NULL);
}
#else
std::string filepath = file.path;
#endif
if (file.name[0] != '.')
{
if (file.is_dir)
{
filepath.append("/");
files->push_back(filepath);
listFilesRecursively(filepath, files);
}
else
{
files->push_back(filepath);
}
}
if (tinydir_next(&dir) == -1)
{
// Error getting next file
break;
}
}
}
tinydir_close(&dir);
}
}
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
// windows os implement should override in platform specific FileUtiles class
bool FileUtils::isDirectoryExistInternal(const std::string& dirPath) const

Просмотреть файл

@ -684,12 +684,12 @@ public:
virtual bool isDirectoryExist(const std::string& dirPath) const;
/**
* Checks whether the absoulate path is a directory, async off of the main cocos thread.
*
* @param dirPath The path of the directory, it must be an absolute path
* @param callback that will accept a boolean, true if the file exists, false otherwise.
* Callback will happen on the main cocos thread.
*/
* Checks whether the absoulate path is a directory, async off of the main cocos thread.
*
* @param dirPath The path of the directory, it must be an absolute path
* @param callback that will accept a boolean, true if the file exists, false otherwise.
* Callback will happen on the main cocos thread.
*/
virtual void isDirectoryExist(const std::string& fullPath, std::function<void(bool)> callback);
/**
@ -802,6 +802,22 @@ public:
*/
virtual void getFileSize(const std::string &filepath, std::function<void(long)> callback);
/**
* List all files in a directory.
*
* @param dirPath The path of the directory, it could be a relative or an absolute path.
* @return File paths in a string vector
*/
virtual std::vector<std::string> listFiles(const std::string& dirPath) const;
/**
* List all files recursively in a directory.
*
* @param dirPath The path of the directory, it could be a relative or an absolute path.
* @return File paths in a string vector
*/
virtual void listFilesRecursively(const std::string& dirPath, std::vector<std::string> *files) const;
/** Returns the full path cache. */
const std::unordered_map<std::string, std::string>& getFullPathCache() const { return _fullPathCache; }

Просмотреть файл

@ -10,6 +10,10 @@ import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.message.BasicHeader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
class DataTaskHandler extends BinaryHttpResponseHandler {
@ -60,6 +64,51 @@ class DataTaskHandler extends BinaryHttpResponseHandler {
}
}
class HeadTaskHandler extends AsyncHttpResponseHandler {
int _id;
String _host;
String _url;
String _path;
private Cocos2dxDownloader _downloader;
void LogD(String msg) {
android.util.Log.d("Cocos2dxDownloader", msg);
}
public HeadTaskHandler(Cocos2dxDownloader downloader, int id, String host, String url, String path) {
super();
_downloader = downloader;
_id = id;
_host = host;
_url = url;
_path = path;
}
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Boolean acceptRanges = false;
for (int i = 0; i < headers.length; ++i) {
Header elem = headers[i];
if (elem.getName().equals("Accept-Ranges")) {
acceptRanges = elem.getValue().equals("bytes");
break;
}
}
Cocos2dxDownloader.setResumingSupport(_host, acceptRanges);
Cocos2dxDownloader.createTask(_downloader, _id, _url, _path);
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable throwable) {
LogD("onFailure(code:" + statusCode + " headers:" + headers + " throwable:" + throwable + " id:" + _id);
String errStr = "";
if (null != throwable) {
errStr = throwable.toString();
}
_downloader.onFinish(_id, statusCode, errStr, null);
}
}
class FileTaskHandler extends FileAsyncHttpResponseHandler {
int _id;
File _finalFile;
@ -171,6 +220,7 @@ public class Cocos2dxDownloader {
private HashMap _taskMap = new HashMap();
private Queue<Runnable> _taskQueue = new LinkedList<Runnable>();
private int _runningTaskCount = 0;
private static HashMap<String, Boolean> _resumingSupport = new HashMap<String, Boolean>();
void onProgress(final int id, final long downloadBytes, final long downloadNow, final long downloadTotal) {
DownloadTask task = (DownloadTask)_taskMap.get(id);
@ -206,6 +256,10 @@ public class Cocos2dxDownloader {
});
}
public static void setResumingSupport(String host, Boolean support) {
Cocos2dxDownloader._resumingSupport.put(host, support);
}
public static Cocos2dxDownloader createDownloader(int id, int timeoutInSeconds, String tempFileNameSufix, int countOfMaxProcessingTasks) {
Cocos2dxDownloader downloader = new Cocos2dxDownloader();
downloader._id = id;
@ -239,6 +293,29 @@ public class Cocos2dxDownloader {
do {
if (0 == path.length()) break;
String domain;
try {
URI uri = new URI(url);
domain = uri.getHost();
}
catch (URISyntaxException e) {
break;
}
final String host = domain.startsWith("www.") ? domain.substring(4) : domain;
Boolean supportResuming = false;
Boolean requestHeader = true;
if (_resumingSupport.containsKey(host)) {
supportResuming = _resumingSupport.get(host);
requestHeader = false;
}
if (requestHeader) {
task.handler = new HeadTaskHandler(downloader, id, host, url, path);
task.handle = downloader._httpClient.head(Cocos2dxHelper.getActivity(), url, null, null, task.handler);
break;
}
// file task
File tempFile = new File(path + downloader._tempFileNameSufix);
if (tempFile.isDirectory()) break;
@ -252,14 +329,23 @@ public class Cocos2dxDownloader {
task.handler = new FileTaskHandler(downloader, id, tempFile, finalFile);
Header[] headers = null;
long fileLen = tempFile.length();
if (fileLen > 0) {
if (supportResuming && fileLen > 0) {
// continue download
List<Header> list = new ArrayList<Header>();
list.add(new BasicHeader("Range", "bytes=" + fileLen + "-"));
headers = list.toArray(new Header[list.size()]);
}
else if (fileLen > 0) {
// Remove previous downloaded context
try {
PrintWriter writer = new PrintWriter(tempFile);
writer.print("");
writer.close();
}
// Not found then nothing to do
catch (FileNotFoundException e) {}
}
task.handle = downloader._httpClient.get(Cocos2dxHelper.getActivity(), url, headers, null, task.handler);
//task.handle = downloader._httpClient.get(url, task.handler);
} while (false);
if (null == task.handle) {

Просмотреть файл

@ -39,6 +39,7 @@ set(JSBINDING_SRC
auto/jsb_cocos2dx_audioengine_auto.cpp
auto/jsb_cocos2dx_builder_auto.cpp
auto/jsb_cocos2dx_extension_auto.cpp
auto/jsb_cocos2dx_network_auto.cpp
auto/jsb_cocos2dx_spine_auto.cpp
auto/jsb_cocos2dx_studio_auto.cpp
auto/jsb_cocos2dx_ui_auto.cpp
@ -69,6 +70,7 @@ set(JSBINDING_SRC
manual/network/XMLHTTPRequest.cpp
manual/network/jsb_websocket.cpp
manual/network/jsb_socketio.cpp
manual/network/js_network_manual.cpp
manual/spine/jsb_cocos2dx_spine_manual.cpp
manual/ui/jsb_cocos2dx_ui_manual.cpp
manual/3d/jsb_cocos2dx_3d_manual.cpp

Просмотреть файл

@ -0,0 +1,319 @@
#include "scripting/js-bindings/auto/jsb_cocos2dx_network_auto.hpp"
#include "scripting/js-bindings/manual/cocos2d_specifics.hpp"
#include "network/CCDownloader.h"
template<class T>
static bool dummy_constructor(JSContext *cx, uint32_t argc, jsval *vp)
{
JS_ReportError(cx, "Constructor for the requested class is not available, please refer to the API reference.");
return false;
}
static bool empty_constructor(JSContext *cx, uint32_t argc, jsval *vp) {
return false;
}
static bool js_is_native_obj(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
args.rval().setBoolean(true);
return true;
}
JSClass *jsb_cocos2d_network_Downloader_class;
JSObject *jsb_cocos2d_network_Downloader_prototype;
bool js_cocos2dx_network_Downloader_setOnTaskError(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
bool ok = true;
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::network::Downloader* cobj = (cocos2d::network::Downloader *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_network_Downloader_setOnTaskError : Invalid Native Object");
if (argc == 1) {
std::function<void (const cocos2d::network::DownloadTask &, int, int, const std::basic_string<char> &)> arg0;
do {
if(JS_TypeOfValue(cx, args.get(0)) == JSTYPE_FUNCTION)
{
JS::RootedObject jstarget(cx, args.thisv().toObjectOrNull());
std::shared_ptr<JSFunctionWrapper> func(new JSFunctionWrapper(cx, jstarget, args.get(0), args.thisv()));
auto lambda = [=](const cocos2d::network::DownloadTask & larg0, int larg1, int larg2, const std::basic_string<char> & larg3) -> void {
JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET
jsval largv[4];
largv[0] = downloadTask_to_jsval(cx, larg0);
largv[1] = int32_to_jsval(cx, larg1);
largv[2] = int32_to_jsval(cx, larg2);
largv[3] = std_string_to_jsval(cx, larg3);
JS::RootedValue rval(cx);
bool succeed = func->invoke(4, &largv[0], &rval);
if (!succeed && JS_IsExceptionPending(cx)) {
JS_ReportPendingException(cx);
}
};
arg0 = lambda;
}
else
{
arg0 = nullptr;
}
} while(0)
;
JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_network_Downloader_setOnTaskError : Error processing arguments");
cobj->setOnTaskError(arg0);
args.rval().setUndefined();
return true;
}
JS_ReportError(cx, "js_cocos2dx_network_Downloader_setOnTaskError : wrong number of arguments: %d, was expecting %d", argc, 1);
return false;
}
bool js_cocos2dx_network_Downloader_setOnTaskProgress(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
bool ok = true;
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::network::Downloader* cobj = (cocos2d::network::Downloader *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_network_Downloader_setOnTaskProgress : Invalid Native Object");
if (argc == 1) {
std::function<void (const cocos2d::network::DownloadTask &, long long, long long, long long)> arg0;
do {
if(JS_TypeOfValue(cx, args.get(0)) == JSTYPE_FUNCTION)
{
JS::RootedObject jstarget(cx, args.thisv().toObjectOrNull());
std::shared_ptr<JSFunctionWrapper> func(new JSFunctionWrapper(cx, jstarget, args.get(0), args.thisv()));
auto lambda = [=](const cocos2d::network::DownloadTask & larg0, long long larg1, long long larg2, long long larg3) -> void {
JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET
jsval largv[4];
largv[0] = downloadTask_to_jsval(cx, larg0);
largv[1] = long_long_to_jsval(cx, larg1);
largv[2] = long_long_to_jsval(cx, larg2);
largv[3] = long_long_to_jsval(cx, larg3);
JS::RootedValue rval(cx);
bool succeed = func->invoke(4, &largv[0], &rval);
if (!succeed && JS_IsExceptionPending(cx)) {
JS_ReportPendingException(cx);
}
};
arg0 = lambda;
}
else
{
arg0 = nullptr;
}
} while(0)
;
JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_network_Downloader_setOnTaskProgress : Error processing arguments");
cobj->setOnTaskProgress(arg0);
args.rval().setUndefined();
return true;
}
JS_ReportError(cx, "js_cocos2dx_network_Downloader_setOnTaskProgress : wrong number of arguments: %d, was expecting %d", argc, 1);
return false;
}
bool js_cocos2dx_network_Downloader_createDownloadFileTask(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
bool ok = true;
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::network::Downloader* cobj = (cocos2d::network::Downloader *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_network_Downloader_createDownloadFileTask : Invalid Native Object");
if (argc == 2) {
std::string arg0;
std::string arg1;
ok &= jsval_to_std_string(cx, args.get(0), &arg0);
ok &= jsval_to_std_string(cx, args.get(1), &arg1);
JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_network_Downloader_createDownloadFileTask : Error processing arguments");
std::shared_ptr<const cocos2d::network::DownloadTask> ret = cobj->createDownloadFileTask(arg0, arg1);
JS::RootedValue jsret(cx);
jsret = downloadTask_to_jsval(cx, *ret);
args.rval().set(jsret);
return true;
}
if (argc == 3) {
std::string arg0;
std::string arg1;
std::string arg2;
ok &= jsval_to_std_string(cx, args.get(0), &arg0);
ok &= jsval_to_std_string(cx, args.get(1), &arg1);
ok &= jsval_to_std_string(cx, args.get(2), &arg2);
JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_network_Downloader_createDownloadFileTask : Error processing arguments");
std::shared_ptr<const cocos2d::network::DownloadTask> ret = cobj->createDownloadFileTask(arg0, arg1, arg2);
JS::RootedValue jsret(cx);
jsret = downloadTask_to_jsval(cx, *ret);
args.rval().set(jsret);
return true;
}
JS_ReportError(cx, "js_cocos2dx_network_Downloader_createDownloadFileTask : wrong number of arguments: %d, was expecting %d", argc, 2);
return false;
}
bool js_cocos2dx_network_Downloader_setOnFileTaskSuccess(JSContext *cx, uint32_t argc, jsval *vp)
{
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
bool ok = true;
JS::RootedObject obj(cx, args.thisv().toObjectOrNull());
js_proxy_t *proxy = jsb_get_js_proxy(obj);
cocos2d::network::Downloader* cobj = (cocos2d::network::Downloader *)(proxy ? proxy->ptr : NULL);
JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_network_Downloader_setOnFileTaskSuccess : Invalid Native Object");
if (argc == 1) {
std::function<void (const cocos2d::network::DownloadTask &)> arg0;
do {
if(JS_TypeOfValue(cx, args.get(0)) == JSTYPE_FUNCTION)
{
JS::RootedObject jstarget(cx, args.thisv().toObjectOrNull());
std::shared_ptr<JSFunctionWrapper> func(new JSFunctionWrapper(cx, jstarget, args.get(0), args.thisv()));
auto lambda = [=](const cocos2d::network::DownloadTask & larg0) -> void {
JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET
jsval largv[1];
largv[0] = downloadTask_to_jsval(cx, larg0);
JS::RootedValue rval(cx);
bool succeed = func->invoke(1, &largv[0], &rval);
if (!succeed && JS_IsExceptionPending(cx)) {
JS_ReportPendingException(cx);
}
};
arg0 = lambda;
}
else
{
arg0 = nullptr;
}
} while(0)
;
JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_network_Downloader_setOnFileTaskSuccess : Error processing arguments");
cobj->setOnFileTaskSuccess(arg0);
args.rval().setUndefined();
return true;
}
JS_ReportError(cx, "js_cocos2dx_network_Downloader_setOnFileTaskSuccess : wrong number of arguments: %d, was expecting %d", argc, 1);
return false;
}
bool js_cocos2dx_network_Downloader_constructor(JSContext *cx, uint32_t argc, jsval *vp)
{
bool ok = true;
cocos2d::network::Downloader* cobj = nullptr;
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
JS::RootedObject obj(cx);
do {
if (argc == 1) {
cocos2d::network::DownloaderHints arg0;
ok &= jsval_to_DownloaderHints(cx, args.get(0), &arg0);
if (!ok) { ok = true; break; }
cobj = new (std::nothrow) cocos2d::network::Downloader(arg0);
js_type_class_t *typeClass = js_get_type_from_native<cocos2d::network::Downloader>(cobj);
JS::RootedObject proto(cx, typeClass->proto.ref());
JS::RootedObject parent(cx, typeClass->parentProto.ref());
obj = JS_NewObject(cx, typeClass->jsclass, proto, parent);
js_proxy_t* p = jsb_new_proxy(cobj, obj);
jsb_non_ref_init(cx, &p->obj, cobj, "cocos2d::network::Downloader");
}
} while(0);
do {
if (argc == 0) {
cobj = new (std::nothrow) cocos2d::network::Downloader();
js_type_class_t *typeClass = js_get_type_from_native<cocos2d::network::Downloader>(cobj);
JS::RootedObject proto(cx, typeClass->proto.ref());
JS::RootedObject parent(cx, typeClass->parentProto.ref());
obj = JS_NewObject(cx, typeClass->jsclass, proto, parent);
js_proxy_t* p = jsb_new_proxy(cobj, obj);
jsb_non_ref_init(cx, &p->obj, cobj, "cocos2d::network::Downloader");
}
} while(0);
if (cobj) {
if (JS_HasProperty(cx, obj, "_ctor", &ok) && ok)
ScriptingCore::getInstance()->executeFunctionWithOwner(OBJECT_TO_JSVAL(obj), "_ctor", args);
args.rval().set(OBJECT_TO_JSVAL(obj));
return true;
}
JS_ReportError(cx, "js_cocos2dx_network_Downloader_constructor : wrong number of arguments");
return false;
}
void js_cocos2d_network_Downloader_finalize(JSFreeOp *fop, JSObject *obj) {
CCLOGINFO("jsbindings: finalizing JS object %p (Downloader)", obj);
js_proxy_t* nproxy;
js_proxy_t* jsproxy;
JSContext *cx = ScriptingCore::getInstance()->getGlobalContext();
JS::RootedObject jsobj(cx, obj);
jsproxy = jsb_get_js_proxy(jsobj);
if (jsproxy) {
cocos2d::network::Downloader *nobj = static_cast<cocos2d::network::Downloader *>(jsproxy->ptr);
nproxy = jsb_get_native_proxy(jsproxy->ptr);
if (nobj) {
jsb_remove_proxy(nproxy, jsproxy);
JS::RootedValue flagValue(cx);
JS_GetProperty(cx, jsobj, "__cppCreated", &flagValue);
if (flagValue.isNullOrUndefined()){
delete nobj;
}
}
else
jsb_remove_proxy(nullptr, jsproxy);
}
}
void js_register_cocos2dx_network_Downloader(JSContext *cx, JS::HandleObject global) {
jsb_cocos2d_network_Downloader_class = (JSClass *)calloc(1, sizeof(JSClass));
jsb_cocos2d_network_Downloader_class->name = "Downloader";
jsb_cocos2d_network_Downloader_class->addProperty = JS_PropertyStub;
jsb_cocos2d_network_Downloader_class->delProperty = JS_DeletePropertyStub;
jsb_cocos2d_network_Downloader_class->getProperty = JS_PropertyStub;
jsb_cocos2d_network_Downloader_class->setProperty = JS_StrictPropertyStub;
jsb_cocos2d_network_Downloader_class->enumerate = JS_EnumerateStub;
jsb_cocos2d_network_Downloader_class->resolve = JS_ResolveStub;
jsb_cocos2d_network_Downloader_class->convert = JS_ConvertStub;
jsb_cocos2d_network_Downloader_class->finalize = js_cocos2d_network_Downloader_finalize;
jsb_cocos2d_network_Downloader_class->flags = JSCLASS_HAS_RESERVED_SLOTS(2);
static JSPropertySpec properties[] = {
JS_PS_END
};
static JSFunctionSpec funcs[] = {
JS_FN("setOnTaskError", js_cocos2dx_network_Downloader_setOnTaskError, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setOnTaskProgress", js_cocos2dx_network_Downloader_setOnTaskProgress, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("createDownloadFileTask", js_cocos2dx_network_Downloader_createDownloadFileTask, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FN("setOnFileTaskSuccess", js_cocos2dx_network_Downloader_setOnFileTaskSuccess, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_FS_END
};
JSFunctionSpec *st_funcs = NULL;
jsb_cocos2d_network_Downloader_prototype = JS_InitClass(
cx, global,
JS::NullPtr(),
jsb_cocos2d_network_Downloader_class,
js_cocos2dx_network_Downloader_constructor, 0, // constructor
properties,
funcs,
NULL, // no static properties
st_funcs);
JS::RootedObject proto(cx, jsb_cocos2d_network_Downloader_prototype);
JS::RootedValue className(cx, std_string_to_jsval(cx, "Downloader"));
JS_SetProperty(cx, proto, "_className", className);
JS_SetProperty(cx, proto, "__nativeObj", JS::TrueHandleValue);
JS_SetProperty(cx, proto, "__is_ref", JS::FalseHandleValue);
// add the proto and JSClass to the type->js info hash table
jsb_register_class<cocos2d::network::Downloader>(cx, jsb_cocos2d_network_Downloader_class, proto, JS::NullPtr());
}
void register_all_cocos2dx_network(JSContext* cx, JS::HandleObject obj) {
// Get the ns
JS::RootedObject ns(cx);
get_or_create_js_obj(cx, obj, "jsb", &ns);
js_register_cocos2dx_network_Downloader(cx, ns);
}

Просмотреть файл

@ -0,0 +1,21 @@
#include "base/ccConfig.h"
#ifndef __cocos2dx_network_h__
#define __cocos2dx_network_h__
#include "jsapi.h"
#include "jsfriendapi.h"
extern JSClass *jsb_cocos2d_network_Downloader_class;
extern JSObject *jsb_cocos2d_network_Downloader_prototype;
bool js_cocos2dx_network_Downloader_constructor(JSContext *cx, uint32_t argc, jsval *vp);
void js_cocos2dx_network_Downloader_finalize(JSContext *cx, JSObject *obj);
void js_register_cocos2dx_network_Downloader(JSContext *cx, JS::HandleObject global);
void register_all_cocos2dx_network(JSContext* cx, JS::HandleObject obj);
bool js_cocos2dx_network_Downloader_setOnTaskError(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_network_Downloader_setOnTaskProgress(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_network_Downloader_createDownloadFileTask(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_network_Downloader_setOnFileTaskSuccess(JSContext *cx, uint32_t argc, jsval *vp);
bool js_cocos2dx_network_Downloader_Downloader(JSContext *cx, uint32_t argc, jsval *vp);
#endif // __cocos2dx_network_h__

Просмотреть файл

@ -2332,7 +2332,6 @@ JSObject* jsb_ref_get_or_create_jsobject(JSContext *cx, cocos2d::Ref *ref, js_ty
return obj;
}
// don't auto-release, don't retain.
JS::RootedObject proto(cx, typeClass->proto.ref());
JS::RootedObject parent(cx, typeClass->parentProto.ref());
JS::RootedObject jsObj(cx, JS_NewObject(cx, typeClass->jsclass, proto, parent));
@ -2344,7 +2343,7 @@ JSObject* jsb_ref_get_or_create_jsobject(JSContext *cx, cocos2d::Ref *ref, js_ty
CCLOG("++++++RETAINED++++++ Cpp(%s): %p - JS: %p", debug, ref, jsObj.get());
#endif // COCOS2D_DEBUG
#else
// don't autorelease it
// don't auto-release, don't retain.
JS::AddNamedObjectRoot(cx, &newproxy->obj, debug);
#endif // CC_ENABLE_GC_FOR_NATIVE_OBJECTS
@ -2450,6 +2449,19 @@ void jsb_ref_rebind(JSContext* cx, JS::HandleObject jsobj, js_proxy_t *proxy, co
#endif
}
void jsb_non_ref_init(JSContext* cx, JS::Heap<JSObject*> *obj, void* native, const char* debug)
{
// CCLOG("jsb_non_ref_init: JSObject address = %p. %s", obj->get(), debug);
#if CC_ENABLE_GC_FOR_NATIVE_OBJECTS
JS::RootedObject jsObj(cx, *obj);
js_add_FinalizeHook(cx, jsObj, false);
// don't retain it, already retained
#if COCOS2D_DEBUG > 1
CCLOG("++++++RETAINED++++++ Cpp(%s): %p - JS: %p", debug, native, jsObj.get());
#endif // COCOS2D_DEBUG
#endif
}
// Register finalize hook
void jsb_register_finalize_hook(JSObject *hook, JSObject *owner)
{

Просмотреть файл

@ -354,10 +354,10 @@ public:
*/
void cleanAllScript();
/**@~english
* Gets the time that the ScriptingCore was initalized
*/
std::chrono::steady_clock::time_point getEngineStartTime() const;
/**@~english
* Gets the time that the ScriptingCore was initalized
*/
std::chrono::steady_clock::time_point getEngineStartTime() const;
/**@~english
* Initialize everything, including the js context, js global object etc.
@ -633,6 +633,11 @@ void jsb_ref_autoreleased_init(JSContext* cx, JS::Heap<JSObject*> *obj, cocos2d:
*/
void jsb_ref_rebind(JSContext* cx, JS::HandleObject jsobj, js_proxy_t *js2native_proxy, cocos2d::Ref* oldRef, cocos2d::Ref* newRef, const char* debug);
/**
* Generic initialization function for non Ref classes
*/
void jsb_non_ref_init(JSContext* cx, JS::Heap<JSObject*> *obj, void* native, const char* debug);
/**
* Creates a new JSObject of a certain type (typeClass) and creates a proxy associated with and the Ref
*/

Просмотреть файл

@ -716,7 +716,6 @@ void js_remove_object_root(JS::HandleValue target)
}
JSCallbackWrapper::JSCallbackWrapper()
: _rooted(true)
{
JSContext* cx = ScriptingCore::getInstance()->getGlobalContext();
_jsCallback = JS::NullValue();
@ -730,7 +729,6 @@ JSCallbackWrapper::JSCallbackWrapper()
}
JSCallbackWrapper::JSCallbackWrapper(JS::HandleValue owner)
: _rooted(false)
{
_owner = owner;
_jsCallback = JS::NullValue();
@ -740,9 +738,10 @@ JSCallbackWrapper::JSCallbackWrapper(JS::HandleValue owner)
JSCallbackWrapper::~JSCallbackWrapper()
{
JSContext* cx = ScriptingCore::getInstance()->getGlobalContext();
ScriptingCore* sc = ScriptingCore::getInstance();
JSContext* cx = sc->getGlobalContext();
JS::RootedValue ownerVal(cx, _owner);
if (_rooted && !ownerVal.isNullOrUndefined())
if (!sc->getFinalizing() && !ownerVal.isNullOrUndefined())
{
JS::RootedValue target(cx, _jsCallback);
if (!target.isNullOrUndefined())
@ -763,55 +762,55 @@ JSCallbackWrapper::~JSCallbackWrapper()
}
void JSCallbackWrapper::setJSCallbackFunc(JS::HandleValue func) {
JSContext* cx = ScriptingCore::getInstance()->getGlobalContext();
JS::RootedValue ownerVal(cx, _owner);
if (!ownerVal.isNullOrUndefined())
{
JS::RootedValue target(cx, _jsCallback);
if (!target.isNullOrUndefined())
{
js_remove_object_reference(ownerVal, target);
}
js_add_object_reference(ownerVal, func);
}
if (!func.isNullOrUndefined())
{
JSContext* cx = ScriptingCore::getInstance()->getGlobalContext();
JS::RootedValue ownerVal(cx, _owner);
if (!ownerVal.isNullOrUndefined())
{
JS::RootedValue target(cx, _jsCallback);
if (!target.isNullOrUndefined())
{
js_remove_object_reference(ownerVal, target);
}
js_add_object_reference(ownerVal, func);
}
_jsCallback = func;
}
}
void JSCallbackWrapper::setJSCallbackThis(JS::HandleValue thisObj) {
JSContext* cx = ScriptingCore::getInstance()->getGlobalContext();
JS::RootedValue ownerVal(cx, _owner);
if (!ownerVal.isNullOrUndefined())
{
JS::RootedValue target(cx, _jsThisObj);
if (!target.isNullOrUndefined())
{
js_remove_object_reference(ownerVal, target);
}
js_add_object_reference(ownerVal, thisObj);
}
if (!thisObj.isNullOrUndefined())
{
JSContext* cx = ScriptingCore::getInstance()->getGlobalContext();
JS::RootedValue ownerVal(cx, _owner);
if (!ownerVal.isNullOrUndefined())
{
JS::RootedValue target(cx, _jsThisObj);
if (!target.isNullOrUndefined())
{
js_remove_object_reference(ownerVal, target);
}
js_add_object_reference(ownerVal, thisObj);
}
_jsThisObj = thisObj;
}
}
void JSCallbackWrapper::setJSExtraData(JS::HandleValue data) {
JSContext* cx = ScriptingCore::getInstance()->getGlobalContext();
JS::RootedValue ownerVal(cx, _owner);
if (!ownerVal.isNullOrUndefined())
{
JS::RootedValue target(cx, _extraData);
if (!target.isNullOrUndefined())
{
js_remove_object_reference(ownerVal, target);
}
js_add_object_reference(ownerVal, data);
}
if (!data.isNullOrUndefined())
{
JSContext* cx = ScriptingCore::getInstance()->getGlobalContext();
JS::RootedValue ownerVal(cx, _owner);
if (!ownerVal.isNullOrUndefined())
{
JS::RootedValue target(cx, _extraData);
if (!target.isNullOrUndefined())
{
js_remove_object_reference(ownerVal, target);
}
js_add_object_reference(ownerVal, data);
}
_extraData = data;
}
}
@ -1286,7 +1285,12 @@ void JSScheduleWrapper::update(float dt)
{
jsval data = DOUBLE_TO_JSVAL(dt);
ScriptingCore::getInstance()->executeFunctionWithOwner(getJSCallbackThis(), "update", 1, &data);
JSContext *cx = ScriptingCore::getInstance()->getGlobalContext();
JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET
JS::RootedValue targetVal(cx, getJSCallbackThis());
ScriptingCore::getInstance()->executeFunctionWithOwner(targetVal, "update", 1, &data);
}
Ref* JSScheduleWrapper::getTarget()
@ -5299,8 +5303,9 @@ void get_or_create_js_obj(const std::string &name, JS::MutableHandleObject jsObj
{
subProp = name.substr(start);
get_or_create_js_obj(cx, obj, subProp, &prop);
jsObj.set(obj);
obj.set(prop);
}
jsObj.set(obj);
}
#if CC_ENABLE_BULLET_INTEGRATION && CC_USE_3D_PHYSICS

Просмотреть файл

@ -172,7 +172,6 @@ protected:
JS::Heap<JS::Value> _jsCallback;
JS::Heap<JS::Value> _jsThisObj;
JS::Heap<JS::Value> _extraData;
bool _rooted;
};

Просмотреть файл

@ -32,6 +32,7 @@
#include "deprecated/CCInteger.h"
#include "deprecated/CCString.h"
#include "editor-support/cocostudio/CocosStudioExtension.h"
#include "extensions/assets-manager/Manifest.h"
#include "math/TransformUtils.h"
#include "scripting/js-bindings/manual/ScriptingCore.h"
#include "scripting/js-bindings/manual/cocos2d_specifics.hpp"
@ -107,7 +108,6 @@ const char* JSStringWrapper::get()
// JSFunctionWrapper
JSFunctionWrapper::JSFunctionWrapper(JSContext* cx, JS::HandleObject jsthis, JS::HandleValue fval)
: _cx(cx)
, _rooted(false)
{
_jsthis = jsthis;
_fval = fval;
@ -129,12 +129,10 @@ JSFunctionWrapper::JSFunctionWrapper(JSContext* cx, JS::HandleObject jsthis, JS:
{
js_add_object_reference(valRoot, funcVal);
}
_rooted = true;
}
}
JSFunctionWrapper::JSFunctionWrapper(JSContext* cx, JS::HandleObject jsthis, JS::HandleValue fval, JS::HandleValue owner)
: _cx(cx)
, _rooted(false)
{
_jsthis = jsthis;
_fval = fval;
@ -157,7 +155,7 @@ JSFunctionWrapper::~JSFunctionWrapper()
{
JS::RootedValue ownerVal(_cx, _owner);
if (_rooted && !ownerVal.isNullOrUndefined())
if (!ScriptingCore::getInstance()->getFinalizing() && !ownerVal.isNullOrUndefined())
{
JS::RootedValue thisVal(_cx, OBJECT_TO_JSVAL(_jsthis));
if (!thisVal.isNullOrUndefined())
@ -181,6 +179,15 @@ bool JSFunctionWrapper::invoke(unsigned int argc, jsval *argv, JS::MutableHandle
return JS_CallFunctionValue(_cx, thisObj, fval, JS::HandleValueArray::fromMarkedLocation(argc, argv), rval);
}
bool JSFunctionWrapper::invoke(JS::HandleValueArray args, JS::MutableHandleValue rval)
{
JSB_AUTOCOMPARTMENT_WITH_GLOBAL_OBJCET
JS::RootedObject thisObj(_cx, _jsthis);
JS::RootedValue fval(_cx, _fval);
return JS_CallFunctionValue(_cx, thisObj, fval, args, rval);
}
static Color3B getColorFromJSObject(JSContext *cx, JS::HandleObject colorObject)
{
JS::RootedValue jsr(cx);
@ -2981,3 +2988,18 @@ jsval resourcedata_to_jsval(JSContext* cx, const ResourceData& v)
}
return JSVAL_NULL;
}
jsval asset_to_jsval(JSContext* cx, const cocos2d::extension::ManifestAsset& v)
{
JS::RootedObject tmp(cx, JS_NewObject(cx, NULL, JS::NullPtr(), JS::NullPtr()));
if (!tmp) return JSVAL_NULL;
bool ok = JS_DefineProperty(cx, tmp, "md5", JS::RootedValue(cx, std_string_to_jsval(cx, v.md5)), JSPROP_ENUMERATE | JSPROP_PERMANENT) &&
JS_DefineProperty(cx, tmp, "path", JS::RootedValue(cx, std_string_to_jsval(cx, v.path)), JSPROP_ENUMERATE | JSPROP_PERMANENT) &&
JS_DefineProperty(cx, tmp, "compressed", v.compressed, JSPROP_ENUMERATE | JSPROP_PERMANENT) &&
JS_DefineProperty(cx, tmp, "size", v.size, JSPROP_ENUMERATE | JSPROP_PERMANENT) &&
JS_DefineProperty(cx, tmp, "downloadState", (int)v.downloadState, JSPROP_ENUMERATE | JSPROP_PERMANENT);
if (ok) {
return OBJECT_TO_JSVAL(tmp);
}
return JSVAL_NULL;
}

Просмотреть файл

@ -49,6 +49,9 @@
NS_CC_BEGIN
struct CC_DLL ResourceData;
namespace extension {
struct ManifestAsset;
}
NS_CC_END
// just a simple utility to avoid mem leaking when using JSString
@ -80,12 +83,12 @@ public:
~JSFunctionWrapper();
bool invoke(unsigned int argc, jsval *argv, JS::MutableHandleValue rval);
bool invoke(JS::HandleValueArray args, JS::MutableHandleValue rval);
private:
JSContext *_cx;
JS::Heap<JSObject*> _jsthis;
JS::Heap<JS::Value> _fval;
JS::Heap<JS::Value> _owner;
bool _rooted;
private:
CC_DISALLOW_COPY_AND_ASSIGN(JSFunctionWrapper);
};
@ -293,7 +296,7 @@ jsval quaternion_to_jsval(JSContext* cx, const cocos2d::Quaternion& q);
jsval meshVertexAttrib_to_jsval(JSContext* cx, const cocos2d::MeshVertexAttrib& q);
jsval uniform_to_jsval(JSContext* cx, const cocos2d::Uniform* uniform);
jsval resourcedata_to_jsval(JSContext* cx, const cocos2d::ResourceData& v);
jsval asset_to_jsval(JSContext* cx, const cocos2d::extension::ManifestAsset& v);
// forward declaration
template <class T>

Просмотреть файл

@ -6,6 +6,7 @@
#include "scripting/js-bindings/auto/jsb_cocos2dx_builder_auto.hpp"
#include "scripting/js-bindings/auto/jsb_cocos2dx_spine_auto.hpp"
#include "scripting/js-bindings/auto/jsb_cocos2dx_extension_auto.hpp"
#include "scripting/js-bindings/auto/jsb_cocos2dx_network_auto.hpp"
#include "scripting/js-bindings/auto/jsb_cocos2dx_3d_auto.hpp"
#include "scripting/js-bindings/auto/jsb_cocos2dx_3d_extension_auto.hpp"
#include "scripting/js-bindings/manual/3d/jsb_cocos2dx_3d_manual.h"
@ -81,6 +82,8 @@ int js_module_register()
sc->addRegisterCallback(register_jsb_websocket);
// socket io can be commented out to reduce the package
sc->addRegisterCallback(register_jsb_socketio);
// Downloader
sc->addRegisterCallback(register_all_cocos2dx_network);
// 3d can be commented out to reduce the package
sc->addRegisterCallback(register_all_cocos2dx_3d);

Просмотреть файл

@ -246,12 +246,12 @@ bool js_EventListenerCustom_create(JSContext *cx, uint32_t argc, jsval *vp)
jsval largv[1];
if (event) {
js_type_class_t *typeClassEvent = js_get_type_from_native<EventCustom>(event);
largv[0] = OBJECT_TO_JSVAL(jsb_get_or_create_weak_jsobject(cx, event, typeClassEvent));
largv[0] = OBJECT_TO_JSVAL(jsb_get_or_create_weak_jsobject(cx, event, typeClassEvent, "EventCustom"));
} else {
largv[0] = JSVAL_NULL;
};
JS::RootedValue rval(cx);
bool succeed = func->invoke(1, &largv[0], &rval);
bool succeed = func->invoke(JS::HandleValueArray::fromMarkedLocation(1, largv), &rval);
if (!succeed && JS_IsExceptionPending(cx)) {
JS_ReportPendingException(cx);
}
@ -303,7 +303,7 @@ bool js_EventDispatcher_addCustomEventListener(JSContext *cx, uint32_t argc, jsv
largv[0] = JSVAL_NULL;
};
JS::RootedValue rval(cx);
bool succeed = func->invoke(1, &largv[0], &rval);
bool succeed = func->invoke(JS::HandleValueArray::fromMarkedLocation(1, largv), &rval);
if (!succeed && JS_IsExceptionPending(cx)) {
JS_ReportPendingException(cx);
}

Просмотреть файл

@ -0,0 +1,64 @@
/*
* Copyright (c) 2017 Chukong Technologies Inc.
* Created by panda on 1/13/17.
*
* 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 "scripting/js-bindings/manual/network/js_network_manual.h"
#include "scripting/js-bindings/manual/js_manual_conversions.h"
bool jsval_to_DownloaderHints(JSContext *cx, JS::HandleValue v, cocos2d::network::DownloaderHints* ret) {
JS::RootedObject tmp(cx);
JS::RootedValue jsCountOfMaxProcessingTasks(cx);
JS::RootedValue jsTimeoutInSeconds(cx);
JS::RootedValue jsTempFileNameSuffix(cx);
double countOfMaxProcessingTasks = 0, timeoutInSeconds = 0;
std::string tempFileNameSuffix;
bool ok = v.isObject() &&
JS_ValueToObject(cx, v, &tmp) &&
JS_GetProperty(cx, tmp, "countOfMaxProcessingTasks", &jsCountOfMaxProcessingTasks) &&
JS_GetProperty(cx, tmp, "timeoutInSeconds", &jsTimeoutInSeconds) &&
JS_GetProperty(cx, tmp, "tempFileNameSuffix", &jsTempFileNameSuffix) &&
JS::ToNumber(cx, jsCountOfMaxProcessingTasks, &countOfMaxProcessingTasks) &&
JS::ToNumber(cx, jsTimeoutInSeconds, &timeoutInSeconds) &&
jsval_to_std_string(cx, jsTempFileNameSuffix, &tempFileNameSuffix);
JSB_PRECONDITION3(ok, cx, false, "Error processing arguments");
ret->countOfMaxProcessingTasks = (uint32_t)countOfMaxProcessingTasks;
ret->timeoutInSeconds = (uint32_t)timeoutInSeconds;
ret->tempFileNameSuffix = tempFileNameSuffix;
return true;
}
jsval downloadTask_to_jsval(JSContext *cx, const cocos2d::network::DownloadTask& v)
{
JS::RootedObject tmp(cx, JS_NewObject(cx, NULL, JS::NullPtr(), JS::NullPtr()));
if (!tmp) return JSVAL_NULL;
bool ok = JS_DefineProperty(cx, tmp, "identifier", JS::RootedValue(cx, std_string_to_jsval(cx, v.identifier)), JSPROP_ENUMERATE | JSPROP_PERMANENT) &&
JS_DefineProperty(cx, tmp, "requestURL", JS::RootedValue(cx, std_string_to_jsval(cx, v.requestURL)), JSPROP_ENUMERATE | JSPROP_PERMANENT) &&
JS_DefineProperty(cx, tmp, "storagePath", JS::RootedValue(cx, std_string_to_jsval(cx, v.storagePath)), JSPROP_ENUMERATE | JSPROP_PERMANENT);
if (ok) {
return OBJECT_TO_JSVAL(tmp);
}
return JSVAL_NULL;
}

Просмотреть файл

@ -0,0 +1,36 @@
/*
* Copyright (c) 2017 Chukong Technologies Inc.
* Created by panda on 1/13/17.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef js_network_manual_h
#define js_network_manual_h
#include "jsapi.h"
#include "jsfriendapi.h"
#include "network/CCDownloader.h"
bool jsval_to_DownloaderHints(JSContext *cx, JS::HandleValue v, cocos2d::network::DownloaderHints* ret);
jsval downloadTask_to_jsval(JSContext *cx, const cocos2d::network::DownloadTask& v);
#endif /* js_network_manual_hpp */

Просмотреть файл

@ -307,6 +307,7 @@ bool js_cocos2dx_extension_WebSocket_constructor(JSContext *cx, uint32_t argc, j
JS::RootedObject proto(cx, js_cocos2dx_websocket_prototype);
JS::RootedObject obj(cx, JS_NewObject(cx, js_cocos2dx_websocket_class, proto, JS::NullPtr()));
//JS::RootedObject obj(cx, JS_NewObjectForConstructor(cx, js_cocos2dx_websocket_class, args));
WebSocket* cobj = nullptr;
if (argc >= 2)

Просмотреть файл

@ -47,6 +47,7 @@ LOCAL_SRC_FILES := ../auto/jsb_cocos2dx_3d_auto.cpp \
../auto/jsb_cocos2dx_studio_auto.cpp \
../auto/jsb_cocos2dx_builder_auto.cpp \
../auto/jsb_cocos2dx_ui_auto.cpp \
../auto/jsb_cocos2dx_network_auto.cpp \
../auto/jsb_cocos2dx_physics3d_auto.cpp \
../auto/js_bindings_chipmunk_auto_classes.cpp \
../auto/js_bindings_chipmunk_functions.cpp \
@ -75,6 +76,7 @@ LOCAL_SRC_FILES := ../auto/jsb_cocos2dx_3d_auto.cpp \
../manual/network/jsb_socketio.cpp \
../manual/network/jsb_websocket.cpp \
../manual/network/XMLHTTPRequest.cpp \
../manual/network/js_network_manual.cpp \
../manual/spine/jsb_cocos2dx_spine_manual.cpp \
../manual/ui/jsb_cocos2dx_ui_manual.cpp \
../manual/navmesh/jsb_cocos2dx_navmesh_conversions.cpp \

Просмотреть файл

@ -275,6 +275,18 @@
BA4095C31A6F730A005E53F6 /* jsb_cocos2dx_studio_conversions.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BA4095C01A6F730A005E53F6 /* jsb_cocos2dx_studio_conversions.cpp */; };
BA4095C41A6F730A005E53F6 /* jsb_cocos2dx_studio_conversions.h in Headers */ = {isa = PBXBuildFile; fileRef = BA4095C11A6F730A005E53F6 /* jsb_cocos2dx_studio_conversions.h */; };
BA4095C51A6F730A005E53F6 /* jsb_cocos2dx_studio_conversions.h in Headers */ = {isa = PBXBuildFile; fileRef = BA4095C11A6F730A005E53F6 /* jsb_cocos2dx_studio_conversions.h */; };
BA6249AD1E77DEB60096291C /* js_network_manual.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BA6249AB1E77DEB60096291C /* js_network_manual.cpp */; };
BA6249AE1E77DEB60096291C /* js_network_manual.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BA6249AB1E77DEB60096291C /* js_network_manual.cpp */; };
BA6249AF1E77DEB60096291C /* js_network_manual.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BA6249AB1E77DEB60096291C /* js_network_manual.cpp */; };
BA6249B01E77DEB60096291C /* js_network_manual.h in Headers */ = {isa = PBXBuildFile; fileRef = BA6249AC1E77DEB60096291C /* js_network_manual.h */; };
BA6249B11E77DEB60096291C /* js_network_manual.h in Headers */ = {isa = PBXBuildFile; fileRef = BA6249AC1E77DEB60096291C /* js_network_manual.h */; };
BA6249B21E77DEB60096291C /* js_network_manual.h in Headers */ = {isa = PBXBuildFile; fileRef = BA6249AC1E77DEB60096291C /* js_network_manual.h */; };
BA6249B51E77FBB30096291C /* jsb_cocos2dx_network_auto.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BA6249B31E77FBB30096291C /* jsb_cocos2dx_network_auto.cpp */; };
BA6249B61E77FBB30096291C /* jsb_cocos2dx_network_auto.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BA6249B31E77FBB30096291C /* jsb_cocos2dx_network_auto.cpp */; };
BA6249B71E77FBB30096291C /* jsb_cocos2dx_network_auto.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BA6249B31E77FBB30096291C /* jsb_cocos2dx_network_auto.cpp */; };
BA6249B81E77FBB30096291C /* jsb_cocos2dx_network_auto.hpp in Headers */ = {isa = PBXBuildFile; fileRef = BA6249B41E77FBB30096291C /* jsb_cocos2dx_network_auto.hpp */; };
BA6249B91E77FBB30096291C /* jsb_cocos2dx_network_auto.hpp in Headers */ = {isa = PBXBuildFile; fileRef = BA6249B41E77FBB30096291C /* jsb_cocos2dx_network_auto.hpp */; };
BA6249BA1E77FBB30096291C /* jsb_cocos2dx_network_auto.hpp in Headers */ = {isa = PBXBuildFile; fileRef = BA6249B41E77FBB30096291C /* jsb_cocos2dx_network_auto.hpp */; };
BA9FD5D21BAC0A7600996C85 /* CCComponentJS.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BA9FD5D01BAC0A7600996C85 /* CCComponentJS.cpp */; };
BA9FD5D31BAC0A7600996C85 /* CCComponentJS.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BA9FD5D01BAC0A7600996C85 /* CCComponentJS.cpp */; };
BA9FD5D41BAC0A7600996C85 /* CCComponentJS.h in Headers */ = {isa = PBXBuildFile; fileRef = BA9FD5D11BAC0A7600996C85 /* CCComponentJS.h */; };
@ -398,6 +410,10 @@
B38AD56D1B1D38700057DD7F /* jsb_cocos2dx_experimental_video_auto.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = jsb_cocos2dx_experimental_video_auto.hpp; sourceTree = "<group>"; };
BA4095C01A6F730A005E53F6 /* jsb_cocos2dx_studio_conversions.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = jsb_cocos2dx_studio_conversions.cpp; sourceTree = "<group>"; };
BA4095C11A6F730A005E53F6 /* jsb_cocos2dx_studio_conversions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = jsb_cocos2dx_studio_conversions.h; sourceTree = "<group>"; };
BA6249AB1E77DEB60096291C /* js_network_manual.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = js_network_manual.cpp; sourceTree = "<group>"; };
BA6249AC1E77DEB60096291C /* js_network_manual.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = js_network_manual.h; sourceTree = "<group>"; };
BA6249B31E77FBB30096291C /* jsb_cocos2dx_network_auto.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = jsb_cocos2dx_network_auto.cpp; sourceTree = "<group>"; };
BA6249B41E77FBB30096291C /* jsb_cocos2dx_network_auto.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; path = jsb_cocos2dx_network_auto.hpp; sourceTree = "<group>"; };
BA9FD5D01BAC0A7600996C85 /* CCComponentJS.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = CCComponentJS.cpp; path = component/CCComponentJS.cpp; sourceTree = "<group>"; };
BA9FD5D11BAC0A7600996C85 /* CCComponentJS.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CCComponentJS.h; path = component/CCComponentJS.h; sourceTree = "<group>"; };
BAEE4D6F1AC3FFAD003BEB0F /* jsb_cocos2dx_3d_extension_auto.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = jsb_cocos2dx_3d_extension_auto.cpp; sourceTree = "<group>"; };
@ -489,6 +505,8 @@
1A119E3318BDF19200352BAA /* jsb_cocos2dx_builder_auto.hpp */,
1A119E3518BDF19200352BAA /* jsb_cocos2dx_extension_auto.cpp */,
1A119E3618BDF19200352BAA /* jsb_cocos2dx_extension_auto.hpp */,
BA6249B31E77FBB30096291C /* jsb_cocos2dx_network_auto.cpp */,
BA6249B41E77FBB30096291C /* jsb_cocos2dx_network_auto.hpp */,
1A119E3B18BDF19200352BAA /* jsb_cocos2dx_spine_auto.cpp */,
1A119E3C18BDF19200352BAA /* jsb_cocos2dx_spine_auto.hpp */,
1A119E3E18BDF19200352BAA /* jsb_cocos2dx_studio_auto.cpp */,
@ -611,6 +629,8 @@
1A119E7918BDF19200352BAA /* jsb_websocket.h */,
1A119E7A18BDF19200352BAA /* XMLHTTPRequest.cpp */,
1A119E7B18BDF19200352BAA /* XMLHTTPRequest.h */,
BA6249AB1E77DEB60096291C /* js_network_manual.cpp */,
BA6249AC1E77DEB60096291C /* js_network_manual.h */,
);
path = network;
sourceTree = "<group>";
@ -746,6 +766,7 @@
507B42591C31DCC60067B53E /* jsb_cocos2dx_experimental_webView_auto.hpp in Headers */,
507B425B1C31DCC60067B53E /* jsb_cocos2dx_spine_auto.hpp in Headers */,
507B425C1C31DCC60067B53E /* jsb_opengl_registration.h in Headers */,
BA6249BA1E77FBB30096291C /* jsb_cocos2dx_network_auto.hpp in Headers */,
507B425D1C31DCC60067B53E /* spidermonkey_specifics.h in Headers */,
507B425E1C31DCC60067B53E /* jsb_opengl_manual.h in Headers */,
507B425F1C31DCC60067B53E /* js_bindings_core.h in Headers */,
@ -759,6 +780,7 @@
507B42661C31DCC60067B53E /* jsb_cocos2dx_ui_manual.h in Headers */,
507B42671C31DCC60067B53E /* jsb_opengl_functions.h in Headers */,
507B42681C31DCC60067B53E /* jsb_cocos2dx_audioengine_auto.hpp in Headers */,
BA6249B21E77DEB60096291C /* js_network_manual.h in Headers */,
507B42691C31DCC60067B53E /* jsb_cocos2dx_ui_auto.hpp in Headers */,
507B426A1C31DCC60067B53E /* js_bindings_opengl.h in Headers */,
507B426B1C31DCC60067B53E /* jsb_cocos2dx_studio_manual.h in Headers */,
@ -789,6 +811,7 @@
1A1D3B7A18C44FD000922D3C /* jsb_event_dispatcher_manual.h in Headers */,
1A119EF518BDF19200352BAA /* js_bindings_system_registration.h in Headers */,
BAFA59051B319F38004F9246 /* jsb_cocos2dx_navmesh_manual.h in Headers */,
BA6249B81E77FBB30096291C /* jsb_cocos2dx_network_auto.hpp in Headers */,
1A119EBF18BDF19200352BAA /* cocosbuilder_specifics.hpp in Headers */,
4B22F4AB1B159A7A0044C14E /* jsb_cocos2dx_experimental_webView_manual.h in Headers */,
1A119ED118BDF19200352BAA /* js_bindings_config.h in Headers */,
@ -822,6 +845,7 @@
ADD1C0DD1C196BDF00733781 /* js_module_register.h in Headers */,
1AB5E62D18D05BC80088DAA4 /* jsb_cocos2dx_ui_auto.hpp in Headers */,
420BBCF91AA48EE900493976 /* jsb_cocos2dx_3d_manual.h in Headers */,
BA6249B01E77DEB60096291C /* js_network_manual.h in Headers */,
1A119ED918BDF19200352BAA /* js_bindings_opengl.h in Headers */,
BA4095C41A6F730A005E53F6 /* jsb_cocos2dx_studio_conversions.h in Headers */,
1A119EC718BDF19200352BAA /* jsb_cocos2dx_studio_manual.h in Headers */,
@ -863,6 +887,7 @@
4BE089E51ADF965E00D65D4B /* jsb_cocos2dx_experimental_webView_auto.hpp in Headers */,
1A119E9E18BDF19200352BAA /* jsb_cocos2dx_spine_auto.hpp in Headers */,
1A119EEC18BDF19200352BAA /* jsb_opengl_registration.h in Headers */,
BA6249B91E77FBB30096291C /* jsb_cocos2dx_network_auto.hpp in Headers */,
1A119F0418BDF19200352BAA /* spidermonkey_specifics.h in Headers */,
1A119EE818BDF19200352BAA /* jsb_opengl_manual.h in Headers */,
1A119ED618BDF19200352BAA /* js_bindings_core.h in Headers */,
@ -876,6 +901,7 @@
1AB5E63618D05BF30088DAA4 /* jsb_cocos2dx_ui_manual.h in Headers */,
1A119EE418BDF19200352BAA /* jsb_opengl_functions.h in Headers */,
BAF638DF1B5F5DC900CDB43A /* jsb_cocos2dx_audioengine_auto.hpp in Headers */,
BA6249B11E77DEB60096291C /* js_network_manual.h in Headers */,
1AB5E62E18D05BC80088DAA4 /* jsb_cocos2dx_ui_auto.hpp in Headers */,
1A119EDA18BDF19200352BAA /* js_bindings_opengl.h in Headers */,
1A119EC818BDF19200352BAA /* jsb_cocos2dx_studio_manual.h in Headers */,
@ -984,6 +1010,7 @@
files = (
507B42151C31DCC60067B53E /* js_module_register.cpp in Sources */,
507B42161C31DCC60067B53E /* JavaScriptObjCBridge.mm in Sources */,
BA6249B71E77FBB30096291C /* jsb_cocos2dx_network_auto.cpp in Sources */,
507B42171C31DCC60067B53E /* jsb_cocos2dx_3d_manual.cpp in Sources */,
507B42181C31DCC60067B53E /* jsb_cocos2dx_builder_auto.cpp in Sources */,
507B421A1C31DCC60067B53E /* js_bindings_system_functions.cpp in Sources */,
@ -1001,6 +1028,7 @@
507B42261C31DCC60067B53E /* jsb_cocos2dx_audioengine_auto.cpp in Sources */,
507B42271C31DCC60067B53E /* js_bindings_opengl.cpp in Sources */,
507B42281C31DCC60067B53E /* CCComponentJS.cpp in Sources */,
BA6249AF1E77DEB60096291C /* js_network_manual.cpp in Sources */,
507B42291C31DCC60067B53E /* jsb_cocos2dx_ui_auto.cpp in Sources */,
507B422A1C31DCC60067B53E /* jsb_cocos2dx_spine_auto.cpp in Sources */,
507B422B1C31DCC60067B53E /* jsb_cocos2dx_experimental_webView_auto.cpp in Sources */,
@ -1053,6 +1081,7 @@
ADD1C0DC1C196BDF00733781 /* js_module_register.cpp in Sources */,
1A119ED718BDF19200352BAA /* js_bindings_opengl.cpp in Sources */,
1AB5E62B18D05BC80088DAA4 /* jsb_cocos2dx_ui_auto.cpp in Sources */,
BA6249B51E77FBB30096291C /* jsb_cocos2dx_network_auto.cpp in Sources */,
1A119E9B18BDF19200352BAA /* jsb_cocos2dx_spine_auto.cpp in Sources */,
1A119EF318BDF19200352BAA /* js_bindings_system_registration.cpp in Sources */,
1A119EBB18BDF19200352BAA /* cocos2d_specifics.cpp in Sources */,
@ -1061,6 +1090,7 @@
1A119F0518BDF19200352BAA /* jsb_cocos2dx_spine_manual.cpp in Sources */,
50864CF91C7CA95200B3BAB1 /* js_bindings_chipmunk_auto_classes.cpp in Sources */,
1A119EB718BDF19200352BAA /* js_bindings_chipmunk_registration.cpp in Sources */,
BA6249AD1E77DEB60096291C /* js_network_manual.cpp in Sources */,
420BBCF71AA48EE900493976 /* jsb_cocos2dx_3d_manual.cpp in Sources */,
BA4095C21A6F730A005E53F6 /* jsb_cocos2dx_studio_conversions.cpp in Sources */,
1A119E8318BDF19200352BAA /* jsb_cocos2dx_auto.cpp in Sources */,
@ -1086,6 +1116,7 @@
files = (
ADAC23EE1C2044DC0049A6A2 /* js_module_register.cpp in Sources */,
0541A75B19738AD200E45470 /* JavaScriptObjCBridge.mm in Sources */,
BA6249B61E77FBB30096291C /* jsb_cocos2dx_network_auto.cpp in Sources */,
420BBCF81AA48EE900493976 /* jsb_cocos2dx_3d_manual.cpp in Sources */,
1A119E8A18BDF19200352BAA /* jsb_cocos2dx_builder_auto.cpp in Sources */,
1A119EEE18BDF19200352BAA /* js_bindings_system_functions.cpp in Sources */,
@ -1103,6 +1134,7 @@
BAF638DD1B5F5DC900CDB43A /* jsb_cocos2dx_audioengine_auto.cpp in Sources */,
1A119ED818BDF19200352BAA /* js_bindings_opengl.cpp in Sources */,
BA9FD5D31BAC0A7600996C85 /* CCComponentJS.cpp in Sources */,
BA6249AE1E77DEB60096291C /* js_network_manual.cpp in Sources */,
1AB5E62C18D05BC80088DAA4 /* jsb_cocos2dx_ui_auto.cpp in Sources */,
1A119E9C18BDF19200352BAA /* jsb_cocos2dx_spine_auto.cpp in Sources */,
4BE089E41ADF965E00D65D4B /* jsb_cocos2dx_experimental_webView_auto.cpp in Sources */,

Просмотреть файл

@ -17,6 +17,7 @@
<ClCompile Include="..\auto\jsb_cocos2dx_audioengine_auto.cpp" />
<ClCompile Include="..\auto\jsb_cocos2dx_builder_auto.cpp" />
<ClCompile Include="..\auto\jsb_cocos2dx_extension_auto.cpp" />
<ClCompile Include="..\auto\jsb_cocos2dx_network_auto.cpp" />
<ClCompile Include="..\auto\jsb_cocos2dx_navmesh_auto.cpp" />
<ClCompile Include="..\auto\jsb_cocos2dx_physics3d_auto.cpp" />
<ClCompile Include="..\auto\jsb_cocos2dx_spine_auto.cpp" />
@ -48,6 +49,7 @@
<ClCompile Include="..\manual\network\jsb_socketio.cpp" />
<ClCompile Include="..\manual\network\jsb_websocket.cpp" />
<ClCompile Include="..\manual\network\XMLHTTPRequest.cpp" />
<ClCompile Include="..\manual\network\js_network_manual.cpp" />
<ClCompile Include="..\manual\physics3d\jsb_cocos2dx_physics3d_manual.cpp" />
<ClCompile Include="..\manual\ScriptingCore.cpp" />
<ClCompile Include="..\manual\spine\jsb_cocos2dx_spine_manual.cpp" />
@ -60,6 +62,7 @@
<ClInclude Include="..\auto\jsb_cocos2dx_audioengine_auto.hpp" />
<ClInclude Include="..\auto\jsb_cocos2dx_builder_auto.hpp" />
<ClInclude Include="..\auto\jsb_cocos2dx_extension_auto.hpp" />
<ClInclude Include="..\auto\jsb_cocos2dx_network_auto.hpp" />
<ClInclude Include="..\auto\jsb_cocos2dx_navmesh_auto.hpp" />
<ClInclude Include="..\auto\jsb_cocos2dx_physics3d_auto.hpp" />
<ClInclude Include="..\auto\jsb_cocos2dx_spine_auto.hpp" />
@ -98,6 +101,7 @@
<ClInclude Include="..\manual\network\jsb_socketio.h" />
<ClInclude Include="..\manual\network\jsb_websocket.h" />
<ClInclude Include="..\manual\network\XMLHTTPRequest.h" />
<ClInclude Include="..\manual\network\js_network_manual.h" />
<ClInclude Include="..\manual\physics3d\jsb_cocos2dx_physics3d_manual.h" />
<ClInclude Include="..\manual\ScriptingCore.h" />
<ClInclude Include="..\manual\spidermonkey_specifics.h" />

Просмотреть файл

@ -107,6 +107,12 @@
<ClCompile Include="..\manual\chipmunk\js_bindings_chipmunk_registration.cpp">
<Filter>manual\chipmunk</Filter>
</ClCompile>
<ClCompile Include="..\auto\jsb_cocos2dx_network_auto.cpp">
<Filter>auto</Filter>
</ClCompile>
<ClCompile Include="..\manual\network\js_network_manual.cpp">
<Filter>manual\network</Filter>
</ClCompile>
<ClCompile Include="..\manual\cocosbuilder\js_bindings_ccbreader.cpp">
<Filter>manual\cocosbuilder</Filter>
</ClCompile>
@ -247,6 +253,12 @@
<ClInclude Include="..\manual\chipmunk\js_bindings_chipmunk_registration.h">
<Filter>manual\chipmunk</Filter>
</ClInclude>
<ClInclude Include="..\auto\jsb_cocos2dx_network_auto.hpp">
<Filter>auto</Filter>
</ClInclude>
<ClInclude Include="..\manual\network\js_network_manual.h">
<Filter>manual\network</Filter>
</ClInclude>
<ClInclude Include="..\manual\cocosbuilder\cocosbuilder_specifics.hpp">
<Filter>manual\cocosbuilder</Filter>
</ClInclude>

Просмотреть файл

@ -29,6 +29,14 @@
*/
jsb.AssetsManager = cc.AssetsManager;
delete cc.AssetsManager;
/**
* @type {Object}
* @name jsb.Manifest
* please refer to this document to know how to use it: http://www.cocos2d-x.org/docs/manual/framework/html5/v3/assets-manager/en
* Only available in JSB
*/
jsb.Manifest = cc.Manifest;
delete cc.Manifest;
/**
* @type {Object}
* @name jsb.EventListenerAssetsManager
@ -224,6 +232,12 @@ cc.CONTROL_STEPPER_LABELFONT = "CourierNewPSMT";
cc.AUTOREPEAT_DELTATIME = 0.15;
cc.AUTOREPEAT_INCREASETIME_INCREMENT = 12;
jsb.Manifest.DownloadState = {
UNSTARTED: 0,
DOWNLOADING: 1,
SUCCESSED: 2,
UNMARKED: 3
};
jsb.EventAssetsManager.ERROR_NO_LOCAL_MANIFEST = 0;
jsb.EventAssetsManager.ERROR_DOWNLOAD_MANIFEST = 1;

Просмотреть файл

@ -1822,6 +1822,29 @@ cc.game = /** @lends cc.game# */{
//+++++++++++++++++++++++++something about CCGame end+++++++++++++++++++++++++++++
// Original bind in Spidermonkey v33 will trigger object life cycle track issue in our memory model and cause crash
Function.prototype.bind = function (oThis) {
if (!cc.isFunction(this)) {
// closest thing possible to the ECMAScript 5
// internal IsCallable function
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function () {},
fBound = function () {
return fToBind.apply(this instanceof fNOP && oThis
? this
: oThis,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
jsb.urlRegExp = new RegExp(
"^" +

Просмотреть файл

@ -37,6 +37,7 @@
NS_CC_EXT_BEGIN
#define TEMP_PACKAGE_SUFFIX "_temp"
#define VERSION_FILENAME "version.manifest"
#define TEMP_MANIFEST_FILENAME "project.manifest.temp"
#define MANIFEST_FILENAME "project.manifest"
@ -44,7 +45,9 @@ NS_CC_EXT_BEGIN
#define BUFFER_SIZE 8192
#define MAX_FILENAME 512
#define DEFAULT_CONNECTION_TIMEOUT 8
#define DEFAULT_CONNECTION_TIMEOUT 45
#define SAVE_POINT_INTERVAL 0.1
const std::string AssetsManagerEx::VERSION_ID = "@version";
const std::string AssetsManagerEx::MANIFEST_ID = "@manifest";
@ -55,7 +58,7 @@ AssetsManagerEx::AssetsManagerEx(const std::string& manifestUrl, const std::stri
: _updateState(State::UNCHECKED)
, _assets(nullptr)
, _storagePath("")
, _cacheVersionPath("")
, _tempVersionPath("")
, _cacheManifestPath("")
, _tempManifestPath("")
, _manifestUrl(manifestUrl)
@ -67,6 +70,11 @@ AssetsManagerEx::AssetsManagerEx(const std::string& manifestUrl, const std::stri
, _percentByFile(0)
, _totalToDownload(0)
, _totalWaitToDownload(0)
, _nextSavePoint(0.0)
, _maxConcurrentTask(32)
, _currConcurrentTask(0)
, _versionCompareHandle(nullptr)
, _verifyCallback(nullptr)
, _inited(false)
{
// Init variables
@ -75,8 +83,13 @@ AssetsManagerEx::AssetsManagerEx(const std::string& manifestUrl, const std::stri
_eventName = EventListenerAssetsManagerEx::LISTENER_ID + pointer;
_fileUtils = FileUtils::getInstance();
_downloader = std::shared_ptr<network::Downloader>(new network::Downloader);
// _downloader->setConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT);
network::DownloaderHints hints =
{
static_cast<uint32_t>(_maxConcurrentTask),
DEFAULT_CONNECTION_TIMEOUT,
".tmp"
};
_downloader = std::shared_ptr<network::Downloader>(new network::Downloader(hints));
_downloader->onTaskError = std::bind(&AssetsManagerEx::onError, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4);
_downloader->onTaskProgress = [this](const network::DownloadTask& task,
int64_t /*bytesReceived*/,
@ -90,9 +103,9 @@ AssetsManagerEx::AssetsManagerEx(const std::string& manifestUrl, const std::stri
this->onSuccess(task.requestURL, task.storagePath, task.identifier);
};
setStoragePath(storagePath);
_cacheVersionPath = _storagePath + VERSION_FILENAME;
_tempVersionPath = _tempStoragePath + VERSION_FILENAME;
_cacheManifestPath = _storagePath + MANIFEST_FILENAME;
_tempManifestPath = _storagePath + TEMP_MANIFEST_FILENAME;
_tempManifestPath = _tempStoragePath + TEMP_MANIFEST_FILENAME;
initManifests(manifestUrl);
}
@ -137,8 +150,17 @@ void AssetsManagerEx::initManifests(const std::string& manifestUrl)
if (_tempManifest)
{
_tempManifest->parse(_tempManifestPath);
if (!_tempManifest->isLoaded() && _fileUtils->isFileExist(_tempManifestPath))
_fileUtils->removeFile(_tempManifestPath);
// Previous update is interrupted
if (_fileUtils->isFileExist(_tempManifestPath))
{
// Manifest parse failed, remove all temp files
if (!_tempManifest->isLoaded())
{
_fileUtils->removeDirectory(_tempStoragePath);
CC_SAFE_RELEASE(_tempManifest);
_tempManifest = nullptr;
}
}
}
else
{
@ -159,9 +181,12 @@ void AssetsManagerEx::initManifests(const std::string& manifestUrl)
if (!_inited)
{
CC_SAFE_DELETE(_localManifest);
CC_SAFE_DELETE(_tempManifest);
CC_SAFE_DELETE(_remoteManifest);
CC_SAFE_RELEASE(_localManifest);
CC_SAFE_RELEASE(_tempManifest);
CC_SAFE_RELEASE(_remoteManifest);
_localManifest = nullptr;
_tempManifest = nullptr;
_remoteManifest = nullptr;
}
}
@ -192,13 +217,34 @@ void AssetsManagerEx::loadLocalManifest(const std::string& /*manifestUrl*/)
}
}
// Ensure no search path of cached manifest is used to load this manifest
std::vector<std::string> searchPaths = _fileUtils->getSearchPaths();
if (cachedManifest)
{
std::vector<std::string> cacheSearchPaths = cachedManifest->getSearchPaths();
std::vector<std::string> trimmedPaths = searchPaths;
for (auto path : cacheSearchPaths)
{
const auto pos = std::find(trimmedPaths.begin(), trimmedPaths.end(), path);
if (pos != trimmedPaths.end())
{
trimmedPaths.erase(pos);
}
}
_fileUtils->setSearchPaths(trimmedPaths);
}
// Load local manifest in app package
_localManifest->parse(_manifestUrl);
if (cachedManifest) {
// Restore search paths
_fileUtils->setSearchPaths(searchPaths);
}
if (_localManifest->isLoaded())
{
// Compare with cached manifest to determine which one to use
if (cachedManifest) {
if (strcmp(_localManifest->getVersion().c_str(), cachedManifest->getVersion().c_str()) > 0)
bool localNewer = _localManifest->versionGreater(cachedManifest, _versionCompareHandle);
if (localNewer)
{
// Recreate storage, to empty the content
_fileUtils->removeDirectory(_storagePath);
@ -265,6 +311,10 @@ void AssetsManagerEx::setStoragePath(const std::string& storagePath)
_storagePath = storagePath;
adjustPath(_storagePath);
_fileUtils->createDirectory(_storagePath);
_tempStoragePath = _storagePath;
_tempStoragePath.insert(_storagePath.size() - 1, TEMP_PACKAGE_SUFFIX);
_fileUtils->createDirectory(_tempStoragePath);
}
void AssetsManagerEx::adjustPath(std::string &path)
@ -413,18 +463,44 @@ bool AssetsManagerEx::decompress(const std::string &zip)
return true;
}
void AssetsManagerEx::decompressDownloadedZip()
void AssetsManagerEx::decompressDownloadedZip(const std::string &customId, const std::string &storagePath)
{
// Decompress all compressed files
for (auto it = _compressedFiles.begin(); it != _compressedFiles.end(); ++it) {
std::string zipfile = *it;
if (!decompress(zipfile))
struct AsyncData
{
std::string customId;
std::string zipFile;
bool succeed;
};
AsyncData* asyncData = new AsyncData;
asyncData->customId = customId;
asyncData->zipFile = storagePath;
asyncData->succeed = false;
std::function<void(void*)> decompressFinished = [this](void* param) {
auto dataInner = reinterpret_cast<AsyncData*>(param);
if (dataInner->succeed)
{
dispatchUpdateEvent(EventAssetsManagerEx::EventCode::ERROR_DECOMPRESS, "", "Unable to decompress file " + zipfile);
fileSuccess(dataInner->customId, dataInner->zipFile);
}
_fileUtils->removeFile(zipfile);
}
_compressedFiles.clear();
else
{
std::string errorMsg = "Unable to decompress file " + dataInner->zipFile;
// Ensure zip file deletion (if decompress failure cause task thread exit anormally)
_fileUtils->removeFile(dataInner->zipFile);
dispatchUpdateEvent(EventAssetsManagerEx::EventCode::ERROR_DECOMPRESS, "", errorMsg);
fileError(dataInner->customId, errorMsg);
}
delete dataInner;
};
AsyncTaskPool::getInstance()->enqueue(AsyncTaskPool::TaskType::TASK_OTHER, decompressFinished, (void*)asyncData, [this, asyncData]() {
// Decompress all compressed files
if (decompress(asyncData->zipFile))
{
asyncData->succeed = true;
}
_fileUtils->removeFile(asyncData->zipFile);
});
}
void AssetsManagerEx::dispatchUpdateEvent(EventAssetsManagerEx::EventCode code, const std::string &assetId/* = ""*/, const std::string &message/* = ""*/, int curle_code/* = CURLE_OK*/, int curlm_code/* = CURLM_OK*/)
@ -475,7 +551,7 @@ void AssetsManagerEx::downloadVersion()
{
_updateState = State::DOWNLOADING_VERSION;
// Download version file asynchronously
_downloader->createDownloadFileTask(versionUrl, _cacheVersionPath, VERSION_ID);
_downloader->createDownloadFileTask(versionUrl, _tempVersionPath, VERSION_ID);
}
// No version file found
else
@ -491,7 +567,7 @@ void AssetsManagerEx::parseVersion()
if (_updateState != State::VERSION_LOADED)
return;
_remoteManifest->parseVersion(_cacheVersionPath);
_remoteManifest->parseVersion(_tempVersionPath);
if (!_remoteManifest->isVersionLoaded())
{
@ -501,25 +577,28 @@ void AssetsManagerEx::parseVersion()
}
else
{
if (_localManifest->versionEquals(_remoteManifest))
if (_localManifest->versionGreater(_remoteManifest, _versionCompareHandle))
{
_updateState = State::UP_TO_DATE;
_fileUtils->removeDirectory(_tempStoragePath);
dispatchUpdateEvent(EventAssetsManagerEx::EventCode::ALREADY_UP_TO_DATE);
}
else
{
// Save the old update entry type since its value may be changed in event listener.
UpdateEntry oldUpdateEntry = _updateEntry;
_updateState = State::NEED_UPDATE;
dispatchUpdateEvent(EventAssetsManagerEx::EventCode::NEW_VERSION_FOUND);
// Wait to update so continue the process
if (oldUpdateEntry == UpdateEntry::DO_UPDATE)
if (_updateEntry == UpdateEntry::DO_UPDATE)
{
// dispatch after checking update entry because event dispatching may modify the update entry
dispatchUpdateEvent(EventAssetsManagerEx::EventCode::NEW_VERSION_FOUND);
_updateState = State::PREDOWNLOAD_MANIFEST;
downloadManifest();
}
else
{
dispatchUpdateEvent(EventAssetsManagerEx::EventCode::NEW_VERSION_FOUND);
}
}
}
}
@ -566,9 +645,10 @@ void AssetsManagerEx::parseManifest()
}
else
{
if (_localManifest->versionEquals(_remoteManifest))
if (_localManifest->versionGreater(_remoteManifest, _versionCompareHandle))
{
_updateState = State::UP_TO_DATE;
_fileUtils->removeDirectory(_tempStoragePath);
dispatchUpdateEvent(EventAssetsManagerEx::EventCode::ALREADY_UP_TO_DATE);
}
else
@ -593,15 +673,16 @@ void AssetsManagerEx::startUpdate()
// Clean up before update
_failedUnits.clear();
_downloadUnits.clear();
_compressedFiles.clear();
_totalWaitToDownload = _totalToDownload = 0;
_nextSavePoint = 0;
_percent = _percentByFile = _sizeCollected = _totalSize = 0;
_downloadedSize.clear();
_totalEnabled = false;
// Temporary manifest exists, resuming previous download
if (_tempManifest->isLoaded() && _tempManifest->versionEquals(_remoteManifest))
if (_tempManifest && _tempManifest->isLoaded() && _tempManifest->versionEquals(_remoteManifest))
{
_tempManifest->saveToFile(_tempManifestPath);
_tempManifest->genResumeAssetsList(&_downloadUnits);
_totalWaitToDownload = _totalToDownload = (int)_downloadUnits.size();
this->batchDownload();
@ -609,15 +690,24 @@ void AssetsManagerEx::startUpdate()
std::string msg = StringUtils::format("Resuming from previous unfinished update, %d files remains to be finished.", _totalToDownload);
dispatchUpdateEvent(EventAssetsManagerEx::EventCode::UPDATE_PROGRESSION, "", msg);
}
// Check difference
else
{
// Temporary manifest not exists or out of date,
// it will be used to register the download states of each asset,
// Temporary manifest exists, but can't be parsed or version doesn't equals remote manifest (out of date)
if (_tempManifest)
{
// Remove all temp files
_fileUtils->removeDirectory(_tempStoragePath);
CC_SAFE_RELEASE(_tempManifest);
// Recreate temp storage path and save remote manifest
_fileUtils->createDirectory(_tempStoragePath);
_remoteManifest->saveToFile(_tempManifestPath);
}
// Temporary manifest will be used to register the download states of each asset,
// in this case, it equals remote manifest.
_tempManifest->release();
_tempManifest = _remoteManifest;
// Check difference between local manifest and remote manifest
std::unordered_map<std::string, Manifest::AssetDiff> diff_map = _localManifest->genDiff(_remoteManifest);
if (diff_map.size() == 0)
{
@ -627,36 +717,22 @@ void AssetsManagerEx::startUpdate()
{
// Generate download units for all assets that need to be updated or added
std::string packageUrl = _remoteManifest->getPackageUrl();
// Save current download manifest information for resuming
_tempManifest->saveToFile(_tempManifestPath);
// Preprocessing local files in previous version and creating download folders
for (auto it = diff_map.begin(); it != diff_map.end(); ++it)
{
Manifest::AssetDiff diff = it->second;
if (diff.type == Manifest::DiffType::DELETED)
{
_fileUtils->removeFile(_storagePath + diff.asset.path);
}
else
if (diff.type != Manifest::DiffType::DELETED)
{
std::string path = diff.asset.path;
// Create path
_fileUtils->createDirectory(basename(_storagePath + path));
DownloadUnit unit;
unit.customId = it->first;
unit.srcUrl = packageUrl + path;
unit.storagePath = _storagePath + path;
unit.storagePath = _tempStoragePath + path;
unit.size = diff.asset.size;
_downloadUnits.emplace(unit.customId, unit);
}
}
// Set other assets' downloadState to SUCCESSED
auto &assets = _remoteManifest->getAssets();
for (auto it = assets.cbegin(); it != assets.cend(); ++it)
{
const std::string &key = it->first;
auto diffIt = diff_map.find(key);
if (diffIt == diff_map.end())
{
_tempManifest->setAssetDownloadState(key, Manifest::DownloadState::SUCCESSED);
_tempManifest->setAssetDownloadState(it->first, Manifest::DownloadState::UNSTARTED);
}
}
_totalWaitToDownload = _totalToDownload = (int)_downloadUnits.size();
@ -672,58 +748,50 @@ void AssetsManagerEx::updateSucceed()
{
// Every thing is correctly downloaded, do the following
// 1. rename temporary manifest to valid manifest
_fileUtils->renameFile(_storagePath, std::string(TEMP_MANIFEST_FILENAME), std::string(MANIFEST_FILENAME));
// 2. swap the localManifest
if (_localManifest != nullptr)
_localManifest->release();
_localManifest = _remoteManifest;
_remoteManifest = nullptr;
// 3. make local manifest take effect
prepareLocalManifest();
_updateState = State::UNZIPPING;
// 4. decompress all compressed files
//decompressDownloadedZip();
struct AsyncData
std::string tempFileName = TEMP_MANIFEST_FILENAME;
std::string fileName = MANIFEST_FILENAME;
_fileUtils->renameFile(_tempStoragePath, tempFileName, fileName);
// 2. merge temporary storage path to storage path so that temporary version turns to cached version
if (_fileUtils->isDirectoryExist(_tempStoragePath))
{
std::vector<std::string> compressedFiles;
std::string errorCompressedFile;
};
AsyncData* asyncData = new AsyncData;
asyncData->compressedFiles = _compressedFiles;
_compressedFiles.clear();
std::function<void(void*)> mainThread = [this](void* param) {
auto asyncDataInner = reinterpret_cast<AsyncData*>(param);
if (asyncDataInner->errorCompressedFile.empty())
// Merging all files in temp storage path to storage path
std::vector<std::string> files;
_fileUtils->listFilesRecursively(_tempStoragePath, &files);
int baseOffset = (int)_tempStoragePath.length();
std::string relativePath, dstPath;
for (std::vector<std::string>::iterator it = files.begin(); it != files.end(); ++it)
{
// 5. Set update state
_updateState = State::UP_TO_DATE;
// 6. Notify finished event
dispatchUpdateEvent(EventAssetsManagerEx::EventCode::UPDATE_FINISHED);
}
else
{
_updateState = State::FAIL_TO_UPDATE;
dispatchUpdateEvent(EventAssetsManagerEx::EventCode::ERROR_DECOMPRESS, "", "Unable to decompress file " + asyncDataInner->errorCompressedFile);
}
delete asyncDataInner;
};
AsyncTaskPool::getInstance()->enqueue(AsyncTaskPool::TaskType::TASK_OTHER, mainThread, (void*)asyncData, [this, asyncData]() {
// Decompress all compressed files
for (auto& zipFile : asyncData->compressedFiles) {
if (!decompress(zipFile))
relativePath.assign((*it).substr(baseOffset));
dstPath.assign(_storagePath + relativePath);
// Create directory
if (relativePath.back() == '/')
{
asyncData->errorCompressedFile = zipFile;
break;
_fileUtils->createDirectory(dstPath);
}
// Copy file
else
{
if (_fileUtils->isFileExist(dstPath))
{
_fileUtils->removeFile(dstPath);
}
_fileUtils->renameFile(*it, dstPath);
}
_fileUtils->removeFile(zipFile);
}
});
// Remove temp storage path
_fileUtils->removeDirectory(_tempStoragePath);
}
// 3. swap the localManifest
CC_SAFE_RELEASE(_localManifest);
_localManifest = _remoteManifest;
_localManifest->setManifestRoot(_storagePath);
_remoteManifest = nullptr;
// 4. make local manifest take effect
prepareLocalManifest();
// 5. Set update state
_updateState = State::UP_TO_DATE;
// 6. Notify finished event
dispatchUpdateEvent(EventAssetsManagerEx::EventCode::UPDATE_FINISHED);
}
void AssetsManagerEx::checkUpdate()
@ -853,18 +921,21 @@ void AssetsManagerEx::updateAssets(const DownloadUnits& assets)
if (_updateState != State::UPDATING && _localManifest->isLoaded() && _remoteManifest->isLoaded())
{
int size = (int)(assets.size());
if (size > 0)
_updateState = State::UPDATING;
_downloadUnits.clear();
_downloadedSize.clear();
_percent = _percentByFile = _sizeCollected = _totalSize = 0;
_totalWaitToDownload = _totalToDownload = (int)assets.size();
_nextSavePoint = 0;
_totalEnabled = false;
if (_totalToDownload > 0)
{
_updateState = State::UPDATING;
_downloadUnits.clear();
_downloadUnits = assets;
_totalWaitToDownload = _totalToDownload = (int)_downloadUnits.size();
this->batchDownload();
}
else if (size == 0 && _totalWaitToDownload == 0)
else if (_totalToDownload == 0)
{
updateSucceed();
onDownloadUnitsFinished();
}
}
}
@ -880,6 +951,53 @@ void AssetsManagerEx::downloadFailedAssets()
updateAssets(_failedUnits);
}
void AssetsManagerEx::fileError(const std::string& identifier, const std::string& errorStr, int errorCode, int errorCodeInternal)
{
auto unitIt = _downloadUnits.find(identifier);
// Found unit and add it to failed units
if (unitIt != _downloadUnits.end())
{
_totalWaitToDownload--;
DownloadUnit unit = unitIt->second;
_failedUnits.emplace(unit.customId, unit);
}
dispatchUpdateEvent(EventAssetsManagerEx::EventCode::ERROR_UPDATING, identifier, errorStr, errorCode, errorCodeInternal);
_tempManifest->setAssetDownloadState(identifier, Manifest::DownloadState::UNSTARTED);
_currConcurrentTask = MAX(0, _currConcurrentTask-1);
queueDowload();
}
void AssetsManagerEx::fileSuccess(const std::string &customId, const std::string &storagePath)
{
// Set download state to SUCCESSED
_tempManifest->setAssetDownloadState(customId, Manifest::DownloadState::SUCCESSED);
auto unitIt = _failedUnits.find(customId);
// Found unit and delete it
if (unitIt != _failedUnits.end())
{
// Remove from failed units list
_failedUnits.erase(unitIt);
}
unitIt = _downloadUnits.find(customId);
if (unitIt != _downloadUnits.end())
{
// Reduce count only when unit found in _downloadUnits
_totalWaitToDownload--;
_percentByFile = 100 * (float)(_totalToDownload - _totalWaitToDownload) / _totalToDownload;
// Notify progression event
dispatchUpdateEvent(EventAssetsManagerEx::EventCode::UPDATE_PROGRESSION, "");
}
// Notify asset updated event
dispatchUpdateEvent(EventAssetsManagerEx::EventCode::ASSET_UPDATED, customId);
_currConcurrentTask = MAX(0, _currConcurrentTask-1);
queueDowload();
}
void AssetsManagerEx::onError(const network::DownloadTask& task,
int errorCode,
@ -896,24 +1014,11 @@ void AssetsManagerEx::onError(const network::DownloadTask& task,
else if (task.identifier == MANIFEST_ID)
{
dispatchUpdateEvent(EventAssetsManagerEx::EventCode::ERROR_DOWNLOAD_MANIFEST, task.identifier, errorStr, errorCode, errorCodeInternal);
_updateState = State::FAIL_TO_UPDATE;
}
else
{
auto unitIt = _downloadUnits.find(task.identifier);
// Found unit and add it to failed units
if (unitIt != _downloadUnits.end())
{
_totalWaitToDownload--;
DownloadUnit unit = unitIt->second;
_failedUnits.emplace(unit.customId, unit);
}
dispatchUpdateEvent(EventAssetsManagerEx::EventCode::ERROR_UPDATING, task.identifier, errorStr, errorCode, errorCodeInternal);
if (_totalWaitToDownload <= 0)
{
this->onDownloadUnitsFinished();
}
fileError(task.identifier, errorStr, errorCode, errorCodeInternal);
}
}
@ -947,12 +1052,16 @@ void AssetsManagerEx::onProgress(double total, double downloaded, const std::str
_tempManifest->setAssetDownloadState(customId, Manifest::DownloadState::DOWNLOADING);
// Register the download size information
_downloadedSize.emplace(customId, downloaded);
_totalSize += total;
_sizeCollected++;
// All collected, enable total size
if (_sizeCollected == _totalToDownload)
// Check download unit size existance, if not exist collect size in total size
if (_downloadUnits[customId].size == 0)
{
_totalEnabled = true;
_totalSize += total;
_sizeCollected++;
// All collected, enable total size
if (_sizeCollected == _totalToDownload)
{
_totalEnabled = true;
}
}
}
@ -983,59 +1092,91 @@ void AssetsManagerEx::onSuccess(const std::string &/*srcUrl*/, const std::string
}
else
{
bool ok = true;
auto &assets = _remoteManifest->getAssets();
auto assetIt = assets.find(customId);
if (assetIt != assets.end())
{
// Set download state to SUCCESSED
_tempManifest->setAssetDownloadState(customId, Manifest::DownloadState::SUCCESSED);
// Add file to need decompress list
if (assetIt->second.compressed) {
_compressedFiles.push_back(storagePath);
Manifest::Asset asset = assetIt->second;
if (_verifyCallback != nullptr)
{
ok = _verifyCallback(storagePath, asset);
}
}
auto unitIt = _downloadUnits.find(customId);
if (unitIt != _downloadUnits.end())
if (ok)
{
// Reduce count only when unit found in _downloadUnits
_totalWaitToDownload--;
_percentByFile = 100 * (float)(_totalToDownload - _totalWaitToDownload) / _totalToDownload;
// Notify progression event
dispatchUpdateEvent(EventAssetsManagerEx::EventCode::UPDATE_PROGRESSION, "");
bool compressed = assetIt != assets.end() ? assetIt->second.compressed : false;
if (compressed)
{
decompressDownloadedZip(customId, storagePath);
}
else
{
fileSuccess(customId, storagePath);
}
}
// Notify asset updated event
dispatchUpdateEvent(EventAssetsManagerEx::EventCode::ASSET_UPDATED, customId);
unitIt = _failedUnits.find(customId);
// Found unit and delete it
if (unitIt != _failedUnits.end())
else
{
// Remove from failed units list
_failedUnits.erase(unitIt);
}
if (_totalWaitToDownload <= 0)
{
this->onDownloadUnitsFinished();
fileError(customId, "Asset file verification failed after downloaded");
}
}
}
void AssetsManagerEx::destroyDownloadedVersion()
{
_fileUtils->removeFile(_cacheVersionPath);
_fileUtils->removeFile(_cacheManifestPath);
_fileUtils->removeDirectory(_storagePath);
_fileUtils->removeDirectory(_tempStoragePath);
}
void AssetsManagerEx::batchDownload()
{
_queue.clear();
for(auto iter : _downloadUnits)
{
DownloadUnit& unit = iter.second;
const DownloadUnit& unit = iter.second;
if (unit.size > 0)
{
_totalSize += unit.size;
_sizeCollected++;
}
_queue.push_back(iter.first);
}
// All collected, enable total size
if (_sizeCollected == _totalToDownload)
{
_totalEnabled = true;
}
queueDowload();
}
void AssetsManagerEx::queueDowload()
{
if (_totalWaitToDownload == 0)
{
this->onDownloadUnitsFinished();
return;
}
while (_currConcurrentTask < _maxConcurrentTask && _queue.size() > 0)
{
std::string key = _queue.back();
_queue.pop_back();
_currConcurrentTask++;
DownloadUnit& unit = _downloadUnits[key];
_fileUtils->createDirectory(basename(unit.storagePath));
_downloader->createDownloadFileTask(unit.srcUrl, unit.storagePath, unit.customId);
_tempManifest->setAssetDownloadState(key, Manifest::DownloadState::DOWNLOADING);
}
if (_percentByFile / 100 > _nextSavePoint)
{
// Save current download manifest information for resuming
_tempManifest->saveToFile(_tempManifestPath);
_nextSavePoint += SAVE_POINT_INTERVAL;
}
}
@ -1047,12 +1188,10 @@ void AssetsManagerEx::onDownloadUnitsFinished()
// Save current download manifest information for resuming
_tempManifest->saveToFile(_tempManifestPath);
decompressDownloadedZip();
_updateState = State::FAIL_TO_UPDATE;
dispatchUpdateEvent(EventAssetsManagerEx::EventCode::UPDATE_FAILED);
}
else
else if (_updateState == State::UPDATING)
{
updateSucceed();
}

Просмотреть файл

@ -100,14 +100,32 @@ public:
*/
const std::string& getStoragePath() const;
/** @brief Function for retrieve the local manifest object
/** @brief Function for retrieving the local manifest object
*/
const Manifest* getLocalManifest() const;
/** @brief Function for retrieve the remote manifest object
/** @brief Function for retrieving the remote manifest object
*/
const Manifest* getRemoteManifest() const;
/** @brief Function for retrieving the max concurrent task count
*/
const int getMaxConcurrentTask() const {return _maxConcurrentTask;};
/** @brief Function for setting the max concurrent task count
*/
void setMaxConcurrentTask(const int max) {_maxConcurrentTask = max;};
/** @brief Set the handle function for comparing manifests versions
* @param handle The compare function
*/
void setVersionCompareHandle(const std::function<int(const std::string& versionA, const std::string& versionB)>& handle) {_versionCompareHandle = handle;};
/** @brief Set the verification function for checking whether downloaded asset is correct, e.g. using md5 verification
* @param callback The verify callback function
*/
void setVerifyCallback(const std::function<bool(const std::string& path, Manifest::Asset asset)>& callback) {_verifyCallback = callback;};
CC_CONSTRUCTOR_ACCESS:
AssetsManagerEx(const std::string& manifestUrl, const std::string& storagePath);
@ -139,7 +157,7 @@ protected:
void startUpdate();
void updateSucceed();
bool decompress(const std::string &filename);
void decompressDownloadedZip();
void decompressDownloadedZip(const std::string &customId, const std::string &storagePath);
/** @brief Update a list of assets under the current AssetsManagerEx context
*/
@ -153,6 +171,14 @@ protected:
*/
void destroyDownloadedVersion();
/** @brief Download items in queue with max concurrency setting
*/
void queueDowload();
void fileError(const std::string& identifier, const std::string& errorStr, int errorCode = 0, int errorCodeInternal = 0);
void fileSuccess(const std::string &customId, const std::string &storagePath);
/** @brief Call back function for error handling,
the error will then be reported to user's listener registed in addUpdateEventListener
@param error The error object contains ErrorCode, message, asset url, asset key
@ -210,11 +236,14 @@ private:
//! The reference to the local assets
const std::unordered_map<std::string, Manifest::Asset> *_assets;
//! The path to store downloaded resources.
//! The path to store successfully downloaded version.
std::string _storagePath;
//! The local path of cached version file
std::string _cacheVersionPath;
//! The path to store downloading version.
std::string _tempStoragePath;
//! The local path of cached temporary version file
std::string _tempVersionPath;
//! The local path of cached manifest file
std::string _cacheManifestPath;
@ -250,8 +279,14 @@ private:
//! All failed units
DownloadUnits _failedUnits;
//! All files to be decompressed
std::vector<std::string> _compressedFiles;
//! Download queue
std::vector<std::string> _queue;
//! Max concurrent task count for downloading
int _maxConcurrentTask;
//! Current concurrent task count
int _currConcurrentTask;
//! Download percent
float _percent;
@ -275,6 +310,14 @@ private:
int _totalToDownload;
//! Total number of assets still waiting to be downloaded
int _totalWaitToDownload;
//! Next target percent for saving the manifest file
float _nextSavePoint;
//! Handle function to compare versions between different manifests
std::function<int(const std::string& versionA, const std::string& versionB)> _versionCompareHandle;
//! Callback function to verify the downloaded assets
std::function<bool(const std::string& path, Manifest::Asset asset)> _verifyCallback;
//! Marker for whether the assets manager is inited
bool _inited;

Просмотреть файл

@ -27,6 +27,7 @@
#include "json/stringbuffer.h"
#include <fstream>
#include <stdio.h>
#define KEY_VERSION "version"
#define KEY_PACKAGE_URL "packageUrl"
@ -42,11 +43,33 @@
#define KEY_MD5 "md5"
#define KEY_GROUP "group"
#define KEY_COMPRESSED "compressed"
#define KEY_SIZE "size"
#define KEY_COMPRESSED_FILE "compressedFile"
#define KEY_DOWNLOAD_STATE "downloadState"
NS_CC_EXT_BEGIN
static int cmpVersion(const std::string& v1, const std::string& v2)
{
int i;
int oct_v1[4] = {0}, oct_v2[4] = {0};
int filled1 = std::sscanf(v1.c_str(), "%d.%d.%d.%d", &oct_v1[0], &oct_v1[1], &oct_v1[2], &oct_v1[3]);
int filled2 = std::sscanf(v2.c_str(), "%d.%d.%d.%d", &oct_v2[0], &oct_v2[1], &oct_v2[2], &oct_v2[3]);
if (filled1 == 0 || filled2 == 0)
{
return strcmp(v1.c_str(), v2.c_str());
}
for (i = 0; i < 4; i++)
{
if (oct_v1[i] > oct_v2[i])
return 1;
else if (oct_v1[i] < oct_v2[i])
return -1;
}
return 0;
}
Manifest::Manifest(const std::string& manifestUrl/* = ""*/)
: _versionLoaded(false)
, _loaded(false)
@ -105,7 +128,7 @@ void Manifest::parse(const std::string& manifestUrl)
{
loadJson(manifestUrl);
if (_json.IsObject())
if (!_json.HasParseError() && _json.IsObject())
{
// Register the local manifest root
size_t found = manifestUrl.find_last_of("/\\");
@ -156,16 +179,36 @@ bool Manifest::versionEquals(const Manifest *b) const
return true;
}
bool Manifest::versionGreater(const Manifest *b, const std::function<int(const std::string& versionA, const std::string& versionB)>& handle) const
{
std::string localVersion = getVersion();
std::string bVersion = b->getVersion();
bool greater;
if (handle)
{
greater = handle(localVersion, bVersion) >= 0;
}
else
{
greater = cmpVersion(localVersion, bVersion) >= 0;
}
return greater;
}
std::unordered_map<std::string, Manifest::AssetDiff> Manifest::genDiff(const Manifest *b) const
{
std::unordered_map<std::string, AssetDiff> diff_map;
const std::unordered_map<std::string, Asset> &bAssets = b->getAssets();
std::string key;
Asset valueA;
Asset valueB;
std::unordered_map<std::string, Asset>::const_iterator valueIt, it;
for (it = _assets.begin(); it != _assets.end(); ++it)
{
const auto &key = it->first;
const auto &valueA = it->second;
key = it->first;
valueA = it->second;
// Deleted
valueIt = bAssets.find(key);
@ -178,7 +221,7 @@ std::unordered_map<std::string, Manifest::AssetDiff> Manifest::genDiff(const Man
}
// Modified
auto &valueB = valueIt->second;
valueB = valueIt->second;
if (valueA.md5 != valueB.md5) {
AssetDiff diff;
diff.asset = valueB;
@ -189,8 +232,8 @@ std::unordered_map<std::string, Manifest::AssetDiff> Manifest::genDiff(const Man
for (it = bAssets.begin(); it != bAssets.end(); ++it)
{
const auto &key = it->first;
const auto &valueB = it->second;
key = it->first;
valueB = it->second;
// Added
valueIt = _assets.find(key);
@ -211,12 +254,13 @@ void Manifest::genResumeAssetsList(DownloadUnits *units) const
{
Asset asset = it->second;
if (asset.downloadState != DownloadState::SUCCESSED)
if (asset.downloadState != DownloadState::SUCCESSED && asset.downloadState != DownloadState::UNMARKED)
{
DownloadUnit unit;
unit.customId = it->first;
unit.srcUrl = _packageUrl + asset.path;
unit.storagePath = _manifestRoot + asset.path;
unit.size = asset.size;
units->emplace(unit.customId, unit);
}
}
@ -321,18 +365,16 @@ void Manifest::setAssetDownloadState(const std::string &key, const Manifest::Dow
rapidjson::Value &assets = _json[KEY_ASSETS];
if (assets.IsObject())
{
for (rapidjson::Value::MemberIterator itr = assets.MemberBegin(); itr != assets.MemberEnd(); ++itr)
if (assets.HasMember(key.c_str()))
{
if (key.compare(itr->name.GetString()) == 0) {
rapidjson::Value &entry = itr->value;
if (entry.HasMember(KEY_DOWNLOAD_STATE) && entry[KEY_DOWNLOAD_STATE].IsInt())
{
entry[KEY_DOWNLOAD_STATE].SetInt((int) state);
}
else
{
entry.AddMember<int>(KEY_DOWNLOAD_STATE, (int)state, _json.GetAllocator());
}
rapidjson::Value &entry = assets[key.c_str()];
if (entry.HasMember(KEY_DOWNLOAD_STATE) && entry[KEY_DOWNLOAD_STATE].IsInt())
{
entry[KEY_DOWNLOAD_STATE].SetInt((int) state);
}
else
{
entry.AddMember<int>(KEY_DOWNLOAD_STATE, (int)state, _json.GetAllocator());
}
}
}
@ -386,11 +428,17 @@ Manifest::Asset Manifest::parseAsset(const std::string &path, const rapidjson::V
}
else asset.compressed = false;
if ( json.HasMember(KEY_SIZE) && json[KEY_SIZE].IsInt() )
{
asset.size = json[KEY_SIZE].GetInt();
}
else asset.size = 0;
if ( json.HasMember(KEY_DOWNLOAD_STATE) && json[KEY_DOWNLOAD_STATE].IsInt() )
{
asset.downloadState = (DownloadState)(json[KEY_DOWNLOAD_STATE].GetInt());
asset.downloadState = (json[KEY_DOWNLOAD_STATE].GetInt());
}
else asset.downloadState = DownloadState::UNSTARTED;
else asset.downloadState = DownloadState::UNMARKED;
return asset;
}

Просмотреть файл

@ -43,6 +43,15 @@ struct DownloadUnit
std::string srcUrl;
std::string storagePath;
std::string customId;
float size;
};
struct ManifestAsset {
std::string md5;
std::string path;
bool compressed;
float size;
int downloadState;
};
typedef std::unordered_map<std::string, DownloadUnit> DownloadUnits;
@ -60,19 +69,15 @@ public:
MODIFIED
};
enum class DownloadState {
enum DownloadState {
UNSTARTED,
DOWNLOADING,
SUCCESSED
SUCCESSED,
UNMARKED
};
//! Asset object
struct Asset {
std::string md5;
std::string path;
bool compressed;
DownloadState downloadState;
};
typedef ManifestAsset Asset;
//! Object indicate the difference between two Assets
struct AssetDiff {
@ -132,9 +137,17 @@ protected:
/** @brief Check whether the version of this manifest equals to another.
* @param b The other manifest
* @return Equal or not
*/
bool versionEquals(const Manifest *b) const;
/** @brief Check whether the version of this manifest is greater than another.
* @param b The other manifest
* @param [handle] Customized comparasion handle function
* @return Greater or not
*/
bool versionGreater(const Manifest *b, const std::function<int(const std::string& versionA, const std::string& versionB)>& handle) const;
/** @brief Generate difference between this Manifest and another.
* @param b The other manifest
*/
@ -184,6 +197,8 @@ protected:
*/
void setAssetDownloadState(const std::string &key, const DownloadState &state);
void setManifestRoot(const std::string &root) {_manifestRoot = root;};
private:
//! Indicate whether the version informations have been fully loaded

2
external/config.json поставляемый
Просмотреть файл

@ -1,5 +1,5 @@
{
"version": "v3-deps-128",
"version": "v3-deps-129",
"zip_file_size": "112893722",
"repo_name": "cocos2d-x-3rd-party-libs-bin",
"repo_parent": "https://github.com/cocos2d/",

Просмотреть файл

@ -6,6 +6,7 @@
#include "scripting/js-bindings/auto/jsb_cocos2dx_auto.hpp"
#include "scripting/js-bindings/auto/jsb_cocos2dx_builder_auto.hpp"
#include "scripting/js-bindings/auto/jsb_cocos2dx_extension_auto.hpp"
#include "scripting/js-bindings/auto/jsb_cocos2dx_network_auto.hpp"
#include "scripting/js-bindings/auto/jsb_cocos2dx_navmesh_auto.hpp"
#include "scripting/js-bindings/auto/jsb_cocos2dx_physics3d_auto.hpp"
#include "scripting/js-bindings/auto/jsb_cocos2dx_spine_auto.hpp"
@ -115,6 +116,8 @@ bool AppDelegate::applicationDidFinishLaunching()
sc->addRegisterCallback(register_jsb_websocket);
// socket io can be commented out to reduce the package
sc->addRegisterCallback(register_jsb_socketio);
// Downloader
sc->addRegisterCallback(register_all_cocos2dx_network);
// 3d can be commented out to reduce the package
sc->addRegisterCallback(register_all_cocos2dx_3d);

Просмотреть файл

@ -7,6 +7,7 @@
#include "scripting/js-bindings/auto/jsb_cocos2dx_auto.hpp"
#include "scripting/js-bindings/auto/jsb_cocos2dx_builder_auto.hpp"
#include "scripting/js-bindings/auto/jsb_cocos2dx_extension_auto.hpp"
#include "scripting/js-bindings/auto/jsb_cocos2dx_network_auto.hpp"
#include "scripting/js-bindings/auto/jsb_cocos2dx_navmesh_auto.hpp"
#include "scripting/js-bindings/auto/jsb_cocos2dx_physics3d_auto.hpp"
#include "scripting/js-bindings/auto/jsb_cocos2dx_spine_auto.hpp"
@ -104,6 +105,7 @@ bool AppDelegate::applicationDidFinishLaunching()
sc->addRegisterCallback(MinXmlHttpRequest::_js_register);
sc->addRegisterCallback(register_jsb_websocket);
sc->addRegisterCallback(register_jsb_socketio);
sc->addRegisterCallback(register_all_cocos2dx_network);
sc->addRegisterCallback(register_all_cocos2dx_builder);
sc->addRegisterCallback(register_CCBuilderReader);

Просмотреть файл

@ -1493,7 +1493,7 @@ var TMXBug987 = TileDemo.extend({
node = childs[i];
if (!node) break;
if ("opengl" in cc.sys.capabilities)
node.texture.setAntiAliasTexParameters();
node.texture.setAliasTexParameters();
}
map.anchorX = 0;

@ -1 +1 @@
Subproject commit 9d4b117bf8ee0e7daf84d9566cab8b7ba2da01ae
Subproject commit 3d7c67d5ff722df97455b67e32638adf2cc0130d

Просмотреть файл

@ -7,7 +7,7 @@ prefix = cocos2dx_3d_extension
# all classes will be embedded in that namespace
target_namespace = jsb
android_headers = -I%(androidndkdir)s/platforms/android-14/arch-arm/usr/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.7/libs/armeabi-v7a/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.7/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
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_flags = -D_SIZE_T_DEFINED_
clang_headers = -I%(clangllvmdir)s/%(clang_include)s

Просмотреть файл

@ -9,7 +9,7 @@ target_namespace = jsb
macro_judgement = #if CC_USE_NAVMESH
android_headers = -I%(androidndkdir)s/platforms/android-14/arch-arm/usr/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.7/libs/armeabi-v7a/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.7/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
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_flags = -D_SIZE_T_DEFINED_
clang_headers = -I%(clangllvmdir)s/%(clang_include)s

Просмотреть файл

@ -0,0 +1,60 @@
[cocos2dx_network]
# the prefix to be added to the generated functions. You might or might not use this in your own
# templates
prefix = cocos2dx_network
# create a target namespace (in javascript, this would create some code like the equiv. to `ns = ns || {}`)
# all classes will be embedded in that namespace
target_namespace = jsb
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_flags = -D_SIZE_T_DEFINED_
clang_headers = -I%(clangllvmdir)s/%(clang_include)s
clang_flags = -nostdinc -x c++ -std=c++11 -U __SSE__
cocos_headers = -I%(cocosdir)s -I%(cocosdir)s/cocos -I%(cocosdir)s/cocos/platform/android -I%(cocosdir)s/external
cocos_flags = -DANDROID
cxxgenerator_headers =
# extra arguments for clang
extra_arguments = %(android_headers)s %(clang_headers)s %(cxxgenerator_headers)s %(cocos_headers)s %(android_flags)s %(clang_flags)s %(cocos_flags)s %(extra_flags)s
# what headers to parse
headers = %(cocosdir)s/cocos/network/CCDownloader.h
cpp_headers = scripting/js-bindings/manual/network/js_network_manual.h
# what classes to produce code for. You can use regular expressions here. When testing the regular
# expression, it will be enclosed in "^$", like this: "^Menu*$".
classes = Downloader
# what should we skip? in the format ClassName::[function function]
# ClassName is a regular expression, but will be used like this: "^ClassName$" functions are also
# regular expressions, they will not be surrounded by "^$". If you want to skip a whole class, just
# add a single "*" as functions. See bellow for several examples. A special class name is "*", which
# will apply to all class names. This is a convenience wildcard to be able to skip similar named
# functions from all classes.
skip = Downloader::[createDownloadDataTask]
rename_functions =
rename_classes =
# for all class names, should we remove something when registering in the target VM?
remove_prefix =
# classes for which there will be no "parent" lookup
classes_have_no_parents = Downloader
# base classes which will be skipped when their sub-classes found them.
base_classes_to_skip = Clonable
# classes that create no constructor
# Set is special and we will use a hand-written constructor
abstract_classes =
# Determining whether to use script object(js object) to control the lifecycle of native(cpp) object or the other way around. Supported values are 'yes' or 'no'.
script_control_cpp = yes

Просмотреть файл

@ -9,7 +9,7 @@ target_namespace = jsb
macro_judgement = #if CC_USE_3D_PHYSICS && CC_ENABLE_BULLET_INTEGRATION
android_headers = -I%(androidndkdir)s/platforms/android-14/arch-arm/usr/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.7/libs/armeabi-v7a/include -I%(androidndkdir)s/sources/cxx-stl/gnu-libstdc++/4.7/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
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_flags = -D_SIZE_T_DEFINED_
clang_headers = -I%(clangllvmdir)s/%(clang_include)s

Просмотреть файл

@ -153,6 +153,7 @@ def main():
cmd_args = {'cocos2dx.ini': ('cocos2d-x', 'jsb_cocos2dx_auto'),
'cocos2dx_audioengine.ini': ('cocos2dx_audioengine', 'jsb_cocos2dx_audioengine_auto'),
'cocos2dx_extension.ini': ('cocos2dx_extension', 'jsb_cocos2dx_extension_auto'),
'cocos2dx_network.ini': ('cocos2dx_network', 'jsb_cocos2dx_network_auto'),
'cocos2dx_builder.ini': ('cocos2dx_builder', 'jsb_cocos2dx_builder_auto'),
'cocos2dx_ui.ini': ('cocos2dx_ui', 'jsb_cocos2dx_ui_auto'),
'cocos2dx_studio.ini': ('cocos2dx_studio', 'jsb_cocos2dx_studio_auto'),