From 6a553f105beed74e18add6222c61f23ebe92c835 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B1=9F=E6=88=98?= <40414978+PatriceJiang@users.noreply.github.com> Date: Thu, 9 Sep 2021 13:58:03 +0800 Subject: [PATCH 01/11] 3.3.1 fix mac crash (#3873) --- native/cocos/bindings/jswrapper/Value.cpp | 7 +++++-- native/cocos/bindings/manual/jsb_conversions.h | 4 +++- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/native/cocos/bindings/jswrapper/Value.cpp b/native/cocos/bindings/jswrapper/Value.cpp index cd11b8c5f7..768bfbeef4 100644 --- a/native/cocos/bindings/jswrapper/Value.cpp +++ b/native/cocos/bindings/jswrapper/Value.cpp @@ -415,14 +415,17 @@ float Value::toFloat() const { } double Value::toDouble() const { - assert(_type == Type::Number || _type == Type::Boolean); - // assert(_type != Type::BigInt); + assert(_type == Type::Number || _type == Type::Boolean || _type == Type::BigInt); if (_type == Type::Boolean) { if (_u._boolean) { return 1.0; } return 0.0; } + if (_type == Type::BigInt) { + // CC_LOG_WARNING("convert int64 to double"); + return static_cast(_u._bigint); + } return _u._number; } diff --git a/native/cocos/bindings/manual/jsb_conversions.h b/native/cocos/bindings/manual/jsb_conversions.h index 77d54e82c9..f451573e45 100644 --- a/native/cocos/bindings/manual/jsb_conversions.h +++ b/native/cocos/bindings/manual/jsb_conversions.h @@ -932,7 +932,9 @@ inline bool sevalue_to_native(const se::Value &from, int64_t *to, se::Object * / #if CC_PLATFORM == CC_PLATFORM_MAC_IOS || CC_PLATFORM == CC_PLATFORM_MAC_OSX template <> inline bool sevalue_to_native(const se::Value &from, unsigned long *to, se::Object * /*ctx*/) { - *to = static_cast(from.toDouble()); + // on mac: unsiged long === uintptr_t + CC_STATIC_ASSERT(sizeof(*to) == 8); + *to = static_cast(from.toUint64()); return true; } #endif From cbaa9530ad111ec8289e9a88c41265d76ebf5aea Mon Sep 17 00:00:00 2001 From: GengineJS <476393671@qq.com> Date: Thu, 9 Sep 2021 15:39:10 +0800 Subject: [PATCH 02/11] Fix the crash of camera scene in testcase3d (#3876) Co-authored-by: zhengxiangkui <> --- native/cocos/renderer/pipeline/deferred/LightingStage.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/native/cocos/renderer/pipeline/deferred/LightingStage.cpp b/native/cocos/renderer/pipeline/deferred/LightingStage.cpp index 86b7cd9e6d..6bc9266dfc 100644 --- a/native/cocos/renderer/pipeline/deferred/LightingStage.cpp +++ b/native/cocos/renderer/pipeline/deferred/LightingStage.cpp @@ -276,7 +276,7 @@ void LightingStage::activate(RenderPipeline *pipeline, RenderFlow *flow) { _reflectionComp = new ReflectionComp(); gfx::ColorAttachment cAttch = { - gfx::Format::RGBA8, + gfx::Format::RGBA16F, gfx::SampleCount::X1, gfx::LoadOp::LOAD, gfx::StoreOp::STORE, From cc9f23ce25b3222c9c3dd614597e9cc0c7345aa6 Mon Sep 17 00:00:00 2001 From: troublemaker52025 Date: Fri, 10 Sep 2021 14:26:44 +0800 Subject: [PATCH 03/11] fix no shadow scene error for v3.3.1 (#3879) --- native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp b/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp index 39a326020e..f444a0cc6e 100644 --- a/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp +++ b/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp @@ -69,7 +69,7 @@ void ShadowFlow::render(scene::Camera *camera) { lightCollecting(camera, &_validLights); - if (sceneData->getShadowObjects().empty()) { + if (sceneData->getShadowObjects().empty() && sceneData->getRenderObjects().empty()) { clearShadowMap(camera); return; } From 1bac46bb234c3af5dddf1ffb7696ceb0113b8ed8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B1=9F=E6=88=98?= <40414978+PatriceJiang@users.noreply.github.com> Date: Mon, 13 Sep 2021 10:41:27 +0800 Subject: [PATCH 04/11] Use c++14 by default (#3880) --- .../.github/workflows/compile-platforms.yaml | 1 + native/.github/workflows/linter-android.yml | 4 +- native/CMakeLists.txt | 11 +- native/cmake/predefine.cmake | 2 +- .../cocos/audio/oalsoft/AudioEngine-soft.cpp | 6 +- native/cocos/base/IndexHandle.h | 10 +- native/cocos/base/ZipUtils.cpp | 2 +- .../job-system-dummy/DummyJobGraph.h | 2 +- native/cocos/base/memory/MemDef.h | 77 +- native/cocos/base/threading/ReadWriteLock.h | 30 +- native/cocos/bindings/jswrapper/config.cpp | 14 +- .../cocos/bindings/manual/jsb_conversions.h | 2 +- .../cocos/bindings/manual/jsb_global_init.cpp | 16 +- .../bindings/manual/jsb_scene_manual_ext.cpp | 6 +- .../dragonbones/parser/JSONDataParser.h | 300 ++-- .../editor-support/spine/AnimationState.cpp | 1341 +++++++++-------- native/cocos/platform/Image.cpp | 8 +- .../platform/android/Application-android.cpp | 4 +- native/cocos/platform/ios/Application-ios.mm | 4 +- native/cocos/platform/mac/Application-mac.mm | 4 +- .../cocos/platform/ohos/Application-ohos.cpp | 4 +- .../cocos/platform/win32/FileUtils-win32.cpp | 42 +- .../renderer/gfx-agent/CommandBufferAgent.cpp | 14 +- .../cocos/renderer/gfx-agent/DeviceAgent.cpp | 18 +- native/cocos/renderer/gfx-base/GFXDevice.cpp | 6 +- .../cocos/renderer/gfx-base/GFXRenderPass.cpp | 14 +- .../renderer/gfx-gles2/GLES2Commands.cpp | 11 +- .../renderer/gfx-gles2/GLES2RenderPass.cpp | 3 +- .../renderer/gfx-gles3/GLES3Commands.cpp | 24 +- .../cocos/renderer/gfx-gles3/GLES3Device.cpp | 6 +- .../gfx-gles3/GLES3PipelineLayout.cpp | 10 +- .../renderer/gfx-gles3/GLES3RenderPass.cpp | 5 +- .../gfx-validator/ValidationUtils.cpp | 6 +- .../cocos/renderer/gfx-vulkan/VKCommands.cpp | 5 +- .../renderer/gfx-vulkan/VKRenderPass.cpp | 3 +- native/cocos/renderer/gfx-vulkan/VKSPIRV.cpp | 34 + native/cocos/renderer/gfx-vulkan/VKSPIRV.h | 4 +- .../pipeline/RenderAdditiveLightQueue.cpp | 31 +- .../pipeline/deferred/GbufferStage.cpp | 4 +- .../pipeline/deferred/LightingStage.cpp | 6 +- .../pipeline/deferred/PostprocessStage.cpp | 4 +- .../pipeline/forward/ForwardStage.cpp | 20 +- .../renderer/pipeline/shadow/ShadowFlow.cpp | 8 +- .../renderer/pipeline/shadow/ShadowStage.cpp | 4 +- native/cocos/scene/Sphere.cpp | 7 +- native/templates/common/CMakeLists.txt | 2 +- 46 files changed, 1107 insertions(+), 1032 deletions(-) create mode 100644 native/cocos/renderer/gfx-vulkan/VKSPIRV.cpp diff --git a/native/.github/workflows/compile-platforms.yaml b/native/.github/workflows/compile-platforms.yaml index e5af800016..ec41fb7003 100644 --- a/native/.github/workflows/compile-platforms.yaml +++ b/native/.github/workflows/compile-platforms.yaml @@ -190,6 +190,7 @@ jobs: echo "set(CC_USE_VULKAN OFF)" >> build-ios/proj/cfg.cmake echo "set(CC_USE_GLES2 OFF)" >> build-ios/proj/cfg.cmake echo "set(CC_USE_METAL ON)" >> build-ios/proj/cfg.cmake + echo "set(TARGET_IOS_VERSION 12.0)" >> build-ios/proj/cfg.cmake echo "set(USE_WEBSOCKET_SERVER OFF)" >> build-ios/proj/cfg.cmake echo "set(USE_DRAGONBONES OFF)" >> build-ios/proj/cfg.cmake echo "set(MACOSX_BUNDLE_GUI_IDENTIFIER com.cocos.demo.ios)" >> build-ios/proj/cfg.cmake diff --git a/native/.github/workflows/linter-android.yml b/native/.github/workflows/linter-android.yml index b5b297c724..908a1f11e0 100644 --- a/native/.github/workflows/linter-android.yml +++ b/native/.github/workflows/linter-android.yml @@ -50,7 +50,7 @@ jobs: - added|modified: '**/*.m' - added|modified: '**/*.mm' - added|modified: '**/*.c' - - exclude: 'cocos/editor-support/dragonbones/**' + - exclude: 'cocos/editor-support/**' - exclude: 'cocos/base/etc1.*' - exclude: 'cocos/base/etc2.*' - exclude: 'cocos/bindings/manual/jsb_global.cpp' @@ -61,7 +61,7 @@ jobs: - added|modified|deleted: '**' skipedDebug: - added|modified|deleted: '**' - - exclude: 'cocos/editor-support/dragonbones/**' + - exclude: 'cocos/editor-support/**' - name: Install CMake & Clang Tidy run: | sudo apt install -y cmake llvm clang-tidy-11 diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt index 2567c2e80d..b3fccadd90 100644 --- a/native/CMakeLists.txt +++ b/native/CMakeLists.txt @@ -89,10 +89,12 @@ if(USE_JOB_SYSTEM_TASKFLOW AND USE_JOB_SYSTEM_TBB) set(USE_JOB_SYSTEM_TBB OFF) endif() -# if(USE_JOB_SYSTEM_TASKFLOW) -# set(CMAKE_CXX_STANDARD 17) -# set(TARGET_IOS_VERSION "12.0" CACHE STRING "Target iOS version" FORCE) -# endif() +if(USE_JOB_SYSTEM_TASKFLOW) + set(CMAKE_CXX_STANDARD 17) + if("${TARGET_IOS_VERSION}" VERSION_LESS "12.0") + message(FATAL_ERROR "Target iOS version requires 12.0+ when enable taskflow") + endif() +endif() ################################# list all option values ############################## @@ -1095,6 +1097,7 @@ if(CC_USE_VULKAN) cocos/renderer/gfx-vulkan/VKShader.cpp cocos/renderer/gfx-vulkan/VKShader.h cocos/renderer/gfx-vulkan/VKSPIRV.h + cocos/renderer/gfx-vulkan/VKSPIRV.cpp cocos/renderer/gfx-vulkan/VKStd.cpp cocos/renderer/gfx-vulkan/VKStd.h cocos/renderer/gfx-vulkan/VKTexture.cpp diff --git a/native/cmake/predefine.cmake b/native/cmake/predefine.cmake index 27ca7d3af9..cd394723c2 100644 --- a/native/cmake/predefine.cmake +++ b/native/cmake/predefine.cmake @@ -55,7 +55,7 @@ set_property(GLOBAL PROPERTY USE_FOLDERS ON) # set c++ standard set(CMAKE_C_STANDARD 99) set(CMAKE_C_STANDARD_REQUIRED ON) -set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD 14) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) diff --git a/native/cocos/audio/oalsoft/AudioEngine-soft.cpp b/native/cocos/audio/oalsoft/AudioEngine-soft.cpp index bd70e03364..5cbb5dabf1 100644 --- a/native/cocos/audio/oalsoft/AudioEngine-soft.cpp +++ b/native/cocos/audio/oalsoft/AudioEngine-soft.cpp @@ -73,7 +73,7 @@ static void _winLog(const char *format, va_list args) { strcat(buf, "\n"); int pos = 0; - int len = strlen(buf); + auto len = static_cast(strlen(buf)); char tempBuf[MAX_LOG_LENGTH + 1] = {0}; WCHAR wszBuf[MAX_LOG_LENGTH + 1] = {0}; @@ -92,14 +92,14 @@ static void _winLog(const char *format, va_list args) { delete[] buf; } -#ifndef audioLog + #ifndef audioLog void audioLog(const char *format, ...) { va_list args; va_start(args, format); _winLog(format, args); va_end(args); } -#endif + #endif #else diff --git a/native/cocos/base/IndexHandle.h b/native/cocos/base/IndexHandle.h index 935f201b41..66779f2eb5 100644 --- a/native/cocos/base/IndexHandle.h +++ b/native/cocos/base/IndexHandle.h @@ -31,7 +31,7 @@ namespace cc { -template >> +template ::value>> class IndexHandle { public: struct Hasher { @@ -46,10 +46,10 @@ public: inline bool isValid() const noexcept; inline void clear() noexcept; - inline bool operator<(IndexHandle const &rhs) const noexcept; - inline bool operator==(IndexHandle const &rhs) const noexcept; - inline bool operator!=(IndexHandle const &rhs) const noexcept; - inline operator IndexType() const noexcept; + inline bool operator<(IndexHandle const &rhs) const noexcept; + inline bool operator==(IndexHandle const &rhs) const noexcept; + inline bool operator!=(IndexHandle const &rhs) const noexcept; + inline operator IndexType() const noexcept; static IndexType constexpr UNINITIALIZED{std::numeric_limits::max()}; diff --git a/native/cocos/base/ZipUtils.cpp b/native/cocos/base/ZipUtils.cpp index 7478e23635..b949e78f15 100644 --- a/native/cocos/base/ZipUtils.cpp +++ b/native/cocos/base/ZipUtils.cpp @@ -400,7 +400,7 @@ int ZipUtils::inflateCCZBuffer(const unsigned char *buffer, ssize_t bufferLen, u uLongf destlen = len; const auto *source = reinterpret_cast(buffer + sizeof(*header)); - int ret = uncompress(*out, &destlen, source, bufferLen - sizeof(*header)); + int ret = uncompress(*out, &destlen, source, static_cast(bufferLen - sizeof(*header))); if (ret != Z_OK) { CC_LOG_DEBUG("CCZ: Failed to uncompress data"); diff --git a/native/cocos/base/job-system/job-system-dummy/DummyJobGraph.h b/native/cocos/base/job-system/job-system-dummy/DummyJobGraph.h index 81f7de6727..a62b494a34 100644 --- a/native/cocos/base/job-system/job-system-dummy/DummyJobGraph.h +++ b/native/cocos/base/job-system/job-system-dummy/DummyJobGraph.h @@ -113,7 +113,7 @@ DummyGraphNodeTaskImpl::DummyGraphNodeTaskImpl(Fn &&t) noexcept : _task(t) { template size_t DummyGraph::addNode(Fn &&fn) { DummyGraphNode *n = DummyGraphNode::alloc(); - n->_callback = new DummyGraphNodeTaskImpl(std::forward(fn)); + n->_callback = new DummyGraphNodeTaskImpl(std::forward(fn)); n->_generation = _generation; _nodes.emplace_back(n); return _nodes.size() - 1; diff --git a/native/cocos/base/memory/MemDef.h b/native/cocos/base/memory/MemDef.h index d0b03567be..ac7ded465f 100755 --- a/native/cocos/base/memory/MemDef.h +++ b/native/cocos/base/memory/MemDef.h @@ -27,9 +27,9 @@ #define CC_MEM_DEF_H_ #include "AllocatedObj.h" -#include "StdAlloc.h" -#include "NedPooling.h" #include "JeAlloc.h" +#include "NedPooling.h" +#include "StdAlloc.h" namespace cc { @@ -88,24 +88,24 @@ T *ConstructN(T *basePtr, size_t count) { /// Allocate a block of raw memory. #define _CC_MALLOC(bytes) ::cc::CategorisedAllocPolicy::AllocateBytes(bytes, __FILE__, __LINE__, __FUNCTION__) - /// Reallocate a block of raw memory. +/// Reallocate a block of raw memory. #define _CC_REALLOC(ptr, bytes) ::cc::CategorisedAllocPolicy::ReallocateBytes(ptr, bytes, __FILE__, __LINE__, __FUNCTION__) - /// Allocate a block of memory for a primitive type. +/// Allocate a block of memory for a primitive type. #define _CC_ALLOC_T(T, count) static_cast(::cc::CategorisedAllocPolicy::AllocateBytes(sizeof(T) * (count), __FILE__, __LINE__, __FUNCTION__)) - /// Free the memory allocated with _CC_MALLOC or _CC_ALLOC_T. +/// Free the memory allocated with _CC_MALLOC or _CC_ALLOC_T. #define _CC_FREE(ptr) ::cc::CategorisedAllocPolicy::DeallocateBytes((void *)ptr) /// Allocate space for one primitive type, external type or non-virtual type with constructor parameters #define _CC_NEW_T(T) new (::cc::CategorisedAllocPolicy::AllocateBytes(sizeof(T), __FILE__, __LINE__, __FUNCTION__)) T - /// Allocate a block of memory for 'count' primitive types - do not use for classes that inherit from AllocatedObject +/// Allocate a block of memory for 'count' primitive types - do not use for classes that inherit from AllocatedObject #define _CC_NEW_ARRAY_T(T, count) ::cc::ConstructN(static_cast(::cc::CategorisedAllocPolicy::AllocateBytes(sizeof(T) * (count), __FILE__, __LINE__, __FUNCTION__)), count) - /// Free the memory allocated with _CC_NEW_T. +/// Free the memory allocated with _CC_NEW_T. #define _CC_DELETE_T(ptr, T) \ if (ptr) { \ (ptr)->~T(); \ ::cc::CategorisedAllocPolicy::DeallocateBytes((void *)ptr); \ } - /// Free the memory allocated with _CC_NEW_ARRAY_T. +/// Free the memory allocated with _CC_NEW_ARRAY_T. #define _CC_DELETE_ARRAY_T(ptr, T, count) \ if (ptr) { \ for (size_t b = 0; b < (size_t)count; ++b) { \ @@ -117,28 +117,28 @@ T *ConstructN(T *basePtr, size_t count) { // aligned allocation /// Allocate a block of raw memory aligned to user defined boundaries. #define _CC_MALLOC_ALIGN(bytes, align) ::cc::CategorisedAllocPolicy::AllocateBytesAligned(align, bytes, __FILE__, __LINE__, __FUNCTION__) - /// Allocate a block of memory for a primitive type aligned to user defined boundaries. +/// Allocate a block of memory for a primitive type aligned to user defined boundaries. #define _CC_ALLOC_T_ALIGN(T, count, align) static_cast(::cc::CategorisedAllocPolicy::AllocateBytesAligned(align, sizeof(T) * (count), __FILE__, __LINE__, __FUNCTION__)) - /// Free the memory allocated with either _CC_MALLOC_ALIGN or _CC_ALLOC_T_ALIGN. +/// Free the memory allocated with either _CC_MALLOC_ALIGN or _CC_ALLOC_T_ALIGN. #define _CC_FREE_ALIGN(ptr, align) ::cc::CategorisedAllocPolicy::DeallocateBytesAligned(ptr) - /// Allocate a block of raw memory aligned to SIMD boundaries. +/// Allocate a block of raw memory aligned to SIMD boundaries. #define _CC_MALLOC_SIMD(bytes) _CC_MALLOC_ALIGN(bytes, CC_SIMD_ALIGNMENT) - /// Allocate a block of memory for a primitive type aligned to SIMD boundaries. +/// Allocate a block of memory for a primitive type aligned to SIMD boundaries. #define _CC_ALLOC_T_SIMD(T, count) _CC_ALLOC_T_ALIGN(T, count, CC_SIMD_ALIGNMENT) - /// Free the memory allocated with either _CC_MALLOC_SIMD or _CC_ALLOC_T_SIMD. +/// Free the memory allocated with either _CC_MALLOC_SIMD or _CC_ALLOC_T_SIMD. #define _CC_FREE_SIMD(ptr) _CC_FREE_ALIGN(ptr, CC_SIMD_ALIGNMENT) /// Allocate space for one primitive type, external type or non-virtual type aligned to user defined boundaries #define _CC_NEW_T_ALIGN(T, align) new (::cc::CategorisedAllocPolicy::AllocateBytesAligned(align, sizeof(T), __FILE__, __LINE__, __FUNCTION__)) T - /// Allocate a block of memory for 'count' primitive types aligned to user defined boundaries - do not use for classes that inherit from AllocatedObject +/// Allocate a block of memory for 'count' primitive types aligned to user defined boundaries - do not use for classes that inherit from AllocatedObject #define _CC_NEW_ARRAY_T_ALIGN(T, count, align) ::cc::ConstructN(static_cast(::cc::CategorisedAllocPolicy::AllocateBytesAligned(align, sizeof(T) * (count), __FILE__, __LINE__, __FUNCTION__)), count) - /// Free the memory allocated with _CC_NEW_T_ALIGN. +/// Free the memory allocated with _CC_NEW_T_ALIGN. #define _CC_DELETE_T_ALIGN(ptr, T, align) \ if (ptr) { \ (ptr)->~T(); \ ::cc::CategorisedAllocPolicy::DeallocateBytesAligned(ptr); \ } - /// Free the memory allocated with _CC_NEW_ARRAY_T_ALIGN. +/// Free the memory allocated with _CC_NEW_ARRAY_T_ALIGN. #define _CC_DELETE_ARRAY_T_ALIGN(ptr, T, count, align) \ if (ptr) { \ for (size_t _b = 0; _b < (size_t)count; ++_b) { \ @@ -146,13 +146,13 @@ T *ConstructN(T *basePtr, size_t count) { } \ ::cc::CategorisedAllocPolicy::DeallocateBytesAligned(ptr); \ } - /// Allocate space for one primitive type, external type or non-virtual type aligned to SIMD boundaries +/// Allocate space for one primitive type, external type or non-virtual type aligned to SIMD boundaries #define _CC_NEW_T_SIMD(T) _CC_NEW_T_ALIGN(T, CC_SIMD_ALIGNMENT) - /// Allocate a block of memory for 'count' primitive types aligned to SIMD boundaries - do not use for classes that inherit from AllocatedObject +/// Allocate a block of memory for 'count' primitive types aligned to SIMD boundaries - do not use for classes that inherit from AllocatedObject #define _CC_NEW_ARRAY_T_SIMD(T, count) _CC_NEW_ARRAY_T_ALIGN(T, count, CC_SIMD_ALIGNMENT) - /// Free the memory allocated with _CC_NEW_T_SIMD. +/// Free the memory allocated with _CC_NEW_T_SIMD. #define _CC_DELETE_T_SIMD(ptr, T) _CC_DELETE_T_ALIGN(ptr, T, CC_SIMD_ALIGNMENT) - /// Free the memory allocated with _CC_NEW_ARRAY_T_SIMD. +/// Free the memory allocated with _CC_NEW_ARRAY_T_SIMD. #define _CC_DELETE_ARRAY_T_SIMD(ptr, T, count) _CC_DELETE_ARRAY_T_ALIGN(ptr, T, CC_SIMD_ALIGNMENT) // new / delete for classes deriving from AllocatedObject (alignment determined by per-class policy) @@ -165,24 +165,24 @@ T *ConstructN(T *basePtr, size_t count) { /// Allocate a block of raw memory. #define _CC_MALLOC(bytes) ::cc::CategorisedAllocPolicy::AllocateBytes(bytes) - /// Reallocate a block of raw memory. +/// Reallocate a block of raw memory. #define _CC_REALLOC(ptr, bytes) ::cc::CategorisedAllocPolicy::ReallocateBytes(ptr, bytes) - /// Allocate a block of memory for a primitive type. +/// Allocate a block of memory for a primitive type. #define _CC_ALLOC_T(T, count) static_cast(::cc::CategorisedAllocPolicy::AllocateBytes(sizeof(T) * (count))) - /// Free the memory allocated with _CC_MALLOC or _CC_ALLOC_T. Category is required to be restated to ensure the matching policy is used +/// Free the memory allocated with _CC_MALLOC or _CC_ALLOC_T. Category is required to be restated to ensure the matching policy is used #define _CC_FREE(ptr) ::cc::CategorisedAllocPolicy::DeallocateBytes((void *)ptr) /// Allocate space for one primitive type, external type or non-virtual type with constructor parameters #define _CC_NEW_T(T) new (::cc::CategorisedAllocPolicy::AllocateBytes(sizeof(T))) T - /// Allocate a block of memory for 'count' primitive types - do not use for classes that inherit from AllocatedObject +/// Allocate a block of memory for 'count' primitive types - do not use for classes that inherit from AllocatedObject #define _CC_NEW_ARRAY_T(T, count) ::cc::ConstructN(static_cast(::cc::CategorisedAllocPolicy::AllocateBytes(sizeof(T) * (count))), count) - /// Free the memory allocated with _CC_NEW_T. +/// Free the memory allocated with _CC_NEW_T. #define _CC_DELETE_T(ptr, T) \ if (ptr) { \ (ptr)->~T(); \ ::cc::CategorisedAllocPolicy::DeallocateBytes((void *)ptr); \ } - /// Free the memory allocated with _CC_NEW_ARRAY_T. +/// Free the memory allocated with _CC_NEW_ARRAY_T. #define _CC_DELETE_ARRAY_T(ptr, T, count) \ if (ptr) { \ for (size_t b = 0; b < (size_t)count; ++b) { \ @@ -194,28 +194,29 @@ T *ConstructN(T *basePtr, size_t count) { // aligned allocation /// Allocate a block of raw memory aligned to user defined boundaries. #define _CC_MALLOC_ALIGN(bytes, align) ::cc::CategorisedAllocPolicy::AllocateBytesAligned(align, bytes) - /// Allocate a block of memory for a primitive type aligned to user defined boundaries. +/// Allocate a block of memory for a primitive type aligned to user defined boundaries. #define _CC_ALLOC_T_ALIGN(T, count, align) static_cast(::cc::CategorisedAllocPolicy::AllocateBytesAligned(align, sizeof(T) * (count))) - /// Free the memory allocated with either _CC_MALLOC_ALIGN or _CC_ALLOC_T_ALIGN. +/// Free the memory allocated with either _CC_MALLOC_ALIGN or _CC_ALLOC_T_ALIGN. #define _CC_FREE_ALIGN(ptr, align) ::cc::CategorisedAllocPolicy::DeallocateBytesAligned((void *)ptr) - /// Allocate a block of raw memory aligned to SIMD boundaries. +/// Allocate a block of raw memory aligned to SIMD boundaries. #define _CC_MALLOC_SIMD(bytes) _CC_MALLOC_ALIGN(bytes, CC_SIMD_ALIGNMENT) - /// Allocate a block of memory for a primitive type aligned to SIMD boundaries. +/// Allocate a block of memory for a primitive type aligned to SIMD boundaries. #define _CC_ALLOC_T_SIMD(T, count) _CC_ALLOC_T_ALIGN(T, count, CC_SIMD_ALIGNMENT) - /// Free the memory allocated with either _CC_MALLOC_SIMD or _CC_ALLOC_T_SIMD. +/// Free the memory allocated with either _CC_MALLOC_SIMD or _CC_ALLOC_T_SIMD. #define _CC_FREE_SIMD(ptr) _CC_FREE_ALIGN(ptr, CC_SIMD_ALIGNMENT) /// Allocate space for one primitive type, external type or non-virtual type aligned to user defined boundaries #define _CC_NEW_T_ALIGN(T, align) new (::cc::CategorisedAllocPolicy::AllocateBytesAligned(align, sizeof(T))) T - /// Allocate a block of memory for 'count' primitive types aligned to user defined boundaries - do not use for classes that inherit from AllocatedObject + #define _CC_NEW_T_ALIGN_ARGS(T, align, ...) new (::cc::CategorisedAllocPolicy::AllocateBytesAligned(align, sizeof(T))) T(__VA_ARGS__) +/// Allocate a block of memory for 'count' primitive types aligned to user defined boundaries - do not use for classes that inherit from AllocatedObject #define _CC_NEW_ARRAY_T_ALIGN(T, count, align) ::cc::ConstructN(static_cast(::cc::CategorisedAllocPolicy::AllocateBytesAligned(align, sizeof(T) * (count))), count) - /// Free the memory allocated with _CC_NEW_T_ALIGN. +/// Free the memory allocated with _CC_NEW_T_ALIGN. #define _CC_DELETE_T_ALIGN(ptr, T, align) \ if (ptr) { \ (ptr)->~T(); \ ::cc::CategorisedAllocPolicy::DeallocateBytesAligned((void *)ptr); \ } - /// Free the memory allocated with _CC_NEW_ARRAY_T_ALIGN. +/// Free the memory allocated with _CC_NEW_ARRAY_T_ALIGN. #define _CC_DELETE_ARRAY_T_ALIGN(ptr, T, count, align) \ if (ptr) { \ for (size_t _b = 0; _b < (size_t)count; ++_b) { \ @@ -223,13 +224,13 @@ T *ConstructN(T *basePtr, size_t count) { } \ ::cc::CategorisedAllocPolicy::DeallocateBytesAligned((void *)ptr); \ } - /// Allocate space for one primitive type, external type or non-virtual type aligned to SIMD boundaries +/// Allocate space for one primitive type, external type or non-virtual type aligned to SIMD boundaries #define _CC_NEW_T_SIMD(T) _CC_NEW_T_ALIGN(T, CC_SIMD_ALIGNMENT) - /// Allocate a block of memory for 'count' primitive types aligned to SIMD boundaries - do not use for classes that inherit from AllocatedObject +/// Allocate a block of memory for 'count' primitive types aligned to SIMD boundaries - do not use for classes that inherit from AllocatedObject #define _CC_NEW_ARRAY_T_SIMD(T, count) _CC_NEW_ARRAY_T_ALIGN(T, count, CC_SIMD_ALIGNMENT) - /// Free the memory allocated with _CC_NEW_T_SIMD. +/// Free the memory allocated with _CC_NEW_T_SIMD. #define _CC_DELETE_T_SIMD(ptr, T) _CC_DELETE_T_ALIGN(ptr, T, CC_SIMD_ALIGNMENT) - /// Free the memory allocated with _CC_NEW_ARRAY_T_SIMD. +/// Free the memory allocated with _CC_NEW_ARRAY_T_SIMD. #define _CC_DELETE_ARRAY_T_SIMD(ptr, T, count) _CC_DELETE_ARRAY_T_ALIGN(ptr, T, count, CC_SIMD_ALIGNMENT) // new / delete for classes deriving from AllocatedObject (alignment determined by per-class policy) diff --git a/native/cocos/base/threading/ReadWriteLock.h b/native/cocos/base/threading/ReadWriteLock.h index 0576fe53f3..1fecc814c1 100644 --- a/native/cocos/base/threading/ReadWriteLock.h +++ b/native/cocos/base/threading/ReadWriteLock.h @@ -25,13 +25,19 @@ #pragma once -#include +#include +#include namespace cc { class ReadWriteLock final { public: - ReadWriteLock() = default; + ReadWriteLock() { + uv_rwlock_init(&_lock); + }; + ~ReadWriteLock() { + uv_rwlock_destroy(&_lock); + } template auto lockRead(Function &&func, Args &&...args) noexcept -> decltype(func(std::forward(args)...)); @@ -40,18 +46,32 @@ public: auto lockWrite(Function &&func, Args &&...args) noexcept -> decltype(func(std::forward(args)...)); private: - std::shared_mutex _mutex; + uv_rwlock_t _lock; + + struct Defer final { + Defer(std::function &&f) : fn(f) {} + ~Defer() { + fn(); + } + std::function fn; + }; }; template auto ReadWriteLock::lockRead(Function &&func, Args &&...args) noexcept -> decltype(func(std::forward(args)...)) { - std::shared_lock lock(_mutex); + uv_rwlock_rdlock(&_lock); + auto defer = Defer([&]() { + uv_rwlock_rdunlock(&_lock); + }); return func(std::forward(args)...); } template auto ReadWriteLock::lockWrite(Function &&func, Args &&...args) noexcept -> decltype(func(std::forward(args)...)) { - std::lock_guard lock(_mutex); + uv_rwlock_wrlock(&_lock); + auto defer = Defer([&]() { + uv_rwlock_wrunlock(&_lock); + }); return func(std::forward(args)...); } diff --git a/native/cocos/bindings/jswrapper/config.cpp b/native/cocos/bindings/jswrapper/config.cpp index 07b6c4eaca..96ac3bdc42 100644 --- a/native/cocos/bindings/jswrapper/config.cpp +++ b/native/cocos/bindings/jswrapper/config.cpp @@ -24,8 +24,8 @@ ****************************************************************************/ #include "config.h" -#include #include +#include #if defined(_WIN32) && defined(_WINDOWS) @@ -33,8 +33,8 @@ static void _winLog(FILE *fp, const char *format, va_list args) { static const int MAX_LOG_LENGTH = 16 * 1024; - int bufferSize = MAX_LOG_LENGTH; - char *buf = nullptr; + int bufferSize = MAX_LOG_LENGTH; + char * buf = nullptr; do { buf = new (std::nothrow) char[bufferSize]; @@ -51,10 +51,10 @@ static void _winLog(FILE *fp, const char *format, va_list args) { } while (true); - int pos = 0; - int len = strlen(buf); - char tempBuf[MAX_LOG_LENGTH + 1] = {0}; - WCHAR wszBuf[MAX_LOG_LENGTH + 1] = {0}; + int pos = 0; + auto len = static_cast(strlen(buf)); + char tempBuf[MAX_LOG_LENGTH + 1] = {0}; + WCHAR wszBuf[MAX_LOG_LENGTH + 1] = {0}; do { std::copy(buf + pos, buf + pos + MAX_LOG_LENGTH, tempBuf); diff --git a/native/cocos/bindings/manual/jsb_conversions.h b/native/cocos/bindings/manual/jsb_conversions.h index f451573e45..172547f970 100644 --- a/native/cocos/bindings/manual/jsb_conversions.h +++ b/native/cocos/bindings/manual/jsb_conversions.h @@ -806,7 +806,7 @@ template inline typename std::enable_if_t::value && !std::is_pointer::value, bool> sevalue_to_native(const se::Value & /*from*/, T * /*to*/, se::Object * /*unused*/) { // NOLINT(readability-identifier-naming) SE_LOGE("Can not convert type ???\n - [[ %s ]]\n", typeid(T).name()); - CC_STATIC_ASSERT(std::is_same::value, "sevalue_to_native not implemented for T"); + CC_STATIC_ASSERT((std::is_same::value), "sevalue_to_native not implemented for T"); return false; } diff --git a/native/cocos/bindings/manual/jsb_global_init.cpp b/native/cocos/bindings/manual/jsb_global_init.cpp index 539ffef4aa..3e48cee193 100644 --- a/native/cocos/bindings/manual/jsb_global_init.cpp +++ b/native/cocos/bindings/manual/jsb_global_init.cpp @@ -24,9 +24,10 @@ ****************************************************************************/ // clang-format: off +#include #if CC_PLATFORM == CC_PLATFORM_WINDOWS -// Fix ssize_t defination -#include "cocos/bindings/jswrapper/config.h" + // Fix ssize_t defination + #include "cocos/bindings/jswrapper/config.h" #endif #include "uv.h" // clang-format: on @@ -42,15 +43,16 @@ #include #include #include +#include using namespace cc; //NOLINT se::Object *__jsbObj = nullptr; //NOLINT se::Object *__glObj = nullptr; //NOLINT -static std::string xxteaKey; -void jsb_set_xxtea_key(const std::string &key) { //NOLINT - xxteaKey = key; +static std::basic_string xxteaKey; +void jsb_set_xxtea_key(const std::string &key) { //NOLINT + xxteaKey.assign(key.begin(), key.end()); } static const char *BYTE_CODE_FILE_EXT = ".jsc"; //NOLINT @@ -103,7 +105,7 @@ void jsb_init_file_operation_delegate() { //NOLINT size_t dataLen = 0; uint8_t *data = xxtea_decrypt(fileData.getBytes(), static_cast(fileData.getSize()), - reinterpret_cast(xxteaKey.data()), + const_cast(xxteaKey.data()), static_cast(xxteaKey.size()), reinterpret_cast(&dataLen)); if (data == nullptr) { @@ -144,7 +146,7 @@ void jsb_init_file_operation_delegate() { //NOLINT uint32_t dataLen; uint8_t *data = xxtea_decrypt(static_cast(fileData.getBytes()), static_cast(fileData.getSize()), - reinterpret_cast(xxteaKey.data()), + const_cast(xxteaKey.data()), static_cast(xxteaKey.size()), &dataLen); if (data == nullptr) { diff --git a/native/cocos/bindings/manual/jsb_scene_manual_ext.cpp b/native/cocos/bindings/manual/jsb_scene_manual_ext.cpp index 7f617cc378..48c93966e2 100644 --- a/native/cocos/bindings/manual/jsb_scene_manual_ext.cpp +++ b/native/cocos/bindings/manual/jsb_scene_manual_ext.cpp @@ -47,12 +47,12 @@ void fastSetPasses(void *buffer) { uint32_t passSize; AlignedPtr passes[0]; }; - static_assert(offsetof(Heap, passes) == 12); + //static_assert(offsetof(Heap, passes) == 12); // c++17 Heap *heap = reinterpret_cast(buffer); auto &passes = heap->selfPtr.get()->passes; passes.resize(heap->passSize); - for (auto i = 0; i < heap->passSize; i++) { + for (size_t i = 0; i < heap->passSize; i++) { passes[i] = heap->passes[i].get(); } } @@ -66,7 +66,7 @@ void fastSetShaders(void *buffer) { Heap *heap = reinterpret_cast(buffer); auto &shaders = heap->selfPtr.get()->shaders; shaders.resize(heap->shaderSize); - for (auto i = 0; i < heap->shaderSize; i++) { + for (size_t i = 0; i < heap->shaderSize; i++) { shaders[i] = heap->shaders[i].get(); } } diff --git a/native/cocos/editor-support/dragonbones/parser/JSONDataParser.h b/native/cocos/editor-support/dragonbones/parser/JSONDataParser.h index 0e1f12a46f..f8b04edc59 100644 --- a/native/cocos/editor-support/dragonbones/parser/JSONDataParser.h +++ b/native/cocos/editor-support/dragonbones/parser/JSONDataParser.h @@ -6,34 +6,26 @@ DRAGONBONES_NAMESPACE_BEGIN -class ActionFrame -{ +class ActionFrame { public: - unsigned frameStart; + unsigned frameStart; std::vector actions; - bool operator < (const ActionFrame& b) const - { + bool operator<(const ActionFrame& b) const { return frameStart < b.frameStart; } }; -class JSONDataParser : public DataParser -{ +class JSONDataParser : public DataParser { DRAGONBONES_DISALLOW_COPY_AND_ASSIGN(JSONDataParser) protected: - inline static bool _getBoolean(const rapidjson::Value& rawData, const char* key, bool defaultValue) - { - if (rawData.HasMember(key)) - { + inline static bool _getBoolean(const rapidjson::Value& rawData, const char* key, bool defaultValue) { + if (rawData.HasMember(key)) { const auto& value = rawData[key]; - if (value.IsBool()) - { + if (value.IsBool()) { return value.GetBool(); - } - else if (value.IsString()) - { + } else if (value.IsString()) { const std::string stringValue = value.GetString(); if ( stringValue == "0" || @@ -41,16 +33,12 @@ protected: stringValue == "" || stringValue == "false" || stringValue == "null" || - stringValue == "undefined" - ) - { + stringValue == "undefined") { return false; } return true; - } - else if (value.IsNumber()) - { + } else if (value.IsNumber()) { return value.GetInt() != 0; } } @@ -58,42 +46,33 @@ protected: return defaultValue; } - inline static unsigned _getNumber(const rapidjson::Value& rawData, const char* key, unsigned defaultValue) - { - if (rawData.HasMember(key)) - { + inline static unsigned _getNumber(const rapidjson::Value& rawData, const char* key, unsigned defaultValue) { + if (rawData.HasMember(key)) { return rawData[key].GetUint(); } return defaultValue; } - inline static int _getNumber(const rapidjson::Value& rawData, const char* key, int defaultValue) - { - if (rawData.HasMember(key)) - { + inline static int _getNumber(const rapidjson::Value& rawData, const char* key, int defaultValue) { + if (rawData.HasMember(key)) { return rawData[key].GetInt(); } return defaultValue; } - inline static float _getNumber(const rapidjson::Value& rawData, const char* key, float defaultValue) - { - if (rawData.HasMember(key) && rawData[key].IsNumber()) - { - return rawData[key].GetDouble(); // cocos can not support GetFloat(); + inline static float _getNumber(const rapidjson::Value& rawData, const char* key, float defaultValue) { + if (rawData.HasMember(key) && rawData[key].IsNumber()) { + return rawData[key].GetFloat(); // cocos can not support GetFloat(); } return defaultValue; } - inline static std::string _getString(const rapidjson::Value& rawData, const char* key, const std::string& defaultValue) - { - if (rawData.HasMember(key)) - { - if (rawData[key].IsString()) - { + inline static std::string _getString(const rapidjson::Value& rawData, const char* key, const std::string& defaultValue) { + if (rawData.HasMember(key)) { + if (rawData[key].IsString()) { return rawData[key].GetString(); } @@ -103,167 +82,156 @@ protected: return defaultValue; } - inline static int _getParameter(const rapidjson::Value& rawData, std::size_t index, int defaultValue) - { - if (rawData.Size() > index) - { - return rawData[(int) index].GetInt(); + inline static int _getParameter(const rapidjson::Value& rawData, std::size_t index, int defaultValue) { + if (rawData.Size() > index) { + return rawData[(int)index].GetInt(); } return defaultValue; } - inline static float _getParameter(const rapidjson::Value& rawData, std::size_t index, float defaultValue) - { - if (rawData.Size() > index) - { - return rawData[(int) index].GetDouble(); + inline static float _getParameter(const rapidjson::Value& rawData, std::size_t index, float defaultValue) { + if (rawData.Size() > index) { + return rawData[(int)index].GetFloat(); } return defaultValue; } - inline static std::string _getParameter(const rapidjson::Value& rawData, std::size_t index, const std::string& defaultValue) - { - if (rawData.Size() > index) - { - return rawData[(int) index].GetString(); + inline static std::string _getParameter(const rapidjson::Value& rawData, std::size_t index, const std::string& defaultValue) { + if (rawData.Size() > index) { + return rawData[(int)index].GetString(); } return defaultValue; } protected: - unsigned _rawTextureAtlasIndex; + unsigned _rawTextureAtlasIndex; std::vector _rawBones; - DragonBonesData* _data; - ArmatureData* _armature; - BoneData* _bone; - SlotData* _slot; - SkinData* _skin; - MeshDisplayData* _mesh; - AnimationData* _animation; - TimelineData* _timeline; - rapidjson::Value* _rawTextureAtlases; + DragonBonesData* _data; + ArmatureData* _armature; + BoneData* _bone; + SlotData* _slot; + SkinData* _skin; + MeshDisplayData* _mesh; + AnimationData* _animation; + TimelineData* _timeline; + rapidjson::Value* _rawTextureAtlases; private: - int _defaultColorOffset; - int _prevClockwise; - float _prevRotation; - Matrix _helpMatrixA; - Matrix _helpMatrixB; - Transform _helpTransform; - ColorTransform _helpColorTransform; - Point _helpPoint; - std::vector _helpArray; - std::vector _intArray; - std::vector _floatArray; - std::vector _frameIntArray; - std::vector _frameFloatArray; - std::vector _frameArray; - std::vector _timelineArray; - std::vector _cacheRawMeshes; - std::vector _cacheMeshes; - std::vector _actionFrames; - std::map _weightSlotPose; - std::map _weightBonePoses; - std::map> _cacheBones; + int _defaultColorOffset; + int _prevClockwise; + float _prevRotation; + Matrix _helpMatrixA; + Matrix _helpMatrixB; + Transform _helpTransform; + ColorTransform _helpColorTransform; + Point _helpPoint; + std::vector _helpArray; + std::vector _intArray; + std::vector _floatArray; + std::vector _frameIntArray; + std::vector _frameFloatArray; + std::vector _frameArray; + std::vector _timelineArray; + std::vector _cacheRawMeshes; + std::vector _cacheMeshes; + std::vector _actionFrames; + std::map _weightSlotPose; + std::map _weightBonePoses; + std::map> _cacheBones; std::map> _slotChildActions; public: - JSONDataParser() : - _rawTextureAtlasIndex(0), - _rawBones(), - _data(nullptr), - _armature(nullptr), - _bone(nullptr), - _slot(nullptr), - _skin(nullptr), - _mesh(nullptr), - _animation(nullptr), - _timeline(nullptr), - _rawTextureAtlases(nullptr), + JSONDataParser() : _rawTextureAtlasIndex(0), + _rawBones(), + _data(nullptr), + _armature(nullptr), + _bone(nullptr), + _slot(nullptr), + _skin(nullptr), + _mesh(nullptr), + _animation(nullptr), + _timeline(nullptr), + _rawTextureAtlases(nullptr), - _defaultColorOffset(-1), - _prevClockwise(0), - _prevRotation(0.0f), - _helpMatrixA(), - _helpMatrixB(), - _helpTransform(), - _helpColorTransform(), - _helpPoint(), - _helpArray(), - _intArray(), - _floatArray(), - _frameIntArray(), - _frameFloatArray(), - _frameArray(), - _timelineArray(), - _cacheMeshes(), - _cacheRawMeshes(), - _actionFrames(), - _weightSlotPose(), - _weightBonePoses(), - _cacheBones(), - _slotChildActions() - { + _defaultColorOffset(-1), + _prevClockwise(0), + _prevRotation(0.0f), + _helpMatrixA(), + _helpMatrixB(), + _helpTransform(), + _helpColorTransform(), + _helpPoint(), + _helpArray(), + _intArray(), + _floatArray(), + _frameIntArray(), + _frameFloatArray(), + _frameArray(), + _timelineArray(), + _cacheMeshes(), + _cacheRawMeshes(), + _actionFrames(), + _weightSlotPose(), + _weightBonePoses(), + _cacheBones(), + _slotChildActions() { } - virtual ~JSONDataParser() - { + virtual ~JSONDataParser() { } private: void _getCurvePoint( - float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, - float t, - Point& result - ); - void _samplingEasingCurve(const rapidjson::Value& curve, std::vector& samples); - void _parseActionDataInFrame(const rapidjson::Value& rawData, unsigned frameStart, BoneData* bone, SlotData* slot); - void _mergeActionFrame(const rapidjson::Value& rawData, unsigned frameStart, ActionType type, BoneData* bone, SlotData* slot); + float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, + float t, + Point& result); + void _samplingEasingCurve(const rapidjson::Value& curve, std::vector& samples); + void _parseActionDataInFrame(const rapidjson::Value& rawData, unsigned frameStart, BoneData* bone, SlotData* slot); + void _mergeActionFrame(const rapidjson::Value& rawData, unsigned frameStart, ActionType type, BoneData* bone, SlotData* slot); unsigned _parseCacheActionFrame(ActionFrame& frame); protected: - virtual ArmatureData* _parseArmature(const rapidjson::Value& rawData, float scale); - virtual BoneData* _parseBone(const rapidjson::Value& rawData); - virtual ConstraintData* _parseIKConstraint(const rapidjson::Value& rawData); - virtual SlotData* _parseSlot(const rapidjson::Value& rawData, int zOrder); - virtual SkinData* _parseSkin(const rapidjson::Value& rawData); - virtual DisplayData* _parseDisplay(const rapidjson::Value& rawData); - virtual void _parsePivot(const rapidjson::Value& rawData, ImageDisplayData& display); - virtual void _parseMesh(const rapidjson::Value& rawData, MeshDisplayData& mesh); - virtual BoundingBoxData* _parseBoundingBox(const rapidjson::Value& rawData); + virtual ArmatureData* _parseArmature(const rapidjson::Value& rawData, float scale); + virtual BoneData* _parseBone(const rapidjson::Value& rawData); + virtual ConstraintData* _parseIKConstraint(const rapidjson::Value& rawData); + virtual SlotData* _parseSlot(const rapidjson::Value& rawData, int zOrder); + virtual SkinData* _parseSkin(const rapidjson::Value& rawData); + virtual DisplayData* _parseDisplay(const rapidjson::Value& rawData); + virtual void _parsePivot(const rapidjson::Value& rawData, ImageDisplayData& display); + virtual void _parseMesh(const rapidjson::Value& rawData, MeshDisplayData& mesh); + virtual BoundingBoxData* _parseBoundingBox(const rapidjson::Value& rawData); virtual PolygonBoundingBoxData* _parsePolygonBoundingBox(const rapidjson::Value& rawData); - virtual AnimationData* _parseAnimation(const rapidjson::Value& rawData); - virtual TimelineData* _parseTimeline( - const rapidjson::Value& rawData, const char* framesKey, TimelineType type, - bool addIntOffset, bool addFloatOffset, unsigned frameValueCount, - const std::function& frameParser - ); - virtual void _parseBoneTimeline(const rapidjson::Value& rawData); - virtual void _parseSlotTimeline(const rapidjson::Value& rawData); - virtual unsigned _parseFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount); - virtual unsigned _parseTweenFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount); - virtual unsigned _parseActionFrame(const ActionFrame& rawData, unsigned frameStart, unsigned frameCount); - virtual unsigned _parseZOrderFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount); - virtual unsigned _parseBoneAllFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount); - virtual unsigned _parseBoneTranslateFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount); - virtual unsigned _parseBoneRotateFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount); - virtual unsigned _parseBoneScaleFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount); - virtual unsigned _parseSlotDisplayFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount); - virtual unsigned _parseSlotColorFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount); - virtual unsigned _parseSlotFFDFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount); - virtual unsigned _parseIKConstraintFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount); + virtual AnimationData* _parseAnimation(const rapidjson::Value& rawData); + virtual TimelineData* _parseTimeline( + const rapidjson::Value& rawData, const char* framesKey, TimelineType type, + bool addIntOffset, bool addFloatOffset, unsigned frameValueCount, + const std::function& frameParser); + virtual void _parseBoneTimeline(const rapidjson::Value& rawData); + virtual void _parseSlotTimeline(const rapidjson::Value& rawData); + virtual unsigned _parseFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount); + virtual unsigned _parseTweenFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount); + virtual unsigned _parseActionFrame(const ActionFrame& rawData, unsigned frameStart, unsigned frameCount); + virtual unsigned _parseZOrderFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount); + virtual unsigned _parseBoneAllFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount); + virtual unsigned _parseBoneTranslateFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount); + virtual unsigned _parseBoneRotateFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount); + virtual unsigned _parseBoneScaleFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount); + virtual unsigned _parseSlotDisplayFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount); + virtual unsigned _parseSlotColorFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount); + virtual unsigned _parseSlotFFDFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount); + virtual unsigned _parseIKConstraintFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount); virtual const std::vector& _parseActionData(const rapidjson::Value& rawData, ActionType type, BoneData* bone, SlotData* slot); - virtual void _parseTransform(const rapidjson::Value& rawData, Transform& transform, float scale); - virtual void _parseColorTransform(const rapidjson::Value& rawData, ColorTransform& color); - virtual void _parseArray(const rapidjson::Value& rawData); - virtual DragonBonesData* _parseDragonBonesData(const rapidjson::Value& rawData, float scale = 1.0f); - virtual void _parseTextureAtlasData(const rapidjson::Value& rawData, TextureAtlasData& textureAtlasData, float scale = 1.0f); + virtual void _parseTransform(const rapidjson::Value& rawData, Transform& transform, float scale); + virtual void _parseColorTransform(const rapidjson::Value& rawData, ColorTransform& color); + virtual void _parseArray(const rapidjson::Value& rawData); + virtual DragonBonesData* _parseDragonBonesData(const rapidjson::Value& rawData, float scale = 1.0f); + virtual void _parseTextureAtlasData(const rapidjson::Value& rawData, TextureAtlasData& textureAtlasData, float scale = 1.0f); public: virtual DragonBonesData* parseDragonBonesData(const char* rawData, float scale = 1.0f) override; - virtual bool parseTextureAtlasData(const char* rawData, TextureAtlasData& textureAtlasData, float scale = 1.0f) override; + virtual bool parseTextureAtlasData(const char* rawData, TextureAtlasData& textureAtlasData, float scale = 1.0f) override; }; DRAGONBONES_NAMESPACE_END diff --git a/native/cocos/editor-support/spine/AnimationState.cpp b/native/cocos/editor-support/spine/AnimationState.cpp index 26bb864716..399a2521a7 100644 --- a/native/cocos/editor-support/spine/AnimationState.cpp +++ b/native/cocos/editor-support/spine/AnimationState.cpp @@ -28,42 +28,37 @@ *****************************************************************************/ #ifdef SPINE_UE4 -#include "SpinePluginPrivatePCH.h" + #include "SpinePluginPrivatePCH.h" #endif -#include #include -#include +#include #include -#include -#include -#include +#include #include #include -#include #include +#include #include +#include +#include +#include #include using namespace spine; void dummyOnAnimationEventFunc(AnimationState *state, spine::EventType type, TrackEntry *entry, Event *event = NULL) { - SP_UNUSED(state); - SP_UNUSED(type); - SP_UNUSED(entry); - SP_UNUSED(event); + SP_UNUSED(state); + SP_UNUSED(type); + SP_UNUSED(entry); + SP_UNUSED(event); } -TrackEntry::TrackEntry() : _animation(NULL), _next(NULL), _mixingFrom(NULL), _mixingTo(0), _trackIndex(0), _loop(false), _holdPrevious(false), - _eventThreshold(0), _attachmentThreshold(0), _drawOrderThreshold(0), _animationStart(0), - _animationEnd(0), _animationLast(0), _nextAnimationLast(0), _delay(0), _trackTime(0), - _trackLast(0), _nextTrackLast(0), _trackEnd(0), _timeScale(1.0f), _alpha(0), _mixTime(0), - _mixDuration(0), _interruptAlpha(0), _totalAlpha(0), _mixBlend(MixBlend_Replace), - _listener(dummyOnAnimationEventFunc), _listenerObject(NULL) { +TrackEntry::TrackEntry() : _animation(NULL), _next(NULL), _mixingFrom(NULL), _mixingTo(0), _trackIndex(0), _loop(false), _holdPrevious(false), _eventThreshold(0), _attachmentThreshold(0), _drawOrderThreshold(0), _animationStart(0), _animationEnd(0), _animationLast(0), _nextAnimationLast(0), _delay(0), _trackTime(0), _trackLast(0), _nextTrackLast(0), _trackEnd(0), _timeScale(1.0f), _alpha(0), _mixTime(0), _mixDuration(0), _interruptAlpha(0), _totalAlpha(0), _mixBlend(MixBlend_Replace), _listener(dummyOnAnimationEventFunc), _listenerObject(NULL) { } -TrackEntry::~TrackEntry() { } +TrackEntry::~TrackEntry() {} int TrackEntry::getTrackIndex() { return _trackIndex; } @@ -100,18 +95,18 @@ void TrackEntry::setAnimationEnd(float inValue) { _animationEnd = inValue; } float TrackEntry::getAnimationLast() { return _animationLast; } void TrackEntry::setAnimationLast(float inValue) { - _animationLast = inValue; - _nextAnimationLast = inValue; + _animationLast = inValue; + _nextAnimationLast = inValue; } float TrackEntry::getAnimationTime() { - if (_loop) { - float duration = _animationEnd - _animationStart; - if (duration == 0) return _animationStart; - return MathUtil::fmod(_trackTime, duration) + _animationStart; - } + if (_loop) { + float duration = _animationEnd - _animationStart; + if (duration == 0) return _animationStart; + return MathUtil::fmod(_trackTime, duration) + _animationStart; + } - return MathUtil::min(_trackTime + _animationStart, _animationEnd); + return MathUtil::min(_trackTime + _animationStart, _animationEnd); } float TrackEntry::getTimeScale() { return _timeScale; } @@ -137,7 +132,7 @@ void TrackEntry::setDrawOrderThreshold(float inValue) { _drawOrderThreshold = in TrackEntry *TrackEntry::getNext() { return _next; } bool TrackEntry::isComplete() { - return _trackTime >= _animationEnd - _animationStart; + return _trackTime >= _animationEnd - _animationStart; } float TrackEntry::getMixTime() { return _mixTime; } @@ -157,875 +152,889 @@ void TrackEntry::setMixBlend(MixBlend blend) { _mixBlend = blend; } MixBlend TrackEntry::getMixBlend() { return _mixBlend; } void TrackEntry::resetRotationDirections() { - _timelinesRotation.clear(); + _timelinesRotation.clear(); } void TrackEntry::setListener(AnimationStateListener inValue) { - _listener = inValue; - _listenerObject = NULL; + _listener = inValue; + _listenerObject = NULL; } -void TrackEntry::setListener(AnimationStateListenerObject* inValue) { - _listener = dummyOnAnimationEventFunc; - _listenerObject = inValue; +void TrackEntry::setListener(AnimationStateListenerObject *inValue) { + _listener = dummyOnAnimationEventFunc; + _listenerObject = inValue; } void TrackEntry::reset() { - _animation = NULL; - _next = NULL; - _mixingFrom = NULL; - _mixingTo = NULL; + _animation = NULL; + _next = NULL; + _mixingFrom = NULL; + _mixingTo = NULL; - setRendererObject(NULL); + setRendererObject(NULL); - _timelineMode.clear(); - _timelineHoldMix.clear(); - _timelinesRotation.clear(); + _timelineMode.clear(); + _timelineHoldMix.clear(); + _timelinesRotation.clear(); - _listener = dummyOnAnimationEventFunc; - _listenerObject = NULL; + _listener = dummyOnAnimationEventFunc; + _listenerObject = NULL; } -EventQueueEntry::EventQueueEntry(EventType eventType, TrackEntry *trackEntry, Event *event) : - _type(eventType), - _entry(trackEntry), - _event(event) { +EventQueueEntry::EventQueueEntry(EventType eventType, TrackEntry *trackEntry, Event *event) : _type(eventType), + _entry(trackEntry), + _event(event) { } EventQueue *EventQueue::newEventQueue(AnimationState &state, Pool &trackEntryPool) { - return new(__FILE__, __LINE__) EventQueue(state, trackEntryPool); + return new (__FILE__, __LINE__) EventQueue(state, trackEntryPool); } EventQueueEntry EventQueue::newEventQueueEntry(EventType eventType, TrackEntry *entry, Event *event) { - return EventQueueEntry(eventType, entry, event); + return EventQueueEntry(eventType, entry, event); } EventQueue::EventQueue(AnimationState &state, Pool &trackEntryPool) : _state(state), - _trackEntryPool(trackEntryPool), - _drainDisabled(false) { + _trackEntryPool(trackEntryPool), + _drainDisabled(false) { } EventQueue::~EventQueue() { } void EventQueue::start(TrackEntry *entry) { - _eventQueueEntries.add(newEventQueueEntry(EventType_Start, entry)); - _state._animationsChanged = true; + _eventQueueEntries.add(newEventQueueEntry(EventType_Start, entry)); + _state._animationsChanged = true; } void EventQueue::interrupt(TrackEntry *entry) { - _eventQueueEntries.add(newEventQueueEntry(EventType_Interrupt, entry)); + _eventQueueEntries.add(newEventQueueEntry(EventType_Interrupt, entry)); } void EventQueue::end(TrackEntry *entry) { - _eventQueueEntries.add(newEventQueueEntry(EventType_End, entry)); - _state._animationsChanged = true; + _eventQueueEntries.add(newEventQueueEntry(EventType_End, entry)); + _state._animationsChanged = true; } void EventQueue::dispose(TrackEntry *entry) { - _eventQueueEntries.add(newEventQueueEntry(EventType_Dispose, entry)); + _eventQueueEntries.add(newEventQueueEntry(EventType_Dispose, entry)); } void EventQueue::complete(TrackEntry *entry) { - _eventQueueEntries.add(newEventQueueEntry(EventType_Complete, entry)); + _eventQueueEntries.add(newEventQueueEntry(EventType_Complete, entry)); } void EventQueue::event(TrackEntry *entry, Event *event) { - _eventQueueEntries.add(newEventQueueEntry(EventType_Event, entry, event)); + _eventQueueEntries.add(newEventQueueEntry(EventType_Event, entry, event)); } /// Raises all events in the queue and drains the queue. void EventQueue::drain() { - if (_drainDisabled) { - return; - } + if (_drainDisabled) { + return; + } - _drainDisabled = true; + _drainDisabled = true; - AnimationState &state = _state; + AnimationState &state = _state; - // Don't cache _eventQueueEntries.size() so callbacks can queue their own events (eg, call setAnimation in AnimationState_Complete). - for (size_t i = 0; i < _eventQueueEntries.size(); ++i) { - EventQueueEntry *queueEntry = &_eventQueueEntries[i]; - TrackEntry *trackEntry = queueEntry->_entry; + // Don't cache _eventQueueEntries.size() so callbacks can queue their own events (eg, call setAnimation in AnimationState_Complete). + for (size_t i = 0; i < _eventQueueEntries.size(); ++i) { + EventQueueEntry *queueEntry = &_eventQueueEntries[i]; + TrackEntry * trackEntry = queueEntry->_entry; - switch (queueEntry->_type) { - case EventType_Start: - case EventType_Interrupt: - case EventType_Complete: - if (!trackEntry->_listenerObject) trackEntry->_listener(&state, queueEntry->_type, trackEntry, NULL); - else trackEntry->_listenerObject->callback(&state, queueEntry->_type, trackEntry, NULL); - if(!state._listenerObject) state._listener(&state, queueEntry->_type, trackEntry, NULL); - else state._listenerObject->callback(&state, queueEntry->_type, trackEntry, NULL); - break; - case EventType_End: - if (!trackEntry->_listenerObject) trackEntry->_listener(&state, queueEntry->_type, trackEntry, NULL); - else trackEntry->_listenerObject->callback(&state, queueEntry->_type, trackEntry, NULL); - if (!state._listenerObject) state._listener(&state, queueEntry->_type, trackEntry, NULL); - else state._listenerObject->callback(&state, queueEntry->_type, trackEntry, NULL); - /* Fall through. */ - case EventType_Dispose: - if (!trackEntry->_listenerObject) trackEntry->_listener(&state, EventType_Dispose, trackEntry, NULL); - else trackEntry->_listenerObject->callback(&state, EventType_Dispose, trackEntry, NULL); - if (!state._listenerObject) state._listener(&state, EventType_Dispose, trackEntry, NULL); - else state._listenerObject->callback(&state, EventType_Dispose, trackEntry, NULL); + switch (queueEntry->_type) { + case EventType_Start: + case EventType_Interrupt: + case EventType_Complete: + if (!trackEntry->_listenerObject) + trackEntry->_listener(&state, queueEntry->_type, trackEntry, NULL); + else + trackEntry->_listenerObject->callback(&state, queueEntry->_type, trackEntry, NULL); + if (!state._listenerObject) + state._listener(&state, queueEntry->_type, trackEntry, NULL); + else + state._listenerObject->callback(&state, queueEntry->_type, trackEntry, NULL); + break; + case EventType_End: + if (!trackEntry->_listenerObject) + trackEntry->_listener(&state, queueEntry->_type, trackEntry, NULL); + else + trackEntry->_listenerObject->callback(&state, queueEntry->_type, trackEntry, NULL); + if (!state._listenerObject) + state._listener(&state, queueEntry->_type, trackEntry, NULL); + else + state._listenerObject->callback(&state, queueEntry->_type, trackEntry, NULL); + /* Fall through. */ + case EventType_Dispose: + if (!trackEntry->_listenerObject) + trackEntry->_listener(&state, EventType_Dispose, trackEntry, NULL); + else + trackEntry->_listenerObject->callback(&state, EventType_Dispose, trackEntry, NULL); + if (!state._listenerObject) + state._listener(&state, EventType_Dispose, trackEntry, NULL); + else + state._listenerObject->callback(&state, EventType_Dispose, trackEntry, NULL); - trackEntry->reset(); - _trackEntryPool.free(trackEntry); - break; - case EventType_Event: - if (!trackEntry->_listenerObject) trackEntry->_listener(&state, queueEntry->_type, trackEntry, queueEntry->_event); - else trackEntry->_listenerObject->callback(&state, queueEntry->_type, trackEntry, queueEntry->_event); - if (!state._listenerObject) state._listener(&state, queueEntry->_type, trackEntry, queueEntry->_event); - else state._listenerObject->callback(&state, queueEntry->_type, trackEntry, queueEntry->_event); - break; - } - } - _eventQueueEntries.clear(); + trackEntry->reset(); + _trackEntryPool.free(trackEntry); + break; + case EventType_Event: + if (!trackEntry->_listenerObject) + trackEntry->_listener(&state, queueEntry->_type, trackEntry, queueEntry->_event); + else + trackEntry->_listenerObject->callback(&state, queueEntry->_type, trackEntry, queueEntry->_event); + if (!state._listenerObject) + state._listener(&state, queueEntry->_type, trackEntry, queueEntry->_event); + else + state._listenerObject->callback(&state, queueEntry->_type, trackEntry, queueEntry->_event); + break; + } + } + _eventQueueEntries.clear(); - _drainDisabled = false; + _drainDisabled = false; } const int Subsequent = 0; -const int First = 1; -const int Hold = 2; -const int HoldMix = 3; -const int NotLast = 4; +const int First = 1; +const int Hold = 2; +const int HoldMix = 3; +const int NotLast = 4; -AnimationState::AnimationState(AnimationStateData *data) : - _data(data), - _queue(EventQueue::newEventQueue(*this, _trackEntryPool)), - _animationsChanged(false), - _listener(dummyOnAnimationEventFunc), - _listenerObject(NULL), - _timeScale(1) { +AnimationState::AnimationState(AnimationStateData *data) : _data(data), + _queue(EventQueue::newEventQueue(*this, _trackEntryPool)), + _animationsChanged(false), + _listener(dummyOnAnimationEventFunc), + _listenerObject(NULL), + _timeScale(1) { } AnimationState::~AnimationState() { - for (size_t i = 0; i < _tracks.size(); i++) { - TrackEntry* entry = _tracks[i]; - if (entry) { - TrackEntry* from = entry->_mixingFrom; - while (from) { - TrackEntry* curr = from; - from = curr->_mixingFrom; - delete curr; - } - TrackEntry* next = entry->_next; - while (next) { - TrackEntry* curr = next; - next = curr->_next; - delete curr; - } - delete entry; - } - } - delete _queue; + for (size_t i = 0; i < _tracks.size(); i++) { + TrackEntry *entry = _tracks[i]; + if (entry) { + TrackEntry *from = entry->_mixingFrom; + while (from) { + TrackEntry *curr = from; + from = curr->_mixingFrom; + delete curr; + } + TrackEntry *next = entry->_next; + while (next) { + TrackEntry *curr = next; + next = curr->_next; + delete curr; + } + delete entry; + } + } + delete _queue; } void AnimationState::update(float delta) { - delta *= _timeScale; - for (size_t i = 0, n = _tracks.size(); i < n; ++i) { - TrackEntry *currentP = _tracks[i]; - if (currentP == NULL) { - continue; - } + delta *= _timeScale; + for (size_t i = 0, n = _tracks.size(); i < n; ++i) { + TrackEntry *currentP = _tracks[i]; + if (currentP == NULL) { + continue; + } - TrackEntry ¤t = *currentP; + TrackEntry ¤t = *currentP; - current._animationLast = current._nextAnimationLast; - current._trackLast = current._nextTrackLast; + current._animationLast = current._nextAnimationLast; + current._trackLast = current._nextTrackLast; - float currentDelta = delta * current._timeScale; + float currentDelta = delta * current._timeScale; - if (current._delay > 0) { - current._delay -= currentDelta; - if (current._delay > 0) { - continue; - } - currentDelta = -current._delay; - current._delay = 0; - } + if (current._delay > 0) { + current._delay -= currentDelta; + if (current._delay > 0) { + continue; + } + currentDelta = -current._delay; + current._delay = 0; + } - TrackEntry *next = current._next; - if (next != NULL) { - // When the next entry's delay is passed, change to the next entry, preserving leftover time. - float nextTime = current._trackLast - next->_delay; - if (nextTime >= 0) { - next->_delay = 0; - next->_trackTime += current._timeScale == 0 ? 0 : (nextTime / current._timeScale + delta) * next->_timeScale; - current._trackTime += currentDelta; - setCurrent(i, next, true); - while (next->_mixingFrom != NULL) { - next->_mixTime += delta; - next = next->_mixingFrom; - } - continue; - } - } else if (current._trackLast >= current._trackEnd && current._mixingFrom == NULL) { - // clear the track when there is no next entry, the track end time is reached, and there is no mixingFrom. - _tracks[i] = NULL; + TrackEntry *next = current._next; + if (next != NULL) { + // When the next entry's delay is passed, change to the next entry, preserving leftover time. + float nextTime = current._trackLast - next->_delay; + if (nextTime >= 0) { + next->_delay = 0; + next->_trackTime += current._timeScale == 0 ? 0 : (nextTime / current._timeScale + delta) * next->_timeScale; + current._trackTime += currentDelta; + setCurrent(i, next, true); + while (next->_mixingFrom != NULL) { + next->_mixTime += delta; + next = next->_mixingFrom; + } + continue; + } + } else if (current._trackLast >= current._trackEnd && current._mixingFrom == NULL) { + // clear the track when there is no next entry, the track end time is reached, and there is no mixingFrom. + _tracks[i] = NULL; - _queue->end(currentP); - disposeNext(currentP); - continue; - } + _queue->end(currentP); + disposeNext(currentP); + continue; + } - if (current._mixingFrom != NULL && updateMixingFrom(currentP, delta)) { - // End mixing from entries once all have completed. - TrackEntry *from = current._mixingFrom; - current._mixingFrom = NULL; - if (from != NULL) from->_mixingTo = NULL; - while (from != NULL) { - _queue->end(from); - from = from->_mixingFrom; - } - } + if (current._mixingFrom != NULL && updateMixingFrom(currentP, delta)) { + // End mixing from entries once all have completed. + TrackEntry *from = current._mixingFrom; + current._mixingFrom = NULL; + if (from != NULL) from->_mixingTo = NULL; + while (from != NULL) { + _queue->end(from); + from = from->_mixingFrom; + } + } - current._trackTime += currentDelta; - } + current._trackTime += currentDelta; + } - _queue->drain(); + _queue->drain(); } bool AnimationState::apply(Skeleton &skeleton) { - if (_animationsChanged) { - animationsChanged(); - } + if (_animationsChanged) { + animationsChanged(); + } - bool applied = false; - for (size_t i = 0, n = _tracks.size(); i < n; ++i) { - TrackEntry *currentP = _tracks[i]; - if (currentP == NULL || currentP->_delay > 0) { - continue; - } + bool applied = false; + for (size_t i = 0, n = _tracks.size(); i < n; ++i) { + TrackEntry *currentP = _tracks[i]; + if (currentP == NULL || currentP->_delay > 0) { + continue; + } - TrackEntry ¤t = *currentP; + TrackEntry ¤t = *currentP; - applied = true; - MixBlend blend = i == 0 ? MixBlend_First : current._mixBlend; + applied = true; + MixBlend blend = i == 0 ? MixBlend_First : current._mixBlend; - // apply mixing from entries first. - float mix = current._alpha; - if (current._mixingFrom != NULL) { - mix *= applyMixingFrom(currentP, skeleton, blend); - } else if (current._trackTime >= current._trackEnd && current._next == NULL) { - mix = 0; // Set to setup pose the last time the entry will be applied. - } + // apply mixing from entries first. + float mix = current._alpha; + if (current._mixingFrom != NULL) { + mix *= applyMixingFrom(currentP, skeleton, blend); + } else if (current._trackTime >= current._trackEnd && current._next == NULL) { + mix = 0; // Set to setup pose the last time the entry will be applied. + } - // apply current entry. - float animationLast = current._animationLast, animationTime = current.getAnimationTime(); - size_t timelineCount = current._animation->_timelines.size(); - Vector &timelines = current._animation->_timelines; - if ((i == 0 && mix == 1) || blend == MixBlend_Add) { - for (size_t ii = 0; ii < timelineCount; ++ii) - timelines[ii]->apply(skeleton, animationLast, animationTime, &_events, mix, blend, MixDirection_In); - } else { - Vector &timelineMode = current._timelineMode; + // apply current entry. + float animationLast = current._animationLast, animationTime = current.getAnimationTime(); + size_t timelineCount = current._animation->_timelines.size(); + Vector &timelines = current._animation->_timelines; + if ((i == 0 && mix == 1) || blend == MixBlend_Add) { + for (size_t ii = 0; ii < timelineCount; ++ii) + timelines[ii]->apply(skeleton, animationLast, animationTime, &_events, mix, blend, MixDirection_In); + } else { + Vector &timelineMode = current._timelineMode; - bool firstFrame = current._timelinesRotation.size() == 0; - if (firstFrame) current._timelinesRotation.setSize(timelines.size() << 1, 0); - Vector &timelinesRotation = current._timelinesRotation; + bool firstFrame = current._timelinesRotation.size() == 0; + if (firstFrame) current._timelinesRotation.setSize(timelines.size() << 1, 0); + Vector &timelinesRotation = current._timelinesRotation; - for (size_t ii = 0; ii < timelineCount; ++ii) { - Timeline *timeline = timelines[ii]; - assert(timeline); + for (size_t ii = 0; ii < timelineCount; ++ii) { + Timeline *timeline = timelines[ii]; + assert(timeline); - MixBlend timelineBlend = (timelineMode[ii] & (NotLast - 1)) == Subsequent ? blend : MixBlend_Setup; + MixBlend timelineBlend = (timelineMode[ii] & (NotLast - 1)) == Subsequent ? blend : MixBlend_Setup; - RotateTimeline *rotateTimeline = NULL; - if (timeline->getRTTI().isExactly(RotateTimeline::rtti)) rotateTimeline = static_cast(timeline); + RotateTimeline *rotateTimeline = NULL; + if (timeline->getRTTI().isExactly(RotateTimeline::rtti)) rotateTimeline = static_cast(timeline); - if (rotateTimeline != NULL) - applyRotateTimeline(rotateTimeline, skeleton, animationTime, mix, timelineBlend, timelinesRotation, ii << 1, firstFrame); - else - timeline->apply(skeleton, animationLast, animationTime, &_events, mix, timelineBlend, MixDirection_In); - } - } + if (rotateTimeline != NULL) + applyRotateTimeline(rotateTimeline, skeleton, animationTime, mix, timelineBlend, timelinesRotation, ii << 1, firstFrame); + else + timeline->apply(skeleton, animationLast, animationTime, &_events, mix, timelineBlend, MixDirection_In); + } + } - queueEvents(currentP, animationTime); - _events.clear(); - current._nextAnimationLast = animationTime; - current._nextTrackLast = current._trackTime; - } + queueEvents(currentP, animationTime); + _events.clear(); + current._nextAnimationLast = animationTime; + current._nextTrackLast = current._trackTime; + } - _queue->drain(); - return applied; + _queue->drain(); + return applied; } void AnimationState::clearTracks() { - bool oldDrainDisabled = _queue->_drainDisabled; - _queue->_drainDisabled = true; - for (size_t i = 0, n = _tracks.size(); i < n; ++i) - clearTrack(i); - _tracks.clear(); - _queue->_drainDisabled = oldDrainDisabled; - _queue->drain(); + bool oldDrainDisabled = _queue->_drainDisabled; + _queue->_drainDisabled = true; + for (size_t i = 0, n = _tracks.size(); i < n; ++i) + clearTrack(i); + _tracks.clear(); + _queue->_drainDisabled = oldDrainDisabled; + _queue->drain(); } void AnimationState::clearTrack(size_t trackIndex) { - if (trackIndex >= _tracks.size()) return; + if (trackIndex >= _tracks.size()) return; - TrackEntry *current = _tracks[trackIndex]; - if (current == NULL) return; + TrackEntry *current = _tracks[trackIndex]; + if (current == NULL) return; - _queue->end(current); + _queue->end(current); - disposeNext(current); + disposeNext(current); - TrackEntry *entry = current; - while (true) { - TrackEntry *from = entry->_mixingFrom; - if (from == NULL) break; + TrackEntry *entry = current; + while (true) { + TrackEntry *from = entry->_mixingFrom; + if (from == NULL) break; - _queue->end(from); - entry->_mixingFrom = NULL; - entry->_mixingTo = NULL; - entry = from; - } + _queue->end(from); + entry->_mixingFrom = NULL; + entry->_mixingTo = NULL; + entry = from; + } - _tracks[current->_trackIndex] = NULL; + _tracks[current->_trackIndex] = NULL; - _queue->drain(); + _queue->drain(); } TrackEntry *AnimationState::setAnimation(size_t trackIndex, const String &animationName, bool loop) { - Animation *animation = _data->_skeletonData->findAnimation(animationName); - assert(animation != NULL); - return setAnimation(trackIndex, animation, loop); + Animation *animation = _data->_skeletonData->findAnimation(animationName); + assert(animation != NULL); + return setAnimation(trackIndex, animation, loop); } TrackEntry *AnimationState::setAnimation(size_t trackIndex, Animation *animation, bool loop) { - assert(animation != NULL); + assert(animation != NULL); - bool interrupt = true; - TrackEntry *current = expandToIndex(trackIndex); - if (current != NULL) { - if (current->_nextTrackLast == -1) { - // Don't mix from an entry that was never applied. - _tracks[trackIndex] = current->_mixingFrom; - _queue->interrupt(current); - _queue->end(current); - disposeNext(current); - current = current->_mixingFrom; - interrupt = false; - } else { - disposeNext(current); - } - } + bool interrupt = true; + TrackEntry *current = expandToIndex(trackIndex); + if (current != NULL) { + if (current->_nextTrackLast == -1) { + // Don't mix from an entry that was never applied. + _tracks[trackIndex] = current->_mixingFrom; + _queue->interrupt(current); + _queue->end(current); + disposeNext(current); + current = current->_mixingFrom; + interrupt = false; + } else { + disposeNext(current); + } + } - TrackEntry *entry = newTrackEntry(trackIndex, animation, loop, current); - setCurrent(trackIndex, entry, interrupt); - _queue->drain(); + TrackEntry *entry = newTrackEntry(trackIndex, animation, loop, current); + setCurrent(trackIndex, entry, interrupt); + _queue->drain(); - return entry; + return entry; } TrackEntry *AnimationState::addAnimation(size_t trackIndex, const String &animationName, bool loop, float delay) { - Animation *animation = _data->_skeletonData->findAnimation(animationName); - assert(animation != NULL); - return addAnimation(trackIndex, animation, loop, delay); + Animation *animation = _data->_skeletonData->findAnimation(animationName); + assert(animation != NULL); + return addAnimation(trackIndex, animation, loop, delay); } TrackEntry *AnimationState::addAnimation(size_t trackIndex, Animation *animation, bool loop, float delay) { - assert(animation != NULL); + assert(animation != NULL); - TrackEntry *last = expandToIndex(trackIndex); - if (last != NULL) { - while (last->_next != NULL) - last = last->_next; - } + TrackEntry *last = expandToIndex(trackIndex); + if (last != NULL) { + while (last->_next != NULL) + last = last->_next; + } - TrackEntry *entry = newTrackEntry(trackIndex, animation, loop, last); + TrackEntry *entry = newTrackEntry(trackIndex, animation, loop, last); - if (last == NULL) { - setCurrent(trackIndex, entry, true); - _queue->drain(); - } else { - last->_next = entry; - if (delay <= 0) { - float duration = last->_animationEnd - last->_animationStart; - if (duration != 0) { - if (last->_loop) { - delay += duration * (1 + (int) (last->_trackTime / duration)); - } else { - delay += MathUtil::max(duration, last->_trackTime); - } - delay -= _data->getMix(last->_animation, animation); - } else { - delay = last->_trackTime; - } - } - } + if (last == NULL) { + setCurrent(trackIndex, entry, true); + _queue->drain(); + } else { + last->_next = entry; + if (delay <= 0) { + float duration = last->_animationEnd - last->_animationStart; + if (duration != 0) { + if (last->_loop) { + delay += duration * (1 + (int)(last->_trackTime / duration)); + } else { + delay += MathUtil::max(duration, last->_trackTime); + } + delay -= _data->getMix(last->_animation, animation); + } else { + delay = last->_trackTime; + } + } + } - entry->_delay = delay; - return entry; + entry->_delay = delay; + return entry; } TrackEntry *AnimationState::setEmptyAnimation(size_t trackIndex, float mixDuration) { - TrackEntry *entry = setAnimation(trackIndex, AnimationState::getEmptyAnimation(), false); - entry->_mixDuration = mixDuration; - entry->_trackEnd = mixDuration; - return entry; + TrackEntry *entry = setAnimation(trackIndex, AnimationState::getEmptyAnimation(), false); + entry->_mixDuration = mixDuration; + entry->_trackEnd = mixDuration; + return entry; } TrackEntry *AnimationState::addEmptyAnimation(size_t trackIndex, float mixDuration, float delay) { - if (delay <= 0) { - delay -= mixDuration; - } + if (delay <= 0) { + delay -= mixDuration; + } - TrackEntry *entry = addAnimation(trackIndex, AnimationState::getEmptyAnimation(), false, delay); - entry->_mixDuration = mixDuration; - entry->_trackEnd = mixDuration; - return entry; + TrackEntry *entry = addAnimation(trackIndex, AnimationState::getEmptyAnimation(), false, delay); + entry->_mixDuration = mixDuration; + entry->_trackEnd = mixDuration; + return entry; } void AnimationState::setEmptyAnimations(float mixDuration) { - bool oldDrainDisabled = _queue->_drainDisabled; - _queue->_drainDisabled = true; - for (size_t i = 0, n = _tracks.size(); i < n; ++i) { - TrackEntry *current = _tracks[i]; - if (current != NULL) { - setEmptyAnimation(i, mixDuration); - } - } - _queue->_drainDisabled = oldDrainDisabled; - _queue->drain(); + bool oldDrainDisabled = _queue->_drainDisabled; + _queue->_drainDisabled = true; + for (size_t i = 0, n = _tracks.size(); i < n; ++i) { + TrackEntry *current = _tracks[i]; + if (current != NULL) { + setEmptyAnimation(i, mixDuration); + } + } + _queue->_drainDisabled = oldDrainDisabled; + _queue->drain(); } TrackEntry *AnimationState::getCurrent(size_t trackIndex) { - return trackIndex >= _tracks.size() ? NULL : _tracks[trackIndex]; + return trackIndex >= _tracks.size() ? NULL : _tracks[trackIndex]; } AnimationStateData *AnimationState::getData() { - return _data; + return _data; } Vector &AnimationState::getTracks() { - return _tracks; + return _tracks; } float AnimationState::getTimeScale() { - return _timeScale; + return _timeScale; } void AnimationState::setTimeScale(float inValue) { - _timeScale = inValue; + _timeScale = inValue; } void AnimationState::setListener(AnimationStateListener inValue) { - _listener = inValue; - _listenerObject = NULL; + _listener = inValue; + _listenerObject = NULL; } -void AnimationState::setListener(AnimationStateListenerObject* inValue) { - _listener = dummyOnAnimationEventFunc; - _listenerObject = inValue; +void AnimationState::setListener(AnimationStateListenerObject *inValue) { + _listener = dummyOnAnimationEventFunc; + _listenerObject = inValue; } void AnimationState::disableQueue() { - _queue->_drainDisabled = true; + _queue->_drainDisabled = true; } void AnimationState::enableQueue() { - _queue->_drainDisabled = false; + _queue->_drainDisabled = false; } Animation *AnimationState::getEmptyAnimation() { - static Vector timelines; - static Animation ret(String(""), timelines, 0); - return &ret; + static Vector timelines; + static Animation ret(String(""), timelines, 0); + return &ret; } void AnimationState::applyRotateTimeline(RotateTimeline *rotateTimeline, Skeleton &skeleton, float time, float alpha, - MixBlend blend, Vector &timelinesRotation, size_t i, bool firstFrame -) { - if (firstFrame) timelinesRotation[i] = 0; + MixBlend blend, Vector &timelinesRotation, size_t i, bool firstFrame) { + if (firstFrame) timelinesRotation[i] = 0; - if (alpha == 1) { - rotateTimeline->apply(skeleton, 0, time, NULL, 1, blend, MixDirection_In); - return; - } + if (alpha == 1) { + rotateTimeline->apply(skeleton, 0, time, NULL, 1, blend, MixDirection_In); + return; + } - Bone *bone = skeleton._bones[rotateTimeline->_boneIndex]; - if (!bone->isActive()) return; - Vector& frames = rotateTimeline->_frames; - float r1, r2; - if (time < frames[0]) { - switch (blend) { - case MixBlend_Setup: - bone->_rotation = bone->_data._rotation; - default: - return; - case MixBlend_First: - r1 = bone->_rotation; - r2 = bone->_data._rotation; - } - } else { - r1 = blend == MixBlend_Setup ? bone->_data._rotation : bone->_rotation; - if (time >= frames[frames.size() - RotateTimeline::ENTRIES]) { - // Time is after last frame. - r2 = bone->_data._rotation + frames[frames.size() + RotateTimeline::PREV_ROTATION]; - } else { - // Interpolate between the previous frame and the current frame. - int frame = Animation::binarySearch(frames, time, RotateTimeline::ENTRIES); - float prevRotation = frames[frame + RotateTimeline::PREV_ROTATION]; - float frameTime = frames[frame]; - float percent = rotateTimeline->getCurvePercent((frame >> 1) - 1, 1 - (time - frameTime) / (frames[frame + - RotateTimeline::PREV_TIME] - frameTime)); - r2 = frames[frame + RotateTimeline::ROTATION] - prevRotation; - r2 -= (16384 - (int) (16384.499999999996 - r2 / 360)) * 360; - r2 = prevRotation + r2 * percent + bone->_data._rotation; - r2 -= (16384 - (int) (16384.499999999996 - r2 / 360)) * 360; - } - } + Bone *bone = skeleton._bones[rotateTimeline->_boneIndex]; + if (!bone->isActive()) return; + Vector &frames = rotateTimeline->_frames; + float r1, r2; + if (time < frames[0]) { + switch (blend) { + case MixBlend_Setup: + bone->_rotation = bone->_data._rotation; + default: + return; + case MixBlend_First: + r1 = bone->_rotation; + r2 = bone->_data._rotation; + } + } else { + r1 = blend == MixBlend_Setup ? bone->_data._rotation : bone->_rotation; + if (time >= frames[frames.size() - RotateTimeline::ENTRIES]) { + // Time is after last frame. + r2 = bone->_data._rotation + frames[frames.size() + RotateTimeline::PREV_ROTATION]; + } else { + // Interpolate between the previous frame and the current frame. + int frame = Animation::binarySearch(frames, time, RotateTimeline::ENTRIES); + float prevRotation = frames[frame + RotateTimeline::PREV_ROTATION]; + float frameTime = frames[frame]; + float percent = rotateTimeline->getCurvePercent((frame >> 1) - 1, 1 - (time - frameTime) / (frames[frame + + RotateTimeline::PREV_TIME] - + frameTime)); + r2 = frames[frame + RotateTimeline::ROTATION] - prevRotation; + r2 -= (16384 - (int)(16384.499999999996 - r2 / 360)) * 360; + r2 = prevRotation + r2 * percent + bone->_data._rotation; + r2 -= (16384 - (int)(16384.499999999996 - r2 / 360)) * 360; + } + } - // Mix between rotations using the direction of the shortest route on the first frame while detecting crosses. - float total, diff = r2 - r1; - diff -= (16384 - (int) (16384.499999999996 - diff / 360)) * 360; - if (diff == 0) { - total = timelinesRotation[i]; - } else { - float lastTotal, lastDiff; - if (firstFrame) { - lastTotal = 0; - lastDiff = diff; - } else { - lastTotal = timelinesRotation[i]; // Angle and direction of mix, including loops. - lastDiff = timelinesRotation[i + 1]; // Difference between bones. - } + // Mix between rotations using the direction of the shortest route on the first frame while detecting crosses. + float total, diff = r2 - r1; + diff -= (16384 - (int)(16384.499999999996 - diff / 360)) * 360; + if (diff == 0) { + total = timelinesRotation[i]; + } else { + float lastTotal, lastDiff; + if (firstFrame) { + lastTotal = 0; + lastDiff = diff; + } else { + lastTotal = timelinesRotation[i]; // Angle and direction of mix, including loops. + lastDiff = timelinesRotation[i + 1]; // Difference between bones. + } - bool current = diff > 0, dir = lastTotal >= 0; - // Detect cross at 0 (not 180). - if (MathUtil::sign(lastDiff) != MathUtil::sign(diff) && MathUtil::abs(lastDiff) <= 90) { - // A cross after a 360 rotation is a loop. - if (MathUtil::abs(lastTotal) > 180) lastTotal += 360 * MathUtil::sign(lastTotal); - dir = current; - } + bool current = diff > 0, dir = lastTotal >= 0; + // Detect cross at 0 (not 180). + if (MathUtil::sign(lastDiff) != MathUtil::sign(diff) && MathUtil::abs(lastDiff) <= 90) { + // A cross after a 360 rotation is a loop. + if (MathUtil::abs(lastTotal) > 180) lastTotal += 360 * MathUtil::sign(lastTotal); + dir = current; + } - total = diff + lastTotal - MathUtil::fmod(lastTotal, 360); // Store loops as part of lastTotal. - if (dir != current) { - total += 360 * MathUtil::sign(lastTotal); - } - timelinesRotation[i] = total; - } - timelinesRotation[i + 1] = diff; - r1 += total * alpha; - bone->_rotation = r1 - (16384 - (int) (16384.499999999996 - r1 / 360)) * 360; + total = diff + lastTotal - MathUtil::fmod(lastTotal, 360); // Store loops as part of lastTotal. + if (dir != current) { + total += 360 * MathUtil::sign(lastTotal); + } + timelinesRotation[i] = total; + } + timelinesRotation[i + 1] = diff; + r1 += total * alpha; + bone->_rotation = r1 - (16384 - (int)(16384.499999999996 - r1 / 360)) * 360; } bool AnimationState::updateMixingFrom(TrackEntry *to, float delta) { - TrackEntry *from = to->_mixingFrom; - if (from == NULL) { - return true; - } + TrackEntry *from = to->_mixingFrom; + if (from == NULL) { + return true; + } - bool finished = updateMixingFrom(from, delta); + bool finished = updateMixingFrom(from, delta); - from->_animationLast = from->_nextAnimationLast; - from->_trackLast = from->_nextTrackLast; + from->_animationLast = from->_nextAnimationLast; + from->_trackLast = from->_nextTrackLast; - // Require mixTime > 0 to ensure the mixing from entry was applied at least once. - if (to->_mixTime > 0 && to->_mixTime >= to->_mixDuration) { - // Require totalAlpha == 0 to ensure mixing is complete, unless mixDuration == 0 (the transition is a single frame). - if (from->_totalAlpha == 0 || to->_mixDuration == 0) { - to->_mixingFrom = from->_mixingFrom; - if (from->_mixingFrom != NULL) from->_mixingFrom->_mixingTo = to; - to->_interruptAlpha = from->_interruptAlpha; - _queue->end(from); - } - return finished; - } + // Require mixTime > 0 to ensure the mixing from entry was applied at least once. + if (to->_mixTime > 0 && to->_mixTime >= to->_mixDuration) { + // Require totalAlpha == 0 to ensure mixing is complete, unless mixDuration == 0 (the transition is a single frame). + if (from->_totalAlpha == 0 || to->_mixDuration == 0) { + to->_mixingFrom = from->_mixingFrom; + if (from->_mixingFrom != NULL) from->_mixingFrom->_mixingTo = to; + to->_interruptAlpha = from->_interruptAlpha; + _queue->end(from); + } + return finished; + } - from->_trackTime += delta * from->_timeScale; - to->_mixTime += delta; + from->_trackTime += delta * from->_timeScale; + to->_mixTime += delta; - return false; + return false; } float AnimationState::applyMixingFrom(TrackEntry *to, Skeleton &skeleton, MixBlend blend) { - TrackEntry *from = to->_mixingFrom; - if (from->_mixingFrom != NULL) applyMixingFrom(from, skeleton, blend); + TrackEntry *from = to->_mixingFrom; + if (from->_mixingFrom != NULL) applyMixingFrom(from, skeleton, blend); - float mix; - if (to->_mixDuration == 0) { - // Single frame mix to undo mixingFrom changes. - mix = 1; - if (blend == MixBlend_First) blend = MixBlend_Setup; - } else { - mix = to->_mixTime / to->_mixDuration; - if (mix > 1) { - mix = 1; - } - if (blend != MixBlend_First) blend = from->_mixBlend; - } + float mix; + if (to->_mixDuration == 0) { + // Single frame mix to undo mixingFrom changes. + mix = 1; + if (blend == MixBlend_First) blend = MixBlend_Setup; + } else { + mix = to->_mixTime / to->_mixDuration; + if (mix > 1) { + mix = 1; + } + if (blend != MixBlend_First) blend = from->_mixBlend; + } - Vector *eventBuffer = mix < from->_eventThreshold ? &_events : NULL; - bool attachments = mix < from->_attachmentThreshold, drawOrder = mix < from->_drawOrderThreshold; - float animationLast = from->_animationLast, animationTime = from->getAnimationTime(); - Vector &timelines = from->_animation->_timelines; - size_t timelineCount = timelines.size(); - float alphaHold = from->_alpha * to->_interruptAlpha, alphaMix = alphaHold * (1 - mix); + Vector * eventBuffer = mix < from->_eventThreshold ? &_events : NULL; + bool attachments = mix < from->_attachmentThreshold, drawOrder = mix < from->_drawOrderThreshold; + float animationLast = from->_animationLast, animationTime = from->getAnimationTime(); + Vector &timelines = from->_animation->_timelines; + size_t timelineCount = timelines.size(); + float alphaHold = from->_alpha * to->_interruptAlpha, alphaMix = alphaHold * (1 - mix); - if (blend == MixBlend_Add) { - for (size_t i = 0; i < timelineCount; i++) - timelines[i]->apply(skeleton, animationLast, animationTime, eventBuffer, alphaMix, blend, MixDirection_Out); - } else { - Vector &timelineMode = from->_timelineMode; - Vector &timelineHoldMix = from->_timelineHoldMix; + if (blend == MixBlend_Add) { + for (size_t i = 0; i < timelineCount; i++) + timelines[i]->apply(skeleton, animationLast, animationTime, eventBuffer, alphaMix, blend, MixDirection_Out); + } else { + Vector & timelineMode = from->_timelineMode; + Vector &timelineHoldMix = from->_timelineHoldMix; - bool firstFrame = from->_timelinesRotation.size() == 0; - if (firstFrame) from->_timelinesRotation.setSize(timelines.size() << 1, 0); + bool firstFrame = from->_timelinesRotation.size() == 0; + if (firstFrame) from->_timelinesRotation.setSize(timelines.size() << 1, 0); - Vector &timelinesRotation = from->_timelinesRotation; + Vector &timelinesRotation = from->_timelinesRotation; - from->_totalAlpha = 0; - for (size_t i = 0; i < timelineCount; i++) { - Timeline *timeline = timelines[i]; - MixDirection direction = MixDirection_Out; - MixBlend timelineBlend; - float alpha; - switch (timelineMode[i] & (NotLast - 1)) { - case Subsequent: - timelineBlend = blend; - if (!attachments && (timeline->getRTTI().isExactly(AttachmentTimeline::rtti))) { - if ((timelineMode[i] & NotLast) == NotLast) continue; - timelineBlend = MixBlend_Setup; - } - if (!drawOrder && (timeline->getRTTI().isExactly(DrawOrderTimeline::rtti))) continue; - alpha = alphaMix; - break; - case First: - timelineBlend = MixBlend_Setup; - alpha = alphaMix; - break; - case Hold: - timelineBlend = MixBlend_Setup; - alpha = alphaHold; - break; - default: - timelineBlend = MixBlend_Setup; - TrackEntry *holdMix = timelineHoldMix[i]; - alpha = alphaHold * MathUtil::max(0.0f, 1.0f - holdMix->_mixTime / holdMix->_mixDuration); - break; - } - from->_totalAlpha += alpha; - if ((timeline->getRTTI().isExactly(RotateTimeline::rtti))) { - applyRotateTimeline((RotateTimeline*)timeline, skeleton, animationTime, alpha, timelineBlend, timelinesRotation, i << 1, firstFrame); - } else { - if (timelineBlend == MixBlend_Setup) { - if (timeline->getRTTI().isExactly(AttachmentTimeline::rtti)) { - if (attachments || (timelineMode[i] & NotLast) == NotLast) direction = MixDirection_In; - } else if (timeline->getRTTI().isExactly(DrawOrderTimeline::rtti)) { - if (drawOrder) direction = MixDirection_In; - } - } - timeline->apply(skeleton, animationLast, animationTime, eventBuffer, alpha, timelineBlend, direction); - } - } - } + from->_totalAlpha = 0; + for (size_t i = 0; i < timelineCount; i++) { + Timeline * timeline = timelines[i]; + MixDirection direction = MixDirection_Out; + MixBlend timelineBlend; + float alpha; + switch (timelineMode[i] & (NotLast - 1)) { + case Subsequent: + timelineBlend = blend; + if (!attachments && (timeline->getRTTI().isExactly(AttachmentTimeline::rtti))) { + if ((timelineMode[i] & NotLast) == NotLast) continue; + timelineBlend = MixBlend_Setup; + } + if (!drawOrder && (timeline->getRTTI().isExactly(DrawOrderTimeline::rtti))) continue; + alpha = alphaMix; + break; + case First: + timelineBlend = MixBlend_Setup; + alpha = alphaMix; + break; + case Hold: + timelineBlend = MixBlend_Setup; + alpha = alphaHold; + break; + default: + timelineBlend = MixBlend_Setup; + TrackEntry *holdMix = timelineHoldMix[i]; + alpha = alphaHold * MathUtil::max(0.0f, 1.0f - holdMix->_mixTime / holdMix->_mixDuration); + break; + } + from->_totalAlpha += alpha; + if ((timeline->getRTTI().isExactly(RotateTimeline::rtti))) { + applyRotateTimeline((RotateTimeline *)timeline, skeleton, animationTime, alpha, timelineBlend, timelinesRotation, i << 1, firstFrame); + } else { + if (timelineBlend == MixBlend_Setup) { + if (timeline->getRTTI().isExactly(AttachmentTimeline::rtti)) { + if (attachments || (timelineMode[i] & NotLast) == NotLast) direction = MixDirection_In; + } else if (timeline->getRTTI().isExactly(DrawOrderTimeline::rtti)) { + if (drawOrder) direction = MixDirection_In; + } + } + timeline->apply(skeleton, animationLast, animationTime, eventBuffer, alpha, timelineBlend, direction); + } + } + } - if (to->_mixDuration > 0) { - queueEvents(from, animationTime); - } + if (to->_mixDuration > 0) { + queueEvents(from, animationTime); + } - _events.clear(); - from->_nextAnimationLast = animationTime; - from->_nextTrackLast = from->_trackTime; + _events.clear(); + from->_nextAnimationLast = animationTime; + from->_nextTrackLast = from->_trackTime; - return mix; + return mix; } void AnimationState::queueEvents(TrackEntry *entry, float animationTime) { - float animationStart = entry->_animationStart, animationEnd = entry->_animationEnd; - float duration = animationEnd - animationStart; - float trackLastWrapped = MathUtil::fmod(entry->_trackLast, duration); + float animationStart = entry->_animationStart, animationEnd = entry->_animationEnd; + float duration = animationEnd - animationStart; + float trackLastWrapped = MathUtil::fmod(entry->_trackLast, duration); - // Queue events before complete. - size_t i = 0, n = _events.size(); - for (; i < n; ++i) { - Event *e = _events[i]; - if (e->_time < trackLastWrapped) break; - if (e->_time > animationEnd) continue; // Discard events outside animation start/end. - _queue->event(entry, e); - } + // Queue events before complete. + size_t i = 0, n = _events.size(); + for (; i < n; ++i) { + Event *e = _events[i]; + if (e->_time < trackLastWrapped) break; + if (e->_time > animationEnd) continue; // Discard events outside animation start/end. + _queue->event(entry, e); + } - // Queue complete if completed a loop iteration or the animation. - bool complete = false; - if (entry->_loop) - complete = duration == 0 || (trackLastWrapped > MathUtil::fmod(entry->_trackTime, duration)); - else - complete = animationTime >= animationEnd && entry->_animationLast < animationEnd; - if (complete) _queue->complete(entry); + // Queue complete if completed a loop iteration or the animation. + bool complete = false; + if (entry->_loop) + complete = duration == 0 || (trackLastWrapped > MathUtil::fmod(entry->_trackTime, duration)); + else + complete = animationTime >= animationEnd && entry->_animationLast < animationEnd; + if (complete) _queue->complete(entry); - // Queue events after complete. - for (; i < n; ++i) { - Event *e = _events[i]; - if (e->_time < animationStart) continue; // Discard events outside animation start/end. - _queue->event(entry, _events[i]); - } + // Queue events after complete. + for (; i < n; ++i) { + Event *e = _events[i]; + if (e->_time < animationStart) continue; // Discard events outside animation start/end. + _queue->event(entry, _events[i]); + } } void AnimationState::setCurrent(size_t index, TrackEntry *current, bool interrupt) { - TrackEntry *from = expandToIndex(index); - _tracks[index] = current; + TrackEntry *from = expandToIndex(index); + _tracks[index] = current; - if (from != NULL) { - if (interrupt) _queue->interrupt(from); + if (from != NULL) { + if (interrupt) _queue->interrupt(from); - current->_mixingFrom = from; - from->_mixingTo = current; - current->_mixTime = 0; + current->_mixingFrom = from; + from->_mixingTo = current; + current->_mixTime = 0; - // Store interrupted mix percentage. - if (from->_mixingFrom != NULL && from->_mixDuration > 0) { - current->_interruptAlpha *= MathUtil::min(1.0f, from->_mixTime / from->_mixDuration); - } + // Store interrupted mix percentage. + if (from->_mixingFrom != NULL && from->_mixDuration > 0) { + current->_interruptAlpha *= MathUtil::min(1.0f, from->_mixTime / from->_mixDuration); + } - from->_timelinesRotation.clear(); // Reset rotation for mixing out, in case entry was mixed in. - } + from->_timelinesRotation.clear(); // Reset rotation for mixing out, in case entry was mixed in. + } - _queue->start(current); // triggers animationsChanged + _queue->start(current); // triggers animationsChanged } TrackEntry *AnimationState::expandToIndex(size_t index) { - if (index < _tracks.size()) return _tracks[index]; - while (index >= _tracks.size()) - _tracks.add(NULL); - return NULL; + if (index < _tracks.size()) return _tracks[index]; + while (index >= _tracks.size()) + _tracks.add(NULL); + return NULL; } TrackEntry *AnimationState::newTrackEntry(size_t trackIndex, Animation *animation, bool loop, TrackEntry *last) { - TrackEntry *entryP = _trackEntryPool.obtain(); // Pooling - TrackEntry &entry = *entryP; + TrackEntry *entryP = _trackEntryPool.obtain(); // Pooling + TrackEntry &entry = *entryP; - entry._trackIndex = trackIndex; - entry._animation = animation; - entry._loop = loop; - entry._holdPrevious = 0; + entry._trackIndex = trackIndex; + entry._animation = animation; + entry._loop = loop; + entry._holdPrevious = 0; - entry._eventThreshold = 0; - entry._attachmentThreshold = 0; - entry._drawOrderThreshold = 0; + entry._eventThreshold = 0; + entry._attachmentThreshold = 0; + entry._drawOrderThreshold = 0; - entry._animationStart = 0; - entry._animationEnd = animation->getDuration(); - entry._animationLast = -1; - entry._nextAnimationLast = -1; + entry._animationStart = 0; + entry._animationEnd = animation->getDuration(); + entry._animationLast = -1; + entry._nextAnimationLast = -1; - entry._delay = 0; - entry._trackTime = 0; - entry._trackLast = -1; - entry._nextTrackLast = -1; // nextTrackLast == -1 signifies a TrackEntry that wasn't applied yet. - entry._trackEnd = FLT_MAX; // loop ? float.MaxValue : animation.Duration; - entry._timeScale = 1; + entry._delay = 0; + entry._trackTime = 0; + entry._trackLast = -1; + entry._nextTrackLast = -1; // nextTrackLast == -1 signifies a TrackEntry that wasn't applied yet. + entry._trackEnd = FLT_MAX; // loop ? float.MaxValue : animation.Duration; + entry._timeScale = 1; - entry._alpha = 1; - entry._interruptAlpha = 1; - entry._mixTime = 0; - entry._mixDuration = (last == NULL) ? 0 : _data->getMix(last->_animation, animation); + entry._alpha = 1; + entry._interruptAlpha = 1; + entry._mixTime = 0; + entry._mixDuration = (last == NULL) ? 0 : _data->getMix(last->_animation, animation); - return entryP; + return entryP; } void AnimationState::disposeNext(TrackEntry *entry) { - TrackEntry *next = entry->_next; - while (next != NULL) { - _queue->dispose(next); - next = next->_next; - } - entry->_next = NULL; + TrackEntry *next = entry->_next; + while (next != NULL) { + _queue->dispose(next); + next = next->_next; + } + entry->_next = NULL; } void AnimationState::animationsChanged() { - _animationsChanged = false; + _animationsChanged = false; - _propertyIDs.clear(); + _propertyIDs.clear(); - for (size_t i = 0, n = _tracks.size(); i < n; ++i) { - TrackEntry *entry = _tracks[i]; - if (!entry) continue; + for (size_t i = 0, n = _tracks.size(); i < n; ++i) { + TrackEntry *entry = _tracks[i]; + if (!entry) continue; - while (entry->_mixingFrom != NULL) - entry = entry->_mixingFrom; + while (entry->_mixingFrom != NULL) + entry = entry->_mixingFrom; - do { - if (entry->_mixingTo == NULL || entry->_mixBlend != MixBlend_Add) computeHold(entry); - entry = entry->_mixingTo; - } while (entry != NULL); - } + do { + if (entry->_mixingTo == NULL || entry->_mixBlend != MixBlend_Add) computeHold(entry); + entry = entry->_mixingTo; + } while (entry != NULL); + } - _propertyIDs.clear(); - for (int i = (int)_tracks.size() - 1; i >= 0; i--) { - TrackEntry *entry = _tracks[i]; - while (entry) { - computeNotLast(entry); - entry = entry->_mixingFrom; - } - } + _propertyIDs.clear(); + for (int i = (int)_tracks.size() - 1; i >= 0; i--) { + TrackEntry *entry = _tracks[i]; + while (entry) { + computeNotLast(entry); + entry = entry->_mixingFrom; + } + } } void AnimationState::computeHold(TrackEntry *entry) { - TrackEntry* to = entry->_mixingTo; - Vector &timelines = entry->_animation->_timelines; - size_t timelinesCount = timelines.size(); - Vector &timelineMode = entry->_timelineMode; - timelineMode.setSize(timelinesCount, 0); - Vector &timelineHoldMix = entry->_timelineHoldMix; - timelineHoldMix.setSize(timelinesCount, 0); + TrackEntry * to = entry->_mixingTo; + Vector &timelines = entry->_animation->_timelines; + size_t timelinesCount = timelines.size(); + Vector & timelineMode = entry->_timelineMode; + timelineMode.setSize(timelinesCount, 0); + Vector &timelineHoldMix = entry->_timelineHoldMix; + timelineHoldMix.setSize(timelinesCount, 0); - if (to != NULL && to->_holdPrevious) { - for (size_t i = 0; i < timelinesCount; i++) { - int id = timelines[i]->getPropertyId(); - if (!_propertyIDs.containsKey(id)) _propertyIDs.put(id, true); - timelineMode[i] = Hold; - } - return; - } + if (to != NULL && to->_holdPrevious) { + for (size_t i = 0; i < timelinesCount; i++) { + int id = timelines[i]->getPropertyId(); + if (!_propertyIDs.containsKey(id)) _propertyIDs.put(id, true); + timelineMode[i] = Hold; + } + return; + } - // outer: - size_t i = 0; - continue_outer: - for (; i < timelinesCount; ++i) { - Timeline *timeline = timelines[i]; - int id = timeline->getPropertyId(); - if (_propertyIDs.containsKey(id)) { - timelineMode[i] = Subsequent; - } else { - _propertyIDs.put(id, true); + // outer: + size_t i = 0; +continue_outer: + for (; i < timelinesCount; ++i) { + Timeline *timeline = timelines[i]; + int id = timeline->getPropertyId(); + if (_propertyIDs.containsKey(id)) { + timelineMode[i] = Subsequent; + } else { + _propertyIDs.put(id, true); - if (to == NULL || timeline->getRTTI().isExactly(AttachmentTimeline::rtti) || - timeline->getRTTI().isExactly(DrawOrderTimeline::rtti) || - timeline->getRTTI().isExactly(EventTimeline::rtti) || !to->_animation->hasTimeline(id)) { - timelineMode[i] = First; - } else { - for (TrackEntry *next = to->_mixingTo; next != NULL; next = next->_mixingTo) { - if (next->_animation->hasTimeline(id)) continue; - if (entry->_mixDuration > 0) { - timelineMode[i] = HoldMix; - timelineHoldMix[i] = entry; - i++; - goto continue_outer; // continue outer; - } - break; - } - timelineMode[i] = Hold; - } - } - } + if (to == NULL || timeline->getRTTI().isExactly(AttachmentTimeline::rtti) || + timeline->getRTTI().isExactly(DrawOrderTimeline::rtti) || + timeline->getRTTI().isExactly(EventTimeline::rtti) || !to->_animation->hasTimeline(id)) { + timelineMode[i] = First; + } else { + for (TrackEntry *next = to->_mixingTo; next != NULL; next = next->_mixingTo) { + if (next->_animation->hasTimeline(id)) continue; + if (entry->_mixDuration > 0) { + timelineMode[i] = HoldMix; + timelineHoldMix[i] = entry; + i++; + goto continue_outer; // continue outer; + } + break; + } + timelineMode[i] = Hold; + } + } + } } void AnimationState::computeNotLast(TrackEntry *entry) { - Vector &timelines = entry->_animation->_timelines; - size_t timelinesCount = timelines.size(); - Vector &timelineMode = entry->_timelineMode; + Vector &timelines = entry->_animation->_timelines; + size_t timelinesCount = timelines.size(); + Vector & timelineMode = entry->_timelineMode; - for (size_t i = 0; i < timelinesCount; i++) { - if (timelines[i]->getRTTI().isExactly(AttachmentTimeline::rtti)) { - AttachmentTimeline *timeline = static_cast(timelines[i]); - if (!_propertyIDs.containsKey(timeline->getSlotIndex())) - _propertyIDs.put(timeline->getSlotIndex(), true); - else - timelineMode[i] |= NotLast; - } - } + for (size_t i = 0; i < timelinesCount; i++) { + if (timelines[i]->getRTTI().isExactly(AttachmentTimeline::rtti)) { + AttachmentTimeline *timeline = static_cast(timelines[i]); + if (!_propertyIDs.containsKey(timeline->getSlotIndex())) + _propertyIDs.put(timeline->getSlotIndex(), true); + else + timelineMode[i] |= NotLast; + } + } } diff --git a/native/cocos/platform/Image.cpp b/native/cocos/platform/Image.cpp index 7e3001e0c1..f748b2607f 100644 --- a/native/cocos/platform/Image.cpp +++ b/native/cocos/platform/Image.cpp @@ -252,7 +252,7 @@ void pngReadCallback(png_structp pngPtr, png_bytep data, png_size_t length) { if (static_cast(isource->offset + length) <= isource->size) { memcpy(data, isource->data + isource->offset, length); - isource->offset += length; + isource->offset += static_cast(length); } else { png_error(pngPtr, "pngReaderCallback failed"); } @@ -744,9 +744,9 @@ bool Image::initWithPVRv2Data(const unsigned char *data, ssize_t dataLen) { _renderFormat = it->second; //Get size of mipmap - _width = CC_SWAP_INT32_LITTLE_TO_HOST(header->width); - _height = CC_SWAP_INT32_LITTLE_TO_HOST(header->height); - _isCompressed = true; + _width = CC_SWAP_INT32_LITTLE_TO_HOST(header->width); + _height = CC_SWAP_INT32_LITTLE_TO_HOST(header->height); + _isCompressed = true; //Move by size of header _dataLen = dataLen - sizeof(PVRv2TexHeader); diff --git a/native/cocos/platform/android/Application-android.cpp b/native/cocos/platform/android/Application-android.cpp index 8662aab259..1c7a2f0763 100644 --- a/native/cocos/platform/android/Application-android.cpp +++ b/native/cocos/platform/android/Application-android.cpp @@ -66,10 +66,10 @@ bool setCanvasCallback(se::Object * /*global*/) { ss << "window.innerWidth = " << static_cast(viewLogicalSize.x) << ";"; ss << "window.innerHeight = " << static_cast(viewLogicalSize.y) << ";"; ss << "window.windowHandler = "; - if constexpr (sizeof(windowPtr) == 8) { // use bigint + if (sizeof(windowPtr) == 8) { // use bigint ss << static_cast(windowPtr) << "n;"; } - if constexpr (sizeof(windowPtr) == 4) { + if (sizeof(windowPtr) == 4) { ss << static_cast(windowPtr) << ";"; } } diff --git a/native/cocos/platform/ios/Application-ios.mm b/native/cocos/platform/ios/Application-ios.mm index a5f4578ce6..f8fd9f26f2 100644 --- a/native/cocos/platform/ios/Application-ios.mm +++ b/native/cocos/platform/ios/Application-ios.mm @@ -108,10 +108,10 @@ bool setCanvasCallback(se::Object *global) { << "; window.nativeWidth= " << nativeWidth << "; window.nativeHeight = " << nativeHeight << "; window.windowHandler = "; - if constexpr (sizeof(windowHandle) == 8) { // use bigint + if (sizeof(windowHandle) == 8) { // use bigint ss << static_cast(windowHandle) << "n;"; } - if constexpr (sizeof(windowHandle) == 4) { + if (sizeof(windowHandle) == 4) { ss << static_cast(windowHandle) << ";"; } } diff --git a/native/cocos/platform/mac/Application-mac.mm b/native/cocos/platform/mac/Application-mac.mm index c25de6f65b..be0328593d 100644 --- a/native/cocos/platform/mac/Application-mac.mm +++ b/native/cocos/platform/mac/Application-mac.mm @@ -108,10 +108,10 @@ bool setCanvasCallback(se::Object *global) { << "; window.innerHeight = " << viewLogicalSize.y << "; window.windowHandler = "; - if constexpr (sizeof(windowPtr) == 8) { // use bigint + if (sizeof(windowPtr) == 8) { // use bigint ss << static_cast(windowPtr) << "n;"; } - if constexpr (sizeof(windowPtr) == 4) { + if (sizeof(windowPtr) == 4) { ss << static_cast(windowPtr) << ";"; } } diff --git a/native/cocos/platform/ohos/Application-ohos.cpp b/native/cocos/platform/ohos/Application-ohos.cpp index 0a721748bb..78d7bc88f4 100644 --- a/native/cocos/platform/ohos/Application-ohos.cpp +++ b/native/cocos/platform/ohos/Application-ohos.cpp @@ -56,10 +56,10 @@ bool setCanvasCallback(se::Object *global) { //NOLINT ss << "window.innerWidth = " << static_cast(viewLogicalSize.x) << ";" << "window.innerHeight = " << static_cast(viewLogicalSize.y) << ";" << "window.windowHandler = "; - if constexpr (sizeof(windowPtr) == 8) { // use bigint + if (sizeof(windowPtr) == 8) { // use bigint ss << static_cast(windowPtr) << "n;"; } - if constexpr (sizeof(windowPtr) == 4) { + if (sizeof(windowPtr) == 4) { ss << static_cast(windowPtr) << ";"; } } diff --git a/native/cocos/platform/win32/FileUtils-win32.cpp b/native/cocos/platform/win32/FileUtils-win32.cpp index eb8f8e599f..b6847a7505 100644 --- a/native/cocos/platform/win32/FileUtils-win32.cpp +++ b/native/cocos/platform/win32/FileUtils-win32.cpp @@ -28,12 +28,12 @@ #if CC_PLATFORM == CC_PLATFORM_WINDOWS #include "platform/win32/FileUtils-win32.h" - #include "platform/win32/Utils-win32.h" - #include "base/Log.h" #include #include #include #include + #include "base/Log.h" + #include "platform/win32/Utils-win32.h" using namespace std; @@ -48,8 +48,8 @@ static std::string s_resourcePath = ""; // D:\aaa\bbb\ccc\ddd\abc.txt --> D:/aaa/bbb/ccc/ddd/abc.txt static inline std::string convertPathFormatToUnixStyle(const std::string &path) { std::string ret = path; - int len = ret.length(); - for (int i = 0; i < len; ++i) { + size_t len = ret.length(); + for (size_t i = 0; i < len; ++i) { if (ret[i] == '\\') { ret[i] = '/'; } @@ -67,7 +67,7 @@ static void _checkPath() { WCHAR *pUtf16DirEnd = wcsrchr(pUtf16ExePath, L'\\'); char utf8ExeDir[CC_MAX_PATH] = {0}; - int nNum = WideCharToMultiByte(CP_UTF8, 0, pUtf16ExePath, pUtf16DirEnd - pUtf16ExePath + 1, utf8ExeDir, sizeof(utf8ExeDir), nullptr, nullptr); + int nNum = WideCharToMultiByte(CP_UTF8, 0, pUtf16ExePath, static_cast(pUtf16DirEnd - pUtf16ExePath + 1), utf8ExeDir, sizeof(utf8ExeDir), nullptr, nullptr); s_resourcePath = convertPathFormatToUnixStyle(utf8ExeDir); } @@ -114,7 +114,7 @@ long FileUtilsWin32::getFileSize(const std::string &filepath) { } LARGE_INTEGER size; size.HighPart = fad.nFileSizeHigh; - size.LowPart = fad.nFileSizeLow; + size.LowPart = fad.nFileSizeLow; return (long)size.QuadPart; } @@ -153,7 +153,7 @@ FileUtils::Status FileUtilsWin32::getContents(const std::string &filename, Resiz return FileUtils::Status::OPEN_FAILED; DWORD hi; - auto size = ::GetFileSize(fileHandle, &hi); + auto size = ::GetFileSize(fileHandle, &hi); if (hi > 0) { ::CloseHandle(fileHandle); return FileUtils::Status::TOO_LARGE; @@ -165,8 +165,8 @@ FileUtils::Status FileUtilsWin32::getContents(const std::string &filename, Resiz } buffer->resize(size); - DWORD sizeRead = 0; - BOOL successed = ::ReadFile(fileHandle, buffer->buffer(), size, &sizeRead, nullptr); + DWORD sizeRead = 0; + BOOL successed = ::ReadFile(fileHandle, buffer->buffer(), size, &sizeRead, nullptr); ::CloseHandle(fileHandle); if (!successed) { @@ -178,7 +178,7 @@ FileUtils::Status FileUtilsWin32::getContents(const std::string &filename, Resiz } std::string FileUtilsWin32::getPathForFilename(const std::string &filename, const std::string &searchPath) const { - std::string unixFileName = convertPathFormatToUnixStyle(filename); + std::string unixFileName = convertPathFormatToUnixStyle(filename); std::string unixSearchPath = convertPathFormatToUnixStyle(searchPath); return FileUtils::getPathForFilename(unixFileName, unixSearchPath); @@ -186,7 +186,7 @@ std::string FileUtilsWin32::getPathForFilename(const std::string &filename, cons std::string FileUtilsWin32::getFullPathForDirectoryAndFilename(const std::string &strDirectory, const std::string &strFilename) const { std::string unixDirectory = convertPathFormatToUnixStyle(strDirectory); - std::string unixFilename = convertPathFormatToUnixStyle(strFilename); + std::string unixFilename = convertPathFormatToUnixStyle(strFilename); return FileUtils::getFullPathForDirectoryAndFilename(unixDirectory, unixFilename); } @@ -203,7 +203,7 @@ string FileUtilsWin32::getWritablePath() const { // Debug app uses executable directory; Non-debug app uses local app data directory //#ifndef _DEBUG // Get filename of executable only, e.g. MyGame.exe - WCHAR *base_name = wcsrchr(full_path, '\\'); + WCHAR * base_name = wcsrchr(full_path, '\\'); wstring retPath; if (base_name) { WCHAR app_data_path[CC_MAX_PATH + 1]; @@ -265,7 +265,7 @@ bool FileUtilsWin32::renameFile(const std::string &path, const std::string &oldn std::string oldPath = path + oldname; std::string newPath = path + name; - std::regex pat("\\/"); + std::regex pat("\\/"); std::string _old = std::regex_replace(oldPath, pat, "\\"); std::string _new = std::regex_replace(newPath, pat, "\\"); @@ -281,9 +281,9 @@ bool FileUtilsWin32::createDirectory(const std::string &dirPath) { std::wstring path = StringUtf8ToWideChar(dirPath); // Split the path - size_t start = 0; - size_t found = path.find_first_of(L"/\\", start); - std::wstring subpath; + size_t start = 0; + size_t found = path.find_first_of(L"/\\", start); + std::wstring subpath; std::vector dirs; if (found != std::wstring::npos) { @@ -321,7 +321,7 @@ bool FileUtilsWin32::createDirectory(const std::string &dirPath) { } bool FileUtilsWin32::removeFile(const std::string &filepath) { - std::regex pat("\\/"); + std::regex pat("\\/"); std::string win32path = std::regex_replace(filepath, pat, "\\"); if (DeleteFile(StringUtf8ToWideChar(win32path).c_str())) { @@ -333,11 +333,11 @@ bool FileUtilsWin32::removeFile(const std::string &filepath) { } bool FileUtilsWin32::removeDirectory(const std::string &dirPath) { - std::wstring wpath = StringUtf8ToWideChar(dirPath); - std::wstring files = wpath + L"*.*"; + std::wstring wpath = StringUtf8ToWideChar(dirPath); + std::wstring files = wpath + L"*.*"; WIN32_FIND_DATA wfd; - HANDLE search = FindFirstFileEx(files.c_str(), FindExInfoStandard, &wfd, FindExSearchNameMatch, NULL, 0); - bool ret = true; + HANDLE search = FindFirstFileEx(files.c_str(), FindExInfoStandard, &wfd, FindExSearchNameMatch, NULL, 0); + bool ret = true; if (search != INVALID_HANDLE_VALUE) { BOOL find = true; while (find) { diff --git a/native/cocos/renderer/gfx-agent/CommandBufferAgent.cpp b/native/cocos/renderer/gfx-agent/CommandBufferAgent.cpp index 25d170cd82..722dbb1ed7 100644 --- a/native/cocos/renderer/gfx-agent/CommandBufferAgent.cpp +++ b/native/cocos/renderer/gfx-agent/CommandBufferAgent.cpp @@ -82,14 +82,17 @@ CommandBufferAgent::~CommandBufferAgent() { void CommandBufferAgent::initMessageQueue() { DeviceAgent *device = DeviceAgent::getInstance(); device->_cmdBuffRefs.insert(this); + // TODO(PatriceJiang): replace with: _messageQueue = CC_NEW(MessageQueue); + _messageQueue = _CC_NEW_T_ALIGN(MessageQueue, alignof(MessageQueue)); - _messageQueue = CC_NEW(MessageQueue); if (device->_multithreaded) _messageQueue->setImmediateMode(false); } void CommandBufferAgent::destroyMessageQueue() { DeviceAgent::getInstance()->getMessageQueue()->kickAndWait(); - CC_SAFE_DELETE(_messageQueue); + // TODO(PatriceJiang): replace with: CC_SAFE_DELETE(_messageQueue); + _CC_DELETE_T_ALIGN(_messageQueue, MessageQueue, alignof(MessageQueue)); + _messageQueue = nullptr; DeviceAgent::getInstance()->_cmdBuffRefs.erase(this); } @@ -380,7 +383,8 @@ void CommandBufferAgent::copyBuffersToTexture(const uint8_t *const *buffers, Tex totalSize += size * region.texSubres.layerCount; } - auto *allocator = CC_NEW(ThreadSafeLinearAllocator(totalSize)); + // TODO(PatriceJiang): in C++17 replace with: auto *allocator = CC_NEW(ThreadSafeLinearAllocator(totalSize)); + auto *allocator = _CC_NEW_T_ALIGN_ARGS(ThreadSafeLinearAllocator, alignof(ThreadSafeLinearAllocator), totalSize); auto *actorRegions = allocator->allocate(count); memcpy(actorRegions, regions, count * sizeof(BufferTextureCopy)); @@ -407,7 +411,9 @@ void CommandBufferAgent::copyBuffersToTexture(const uint8_t *const *buffers, Tex allocator, allocator, { actor->copyBuffersToTexture(buffers, dst, regions, count); - CC_DELETE(allocator); + // TODO(PatriceJiang): C++17 replace with: CC_DELETE(allocator); + _CC_DELETE_T_ALIGN(allocator, ThreadSafeLinearAllocator, alignof(ThreadSafeLinearAllocator)); + allocator = nullptr; }); } diff --git a/native/cocos/renderer/gfx-agent/DeviceAgent.cpp b/native/cocos/renderer/gfx-agent/DeviceAgent.cpp index 0421554d5f..65f7e8805a 100644 --- a/native/cocos/renderer/gfx-agent/DeviceAgent.cpp +++ b/native/cocos/renderer/gfx-agent/DeviceAgent.cpp @@ -23,6 +23,7 @@ THE SOFTWARE. ****************************************************************************/ +#include #include "base/CoreStd.h" #include "base/threading/MessageQueue.h" @@ -76,7 +77,9 @@ bool DeviceAgent::doInit(const DeviceInfo &info) { _caps = _actor->_caps; memcpy(_features.data(), _actor->_features.data(), static_cast(Feature::COUNT) * sizeof(bool)); - _mainMessageQueue = CC_NEW(MessageQueue); + // NOTE: C++17 is required when enable alignment + // TODO(PatriceJiang): replace with: _mainMessageQueue = CC_NEW(MessageQueue); + _mainMessageQueue = _CC_NEW_T_ALIGN(MessageQueue, alignof(MessageQueue)); //NOLINT static_cast(_cmdBuff)->initMessageQueue(); @@ -106,7 +109,11 @@ void DeviceAgent::doDestroy() { } _mainMessageQueue->terminateConsumerThread(); - CC_SAFE_DELETE(_mainMessageQueue); + + // NOTE: C++17 required when enable alignment + // TODO(PatriceJiang): replace with: CC_SAFE_DELETE(_mainMessageQueue); + _CC_DELETE_T_ALIGN(_mainMessageQueue, MessageQueue, alignof(MessageQueue)); // NOLINT + _mainMessageQueue = nullptr; } void DeviceAgent::resize(uint width, uint height) { @@ -287,7 +294,8 @@ void DeviceAgent::copyBuffersToTexture(const uint8_t *const *buffers, Texture *d totalSize += size * region.texSubres.layerCount; } - auto *allocator = CC_NEW(ThreadSafeLinearAllocator(totalSize)); + //TODO(PatriceJiang): in C++17 replace with:*allocator = CC_NEW(ThreadSafeLinearAllocator(totalSize)); + auto *allocator = _CC_NEW_T_ALIGN_ARGS(ThreadSafeLinearAllocator, alignof(ThreadSafeLinearAllocator), totalSize); auto *actorRegions = allocator->allocate(count); memcpy(actorRegions, regions, count * sizeof(BufferTextureCopy)); @@ -314,7 +322,9 @@ void DeviceAgent::copyBuffersToTexture(const uint8_t *const *buffers, Texture *d allocator, allocator, { actor->copyBuffersToTexture(buffers, dst, regions, count); - CC_DELETE(allocator); + // TODO(PatriceJiang): C++17 replace with: CC_DELETE(allocator); + _CC_DELETE_T_ALIGN(allocator, ThreadSafeLinearAllocator, alignof(ThreadSafeLinearAllocator)); + allocator = nullptr; }); } diff --git a/native/cocos/renderer/gfx-base/GFXDevice.cpp b/native/cocos/renderer/gfx-base/GFXDevice.cpp index cace521ade..c9bb23adab 100644 --- a/native/cocos/renderer/gfx-base/GFXDevice.cpp +++ b/native/cocos/renderer/gfx-base/GFXDevice.cpp @@ -77,8 +77,10 @@ void Device::destroy() { _bindingMappingInfo.bufferOffsets.clear(); _bindingMappingInfo.samplerOffsets.clear(); - _width = _height = _windowHandle = 0U; - _pixelRatio = 1.0F; + _width = 0; + _height = 0; + _windowHandle = 0; + _pixelRatio = 1.0F; } } // namespace gfx diff --git a/native/cocos/renderer/gfx-base/GFXRenderPass.cpp b/native/cocos/renderer/gfx-base/GFXRenderPass.cpp index 0a8abe55d3..52a2cae9ef 100644 --- a/native/cocos/renderer/gfx-base/GFXRenderPass.cpp +++ b/native/cocos/renderer/gfx-base/GFXRenderPass.cpp @@ -126,26 +126,26 @@ uint RenderPass::computeHash(const RenderPassInfo &info) { for (const uint iaIndex : subPass.inputs) { if (iaIndex >= info.colorAttachments.size()) break; const ColorAttachment &ia = info.colorAttachments[iaIndex]; - seed += 4 + ia.beginAccesses.size() + ia.endAccesses.size(); + seed += static_cast(4 + ia.beginAccesses.size() + ia.endAccesses.size()); } for (const uint caIndex : subPass.colors) { if (caIndex >= info.colorAttachments.size()) break; const ColorAttachment &ca = info.colorAttachments[caIndex]; - seed += 4 + ca.beginAccesses.size() + ca.endAccesses.size(); + seed += static_cast(4 + ca.beginAccesses.size() + ca.endAccesses.size()); } for (const uint raIndex : subPass.resolves) { if (raIndex >= info.colorAttachments.size()) break; const ColorAttachment &ra = info.colorAttachments[raIndex]; - seed += 4 + ra.beginAccesses.size() + ra.endAccesses.size(); + seed += static_cast(4 + ra.beginAccesses.size() + ra.endAccesses.size()); } for (const uint paIndex : subPass.preserves) { if (paIndex >= info.colorAttachments.size()) break; const ColorAttachment &pa = info.colorAttachments[paIndex]; - seed += 4 + pa.beginAccesses.size() + pa.endAccesses.size(); + seed += static_cast(4 + pa.beginAccesses.size() + pa.endAccesses.size()); } if (subPass.depthStencil < info.colorAttachments.size()) { const ColorAttachment &ds = info.colorAttachments[subPass.depthStencil]; - seed += 4 + ds.beginAccesses.size() + ds.endAccesses.size(); + seed += static_cast(4 + ds.beginAccesses.size() + ds.endAccesses.size()); } } for (const SubpassInfo &subpass : info.subpasses) { @@ -171,9 +171,9 @@ uint RenderPass::computeHash(const RenderPassInfo &info) { } } else { for (const ColorAttachment &ca : info.colorAttachments) { - seed += 4 + ca.beginAccesses.size() + ca.endAccesses.size(); + seed += static_cast(4 + ca.beginAccesses.size() + ca.endAccesses.size()); } - seed += 6 + info.depthStencilAttachment.beginAccesses.size() + info.depthStencilAttachment.endAccesses.size(); + seed += static_cast(6 + info.depthStencilAttachment.beginAccesses.size() + info.depthStencilAttachment.endAccesses.size()); for (const ColorAttachment &ca : info.colorAttachments) { computeAttachmentHash(ca, seed); diff --git a/native/cocos/renderer/gfx-gles2/GLES2Commands.cpp b/native/cocos/renderer/gfx-gles2/GLES2Commands.cpp index bce176d555..3b7cb676f6 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Commands.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2Commands.cpp @@ -1002,7 +1002,8 @@ void cmdFuncGLES2CreateShader(GLES2Device *device, GLES2GPUShader *gpuShader) { // fallback subpassInputs into samplerTextures if not using FBF or PLS if (device->constantRegistry()->mFBF == FBFSupportLevel::NONE) { for (const auto &subpassInput : gpuShader->subpassInputs) { - auto &samplerTexture = gpuShader->samplerTextures.emplace_back(); + gpuShader->samplerTextures.emplace_back(UniformSamplerTexture()); + auto &samplerTexture = *gpuShader->samplerTextures.rbegin(); samplerTexture.name = subpassInput.name; samplerTexture.set = subpassInput.set; samplerTexture.binding = subpassInput.binding; @@ -1056,7 +1057,8 @@ void cmdFuncGLES2CreateShader(GLES2Device *device, GLES2GPUShader *gpuShader) { glUniform.count = glSize; glUniform.size = glUniform.stride * glUniform.count; - auto &activeUniform = glBlock.glActiveUniforms.emplace_back(glUniform); + glBlock.glActiveUniforms.emplace_back(GLES2GPUUniform()); + auto &activeUniform = *glBlock.glActiveUniforms.rbegin(); activeUniform.buff.resize(activeUniform.size); glBlock.activeUniformIndices.push_back(i); break; @@ -1375,7 +1377,9 @@ void cmdFuncGLES2CreateFramebuffer(GLES2Device *device, GLES2GPUFramebuffer *gpu doCreateFramebufferInstance(device, gpuFBO, gpuFBO->uberColorAttachmentIndices, gpuFBO->gpuColorTextures.size(), &gpuFBO->uberInstance); } else { for (const auto &subpass : gpuFBO->gpuRenderPass->subpasses) { - doCreateFramebufferInstance(device, gpuFBO, subpass.colors, subpass.depthStencil, &gpuFBO->instances.emplace_back(), + gpuFBO->instances.emplace_back(GLES2GPUFramebuffer::GLFramebuffer()); + auto &fboInst = *gpuFBO->instances.rbegin(); + doCreateFramebufferInstance(device, gpuFBO, subpass.colors, subpass.depthStencil, &fboInst, subpass.resolves.empty() ? nullptr : subpass.resolves.data(), subpass.depthStencilResolve); } } @@ -1713,6 +1717,7 @@ void cmdFuncGLES2EndRenderPass(GLES2Device *device) { } } +// NOLINTNEXTLINE void cmdFuncGLES2BindState(GLES2Device *device, GLES2GPUPipelineState *gpuPipelineState, GLES2GPUInputAssembler *gpuInputAssembler, const GLES2GPUDescriptorSet *const *gpuDescriptorSets, const uint *dynamicOffsets, const DynamicStates *dynamicStates) { diff --git a/native/cocos/renderer/gfx-gles2/GLES2RenderPass.cpp b/native/cocos/renderer/gfx-gles2/GLES2RenderPass.cpp index d6a1efe173..b87628fc32 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2RenderPass.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2RenderPass.cpp @@ -47,7 +47,8 @@ void GLES2RenderPass::doInit(const RenderPassInfo & /*info*/) { // assign a dummy subpass if not specified if (_gpuRenderPass->subpasses.empty()) { - auto &subpass = _gpuRenderPass->subpasses.emplace_back(); + _gpuRenderPass->subpasses.emplace_back(SubpassInfo()); + auto &subpass = *_gpuRenderPass->subpasses.rbegin(); subpass.colors.resize(_colorAttachments.size()); for (uint i = 0U; i < _colorAttachments.size(); ++i) { subpass.colors[i] = i; diff --git a/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp b/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp index e192a03261..a83991b92e 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp @@ -185,7 +185,7 @@ GLenum mapGLFormat(Format format) { case Format::RGB32F: case Format::R11G11B10F: case Format::R5G6B5: - case Format::RGB9E5: + case Format::RGB9E5: case Format::SRGB8: return GL_RGB; case Format::RGBA8: case Format::RGBA8SN: @@ -1140,7 +1140,7 @@ void cmdFuncGLES3DestroySampler(GLES3Device *device, GLES3GPUSampler *gpuSampler } } -void cmdFuncGLES3CreateShader(GLES3Device *device, GLES3GPUShader *gpuShader) { +void cmdFuncGLES3CreateShader(GLES3Device *device, GLES3GPUShader *gpuShader) { // NOLINT(google-readability-function-size,readability-function-size) GLenum glShaderStage = 0; String shaderStageStr; GLint status; @@ -1332,7 +1332,8 @@ void cmdFuncGLES3CreateShader(GLES3Device *device, GLES3GPUShader *gpuShader) { if (device->constantRegistry()->mFBF == FBFSupportLevel::NONE && device->constantRegistry()->mPLS == PLSSupportLevel::NONE) { for (const auto &subpassInput : gpuShader->subpassInputs) { - auto &samplerTexture = gpuShader->samplerTextures.emplace_back(); + gpuShader->samplerTextures.emplace_back(UniformSamplerTexture()); + auto &samplerTexture = *gpuShader->samplerTextures.rbegin(); samplerTexture.name = subpassInput.name; samplerTexture.set = subpassInput.set; samplerTexture.binding = subpassInput.binding; @@ -1587,7 +1588,7 @@ static GLuint doCreateFramebuffer(GLES3Device * device, if (depthStencilResolve) *resolveMask |= hasStencil ? GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT : GL_DEPTH_BUFFER_BIT; } - GL_CHECK(glDrawBuffers(drawBuffers.size(), drawBuffers.data())); + GL_CHECK(glDrawBuffers(static_cast(drawBuffers.size()), drawBuffers.data())); GLenum status; GL_CHECK(status = glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER)); @@ -1641,10 +1642,10 @@ static void doCreateFramebufferInstance(GLES3Device *device, GLES3GPUFramebuffer } if (offscreenCount || depthStencilTexture) { - outFBO->glFramebuffer = doCreateFramebuffer(device, gpuFBO->gpuColorTextures, colors.data(), colors.size(), + outFBO->glFramebuffer = doCreateFramebuffer(device, gpuFBO->gpuColorTextures, colors.data(), static_cast(colors.size()), depthStencilTexture, resolves, depthStencilResolveTexture, &outFBO->resolveMask); if (outFBO->resolveMask) { - uint resolveCount = outFBO->resolveMask & GL_COLOR_BUFFER_BIT ? colors.size() : 0U; + uint resolveCount = outFBO->resolveMask & GL_COLOR_BUFFER_BIT ? static_cast(colors.size()) : 0U; outFBO->glResolveFramebuffer = doCreateFramebuffer(device, gpuFBO->gpuColorTextures, resolves, resolveCount, depthStencilResolveTexture); } } else { @@ -1668,10 +1669,12 @@ void cmdFuncGLES3CreateFramebuffer(GLES3Device *device, GLES3GPUFramebuffer *gpu if (GFX_FORMAT_INFOS[toNumber(gpuTexture->format)].hasDepth) continue; gpuFBO->uberColorAttachmentIndices.push_back(i); } - doCreateFramebufferInstance(device, gpuFBO, gpuFBO->uberColorAttachmentIndices, gpuFBO->gpuColorTextures.size(), &gpuFBO->uberInstance); + doCreateFramebufferInstance(device, gpuFBO, gpuFBO->uberColorAttachmentIndices, static_cast(gpuFBO->gpuColorTextures.size()), &gpuFBO->uberInstance); } else { for (const auto &subpass : gpuFBO->gpuRenderPass->subpasses) { - doCreateFramebufferInstance(device, gpuFBO, subpass.colors, subpass.depthStencil, &gpuFBO->instances.emplace_back(), + gpuFBO->instances.emplace_back(GLES3GPUFramebuffer::GLFramebuffer()); + auto &fboInst = *gpuFBO->instances.rbegin(); + doCreateFramebufferInstance(device, gpuFBO, subpass.colors, subpass.depthStencil, &fboInst, subpass.resolves.empty() ? nullptr : subpass.resolves.data(), subpass.depthStencilResolve); } } @@ -1842,7 +1845,7 @@ void cmdFuncGLES3BeginRenderPass(GLES3Device *device, uint subpassIdx, GLES3GPUR } if (!invalidAttachments.empty()) { - GL_CHECK(glInvalidateFramebuffer(GL_DRAW_FRAMEBUFFER, invalidAttachments.size(), invalidAttachments.data())); + GL_CHECK(glInvalidateFramebuffer(GL_DRAW_FRAMEBUFFER, static_cast(invalidAttachments.size()), invalidAttachments.data())); } if (glClears) { @@ -1946,7 +1949,7 @@ void cmdFuncGLES3EndRenderPass(GLES3Device *device) { } } if (!invalidAttachments.empty()) { - GL_CHECK(glInvalidateFramebuffer(invalidateTarget, invalidAttachments.size(), invalidAttachments.data())); + GL_CHECK(glInvalidateFramebuffer(invalidateTarget, static_cast(invalidAttachments.size()), invalidAttachments.data())); } }; @@ -2026,6 +2029,7 @@ void cmdFuncGLES3EndRenderPass(GLES3Device *device) { } } +// NOLINTNEXTLINE void cmdFuncGLES3BindState(GLES3Device *device, GLES3GPUPipelineState *gpuPipelineState, GLES3GPUInputAssembler *gpuInputAssembler, const GLES3GPUDescriptorSet *const *gpuDescriptorSets, const uint *dynamicOffsets, const DynamicStates *dynamicStates) { GLES3ObjectCache &gfxStateCache = device->stateCache()->gfxStateCache; diff --git a/native/cocos/renderer/gfx-gles3/GLES3Device.cpp b/native/cocos/renderer/gfx-gles3/GLES3Device.cpp index a7ed159278..43dd22d46a 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Device.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Device.cpp @@ -302,7 +302,7 @@ void GLES3Device::bindRenderContext(bool bound) { _context = bound ? _renderContext : nullptr; if (bound) { - _gpuConstantRegistry->currentBoundThreadID = std::hash{}(std::this_thread::get_id()); + _gpuConstantRegistry->currentBoundThreadID = static_cast(std::hash{}(std::this_thread::get_id())); _gpuStateCache->reset(); } } @@ -320,7 +320,7 @@ void GLES3Device::bindDeviceContext(bool bound) { _context = bound ? _deviceContext : nullptr; if (bound) { - _gpuConstantRegistry->currentBoundThreadID = std::hash{}(std::this_thread::get_id()); + _gpuConstantRegistry->currentBoundThreadID = static_cast(std::hash{}(std::this_thread::get_id())); _gpuStateCache->reset(); } } @@ -391,7 +391,7 @@ void GLES3Device::copyBuffersToTexture(const uint8_t *const *buffers, Texture *d } void GLES3Device::copyTextureToBuffers(Texture *srcTexture, uint8_t *const *buffers, const BufferTextureCopy *regions, uint count) { - cmdFuncGLES3CopyTextureToBuffers(this, srcTexture ? static_cast(srcTexture)->gpuTexture() : nullptr, buffers, regions, count); + cmdFuncGLES3CopyTextureToBuffers(this, srcTexture ? static_cast(srcTexture)->gpuTexture() : nullptr, buffers, regions, count); } } // namespace gfx diff --git a/native/cocos/renderer/gfx-gles3/GLES3PipelineLayout.cpp b/native/cocos/renderer/gfx-gles3/GLES3PipelineLayout.cpp index 16b8b47c6f..7985f35655 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3PipelineLayout.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3PipelineLayout.cpp @@ -43,7 +43,7 @@ GLES3PipelineLayout::~GLES3PipelineLayout() { void GLES3PipelineLayout::doInit(const PipelineLayoutInfo & /*info*/) { _gpuPipelineLayout = CC_NEW(GLES3GPUPipelineLayout); - uint offset = 0U; + size_t offset = 0; _gpuPipelineLayout->dynamicOffsetIndices.resize(_setLayouts.size()); for (uint i = 0U; i < _setLayouts.size(); i++) { DescriptorSetLayout * setLayout = _setLayouts[i]; @@ -54,14 +54,14 @@ void GLES3PipelineLayout::doInit(const PipelineLayoutInfo & /*info*/) { for (uint j = 0U; j < dynamicCount; j++) { uint binding = gpuSetLayout->dynamicBindings[j]; - if (indices[binding] < 0) indices[binding] = offset + j; + if (indices[binding] < 0) indices[binding] = static_cast(offset + j); } - _gpuPipelineLayout->dynamicOffsetOffsets.push_back(offset); + _gpuPipelineLayout->dynamicOffsetOffsets.push_back(static_cast(offset)); _gpuPipelineLayout->setLayouts.push_back(gpuSetLayout); offset += dynamicCount; } - _gpuPipelineLayout->dynamicOffsetOffsets.push_back(offset); - _gpuPipelineLayout->dynamicOffsetCount = offset; + _gpuPipelineLayout->dynamicOffsetOffsets.push_back(static_cast(offset)); + _gpuPipelineLayout->dynamicOffsetCount = static_cast(offset); _gpuPipelineLayout->dynamicOffsets.resize(offset); } diff --git a/native/cocos/renderer/gfx-gles3/GLES3RenderPass.cpp b/native/cocos/renderer/gfx-gles3/GLES3RenderPass.cpp index 17a6828940..53949a152e 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3RenderPass.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3RenderPass.cpp @@ -47,12 +47,13 @@ void GLES3RenderPass::doInit(const RenderPassInfo & /*info*/) { // assign a dummy subpass if not specified if (_gpuRenderPass->subpasses.empty()) { - auto &subpass = _gpuRenderPass->subpasses.emplace_back(); + _gpuRenderPass->subpasses.emplace_back(SubpassInfo()); + auto &subpass = *_gpuRenderPass->subpasses.rbegin(); subpass.colors.resize(_colorAttachments.size()); for (uint i = 0U; i < _colorAttachments.size(); ++i) { subpass.colors[i] = i; } - subpass.depthStencil = _colorAttachments.size(); + subpass.depthStencil = static_cast(_colorAttachments.size()); } else { // the depth stencil attachment is the default fallback // when none are specified in subpass diff --git a/native/cocos/renderer/gfx-validator/ValidationUtils.cpp b/native/cocos/renderer/gfx-validator/ValidationUtils.cpp index 47955b577d..62e76cfffd 100644 --- a/native/cocos/renderer/gfx-validator/ValidationUtils.cpp +++ b/native/cocos/renderer/gfx-validator/ValidationUtils.cpp @@ -43,7 +43,8 @@ String getStacktraceJS() { namespace gfx { void CommandRecorder::recordBeginRenderPass(const RenderPassSnapshot &renderPass) { - RenderPassCommand &command = _renderPassCommands.emplace_back(); + _renderPassCommands.emplace_back(RenderPassCommand()); + RenderPassCommand &command = *_renderPassCommands.rbegin(); command.renderArea = renderPass.renderArea; command.clearColors = renderPass.clearColors; command.clearDepth = renderPass.clearDepth; @@ -56,7 +57,8 @@ void CommandRecorder::recordBeginRenderPass(const RenderPassSnapshot &renderPass } void CommandRecorder::recordDrawcall(const DrawcallSnapshot &drawcall) { - DrawcallCommand &command = _drawcallCommands.emplace_back(); + _drawcallCommands.emplace_back(DrawcallCommand()); + DrawcallCommand &command = *_drawcallCommands.rbegin(); command.inputState = drawcall.pipelineState->getInputState(); command.rasterizerState = drawcall.pipelineState->getRasterizerState(); command.depthStencilState = drawcall.pipelineState->getDepthStencilState(); diff --git a/native/cocos/renderer/gfx-vulkan/VKCommands.cpp b/native/cocos/renderer/gfx-vulkan/VKCommands.cpp index 40b70d1033..5a6acc5efa 100644 --- a/native/cocos/renderer/gfx-vulkan/VKCommands.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKCommands.cpp @@ -234,7 +234,7 @@ void cmdFuncCCVKCreateBuffer(CCVKDevice *device, CCVKGPUBuffer *gpuBuffer) { //gpuBuffer->instanceSize = roundUp(gpuBuffer->size, device->getCapabilities().uboOffsetAlignment); //bufferInfo.size = gpuBuffer->instanceSize * device->gpuDevice()->backBufferCount; //allocInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT; - allocInfo.usage = VMA_MEMORY_USAGE_CPU_TO_GPU; + allocInfo.usage = VMA_MEMORY_USAGE_CPU_TO_GPU; bufferInfo.usage |= VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT; } @@ -1472,7 +1472,8 @@ void CCVKGPUBarrierManager::update(CCVKGPUTransportHub *transportHub) { VkPipelineStageFlags tempSrcStageMask = 0; VkPipelineStageFlags tempDstStageMask = 0; - thsvsGetVulkanImageMemoryBarrier(imageBarrier, &tempSrcStageMask, &tempDstStageMask, &vkImageBarriers.emplace_back()); + vkImageBarriers.emplace_back(VkImageMemoryBarrier()); + thsvsGetVulkanImageMemoryBarrier(imageBarrier, &tempSrcStageMask, &tempDstStageMask, &(*vkImageBarriers.rbegin())); srcStageMask |= tempSrcStageMask; dstStageMask |= tempDstStageMask; diff --git a/native/cocos/renderer/gfx-vulkan/VKRenderPass.cpp b/native/cocos/renderer/gfx-vulkan/VKRenderPass.cpp index c46d1de95a..e21c40e2da 100644 --- a/native/cocos/renderer/gfx-vulkan/VKRenderPass.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKRenderPass.cpp @@ -50,7 +50,8 @@ void CCVKRenderPass::doInit(const RenderPassInfo & /*info*/) { // when none are specified in subpass const bool hasDepth = _depthStencilAttachment.format != Format::UNKNOWN; if (_gpuRenderPass->subpasses.empty()) { - auto &subpass = _gpuRenderPass->subpasses.emplace_back(); + _gpuRenderPass->subpasses.emplace_back(SubpassInfo()); + auto &subpass = *_gpuRenderPass->subpasses.rbegin(); subpass.colors.resize(_colorAttachments.size()); for (uint i = 0U; i < _colorAttachments.size(); ++i) { subpass.colors[i] = i; diff --git a/native/cocos/renderer/gfx-vulkan/VKSPIRV.cpp b/native/cocos/renderer/gfx-vulkan/VKSPIRV.cpp new file mode 100644 index 0000000000..de76beddf9 --- /dev/null +++ b/native/cocos/renderer/gfx-vulkan/VKSPIRV.cpp @@ -0,0 +1,34 @@ +/**************************************************************************** + Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + 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 "renderer/gfx-vulkan/VKSPIRV.h" + +namespace cc { +namespace gfx { + +bool glslangInitialized = false; + +} // namespace gfx +} // namespace cc diff --git a/native/cocos/renderer/gfx-vulkan/VKSPIRV.h b/native/cocos/renderer/gfx-vulkan/VKSPIRV.h index 22503b678b..d845afb284 100644 --- a/native/cocos/renderer/gfx-vulkan/VKSPIRV.h +++ b/native/cocos/renderer/gfx-vulkan/VKSPIRV.h @@ -28,9 +28,9 @@ #include "base/Log.h" #include "gfx-base/GFXDef.h" -#include "glslang/StandAlone/ResourceLimits.h" #include "glslang/Public/ShaderLang.h" #include "glslang/SPIRV/GlslangToSpv.h" +#include "glslang/StandAlone/ResourceLimits.h" namespace cc { namespace gfx { @@ -74,7 +74,7 @@ inline glslang::EShTargetLanguageVersion getTargetVersion(int vulkanMinorVersion } } -inline bool glslangInitialized = false; +extern bool glslangInitialized; inline vector glsl2spirv(ShaderStageFlagBit type, const String &source, int vulkanMinorVersion = 0) { if (!glslangInitialized) { diff --git a/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.cpp b/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.cpp index 8677156c60..f1f27149ab 100644 --- a/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.cpp +++ b/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.cpp @@ -31,6 +31,7 @@ #include "RenderAdditiveLightQueue.h" #include "Define.h" +#include "GlobalDescriptorSetManager.h" #include "RenderBatchedQueue.h" #include "RenderInstancedQueue.h" #include "SceneCulling.h" @@ -44,7 +45,6 @@ #include "gfx-base/GFXTexture.h" #include "scene/RenderScene.h" #include "scene/Sphere.h" -#include "GlobalDescriptorSetManager.h" namespace cc { namespace pipeline { @@ -63,7 +63,7 @@ RenderAdditiveLightQueue::RenderAdditiveLightQueue(RenderPipeline *pipeline) : _ _lightBufferStride, }); _firstLightBufferView = device->createBuffer({_lightBuffer, 0, UBOForwardLight::SIZE}); - _lightBufferData.resize(_lightBufferElementCount * _lightBufferCount); + _lightBufferData.resize(static_cast(_lightBufferElementCount) * _lightBufferCount); _dynamicOffsets.resize(1, 0); _phaseID = getPhaseID("forward-add"); _shadowUBO.fill(0.F); @@ -237,16 +237,17 @@ void RenderAdditiveLightQueue::updateUBOs(const scene::Camera *camera, gfx::Comm const auto validLightCount = _validLights.size(); auto *const sceneData = _pipeline->getPipelineSceneData(); auto *const sharedData = sceneData->getSharedData(); + size_t offset = 0; if (validLightCount > _lightBufferCount) { _firstLightBufferView->destroy(); _lightBufferCount = nextPow2(static_cast(validLightCount)); - _lightBuffer->resize(_lightBufferStride * _lightBufferCount); - _lightBufferData.resize(_lightBufferElementCount * _lightBufferCount); + _lightBuffer->resize(static_cast(_lightBufferStride * _lightBufferCount)); + _lightBufferData.resize(static_cast(_lightBufferElementCount) * _lightBufferCount); _firstLightBufferView->initialize({_lightBuffer, 0, UBOForwardLight::SIZE}); } - for (unsigned l = 0, offset = 0; l < validLightCount; l++, offset += _lightBufferElementCount) { + for (unsigned l = 0; l < validLightCount; l++, offset += _lightBufferElementCount) { auto * light = _validLights[l]; const bool isSpotLight = scene::LightType::SPOT == light->getType(); const auto *spotLight = isSpotLight ? static_cast(light) : nullptr; @@ -306,14 +307,14 @@ void RenderAdditiveLightQueue::updateUBOs(const scene::Camera *camera, gfx::Comm } void RenderAdditiveLightQueue::updateLightDescriptorSet(const scene::Camera *camera, gfx::CommandBuffer *cmdBuffer) { - auto *const sceneData = _pipeline->getPipelineSceneData(); - auto * shadowInfo = sceneData->getSharedData()->shadow; - const auto *const scene = camera->scene; - auto * device = gfx::Device::getInstance(); - const bool hFTexture = supportsHalfFloatTexture(device); - const float linear = 0.0F; - const float packing = hFTexture ? 0.0F : 1.0F; - const scene::Light *mainLight = scene->getMainLight(); + auto *const sceneData = _pipeline->getPipelineSceneData(); + auto * shadowInfo = sceneData->getSharedData()->shadow; + const auto *const scene = camera->scene; + auto * device = gfx::Device::getInstance(); + const bool hFTexture = supportsHalfFloatTexture(device); + const float linear = 0.0F; + const float packing = hFTexture ? 0.0F : 1.0F; + const scene::Light *mainLight = scene->getMainLight(); for (uint i = 0; i < _validLights.size(); ++i) { const auto *light = _validLights[i]; @@ -351,7 +352,7 @@ void RenderAdditiveLightQueue::updateLightDescriptorSet(const scene::Camera *cam cc::Mat4 matShadowProj; cc::Mat4::createPerspective(spotLight->getSpotAngle(), spotLight->getAspect(), 0.001F, spotLight->getRange(), &matShadowProj); cc::Mat4 matShadowViewProj = matShadowProj; - cc::Mat4 matShadowInvProj = matShadowProj; + cc::Mat4 matShadowInvProj = matShadowProj; matShadowInvProj.inverse(); matShadowViewProj.multiply(matShadowView); @@ -435,7 +436,7 @@ void RenderAdditiveLightQueue::lightCulling(const scene::Model *model) { break; } if (!isCulled) { - _lightIndices.emplace_back(i); + _lightIndices.emplace_back(static_cast(i)); } } } diff --git a/native/cocos/renderer/pipeline/deferred/GbufferStage.cpp b/native/cocos/renderer/pipeline/deferred/GbufferStage.cpp index 12857954fb..5f511752ff 100644 --- a/native/cocos/renderer/pipeline/deferred/GbufferStage.cpp +++ b/native/cocos/renderer/pipeline/deferred/GbufferStage.cpp @@ -155,8 +155,8 @@ void GbufferStage::render(scene::Camera *camera) { cmdBuff->beginRenderPass(renderPass, framebuffer, _renderArea, _clearColors, camera->clearDepth, camera->clearStencil); - uint const globalOffsets[] = {_pipeline->getPipelineUBO()->getCurrentCameraUBOOffset()}; - cmdBuff->bindDescriptorSet(globalSet, _pipeline->getDescriptorSet(), static_cast(std::size(globalOffsets)), globalOffsets); + const std::array globalOffsets = {_pipeline->getPipelineUBO()->getCurrentCameraUBOOffset()}; + cmdBuff->bindDescriptorSet(globalSet, _pipeline->getDescriptorSet(), static_cast(globalOffsets.size()), globalOffsets.data()); _renderQueues[0]->recordCommandBuffer(_device, renderPass, cmdBuff); _instancedQueue->recordCommandBuffer(_device, renderPass, cmdBuff); diff --git a/native/cocos/renderer/pipeline/deferred/LightingStage.cpp b/native/cocos/renderer/pipeline/deferred/LightingStage.cpp index 6bc9266dfc..820c4d1123 100644 --- a/native/cocos/renderer/pipeline/deferred/LightingStage.cpp +++ b/native/cocos/renderer/pipeline/deferred/LightingStage.cpp @@ -222,7 +222,7 @@ void LightingStage::initLightingBuffer() { auto *const device = _pipeline->getDevice(); // color/pos/dir/angle 都是vec4存储, 最后一个vec4只要x存储光源个数 - uint stride = utils::alignTo(sizeof(Vec4) * 4, device->getCapabilities().uboOffsetAlignment); + uint stride = utils::alignTo(sizeof(Vec4) * 4, device->getCapabilities().uboOffsetAlignment); uint totalSize = stride * _maxDeferredLights; // create lighting buffer and view @@ -356,8 +356,8 @@ void LightingStage::render(scene::Camera *camera) { cmdBuff->beginRenderPass(renderPass, frameBuffer, renderArea, &clearColor, camera->clearDepth, camera->clearStencil); - uint const globalOffsets[] = {_pipeline->getPipelineUBO()->getCurrentCameraUBOOffset()}; - cmdBuff->bindDescriptorSet(globalSet, pipeline->getDescriptorSet(), static_cast(std::size(globalOffsets)), globalOffsets); + const std::array globalOffsets = {_pipeline->getPipelineUBO()->getCurrentCameraUBOOffset()}; + cmdBuff->bindDescriptorSet(globalSet, pipeline->getDescriptorSet(), static_cast(globalOffsets.size()), globalOffsets.data()); // get pso and draw quad scene::Pass *pass = sceneData->getSharedData()->deferredLightPass; gfx::Shader *shader = sceneData->getSharedData()->deferredLightPassShader; diff --git a/native/cocos/renderer/pipeline/deferred/PostprocessStage.cpp b/native/cocos/renderer/pipeline/deferred/PostprocessStage.cpp index 9cd14cf472..cbe15f84f9 100644 --- a/native/cocos/renderer/pipeline/deferred/PostprocessStage.cpp +++ b/native/cocos/renderer/pipeline/deferred/PostprocessStage.cpp @@ -103,8 +103,8 @@ void PostprocessStage::render(scene::Camera *camera) { gfx::RenderPass * rp = !colorTextures.empty() && colorTextures[0] ? fb->getRenderPass() : pp->getOrCreateRenderPass(static_cast(camera->clearFlag)); cmdBf->beginRenderPass(rp, fb, renderArea, _clearColors, camera->clearDepth, camera->clearStencil); - uint const globalOffsets[] = {_pipeline->getPipelineUBO()->getCurrentCameraUBOOffset()}; - cmdBf->bindDescriptorSet(globalSet, pp->getDescriptorSet(), static_cast(std::size(globalOffsets)), globalOffsets); + const std::array globalOffsets = {_pipeline->getPipelineUBO()->getCurrentCameraUBOOffset()}; + cmdBf->bindDescriptorSet(globalSet, pp->getDescriptorSet(), static_cast(globalOffsets.size()), globalOffsets.data()); // post proces auto *const sceneData = _pipeline->getPipelineSceneData(); diff --git a/native/cocos/renderer/pipeline/forward/ForwardStage.cpp b/native/cocos/renderer/pipeline/forward/ForwardStage.cpp index b36a22ebc4..69c51bcf11 100644 --- a/native/cocos/renderer/pipeline/forward/ForwardStage.cpp +++ b/native/cocos/renderer/pipeline/forward/ForwardStage.cpp @@ -117,15 +117,15 @@ void ForwardStage::render(scene::Camera *camera) { uint passIdx = 0; size_t k = 0; for (auto ro : renderObjects) { - const auto *const model = ro.model; - const auto& subModels = model->getSubModels(); - auto subModelCount = subModels.size(); + const auto *const model = ro.model; + const auto & subModels = model->getSubModels(); + auto subModelCount = subModels.size(); for (subModelIdx = 0; subModelIdx < subModelCount; ++subModelIdx) { - const auto& subModel = subModels[subModelIdx]; - const auto& passes = subModel->getPasses(); - auto passCount = passes.size(); + const auto &subModel = subModels[subModelIdx]; + const auto &passes = subModel->getPasses(); + auto passCount = passes.size(); for (passIdx = 0; passIdx < passCount; ++passIdx) { - const auto& pass = passes[passIdx]; + const auto &pass = passes[passIdx]; if (pass->getPhase() != _phaseID) continue; if (pass->getBatchingScheme() == scene::BatchingSchemes::INSTANCING) { auto *instancedBuffer = InstancedBuffer::get(pass); @@ -143,7 +143,7 @@ void ForwardStage::render(scene::Camera *camera) { } } } - + for (auto *queue : _renderQueues) { queue->sort(); } @@ -186,8 +186,8 @@ void ForwardStage::render(scene::Camera *camera) { cmdBuff->beginRenderPass(renderPass, framebuffer, _renderArea, _clearColors, camera->clearDepth, camera->clearStencil); - uint const globalOffsets[] = {_pipeline->getPipelineUBO()->getCurrentCameraUBOOffset()}; - cmdBuff->bindDescriptorSet(globalSet, _pipeline->getDescriptorSet(), static_cast(std::size(globalOffsets)), globalOffsets); + const std::array globalOffsets = {_pipeline->getPipelineUBO()->getCurrentCameraUBOOffset()}; + cmdBuff->bindDescriptorSet(globalSet, _pipeline->getDescriptorSet(), static_cast(globalOffsets.size()), globalOffsets.data()); _renderQueues[0]->recordCommandBuffer(_device, renderPass, cmdBuff); _instancedQueue->recordCommandBuffer(_device, renderPass, cmdBuff); diff --git a/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp b/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp index f444a0cc6e..2e1e9a5568 100644 --- a/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp +++ b/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp @@ -34,7 +34,8 @@ #include "gfx-base/GFXRenderPass.h" #include "gfx-base/GFXTexture.h" -namespace cc::pipeline { +namespace cc { +namespace pipeline { std::unordered_map ShadowFlow::renderPassHashMap; RenderFlowInfo ShadowFlow::initInfo = { @@ -175,7 +176,7 @@ void ShadowFlow::initShadowFrameBuffer(RenderPipeline *pipeline, const scene::Li const auto width = static_cast(shadowMapSize.x); const auto height = static_cast(shadowMapSize.y); const auto format = supportsHalfFloatTexture(device) ? gfx::Format::R32F : gfx::Format::RGBA8; - + const gfx::ColorAttachment colorAttachment = { format, gfx::SampleCount::X1, @@ -256,4 +257,5 @@ void ShadowFlow::destroy() { RenderFlow::destroy(); } -} // namespace cc::pipeline +} // namespace pipeline +} // namespace cc diff --git a/native/cocos/renderer/pipeline/shadow/ShadowStage.cpp b/native/cocos/renderer/pipeline/shadow/ShadowStage.cpp index f406752028..a8a16f391c 100644 --- a/native/cocos/renderer/pipeline/shadow/ShadowStage.cpp +++ b/native/cocos/renderer/pipeline/shadow/ShadowStage.cpp @@ -81,8 +81,8 @@ void ShadowStage::render(scene::Camera *camera) { cmdBuffer->beginRenderPass(renderPass, _framebuffer, _renderArea, _clearColors, camera->clearDepth, camera->clearStencil); - uint const globalOffsets[] = {_pipeline->getPipelineUBO()->getCurrentCameraUBOOffset()}; - cmdBuffer->bindDescriptorSet(globalSet, _pipeline->getDescriptorSet(), static_cast(std::size(globalOffsets)), globalOffsets); + const std::array globalOffsets = {_pipeline->getPipelineUBO()->getCurrentCameraUBOOffset()}; + cmdBuffer->bindDescriptorSet(globalSet, _pipeline->getDescriptorSet(), static_cast(globalOffsets.size()), globalOffsets.data()); _additiveShadowQueue->recordCommandBuffer(_device, renderPass, cmdBuffer); cmdBuffer->endRenderPass(); diff --git a/native/cocos/scene/Sphere.cpp b/native/cocos/scene/Sphere.cpp index 057826022c..fd70a75f73 100644 --- a/native/cocos/scene/Sphere.cpp +++ b/native/cocos/scene/Sphere.cpp @@ -23,8 +23,8 @@ THE SOFTWARE. ****************************************************************************/ -#include #include "scene/Sphere.h" +#include #include "base/TypeDef.h" namespace cc { @@ -60,8 +60,9 @@ void Sphere::merge(const Vec3 &point) { return; } - Vec3 offset = point - _center; - if (const float distance = offset.length(); distance > _radius) { + Vec3 offset = point - _center; + const float distance = offset.length(); + if (distance > _radius) { const float half = (distance - _radius) * 0.5F; _radius += half; offset.scale(half / distance); diff --git a/native/templates/common/CMakeLists.txt b/native/templates/common/CMakeLists.txt index 93d31ca8dc..7bdafdc0aa 100755 --- a/native/templates/common/CMakeLists.txt +++ b/native/templates/common/CMakeLists.txt @@ -6,7 +6,7 @@ set(RES_DIR "" CACHE STRING "Resource path") set(COCOS_X_PATH "" CACHE STRING "Path to cocos2d-x-lite/") set(TARGET_OSX_VERSION "10.14" CACHE STRING "Target MacOSX version" FORCE) -set(TARGET_IOS_VERSION "12.0" CACHE STRING "Target iOS version" FORCE) +set(TARGET_IOS_VERSION "10.0" CACHE STRING "Target iOS version" FORCE) set(CMAKE_CXX_STANDARD 14) option(USE_SE_V8 "Use V8 JavaScript Engine" ON) From 3e28c2821af882aa0a161beca51f485ef87e9a28 Mon Sep 17 00:00:00 2001 From: Zeqiang Li Date: Wed, 15 Sep 2021 16:03:12 +0800 Subject: [PATCH 05/11] api min required -> ios 10.0 (#3885) * ios 10 alignas * ios 10 api --- native/cocos/base/memory/Memory.h | 9 +++++++++ native/cocos/base/threading/MessageQueue.h | 9 +++++---- native/cocos/base/threading/ThreadSafeLinearAllocator.h | 3 ++- native/cocos/renderer/gfx-metal/MTLCommandBuffer.mm | 4 +++- native/cocos/renderer/gfx-metal/MTLUtils.h | 4 +++- native/cocos/renderer/gfx-metal/MTLUtils.mm | 1 + 6 files changed, 23 insertions(+), 7 deletions(-) diff --git a/native/cocos/base/memory/Memory.h b/native/cocos/base/memory/Memory.h index cee4b7ff2c..dcc5a03e18 100755 --- a/native/cocos/base/memory/Memory.h +++ b/native/cocos/base/memory/Memory.h @@ -29,6 +29,9 @@ #include "MemDef.h" #include "MemTracker.h" #include "StlAlloc.h" +#if (CC_PLATFORM == CC_PLATFORM_MAC_IOS) +#include +#endif // Global Interface Definitions @@ -145,3 +148,9 @@ inline void *operator new(size_t sz) { return BareNewErroneouslyCalled(sz); } inline void operator delete(void *ptr) throw() { free(ptr); } #endif #endif + +#if (CC_PLATFORM == CC_PLATFORM_MAC_IOS) && (__IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_11_0) +#define ALIGNAS(x) +#else +#define ALIGNAS(x) alignas(x) +#endif diff --git a/native/cocos/base/threading/MessageQueue.h b/native/cocos/base/threading/MessageQueue.h index 63df31ffa9..dca33283fb 100644 --- a/native/cocos/base/threading/MessageQueue.h +++ b/native/cocos/base/threading/MessageQueue.h @@ -28,6 +28,7 @@ #include #include "Event.h" #include "concurrentqueue/concurrentqueue.h" +#include "../memory/Memory.h" namespace cc { @@ -65,7 +66,7 @@ private: friend class MessageQueue; }; -struct alignas(64) WriterContext final { +struct ALIGNAS(64) WriterContext final { uint8_t * currentMemoryChunk{nullptr}; Message * lastMessage{nullptr}; uint32_t offset{0}; @@ -73,7 +74,7 @@ struct alignas(64) WriterContext final { std::atomic writtenMessageCount{0}; }; -struct alignas(64) ReaderContext final { +struct ALIGNAS(64) ReaderContext final { uint8_t *currentMemoryChunk{nullptr}; Message *lastMessage{nullptr}; uint32_t offset{0}; @@ -85,7 +86,7 @@ struct alignas(64) ReaderContext final { // A single-producer single-consumer circular buffer queue. // Both the messages and their submitting data should be allocated from here. -class alignas(64) MessageQueue final { +class ALIGNAS(64) MessageQueue final { public: static constexpr uint32_t MEMORY_CHUNK_SIZE = 4096 * 16; @@ -132,7 +133,7 @@ public: inline uint32_t getNewMessageCount() const noexcept { return _reader.newMessageCount; } private: - class alignas(64) MemoryAllocator final { + class ALIGNAS(64) MemoryAllocator final { public: MemoryAllocator() = default; ~MemoryAllocator() = default; diff --git a/native/cocos/base/threading/ThreadSafeLinearAllocator.h b/native/cocos/base/threading/ThreadSafeLinearAllocator.h index c9ab659933..a045ab27f9 100644 --- a/native/cocos/base/threading/ThreadSafeLinearAllocator.h +++ b/native/cocos/base/threading/ThreadSafeLinearAllocator.h @@ -28,10 +28,11 @@ #include #include #include +#include "../memory/Memory.h" namespace cc { -class alignas(16) ThreadSafeLinearAllocator final { +class ALIGNAS(16) ThreadSafeLinearAllocator final { public: explicit ThreadSafeLinearAllocator(uint32_t size) noexcept; ~ThreadSafeLinearAllocator(); diff --git a/native/cocos/renderer/gfx-metal/MTLCommandBuffer.mm b/native/cocos/renderer/gfx-metal/MTLCommandBuffer.mm index d6634f26b4..3f965a6d1e 100644 --- a/native/cocos/renderer/gfx-metal/MTLCommandBuffer.mm +++ b/native/cocos/renderer/gfx-metal/MTLCommandBuffer.mm @@ -290,7 +290,9 @@ void CCMTLCommandBuffer::updateDepthStencilState(uint32_t index, MTLRenderPassDe descriptor.stencilAttachment.storeAction = subpass.stencilResolveMode == ResolveMode::NONE ? MTLStoreActionMultisampleResolve : MTLStoreActionStoreAndMultisampleResolve; descriptor.depthAttachment.depthResolveFilter = mu::toMTLDepthResolveMode(subpass.depthResolveMode); - descriptor.stencilAttachment.stencilResolveFilter = mu::toMTLStencilResolveMode(subpass.stencilResolveMode); + if (@available(iOS 12.0, *)) { + descriptor.stencilAttachment.stencilResolveFilter = mu::toMTLStencilResolveMode(subpass.stencilResolveMode); + } } } } diff --git a/native/cocos/renderer/gfx-metal/MTLUtils.h b/native/cocos/renderer/gfx-metal/MTLUtils.h index a3e0ce725d..dbe8577a92 100644 --- a/native/cocos/renderer/gfx-metal/MTLUtils.h +++ b/native/cocos/renderer/gfx-metal/MTLUtils.h @@ -39,6 +39,9 @@ namespace gfx { class CCMTLGPUShader; class CCMTLDevice; namespace mu { + +API_AVAILABLE(ios(12.0)) MTLMultisampleStencilResolveFilter toMTLStencilResolveMode(ResolveMode mode); + MTLResourceOptions toMTLResourceOption(MemoryUsage usage); MTLLoadAction toMTLLoadAction(LoadOp op); MTLStoreAction toMTLStoreAction(StoreOp op); @@ -47,7 +50,6 @@ MTLClearColor toMTLClearColor(const Color &clearColor); MTLVertexFormat toMTLVertexFormat(Format, bool); MTLPixelFormat toMTLPixelFormat(Format); MTLMultisampleDepthResolveFilter toMTLDepthResolveMode(ResolveMode mode); -MTLMultisampleStencilResolveFilter toMTLStencilResolveMode(ResolveMode mode); // Because some pixel format is not supported on metal, so need to convert to supported pixel format. Format convertGFXPixelFormat(Format); MTLColorWriteMask toMTLColorWriteMask(ColorMask); diff --git a/native/cocos/renderer/gfx-metal/MTLUtils.mm b/native/cocos/renderer/gfx-metal/MTLUtils.mm index 57a3b1398d..b415007449 100644 --- a/native/cocos/renderer/gfx-metal/MTLUtils.mm +++ b/native/cocos/renderer/gfx-metal/MTLUtils.mm @@ -523,6 +523,7 @@ MTLMultisampleDepthResolveFilter mu::toMTLDepthResolveMode(ResolveMode mode) { } } +API_AVAILABLE(ios(12.0)) MTLMultisampleStencilResolveFilter mu::toMTLStencilResolveMode(ResolveMode mode) { switch (mode) { case ResolveMode::SAMPLE_ZERO: From 1016f7d609b1d0963ed3345f357b6aead4f3b1cd Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Thu, 16 Sep 2021 10:23:29 +0800 Subject: [PATCH 06/11] should trigger update when set instance (#3888) --- native/cocos/renderer/pipeline/InstancedBuffer.cpp | 2 +- native/cocos/scene/Model.h | 9 +++++---- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/native/cocos/renderer/pipeline/InstancedBuffer.cpp b/native/cocos/renderer/pipeline/InstancedBuffer.cpp index 6f3a05f3ea..d458462084 100644 --- a/native/cocos/renderer/pipeline/InstancedBuffer.cpp +++ b/native/cocos/renderer/pipeline/InstancedBuffer.cpp @@ -102,7 +102,7 @@ void InstancedBuffer::merge(const scene::Model *model, const scene::SubModel *su } if (instance.stride != stride) { - return; + continue; } if (instance.count >= instance.capacity) { // resize buffers instance.capacity <<= 1; diff --git a/native/cocos/scene/Model.h b/native/cocos/scene/Model.h index ad8ffd7822..e52559e598 100644 --- a/native/cocos/scene/Model.h +++ b/native/cocos/scene/Model.h @@ -1,8 +1,8 @@ /**************************************************************************** Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. - + http://www.cocos.com - + Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated engine source code (the "Software"), a limited, worldwide, royalty-free, non-assignable, revocable and non-exclusive license @@ -10,10 +10,10 @@ not use Cocos Creator software for developing other software or tools that's used for developing games. You are not granted to publish, distribute, sublicense, and/or sell copies of Cocos Creator. - + The software or tools in this License Agreement are licensed, not sold. Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - + 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 @@ -81,6 +81,7 @@ public: _instancedBuffer = {buffer, size}; _instanceAttributeBlock = std::move(block); _instanceAttributes = attributes; + _transformUpdated = true; } inline bool getCastShadow() const { return _castShadow; } From 3b77662e8721f47abaa2544d01e3564a5c4de7da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B1=9F=E6=88=98?= <40414978+PatriceJiang@users.noreply.github.com> Date: Thu, 16 Sep 2021 18:33:51 +0800 Subject: [PATCH 07/11] fix double conversion (#3892) --- native/cocos/bindings/jswrapper/Value.cpp | 64 ++++++++++++++++------- 1 file changed, 44 insertions(+), 20 deletions(-) diff --git a/native/cocos/bindings/jswrapper/Value.cpp b/native/cocos/bindings/jswrapper/Value.cpp index 768bfbeef4..2d70118671 100644 --- a/native/cocos/bindings/jswrapper/Value.cpp +++ b/native/cocos/bindings/jswrapper/Value.cpp @@ -25,15 +25,42 @@ ****************************************************************************/ #include "Value.h" +#include +#include #include +#include #include "Object.h" namespace se { +#ifndef LIKELY + #ifdef __GNUC__ + #define LIKELY(expr) __builtin_expect(!!(expr), 1) + #else + #define LIKELY(expr) expr + #endif +#endif + +template +inline + typename std::enable_if::value, T>::type + fromDoubleToIntegral(double d) { + return static_cast(static_cast(d)); +} + +template +inline + typename std::enable_if::value, T>::type + fromDoubleToIntegral(double d) { + return static_cast(d); +} + +#define CONVERT_TO_TYPE(type) fromDoubleToIntegral(toDouble()) + ValueArray EmptyValueArray; // NOLINT(readability-identifier-naming) -Value Value::Null = Value(Type::Null); -Value Value::Undefined = Value(Type::Undefined); +Value Value::Null = Value(Type::Null); //NOLINT(readability-identifier-naming) +Value Value::Undefined = Value(Type::Undefined); //NOLINT(readability-identifier-naming) Value::Value() : _type(Type::Undefined), @@ -377,37 +404,37 @@ void Value::setObject(const HandleObject &o, bool autoRootUnroot /* = false*/) { } int8_t Value::toInt8() const { - return static_cast(toDouble()); + return CONVERT_TO_TYPE(int8_t); } uint8_t Value::toUint8() const { - return static_cast(toDouble()); + return CONVERT_TO_TYPE(uint8_t); } int16_t Value::toInt16() const { - return static_cast(toDouble()); + return CONVERT_TO_TYPE(int16_t); } uint16_t Value::toUint16() const { - return static_cast(toDouble()); + return CONVERT_TO_TYPE(uint16_t); } int32_t Value::toInt32() const { - return static_cast(toDouble()); + return CONVERT_TO_TYPE(int32_t); } uint32_t Value::toUint32() const { - return static_cast(toDouble()); + return CONVERT_TO_TYPE(uint32_t); } int64_t Value::toInt64() const { assert(isBigInt() || isNumber()); - return _type == Type::BigInt ? _u._bigint : static_cast(_u._number); + return _type == Type::BigInt ? _u._bigint : CONVERT_TO_TYPE(int64_t); } uint64_t Value::toUint64() const { assert(isBigInt() || isNumber()); - return _type == Type::BigInt ? static_cast(_u._bigint) : static_cast(_u._number); + return _type == Type::BigInt ? static_cast(_u._bigint) : CONVERT_TO_TYPE(uint64_t); } float Value::toFloat() const { @@ -416,17 +443,14 @@ float Value::toFloat() const { double Value::toDouble() const { assert(_type == Type::Number || _type == Type::Boolean || _type == Type::BigInt); - if (_type == Type::Boolean) { - if (_u._boolean) { - return 1.0; - } - return 0.0; + if(LIKELY(_type == Type::Number)) { + return _u._number; } if (_type == Type::BigInt) { // CC_LOG_WARNING("convert int64 to double"); return static_cast(_u._bigint); } - return _u._number; + return _u._boolean ? 1.0 : 0.0; } bool Value::toBoolean() const { @@ -523,15 +547,15 @@ void Value::setNumber(double v) { } unsigned int Value::toUint() const { - return static_cast(toDouble()); + return CONVERT_TO_TYPE(unsigned int); } long Value::toLong() const { // NOLINT(google-runtime-int) - return static_cast(toDouble()); // NOLINT(google-runtime-int) + return CONVERT_TO_TYPE(long); } -unsigned long Value::toUlong() const { // NOLINT(google-runtime-int) - return static_cast(toDouble()); // NOLINT(google-runtime-int) +unsigned long Value::toUlong() const { // NOLINT(google-runtime-int) + return CONVERT_TO_TYPE(unsigned long); } double Value::toNumber() const { From 7833da0210f13d39e0c7b5b22ea8688532175b98 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B1=9F=E6=88=98?= <40414978+PatriceJiang@users.noreply.github.com> Date: Wed, 22 Sep 2021 10:17:24 +0800 Subject: [PATCH 08/11] fix cmake error (#3903) --- native/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt index b3fccadd90..92caf1ba3b 100644 --- a/native/CMakeLists.txt +++ b/native/CMakeLists.txt @@ -91,7 +91,7 @@ endif() if(USE_JOB_SYSTEM_TASKFLOW) set(CMAKE_CXX_STANDARD 17) - if("${TARGET_IOS_VERSION}" VERSION_LESS "12.0") + if(IOS AND "${TARGET_IOS_VERSION}" VERSION_LESS "12.0") message(FATAL_ERROR "Target iOS version requires 12.0+ when enable taskflow") endif() endif() From 4c620f60cd2810b495561bdb64794d6af2a81910 Mon Sep 17 00:00:00 2001 From: timlyeee <43355299+timlyeee@users.noreply.github.com> Date: Wed, 22 Sep 2021 10:17:51 +0800 Subject: [PATCH 09/11] Update config.json (#3901) --- native/external/config.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/native/external/config.json b/native/external/config.json index 3d5649360f..893b7fec39 100644 --- a/native/external/config.json +++ b/native/external/config.json @@ -1,9 +1,9 @@ { - "version": "v3d-gfx-69", + "version": "v3d-gfx-75", "from": { "type": "github", "owner": "cocos-creator", "name": "engine-native-external", - "checkout": "v3d-gfx-69" + "checkout": "v3d-gfx-75" } } From c5aef2467f891b58556a204bcca110e1aa5f940c Mon Sep 17 00:00:00 2001 From: Zeqiang Li Date: Wed, 22 Sep 2021 20:49:16 +0800 Subject: [PATCH 10/11] subpass fallback (#3907) --- .../cocos/renderer/gfx-metal/MTLGPUObjects.h | 3 + native/cocos/renderer/gfx-metal/MTLShader.mm | 90 ++++++++++++++----- native/cocos/renderer/gfx-metal/MTLUtils.mm | 2 +- 3 files changed, 73 insertions(+), 22 deletions(-) diff --git a/native/cocos/renderer/gfx-metal/MTLGPUObjects.h b/native/cocos/renderer/gfx-metal/MTLGPUObjects.h index f0ce2eb359..1f9c7049a8 100644 --- a/native/cocos/renderer/gfx-metal/MTLGPUObjects.h +++ b/native/cocos/renderer/gfx-metal/MTLGPUObjects.h @@ -95,6 +95,9 @@ public: vector inputs; vector outputs; + + NSString *shaderSrc = nil; + bool specializeColor = true; }; struct CCMTLGPUPipelineState { diff --git a/native/cocos/renderer/gfx-metal/MTLShader.mm b/native/cocos/renderer/gfx-metal/MTLShader.mm index 1736fdeba7..c1769cd231 100644 --- a/native/cocos/renderer/gfx-metal/MTLShader.mm +++ b/native/cocos/renderer/gfx-metal/MTLShader.mm @@ -72,6 +72,8 @@ void CCMTLShader::doDestroy() { id cmptFunc = _cmptFunction; _cmptFunction = nil; + [_gpuShader->shaderSrc release]; + // [_specializedFragFuncs release]; const auto specFragFuncs = [_specializedFragFuncs retain]; [_specializedFragFuncs release]; @@ -79,7 +81,7 @@ void CCMTLShader::doDestroy() { CC_SAFE_DELETE(_gpuShader); std::function destroyFunc = [=]() { - if(specFragFuncs.count > 0) { + if([specFragFuncs count] > 0) { for (NSString* key in [specFragFuncs allKeys]) { [[specFragFuncs valueForKey:key] release]; } @@ -132,18 +134,35 @@ bool CCMTLShader::createMTLFunction(const ShaderStage &stage) { NSString * rawSrc = [NSString stringWithUTF8String:stage.source.c_str()]; NSString * shader = [NSString stringWithUTF8String:mtlShader.c_str()]; NSError * error = nil; - MTLCompileOptions *opts = [[MTLCompileOptions alloc] init];; - //opts.languageVersion = MTLLanguageVersion2_3; + MTLCompileOptions *opts = [[MTLCompileOptions alloc] init]; id &library = isVertexShader ? _vertLibrary : isFragmentShader ? _fragLibrary : _cmptLibrary; String shaderStage = isVertexShader ? "vertex" : isFragmentShader ? "fragment" : "compute"; - library = [mtlDevice newLibraryWithSource:shader options:opts error:&error]; - [opts release]; - if (!library) { - CC_LOG_ERROR("Can not compile %s shader: %s", shaderStage.c_str(), [[error localizedDescription] UTF8String]); - CC_LOG_ERROR("%s", stage.source.c_str()); - return false; + if(isFragmentShader) { + if(@available(iOS 11.0, *)) { + library = [mtlDevice newLibraryWithSource:shader options:opts error:&error]; + if (!library) { + CC_LOG_ERROR("Can not compile %s shader: %s", shaderStage.c_str(), [[error localizedDescription] UTF8String]); + CC_LOG_ERROR("%s", stage.source.c_str()); + return false; + } + } else { + //delayed instance and pretend tobe specialized function. + _gpuShader->specializeColor = false; + _gpuShader->shaderSrc = [shader retain]; + assert(_gpuShader->shaderSrc != nil); + return true; + } + } else { + library = [mtlDevice newLibraryWithSource:shader options:opts error:&error]; + if (!library) { + CC_LOG_ERROR("Can not compile %s shader: %s", shaderStage.c_str(), [[error localizedDescription] UTF8String]); + CC_LOG_ERROR("%s", stage.source.c_str()); + return false; + } } + + [opts release]; if (isVertexShader) { _vertFunction = [library newFunctionWithName:@"main0"]; @@ -192,22 +211,51 @@ id CCMTLShader::getSpecializedFragFunction(uint* index, int* val, u for (size_t i = 0; i < count; i++) { notEvenHash += val[i] * std::pow(10, index[i]); } - NSString *hashStr = [NSString stringWithFormat:@"%d", notEvenHash]; id specFunc = [_specializedFragFuncs objectForKey:hashStr]; + if(!specFunc) { - MTLFunctionConstantValues* constantValues = [MTLFunctionConstantValues new]; - for (size_t i = 0; i < count; i++) { - [constantValues setConstantValue:&val[i] type:MTLDataTypeInt atIndex:index[i]]; + if(_gpuShader->specializeColor) { + MTLFunctionConstantValues* constantValues = [MTLFunctionConstantValues new]; + for (size_t i = 0; i < count; i++) { + [constantValues setConstantValue:&val[i] type:MTLDataTypeInt atIndex:index[i]]; + } + + NSError * error = nil; + id specFragFunc = [_fragLibrary newFunctionWithName:@"main0" constantValues:constantValues error:&error]; + [constantValues release]; + if (!specFragFunc) { + CC_LOG_ERROR("Can not specialize shader: %s", [[error localizedDescription] UTF8String]); + } + [_specializedFragFuncs setObject:specFragFunc forKey:hashStr]; + } else { + NSString* res = nil; + for(size_t i = 0; i < count; i++) { + NSString* targetStr = [NSString stringWithFormat:@"(indexOffset%u)", static_cast(i)]; + NSString* index = [NSString stringWithFormat:@"(%u)", static_cast(i)]; + res = [_gpuShader->shaderSrc stringByReplacingOccurrencesOfString:targetStr withString:index]; + + } + id mtlDevice = id(CCMTLDevice::getInstance()->getMTLDevice()); + NSError * error = nil; + MTLCompileOptions *opts = [[MTLCompileOptions alloc] init]; + // always current + if(_fragLibrary) { + [_fragLibrary release]; + } + _fragLibrary = [mtlDevice newLibraryWithSource:res options:opts error:&error]; + if (!_fragLibrary) { + CC_LOG_ERROR("Can not compile frag shader: %s", [[error localizedDescription] UTF8String]); + } + [opts release]; + _fragFunction = [_fragLibrary newFunctionWithName:@"main0"]; + if (!_fragFunction) { + [_fragLibrary release]; + CC_LOG_ERROR("Can not create fragment function: main0"); + } + + [_specializedFragFuncs setObject:_fragFunction forKey:hashStr]; } - - NSError * error = nil; - id specFragFunc = [_fragLibrary newFunctionWithName:@"main0" constantValues:constantValues error:&error]; - [constantValues release]; - if (!specFragFunc) { - CC_LOG_ERROR("Can not specialize shader: %s", [[error localizedDescription] UTF8String]); - } - [_specializedFragFuncs setObject:specFragFunc forKey:hashStr]; } return [_specializedFragFuncs valueForKey:hashStr]; } diff --git a/native/cocos/renderer/gfx-metal/MTLUtils.mm b/native/cocos/renderer/gfx-metal/MTLUtils.mm index b415007449..4ad872326f 100644 --- a/native/cocos/renderer/gfx-metal/MTLUtils.mm +++ b/native/cocos/renderer/gfx-metal/MTLUtils.mm @@ -1140,7 +1140,7 @@ String mu::compileGLSLShader2Msl(const String &src, int32_t maxIndex = static_cast(resources.stage_outputs.size() - 1); for(int i = maxIndex; i >=0; --i) { String indexStr = std::to_string(i); - output.insert(customCodingPos, "\nconstant int indexOffset" + indexStr + " [[ function_constant(" + indexStr + ") ]];\n"); + output.insert(customCodingPos, "\nconstant int indexOffset" + indexStr + " [[function_constant(" + indexStr + ")]];\n"); output.replace(output.find("color(" + indexStr + ")"), 8, "color(indexOffset" + indexStr + ")"); } } From e14fd7350624e269f2ccbbba97382ea6208914ae Mon Sep 17 00:00:00 2001 From: minggo Date: Fri, 24 Sep 2021 14:09:30 +0800 Subject: [PATCH 11/11] fix compling error and review --- native/CMakeLists.txt | 2 - native/cocos/base/IndexHandle.h | 2 +- .../cocos/bindings/manual/jsb_global_init.cpp | 7 +- .../renderer/gfx-agent/CommandBufferAgent.cpp | 2 - native/cocos/renderer/gfx-vulkan/VKSPIRV.cpp | 34 ----- native/cocos/renderer/gfx-vulkan/VKSPIRV.h | 120 ------------------ .../renderer/pipeline/shadow/ShadowFlow.cpp | 2 +- 7 files changed, 4 insertions(+), 165 deletions(-) delete mode 100644 native/cocos/renderer/gfx-vulkan/VKSPIRV.cpp delete mode 100644 native/cocos/renderer/gfx-vulkan/VKSPIRV.h diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt index 57e5190d69..b4b5b8281d 100644 --- a/native/CMakeLists.txt +++ b/native/CMakeLists.txt @@ -1073,8 +1073,6 @@ if(CC_USE_VULKAN) cocos/renderer/gfx-vulkan/VKRenderPass.h cocos/renderer/gfx-vulkan/VKShader.cpp cocos/renderer/gfx-vulkan/VKShader.h - cocos/renderer/gfx-vulkan/VKSPIRV.h - cocos/renderer/gfx-vulkan/VKSPIRV.cpp cocos/renderer/gfx-vulkan/VKStd.cpp cocos/renderer/gfx-vulkan/VKStd.h cocos/renderer/gfx-vulkan/VKSwapchain.cpp diff --git a/native/cocos/base/IndexHandle.h b/native/cocos/base/IndexHandle.h index 66779f2eb5..ea03bbb7db 100644 --- a/native/cocos/base/IndexHandle.h +++ b/native/cocos/base/IndexHandle.h @@ -49,7 +49,7 @@ public: inline bool operator<(IndexHandle const &rhs) const noexcept; inline bool operator==(IndexHandle const &rhs) const noexcept; inline bool operator!=(IndexHandle const &rhs) const noexcept; - inline operator IndexType() const noexcept; + inline operator IndexType() const noexcept; // NOLINT(google-explicit-constructor) we need this implicitly static IndexType constexpr UNINITIALIZED{std::numeric_limits::max()}; diff --git a/native/cocos/bindings/manual/jsb_global_init.cpp b/native/cocos/bindings/manual/jsb_global_init.cpp index 9565a1e709..e246048e2e 100644 --- a/native/cocos/bindings/manual/jsb_global_init.cpp +++ b/native/cocos/bindings/manual/jsb_global_init.cpp @@ -27,10 +27,6 @@ #include "base/Macros.h" // clang-format: off #include -#if CC_PLATFORM == CC_PLATFORM_WINDOWS - // Fix ssize_t defination - #include "cocos/bindings/jswrapper/config.h" -#endif #include "uv.h" // clang-format on @@ -57,7 +53,8 @@ se::Object *__jsbObj = nullptr; //NOLINT se::Object *__glObj = nullptr; //NOLINT static std::basic_string xxteaKey; -void jsb_set_xxtea_key(const std::string &key) { //NOLINT + +void jsb_set_xxtea_key(const std::string &key) { //NOLINT xxteaKey.assign(key.begin(), key.end()); } diff --git a/native/cocos/renderer/gfx-agent/CommandBufferAgent.cpp b/native/cocos/renderer/gfx-agent/CommandBufferAgent.cpp index 5fca80dc8d..4184c4b0d4 100644 --- a/native/cocos/renderer/gfx-agent/CommandBufferAgent.cpp +++ b/native/cocos/renderer/gfx-agent/CommandBufferAgent.cpp @@ -83,8 +83,6 @@ CommandBufferAgent::~CommandBufferAgent() { void CommandBufferAgent::initMessageQueue() { DeviceAgent *device = DeviceAgent::getInstance(); device->_cmdBuffRefs.insert(this); - // TODO(PatriceJiang): replace with: _messageQueue = CC_NEW(MessageQueue); - _messageQueue = _CC_NEW_T_ALIGN(MessageQueue, alignof(MessageQueue)); // TODO(PatriceJiang): replace with: _messageQueue = CC_NEW(MessageQueue); _messageQueue = _CC_NEW_T_ALIGN(MessageQueue, alignof(MessageQueue)); diff --git a/native/cocos/renderer/gfx-vulkan/VKSPIRV.cpp b/native/cocos/renderer/gfx-vulkan/VKSPIRV.cpp deleted file mode 100644 index de76beddf9..0000000000 --- a/native/cocos/renderer/gfx-vulkan/VKSPIRV.cpp +++ /dev/null @@ -1,34 +0,0 @@ -/**************************************************************************** - Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - 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 "renderer/gfx-vulkan/VKSPIRV.h" - -namespace cc { -namespace gfx { - -bool glslangInitialized = false; - -} // namespace gfx -} // namespace cc diff --git a/native/cocos/renderer/gfx-vulkan/VKSPIRV.h b/native/cocos/renderer/gfx-vulkan/VKSPIRV.h deleted file mode 100644 index d845afb284..0000000000 --- a/native/cocos/renderer/gfx-vulkan/VKSPIRV.h +++ /dev/null @@ -1,120 +0,0 @@ -/**************************************************************************** - Copyright (c) 2020-2021 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -****************************************************************************/ - -#pragma once - -#include "base/Log.h" -#include "gfx-base/GFXDef.h" - -#include "glslang/Public/ShaderLang.h" -#include "glslang/SPIRV/GlslangToSpv.h" -#include "glslang/StandAlone/ResourceLimits.h" - -namespace cc { -namespace gfx { - -inline EShLanguage getShaderStage(ShaderStageFlagBit type) { - switch (type) { - case ShaderStageFlagBit::VERTEX: return EShLangVertex; - case ShaderStageFlagBit::CONTROL: return EShLangTessControl; - case ShaderStageFlagBit::EVALUATION: return EShLangTessEvaluation; - case ShaderStageFlagBit::GEOMETRY: return EShLangGeometry; - case ShaderStageFlagBit::FRAGMENT: return EShLangFragment; - case ShaderStageFlagBit::COMPUTE: return EShLangCompute; - default: { - CCASSERT(false, "Unsupported ShaderStageFlagBit, convert to EShLanguage failed."); - return EShLangVertex; - } - } -} - -inline glslang::EShTargetClientVersion getClientVersion(int vulkanMinorVersion) { - switch (vulkanMinorVersion) { - case 0: return glslang::EShTargetVulkan_1_0; - case 1: return glslang::EShTargetVulkan_1_1; - case 2: return glslang::EShTargetVulkan_1_2; - default: { - CCASSERT(false, "Unsupported vulkan version, convert to EShTargetClientVersion failed."); - return glslang::EShTargetVulkan_1_0; - } - } -} - -inline glslang::EShTargetLanguageVersion getTargetVersion(int vulkanMinorVersion) { - switch (vulkanMinorVersion) { - case 0: return glslang::EShTargetSpv_1_0; - case 1: return glslang::EShTargetSpv_1_3; - case 2: return glslang::EShTargetSpv_1_5; - default: { - CCASSERT(false, "Unsupported vulkan version, convert to EShTargetLanguageVersion failed."); - return glslang::EShTargetSpv_1_0; - } - } -} - -extern bool glslangInitialized; - -inline vector glsl2spirv(ShaderStageFlagBit type, const String &source, int vulkanMinorVersion = 0) { - if (!glslangInitialized) { - glslang::InitializeProcess(); - glslangInitialized = true; - } - - EShLanguage stage = getShaderStage(type); - const char * string = source.c_str(); - glslang::TShader shader(stage); - shader.setStrings(&string, 1); - - int clientInputSemanticsVersion = 100 + vulkanMinorVersion * 10; - glslang::EShTargetClientVersion clientVersion = getClientVersion(vulkanMinorVersion); - glslang::EShTargetLanguageVersion targetVersion = getTargetVersion(vulkanMinorVersion); - - shader.setEnvInput(glslang::EShSourceGlsl, stage, glslang::EShClientVulkan, clientInputSemanticsVersion); - shader.setEnvClient(glslang::EShClientVulkan, clientVersion); - shader.setEnvTarget(glslang::EShTargetSpv, targetVersion); - - auto messages = static_cast(EShMsgSpvRules | EShMsgVulkanRules); - - if (!shader.parse(&glslang::DefaultTBuiltInResource, clientInputSemanticsVersion, false, messages)) { - CC_LOG_ERROR("GLSL Parsing Failed:\n%s\n%s", shader.getInfoLog(), shader.getInfoDebugLog()); - } - - glslang::TProgram program; - program.addShader(&shader); - - if (!program.link(messages)) { - CC_LOG_ERROR("GLSL Linking Failed:\n%s\n%s", program.getInfoLog(), program.getInfoDebugLog()); - } - - vector spirv; - spv::SpvBuildLogger logger; - glslang::SpvOptions spvOptions; - glslang::GlslangToSpv(*program.getIntermediate(stage), spirv, &logger, &spvOptions); - - return spirv; -} - -} // namespace gfx -} // namespace cc diff --git a/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp b/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp index 5ef84a63ad..e43452f2bf 100644 --- a/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp +++ b/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp @@ -70,7 +70,7 @@ void ShadowFlow::render(scene::Camera *camera) { lightCollecting(camera, &_validLights); - if (sceneData->getShadowObjects().empty() && sceneData->getRenderObjects().empty()) { + if (sceneData->getDirShadowObjects().empty() && sceneData->getRenderObjects().empty()) { clearShadowMap(camera); return; }