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/cocos/base/IndexHandle.h b/native/cocos/base/IndexHandle.h index f81b8bcae1..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; // NOLINT(google-explicit-constructor) we need this implicity + 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/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/ReadWriteLock.h b/native/cocos/base/threading/ReadWriteLock.h index 12e19dd917..3ae1e1b0c3 100644 --- a/native/cocos/base/threading/ReadWriteLock.h +++ b/native/cocos/base/threading/ReadWriteLock.h @@ -27,11 +27,10 @@ // clang-format off #include "base/Macros.h" -#include "uv.h" // clang-format on #include -#include +#include namespace cc { 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/bindings/jswrapper/Value.cpp b/native/cocos/bindings/jswrapper/Value.cpp index cd11b8c5f7..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 { @@ -415,15 +442,15 @@ float Value::toFloat() const { } double Value::toDouble() const { - assert(_type == Type::Number || _type == Type::Boolean); - // assert(_type != Type::BigInt); - if (_type == Type::Boolean) { - if (_u._boolean) { - return 1.0; - } - return 0.0; + assert(_type == Type::Number || _type == Type::Boolean || _type == Type::BigInt); + if(LIKELY(_type == Type::Number)) { + return _u._number; } - return _u._number; + if (_type == Type::BigInt) { + // CC_LOG_WARNING("convert int64 to double"); + return static_cast(_u._bigint); + } + return _u._boolean ? 1.0 : 0.0; } bool Value::toBoolean() const { @@ -520,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 { diff --git a/native/cocos/bindings/manual/jsb_conversions.h b/native/cocos/bindings/manual/jsb_conversions.h index 1f0191f12e..d271f79c0e 100644 --- a/native/cocos/bindings/manual/jsb_conversions.h +++ b/native/cocos/bindings/manual/jsb_conversions.h @@ -941,7 +941,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 diff --git a/native/cocos/bindings/manual/jsb_global_init.cpp b/native/cocos/bindings/manual/jsb_global_init.cpp index 64eed1e1c9..e246048e2e 100644 --- a/native/cocos/bindings/manual/jsb_global_init.cpp +++ b/native/cocos/bindings/manual/jsb_global_init.cpp @@ -25,13 +25,12 @@ // clang-format off #include "base/Macros.h" +// clang-format: off +#include #include "uv.h" // clang-format on #include "jsb_global_init.h" -#include -#include -#include #include #include @@ -43,14 +42,17 @@ #include "jsb_conversions.h" #include "xxtea/xxtea.h" +#include +#include +#include +#include + using namespace cc; //NOLINT se::Object *__jsbObj = nullptr; //NOLINT se::Object *__glObj = nullptr; //NOLINT -namespace { -std::basic_string xxteaKey; -} +static std::basic_string xxteaKey; void jsb_set_xxtea_key(const std::string &key) { //NOLINT xxteaKey.assign(key.begin(), key.end()); diff --git a/native/cocos/bindings/manual/jsb_scene_manual_ext.cpp b/native/cocos/bindings/manual/jsb_scene_manual_ext.cpp index 663ba4612e..3fb560e3e4 100644 --- a/native/cocos/bindings/manual/jsb_scene_manual_ext.cpp +++ b/native/cocos/bindings/manual/jsb_scene_manual_ext.cpp @@ -47,7 +47,6 @@ void fastSetPasses(void *buffer) { uint32_t passSize; AlignedPtr passes[0]; }; - // static_assert(offsetof(Heap, passes) == 12); // C++17 required Heap *heap = reinterpret_cast(buffer); auto &passes = heap->selfPtr.get()->passes; 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/win32/FileUtils-win32.cpp b/native/cocos/platform/win32/FileUtils-win32.cpp index 3ca82e5cfc..7abd53e31f 100644 --- a/native/cocos/platform/win32/FileUtils-win32.cpp +++ b/native/cocos/platform/win32/FileUtils-win32.cpp @@ -48,7 +48,7 @@ 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; - auto len = ret.length(); + size_t len = ret.length(); for (size_t i = 0; i < len; ++i) { if (ret[i] == '\\') { ret[i] = '/'; diff --git a/native/cocos/renderer/gfx-agent/CommandBufferAgent.cpp b/native/cocos/renderer/gfx-agent/CommandBufferAgent.cpp index 2c1c70a325..4184c4b0d4 100644 --- a/native/cocos/renderer/gfx-agent/CommandBufferAgent.cpp +++ b/native/cocos/renderer/gfx-agent/CommandBufferAgent.cpp @@ -414,7 +414,8 @@ void CommandBufferAgent::copyBuffersToTexture(const uint8_t *const *buffers, Tex actor->copyBuffersToTexture(buffers, dst, regions, count); // TODO(PatriceJiang): C++17 replace with: CC_DELETE(allocator); _CC_DELETE_T_ALIGN(allocator, ThreadSafeLinearAllocator, alignof(ThreadSafeLinearAllocator)); - allocator = nullptr; }); + allocator = nullptr; + }); } void CommandBufferAgent::blitTexture(Texture *srcTexture, Texture *dstTexture, const TextureBlit *regions, uint32_t count, Filter filter) { diff --git a/native/cocos/renderer/gfx-agent/DeviceAgent.cpp b/native/cocos/renderer/gfx-agent/DeviceAgent.cpp index e899ba21e2..ef18f66eb8 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" @@ -109,6 +110,7 @@ void DeviceAgent::doDestroy() { } _mainMessageQueue->terminateConsumerThread(); + // NOTE: C++17 required when enable alignment // TODO(PatriceJiang): replace with: CC_SAFE_DELETE(_mainMessageQueue); _CC_DELETE_T_ALIGN(_mainMessageQueue, MessageQueue, alignof(MessageQueue)); // NOLINT @@ -302,7 +304,8 @@ void DeviceAgent::copyBuffersToTexture(const uint8_t *const *buffers, Texture *d actor->copyBuffersToTexture(buffers, dst, regions, count); // TODO(PatriceJiang): C++17 replace with: CC_DELETE(allocator); _CC_DELETE_T_ALIGN(allocator, ThreadSafeLinearAllocator, alignof(ThreadSafeLinearAllocator)); - allocator = nullptr; }); + allocator = nullptr; + }); } void DeviceAgent::copyTextureToBuffers(Texture *srcTexture, uint8_t *const *buffers, const BufferTextureCopy *regions, uint32_t count) { diff --git a/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp b/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp index 3993b95612..3d1051c20f 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp @@ -1602,10 +1602,10 @@ static void doCreateFramebufferInstance(GLES3Device *device, GLES3GPUFramebuffer : gpuFBO->gpuDepthStencilTexture; } - outFBO->framebuffer.initialize(doCreateFramebuffer(device, gpuFBO->gpuColorTextures, colors.data(), colors.size(), + outFBO->framebuffer.initialize(doCreateFramebuffer(device, gpuFBO->gpuColorTextures, colors.data(), utils::toUint(colors.size()), depthStencilTexture, resolves, depthStencilResolveTexture, &outFBO->resolveMask)); if (outFBO->resolveMask) { - size_t resolveCount = outFBO->resolveMask & GL_COLOR_BUFFER_BIT ? colors.size() : 0U; + size_t resolveCount = outFBO->resolveMask & GL_COLOR_BUFFER_BIT ? utils::toUint(colors.size()) : 0U; GLES3GPUSwapchain *resolveSwapchain{getSwapchainIfExists(gpuFBO->gpuColorTextures, resolves, resolveCount)}; if (!resolveSwapchain) { outFBO->resolveFramebuffer.initialize(doCreateFramebuffer(device, gpuFBO->gpuColorTextures, resolves, resolveCount, depthStencilResolveTexture)); diff --git a/native/cocos/renderer/gfx-gles3/GLES3PipelineLayout.cpp b/native/cocos/renderer/gfx-gles3/GLES3PipelineLayout.cpp index 5a43346e2c..8f620e7617 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3PipelineLayout.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3PipelineLayout.cpp @@ -57,12 +57,12 @@ void GLES3PipelineLayout::doInit(const PipelineLayoutInfo & /*info*/) { uint32_t binding = gpuSetLayout->dynamicBindings[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-metal/MTLCommandBuffer.mm b/native/cocos/renderer/gfx-metal/MTLCommandBuffer.mm index 3e9e8b8cf7..4667af9fc7 100644 --- a/native/cocos/renderer/gfx-metal/MTLCommandBuffer.mm +++ b/native/cocos/renderer/gfx-metal/MTLCommandBuffer.mm @@ -302,7 +302,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/MTLGPUObjects.h b/native/cocos/renderer/gfx-metal/MTLGPUObjects.h index ccdd1f2634..4f0c1852be 100644 --- a/native/cocos/renderer/gfx-metal/MTLGPUObjects.h +++ b/native/cocos/renderer/gfx-metal/MTLGPUObjects.h @@ -102,6 +102,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 799b49e7f5..179a6a98d2 100644 --- a/native/cocos/renderer/gfx-metal/MTLShader.mm +++ b/native/cocos/renderer/gfx-metal/MTLShader.mm @@ -75,6 +75,8 @@ void CCMTLShader::doDestroy() { id cmptFunc = _cmptFunction; _cmptFunction = nil; + [_gpuShader->shaderSrc release]; + // [_specializedFragFuncs release]; const auto specFragFuncs = [_specializedFragFuncs retain]; [_specializedFragFuncs release]; @@ -82,7 +84,7 @@ void CCMTLShader::doDestroy() { CC_SAFE_DELETE(_gpuShader); std::function destroyFunc = [=]() { - if([specFragFuncs count]) { + if([specFragFuncs count] > 0) { for (NSString* key in [specFragFuncs allKeys]) { [[specFragFuncs valueForKey:key] release]; } @@ -146,13 +148,31 @@ bool CCMTLShader::createMTLFunction(const ShaderStage &stage) { 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"]; @@ -201,22 +221,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.h b/native/cocos/renderer/gfx-metal/MTLUtils.h index 4e4d92f279..211723d68f 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 fbcb1986a7..5bad2d31e8 100644 --- a/native/cocos/renderer/gfx-metal/MTLUtils.mm +++ b/native/cocos/renderer/gfx-metal/MTLUtils.mm @@ -477,6 +477,7 @@ MTLMultisampleDepthResolveFilter mu::toMTLDepthResolveMode(ResolveMode mode) { } } +API_AVAILABLE(ios(12.0)) MTLMultisampleStencilResolveFilter mu::toMTLStencilResolveMode(ResolveMode mode) { switch (mode) { case ResolveMode::SAMPLE_ZERO: @@ -1083,7 +1084,7 @@ String mu::spirv2MSL(const uint32_t *ir, size_t word_count, 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 + ")"); } } diff --git a/native/cocos/renderer/pipeline/InstancedBuffer.cpp b/native/cocos/renderer/pipeline/InstancedBuffer.cpp index 7075e19bcd..c8e048d959 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/renderer/pipeline/RenderAdditiveLightQueue.cpp b/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.cpp index 6f52b8cc2c..1843fbc295 100644 --- a/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.cpp +++ b/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.cpp @@ -232,6 +232,7 @@ 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(); @@ -241,7 +242,7 @@ void RenderAdditiveLightQueue::updateUBOs(const scene::Camera *camera, gfx::Comm _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; diff --git a/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp b/native/cocos/renderer/pipeline/shadow/ShadowFlow.cpp index d3749b44f7..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->getDirShadowObjects().empty()) { + if (sceneData->getDirShadowObjects().empty() && sceneData->getRenderObjects().empty()) { clearShadowMap(camera); return; } @@ -256,5 +256,6 @@ void ShadowFlow::destroy() { RenderFlow::destroy(); } + } // namespace pipeline } // namespace cc diff --git a/native/cocos/scene/Model.h b/native/cocos/scene/Model.h index 11a403646f..6b5260cff9 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 @@ -84,6 +84,7 @@ public: _instancedBuffer = {buffer, size}; _instanceAttributeBlock = std::move(block); _instanceAttributes = attributes; + _transformUpdated = true; } inline void setOctreeNode(OctreeNode *node) { _octreeNode = node; } inline void setScene(RenderScene *scene) { _scene = scene; }