From 34939f30fd03f88559db3c2fa0975936a53085ae Mon Sep 17 00:00:00 2001 From: Wenhai Lin Date: Thu, 7 Apr 2016 21:56:09 +0800 Subject: [PATCH] sync bug fix++ --- native/cocos/2d/CCActionInterval.cpp | 30 ++-- native/cocos/base/CCMap.h | 2 +- native/cocos/base/CCVector.h | 2 +- native/cocos/base/ccTypes.cpp | 8 +- native/cocos/base/ccTypes.h | 4 +- native/cocos/network/CCDownloader-android.cpp | 19 ++- native/cocos/network/CCDownloader-android.h | 3 + native/cocos/network/CCDownloader-apple.mm | 156 +++++++++++++----- native/cocos/network/CCDownloader-curl.cpp | 4 +- native/cocos/platform/CCImage.cpp | 9 - .../platform/android/javaactivity-android.cpp | 2 + .../cocos/platform/apple/CCFileUtils-apple.h | 2 +- .../cocos/platform/apple/CCFileUtils-apple.mm | 20 +-- .../cocos/platform/win32/CCDevice-win32.cpp | 2 +- .../platform/win32/CCFileUtils-win32.cpp | 5 +- .../js-bindings/manual/cocos2d_specifics.cpp | 2 + 16 files changed, 171 insertions(+), 99 deletions(-) diff --git a/native/cocos/2d/CCActionInterval.cpp b/native/cocos/2d/CCActionInterval.cpp index cd96e34e8d..e3ddf96914 100644 --- a/native/cocos/2d/CCActionInterval.cpp +++ b/native/cocos/2d/CCActionInterval.cpp @@ -431,23 +431,25 @@ Repeat* Repeat::create(FiniteTimeAction *action, unsigned int times) bool Repeat::initWithAction(FiniteTimeAction *action, unsigned int times) { - float d = action->getDuration() * times; - - if (action && ActionInterval::initWithDuration(d)) + if (action) { - _times = times; - _innerAction = action; - action->retain(); - - _actionInstant = dynamic_cast(action) ? true : false; - //an instant action needs to be executed one time less in the update method since it uses startWithTarget to execute the action - if (_actionInstant) + float d = action->getDuration() * times; + if (ActionInterval::initWithDuration(d)) { - _times -=1; + _times = times; + _innerAction = action; + action->retain(); + + _actionInstant = dynamic_cast(action) ? true : false; + //an instant action needs to be executed one time less in the update method since it uses startWithTarget to execute the action + if (_actionInstant) + { + _times -=1; + } + _total = 0; + + return true; } - _total = 0; - - return true; } return false; diff --git a/native/cocos/base/CCMap.h b/native/cocos/base/CCMap.h index 098057b378..e091c4d13a 100644 --- a/native/cocos/base/CCMap.h +++ b/native/cocos/base/CCMap.h @@ -346,7 +346,7 @@ public: { if (!_data.empty()) { - ssize_t randIdx = RandomHelper::random_int(0, _data.size() - 1); + ssize_t randIdx = RandomHelper::random_int(0, static_cast(_data.size()) - 1); const_iterator randIter = _data.begin(); std::advance(randIter , randIdx); return randIter->second; diff --git a/native/cocos/base/CCVector.h b/native/cocos/base/CCVector.h index 7fe1f9cf6f..83a5bf6a60 100644 --- a/native/cocos/base/CCVector.h +++ b/native/cocos/base/CCVector.h @@ -279,7 +279,7 @@ public: { if (!_data.empty()) { - ssize_t randIdx = RandomHelper::random_int(0, _data.size() - 1); + ssize_t randIdx = RandomHelper::random_int(0, static_cast(_data.size()) - 1); return *(_data.begin() + randIdx); } return nullptr; diff --git a/native/cocos/base/ccTypes.cpp b/native/cocos/base/ccTypes.cpp index 9aaba07d57..bbe730c926 100644 --- a/native/cocos/base/ccTypes.cpp +++ b/native/cocos/base/ccTypes.cpp @@ -108,11 +108,11 @@ Color4B::Color4B(GLubyte _r, GLubyte _g, GLubyte _b, GLubyte _a) , a(_a) {} -Color4B::Color4B(const Color3B& color) +Color4B::Color4B(const Color3B& color, GLubyte _a) : r(color.r) , g(color.g) , b(color.b) -, a(255) +, a(_a) {} Color4B::Color4B(const Color4F& color) @@ -170,11 +170,11 @@ Color4F::Color4F(float _r, float _g, float _b, float _a) , a(_a) {} -Color4F::Color4F(const Color3B& color) +Color4F::Color4F(const Color3B& color, float _a) : r(color.r / 255.0f) , g(color.g / 255.0f) , b(color.b / 255.0f) -, a(1.0f) +, a(_a) {} Color4F::Color4F(const Color4B& color) diff --git a/native/cocos/base/ccTypes.h b/native/cocos/base/ccTypes.h index 30f88a4577..799645a3e5 100644 --- a/native/cocos/base/ccTypes.h +++ b/native/cocos/base/ccTypes.h @@ -91,7 +91,7 @@ struct CC_DLL Color4B { Color4B(); Color4B(GLubyte _r, GLubyte _g, GLubyte _b, GLubyte _a); - explicit Color4B(const Color3B& color); + explicit Color4B(const Color3B& color, GLubyte _a = 255); explicit Color4B(const Color4F& color); inline void set(GLubyte _r, GLubyte _g, GLubyte _b, GLubyte _a) @@ -134,7 +134,7 @@ struct CC_DLL Color4F { Color4F(); Color4F(float _r, float _g, float _b, float _a); - explicit Color4F(const Color3B& color); + explicit Color4F(const Color3B& color, float _a = 1.0f); explicit Color4F(const Color4B& color); bool operator==(const Color4F& right) const; diff --git a/native/cocos/network/CCDownloader-android.cpp b/native/cocos/network/CCDownloader-android.cpp index 2f33456f98..1c71b6518c 100644 --- a/native/cocos/network/CCDownloader-android.cpp +++ b/native/cocos/network/CCDownloader-android.cpp @@ -43,6 +43,7 @@ namespace cocos2d { namespace network { static int sTaskCounter; static int sDownloaderCounter; + static bool _registered = false; struct DownloadTaskAndroid : public IDownloadTask { @@ -53,7 +54,6 @@ namespace cocos2d { namespace network { } virtual ~DownloadTaskAndroid() { - DLLOG("Destruct DownloadTaskAndroid: %p", this); } @@ -65,14 +65,12 @@ namespace cocos2d { namespace network { : _id(++sDownloaderCounter) , _impl(nullptr) { - // use local static variable make sure native methods registered once - static bool _registered = _registerNativeMethods(JniHelper::getEnv()); DLLOG("Construct DownloaderAndroid: %p", this); JniMethodInfo methodInfo; if (JniHelper::getStaticMethodInfo(methodInfo, JCLS_DOWNLOADER, "createDownloader", - "(II" JARG_STR ")" JARG_DOWNLOADER)) + "(II" JARG_STR "I)" JARG_DOWNLOADER)) { jobject jStr = methodInfo.env->NewStringUTF(hints.tempFileNameSuffix.c_str()); jobject jObj = methodInfo.env->CallStaticObjectMethod( @@ -80,7 +78,8 @@ namespace cocos2d { namespace network { methodInfo.methodID, _id, hints.timeoutInSeconds, - jStr + jStr, + hints.countOfMaxProcessingTasks ); _impl = methodInfo.env->NewGlobalRef(jObj); DLLOG("android downloader: jObj: %p, _impl: %p", jObj, _impl); @@ -163,6 +162,7 @@ namespace cocos2d { namespace network { } DownloadTaskAndroid *coTask = iter->second; string str = (errStr ? errStr : ""); + _taskMap.erase(iter); onTaskFinish(*coTask->task, errStr ? DownloadTask::ERROR_IMPL_INTERNAL : DownloadTask::ERROR_NO_ERROR, errCode, @@ -170,7 +170,14 @@ namespace cocos2d { namespace network { data ); coTask->task.reset(); - _taskMap.erase(iter); + } + + void _preloadJavaDownloaderClass() + { + if(!_registered) + { + _registered = _registerNativeMethods(JniHelper::getEnv()); + } } } } // namespace cocos2d::network diff --git a/native/cocos/network/CCDownloader-android.h b/native/cocos/network/CCDownloader-android.h index 75f5a3a74e..868f602736 100644 --- a/native/cocos/network/CCDownloader-android.h +++ b/native/cocos/network/CCDownloader-android.h @@ -50,5 +50,8 @@ namespace cocos2d { namespace network std::unordered_map _taskMap; }; + // Load java downloader class from main thread, to void addImageAsync function + // perform in sub-thread cause java downloader unusable + void _preloadJavaDownloaderClass(); }} // namespace cocos2d::network diff --git a/native/cocos/network/CCDownloader-apple.mm b/native/cocos/network/CCDownloader-apple.mm index 9c7f37832e..1d83fb87f2 100644 --- a/native/cocos/network/CCDownloader-apple.mm +++ b/native/cocos/network/CCDownloader-apple.mm @@ -25,6 +25,8 @@ #include "network/CCDownloader-apple.h" #include "network/CCDownloader.h" +#include +#include "base/CCString.h" //////////////////////////////////////////////////////////////////////////////// // OC Classes Declaration @@ -51,6 +53,7 @@ { const cocos2d::network::DownloaderApple *_outer; cocos2d::network::DownloaderHints _hints; + std::queue _taskQueue; } @property (nonatomic, strong) NSURLSession *downloadSession; @property (nonatomic, strong) NSMutableDictionary *taskDict; // ocTask: DownloadTaskWrapper @@ -59,7 +62,7 @@ -(const cocos2d::network::DownloaderHints&)getHints; -(NSURLSessionDataTask *)createDataTask:(std::shared_ptr&) task; -(NSURLSessionDownloadTask *)createFileTask:(std::shared_ptr&) task; --(void)doDestory; +-(void)doDestroy; @end @@ -97,7 +100,7 @@ namespace cocos2d { namespace network { DownloaderApple::~DownloaderApple() { DeclareDownloaderImplVar; - [impl doDestory]; + [impl doDestroy]; DLLOG("Destruct DownloaderApple %p", this); } IDownloadTask *DownloaderApple::createCoTask(std::shared_ptr& task) @@ -225,14 +228,20 @@ namespace cocos2d { namespace network { } NSURLSessionDataTask *ocTask = [self.downloadSession dataTaskWithRequest:request]; [self.taskDict setObject:[[DownloadTaskWrapper alloc] init:task] forKey:ocTask]; - [ocTask resume]; + + if (_taskQueue.size() < _hints.countOfMaxProcessingTasks) { + [ocTask resume]; + _taskQueue.push(nil); + } else { + _taskQueue.push(ocTask); + } return ocTask; }; -(NSURLSessionDownloadTask *)createFileTask:(std::shared_ptr&) task { const char *urlStr = task->requestURL.c_str(); - DLLOG("DownloaderAppleImpl createDataTask: %s", urlStr); + DLLOG("DownloaderAppleImpl createFileTask: %s", urlStr); NSURL *url = [NSURL URLWithString:[NSString stringWithUTF8String:urlStr]]; NSURLRequest *request = nil; if (_hints.timeoutInSeconds > 0) @@ -255,47 +264,64 @@ namespace cocos2d { namespace network { ocTask = [self.downloadSession downloadTaskWithRequest:request]; } [self.taskDict setObject:[[DownloadTaskWrapper alloc] init:task] forKey:ocTask]; - [ocTask resume]; + + if (_taskQueue.size() < _hints.countOfMaxProcessingTasks) { + [ocTask resume]; + _taskQueue.push(nil); + } else { + _taskQueue.push(ocTask); + } return ocTask; }; --(void)doDestory +-(void)doDestroy { // cancel all download task NSEnumerator * enumeratorKey = [self.taskDict keyEnumerator]; for (NSURLSessionDownloadTask *task in enumeratorKey) { DownloadTaskWrapper *wrapper = [self.taskDict objectForKey:task]; - NSString *tempFilePath = [NSString stringWithFormat:@"%s%s", [wrapper get]->storagePath.c_str(), _hints.tempFileNameSuffix.c_str()]; - NSString *tempFileDir = [tempFilePath stringByDeletingLastPathComponent]; - NSFileManager *fileManager = [NSFileManager defaultManager]; - BOOL isDir = false; - if ([fileManager fileExistsAtPath:tempFileDir isDirectory:&isDir]) - { - if (NO == isDir) - { - // TODO: the directory is a file, not a directory, how to echo to developer? - continue; - } + + // no resume support for a data task + std::string storagePath = [wrapper get]->storagePath; + if(storagePath.length() == 0) { + [task cancel]; } - else - { - NSURL *tempFileURL = [NSURL fileURLWithPath:tempFileDir]; - if (NO == [fileManager createDirectoryAtURL:tempFileURL withIntermediateDirectories:YES attributes:nil error:nil]) - { - // create directory failed - continue; - } + else { + [task cancelByProducingResumeData:^(NSData *resumeData) { + if (resumeData) + { + NSString *tempFilePath = [NSString stringWithFormat:@"%s%s", storagePath.c_str(), _hints.tempFileNameSuffix.c_str()]; + NSString *tempFileDir = [tempFilePath stringByDeletingLastPathComponent]; + NSFileManager *fileManager = [NSFileManager defaultManager]; + BOOL isDir = false; + if ([fileManager fileExistsAtPath:tempFileDir isDirectory:&isDir]) + { + if (NO == isDir) + { + // TODO: the directory is a file, not a directory, how to echo to developer? + DLLOG("DownloaderAppleImpl temp dir is a file!"); + return; + } + } + else + { + NSURL *tempFileURL = [NSURL fileURLWithPath:tempFileDir]; + if (NO == [fileManager createDirectoryAtURL:tempFileURL withIntermediateDirectories:YES attributes:nil error:nil]) + { + // create directory failed + DLLOG("DownloaderAppleImpl create temp dir failed"); + return; + } + } + + [resumeData writeToFile:tempFilePath atomically:YES]; + } + }]; } - [task cancelByProducingResumeData:^(NSData *resumeData) { - if (resumeData) - { - [resumeData writeToFile:tempFilePath atomically:YES]; - } - }]; } _outer = nullptr; - + [self.downloadSession invalidateAndCancel]; [self release]; } @@ -360,19 +386,64 @@ namespace cocos2d { namespace network { // clean wrapper C++ object DownloadTaskWrapper *wrapper = [self.taskDict objectForKey:task]; - - // if no error, callback has been called in finish task - if (_outer && error) + + if(_outer) { - std::vector buf; // just a placeholder - _outer->onTaskFinish(*[wrapper get], + if(error) + { + std::vector buf; // just a placeholder + _outer->onTaskFinish(*[wrapper get], cocos2d::network::DownloadTask::ERROR_IMPL_INTERNAL, (int)error.code, [error.localizedDescription cStringUsingEncoding:NSUTF8StringEncoding], buf); + } + else if (![wrapper get]->storagePath.length()) + { + // call onTaskFinish for a data task + // (for a file download task, callback is called in didFinishDownloadingToURL) + std::string errorString; + + const int64_t buflen = [wrapper totalBytesReceived]; + char buf[buflen]; + [wrapper transferDataToBuffer:buf lengthOfBuffer:buflen]; + std::vector data(buf, buf + buflen); + + _outer->onTaskFinish(*[wrapper get], + cocos2d::network::DownloadTask::ERROR_NO_ERROR, + 0, + errorString, + data); + } + else + { + NSInteger statusCode = ((NSHTTPURLResponse*)task.response).statusCode; + + // Check for error status code + if (statusCode >= 400) + { + std::vector buf; // just a placeholder + const char *orignalURL = [task.originalRequest.URL.absoluteString cStringUsingEncoding:NSUTF8StringEncoding]; + std::string errorMessage = cocos2d::StringUtils::format("Downloader: Failed to download %s with status code (%d)", orignalURL, (int)statusCode); + + _outer->onTaskFinish(*[wrapper get], + cocos2d::network::DownloadTask::ERROR_IMPL_INTERNAL, + 0, + errorMessage, + buf); + } + } } [self.taskDict removeObjectForKey:task]; [wrapper release]; + + while (!_taskQueue.empty() && _taskQueue.front() == nil) { + _taskQueue.pop(); + } + if (!_taskQueue.empty()) { + [_taskQueue.front() resume]; + _taskQueue.pop(); + } } #pragma mark - NSURLSessionDataDelegate methods @@ -457,7 +528,16 @@ namespace cocos2d { namespace network { { return; } - + + // On iOS 9 a response with status code 4xx(Client Error) or 5xx(Server Error) + // might end up calling this delegate method, saving the error message to the storage path + // and treating this download task as a successful one, so we need to check the status code here + NSInteger statusCode = ((NSHTTPURLResponse*)downloadTask.response).statusCode; + if (statusCode >= 400) + { + return; + } + DownloadTaskWrapper *wrapper = [self.taskDict objectForKey:downloadTask]; const char * storagePath = [wrapper get]->storagePath.c_str(); NSString *destPath = [NSString stringWithUTF8String:storagePath]; diff --git a/native/cocos/network/CCDownloader-curl.cpp b/native/cocos/network/CCDownloader-curl.cpp index 8c327ff9e5..61218485dc 100644 --- a/native/cocos/network/CCDownloader-curl.cpp +++ b/native/cocos/network/CCDownloader-curl.cpp @@ -64,7 +64,7 @@ namespace cocos2d { namespace network { virtual ~DownloadTaskCURL() { - // if task destoried unnormally, we should release WritenFileName stored in set. + // if task destroyed unnormally, we should release WritenFileName stored in set. // Normally, this action should done when task finished. if (_tempFileName.length() && _sStoragePathSet.end() != _sStoragePathSet.find(_tempFileName)) { @@ -94,7 +94,7 @@ namespace cocos2d { namespace network { if (_sStoragePathSet.end() != _sStoragePathSet.find(_tempFileName)) { - // there is another task uses this storate path + // there is another task uses this storage path _errCode = DownloadTask::ERROR_FILE_OP_FAILED; _errCodeInternal = 0; _errDescription = "More than one download file task write to same file:"; diff --git a/native/cocos/platform/CCImage.cpp b/native/cocos/platform/CCImage.cpp index 5e1001a4c8..e8c9ee090e 100644 --- a/native/cocos/platform/CCImage.cpp +++ b/native/cocos/platform/CCImage.cpp @@ -542,17 +542,8 @@ Image::Format Image::detectFormat(const unsigned char * data, ssize_t dataLen) { return Format::ETC; } -// else if (isS3TC(data, dataLen)) -// { -// return Format::S3TC; -// } -// else if (isATITC(data, dataLen)) -// { -// return Format::ATITC; -// } else { - CCLOG("cocos2d: can't detect image format"); return Format::UNKNOWN; } } diff --git a/native/cocos/platform/android/javaactivity-android.cpp b/native/cocos/platform/android/javaactivity-android.cpp index ecd9048550..fe20250a33 100644 --- a/native/cocos/platform/android/javaactivity-android.cpp +++ b/native/cocos/platform/android/javaactivity-android.cpp @@ -36,6 +36,7 @@ THE SOFTWARE. #include "renderer/ccGLStateCache.h" #include "2d/CCDrawingPrimitives.h" #include "platform/android/jni/JniHelper.h" +#include "network/CCDownloader-android.h" #include #include @@ -79,6 +80,7 @@ JNIEXPORT void Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeInit(JNIEnv* env, jo director->getEventDispatcher()->dispatchEvent(&recreatedEvent); director->setGLDefaultValues(); } + cocos2d::network::_preloadJavaDownloaderClass(); } JNIEXPORT jintArray Java_org_cocos2dx_lib_Cocos2dxActivity_getGLContextAttrs(JNIEnv* env, jobject thiz) diff --git a/native/cocos/platform/apple/CCFileUtils-apple.h b/native/cocos/platform/apple/CCFileUtils-apple.h index 9dbfc3020b..9d507fd48c 100644 --- a/native/cocos/platform/apple/CCFileUtils-apple.h +++ b/native/cocos/platform/apple/CCFileUtils-apple.h @@ -47,7 +47,7 @@ public: FileUtilsApple(); virtual ~FileUtilsApple(); - /* override funtions */ + /* override functions */ virtual std::string getWritablePath() const override; virtual std::string getFullPathForDirectoryAndFilename(const std::string& directory, const std::string& filename) const override; diff --git a/native/cocos/platform/apple/CCFileUtils-apple.mm b/native/cocos/platform/apple/CCFileUtils-apple.mm index f457dfa95a..ee4751bac7 100644 --- a/native/cocos/platform/apple/CCFileUtils-apple.mm +++ b/native/cocos/platform/apple/CCFileUtils-apple.mm @@ -450,24 +450,8 @@ std::string FileUtilsApple::getFullPathForDirectoryAndFilename(const std::string ValueMap FileUtilsApple::getValueMapFromFile(const std::string& filename) { - ValueMap ret; - - std::string fullPath = fullPathForFilename(filename); - if (!fullPath.empty()) { - NSString* path = [NSString stringWithUTF8String:fullPath.c_str()]; - NSDictionary* dict = [NSDictionary dictionaryWithContentsOfFile:path]; - - if (dict != nil) - { - for (id key in [dict allKeys]) - { - id value = [dict objectForKey:key]; - addValueToDict(key, value, ret); - } - } - } - - return ret; + auto d(FileUtils::getInstance()->getDataFromFile(filename)); + return getValueMapFromData(reinterpret_cast(d.getBytes()), static_cast(d.getSize())); } ValueMap FileUtilsApple::getValueMapFromData(const char* filedata, int filesize) diff --git a/native/cocos/platform/win32/CCDevice-win32.cpp b/native/cocos/platform/win32/CCDevice-win32.cpp index 52b8f78e3b..13cac96bf5 100644 --- a/native/cocos/platform/win32/CCDevice-win32.cpp +++ b/native/cocos/platform/win32/CCDevice-win32.cpp @@ -464,7 +464,7 @@ Data Device::getTextureDataForText(const char * text, const FontDefinition& text width = (short)size.cx; height = (short)size.cy; - // copy pixed data + // copy pixel data bi.bmiHeader.biHeight = (bi.bmiHeader.biHeight > 0) ? - bi.bmiHeader.biHeight : bi.bmiHeader.biHeight; GetDIBits(dc.getDC(), dc.getBitmap(), 0, height, dataBuf, diff --git a/native/cocos/platform/win32/CCFileUtils-win32.cpp b/native/cocos/platform/win32/CCFileUtils-win32.cpp index ea3f9e6f12..c4c376ded1 100644 --- a/native/cocos/platform/win32/CCFileUtils-win32.cpp +++ b/native/cocos/platform/win32/CCFileUtils-win32.cpp @@ -136,8 +136,9 @@ static void _checkPath() { if (s_resourcePath.empty()) { - WCHAR *pUtf16ExePath = nullptr; - _get_wpgmptr(&pUtf16ExePath); + WCHAR utf16Path[CC_MAX_PATH] = { 0 }; + GetModuleFileNameW(NULL, utf16Path, CC_MAX_PATH - 1); + WCHAR *pUtf16ExePath = &(utf16Path[0]); // We need only directory part without exe WCHAR *pUtf16DirEnd = wcsrchr(pUtf16ExePath, L'\\'); diff --git a/native/cocos/scripting/js-bindings/manual/cocos2d_specifics.cpp b/native/cocos/scripting/js-bindings/manual/cocos2d_specifics.cpp index 73bfee9d84..8ff590c668 100644 --- a/native/cocos/scripting/js-bindings/manual/cocos2d_specifics.cpp +++ b/native/cocos/scripting/js-bindings/manual/cocos2d_specifics.cpp @@ -5574,6 +5574,8 @@ void register_cocos2dx_js_core(JSContext* cx, JS::HandleObject global) tmpObj.set(jsb_cocos2d_RenderTexture_prototype); JS_DefineFunction(cx, tmpObj, "saveToFile", js_cocos2dx_RenderTexture_saveToFile, 4, JSPROP_ENUMERATE | JSPROP_PERMANENT); + JS_DefineFunction(cx, tmpObj, "retain", js_cocos2dx_retain, 0, JSPROP_ENUMERATE | JSPROP_PERMANENT); + JS_DefineFunction(cx, tmpObj, "release", js_cocos2dx_release, 0, JSPROP_ENUMERATE | JSPROP_PERMANENT); JS_GetProperty(cx, ccObj, "Menu", &tmpVal); tmpObj = tmpVal.toObjectOrNull();